import {z} from 'zod' export type GetApi10KbOverdueOptions = {baseUrl: string, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const duration = z.object({unit: z.enum(["DAYS", "WEEKS", "MONTHS", "YEARS", "UNLIMITED"]).optional(), number: z.number().int().optional()}); export const overdueCondition = z.object({timeSinceEarliestUnpaidInvoiceEqualsOrExceeds: duration.optional(), controlTagInclusion: z.enum(["AUTO_PAY_OFF", "AUTO_INVOICING_OFF", "OVERDUE_ENFORCEMENT_OFF", "WRITTEN_OFF", "MANUAL_PAY", "TEST", "PARTNER", "AUTO_INVOICING_DRAFT", "AUTO_INVOICING_REUSE_DRAFT"]).optional(), controlTagExclusion: z.enum(["AUTO_PAY_OFF", "AUTO_INVOICING_OFF", "OVERDUE_ENFORCEMENT_OFF", "WRITTEN_OFF", "MANUAL_PAY", "TEST", "PARTNER", "AUTO_INVOICING_DRAFT", "AUTO_INVOICING_REUSE_DRAFT"]).optional(), numberOfUnpaidInvoicesEqualsOrExceeds: z.number().int().optional(), responseForLastFailedPayment: z.array(z.enum(["INVALID_CARD", "EXPIRED_CARD", "LOST_OR_STOLEN_CARD", "DO_NOT_HONOR", "INSUFFICIENT_FUNDS", "DECLINE", "PROCESSING_ERROR", "INVALID_AMOUNT", "DUPLICATE_TRANSACTION", "OTHER"])).optional(), totalUnpaidInvoiceBalanceEqualsOrExceeds: z.number().optional()}); export const overdueStateConfig = z.object({name: z.string().optional(), isClearState: z.boolean().optional(), condition: overdueCondition.optional(), externalMessage: z.string().optional(), isBlockChanges: z.boolean().optional(), isDisableEntitlement: z.boolean().optional(), subscriptionCancellationPolicy: z.enum(["END_OF_TERM", "IMMEDIATE", "NONE"]).optional(), autoReevaluationIntervalDays: z.number().int().optional()}); export const overdue = z.object({initialReevaluationInterval: z.number().int().optional(), overdueStates: z.array(overdueStateConfig).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 }; /** * Retrieve the overdue config as JSON * * GET /1.0/kb/overdue * * Also accepts auth: Killbill_Api_Key, Killbill_Api_Secret */ export const getApi10KbOverdue = async (options: GetApi10KbOverdueOptions) => { const {baseUrl, fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/1.0/kb/overdue${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(overdue, await res.json()) };