import {z} from 'zod' export type OrderItem = {externalItemId: string, name?: string | undefined, category?: string | undefined, quantity: number, cost?: number | undefined, url?: string | undefined, imageUrl?: string | undefined, description?: string | undefined}; export type Order = {externalOrderId: string, externalCustomerId?: string | undefined, totalCost: number, status: 'INITIALIZED' | 'IN_PROGRESS' | 'DELIVERED' | 'CANCELLED' | 'ABANDONED_SHOPPING_CART', date: string, currency: string, email?: string | undefined, phone?: string | undefined, firstName?: string | undefined, lastName?: string | undefined, shipping?: number | undefined, discount?: number | undefined, taxes?: number | undefined, restoreUrl?: string | undefined, statusDescription?: string | undefined, storeId?: string | undefined, marketId?: string | undefined, source?: string | undefined, deliveryMethod?: string | undefined, paymentMethod?: string | undefined, deliveryAddress?: string | undefined, additionalInfo?: {[key: string]: Record} | undefined, items?: Array | undefined}; export type Orders = {orders?: Array | undefined}; export type CreateApiApiV1OrdersArgs = {body: Orders}; export type CreateApiApiV1OrdersOptions = {baseUrl?: string | undefined, basicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const orderItem = z.object({externalItemId: z.string(), name: z.string().optional(), category: z.string().optional(), quantity: z.number(), cost: z.number().optional(), url: z.string().optional(), imageUrl: z.string().optional(), description: z.string().optional()}); export const order = z.object({externalOrderId: z.string(), externalCustomerId: z.string().optional(), totalCost: z.number(), status: z.enum(["INITIALIZED", "IN_PROGRESS", "DELIVERED", "CANCELLED", "ABANDONED_SHOPPING_CART"]), date: z.string(), currency: z.string(), email: z.string().optional(), phone: z.string().optional(), firstName: z.string().optional(), lastName: z.string().optional(), shipping: z.number().optional(), discount: z.number().optional(), taxes: z.number().optional(), restoreUrl: z.string().optional(), statusDescription: z.string().optional(), storeId: z.string().optional(), marketId: z.string().optional(), source: z.string().optional(), deliveryMethod: z.string().optional(), paymentMethod: z.string().optional(), deliveryAddress: z.string().optional(), additionalInfo: z.record(z.string(), z.object({})).optional(), items: z.array(orderItem).optional()}); export const failedOrder = z.object({order: order, error: z.string()}); export const failedOrders = z.object({failedOrders: z.array(failedOrder).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 }; /** * Add orders * * POST /api/v1/orders */ export const createApiApiV1Orders = async (args: CreateApiApiV1OrdersArgs, options?: CreateApiApiV1OrdersOptions) => { const {baseUrl = "https://api.reteno.com", fetch: fetchFn = fetch, basicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json; charset=UTF-8") if (basicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${basicAuth.username}:${basicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/orders${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(failedOrders, await res.json()) };