Skip to content

Commit 5c046d5

Browse files
committed
fix: fixed issue of always creating a new label when saving chatwoot
1 parent 487d8b9 commit 5c046d5

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

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

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -374,23 +374,30 @@ export class ChatwootService {
374374

375375
if (!uri) return false;
376376

377-
const sqlTags = `SELECT id FROM tags WHERE name = '${nameInbox}' LIMIT 1`;
378-
379-
const tagData = (await this.pgClient.query(sqlTags))?.rows[0];
377+
const sqlTags = `SELECT id, taggings_count FROM tags WHERE name = $1 LIMIT 1`;
378+
const tagData = (await this.pgClient.query(sqlTags, [nameInbox]))?.rows[0];
380379
let tagId = tagData?.id;
381380
const taggingsCount = tagData?.taggings_count || 0;
382381

383-
const sqlTag = `INSERT INTO tags (name, taggings_count) VALUES ('${nameInbox}', ${
384-
taggingsCount + 1
385-
}) ON CONFLICT (name) DO UPDATE SET taggings_count = ${taggingsCount + 1} RETURNING id`;
382+
const sqlTag = `INSERT INTO tags (name, taggings_count)
383+
VALUES ($1, $2)
384+
ON CONFLICT (name)
385+
DO UPDATE SET taggings_count = tags.taggings_count + 1
386+
RETURNING id`;
387+
388+
tagId = (await this.pgClient.query(sqlTag, [nameInbox, taggingsCount + 1]))?.rows[0]?.id;
386389

387-
tagId = (await this.pgClient.query(sqlTag))?.rows[0]?.id;
390+
const sqlCheckTagging = `SELECT 1 FROM taggings
391+
WHERE tag_id = $1 AND taggable_type = 'Contact' AND taggable_id = $2 AND context = 'labels' LIMIT 1`;
388392

389-
await this.pgClient.query(sqlTag);
393+
const taggingExists = (await this.pgClient.query(sqlCheckTagging, [tagId, contactId]))?.rowCount > 0;
390394

391-
const sqlInsertLabel = `INSERT INTO taggings (tag_id, taggable_type, taggable_id, context, created_at) VALUES (${tagId}, 'Contact', ${contactId}, 'labels', NOW())`;
395+
if (!taggingExists) {
396+
const sqlInsertLabel = `INSERT INTO taggings (tag_id, taggable_type, taggable_id, context, created_at)
397+
VALUES ($1, 'Contact', $2, 'labels', NOW())`;
392398

393-
await this.pgClient.query(sqlInsertLabel);
399+
await this.pgClient.query(sqlInsertLabel, [tagId, contactId]);
400+
}
394401

395402
return true;
396403
} catch (error) {

0 commit comments

Comments
 (0)