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

98.67% Statements 149/151
85.71% Branches 12/14
100% Functions 2/2
98.67% Lines 149/151

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 1521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 1x 1x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 4x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { Session } 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 { RouteContext } from "@/lib/api/middleware";
 
/**
 * GET /api/admin/affiliates/payouts
 * List all affiliate payouts 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 [payouts, total] = await Promise.all([
    prisma.affiliatePayout.findMany({
      where,
      skip,
      take: limit,
      orderBy: { requestedAt: "desc" },
      include: {
        affiliate: {
          select: {
            id: true,
            code: true,
            userId: true,
            payoutMethod: true}}}}),
    prisma.affiliatePayout.count({ where }),
  ]);
 
  // Get affiliate user info
  const userIds = [...new Set(payouts.map((p) => p.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({
    payouts: payouts.map((payout) => ({
      id: payout.id,
      affiliateId: payout.affiliateId,
      affiliateCode: payout.affiliate.code,
      affiliateUser: userMap.get(payout.affiliate.userId),
      amount: payout.amount,
      method: payout.method,
      status: payout.status,
      transactionId: payout.transactionId,
      transactionFee: payout.transactionFee,
      notes: payout.notes,
      requestedAt: payout.requestedAt,
      processedAt: payout.processedAt,
      processedBy: payout.processedBy,
      saleIds: payout.saleIds})),
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit)}});
}
 
// Schema for processing payouts
const processPayoutSchema = z.object({
  payoutId: z.number().int().positive(),
  action: z.enum(["process", "cancel"]),
  transactionId: z.string().max(100).optional(),
  notes: z.string().optional()});
 
/**
 * POST /api/admin/affiliates/payouts
 * Process or cancel a payout
 */
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const result = processPayoutSchema.safeParse(body);
 
  if (!result.success) {
    throw ApiError.validation("Invalid data", result.error.issues);
  }
 
  const validatedData = result.data;
 
  if (validatedData.action === "process") {
    const success = await affiliateSystem.processPayout(
      validatedData.payoutId,
      session.user.id,
      validatedData.transactionId
    );
    if (!success) {
      throw ApiError.badRequest("Failed to process payout");
    }
    return successResponse({ message: "Payout processed successfully" });
  } else {
    // Cancel payout
    const payout = await prisma.affiliatePayout.findUnique({
      where: { id: validatedData.payoutId }});
 
    if (!payout || !["PENDING", "PROCESSING"].includes(payout.status)) {
      throw ApiError.badRequest("Cannot cancel this payout");
    }
 
    await prisma.$transaction([
      // Update payout status
      prisma.affiliatePayout.update({
        where: { id: validatedData.payoutId },
        data: {
          status: "CANCELLED",
          notes: validatedData.notes || "Cancelled by admin"}}),
      // Unlink sales from payout
      prisma.affiliateSale.updateMany({
        where: { payoutId: validatedData.payoutId },
        data: { payoutId: null }}),
    ]);
 
    return successResponse({ message: "Payout cancelled successfully" });
  }
}
 
export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));