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, })