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 | 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 { withAdmin, withErrorHandling, successResponse, createdResponse, ApiError, ApiSuccessResponse, ApiErrorResponse } from "@/lib/api"; import { } from "@/lib/api/middleware"; const CreateCampaignSchema = z.object({ name: z.string().min(1), referrerReward: z.object({ type: z.enum(["points", "credit", "discount"]), value: z.number(), discountType: z.enum(["percentage", "fixed"]).optional() }), refereeReward: z.object({ type: z.enum(["points", "credit", "discount"]), value: z.number(), discountType: z.enum(["percentage", "fixed"]).optional() }), minPurchase: z.number().optional(), isActive: z.boolean().optional() }); /** * GET /api/admin/referrals/campaigns * List all referral campaigns/programs */ 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 skip = (page - 1) * limit; const [campaigns, total] = await Promise.all([ prisma.referralProgram.findMany({ skip, take: limit, orderBy: { createdAt: "desc" } }), prisma.referralProgram.count(), ]); // Get referral counts for each campaign const campaignsWithCounts = await Promise.all( campaigns.map(async (campaign) => { const referralCount = await prisma.referral.count({ where: { programId: campaign.id } }); return { ...campaign, referralCount }; }) ); return successResponse({ campaigns: campaignsWithCounts, pagination: { page, limit, total, totalPages: Math.ceil(total / limit) } }); } /** * POST /api/admin/referrals/campaigns * Create new referral campaign */ async function handlePost(request: NextRequest): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> { const body = await request.json(); const result = CreateCampaignSchema.safeParse(body); if (!result.success) { throw ApiError.validation("Invalid campaign data", result.error.issues); } const validatedData = result.data; const campaign = await prisma.referralProgram.create({ data: { name: validatedData.name, referrerReward: validatedData.referrerReward, refereeReward: validatedData.refereeReward, minPurchase: validatedData.minPurchase, isActive: validatedData.isActive ?? true } }); return createdResponse(campaign); } export const GET = withErrorHandling(withAdmin(handleGet)); export const POST = withErrorHandling(withAdmin(handlePost)); |