All files / src/lib/dev-ticket ticket-utils.ts

37.86% Statements 465/1228
100% Branches 59/59
12.82% Functions 5/39
37.86% Lines 465/1228

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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 12291x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 24x 24x 24x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 32x 3x 1x 3x 2x 2x 3x 32x 32x 32x 2x 1x 1x 1x 1x 2x 32x 32x 32x 3x 2x 3x 1x 1x 3x 32x 32x 32x 2x 1x 1x 1x 1x 2x 32x 32x 32x 2x 1x 1x 1x 1x 2x 32x 32x 32x 2x 1x 1x 1x 1x 2x 32x 32x 32x 1x 1x 32x 32x 32x 2x 2x 32x 32x 32x 1x 1x 32x 32x 32x 1x 1x 32x 32x 32x 1x 1x 32x 32x 32x 3x 2x 3x 1x 1x 3x 32x 32x 32x 2x 2x 2x 2x 2x 2x 2x 32x 32x 32x 2x 2x 2x 2x 2x 2x 32x 32x 32x 3x 3x 2x 2x 3x 2x 2x 3x 32x 32x 2x 2x 1x 1x 2x 1x 1x 2x 32x 32x 32x 1x 1x 32x 30x 30x 30x 32x 32x 32x 32x 1x 1x 1x 1x 13x 13x 13x 13x 1x 1x 12x 13x 13x 13x 13x 2x 13x 1x 13x 1x 13x 1x 13x 1x 13x 1x 13x 1x 13x 1x 13x 13x 3x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x                                       1x 1x 1x 1x 1x                                       1x 1x 1x 1x 1x                                 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x                                                 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 25x 25x 25x 25x 25x 25x 5x 5x 20x 20x 20x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x                                                     1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x                                                                       1x 1x 1x 1x 1x                                             1x 1x 1x 1x 1x                                                                                                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                             1x 1x 1x 1x 1x                                                                                                                                                                     1x 1x 1x 1x                                       1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x                                             1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                 1x 1x 1x 1x 1x                                                                                     1x 1x 1x 1x 1x 1x                                                                   1x 1x 1x 1x 1x           1x 1x 1x 1x 1x            
export const dynamic = "force-dynamic";
 
/**
 * Dev Ticket Utility Functions
 *
 * Core business logic and helper functions for the dev ticketing system.
 */
 
import { prisma } from '@/lib/prisma';
import {
  DevTicketStatus,
  DevTicketPriority,
  DevTicketCategory,
  DevTicketFilters,
  DevTicketSortOptions,
  DevTicketBreadcrumb,
  DevTicketHierarchyNode,
  DevTicketHierarchyProgress } from '@/types/dev-ticket';
import { DEV_TICKET_STATUS_TRANSITIONS, CATEGORY_HIERARCHY_RULES } from '@/constants/dev-ticket';
import { Prisma } from '@prisma/client';
 
// ==========================================
// TICKET NUMBER GENERATION
// ==========================================
 
/**
 * Generates a unique ticket number in format DEV-XXXXXX
 */
export async function generateTicketNumber(): Promise<string> {
  const lastTicket = await prisma.devTicket.findFirst({
    orderBy: { createdAt: 'desc' },
    select: { ticketNumber: true }});

  let nextNumber = 1;
  if (lastTicket?.ticketNumber) {
    const match = lastTicket.ticketNumber.match(/DEV-(\d+)/);
    if (match) {
      nextNumber = parseInt(match[1], 10) + 1;
    }
  }

  return `DEV-${nextNumber.toString().padStart(6, '0')}`;
}
 
// ==========================================
// STATUS VALIDATION
// ==========================================
 
/**
 * Checks if a status transition is valid
 */
export function isValidStatusTransition(
  currentStatus: DevTicketStatus,
  newStatus: DevTicketStatus
): boolean {
  if (currentStatus === newStatus) return true;
  const allowedTransitions = DEV_TICKET_STATUS_TRANSITIONS[currentStatus];
  return allowedTransitions.includes(newStatus);
}
 
/**
 * Gets all valid next statuses from current status
 */
export function getValidNextStatuses(currentStatus: DevTicketStatus): DevTicketStatus[] {
  return DEV_TICKET_STATUS_TRANSITIONS[currentStatus];
}
 
