import {z} from 'zod' export type InstallmentPreferences = {cadence?: ('none' | 'fullPay' | 'weekly' | 'everyOtherWeek' | 'monthly' | 'quarterly' | 'semiannually' | 'annually' | 'thirtyDays' | 'everyNDays') | undefined, anchorMode?: ('generateDay' | 'termStartDay' | 'dueDay') | undefined, generateLeadDays?: number | undefined, dueLeadDays?: number | undefined, installmentWeights: Array, maxInstallmentsPerTerm?: number | undefined, installmentPlanName?: string | undefined, anchorType?: ('none' | 'dayOfMonth' | 'anchorTime' | 'dayOfWeek' | 'weekOfMonth') | undefined, dayOfMonth?: number | undefined, dayOfWeek?: ('monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday') | undefined, weekOfMonth?: ('none' | 'first' | 'second' | 'third' | 'fourth' | 'fifth') | undefined, anchorTime?: string | undefined, autopayLeadDays?: number | undefined}; export type Preferences = {installmentPreferences?: InstallmentPreferences | undefined}; export type AccountUpdateRequest = {type: string, delinquencyPlanName: string, shortfallTolerancePlanName: string, autoRenewalPlanName: string, excessCreditPlanName: string, setData: {[key: string]: Record}, removeData: {[key: string]: Record}, preferences: Preferences, billingLevel: 'account' | 'inherit' | 'policy', invoiceDocument: string, timezone: string, invoicingPlanName: string, paymentExecutionRetryPlanName: string, autoValidate: boolean}; export type PatchApiPolicyTenantLocatorAccountsLocatorArgs = {tenantLocator: string, locator: unknown, body: AccountUpdateRequest}; export type PatchApiPolicyTenantLocatorAccountsLocatorOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const installmentPreferences = z.object({cadence: z.enum(["none", "fullPay", "weekly", "everyOtherWeek", "monthly", "quarterly", "semiannually", "annually", "thirtyDays", "everyNDays"]).optional(), anchorMode: z.enum(["generateDay", "termStartDay", "dueDay"]).optional(), generateLeadDays: z.number().int().optional(), dueLeadDays: z.number().int().optional(), installmentWeights: z.array(z.number()), maxInstallmentsPerTerm: z.number().int().optional(), installmentPlanName: z.string().optional(), anchorType: z.enum(["none", "dayOfMonth", "anchorTime", "dayOfWeek", "weekOfMonth"]).optional(), dayOfMonth: z.number().int().optional(), dayOfWeek: z.enum(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]).optional(), weekOfMonth: z.enum(["none", "first", "second", "third", "fourth", "fifth"]).optional(), anchorTime: z.string().optional(), autopayLeadDays: z.number().optional()}); export const preferences = z.object({installmentPreferences: installmentPreferences.optional()}); export const validationItemResponse = z.object({elementType: z.string(), locator: z.string(), errors: z.array(z.string())}); export const validationResult = z.object({validationItems: z.array(validationItemResponse).optional(), success: z.boolean()}); export const contactRoles = z.object({contactLocator: z.string(), roles: z.array(z.string())}); export const accountResponse = z.object({locator: z.string(), type: z.string(), accountState: z.enum(["draft", "validated", "discarded"]), data: z.record(z.string(), z.object({})), createdAt: z.string(), createdBy: z.string(), delinquencyPlanName: z.string().optional(), shortfallTolerancePlanName: z.string().optional(), autoRenewalPlanName: z.string().optional(), excessCreditPlanName: z.string().optional(), preferences: preferences.optional(), validationResult: validationResult.optional(), billingLevel: z.enum(["account", "inherit", "policy"]), invoicingPlanName: z.string().optional(), region: z.string().optional(), invoiceDocument: z.string().optional(), timezone: z.string().optional(), accountNumber: z.string(), contacts: z.array(contactRoles), anonymizedAt: z.string().optional(), paymentExecutionRetryPlanName: z.string().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 }; /** * Updates the account and individual data extensions. * * PATCH /policy/{tenantLocator}/accounts/{locator} */ export const patchApiPolicyTenantLocatorAccountsLocator = async (args: PatchApiPolicyTenantLocatorAccountsLocatorArgs, options: PatchApiPolicyTenantLocatorAccountsLocatorOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/policy/${encodeURIComponent(String(args.tenantLocator))}/accounts/${encodeURIComponent(String(args.locator))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", 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(accountResponse, await res.json()) };