import {z} from 'zod' export type Address = {phoneNumber?: string | undefined, line1?: string | undefined, line2?: string | undefined, postalCode?: string | undefined, city?: string | undefined, state?: string | undefined, country?: string | undefined}; export type SettingDataType = 'STRING' | 'NUMERIC' | 'JSON' | 'JSON_LOGIC'; export type CreateEntitySetting = {id: string, value: string, namespace: string, name: string, dataType: SettingDataType}; export type CreateAccountAliasRequest = {value: string, effectiveFrom?: string | undefined, effectiveUntil?: string | undefined}; export type CreateAccountRequestWithoutCustomerId = {id: string, name: string, invoiceCurrency?: string | undefined, aliases?: Array | undefined, accountAliases?: Array | undefined, address?: Address | undefined, primaryEmail?: string | undefined, settings?: Array | undefined, netTermDays?: number | undefined, metadata?: {[key: string]: string} | undefined, tags?: Array | undefined, status?: ('ACTIVE' | 'DRAFT') | undefined}; export type CreateCustomerRequest = {id: string, name: string, primaryEmail: string, address: Address, settings?: Array | undefined, account?: CreateAccountRequestWithoutCustomerId | undefined}; export type CreateApiCustomersArgs = {body: CreateCustomerRequest}; export type CreateApiCustomersOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const address = z.object({phoneNumber: z.string().optional(), line1: z.string().optional(), line2: z.string().optional(), postalCode: z.string().optional(), city: z.string().optional(), state: z.string().optional(), country: z.string().optional()}); export const settingDataType = z.enum(["STRING", "NUMERIC", "JSON", "JSON_LOGIC"]); export const createEntitySetting = z.object({id: z.string(), value: z.string(), namespace: z.string(), name: z.string(), dataType: settingDataType}); export const invoiceGroupDetails = z.object({id: z.string(), name: z.string(), email: z.string().max(320), dailyInvoiceConsolidation: z.boolean(), netTermDays: z.number().int().optional(), invoiceCurrency: z.string(), billingAddress: address}); export const account = z.object({id: z.string().max(50), togaiAccountId: z.string(), togaiCustomerId: z.string(), name: z.string().min(3).max(255), customerId: z.string(), invoiceCurrency: z.string().min(3).max(3).optional(), aliases: z.array(z.object({alias: z.string().max(50).optional()})).optional(), netTermDays: z.number().int().optional(), address: address.optional(), primaryEmail: z.string().max(320).optional(), status: z.enum(["ACTIVE", "DRAFT", "ARCHIVED"]), settings: z.array(createEntitySetting).optional(), invoiceGroupDetails: invoiceGroupDetails.optional(), metadata: z.record(z.string(), z.string()).optional(), tags: z.array(z.string()).optional()}); export const createCustomerResponse = z.object({id: z.string().max(50), togaiCustomerId: z.string(), name: z.string().min(3).max(255), primaryEmail: z.string().max(320), billingAddress: z.string().optional(), address: address.optional(), settings: z.array(createEntitySetting).optional(), account: account.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 a customer * * POST /customers */ export const createApiCustomers = async (args: CreateApiCustomersArgs, options?: CreateApiCustomersOptions) => { const {baseUrl = "https://api.togai.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/customers${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(createCustomerResponse, await res.json()) };