All files / src/lib/promotions validators.ts

95.02% Statements 325/342
41.66% Branches 10/24
100% Functions 9/9
95.02% Lines 325/342

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 3431x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 5x   5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { z } from "zod";
import type { PromotionType, DiscountType, PromotionTargetType } from "@prisma/client";
 
// Promotion type enum values
const promotionTypes: PromotionType[] = [
  "PERCENTAGE_OFF",
  "FIXED_AMOUNT_OFF",
  "BOGO",
  "FREE_SHIPPING",
  "BUNDLE",
  "FREE_GIFT",
  "TIERED",
  "LOYALTY_REDEMPTION",
  "REFERRAL",
  "FLASH_SALE",
  "SEASONAL",
  "FIRST_PURCHASE",
];
 
// Discount type enum values
const discountTypes: DiscountType[] = ["PERCENTAGE", "FIXED_AMOUNT"];
 
// Target type enum values
const targetTypes: PromotionTargetType[] = [
  "ALL_PRODUCTS",
  "SPECIFIC_PRODUCTS",
  "SPECIFIC_CATEGORIES",
  "CART_TOTAL",
  "SHIPPING",
];
 
// Condition types
const conditionTypes = [
  "min_quantity",
  "min_amount",
  "max_amount",
  "includes_product",
  "includes_category",
  "excludes_product",
  "excludes_category",
  "customer_segment",
  "first_purchase",
  "day_of_week",
  "time_of_day",
  "cart_item_count",
] as const;
 
// Operators
const operators = [
  "equals",
  "not_equals",
  "greater_than",
  "less_than",
  "greater_than_or_equal",
  "less_than_or_equal",
  "in",
  "not_in",
  "between",
] as const;
 
// Condition schema
export const conditionSchema = z.object({
  conditionType: z.enum(conditionTypes),
  operator: z.enum(operators),
  value: z.string(), // JSON string that will be parsed
});
 
// BOGO config schema
export const bogoConfigSchema = z.object({
  buyQuantity: z.number().int().min(1),
  getQuantity: z.number().int().min(1),
  getProductId: z.number().int().optional(),
  getCategoryId: z.number().int().optional(),
  discountPercent: z.number().min(0).max(100).default(100)});
 
// Bundle product schema
export const bundleProductSchema = z.object({
  productId: z.number().int(),
  quantity: z.number().int().min(1).default(1)});
 
// Bundle config schema
export const bundleConfigSchema = z.object({
  bundlePrice: z.number().min(0).optional(),
  products: z.array(bundleProductSchema).min(2, "Bundle must have at least 2 products")});
 
// Free gift config schema
export const freeGiftConfigSchema = z.object({
  giftProductId: z.number().int(),
  giftQuantity: z.number().int().min(1).default(1)});
 
// Tier schema
export const tierSchema = z.object({
  minQuantity: z.number().int().min(1),
  discountType: z.enum(discountTypes as [DiscountType, ...DiscountType[]]),
  discountValue: z.number().min(0)});
 
// Tiered config schema
export const tieredConfigSchema = z.object({
  tiers: z.array(tierSchema).min(2, "Tiered promotion must have at least 2 tiers")});
 
// Flash sale config schema
export const flashSaleConfigSchema = z.object({
  headline: z.string().min(1).max(100),
  subheadline: z.string().max(200).optional(),
  bannerImage: z.string().url().optional(),
  countdown: z.boolean().default(true)});
 
// Base promotion schema
const basePromotionSchema = z.object({
  name: z.string().min(1, "Name is required").max(100),
  displayName: z.string().max(100).optional(),
  description: z.string().max(1000).optional(),
  type: z.enum(promotionTypes as [PromotionType, ...PromotionType[]]),
  discountType: z.enum(discountTypes as [DiscountType, ...DiscountType[]]),
  discountValue: z.number().min(0),
  startDate: z.coerce.date(),
  endDate: z.coerce.date(),
  isActive: z.boolean().default(true),
  usageLimit: z.number().int().min(1).nullable().optional(),
  perCustomerLimit: z.number().int().min(1).nullable().optional(),
  minimumPurchase: z.number().min(0).nullable().optional(),
  maximumDiscount: z.number().min(0).nullable().optional(),
  targetType: z.enum(targetTypes as [PromotionTargetType, ...PromotionTargetType[]]),
  stackable: z.boolean().default(false),
  priority: z.number().int().default(0)});
 
