@adatechnology/meta-whatsapp-module 0.11.0 → 0.13.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.js CHANGED
@@ -215,6 +215,14 @@ var flowGraphs = metaWhatsAppSchema.table("flow_graphs", {
215
215
  menuOptionLabel: varchar("menu_option_label", {
216
216
  length: 64
217
217
  }),
218
+ // 'seed' | 'edited' (FLOW_GRAPH_ORIGIN). Linha anterior ao campo vira 'edited': sem como saber se
219
+ // alguém mexeu, o reseed do produto não pode sobrescrevê-la.
220
+ origin: varchar("origin", {
221
+ length: 16
222
+ }).notNull().default("edited"),
223
+ seedVersion: varchar("seed_version", {
224
+ length: 64
225
+ }),
218
226
  createdAt: timestamp("created_at", {
219
227
  withTimezone: true
220
228
  }).notNull().defaultNow(),
@@ -272,6 +280,29 @@ var flowMedia = metaWhatsAppSchema.table("flow_media", {
272
280
  // receberia o documento repetido.
273
281
  uniqueIndex("idx_flow_media_node_upload").on(table.companyId, table.flowKey, table.nodeId, table.uploadId)
274
282
  ]);
283
+ var quickReplies = metaWhatsAppSchema.table("quick_replies", {
284
+ id: uuid("id").primaryKey().defaultRandom(),
285
+ companyId: uuid("company_id").notNull(),
286
+ title: varchar("title", {
287
+ length: 40
288
+ }).notNull(),
289
+ shortcut: varchar("shortcut", {
290
+ length: 20
291
+ }).notNull(),
292
+ body: varchar("body", {
293
+ length: 1e3
294
+ }).notNull(),
295
+ sortOrder: integer("sort_order").notNull().default(0),
296
+ createdAt: timestamp("created_at", {
297
+ withTimezone: true
298
+ }).notNull().defaultNow(),
299
+ updatedAt: timestamp("updated_at", {
300
+ withTimezone: true
301
+ }).notNull().defaultNow()
302
+ }, (table) => [
303
+ uniqueIndex("idx_quick_replies_company_shortcut").on(table.companyId, table.shortcut),
304
+ index("idx_quick_replies_company_order").on(table.companyId, table.sortOrder)
305
+ ]);
275
306
  var settings = metaWhatsAppSchema.table("settings", {
276
307
  companyId: uuid("company_id").primaryKey(),
277
308
  templateName: varchar("template_name", {
@@ -728,6 +759,7 @@ var MessageRepository = class {
728
759
  // src/repositories/FlowGraphRepository.ts
729
760
  import { and as and3, eq as eq3, isNotNull, sql as sql4 } from "drizzle-orm";
730
761
  import { flowGraphNodesSchema } from "@adatechnology/meta-whatsapp-contracts";
762
+ import { FLOW_GRAPH_ORIGIN } from "@adatechnology/meta-whatsapp-contracts";
731
763
  var InvalidFlowGraphError = class extends Error {
732
764
  static {
733
765
  __name(this, "InvalidFlowGraphError");
@@ -746,10 +778,18 @@ function toContractGraph(row) {
746
778
  label: row.label,
747
779
  startNodeId: row.startNodeId,
748
780
  version: row.version,
749
- nodes: parsed.data
781
+ nodes: parsed.data,
782
+ origin: toOrigin(row.origin),
783
+ ...row.seedVersion ? {
784
+ seedVersion: row.seedVersion
785
+ } : {}
750
786
  };
751
787
  }
752
788
  __name(toContractGraph, "toContractGraph");
789
+ function toOrigin(value) {
790
+ return value === FLOW_GRAPH_ORIGIN.SEED ? FLOW_GRAPH_ORIGIN.SEED : FLOW_GRAPH_ORIGIN.EDITED;
791
+ }
792
+ __name(toOrigin, "toOrigin");
753
793
  var OptimisticLockError = class extends Error {
754
794
  static {
755
795
  __name(this, "OptimisticLockError");
@@ -788,7 +828,11 @@ var FlowGraphRepository = class {
788
828
  nodeCount: Object.keys(row.nodes).length,
789
829
  showInMenu: row.showInMenu,
790
830
  menuOptionLabel: row.menuOptionLabel ?? void 0,
791
- updatedAt: row.updatedAt.toISOString()
831
+ updatedAt: row.updatedAt.toISOString(),
832
+ origin: toOrigin(row.origin),
833
+ ...row.seedVersion ? {
834
+ seedVersion: row.seedVersion
835
+ } : {}
792
836
  }));
793
837
  }
794
838
  // Valida antes de gravar: aceitar um grafo malformado e só reclamar na leitura empurraria a
@@ -806,7 +850,10 @@ var FlowGraphRepository = class {
806
850
  startNodeId: graph.startNodeId,
807
851
  nodes: graph.nodes,
808
852
  showInMenu: graph.showInMenu ?? false,
809
- menuOptionLabel: graph.menuOptionLabel
853
+ menuOptionLabel: graph.menuOptionLabel,
854
+ // Quem informa `seedVersion` é o produto semeando; criado pelo editor não traz e fica `edited`.
855
+ origin: graph.seedVersion ? FLOW_GRAPH_ORIGIN.SEED : FLOW_GRAPH_ORIGIN.EDITED,
856
+ seedVersion: graph.seedVersion ?? null
810
857
  }).returning();
811
858
  const createdGraph = toContractGraph(created);
812
859
  await this.cache?.invalidate(companyId, createdGraph.key);
@@ -820,6 +867,8 @@ var FlowGraphRepository = class {
820
867
  label: graph.label,
821
868
  startNodeId: graph.startNodeId,
822
869
  nodes: graph.nodes,
870
+ // Salvar é sempre edição humana, mesmo que o editor devolva `origin: 'seed'` do grafo que carregou.
871
+ origin: FLOW_GRAPH_ORIGIN.EDITED,
823
872
  version: expectedVersion + 1,
824
873
  updatedAt: /* @__PURE__ */ new Date()
825
874
  }).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, graph.key), eq3(flowGraphs.version, expectedVersion))).returning();
@@ -827,6 +876,38 @@ var FlowGraphRepository = class {
827
876
  await this.cache?.invalidate(companyId, graph.key);
828
877
  return toContractGraph(rows[0]);
829
878
  }
879
+ /**
880
+ * Atualiza um grafo semeado que ninguém editou. A condição `origin = 'seed'` vai no próprio UPDATE:
881
+ * se uma pessoa salvar pelo editor entre a leitura e a escrita, o grafo vira `edited` e este update
882
+ * não casa nenhuma linha — a edição nunca é sobrescrita. Idempotente por `seedVersion`.
883
+ */
884
+ async reseed(params) {
885
+ this.assertValidNodes(params.key, params.content.nodes);
886
+ const rows = await this.db.update(flowGraphs).set({
887
+ label: params.content.label,
888
+ startNodeId: params.content.startNodeId,
889
+ nodes: params.content.nodes,
890
+ seedVersion: params.seedVersion,
891
+ version: sql4`${flowGraphs.version} + 1`,
892
+ updatedAt: /* @__PURE__ */ new Date()
893
+ }).where(and3(eq3(flowGraphs.companyId, params.companyId), eq3(flowGraphs.key, params.key), eq3(flowGraphs.origin, FLOW_GRAPH_ORIGIN.SEED), sql4`${flowGraphs.seedVersion} is distinct from ${params.seedVersion}`)).returning();
894
+ if (rows.length > 0) {
895
+ await this.cache?.invalidate(params.companyId, params.key);
896
+ return {
897
+ status: "updated",
898
+ graph: toContractGraph(rows[0])
899
+ };
900
+ }
901
+ const [existing] = await this.db.select({
902
+ origin: flowGraphs.origin
903
+ }).from(flowGraphs).where(and3(eq3(flowGraphs.companyId, params.companyId), eq3(flowGraphs.key, params.key))).limit(1);
904
+ if (!existing) return {
905
+ status: "missing"
906
+ };
907
+ return {
908
+ status: existing.origin === FLOW_GRAPH_ORIGIN.SEED ? "current" : "edited"
909
+ };
910
+ }
830
911
  async delete(companyId, key) {
831
912
  await this.db.delete(flowGraphs).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, key)));
