import { Injectable } from "@nestjs/common"; import { PrismaService } from "../prisma/prisma.service"; @Injectable() export class SupportChatAnalyticsService { constructor(private readonly prisma: PrismaService) {} async stats(startDate?: string, endDate?: string) { const where = this.range(startDate, endDate); const [conversations, messages, authenticated, unanswered, followup, escalated, topics] = await Promise.all([ this.prisma.supportConversation.count({ where }), this.prisma.supportConversationMessage.count({ where: { conversation: where } }), this.prisma.supportConversation.count({ where: { ...where, userId: { not: null } } }), this.prisma.supportConversation.count({ where: { ...where, unanswered: true } }), this.prisma.supportConversation.count({ where: { ...where, needsFollowup: true } }), this.prisma.supportConversation.count({ where: { ...where, escalationSignal: true } }), this.prisma.supportConversation.findMany({ where, select: { topics: true }, take: 5000 }), ]); const topicCounts: Record = {}; for (const row of topics) for (const topic of Array.isArray(row.topics) ? row.topics : []) if (typeof topic === "string") topicCounts[topic] = (topicCounts[topic] || 0) + 1; return { conversations, messages, authenticated, anonymous: conversations - authenticated, unanswered, followup, escalated, topics: topicCounts }; } async conversations(page = 1, limit = 25, startDate?: string, endDate?: string, onlyUnanswered = false) { const safePage = Math.max(1, Math.min(10000, Number(page) || 1)); const safeLimit = Math.max(1, Math.min(100, Number(limit) || 25)); const where = { ...this.range(startDate, endDate), ...(onlyUnanswered ? { unanswered: true } : {}) }; const [data, total] = await Promise.all([ this.prisma.supportConversation.findMany({ where, orderBy: { updatedAt: "desc" }, skip: (safePage - 1) * safeLimit, take: safeLimit, include: { user: { select: { id: true, firstName: true, lastName: true, mobile: true, email: true } }, messages: { orderBy: { sequence: "asc" }, take: 40 } } }), this.prisma.supportConversation.count({ where }), ]); return { data, meta: { total, page: safePage, limit: safeLimit, lastPage: Math.ceil(total / safeLimit) } }; } private range(startDate?: string, endDate?: string) { const createdAt: any = {}; if (startDate && /^\d{4}-\d{2}-\d{2}$/.test(startDate)) createdAt.gte = new Date(`${startDate}T00:00:00.000Z`); if (endDate && /^\d{4}-\d{2}-\d{2}$/.test(endDate)) { const end = new Date(`${endDate}T00:00:00.000Z`); end.setUTCDate(end.getUTCDate() + 1); createdAt.lt = end; } return Object.keys(createdAt).length ? { createdAt } : {}; } }