import {z} from 'zod' export type PromotionValidityCreate = {starts_at: string, ends_at?: (string | null) | undefined, recurring_weekdays: Array<'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY'>}; export type PromotionEligibilityCreate = {scope: 'ALL' | 'ONLY' | 'EXCEPT', cluster_ids: Array, strategy_ids: Array, apply_to_all_channels: boolean, channel_ids: Array}; export type PromotionBenefitCreate = {type: 'DISCOUNT' | 'SHIPPING' | 'GIFT', kind?: string | undefined, value?: number | undefined, apply_by?: ('CART' | 'ITEM') | undefined, quantity?: number | undefined, product_ids?: Array | undefined}; export type PromotionItemRestrictionCreate = {dimension: 'PRODUCT' | 'CATEGORY', operator: 'IN' | 'NOT_IN', values: Array}; export type PromotionConditionCreate = {type: 'ORDER_VALUE' | 'SHIPPING_TYPE' | 'PAYMENT_METHOD' | 'INSTALLMENTS', min?: number | undefined, max?: number | undefined, values?: Array | undefined}; export type PromotionEligibleItemsLimitCreate = {limit: number, count_by: 'ORDER' | 'PRODUCT'}; export type PromotionUsageLimitsCreate = {per_customer?: (number | null) | undefined, total?: (number | null) | undefined, eligible_items?: (PromotionEligibleItemsLimitCreate | null) | undefined}; export type PromotionAccumulationCreate = {with_discount_promotions: boolean, with_manual_prices: boolean}; export type PromotionCreate = {code: string, name: string, description?: (string | null) | undefined, validity: PromotionValidityCreate, eligibility: PromotionEligibilityCreate, benefit: PromotionBenefitCreate, item_restrictions: Array, conditions: Array, usage_limits: PromotionUsageLimitsCreate, accumulation: PromotionAccumulationCreate, metadata?: Record | undefined}; export type CreateApiApiV1PromotionsArgs = {body: PromotionCreate}; export type CreateApiApiV1PromotionsOptions = {baseUrl?: string | undefined, basic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const promotionCreateResponse = z.object({id: z.string(), code: z.string(), name: z.string(), description: z.string().nullable(), active: z.boolean(), validity: z.object({}), eligibility: z.object({}), benefit: z.object({}), item_restrictions: z.array(z.object({})), conditions: z.array(z.object({})), usage_limits: z.object({}), accumulation: z.object({}), metadata: z.object({}).nullable(), created_at: z.string(), updated_at: z.string()}); 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 promotion * * POST /api/v1/promotions * * Also accepts auth: bearer */ export const createApiApiV1Promotions = async (args: CreateApiApiV1PromotionsArgs, options?: CreateApiApiV1PromotionsOptions) => { const {baseUrl = "https://oms-api.tenant.krzlabs.io", fetch: fetchFn = fetch, basic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (basic !== undefined) headers.set('authorization', `Basic ${btoa(`${basic.username}:${basic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/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(promotionCreateResponse, await res.json()) };