fix(send-media): use upsert to prevent P2002 duplicate messageId error

MessageHandler can insert the echo of a sent message before the HTTP
handler does — replace prisma.message.create() with upsert() so both
paths converge safely instead of crashing with a unique constraint error.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
VPS 4 Deploy Agent
2026-05-11 09:21:50 +02:00
parent d7acd75bd5
commit 7b55354653
@@ -167,8 +167,10 @@ export function buildMediaRoutes(manager: WhatsAppConnectionManager): Router {
}) })
const messageType = mediaType.toUpperCase() as any const messageType = mediaType.toUpperCase() as any
const msg = await prisma.message.create({ // Usa upsert para evitar P2002 — o MessageHandler pode ter inserido antes
data: { const msg = await prisma.message.upsert({
where: { instanceId_messageId: { instanceId, messageId } },
create: {
tenantId, tenantId,
instanceId, instanceId,
chatId: chat.id, chatId: chat.id,
@@ -183,6 +185,11 @@ export function buildMediaRoutes(manager: WhatsAppConnectionManager): Router {
status: 'SENT', status: 'SENT',
timestamp: new Date(), timestamp: new Date(),
}, },
update: {
mediaUrl,
mimeType: mimetype,
status: 'SENT',
},
}) })
logger.info({ instanceId, jid, mediaType, size }, 'Mídia enviada') logger.info({ instanceId, jid, mediaType, size }, 'Mídia enviada')