// ==========================================
// QUERY BUILDERS
// ==========================================
 
/**
 * Builds a Prisma where clause from ticket filters
 */
export function buildTicketWhereClause(
  filters: DevTicketFilters
): Prisma.DevTicketWhereInput {
  const where: Prisma.DevTicketWhereInput = {};
 
  // Status filter (single or array)
  if (filters.status) {
    if (Array.isArray(filters.status)) {
      where.status = { in: filters.status };
    } else {
      where.status = filters.status;
    }
  }
 
  // Type filter (single or array)
  if (filters.type) {
    if (Array.isArray(filters.type)) {
      where.type = { in: filters.type };
    } else {
      where.type = filters.type;
    }
  }
 
  // Priority filter (single or array)
  if (filters.priority) {
    if (Array.isArray(filters.priority)) {
      where.priority = { in: filters.priority };
    } else {
      where.priority = filters.priority;
    }
  }
 
  // Severity filter (single or array)
  if (filters.severity) {
    if (Array.isArray(filters.severity)) {
      where.severity = { in: filters.severity };
    } else {
      where.severity = filters.severity;
    }
  }
 
  // Category filter (single or array)
  if (filters.category) {
    if (Array.isArray(filters.category)) {
      where.category = { in: filters.category };
    } else {
      where.category = filters.category;
    }
  }
 
  // Parent filter (specific parent or root-level)
  if (filters.parentId !== undefined) {
    if (filters.parentId === 'root') {
      where.parentId = null;
    } else {
      where.parentId = filters.parentId;
    }
  }
 
  // Hierarchy level filter
  if (filters.hierarchyLevel !== undefined) {
    where.hierarchyLevel = filters.hierarchyLevel;
  }
 
  // Project filter
  if (filters.projectId) {
    where.projectId = filters.projectId;
  }
 
  // Milestone filter
  if (filters.milestoneId) {
    where.milestoneId = filters.milestoneId;
  }
 
  // Sprint filter
  if (filters.sprintId) {
    where.sprintId = filters.sprintId;
  }
 
  // Reporter filter
  if (filters.reporterId) {
    where.reporterId = filters.reporterId;
  }
 
  // Assignee filter (including unassigned)
  if (filters.assigneeId !== undefined) {
    if (filters.assigneeId === 'unassigned') {
      where.assigneeId = null;
    } else {
      where.assigneeId = filters.assigneeId;
    }
  }
 
  // Label filter
  if (filters.labelIds) {
    const labelIdArray = Array.isArray(filters.labelIds) ? filters.labelIds : [filters.labelIds];
    if (labelIdArray.length > 0) {
      where.labels = {
        some: {
          id: { in: labelIdArray }}};
    }
  }
 
  // Search filter (searches title, description, ticket number)
  if (filters.search) {
    where.OR = [
      { title: { contains: filters.search } },
      { description: { contains: filters.search } },
      { ticketNumber: { contains: filters.search } },
    ];
  }
 
  // Date filters
  if (filters.createdAfter || filters.createdBefore) {
    where.createdAt = {};
    if (filters.createdAfter) {
      where.createdAt.gte = filters.createdAfter;
    }
    if (filters.createdBefore) {
      where.createdAt.lte = filters.createdBefore;
    }
  }
 
  if (filters.dueAfter || filters.dueBefore) {
    where.dueDate = {};
    if (filters.dueAfter) {
      where.dueDate.gte = filters.dueAfter;
    }
    if (filters.dueBefore) {
      where.dueDate.lte = filters.dueBefore;
    }
  }
 
  // Soft delete filters
  if (filters.onlyDeleted) {
    // Show only soft-deleted tickets (trash view)
    where.deletedAt = { not: null };
  } else if (!filters.includeDeleted) {
    // By default, exclude soft-deleted tickets
    where.deletedAt = null;
  }
  // If includeDeleted is true, don't add any deletedAt filter
 
  return where;
}
 
/**
 * Builds a Prisma orderBy clause from sort options
 */
