All files / src/app/api/support/tickets route.ts

97.2% Statements 174/179
90.47% Branches 19/21
100% Functions 2/2
97.2% Lines 174/179

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 1801x 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 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 4x 4x 4x 4x 4x 6x 6x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 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 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x           5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x  
export const dynamic = "force-dynamic";
 
/**
 * Customer Support Tickets API
 * POST /api/support/tickets - Create a new ticket (authenticated or guest)
 * GET /api/support/tickets - List customer's tickets (authenticated)
 */
 
import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import { CreateTicketSchema, TicketFilterSchema } from "@/lib/validation/support-schemas";
import {
  generateTicketNumber,
  recordTicketCreation,
  buildTicketWhereClause } from "@/lib/support/ticket-utils";
import {
  notifyTicketCreated,
  notifyAdminsOfUrgentTicket } from "@/lib/support/notification-utils";
import { TicketStatus, TicketPriority, SupportTicketWithRelations } from "@/types/support";
import { logger } from "@/lib/logging";
import {
  withErrorHandling,
  withAuth,
  createdResponse,
  paginatedResponse,
  ApiError,
  ApiSuccessResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { getServerSession } from "@/lib/auth";
 
interface TicketCreateResponse {
  id: string;
  ticketNumber: string;
  subject: string;
  status: string;
  message: string;
  [key: string]: unknown;
}
 
/**
 * POST /api/support/tickets
 * Create a new ticket (can be unauthenticated for guest tickets)
 */
async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<TicketCreateResponse>>> {
  const body = await request.json();
 
  // Validate input
  const validationResult = CreateTicketSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation(
      "Validation failed",
      validationResult.error.flatten().fieldErrors
    );
  }
 
  const data = validationResult.data;
 
  // Check if user is authenticated (optional)
  const session = await getServerSession();
  const userId = session?.user?.id ? Number(session.user.id) : null;
 
  // Generate ticket number
  const ticketNumber = await generateTicketNumber();
 
  // Create the ticket
  const ticket = await prisma.supportTicket.create({
    data: {
      ticketNumber,
      userId,
      customerEmail: data.customerEmail,
      customerName: data.customerName,
      subject: data.subject,
      description: data.description,
      category: data.category,
      priority: data.priority || TicketPriority.MEDIUM,
      status: TicketStatus.OPEN,
      orderId: data.orderId || null,
      productId: data.productId || null},
    include: {
      user: {
        select: { id: true, name: true, email: true }},
      order: {
        select: { id: true, status: true, total: true, createdAt: true }},
      product: {
        select: { id: true, title: true }}}});
 
  // Record creation in history
  await recordTicketCreation(ticket.id, userId);
 
  // Create initial system message
  await prisma.supportMessage.create({
    data: {
      ticketId: ticket.id,
      senderType: "SYSTEM",
      senderName: "System",
      content: `Ticket #${ticketNumber} created. Our support team will respond shortly.`,
      isInternal: false}});
 
  // Send notifications
  const ticketWithRelations = ticket as unknown as SupportTicketWithRelations;
  await notifyTicketCreated(ticketWithRelations);
  await notifyAdminsOfUrgentTicket(ticketWithRelations);
 
  logger.info("Support ticket created", {
    category: "API",
    ticketId: ticket.id,
    ticketNumber,
    userId,
    ticketCategory: data.category,
    priority: data.priority});
 
  return createdResponse({
    ...ticket,
    message: `Ticket ${ticketNumber} created successfully`});
}
 
export const POST = withErrorHandling(handlePost);
 
/**
 * GET /api/support/tickets
 * List customer's tickets (authenticated)
 */
async function handleGet(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse> {
  const userId = Number(session.user.id);
 
  // Parse query parameters
  const { searchParams } = new URL(request.url);
  const queryParams = {
    status: searchParams.get("status") || undefined,
    page: searchParams.get("page") || "1",
    limit: searchParams.get("limit") || "20",
    sortBy: searchParams.get("sortBy") || "createdAt",
    sortOrder: searchParams.get("sortOrder") || "desc"};
 
  const filterResult = TicketFilterSchema.safeParse(queryParams);
  if (!filterResult.success) {
    throw ApiError.validation(
      "Invalid query parameters",
      filterResult.error.flatten().fieldErrors
    );
  }
 
  const filters = filterResult.data;
 
  // Build where clause - only show user's own tickets
  const where = buildTicketWhereClause({
    ...filters,
    userId});
 
  // Get total count
  const total = await prisma.supportTicket.count({ where });
 
  // Get tickets with pagination
  const tickets = await prisma.supportTicket.findMany({
    where,
    include: {
      order: {
        select: { id: true, status: true, total: true }},
      product: {
        select: { id: true, title: true }},
      _count: {
        select: { messages: true }}},
    orderBy: {
      [filters.sortBy]: filters.sortOrder},
    skip: (filters.page - 1) * filters.limit,
    take: filters.limit});
 
  return paginatedResponse(tickets, {
    page: filters.page,
    limit: filters.limit,
    total});
}
 
export const GET = withErrorHandling(withAuth(handleGet));