All files / src/app/api/admin/pricing route.ts

97.98% Statements 243/248
81.81% Branches 27/33
100% Functions 2/2
97.98% Lines 243/248

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 2491x 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 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x           5x 5x 1x 1x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 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 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 5x 5x 5x 5x 5x 5x 5x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { z } from "zod";
import { pricingEngine } from "@/lib/ecommerce";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";
 
const LOG_CATEGORY = "ADMIN_PRICING_API";
 
// Validation schemas
const pricingConditionSchema = z.object({
  field: z.string(),
  operator: z.enum([
    "equals",
    "not_equals",
    "greater_than",
    "less_than",
    "greater_than_or_equal",
    "less_than_or_equal",
    "in",
    "not_in",
    "between",
  ]),
  value: z.union([
    z.string(),
    z.number(),
    z.array(z.string()),
    z.array(z.number()),
  ]) });
 
const pricingRuleSchema = z.object({
  name: z.string().min(1).max(100),
  description: z.string().max(500).optional(),
  type: z.enum([
    "VOLUME_DISCOUNT",
    "TIME_BASED",
    "INVENTORY_BASED",
    "SEGMENT_BASED",
    "CLEARANCE",
    "FIRST_TIME_BUYER",
    "BUNDLE_DISCOUNT",
    "COMPETITIVE",
    "SEASONAL",
    "DEMAND_BASED",
  ]),
  discountType: z.enum(["PERCENTAGE", "FIXED_AMOUNT"]),
  discountValue: z.number().min(0),
  conditions: z.array(pricingConditionSchema).default([]),
  priority: z.number().int().min(0).max(100).default(0),
  stackable: z.boolean().default(false),
  minimumQuantity: z.number().int().min(1).optional().nullable(),
  minimumPurchase: z.number().min(0).optional().nullable(),
  maximumDiscount: z.number().min(0).optional().nullable(),
  startDate: z.string().datetime().optional().nullable(),
  endDate: z.string().datetime().optional().nullable(),
  isActive: z.boolean().default(true),
  targetType: z.enum([
    "ALL_PRODUCTS",
    "SPECIFIC_PRODUCTS",
    "SPECIFIC_CATEGORIES",
    "CART_TOTAL",
  ]).default("ALL_PRODUCTS"),
  targetProductIds: z.array(z.number()).default([]),
  targetCategoryIds: z.array(z.number()).default([]),
  targetSegmentIds: z.array(z.number()).default([]),
  abTestEnabled: z.boolean().default(false),
  abTestVariant: z.string().max(50).optional().nullable(),
  abTestPercent: z.number().int().min(0).max(100).optional().nullable() });
 
/**
 * GET /api/admin/pricing
 * List all pricing rules with pagination
 */
async function handleGet(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");
  const search = searchParams.get("search") || "";
  const type = searchParams.get("type") || "";
  const isActive = searchParams.get("isActive");
 
  const skip = (page - 1) * limit;
 
  // Build where clause
  const where: Record<string, unknown> = {};
 
  if (search) {
    where.OR = [
      { name: { contains: search } },
      { description: { contains: search } },
    ];
  }
 
  if (type) {
    where.type = type;
  }
 
  if (isActive !== null && isActive !== "") {
    where.isActive = isActive === "true";
  }
 
  const [rules, total] = await Promise.all([
    prisma.pricingRule.findMany({
      where,
      skip,
      take: limit,
      orderBy: [{ priority: "desc" }, { createdAt: "desc" }],
      include: {
        targetProducts: { select: { productId: true } },
        targetCategories: { select: { categoryId: true } },
        targetSegments: { select: { segmentId: true } },
        _count: {
          select: { applications: true } } } }),
    prisma.pricingRule.count({ where }),
  ]);
 
  logger.info("Pricing rules fetched", { category: LOG_CATEGORY, count: rules.length, page, limit });
 
  return successResponse({
    rules: rules.map((rule) => ({
      id: rule.id,
      name: rule.name,
      description: rule.description,
      type: rule.type,
      discountType: rule.discountType,
      discountValue: rule.discountValue,
      conditions: rule.conditions,
      priority: rule.priority,
      stackable: rule.stackable,
      minimumQuantity: rule.minimumQuantity,
      minimumPurchase: rule.minimumPurchase,
      maximumDiscount: rule.maximumDiscount,
      startDate: rule.startDate,
      endDate: rule.endDate,
      isActive: rule.isActive,
      targetType: rule.targetType,
      targetProductIds: rule.targetProducts.map((tp) => tp.productId),
      targetCategoryIds: rule.targetCategories.map((tc) => tc.categoryId),
      targetSegmentIds: rule.targetSegments.map((ts) => ts.segmentId),
      abTestEnabled: rule.abTestEnabled,
      abTestVariant: rule.abTestVariant,
      abTestPercent: rule.abTestPercent,
      applicationCount: rule._count.applications,
      totalDiscounted: rule.totalDiscounted,
      createdAt: rule.createdAt,
      updatedAt: rule.updatedAt })),
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit) } });
}
 
