Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions 8cbc_backend/controllers/calls/call-statistics.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import express from "express";
import { z } from "zod";
import {
getCallVolumeAnalytics,
getCallResolutionMetrics,
getCallStatisticsSummary,
} from "../../model/calls/call-statistics.model.ts";
import { ResponseBuilder } from "../../responses/response.builder.ts";
import { requireAdmin } from "../../middleware/authorization.ts";

const CallStatisticsController = () => {
const router = express.Router();

// Validation schemas
const dateRangeSchema = z.object({
startDate: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Invalid start date format (YYYY-MM-DD)")
.optional(),
endDate: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Invalid end date format (YYYY-MM-DD)")
.optional(),
});

const volumeAnalyticsQuerySchema = dateRangeSchema.extend({
period: z.enum(["day", "week", "month"]).optional().default("month"),
category: z.enum([
"General Inquiry",
"Technical Support",
"Billing",
"Fraud Report",
"Loan Inquiry",
"Other",
]).optional(),
});

const resolutionMetricsQuerySchema = dateRangeSchema.extend({
category: z.enum([
"General Inquiry",
"Technical Support",
"Billing",
"Fraud Report",
"Loan Inquiry",
"Other",
]).optional(),
});

/**
* GET /analytics/volume
* Get call volume analytics with trends and breakdowns
* Admin only
*/
router.get(
"/analytics/volume",
requireAdmin,
async (req, res, next) => {
try {
const query = volumeAnalyticsQuerySchema.parse(req.query);
const analytics = await getCallVolumeAnalytics(query);

return ResponseBuilder.success(
res,
analytics,
"Call volume analytics retrieved successfully"
);
} catch (error) {
next(error);
}
}
);

/**
* GET /analytics/resolution
* Get call resolution metrics with completion/no-show/cancellation rates
* Admin only
*/
router.get(
"/analytics/resolution",
requireAdmin,
async (req, res, next) => {
try {
const query = resolutionMetricsQuerySchema.parse(req.query);
const metrics = await getCallResolutionMetrics(query);

return ResponseBuilder.success(
res,
metrics,
"Call resolution metrics retrieved successfully"
);
} catch (error) {
next(error);
}
}
);

/**
* GET /analytics/summary
* Get comprehensive call statistics summary (volume + resolution)
*/
router.get(
"/analytics/summary",
requireAdmin,
async (req, res, next) => {
try {
const query = dateRangeSchema.parse(req.query);
const summary = await getCallStatisticsSummary(query);

return ResponseBuilder.success(
res,
summary,
"Call statistics summary retrieved successfully"
);
} catch (error) {
next(error);
}
}
);

return router;
};

export default CallStatisticsController;
5 changes: 5 additions & 0 deletions 8cbc_backend/controllers/calls/calls.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
getAgentStatistics,
getBatchAgentStatistics,
} from "../../model/calls/calls.model.ts";
import CallStatisticsController from "./call-statistics.controller.ts";
import { ResponseBuilder } from "../../responses/response.builder.ts";
import { validate } from "../../middleware/validation.ts";
import { BaseError } from "../../errors/base.error.ts";
Expand Down Expand Up @@ -923,6 +924,10 @@ const CallsController = () => {
}
},
);

// Integrate call statistics routes
router.use("/", CallStatisticsController());

return router;
};

Expand Down
223 changes: 223 additions & 0 deletions 8cbc_backend/drizzle/seeds/seed_call_bookings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import { db } from "../../database/index.ts";
import {
callSlotsTable,
callBookingsTable,
callCategoryEnum,
callStatusEnum,
usersTable,
} from "../../database/schema.ts";
import { and, eq, inArray } from "drizzle-orm";

const CATEGORIES = [
"General Inquiry",
"Technical Support",
"Billing",
"Fraud Report",
"Loan Inquiry",
"Other",
] as const;

const STATUSES = [
"Pending",
"Confirmed",
"Processing",
"Completed",
"NoShow",
"Cancelled",
] as const;

const REASONS = [
"Need help with account setup",
"Unable to access online banking",
"Question about recent transaction",
"Billing dispute",
"Card not working",
"Want to apply for loan",
"Fraud detection on account",
"Password reset assistance",
"Account balance inquiry",
"Transfer issues",
"Statement request",
"Need to update personal information",
"Interest rate inquiry",
"ATM withdrawal problem",
"Mobile app not working",
];

const randomElement = <T,>(arr: readonly T[]): T => {
const index = Math.floor(Math.random() * arr.length);
return arr[index]!;
};

const randomInt = (min: number, max: number): number =>
Math.floor(Math.random() * (max - min + 1)) + min;

const randomPhone = (): string =>
`+65${randomInt(60000000, 99999999)}`;

