diff --git a/src/api/integrations/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatwoot/services/chatwoot.service.ts index fa97ac2e..fed5b787 100644 --- a/src/api/integrations/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatwoot/services/chatwoot.service.ts @@ -28,6 +28,7 @@ import { PrismaRepository } from '../../../repository/repository.service'; import { WAMonitoringService } from '../../../services/monitor.service'; import { Events } from '../../../types/wa.types'; import { ChatwootDto } from '../dto/chatwoot.dto'; +import { postgresClient } from '../libs/postgres.client'; import { chatwootImport } from '../utils/chatwoot-import-helper'; interface ChatwootMessage { @@ -50,6 +51,8 @@ export class ChatwootService { private readonly cache: ICache, ) {} + private pgClient = postgresClient.getChatwootConnection(); + private async getProvider(instance: InstanceDto) { const cacheKey = `${instance.instanceName}:getProvider`; if (await this.cache.has(cacheKey)) { @@ -320,6 +323,12 @@ export class ChatwootService { return null; } + const findContact = await this.findContact(instance, phoneNumber); + + const contactId = findContact?.id; + + await this.addLabelToContact(this.provider.nameInbox, contactId); + return contact; } @@ -349,6 +358,33 @@ export class ChatwootService { } } + public async addLabelToContact(nameInbox: string, contactId: number) { + try { + const sqlTags = `SELECT id FROM tags WHERE name = '${nameInbox}' LIMIT 1`; + + const tagData = (await this.pgClient.query(sqlTags))?.rows[0]; + let tagId = tagData?.id; + const taggingsCount = tagData?.taggings_count || 0; + + const sqlTag = `INSERT INTO tags (name, taggings_count) VALUES ('${nameInbox}', ${ + taggingsCount + 1 + }) ON CONFLICT (name) DO UPDATE SET taggings_count = ${taggingsCount + 1} RETURNING id`; + + tagId = (await this.pgClient.query(sqlTag))?.rows[0]?.id; + + await this.pgClient.query(sqlTag); + + const sqlInsertLabel = `INSERT INTO taggings (tag_id, taggable_type, taggable_id, context, created_at) VALUES (${tagId}, 'Contact', ${contactId}, 'labels', NOW())`; + + await this.pgClient.query(sqlInsertLabel); + + return true; + } catch (error) { + this.logger.error(error); + return false; + } + } + public async findContact(instance: InstanceDto, phoneNumber: string) { const client = await this.clientCw(instance); diff --git a/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts index b59d6227..eea3831b 100644 --- a/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatwoot/utils/chatwoot-import-helper.ts @@ -96,6 +96,17 @@ class ChatwootImport { let contactsChunk: Contact[] = this.sliceIntoChunks(contacts, 3000); while (contactsChunk.length > 0) { + const labelSql = `SELECT id FROM labels WHERE title = '${provider.nameInbox}' AND account_id = ${provider.accountId} LIMIT 1`; + + let labelId = (await pgClient.query(labelSql))?.rows[0]?.id; + + if (!labelId) { + // creating label in chatwoot db and getting the id + const sqlLabel = `INSERT INTO labels (title, color, show_on_sidebar, account_id, created_at, updated_at) VALUES ('${provider.nameInbox}', '#34039B', true, ${provider.accountId}, NOW(), NOW()) RETURNING id`; + + labelId = (await pgClient.query(sqlLabel))?.rows[0]?.id; + } + // inserting contacts in chatwoot db let sqlInsert = `INSERT INTO contacts (name, phone_number, account_id, identifier, created_at, updated_at) VALUES `; @@ -123,6 +134,31 @@ class ChatwootImport { identifier = EXCLUDED.identifier`; totalContactsImported += (await pgClient.query(sqlInsert, bindInsert))?.rowCount ?? 0; + + const sqlTags = `SELECT id FROM tags WHERE name = '${provider.nameInbox}' LIMIT 1`; + + const tagData = (await pgClient.query(sqlTags))?.rows[0]; + let tagId = tagData?.id; + + const sqlTag = `INSERT INTO tags (name, taggings_count) VALUES ('${provider.nameInbox}', ${totalContactsImported}) ON CONFLICT (name) DO UPDATE SET taggings_count = tags.taggings_count + ${totalContactsImported} RETURNING id`; + + tagId = (await pgClient.query(sqlTag))?.rows[0]?.id; + + await pgClient.query(sqlTag); + + let sqlInsertLabel = `INSERT INTO taggings (tag_id, taggable_type, taggable_id, context, created_at) VALUES `; + + contactsChunk.forEach((contact) => { + const bindTaggableId = `(SELECT id FROM contacts WHERE identifier = '${contact.remoteJid}' AND account_id = ${provider.accountId})`; + sqlInsertLabel += `($1, $2, ${bindTaggableId}, $3, NOW()),`; + }); + + if (sqlInsertLabel.slice(-1) === ',') { + sqlInsertLabel = sqlInsertLabel.slice(0, -1); + } + + await pgClient.query(sqlInsertLabel, [tagId, 'Contact', 'labels']); + contactsChunk = this.sliceIntoChunks(contacts, 3000); } diff --git a/src/api/services/channels/whatsapp.baileys.service.ts b/src/api/services/channels/whatsapp.baileys.service.ts index e7b6390c..30e662aa 100644 --- a/src/api/services/channels/whatsapp.baileys.service.ts +++ b/src/api/services/channels/whatsapp.baileys.service.ts @@ -950,7 +950,7 @@ export class BaileysStartupService extends ChannelStartupService { this.sendDataWebhook(Events.CHATS_SET, chatsRaw); - console.log('chatsRaw', chatsRaw); + // console.log('chatsRaw', chatsRaw); const chatsSaved = await this.prismaRepository.chat.createMany({ data: chatsRaw, @@ -1012,7 +1012,7 @@ export class BaileysStartupService extends ChannelStartupService { }); } - console.log('messagesRaw', messagesRaw); + // console.log('messagesRaw', messagesRaw); this.sendDataWebhook(Events.MESSAGES_SET, [...messagesRaw]);