@adatechnology/meta-whatsapp-module 0.6.0 → 0.8.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.
Files changed (24) hide show
  1. package/dist/index.cjs +102 -7
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +379 -530
  4. package/dist/index.d.ts +379 -530
  5. package/dist/index.js +103 -11
  6. package/dist/index.js.map +1 -1
  7. package/dist/migrations/20260725195853_freezing_switch/snapshot.json +555 -0
  8. package/dist/migrations/20260725210958_military_leper_queen/snapshot.json +742 -0
  9. package/dist/migrations/20260725214800_illegal_black_tarantula/snapshot.json +810 -0
  10. package/dist/migrations/20260725234507_normal_viper/snapshot.json +930 -0
  11. package/dist/migrations/20260731041538_flow_media_meta_ids/snapshot.json +1649 -0
  12. package/package.json +6 -6
  13. package/dist/migrations/meta/_journal.json +0 -76
  14. /package/dist/migrations/{0000_freezing_switch.sql → 20260725195853_freezing_switch/migration.sql} +0 -0
  15. /package/dist/migrations/{0001_military_leper_queen.sql → 20260725210958_military_leper_queen/migration.sql} +0 -0
  16. /package/dist/migrations/{0002_illegal_black_tarantula.sql → 20260725214800_illegal_black_tarantula/migration.sql} +0 -0
  17. /package/dist/migrations/{0003_normal_viper.sql → 20260725234507_normal_viper/migration.sql} +0 -0
  18. /package/dist/migrations/{0004_widen_message_type.sql → 20260725234508_widen_message_type/migration.sql} +0 -0
  19. /package/dist/migrations/{0005_message_moderation.sql → 20260727182141_message_moderation/migration.sql} +0 -0
  20. /package/dist/migrations/{0006_conversation_documents.sql → 20260727215549_conversation_documents/migration.sql} +0 -0
  21. /package/dist/migrations/{0007_flow_media.sql → 20260728220000_flow_media/migration.sql} +0 -0
  22. /package/dist/migrations/{0008_message_transcription.sql → 20260731041536_message_transcription/migration.sql} +0 -0
  23. /package/dist/migrations/{0009_settings_transcription_policy.sql → 20260731041537_settings_transcription_policy/migration.sql} +0 -0
  24. /package/dist/migrations/{0010_flow_media_meta_ids.sql → 20260731041538_flow_media_meta_ids/migration.sql} +0 -0
package/dist/index.js CHANGED
@@ -525,7 +525,12 @@ var SessionRepository = class {
525
525
  };
526
526
 
527
527
  // src/repositories/MessageRepository.ts
