import {z} from 'zod' export type ActionError = {code: 'INVALID_INPUT' | 'DATA_NOT_FOUND' | 'UNEXPECTED' | 'UNAVAILABLE' | 'TOO_MANY_REQUEST' | 'ACTION_NOT_SUPPORTED' | 'ORDER_IN_WRONG_STATE' | 'INVALID_PRODUCT_ID' | 'OUT_OF_STOCK' | 'RETURN_IN_WRONG_STATE' | 'OTHER', message: string}; export type ActionItemRequest = {entity_id: string, entity_type: 'ORDER', errors?: Array | undefined, executed_at: string, status: 'FAILED' | 'SUCCESS', type: 'SYNCHRONIZE_ORDER' | 'SYNCHRONIZE_ORDER_UPDATE'}; export type ActionRequest = {actions: Array}; export type CreateApiV2OrdersActionsArgs = {body: ActionRequest}; export type CreateApiV2OrdersActionsOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const actionCreatedResponse = z.object({action_id: z.string()}); export const actionsCreatedResponse = z.object({actions: z.array(actionCreatedResponse)}); 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-reportOrderActions - Log order action results and errors * * POST /v2/orders/actions */ export const createApiV2OrdersActions = async (args: CreateApiV2OrdersActionsArgs, options?: CreateApiV2OrdersActionsOptions) => { const {baseUrl = "https://miraklconnect.com/api", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/orders/actions${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(actionsCreatedResponse, await res.json()) };