import {z} from 'zod' export type SellerId = string; export type ChannelOrderStatus = 'UNACKED' | 'CREATED' | 'ACCEPTED' | 'SHIPPED' | 'PARTIALLY_SHIPPED' | 'CANCELED_BY_SELLER' | 'CANCELED_BY_BUYER'; export type ChannelOrderId = string; export type OrderItemId = unknown; export type OrderItemStatus = 'UNSHIPPED' | 'SHIPPED' | 'CANCELED_BY_SELLER' | 'CANCELED_BY_BUYER' | 'RETURNED' | 'REFUNDED'; export type OrderItemPaymentStatus = 'PENDING' | 'PAID'; export type OfferId = number; export type ChannelOfferId = string; export type SKU = string; export type AdditionalOrderDataGroupValues = {key?: string | undefined, value?: string | undefined}; export type AdditionalOrderDataGroup = {group?: string | undefined, values?: Array | undefined}; export type ShippingGroup = string; export type OrderItem = {orderItemId: OrderItemId, type: string, itemStatus?: OrderItemStatus | undefined, itemPaymentStatus?: OrderItemPaymentStatus | undefined, grossPrice: string, total: string, taxPercent?: (string | null) | undefined, grossFee?: (string | null) | undefined, offerId?: OfferId | undefined, channelOfferId?: ChannelOfferId | undefined, sku?: SKU | undefined, quantity?: string | undefined, title?: string | undefined, estimatedShippingDate?: string | undefined, estimatedDeliveryDate?: string | undefined, remainingQuantity?: (string | null) | undefined, additionalOrderItemData?: Array | undefined, shipFromCountry?: (string | null) | undefined} | {orderItemId: OrderItemId, type: string, grossPrice: string, taxPercent?: (string | null) | undefined, shippingGroup: ShippingGroup} | {orderItemId: OrderItemId, type: string, grossPrice: string, taxPercent?: (string | null) | undefined, note: string}; export type Address = {firstName?: string | undefined, lastName: string, gender?: ('male' | 'female' | 'diverse') | undefined, companyName?: string | undefined, street: string, houseNumber?: string | undefined, addition?: string | undefined, postcode?: string | undefined, city: string, phone?: string | undefined, country: string, state?: (string | null) | undefined}; export type OrderBuyer = {email?: string | undefined, vatId?: string | undefined}; export type Order = {sellerId: SellerId, orderStatus: ChannelOrderStatus, orderAcceptUntil?: string | undefined, paymentMethod?: string | undefined, paymentReference?: string | undefined, orderId: ChannelOrderId, purchasedAt: string, lastChangedAt: string, currency: string, orderItem: Array, billingAddress?: Address | undefined, shippingAddress?: Address | undefined, note?: string | undefined, buyer?: OrderBuyer | undefined, weeePickup?: (boolean | null) | undefined, language?: (string | null) | undefined, invoiceDocumentTransfer?: ('not-set' | 'from-seller' | 'from-channel' | null) | undefined, additionalOrderData?: Array | undefined, fbc?: (boolean | null) | undefined, b2b?: (boolean | null) | undefined, salesChannelName?: (string | null) | undefined}; export type OrderList = {orderList: Array}; export type CreateApiV1ChannelOrderArgs = {body: OrderList}; export type CreateApiV1ChannelOrderOptions = {baseUrl?: string | undefined, ChannelAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const errorResponseList = z.object({errorList: z.array(z.object({code: z.string().optional(), message: z.string().optional(), severity: z.enum(["error", "warning", "info"]).optional(), hint: z.string().nullable().optional()})).nullable().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 Orders * * POST /v1/channel/order */ export const createApiV1ChannelOrder = async (args: CreateApiV1ChannelOrderArgs, options?: CreateApiV1ChannelOrderOptions) => { const {baseUrl = "https://scx-sbx.api.jtl-software.com", fetch: fetchFn = fetch, ChannelAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ChannelAuth !== undefined) headers.set('authorization', `Bearer ${ChannelAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/channel/order${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(errorResponseList, await res.json()) };