import {z} from 'zod' export type PromotionRequestShipping = {shippingMethodId?: string | undefined, shippingPrice?: number | undefined}; export type PricePromoParam = {options?: {[key: string]: Record} | undefined}; export type ItemPriceOverride = {sale?: number | undefined, base?: number | undefined}; export type PromotionRequestItem = {lineItemId?: number | undefined, priceList: string, sku?: string | undefined, itemId?: number | undefined, quantity: number, group?: Array | undefined, hierarchy?: Array> | undefined, productAttributes?: ({[key: string]: Array | string}) | undefined, priceParams?: PricePromoParam | undefined, price?: ItemPriceOverride | undefined, channel?: Array | undefined, shippingMethodId?: string | undefined, shippingPrice?: number | undefined}; export type PromotionEvaluationRequest = {traceId?: string | undefined, isLoggedIn?: boolean | undefined, userId?: string | undefined, promoCodes?: Array | undefined, shipping?: Array | undefined, items: Array, date?: string | undefined, userProfile?: Array<{[key: string]: Array}> | undefined}; export type CreateApiV1PromoEvaluatePromotionsArgs = {'x-site-context': string, body: PromotionEvaluationRequest}; export type CreateApiV1PromoEvaluatePromotionsOptions = {baseUrl?: string | undefined, AuthorizationToken?: string | undefined, fetch?: typeof fetch | undefined}; export const itemPrice = z.object({currency: z.string().optional(), base: z.number().optional(), kind: z.string().optional(), totalPrice: z.number().optional(), finalPrice: z.number().optional(), sale: z.number().optional()}); export const itemPriceAttributes = z.object({cost: z.number().optional(), floor: z.number().optional(), clearance: z.number().optional()}); export const offerDiscount = z.object({quantity: z.number().int().optional(), amount: z.number().optional(), unit: z.string().optional(), value: z.number().optional(), promoId: z.string().optional(), promoCode: z.string().optional(), promoTitle: z.string().optional(), type: z.string().optional(), application: z.number().int().optional(), isStackable: z.boolean().optional(), isAlwaysApplied: z.boolean().optional(), level: z.number().int().optional(), stackingType: z.enum(["STACKABLE", "EXCLUSIVE", "TYPE_EXCLUSIVE", "UNIVERSAL"]).optional(), proratedAmount: z.number().optional(), proratedQuantity: z.number().int().optional()}); export const promotionResponseItem = z.object({lineItemId: z.number().int().optional(), sku: z.string().optional(), itemId: z.number().int().optional(), priceList: z.string().optional(), group: z.array(z.string()).optional(), quantity: z.number().optional(), price: itemPrice.optional(), priceAttributes: itemPriceAttributes.optional(), discount: z.array(offerDiscount).optional(), attributes: z.record(z.string(), z.object({})).optional(), shippingPrice: z.number().optional(), shippingMethodId: z.string().optional(), shippingDiscount: z.number().optional()}); export const promotionResponseShipping = z.object({shippingMethodId: z.string().optional(), shippingPrice: z.number().optional(), shippingDiscount: z.number().optional()}); export const appliedDiscount = z.object({promoId: z.string().optional(), promoCode: z.string().optional(), promoTitle: z.string().optional(), type: z.string().optional(), amount: z.number().optional()}); export const suggestedProducts = z.object({promotionId: z.string().optional(), promotionTitle: z.string().optional(), itemId: z.string().optional(), sku: z.string().optional(), eligiblePriceLists: z.array(z.string()).optional(), quantity: z.number().int().optional(), free: z.boolean().optional(), discountType: z.enum(["%OFF", "AMOUNT_OFF", "FIXED_PRICE"]).optional(), amount: z.number().optional()}); export const couponError = z.object({promoCode: z.string().optional(), promoId: z.string().optional(), message: z.string().optional()}); export const rtpePromotionMessages = z.array(z.object({promoId: z.string().optional(), title: z.string().optional(), message: z.string().optional(), pages: z.array(z.enum(["PDP", "PLP", "Cart", "Checkout"])).optional(), locales: z.array(z.string()).optional(), type: z.enum(["DISCOUNT", "PROXIMITY", "POTENTIAL_DISCOUNT"]).optional(), threshold: z.number().int().optional()})); export const promotionEvaluationResponse = z.object({items: z.array(promotionResponseItem).optional(), errors: z.array(z.string()).optional(), shipping: z.array(promotionResponseShipping).optional(), appliedDiscounts: z.array(appliedDiscount).optional(), suggestedProducts: z.array(suggestedProducts).optional(), notAppliedCoupons: z.array(couponError).optional(), promotionMessages: rtpePromotionMessages.optional(), success: z.boolean().optional()}); export const createApiV1PromoEvaluatePromotionsResponse = z.array(promotionEvaluationResponse); 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 }; /** * Evaluate promotions * * POST /v1/promo/evaluate-promotions */ export const createApiV1PromoEvaluatePromotions = async (args: CreateApiV1PromoEvaluatePromotionsArgs, options?: CreateApiV1PromoEvaluatePromotionsOptions) => { const {baseUrl = "https://live.copilot.fabric.inc", fetch: fetchFn = fetch, AuthorizationToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-site-context'] != null) headers.set("x-site-context", String(args['x-site-context'])) if (AuthorizationToken !== undefined) headers.set('authorization', `Bearer ${AuthorizationToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/promo/evaluate-promotions${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(createApiV1PromoEvaluatePromotionsResponse, await res.json()) };