import {z} from 'zod' export type CreateApiV3InvoiceArgs = {echo?: boolean | undefined, body: {merchantId: number, isClick2PayEnabled?: boolean | undefined, allowCreditCard?: boolean | undefined, status?: string | undefined, terms?: string | undefined, dueDate?: string | undefined, purchases: Array<{id?: number | undefined, originalId?: number | undefined, productName: string, price: number, quantity: number, discount?: number | undefined, tax?: number | undefined, totalAmount?: number | undefined}>, shippingAddress: {name?: string | undefined, address1?: string | undefined, address2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, isDefault?: boolean | undefined}, billingAddress: {name?: string | undefined, address1?: string | undefined, address2?: string | undefined, city?: string | undefined, state?: string | undefined, zip?: string | undefined, isDefault?: boolean | undefined}, customer: {id: number, customerType?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, primaryContact?: string | undefined, email?: string | undefined, phone?: string | undefined, mobile?: string | undefined}, purchaseOrderNumber?: string | undefined, memo?: string | undefined, orderId?: string | undefined, order?: ({lineItems?: (Array<{id?: number | undefined, name?: string | undefined, price?: number | undefined, quantity?: string | undefined, discountAmount?: number | undefined, tax?: Array | undefined, totalAmount?: number | undefined, taxCategory?: ({name?: string | undefined, code?: string | undefined, id?: number | undefined, display?: string | undefined, taxes?: (Array<{id?: string | undefined, name?: string | undefined, description?: string | undefined, rate?: number | undefined}>) | undefined, taxRate?: number | undefined, showTaxes?: boolean | undefined, noTaxes?: boolean | undefined}) | undefined}>) | undefined}) | undefined}}; export type CreateApiV3InvoiceOptions = {baseUrl?: string | undefined, sec0?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const createApiV3InvoiceResponse = z.object({id: z.number().int().optional(), merchantId: z.number().int().optional(), type: z.string().optional(), receiptNumber: z.string().optional(), accessCode: z.string().optional(), invoiceNumber: z.number().int().optional(), isTaxExempt: z.boolean().optional(), quantity: z.string().optional(), saleQuantity: z.string().optional(), returnQuantity: z.string().optional(), returnStatus: z.string().optional(), netQuantity: z.string().optional(), totalAmount: z.string().optional(), taxAmount: z.string().optional(), subTotalAmount: z.string().optional(), discountAmount: z.string().optional(), balance: z.string().optional(), paidAmount: z.string().optional(), dueDate: z.string().optional(), created: z.string().optional(), purchaseOrderNumber: z.string().optional(), invoiceDate: z.string().optional(), sourceType: z.string().optional(), purchases: z.array(z.object({id: z.number().int().optional(), productName: z.string().optional(), quantity: z.number().int().optional(), quantityReturned: z.number().int().optional(), price: z.string().optional(), discountAmount: z.string().optional(), priceDiscountAmount: z.string().optional(), subTotalAmount: z.string().optional(), taxAmount: z.string().optional(), totalAmount: z.string().optional(), trackingNumber: z.number().int().optional(), created: z.string().optional(), taxes: z.array(z.object({})).optional(), discounts: z.array(z.object({})).optional(), originalId: z.number().int().optional()})).optional(), shippingLineItems: z.array(z.object({})).optional(), discounts: z.array(z.object({})).optional(), taxes: z.array(z.object({})).optional(), customer: z.object({id: z.number().int().optional()}).optional(), billingAddress: z.object({address1: z.string().optional(), address2: z.string().optional(), city: z.string().optional(), state: z.string().optional(), zip: z.string().optional()}).optional(), shippingAddress: z.object({address1: z.string().optional(), address2: z.string().optional(), city: z.string().optional(), state: z.string().optional(), zip: z.string().optional()}).optional(), masterCardSecureCode: z.string().optional(), status: z.string().optional(), payments: z.array(z.object({})).optional(), barCode: z.string().optional(), allowCreditCard: z.boolean().optional(), isShippingSameAsBilling: z.boolean().optional(), orderId: z.number().int().optional(), legacy: z.boolean().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 Invoice * * POST /v3/invoice */ export const createApiV3Invoice = async (args: CreateApiV3InvoiceArgs, options?: CreateApiV3InvoiceOptions) => { const {baseUrl = "https://sandbox.api.mxmerchant.com/checkout", fetch: fetchFn = fetch, sec0} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.echo != null) query.append("echo", String(args.echo)) if (sec0 !== undefined) headers.set('authorization', `Basic ${btoa(`${sec0.username}:${sec0.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/invoice${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(createApiV3InvoiceResponse, await res.json()) };