import {z} from 'zod' export type RewardValidityDailyHoursRequest = {days_of_week: Array, start_time: string, end_time: string}; export type RewardValidityHoursRequest = {type: 'DAILY' | 'ANY_TIME', daily?: (Array | null) | undefined}; export type LoyaltyV2ActivityRewardMaterialProduct = {id: string}; export type LoyaltyV2ActivityRewardMaterialSKU = {product_id: string, id: string}; export type RewardMaterialRequest = {type: 'PRODUCT' | 'SKU', product?: (LoyaltyV2ActivityRewardMaterialProduct | null) | undefined, sku?: (LoyaltyV2ActivityRewardMaterialSKU | null) | undefined}; export type LoyaltyV2ActivityRewardDigitalDiscountCoupons = {campaign_id: string}; export type RewardDigitalGiftVouchersRequest = {campaign_id: string, balance: number}; export type RewardDigitalLoyaltyCardPointsRequest = {points: number, card_definition_id: string}; export type RewardDigitalRequest = {type: 'DISCOUNT_COUPONS' | 'GIFT_VOUCHERS' | 'LOYALTY_CARD_POINTS', discount_coupons?: (LoyaltyV2ActivityRewardDigitalDiscountCoupons | null) | undefined, gift_vouchers?: (RewardDigitalGiftVouchersRequest | null) | undefined, loyalty_card_points?: (RewardDigitalLoyaltyCardPointsRequest | null) | undefined}; export type RewardCostRulesRequest = {logic: string}; export type RewardCostSpendingRequest = {id?: string | undefined, name?: (string | null) | undefined, points: number, card_definition_id: string}; export type RewardCostCreateRequest = {rules?: RewardCostRulesRequest | undefined, spending: Array}; export type RewardPurchaseLimitsCooldownFixedCooldownPeriodInput = {value: number, unit: 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR'}; export type RewardPurchaseLimitsCooldownFixedCooldownInput = {period: RewardPurchaseLimitsCooldownFixedCooldownPeriodInput}; export type RewardPurchaseLimitsCooldownInput = {type: 'NO_COOLDOWN' | 'FIXED_COOLDOWN', fixed_cooldown?: (RewardPurchaseLimitsCooldownFixedCooldownInput | null) | undefined}; export type CardDefinitionSpendingLimitsGlobalTimeBasedCurrentPeriodInput = {unit: 'DAY' | 'WEEK' | 'MONTH' | 'QUARTER' | 'YEAR'}; export type CardDefinitionSpendingLimitsGlobalTimeBasedPeriodInput = {type: 'CURRENT_PERIOD', current_period?: (CardDefinitionSpendingLimitsGlobalTimeBasedCurrentPeriodInput | null) | undefined}; export type RewardPurchaseLimitsFrequencyLimitTriggersInput = {max: number}; export type RewardPurchaseLimitsFrequencyLimitInput = {type: 'TIME_BASED', period: CardDefinitionSpendingLimitsGlobalTimeBasedPeriodInput, triggers: RewardPurchaseLimitsFrequencyLimitTriggersInput}; export type RewardPurchaseLimitsFrequencyInput = {type: 'NO_LIMIT' | 'LIMITED', limits?: (Array | null) | undefined}; export type RewardPurchaseLimitsInput = {cooldown?: (RewardPurchaseLimitsCooldownInput | null) | undefined, frequency?: (RewardPurchaseLimitsFrequencyInput | null) | undefined}; export type LoyaltyV2ActivityRewardRefunds = {type: 'NONE' | 'REFUNDABLE'}; export type V2LoyaltiesRewardsCreateRequestBody = {name: string, type: 'MATERIAL' | 'DIGITAL', status?: ('DRAFT' | 'ACTIVE') | undefined, validity_hours?: (RewardValidityHoursRequest | null) | undefined, start_date?: (string | null) | undefined, end_date?: (string | null) | undefined, material?: (RewardMaterialRequest | null) | undefined, digital?: (RewardDigitalRequest | null) | undefined, costs: Array, purchase_limits?: (RewardPurchaseLimitsInput | null) | undefined, refunds?: (LoyaltyV2ActivityRewardRefunds | null) | undefined, metadata?: (Record | null) | undefined}; export type CreateApiV2LoyaltiesRewardsArgs = {body: V2LoyaltiesRewardsCreateRequestBody}; export type CreateApiV2LoyaltiesRewardsOptions = {baseUrl?: string | undefined, XAppId?: string | undefined, XAppToken?: string | undefined, fetch?: typeof fetch | undefined}; export const loyaltyV2ActivityRewardValidityDailyHoursResponse = z.object({days_of_week: z.array(z.number().int().gte(0).lte(6)), start_time: z.string(), end_time: z.string()}); export const rewardValidityHoursResponse = z.object({type: z.enum(["DAILY", "ANY_TIME"]), daily: z.array(loyaltyV2ActivityRewardValidityDailyHoursResponse).optional()}); export const loyaltyV2ActivityRewardMaterialProduct = z.object({id: z.string()}); export const loyaltyV2ActivityRewardMaterialSKU = z.object({product_id: z.string(), id: z.string()}); export const rewardMaterialResponse = z.object({type: z.enum(["PRODUCT", "SKU"]), product: loyaltyV2ActivityRewardMaterialProduct.optional(), sku: loyaltyV2ActivityRewardMaterialSKU.optional()}); export const loyaltyV2ActivityRewardDigitalDiscountCoupons = z.object({campaign_id: z.string()}); export const loyaltyV2ActivityRewardDigitalGiftVouchersResponse = z.object({campaign_id: z.string(), balance: z.number()}); export const loyaltyV2ActivityRewardDigitalLoyaltyCardPointsResponse = z.object({points: z.number().int(), card_definition_id: z.string()}); export const rewardDigitalResponse = z.object({type: z.enum(["DISCOUNT_COUPONS", "GIFT_VOUCHERS", "LOYALTY_CARD_POINTS"]), discount_coupons: loyaltyV2ActivityRewardDigitalDiscountCoupons.optional(), gift_vouchers: loyaltyV2ActivityRewardDigitalGiftVouchersResponse.optional(), loyalty_card_points: loyaltyV2ActivityRewardDigitalLoyaltyCardPointsResponse.optional()}); export const loyaltyV2ActivityRewardRefunds = z.object({type: z.enum(["NONE", "REFUNDABLE"])}); export const rewardCostRuleGroupResponse = z.object({logic: z.string().optional()}); export const loyaltyV2ActivityRewardCostSpendingResponse = z.object({id: z.string(), name: z.string().max(200).nullable().optional(), points: z.number().int(), card_definition_id: z.string()}); export const rewardCostTierRulesAnyOfEntryResponse = z.object({tier_structure_id: z.string(), tier_ids: z.array(z.string())}); export const rewardCostTierRulesResponse = z.object({type: z.enum(["NO_REQUIREMENTS", "ANY_OF"]), any_of: z.array(rewardCostTierRulesAnyOfEntryResponse).optional()}); export const rewardCostResponse = z.object({id: z.string(), name: z.string().max(200).nullable().optional(), rules: rewardCostRuleGroupResponse.optional(), spending: z.array(loyaltyV2ActivityRewardCostSpendingResponse).nullable().optional(), tier_rules: rewardCostTierRulesResponse}); export const loyaltyV2ActivityRewardPurchaseLimitsCooldownFixedCooldownPeriod = z.object({value: z.number().int().gte(1), unit: z.enum(["HOUR", "DAY", "WEEK", "MONTH", "YEAR"])}); export const rewardPurchaseLimitsCooldownFixedCooldown = z.object({period: loyaltyV2ActivityRewardPurchaseLimitsCooldownFixedCooldownPeriod}); export const rewardPurchaseLimitsCooldown = z.object({type: z.enum(["NO_COOLDOWN", "FIXED_COOLDOWN"]), fixed_cooldown: rewardPurchaseLimitsCooldownFixedCooldown.optional()}); export const loyaltyV2ActivityCardDefinitionLimitTimeBasedPeriod = z.object({type: z.literal("CURRENT_PERIOD"), current_period: z.object({unit: z.enum(["DAY", "WEEK", "MONTH", "QUARTER", "YEAR"])}).optional()}); export const loyaltyV2ActivityRewardPurchaseLimitsFrequencyLimitTriggers = z.object({max: z.number().int().gte(1)}); export const rewardPurchaseLimitsFrequencyLimit = z.object({type: z.literal("TIME_BASED"), period: loyaltyV2ActivityCardDefinitionLimitTimeBasedPeriod, triggers: loyaltyV2ActivityRewardPurchaseLimitsFrequencyLimitTriggers}); export const rewardPurchaseLimitsFrequency = z.object({type: z.enum(["NO_LIMIT", "LIMITED"]), limits: z.array(rewardPurchaseLimitsFrequencyLimit)}); export const rewardPurchaseLimits = z.object({cooldown: rewardPurchaseLimitsCooldown, frequency: rewardPurchaseLimitsFrequency}); export const v2LoyaltiesRewardsCreateResponseBody = z.object({id: z.string(), name: z.string(), type: z.enum(["MATERIAL", "DIGITAL"]), status: z.enum(["ACTIVE", "DRAFT", "INACTIVE", "DELETED"]), start_date: z.string().nullable(), end_date: z.string().nullable(), validity_hours: rewardValidityHoursResponse, material: rewardMaterialResponse.optional(), digital: rewardDigitalResponse.optional(), refunds: loyaltyV2ActivityRewardRefunds, costs: z.array(rewardCostResponse), purchase_limits: rewardPurchaseLimits, metadata: z.object({}), created_at: z.string(), updated_at: z.string().nullable(), object: z.literal("reward")}); 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 a reward * * POST /v2/loyalties/rewards * * Also accepts auth: bearerAuth */ export const createApiV2LoyaltiesRewards = async (args: CreateApiV2LoyaltiesRewardsArgs, options?: CreateApiV2LoyaltiesRewardsOptions) => { const {baseUrl = "https://api.voucherify.io", fetch: fetchFn = fetch, XAppId, XAppToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (XAppId !== undefined) headers.set("X-App-Id", XAppId) if (XAppToken !== undefined) headers.set("X-App-Token", XAppToken) const url = `${baseUrl.replace(/\/+$/, '')}/v2/loyalties/rewards${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(v2LoyaltiesRewardsCreateResponseBody, await res.json()) };