diff --git a/convex/liveChat.ts b/convex/liveChat.ts index 2361784..8009d20 100644 --- a/convex/liveChat.ts +++ b/convex/liveChat.ts @@ -16,6 +16,18 @@ function hashToken(token: string) { return toHex(sha256(utf8(token))) } +async function getLastHeartbeatAt(ctx: MutationCtx | QueryCtx, machineId: Id<"machines">) { + const heartbeat = await ctx.db + .query("machineHeartbeats") + .withIndex("by_machine", (q) => q.eq("machineId", machineId)) + .first() + + if (heartbeat?.lastHeartbeatAt) return heartbeat.lastHeartbeatAt + + const machine = await ctx.db.get(machineId) + return machine?.lastHeartbeatAt ?? null +} + async function validateMachineToken( ctx: MutationCtx | QueryCtx, machineToken: string @@ -84,8 +96,9 @@ export const startSession = mutation({ throw new ConvexError("Máquina não encontrada") } + const lastHeartbeatAt = await getLastHeartbeatAt(ctx, machine._id) const fiveMinutesAgo = Date.now() - 5 * 60 * 1000 - if (!machine.lastHeartbeatAt || machine.lastHeartbeatAt < fiveMinutesAgo) { + if (!lastHeartbeatAt || lastHeartbeatAt < fiveMinutesAgo) { throw new ConvexError("Máquina offline. A máquina precisa estar online para iniciar o chat.") } @@ -567,8 +580,9 @@ export const getTicketSession = query({ // Verificar se maquina esta online (sempre, mesmo sem sessao) const machine = ticket.machineId ? await ctx.db.get(ticket.machineId) : null + const lastHeartbeatAt = machine ? await getLastHeartbeatAt(ctx, machine._id) : null const fiveMinutesAgo = Date.now() - 5 * 60 * 1000 - const machineOnline = machine?.lastHeartbeatAt && machine.lastHeartbeatAt > fiveMinutesAgo + const machineOnline = lastHeartbeatAt !== null && lastHeartbeatAt > fiveMinutesAgo const session = await ctx.db .query("liveChatSessions") @@ -889,3 +903,4 @@ export const generateMachineUploadUrl = action({ return { uploadUrl } }, }) +