@adatechnology/meta-whatsapp-module 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -648,11 +648,41 @@ var MessageRepository = class {
648
648
  const [created] = await this.db.insert(messages).values(values).onConflictDoNothing().returning();
649
649
  return created;
650
650
  }
651
- async updateMessageStatus(companyId, waMessageId, status) {
651
+ /**
652
+ * O motivo da recusa entra em `payload` por merge, não por sobrescrita: a coluna já pode guardar
653
+ * o que o envio gravou, e trocar aquilo pelo erro perderia o conteúdo para registrar a falha —
654
+ * exatamente a linha em que se vai querer os dois juntos.
655
+ *
656
+ * O parâmetro vai como objeto, nunca como `JSON.stringify`: o driver `bun-sql` liga string a
657
+ * jsonb como *escalar string*, e aí `||` concatena em array (`[{...}, "{...}"]`) em vez de
658
+ * mesclar, sem erro nenhum para denunciar.
659
+ *
660
+ * `normalizedPayload` existe porque a mesma armadilha já gravou linha torta: `mapToDriverValue`
661
+ * do jsonb do drizzle faz `JSON.stringify`, então toda escrita anterior sob `bun-sql` virou
662
+ * escalar string no banco. A leitura desfaz (`JSON.parse`) e esconde isso do app, mas o `||`
663
+ * não desfaz. Aqui a linha é normalizada de volta a objeto na própria escrita, em vez de o
664
+ * merge produzir lixo sobre um dado que já estava errado.
665
+ *
666
+ * Coberto por `MessageRepository.deliveryError.integration.test.ts` contra Postgres de verdade:
667
+ * é diferença de driver, e mock nenhum a reproduz.
668
+ */
669
+ async updateMessageStatus(params) {
670
+ const { companyId, waMessageId, status, deliveryError } = params;
671
+ const column = messages.payload;
672
+ const normalizedPayload = import_drizzle_orm3.sql`case
673
+ when jsonb_typeof(${column}) = 'object' then ${column}
674
+ when jsonb_typeof(${column}) = 'string' then (${column} #>> '{}')::jsonb
675
+ else '{}'::jsonb
676
+ end`;
652
677
  const [updated] = await this.db.update(messages).set({
653
678
  status,
654
679
  ...status === "read" ? {
655
680
  readAt: /* @__PURE__ */ new Date()
681
+ } : {},
682
+ ...deliveryError ? {
683
+ payload: import_drizzle_orm3.sql`${normalizedPayload} || ${{
684
+ deliveryError
685
+ }}::jsonb`
656
686
  } : {}
657
687
  }).where((0, import_drizzle_orm3.and)((0, import_drizzle_orm3.eq)(messages.companyId, companyId), (0, import_drizzle_orm3.eq)(messages.waMessageId, waMessageId))).returning();
658
688
  return updated;
@@ -2826,8 +2856,22 @@ var ReceiveWebhookUseCase = class {
2826
2856
  receivedAt: Date.now()
2827
2857
  });
2828
2858
  }
2859
+ /**
2860
+ * Recusa de entrega não é exceção: a Meta responde 200 ao envio e só depois manda `failed` neste
2861
+ * webhook. Para quem não guarda o motivo aqui, todo envio recusado vira silêncio idêntico ao de
2862
+ * um bug próprio — o cliente não recebe nada e não há onde ler de quem é a culpa.
2863
+ *
2864
+ * O motivo segue em duas direções porque as perguntas são duas: `payload` responde "este envio
2865
+ * chegou?" muito depois, e `onStatusUpdate` deixa o host reagir agora (alertar, pausar a fila,
2866
+ * trocar de canal).
2867
+ */
2829
2868
  async handleStatus(companyId, status) {
2830
- const updated = await this.params.messageRepository.updateMessageStatus(companyId, status.id, status.status);
2869
+ const updated = await this.params.messageRepository.updateMessageStatus({
2870
+ companyId,
2871
+ waMessageId: status.id,
2872
+ status: status.status,
2873
+ deliveryError: status.errors?.[0]
2874
+ });
2831
2875
  if (!updated) return;
2832
2876
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
2833
2877
  waMessageId: status.id,