fix(secretaria): corrige 7 inconsistências do issue #14
SEC-01+SEC-11: /secretaria/ask agora envia reply via WhatsApp (sock.sendMessage) e persiste a mensagem no banco Prisma após brain.chat(), com notify Socket.IO. SEC-02+SEC-03: MessageHandler emite hookBus 'ext:message.new' para todo msg recebido. Listener no ext-api auto-dispara a Secretária apenas se NÃO houver AIBot ativo na instância (exclusão mútua — chatbot tem prioridade). SEC-04: ChatListItem exibe ícone BotOff (âmbar) quando chat.bot_paused = true, com tooltip "Bot pausado — aguardando atendente". SEC-05: chatToLegacy() mapeia c.botPaused → bot_paused na bridge legada. NewWhatsChat recebe campo bot_paused opcional. SEC-08: POST /secretaria/ask valida que existe instância CONNECTED antes de criar conversa. Retorna 503 se nenhuma instância disponível. SEC-10: POST /api/chatbot/bots/:instanceId valida que credentialId pertence ao mesmo tenantId antes de criar o bot. Retorna 403 se não pertencer. SEC-12: chatBotState.resumeBot() limpa botSummary (= null) ao retomar, evitando contexto defasado após escalação humana. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@ import type { Knex } from 'knex'
|
||||
import type { WhatsAppConnectionManager } from '../../../backend/src/modules/whatsapp/connection/WhatsAppConnectionManager'
|
||||
import type { PluginConfigStore } from '../../../backend/src/core/plugin-config'
|
||||
import type { HookBus } from '../../../backend/src/core/hook-bus'
|
||||
import type { Server as SocketServer } from 'socket.io'
|
||||
let dragonfly: any;
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
dragonfly = require('../../../dist/infra/cache/dragonfly').dragonfly;
|
||||
@@ -76,9 +77,79 @@ export function buildExtRoutes(
|
||||
db: Knex,
|
||||
config: PluginConfigStore,
|
||||
hooks: HookBus,
|
||||
io?: SocketServer,
|
||||
): Router {
|
||||
const router = Router()
|
||||
|
||||
// ── Helper: envia reply da IA via WA e persiste no banco principal ─────────
|
||||
async function sendSecretariaReply(opts: {
|
||||
instanceId: string
|
||||
tenantId: string
|
||||
chatId: string
|
||||
jid: string
|
||||
reply: string
|
||||
}): Promise<void> {
|
||||
const { instanceId, tenantId, chatId, jid, reply } = opts
|
||||
const sock = manager?.getSocket(instanceId)
|
||||
if (!sock) return
|
||||
const sent = await sock.sendMessage(jid, { text: reply }).catch(() => null)
|
||||
const persisted = await prisma.message.create({
|
||||
data: {
|
||||
tenantId,
|
||||
instanceId,
|
||||
chatId,
|
||||
remoteJid: jid,
|
||||
messageId: sent?.key.id ?? `sec-${Date.now()}`,
|
||||
fromMe: true,
|
||||
type: 'TEXT',
|
||||
body: reply,
|
||||
status: 'SENT',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
}).catch(() => null)
|
||||
if (persisted && io) {
|
||||
io.to(`chat:${chatId}`).emit('message:new', persisted)
|
||||
}
|
||||
}
|
||||
|
||||
// ── SEC-02+SEC-03: auto-trigger da Secretária para mensagens recebidas ────
|
||||
// Só processa se NÃO houver AIBot ativo (exclusão mútua com Chatbot Rápido).
|
||||
hooks.register('ext:message.new', async (data: any) => {
|
||||
const { tenantId, instanceId, chatId, jid, text } = data as {
|
||||
tenantId: string; instanceId: string; chatId: string; jid: string; text: string
|
||||
}
|
||||
if (!text?.trim()) return
|
||||
|
||||
// Exclusão mútua: chatbot rápido tem prioridade se estiver ativo
|
||||
const activeBot = await prisma.aIBot.findFirst({ where: { tenantId, instanceId, enabled: true } })
|
||||
if (activeBot) return
|
||||
|
||||
const extKey = `${tenantId}:${jid}`
|
||||
let conv = await db('sec_conversations').where({ ext_chat_id: extKey, status: 'active' }).first()
|
||||
|
||||
if (!conv) {
|
||||
const agent = await db('sec_agents').where({ active: true }).orderBy('created_at').first()
|
||||
if (!agent) return
|
||||
const [newConv] = await db('sec_conversations').insert({
|
||||
id: uuid(),
|
||||
agent_id: agent.id,
|
||||
contact_name: jid,
|
||||
protocol_number: ProtocolEngine.generateProtocolNumber(),
|
||||
status: 'active',
|
||||
ext_chat_id: extKey,
|
||||
handoff_mode: 'ia',
|
||||
}).returning('*')
|
||||
conv = newConv
|
||||
}
|
||||
|
||||
if (conv.handoff_mode === 'humano') return
|
||||
|
||||
const brain = new ProtocolEngine(db, config)
|
||||
const reply = await brain.chat(conv.id as string, text.trim(), { tenantId, hooks })
|
||||
|
||||
await sendSecretariaReply({ instanceId, tenantId, chatId, jid, reply })
|
||||
})
|
||||
|
||||
// ── Escalation notification listener ──────────────────────────────────────
|
||||
// When escalar_humano tool fires, send a WA message to the configured admin phone.
|
||||
hooks.register('ext:escalated', async (data: any) => {
|
||||
@@ -696,6 +767,16 @@ export function buildExtRoutes(
|
||||
}
|
||||
|
||||
try {
|
||||
// SEC-08: valida que existe instância conectada para este tenant
|
||||
const connectedInstance = await prisma.instance.findFirst({
|
||||
where: { tenantId, status: 'CONNECTED' },
|
||||
select: { id: true },
|
||||
})
|
||||
if (!connectedInstance) {
|
||||
res.status(503).json({ error: 'Nenhuma instância WhatsApp conectada para este tenant.' })
|
||||
return
|
||||
}
|
||||
|
||||
const extKey = `${tenantId}:${chatId}`
|
||||
|
||||
let conv = await db('sec_conversations')
|
||||
@@ -743,6 +824,22 @@ export function buildExtRoutes(
|
||||
tenantId,
|
||||
})
|
||||
|
||||
// SEC-01+SEC-11: envia reply via WA e persiste no banco principal
|
||||
const chat = await prisma.chat.findFirst({
|
||||
where: { tenantId, remoteJid: chatId },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
select: { id: true, instanceId: true },
|
||||
})
|
||||
if (chat) {
|
||||
await sendSecretariaReply({
|
||||
instanceId: chat.instanceId,
|
||||
tenantId,
|
||||
chatId: chat.id,
|
||||
jid: chatId,
|
||||
reply,
|
||||
})
|
||||
}
|
||||
|
||||
res.json({
|
||||
reply,
|
||||
conversationId: conv.id,
|
||||
|
||||
Reference in New Issue
Block a user