832
913
  await this.cache?.invalidate(companyId, key);
@@ -1815,6 +1896,169 @@ var DocumentRepository = class {
1815
1896
  }
1816
1897
  };
1817
1898
 
1899
+ // src/repositories/QuickReplyRepository.ts
1900
+ import { and as and5, asc as asc2, count as count3, eq as eq6, ilike as ilike2, max, ne, or as or2, sql as sql5 } from "drizzle-orm";
1901
+ import { QuickReplyLimitReachedError, QuickReplyNotFoundError, QuickReplyShortcutTakenError, QUICK_REPLY_LIMITS } from "@adatechnology/meta-whatsapp-contracts";
1902
+ var UNIQUE_VIOLATION_SQLSTATE = "23505";
1903
+ function hasUniqueViolationState(error) {
1904
+ const state = error;
1905
+ return state?.code === UNIQUE_VIOLATION_SQLSTATE || state?.errno === UNIQUE_VIOLATION_SQLSTATE;
1906
+ }
1907
+ __name(hasUniqueViolationState, "hasUniqueViolationState");
1908
+ function isUniqueViolation(error) {
1909
+ return hasUniqueViolationState(error) || hasUniqueViolationState(error?.cause);
1910
+ }
1911
+ __name(isUniqueViolation, "isUniqueViolation");
1912
+ function escapeLikePattern(text2) {
1913
+ return text2.replace(/[\\%_]/g, (character) => `\\${character}`);
1914
+ }
1915
+ __name(escapeLikePattern, "escapeLikePattern");
1916
+ var QuickReplyRepository = class {
1917
+ static {
1918
+ __name(this, "QuickReplyRepository");
1919
+ }
1920
+ db;
1921
+ constructor(db) {
1922
+ this.db = db;
1923
+ }
1924
+ async list(params) {
1925
+ const filters = [
1926
+ eq6(quickReplies.companyId, params.companyId)
1927
+ ];
1928
+ if (params.search) {
1929
+ const pattern = `%${escapeLikePattern(params.search)}%`;
1930
+ const matches = or2(ilike2(quickReplies.title, pattern), ilike2(quickReplies.shortcut, pattern), ilike2(quickReplies.body, pattern));
1931
+ if (matches) filters.push(matches);
1932
+ }
1933
+ return this.db.select().from(quickReplies).where(and5(...filters)).orderBy(asc2(quickReplies.sortOrder), asc2(quickReplies.title), asc2(quickReplies.id));
1934
+ }
1935
+ async get(companyId, id) {
1936
+ const [row] = await this.db.select().from(quickReplies).where(and5(eq6(quickReplies.companyId, companyId), eq6(quickReplies.id, id))).limit(1);
1937
+ return row;
1938
+ }
1939
+ async create(params) {
1940
+ const [totals] = await this.db.select({
1941
+ total: count3(),
1942
+ highestOrder: max(quickReplies.sortOrder)
1943
+ }).from(quickReplies).where(eq6(quickReplies.companyId, params.companyId));
1944
+ if ((totals?.total ?? 0) >= QUICK_REPLY_LIMITS.MAX_PER_COMPANY) {
1945
+ throw new QuickReplyLimitReachedError(QUICK_REPLY_LIMITS.MAX_PER_COMPANY);
1946
+ }
1947
+ try {
1948
+ const [row] = await this.db.insert(quickReplies).values({
1949
+ companyId: params.companyId,
1950
+ title: params.title,
1951
+ shortcut: params.shortcut,
1952
+ body: params.body,
1953
+ // Sem ordem explícita vai para o fim da lista.
1954
+ sortOrder: params.sortOrder ?? (totals?.highestOrder ?? -1) + 1
1955
+ }).returning();
1956
+ return row;
1957
+ } catch (error) {
1958
+ if (isUniqueViolation(error)) throw new QuickReplyShortcutTakenError(params.shortcut);
1959
+ throw error;
1960
+ }
1961
+ }
1962
+ async update(params) {
1963
+ const [taken] = await this.db.select({
1964
+ id: quickReplies.id
1965
+ }).from(quickReplies).where(and5(eq6(quickReplies.companyId, params.companyId), eq6(quickReplies.shortcut, params.shortcut), ne(quickReplies.id, params.id))).limit(1);
1966
+ if (taken) throw new QuickReplyShortcutTakenError(params.shortcut);
1967
+ try {
1968
+ const [row] = await this.db.update(quickReplies).set({
1969
+ title: params.title,
1970
+ shortcut: params.shortcut,
1971
+ body: params.body,
1972
+ ...params.sortOrder !== void 0 ? {
1973
+ sortOrder: params.sortOrder
1974
+ } : {},
1975
+ updatedAt: sql5`now()`
1976
+ }).where(and5(eq6(quickReplies.companyId, params.companyId), eq6(quickReplies.id, params.id))).returning();
1977
+ if (!row) throw new QuickReplyNotFoundError(params.id);
1978
+ return row;
1979
+ } catch (error) {
1980
+ if (isUniqueViolation(error)) throw new QuickReplyShortcutTakenError(params.shortcut);
1981
+ throw error;
1982
+ }
1983
+ }
1984
+ async delete(companyId, id) {
1985
+ const rows = await this.db.delete(quickReplies).where(and5(eq6(quickReplies.companyId, companyId), eq6(quickReplies.id, id))).returning({
1986
+ id: quickReplies.id
1987
+ });
1988
+ return rows.length > 0;
1989
+ }
1990
+ };
1991
+
1992
+ // src/use-cases/QuickReply.use-cases.ts
1993
+ import { QuickReplyNotFoundError as QuickReplyNotFoundError2 } from "@adatechnology/meta-whatsapp-contracts";
1994
+ function toQuickReplyView(row) {
1995
+ return {
1996
+ id: row.id,
1997
+ title: row.title,
1998
+ shortcut: row.shortcut,
1999
+ body: row.body,
2000
+ sortOrder: row.sortOrder,
2001
+ createdAt: row.createdAt.toISOString(),
2002
+ updatedAt: row.updatedAt.toISOString()
2003
+ };
2004
+ }
2005
+ __name(toQuickReplyView, "toQuickReplyView");
2006
+ var ListQuickRepliesUseCase = class {
2007
+ static {
2008
+ __name(this, "ListQuickRepliesUseCase");
2009
+ }
2010
+ repository;
2011
+ constructor(repository) {
2012
+ this.repository = repository;
2013
+ }
2014
+ async execute(params) {
2015
+ const rows = await this.repository.list({
2016
+ companyId: params.companyId,
2017
+ ...params.search ? {
2018
+ search: params.search
2019
+ } : {}
2020
+ });
2021
+ return rows.map(toQuickReplyView);
2022
+ }
2023
+ };
2024
+ var CreateQuickReplyUseCase = class {
2025
+ static {
2026
+ __name(this, "CreateQuickReplyUseCase");
2027
+ }
2028
+ repository;
2029
+ constructor(repository) {
2030
+ this.repository = repository;
2031
+ }
2032
+ async execute(params) {
2033
+ return toQuickReplyView(await this.repository.create(params));
2034
+ }
2035
+ };
2036
+ var UpdateQuickReplyUseCase = class {
2037
+ static {
2038
+ __name(this, "UpdateQuickReplyUseCase");
2039
+ }
2040
+ repository;
2041
+ constructor(repository) {
2042
+ this.repository = repository;
2043
+ }
2044
+ async execute(params) {
2045
+ return toQuickReplyView(await this.repository.update(params));
2046
+ }
2047
+ };
2048
+ var DeleteQuickReplyUseCase = class {
2049
+ static {
2050
+ __name(this, "DeleteQuickReplyUseCase");
2051
+ }
2052
+ repository;
2053
+ constructor(repository) {
2054
+ this.repository = repository;
2055
+ }
2056
+ async execute(params) {
2057
+ const wasDeleted = await this.repository.delete(params.companyId, params.id);
2058
+ if (!wasDeleted) throw new QuickReplyNotFoundError2(params.id);
2059
+ }
2060
+ };
2061
+
1818
2062
  // src/use-cases/ExportConversation.use-case.ts
