livechat: inicializar sessão com não lidas prévias
This commit is contained in:
parent
c7711dfda5
commit
fe361ff4d8
1 changed files with 37 additions and 1 deletions
|
|
@ -103,6 +103,42 @@ export const startSession = mutation({
|
||||||
|
|
||||||
const now = Date.now()
|
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
|
// Criar nova sessao
|
||||||
const sessionId = await ctx.db.insert("liveChatSessions", {
|
const sessionId = await ctx.db.insert("liveChatSessions", {
|
||||||
tenantId: ticket.tenantId,
|
tenantId: ticket.tenantId,
|
||||||
|
|
@ -117,7 +153,7 @@ export const startSession = mutation({
|
||||||
status: "ACTIVE",
|
status: "ACTIVE",
|
||||||
startedAt: now,
|
startedAt: now,
|
||||||
lastActivityAt: now,
|
lastActivityAt: now,
|
||||||
unreadByMachine: 0,
|
unreadByMachine,
|
||||||
unreadByAgent: 0,
|
unreadByAgent: 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue