Skip to content

Commit 62ea22a

Browse files
Merge pull request #1076 from verbeux-ai/main
[FIX] Fixando label handler e chats
2 parents c4e87c1 + 5d13f70 commit 62ea22a

File tree

4 files changed

+79
-27
lines changed

4 files changed

+79
-27
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"class-validator": "^0.14.1",
6262
"compression": "^1.7.4",
6363
"cors": "^2.8.5",
64+
"cuid": "^3.0.0",
6465
"dayjs": "^1.11.7",
6566
"dotenv": "^16.4.5",
6667
"eventemitter2": "^6.4.9",

prisma/mysql-schema.prisma

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ model Chat {
127127
unreadMessages Int @default(0)
128128
@@index([instanceId])
129129
@@index([remoteJid])
130-
@@unique([instanceId, remoteJid])
130+
@@unique([instanceId, remoteJid])
131131
}
132132

133133
model Contact {

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 73 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ import { LabelAssociation } from 'baileys/lib/Types/LabelAssociation';
125125
import { spawn } from 'child_process';
126126
import { isArray, isBase64, isURL } from 'class-validator';
127127
import { randomBytes } from 'crypto';
128+
import cuid from 'cuid';
128129
import EventEmitter2 from 'eventemitter2';
129130
import ffmpeg from 'fluent-ffmpeg';
130131
import FormData from 'form-data';
@@ -1148,7 +1149,10 @@ export class BaileysStartupService extends ChannelStartupService {
11481149
this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]);
11491150
if (this.configService.get<Database>('DATABASE').SAVE_DATA.CHATS) {
11501151
try {
1151-
await this.prismaRepository.chat.create({
1152+
await this.prismaRepository.chat.update({
1153+
where: {
1154+
id: existingChat.id,
1155+
},
11521156
data: chatToInsert,
11531157
});
11541158
}
@@ -1489,7 +1493,10 @@ export class BaileysStartupService extends ChannelStartupService {
14891493
this.sendDataWebhook(Events.CHATS_UPSERT, [chatToInsert]);
14901494
if (this.configService.get<Database>('DATABASE').SAVE_DATA.CHATS) {
14911495
try {
1492-
await this.prismaRepository.chat.create({
1496+
await this.prismaRepository.chat.update({
1497+
where: {
1498+
id: existingChat.id,
1499+
},
14931500
data: chatToInsert,
14941501
});
14951502
}
@@ -1533,6 +1540,8 @@ export class BaileysStartupService extends ChannelStartupService {
15331540

15341541
private readonly labelHandle = {
15351542
[Events.LABELS_EDIT]: async (label: Label) => {
1543+
this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name });
1544+
15361545
const labelsRepository = await this.prismaRepository.label.findMany({
15371546
where: { instanceId: this.instanceId },
15381547
});
@@ -1567,34 +1576,25 @@ export class BaileysStartupService extends ChannelStartupService {
15671576
create: labelData,
15681577
});
15691578
}
1570-
this.sendDataWebhook(Events.LABELS_EDIT, { ...label, instance: this.instance.name });
15711579
}
15721580
},
15731581

15741582
[Events.LABELS_ASSOCIATION]: async (
15751583
data: { association: LabelAssociation; type: 'remove' | 'add' },
15761584
database: Database,
15771585
) => {
1586+
this.logger.info(
1587+
`labels association - ${data?.association?.chatId} (${data.type}-${data?.association?.type}): ${data?.association?.labelId}`,
1588+
);
15781589
if (database.SAVE_DATA.CHATS) {
1579-
const chats = await this.prismaRepository.chat.findMany({
1580-
where: { instanceId: this.instanceId },
1581-
});
1582-
const chat = chats.find((c) => c.remoteJid === data.association.chatId);
1583-
if (chat) {
1584-
const labelsArray = Array.isArray(chat.labels) ? chat.labels.map((event) => String(event)) : [];
1585-
let labels = [...labelsArray];
1586-
1587-
if (data.type === 'remove') {
1588-
labels = labels.filter((label) => label !== data.association.labelId);
1589-
} else if (data.type === 'add') {
1590-
labels = [...labels, data.association.labelId];
1591-
}
1592-
await this.prismaRepository.chat.update({
1593-
where: { id: chat.id },
1594-
data: {
1595-
labels,
1596-
},
1597-
});
1590+
const instanceId = this.instanceId;
1591+
const chatId = data.association.chatId;
1592+
const labelId = data.association.labelId;
1593+
1594+
if (data.type === 'add') {
1595+
await this.addLabel(labelId, instanceId, chatId);
1596+
} else if (data.type === 'remove') {
1597+
await this.removeLabel(labelId, instanceId, chatId);
15981598
}
15991599
}
16001600

@@ -3884,11 +3884,13 @@ export class BaileysStartupService extends ChannelStartupService {
38843884
try {
38853885
if (data.action === 'add') {
38863886
await this.client.addChatLabel(contact.jid, data.labelId);
3887+
await this.addLabel(data.labelId, this.instanceId, contact.jid);
38873888

38883889
return { numberJid: contact.jid, labelId: data.labelId, add: true };
38893890
}
38903891
if (data.action === 'remove') {
38913892
await this.client.removeChatLabel(contact.jid, data.labelId);
3893+
await this.removeLabel(data.labelId, this.instanceId, contact.jid);
38923894

38933895
return { numberJid: contact.jid, labelId: data.labelId, remove: true };
38943896
}
@@ -4233,6 +4235,7 @@ export class BaileysStartupService extends ChannelStartupService {
42334235
throw new BadRequestException('Unable to leave the group', error.toString());
42344236
}
42354237
}
4238+
42364239
public async templateMessage() {
42374240
throw new Error('Method not available in the Baileys service');
42384241
}
@@ -4349,4 +4352,52 @@ export class BaileysStartupService extends ChannelStartupService {
43494352

43504353
return unreadMessages;
43514354
}
4355+
4356+
private async addLabel(labelId: string, instanceId: string, chatId: string) {
4357+
const id = cuid();
4358+
4359+
await this.prismaRepository.$executeRawUnsafe(
4360+
`INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt")
4361+
VALUES ($4, $2, $3, to_jsonb(ARRAY[$1]::text[]), NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid")
4362+
DO
4363+
UPDATE
4364+
SET "labels" = (
4365+
SELECT to_jsonb(array_agg(DISTINCT elem))
4366+
FROM (
4367+
SELECT jsonb_array_elements_text("Chat"."labels") AS elem
4368+
UNION
4369+
SELECT $1::text AS elem
4370+
) sub
4371+
),
4372+
"updatedAt" = NOW();`,
4373+
labelId,
4374+
instanceId,
4375+
chatId,
4376+
id,
4377+
);
4378+
}
4379+
4380+
private async removeLabel(labelId: string, instanceId: string, chatId: string) {
4381+
const id = cuid();
4382+
4383+
await this.prismaRepository.$executeRawUnsafe(
4384+
`INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt")
4385+
VALUES ($4, $2, $3, '[]'::jsonb, NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid")
4386+
DO
4387+
UPDATE
4388+
SET "labels" = COALESCE (
4389+
(
4390+
SELECT jsonb_agg(elem)
4391+
FROM jsonb_array_elements_text("Chat"."labels") AS elem
4392+
WHERE elem <> $1
4393+
),
4394+
'[]'::jsonb
4395+
),
4396+
"updatedAt" = NOW();`,
4397+
labelId,
4398+
instanceId,
4399+
chatId,
4400+
id,
4401+
);
4402+
}
43524403
}

src/api/services/channel.service.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -655,8 +655,8 @@ export class ChannelStartupService {
655655
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
656656
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
657657
FROM "Chat"
658-
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
659-
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
658+
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid" AND "Chat"."instanceId" = "Message"."instanceId"
659+
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" AND "Chat"."instanceId" = "Contact"."instanceId"
660660
WHERE
661661
"Chat"."instanceId" = ${this.instanceId}
662662
GROUP BY
@@ -690,8 +690,8 @@ export class ChannelStartupService {
690690
(ARRAY_AGG("Message"."sessionId" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_session_id,
691691
(ARRAY_AGG("Message"."status" ORDER BY "Message"."messageTimestamp" DESC))[1] AS last_message_status
692692
FROM "Chat"
693-
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid"
694-
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid"
693+
LEFT JOIN "Message" ON "Message"."messageType" != 'reactionMessage' and "Message"."key"->>'remoteJid' = "Chat"."remoteJid" AND "Chat"."instanceId" = "Message"."instanceId"
694+
LEFT JOIN "Contact" ON "Chat"."remoteJid" = "Contact"."remoteJid" AND "Chat"."instanceId" = "Contact"."instanceId"
695695
WHERE
696696
"Chat"."instanceId" = ${this.instanceId} AND "Chat"."remoteJid" = ${remoteJid} and "Message"."messageType" != 'reactionMessage'
697697
GROUP BY

0 commit comments

Comments
 (0)