export function buildTicketOrderByClause(
  sort?: DevTicketSortOptions
): Prisma.DevTicketOrderByWithRelationInput {
  if (!sort) {
    return { createdAt: 'desc' };
  }
 
  const direction = sort.direction || 'desc';
 
  switch (sort.field) {
    case 'priority':
      return { priority: direction };
    case 'status':
      return { status: direction };
    case 'dueDate':
      return { dueDate: direction };
    case 'title':
      return { title: direction };
    case 'ticketNumber':
      return { ticketNumber: direction };
    case 'updatedAt':
      return { updatedAt: direction };
    case 'category':
      return { category: direction };
    case 'hierarchyLevel':
      return { hierarchyLevel: direction };
    case 'createdAt':
    default:
      return { createdAt: direction };
  }
}
 
// ==========================================
// HISTORY RECORDING
// ==========================================
 
/**
 * Records a ticket history entry
 */
export async function createTicketHistory(
  ticketId: string,
  performedById: number,
  action: string,
  field?: string,
  oldValue?: string | null,
  newValue?: string | null
): Promise<void> {
  await prisma.devTicketHistory.create({
    data: {
      ticketId,
      performedById,
      action,
      field,
      oldValue,
      newValue}});
}
 
/**
 * Records ticket creation
 */
export async function recordTicketCreation(
  ticketId: string,
  performedById: number
): Promise<void> {
  await createTicketHistory(ticketId, performedById, 'created');
}
 
/**
 * Records status change
 */
export async function recordStatusChange(
  ticketId: string,
  performedById: number,
  oldStatus: DevTicketStatus,
  newStatus: DevTicketStatus
): Promise<void> {
  await createTicketHistory(
    ticketId,
    performedById,
    'status_changed',
    'status',
    oldStatus,
    newStatus
  );
}
 
/**
 * Records priority change
 */
export async function recordPriorityChange(
  ticketId: string,
  performedById: number,
  oldPriority: DevTicketPriority,
  newPriority: DevTicketPriority
): Promise<void> {
  await createTicketHistory(
    ticketId,
    performedById,
    'priority_changed',
    'priority',
    oldPriority,
    newPriority
  );
}
 
/**
 * Records assignment change
 */
export async function recordAssignment(
  ticketId: string,
  performedById: number,
  oldAssigneeId: number | null,
  newAssigneeId: number | null
): Promise<void> {
  const action = newAssigneeId ? 'assigned' : 'unassigned';
  await createTicketHistory(
    ticketId,
    performedById,
    action,
    'assigneeId',
    oldAssigneeId?.toString() ?? null,
    newAssigneeId?.toString() ?? null
  );
}
 
// ==========================================
// TICKET QUERIES
// ==========================================
 
/**
 * Gets tickets assigned to a specific user
 */
export async function getUserAssignedTickets(
  userId: number,
  statusFilter?: DevTicketStatus[]
): Promise<{ id: string; ticketNumber: string; title: string; status: DevTicketStatus }[]> {
  const where: Prisma.DevTicketWhereInput = {
    assigneeId: userId};

  if (statusFilter && statusFilter.length > 0) {
    where.status = { in: statusFilter };
  }

  return prisma.devTicket.findMany({
    where,
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      status: true},
    orderBy: { updatedAt: 'desc' }}) as Promise<{ id: string; ticketNumber: string; title: string; status: DevTicketStatus }[]>;
}
 
/**
 * Gets unassigned tickets
 */
export async function getUnassignedTickets(
  projectId?: string
): Promise<{ id: string; ticketNumber: string; title: string; priority: DevTicketPriority }[]> {
  const where: Prisma.DevTicketWhereInput = {
    assigneeId: null,
    status: { in: ['OPEN', 'IN_PROGRESS'] }};

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

  return prisma.devTicket.findMany({
    where,
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      priority: true},
    orderBy: { priority: 'desc' }}) as Promise<{ id: string; ticketNumber: string; title: string; priority: DevTicketPriority }[]>;
}
 
/**
 * Gets overdue tickets
 */
export async function getOverdueTickets(): Promise<
  { id: string; ticketNumber: string; title: string; dueDate: Date; assigneeId: number | null }[]
> {
  return prisma.devTicket.findMany({
    where: {
      dueDate: { lt: new Date() },
      status: { notIn: ['COMPLETED', 'CANCELLED', 'WONT_FIX'] }},
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      dueDate: true,
      assigneeId: true},
    orderBy: { dueDate: 'asc' }}) as Promise<
    { id: string; ticketNumber: string; title: string; dueDate: Date; assigneeId: number | null }[]
  >;
}
 
