diff --git a/CHANGELOG.md b/CHANGELOG.md index a21a04c91..790186755 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * [WIDGET-WORKS] Fix `PrismaClientValidationError` in `messages.update` (missing `Message` relation) by guarding `messageUpdate.create` calls. * [WIDGET-WORKS] Guard `messages.update` cache cleanup with a derived key and optional `MESSAGE_UPDATE_CACHE_DELETE_DISABLED` flag to prevent cache.delete crash-loops. +* [WIDGET-WORKS] Save messages before Chatwoot sync in `/message/sendText` to avoid missing `chatwootMessageId` and log async sync failures. ### Features diff --git a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts index 9ce654344..ab1ecd0db 100644 --- a/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts +++ b/src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts @@ -2195,14 +2195,6 @@ export class BaileysStartupService extends ChannelStartupService { messageSent?.message?.ptvMessage || messageSent?.message?.audioMessage; - if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { - this.chatwootService.eventWhatsapp( - Events.SEND_MESSAGE, - { instanceName: this.instance.name, instanceId: this.instanceId }, - messageRaw, - ); - } - if (this.configService.get('OPENAI').ENABLED && messageRaw?.message?.audioMessage) { const openAiDefaultSettings = await this.prismaRepository.openaiSetting.findFirst({ where: { instanceId: this.instanceId }, @@ -2214,9 +2206,29 @@ export class BaileysStartupService extends ChannelStartupService { } } - if (this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE) { - const msg = await this.prismaRepository.message.create({ data: messageRaw }); + const shouldSaveMessage = this.configService.get('DATABASE').SAVE_DATA.NEW_MESSAGE; + let msg; + + if (shouldSaveMessage) { + msg = await this.prismaRepository.message.create({ data: messageRaw }); + } + + if (this.configService.get('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) { + // [WIDGET-WORKS] Run after DB save to avoid chatwootMessageId race and surface async Chatwoot failures + this.chatwootService + .eventWhatsapp( + Events.SEND_MESSAGE, + { instanceName: this.instance.name, instanceId: this.instanceId }, + messageRaw, + ) + .catch((error) => { + this.logger.error( + `[WIDGET-WORKS] Chatwoot sync failed for message ${messageRaw?.key?.id ?? 'unknown'}: ${error?.message}`, + ); + }); + } + if (shouldSaveMessage && msg) { if (isMedia && this.configService.get('S3').ENABLE) { try { const message: any = messageRaw;