From 7b55354653974d273c2ef0022928aa80ad9ba23d Mon Sep 17 00:00:00 2001 From: VPS 4 Deploy Agent Date: Mon, 11 May 2026 09:21:50 +0200 Subject: [PATCH] fix(send-media): use upsert to prevent P2002 duplicate messageId error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../src/modules/whatsapp/whatsapp.media.routes.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/clube67/newwhats.local/backend/src/modules/whatsapp/whatsapp.media.routes.ts b/clube67/newwhats.local/backend/src/modules/whatsapp/whatsapp.media.routes.ts index 3eb913d..add9197 100644 --- a/clube67/newwhats.local/backend/src/modules/whatsapp/whatsapp.media.routes.ts +++ b/clube67/newwhats.local/backend/src/modules/whatsapp/whatsapp.media.routes.ts @@ -167,8 +167,10 @@ export function buildMediaRoutes(manager: WhatsAppConnectionManager): Router { }) const messageType = mediaType.toUpperCase() as any - const msg = await prisma.message.create({ - data: { + // Usa upsert para evitar P2002 — o MessageHandler pode ter inserido antes + const msg = await prisma.message.upsert({ + where: { instanceId_messageId: { instanceId, messageId } }, + create: { tenantId, instanceId, chatId: chat.id, @@ -183,6 +185,11 @@ export function buildMediaRoutes(manager: WhatsAppConnectionManager): Router { status: 'SENT', timestamp: new Date(), }, + update: { + mediaUrl, + mimeType: mimetype, + status: 'SENT', + }, }) logger.info({ instanceId, jid, mediaType, size }, 'Mídia enviada')