// Create promotion schema with all optional configs
export const createPromotionSchema = basePromotionSchema
  .extend({
    targetProductIds: z.array(z.number().int()).optional(),
    targetCategoryIds: z.array(z.number().int()).optional(),
    conditions: z.array(conditionSchema).optional(),
    bogoConfig: bogoConfigSchema.optional(),
    bundleConfig: bundleConfigSchema.optional(),
    freeGiftConfig: freeGiftConfigSchema.optional(),
    tieredConfig: tieredConfigSchema.optional(),
    flashSaleConfig: flashSaleConfigSchema.optional()})
  .refine(
    (data) => {
      // Validate end date is after start date
      return data.endDate > data.startDate;
    },
    {
      message: "End date must be after start date",
      path: ["endDate"]}
  )
  .refine(
    (data) => {
      // Validate percentage discount is <= 100
      if (data.discountType === "PERCENTAGE" && data.discountValue > 100) {
        return false;
      }
      return true;
    },
    {
      message: "Percentage discount cannot exceed 100%",
      path: ["discountValue"]}
  )
  .refine(
    (data) => {
      // Validate target products if targeting specific products
      if (
        data.targetType === "SPECIFIC_PRODUCTS" &&
        (!data.targetProductIds || data.targetProductIds.length === 0)
      ) {
        return false;
      }
      return true;
    },
    {
      message: "At least one product must be selected for product-specific promotion",
      path: ["targetProductIds"]}
  )
  .refine(
    (data) => {
      // Validate target categories if targeting specific categories
      if (
        data.targetType === "SPECIFIC_CATEGORIES" &&
        (!data.targetCategoryIds || data.targetCategoryIds.length === 0)
      ) {
        return false;
      }
      return true;
    },
    {
      message: "At least one category must be selected for category-specific promotion",
      path: ["targetCategoryIds"]}
  )
  .refine(
    (data) => {
      // Validate BOGO config is provided for BOGO promotions
      if (data.type === "BOGO" && !data.bogoConfig) {
        return false;
      }
      return true;
    },
    {
      message: "BOGO configuration is required for BOGO promotions",
      path: ["bogoConfig"]}
  )
  .refine(
    (data) => {
      // Validate bundle config is provided for bundle promotions
      if (data.type === "BUNDLE" && !data.bundleConfig) {
        return false;
      }
      return true;
    },
    {
      message: "Bundle configuration is required for bundle promotions",
      path: ["bundleConfig"]}
  )
  .refine(
    (data) => {
      // Validate free gift config is provided for free gift promotions
      if (data.type === "FREE_GIFT" && !data.freeGiftConfig) {
        return false;
      }
      return true;
    },
    {
      message: "Free gift configuration is required for free gift promotions",
      path: ["freeGiftConfig"]}
  )
  .refine(
    (data) => {
      // Validate tiered config is provided for tiered promotions
      if (data.type === "TIERED" && !data.tieredConfig) {
        return false;
      }
      return true;
    },
    {
      message: "Tiered configuration is required for tiered promotions",
      path: ["tieredConfig"]}
  )
  .refine(
    (data) => {
      // Validate flash sale config is provided for flash sale promotions
      if (data.type === "FLASH_SALE" && !data.flashSaleConfig) {
        return false;
      }
      return true;
    },
    {
      message: "Flash sale configuration is required for flash sale promotions",
      path: ["flashSaleConfig"]}
  );
 
