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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x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5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 5x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 3x 3x 3x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 4x 4x 4x 3x 3x 3x 3x 3x | export const dynamic = "force-dynamic";
/**
* Support Ticket Utility Functions
*/
import { prisma } from '@/lib/prisma';
import {
TicketStatus,
TicketPriority,
SupportTicket,
SupportTicketWithRelations,
TicketFilters } from '@/types/support';
import {
TICKET_NUMBER_PREFIX,
STATUS_TRANSITIONS,
SLA_TARGETS,
TICKET_HISTORY_ACTIONS } from '@/constants/support';
import { Prisma, TicketStatus as PrismaTicketStatus, TicketPriority as PrismaTicketPriority, TicketCategory as PrismaTicketCategory } from '@prisma/client';
/**
* Generate a unique ticket number
* Format: TKT-XXXXXX (e.g., TKT-001234)
*/
export async function generateTicketNumber(): Promise<string> {
// Get the count of existing tickets
const count = await prisma.supportTicket.count();
const nextNumber = count + 1;
// Format with leading zeros (6 digits)
const paddedNumber = String(nextNumber).padStart(6, '0');
return `${TICKET_NUMBER_PREFIX}-${paddedNumber}`;
}
/**
* Check if a status transition is valid
*/
export function isValidStatusTransition(
currentStatus: TicketStatus,
newStatus: TicketStatus
): boolean {
const allowedTransitions = STATUS_TRANSITIONS[currentStatus];
return allowedTransitions.includes(newStatus);
}
/**
* Get SLA deadline based on priority
*/
export function getSLADeadline(
priority: TicketPriority,
type: 'firstResponse' | 'resolution',
fromDate: Date = new Date()
): Date {
const hours = SLA_TARGETS[priority][type];
const deadline = new Date(fromDate);
deadline.setHours(deadline.getHours() + hours);
return deadline;
}
/**
* Check if SLA is breached
*/
export function isSLABreached(
ticket: Pick<SupportTicket, 'priority' | 'createdAt' | 'firstResponseAt' | 'resolvedAt'>,
type: 'firstResponse' | 'resolution'
): boolean {
const deadline = getSLADeadline(ticket.priority, type, ticket.createdAt);
const now = new Date();
if (type === 'firstResponse') {
// If already responded, check if it was within SLA
if (ticket.firstResponseAt) {
return ticket.firstResponseAt > deadline;
}
// Otherwise, check if current time is past deadline
return now > deadline;
}
// Resolution SLA
if (ticket.resolvedAt) {
return ticket.resolvedAt > deadline;
}
return now > deadline;
}
/**
* Calculate time remaining until SLA breach (in milliseconds)
* Returns negative number if already breached
*/
export function getTimeUntilSLABreach(
ticket: Pick<SupportTicket, 'priority' | 'createdAt' | 'firstResponseAt' | 'resolvedAt'>,
type: 'firstResponse' | 'resolution'
): number {
const deadline = getSLADeadline(ticket.priority, type, ticket.createdAt);
const now = new Date();
if (type === 'firstResponse' && ticket.firstResponseAt) {
return deadline.getTime() - ticket.firstResponseAt.getTime();
}
if (type === 'resolution' && ticket.resolvedAt) {
return deadline.getTime() - ticket.resolvedAt.getTime();
}
return deadline.getTime() - now.getTime();
}
/**
* Build Prisma where clause from filters
*/
export function buildTicketWhereClause(filters: TicketFilters): Prisma.SupportTicketWhereInput {
const where: Prisma.SupportTicketWhereInput = {};
if (filters.status) {
where.status = Array.isArray(filters.status)
? { in: filters.status as PrismaTicketStatus[] }
: filters.status as PrismaTicketStatus;
}
if (filters.priority) {
where.priority = Array.isArray(filters.priority)
? { in: filters.priority as PrismaTicketPriority[] }
: filters.priority as PrismaTicketPriority;
}
if (filters.category) {
where.category = Array.isArray(filters.category)
? { in: filters.category as PrismaTicketCategory[] }
: filters.category as PrismaTicketCategory;
}
if (filters.assignedToId !== undefined) {
where.assignedToId = filters.assignedToId;
}
if (filters.userId) {
where.userId = filters.userId;
}
if (filters.search) {
where.OR = [
{ ticketNumber: { contains: filters.search } },
{ subject: { contains: filters.search } },
{ description: { contains: filters.search } },
{ customerEmail: { contains: filters.search } },
{ customerName: { contains: filters.search } },
];
}
if (filters.dateFrom || filters.dateTo) {
where.createdAt = {};
if (filters.dateFrom) {
where.createdAt.gte = filters.dateFrom;
}
if (filters.dateTo) {
where.createdAt.lte = filters.dateTo;
}
}
return where;
}
/**
* Create a ticket history entry
*/
export async function createTicketHistory(
ticketId: string,
action: string,
oldValue: string | null,
newValue: string | null,
performedBy: number | null
): Promise<void> {
await prisma.ticketHistory.create({
data: {
ticketId,
action,
oldValue,
newValue,
performedBy}});
}
/**
* Record ticket creation in history
*/
export async function recordTicketCreation(
ticketId: string,
userId: number | null
): Promise<void> {
await createTicketHistory(
ticketId,
TICKET_HISTORY_ACTIONS.CREATED,
null,
null,
userId
);
}
/**
* Record status change in history
*/
export async function recordStatusChange(
ticketId: string,
oldStatus: TicketStatus,
newStatus: TicketStatus,
performedBy: number | null
): Promise<void> {
await createTicketHistory(
ticketId,
TICKET_HISTORY_ACTIONS.STATUS_CHANGED,
oldStatus,
newStatus,
performedBy
);
}
/**
* Record priority change in history
*/
export async function recordPriorityChange(
ticketId: string,
oldPriority: TicketPriority,
newPriority: TicketPriority,
performedBy: number | null
): Promise<void> {
await createTicketHistory(
ticketId,
TICKET_HISTORY_ACTIONS.PRIORITY_CHANGED,
oldPriority,
newPriority,
performedBy
);
}
/**
* Record ticket assignment in history
*/
export async function recordAssignment(
ticketId: string,
oldAssigneeId: number | null,
newAssigneeId: number | null,
performedBy: number | null
): Promise<void> {
const action = newAssigneeId
? TICKET_HISTORY_ACTIONS.ASSIGNED
: TICKET_HISTORY_ACTIONS.UNASSIGNED;
await createTicketHistory(
ticketId,
action,
oldAssigneeId?.toString() ?? null,
newAssigneeId?.toString() ?? null,
performedBy
);
}
/**
* Get tickets assigned to a specific agent
*/
export async function getAgentTickets(
agentId: number,
status?: TicketStatus | TicketStatus[]
): Promise<SupportTicketWithRelations[]> {
const where: Prisma.SupportTicketWhereInput = {
assignedToId: agentId};
if (status) {
where.status = Array.isArray(status) ? { in: status } : status;
}
const tickets = await prisma.supportTicket.findMany({
where,
include: {
user: {
select: { id: true, name: true, email: true }},
_count: {
select: { messages: true }}},
orderBy: [
{ priority: 'desc' },
{ createdAt: 'asc' },
]});
return tickets as unknown as SupportTicketWithRelations[];
}
/**
* Get unassigned tickets
*/
export async function getUnassignedTickets(): Promise<SupportTicketWithRelations[]> {
const tickets = await prisma.supportTicket.findMany({
where: {
assignedToId: null,
status: {
in: [TicketStatus.OPEN, TicketStatus.IN_PROGRESS]}},
include: {
user: {
select: { id: true, name: true, email: true }},
_count: {
select: { messages: true }}},
orderBy: [
{ priority: 'desc' },
{ createdAt: 'asc' },
]});
return tickets as unknown as SupportTicketWithRelations[];
}
/**
* Get tickets needing attention (SLA at risk)
*/
export async function getTicketsAtRisk(): Promise<SupportTicketWithRelations[]> {
// Get all open/in-progress tickets
const tickets = await prisma.supportTicket.findMany({
where: {
status: {
in: [
TicketStatus.OPEN,
TicketStatus.IN_PROGRESS,
TicketStatus.AWAITING_AGENT,
]}},
include: {
user: {
select: { id: true, name: true, email: true }},
assignedTo: {
select: { id: true, name: true, email: true }},
_count: {
select: { messages: true }}},
orderBy: { createdAt: 'asc' }});
// Filter to tickets where SLA is at risk (< 1 hour remaining or breached)
const atRiskTickets = tickets.filter((ticket) => {
const type = ticket.firstResponseAt ? 'resolution' : 'firstResponse';
const timeRemaining = getTimeUntilSLABreach(
{
priority: ticket.priority as TicketPriority,
createdAt: ticket.createdAt,
firstResponseAt: ticket.firstResponseAt,
resolvedAt: ticket.resolvedAt},
type
);
// At risk if less than 1 hour remaining
return timeRemaining < 60 * 60 * 1000;
});
return atRiskTickets as unknown as SupportTicketWithRelations[];
}
/**
* Auto-assign ticket to available agent
* Returns the agent ID if assigned, null if no agents available
*/
export async function autoAssignTicket(
ticketId: string,
category: string
): Promise<number | null> {
// Find available agents who handle this category
const availableAgents = await prisma.supportAgentProfile.findMany({
where: {
isAvailable: true,
OR: [
{ specialties: { contains: category } },
{ specialties: null }, // Agents without specialties handle all categories
]},
include: {
user: {
select: { id: true }}},
orderBy: {
totalTickets: 'asc', // Assign to agent with fewer tickets
}});
if (availableAgents.length === 0) {
return null;
}
// Get ticket counts for each agent
const agentCounts = await Promise.all(
availableAgents.map(async (agent) => {
const activeCount = await prisma.supportTicket.count({
where: {
assignedToId: agent.userId,
status: {
in: [
TicketStatus.OPEN,
TicketStatus.IN_PROGRESS,
TicketStatus.AWAITING_CUSTOMER,
TicketStatus.AWAITING_AGENT,
]}}});
return {
agent,
activeCount};
})
);
// Find agent with capacity (active tickets < max)
const availableAgent = agentCounts.find(
({ agent, activeCount }) => activeCount < agent.maxActiveTickets
);
if (!availableAgent) {
return null;
}
// Assign the ticket
await prisma.supportTicket.update({
where: { id: ticketId },
data: { assignedToId: availableAgent.agent.userId }});
return availableAgent.agent.userId;
}
/**
* Format ticket for display
*/
export function formatTicketSummary(ticket: SupportTicketWithRelations): string {
return `${ticket.ticketNumber}: ${ticket.subject} (${ticket.status})`;
}
/**
* Calculate average response time for an agent (in seconds)
*/
export async function calculateAgentResponseTime(agentId: number): Promise<number | null> {
const tickets = await prisma.supportTicket.findMany({
where: {
assignedToId: agentId,
firstResponseAt: { not: null }},
select: {
createdAt: true,
firstResponseAt: true}});
if (tickets.length === 0) {
return null;
}
const totalResponseTime = tickets.reduce((sum, ticket) => {
if (ticket.firstResponseAt) {
return sum + (ticket.firstResponseAt.getTime() - ticket.createdAt.getTime());
}
return sum;
}, 0);
// Return average in seconds
return Math.round(totalResponseTime / tickets.length / 1000);
}
/**
* Calculate average resolution time for an agent (in seconds)
*/
export async function calculateAgentResolutionTime(agentId: number): Promise<number | null> {
const tickets = await prisma.supportTicket.findMany({
where: {
assignedToId: agentId,
resolvedAt: { not: null }},
select: {
createdAt: true,
resolvedAt: true}});
if (tickets.length === 0) {
return null;
}
const totalResolutionTime = tickets.reduce((sum, ticket) => {
if (ticket.resolvedAt) {
return sum + (ticket.resolvedAt.getTime() - ticket.createdAt.getTime());
}
return sum;
}, 0);
// Return average in seconds
return Math.round(totalResolutionTime / tickets.length / 1000);
}
|