(data: ISaveOnWhatsappCacheParams[])
| 71 | } |
| 72 | |
| 73 | export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) { |
| 74 | if (!configService.get<Database>('DATABASE').SAVE_DATA.IS_ON_WHATSAPP) { |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | // Processa todos os itens em paralelo para melhor performance |
| 79 | const processingPromises = data.map(async (item) => { |
| 80 | try { |
| 81 | const remoteJid = normalizeJid(item.remoteJid); |
| 82 | if (!remoteJid) { |
| 83 | logger.warn('[saveOnWhatsappCache] Item skipped, missing remoteJid.'); |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | const altJidNormalized = normalizeJid(item.remoteJidAlt); |
| 88 | const lidAltJid = altJidNormalized && altJidNormalized.includes('@lid') ? altJidNormalized : null; |
| 89 | |
| 90 | const baseJids = [remoteJid]; // Garante que o remoteJid esteja na lista inicial |
| 91 | if (lidAltJid) { |
| 92 | baseJids.push(lidAltJid); |
| 93 | } |
| 94 | |
| 95 | const expandedJids = baseJids.flatMap((jid) => getAvailableNumbers(jid)); |
| 96 | |
| 97 | // 1. Busca entrada por jidOptions e também remoteJid |
| 98 | // Às vezes acontece do remoteJid atual NÃO ESTAR no jidOptions ainda, ocasionando o erro: |
| 99 | // 'Unique constraint failed on the fields: (`remoteJid`)' |
| 100 | // Isso acontece principalmente em grupos que possuem o número do criador no ID (ex.: '559911223345-1234567890@g.us') |
| 101 | const existingRecord = await prismaRepository.isOnWhatsapp.findFirst({ |
| 102 | where: { |
| 103 | OR: [ |
| 104 | ...expandedJids.map((jid) => ({ jidOptions: { contains: jid } })), |
| 105 | { remoteJid: remoteJid }, // TODO: Descobrir o motivo que causa o remoteJid não estar (às vezes) incluso na lista de jidOptions |
| 106 | ], |
| 107 | }, |
| 108 | }); |
| 109 | |
| 110 | logger.verbose( |
| 111 | `[saveOnWhatsappCache] Register exists for [${expandedJids.join(',')}]? => ${existingRecord ? existingRecord.remoteJid : 'Not found'}`, |
| 112 | ); |
| 113 | |
| 114 | // 2. Unifica todos os JIDs usando um Set para garantir valores únicos |
| 115 | const finalJidOptions = new Set(expandedJids); |
| 116 | |
| 117 | if (lidAltJid) { |
| 118 | finalJidOptions.add(lidAltJid); |
| 119 | } |
| 120 | |
| 121 | if (existingRecord?.jidOptions) { |
| 122 | existingRecord.jidOptions.split(',').forEach((jid) => finalJidOptions.add(jid)); |
| 123 | } |
| 124 | |
| 125 | // 3. Prepara o payload final |
| 126 | // Ordena os JIDs para garantir consistência na string final |
| 127 | const sortedJidOptions = [...finalJidOptions].sort(); |
| 128 | const newJidOptionsString = sortedJidOptions.join(','); |
| 129 | const newLid = item.lid === 'lid' || item.remoteJid?.includes('@lid') ? 'lid' : null; |
| 130 |
no test coverage detected