// ==========================================
// TIME TRACKING
// ==========================================
 
/**
 * Calculates total logged time for a ticket
 */
export async function getTicketTotalTime(ticketId: string): Promise<number> {
  const result = await prisma.devTimeEntry.aggregate({
    where: { ticketId },
    _sum: { hours: true }});
  return result._sum.hours || 0;
}
 
/**
 * Updates ticket's actualHours based on time entries
 */
export async function updateTicketActualHours(ticketId: string): Promise<void> {
  const totalHours = await getTicketTotalTime(ticketId);
  await prisma.devTicket.update({
    where: { id: ticketId },
    data: { actualHours: totalHours }});
}
 
// ==========================================
// SPRINT UTILITIES
// ==========================================
 
/**
 * Gets the active sprint for a project
 */
export async function getActiveSprint(projectId: string) {
  return prisma.devSprint.findFirst({
    where: {
      projectId,
      status: 'ACTIVE'}});
}
 
/**
 * Calculates sprint progress
 */
export async function getSprintProgress(sprintId: string) {
  const tickets = await prisma.devTicket.findMany({
    where: { sprintId },
    select: {
      status: true,
      storyPoints: true}});

  const total = tickets.length;
  const completed = tickets.filter((t) =>
    ['COMPLETED', 'CANCELLED', 'WONT_FIX'].includes(t.status)
  ).length;

  const totalPoints = tickets.reduce((sum, t) => sum + (t.storyPoints || 0), 0);
  const completedPoints = tickets
    .filter((t) => ['COMPLETED'].includes(t.status))
    .reduce((sum, t) => sum + (t.storyPoints || 0), 0);

  return {
    totalTickets: total,
    completedTickets: completed,
    completionPercentage: total > 0 ? Math.round((completed / total) * 100) : 0,
    totalStoryPoints: totalPoints,
    completedStoryPoints: completedPoints,
    pointsPercentage: totalPoints > 0 ? Math.round((completedPoints / totalPoints) * 100) : 0};
}
 
// ==========================================
// MILESTONE UTILITIES
// ==========================================
 
/**
 * Calculates milestone progress
 */
export async function getMilestoneProgress(milestoneId: string) {
  const tickets = await prisma.devTicket.findMany({
    where: { milestoneId },
    select: {
      status: true}});

  const total = tickets.length;
  const completed = tickets.filter((t) =>
    ['COMPLETED', 'CANCELLED', 'WONT_FIX'].includes(t.status)
  ).length;

  return {
    totalTickets: total,
    completedTickets: completed,
    completionPercentage: total > 0 ? Math.round((completed / total) * 100) : 0};
}
 
// ==========================================
// DASHBOARD STATS
// ==========================================
 
/**
 * Gets dashboard statistics
 */
export async function getDashboardStats() {
  const now = new Date();
  const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

  const [
    totalTickets,
    openTickets,
    inProgressTickets,
    completedThisWeek,
    overdueTickets,
    unassignedTickets,
    statusCounts,
    typeCounts,
    priorityCounts,
  ] = await Promise.all([
    prisma.devTicket.count(),
    prisma.devTicket.count({ where: { status: 'OPEN' } }),
    prisma.devTicket.count({ where: { status: 'IN_PROGRESS' } }),
    prisma.devTicket.count({
      where: {
        status: 'COMPLETED',
        completedAt: { gte: weekAgo }}}),
    prisma.devTicket.count({
      where: {
        dueDate: { lt: now },
        status: { notIn: ['COMPLETED', 'CANCELLED', 'WONT_FIX'] }}}),
    prisma.devTicket.count({
      where: {
        assigneeId: null,
        status: { in: ['OPEN', 'IN_PROGRESS'] }}}),
    prisma.devTicket.groupBy({
      by: ['status'],
      _count: true}),
    prisma.devTicket.groupBy({
      by: ['type'],
      _count: true}),
    prisma.devTicket.groupBy({
      by: ['priority'],
      _count: true}),
  ]);

  // Convert group by results to records
  const byStatus = Object.fromEntries(
    statusCounts.map((s) => [s.status, s._count])
  ) as Record<DevTicketStatus, number>;

  const byType = Object.fromEntries(
    typeCounts.map((t) => [t.type, t._count])
  );

  const byPriority = Object.fromEntries(
    priorityCounts.map((p) => [p.priority, p._count])
  ) as Record<DevTicketPriority, number>;

  return {
    totalTickets,
    openTickets,
    inProgressTickets,
    completedThisWeek,
    overdueTickets,
    unassignedTickets,
    byStatus,
    byType,
    byPriority};
}
 
