fix(chat): melhora fixLegacySessions para buscar todas sessoes

- Busca todas as sessoes, nao apenas por index
- Corrige sessoes encerradas que tambem nao tem o campo
- Adiciona log das sessoes problematicas encontradas

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
rever-tecnologia 2025-12-15 16:30:45 -03:00
parent 0f3ba07a5e
commit f1833be1ea

View file

@ -902,19 +902,22 @@ export const fixLegacySessions = mutation({
handler: async (ctx) => { handler: async (ctx) => {
const now = Date.now() const now = Date.now()
// Buscar sessoes ativas que podem ter campos faltando // Buscar TODAS as sessoes (nao so por index) para garantir que pegamos as problematicas
const activeSessions = await ctx.db const allSessions = await ctx.db
.query("liveChatSessions") .query("liveChatSessions")
.withIndex("by_status_lastActivity", (q) => q.eq("status", "ACTIVE")) .take(500)
.take(100)
let fixed = 0 let fixed = 0
let ended = 0 let ended = 0
const problematic: string[] = []
for (const session of activeSessions) { for (const session of allSessions) {
// Se sessao nao tem lastAgentMessageAt, adiciona o valor de startedAt // Se sessao nao tem lastAgentMessageAt, adiciona o valor
if (session.lastAgentMessageAt === undefined) { if (session.lastAgentMessageAt === undefined) {
// Sessao muito antiga (mais de 24h) - encerrar problematic.push(session._id)
if (session.status === "ACTIVE") {
// Sessao ativa muito antiga (mais de 24h) - encerrar
if (now - session.startedAt > 24 * 60 * 60 * 1000) { if (now - session.startedAt > 24 * 60 * 60 * 1000) {
await ctx.db.patch(session._id, { await ctx.db.patch(session._id, {
status: "ENDED", status: "ENDED",
@ -929,11 +932,18 @@ export const fixLegacySessions = mutation({
}) })
fixed++ fixed++
} }
} else {
// Sessao ja encerrada - apenas adicionar o campo
await ctx.db.patch(session._id, {
lastAgentMessageAt: session.lastActivityAt ?? session.startedAt,
})
fixed++
}
} }
} }
console.log(`fixLegacySessions: fixed=${fixed}, ended=${ended}`) console.log(`fixLegacySessions: fixed=${fixed}, ended=${ended}, problematic=${problematic.join(",")}`)
return { fixed, ended, total: activeSessions.length } return { fixed, ended, total: allSessions.length, problematic }
}, },
}) })