@adatechnology/meta-whatsapp-module 0.10.0 → 0.11.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
@@ -541,7 +541,7 @@ var SessionRepository = class {
541
541
  };
542
542
 
543
543
  // src/repositories/MessageRepository.ts
544
- import { and as and2, count, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
544
+ import { and as and2, count, desc as desc2, eq as eq2, lt, sql as sql3 } from "drizzle-orm";
545
545
 
546
546
  // src/inboundLocation.constant.ts
547
547
  var INBOUND_LOCATION_CONTENT = "\u{1F4CD} Localiza\xE7\xE3o";
@@ -720,7 +720,8 @@ var MessageRepository = class {
720
720
  eq2(messages.sessionId, params.sessionId)
721
721
  ];
722
722
  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);
723
+ const newestFirst = await this.db.select().from(messages).where(and2(...conditions)).orderBy(desc2(messages.createdAt), desc2(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
724
+ return newestFirst.reverse();
724
725
  }
725
726
  };
726
727
 
@@ -1003,6 +1004,7 @@ var LogMessageUseCase = class {
1003
1004
  await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
1004
1005
  }
1005
1006
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
1007
+ companyId: params.companyId,
1006
1008
  direction: params.direction,
1007
1009
  sender: params.sender
1008
1010
  });
@@ -1221,6 +1223,7 @@ var TakeoverConversationUseCase = class {
1221
1223
  async execute(params) {
1222
1224
  await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
1223
1225
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1226
+ companyId: params.companyId,
1224
1227
  mode: "human",
1225
1228
  assignedUserId: params.agentUserId
1226
1229
  });
@@ -1253,6 +1256,7 @@ var ReleaseConversationUseCase = class {
1253
1256
  async execute(params) {
1254
1257
  await this.sessionRepository.release(params.companyId, params.whatsappNumber);
1255
1258
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
1259
+ companyId: params.companyId,
1256
1260
  mode: "bot",
1257
1261
  assignedUserId: null
1258
1262
  });
@@ -1399,6 +1403,7 @@ var RequestHumanConversationUseCase = class {
1399
1403
  const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
1400
1404
  if (!session) throw new SessionNotFoundError(params.whatsappNumber);
1401
1405
  this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
1406
+ companyId: params.companyId,
1402
1407
  humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
1403
1408
  });
1404
1409
  this.realtime?.emit("global", "data-changed", {});
@@ -1663,7 +1668,7 @@ var RedactInboundLocationsUseCase = class {
1663
1668
  };
1664
1669
 
1665
1670
  // 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";
1671
+ import { and as and4, asc, count as count2, desc as desc3, eq as eq5, ilike, inArray, lt as lt2, or } from "drizzle-orm";
1667
1672
  var DEFAULT_LIMIT3 = 50;
