All files / src/app/api/admin/segments/preview route.ts

0% Statements 0/172
100% Branches 0/0
0% Functions 0/1
0% Lines 0/172

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                                                                                                                                                                                                                                                                                                                                                         
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 {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";

const LOG_CATEGORY = "ADMIN_SEGMENT_PREVIEW_API";

interface SegmentRule {
  field: string;
  operator: string;
  value: string | number | string[] | number[];
}

interface SegmentRuleGroup {
  conditions: SegmentRule[];
  logic: "AND" | "OR";
}

/**
 * POST /api/admin/segments/preview
 * Preview segment member count based on rules
 */
async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const rules: SegmentRuleGroup[] = body.rules || [];

  const whereClause = buildWhereClause(rules);
  const count = await prisma.user.count({ where: whereClause });

  // Get sample members
  const sampleMembers = await prisma.user.findMany({
    where: whereClause,
    take: 5,
    select: {
      id: true,
      email: true,
      name: true,
      createdAt: true },
    orderBy: { createdAt: "desc" } });

  logger.info("Segment preview", { category: LOG_CATEGORY, rulesCount: rules.length, matchCount: count });

  return successResponse({
    count,
    sampleMembers: sampleMembers.map((u) => ({
      id: u.id,
      email: u.email,
      name: u.name || "N/A",
      joinedAt: u.createdAt })) });
}

/**
 * Build Prisma where clause from segment rules
 */
function buildWhereClause(rules: SegmentRuleGroup[]): Record<string, unknown> {
  if (!rules || rules.length === 0) {
    return {};
  }

  const conditions: Record<string, unknown>[] = [];

  for (const ruleGroup of rules) {
    const groupConditions: Record<string, unknown>[] = [];

    for (const condition of ruleGroup.conditions) {
      const prismaCondition = buildCondition(condition);
      if (prismaCondition) {
        groupConditions.push(prismaCondition);
      }
    }

    if (groupConditions.length > 0) {
      if (ruleGroup.logic === "OR") {
        conditions.push({ OR: groupConditions });
      } else {
        conditions.push({ AND: groupConditions });
      }
    }
  }

  return conditions.length > 0 ? { AND: conditions } : {};
}

/**
 * Build a single Prisma condition from a rule
 */
function buildCondition(rule: SegmentRule): Record<string, unknown> | null {
  const { field, operator, value } = rule;

  // Map field names to Prisma paths
  const fieldMap: Record<string, string> = {
    total_spent: "orders",
    orders_count: "orders",
    lifetime_points: "customerLoyalty.lifetimePoints",
    current_tier: "customerLoyalty.currentTierId",
    created_at: "createdAt",
    email_domain: "email",
    has_reviewed: "reviews" };

  const prismaField = fieldMap[field] || field;

  // Special handling for aggregate fields
  if (field === "orders_count" || field === "total_spent") {
    // These require subqueries which are complex in Prisma
    // For now, we'll use a simplified approach
    return null;
  }

  if (field === "has_reviewed") {
    const hasReviewed = String(value) === "true";
    return hasReviewed
      ? { reviews: { some: {} } }
      : { reviews: { none: {} } };
  }

  if (field === "email_domain") {
    const domain = String(value);
    switch (operator) {
      case "equals":
        return { email: { endsWith: `@${domain}` } };
      case "not_equals":
        return { NOT: { email: { endsWith: `@${domain}` } } };
      case "contains":
        return { email: { contains: domain } };
      case "not_contains":
        return { NOT: { email: { contains: domain } } };
      default:
        return null;
    }
  }

  // Build condition based on operator
  switch (operator) {
    case "equals":
      return { [prismaField]: value };
    case "not_equals":
      return { [prismaField]: { not: value } };
    case "greater_than":
      return { [prismaField]: { gt: value } };
    case "less_than":
      return { [prismaField]: { lt: value } };
    case "greater_than_or_equal":
      return { [prismaField]: { gte: value } };
    case "less_than_or_equal":
      return { [prismaField]: { lte: value } };
    case "contains":
      return { [prismaField]: { contains: value as string } };
    case "not_contains":
      return { [prismaField]: { not: { contains: value as string } } };
    case "in":
      return { [prismaField]: { in: value as (string | number)[] } };
    case "not_in":
      return { [prismaField]: { notIn: value as (string | number)[] } };
    case "is_empty":
      return { [prismaField]: null };
    case "is_not_empty":
      return { [prismaField]: { not: null } };
    default:
      return null;
  }
}

export const POST = withErrorHandling(withAdmin(handlePost));