async function seedCallBookingsForMonth(
year: number,
month: number,
daysInMonth: number,
agentIds: number[],
targetCallsPerMonth: number
) {
const bookingsToInsert: typeof callBookingsTable.$inferInsert[] = [];
const slotsMap = new Map<string, number>();
let callsCreated = 0;

for (let dayNum = 1; dayNum <= daysInMonth && callsCreated < targetCallsPerMonth; dayNum++) {
const dateStr = `${year}-${String(month).padStart(2, "0")}-${String(
dayNum
).padStart(2, "0")}`;

const remainingDays = daysInMonth - dayNum + 1;
const remainingCalls = targetCallsPerMonth - callsCreated;
const avgCallsPerDay = remainingCalls / remainingDays;

const minCalls = remainingCalls > 0 ? Math.max(1, Math.floor(avgCallsPerDay * 0.6)) : 0;
const maxCalls = Math.ceil(avgCallsPerDay * 1.4);
const callsForToday = Math.min(
randomInt(minCalls, maxCalls),
remainingCalls
);

for (let callNum = 0; callNum < callsForToday; callNum++) {
const hour = randomInt(9, 16);
const minute = randomInt(0, 11) * 5;
const timeStr = `${String(hour).padStart(2, "0")}:${String(minute).padStart(
2,
"0"
)}`;

const slotKey = `${dateStr}|${timeStr}`;

// Get or create slot ID
let slotId = slotsMap.get(slotKey);
if (!slotId) {
const slot = await db
.select()
.from(callSlotsTable)
.where(
and(
eq(callSlotsTable.date, dateStr),
eq(callSlotsTable.startTime, timeStr)
)
)
.limit(1);

if (slot.length === 0) {
const result = await db
.insert(callSlotsTable)
.values({
date: dateStr,
startTime: timeStr,
isActive: true,
})
.returning();
slotId = result[0]!.id;
} else {
slotId = slot[0]!.id;
}
slotsMap.set(slotKey, slotId);
}

// Generate booking data
const category = randomElement(CATEGORIES);
const status = randomElement(STATUSES);
const reason = randomElement(REASONS);
const agentId =
Math.random() > 0.3 && agentIds.length > 0 ? randomElement(agentIds) : null;

const date = new Date(`${dateStr}T${timeStr}`);
const updatedAt = new Date(date);

if (status === "Completed") {
updatedAt.setDate(
updatedAt.getDate() + randomInt(1, 4)
);
updatedAt.setHours(updatedAt.getHours() + randomInt(0, 11));
} else if (status === "NoShow") {
updatedAt.setHours(updatedAt.getHours() + randomInt(0, 7));
} else if (status === "Cancelled") {
updatedAt.setHours(updatedAt.getHours() + randomInt(0, 47));
} else if (status === "Processing") {
updatedAt.setHours(updatedAt.getHours() + randomInt(2, 20));
} else if (status === "Confirmed") {
updatedAt.setMinutes(updatedAt.getMinutes() + randomInt(10, 120));
} else if (status === "Pending") {
updatedAt.setMinutes(updatedAt.getMinutes() + randomInt(1, 30));
}

bookingsToInsert.push({
userId: 1,
slotId: slotId,
phoneNumber: randomPhone(),
category: category as typeof callCategoryEnum.enumValues[number],
reason: reason,
status: status as typeof callStatusEnum.enumValues[number],
assignedAgentId: agentId,
createdAt: date,
updatedAt: updatedAt,
});

callsCreated++;
}
}

// Batch insert all bookings for the month
if (bookingsToInsert.length > 0) {
await db.insert(callBookingsTable).values(bookingsToInsert);
}
}

export async function seedCallBookings() {
try {
console.log("🌱 Seeding call bookings...");

// Check if bookings already exist
const existingBookings = await db
.select()
.from(callBookingsTable)
.limit(1);

if (existingBookings.length > 0) {
console.log("Call bookings already exist, skipping...");
return;
}

// Get all staff users (not customers)
const staffUsers = await db
.select({ id: usersTable.id })
.from(usersTable)
.where(inArray(usersTable.userType, ["customer_support", "administrator"]));

const agentIds = staffUsers.map((u) => u.id);

if (agentIds.length === 0) {
console.log("No staff users found, skipping...");
return;
}

// Seed November 2025 - High volume (120 calls)
await seedCallBookingsForMonth(2025, 11, 30, agentIds, 120);
console.log("Seeded November 2025 - 120 calls");

// Seed December 2025 - Decrease (90 calls)
await seedCallBookingsForMonth(2025, 12, 31, agentIds, 90);
console.log("Seeded December 2025 - 90 calls");

// Seed January 2026 - Increase (110 calls)
await seedCallBookingsForMonth(2026, 1, 31, agentIds, 110);
console.log("Seeded January 2026 - 110 calls");

// Seed February 2026 - Decrease (80 calls)
await seedCallBookingsForMonth(2026, 2, 28, agentIds, 80);
console.log("Seeded February 2026 - 80 calls");

console.log("✅ Call bookings seeding complete.");
} catch (error) {
console.error("❌ Seeding call bookings failed:", error);
throw error;
}
}
Loading