From fe361ff4d861eec2b9e851c554691d86f4b6e6b8 Mon Sep 17 00:00:00 2001 From: esdrasrenan Date: Tue, 9 Dec 2025 01:44:24 -0300 Subject: [PATCH] =?UTF-8?q?livechat:=20inicializar=20sess=C3=A3o=20com=20n?= =?UTF-8?q?=C3=A3o=20lidas=20pr=C3=A9vias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convex/liveChat.ts | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/convex/liveChat.ts b/convex/liveChat.ts index 1468d96..d24eac1 100644 --- a/convex/liveChat.ts +++ b/convex/liveChat.ts @@ -103,6 +103,42 @@ export const startSession = mutation({ const now = Date.now() + // Calcular não lidas iniciais: mensagens do ticket após a última sessão encerrada + // que não foram enviadas pela própria máquina/usuário vinculado. + const lastEndedSession = await ctx.db + .query("liveChatSessions") + .withIndex("by_ticket", (q) => q.eq("ticketId", ticketId)) + .filter((q) => q.eq(q.field("status"), "ENDED")) + .collect() + .then((sessions) => + sessions.reduce( + (latest, current) => + !latest || (current.endedAt ?? 0) > (latest.endedAt ?? 0) ? current : latest, + null as typeof sessions[number] | null + ) + ) + + const cutoff = lastEndedSession?.endedAt ?? 0 + + const machineUserIds = [ + machine.assignedUserId, + ...(machine.linkedUserIds ?? []), + ticket.requesterId, + ] + .filter(Boolean) + .map((id) => id!.toString()) + + const unreadByMachine = await ctx.db + .query("ticketChatMessages") + .withIndex("by_ticket_created", (q) => q.eq("ticketId", ticketId)) + .collect() + .then((messages) => + messages.filter((msg) => { + if (msg.createdAt <= cutoff) return false + return !machineUserIds.includes(msg.authorId.toString()) + }).length + ) + // Criar nova sessao const sessionId = await ctx.db.insert("liveChatSessions", { tenantId: ticket.tenantId, @@ -117,7 +153,7 @@ export const startSession = mutation({ status: "ACTIVE", startedAt: now, lastActivityAt: now, - unreadByMachine: 0, + unreadByMachine, unreadByAgent: 0, })