import {z} from 'zod' export type PaymentInfoDtoV2 = {quoteId?: number | undefined, paymentToken?: string | undefined, paymentIntent?: string | undefined, paymentMethod?: string | undefined, customer?: string | undefined, paymentIp?: string | undefined, paymentMethodNonce?: string | undefined, paymentService: 'stripe' | 'checkOut', useVoucher?: boolean | undefined, purchasePaymentType?: ('full' | 'deposit') | undefined, validateIntentAmount?: boolean | undefined, companyId?: number | undefined}; export type ResidencyDtoV2 = {country?: (string | null) | undefined, areaLevel1?: (string | null) | undefined, locality?: (string | null) | undefined, label?: (string | null) | undefined, googleId?: (string | null) | undefined, fullCountryName?: (string | null) | undefined, streetAndNumber?: (string | null) | undefined, city?: (string | null) | undefined, apartment?: (string | null) | undefined, zipCode?: (string | null) | undefined}; export type OsInfoDtoV2 = {customerTZ: string, operationSystem: string, osVersion: string}; export type SaveAndPayDtoV2 = {paymentInfo: PaymentInfoDtoV2, address?: ResidencyDtoV2 | undefined, policyCodeHash: string, osInfoDto?: OsInfoDtoV2 | undefined}; export type CreateApiV2PurchaseArgs = {Authorization?: string | undefined, body: SaveAndPayDtoV2}; export type CreateApiV2PurchaseOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const policyholderDto = z.object({name: z.string(), planId: z.string()}); export const purchasePolicyDto = z.object({purchaseId: z.string(), plans: z.array(policyholderDto).optional(), totalPrice: z.number().multipleOf(0.01), paymentIntent: z.string().optional(), policyUrl: z.string().optional(), receiptUrl: 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 }; /** * Save and pay for a quote (V2) * * POST /v2/purchase */ export const createApiV2Purchase = async (args: CreateApiV2PurchaseArgs, options?: CreateApiV2PurchaseOptions) => { const {baseUrl = "https://partnerapi.withfaye.com", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/purchase${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(purchasePolicyDto, await res.json()) };