@adatechnology/meta-whatsapp-module 0.4.1 → 0.6.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;
@@ -2188,6 +2218,7 @@ var WhatsAppChannelAdapter = class {
2188
2218
 
2189
2219
  // src/channel/ReceiveWebhook.use-case.ts
2190
2220
  var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
2221
+ var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
2191
2222
 
2192
2223
  // src/channel/webhookSecurity.ts
2193
2224
  var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
@@ -2826,8 +2857,22 @@ var ReceiveWebhookUseCase = class {
2826
2857
  receivedAt: Date.now()
2827
2858
  });
2828
2859
  }
2860
+ /**
2861
+ * Recusa de entrega não é exceção: a Meta responde 200 ao envio e só depois manda `failed` neste
2862
+ * webhook. Para quem não guarda o motivo aqui, todo envio recusado vira silêncio idêntico ao de
2863
+ * um bug próprio — o cliente não recebe nada e não há onde ler de quem é a culpa.
2864
+ *
2865
+ * O motivo segue em duas direções porque as perguntas são duas: `payload` responde "este envio
2866
+ * chegou?" muito depois, e `onStatusUpdate` deixa o host reagir agora (alertar, pausar a fila,
2867
+ * trocar de canal).
2868
+ */
2829
2869
  async handleStatus(companyId, status) {
2830
- const updated = await this.params.messageRepository.updateMessageStatus(companyId, status.id, status.status);
2870
+ const updated = await this.params.messageRepository.updateMessageStatus({
2871
+ companyId,
2872
+ waMessageId: status.id,
2873
+ status: status.status,
2874
+ deliveryError: status.errors?.[0]
2875
+ });
2831
2876
  if (!updated) return;
2832
2877
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
2833
2878
  waMessageId: status.id,
@@ -2850,9 +2895,24 @@ var ReceiveWebhookUseCase = class {
2850
2895
  });
2851
2896
  return;
2852
2897
  }
2853
- await this.dispatcher.run(job);
2898
+ try {
2899
+ await this.dispatcher.run(job);
2900
+ } catch (error) {
2901
+ if (!(0, import_meta_graph_core3.isDeterministicMetaRejection)(error)) throw error;
2902
+ await this.params.hooks?.onInboundEffectRejected?.({
2903
+ companyId: job.companyId,
2904
+ kind: job.kind,
2905
+ whatsappNumber: resolveJobNumber(job),
2906
+ code: error.code,
2907
+ error
2908
+ });
2909
+ }
2854
2910
  }
2855
2911
  };
2912
+ function resolveJobNumber(job) {
2913
+ return job.kind === "message" ? job.message.from : job.whatsappNumber;
2914
+ }
2915
+ __name(resolveJobNumber, "resolveJobNumber");
2856
2916
 
2857
2917
  // src/use-cases/resolveTranscriptionPolicy.ts
2858
2918
  function createTranscriptionPolicyResolver(dependencies) {