import {z} from 'zod' export type Entity = {id?: string | undefined, updatedDate?: string | undefined, createdDate?: string | undefined}; export type AuditLog = {changeType?: string | undefined, changeDate?: string | undefined, objectType?: ('ACCOUNT' | 'ACCOUNT_EMAIL' | 'BLOCKING_STATES' | 'BUNDLE' | 'CUSTOM_FIELD' | 'INVOICE' | 'PAYMENT' | 'TRANSACTION' | 'INVOICE_ITEM' | 'INVOICE_PAYMENT' | 'SUBSCRIPTION' | 'SUBSCRIPTION_EVENT' | 'SERVICE_BROADCAST' | 'PAYMENT_ATTEMPT' | 'PAYMENT_METHOD' | 'TAG' | 'TAG_DEFINITION' | 'TENANT' | 'TENANT_KVS') | undefined, objectId?: string | undefined, changedBy?: string | undefined, reasonCode?: string | undefined, comments?: string | undefined, userToken?: string | undefined, history?: Entity | undefined}; export type EventSubscription = {eventId?: string | undefined, billingPeriod?: ('DAILY' | 'WEEKLY' | 'BIWEEKLY' | 'THIRTY_DAYS' | 'SIXTY_DAYS' | 'NINETY_DAYS' | 'MONTHLY' | 'BIMESTRIAL' | 'QUARTERLY' | 'TRIANNUAL' | 'BIANNUAL' | 'ANNUAL' | 'BIENNIAL' | 'NO_BILLING_PERIOD') | undefined, effectiveDate?: string | undefined, plan?: string | undefined, product?: string | undefined, priceList?: string | undefined, eventType?: ('START_ENTITLEMENT' | 'START_BILLING' | 'PAUSE_ENTITLEMENT' | 'PAUSE_BILLING' | 'RESUME_ENTITLEMENT' | 'RESUME_BILLING' | 'PHASE' | 'CHANGE' | 'STOP_ENTITLEMENT' | 'STOP_BILLING' | 'SERVICE_STATE_CHANGE') | undefined, isBlockedBilling?: boolean | undefined, isBlockedEntitlement?: boolean | undefined, serviceName?: string | undefined, serviceStateName?: string | undefined, phase?: string | undefined, auditLogs?: Array | undefined}; export type BlockPrice = {unitName?: string | undefined, size?: number | undefined, price?: number | undefined, max?: number | undefined}; export type TierPrice = {blockPrices?: Array | undefined}; export type UsagePrice = {usageName?: string | undefined, usageType?: ('CAPACITY' | 'CONSUMABLE') | undefined, billingMode?: ('IN_ADVANCE' | 'IN_ARREAR') | undefined, tierBlockPolicy?: ('ALL_TIERS' | 'TOP_TIER') | undefined, tierPrices?: Array | undefined}; export type PhasePrice = {planName?: string | undefined, phaseName?: string | undefined, phaseType?: string | undefined, fixedPrice?: number | undefined, recurringPrice?: number | undefined, usagePrices?: Array | undefined}; export type Subscription = {accountId?: string | undefined, bundleId?: string | undefined, bundleExternalKey?: string | undefined, subscriptionId?: string | undefined, externalKey?: string | undefined, startDate?: string | undefined, productName: string, productCategory?: ('BASE' | 'ADD_ON' | 'STANDALONE') | undefined, billingPeriod: 'DAILY' | 'WEEKLY' | 'BIWEEKLY' | 'THIRTY_DAYS' | 'SIXTY_DAYS' | 'NINETY_DAYS' | 'MONTHLY' | 'BIMESTRIAL' | 'QUARTERLY' | 'TRIANNUAL' | 'BIANNUAL' | 'ANNUAL' | 'BIENNIAL' | 'NO_BILLING_PERIOD', phaseType?: ('TRIAL' | 'DISCOUNT' | 'FIXEDTERM' | 'EVERGREEN') | undefined, priceList: string, planName: string, state?: ('PENDING' | 'ACTIVE' | 'BLOCKED' | 'CANCELLED' | 'EXPIRED') | undefined, sourceType?: ('NATIVE' | 'MIGRATED' | 'TRANSFERRED') | undefined, cancelledDate?: string | undefined, chargedThroughDate?: string | undefined, billingStartDate?: string | undefined, billingEndDate?: string | undefined, billCycleDayLocal?: number | undefined, events?: Array | undefined, priceOverrides?: Array | undefined, prices?: Array | undefined, auditLogs?: Array | undefined}; export type CreateApi10KbSubscriptionsArgs = {entitlementDate?: string | undefined, billingDate?: string | undefined, renameKeyIfExistsAndUnused?: boolean | undefined, migrated?: boolean | undefined, callCompletion?: boolean | undefined, callTimeoutSec?: number | undefined, pluginProperty?: Array | undefined, 'X-Killbill-CreatedBy': string, 'X-Killbill-Reason'?: string | undefined, 'X-Killbill-Comment'?: string | undefined, body: Subscription}; export type CreateApi10KbSubscriptionsOptions = {baseUrl: string, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const entity = z.object({id: z.string().optional(), updatedDate: z.string().optional(), createdDate: z.string().optional()}); export const auditLog = z.object({changeType: z.string().optional(), changeDate: z.string().optional(), objectType: z.enum(["ACCOUNT", "ACCOUNT_EMAIL", "BLOCKING_STATES", "BUNDLE", "CUSTOM_FIELD", "INVOICE", "PAYMENT", "TRANSACTION", "INVOICE_ITEM", "INVOICE_PAYMENT", "SUBSCRIPTION", "SUBSCRIPTION_EVENT", "SERVICE_BROADCAST", "PAYMENT_ATTEMPT", "PAYMENT_METHOD", "TAG", "TAG_DEFINITION", "TENANT", "TENANT_KVS"]).optional(), objectId: z.string().optional(), changedBy: z.string().optional(), reasonCode: z.string().optional(), comments: z.string().optional(), userToken: z.string().optional(), history: entity.optional()}); export const eventSubscription = z.object({eventId: z.string().optional(), billingPeriod: z.enum(["DAILY", "WEEKLY", "BIWEEKLY", "THIRTY_DAYS", "SIXTY_DAYS", "NINETY_DAYS", "MONTHLY", "BIMESTRIAL", "QUARTERLY", "TRIANNUAL", "BIANNUAL", "ANNUAL", "BIENNIAL", "NO_BILLING_PERIOD"]).optional(), effectiveDate: z.string().optional(), plan: z.string().optional(), product: z.string().optional(), priceList: z.string().optional(), eventType: z.enum(["START_ENTITLEMENT", "START_BILLING", "PAUSE_ENTITLEMENT", "PAUSE_BILLING", "RESUME_ENTITLEMENT", "RESUME_BILLING", "PHASE", "CHANGE", "STOP_ENTITLEMENT", "STOP_BILLING", "SERVICE_STATE_CHANGE"]).optional(), isBlockedBilling: z.boolean().optional(), isBlockedEntitlement: z.boolean().optional(), serviceName: z.string().optional(), serviceStateName: z.string().optional(), phase: z.string().optional(), auditLogs: z.array(auditLog).optional()}); export const blockPrice = z.object({unitName: z.string().optional(), size: z.number().optional(), price: z.number().optional(), max: z.number().optional()}); export const tierPrice = z.object({blockPrices: z.array(blockPrice).optional()}); export const usagePrice = z.object({usageName: z.string().optional(), usageType: z.enum(["CAPACITY", "CONSUMABLE"]).optional(), billingMode: z.enum(["IN_ADVANCE", "IN_ARREAR"]).optional(), tierBlockPolicy: z.enum(["ALL_TIERS", "TOP_TIER"]).optional(), tierPrices: z.array(tierPrice).optional()}); export const phasePrice = z.object({planName: z.string().optional(), phaseName: z.string().optional(), phaseType: z.string().optional(), fixedPrice: z.number().optional(), recurringPrice: z.number().optional(), usagePrices: z.array(usagePrice).optional()}); export const subscription = z.object({accountId: z.string().optional(), bundleId: z.string().optional(), bundleExternalKey: z.string().optional(), subscriptionId: z.string().optional(), externalKey: z.string().optional(), startDate: z.string().optional(), productName: z.string(), productCategory: z.enum(["BASE", "ADD_ON", "STANDALONE"]).optional(), billingPeriod: z.enum(["DAILY", "WEEKLY", "BIWEEKLY", "THIRTY_DAYS", "SIXTY_DAYS", "NINETY_DAYS", "MONTHLY", "BIMESTRIAL", "QUARTERLY", "TRIANNUAL", "BIANNUAL", "ANNUAL", "BIENNIAL", "NO_BILLING_PERIOD"]), phaseType: z.enum(["TRIAL", "DISCOUNT", "FIXEDTERM", "EVERGREEN"]).optional(), priceList: z.string(), planName: z.string(), state: z.enum(["PENDING", "ACTIVE", "BLOCKED", "CANCELLED", "EXPIRED"]).optional(), sourceType: z.enum(["NATIVE", "MIGRATED", "TRANSFERRED"]).optional(), cancelledDate: z.string().optional(), chargedThroughDate: z.string().optional(), billingStartDate: z.string().optional(), billingEndDate: z.string().optional(), billCycleDayLocal: z.number().int().optional(), events: z.array(eventSubscription).optional(), priceOverrides: z.array(phasePrice).optional(), prices: z.array(phasePrice).optional(), auditLogs: z.array(auditLog).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 }; /** * Create an subscription * * POST /1.0/kb/subscriptions * * Also accepts auth: Killbill_Api_Key, Killbill_Api_Secret */ export const createApi10KbSubscriptions = async (args: CreateApi10KbSubscriptionsArgs, options: CreateApi10KbSubscriptionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.entitlementDate != null) query.append("entitlementDate", String(args.entitlementDate)) if (args.billingDate != null) query.append("billingDate", String(args.billingDate)) if (args.renameKeyIfExistsAndUnused != null) query.append("renameKeyIfExistsAndUnused", String(args.renameKeyIfExistsAndUnused)) if (args.migrated != null) query.append("migrated", String(args.migrated)) if (args.callCompletion != null) query.append("callCompletion", String(args.callCompletion)) if (args.callTimeoutSec != null) query.append("callTimeoutSec", String(args.callTimeoutSec)) for (const item of args.pluginProperty ?? []) query.append("pluginProperty", String(item)) if (args['X-Killbill-CreatedBy'] != null) headers.set("X-Killbill-CreatedBy", String(args['X-Killbill-CreatedBy'])) if (args['X-Killbill-Reason'] != null) headers.set("X-Killbill-Reason", String(args['X-Killbill-Reason'])) if (args['X-Killbill-Comment'] != null) headers.set("X-Killbill-Comment", String(args['X-Killbill-Comment'])) if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/1.0/kb/subscriptions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(subscription, await res.json()) };