1668
1673
  function companyDocumentSearch(search) {
1669
1674
  const term = search?.trim();
@@ -1718,7 +1723,7 @@ var DocumentRepository = class {
1718
1723
  const where = and4(...filters);
1719
1724
  const limit = params.limit ?? DEFAULT_LIMIT3;
1720
1725
  const page = params.page && params.page > 0 ? params.page : 1;
1721
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1726
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1722
1727
  const [rows, counted] = await Promise.all([
1723
1728
  this.db.select().from(documents).where(where).orderBy(orderBy).limit(limit).offset((page - 1) * limit),
1724
1729
  this.db.select({
@@ -1755,7 +1760,7 @@ var DocumentRepository = class {
1755
1760
  const where = and4(...filters);
1756
1761
  const limit = params.limit ?? DEFAULT_LIMIT3;
1757
1762
  const page = params.page && params.page > 0 ? params.page : 1;
1758
- const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc2(documents.linkedAt);
1763
+ const orderBy = params.sortDirection === "asc" ? asc(documents.linkedAt) : desc3(documents.linkedAt);
1759
1764
  const [rows, counted] = await Promise.all([
1760
1765
  this.db.select({
1761
1766
  id: documents.id,
@@ -2067,7 +2072,7 @@ var FlowInterpreter = class {
2067
2072
  };
2068
2073
 
2069
2074
  // 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";
2075
+ import { ConfigMissingError, FLOW_DATE_LOCALE_PT_BR, FlowRunnerError as FlowRunnerError2, isCrossFlowTarget as isCrossFlowTarget2, crossFlowKey as crossFlowKey2 } from "@adatechnology/meta-whatsapp-contracts";
2071
2076
 
2072
2077
  // src/flows/resolveFlowAnswer.ts
2073
2078
  import { matchFlowChoice, matchFlowKeywordRoute, validateFlowAnswer } from "@adatechnology/meta-whatsapp-contracts";
@@ -2105,7 +2110,7 @@ function matchOption(answer, options, isInteractiveReply) {
2105
2110
  }
2106
2111
  __name(matchOption, "matchOption");
2107
2112
  function resolveChoice(params, answer) {
2108
- const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
2113
+ const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
2109
2114
  if (optionId) return {
2110
2115
  kind: "answer",
2111
2116
  userAnswer: optionId
@@ -2411,6 +2416,51 @@ function readFlowInbound(message) {
2411
2416
  }
2412
2417
  __name(readFlowInbound, "readFlowInbound");
2413
2418
 
2419
+ // src/flows/matchGlobalKeyword.ts
2420
+ import { normalizeFlowText } from "@adatechnology/meta-whatsapp-contracts";
2421
+ function matchGlobalKeyword(text2, entries) {
2422
+ const normalized = normalizeFlowText(text2);
2423
+ if (normalized.length === 0) return void 0;
2424
+ const padded = ` ${normalized} `;
2425
+ let best;
2426
+ for (const entry of entries) {
2427
+ const isWordMatch = entry.match === "word";
2428
+ for (const keyword of entry.keywords) {
2429
+ const normalizedKeyword = normalizeFlowText(keyword);
2430
+ if (normalizedKeyword.length === 0) continue;
2431
+ const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
2432
+ if (isMatch && (!best || normalizedKeyword.length > best.length)) {
2433
+ best = {
2434
+ length: normalizedKeyword.length,
2435
+ target: entry.target
2436
+ };
2437
+ }
2438
+ }
2439
+ }
2440
+ return best?.target;
2441
+ }
2442
+ __name(matchGlobalKeyword, "matchGlobalKeyword");
2443
+
2444
+ // src/flows/resolveFlowConfigText.ts
2445
+ async function resolveOne(text2, params) {
2446
+ if (typeof text2 !== "function") return text2;
2447
+ try {
2448
+ return await text2(params.context);
2449
+ } catch (error) {
2450
+ await params.onError?.(error);
2451
+ return void 0;
2452
+ }
2453
+ }
2454
+ __name(resolveOne, "resolveOne");
2455
+ async function resolveFlowConfigText(params) {
2456
+ for (const text2 of params.chain) {
2457
+ const resolved = await resolveOne(text2, params);
2458
+ if (resolved !== void 0) return resolved;
2459
+ }
2460
+ return void 0;
2461
+ }
2462
+ __name(resolveFlowConfigText, "resolveFlowConfigText");
2463
+
2414
2464
  // src/flows/FlowRunner.ts
2415
2465
  function contactVariables(profileName) {
2416
2466
  if (!profileName) return {};
@@ -2614,8 +2664,7 @@ var FlowRunner = class {
2614
2664
  return this.dependencies.flowGraphRepository.get(companyId, flowKey);
2615
2665
  }
2616
2666
  globalKeywordTarget(answer) {
2617
- const keywords = this.dependencies.config.globalKeywords ?? [];
2618
- return keywords.find((entry) => matchesFlowKeyword(answer, entry.keywords))?.target;
2667
+ return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
2619
2668
  }
2620
2669
  keywordJumpAtStart(start, inbound) {
2621
2670
  if (inbound.kind === "unsupported") return void 0;
@@ -2660,8 +2709,13 @@ var FlowRunner = class {
2660
2709
  const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
2661
2710
  const page = dynamic?.page ?? 0;
2662
2711
  if (inbound.kind === "unsupported") {
2663
- const text2 = this.dependencies.config.nonTextAnswerMessage ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER;
2664
- await this.say(turn, text2, context);
2712
+ const text2 = await this.configText(turn, node, {
2713
+ chain: [
2714
+ this.dependencies.config.nonTextAnswerMessage
2715
+ ],
2716
+ kind: "non-text-answer"
2717
+ });
2718
+ await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
2665
2719
  return this.awaitAnswer(turn, graph, node, context, page);
2666
2720
  }
2667
2721
  const decision = resolveFlowAnswer({
@@ -2672,6 +2726,9 @@ var FlowRunner = class {
2672
2726
  clock: this.clock(),
2673
2727
  ...dynamic ? {
2674
2728
  dynamicOptions: dynamic.options
2729
+ } : {},
2730
+ ...isChoiceNode(node) ? {
2731
+ options: this.renderedOptions(turn, node, context)
2675
2732
  } : {}
2676
2733
  });
2677
2734
  if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
@@ -2685,7 +2742,16 @@ var FlowRunner = class {
2685
2742
  enterInitialNode: false
2686
2743
  });
2687
2744
  }
2688
- if (decision.kind === "invalid") return this.handleInvalid(turn, graph, node, context, decision.rejection);
2745
+ if (decision.kind === "invalid") {
2746
+ return this.handleInvalid(turn, graph, node, context, {
2747
+ rejection: decision.rejection
2748
+ });
2749
+ }
2750
+ const hostRejection = await this.validateWithHost(turn, node, context, {
2751
+ answer: inbound.answer,
2752
+ value: decision.value
2753
+ });
2754
+ if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
2689
2755
  await this.runFrom(turn, {
2690
2756
  graph,
2691
2757
  nodeId: node.id,
@@ -2697,11 +2763,68 @@ var FlowRunner = class {
2697
2763
  enterInitialNode: false
2698
2764
  });
2699
2765
  }
2766
+ /** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
2767
+ renderedOptions(turn, node, context) {
2768
+ const variables = {
2769
+ ...context,
2770
+ ...turn.baseVariables
2771
+ };
2772
+ return (node.options ?? []).map(([id, title]) => [
2773
+ id,
2774
+ this.renderer.interpolate(title, variables)
2775
+ ]);
2776
+ }
2777
+ /**
2778
+ * Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
2779
+ * Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
2780
+ */
2781
+ async validateWithHost(turn, node, context, answer) {
2782
+ const validator = this.dependencies.config.validateAnswer;
2783
+ if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
2784
+ try {
2785
+ const result = await validator({
2786
+ companyId: turn.companyId,
2787
+ session: turn.session,
2788
+ node,
2789
+ answer: answer.answer.trim(),
2790
+ value: answer.value ?? answer.answer,
2791
+ context
2792
+ });
2793
+ if (!result || result.isValid) return void 0;
2794
+ return {
2795
+ rejection: "rejected-by-host",
2796
+ ...result.message ? {
2797
+ message: result.message
2798
+ } : {}
2799
+ };
2800
+ } catch (error) {
2801
+ await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
2802
+ return void 0;
2803
+ }
2804
+ }
2805
+ configText(turn, node, params) {
2806
+ return resolveFlowConfigText({
2807
+ chain: params.chain,
2808
+ context: {
2809
+ companyId: turn.companyId,
2810
+ whatsappNumber: turn.session.whatsappNumber,
2811
+ kind: params.kind,
2812
+ flowKey: turn.session.flowKey,
2813
+ ...node ? {
2814
+ nodeId: node.id
2815
+ } : {},
2816
+ ...params.rejection ? {
2817
+ rejection: params.rejection
2818
+ } : {}
2819
+ },
2820
+ onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
2821
+ });
2822
+ }
2700
2823
  followsDefaultWhenUnmatched(node) {
2701
2824
  if (!isChoiceNode(node)) return false;
2702
2825
  return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
2703
2826
  }
2704
- async handleInvalid(turn, graph, node, context, rejection) {
2827
+ async handleInvalid(turn, graph, node, context, invalid) {
2705
2828
  const runtime = runtimeOf(context);
2706
2829
  const attempts = (runtime.invalidAnswers ?? 0) + 1;
2707
2830
  const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
@@ -2710,12 +2833,30 @@ var FlowRunner = class {
2710
2833
  ...runtime,
2711
2834
  invalidAnswers: attempts
2712
2835
  });
2713
- await this.say(turn, this.fallbackText(node, rejection), updated);
2836
+ await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
2714
2837
  await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
2715
2838
  }
2716
- fallbackText(node, rejection) {
2839
+ /** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
2840
+ async fallbackText(turn, node, invalid) {
2717
2841
  const { config } = this.dependencies;
2718
- return node.fallbackMessage ?? (rejection ? config.rejectionMessages?.[rejection] : void 0) ?? config.defaultFallbackMessage ?? DEFAULT_FLOW_TEXT.FALLBACK;
2842
+ const fixed = invalid.message ?? node.fallbackMessage;
2843
+ if (fixed !== void 0) return fixed;
2844
+ const { rejection } = invalid;
2845
+ const byRejection = rejection ? await this.configText(turn, node, {
2846
+ chain: [
2847
+ config.rejectionMessages?.[rejection]
2848
+ ],
2849
+ kind: "rejection",
2850
+ rejection
2851
+ }) : void 0;
2852
+ if (byRejection !== void 0) return byRejection;
2853
+ const fallback = await this.configText(turn, node, {
2854
+ chain: [
2855
+ config.defaultFallbackMessage
2856
+ ],
2857
+ kind: "fallback"
2858
+ });
2859
+ return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
2719
2860
  }
2720
2861
  async handOff(turn, context) {
2721
2862
  const isWithinHours = await this.dependencies.handoff.request({
@@ -2923,10 +3064,10 @@ var FlowHandoff = class {
2923
3064
  whatsappNumber: params.whatsappNumber
2924
3065
  });
2925
3066
  } catch (error) {
2926
- await this.reportFailure(error, params);
3067
+ await this.reportFailure(error, params, "handoff");
2927
3068
  }
2928
3069
  const isWithinHours = await this.isWithinHours(params.companyId);
2929
- const template = this.messageFor(isWithinHours, params.node);
3070
+ const template = await this.messageFor(isWithinHours, params);
2930
3071
  await sendMessage.sendText({
2931
3072
  companyId: params.companyId,
2932
3073
  whatsappNumber: params.whatsappNumber,
@@ -2958,14 +3099,14 @@ var FlowHandoff = class {
2958
3099
  };
2959
3100
  };
2960
3101
  }
2961
- async reportFailure(error, params) {
3102
+ async reportFailure(error, params, stage) {
2962
3103
  try {
2963
3104
  await this.dependencies.hooks?.onFlowRunnerError?.(error, {
2964
3105
  companyId: params.companyId,
2965
3106
  whatsappNumber: params.whatsappNumber,
2966
3107
  flowKey: null,
2967
3108
  nodeId: params.node?.id ?? null,
2968
- stage: "handoff"
3109
+ stage
2969
3110
  });
2970
3111
  } catch {
2971
3112
  }
@@ -2975,11 +3116,33 @@ var FlowHandoff = class {
2975
3116
  const hours = typeof source === "function" ? await source(companyId) : source;
2976
3117
  return hours ? isWithinBusinessHours(hours, this.dependencies.now()) : true;
2977
3118
  }
2978
- messageFor(isWithinHours, node) {
3119
+ async messageFor(isWithinHours, params) {
2979
3120
  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;
3121
+ const { node } = params;
3122
+ const chain = isWithinHours ? [
3123
+ readParam(node, "message"),
3124
+ config.message,
3125
+ DEFAULT_FLOW_TEXT.HANDOFF
3126
+ ] : [
3127
+ readParam(node, "outOfHoursMessage"),
3128
+ config.outOfHoursMessage,
3129
+ readParam(node, "message"),
3130
+ config.message,
3131
+ DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
3132
+ ];
3133
+ const text2 = await resolveFlowConfigText({
3134
+ chain,
3135
+ context: {
3136
+ companyId: params.companyId,
3137
+ whatsappNumber: params.whatsappNumber,
3138
+ kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
3139
+ ...node ? {
3140
+ nodeId: node.id
3141
+ } : {}
3142
+ },
3143
+ onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
3144
+ });
3145
+ return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
2983
3146
  }
2984
3147
  };
2985
3148
 
@@ -4037,6 +4200,7 @@ var ReceiveWebhookUseCase = class {
4037
4200
  });
4038
4201
  if (!updated) return;
4039
4202
  this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
4203
+ companyId,
4040
4204
  waMessageId: status.id,
4041
4205
  status: status.status
4042
4206
  });
@@ -4547,6 +4711,7 @@ export {
4547
4711
  redeemSseTicket,
4548
4712
  resolveFailureStatus,
4549
4713
  resolveFlowAnswer,
4714
+ resolveFlowConfigText,
4550
4715
  resolveFlowTimeZone,
4551
4716
  resolvePreviewUploadId,
4552
4717
  runMetaWhatsAppMigrations,