All files / src/app/api/admin/affiliates/sales route.ts

95.55% Statements 129/135
78.57% Branches 11/14
100% Functions 2/2
95.55% Lines 129/135

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 1361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 2x 2x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 2x     1x 1x 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 { z } from "zod";
import { affiliateSystem } from "@/lib/affiliate-system";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";
 
/**
 * GET /api/admin/affiliates/sales
 * List all affiliate sales with filtering
 */
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 affiliateId = searchParams.get("affiliateId");
  const status = searchParams.get("status") || "";
 
  const skip = (page - 1) * limit;
 
  // Build where clause
  const where: Record<string, unknown> = {};
 
  if (affiliateId) {
    where.affiliateId = parseInt(affiliateId);
  }
 
  if (status) {
    where.status = status;
  }
 
  const [sales, total] = await Promise.all([
    prisma.affiliateSale.findMany({
      where,
      skip,
      take: limit,
      orderBy: { createdAt: "desc" },
      include: {
        affiliate: {
          select: {
            id: true,
            code: true,
            userId: true } } } }),
    prisma.affiliateSale.count({ where }),
  ]);
 
  // Get affiliate user info
  const userIds = [...new Set(sales.map((s) => s.affiliate.userId))];
  const users = await prisma.user.findMany({
    where: { id: { in: userIds } },
    select: { id: true, name: true, email: true } });
  const userMap = new Map(users.map((u) => [u.id, u]));
 
  return successResponse({
    sales: sales.map((sale) => ({
      id: sale.id,
      affiliateId: sale.affiliateId,
      affiliateCode: sale.affiliate.code,
      affiliateUser: userMap.get(sale.affiliate.userId),
      orderId: sale.orderId,
      orderTotal: sale.orderTotal,
      commissionType: sale.commissionType,
      commissionRate: sale.commissionRate,
      commissionAmount: sale.commissionAmount,
      status: sale.status,
      approvedAt: sale.approvedAt,
      rejectedAt: sale.rejectedAt,
      rejectionReason: sale.rejectionReason,
      payoutId: sale.payoutId,
      paidAt: sale.paidAt,
      createdAt: sale.createdAt,
      updatedAt: sale.updatedAt })),
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit) } });
}
 
// Schema for approving/rejecting sales
const updateSaleSchema = z.object({
  saleId: z.number().int().positive(),
  action: z.enum(["approve", "reject"]),
  rejectionReason: z.string().max(500).optional() });
 
/**
 * POST /api/admin/affiliates/sales
 * Approve or reject a sale
 */
async function handlePost(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const result = updateSaleSchema.safeParse(body);
 
  if (!result.success) {
    throw ApiError.validation("Invalid data", result.error.issues);
  }
 
  const validatedData = result.data;
 
  if (validatedData.action === "approve") {
    const success = await affiliateSystem.approveSale(validatedData.saleId);
    if (!success) {
      throw ApiError.badRequest("Failed to approve sale");
    }
    return successResponse({ message: "Sale approved successfully" });
  } else {
    if (!validatedData.rejectionReason) {
      throw ApiError.badRequest("Rejection reason is required");
    }
    const success = await affiliateSystem.rejectSale(
      validatedData.saleId,
      validatedData.rejectionReason
    );
    if (!success) {
      throw ApiError.badRequest("Failed to reject sale");
    }
    return successResponse({ message: "Sale rejected successfully" });
  }
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));