import {z} from 'zod' export type FormLineItem = {productId: string, variantId: string, quantity: number}; export type CreateDashboardOrderForm = {cost?: (number | null) | undefined, items: Array, gateway: string, couponCode?: (string | null) | undefined, affiliateCode?: (string | null) | undefined, emailAddress: string, returnUrl?: (string | null) | undefined, sendReceipt: boolean, metadata?: ({[key: string]: string} | null) | undefined, ipAddress?: (string | null) | undefined, userAgent?: (string | null) | undefined, countryCode?: (string | null) | undefined}; export type CreateApiStoresStoreIdOrdersArgs = {storeId: string, body: CreateDashboardOrderForm}; export type CreateApiStoresStoreIdOrdersOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const publicVolumeDiscountType = z.union([z.literal(0), z.literal(1), z.literal(2)]); export const billingInterval = z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4)]); export const publicLineItem = z.object({id: z.string(), dateCreated: z.string(), productName: z.string(), productId: z.string(), variantId: z.string(), variantName: z.string(), amount: z.number(), lineTotal: z.number(), additionalFeePercentage: z.number(), additionalFeeAmount: z.number(), additionalFixedFeeAmount: z.number(), volumeDiscountAmount: z.number(), volumeDiscountType: publicVolumeDiscountType.optional(), volumeDiscountValue: z.number().nullable().optional(), volumeDiscountTierQuantity: z.number().int().nullable().optional(), quantity: z.number().int(), billingInterval: billingInterval.optional(), customIntervalDays: z.number().int().nullable().optional()}); export const publicCustomerDetails = z.object({id: z.string(), dateCreated: z.string(), countryCode: z.string(), emailAddress: z.string(), customerId: z.string()}); export const publicChargeback = z.object({id: z.string(), dateCreated: z.string(), status: z.string(), reason: z.string()}); export const publicGatewayMetadata = z.object({id: z.string(), dateCreated: z.string(), transactionId: z.string().nullable().optional(), clientSecret: z.string().nullable().optional(), note: z.string().nullable().optional(), cryptocurrencyAddress: z.string().nullable().optional(), cryptocurrencyAmount: z.number().nullable().optional(), cryptocurrencyExpiration: z.string().nullable().optional()}); export const publicOrderCoupon = z.object({id: z.string(), dateCreated: z.string(), percentageDecrease: z.number().nullable().optional(), netDecrease: z.number(), code: z.string(), couponId: z.string()}); export const publicOrderDiscount = z.object({id: z.string(), dateCreated: z.string(), percentageDecrease: z.number().nullable().optional(), netDecrease: z.number()}); export const publicOrderTax = z.object({taxAmount: z.number(), taxRate: z.number(), taxName: z.string(), isReverseCharge: z.boolean(), customerVatId: z.string().nullable().optional(), preTaxAmount: z.number(), taxBehavior: z.string()}); export const publicStoredFile = z.object({id: z.string(), dateCreated: z.string(), friendlyName: z.string().min(1).max(128)}); export const publicDeliveredItem = z.object({id: z.string(), dateCreated: z.string(), orderId: z.string(), storeId: z.string(), productId: z.string().nullable().optional(), variantId: z.string().nullable().optional(), type: z.string().max(128), source: z.string().max(128), textContent: z.string().max(10000).nullable().optional(), file: publicStoredFile.optional()}); export const publicOrderDiscordAccount = z.object({discordUserId: z.string(), username: z.string(), displayName: z.string().nullable().optional(), avatarUrl: z.string().nullable().optional()}); export const publicOrder = z.object({id: z.string(), dateCreated: z.string(), items: z.array(publicLineItem), currencyCode: z.string(), gateway: z.string(), customer: publicCustomerDetails, chargeback: publicChargeback.optional(), gatewayMetadata: publicGatewayMetadata, status: z.string(), amountPaid: z.number(), amount: z.number(), coupon: publicOrderCoupon.optional(), affiliateDiscount: publicOrderDiscount.optional(), tax: publicOrderTax.optional(), globalGatewayFeePercentage: z.number(), globalGatewayFeeAmount: z.number(), globalGatewayFixedFee: z.number(), globalGatewayFixedFeeAmount: z.number(), deliveredItems: z.array(publicDeliveredItem), customFieldAnswers: z.record(z.string(), z.string()).nullable().optional(), returnUrl: z.string().nullable().optional(), metadata: z.record(z.string(), z.string()).nullable().optional(), source: z.string(), discordAccount: publicOrderDiscordAccount.optional(), marketingOptIn: z.boolean().nullable().optional()}); export const publicOrderResponse = z.object({success: z.boolean(), message: z.string().nullable().optional(), code: z.string().nullable().optional(), data: publicOrder.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 /stores/{storeId}/orders */ export const createApiStoresStoreIdOrders = async (args: CreateApiStoresStoreIdOrdersArgs, options?: CreateApiStoresStoreIdOrdersOptions) => { const {baseUrl = "https://api.komerza.com", 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(/\/+$/, '')}/stores/${encodeURIComponent(String(args.storeId))}/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(publicOrderResponse, await res.json()) };