// ==========================================
// HIERARCHY UTILITIES
// ==========================================
 
/**
 * Validates if a parent-child category relationship is allowed
 */
export function isValidParentChildCategory(
  childCategory: DevTicketCategory,
  parentCategory: DevTicketCategory | null
): boolean {
  const allowedParents = CATEGORY_HIERARCHY_RULES[childCategory];
 
  // If no parent, check if category can be root
  if (parentCategory === null) {
    return allowedParents.length === 0; // Only EPICs can be root
  }
 
  return allowedParents.includes(parentCategory);
}
 
/**
 * Builds the hierarchy path for a ticket based on its parent
 */
export async function buildHierarchyPath(parentId: string | null): Promise<string | null> {
  if (!parentId) return null;

  const parent = await prisma.devTicket.findUnique({
    where: { id: parentId },
    select: { hierarchyPath: true, id: true }});

  if (!parent) return null;

  // Build path: parent's path + parent's id
  return parent.hierarchyPath ? `${parent.hierarchyPath}/${parent.id}` : parent.id;
}
 
/**
 * Calculates hierarchy level based on parent
 */
export async function calculateHierarchyLevel(parentId: string | null): Promise<number> {
  if (!parentId) return 0;

  const parent = await prisma.devTicket.findUnique({
    where: { id: parentId },
    select: { hierarchyLevel: true }});

  return parent ? parent.hierarchyLevel + 1 : 0;
}
 
/**
 * Updates child counts for a ticket and all its ancestors
 */
export async function updateChildCounts(ticketId: string): Promise<void> {
  const ticket = await prisma.devTicket.findUnique({
    where: { id: ticketId },
    select: { parentId: true }});

  if (!ticket?.parentId) return;

  // Count direct children and completed children
  const childStats = await prisma.devTicket.aggregate({
    where: { parentId: ticket.parentId },
    _count: { id: true }});

  const completedStats = await prisma.devTicket.count({
    where: {
      parentId: ticket.parentId,
      status: { in: ['COMPLETED'] }}});

  // Update parent
  await prisma.devTicket.update({
    where: { id: ticket.parentId },
    data: {
      childCount: childStats._count.id,
      completedChildCount: completedStats}});

  // Recursively update ancestors
  await updateChildCounts(ticket.parentId);
}
 
/**
 * Updates child counts directly for a specific parent
 */
export async function updateParentChildCounts(parentId: string): Promise<void> {
  const childCount = await prisma.devTicket.count({
    where: { parentId }});

  const completedChildCount = await prisma.devTicket.count({
    where: {
      parentId,
      status: 'COMPLETED'}});

  await prisma.devTicket.update({
    where: { id: parentId },
    data: {
      childCount,
      completedChildCount}});
}
 
/**
 * Gets all ancestors of a ticket (for breadcrumb navigation)
 */
export async function getTicketAncestors(ticketId: string): Promise<DevTicketBreadcrumb[]> {
  const ancestors: DevTicketBreadcrumb[] = [];
  let currentId: string | null = ticketId;

  while (currentId) {
    const ticketData: {
      id: string;
      ticketNumber: string;
      title: string;
      category: string;
      parentId: string | null;
    } | null = await prisma.devTicket.findUnique({
      where: { id: currentId },
      select: {
        id: true,
        ticketNumber: true,
        title: true,
        category: true,
        parentId: true}});

    if (!ticketData) break;

    // Don't include the original ticket in ancestors
    if (ticketData.id !== ticketId) {
      ancestors.unshift({
        id: ticketData.id,
        ticketNumber: ticketData.ticketNumber,
        title: ticketData.title,
        category: ticketData.category as DevTicketCategory});
    }

    currentId = ticketData.parentId;
  }

  return ancestors;
}
 
/**
 * Gets all descendants of a ticket up to a specified depth
 */