1819
2063
  import { SessionNotFoundError as SessionNotFoundError5 } from "@adatechnology/meta-whatsapp-contracts";
1820
2064
  var ExportConversationUseCase = class {
@@ -1881,6 +2125,18 @@ var SaveFlowGraphUseCase = class {
1881
2125
  return this.flowGraphRepository.save(params.companyId, params.graph, params.expectedVersion);
1882
2126
  }
1883
2127
  };
2128
+ var ReseedFlowGraphUseCase = class {
2129
+ static {
2130
+ __name(this, "ReseedFlowGraphUseCase");
2131
+ }
2132
+ flowGraphRepository;
2133
+ constructor(flowGraphRepository) {
2134
+ this.flowGraphRepository = flowGraphRepository;
2135
+ }
2136
+ async execute(params) {
2137
+ return this.flowGraphRepository.reseed(params);
2138
+ }
2139
+ };
1884
2140
  var DeleteFlowGraphUseCase = class {
1885
2141
  static {
1886
2142
  __name(this, "DeleteFlowGraphUseCase");
@@ -2081,6 +2337,9 @@ import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@ada
2081
2337
  var DEFAULT_START_FLOW_KEY = "main";
2082
2338
  var DEFAULT_MAX_INVALID_ANSWERS = 2;
2083
2339
  var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
2340
+ var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
2341
+ var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
2342
+ var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
2084
2343
  var DEFAULT_FLOW_TEXT = {
2085
2344
  FALLBACK: "N\xE3o entendi. Pode responder de novo?",
2086
2345
  CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
@@ -2307,7 +2566,7 @@ var FlowQuestionRenderer = class {
2307
2566
  ...params.variables
2308
2567
  };
2309
2568
  const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2310
- const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2569
+ const listButtonLabel = this.interpolate(node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL, variables);
2311
2570
  if (node.type === "dynamic_choice") {
2312
2571
  const options = await this.loadDynamicOptions(params);
2313
2572
  const shown = options.map((option) => [
@@ -2461,6 +2720,47 @@ async function resolveFlowConfigText(params) {
2461
2720
  }
2462
2721
  __name(resolveFlowConfigText, "resolveFlowConfigText");
2463
2722
 
2723
+ // src/flows/sendWithRetry.ts
2724
+ import { WhatsAppConnectionError } from "@adatechnology/meta-graph-core";
2725
+ function isTransientSendError(error) {
2726
+ return error instanceof WhatsAppConnectionError;
2727
+ }
2728
+ __name(isTransientSendError, "isTransientSendError");
2729
+ var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
2730
+ var SendRetriesExhausted = class {
2731
+ static {
2732
+ __name(this, "SendRetriesExhausted");
2733
+ }
2734
+ error;
2735
+ attempts;
2736
+ isTransient;
2737
+ constructor(error, attempts, isTransient) {
2738
+ this.error = error;
2739
+ this.attempts = attempts;
2740
+ this.isTransient = isTransient;
2741
+ }
2742
+ };
2743
+ async function sendWithRetry(send, config = {}) {
2744
+ const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
2745
+ const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
2746
+ const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
2747
+ const shouldRetry = config.shouldRetry ?? isTransientSendError;
2748
+ const sleep = config.sleep ?? sleepFor;
2749
+ for (let attempt = 1; ; attempt++) {
2750
+ try {
2751
+ await send();
2752
+ return {
2753
+ attempts: attempt
2754
+ };
2755
+ } catch (error) {
2756
+ const isTransient = shouldRetry(error);
2757
+ if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
2758
+ await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
2759
+ }
2760
+ }
2761
+ }
2762
+ __name(sendWithRetry, "sendWithRetry");
2763
+
2464
2764
  // src/flows/FlowRunner.ts
2465
2765
  function contactVariables(profileName) {
2466
2766
  if (!profileName) return {};
@@ -2490,6 +2790,8 @@ var FlowRunner = class {
2490
2790
  // Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
2491
2791
  // enxerga o nome do contato sem que ele precise ir para o contexto gravado.
2492
2792
  turnVariables = /* @__PURE__ */ new WeakMap();
2793
+ // Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
2794
+ sendFailures = /* @__PURE__ */ new WeakMap();
2493
2795
  constructor(dependencies) {
2494
2796
  this.dependencies = dependencies;
2495
2797
  this.renderer = new FlowQuestionRenderer(dependencies.config);
@@ -2984,6 +3286,10 @@ var FlowRunner = class {
2984
3286
  body
2985
3287
  });
2986
3288
  }
3289
+ /**
3290
+ * Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
3291
+ * Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
3292
+ */
2987
3293
  async send(turn, message) {
2988
3294
  const common = {
2989
3295
  companyId: turn.companyId,
@@ -2991,14 +3297,29 @@ var FlowRunner = class {
2991
3297
  sender: "bot",
2992
3298
  startState: this.dependencies.startState
2993
3299
  };
2994
- if (message.kind === "text") await this.dependencies.sendMessage.sendText({
2995
- ...common,
2996
- body: message.body
2997
- });
2998
- else await this.dependencies.sendMessage.sendInteractive({
2999
- ...common,
3000
- interactive: message.interactive
3001
- });
3300
+ const deliver = /* @__PURE__ */ __name(async () => {
3301
+ if (message.kind === "text") await this.dependencies.sendMessage.sendText({
3302
+ ...common,
3303
+ body: message.body
3304
+ });
3305
+ else await this.dependencies.sendMessage.sendInteractive({
3306
+ ...common,
3307
+ interactive: message.interactive
3308
+ });
3309
+ }, "deliver");
3310
+ try {
3311
+ await sendWithRetry(deliver, this.dependencies.config.sendRetry);
3312
+ } catch (failure) {
3313
+ if (!(failure instanceof SendRetriesExhausted)) throw failure;
3314
+ if (typeof failure.error === "object" && failure.error !== null) {
3315
+ this.sendFailures.set(failure.error, {
3316
+ attempts: failure.attempts,
3317
+ messageKind: message.kind,
3318
+ isTransient: failure.isTransient
3319
+ });
3320
+ }
3321
+ throw failure.error;
3322
+ }
3002
3323
  }
3003
3324
  save(turn, progress) {
3004
3325
  const runtime = runtimeOf(progress.context);
@@ -3026,12 +3347,16 @@ var FlowRunner = class {
3026
3347
  * ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
3027
3348
  */
3028
3349
  async report(turn, flowKey, nodeId, stage, error) {
3350
+ const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
3029
3351
  const details = {
3030
3352
  companyId: turn.companyId,
3031
3353
  whatsappNumber: turn.session.whatsappNumber,
3032
3354
  flowKey,
3033
3355
  nodeId,
3034
- stage
3356
+ stage,
3357
+ ...send ? {
3358
+ send
3359
+ } : {}
3035
3360
  };
3036
3361
  try {
3037
3362
  await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
@@ -3147,7 +3472,7 @@ var FlowHandoff = class {
3147
3472
  };
3148
3473
 
3149
3474
  // src/flows/flowTurnLock.ts
3150
- import { sql as sql5 } from "drizzle-orm";
3475
+ import { sql as sql6 } from "drizzle-orm";
3151
3476
  function lockName(key) {
3152
3477
  return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
3153
3478
  }
@@ -3162,7 +3487,7 @@ var PostgresAdvisoryFlowTurnLock = class {
3162
3487
  }
3163
3488
  withLock(key, work) {
3164
3489
  return this.db.transaction(async (transaction) => {
3165
- await transaction.execute(sql5`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3490
+ await transaction.execute(sql6`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3166
3491
  return work();
3167
3492
  });
3168
3493
  }
@@ -3350,7 +3675,7 @@ async function listAvailableProducts(params) {
3350
3675
  __name(listAvailableProducts, "listAvailableProducts");
3351
3676
 
3352
3677
  // src/repositories/FlowMediaRepository.ts
3353
- import { and as and5, asc as asc2, eq as eq6, sql as sql6 } from "drizzle-orm";
3678
+ import { and as and6, asc as asc3, eq as eq7, sql as sql7 } from "drizzle-orm";
3354
3679
  var FlowMediaRepository = class {
3355
3680
  static {
3356
3681
  __name(this, "FlowMediaRepository");
@@ -3360,18 +3685,18 @@ var FlowMediaRepository = class {
3360
3685
  this.db = db;
3361
3686
  }
3362
3687
  locationFilter(location) {
3363
- return and5(eq6(flowMedia.companyId, location.companyId), eq6(flowMedia.flowKey, location.flowKey), eq6(flowMedia.nodeId, location.nodeId));
3688
+ return and6(eq7(flowMedia.companyId, location.companyId), eq7(flowMedia.flowKey, location.flowKey), eq7(flowMedia.nodeId, location.nodeId));
3364
3689
  }
3365
3690
  // O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
3366
3691
  // é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
3367
3692
  // justamente o material que alguém desligou.
3368
3693
  async listActive(location) {
3369
- return this.db.select().from(flowMedia).where(and5(this.locationFilter(location), eq6(flowMedia.active, true))).orderBy(asc2(flowMedia.sortOrder), asc2(flowMedia.createdAt));
3694
+ return this.db.select().from(flowMedia).where(and6(this.locationFilter(location), eq7(flowMedia.active, true))).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
3370
3695
  }
3371
3696
  // Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
3372
3697
  // poder ser religado.
3373
3698
  async listAll(location) {
3374
- return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(asc2(flowMedia.sortOrder), asc2(flowMedia.createdAt));
3699
+ return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
3375
3700
  }
3376
3701
  /**
3377
3702
  * Anexa um arquivo já existente no storage ao nó.
@@ -3402,7 +3727,7 @@ var FlowMediaRepository = class {
3402
3727
  caption: params.caption ?? null,
3403
3728
  sortOrder: params.sortOrder ?? 0,
3404
3729
  active: true,
3405
- updatedAt: sql6`now()`
3730
+ updatedAt: sql7`now()`
3406
3731
  }
3407
3732
  }).returning();
3408
3733
  return row;
@@ -3418,8 +3743,8 @@ var FlowMediaRepository = class {
3418
3743
  ...params.active !== void 0 ? {
3419
3744
  active: params.active
3420
3745
  } : {},
3421
- updatedAt: sql6`now()`
3422
- }).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id))).returning();
3746
+ updatedAt: sql7`now()`
3747
+ }).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id))).returning();
3423
3748
  return row;
3424
3749
  }
3425
3750
  /**
@@ -3428,17 +3753,17 @@ var FlowMediaRepository = class {
3428
3753
  * host, que é dono da biblioteca de arquivos.
3429
3754
  */
3430
3755
  async detach(params) {
3431
- await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id)));
3756
+ await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id)));
3432
3757
  }
3433
3758
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
3434
3759
  async detachRemovedNodes(params) {
3435
- const condition = params.existingNodeIds.length === 0 ? void 0 : sql6`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3436
- await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.flowKey, params.flowKey), condition));
3760
+ const condition = params.existingNodeIds.length === 0 ? void 0 : sql7`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3761
+ await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.flowKey, params.flowKey), condition));
3437
3762
  }
3438
3763
  };
3439
3764
 
3440
3765
  // src/repositories/FlowMediaIdRepository.ts
3441
- import { eq as eq7, sql as sql7 } from "drizzle-orm";
3766
+ import { eq as eq8, sql as sql8 } from "drizzle-orm";
3442
3767
  var FlowMediaIdRepository = class {
3443
3768
  static {
3444
3769
  __name(this, "FlowMediaIdRepository");
@@ -3450,7 +3775,7 @@ var FlowMediaIdRepository = class {
3450
3775
  async get(params) {
3451
3776
  const rows = await this.db.select({
3452
3777
  ids: flowMedia.metaMediaIds
3453
- }).from(flowMedia).where(eq7(flowMedia.id, params.flowMediaId)).limit(1);
3778
+ }).from(flowMedia).where(eq8(flowMedia.id, params.flowMediaId)).limit(1);
3454
3779
  return rows[0]?.ids?.[params.senderKey];
3455
3780
  }
3456
3781
  /**
@@ -3462,14 +3787,14 @@ var FlowMediaIdRepository = class {
3462
3787
  */
3463
3788
  async set(params) {
3464
3789
  await this.db.update(flowMedia).set({
3465
- metaMediaIds: sql7`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3466
- }).where(eq7(flowMedia.id, params.flowMediaId));
3790
+ metaMediaIds: sql8`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3791
+ }).where(eq8(flowMedia.id, params.flowMediaId));
3467
3792
  }
3468
3793
  /** Remove só a chave deste número — o id do outro número continua válido. */
3469
3794
  async clear(params) {
3470
3795
  await this.db.update(flowMedia).set({
3471
- metaMediaIds: sql7`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3472
- }).where(eq7(flowMedia.id, params.flowMediaId));
3796
+ metaMediaIds: sql8`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3797
+ }).where(eq8(flowMedia.id, params.flowMediaId));
3473
3798
  }
3474
3799
  };
3475
3800
 
@@ -3650,7 +3975,7 @@ async function confirmWebhookDelivery(params) {
3650
3975
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
3651
3976
 
3652
3977
  // src/channel/IngestInboundMedia.use-case.ts
3653
- import { eq as eq8, and as and6 } from "drizzle-orm";
3978
+ import { eq as eq9, and as and7 } from "drizzle-orm";
3654
3979
 
3655
3980
  // src/use-cases/TranscribeAudio.use-case.ts
3656
3981
  import { AudioNotIngestedError, MessageNotAudioError, TranscriptionDisabledError } from "@adatechnology/meta-whatsapp-contracts";
@@ -3822,7 +4147,7 @@ var IngestInboundMediaUseCase = class {
3822
4147
  this.transcription = transcription;
3823
4148
  }
3824
4149
  async execute(params) {
3825
- const [message] = await this.db.select().from(messages).where(and6(eq8(messages.companyId, params.companyId), eq8(messages.id, params.messageId))).limit(1);
4150
+ const [message] = await this.db.select().from(messages).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId))).limit(1);
3826
4151
  if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
3827
4152
  const payload = message.payload ?? {};
3828
4153
  if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
@@ -3853,7 +4178,7 @@ var IngestInboundMediaUseCase = class {
3853
4178
  };
3854
4179
  await this.db.update(messages).set({
3855
4180
  payload: updatedPayload
3856
- }).where(and6(eq8(messages.companyId, params.companyId), eq8(messages.id, params.messageId)));
4181
+ }).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId)));
3857
4182
  await this.documentRepository?.link({
3858
4183
  companyId: params.companyId,
3859
4184
  sessionId: message.sessionId,
@@ -4302,6 +4627,7 @@ function createMetaWhatsAppModule(params) {
4302
4627
  const flowGraphCache = flowGraphCacheFeature && providers.cache ? new FlowGraphCache(providers.cache, typeof flowGraphCacheFeature === "object" ? flowGraphCacheFeature.ttlSeconds ?? DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS : DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS) : void 0;
4303
4628
  const flowGraphRepository = new FlowGraphRepository(db, flowGraphCache);
4304
4629
  const documentRepository = new DocumentRepository(db);
4630
+ const quickReplyRepository = new QuickReplyRepository(db);
4305
4631
  const flowMediaRepository = new FlowMediaRepository(db);
4306
4632
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
4307
4633
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
@@ -4459,6 +4785,18 @@ function createMetaWhatsAppModule(params) {
4459
4785
  } : void 0,
4460
4786
  settings: settingsRepository,
4461
4787
  /**
4788
+ * Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
4789
+ * `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
4790
+ * casos de uso daqui.
4791
+ */
4792
+ quickReplies: {
4793
+ list: new ListQuickRepliesUseCase(quickReplyRepository),
4794
+ create: new CreateQuickReplyUseCase(quickReplyRepository),
4795
+ update: new UpdateQuickReplyUseCase(quickReplyRepository),
4796
+ delete: new DeleteQuickReplyUseCase(quickReplyRepository),
4797
+ repository: quickReplyRepository
4798
+ },
4799
+ /**
4462
4800
  * `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
4463
4801
  * ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
4464
4802
  */
@@ -4511,6 +4849,7 @@ function createMetaWhatsAppModule(params) {
4511
4849
  list: new ListFlowGraphsUseCase(flowGraphRepository),
4512
4850
  create: new CreateFlowGraphUseCase(flowGraphRepository),
4513
4851
  save: new SaveFlowGraphUseCase(flowGraphRepository),
4852
+ reseed: new ReseedFlowGraphUseCase(flowGraphRepository),
4514
4853
  delete: new DeleteFlowGraphUseCase(flowGraphRepository),
4515
4854
  livePositions: new GetLiveFlowPositionsUseCase(flowGraphRepository),
4516
4855
  repository: flowGraphRepository,
@@ -4628,17 +4967,148 @@ async function redeemSseTicket(store, ticket) {
4628
4967
  return JSON.parse(raw);
4629
4968
  }
4630
4969
  __name(redeemSseTicket, "redeemSseTicket");
4970
+
4971
+ // src/http/quickReplyRoutes.ts
4972
+ import { QuickReplyNotFoundError as QuickReplyNotFoundError3, MetaWhatsAppError, META_WHATSAPP_ERROR_CODES, listWhatsAppQuickRepliesQuerySchema, whatsAppQuickReplyInputSchema } from "@adatechnology/meta-whatsapp-contracts";
4973
+ import { HTTP_METHOD, ROUTE_SCOPE } from "@adatechnology/module-http";
4974
+
4975
+ // src/http/quickReplyScope.constant.ts
4976
+ var QUICK_REPLY_SCOPE = {
4977
+ WRITE: "quick-replies:write"
4978
+ };
4979
+ var DEFAULT_QUICK_REPLY_WRITE_SCOPES = [
4980
+ QUICK_REPLY_SCOPE.WRITE
4981
+ ];
4982
+
4983
+ // src/http/quickReplyRoutes.ts
4984
+ function requireCompany(context) {
4985
+ if (!context.auth?.companyId) {
4986
+ throw new MetaWhatsAppError("Rota exige contexto autenticado.", 401, META_WHATSAPP_ERROR_CODES.CONFIG_MISSING);
4987
+ }
4988
+ return context.auth.companyId;
4989
+ }
4990
+ __name(requireCompany, "requireCompany");
4991
+ function requireId(context) {
4992
+ const id = context.params.id;
4993
+ if (!id) throw new QuickReplyNotFoundError3("");
4994
+ return id;
4995
+ }
4996
+ __name(requireId, "requireId");
4997
+ function createMetaWhatsAppQuickReplyRoutes(params) {
4998
+ const { list, create, update, delete: remove } = params.module.quickReplies;
4999
+ const write = {
5000
+ scope: ROUTE_SCOPE.ADMIN,
5001
+ requiredScopes: params.scopes?.write ?? DEFAULT_QUICK_REPLY_WRITE_SCOPES
5002
+ };
5003
+ const read = {
5004
+ scope: ROUTE_SCOPE.USER,
5005
+ ...params.scopes?.read?.length ? {
5006
+ requiredScopes: params.scopes.read
5007
+ } : {}
5008
+ };
5009
+ const routes = [
5010
+ {
5011
+ ...read,
5012
+ method: HTTP_METHOD.GET,
5013
+ path: "/quick-replies",
5014
+ querySchema: listWhatsAppQuickRepliesQuerySchema,
5015
+ operationId: "listWhatsAppQuickReplies",
5016
+ summary: "Lista as respostas r\xE1pidas da empresa, na ordem de exibi\xE7\xE3o",
5017
+ async handler(context) {
5018
+ const query = context.query;
5019
+ const data = await list.execute({
5020
+ companyId: requireCompany(context),
5021
+ ...query
5022
+ });
5023
+ return {
5024
+ kind: "json",
5025
+ status: 200,
5026
+ body: {
5027
+ data
5028
+ }
5029
+ };
5030
+ }
5031
+ },
5032
+ {
5033
+ ...write,
5034
+ method: HTTP_METHOD.POST,
5035
+ path: "/quick-replies",
5036
+ bodySchema: whatsAppQuickReplyInputSchema,
5037
+ operationId: "createWhatsAppQuickReply",
5038
+ summary: "Cria uma resposta r\xE1pida (atalho \xFAnico por empresa)",
5039
+ async handler(context) {
5040
+ const input = context.body;
5041
+ const data = await create.execute({
5042
+ ...input,
5043
+ companyId: requireCompany(context)
5044
+ });
5045
+ return {
5046
+ kind: "json",
5047
+ status: 201,
5048
+ body: {
5049
+ data
5050
+ }
5051
+ };
5052
+ }
5053
+ },
5054
+ {
5055
+ ...write,
5056
+ method: HTTP_METHOD.PUT,
5057
+ path: "/quick-replies/:id",
5058
+ bodySchema: whatsAppQuickReplyInputSchema,
5059
+ operationId: "updateWhatsAppQuickReply",
5060
+ summary: "Substitui t\xEDtulo, atalho e texto de uma resposta r\xE1pida",
5061
+ async handler(context) {
5062
+ const input = context.body;
5063
+ const data = await update.execute({
5064
+ ...input,
5065
+ companyId: requireCompany(context),
5066
+ id: requireId(context)
5067
+ });
5068
+ return {
5069
+ kind: "json",
5070
+ status: 200,
5071
+ body: {
5072
+ data
5073
+ }
5074
+ };
5075
+ }
5076
+ },
5077
+ {
5078
+ ...write,
5079
+ method: HTTP_METHOD.DELETE,
5080
+ path: "/quick-replies/:id",
5081
+ operationId: "deleteWhatsAppQuickReply",
5082
+ summary: "Apaga uma resposta r\xE1pida",
5083
+ async handler(context) {
5084
+ await remove.execute({
5085
+ companyId: requireCompany(context),
5086
+ id: requireId(context)
5087
+ });
5088
+ return {
5089
+ kind: "empty",
5090
+ status: 204
5091
+ };
5092
+ }
5093
+ }
5094
+ ];
5095
+ return routes;
5096
+ }
5097
+ __name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes");
4631
5098
  export {
4632
5099
  CountInboundLocationsUseCase,
4633
5100
  CreateFlowGraphUseCase,
5101
+ CreateQuickReplyUseCase,
4634
5102
  DEFAULT_FALLBACK_LIST_LABEL,
4635
5103
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4636
5104
  DEFAULT_FLOW_TEXT,
4637
5105
  DEFAULT_MAX_INVALID_ANSWERS,
5106
+ DEFAULT_QUICK_REPLY_WRITE_SCOPES,
4638
5107
  DEFAULT_START_FLOW_KEY,
4639
5108
  DYNAMIC_CHOICE_MORE_ID,
4640
5109
  DeleteConversationUseCase,
4641
5110
  DeleteFlowGraphUseCase,
5111
+ DeleteQuickReplyUseCase,
4642
5112
  DocumentRepository,
4643
5113
  ExportConversationUseCase,
4644
5114
  FLOW_RUNTIME_CONTEXT_KEY,
@@ -4661,6 +5131,7 @@ export {
4661
5131
  ListConversationsUseCase,
4662
5132
  ListFlowGraphsUseCase,
4663
5133
  ListMessagesUseCase,
5134
+ ListQuickRepliesUseCase,
4664
5135
  LogMessageUseCase,
4665
5136
  META_WHATSAPP_MIGRATIONS_TABLE,
4666
5137
  MessageRepository,
@@ -4670,10 +5141,13 @@ export {
4670
5141
  PostgresAdvisoryFlowTurnLock,
4671
5142
  ProcessInboundDispatchUseCase,
4672
5143
  PurgeExpiredDocumentsUseCase,
5144
+ QUICK_REPLY_SCOPE,
5145
+ QuickReplyRepository,
4673
5146
  ReceiveWebhookUseCase,
4674
5147
  RedactInboundLocationsUseCase,
4675
5148
  ReleaseConversationUseCase,
4676
5149
  RequestHumanConversationUseCase,
5150
+ ReseedFlowGraphUseCase,
4677
5151
  SaveFlowGraphUseCase,
4678
5152
  SendMessageUseCase,
4679
5153
  SessionRepository,
@@ -4684,6 +5158,7 @@ export {
4684
5158
  TRANSCRIPTION_STATUS,
4685
5159
  TakeoverConversationUseCase,
4686
5160
  TranscribeAudioUseCase,
5161
+ UpdateQuickReplyUseCase,
4687
5162
  WEBHOOK_CLAIM_TTL_SECONDS,
4688
5163
  WEBHOOK_NONCE_TTL_SECONDS,
4689
5164
  WhatsAppChannelAdapter,
@@ -4692,6 +5167,7 @@ export {
4692
5167
  claimWebhookDelivery,
4693
5168
  confirmWebhookDelivery,
4694
5169
  createMetaWhatsAppModule,
5170
+ createMetaWhatsAppQuickReplyRoutes,
4695
5171
  createSendMediaAction,
4696
5172
  createSendProductListAction,
4697
5173
  createTranscriptionPolicyResolver,
@@ -4702,11 +5178,13 @@ export {
4702
5178
  isAudioMimeType,
4703
5179
  isChoiceNode,
4704
5180
  isRetriableTranscriptionError,
5181
+ isTransientSendError,
4705
5182
  isUnsupportedTranscriptionError,
4706
5183
  issueSseTicket,
4707
5184
  messages,
4708
5185
  metaWhatsAppMigrationsFolder,
4709
5186
  metaWhatsAppSchema,
5187
+ quickReplies,
4710
5188
  readFlowInbound,
4711
5189
  redeemSseTicket,
4712
5190
  resolveFailureStatus,
@@ -4718,6 +5196,7 @@ export {
4718
5196
  sessions,
4719
5197
  settings,
4720
5198
  toPreviewMediaId,
5199
+ toQuickReplyView,
4721
5200
  toSessionContract,
4722
5201
  transcriptionRetryAfterSeconds,
4723
5202
  verifyWebhookChallenge,