import {z} from 'zod' export type SubscriptionStatusEnum = 'active' | 'inactive' | 'canceled' | 'expired' | 'paused' | 'trial'; export type GetApiPublicApiSubscriptionsArgs = {limit?: number | undefined, page?: number | undefined, search?: string | undefined, ordering?: ('status' | 'amount' | 'paymentMethod' | 'createdAt' | 'updatedAt' | 'canceledAt' | 'next_payment_date') | undefined, status?: SubscriptionStatusEnum | undefined, paymentMethod?: string | undefined, current_situation?: ('new' | 'renewed') | undefined}; export type GetApiPublicApiSubscriptionsOptions = {baseUrl?: string | undefined, OAuthToken?: string | undefined, fetch?: typeof fetch | undefined}; export const subscriptionStatusEnum = z.enum(["active", "inactive", "canceled", "expired", "paused", "trial"]); export const subscriptionOwnerFlex = z.object({id: z.string().max(255), status: subscriptionStatusEnum, current_period: z.number().int().optional(), recurrence_period: z.number().int().optional(), quantity_recurrences: z.number().int().optional(), trial_days: z.number().int().optional(), max_retries: z.number().int().optional(), amount: z.string(), retry_interval: z.number().int().optional(), paid_payments_quantity: z.number().int().optional(), retention: z.string().optional(), parent_order: z.object({}), paymentMethod: z.object({}), customer: z.object({}), product: z.object({}), offer: z.object({}), orders: z.array(z.object({})).optional(), next_payment_date: z.string().nullable().optional(), createdAt: z.string(), updatedAt: z.string(), canceledAt: z.string().nullable().optional()}); export const paginatedSubscriptionOwnerFlexList = z.object({count: z.number().int().optional(), next: z.string().nullable().optional(), previous: z.string().nullable().optional(), results: z.array(subscriptionOwnerFlex).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Lista assinaturas da conta com filtros, busca e paginação. * * GET /public_api/subscriptions/ */ export const getApiPublicApiSubscriptions = async (args: GetApiPublicApiSubscriptionsArgs, options?: GetApiPublicApiSubscriptionsOptions) => { const {baseUrl = "https://api.cakto.com.br", fetch: fetchFn = fetch, OAuthToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.page != null) query.append("page", String(args.page)) if (args.search != null) query.append("search", String(args.search)) if (args.ordering != null) query.append("ordering", String(args.ordering)) if (args.status != null) query.append("status", String(args.status)) if (args.paymentMethod != null) query.append("paymentMethod", String(args.paymentMethod)) if (args.current_situation != null) query.append("current_situation", String(args.current_situation)) if (OAuthToken !== undefined) headers.set('authorization', `Bearer ${OAuthToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/public_api/subscriptions/${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(paginatedSubscriptionOwnerFlexList, await res.json()) };