From f54a00a07f669d1f70a9de0b014ef9316089fcae Mon Sep 17 00:00:00 2001 From: Judson Cairo Date: Wed, 25 Sep 2024 11:56:51 -0300 Subject: [PATCH] fix: Validate if source id already exists in chatwoot Check if message is already saved before sending it --- .../chatbot/chatwoot/services/chatwoot.service.ts | 7 +++++++ .../chatbot/chatwoot/utils/chatwoot-import-helper.ts | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index fe1c0301..8f5e8f2a 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -890,6 +890,13 @@ export class ChatwootService { sourceId?: string, quotedMsg?: MessageModel, ) { + if (sourceId) { + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); + if (messageAlreadySaved.size > 0) { + this.logger.warn('Message already saved on chatwoot'); + return null; + } + } const data = new FormData(); if (content) { diff --git a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts index 8f1ae580..50881465 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -169,16 +169,17 @@ class ChatwootImport { } } - private async getExistingSourceIds(sourceIds: string[]): Promise> { + public async getExistingSourceIds(sourceIds: string[]): Promise> { const existingSourceIdsSet = new Set(); if (sourceIds.length === 0) { return existingSourceIdsSet; } + const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); // Make sure the sourceId is always formatted as WAID:1234567890 const query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; const pgClient = postgresClient.getChatwootConnection(); - const result = await pgClient.query(query, [sourceIds]); + const result = await pgClient.query(query, [formattedSourceIds]); for (const row of result.rows) { existingSourceIdsSet.add(row.source_id);