export async function getTicketDescendants(
  ticketId: string,
  maxDepth: number = 10
): Promise<string[]> {
  const descendants: string[] = [];
  const queue: { id: string; depth: number }[] = [{ id: ticketId, depth: 0 }];

  while (queue.length > 0) {
    const current = queue.shift()!;
    if (current.depth >= maxDepth) continue;

    const children = await prisma.devTicket.findMany({
      where: { parentId: current.id },
      select: { id: true }});

    for (const child of children) {
      descendants.push(child.id);
      queue.push({ id: child.id, depth: current.depth + 1 });
    }
  }

  return descendants;
}
 
/**
 * Calculates progress for a ticket hierarchy
 */
export async function calculateHierarchyProgress(
  ticketId: string
): Promise<DevTicketHierarchyProgress> {
  const descendants = await getTicketDescendants(ticketId);

  if (descendants.length === 0) {
    // Leaf node
    const ticket = await prisma.devTicket.findUnique({
      where: { id: ticketId },
      select: { status: true, estimatedHours: true, actualHours: true }});

    const isCompleted = ticket?.status === 'COMPLETED';
    return {
      ticketId,
      totalDescendants: 0,
      completedDescendants: 0,
      inProgressDescendants: 0,
      blockedDescendants: 0,
      progressPercentage: isCompleted ? 100 : 0,
      estimatedHoursTotal: ticket?.estimatedHours || 0,
      actualHoursTotal: ticket?.actualHours || 0};
  }

  const descendantTickets = await prisma.devTicket.findMany({
    where: { id: { in: descendants } },
    select: {
      status: true,
      estimatedHours: true,
      actualHours: true}});

  const completed = descendantTickets.filter((t) => t.status === 'COMPLETED').length;
  const inProgress = descendantTickets.filter((t) => t.status === 'IN_PROGRESS').length;
  const blocked = descendantTickets.filter((t) => t.status === 'BLOCKED').length;
  const total = descendantTickets.length;

  const estimatedTotal = descendantTickets.reduce(
    (sum, t) => sum + (t.estimatedHours || 0),
    0
  );
  const actualTotal = descendantTickets.reduce(
    (sum, t) => sum + (t.actualHours || 0),
    0
  );

  return {
    ticketId,
    totalDescendants: total,
    completedDescendants: completed,
    inProgressDescendants: inProgress,
    blockedDescendants: blocked,
    progressPercentage: total > 0 ? Math.round((completed / total) * 100) : 0,
    estimatedHoursTotal: estimatedTotal,
    actualHoursTotal: actualTotal};
}
 
// Type for hierarchy tree building
type HierarchyTicketData = {
  id: string;
  ticketNumber: string;
  title: string;
  status: string;
  category: string;
  childCount: number;
  completedChildCount: number;
};
 
/**
 * Builds a hierarchy tree for display
 */
export async function buildHierarchyTree(
  rootTicketId: string,
  maxDepth: number = 5
): Promise<DevTicketHierarchyNode | null> {
  const rootTicket = await prisma.devTicket.findUnique({
    where: { id: rootTicketId },
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      status: true,
      category: true,
      childCount: true,
      completedChildCount: true}});

  if (!rootTicket) return null;

  async function buildNode(
    ticket: HierarchyTicketData,
    depth: number
  ): Promise<DevTicketHierarchyNode> {
    const progress =
      ticket.childCount > 0
        ? Math.round((ticket.completedChildCount / ticket.childCount) * 100)
        : ticket.status === 'COMPLETED'
          ? 100
          : 0;

    const node: DevTicketHierarchyNode = {
      id: ticket.id,
      ticketNumber: ticket.ticketNumber,
      title: ticket.title,
      status: ticket.status as DevTicketStatus,
      category: ticket.category as DevTicketCategory,
      childCount: ticket.childCount,
      completedChildCount: ticket.completedChildCount,
      progress,
      children: [],
      depth};

    if (depth < maxDepth) {
      const children = await prisma.devTicket.findMany({
        where: { parentId: ticket.id },
        select: {
          id: true,
          ticketNumber: true,
          title: true,
          status: true,
          category: true,
          childCount: true,
          completedChildCount: true},
        orderBy: [{ category: 'asc' }, { createdAt: 'asc' }]});

      for (const child of children) {
        node.children.push(await buildNode(child, depth + 1));
      }
    }

    return node;
  }

  return buildNode(rootTicket, 0);
}
 