/**
 * POST /api/admin/pricing
 * Create a new pricing rule
 */
async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
 
  // Validate input
  const validationResult = pricingRuleSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Validation failed", validationResult.error.issues);
  }
 
  const validatedData = validationResult.data;
 
  // Create the pricing rule with relations
  const rule = await prisma.pricingRule.create({
    data: {
      name: validatedData.name,
      description: validatedData.description || null,
      type: validatedData.type,
      discountType: validatedData.discountType,
      discountValue: validatedData.discountValue,
      conditions: validatedData.conditions,
      priority: validatedData.priority,
      stackable: validatedData.stackable,
      minimumQuantity: validatedData.minimumQuantity ?? null,
      minimumPurchase: validatedData.minimumPurchase ?? null,
      maximumDiscount: validatedData.maximumDiscount ?? null,
      startDate: validatedData.startDate ? new Date(validatedData.startDate) : null,
      endDate: validatedData.endDate ? new Date(validatedData.endDate) : null,
      isActive: validatedData.isActive,
      targetType: validatedData.targetType,
      abTestEnabled: validatedData.abTestEnabled,
      abTestVariant: validatedData.abTestVariant ?? null,
      abTestPercent: validatedData.abTestPercent ?? null,
      targetProducts: {
        create: validatedData.targetProductIds.map((productId) => ({
          productId })) },
      targetCategories: {
        create: validatedData.targetCategoryIds.map((categoryId) => ({
          categoryId })) },
      targetSegments: {
        create: validatedData.targetSegmentIds.map((segmentId) => ({
          segmentId })) } },
    include: {
      targetProducts: { select: { productId: true } },
      targetCategories: { select: { categoryId: true } },
      targetSegments: { select: { segmentId: true } } } });
 
  // Clear pricing engine cache
  pricingEngine.clearCache();
 
  logger.info("Pricing rule created", { category: LOG_CATEGORY, ruleId: rule.id, name: rule.name });
 
  return createdResponse({
    id: rule.id,
    name: rule.name,
    description: rule.description,
    type: rule.type,
    discountType: rule.discountType,
    discountValue: rule.discountValue,
    conditions: rule.conditions,
    priority: rule.priority,
    stackable: rule.stackable,
    minimumQuantity: rule.minimumQuantity,
    minimumPurchase: rule.minimumPurchase,
    maximumDiscount: rule.maximumDiscount,
    startDate: rule.startDate,
    endDate: rule.endDate,
    isActive: rule.isActive,
    targetType: rule.targetType,
    targetProductIds: rule.targetProducts.map((tp) => tp.productId),
    targetCategoryIds: rule.targetCategories.map((tc) => tc.categoryId),
    targetSegmentIds: rule.targetSegments.map((ts) => ts.segmentId),
    abTestEnabled: rule.abTestEnabled,
    abTestVariant: rule.abTestVariant,
    abTestPercent: rule.abTestPercent,
    createdAt: rule.createdAt,
    updatedAt: rule.updatedAt });
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));