diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index aa71000a..4df0904f 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -933,9 +933,11 @@ export class ChatwootService { ) { if (sourceId && this.isImportHistoryAvailable()) { const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); - if (messageAlreadySaved.size > 0) { - this.logger.warn('Message already saved on chatwoot'); - return null; + if (messageAlreadySaved) { + if (messageAlreadySaved.size > 0) { + this.logger.warn('Message already saved on chatwoot'); + return null; + } } } const data = new FormData(); @@ -2442,57 +2444,61 @@ export class ChatwootService { chatwootConfig: ChatwootDto, prepareMessage: (message: any) => any, ) { - if (!this.isImportHistoryAvailable()) { - return; - } - if (!this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) { - return; - } + try { + if (!this.isImportHistoryAvailable()) { + return; + } + if (!this.configService.get('DATABASE').SAVE_DATA.MESSAGE_UPDATE) { + return; + } - const inbox = await this.getInbox(instance); + const inbox = await this.getInbox(instance); - const sqlMessages = `select * from messages m - where account_id = ${chatwootConfig.accountId} - and inbox_id = ${inbox.id} - and created_at >= now() - interval '6h' - order by created_at desc`; + const sqlMessages = `select * from messages m + where account_id = ${chatwootConfig.accountId} + and inbox_id = ${inbox.id} + and created_at >= now() - interval '6h' + order by created_at desc`; - const messagesData = (await this.pgClient.query(sqlMessages))?.rows; - const ids: string[] = messagesData - .filter((message) => !!message.source_id) - .map((message) => message.source_id.replace('WAID:', '')); + const messagesData = (await this.pgClient.query(sqlMessages))?.rows; + const ids: string[] = messagesData + .filter((message) => !!message.source_id) + .map((message) => message.source_id.replace('WAID:', '')); - const savedMessages = await this.prismaRepository.message.findMany({ - where: { - Instance: { name: instance.instanceName }, - messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() }, - AND: ids.map((id) => ({ key: { path: ['id'], not: id } })), - }, - }); + const savedMessages = await this.prismaRepository.message.findMany({ + where: { + Instance: { name: instance.instanceName }, + messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() }, + AND: ids.map((id) => ({ key: { path: ['id'], not: id } })), + }, + }); - const filteredMessages = savedMessages.filter( - (msg: any) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid), - ); - const messagesRaw: any[] = []; - for (const m of filteredMessages) { - if (!m.message || !m.key || !m.messageTimestamp) { - continue; - } + const filteredMessages = savedMessages.filter( + (msg: any) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid), + ); + const messagesRaw: any[] = []; + for (const m of filteredMessages) { + if (!m.message || !m.key || !m.messageTimestamp) { + continue; + } - if (Long.isLong(m?.messageTimestamp)) { - m.messageTimestamp = m.messageTimestamp?.toNumber(); - } + if (Long.isLong(m?.messageTimestamp)) { + m.messageTimestamp = m.messageTimestamp?.toNumber(); + } - messagesRaw.push(prepareMessage(m as any)); - } + messagesRaw.push(prepareMessage(m as any)); + } - this.addHistoryMessages( - instance, - messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), - ); + this.addHistoryMessages( + instance, + messagesRaw.filter((msg) => !chatwootImport.isIgnorePhoneNumber(msg.key?.remoteJid)), + ); - await chatwootImport.importHistoryMessages(instance, this, inbox, this.provider); - const waInstance = this.waMonitor.waInstances[instance.instanceName]; - waInstance.clearCacheChatwoot(); + await chatwootImport.importHistoryMessages(instance, this, inbox, this.provider); + const waInstance = this.waMonitor.waInstances[instance.instanceName]; + waInstance.clearCacheChatwoot(); + } catch (error) { + return; + } } } 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 e3e15c78..52453f59 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -170,22 +170,26 @@ class ChatwootImport { } public async getExistingSourceIds(sourceIds: string[]): Promise> { - const existingSourceIdsSet = new Set(); + try { + const existingSourceIdsSet = new Set(); - if (sourceIds.length === 0) { - return existingSourceIdsSet; - } + 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, [formattedSourceIds]); + 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, [formattedSourceIds]); - for (const row of result.rows) { - existingSourceIdsSet.add(row.source_id); - } + for (const row of result.rows) { + existingSourceIdsSet.add(row.source_id); + } - return existingSourceIdsSet; + return existingSourceIdsSet; + } catch (error) { + return null; + } } public async importHistoryMessages(