From 25450130401d81e2292fb199f20a1b588741cf90 Mon Sep 17 00:00:00 2001 From: Alex Szefezuk Date: Wed, 21 May 2025 10:36:26 -0300 Subject: [PATCH] fix: enable sourceId exists in a conversation --- .../chatbot/chatwoot/services/chatwoot.service.ts | 2 +- .../chatwoot/utils/chatwoot-import-helper.ts | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index e9b3448a..986d244e 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -930,7 +930,7 @@ export class ChatwootService { quotedMsg?: MessageModel, ) { if (sourceId && this.isImportHistoryAvailable()) { - const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId], conversationId); if (messageAlreadySaved) { if (messageAlreadySaved.size > 0) { this.logger.warn('Message already saved on chatwoot'); 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 52453f59..fb6bcb47 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -169,7 +169,7 @@ class ChatwootImport { } } - public async getExistingSourceIds(sourceIds: string[]): Promise> { + public async getExistingSourceIds(sourceIds: string[], conversationId?: number): Promise> { try { const existingSourceIdsSet = new Set(); @@ -178,9 +178,17 @@ class ChatwootImport { } 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)'; + let query: string; + if (conversationId) { + query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; + } + + if(!conversationId) { + query = 'SELECT source_id FROM messages WHERE source_id = ANY($1) AND conversation_id = $2'; + } + const pgClient = postgresClient.getChatwootConnection(); - const result = await pgClient.query(query, [formattedSourceIds]); + const result = await pgClient.query(query, [formattedSourceIds, conversationId]); for (const row of result.rows) { existingSourceIdsSet.add(row.source_id);