@adatechnology/meta-whatsapp-module 0.10.0 → 0.12.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", {
@@ -541,7 +572,7 @@ var SessionRepository = class {
541
572
  };
542
573
 
543
574
  // src/repositories/MessageRepository.ts
544
- import { and as and2, count, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
575
+ import { and as and2, count, desc as desc2, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
545
576
 
546
577
  // src/inboundLocation.constant.ts
547
578
  var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
@@ -720,13 +751,15 @@ var MessageRepository = class {
720
751
  eq2(messages.sessionId, params.sessionId)
721
752
  ];
722
753
  if (params.before) conditions.push(lt(messages.createdAt, new Date(params.before)));
723
- return this.db.select().from(messages).where(and2(...conditions)).orderBy(messages.createdAt).limit(params.limit ?? DEFAULT_LIMIT2);
754
+ const newestFirst = await this.db.select().from(messages).where(and2(...conditions)).orderBy(desc2(messages.createdAt), desc2(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
755
+ return newestFirst.reverse();
724
756
  }
725
757
  };
726
758
 
727
759
  // src/repositories/FlowGraphRepository.ts
728
760
  import { and as and3, eq as eq3, isNotNull, sql as sql4 } from "drizzle-orm";
729
761
  import { flowGraphNodesSchema } from "@adatechnology/meta-whatsapp-contracts";
762
+ import { FLOW_GRAPH_ORIGIN } from "@adatechnology/meta-whatsapp-contracts";
730
763
  var InvalidFlowGraphError = class extends Error {
731
764
  static {
732
765
  __name(this, "InvalidFlowGraphError");
@@ -745,10 +778,18 @@ function toContractGraph(row) {
745
778
  label: row.label,
746
779
  startNodeId: row.startNodeId,
747
780
  version: row.version,
748
- nodes: parsed.data
781
+ nodes: parsed.data,
782
+ origin: toOrigin(row.origin),
783
+ ...row.seedVersion ? {
784
+ seedVersion: row.seedVersion
785
+ } : {}
749
786
  };
750
787
  }
751
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");
752
793
  var OptimisticLockError = class extends Error {
753
794
  static {
754
795
  __name(this, "OptimisticLockError");
@@ -787,7 +828,11 @@ var FlowGraphRepository = class {
787
828
  nodeCount: Object.keys(row.nodes).length,
788
829
  showInMenu: row.showInMenu,
789
830
  menuOptionLabel: row.menuOptionLabel ?? void 0,
790
- updatedAt: row.updatedAt.toISOString()
831
+ updatedAt: row.updatedAt.toISOString(),
832
+ origin: toOrigin(row.origin),
833
+ ...row.seedVersion ? {
834
+ seedVersion: row.seedVersion
835
+ } : {}
791
836
  }));
792
837
  }
793
838
  // Valida antes de gravar: aceitar um grafo malformado e só reclamar na leitura empurraria a
@@ -805,7 +850,10 @@ var FlowGraphRepository = class {
805
850
  startNodeId: graph.startNodeId,
806
851
  nodes: graph.nodes,
807
852
  showInMenu: graph.showInMenu ?? false,
808
- 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
809
857
  }).returning();
810
858
  const createdGraph = toContractGraph(created);
811
859
  await this.cache?.invalidate(companyId, createdGraph.key);
@@ -819,6 +867,8 @@ var FlowGraphRepository = class {
819
867
  label: graph.label,
820
868
  startNodeId: graph.startNodeId,
821
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,
822
872
  version: expectedVersion + 1,
823
873
  updatedAt: /* @__PURE__ */ new Date()
824
874
  }).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, graph.key), eq3(flowGraphs.version, expectedVersion))).returning();
@@ -826,6 +876,38 @@ var FlowGraphRepository = class {
826
876
  await this.cache?.invalidate(companyId, graph.key);
827
877
  return toContractGraph(rows[0]);
828
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
+ }
829
911
  async delete(companyId, key) {
830
912
  await this.db.delete(flowGraphs).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, key)));
831
913
  await this.cache?.invalidate(companyId, key);
@@ -1003,6 +1085,7 @@ var LogMessageUseCase = class {
1003
1085
  await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
1004
1086
  }
1005
1087
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
1088
+ companyId: params.companyId,
1006
1089
  direction: params.direction,
1007
1090
  sender: params.sender
1008
1091
  });
@@ -1221,6 +1304,7 @@ var TakeoverConversationUseCase = class {
1221
1304
  async execute(params) {
1222
1305
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
1223
1306
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1307
+ companyId: params.companyId,
1224
1308
  mode: "human",
1225
1309
  assignedUserId: params.agentUserId
1226
1310
  });
@@ -1253,6 +1337,7 @@ var ReleaseConversationUseCase = class {
1253
1337
  async execute(params) {
1254
1338
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
1255
1339
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1340
+ companyId: params.companyId,
1256
1341
  mode: "bot",
1257
1342
  assignedUserId: null
1258
1343
  });
