import {z} from 'zod' export type GetApiSubscriptionsArgs = {page?: number | undefined, per_page?: number | undefined, currency?: string | undefined, external_customer_id?: string | undefined, external_id?: string | undefined, plan_code?: string | undefined, overridden?: boolean | undefined, 'status[]'?: (Array<'active' | 'canceled' | 'incomplete' | 'pending' | 'terminated'>) | undefined, 'billing_entity_codes[]'?: Array | undefined}; export type GetApiSubscriptionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const currency = z.enum(["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLF", "CLP", "CNY", "COP", "CRC", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "ISK", "JMD", "JPY", "KES", "KGS", "KHR", "KMF", "KRW", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "STD", "SYP", "SZL", "THB", "TJS", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VND", "VUV", "WST", "XAF", "XCD", "XOF", "XPF", "YER", "ZAR", "ZMW"]); export const invoiceCustomSectionObject = z.object({lago_id: z.string(), name: z.string(), code: z.string(), description: z.string().optional(), details: z.string().optional(), display_name: z.string().optional(), applied_to_organization: z.boolean().optional(), organization_id: z.string().optional(), created_at: z.string().optional()}); export const appliedInvoiceCustomSectionObject = z.object({lago_id: z.string(), created_at: z.string(), invoice_custom_section_id: z.string().optional(), invoice_custom_section: invoiceCustomSectionObject}); export const paymentMethodReference = z.object({payment_method_type: z.enum(["provider", "manual"]).optional(), payment_method_id: z.string().optional()}); export const subscriptionActivationRuleObject = z.object({lago_id: z.string(), type: z.literal("payment"), timeout_hours: z.number().int(), status: z.enum(["inactive", "pending", "satisfied", "declined", "failed", "expired", "not_applicable"]), expires_at: z.string().nullable(), created_at: z.string(), updated_at: z.string()}); export const subscriptionObject = z.object({lago_id: z.string(), external_id: z.string(), lago_customer_id: z.string(), external_customer_id: z.string(), billing_entity_code: z.string().optional(), billing_time: z.enum(["calendar", "anniversary"]), name: z.string().nullable(), plan_code: z.string(), plan_amount_cents: z.number().int(), plan_amount_currency: currency, status: z.enum(["active", "canceled", "incomplete", "pending", "terminated"]), created_at: z.string(), canceled_at: z.string().nullable(), started_at: z.string().nullable(), ending_at: z.string().nullable(), subscription_at: z.string(), terminated_at: z.string().nullable(), previous_plan_code: z.string().nullable(), next_plan_code: z.string().nullable(), downgrade_plan_date: z.string().nullable(), trial_ended_at: z.string().nullable(), current_billing_period_started_at: z.string().nullable(), current_billing_period_ending_at: z.string().nullable(), on_termination_credit_note: z.enum(["credit", "refund", "offset", "skip"]).nullable(), on_termination_invoice: z.enum(["generate", "skip"]), applied_invoice_custom_sections: z.array(appliedInvoiceCustomSectionObject).optional(), payment_method: paymentMethodReference, consolidate_invoice: z.boolean(), progressive_billing_disabled: z.boolean(), cancellation_reason: z.enum(["payment_failed", "timeout", "manual"]).nullable(), activated_at: z.string().nullable(), activation_rules: z.array(subscriptionActivationRuleObject), purchase_order_number: z.string().nullable()}); export const paginationMeta = z.object({current_page: z.number().int(), next_page: z.number().int().nullable().optional(), prev_page: z.number().int().nullable().optional(), total_pages: z.number().int(), total_count: z.number().int()}); export const subscriptionsPaginated = z.object({subscriptions: z.array(subscriptionObject), meta: paginationMeta}); 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 }; /** * List all subscriptions * * GET /subscriptions */ export const getApiSubscriptions = async (args: GetApiSubscriptionsArgs, options?: GetApiSubscriptionsOptions) => { const {baseUrl = "https://api.getlago.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.currency != null) query.append("currency", String(args.currency)) if (args.external_customer_id != null) query.append("external_customer_id", String(args.external_customer_id)) if (args.external_id != null) query.append("external_id", String(args.external_id)) if (args.plan_code != null) query.append("plan_code", String(args.plan_code)) if (args.overridden != null) query.append("overridden", String(args.overridden)) for (const item of args['status[]'] ?? []) query.append("status[]", String(item)) for (const item of args['billing_entity_codes[]'] ?? []) query.append("billing_entity_codes[]", String(item)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/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(subscriptionsPaginated, await res.json()) };