import {z} from 'zod' export type PaymentMedium = 'POS' | 'VIRTUAL_TERMINAL' | 'PAYMENT_LINK' | 'PAYMENT_PLAN' | 'SUBSCRIPTION' | 'SAVED_PAYMENT_METHOD' | 'MEMBERSHIP' | 'CASH' | 'CHECK' | 'CARE_CREDIT' | 'PATIENT_CREDIT'; export type PaymentPlanFrequency = 'WEEKLY' | 'BIWEEKLY' | 'MONTHLY'; export type PaymentPlanCreateWithoutID = {initialAmount: number, chargeIds: Array, frequency: PaymentPlanFrequency, installments: number, installmentAmount: number, locationId?: (string | null) | undefined, startDate?: (string | null) | undefined}; export type UserType = 'PROVIDER' | 'PATIENT' | 'ASSISTANT'; export type PatientTagSummary = {id: string, name: string, emoji?: (string | null) | undefined, color?: (string | null) | undefined, isActive: boolean, createdDate: string, updatedDate?: (string | null) | undefined}; export type PatientSummary = {id: string, firstName?: (string | null) | undefined, lastName?: (string | null) | undefined, phoneNumber?: (string | null) | undefined, email?: (string | null) | undefined, type: UserType, locationId?: (string | null) | undefined, externalId?: (string | null) | undefined, address?: (string | null) | undefined, addressLineTwo?: (string | null) | undefined, city?: (string | null) | undefined, state?: (string | null) | undefined, zipCode?: (string | null) | undefined, country?: (string | null) | undefined, createdDate: string, addressValid?: (boolean | null) | undefined, meta?: (Record | null) | undefined, isArchived?: (boolean | null) | undefined, primaryLocationId?: (string | null) | undefined, gender?: (string | null) | undefined, dateOfBirth?: (string | null) | undefined, patientMedications?: (Array | null) | undefined, onSchedulingBlacklist?: (boolean | null) | undefined, surchargeDisabled?: (boolean | null) | undefined, tags?: (Array | null) | undefined, creditBalance?: (number | null) | undefined, preferredProviderId?: (string | null) | undefined}; export type ChargeStatus = 'OUTSTANDING' | 'PAID' | 'EXTERNAL_SETTLEMENT' | 'VOID' | 'WRITE_OFF' | 'REFUNDED' | 'CHARGEBACK' | 'PAYMENT_PLAN' | 'COLLECTIONS'; export type ChargeItem = {id?: (string | null) | undefined, itemId?: (string | null) | undefined, chargeId: string, name?: (string | null) | undefined, description?: (string | null) | undefined, quantity: number, discountAmount?: (number | null) | undefined, discountPercentage?: (number | null) | undefined, discountReason?: (string | null) | undefined, price: number, soldPackageId?: (string | null) | undefined, bankedQuantity?: (number | null) | undefined, bankedItemId?: (string | null) | undefined, issuedDiscountId?: (string | null) | undefined, soldByProviderId?: (string | null) | undefined, taxAmount?: (number | null) | undefined, pricingId?: (string | null) | undefined, shipmentIds?: (Array | null) | undefined}; export type ProviderTiny = {id: string, firstName: string, lastName?: (string | null) | undefined, email?: (string | null) | undefined, createdDate?: (string | null) | undefined}; export type TipDetail = {chargeId: string, amount: number, providerId: string, id?: string | undefined, provider?: (ProviderTiny | null) | undefined}; export type ChargeSummaryInput = {id?: (string | null) | undefined, patientId: string, patient?: (PatientSummary | null) | undefined, total?: number | undefined, totalOutstanding: number, description?: (string | null) | undefined, status?: ChargeStatus | undefined, discountAmount?: (number | null) | undefined, discountPercentage?: (number | null) | undefined, externalId?: (string | null) | undefined, externalCreatedDate?: (string | null) | undefined, ruleSetId?: (string | null) | undefined, createdDate?: (string | null) | undefined, creatorId?: (string | null) | undefined, items?: Array | undefined, tips?: Array | undefined, locationId?: (string | null) | undefined, eventId?: (string | null) | undefined, memberId?: (string | null) | undefined, comment?: (string | null) | undefined, meta?: (Record | null) | undefined, merchantAccountId?: (string | null) | undefined}; export type PayinConfigCreate = {paymentAmount?: (number | null) | undefined, savePaymentMethod?: boolean | undefined, textReceipt?: boolean | undefined, paymentMedium: PaymentMedium, paymentPlan?: (PaymentPlanCreateWithoutID | null) | undefined, isSurcharged?: boolean | undefined, locationId?: (string | null) | undefined, creatorId?: (string | null) | undefined, membershipId?: (string | null) | undefined, membershipStartDate?: (string | null) | undefined, soldByProviderId?: (string | null) | undefined, merchantAccountId?: (string | null) | undefined, charges: Array}; export type CreateApiBillingPaymentTerminalPayinConfigArgs = {TENANT: string, 'API-KEY': string, body: PayinConfigCreate}; export type CreateApiBillingPaymentTerminalPayinConfigOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const paymentMethodType = z.enum(["CARD", "ACH", "APPLE_PAY"]); export const paymentMethodSummary = z.object({id: z.string(), patientId: z.string().nullable(), rainforestPaymentMethodId: z.string(), brand: z.string().nullable(), last4: z.string().nullable(), expMonth: z.number().int().nullable(), expYear: z.number().int().nullable(), accountHolderType: z.string().nullable(), accountNumberLast4: z.number().int().nullable(), bankName: z.string().nullable(), routingNumber: z.number().int().nullable(), description: z.string().nullable(), type: paymentMethodType.nullable(), isDefault: z.boolean().optional(), isArchived: z.boolean().optional()}); export const payinComponentSetupResponse = z.object({sessionKey: z.string(), payinConfigId: z.string(), paymentMethods: z.array(paymentMethodSummary).optional(), sandbox: z.boolean()}); 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 }; /** * Setup Payin Component * * POST /billing/payment-terminal/payin-config */ export const createApiBillingPaymentTerminalPayinConfig = async (args: CreateApiBillingPaymentTerminalPayinConfigArgs, options: CreateApiBillingPaymentTerminalPayinConfigOptions) => { 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") if (args.TENANT != null) headers.set("TENANT", String(args.TENANT)) if (args['API-KEY'] != null) headers.set("API-KEY", String(args['API-KEY'])) const url = `${baseUrl.replace(/\/+$/, '')}/billing/payment-terminal/payin-config${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(payinComponentSetupResponse, await res.json()) };