Skip to content

Commit f54a00a

Browse files
committed
fix: Validate if source id already exists in chatwoot
Check if message is already saved before sending it
1 parent e241cf4 commit f54a00a

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,6 +890,13 @@ export class ChatwootService {
890890
sourceId?: string,
891891
quotedMsg?: MessageModel,
892892
) {
893+
if (sourceId) {
894+
const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]);
895+
if (messageAlreadySaved.size > 0) {
896+
this.logger.warn('Message already saved on chatwoot');
897+
return null;
898+
}
899+
}
893900
const data = new FormData();
894901

895902
if (content) {

src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,16 +169,17 @@ class ChatwootImport {
169169
}
170170
}
171171

172-
private async getExistingSourceIds(sourceIds: string[]): Promise<Set<string>> {
172+
public async getExistingSourceIds(sourceIds: string[]): Promise<Set<string>> {
173173
const existingSourceIdsSet = new Set<string>();
174174

175175
if (sourceIds.length === 0) {
176176
return existingSourceIdsSet;
177177
}
178178

179+
const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); // Make sure the sourceId is always formatted as WAID:1234567890
179180
const query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)';
180181
const pgClient = postgresClient.getChatwootConnection();
181-
const result = await pgClient.query(query, [sourceIds]);
182+
const result = await pgClient.query(query, [formattedSourceIds]);
182183

183184
for (const row of result.rows) {
184185
existingSourceIdsSet.add(row.source_id);

0 commit comments

Comments
 (0)