/**
 * Moves a ticket to a new parent
 */
export async function moveTicketToParent(
  ticketId: string,
  newParentId: string | null,
  performedById: number
): Promise<{ success: boolean; error?: string }> {
  const ticket = await prisma.devTicket.findUnique({
    where: { id: ticketId },
    select: { id: true, parentId: true, category: true, ticketNumber: true }});

  if (!ticket) {
    return { success: false, error: 'Ticket not found' };
  }

  // Check if trying to move to same parent
  if (ticket.parentId === newParentId) {
    return { success: true };
  }

  // Check for circular reference
  if (newParentId) {
    const descendants = await getTicketDescendants(ticketId);
    if (descendants.includes(newParentId)) {
      return { success: false, error: 'Cannot move ticket to one of its descendants' };
    }

    // Validate parent-child category relationship
    const newParent = await prisma.devTicket.findUnique({
      where: { id: newParentId },
      select: { category: true }});

    if (!newParent) {
      return { success: false, error: 'New parent ticket not found' };
    }

    if (!isValidParentChildCategory(ticket.category as DevTicketCategory, newParent.category as DevTicketCategory)) {
      return {
        success: false,
        error: `Cannot move ${ticket.category} under ${newParent.category}`};
    }
  } else {
    // Moving to root - validate category can be root
    if (!isValidParentChildCategory(ticket.category as DevTicketCategory, null)) {
      return {
        success: false,
        error: `${ticket.category} cannot be a root-level ticket`};
    }
  }

  const oldParentId = ticket.parentId;
  const newHierarchyPath = await buildHierarchyPath(newParentId);
  const newHierarchyLevel = await calculateHierarchyLevel(newParentId);

  // Update the ticket
  await prisma.devTicket.update({
    where: { id: ticketId },
    data: {
      parentId: newParentId,
      hierarchyPath: newHierarchyPath,
      hierarchyLevel: newHierarchyLevel}});

  // Record history
  await createTicketHistory(
    ticketId,
    performedById,
    'parent_changed',
    'parentId',
    oldParentId,
    newParentId
  );

  // Update child counts for old and new parents
  if (oldParentId) {
    await updateParentChildCounts(oldParentId);
  }
  if (newParentId) {
    await updateParentChildCounts(newParentId);
  }

  // Update hierarchy path for all descendants
  await updateDescendantHierarchyPaths(ticketId);

  return { success: true };
}
 
/**
 * Updates hierarchy paths for all descendants of a ticket
 */
async function updateDescendantHierarchyPaths(parentId: string): Promise<void> {
  const children = await prisma.devTicket.findMany({
    where: { parentId },
    select: { id: true }});

  for (const child of children) {
    const newPath = await buildHierarchyPath(parentId);
    const newLevel = await calculateHierarchyLevel(parentId);

    await prisma.devTicket.update({
      where: { id: child.id },
      data: {
        hierarchyPath: newPath ? `${newPath}/${parentId}` : parentId,
        hierarchyLevel: newLevel + 1}});

    // Recursively update descendants
    await updateDescendantHierarchyPaths(child.id);
  }
}
 
/**
 * Records category change in history
 */
export async function recordCategoryChange(
  ticketId: string,
  performedById: number,
  oldCategory: DevTicketCategory,
  newCategory: DevTicketCategory
): Promise<void> {
  await createTicketHistory(
    ticketId,
    performedById,
    'category_changed',
    'category',
    oldCategory,
    newCategory
  );
}
 
/**
 * Records parent change in history
 */
export async function recordParentChange(
  ticketId: string,
  performedById: number,
  oldParentId: string | null,
  newParentId: string | null
): Promise<void> {
  await createTicketHistory(
    ticketId,
    performedById,
    'parent_changed',
    'parentId',
    oldParentId,
    newParentId
  );
}
 
/**
 * Gets all epics (root-level tickets with EPIC category)
 */
export async function getEpics(projectId?: string) {
  const where: Prisma.DevTicketWhereInput = {
    category: 'EPIC',
    parentId: null};

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

  return prisma.devTicket.findMany({
    where,
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      status: true,
      category: true,
      childCount: true,
      completedChildCount: true,
      projectId: true,
      createdAt: true},
    orderBy: { createdAt: 'desc' }});
}
 
/**
 * Gets direct children of a ticket
 */
