import {z} from 'zod' export type OrderAddressAdditionalIdentifier = {identifier?: string | undefined, type?: string | undefined}; export type OrderPostDeliveryAddress = {name?: string | undefined, company?: string | undefined, phone?: string | undefined, email?: string | undefined, street: string, street2?: string | undefined, zip?: string | undefined, city: string, state?: string | undefined, countryIso2: string, addressIdentifier?: string | undefined, additionalIdentifiers?: Array | undefined, latitude?: number | undefined, longitude?: number | undefined}; export type OrderPostAddress = {name?: string | undefined, company?: string | undefined, phone?: string | undefined, email?: string | undefined, street: string, street2?: string | undefined, zip?: string | undefined, city: string, state?: string | undefined, countryIso2: string}; export type OrderPostPosition = {sku: string, name: string, quantity: number, price?: number | undefined, lot?: string | undefined, expirationDate?: string | undefined, location?: string | undefined, positionIdentifier?: string | undefined, productIdentifier?: string | undefined, customAttributes?: {[key: string]: string} | undefined}; export type OrderAttachmentPost = {filename?: string | undefined, printerType: 'LABEL_PRINTER' | 'DOCUMENT_PRINTER' | 'DOCUMENT_PRINTER_2_A6' | 'DOCUMENT_PRINTER_2_FOLIO', attachmentPlacement: 'INSIDE_PACKAGE' | 'OUTSIDE_PACKAGE', copyCount: number, printingType?: ('ORDER' | 'SHIPMENT') | undefined, fileKey?: string | undefined, mimeType?: string | undefined}; export type OrderPost = {sellerId: number, warehouseId?: number | undefined, orderIdentifier: string, orderReference: string, hasInvoiceAddress?: boolean | undefined, hasInvoiceData?: boolean | undefined, deliveryAddress: OrderPostDeliveryAddress, invoiceAddress?: OrderPostAddress | undefined, orderDate?: string | undefined, currencyCode?: string | undefined, invoiceIds?: Array | undefined, comment?: string | undefined, positions: Array, earliestDeliveryDate?: string | undefined, latestDeliveryDate?: string | undefined, transportInsuranceAmount?: number | undefined, cashOnDeliveryAmount?: number | undefined, cashOnDeliveryCurrency?: string | undefined, shippingMethodIdentifier?: string | undefined, shippingMethodName?: string | undefined, tags?: Array | undefined, trackingEnabled?: boolean | undefined, orderPriority?: number | undefined, orderReference2?: string | undefined, customerPurchaseOrderNumber?: string | undefined, ssccLabel?: boolean | undefined, channelId?: string | undefined, channelName?: string | undefined, attachments?: Array | undefined, customAttributes?: {[key: string]: string} | undefined}; export type CreateApiOrdersArgs = {body: OrderPost}; export type CreateApiOrdersOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const orderPostResult = z.object({status: z.string().optional(), field: z.string().optional(), message: z.string().optional(), orderId: z.number().int().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 order * * POST /orders */ export const createApiOrders = async (args: CreateApiOrdersArgs, options?: CreateApiOrdersOptions) => { const {baseUrl = "https://api.quivo.co", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/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(orderPostResult, await res.json()) };