import {z} from 'zod' export type SearchPromotionRequest = {size?: number | undefined, offset?: number | undefined, sort?: ('+updatedAt' | '+name' | '+startAt' | '+endAt' | '+level' | '-updatedAt' | '-name' | '-startAt' | '-endAt' | '-level') | undefined, filters?: (Array<{field: string, value: string | Array, operator: 'EQUAL' | 'GREATER_THAN_OR_EQUAL_TO' | 'LESS_THAN' | 'IN'}>) | undefined}; export type CreateApiCouponsSearchArgs = {'x-fabric-tenant-id': string, 'x-fabric-channel-id'?: string | undefined, 'x-client-id'?: string | undefined, 'x-fabric-request-id'?: string | undefined, body: SearchPromotionRequest}; export type CreateApiCouponsSearchOptions = {baseUrl?: string | undefined, AuthorizationToken?: string | undefined, fetch?: typeof fetch | undefined}; export const offsetQuery = z.object({size: z.number().int().gte(1).lte(100).optional(), offset: z.number().int().gte(0).optional(), count: z.number().int().optional()}); export const promotionMessages = z.array(z.object({title: z.string().optional(), message: z.string().optional(), pages: z.array(z.string()).optional(), locales: z.array(z.string()).optional()})); export const proximityMessages = z.object({threshold: z.number().int().gte(0).optional(), localizedMessages: z.array(z.object({locales: z.array(z.string()).optional(), message: z.string().optional()})).optional()}); export const promoSearchObject = z.object({id: z.string().optional(), couponCodes: z.array(z.string()).optional(), couponCodesCount: z.number().optional(), status: z.enum(["ACTIVE", "SCHEDULED", "DISABLED", "EXPIRED"]).optional(), name: z.string().optional(), startAt: z.string().optional(), endAt: z.string().optional(), updatedAt: z.string().optional(), singleMultiUse: z.enum(["MULTI_USE", "SINGLE_USE"]).optional(), type: z.string().optional(), level: z.number().optional(), stackingType: z.enum(["STACKABLE", "EXCLUSIVE", "TYPE_EXCLUSIVE", "UNIVERSAL"]).optional(), isStackable: z.boolean().optional(), isAlwaysApplied: z.boolean().optional(), additionalAttributes: z.array(z.object({name: z.string(), values: z.union([z.string(), z.array(z.string())]), attributeId: z.number().optional()})).optional(), promotionMessages: promotionMessages.optional(), proximityMessages: proximityMessages.optional()}); export const searchPromotionResponse = z.object({query: offsetQuery.optional(), data: z.array(promoSearchObject).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 }; /** * Search for coupons * * POST /coupons/search */ export const createApiCouponsSearch = async (args: CreateApiCouponsSearchArgs, options?: CreateApiCouponsSearchOptions) => { const {baseUrl = "https://api.fabric.inc/v3", 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-fabric-tenant-id'] != null) headers.set("x-fabric-tenant-id", String(args['x-fabric-tenant-id'])) if (args['x-fabric-channel-id'] != null) headers.set("x-fabric-channel-id", String(args['x-fabric-channel-id'])) if (args['x-client-id'] != null) headers.set("x-client-id", String(args['x-client-id'])) if (args['x-fabric-request-id'] != null) headers.set("x-fabric-request-id", String(args['x-fabric-request-id'])) if (AuthorizationToken !== undefined) headers.set('authorization', `Bearer ${AuthorizationToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/coupons/search${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(searchPromotionResponse, await res.json()) };