All files / src/app/api/orders route.ts

98.24% Statements 168/171
61.9% Branches 13/21
100% Functions 2/2
98.24% Lines 168/171

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 1721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 8x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 8x 8x 8x 8x 8x 8x 8x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 1x 1x 1x  
import { NextRequest, NextResponse } from 'next/server';
import {
  withAuth,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { isDemoMode } from "@/lib/demo-mode";
import { emailService } from "@/lib/email/emailService";
import { emitNewOrder } from "@/lib/socket/emitters";
import { z } from "zod";
import { Prisma } from "@prisma/client";
import { Session } from "next-auth";
 
// Order schema
const OrderSchema = z.object({
  shippingAddress: z.object({
    street: z.string().min(5),
    city: z.string().min(2),
    state: z.string().min(2),
    zipCode: z.string().min(5),
    country: z.string().min(2)}),
  billingAddress: z.object({
    street: z.string().min(5),
    city: z.string().min(2),
    state: z.string().min(2),
    zipCode: z.string().min(5),
    country: z.string().min(2)}),
  paymentMethod: z.enum(["credit_card", "paypal", "apple_pay"]).optional()});
 
// POST /api/orders - Create a new order
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = session.user.id;
  const body = await request.json();
 
  // Validate input
  const validatedData = OrderSchema.parse(body);
 
  // Get user's cart
  const cartItems = await prisma.cart.findMany({
    where: { userId },
    include: { product: true }});
 
  if (cartItems.length === 0) {
    throw ApiError.cartEmpty();
  }
 
  // Calculate total
  const total = cartItems.reduce(
    (sum: number, item: { product: { discountedPrice: number }; quantity: number }) => sum + item.product.discountedPrice * item.quantity,
    0
  );
 
  // Check if demo mode is enabled
  const demoMode = isDemoMode();
  if (demoMode) {
    logger.info("Demo mode enabled - skipping payment processing", { category: 'ORDER' });
  }
 
  // Create order in transaction
  const order = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
    // Create order (with isDemo flag if demo mode is enabled)
    const newOrder = await tx.order.create({
      data: {
        userId,
        status: "PROCESSING",
        total,
        shippingAddress: JSON.stringify(validatedData.shippingAddress),
        billingAddress: JSON.stringify(validatedData.billingAddress),
        isDemo: demoMode,
        items: {
          createMany: {
            data: cartItems.map((item: { productId: number; quantity: number; product: { discountedPrice: number } }) => ({
              productId: item.productId,
              quantity: item.quantity,
              price: item.product.discountedPrice}))}}},
      include: {
        items: {
          include: { product: true }
        }
      }});
 
    // Clear cart
    await tx.cart.deleteMany({ where: { userId } });
 
    // In demo mode, skip payment processing
    // In production mode, this is where Stripe payment would be processed
    if (!demoMode) {
      // TODO: Add real payment processing here when Stripe is integrated
      // await processStripePayment(newOrder, validatedData.paymentMethod);
    }
 
    return newOrder;
  });
 
  // Get user info for email
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { email: true, name: true }
  });
 
  // Send order confirmation email via queue (async, don't wait)
  if (user?.email) {
    const shippingAddr = validatedData.shippingAddress;
    emailService.sendOrderConfirmation({
      id: order.id,
      orderNumber: `ORD-${order.id.toString().padStart(6, '0')}`,
      userId: userId,
      customerEmail: user.email,
      customerName: user.name || 'Valued Customer',
      items: order.items.map((item: { product: { title: string; discountedPrice: number; images?: { url: string }[] }; quantity: number }) => ({
        name: item.product.title,
        quantity: item.quantity,
        price: Number(item.product.discountedPrice),
        image: item.product.images?.[0]?.url
      })),
      subtotal: order.total,
      shipping: 0, // TODO: Add shipping calculation
      tax: 0, // TODO: Add tax calculation
      total: order.total,
      shippingAddress: {
        name: user.name || 'Customer',
        street: shippingAddr.street,
        city: shippingAddr.city,
        state: shippingAddr.state,
        zip: shippingAddr.zipCode,
        country: shippingAddr.country
      }
    }).catch((err) => {
      logger.error("Failed to queue order confirmation email", err as Error, { category: 'ORDER', orderId: order.id });
    });
  }
 
  // Emit real-time new order notification to admins
  emitNewOrder({
    orderId: order.id.toString(),
    orderNumber: `ORD-${order.id.toString().padStart(6, '0')}`,
    total: order.total,
    customerName: session.user.name || session.user.email || 'Customer',
    itemCount: order.items.length,
    timestamp: new Date().toISOString()
  });
 
  return createdResponse(order);
}
 
// GET /api/orders - Get user's orders
async function handleGet(
  _request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown>>> {
  const orders = await prisma.order.findMany({
    where: { userId: session.user.id },
    include: { items: { include: { product: true } } },
    orderBy: { createdAt: "desc" }});
 
  return successResponse(orders);
}
 
export const GET = withErrorHandling(withAuth(handleGet));
export const POST = withErrorHandling(withAuth(handlePost));