All files / src/app/api/dev/milestones route.ts

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

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                                                                                                                                                                                                                                                                                                                                               
export const dynamic = "force-dynamic";

/**
 * Dev Milestones API
 * GET /api/dev/milestones - List all milestones
 * POST /api/dev/milestones - Create a new milestone
 */

import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse
} from "@/lib/api";
import { AuthenticatedUser } from "@/lib/api/middleware";
import { prisma } from '@/lib/prisma';
import { CreateDevMilestoneSchema, PaginationSchema } from '@/lib/validation/dev-ticket-schemas';
import { logger } from '@/lib/logging';

async function handleGet(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { searchParams } = new URL(request.url);

  // Parse pagination
  const paginationResult = PaginationSchema.safeParse({
    page: searchParams.get('page'),
    limit: searchParams.get('limit')
  });

  const { page, limit } = paginationResult.success
    ? paginationResult.data
    : { page: 1, limit: 50 };

  // Parse filters
  const projectId = searchParams.get('projectId');
  const status = searchParams.get('status');

  const where: Record<string, unknown> = {};

  if (projectId) {
    where.projectId = projectId;
  }

  if (status) {
    where.status = status;
  }

  // Get total count
  const total = await prisma.devMilestone.count({ where });

  // Get milestones
  const milestones = await prisma.devMilestone.findMany({
    where,
    include: {
      project: {
        select: { id: true, name: true, key: true, color: true }
      },
      _count: {
        select: { tickets: true }
      }
    },
    orderBy: [{ status: 'asc' }, { dueDate: 'asc' }],
    skip: (page - 1) * limit,
    take: limit
  });

  // Get ticket stats for each milestone
  const milestonesWithStats = await Promise.all(
    milestones.map(async (milestone) => {
      const ticketStats = await prisma.devTicket.groupBy({
        by: ['status'],
        where: { milestoneId: milestone.id },
        _count: true
      });

      const completedCount = ticketStats
        .filter((s) => s.status === 'COMPLETED')
        .reduce((sum, s) => sum + s._count, 0);

      return {
        ...milestone,
        stats: {
          totalTickets: milestone._count.tickets,
          completedTickets: completedCount,
          progress: milestone._count.tickets > 0
            ? Math.round((completedCount / milestone._count.tickets) * 100)
            : 0
        }
      };
    })
  );

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

async function handlePost(
  request: NextRequest,
  context: unknown,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const validationResult = CreateDevMilestoneSchema.safeParse(body);

  if (!validationResult.success) {
    throw ApiError.validation(
      'Validation failed',
      validationResult.error.flatten().fieldErrors
    );
  }

  const data = validationResult.data;

  // Verify project exists
  const project = await prisma.devProject.findUnique({
    where: { id: data.projectId }
  });

  if (!project) {
    throw ApiError.notFound('Project not found');
  }

  // Create milestone
  const milestone = await prisma.devMilestone.create({
    data: {
      name: data.name,
      description: data.description,
      projectId: data.projectId,
      startDate: data.startDate,
      dueDate: data.dueDate
    },
    include: {
      project: {
        select: { id: true, name: true, key: true, color: true }
      },
      _count: {
        select: { tickets: true }
      }
    }
  });

  logger.info(`Created milestone "${data.name}"`, {
    category: 'DEV_MILESTONES',
    milestoneId: milestone.id,
    projectId: data.projectId,
    userId: user.id
  });

  return createdResponse(milestone);
}

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