// Update promotion schema
export const updatePromotionSchema = basePromotionSchema.partial().extend({
  id: z.number().int(),
  targetProductIds: z.array(z.number().int()).optional(),
  targetCategoryIds: z.array(z.number().int()).optional(),
  conditions: z.array(conditionSchema).optional(),
  bogoConfig: bogoConfigSchema.optional(),
  bundleConfig: bundleConfigSchema.optional(),
  freeGiftConfig: freeGiftConfigSchema.optional(),
  tieredConfig: tieredConfigSchema.optional(),
  flashSaleConfig: flashSaleConfigSchema.optional()});
 
// Promo code schema
export const promoCodeSchema = z.object({
  code: z
    .string()
    .min(3, "Code must be at least 3 characters")
    .max(20, "Code must be at most 20 characters")
    .regex(/^[A-Z0-9-]+$/i, "Code can only contain letters, numbers, and hyphens")
    .transform((val) => val.toUpperCase()),
  promotionId: z.number().int(),
  usageLimit: z.number().int().min(1).nullable().optional(),
  expiresAt: z.coerce.date().nullable().optional()});
 
// Generate codes schema
export const generateCodesSchema = z.object({
  promotionId: z.number().int(),
  count: z.number().int().min(1).max(10000, "Cannot generate more than 10,000 codes at once"),
  prefix: z
    .string()
    .max(10)
    .regex(/^[A-Z0-9]*$/i, "Prefix can only contain letters and numbers")
    .transform((val) => val.toUpperCase())
    .optional(),
  length: z.number().int().min(4).max(16).default(8),
  usageLimit: z.number().int().min(1).nullable().optional(),
  expiresAt: z.coerce.date().nullable().optional()});
 
// Apply promo code schema
export const applyPromoCodeSchema = z.object({
  code: z.string().min(1).transform((val) => val.toUpperCase().trim())});
 
// Customer segment schema
export const customerSegmentSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  rules: z.record(z.string(), z.unknown()), // JSON rules object
  isActive: z.boolean().default(true)});
 
// Loyalty program schema
export const loyaltyProgramSchema = z.object({
  name: z.string().min(1).max(100),
  pointsPerDollar: z.number().min(0).default(1),
  redemptionRate: z.number().min(0).max(1).default(0.01),
  isActive: z.boolean().default(true)});
 
// Loyalty tier schema
export const loyaltyTierSchema = z.object({
  programId: z.number().int(),
  name: z.string().min(1).max(50),
  minPoints: z.number().int().min(0),
  pointsMultiplier: z.number().min(1).default(1),
  perks: z.record(z.string(), z.unknown()).optional()});
 
// Redeem points schema
export const redeemPointsSchema = z.object({
  points: z.number().int().min(1)});
 
// Referral program schema
export const referralProgramSchema = z.object({
  name: z.string().min(1).max(100),
  referrerReward: z.object({
    type: z.enum(["points", "credit", "discount"]),
    value: z.number().min(0),
    discountType: z.enum(["PERCENTAGE", "FIXED_AMOUNT"]).optional()}),
  refereeReward: z.object({
    type: z.enum(["points", "credit", "discount"]),
    value: z.number().min(0),
    discountType: z.enum(["PERCENTAGE", "FIXED_AMOUNT"]).optional()}),
  minPurchase: z.number().min(0).nullable().optional(),
  isActive: z.boolean().default(true)});
 
// Type exports for use in other files
export type CreatePromotionInput = z.infer<typeof createPromotionSchema>;
export type UpdatePromotionInput = z.infer<typeof updatePromotionSchema>;
export type PromoCodeInput = z.infer<typeof promoCodeSchema>;
export type GenerateCodesInput = z.infer<typeof generateCodesSchema>;
export type ApplyPromoCodeInput = z.infer<typeof applyPromoCodeSchema>;
export type CustomerSegmentInput = z.infer<typeof customerSegmentSchema>;
export type LoyaltyProgramInput = z.infer<typeof loyaltyProgramSchema>;
export type LoyaltyTierInput = z.infer<typeof loyaltyTierSchema>;
export type RedeemPointsInput = z.infer<typeof redeemPointsSchema>;
export type ReferralProgramInput = z.infer<typeof referralProgramSchema>;