fix: Validate if source id already exists in chatwoot

Check if message is already saved before sending it
This commit is contained in:
Judson Cairo 2024-09-25 11:56:51 -03:00
parent e241cf4ee0
commit f54a00a07f
2 changed files with 10 additions and 2 deletions

View File

@ -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) {

View File

@ -169,16 +169,17 @@ class ChatwootImport {
}
}
private async getExistingSourceIds(sourceIds: string[]): Promise<Set<string>> {
public async getExistingSourceIds(sourceIds: string[]): Promise<Set<string>> {
const existingSourceIdsSet = new Set<string>();
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);