All files / src/app/api/admin/loyalty/points route.ts

0% Statements 0/137
100% Branches 0/0
0% Functions 0/1
0% Lines 0/137

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                                                                                                                                                                                                                                                                                   
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 { logger } from "@/lib/logging";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import type { AuthenticatedUser } from '@/lib/api/middleware/types';

const AdjustPointsSchema = z.object({
  userId: z.number(),
  points: z.number().int(),
  reason: z.string().min(1),
  type: z.enum(["award", "deduct"]) });

/**
 * GET /api/admin/loyalty/points
 * List admin-made point adjustments
 */
async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { searchParams } = request.nextUrl;
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "20");

  const skip = (page - 1) * limit;

  const [adjustments, total] = await Promise.all([
    prisma.loyaltyTransaction.findMany({
      where: { type: "adjust" },
      skip,
      take: limit,
      include: {
        customerLoyalty: {
          include: {
            user: {
              select: {
                id: true,
                email: true,
                name: true } } } } },
      orderBy: { createdAt: "desc" } }),
    prisma.loyaltyTransaction.count({ where: { type: "adjust" } }),
  ]);

  const formattedAdjustments = adjustments.map((adj) => ({
    id: adj.id,
    userId: adj.customerLoyalty.userId,
    user: {
      id: adj.customerLoyalty.user.id,
      email: adj.customerLoyalty.user.email,
      name: adj.customerLoyalty.user.name || "N/A" },
    points: adj.points,
    description: adj.description,
    createdAt: adj.createdAt }));

  return successResponse({
    adjustments: formattedAdjustments,
    pagination: {
      page,
      limit,
      total,
      totalPages: Math.ceil(total / limit) } });
}

/**
 * POST /api/admin/loyalty/points
 * Award or deduct points manually
 */
async function handlePost(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const validationResult = AdjustPointsSchema.safeParse(body);

  if (!validationResult.success) {
    throw ApiError.validation("Invalid data", validationResult.error.issues);
  }

  const validatedData = validationResult.data;

  // Find or create customer loyalty record
  let customerLoyalty = await prisma.customerLoyalty.findUnique({
    where: { userId: validatedData.userId } });

  if (!customerLoyalty) {
    customerLoyalty = await prisma.customerLoyalty.create({
      data: {
        userId: validatedData.userId,
        totalPoints: 0,
        lifetimePoints: 0 } });
  }

  const pointsChange = validatedData.type === "award"
    ? Math.abs(validatedData.points)
    : -Math.abs(validatedData.points);

  // Create transaction and update points
  const [transaction] = await prisma.$transaction([
    prisma.loyaltyTransaction.create({
      data: {
        customerLoyaltyId: customerLoyalty.id,
        type: "adjust",
        points: pointsChange,
        description: `Admin ${validatedData.type}: ${validatedData.reason}` } }),
    prisma.customerLoyalty.update({
      where: { id: customerLoyalty.id },
      data: {
        totalPoints: { increment: pointsChange },
        lifetimePoints: pointsChange > 0
          ? { increment: pointsChange }
          : undefined } }),
  ]);

  logger.info(`Points adjusted for user ${validatedData.userId}`, {
    category: 'API',
    points: pointsChange,
    reason: validatedData.reason,
    adminId: user.id });

  return createdResponse(transaction);
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const POST = withErrorHandling(withAdmin(handlePost));