import {z} from 'zod' export type OrderAddressCreate = {zip_code: string, street: string, number: string, complement?: (string | null) | undefined, district: string, city: string, state: string, country: string}; export type OrderItemCreate = {sku: string, name: string, quantity: number, unit_price: number, discount?: number | undefined, total_price: number, category?: (string | null) | undefined, metadata?: (Record | null) | undefined}; export type OrderPaymentInput = {method: string, amount: number, installments?: number | undefined, gateway_payment_id?: (string | null) | undefined, status: 'PENDING' | 'PAID' | 'REJECTED' | 'REFUNDED'}; export type OrderTotalsCreate = {subtotal: number, shipping: number, discount: number, total: number}; export type OrderCreate = {requested_strategy_code?: (string | null) | undefined, source_store?: (string | null) | undefined, shipping_method?: (string | null) | undefined, currency?: ('BRL' | 'USD') | undefined, customer_id?: (string | null) | undefined, shipping_address?: (OrderAddressCreate | null) | undefined, billing_address?: (OrderAddressCreate | null) | undefined, items: Array, payments: Array, totals: OrderTotalsCreate, metadata?: ({[key: string]: unknown} | null) | undefined, external_order_id: string, channel_code: string}; export type CreateApiApiV1OrdersArgs = {body: OrderCreate}; export type CreateApiApiV1OrdersOptions = {baseUrl?: string | undefined, basic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const orderCreateResponse = z.object({id: z.string(), external_order_id: z.string(), channel_id: z.string(), customer_id: z.string().nullable(), requested_strategy_code: z.string().nullable(), source_store: z.string().nullable(), shipping_method: z.string().nullable(), status: z.string(), state_machine_version_id: z.string(), state_machine_id: z.string(), currency: z.enum(["BRL", "USD"]), subtotal: z.number(), shipping: z.number(), discount: z.number(), total: z.number(), item_count: z.number(), created_at: z.string(), updated_at: z.string()}); 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 channel order (synchronous) * * POST /api/v1/orders * * Also accepts auth: bearer */ export const createApiApiV1Orders = async (args: CreateApiApiV1OrdersArgs, options?: CreateApiApiV1OrdersOptions) => { const {baseUrl = "https://oms-api.tenant.krzlabs.io", fetch: fetchFn = fetch, basic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basic !== undefined) headers.set('authorization', `Basic ${btoa(`${basic.username}:${basic.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(orderCreateResponse, await res.json()) };