All files / src/app/api/dev/reports/workload route.ts

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

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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
export const dynamic = "force-dynamic";

/**
 * Dev Workload Report API
 * GET /api/dev/reports/workload - Get team workload distribution
 */

import { NextRequest, NextResponse } from 'next/server';
import { } from "next-auth";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiSuccessResponse,
  ApiErrorResponse
} from "@/lib/api";
import { } from "@/lib/api/middleware";
import { prisma } from '@/lib/prisma';
import { } from '@/lib/core';

interface AssigneeWorkload {
  user: {
    id: number;
    name: string | null;
    email: string;
    image: string | null;
  } | null;
  tickets: {
    total: number;
    open: number;
    inProgress: number;
    inReview: number;
    testing: number;
    blocked: number;
  };
  storyPoints: {
    total: number;
    completed: number;
    remaining: number;
  };
  overdue: number;
  dueThisWeek: number;
  hoursLogged: {
    thisWeek: number;
    thisMonth: number;
  };
  projects: Array<{
    id: string;
    name: string;
    key: string;
    color: string;
    ticketCount: number;
  }>;
}

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

  const now = new Date();
  const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const weekFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

  // Build base where clause
  const ticketWhere: Record<string, unknown> = {
    status: { notIn: ['COMPLETED', 'CANCELLED', 'WONT_FIX'] }
  };

  if (projectId) {
    ticketWhere.projectId = projectId;
  }
  if (sprintId) {
    ticketWhere.sprintId = sprintId;
  }

  // Get all users with assigned tickets
  const usersWithTickets = await prisma.user.findMany({
    where: {
      devTicketsAssigned: {
        some: ticketWhere
      }
    },
    select: {
      id: true,
      name: true,
      email: true,
      image: true,
      devTicketsAssigned: {
        where: ticketWhere,
        select: {
          id: true,
          status: true,
          storyPoints: true,
          dueDate: true,
          project: {
            select: { id: true, name: true, key: true, color: true }
          }
        }
      }
    }
  });

  // Get unassigned tickets count
  const unassignedCount = await prisma.devTicket.count({
    where: {
      ...ticketWhere,
      assigneeId: null
    }
  });

  const unassignedPoints = await prisma.devTicket.aggregate({
    where: {
      ...ticketWhere,
      assigneeId: null
    },
    _sum: { storyPoints: true }
  });

  // Calculate workload for each user
  const workloadData: AssigneeWorkload[] = await Promise.all(
    usersWithTickets.map(async (user) => {
      const tickets = user.devTicketsAssigned;

      // Count by status
      const statusCounts = {
        open: tickets.filter((t) => t.status === 'OPEN').length,
        inProgress: tickets.filter((t) => t.status === 'IN_PROGRESS').length,
        inReview: tickets.filter((t) => t.status === 'IN_REVIEW').length,
        testing: tickets.filter((t) => t.status === 'TESTING').length,
        blocked: tickets.filter((t) => t.status === 'BLOCKED').length
      };

      // Story points
      const totalPoints = tickets.reduce((sum, t) => sum + (t.storyPoints || 0), 0);

      // Get completed points from all time
      const completedTickets = await prisma.devTicket.findMany({
        where: {
          assigneeId: user.id,
          status: 'COMPLETED',
          ...(projectId ? { projectId } : {}),
          ...(sprintId ? { sprintId } : {})
        },
        select: { storyPoints: true }
      });
      const completedPoints = completedTickets.reduce(
        (sum, t) => sum + (t.storyPoints || 0),
        0
      );

      // Overdue tickets
      const overdue = tickets.filter(
        (t) => t.dueDate && new Date(t.dueDate) < now
      ).length;

      // Due this week
      const dueThisWeek = tickets.filter(
        (t) => t.dueDate && new Date(t.dueDate) >= now && new Date(t.dueDate) <= weekFromNow
      ).length;

      // Time logged
      const hoursThisWeek = await prisma.devTimeEntry.aggregate({
        where: {
          userId: user.id,
          date: { gte: weekAgo },
          ...(projectId ? { ticket: { projectId } } : {})
        },
        _sum: { hours: true }
      });

      const hoursThisMonth = await prisma.devTimeEntry.aggregate({
        where: {
          userId: user.id,
          date: { gte: monthAgo },
          ...(projectId ? { ticket: { projectId } } : {})
        },
        _sum: { hours: true }
      });

      // Project breakdown
      const projectMap = new Map<
        string,
        { id: string; name: string; key: string; color: string; count: number }
      >();
      tickets.forEach((t) => {
        if (t.project) {
          const existing = projectMap.get(t.project.id);
          if (existing) {
            existing.count++;
          } else {
            projectMap.set(t.project.id, {
              id: t.project.id,
              name: t.project.name,
              key: t.project.key,
              color: t.project.color,
              count: 1
            });
          }
        }
      });

      return {
        user: {
          id: user.id,
          name: user.name,
          email: user.email,
          image: user.image
        },
        tickets: {
          total: tickets.length,
          ...statusCounts
        },
        storyPoints: {
          total: totalPoints + completedPoints,
          completed: completedPoints,
          remaining: totalPoints
        },
        overdue,
        dueThisWeek,
        hoursLogged: {
          thisWeek: hoursThisWeek._sum.hours || 0,
          thisMonth: hoursThisMonth._sum.hours || 0
        },
        projects: Array.from(projectMap.values())
          .map((p) => ({ ...p, ticketCount: p.count }))
          .sort((a, b) => b.ticketCount - a.ticketCount)
      };
    })
  );

  // Add unassigned as a special entry
  const unassignedWorkload: AssigneeWorkload = {
    user: null,
    tickets: {
      total: unassignedCount,
      open: 0,
      inProgress: 0,
      inReview: 0,
      testing: 0,
      blocked: 0
    },
    storyPoints: {
      total: unassignedPoints._sum.storyPoints || 0,
      completed: 0,
      remaining: unassignedPoints._sum.storyPoints || 0
    },
    overdue: 0,
    dueThisWeek: 0,
    hoursLogged: { thisWeek: 0, thisMonth: 0 },
    projects: []
  };

  // Calculate team totals
  const teamTotals = {
    totalTickets:
      workloadData.reduce((sum, w) => sum + w.tickets.total, 0) + unassignedCount,
    totalStoryPoints:
      workloadData.reduce((sum, w) => sum + w.storyPoints.remaining, 0) +
      (unassignedPoints._sum.storyPoints || 0),
    totalOverdue: workloadData.reduce((sum, w) => sum + w.overdue, 0),
    totalDueThisWeek: workloadData.reduce((sum, w) => sum + w.dueThisWeek, 0),
    totalHoursThisWeek: workloadData.reduce((sum, w) => sum + w.hoursLogged.thisWeek, 0),
    assignedCount: workloadData.length,
    unassignedCount
  };

  // Calculate average workload
  const averageTicketsPerPerson =
    workloadData.length > 0
      ? Math.round(
        workloadData.reduce((sum, w) => sum + w.tickets.total, 0) / workloadData.length
      )
      : 0;

  const averagePointsPerPerson =
    workloadData.length > 0
      ? Math.round(
        workloadData.reduce((sum, w) => sum + w.storyPoints.remaining, 0) /
        workloadData.length
      )
      : 0;

  // Sort by total active tickets (descending)
  workloadData.sort((a, b) => b.tickets.total - a.tickets.total);

  return successResponse({
    workload: [...workloadData, unassignedWorkload],
    summary: {
      ...teamTotals,
      averageTicketsPerPerson,
      averagePointsPerPerson
    },
    filters: {
      projectId,
      sprintId
    }
  });
}

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