import {z} from 'zod' export type GetApiV2OrdersArgs = {order_ids?: Array | undefined, statuses?: (Array<'AWAITING_FRAUD_CHECK' | 'AWAITING_ACCEPTANCE' | 'AWAITING_PAYMENT' | 'AWAITING_SHIPMENT' | 'SHIPPED' | 'DELIVERED' | 'CLOSED'>) | undefined, updated_from?: string | undefined, fulfillment_type?: ('FULFILLED_BY_SELLER' | 'FULFILLED_BY_PARTNER') | undefined, page_token?: string | undefined, limit?: number | undefined}; export type GetApiV2OrdersOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const address = z.object({additional_info: z.string().optional(), city: z.string(), company: z.string().optional(), country: z.string().optional(), country_iso_code: z.string().optional(), first_name: z.string().optional(), last_name: z.string(), phone: z.string().optional(), state: z.string().optional(), street: z.string().optional(), street_additional_info: z.string().optional(), zip_code: z.string().optional()}); export const billingInfo = z.object({address: address.optional()}); export const customAttributeResponse = z.object({id: z.string().min(1).max(255), type: z.enum(["STRING", "NUMERIC", "BOOLEAN", "DATE", "LIST"]), value: z.object({})}); export const customAttributesResponse = z.array(customAttributeResponse); export const fulfillment = z.object({code: z.string().optional(), type: z.enum(["FULFILLED_BY_SELLER", "FULFILLED_BY_PARTNER"])}); export const money = z.object({amount: z.number().gte(0), currency: z.string().min(1)}); export const taxAdjustment = z.object({amount: money, code: z.string()}); export const adjustment = z.object({adjustment_id: z.string(), created_at: z.string(), id: z.string(), price: money, quantity: z.number().int(), reason: z.enum(["CUSTOMER_CANCELATION", "OUT_OF_STOCK", "RETURN", "ITEM_NOT_RECEIVED", "AGREEMENT", "DEFECT", "UNABLE_TO_DELIVER", "CHANNEL_SPECIFIC"]), shipping_price: money, shipping_taxes: z.array(taxAdjustment).optional(), taxes: z.array(taxAdjustment).optional(), type: z.enum(["REFUND", "CANCELATION"])}); export const orderProduct = z.object({id: z.string(), title: z.string()}); export const tax = z.object({amount: money, channel_collectible: money.optional(), code: z.string(), rate: z.number().optional(), seller_collectible: money.optional()}); export const orderLineResponse = z.object({adjustments: z.array(adjustment), can_cancel: z.boolean(), can_refund: z.boolean(), channel_order_line_id: z.string(), custom_attributes: customAttributesResponse, id: z.string(), price: money, product: orderProduct, quantity: z.number().int(), ship_from: z.object({warehouse: z.object({id: z.string().optional()}).optional()}).optional(), shipping_taxes: z.array(tax), status: z.enum(["AWAITING_FRAUD_CHECK", "AWAITING_ACCEPTANCE", "AWAITING_PAYMENT", "AWAITING_SHIPMENT", "SHIPPED", "DELIVERED", "CLOSED", "CHANNEL_SPECIFIC"]), status_reason: z.enum(["REFUSED", "ACCEPTANCE_TIMEOUT", "FRAUD_CHECK_FAILED", "FRAUD_CHECK_TIMEOUT", "REFUSED_PAYMENT", "PAYMENT_TIMEOUT", "CANCELED", "REFUNDED", "AUTOMATICALLY_CLOSED"]).optional(), taxes: z.array(tax), total_shipping_price: money}); export const origin = z.object({channel_id: z.string(), channel_name: z.string().optional(), channel_store_id: z.string().optional(), channel_store_name: z.string().optional(), sub_channel_code: z.string().optional(), sub_channel_name: z.string().optional()}); export const shippingInfo = z.object({address: address.optional(), carrier: z.string().optional(), delivery_date: z.object({earliest: z.string(), latest: z.string()}).optional(), email: z.string().optional(), method: z.string().optional(), pudo_id: z.string().optional(), shipping_deadline: z.string().optional()}); export const orderResponse = z.object({anonymized_at: z.string().optional(), billing_info: billingInfo.optional(), channel_order_id: z.string(), channel_updated_at: z.string().optional(), created_at: z.string(), custom_attributes: customAttributesResponse, fulfillment: fulfillment, id: z.string(), order_lines: z.array(orderLineResponse), origin: origin, shipping_info: shippingInfo, status: z.enum(["AWAITING_FRAUD_CHECK", "AWAITING_ACCEPTANCE", "AWAITING_PAYMENT", "AWAITING_SHIPMENT", "SHIPPED", "DELIVERED", "CLOSED", "CHANNEL_SPECIFIC"]), status_reason: z.enum(["REFUSED", "ACCEPTANCE_TIMEOUT", "FRAUD_CHECK_FAILED", "FRAUD_CHECK_TIMEOUT", "REFUSED_PAYMENT", "PAYMENT_TIMEOUT", "CANCELED", "REFUNDED", "AUTOMATICALLY_CLOSED"]).optional(), updated_at: z.string()}); export const ordersPageResponse = z.object({next_page_token: z.string().min(1).optional(), previous_page_token: z.string().min(1).optional(), data: z.array(orderResponse)}); 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 }; /** * v2-listOrders - List Mirakl Connect orders * * GET /v2/orders */ export const getApiV2Orders = async (args: GetApiV2OrdersArgs, options?: GetApiV2OrdersOptions) => { const {baseUrl = "https://miraklconnect.com/api", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.order_ids ?? []) query.append("order_ids", String(item)) for (const item of args.statuses ?? []) query.append("statuses", String(item)) if (args.updated_from != null) query.append("updated_from", String(args.updated_from)) if (args.fulfillment_type != null) query.append("fulfillment_type", String(args.fulfillment_type)) if (args.page_token != null) query.append("page_token", String(args.page_token)) if (args.limit != null) query.append("limit", String(args.limit)) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/orders${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(ordersPageResponse, await res.json()) };