528
- import { and as and2, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
528
+ import { and as and2, count, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
529
+
530
+ // src/inboundLocation.constant.ts
531
+ var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
532
+
533
+ // src/repositories/MessageRepository.ts
529
534
  var DEFAULT_LIMIT2 = 50;
530
535
  var MessageRepository = class {
531
536
  static {
@@ -599,6 +604,49 @@ var MessageRepository = class {
599
604
  return updated;
600
605
  }
601
606
  /**
607
+ * Linhas de entrada com `payload.location` que a redação alcança, mais as localizações com
608
+ * `payload` escalar string (gravação antiga do `bun-sql` com drizzle 0.x), nas quais `payload ?
609
+ * 'location'` dá falso e que, por isso, a redação não toca.
610
+ */
611
+ async countInboundLocations(params) {
612
+ const inboundScope = and2(eq2(messages.companyId, params.companyId), eq2(messages.direction, "inbound"), lt(messages.createdAt, params.receivedBefore));
613
+ const [reachable] = await this.db.select({
614
+ total: count()
615
+ }).from(messages).where(and2(inboundScope, this.hasRedactableLocation()));
616
+ const [unreachable] = await this.db.select({
617
+ total: count()
618
+ }).from(messages).where(and2(inboundScope, eq2(messages.type, "location"), sql3`jsonb_typeof(${messages.payload}) = 'string'`));
619
+ return {
620
+ counted: reachable?.total ?? 0,
621
+ unreachable: unreachable?.total ?? 0
622
+ };
623
+ }
624
+ /**
625
+ * Redige UMA passada: tira `location` de `payload` (NULL quando não sobra chave) e põe o rótulo
626
+ * neutro em `content` das linhas de tipo `location`. Sem `ORDER BY`: o índice por empresa não serve
627
+ * à ordenação e a passada não precisa dela. `FOR UPDATE SKIP LOCKED` evita brigar com o webhook; o
628
+ * `company_id` é repetido fora da subconsulta. Nunca devolve nem registra os ids das linhas.
629
+ */
630
+ async redactInboundLocations(params) {
631
+ const batch = this.db.$with("batch").as(this.db.select({
632
+ id: messages.id
633
+ }).from(messages).where(and2(eq2(messages.companyId, params.companyId), eq2(messages.direction, "inbound"), lt(messages.createdAt, params.receivedBefore), this.hasRedactableLocation())).limit(params.batchSize).for("update", {
634
+ skipLocked: true
635
+ }));
636
+ const updated = await this.db.with(batch).update(messages).set({
637
+ payload: sql3`nullif(${messages.payload} - 'location', '{}'::jsonb)`,
638
+ content: sql3`case when ${messages.type} = 'location' then ${INBOUND_LOCATION_CONTENT} else ${messages.content} end`
639
+ }).from(batch).where(and2(eq2(messages.id, batch.id), eq2(messages.companyId, params.companyId))).returning({
640
+ id: messages.id
641
+ });
642
+ return {
643
+ redacted: updated.length
644
+ };
645
+ }
646
+ hasRedactableLocation() {
647
+ return sql3`jsonb_typeof(${messages.payload}) = 'object' and ${messages.payload} ? 'location'`;
648
+ }
649
+ /**
602
650
  * Grava a transcrição endereçando pelo id da Meta, para quem só tem esse.
603
651
  *
604
652
  * Serve ao caso em que a transcrição acontece no próprio webhook — o grafo precisa do texto para
@@ -1338,8 +1386,38 @@ var PurgeExpiredDocumentsUseCase = class {
1338
1386
  }
1339
1387
  };
1340
1388
 
1389
+ // src/use-cases/RedactInboundLocations.use-case.ts
1390
+ var DEFAULT_BATCH_SIZE2 = 500;
1391
+ var CountInboundLocationsUseCase = class {
1392
+ static {
1393
+ __name(this, "CountInboundLocationsUseCase");
1394
+ }
1395
+ messageRepository;
1396
+ constructor(messageRepository) {
1397
+ this.messageRepository = messageRepository;
1398
+ }
1399
+ async execute(params) {
1400
+ return this.messageRepository.countInboundLocations(params);
1401
+ }
1402
+ };
1403
+ var RedactInboundLocationsUseCase = class {
1404
+ static {
1405
+ __name(this, "RedactInboundLocationsUseCase");
1406
+ }
1407
+ messageRepository;
1408
+ constructor(messageRepository) {
1409
+ this.messageRepository = messageRepository;
1410
+ }
1411
+ async execute(params) {
1412
+ return this.messageRepository.redactInboundLocations({
1413
+ ...params,
1414
+ batchSize: params.batchSize ?? DEFAULT_BATCH_SIZE2
1415
+ });
1416
+ }
1417
+ };
1418
+
1341
1419
  // src/repositories/DocumentRepository.ts
1342
- import { and as and4, asc, count, desc as desc2, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1420
+ import { and as and4, asc, count as count2, desc as desc2, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1343
1421
  var DEFAULT_LIMIT3 = 50;
1344
1422
  function companyDocumentSearch(search) {
1345
1423
  const term = search?.trim();
@@ -1398,7 +1476,7 @@ var DocumentRepository = class {
1398
1476
  const [rows, counted] = await Promise.all([
1399
1477
  this.db.select().from(documents).where(where).orderBy(orderBy).limit(limit).offset((page - 1) * limit),
1400
1478
  this.db.select({
1401
- value: count()
1479
+ value: count2()
1402
1480
  }).from(documents).where(where)
1403
1481
  ]);
1404
1482
  return {
@@ -1449,7 +1527,7 @@ var DocumentRepository = class {
1449
1527
  // `sessions.whatsapp_number`, e uma contagem sem a tabela na cláusula não compila — pior,
1450
1528
  // se compilasse, o total divergiria das linhas e a paginação prometeria páginas vazias.
1451
1529
  this.db.select({
1452
- value: count()
1530
+ value: count2()
1453
1531
  }).from(documents).innerJoin(sessions, eq5(documents.sessionId, sessions.id)).where(where)
1454
1532
  ]);
1455
1533
  return {
@@ -2572,7 +2650,10 @@ var EMPTY_RESULT = {
2572
2650
  accountEventsProcessed: 0,
2573
2651
  unhandledEvents: 0
2574
2652
  };
2575
- function extractContent(message) {
2653
+ var DEFAULT_EXTRACTION_OPTIONS = {
2654
+ isLocationRedacted: false
2655
+ };
2656
+ function extractContent(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPTIONS) {
2576
2657
  if (message.text?.body) return message.text.body;
2577
2658
  const interactive = message.interactive;
2578
2659
  if (interactive?.button_reply) return interactive.button_reply.title || interactive.button_reply.id;
@@ -2582,13 +2663,14 @@ function extractContent(message) {
2582
2663
  return `Pedido: ${items} item(ns)`;
2583
2664
  }
2584
2665
  if (message.location) {
2666
+ if (isLocationRedacted) return INBOUND_LOCATION_CONTENT;
2585
2667
  const label = message.location.name ?? message.location.address;
2586
- return label ? `\u{1F4CD} Localiza\xE7\xE3o: ${label}` : "\u{1F4CD} Localiza\xE7\xE3o";
2668
+ return label ? `\u{1F4CD} Localiza\xE7\xE3o: ${label}` : INBOUND_LOCATION_CONTENT;
2587
2669
  }
2588
2670
  return message.image?.caption ?? message.document?.caption ?? null;
2589
2671
  }
2590
2672
  __name(extractContent, "extractContent");
2591
- function extractPayload(message) {
2673
+ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPTIONS) {
2592
2674
  const payload = {};
2593
2675
  if (message.interactive) payload["interactive"] = message.interactive;
2594
2676
  if (message.order) payload["order"] = message.order;
@@ -2597,7 +2679,7 @@ function extractPayload(message) {
2597
2679
  if (message.video) payload["video"] = message.video;
2598
2680
  if (message.document) payload["document"] = message.document;
2599
2681
  if (message.sticker) payload["sticker"] = message.sticker;
2600
- if (message.location) payload["location"] = message.location;
2682
+ if (message.location && !isLocationRedacted) payload["location"] = message.location;
2601
2683
  if (message.context?.referred_product) payload["referredProduct"] = message.context.referred_product;
2602
2684
  return Object.keys(payload).length > 0 ? payload : null;
2603
2685
  }
@@ -2740,14 +2822,17 @@ var ReceiveWebhookUseCase = class {
2740
2822
  return true;
2741
2823
  }
2742
2824
  async handleMessage(companyId, message, profileName) {
2825
+ const extractionOptions = {
2826
+ isLocationRedacted: this.params.redactInboundLocation ?? false
2827
+ };
2743
2828
  const saved = await this.params.logMessage.execute({
2744
2829
  companyId,
2745
2830
  whatsappNumber: message.from,
2746
2831
  direction: "inbound",
2747
2832
  sender: "customer",
2748
2833
  type: message.type,
2749
- content: extractContent(message),
2750
- payload: extractPayload(message),
2834
+ content: extractContent(message, extractionOptions),
2835
+ payload: extractPayload(message, extractionOptions),
2751
2836
  waMessageId: message.id,
2752
2837
  status: "received",
2753
2838
  startState: this.params.startState
@@ -2906,7 +2991,8 @@ function createMetaWhatsAppModule(params) {
2906
2991
  logMessage,
2907
2992
  startState,
2908
2993
  hooks,
2909
- realtime: providers.realtime
2994
+ realtime: providers.realtime,
2995
+ redactInboundLocation: params.features?.redactInboundLocation ?? false
2910
2996
  });
2911
2997
  const flowInterpreter = flowEngineEnabled ? new FlowInterpreter() : void 0;
2912
2998
  if (flowInterpreter && providers.objectStorage?.getObject) {
@@ -2987,6 +3073,9 @@ function createMetaWhatsAppModule(params) {
2987
3073
  // órfãos, já que a lista de uploadId vive justamente nas linhas que ela derruba.
2988
3074
  delete: new DeleteConversationUseCase(sessionRepository, documentRepository, providers.objectStorage),
2989
3075
  purgeExpiredDocuments: new PurgeExpiredDocumentsUseCase(documentRepository, providers.objectStorage),
3076
+ // Legado de `features.redactInboundLocation`: conta e redige a coordenada já gravada, por empresa.
3077
+ countInboundLocations: new CountInboundLocationsUseCase(messageRepository),
3078
+ redactInboundLocations: new RedactInboundLocationsUseCase(messageRepository),
2990
3079
  export: new ExportConversationUseCase(sessionRepository),
2991
3080
  // undefined quando transcrição não foi injetada, ou quando o storage não sabe ler de volta.
2992
3081
  // O painel consulta a ausência para decidir se desenha o botão "transcrever".
@@ -3130,6 +3219,7 @@ async function redeemSseTicket(store, ticket) {
3130
3219
  }
3131
3220
  __name(redeemSseTicket, "redeemSseTicket");
3132
3221
  export {
3222
+ CountInboundLocationsUseCase,
3133
3223
  CreateFlowGraphUseCase,
3134
3224
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
3135
3225
  DeleteConversationUseCase,
@@ -3143,6 +3233,7 @@ export {
3143
3233
  FlowMediaRepository,
3144
3234
  GetFlowGraphUseCase,
3145
3235
  GetLiveFlowPositionsUseCase,
3236
+ INBOUND_LOCATION_CONTENT,
3146
3237
  InboundEffectsDispatcher,
3147
3238
  IngestInboundMediaUseCase,
3148
3239
  InvalidFlowGraphError,
@@ -3160,6 +3251,7 @@ export {
3160
3251
  ProcessInboundDispatchUseCase,
3161
3252
  PurgeExpiredDocumentsUseCase,
3162
3253
  ReceiveWebhookUseCase,
3254
+ RedactInboundLocationsUseCase,
3163
3255
  ReleaseConversationUseCase,
3164
3256
  SaveFlowGraphUseCase,
3165
3257
  SendMessageUseCase,