import {z} from 'zod' export type TabAmountWithCurrency = {amount: number, currency: string}; export type PayIntentRequest = {terminal_id: string, amount: TabAmountWithCurrency, method: 'CARD' | 'CASH', type: 'FULL' | 'SPLIT'}; export type CreateApiPoslinkV1TabsTabIdPaymentIntentsArgs = {tab_id: string, body: PayIntentRequest}; export type CreateApiPoslinkV1TabsTabIdPaymentIntentsOptions = {baseUrl?: string | undefined, authorisation?: string | undefined, fetch?: typeof fetch | undefined}; export const tabAmountWithCurrency = z.object({amount: z.number().int(), currency: z.string()}); export const payIntentResponse = z.object({tab_id: z.string().optional(), terminal_id: z.string().optional(), amount: tabAmountWithCurrency.optional(), method: z.enum(["CARD", "CASH"]).optional(), type: z.enum(["FULL", "SPLIT"]).optional(), status: z.literal("FORWARDED").optional(), show_bill_expires_at: 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 }; /** * Create a payment intent * * POST /poslink/v1/tabs/{tab_id}/payment-intents */ export const createApiPoslinkV1TabsTabIdPaymentIntents = async (args: CreateApiPoslinkV1TabsTabIdPaymentIntentsArgs, options?: CreateApiPoslinkV1TabsTabIdPaymentIntentsOptions) => { const {baseUrl = "https://api.teya.com", fetch: fetchFn = fetch, authorisation} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (authorisation !== undefined) headers.set('authorization', `Bearer ${authorisation}`) const url = `${baseUrl.replace(/\/+$/, '')}/poslink/v1/tabs/${encodeURIComponent(String(args.tab_id))}/payment-intents${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(payIntentResponse, await res.json()) };