export async function getTicketChildren(parentId: string) {
  return prisma.devTicket.findMany({
    where: { parentId },
    select: {
      id: true,
      ticketNumber: true,
      title: true,
      status: true,
      category: true,
      childCount: true,
      completedChildCount: true,
      priority: true,
      assigneeId: true},
    orderBy: [{ category: 'asc' }, { priority: 'desc' }, { createdAt: 'asc' }]});
}
 
// ==========================================
// SOFT DELETE UTILITIES
// ==========================================
 
/**
 * Soft deletes a ticket (sets deletedAt timestamp)
 */
export async function softDeleteTicket(
  ticketId: string,
  deletedById: number
): Promise<{ success: boolean; error?: string }> {
  const ticket = await prisma.devTicket.findUnique({
    where: { id: ticketId },
    select: { id: true, ticketNumber: true, parentId: true, deletedAt: true }});

  if (!ticket) {
    return { success: false, error: 'Ticket not found' };
  }

  if (ticket.deletedAt) {
    return { success: false, error: 'Ticket is already deleted' };
  }

  // Soft delete the ticket
  await prisma.devTicket.update({
    where: { id: ticketId },
    data: {
      deletedAt: new Date(),
      deletedById}});

  // Record in history
  await createTicketHistory(ticketId, deletedById, 'soft_deleted');

  // Update parent's child count if applicable
  if (ticket.parentId) {
    await updateParentChildCounts(ticket.parentId);
  }

  return { success: true };
}
 
/**
 * Restores a soft-deleted ticket
 */
export async function restoreTicket(
  ticketId: string,
  restoredById: number
): Promise<{ success: boolean; error?: string }> {
  const ticket = await prisma.devTicket.findUnique({
    where: { id: ticketId },
    select: { id: true, ticketNumber: true, parentId: true, deletedAt: true }});

  if (!ticket) {
    return { success: false, error: 'Ticket not found' };
  }

  if (!ticket.deletedAt) {
    return { success: false, error: 'Ticket is not deleted' };
  }

  // Check if parent exists and is not deleted
  if (ticket.parentId) {
    const parent = await prisma.devTicket.findUnique({
      where: { id: ticket.parentId },
      select: { deletedAt: true }});
    if (parent?.deletedAt) {
      return { success: false, error: 'Cannot restore ticket: parent ticket is deleted' };
    }
  }

  // Restore the ticket
  await prisma.devTicket.update({
    where: { id: ticketId },
    data: {
      deletedAt: null,
      deletedById: null}});

  // Record in history
  await createTicketHistory(ticketId, restoredById, 'restored');

  // Update parent's child count if applicable
  if (ticket.parentId) {
    await updateParentChildCounts(ticket.parentId);
  }

  return { success: true };
}
 
/**
 * Permanently deletes a ticket (hard delete)
 * Only allowed for already soft-deleted tickets
 */
export async function permanentlyDeleteTicket(
  ticketId: string
): Promise<{ success: boolean; error?: string }> {
  const ticket = await prisma.devTicket.findUnique({
    where: { id: ticketId },
    select: { id: true, deletedAt: true, parentId: true }});

  if (!ticket) {
    return { success: false, error: 'Ticket not found' };
  }

  if (!ticket.deletedAt) {
    return { success: false, error: 'Cannot permanently delete a ticket that has not been soft-deleted first' };
  }

  // Check if ticket has children
  const childCount = await prisma.devTicket.count({
    where: { parentId: ticketId }});

  if (childCount > 0) {
    return { success: false, error: 'Cannot permanently delete ticket with children. Delete children first.' };
  }

  // Permanently delete the ticket (cascade will handle related records)
  await prisma.devTicket.delete({
    where: { id: ticketId }});

  // Update parent's child count if applicable
  if (ticket.parentId) {
    await updateParentChildCounts(ticket.parentId);
  }

  return { success: true };
}
 
/**
 * Records soft delete in history
 */
export async function recordSoftDelete(
  ticketId: string,
  performedById: number
): Promise<void> {
  await createTicketHistory(ticketId, performedById, 'soft_deleted');
}
 
/**
 * Records restore in history
 */
export async function recordRestore(
  ticketId: string,
  performedById: number
): Promise<void> {
  await createTicketHistory(ticketId, performedById, 'restored');
}