diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bb494b94..5f1dfeb46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * [WIDGET-WORKS] Cache sent message keys in Baileys so WhatsApp echoes are ignored (prevents Chatwoot automation duplicates when `isIntegration=true`). * [WIDGET-WORKS] Skip Chatwoot sync in `messages.upsert` when a message key already has `chatwootMessageId` (handles Chatwoot automation echoes/duplicates). * [WIDGET-WORKS] Avoid dropping group conversations when Chatwoot `updateContact` fails by logging the error and continuing with the existing contact. +* [WIDGET-WORKS] Link template messages to Chatwoot to prevent echo duplicates (fixes "Pending Message" duplicate attribution for automated greetings). ### Features diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index cb2232ac4..e6eee58dd 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -1549,7 +1549,39 @@ export class ChatwootService { sendTelemetry('/message/sendText'); - await waInstance?.textMessage(data); + // [WIDGET-WORKS] Link template messages to Chatwoot to prevent echo duplicates + let messageSent: any; + try { + messageSent = await waInstance?.textMessage(data); + if (!messageSent) { + throw new Error('Template message not sent'); + } + + if (Long.isLong(messageSent?.messageTimestamp)) { + messageSent.messageTimestamp = messageSent.messageTimestamp?.toNumber(); + } + + await this.updateChatwootMessageId( + { + ...messageSent, + instanceId: instance.instanceId, + }, + { + messageId: body.id, + inboxId: body.inbox?.id, + conversationId: body.conversation?.id, + contactInboxSourceId: body.conversation?.contact_inbox?.source_id, + }, + instance, + ); + } catch (error) { + this.logger.warn( + `[WIDGET-WORKS] Failed to update template message ${body.id} with Chatwoot IDs: ${error?.message}`, + ); + if (!messageSent && body.conversation?.id) { + this.onSendMessageError(instance, body.conversation?.id, error); + } + } } return { message: 'bot' };