@adatechnology/meta-whatsapp-module 0.7.0 → 0.8.1

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.d.cts CHANGED
@@ -1499,6 +1499,13 @@ interface SaveTranscriptionParams {
1499
1499
  language?: string | null;
1500
1500
  engine?: string | null;
1501
1501
  }
1502
+ interface InboundLocationScopeParams {
1503
+ companyId: string;
1504
+ receivedBefore: Date;
1505
+ }
1506
+ interface RedactInboundLocationsRepositoryParams extends InboundLocationScopeParams {
1507
+ batchSize: number;
1508
+ }
1502
1509
  declare class MessageRepository {
1503
1510
  private readonly db;
1504
1511
  constructor(db: MetaWhatsAppDatabase);
@@ -1522,6 +1529,25 @@ declare class MessageRepository {
1522
1529
  * é diferença de driver, e mock nenhum a reproduz.
1523
1530
  */
1524
1531
  updateMessageStatus(params: UpdateMessageStatusParams): Promise<MessageRow | undefined>;
1532
+ /**
1533
+ * Linhas de entrada com `payload.location` que a redação alcança, mais as localizações com
1534
+ * `payload` escalar string (gravação antiga do `bun-sql` com drizzle 0.x), nas quais `payload ?
1535
+ * 'location'` dá falso e que, por isso, a redação não toca.
1536
+ */
1537
+ countInboundLocations(params: InboundLocationScopeParams): Promise<{
1538
+ counted: number;
1539
+ unreachable: number;
1540
+ }>;
1541
+ /**
1542
+ * Redige UMA passada: tira `location` de `payload` (NULL quando não sobra chave) e põe o rótulo
1543
+ * neutro em `content` das linhas de tipo `location`. Sem `ORDER BY`: o índice por empresa não serve
1544
+ * à ordenação e a passada não precisa dela. `FOR UPDATE SKIP LOCKED` evita brigar com o webhook; o
1545
+ * `company_id` é repetido fora da subconsulta. Nunca devolve nem registra os ids das linhas.
1546
+ */
1547
+ redactInboundLocations(params: RedactInboundLocationsRepositoryParams): Promise<{
1548
+ redacted: number;
1549
+ }>;
1550
+ private hasRedactableLocation;
1525
1551
  /**
1526
1552
  * Grava a transcrição endereçando pelo id da Meta, para quem só tem esse.
1527
1553
  *
@@ -1945,6 +1971,45 @@ declare class PurgeExpiredDocumentsUseCase {
1945
1971
  execute(params: PurgeExpiredDocumentsParams): Promise<PurgeExpiredDocumentsResult>;
1946
1972
  }
1947
1973
 
1974
+ /**
1975
+ * Copyright (c) 2026 Ada Technology. MIT License.
1976
+ */
1977
+
1978
+ type CountInboundLocationsParams = {
1979
+ readonly companyId: string;
1980
+ /** Só entra o que chegou antes deste instante; o que veio depois já nasceu redigido. */
1981
+ readonly receivedBefore: Date;
1982
+ };
1983
+ type CountInboundLocationsResult = {
1984
+ /** Linhas que a redação alcança. */
1985
+ readonly counted: number;
1986
+ /** Localizações com `payload` escalar string (gravação antiga do driver): a redação não as toca. */
1987
+ readonly unreachable: number;
1988
+ };
1989
+ type RedactInboundLocationsParams = CountInboundLocationsParams & {
1990
+ /** Teto de linhas por passada (padrão 500). Quem chama repete até `redacted` zerar. */
1991
+ readonly batchSize?: number;
1992
+ };
1993
+ type RedactInboundLocationsResult = {
1994
+ readonly redacted: number;
1995
+ };
1996
+ /** Quantas localizações gravadas a redação alcançaria, sem escrever nada. */
1997
+ declare class CountInboundLocationsUseCase {
1998
+ private readonly messageRepository;
1999
+ constructor(messageRepository: MessageRepository);
2000
+ execute(params: CountInboundLocationsParams): Promise<CountInboundLocationsResult>;
2001
+ }
2002
+ /**
2003
+ * Tira `payload.location` e o rótulo das mensagens de entrada já gravadas — o legado de quem ligou
2004
+ * `features.redactInboundLocation` depois de a coordenada ter entrado. UMA passada por chamada:
2005
+ * o host faz o laço, e cada passada é uma transação curta.
2006
+ */
2007
+ declare class RedactInboundLocationsUseCase {
2008
+ private readonly messageRepository;
2009
+ constructor(messageRepository: MessageRepository);
2010
+ execute(params: RedactInboundLocationsParams): Promise<RedactInboundLocationsResult>;
2011
+ }
2012
+
1948
2013
  type ExportConversationParams = {
1949
2014
  companyId: string;
1950
2015
  whatsappNumber: string;
@@ -2174,6 +2239,8 @@ declare function confirmWebhookDelivery(params: {
2174
2239
  * A segunda metade rodava dentro da requisição do webhook. Um deploy no meio de uma conversa
2175
2240
  * matava a chamada em voo, e o cliente ficava sem resposta sem que nada registrasse a perda. Com
2176
2241
  * uma fila no host, derrubar o processo vira atraso: o job espera e é retomado.
2242
+ *
2243
+ * Guia de implementação: `docs/webhook-durability.md`.
2177
2244
  */
2178
2245
 
2179
2246
  type InboundMediaDescriptor = {
@@ -2282,6 +2349,8 @@ declare class ReceiveWebhookUseCase {
2282
2349
  * Configurá-la é o que faz a conversa sobreviver a um deploy no meio do atendimento.
2283
2350
  */
2284
2351
  inboundQueue?: InboundDispatchQueueInterface;
2352
+ /** Não grava `location` no transcript; ver `MetaWhatsAppModuleFeatures.redactInboundLocation`. */
2353
+ redactInboundLocation?: boolean;
2285
2354
  });
2286
2355
  private readonly dispatcher;
2287
2356
  execute(input: ReceiveWebhookParams): Promise<ReceiveWebhookResult>;
@@ -2526,6 +2595,18 @@ interface MetaWhatsAppModuleFeatures {
2526
2595
  * ignorado em vez de produzir um canal que falha na primeira nota de voz.
2527
2596
  */
2528
2597
  previewMedia?: boolean;
2598
+ /**
2599
+ * Não grava a coordenada no transcript: `payload.location` não é copiado e `content` vira
2600
+ * `INBOUND_LOCATION_CONTENT`, sem nome nem endereço. `type` continua `'location'`. O gancho
2601
+ * `onMessageReceived` segue recebendo a mensagem crua inteira — é por ele que o host usa o ponto.
2602
+ *
2603
+ * **Desligado por omissão, e a decisão é consciente.** A coordenada é dado pessoal (a casa do
2604
+ * cliente), mas outros hosts a leem do transcript; quem não tem finalidade para ela liga a opção.
2605
+ *
2606
+ * Ressalva: com `inboundQueue` o job carrega a mensagem CRUA. A opção cobre o transcript, não a
2607
+ * fila do host. Linhas já gravadas se redigem com `conversations.redactInboundLocations`.
2608
+ */
2609
+ redactInboundLocation?: boolean;
2529
2610
  }
2530
2611
  /**
2531
2612
  * Transcrição de áudio. Ausente = desligada, e as colunas ficam nulas ("não avaliado").
@@ -2587,6 +2668,8 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2587
2668
  listCompanyDocuments: ListCompanyDocumentsUseCase;
2588
2669
  delete: DeleteConversationUseCase;
2589
2670
  purgeExpiredDocuments: PurgeExpiredDocumentsUseCase;
2671
+ countInboundLocations: CountInboundLocationsUseCase;
2672
+ redactInboundLocations: RedactInboundLocationsUseCase;
2590
2673
  export: ExportConversationUseCase;
2591
2674
  transcribeAudio: TranscribeAudioUseCase | undefined;
2592
2675
  repository: SessionRepository;
@@ -2723,6 +2806,12 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2723
2806
  }>;
2724
2807
  }
2725
2808
 
2809
+ /**
2810
+ * Copyright (c) 2026 Ada Technology. MIT License.
2811
+ */
2812
+ /** Texto do transcript quando a coordenada não é guardada (ingestão e redação do legado). */
2813
+ declare const INBOUND_LOCATION_CONTENT = "\uD83D\uDCCD Localiza\u00E7\u00E3o";
2814
+
2726
2815
  declare const META_WHATSAPP_MIGRATIONS_TABLE = "meta_whatsapp_migrations";
2727
2816
  declare function metaWhatsAppMigrationsFolder(): string;
2728
2817
  type RunMetaWhatsAppMigrationsParams = {
@@ -2888,4 +2977,4 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
2888
2977
  }): Promise<void>;
2889
2978
  }
2890
2979
 
2891
- export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
2980
+ export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, INBOUND_LOCATION_CONTENT, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
package/dist/index.d.ts CHANGED
@@ -1499,6 +1499,13 @@ interface SaveTranscriptionParams {
1499
1499
  language?: string | null;
1500
1500
  engine?: string | null;
1501
1501
  }
1502
+ interface InboundLocationScopeParams {
1503
+ companyId: string;
1504
+ receivedBefore: Date;
1505
+ }
1506
+ interface RedactInboundLocationsRepositoryParams extends InboundLocationScopeParams {
1507
+ batchSize: number;
1508
+ }
1502
1509
  declare class MessageRepository {
1503
1510
  private readonly db;
1504
1511
  constructor(db: MetaWhatsAppDatabase);
@@ -1522,6 +1529,25 @@ declare class MessageRepository {
1522
1529
  * é diferença de driver, e mock nenhum a reproduz.
1523
1530
  */
1524
1531
  updateMessageStatus(params: UpdateMessageStatusParams): Promise<MessageRow | undefined>;
1532
+ /**
1533
+ * Linhas de entrada com `payload.location` que a redação alcança, mais as localizações com
1534
+ * `payload` escalar string (gravação antiga do `bun-sql` com drizzle 0.x), nas quais `payload ?
1535
+ * 'location'` dá falso e que, por isso, a redação não toca.
1536
+ */
1537
+ countInboundLocations(params: InboundLocationScopeParams): Promise<{
1538
+ counted: number;
1539
+ unreachable: number;
1540
+ }>;
1541
+ /**
1542
+ * Redige UMA passada: tira `location` de `payload` (NULL quando não sobra chave) e põe o rótulo
1543
+ * neutro em `content` das linhas de tipo `location`. Sem `ORDER BY`: o índice por empresa não serve
1544
+ * à ordenação e a passada não precisa dela. `FOR UPDATE SKIP LOCKED` evita brigar com o webhook; o
1545
+ * `company_id` é repetido fora da subconsulta. Nunca devolve nem registra os ids das linhas.
1546
+ */
1547
+ redactInboundLocations(params: RedactInboundLocationsRepositoryParams): Promise<{
1548
+ redacted: number;
1549
+ }>;
1550
+ private hasRedactableLocation;
1525
1551
  /**
1526
1552
  * Grava a transcrição endereçando pelo id da Meta, para quem só tem esse.
1527
1553
  *
@@ -1945,6 +1971,45 @@ declare class PurgeExpiredDocumentsUseCase {
1945
1971
  execute(params: PurgeExpiredDocumentsParams): Promise<PurgeExpiredDocumentsResult>;
1946
1972
  }
1947
1973
 
1974
+ /**
1975
+ * Copyright (c) 2026 Ada Technology. MIT License.
1976
+ */
1977
+
1978
+ type CountInboundLocationsParams = {
1979
+ readonly companyId: string;
1980
+ /** Só entra o que chegou antes deste instante; o que veio depois já nasceu redigido. */
1981
+ readonly receivedBefore: Date;
1982
+ };
1983
+ type CountInboundLocationsResult = {
1984
+ /** Linhas que a redação alcança. */
1985
+ readonly counted: number;
1986
+ /** Localizações com `payload` escalar string (gravação antiga do driver): a redação não as toca. */
1987
+ readonly unreachable: number;
1988
+ };
1989
+ type RedactInboundLocationsParams = CountInboundLocationsParams & {
1990
+ /** Teto de linhas por passada (padrão 500). Quem chama repete até `redacted` zerar. */
1991
+ readonly batchSize?: number;
1992
+ };
1993
+ type RedactInboundLocationsResult = {
1994
+ readonly redacted: number;
1995
+ };
1996
+ /** Quantas localizações gravadas a redação alcançaria, sem escrever nada. */
1997
+ declare class CountInboundLocationsUseCase {
1998
+ private readonly messageRepository;
1999
+ constructor(messageRepository: MessageRepository);
2000
+ execute(params: CountInboundLocationsParams): Promise<CountInboundLocationsResult>;
2001
+ }
2002
+ /**
2003
+ * Tira `payload.location` e o rótulo das mensagens de entrada já gravadas — o legado de quem ligou
2004
+ * `features.redactInboundLocation` depois de a coordenada ter entrado. UMA passada por chamada:
2005
+ * o host faz o laço, e cada passada é uma transação curta.
2006
+ */
2007
+ declare class RedactInboundLocationsUseCase {
2008
+ private readonly messageRepository;
2009
+ constructor(messageRepository: MessageRepository);
2010
+ execute(params: RedactInboundLocationsParams): Promise<RedactInboundLocationsResult>;
2011
+ }
2012
+
1948
2013
  type ExportConversationParams = {
1949
2014
  companyId: string;
1950
2015
  whatsappNumber: string;
@@ -2174,6 +2239,8 @@ declare function confirmWebhookDelivery(params: {
2174
2239
  * A segunda metade rodava dentro da requisição do webhook. Um deploy no meio de uma conversa
2175
2240
  * matava a chamada em voo, e o cliente ficava sem resposta sem que nada registrasse a perda. Com
2176
2241
  * uma fila no host, derrubar o processo vira atraso: o job espera e é retomado.
2242
+ *
2243
+ * Guia de implementação: `docs/webhook-durability.md`.
2177
2244
  */
2178
2245
 
2179
2246
  type InboundMediaDescriptor = {
@@ -2282,6 +2349,8 @@ declare class ReceiveWebhookUseCase {
2282
2349
  * Configurá-la é o que faz a conversa sobreviver a um deploy no meio do atendimento.
2283
2350
  */
2284
2351
  inboundQueue?: InboundDispatchQueueInterface;
2352
+ /** Não grava `location` no transcript; ver `MetaWhatsAppModuleFeatures.redactInboundLocation`. */
2353
+ redactInboundLocation?: boolean;
2285
2354
  });
2286
2355
  private readonly dispatcher;
2287
2356
  execute(input: ReceiveWebhookParams): Promise<ReceiveWebhookResult>;
@@ -2526,6 +2595,18 @@ interface MetaWhatsAppModuleFeatures {
2526
2595
  * ignorado em vez de produzir um canal que falha na primeira nota de voz.
2527
2596
  */
2528
2597
  previewMedia?: boolean;
2598
+ /**
2599
+ * Não grava a coordenada no transcript: `payload.location` não é copiado e `content` vira
2600
+ * `INBOUND_LOCATION_CONTENT`, sem nome nem endereço. `type` continua `'location'`. O gancho
2601
+ * `onMessageReceived` segue recebendo a mensagem crua inteira — é por ele que o host usa o ponto.
2602
+ *
2603
+ * **Desligado por omissão, e a decisão é consciente.** A coordenada é dado pessoal (a casa do
2604
+ * cliente), mas outros hosts a leem do transcript; quem não tem finalidade para ela liga a opção.
2605
+ *
2606
+ * Ressalva: com `inboundQueue` o job carrega a mensagem CRUA. A opção cobre o transcript, não a
2607
+ * fila do host. Linhas já gravadas se redigem com `conversations.redactInboundLocations`.
2608
+ */
2609
+ redactInboundLocation?: boolean;
2529
2610
  }
2530
2611
  /**
2531
2612
  * Transcrição de áudio. Ausente = desligada, e as colunas ficam nulas ("não avaliado").
@@ -2587,6 +2668,8 @@ declare function createMetaWhatsAppModule(params: CreateMetaWhatsAppModuleParams
2587
2668
  listCompanyDocuments: ListCompanyDocumentsUseCase;
2588
2669
  delete: DeleteConversationUseCase;
2589
2670
  purgeExpiredDocuments: PurgeExpiredDocumentsUseCase;
2671
+ countInboundLocations: CountInboundLocationsUseCase;
2672
+ redactInboundLocations: RedactInboundLocationsUseCase;
2590
2673
  export: ExportConversationUseCase;
2591
2674
  transcribeAudio: TranscribeAudioUseCase | undefined;
2592
2675
  repository: SessionRepository;
@@ -2723,6 +2806,12 @@ declare class WhatsAppChannelAdapter implements ChannelAdapterInterface {
2723
2806
  }>;
2724
2807
  }
2725
2808
 
2809
+ /**
2810
+ * Copyright (c) 2026 Ada Technology. MIT License.
2811
+ */
2812
+ /** Texto do transcript quando a coordenada não é guardada (ingestão e redação do legado). */
2813
+ declare const INBOUND_LOCATION_CONTENT = "\uD83D\uDCCD Localiza\u00E7\u00E3o";
2814
+
2726
2815
  declare const META_WHATSAPP_MIGRATIONS_TABLE = "meta_whatsapp_migrations";
2727
2816
  declare function metaWhatsAppMigrationsFolder(): string;
2728
2817
  type RunMetaWhatsAppMigrationsParams = {
@@ -2888,4 +2977,4 @@ declare class FlowMediaIdRepository implements FlowMediaIdStore {
2888
2977
  }): Promise<void>;
2889
2978
  }
2890
2979
 
2891
- export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
2980
+ export { type AttachFlowMediaParams, type AudioTranscriber, type CompanyDocumentView, type CompanyDocumentsPage, type ConversationDocumentView, type ConversationDocumentsPage, type CountInboundLocationsParams, type CountInboundLocationsResult, CountInboundLocationsUseCase, type CreateFlowGraphParams, CreateFlowGraphUseCase, type CreateMetaWhatsAppModuleParams, type CreateSendMediaActionParams, type CreateSendProductListActionParams, DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS, type DeleteConversationParams, type DeleteConversationResult, DeleteConversationUseCase, DeleteFlowGraphUseCase, DocumentRepository, type DocumentRow, type DrizzleMigrateFunction, type ExportConversationParams, type ExportConversationResult, ExportConversationUseCase, FlowGraphCache, FlowGraphRepository, type FlowGraphRow, FlowInterpreter, type FlowMediaIdCache, FlowMediaIdRepository, type FlowMediaIdStore, type FlowMediaLocation, FlowMediaRepository, type FlowMediaRow, type FlowMediaTranscriptLogger, type FlowRunResult, type FlowStepInput, type FlowStepResult, GetFlowGraphUseCase, GetLiveFlowPositionsUseCase, INBOUND_LOCATION_CONTENT, type InboundDispatchJob, type InboundDispatchQueueInterface, InboundEffectsDispatcher, type InboundMediaDescriptor, type InboundMessageEffectsJob, type InboundStatusEffectsJob, type IngestInboundMediaParams, type IngestInboundMediaResult, IngestInboundMediaUseCase, type IngestTranscriptionOptions, type InsertMessageParams, InvalidFlowGraphError, type LinkDocumentParams, type ListCompanyDocumentsParams, ListCompanyDocumentsUseCase, type ListConversationDocumentsParams, ListConversationDocumentsUseCase, type ListConversationsFilters, type ListConversationsParams, ListConversationsUseCase, type ListDocumentsParams, type ListDocumentsResult, ListFlowGraphsUseCase, type ListMessagesParams, ListMessagesUseCase, type LogMessageParams, LogMessageUseCase, META_WHATSAPP_MIGRATIONS_TABLE, type MessageModerator, MessageRepository, type MessageRow, type MetaWhatsAppDatabase, type MetaWhatsAppModule, type MetaWhatsAppModuleConfig, type MetaWhatsAppModuleFeatures, type MetaWhatsAppModuleProviders, type MetaWhatsAppTranscriptionConfig, type NewDocumentRow, type NewFlowGraphRow, type NewFlowMediaRow, type NewMessageRow, type NewSessionRow, type NewSettingsRow, type NonceStoreInterface, OptimisticLockError, PRODUCT_LIST_LIMIT, type PreviewMediaSupport, ProcessInboundDispatchUseCase, type PurgeExpiredDocumentsParams, type PurgeExpiredDocumentsResult, PurgeExpiredDocumentsUseCase, type RealtimeRelay, type ReceiveWebhookParams, type ReceiveWebhookResult, ReceiveWebhookUseCase, type RedactInboundLocationsParams, type RedactInboundLocationsResult, RedactInboundLocationsUseCase, type ReleaseConversationParams, ReleaseConversationUseCase, type ListMessagesParams$1 as RepositoryListMessagesParams, type ResolveTranscriptionPolicyDependencies, type RunMetaWhatsAppMigrationsParams, type SaveFlowGraphParams, SaveFlowGraphUseCase, type SaveTranscriptionByWaMessageIdParams, type SaveTranscriptionParams, type SendMediaParams, SendMessageUseCase, type SendTemplateParams, type SendTextParams, SessionRepository, type SessionRow, SettingsRepository, type SettingsRow, SseHub, type SseListener, type StorePreviewMediaParams, type StorePreviewMediaResult, StorePreviewMediaUseCase, TRANSCRIPTION_MODE, TRANSCRIPTION_STATUS, type TakeoverConversationParams, TakeoverConversationUseCase, type TicketStoreInterface, type TranscribeAudioDependencies, type TranscribeAudioParams, type TranscribeAudioResult, TranscribeAudioUseCase, type TranscriptionPolicy, type TranscriptionPolicyDefaults, type TranscriptionPolicyResolver, type TranscriptionStatus, type UpdateFlowMediaParams, WhatsAppChannelAdapter, buildInboundJobId, claimWebhookDelivery, confirmWebhookDelivery, createMetaWhatsAppModule, createSendMediaAction, createSendProductListAction, createTranscriptionPolicyResolver, documents, extractMediaDescriptor, flowGraphs, flowMedia, isAudioMimeType, isRetriableTranscriptionError, isUnsupportedTranscriptionError, issueSseTicket, messages, metaWhatsAppMigrationsFolder, metaWhatsAppSchema, redeemSseTicket, resolveFailureStatus, runMetaWhatsAppMigrations, sessions, settings, toSessionContract, transcriptionRetryAfterSeconds, verifyWebhookChallenge, verifyWebhookSignature };
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,