Skip to content

Commit 2f1c970

Browse files
committed
fix: corrige queries SQL e problemas de integração Chatwoot
1 parent 0eb162e commit 2f1c970

3 files changed

Lines changed: 86 additions & 50 deletions

File tree

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

Lines changed: 79 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -562,9 +562,9 @@ export class BaileysStartupService extends ChannelStartupService {
562562
try {
563563
// Use raw SQL to avoid JSON path issues
564564
const webMessageInfo = (await this.prismaRepository.$queryRaw`
565-
SELECT * FROM 'Message'
566-
WHERE 'instanceId' = ${this.instanceId}
567-
AND 'key'->>'id' = ${key.id}
565+
SELECT * FROM "Message"
566+
WHERE "instanceId" = ${this.instanceId}
567+
AND "key"->>'id' = ${key.id}
568568
`) as proto.IWebMessageInfo[];
569569

570570
if (full) {
@@ -1958,9 +1958,9 @@ export class BaileysStartupService extends ChannelStartupService {
19581958
if (configDatabaseData.HISTORIC || configDatabaseData.NEW_MESSAGE) {
19591959
// Use raw SQL to avoid JSON path issues
19601960
const messages = (await this.prismaRepository.$queryRaw`
1961-
SELECT * FROM 'Message'
1962-
WHERE 'instanceId' = ${this.instanceId}
1963-
AND 'key'->>'id' = ${key.id}
1961+
SELECT * FROM "Message"
1962+
WHERE "instanceId" = ${this.instanceId}
1963+
AND "key"->>'id' = ${key.id}
19641964
LIMIT 1
19651965
`) as any[];
19661966
findMessage = messages[0] || null;
@@ -2121,6 +2121,10 @@ export class BaileysStartupService extends ChannelStartupService {
21212121

21222122
// Helper to normalize participantId as phone number
21232123
const normalizePhoneNumber = (id: string): string => {
2124+
// CORREÇÃO: Verifica se 'id' é uma string válida. Se não for, retorna string vazia.
2125+
if (typeof id !== 'string' || !id) {
2126+
return '';
2127+
}
21242128
// Remove @lid, @s.whatsapp.net suffixes and extract just the number part
21252129
return id.split('@')[0];
21262130
};
@@ -2164,6 +2168,7 @@ export class BaileysStartupService extends ChannelStartupService {
21642168
}
21652169
);
21662170

2171+
21672172
// Mantém formato original + adiciona dados resolvidos
21682173
const enhancedParticipantsUpdate = {
21692174
...participantsUpdate,
@@ -5617,25 +5622,49 @@ export class BaileysStartupService extends ChannelStartupService {
56175622
): Promise<number> {
56185623
if (timestamp === undefined || timestamp === null) return 0;
56195624

5620-
// Use raw SQL to avoid JSON path issues
5621-
const result = await this.prismaRepository.$executeRaw`
5622-
UPDATE 'Message'
5623-
SET 'status' = ${status[4]}
5624-
WHERE 'instanceId' = ${this.instanceId}
5625-
AND 'key'->>'remoteJid' = ${remoteJid}
5626-
AND ('key'->>'fromMe')::boolean = false
5627-
AND 'messageTimestamp' <= ${timestamp}
5628-
AND ('status' IS NULL OR 'status' = ${status[3]})
5629-
`;
5630-
5631-
if (result) {
5632-
if (result > 0) {
5633-
this.updateChatUnreadMessages(remoteJid);
5634-
}
5625+
// Retry logic to handle deadlocks
5626+
const maxRetries = 3;
5627+
let lastError;
56355628

5636-
return result;
5629+
for (let attempt = 0; attempt < maxRetries; attempt++) {
5630+
try {
5631+
// Use raw SQL to avoid JSON path issues
5632+
const result = await this.prismaRepository.$executeRaw`
5633+
UPDATE "Message"
5634+
SET "status" = ${status[4]}
5635+
WHERE "instanceId" = ${this.instanceId}
5636+
AND "key"->>'remoteJid' = ${remoteJid}
5637+
AND ("key"->>'fromMe')::boolean = false
5638+
AND "messageTimestamp" <= ${timestamp}
5639+
AND ("status" IS NULL OR "status" = ${status[3]})
5640+
`;
5641+
5642+
if (result) {
5643+
if (result > 0) {
5644+
this.updateChatUnreadMessages(remoteJid);
5645+
}
5646+
5647+
return result;
5648+
}
5649+
5650+
return 0;
5651+
} catch (error) {
5652+
lastError = error;
5653+
// Check if it's a deadlock error (code 40P01)
5654+
if (error?.code === 'P2010' && error?.meta?.code === '40P01') {
5655+
// Wait before retry with exponential backoff
5656+
const waitTime = Math.min(100 * Math.pow(2, attempt), 1000);
5657+
await delay(waitTime);
5658+
this.logger.warn(`Deadlock detected, retrying (${attempt + 1}/${maxRetries})...`);
5659+
continue;
5660+
}
5661+
// If it's not a deadlock, throw immediately
5662+
throw error;
5663+
}
56375664
}
56385665

5666+
// If all retries failed, log and return 0 to avoid breaking the flow
5667+
this.logger.error(`Failed to update messages after ${maxRetries} retries: ${lastError?.message}`);
56395668
return 0;
56405669
}
56415670

@@ -5644,11 +5673,11 @@ export class BaileysStartupService extends ChannelStartupService {
56445673
this.prismaRepository.chat.findFirst({ where: { remoteJid } }),
56455674
// Use raw SQL to avoid JSON path issues
56465675
this.prismaRepository.$queryRaw`
5647-
SELECT COUNT(*)::int as count FROM 'Message'
5648-
WHERE 'instanceId' = ${this.instanceId}
5649-
AND 'key'->>'remoteJid' = ${remoteJid}
5650-
AND ('key'->>'fromMe')::boolean = false
5651-
AND 'status' = ${status[3]}
5676+
SELECT COUNT(*)::int as count FROM "Message"
5677+
WHERE "instanceId" = ${this.instanceId}
5678+
AND "key"->>'remoteJid' = ${remoteJid}
5679+
AND ("key"->>'fromMe')::boolean = false
5680+
AND "status" = ${status[3]}
56525681
`.then((result: any[]) => result[0]?.count || 0),
56535682
]);
56545683

@@ -5662,23 +5691,25 @@ export class BaileysStartupService extends ChannelStartupService {
56625691
return unreadMessages;
56635692
}
56645693

5694+
// O método addLabel também precisa da correção
56655695
private async addLabel(labelId: string, instanceId: string, chatId: string) {
56665696
const id = cuid();
56675697

56685698
await this.prismaRepository.$executeRawUnsafe(
5669-
`INSERT INTO 'Chat' ('id', 'instanceId', 'remoteJid', 'labels', 'createdAt', 'updatedAt')
5670-
VALUES ($4, $2, $3, to_jsonb(ARRAY[$1]::text[]), NOW(), NOW()) ON CONFLICT ('instanceId', 'remoteJid')
5671-
DO
5672-
UPDATE
5673-
SET 'labels' = (
5699+
// CORREÇÃO AQUI: "Chat" e aspas duplas em todos os nomes de colunas
5700+
`INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt")
5701+
VALUES ($4, $2, $3, to_jsonb(ARRAY[$1]::text[]), NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid")
5702+
DO
5703+
UPDATE
5704+
SET "labels" = (
56745705
SELECT to_jsonb(array_agg(DISTINCT elem))
56755706
FROM (
5676-
SELECT jsonb_array_elements_text('Chat'.'labels') AS elem
5707+
SELECT jsonb_array_elements_text("Chat"."labels") AS elem
56775708
UNION
56785709
SELECT $1::text AS elem
56795710
) sub
56805711
),
5681-
'updatedAt' = NOW();`,
5712+
"updatedAt" = NOW();`,
56825713
labelId,
56835714
instanceId,
56845715
chatId,
@@ -5694,19 +5725,20 @@ export class BaileysStartupService extends ChannelStartupService {
56945725
const id = cuid();
56955726

56965727
await this.prismaRepository.$executeRawUnsafe(
5697-
`INSERT INTO 'Chat' ('id', 'instanceId', 'remoteJid', 'labels', 'createdAt', 'updatedAt')
5698-
VALUES ($4, $2, $3, '[]'::jsonb, NOW(), NOW()) ON CONFLICT ('instanceId', 'remoteJid')
5699-
DO
5700-
UPDATE
5701-
SET 'labels' = COALESCE (
5702-
(
5703-
SELECT jsonb_agg(elem)
5704-
FROM jsonb_array_elements_text('Chat'.'labels') AS elem
5705-
WHERE elem <> $1
5706-
),
5707-
'[]'::jsonb
5708-
),
5709-
'updatedAt' = NOW();`,
5728+
// Aspas duplas em "Chat" e em todas as colunas
5729+
`INSERT INTO "Chat" ("id", "instanceId", "remoteJid", "labels", "createdAt", "updatedAt")
5730+
VALUES ($4, $2, $3, '[]'::jsonb, NOW(), NOW()) ON CONFLICT ("instanceId", "remoteJid")
5731+
DO
5732+
UPDATE
5733+
SET "labels" = COALESCE (
5734+
(
5735+
SELECT jsonb_agg(elem)
5736+
FROM jsonb_array_elements_text("Chat"."labels") AS elem
5737+
WHERE elem <> $1
5738+
),
5739+
'[]'::jsonb
5740+
),
5741+
"updatedAt" = NOW();`,
57105742
labelId,
57115743
instanceId,
57125744
chatId,

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1302,7 +1302,11 @@ export class ChatwootService {
13021302
if (message) {
13031303
const key = message.key as WAMessageKey;
13041304

1305-
await waInstance?.client.sendMessage(key.remoteJid, { delete: key });
1305+
// Delete for everyone (both mobile and WhatsApp Web)
1306+
await waInstance?.client.sendMessage(key.remoteJid, {
1307+
delete: key,
1308+
revoke: true
1309+
});
13061310

13071311
await this.prismaRepository.message.deleteMany({
13081312
where: {
@@ -2312,7 +2316,7 @@ export class ChatwootService {
23122316

23132317
if (message.chatwootConversationId) {
23142318
const label = `\`${i18next.t('cw.message.edited')}\``; // "Mensagem editada"
2315-
const editedText = `${label}:${editedMessageContent}`;
2319+
const editedText = `${label}: ${editedMessageContent}`;
23162320
const send = await this.createMessage(
23172321
instance,
23182322
message.chatwootConversationId,

src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ class ChatwootImport {
137137
DO UPDATE SET
138138
name = EXCLUDED.name,
139139
phone_number = EXCLUDED.phone_number,
140-
identifier = EXCLUDED.identifier`;
140+
updated_at = NOW()`;
141141

142142
totalContactsImported += (await pgClient.query(sqlInsert, bindInsert))?.rowCount ?? 0;
143143

0 commit comments

Comments
 (0)