@@ -1399,6 +1484,7 @@ var RequestHumanConversationUseCase = class {
1399
1484
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1400
1485
  if (!session) throw new SessionNotFoundError(params.whatsappNumber);
1401
1486
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1487
+ companyId: params.companyId,
1402
1488
  humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1403
1489
  });
1404
1490
  this.realtime?.emit("global", "data-changed", {});
@@ -1663,7 +1749,7 @@ var RedactInboundLocationsUseCase = class {
1663
1749
  };
1664
1750
 
1665
1751
  // src/repositories/DocumentRepository.ts
1666
- import { and as and4, asc, count as count2, desc as desc2, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1752
+ import { and as and4, asc, count as count2, desc as desc3, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1667
1753
  var DEFAULT_LIMIT3 = 50;
1668
1754
  function companyDocumentSearch(search) {
1669
1755
  const term = search?.trim();
@@ -1718,7 +1804,7 @@ var DocumentRepository = class {
1718
1804
  const where = and4(...filters);
1719
1805
  const limit = params.limit ?? DEFAULT_LIMIT3;
1720
1806
  const page = params.page && params.page > 0 ? params.page : 1;
1721
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1807
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1722
1808
  const [rows, counted] = await Promise.all([
1723
1809
  this.db.select().from(documents).where(where).orderBy(orderBy).limit(limit).offset((page - 1) * limit),
1724
1810
  this.db.select({
@@ -1755,7 +1841,7 @@ var DocumentRepository = class {
1755
1841
  const where = and4(...filters);
1756
1842
  const limit = params.limit ?? DEFAULT_LIMIT3;
1757
1843
  const page = params.page && params.page > 0 ? params.page : 1;
1758
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1844
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1759
1845
  const [rows, counted] = await Promise.all([
1760
1846
  this.db.select({
1761
1847
  id: documents.id,
@@ -1810,6 +1896,169 @@ var DocumentRepository = class {
1810
1896
  }
1811
1897
  };
1812
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
+
1813
2062
  // src/use-cases/ExportConversation.use-case.ts
1814
2063
  import { SessionNotFoundError as SessionNotFoundError5 } from "@adatechnology/meta-whatsapp-contracts";
1815
2064
  var ExportConversationUseCase = class {
@@ -1876,6 +2125,18 @@ var SaveFlowGraphUseCase = class {
1876
2125
  return this.flowGraphRepository.save(params.companyId, params.graph, params.expectedVersion);
1877
2126
  }
1878
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
+ };
1879
2140
  var DeleteFlowGraphUseCase = class {
1880
2141
  static {
1881
2142
  __name(this, "DeleteFlowGraphUseCase");
@@ -2067,7 +2328,7 @@ var FlowInterpreter = class {
2067
2328
  };
2068
2329
 
2069
2330
  // src/flows/FlowRunner.ts
2070
- import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2, matchesFlowKeyword } from "@adatechnology/meta-whatsapp-contracts";
2331
+ import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2 } from "@adatechnology/meta-whatsapp-contracts";
2071
2332
 
2072
2333
  // src/flows/resolveFlowAnswer.ts
2073
2334
  import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@adatechnology/meta-whatsapp-contracts";
@@ -2105,7 +2366,7 @@ function matchOption(answer, options, isInteractiveReply) {
2105
2366
  }
2106
2367
  __name(matchOption, "matchOption");
2107
2368
  function resolveChoice(params, answer) {
2108
- const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
2369
+ const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
2109
2370
  if (optionId) return {
2110
2371
  kind: "answer",
2111
2372
  userAnswer: optionId
@@ -2302,7 +2563,7 @@ var FlowQuestionRenderer = class {
2302
2563
  ...params.variables
2303
2564
  };
2304
2565
  const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
2305
- const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
2566
+ const listButtonLabel = this.interpolate(node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL, variables);
2306
2567
  if (node.type === "dynamic_choice") {
2307
2568
  const options = await this.loadDynamicOptions(params);
2308
2569
  const shown = options.map((option) => [
@@ -2411,6 +2672,51 @@ function readFlowInbound(message) {
2411
2672
  }
2412
2673
  __name(readFlowInbound, "readFlowInbound");
2413
2674
 
2675
+ // src/flows/matchGlobalKeyword.ts
2676
+ import { normalizeFlowText } from "@adatechnology/meta-whatsapp-contracts";
2677
+ function matchGlobalKeyword(text2, entries) {
2678
+ const normalized = normalizeFlowText(text2);
2679
+ if (normalized.length === 0) return void 0;
2680
+ const padded = ` ${normalized} `;
2681
+ let best;
2682
+ for (const entry of entries) {
2683
+ const isWordMatch = entry.match === "word";
2684
+ for (const keyword of entry.keywords) {
2685
+ const normalizedKeyword = normalizeFlowText(keyword);
2686
+ if (normalizedKeyword.length === 0) continue;
2687
+ const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
2688
+ if (isMatch && (!best || normalizedKeyword.length > best.length)) {
2689
+ best = {
2690
+ length: normalizedKeyword.length,
2691
+ target: entry.target
2692
+ };
2693
+ }
2694
+ }
2695
+ }
2696
+ return best?.target;
2697
+ }
2698
+ __name(matchGlobalKeyword, "matchGlobalKeyword");
2699
+
2700
+ // src/flows/resolveFlowConfigText.ts
2701
+ async function resolveOne(text2, params) {
2702
+ if (typeof text2 !== "function") return text2;
2703
+ try {
2704
+ return await text2(params.context);
2705
+ } catch (error) {
2706
+ await params.onError?.(error);
2707
+ return void 0;
2708
+ }
2709
+ }
2710
+ __name(resolveOne, "resolveOne");
2711
+ async function resolveFlowConfigText(params) {
2712
+ for (const text2 of params.chain) {
2713
+ const resolved = await resolveOne(text2, params);
2714
+ if (resolved !== void 0) return resolved;
2715
+ }
2716
+ return void 0;
2717
+ }
2718
+ __name(resolveFlowConfigText, "resolveFlowConfigText");
2719
+
2414
2720
  // src/flows/FlowRunner.ts
2415
2721
  function contactVariables(profileName) {
2416
2722
  if (!profileName) return {};
@@ -2614,8 +2920,7 @@ var FlowRunner = class {
2614
2920
  return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2615
2921
  }
2616
2922
  globalKeywordTarget(answer) {
2617
- const keywords = this.dependencies.config.globalKeywords ?? [];
2618
- return keywords.find((entry) => matchesFlowKeyword(answer, entry.keywords))?.target;
2923
+ return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
2619
2924
  }
2620
2925
  keywordJumpAtStart(start, inbound) {
2621
2926
  if (inbound.kind === "unsupported") return void 0;
@@ -2660,8 +2965,13 @@ var FlowRunner = class {
2660
2965
  const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2661
2966
  const page = dynamic?.page ?? 0;
2662
2967
  if (inbound.kind === "unsupported") {
2663
- const text2 = this.dependencies.config.nonTextAnswerMessage ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER;
2664
- await this.say(turn, text2, context);
2968
+ const text2 = await this.configText(turn, node, {
2969
+ chain: [
2970
+ this.dependencies.config.nonTextAnswerMessage
2971
+ ],
2972
+ kind: "non-text-answer"
2973
+ });
2974
+ await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
2665
2975
  return this.awaitAnswer(turn, graph, node, context, page);
2666
2976
  }
2667
2977
  const decision = resolveFlowAnswer({
@@ -2672,6 +2982,9 @@ var FlowRunner = class {
2672
2982
  clock: this.clock(),
2673
2983
  ...dynamic ? {
2674
2984
  dynamicOptions: dynamic.options
2985
+ } : {},
2986
+ ...isChoiceNode(node) ? {
2987
+ options: this.renderedOptions(turn, node, context)
2675
2988
  } : {}
2676
2989
  });
2677
2990
  if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
@@ -2685,7 +2998,16 @@ var FlowRunner = class {
2685
2998
  enterInitialNode: false
2686
2999
  });
2687
3000
  }
2688
- if (decision.kind === "invalid") return this.handleInvalid(turn, graph, node, context, decision.rejection);
3001
+ if (decision.kind === "invalid") {
3002
+ return this.handleInvalid(turn, graph, node, context, {
3003
+ rejection: decision.rejection
3004
+ });
3005
+ }
3006
+ const hostRejection = await this.validateWithHost(turn, node, context, {
3007
+ answer: inbound.answer,
3008
+ value: decision.value
3009
+ });
3010
+ if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
2689
3011
  await this.runFrom(turn, {
2690
3012
  graph,
2691
3013
  nodeId: node.id,
@@ -2697,11 +3019,68 @@ var FlowRunner = class {
2697
3019
  enterInitialNode: false
2698
3020
  });
2699
3021
  }
3022
+ /** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
3023
+ renderedOptions(turn, node, context) {
3024
+ const variables = {
3025
+ ...context,
3026
+ ...turn.baseVariables
3027
+ };
3028
+ return (node.options ?? []).map(([id, title]) => [
3029
+ id,
3030
+ this.renderer.interpolate(title, variables)
3031
+ ]);
3032
+ }
3033
+ /**
3034
+ * Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
3035
+ * Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
3036
+ */
3037
+ async validateWithHost(turn, node, context, answer) {
3038
+ const validator = this.dependencies.config.validateAnswer;
3039
+ if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
3040
+ try {
3041
+ const result = await validator({
3042
+ companyId: turn.companyId,
3043
+ session: turn.session,
3044
+ node,
3045
+ answer: answer.answer.trim(),
3046
+ value: answer.value ?? answer.answer,
3047
+ context
3048
+ });
3049
+ if (!result || result.isValid) return void 0;
3050
+ return {
3051
+ rejection: "rejected-by-host",
3052
+ ...result.message ? {
3053
+ message: result.message
3054
+ } : {}
3055
+ };
3056
+ } catch (error) {
3057
+ await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
3058
+ return void 0;
3059
+ }
3060
+ }
3061
+ configText(turn, node, params) {
3062
+ return resolveFlowConfigText({
3063
+ chain: params.chain,
3064
+ context: {
3065
+ companyId: turn.companyId,
3066
+ whatsappNumber: turn.session.whatsappNumber,
3067
+ kind: params.kind,
3068
+ flowKey: turn.session.flowKey,
3069
+ ...node ? {
3070
+ nodeId: node.id
3071
+ } : {},
3072
+ ...params.rejection ? {
3073
+ rejection: params.rejection
3074
+ } : {}
3075
+ },
3076
+ onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
3077
+ });
3078
+ }
2700
3079
  followsDefaultWhenUnmatched(node) {
2701
3080
  if (!isChoiceNode(node)) return false;
2702
3081
  return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2703
3082
  }
2704
- async handleInvalid(turn, graph, node, context, rejection) {
3083
+ async handleInvalid(turn, graph, node, context, invalid) {
2705
3084
  const runtime = runtimeOf(context);
2706
3085
  const attempts = (runtime.invalidAnswers ?? 0) + 1;
2707
3086
  const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
@@ -2710,12 +3089,30 @@ var FlowRunner = class {
2710
3089
  ...runtime,
2711
3090
  invalidAnswers: attempts
2712
3091
  });
2713
- await this.say(turn, this.fallbackText(node, rejection), updated);
3092
+ await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
2714
3093
  await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2715
3094
  }
2716
- fallbackText(node, rejection) {
3095
+ /** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
3096
+ async fallbackText(turn, node, invalid) {
2717
3097
  const { config } = this.dependencies;
2718
- return node.fallbackMessage ?? (rejection ? config.rejectionMessages?.[rejection] : void 0) ?? config.defaultFallbackMessage ?? DEFAULT_FLOW_TEXT.FALLBACK;
3098
+ const fixed = invalid.message ?? node.fallbackMessage;
3099
+ if (fixed !== void 0) return fixed;
3100
+ const { rejection } = invalid;
3101
+ const byRejection = rejection ? await this.configText(turn, node, {
3102
+ chain: [
3103
+ config.rejectionMessages?.[rejection]
3104
+ ],
3105
+ kind: "rejection",
3106
+ rejection
3107
+ }) : void 0;
3108
+ if (byRejection !== void 0) return byRejection;
3109
+ const fallback = await this.configText(turn, node, {
3110
+ chain: [
3111
+ config.defaultFallbackMessage
3112
+ ],
3113
+ kind: "fallback"
3114
+ });
3115
+ return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
2719
3116
  }
2720
3117
  async handOff(turn, context) {
2721
3118
  const isWithinHours = await this.dependencies.handoff.request({
@@ -2923,10 +3320,10 @@ var FlowHandoff = class {
2923
3320
  whatsappNumber: params.whatsappNumber
2924
3321
  });
2925
3322
  } catch (error) {
2926
- await this.reportFailure(error, params);
3323
+ await this.reportFailure(error, params, "handoff");
2927
3324
  }
2928
3325
  const isWithinHours = await this.isWithinHours(params.companyId);
2929
- const template = this.messageFor(isWithinHours, params.node);
3326
+ const template = await this.messageFor(isWithinHours, params);
2930
3327
  await sendMessage.sendText({
2931
3328
  companyId: params.companyId,
2932
3329
  whatsappNumber: params.whatsappNumber,
@@ -2958,14 +3355,14 @@ var FlowHandoff = class {
2958
3355
  };
2959
3356
  };
2960
3357
  }
2961
- async reportFailure(error, params) {
3358
+ async reportFailure(error, params, stage) {
2962
3359
  try {
2963
3360
  await this.dependencies.hooks?.onFlowRunnerError?.(error, {
2964
3361
  companyId: params.companyId,
2965
3362
  whatsappNumber: params.whatsappNumber,
2966
3363
  flowKey: null,
2967
3364
  nodeId: params.node?.id ?? null,
2968
- stage: "handoff"
3365
+ stage
2969
3366
  });
2970
3367
  } catch {
2971
3368
  }
@@ -2975,16 +3372,38 @@ var FlowHandoff = class {
2975
3372
  const hours = typeof source === "function" ? await source(companyId) : source;
2976
3373
  return hours ? isWithinBusinessHours(hours, this.dependencies.now()) : true;
2977
3374
  }
2978
- messageFor(isWithinHours, node) {
3375
+ async messageFor(isWithinHours, params) {
2979
3376
  const { config } = this.dependencies;
2980
- const inHours = readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF;
2981
- if (isWithinHours) return inHours;
2982
- return readParam(node, "outOfHoursMessage") ?? config.outOfHoursMessage ?? readParam(node, "message") ?? config.message ?? DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS;
3377
+ const { node } = params;
3378
+ const chain = isWithinHours ? [
3379
+ readParam(node, "message"),
3380
+ config.message,
3381
+ DEFAULT_FLOW_TEXT.HANDOFF
3382
+ ] : [
3383
+ readParam(node, "outOfHoursMessage"),
3384
+ config.outOfHoursMessage,
3385
+ readParam(node, "message"),
3386
+ config.message,
3387
+ DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
3388
+ ];
3389
+ const text2 = await resolveFlowConfigText({
3390
+ chain,
3391
+ context: {
3392
+ companyId: params.companyId,
3393
+ whatsappNumber: params.whatsappNumber,
3394
+ kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
3395
+ ...node ? {
3396
+ nodeId: node.id
3397
+ } : {}
3398
+ },
3399
+ onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
3400
+ });
3401
+ return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
2983
3402
  }
2984
3403
  };
2985
3404
 
2986
3405
  // src/flows/flowTurnLock.ts
2987
- import { sql as sql5 } from "drizzle-orm";
3406
+ import { sql as sql6 } from "drizzle-orm";
2988
3407
  function lockName(key) {
2989
3408
  return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
2990
3409
  }
@@ -2999,7 +3418,7 @@ var PostgresAdvisoryFlowTurnLock = class {
2999
3418
  }
3000
3419
  withLock(key, work) {
3001
3420
  return this.db.transaction(async (transaction) => {
3002
- await transaction.execute(sql5`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3421
+ await transaction.execute(sql6`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
3003
3422
  return work();
3004
3423
  });
3005
3424
  }
@@ -3187,7 +3606,7 @@ async function listAvailableProducts(params) {
3187
3606
  __name(listAvailableProducts, "listAvailableProducts");
3188
3607
 
3189
3608
  // src/repositories/FlowMediaRepository.ts
3190
- import { and as and5, asc as asc2, eq as eq6, sql as sql6 } from "drizzle-orm";
3609
+ import { and as and6, asc as asc3, eq as eq7, sql as sql7 } from "drizzle-orm";
3191
3610
  var FlowMediaRepository = class {
3192
3611
  static {
3193
3612
  __name(this, "FlowMediaRepository");
@@ -3197,18 +3616,18 @@ var FlowMediaRepository = class {
3197
3616
  this.db = db;
3198
3617
  }
3199
3618
  locationFilter(location) {
3200
- return and5(eq6(flowMedia.companyId, location.companyId), eq6(flowMedia.flowKey, location.flowKey), eq6(flowMedia.nodeId, location.nodeId));
3619
+ return and6(eq7(flowMedia.companyId, location.companyId), eq7(flowMedia.flowKey, location.flowKey), eq7(flowMedia.nodeId, location.nodeId));
3201
3620
  }
3202
3621
  // O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
3203
3622
  // é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
3204
3623
  // justamente o material que alguém desligou.
3205
3624
  async listActive(location) {
3206
- return this.db.select().from(flowMedia).where(and5(this.locationFilter(location), eq6(flowMedia.active, true))).orderBy(asc2(flowMedia.sortOrder), asc2(flowMedia.createdAt));
3625
+ return this.db.select().from(flowMedia).where(and6(this.locationFilter(location), eq7(flowMedia.active, true))).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
3207
3626
  }
3208
3627
  // Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
3209
3628
  // poder ser religado.
3210
3629
  async listAll(location) {
3211
- return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(asc2(flowMedia.sortOrder), asc2(flowMedia.createdAt));
3630
+ return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
3212
3631
  }
3213
3632
  /**
3214
3633
  * Anexa um arquivo já existente no storage ao nó.
@@ -3239,7 +3658,7 @@ var FlowMediaRepository = class {
3239
3658
  caption: params.caption ?? null,
3240
3659
  sortOrder: params.sortOrder ?? 0,
3241
3660
  active: true,
3242
- updatedAt: sql6`now()`
3661
+ updatedAt: sql7`now()`
3243
3662
  }
3244
3663
  }).returning();
3245
3664
  return row;
@@ -3255,8 +3674,8 @@ var FlowMediaRepository = class {
3255
3674
  ...params.active !== void 0 ? {
3256
3675
  active: params.active
3257
3676
  } : {},
3258
- updatedAt: sql6`now()`
3259
- }).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id))).returning();
3677
+ updatedAt: sql7`now()`
3678
+ }).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id))).returning();
3260
3679
  return row;
3261
3680
  }
3262
3681
  /**
@@ -3265,17 +3684,17 @@ var FlowMediaRepository = class {
3265
3684
  * host, que é dono da biblioteca de arquivos.
3266
3685
  */
3267
3686
  async detach(params) {
3268
- await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.id, params.id)));
3687
+ await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id)));
3269
3688
  }
3270
3689
  // Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
3271
3690
  async detachRemovedNodes(params) {
3272
- const condition = params.existingNodeIds.length === 0 ? void 0 : sql6`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3273
- await this.db.delete(flowMedia).where(and5(eq6(flowMedia.companyId, params.companyId), eq6(flowMedia.flowKey, params.flowKey), condition));
3691
+ const condition = params.existingNodeIds.length === 0 ? void 0 : sql7`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
3692
+ await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.flowKey, params.flowKey), condition));
3274
3693
  }
3275
3694
  };
3276
3695
 
3277
3696
  // src/repositories/FlowMediaIdRepository.ts
3278
- import { eq as eq7, sql as sql7 } from "drizzle-orm";
3697
+ import { eq as eq8, sql as sql8 } from "drizzle-orm";
3279
3698
  var FlowMediaIdRepository = class {
3280
3699
  static {
3281
3700
  __name(this, "FlowMediaIdRepository");
@@ -3287,7 +3706,7 @@ var FlowMediaIdRepository = class {
3287
3706
  async get(params) {
3288
3707
  const rows = await this.db.select({
3289
3708
  ids: flowMedia.metaMediaIds
3290
- }).from(flowMedia).where(eq7(flowMedia.id, params.flowMediaId)).limit(1);
3709
+ }).from(flowMedia).where(eq8(flowMedia.id, params.flowMediaId)).limit(1);
3291
3710
  return rows[0]?.ids?.[params.senderKey];
3292
3711
  }
3293
3712
  /**
@@ -3299,14 +3718,14 @@ var FlowMediaIdRepository = class {
3299
3718
  */
3300
3719
  async set(params) {
3301
3720
  await this.db.update(flowMedia).set({
3302
- metaMediaIds: sql7`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3303
- }).where(eq7(flowMedia.id, params.flowMediaId));
3721
+ metaMediaIds: sql8`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
3722
+ }).where(eq8(flowMedia.id, params.flowMediaId));
3304
3723
  }
3305
3724
  /** Remove só a chave deste número — o id do outro número continua válido. */
3306
3725
  async clear(params) {
3307
3726
  await this.db.update(flowMedia).set({
3308
- metaMediaIds: sql7`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3309
- }).where(eq7(flowMedia.id, params.flowMediaId));
3727
+ metaMediaIds: sql8`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
3728
+ }).where(eq8(flowMedia.id, params.flowMediaId));
3310
3729
  }
3311
3730
  };
3312
3731
 
@@ -3487,7 +3906,7 @@ async function confirmWebhookDelivery(params) {
3487
3906
  __name(confirmWebhookDelivery, "confirmWebhookDelivery");
3488
3907
 
3489
3908
  // src/channel/IngestInboundMedia.use-case.ts
3490
- import { eq as eq8, and as and6 } from "drizzle-orm";
3909
+ import { eq as eq9, and as and7 } from "drizzle-orm";
3491
3910
 
3492
3911
  // src/use-cases/TranscribeAudio.use-case.ts
3493
3912
  import { AudioNotIngestedError, MessageNotAudioError, TranscriptionDisabledError } from "@adatechnology/meta-whatsapp-contracts";
@@ -3659,7 +4078,7 @@ var IngestInboundMediaUseCase = class {
3659
4078
  this.transcription = transcription;
3660
4079
  }
3661
4080
  async execute(params) {
3662
- const [message] = await this.db.select().from(messages).where(and6(eq8(messages.companyId, params.companyId), eq8(messages.id, params.messageId))).limit(1);
4081
+ const [message] = await this.db.select().from(messages).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId))).limit(1);
3663
4082
  if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
3664
4083
  const payload = message.payload ?? {};
3665
4084
  if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
@@ -3690,7 +4109,7 @@ var IngestInboundMediaUseCase = class {
3690
4109
  };
3691
4110
  await this.db.update(messages).set({
3692
4111
  payload: updatedPayload
3693
- }).where(and6(eq8(messages.companyId, params.companyId), eq8(messages.id, params.messageId)));
4112
+ }).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId)));
3694
4113
  await this.documentRepository?.link({
3695
4114
  companyId: params.companyId,
3696
4115
  sessionId: message.sessionId,
@@ -4037,6 +4456,7 @@ var ReceiveWebhookUseCase = class {
4037
4456
  });
4038
4457
  if (!updated) return;
4039
4458
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
4459
+ companyId,
4040
4460
  waMessageId: status.id,
4041
4461
  status: status.status
4042
4462
  });
@@ -4138,6 +4558,7 @@ function createMetaWhatsAppModule(params) {
4138
4558
  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;
4139
4559
  const flowGraphRepository = new FlowGraphRepository(db, flowGraphCache);
4140
4560
  const documentRepository = new DocumentRepository(db);
4561
+ const quickReplyRepository = new QuickReplyRepository(db);
4141
4562
  const flowMediaRepository = new FlowMediaRepository(db);
4142
4563
  const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
4143
4564
  const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
@@ -4295,6 +4716,18 @@ function createMetaWhatsAppModule(params) {
4295
4716
  } : void 0,
4296
4717
  settings: settingsRepository,
4297
4718
  /**
4719
+ * Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
4720
+ * `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
4721
+ * casos de uso daqui.
4722
+ */
4723
+ quickReplies: {
4724
+ list: new ListQuickRepliesUseCase(quickReplyRepository),
4725
+ create: new CreateQuickReplyUseCase(quickReplyRepository),
4726
+ update: new UpdateQuickReplyUseCase(quickReplyRepository),
4727
+ delete: new DeleteQuickReplyUseCase(quickReplyRepository),
4728
+ repository: quickReplyRepository
4729
+ },
4730
+ /**
4298
4731
  * `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
4299
4732
  * ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
4300
4733
  */
@@ -4347,6 +4780,7 @@ function createMetaWhatsAppModule(params) {
4347
4780
  list: new ListFlowGraphsUseCase(flowGraphRepository),
4348
4781
  create: new CreateFlowGraphUseCase(flowGraphRepository),
4349
4782
  save: new SaveFlowGraphUseCase(flowGraphRepository),
4783
+ reseed: new ReseedFlowGraphUseCase(flowGraphRepository),
4350
4784
  delete: new DeleteFlowGraphUseCase(flowGraphRepository),
4351
4785
  livePositions: new GetLiveFlowPositionsUseCase(flowGraphRepository),
4352
4786
  repository: flowGraphRepository,
@@ -4464,17 +4898,148 @@ async function redeemSseTicket(store, ticket) {
4464
4898
  return JSON.parse(raw);
4465
4899
  }
4466
4900
  __name(redeemSseTicket, "redeemSseTicket");
4901
+
4902
+ // src/http/quickReplyRoutes.ts
4903
+ import { QuickReplyNotFoundError as QuickReplyNotFoundError3, MetaWhatsAppError, META_WHATSAPP_ERROR_CODES, listWhatsAppQuickRepliesQuerySchema, whatsAppQuickReplyInputSchema } from "@adatechnology/meta-whatsapp-contracts";
4904
+ import { HTTP_METHOD, ROUTE_SCOPE } from "@adatechnology/module-http";
4905
+
4906
+ // src/http/quickReplyScope.constant.ts
4907
+ var QUICK_REPLY_SCOPE = {
4908
+ WRITE: "quick-replies:write"
4909
+ };
4910
+ var DEFAULT_QUICK_REPLY_WRITE_SCOPES = [
4911
+ QUICK_REPLY_SCOPE.WRITE
4912
+ ];
4913
+
4914
+ // src/http/quickReplyRoutes.ts
4915
+ function requireCompany(context) {
4916
+ if (!context.auth?.companyId) {
4917
+ throw new MetaWhatsAppError("Rota exige contexto autenticado.", 401, META_WHATSAPP_ERROR_CODES.CONFIG_MISSING);
4918
+ }
4919
+ return context.auth.companyId;
4920
+ }
4921
+ __name(requireCompany, "requireCompany");
4922
+ function requireId(context) {
4923
+ const id = context.params.id;
4924
+ if (!id) throw new QuickReplyNotFoundError3("");
4925
+ return id;
4926
+ }
4927
+ __name(requireId, "requireId");
4928
+ function createMetaWhatsAppQuickReplyRoutes(params) {
4929
+ const { list, create, update, delete: remove } = params.module.quickReplies;
4930
+ const write = {
4931
+ scope: ROUTE_SCOPE.ADMIN,
4932
+ requiredScopes: params.scopes?.write ?? DEFAULT_QUICK_REPLY_WRITE_SCOPES
4933
+ };
4934
+ const read = {
4935
+ scope: ROUTE_SCOPE.USER,
4936
+ ...params.scopes?.read?.length ? {
4937
+ requiredScopes: params.scopes.read
4938
+ } : {}
4939
+ };
4940
+ const routes = [
4941
+ {
4942
+ ...read,
4943
+ method: HTTP_METHOD.GET,
4944
+ path: "/quick-replies",
4945
+ querySchema: listWhatsAppQuickRepliesQuerySchema,
4946
+ operationId: "listWhatsAppQuickReplies",
4947
+ summary: "Lista as respostas r\xE1pidas da empresa, na ordem de exibi\xE7\xE3o",
4948
+ async handler(context) {
4949
+ const query = context.query;
4950
+ const data = await list.execute({
4951
+ companyId: requireCompany(context),
4952
+ ...query
4953
+ });
4954
+ return {
4955
+ kind: "json",
4956
+ status: 200,
4957
+ body: {
4958
+ data
4959
+ }
4960
+ };
4961
+ }
4962
+ },
4963
+ {
4964
+ ...write,
4965
+ method: HTTP_METHOD.POST,
4966
+ path: "/quick-replies",
4967
+ bodySchema: whatsAppQuickReplyInputSchema,
4968
+ operationId: "createWhatsAppQuickReply",
4969
+ summary: "Cria uma resposta r\xE1pida (atalho \xFAnico por empresa)",
4970
+ async handler(context) {
4971
+ const input = context.body;
4972
+ const data = await create.execute({
4973
+ ...input,
4974
+ companyId: requireCompany(context)
4975
+ });
4976
+ return {
4977
+ kind: "json",
4978
+ status: 201,
4979
+ body: {
4980
+ data
4981
+ }
4982
+ };
4983
+ }
4984
+ },
4985
+ {
4986
+ ...write,
4987
+ method: HTTP_METHOD.PUT,
4988
+ path: "/quick-replies/:id",
4989
+ bodySchema: whatsAppQuickReplyInputSchema,
4990
+ operationId: "updateWhatsAppQuickReply",
4991
+ summary: "Substitui t\xEDtulo, atalho e texto de uma resposta r\xE1pida",
4992
+ async handler(context) {
4993
+ const input = context.body;
4994
+ const data = await update.execute({
4995
+ ...input,
4996
+ companyId: requireCompany(context),
4997
+ id: requireId(context)
4998
+ });
4999
+ return {
5000
+ kind: "json",
5001
+ status: 200,
5002
+ body: {
5003
+ data
5004
+ }
5005
+ };
5006
+ }
5007
+ },
5008
+ {
5009
+ ...write,
5010
+ method: HTTP_METHOD.DELETE,
5011
+ path: "/quick-replies/:id",
5012
+ operationId: "deleteWhatsAppQuickReply",
5013
+ summary: "Apaga uma resposta r\xE1pida",
5014
+ async handler(context) {
5015
+ await remove.execute({
5016
+ companyId: requireCompany(context),
5017
+ id: requireId(context)
5018
+ });
5019
+ return {
5020
+ kind: "empty",
5021
+ status: 204
5022
+ };
5023
+ }
5024
+ }
5025
+ ];
5026
+ return routes;
5027
+ }
5028
+ __name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes");
4467
5029
  export {
4468
5030
  CountInboundLocationsUseCase,
4469
5031
  CreateFlowGraphUseCase,
5032
+ CreateQuickReplyUseCase,
4470
5033
  DEFAULT_FALLBACK_LIST_LABEL,
4471
5034
  DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
4472
5035
  DEFAULT_FLOW_TEXT,
4473
5036
  DEFAULT_MAX_INVALID_ANSWERS,
5037
+ DEFAULT_QUICK_REPLY_WRITE_SCOPES,
4474
5038
  DEFAULT_START_FLOW_KEY,
4475
5039
  DYNAMIC_CHOICE_MORE_ID,
4476
5040
  DeleteConversationUseCase,
4477
5041
  DeleteFlowGraphUseCase,
5042
+ DeleteQuickReplyUseCase,
4478
5043
  DocumentRepository,
4479
5044
  ExportConversationUseCase,
4480
5045
  FLOW_RUNTIME_CONTEXT_KEY,
@@ -4497,6 +5062,7 @@ export {
4497
5062
  ListConversationsUseCase,
4498
5063
  ListFlowGraphsUseCase,
4499
5064
  ListMessagesUseCase,
5065
+ ListQuickRepliesUseCase,
4500
5066
  LogMessageUseCase,
4501
5067
  META_WHATSAPP_MIGRATIONS_TABLE,
4502
5068
  MessageRepository,
@@ -4506,10 +5072,13 @@ export {
4506
5072
  PostgresAdvisoryFlowTurnLock,
4507
5073
  ProcessInboundDispatchUseCase,
4508
5074
  PurgeExpiredDocumentsUseCase,
5075
+ QUICK_REPLY_SCOPE,
5076
+ QuickReplyRepository,
4509
5077
  ReceiveWebhookUseCase,
4510
5078
  RedactInboundLocationsUseCase,
4511
5079
  ReleaseConversationUseCase,
4512
5080
  RequestHumanConversationUseCase,
5081
+ ReseedFlowGraphUseCase,
4513
5082
  SaveFlowGraphUseCase,
4514
5083
  SendMessageUseCase,
4515
5084
  SessionRepository,
@@ -4520,6 +5089,7 @@ export {
4520
5089
  TRANSCRIPTION_STATUS,
4521
5090
  TakeoverConversationUseCase,
4522
5091
  TranscribeAudioUseCase,
5092
+ UpdateQuickReplyUseCase,
4523
5093
  WEBHOOK_CLAIM_TTL_SECONDS,
4524
5094
  WEBHOOK_NONCE_TTL_SECONDS,
4525
5095
  WhatsAppChannelAdapter,
@@ -4528,6 +5098,7 @@ export {
4528
5098
  claimWebhookDelivery,
4529
5099
  confirmWebhookDelivery,
4530
5100
  createMetaWhatsAppModule,
5101
+ createMetaWhatsAppQuickReplyRoutes,
4531
5102
  createSendMediaAction,
4532
5103
  createSendProductListAction,
4533
5104
  createTranscriptionPolicyResolver,
@@ -4543,16 +5114,19 @@ export {
4543
5114
  messages,
4544
5115
  metaWhatsAppMigrationsFolder,
4545
5116
  metaWhatsAppSchema,
5117
+ quickReplies,
4546
5118
  readFlowInbound,
4547
5119
  redeemSseTicket,
4548
5120
  resolveFailureStatus,
4549
5121
  resolveFlowAnswer,
5122
+ resolveFlowConfigText,
4550
5123
  resolveFlowTimeZone,
4551
5124
  resolvePreviewUploadId,
4552
5125
  runMetaWhatsAppMigrations,
4553
5126
  sessions,
4554
5127
  settings,
4555
5128
  toPreviewMediaId,
5129
+ toQuickReplyView,
4556
5130
  toSessionContract,
4557
5131
  transcriptionRetryAfterSeconds,
4558
5132
  verifyWebhookChallenge,