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

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

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 169 170 171 172 173 174 175 176 177 178 179                                                                                                                                                                                                                                                                                                                                                                     
export const dynamic = "force-dynamic";

/**
 * Dev Sprints API
 * GET /api/dev/sprints - List all sprints
 * POST /api/dev/sprints - Create a new sprint
 */

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 { CreateDevSprintSchema, PaginationSchema } from '@/lib/validation/dev-ticket-schemas';
import { getSprintProgress } from '@/lib/dev-ticket';
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.devSprint.count({ where });

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

  // Get progress stats for each sprint
  const sprintsWithStats = await Promise.all(
    sprints.map(async (sprint) => {
      const progress = await getSprintProgress(sprint.id);
      return {
        ...sprint,
        stats: progress
      };
    })
  );

  return successResponse({
    data: sprintsWithStats,
    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 = CreateDevSprintSchema.safeParse(body);

  if (!validationResult.success) {
    throw ApiError.validation("Invalid sprint data", 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');
  }

  // Check for overlapping active sprints in the same project
  const overlappingSprint = await prisma.devSprint.findFirst({
    where: {
      projectId: data.projectId,
      status: 'ACTIVE',
      OR: [
        {
          AND: [
            { startDate: { lte: data.startDate } },
            { endDate: { gte: data.startDate } },
          ]
        },
        {
          AND: [
            { startDate: { lte: data.endDate } },
            { endDate: { gte: data.endDate } },
          ]
        },
      ]
    }
  });

  if (overlappingSprint) {
    throw ApiError.badRequest(
      `Sprint dates overlap with existing sprint "${overlappingSprint.name}"`
    );
  }

  // Create sprint
  const sprint = await prisma.devSprint.create({
    data: {
      name: data.name,
      goal: data.goal,
      projectId: data.projectId,
      startDate: data.startDate,
      endDate: data.endDate
    },
    include: {
      project: {
        select: { id: true, name: true, key: true, color: true }
      },
      _count: {
        select: { tickets: true }
      }
    }
  });

  logger.info(`Created sprint "${data.name}"`, {
    category: 'DEV_SPRINTS',
    sprintId: sprint.id,
    projectId: data.projectId,
    userId: user.id
  });

  return createdResponse(sprint);
}

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