@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/README.md +122 -4
- package/dist/index.cjs +704 -118
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +411 -9
- package/dist/index.d.ts +411 -9
- package/dist/index.js +623 -49
- package/dist/index.js.map +1 -1
- package/dist/migrations/20261126120000_quick_replies/migration.sql +18 -0
- package/dist/migrations/20261126130000_flow_graph_origin/migration.sql +10 -0
- package/dist/migrations/20261126130000_flow_graph_origin/snapshot.json +1675 -0
- package/dist/migrations-journal/0011_quick_replies.sql +18 -0
- package/dist/migrations-journal/0012_flow_graph_origin.sql +10 -0
- package/dist/migrations-journal/meta/_journal.json +14 -0
- package/package.json +5 -3
package/dist/index.cjs
CHANGED
|
@@ -8,11 +8,11 @@ var __export = (target, all) => {
|
|
|
8
8
|
for (var name in all)
|
|
9
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
10
|
};
|
|
11
|
-
var __copyProps = (to, from, except,
|
|
11
|
+
var __copyProps = (to, from, except, desc4) => {
|
|
12
12
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
13
|
for (let key of __getOwnPropNames(from))
|
|
14
14
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc4 = __getOwnPropDesc(from, key)) || desc4.enumerable });
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
@@ -23,14 +23,17 @@ var index_exports = {};
|
|
|
23
23
|
__export(index_exports, {
|
|
24
24
|
CountInboundLocationsUseCase: () => CountInboundLocationsUseCase,
|
|
25
25
|
CreateFlowGraphUseCase: () => CreateFlowGraphUseCase,
|
|
26
|
+
CreateQuickReplyUseCase: () => CreateQuickReplyUseCase,
|
|
26
27
|
DEFAULT_FALLBACK_LIST_LABEL: () => DEFAULT_FALLBACK_LIST_LABEL,
|
|
27
28
|
DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS: () => DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
|
|
28
29
|
DEFAULT_FLOW_TEXT: () => DEFAULT_FLOW_TEXT,
|
|
29
30
|
DEFAULT_MAX_INVALID_ANSWERS: () => DEFAULT_MAX_INVALID_ANSWERS,
|
|
31
|
+
DEFAULT_QUICK_REPLY_WRITE_SCOPES: () => DEFAULT_QUICK_REPLY_WRITE_SCOPES,
|
|
30
32
|
DEFAULT_START_FLOW_KEY: () => DEFAULT_START_FLOW_KEY,
|
|
31
33
|
DYNAMIC_CHOICE_MORE_ID: () => DYNAMIC_CHOICE_MORE_ID,
|
|
32
34
|
DeleteConversationUseCase: () => DeleteConversationUseCase,
|
|
33
35
|
DeleteFlowGraphUseCase: () => DeleteFlowGraphUseCase,
|
|
36
|
+
DeleteQuickReplyUseCase: () => DeleteQuickReplyUseCase,
|
|
34
37
|
DocumentRepository: () => DocumentRepository,
|
|
35
38
|
ExportConversationUseCase: () => ExportConversationUseCase,
|
|
36
39
|
FLOW_RUNTIME_CONTEXT_KEY: () => FLOW_RUNTIME_CONTEXT_KEY,
|
|
@@ -53,19 +56,23 @@ __export(index_exports, {
|
|
|
53
56
|
ListConversationsUseCase: () => ListConversationsUseCase,
|
|
54
57
|
ListFlowGraphsUseCase: () => ListFlowGraphsUseCase,
|
|
55
58
|
ListMessagesUseCase: () => ListMessagesUseCase,
|
|
59
|
+
ListQuickRepliesUseCase: () => ListQuickRepliesUseCase,
|
|
56
60
|
LogMessageUseCase: () => LogMessageUseCase,
|
|
57
61
|
META_WHATSAPP_MIGRATIONS_TABLE: () => META_WHATSAPP_MIGRATIONS_TABLE,
|
|
58
62
|
MessageRepository: () => MessageRepository,
|
|
59
63
|
OptimisticLockError: () => OptimisticLockError,
|
|
60
|
-
PREVIEW_MEDIA_ID_PREFIX: () =>
|
|
64
|
+
PREVIEW_MEDIA_ID_PREFIX: () => import_meta_whatsapp_contracts18.PREVIEW_MEDIA_ID_PREFIX,
|
|
61
65
|
PRODUCT_LIST_LIMIT: () => PRODUCT_LIST_LIMIT,
|
|
62
66
|
PostgresAdvisoryFlowTurnLock: () => PostgresAdvisoryFlowTurnLock,
|
|
63
67
|
ProcessInboundDispatchUseCase: () => ProcessInboundDispatchUseCase,
|
|
64
68
|
PurgeExpiredDocumentsUseCase: () => PurgeExpiredDocumentsUseCase,
|
|
69
|
+
QUICK_REPLY_SCOPE: () => QUICK_REPLY_SCOPE,
|
|
70
|
+
QuickReplyRepository: () => QuickReplyRepository,
|
|
65
71
|
ReceiveWebhookUseCase: () => ReceiveWebhookUseCase,
|
|
66
72
|
RedactInboundLocationsUseCase: () => RedactInboundLocationsUseCase,
|
|
67
73
|
ReleaseConversationUseCase: () => ReleaseConversationUseCase,
|
|
68
74
|
RequestHumanConversationUseCase: () => RequestHumanConversationUseCase,
|
|
75
|
+
ReseedFlowGraphUseCase: () => ReseedFlowGraphUseCase,
|
|
69
76
|
SaveFlowGraphUseCase: () => SaveFlowGraphUseCase,
|
|
70
77
|
SendMessageUseCase: () => SendMessageUseCase,
|
|
71
78
|
SessionRepository: () => SessionRepository,
|
|
@@ -76,6 +83,7 @@ __export(index_exports, {
|
|
|
76
83
|
TRANSCRIPTION_STATUS: () => TRANSCRIPTION_STATUS,
|
|
77
84
|
TakeoverConversationUseCase: () => TakeoverConversationUseCase,
|
|
78
85
|
TranscribeAudioUseCase: () => TranscribeAudioUseCase,
|
|
86
|
+
UpdateQuickReplyUseCase: () => UpdateQuickReplyUseCase,
|
|
79
87
|
WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_CLAIM_TTL_SECONDS,
|
|
80
88
|
WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core3.WEBHOOK_NONCE_TTL_SECONDS,
|
|
81
89
|
WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
|
|
@@ -84,6 +92,7 @@ __export(index_exports, {
|
|
|
84
92
|
claimWebhookDelivery: () => claimWebhookDelivery,
|
|
85
93
|
confirmWebhookDelivery: () => confirmWebhookDelivery,
|
|
86
94
|
createMetaWhatsAppModule: () => createMetaWhatsAppModule,
|
|
95
|
+
createMetaWhatsAppQuickReplyRoutes: () => createMetaWhatsAppQuickReplyRoutes,
|
|
87
96
|
createSendMediaAction: () => createSendMediaAction,
|
|
88
97
|
createSendProductListAction: () => createSendProductListAction,
|
|
89
98
|
createTranscriptionPolicyResolver: () => createTranscriptionPolicyResolver,
|
|
@@ -99,16 +108,19 @@ __export(index_exports, {
|
|
|
99
108
|
messages: () => messages,
|
|
100
109
|
metaWhatsAppMigrationsFolder: () => metaWhatsAppMigrationsFolder,
|
|
101
110
|
metaWhatsAppSchema: () => metaWhatsAppSchema,
|
|
111
|
+
quickReplies: () => quickReplies,
|
|
102
112
|
readFlowInbound: () => readFlowInbound,
|
|
103
113
|
redeemSseTicket: () => redeemSseTicket,
|
|
104
114
|
resolveFailureStatus: () => resolveFailureStatus,
|
|
105
115
|
resolveFlowAnswer: () => resolveFlowAnswer,
|
|
116
|
+
resolveFlowConfigText: () => resolveFlowConfigText,
|
|
106
117
|
resolveFlowTimeZone: () => resolveFlowTimeZone,
|
|
107
|
-
resolvePreviewUploadId: () =>
|
|
118
|
+
resolvePreviewUploadId: () => import_meta_whatsapp_contracts18.resolvePreviewUploadId,
|
|
108
119
|
runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
|
|
109
120
|
sessions: () => sessions,
|
|
110
121
|
settings: () => settings,
|
|
111
|
-
toPreviewMediaId: () =>
|
|
122
|
+
toPreviewMediaId: () => import_meta_whatsapp_contracts18.toPreviewMediaId,
|
|
123
|
+
toQuickReplyView: () => toQuickReplyView,
|
|
112
124
|
toSessionContract: () => toSessionContract,
|
|
113
125
|
transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
|
|
114
126
|
verifyWebhookChallenge: () => verifyWebhookChallenge,
|
|
@@ -119,7 +131,7 @@ module.exports = __toCommonJS(index_exports);
|
|
|
119
131
|
// src/createMetaWhatsAppModule.ts
|
|
120
132
|
var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
|
|
121
133
|
var import_testing = require("@adatechnology/meta-whatsapp-contracts/testing");
|
|
122
|
-
var
|
|
134
|
+
var import_meta_whatsapp_contracts23 = require("@adatechnology/meta-whatsapp-contracts");
|
|
123
135
|
|
|
124
136
|
// src/repositories/SessionRepository.ts
|
|
125
137
|
var import_drizzle_orm2 = require("drizzle-orm");
|
|
@@ -323,6 +335,14 @@ var flowGraphs = metaWhatsAppSchema.table("flow_graphs", {
|
|
|
323
335
|
menuOptionLabel: (0, import_pg_core.varchar)("menu_option_label", {
|
|
324
336
|
length: 64
|
|
325
337
|
}),
|
|
338
|
+
// 'seed' | 'edited' (FLOW_GRAPH_ORIGIN). Linha anterior ao campo vira 'edited': sem como saber se
|
|
339
|
+
// alguém mexeu, o reseed do produto não pode sobrescrevê-la.
|
|
340
|
+
origin: (0, import_pg_core.varchar)("origin", {
|
|
341
|
+
length: 16
|
|
342
|
+
}).notNull().default("edited"),
|
|
343
|
+
seedVersion: (0, import_pg_core.varchar)("seed_version", {
|
|
344
|
+
length: 64
|
|
345
|
+
}),
|
|
326
346
|
createdAt: (0, import_pg_core.timestamp)("created_at", {
|
|
327
347
|
withTimezone: true
|
|
328
348
|
}).notNull().defaultNow(),
|
|
@@ -380,6 +400,29 @@ var flowMedia = metaWhatsAppSchema.table("flow_media", {
|
|
|
380
400
|
// receberia o documento repetido.
|
|
381
401
|
(0, import_pg_core.uniqueIndex)("idx_flow_media_node_upload").on(table.companyId, table.flowKey, table.nodeId, table.uploadId)
|
|
382
402
|
]);
|
|
403
|
+
var quickReplies = metaWhatsAppSchema.table("quick_replies", {
|
|
404
|
+
id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
|
|
405
|
+
companyId: (0, import_pg_core.uuid)("company_id").notNull(),
|
|
406
|
+
title: (0, import_pg_core.varchar)("title", {
|
|
407
|
+
length: 40
|
|
408
|
+
}).notNull(),
|
|
409
|
+
shortcut: (0, import_pg_core.varchar)("shortcut", {
|
|
410
|
+
length: 20
|
|
411
|
+
}).notNull(),
|
|
412
|
+
body: (0, import_pg_core.varchar)("body", {
|
|
413
|
+
length: 1e3
|
|
414
|
+
}).notNull(),
|
|
415
|
+
sortOrder: (0, import_pg_core.integer)("sort_order").notNull().default(0),
|
|
416
|
+
createdAt: (0, import_pg_core.timestamp)("created_at", {
|
|
417
|
+
withTimezone: true
|
|
418
|
+
}).notNull().defaultNow(),
|
|
419
|
+
updatedAt: (0, import_pg_core.timestamp)("updated_at", {
|
|
420
|
+
withTimezone: true
|
|
421
|
+
}).notNull().defaultNow()
|
|
422
|
+
}, (table) => [
|
|
423
|
+
(0, import_pg_core.uniqueIndex)("idx_quick_replies_company_shortcut").on(table.companyId, table.shortcut),
|
|
424
|
+
(0, import_pg_core.index)("idx_quick_replies_company_order").on(table.companyId, table.sortOrder)
|
|
425
|
+
]);
|
|
383
426
|
var settings = metaWhatsAppSchema.table("settings", {
|
|
384
427
|
companyId: (0, import_pg_core.uuid)("company_id").primaryKey(),
|
|
385
428
|
templateName: (0, import_pg_core.varchar)("template_name", {
|
|
@@ -828,13 +871,15 @@ var MessageRepository = class {
|
|
|
828
871
|
(0, import_drizzle_orm3.eq)(messages.sessionId, params.sessionId)
|
|
829
872
|
];
|
|
830
873
|
if (params.before) conditions.push((0, import_drizzle_orm3.lt)(messages.createdAt, new Date(params.before)));
|
|
831
|
-
|
|
874
|
+
const newestFirst = await this.db.select().from(messages).where((0, import_drizzle_orm3.and)(...conditions)).orderBy((0, import_drizzle_orm3.desc)(messages.createdAt), (0, import_drizzle_orm3.desc)(messages.id)).limit(params.limit ?? DEFAULT_LIMIT2);
|
|
875
|
+
return newestFirst.reverse();
|
|
832
876
|
}
|
|
833
877
|
};
|
|
834
878
|
|
|
835
879
|
// src/repositories/FlowGraphRepository.ts
|
|
836
880
|
var import_drizzle_orm4 = require("drizzle-orm");
|
|
837
881
|
var import_meta_whatsapp_contracts = require("@adatechnology/meta-whatsapp-contracts");
|
|
882
|
+
var import_meta_whatsapp_contracts2 = require("@adatechnology/meta-whatsapp-contracts");
|
|
838
883
|
var InvalidFlowGraphError = class extends Error {
|
|
839
884
|
static {
|
|
840
885
|
__name(this, "InvalidFlowGraphError");
|
|
@@ -853,10 +898,18 @@ function toContractGraph(row) {
|
|
|
853
898
|
label: row.label,
|
|
854
899
|
startNodeId: row.startNodeId,
|
|
855
900
|
version: row.version,
|
|
856
|
-
nodes: parsed.data
|
|
901
|
+
nodes: parsed.data,
|
|
902
|
+
origin: toOrigin(row.origin),
|
|
903
|
+
...row.seedVersion ? {
|
|
904
|
+
seedVersion: row.seedVersion
|
|
905
|
+
} : {}
|
|
857
906
|
};
|
|
858
907
|
}
|
|
859
908
|
__name(toContractGraph, "toContractGraph");
|
|
909
|
+
function toOrigin(value) {
|
|
910
|
+
return value === import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED ? import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED : import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.EDITED;
|
|
911
|
+
}
|
|
912
|
+
__name(toOrigin, "toOrigin");
|
|
860
913
|
var OptimisticLockError = class extends Error {
|
|
861
914
|
static {
|
|
862
915
|
__name(this, "OptimisticLockError");
|
|
@@ -895,7 +948,11 @@ var FlowGraphRepository = class {
|
|
|
895
948
|
nodeCount: Object.keys(row.nodes).length,
|
|
896
949
|
showInMenu: row.showInMenu,
|
|
897
950
|
menuOptionLabel: row.menuOptionLabel ?? void 0,
|
|
898
|
-
updatedAt: row.updatedAt.toISOString()
|
|
951
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
952
|
+
origin: toOrigin(row.origin),
|
|
953
|
+
...row.seedVersion ? {
|
|
954
|
+
seedVersion: row.seedVersion
|
|
955
|
+
} : {}
|
|
899
956
|
}));
|
|
900
957
|
}
|
|
901
958
|
// Valida antes de gravar: aceitar um grafo malformado e só reclamar na leitura empurraria a
|
|
@@ -913,7 +970,10 @@ var FlowGraphRepository = class {
|
|
|
913
970
|
startNodeId: graph.startNodeId,
|
|
914
971
|
nodes: graph.nodes,
|
|
915
972
|
showInMenu: graph.showInMenu ?? false,
|
|
916
|
-
menuOptionLabel: graph.menuOptionLabel
|
|
973
|
+
menuOptionLabel: graph.menuOptionLabel,
|
|
974
|
+
// Quem informa `seedVersion` é o produto semeando; criado pelo editor não traz e fica `edited`.
|
|
975
|
+
origin: graph.seedVersion ? import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED : import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.EDITED,
|
|
976
|
+
seedVersion: graph.seedVersion ?? null
|
|
917
977
|
}).returning();
|
|
918
978
|
const createdGraph = toContractGraph(created);
|
|
919
979
|
await this.cache?.invalidate(companyId, createdGraph.key);
|
|
@@ -927,6 +987,8 @@ var FlowGraphRepository = class {
|
|
|
927
987
|
label: graph.label,
|
|
928
988
|
startNodeId: graph.startNodeId,
|
|
929
989
|
nodes: graph.nodes,
|
|
990
|
+
// Salvar é sempre edição humana, mesmo que o editor devolva `origin: 'seed'` do grafo que carregou.
|
|
991
|
+
origin: import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.EDITED,
|
|
930
992
|
version: expectedVersion + 1,
|
|
931
993
|
updatedAt: /* @__PURE__ */ new Date()
|
|
932
994
|
}).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(flowGraphs.companyId, companyId), (0, import_drizzle_orm4.eq)(flowGraphs.key, graph.key), (0, import_drizzle_orm4.eq)(flowGraphs.version, expectedVersion))).returning();
|
|
@@ -934,6 +996,38 @@ var FlowGraphRepository = class {
|
|
|
934
996
|
await this.cache?.invalidate(companyId, graph.key);
|
|
935
997
|
return toContractGraph(rows[0]);
|
|
936
998
|
}
|
|
999
|
+
/**
|
|
1000
|
+
* Atualiza um grafo semeado que ninguém editou. A condição `origin = 'seed'` vai no próprio UPDATE:
|
|
1001
|
+
* se uma pessoa salvar pelo editor entre a leitura e a escrita, o grafo vira `edited` e este update
|
|
1002
|
+
* não casa nenhuma linha — a edição nunca é sobrescrita. Idempotente por `seedVersion`.
|
|
1003
|
+
*/
|
|
1004
|
+
async reseed(params) {
|
|
1005
|
+
this.assertValidNodes(params.key, params.content.nodes);
|
|
1006
|
+
const rows = await this.db.update(flowGraphs).set({
|
|
1007
|
+
label: params.content.label,
|
|
1008
|
+
startNodeId: params.content.startNodeId,
|
|
1009
|
+
nodes: params.content.nodes,
|
|
1010
|
+
seedVersion: params.seedVersion,
|
|
1011
|
+
version: import_drizzle_orm4.sql`${flowGraphs.version} + 1`,
|
|
1012
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1013
|
+
}).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(flowGraphs.companyId, params.companyId), (0, import_drizzle_orm4.eq)(flowGraphs.key, params.key), (0, import_drizzle_orm4.eq)(flowGraphs.origin, import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED), import_drizzle_orm4.sql`${flowGraphs.seedVersion} is distinct from ${params.seedVersion}`)).returning();
|
|
1014
|
+
if (rows.length > 0) {
|
|
1015
|
+
await this.cache?.invalidate(params.companyId, params.key);
|
|
1016
|
+
return {
|
|
1017
|
+
status: "updated",
|
|
1018
|
+
graph: toContractGraph(rows[0])
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
const [existing] = await this.db.select({
|
|
1022
|
+
origin: flowGraphs.origin
|
|
1023
|
+
}).from(flowGraphs).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(flowGraphs.companyId, params.companyId), (0, import_drizzle_orm4.eq)(flowGraphs.key, params.key))).limit(1);
|
|
1024
|
+
if (!existing) return {
|
|
1025
|
+
status: "missing"
|
|
1026
|
+
};
|
|
1027
|
+
return {
|
|
1028
|
+
status: existing.origin === import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED ? "current" : "edited"
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
937
1031
|
async delete(companyId, key) {
|
|
938
1032
|
await this.db.delete(flowGraphs).where((0, import_drizzle_orm4.and)((0, import_drizzle_orm4.eq)(flowGraphs.companyId, companyId), (0, import_drizzle_orm4.eq)(flowGraphs.key, key)));
|
|
939
1033
|
await this.cache?.invalidate(companyId, key);
|
|
@@ -1111,6 +1205,7 @@ var LogMessageUseCase = class {
|
|
|
1111
1205
|
await this.sessionRepository.touchInbound(params.companyId, params.whatsappNumber);
|
|
1112
1206
|
}
|
|
1113
1207
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "message", {
|
|
1208
|
+
companyId: params.companyId,
|
|
1114
1209
|
direction: params.direction,
|
|
1115
1210
|
sender: params.sender
|
|
1116
1211
|
});
|
|
@@ -1134,7 +1229,7 @@ var LogMessageUseCase = class {
|
|
|
1134
1229
|
};
|
|
1135
1230
|
|
|
1136
1231
|
// src/use-cases/SendMessage.use-case.ts
|
|
1137
|
-
var
|
|
1232
|
+
var import_meta_whatsapp_contracts3 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1138
1233
|
var WHATSAPP_WINDOW_HOURS = 24;
|
|
1139
1234
|
var DEFAULT_FALLBACK_LIST_LABEL = "Op\xE7\xF5es";
|
|
1140
1235
|
var SendMessageUseCase = class {
|
|
@@ -1155,8 +1250,8 @@ var SendMessageUseCase = class {
|
|
|
1155
1250
|
}
|
|
1156
1251
|
async assertWithinWindow(companyId, whatsappNumber) {
|
|
1157
1252
|
const hours = await this.sessionRepository.hoursSinceLastInbound(companyId, whatsappNumber);
|
|
1158
|
-
if (hours === void 0) throw new
|
|
1159
|
-
if (hours >= WHATSAPP_WINDOW_HOURS) throw new
|
|
1253
|
+
if (hours === void 0) throw new import_meta_whatsapp_contracts3.WindowExpiredError();
|
|
1254
|
+
if (hours >= WHATSAPP_WINDOW_HOURS) throw new import_meta_whatsapp_contracts3.WindowExpiredError(hours);
|
|
1160
1255
|
}
|
|
1161
1256
|
async sendText(params) {
|
|
1162
1257
|
await this.assertWithinWindow(params.companyId, params.whatsappNumber);
|
|
@@ -1230,7 +1325,7 @@ var SendMessageUseCase = class {
|
|
|
1230
1325
|
* títulos das opções) em `payload.interactive`, para o histórico mostrar o que foi oferecido.
|
|
1231
1326
|
*/
|
|
1232
1327
|
async sendInteractive(params) {
|
|
1233
|
-
(0,
|
|
1328
|
+
(0, import_meta_whatsapp_contracts3.assertInteractiveWithinLimits)(params.interactive);
|
|
1234
1329
|
await this.assertWithinWindow(params.companyId, params.whatsappNumber);
|
|
1235
1330
|
const { externalMessageId } = await this.sendInteractiveThroughChannel(params);
|
|
1236
1331
|
return this.logMessage.execute({
|
|
@@ -1329,6 +1424,7 @@ var TakeoverConversationUseCase = class {
|
|
|
1329
1424
|
async execute(params) {
|
|
1330
1425
|
await this.sessionRepository.takeover(params.companyId, params.whatsappNumber, params.agentUserId);
|
|
1331
1426
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
|
|
1427
|
+
companyId: params.companyId,
|
|
1332
1428
|
mode: "human",
|
|
1333
1429
|
assignedUserId: params.agentUserId
|
|
1334
1430
|
});
|
|
@@ -1361,6 +1457,7 @@ var ReleaseConversationUseCase = class {
|
|
|
1361
1457
|
async execute(params) {
|
|
1362
1458
|
await this.sessionRepository.release(params.companyId, params.whatsappNumber);
|
|
1363
1459
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "mode-changed", {
|
|
1460
|
+
companyId: params.companyId,
|
|
1364
1461
|
mode: "bot",
|
|
1365
1462
|
assignedUserId: null
|
|
1366
1463
|
});
|
|
@@ -1378,7 +1475,7 @@ var ReleaseConversationUseCase = class {
|
|
|
1378
1475
|
};
|
|
1379
1476
|
|
|
1380
1477
|
// src/use-cases/RequestHumanConversation.use-case.ts
|
|
1381
|
-
var
|
|
1478
|
+
var import_meta_whatsapp_contracts4 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1382
1479
|
|
|
1383
1480
|
// src/channel/inboundDispatch.ts
|
|
1384
1481
|
var import_meta_graph_core = require("@adatechnology/meta-graph-core");
|
|
@@ -1505,8 +1602,9 @@ var RequestHumanConversationUseCase = class {
|
|
|
1505
1602
|
async execute(params) {
|
|
1506
1603
|
await this.sessionRepository.requestHuman(params.companyId, params.whatsappNumber);
|
|
1507
1604
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1508
|
-
if (!session) throw new
|
|
1605
|
+
if (!session) throw new import_meta_whatsapp_contracts4.SessionNotFoundError(params.whatsappNumber);
|
|
1509
1606
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
|
|
1607
|
+
companyId: params.companyId,
|
|
1510
1608
|
humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
|
|
1511
1609
|
});
|
|
1512
1610
|
this.realtime?.emit("global", "data-changed", {});
|
|
@@ -1542,7 +1640,7 @@ var ListConversationsUseCase = class {
|
|
|
1542
1640
|
};
|
|
1543
1641
|
|
|
1544
1642
|
// src/use-cases/ListMessages.use-case.ts
|
|
1545
|
-
var
|
|
1643
|
+
var import_meta_whatsapp_contracts5 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1546
1644
|
var ListMessagesUseCase = class {
|
|
1547
1645
|
static {
|
|
1548
1646
|
__name(this, "ListMessagesUseCase");
|
|
@@ -1555,7 +1653,7 @@ var ListMessagesUseCase = class {
|
|
|
1555
1653
|
}
|
|
1556
1654
|
async execute(params) {
|
|
1557
1655
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1558
|
-
if (!session) throw new
|
|
1656
|
+
if (!session) throw new import_meta_whatsapp_contracts5.SessionNotFoundError(params.whatsappNumber);
|
|
1559
1657
|
const repoParams = {
|
|
1560
1658
|
companyId: params.companyId,
|
|
1561
1659
|
sessionId: session.id,
|
|
@@ -1567,7 +1665,7 @@ var ListMessagesUseCase = class {
|
|
|
1567
1665
|
};
|
|
1568
1666
|
|
|
1569
1667
|
// src/use-cases/ListConversationDocuments.use-case.ts
|
|
1570
|
-
var
|
|
1668
|
+
var import_meta_whatsapp_contracts6 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1571
1669
|
var ListConversationDocumentsUseCase = class {
|
|
1572
1670
|
static {
|
|
1573
1671
|
__name(this, "ListConversationDocumentsUseCase");
|
|
@@ -1580,7 +1678,7 @@ var ListConversationDocumentsUseCase = class {
|
|
|
1580
1678
|
}
|
|
1581
1679
|
async execute(params) {
|
|
1582
1680
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1583
|
-
if (!session) throw new
|
|
1681
|
+
if (!session) throw new import_meta_whatsapp_contracts6.SessionNotFoundError(params.whatsappNumber);
|
|
1584
1682
|
const { rows, total } = await this.documentRepository.listByConversation({
|
|
1585
1683
|
companyId: params.companyId,
|
|
1586
1684
|
sessionId: session.id,
|
|
@@ -1658,7 +1756,7 @@ var ListCompanyDocumentsUseCase = class {
|
|
|
1658
1756
|
};
|
|
1659
1757
|
|
|
1660
1758
|
// src/use-cases/DeleteConversation.use-case.ts
|
|
1661
|
-
var
|
|
1759
|
+
var import_meta_whatsapp_contracts7 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1662
1760
|
var DeleteConversationUseCase = class {
|
|
1663
1761
|
static {
|
|
1664
1762
|
__name(this, "DeleteConversationUseCase");
|
|
@@ -1673,7 +1771,7 @@ var DeleteConversationUseCase = class {
|
|
|
1673
1771
|
}
|
|
1674
1772
|
async execute(params) {
|
|
1675
1773
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1676
|
-
if (!session) throw new
|
|
1774
|
+
if (!session) throw new import_meta_whatsapp_contracts7.SessionNotFoundError(params.whatsappNumber);
|
|
1677
1775
|
const uploadIds = await this.documentRepository.listUploadIdsBySession(params.companyId, session.id);
|
|
1678
1776
|
if (uploadIds.length > 0 && !this.objectStorage?.delete) {
|
|
1679
1777
|
throw new Error("storage_delete_unsupported: a conversa tem arquivos e o storage injetado n\xE3o implementa delete");
|
|
@@ -1918,8 +2016,171 @@ var DocumentRepository = class {
|
|
|
1918
2016
|
}
|
|
1919
2017
|
};
|
|
1920
2018
|
|
|
2019
|
+
// src/repositories/QuickReplyRepository.ts
|
|
2020
|
+
var import_drizzle_orm7 = require("drizzle-orm");
|
|
2021
|
+
var import_meta_whatsapp_contracts8 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2022
|
+
var UNIQUE_VIOLATION_SQLSTATE = "23505";
|
|
2023
|
+
function hasUniqueViolationState(error) {
|
|
2024
|
+
const state = error;
|
|
2025
|
+
return state?.code === UNIQUE_VIOLATION_SQLSTATE || state?.errno === UNIQUE_VIOLATION_SQLSTATE;
|
|
2026
|
+
}
|
|
2027
|
+
__name(hasUniqueViolationState, "hasUniqueViolationState");
|
|
2028
|
+
function isUniqueViolation(error) {
|
|
2029
|
+
return hasUniqueViolationState(error) || hasUniqueViolationState(error?.cause);
|
|
2030
|
+
}
|
|
2031
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
2032
|
+
function escapeLikePattern(text2) {
|
|
2033
|
+
return text2.replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
2034
|
+
}
|
|
2035
|
+
__name(escapeLikePattern, "escapeLikePattern");
|
|
2036
|
+
var QuickReplyRepository = class {
|
|
2037
|
+
static {
|
|
2038
|
+
__name(this, "QuickReplyRepository");
|
|
2039
|
+
}
|
|
2040
|
+
db;
|
|
2041
|
+
constructor(db) {
|
|
2042
|
+
this.db = db;
|
|
2043
|
+
}
|
|
2044
|
+
async list(params) {
|
|
2045
|
+
const filters = [
|
|
2046
|
+
(0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId)
|
|
2047
|
+
];
|
|
2048
|
+
if (params.search) {
|
|
2049
|
+
const pattern = `%${escapeLikePattern(params.search)}%`;
|
|
2050
|
+
const matches = (0, import_drizzle_orm7.or)((0, import_drizzle_orm7.ilike)(quickReplies.title, pattern), (0, import_drizzle_orm7.ilike)(quickReplies.shortcut, pattern), (0, import_drizzle_orm7.ilike)(quickReplies.body, pattern));
|
|
2051
|
+
if (matches) filters.push(matches);
|
|
2052
|
+
}
|
|
2053
|
+
return this.db.select().from(quickReplies).where((0, import_drizzle_orm7.and)(...filters)).orderBy((0, import_drizzle_orm7.asc)(quickReplies.sortOrder), (0, import_drizzle_orm7.asc)(quickReplies.title), (0, import_drizzle_orm7.asc)(quickReplies.id));
|
|
2054
|
+
}
|
|
2055
|
+
async get(companyId, id) {
|
|
2056
|
+
const [row] = await this.db.select().from(quickReplies).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(quickReplies.companyId, companyId), (0, import_drizzle_orm7.eq)(quickReplies.id, id))).limit(1);
|
|
2057
|
+
return row;
|
|
2058
|
+
}
|
|
2059
|
+
async create(params) {
|
|
2060
|
+
const [totals] = await this.db.select({
|
|
2061
|
+
total: (0, import_drizzle_orm7.count)(),
|
|
2062
|
+
highestOrder: (0, import_drizzle_orm7.max)(quickReplies.sortOrder)
|
|
2063
|
+
}).from(quickReplies).where((0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId));
|
|
2064
|
+
if ((totals?.total ?? 0) >= import_meta_whatsapp_contracts8.QUICK_REPLY_LIMITS.MAX_PER_COMPANY) {
|
|
2065
|
+
throw new import_meta_whatsapp_contracts8.QuickReplyLimitReachedError(import_meta_whatsapp_contracts8.QUICK_REPLY_LIMITS.MAX_PER_COMPANY);
|
|
2066
|
+
}
|
|
2067
|
+
try {
|
|
2068
|
+
const [row] = await this.db.insert(quickReplies).values({
|
|
2069
|
+
companyId: params.companyId,
|
|
2070
|
+
title: params.title,
|
|
2071
|
+
shortcut: params.shortcut,
|
|
2072
|
+
body: params.body,
|
|
2073
|
+
// Sem ordem explícita vai para o fim da lista.
|
|
2074
|
+
sortOrder: params.sortOrder ?? (totals?.highestOrder ?? -1) + 1
|
|
2075
|
+
}).returning();
|
|
2076
|
+
return row;
|
|
2077
|
+
} catch (error) {
|
|
2078
|
+
if (isUniqueViolation(error)) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2079
|
+
throw error;
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
async update(params) {
|
|
2083
|
+
const [taken] = await this.db.select({
|
|
2084
|
+
id: quickReplies.id
|
|
2085
|
+
}).from(quickReplies).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId), (0, import_drizzle_orm7.eq)(quickReplies.shortcut, params.shortcut), (0, import_drizzle_orm7.ne)(quickReplies.id, params.id))).limit(1);
|
|
2086
|
+
if (taken) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2087
|
+
try {
|
|
2088
|
+
const [row] = await this.db.update(quickReplies).set({
|
|
2089
|
+
title: params.title,
|
|
2090
|
+
shortcut: params.shortcut,
|
|
2091
|
+
body: params.body,
|
|
2092
|
+
...params.sortOrder !== void 0 ? {
|
|
2093
|
+
sortOrder: params.sortOrder
|
|
2094
|
+
} : {},
|
|
2095
|
+
updatedAt: import_drizzle_orm7.sql`now()`
|
|
2096
|
+
}).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId), (0, import_drizzle_orm7.eq)(quickReplies.id, params.id))).returning();
|
|
2097
|
+
if (!row) throw new import_meta_whatsapp_contracts8.QuickReplyNotFoundError(params.id);
|
|
2098
|
+
return row;
|
|
2099
|
+
} catch (error) {
|
|
2100
|
+
if (isUniqueViolation(error)) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2101
|
+
throw error;
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
async delete(companyId, id) {
|
|
2105
|
+
const rows = await this.db.delete(quickReplies).where((0, import_drizzle_orm7.and)((0, import_drizzle_orm7.eq)(quickReplies.companyId, companyId), (0, import_drizzle_orm7.eq)(quickReplies.id, id))).returning({
|
|
2106
|
+
id: quickReplies.id
|
|
2107
|
+
});
|
|
2108
|
+
return rows.length > 0;
|
|
2109
|
+
}
|
|
2110
|
+
};
|
|
2111
|
+
|
|
2112
|
+
// src/use-cases/QuickReply.use-cases.ts
|
|
2113
|
+
var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2114
|
+
function toQuickReplyView(row) {
|
|
2115
|
+
return {
|
|
2116
|
+
id: row.id,
|
|
2117
|
+
title: row.title,
|
|
2118
|
+
shortcut: row.shortcut,
|
|
2119
|
+
body: row.body,
|
|
2120
|
+
sortOrder: row.sortOrder,
|
|
2121
|
+
createdAt: row.createdAt.toISOString(),
|
|
2122
|
+
updatedAt: row.updatedAt.toISOString()
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
__name(toQuickReplyView, "toQuickReplyView");
|
|
2126
|
+
var ListQuickRepliesUseCase = class {
|
|
2127
|
+
static {
|
|
2128
|
+
__name(this, "ListQuickRepliesUseCase");
|
|
2129
|
+
}
|
|
2130
|
+
repository;
|
|
2131
|
+
constructor(repository) {
|
|
2132
|
+
this.repository = repository;
|
|
2133
|
+
}
|
|
2134
|
+
async execute(params) {
|
|
2135
|
+
const rows = await this.repository.list({
|
|
2136
|
+
companyId: params.companyId,
|
|
2137
|
+
...params.search ? {
|
|
2138
|
+
search: params.search
|
|
2139
|
+
} : {}
|
|
2140
|
+
});
|
|
2141
|
+
return rows.map(toQuickReplyView);
|
|
2142
|
+
}
|
|
2143
|
+
};
|
|
2144
|
+
var CreateQuickReplyUseCase = class {
|
|
2145
|
+
static {
|
|
2146
|
+
__name(this, "CreateQuickReplyUseCase");
|
|
2147
|
+
}
|
|
2148
|
+
repository;
|
|
2149
|
+
constructor(repository) {
|
|
2150
|
+
this.repository = repository;
|
|
2151
|
+
}
|
|
2152
|
+
async execute(params) {
|
|
2153
|
+
return toQuickReplyView(await this.repository.create(params));
|
|
2154
|
+
}
|
|
2155
|
+
};
|
|
2156
|
+
var UpdateQuickReplyUseCase = class {
|
|
2157
|
+
static {
|
|
2158
|
+
__name(this, "UpdateQuickReplyUseCase");
|
|
2159
|
+
}
|
|
2160
|
+
repository;
|
|
2161
|
+
constructor(repository) {
|
|
2162
|
+
this.repository = repository;
|
|
2163
|
+
}
|
|
2164
|
+
async execute(params) {
|
|
2165
|
+
return toQuickReplyView(await this.repository.update(params));
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
var DeleteQuickReplyUseCase = class {
|
|
2169
|
+
static {
|
|
2170
|
+
__name(this, "DeleteQuickReplyUseCase");
|
|
2171
|
+
}
|
|
2172
|
+
repository;
|
|
2173
|
+
constructor(repository) {
|
|
2174
|
+
this.repository = repository;
|
|
2175
|
+
}
|
|
2176
|
+
async execute(params) {
|
|
2177
|
+
const wasDeleted = await this.repository.delete(params.companyId, params.id);
|
|
2178
|
+
if (!wasDeleted) throw new import_meta_whatsapp_contracts9.QuickReplyNotFoundError(params.id);
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
|
|
1921
2182
|
// src/use-cases/ExportConversation.use-case.ts
|
|
1922
|
-
var
|
|
2183
|
+
var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1923
2184
|
var ExportConversationUseCase = class {
|
|
1924
2185
|
static {
|
|
1925
2186
|
__name(this, "ExportConversationUseCase");
|
|
@@ -1930,7 +2191,7 @@ var ExportConversationUseCase = class {
|
|
|
1930
2191
|
}
|
|
1931
2192
|
async execute(params) {
|
|
1932
2193
|
const result = await this.sessionRepository.exportConversation(params.companyId, params.whatsappNumber);
|
|
1933
|
-
if (!result) throw new
|
|
2194
|
+
if (!result) throw new import_meta_whatsapp_contracts10.SessionNotFoundError(params.whatsappNumber);
|
|
1934
2195
|
return result;
|
|
1935
2196
|
}
|
|
1936
2197
|
};
|
|
@@ -1984,6 +2245,18 @@ var SaveFlowGraphUseCase = class {
|
|
|
1984
2245
|
return this.flowGraphRepository.save(params.companyId, params.graph, params.expectedVersion);
|
|
1985
2246
|
}
|
|
1986
2247
|
};
|
|
2248
|
+
var ReseedFlowGraphUseCase = class {
|
|
2249
|
+
static {
|
|
2250
|
+
__name(this, "ReseedFlowGraphUseCase");
|
|
2251
|
+
}
|
|
2252
|
+
flowGraphRepository;
|
|
2253
|
+
constructor(flowGraphRepository) {
|
|
2254
|
+
this.flowGraphRepository = flowGraphRepository;
|
|
2255
|
+
}
|
|
2256
|
+
async execute(params) {
|
|
2257
|
+
return this.flowGraphRepository.reseed(params);
|
|
2258
|
+
}
|
|
2259
|
+
};
|
|
1987
2260
|
var DeleteFlowGraphUseCase = class {
|
|
1988
2261
|
static {
|
|
1989
2262
|
__name(this, "DeleteFlowGraphUseCase");
|
|
@@ -2010,7 +2283,7 @@ var GetLiveFlowPositionsUseCase = class {
|
|
|
2010
2283
|
};
|
|
2011
2284
|
|
|
2012
2285
|
// src/flows/FlowInterpreter.ts
|
|
2013
|
-
var
|
|
2286
|
+
var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2014
2287
|
var DEFAULT_MAX_STEPS = 50;
|
|
2015
2288
|
function evaluateCondition(node, context) {
|
|
2016
2289
|
if (!node.conditionContextKey || !node.conditionOperator || !node.conditionValue) return false;
|
|
@@ -2113,9 +2386,9 @@ var FlowInterpreter = class {
|
|
|
2113
2386
|
kind: "terminal",
|
|
2114
2387
|
context: input.context
|
|
2115
2388
|
};
|
|
2116
|
-
if ((0,
|
|
2389
|
+
if ((0, import_meta_whatsapp_contracts11.isCrossFlowTarget)(nextNodeId)) return {
|
|
2117
2390
|
kind: "cross-flow",
|
|
2118
|
-
flowKey: (0,
|
|
2391
|
+
flowKey: (0, import_meta_whatsapp_contracts11.crossFlowKey)(nextNodeId),
|
|
2119
2392
|
context: input.context
|
|
2120
2393
|
};
|
|
2121
2394
|
if (!input.graph.nodes[nextNodeId]) return {
|
|
@@ -2175,10 +2448,10 @@ var FlowInterpreter = class {
|
|
|
2175
2448
|
};
|
|
2176
2449
|
|
|
2177
2450
|
// src/flows/FlowRunner.ts
|
|
2178
|
-
var
|
|
2451
|
+
var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2179
2452
|
|
|
2180
2453
|
// src/flows/resolveFlowAnswer.ts
|
|
2181
|
-
var
|
|
2454
|
+
var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2182
2455
|
|
|
2183
2456
|
// src/flows/flowRunner.constant.ts
|
|
2184
2457
|
var DEFAULT_START_FLOW_KEY = "main";
|
|
@@ -2204,16 +2477,16 @@ function isChoiceNode(node) {
|
|
|
2204
2477
|
__name(isChoiceNode, "isChoiceNode");
|
|
2205
2478
|
function keywordRoute(node, answer, isInteractiveReply) {
|
|
2206
2479
|
if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
|
|
2207
|
-
return (0,
|
|
2480
|
+
return (0, import_meta_whatsapp_contracts12.matchFlowKeywordRoute)(answer, node.next.byKeyword);
|
|
2208
2481
|
}
|
|
2209
2482
|
__name(keywordRoute, "keywordRoute");
|
|
2210
2483
|
function matchOption(answer, options, isInteractiveReply) {
|
|
2211
2484
|
if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
|
|
2212
|
-
return (0,
|
|
2485
|
+
return (0, import_meta_whatsapp_contracts12.matchFlowChoice)(answer, options);
|
|
2213
2486
|
}
|
|
2214
2487
|
__name(matchOption, "matchOption");
|
|
2215
2488
|
function resolveChoice(params, answer) {
|
|
2216
|
-
const optionId = matchOption(answer, params.node.options ?? [], params.isInteractiveReply);
|
|
2489
|
+
const optionId = matchOption(answer, params.options ?? params.node.options ?? [], params.isInteractiveReply);
|
|
2217
2490
|
if (optionId) return {
|
|
2218
2491
|
kind: "answer",
|
|
2219
2492
|
userAnswer: optionId
|
|
@@ -2251,7 +2524,7 @@ function resolveQuestion(params, answer) {
|
|
|
2251
2524
|
kind: "jump",
|
|
2252
2525
|
target
|
|
2253
2526
|
};
|
|
2254
|
-
const result = (0,
|
|
2527
|
+
const result = (0, import_meta_whatsapp_contracts12.validateFlowAnswer)({
|
|
2255
2528
|
node: params.node,
|
|
2256
2529
|
answer,
|
|
2257
2530
|
context: params.context,
|
|
@@ -2279,10 +2552,10 @@ function resolveFlowAnswer(params) {
|
|
|
2279
2552
|
__name(resolveFlowAnswer, "resolveFlowAnswer");
|
|
2280
2553
|
|
|
2281
2554
|
// src/flows/FlowQuestionRenderer.ts
|
|
2282
|
-
var
|
|
2555
|
+
var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2283
2556
|
|
|
2284
2557
|
// src/flows/buildFlowChoiceMessage.ts
|
|
2285
|
-
var
|
|
2558
|
+
var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2286
2559
|
function groupSections(options) {
|
|
2287
2560
|
const sections = [];
|
|
2288
2561
|
for (const option of options) {
|
|
@@ -2315,7 +2588,7 @@ function asNumberedText(params) {
|
|
|
2315
2588
|
const description = option.description ? ` \u2014 ${option.description}` : "";
|
|
2316
2589
|
return `${index2 + 1}. ${option.title}${description}`;
|
|
2317
2590
|
});
|
|
2318
|
-
const limit =
|
|
2591
|
+
const limit = import_meta_whatsapp_contracts13.WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
|
|
2319
2592
|
const full = `${params.body}
|
|
2320
2593
|
|
|
2321
2594
|
${lines.join("\n")}`;
|
|
@@ -2342,7 +2615,7 @@ ${line}`;
|
|
|
2342
2615
|
__name(asNumberedText, "asNumberedText");
|
|
2343
2616
|
function buildFlowChoiceMessage(params) {
|
|
2344
2617
|
const isPlain = params.options.every((option) => !option.description && !option.section);
|
|
2345
|
-
if (isPlain && params.options.length <=
|
|
2618
|
+
if (isPlain && params.options.length <= import_meta_whatsapp_contracts13.WHATSAPP_CHOICE_LIMIT.BUTTONS) {
|
|
2346
2619
|
const buttons = {
|
|
2347
2620
|
kind: "buttons",
|
|
2348
2621
|
body: params.body,
|
|
@@ -2351,7 +2624,7 @@ function buildFlowChoiceMessage(params) {
|
|
|
2351
2624
|
title: option.title
|
|
2352
2625
|
}))
|
|
2353
2626
|
};
|
|
2354
|
-
if ((0,
|
|
2627
|
+
if ((0, import_meta_whatsapp_contracts13.listInteractiveLimitViolations)(buttons).length === 0) return {
|
|
2355
2628
|
kind: "interactive",
|
|
2356
2629
|
interactive: buttons
|
|
2357
2630
|
};
|
|
@@ -2362,7 +2635,7 @@ function buildFlowChoiceMessage(params) {
|
|
|
2362
2635
|
buttonLabel: params.listButtonLabel,
|
|
2363
2636
|
sections: groupSections(params.options)
|
|
2364
2637
|
};
|
|
2365
|
-
if ((0,
|
|
2638
|
+
if ((0, import_meta_whatsapp_contracts13.listInteractiveLimitViolations)(list).length === 0) return {
|
|
2366
2639
|
kind: "interactive",
|
|
2367
2640
|
interactive: list
|
|
2368
2641
|
};
|
|
@@ -2399,7 +2672,7 @@ var FlowQuestionRenderer = class {
|
|
|
2399
2672
|
this.providers.set(key, provider);
|
|
2400
2673
|
}
|
|
2401
2674
|
interpolate(text2, variables) {
|
|
2402
|
-
return (0,
|
|
2675
|
+
return (0, import_meta_whatsapp_contracts14.interpolateFlowText)(text2, variables, this.config.formatValue ? {
|
|
2403
2676
|
formatValue: this.config.formatValue
|
|
2404
2677
|
} : {});
|
|
2405
2678
|
}
|
|
@@ -2410,7 +2683,7 @@ var FlowQuestionRenderer = class {
|
|
|
2410
2683
|
...params.variables
|
|
2411
2684
|
};
|
|
2412
2685
|
const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
|
|
2413
|
-
const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
|
|
2686
|
+
const listButtonLabel = this.interpolate(node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL, variables);
|
|
2414
2687
|
if (node.type === "dynamic_choice") {
|
|
2415
2688
|
const options = await this.loadDynamicOptions(params);
|
|
2416
2689
|
const shown = options.map((option) => [
|
|
@@ -2471,8 +2744,8 @@ var FlowQuestionRenderer = class {
|
|
|
2471
2744
|
async loadDynamicOptions(params) {
|
|
2472
2745
|
const { node } = params;
|
|
2473
2746
|
const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
|
|
2474
|
-
if (!provider) throw new
|
|
2475
|
-
const pageSize =
|
|
2747
|
+
if (!provider) throw new import_meta_whatsapp_contracts14.FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
|
|
2748
|
+
const pageSize = import_meta_whatsapp_contracts14.WHATSAPP_CHOICE_LIMIT.LIST_ROWS - 1;
|
|
2476
2749
|
const result = await provider({
|
|
2477
2750
|
node,
|
|
2478
2751
|
session: params.session,
|
|
@@ -2519,6 +2792,51 @@ function readFlowInbound(message) {
|
|
|
2519
2792
|
}
|
|
2520
2793
|
__name(readFlowInbound, "readFlowInbound");
|
|
2521
2794
|
|
|
2795
|
+
// src/flows/matchGlobalKeyword.ts
|
|
2796
|
+
var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2797
|
+
function matchGlobalKeyword(text2, entries) {
|
|
2798
|
+
const normalized = (0, import_meta_whatsapp_contracts15.normalizeFlowText)(text2);
|
|
2799
|
+
if (normalized.length === 0) return void 0;
|
|
2800
|
+
const padded = ` ${normalized} `;
|
|
2801
|
+
let best;
|
|
2802
|
+
for (const entry of entries) {
|
|
2803
|
+
const isWordMatch = entry.match === "word";
|
|
2804
|
+
for (const keyword of entry.keywords) {
|
|
2805
|
+
const normalizedKeyword = (0, import_meta_whatsapp_contracts15.normalizeFlowText)(keyword);
|
|
2806
|
+
if (normalizedKeyword.length === 0) continue;
|
|
2807
|
+
const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
|
|
2808
|
+
if (isMatch && (!best || normalizedKeyword.length > best.length)) {
|
|
2809
|
+
best = {
|
|
2810
|
+
length: normalizedKeyword.length,
|
|
2811
|
+
target: entry.target
|
|
2812
|
+
};
|
|
2813
|
+
}
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
return best?.target;
|
|
2817
|
+
}
|
|
2818
|
+
__name(matchGlobalKeyword, "matchGlobalKeyword");
|
|
2819
|
+
|
|
2820
|
+
// src/flows/resolveFlowConfigText.ts
|
|
2821
|
+
async function resolveOne(text2, params) {
|
|
2822
|
+
if (typeof text2 !== "function") return text2;
|
|
2823
|
+
try {
|
|
2824
|
+
return await text2(params.context);
|
|
2825
|
+
} catch (error) {
|
|
2826
|
+
await params.onError?.(error);
|
|
2827
|
+
return void 0;
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
__name(resolveOne, "resolveOne");
|
|
2831
|
+
async function resolveFlowConfigText(params) {
|
|
2832
|
+
for (const text2 of params.chain) {
|
|
2833
|
+
const resolved = await resolveOne(text2, params);
|
|
2834
|
+
if (resolved !== void 0) return resolved;
|
|
2835
|
+
}
|
|
2836
|
+
return void 0;
|
|
2837
|
+
}
|
|
2838
|
+
__name(resolveFlowConfigText, "resolveFlowConfigText");
|
|
2839
|
+
|
|
2522
2840
|
// src/flows/FlowRunner.ts
|
|
2523
2841
|
function contactVariables(profileName) {
|
|
2524
2842
|
if (!profileName) return {};
|
|
@@ -2531,7 +2849,7 @@ __name(contactVariables, "contactVariables");
|
|
|
2531
2849
|
function resolveFlowTimeZone(config) {
|
|
2532
2850
|
const businessHours = config.handoff?.businessHours;
|
|
2533
2851
|
const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
|
|
2534
|
-
if (!timeZone) throw new
|
|
2852
|
+
if (!timeZone) throw new import_meta_whatsapp_contracts16.ConfigMissingError("features.flowRunner.timeZone");
|
|
2535
2853
|
new Intl.DateTimeFormat("en-US", {
|
|
2536
2854
|
timeZone
|
|
2537
2855
|
});
|
|
@@ -2636,7 +2954,7 @@ var FlowRunner = class {
|
|
|
2636
2954
|
const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
|
|
2637
2955
|
if (!graph) return "no-flow";
|
|
2638
2956
|
await this.claim(turn);
|
|
2639
|
-
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new
|
|
2957
|
+
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("flow-not-found", savedFlowKey));
|
|
2640
2958
|
const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
|
|
2641
2959
|
const context = {
|
|
2642
2960
|
...turn.session.context
|
|
@@ -2714,7 +3032,7 @@ var FlowRunner = class {
|
|
|
2714
3032
|
const { config } = this.dependencies;
|
|
2715
3033
|
return {
|
|
2716
3034
|
now: config.now?.() ?? /* @__PURE__ */ new Date(),
|
|
2717
|
-
locale: config.dateLocale ??
|
|
3035
|
+
locale: config.dateLocale ?? import_meta_whatsapp_contracts16.FLOW_DATE_LOCALE_PT_BR,
|
|
2718
3036
|
timeZone: this.timeZone
|
|
2719
3037
|
};
|
|
2720
3038
|
}
|
|
@@ -2722,8 +3040,7 @@ var FlowRunner = class {
|
|
|
2722
3040
|
return this.dependencies.flowGraphRepository.get(companyId, flowKey);
|
|
2723
3041
|
}
|
|
2724
3042
|
globalKeywordTarget(answer) {
|
|
2725
|
-
|
|
2726
|
-
return keywords.find((entry) => (0, import_meta_whatsapp_contracts12.matchesFlowKeyword)(answer, entry.keywords))?.target;
|
|
3043
|
+
return matchGlobalKeyword(answer, this.dependencies.config.globalKeywords ?? []);
|
|
2727
3044
|
}
|
|
2728
3045
|
keywordJumpAtStart(start, inbound) {
|
|
2729
3046
|
if (inbound.kind === "unsupported") return void 0;
|
|
@@ -2750,7 +3067,7 @@ var FlowRunner = class {
|
|
|
2750
3067
|
await this.handOff(turn, context);
|
|
2751
3068
|
return "handled";
|
|
2752
3069
|
}
|
|
2753
|
-
const flowKey = target === "restart" ? this.startFlowKey() : (0,
|
|
3070
|
+
const flowKey = target === "restart" ? this.startFlowKey() : (0, import_meta_whatsapp_contracts16.crossFlowKey)(target);
|
|
2754
3071
|
const graph = await this.loadGraph(turn.companyId, flowKey);
|
|
2755
3072
|
if (!graph) return "no-flow";
|
|
2756
3073
|
await this.claim(turn);
|
|
@@ -2768,8 +3085,13 @@ var FlowRunner = class {
|
|
|
2768
3085
|
const dynamic = runtime.dynamic?.nodeId === node.id ? runtime.dynamic : void 0;
|
|
2769
3086
|
const page = dynamic?.page ?? 0;
|
|
2770
3087
|
if (inbound.kind === "unsupported") {
|
|
2771
|
-
const text2 = this.
|
|
2772
|
-
|
|
3088
|
+
const text2 = await this.configText(turn, node, {
|
|
3089
|
+
chain: [
|
|
3090
|
+
this.dependencies.config.nonTextAnswerMessage
|
|
3091
|
+
],
|
|
3092
|
+
kind: "non-text-answer"
|
|
3093
|
+
});
|
|
3094
|
+
await this.say(turn, text2 ?? DEFAULT_FLOW_TEXT.NON_TEXT_ANSWER, context);
|
|
2773
3095
|
return this.awaitAnswer(turn, graph, node, context, page);
|
|
2774
3096
|
}
|
|
2775
3097
|
const decision = resolveFlowAnswer({
|
|
@@ -2780,6 +3102,9 @@ var FlowRunner = class {
|
|
|
2780
3102
|
clock: this.clock(),
|
|
2781
3103
|
...dynamic ? {
|
|
2782
3104
|
dynamicOptions: dynamic.options
|
|
3105
|
+
} : {},
|
|
3106
|
+
...isChoiceNode(node) ? {
|
|
3107
|
+
options: this.renderedOptions(turn, node, context)
|
|
2783
3108
|
} : {}
|
|
2784
3109
|
});
|
|
2785
3110
|
if (decision.kind === "jump") return this.jumpTo(turn, graph, decision.target, withRuntime(context, {}));
|
|
@@ -2793,7 +3118,16 @@ var FlowRunner = class {
|
|
|
2793
3118
|
enterInitialNode: false
|
|
2794
3119
|
});
|
|
2795
3120
|
}
|
|
2796
|
-
if (decision.kind === "invalid")
|
|
3121
|
+
if (decision.kind === "invalid") {
|
|
3122
|
+
return this.handleInvalid(turn, graph, node, context, {
|
|
3123
|
+
rejection: decision.rejection
|
|
3124
|
+
});
|
|
3125
|
+
}
|
|
3126
|
+
const hostRejection = await this.validateWithHost(turn, node, context, {
|
|
3127
|
+
answer: inbound.answer,
|
|
3128
|
+
value: decision.value
|
|
3129
|
+
});
|
|
3130
|
+
if (hostRejection) return this.handleInvalid(turn, graph, node, context, hostRejection);
|
|
2797
3131
|
await this.runFrom(turn, {
|
|
2798
3132
|
graph,
|
|
2799
3133
|
nodeId: node.id,
|
|
@@ -2805,11 +3139,68 @@ var FlowRunner = class {
|
|
|
2805
3139
|
enterInitialNode: false
|
|
2806
3140
|
});
|
|
2807
3141
|
}
|
|
3142
|
+
/** Títulos como o cliente os viu (`{{chave}}` resolvido): é contra eles que o texto digitado casa. */
|
|
3143
|
+
renderedOptions(turn, node, context) {
|
|
3144
|
+
const variables = {
|
|
3145
|
+
...context,
|
|
3146
|
+
...turn.baseVariables
|
|
3147
|
+
};
|
|
3148
|
+
return (node.options ?? []).map(([id, title]) => [
|
|
3149
|
+
id,
|
|
3150
|
+
this.renderer.interpolate(title, variables)
|
|
3151
|
+
]);
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* Validador do host, só para pergunta (escolha já casou com opção) e nunca para resposta pulada.
|
|
3155
|
+
* Falha do validador não pode prender o cliente na pergunta: reporta e aceita.
|
|
3156
|
+
*/
|
|
3157
|
+
async validateWithHost(turn, node, context, answer) {
|
|
3158
|
+
const validator = this.dependencies.config.validateAnswer;
|
|
3159
|
+
if (!validator || isChoiceNode(node) || node.type === "dynamic_choice" || answer.value === null) return void 0;
|
|
3160
|
+
try {
|
|
3161
|
+
const result = await validator({
|
|
3162
|
+
companyId: turn.companyId,
|
|
3163
|
+
session: turn.session,
|
|
3164
|
+
node,
|
|
3165
|
+
answer: answer.answer.trim(),
|
|
3166
|
+
value: answer.value ?? answer.answer,
|
|
3167
|
+
context
|
|
3168
|
+
});
|
|
3169
|
+
if (!result || result.isValid) return void 0;
|
|
3170
|
+
return {
|
|
3171
|
+
rejection: "rejected-by-host",
|
|
3172
|
+
...result.message ? {
|
|
3173
|
+
message: result.message
|
|
3174
|
+
} : {}
|
|
3175
|
+
};
|
|
3176
|
+
} catch (error) {
|
|
3177
|
+
await this.report(turn, turn.session.flowKey, node.id, "validate-answer", error);
|
|
3178
|
+
return void 0;
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
configText(turn, node, params) {
|
|
3182
|
+
return resolveFlowConfigText({
|
|
3183
|
+
chain: params.chain,
|
|
3184
|
+
context: {
|
|
3185
|
+
companyId: turn.companyId,
|
|
3186
|
+
whatsappNumber: turn.session.whatsappNumber,
|
|
3187
|
+
kind: params.kind,
|
|
3188
|
+
flowKey: turn.session.flowKey,
|
|
3189
|
+
...node ? {
|
|
3190
|
+
nodeId: node.id
|
|
3191
|
+
} : {},
|
|
3192
|
+
...params.rejection ? {
|
|
3193
|
+
rejection: params.rejection
|
|
3194
|
+
} : {}
|
|
3195
|
+
},
|
|
3196
|
+
onError: /* @__PURE__ */ __name((error) => this.report(turn, turn.session.flowKey, node?.id ?? null, "text", error), "onError")
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
2808
3199
|
followsDefaultWhenUnmatched(node) {
|
|
2809
3200
|
if (!isChoiceNode(node)) return false;
|
|
2810
3201
|
return (node.unmatchedChoice ?? this.dependencies.config.unmatchedChoice ?? "reask") === "default";
|
|
2811
3202
|
}
|
|
2812
|
-
async handleInvalid(turn, graph, node, context,
|
|
3203
|
+
async handleInvalid(turn, graph, node, context, invalid) {
|
|
2813
3204
|
const runtime = runtimeOf(context);
|
|
2814
3205
|
const attempts = (runtime.invalidAnswers ?? 0) + 1;
|
|
2815
3206
|
const limit = node.maxInvalidAnswers ?? this.dependencies.config.maxInvalidAnswers ?? DEFAULT_MAX_INVALID_ANSWERS;
|
|
@@ -2818,12 +3209,30 @@ var FlowRunner = class {
|
|
|
2818
3209
|
...runtime,
|
|
2819
3210
|
invalidAnswers: attempts
|
|
2820
3211
|
});
|
|
2821
|
-
await this.say(turn, this.fallbackText(node,
|
|
3212
|
+
await this.say(turn, await this.fallbackText(turn, node, invalid), updated);
|
|
2822
3213
|
await this.awaitAnswer(turn, graph, node, updated, runtime.dynamic?.nodeId === node.id ? runtime.dynamic.page : 0);
|
|
2823
3214
|
}
|
|
2824
|
-
|
|
3215
|
+
/** Precedência: texto do validador do host, `fallbackMessage` do nó, texto do motivo, padrão do host, do pacote. */
|
|
3216
|
+
async fallbackText(turn, node, invalid) {
|
|
2825
3217
|
const { config } = this.dependencies;
|
|
2826
|
-
|
|
3218
|
+
const fixed = invalid.message ?? node.fallbackMessage;
|
|
3219
|
+
if (fixed !== void 0) return fixed;
|
|
3220
|
+
const { rejection } = invalid;
|
|
3221
|
+
const byRejection = rejection ? await this.configText(turn, node, {
|
|
3222
|
+
chain: [
|
|
3223
|
+
config.rejectionMessages?.[rejection]
|
|
3224
|
+
],
|
|
3225
|
+
kind: "rejection",
|
|
3226
|
+
rejection
|
|
3227
|
+
}) : void 0;
|
|
3228
|
+
if (byRejection !== void 0) return byRejection;
|
|
3229
|
+
const fallback = await this.configText(turn, node, {
|
|
3230
|
+
chain: [
|
|
3231
|
+
config.defaultFallbackMessage
|
|
3232
|
+
],
|
|
3233
|
+
kind: "fallback"
|
|
3234
|
+
});
|
|
3235
|
+
return fallback ?? DEFAULT_FLOW_TEXT.FALLBACK;
|
|
2827
3236
|
}
|
|
2828
3237
|
async handOff(turn, context) {
|
|
2829
3238
|
const isWithinHours = await this.dependencies.handoff.request({
|
|
@@ -2844,8 +3253,8 @@ var FlowRunner = class {
|
|
|
2844
3253
|
});
|
|
2845
3254
|
}
|
|
2846
3255
|
async jumpTo(turn, graph, target, context) {
|
|
2847
|
-
if ((0,
|
|
2848
|
-
const targetGraph = await this.loadGraph(turn.companyId, (0,
|
|
3256
|
+
if ((0, import_meta_whatsapp_contracts16.isCrossFlowTarget)(target)) {
|
|
3257
|
+
const targetGraph = await this.loadGraph(turn.companyId, (0, import_meta_whatsapp_contracts16.crossFlowKey)(target));
|
|
2849
3258
|
if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
|
|
2850
3259
|
return this.runFrom(turn, {
|
|
2851
3260
|
graph: targetGraph,
|
|
@@ -2903,7 +3312,7 @@ var FlowRunner = class {
|
|
|
2903
3312
|
nodeId: null,
|
|
2904
3313
|
context: result.context
|
|
2905
3314
|
});
|
|
2906
|
-
return this.report(turn, params.graph.key, null, "max-steps", new
|
|
3315
|
+
return this.report(turn, params.graph.key, null, "max-steps", new import_meta_whatsapp_contracts16.FlowRunnerError("cycle", result.visited.join(" -> ")));
|
|
2907
3316
|
}
|
|
2908
3317
|
const target = await this.loadGraph(turn.companyId, result.flowKey);
|
|
2909
3318
|
if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
|
|
@@ -2919,7 +3328,7 @@ var FlowRunner = class {
|
|
|
2919
3328
|
nodeId: null,
|
|
2920
3329
|
context: params.context
|
|
2921
3330
|
});
|
|
2922
|
-
return this.report(turn, params.graph.key, null, "cross-flow", new
|
|
3331
|
+
return this.report(turn, params.graph.key, null, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("too-many-jumps", params.graph.key));
|
|
2923
3332
|
}
|
|
2924
3333
|
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
2925
3334
|
async awaitAnswer(turn, graph, node, context, page) {
|
|
@@ -2985,7 +3394,7 @@ var FlowRunner = class {
|
|
|
2985
3394
|
nodeId: null,
|
|
2986
3395
|
context
|
|
2987
3396
|
});
|
|
2988
|
-
await this.report(turn, fromFlowKey, null, "cross-flow", new
|
|
3397
|
+
await this.report(turn, fromFlowKey, null, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("flow-not-found", target));
|
|
2989
3398
|
}
|
|
2990
3399
|
/**
|
|
2991
3400
|
* Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
|
|
@@ -3008,7 +3417,7 @@ var FlowRunner = class {
|
|
|
3008
3417
|
};
|
|
3009
3418
|
|
|
3010
3419
|
// src/flows/FlowHandoff.ts
|
|
3011
|
-
var
|
|
3420
|
+
var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3012
3421
|
function readParam(node, key) {
|
|
3013
3422
|
const value = node?.actionParams?.[key];
|
|
3014
3423
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
@@ -3031,14 +3440,14 @@ var FlowHandoff = class {
|
|
|
3031
3440
|
whatsappNumber: params.whatsappNumber
|
|
3032
3441
|
});
|
|
3033
3442
|
} catch (error) {
|
|
3034
|
-
await this.reportFailure(error, params);
|
|
3443
|
+
await this.reportFailure(error, params, "handoff");
|
|
3035
3444
|
}
|
|
3036
3445
|
const isWithinHours = await this.isWithinHours(params.companyId);
|
|
3037
|
-
const template = this.messageFor(isWithinHours, params
|
|
3446
|
+
const template = await this.messageFor(isWithinHours, params);
|
|
3038
3447
|
await sendMessage.sendText({
|
|
3039
3448
|
companyId: params.companyId,
|
|
3040
3449
|
whatsappNumber: params.whatsappNumber,
|
|
3041
|
-
body: (0,
|
|
3450
|
+
body: (0, import_meta_whatsapp_contracts17.interpolateFlowText)(template, params.variables, interpolation),
|
|
3042
3451
|
sender: "bot",
|
|
3043
3452
|
startState
|
|
3044
3453
|
});
|
|
@@ -3066,14 +3475,14 @@ var FlowHandoff = class {
|
|
|
3066
3475
|
};
|
|
3067
3476
|
};
|
|
3068
3477
|
}
|
|
3069
|
-
async reportFailure(error, params) {
|
|
3478
|
+
async reportFailure(error, params, stage) {
|
|
3070
3479
|
try {
|
|
3071
3480
|
await this.dependencies.hooks?.onFlowRunnerError?.(error, {
|
|
3072
3481
|
companyId: params.companyId,
|
|
3073
3482
|
whatsappNumber: params.whatsappNumber,
|
|
3074
3483
|
flowKey: null,
|
|
3075
3484
|
nodeId: params.node?.id ?? null,
|
|
3076
|
-
stage
|
|
3485
|
+
stage
|
|
3077
3486
|
});
|
|
3078
3487
|
} catch {
|
|
3079
3488
|
}
|
|
@@ -3081,18 +3490,40 @@ var FlowHandoff = class {
|
|
|
3081
3490
|
async isWithinHours(companyId) {
|
|
3082
3491
|
const source = this.dependencies.config.businessHours;
|
|
3083
3492
|
const hours = typeof source === "function" ? await source(companyId) : source;
|
|
3084
|
-
return hours ? (0,
|
|
3493
|
+
return hours ? (0, import_meta_whatsapp_contracts17.isWithinBusinessHours)(hours, this.dependencies.now()) : true;
|
|
3085
3494
|
}
|
|
3086
|
-
messageFor(isWithinHours,
|
|
3495
|
+
async messageFor(isWithinHours, params) {
|
|
3087
3496
|
const { config } = this.dependencies;
|
|
3088
|
-
const
|
|
3089
|
-
|
|
3090
|
-
|
|
3497
|
+
const { node } = params;
|
|
3498
|
+
const chain = isWithinHours ? [
|
|
3499
|
+
readParam(node, "message"),
|
|
3500
|
+
config.message,
|
|
3501
|
+
DEFAULT_FLOW_TEXT.HANDOFF
|
|
3502
|
+
] : [
|
|
3503
|
+
readParam(node, "outOfHoursMessage"),
|
|
3504
|
+
config.outOfHoursMessage,
|
|
3505
|
+
readParam(node, "message"),
|
|
3506
|
+
config.message,
|
|
3507
|
+
DEFAULT_FLOW_TEXT.HANDOFF_OUT_OF_HOURS
|
|
3508
|
+
];
|
|
3509
|
+
const text2 = await resolveFlowConfigText({
|
|
3510
|
+
chain,
|
|
3511
|
+
context: {
|
|
3512
|
+
companyId: params.companyId,
|
|
3513
|
+
whatsappNumber: params.whatsappNumber,
|
|
3514
|
+
kind: isWithinHours ? "handoff" : "handoff-out-of-hours",
|
|
3515
|
+
...node ? {
|
|
3516
|
+
nodeId: node.id
|
|
3517
|
+
} : {}
|
|
3518
|
+
},
|
|
3519
|
+
onError: /* @__PURE__ */ __name((error) => this.reportFailure(error, params, "text"), "onError")
|
|
3520
|
+
});
|
|
3521
|
+
return text2 ?? DEFAULT_FLOW_TEXT.HANDOFF;
|
|
3091
3522
|
}
|
|
3092
3523
|
};
|
|
3093
3524
|
|
|
3094
3525
|
// src/flows/flowTurnLock.ts
|
|
3095
|
-
var
|
|
3526
|
+
var import_drizzle_orm8 = require("drizzle-orm");
|
|
3096
3527
|
function lockName(key) {
|
|
3097
3528
|
return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
|
|
3098
3529
|
}
|
|
@@ -3107,7 +3538,7 @@ var PostgresAdvisoryFlowTurnLock = class {
|
|
|
3107
3538
|
}
|
|
3108
3539
|
withLock(key, work) {
|
|
3109
3540
|
return this.db.transaction(async (transaction) => {
|
|
3110
|
-
await transaction.execute(
|
|
3541
|
+
await transaction.execute(import_drizzle_orm8.sql`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
|
|
3111
3542
|
return work();
|
|
3112
3543
|
});
|
|
3113
3544
|
}
|
|
@@ -3295,7 +3726,7 @@ async function listAvailableProducts(params) {
|
|
|
3295
3726
|
__name(listAvailableProducts, "listAvailableProducts");
|
|
3296
3727
|
|
|
3297
3728
|
// src/repositories/FlowMediaRepository.ts
|
|
3298
|
-
var
|
|
3729
|
+
var import_drizzle_orm9 = require("drizzle-orm");
|
|
3299
3730
|
var FlowMediaRepository = class {
|
|
3300
3731
|
static {
|
|
3301
3732
|
__name(this, "FlowMediaRepository");
|
|
@@ -3305,18 +3736,18 @@ var FlowMediaRepository = class {
|
|
|
3305
3736
|
this.db = db;
|
|
3306
3737
|
}
|
|
3307
3738
|
locationFilter(location) {
|
|
3308
|
-
return (0,
|
|
3739
|
+
return (0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(flowMedia.companyId, location.companyId), (0, import_drizzle_orm9.eq)(flowMedia.flowKey, location.flowKey), (0, import_drizzle_orm9.eq)(flowMedia.nodeId, location.nodeId));
|
|
3309
3740
|
}
|
|
3310
3741
|
// O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
|
|
3311
3742
|
// é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
|
|
3312
3743
|
// justamente o material que alguém desligou.
|
|
3313
3744
|
async listActive(location) {
|
|
3314
|
-
return this.db.select().from(flowMedia).where((0,
|
|
3745
|
+
return this.db.select().from(flowMedia).where((0, import_drizzle_orm9.and)(this.locationFilter(location), (0, import_drizzle_orm9.eq)(flowMedia.active, true))).orderBy((0, import_drizzle_orm9.asc)(flowMedia.sortOrder), (0, import_drizzle_orm9.asc)(flowMedia.createdAt));
|
|
3315
3746
|
}
|
|
3316
3747
|
// Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
|
|
3317
3748
|
// poder ser religado.
|
|
3318
3749
|
async listAll(location) {
|
|
3319
|
-
return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0,
|
|
3750
|
+
return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0, import_drizzle_orm9.asc)(flowMedia.sortOrder), (0, import_drizzle_orm9.asc)(flowMedia.createdAt));
|
|
3320
3751
|
}
|
|
3321
3752
|
/**
|
|
3322
3753
|
* Anexa um arquivo já existente no storage ao nó.
|
|
@@ -3347,7 +3778,7 @@ var FlowMediaRepository = class {
|
|
|
3347
3778
|
caption: params.caption ?? null,
|
|
3348
3779
|
sortOrder: params.sortOrder ?? 0,
|
|
3349
3780
|
active: true,
|
|
3350
|
-
updatedAt:
|
|
3781
|
+
updatedAt: import_drizzle_orm9.sql`now()`
|
|
3351
3782
|
}
|
|
3352
3783
|
}).returning();
|
|
3353
3784
|
return row;
|
|
@@ -3363,8 +3794,8 @@ var FlowMediaRepository = class {
|
|
|
3363
3794
|
...params.active !== void 0 ? {
|
|
3364
3795
|
active: params.active
|
|
3365
3796
|
} : {},
|
|
3366
|
-
updatedAt:
|
|
3367
|
-
}).where((0,
|
|
3797
|
+
updatedAt: import_drizzle_orm9.sql`now()`
|
|
3798
|
+
}).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm9.eq)(flowMedia.id, params.id))).returning();
|
|
3368
3799
|
return row;
|
|
3369
3800
|
}
|
|
3370
3801
|
/**
|
|
@@ -3373,17 +3804,17 @@ var FlowMediaRepository = class {
|
|
|
3373
3804
|
* host, que é dono da biblioteca de arquivos.
|
|
3374
3805
|
*/
|
|
3375
3806
|
async detach(params) {
|
|
3376
|
-
await this.db.delete(flowMedia).where((0,
|
|
3807
|
+
await this.db.delete(flowMedia).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm9.eq)(flowMedia.id, params.id)));
|
|
3377
3808
|
}
|
|
3378
3809
|
// Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
|
|
3379
3810
|
async detachRemovedNodes(params) {
|
|
3380
|
-
const condition = params.existingNodeIds.length === 0 ? void 0 :
|
|
3381
|
-
await this.db.delete(flowMedia).where((0,
|
|
3811
|
+
const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm9.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
|
|
3812
|
+
await this.db.delete(flowMedia).where((0, import_drizzle_orm9.and)((0, import_drizzle_orm9.eq)(flowMedia.companyId, params.companyId), (0, import_drizzle_orm9.eq)(flowMedia.flowKey, params.flowKey), condition));
|
|
3382
3813
|
}
|
|
3383
3814
|
};
|
|
3384
3815
|
|
|
3385
3816
|
// src/repositories/FlowMediaIdRepository.ts
|
|
3386
|
-
var
|
|
3817
|
+
var import_drizzle_orm10 = require("drizzle-orm");
|
|
3387
3818
|
var FlowMediaIdRepository = class {
|
|
3388
3819
|
static {
|
|
3389
3820
|
__name(this, "FlowMediaIdRepository");
|
|
@@ -3395,7 +3826,7 @@ var FlowMediaIdRepository = class {
|
|
|
3395
3826
|
async get(params) {
|
|
3396
3827
|
const rows = await this.db.select({
|
|
3397
3828
|
ids: flowMedia.metaMediaIds
|
|
3398
|
-
}).from(flowMedia).where((0,
|
|
3829
|
+
}).from(flowMedia).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId)).limit(1);
|
|
3399
3830
|
return rows[0]?.ids?.[params.senderKey];
|
|
3400
3831
|
}
|
|
3401
3832
|
/**
|
|
@@ -3407,23 +3838,23 @@ var FlowMediaIdRepository = class {
|
|
|
3407
3838
|
*/
|
|
3408
3839
|
async set(params) {
|
|
3409
3840
|
await this.db.update(flowMedia).set({
|
|
3410
|
-
metaMediaIds:
|
|
3411
|
-
}).where((0,
|
|
3841
|
+
metaMediaIds: import_drizzle_orm10.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
|
|
3842
|
+
}).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId));
|
|
3412
3843
|
}
|
|
3413
3844
|
/** Remove só a chave deste número — o id do outro número continua válido. */
|
|
3414
3845
|
async clear(params) {
|
|
3415
3846
|
await this.db.update(flowMedia).set({
|
|
3416
|
-
metaMediaIds:
|
|
3417
|
-
}).where((0,
|
|
3847
|
+
metaMediaIds: import_drizzle_orm10.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
|
|
3848
|
+
}).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId));
|
|
3418
3849
|
}
|
|
3419
3850
|
};
|
|
3420
3851
|
|
|
3421
3852
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3422
3853
|
var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
|
|
3423
|
-
var
|
|
3854
|
+
var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3424
3855
|
|
|
3425
3856
|
// src/channel/previewMedia.ts
|
|
3426
|
-
var
|
|
3857
|
+
var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3427
3858
|
|
|
3428
3859
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3429
3860
|
var WhatsAppChannelAdapter = class {
|
|
@@ -3440,14 +3871,14 @@ var WhatsAppChannelAdapter = class {
|
|
|
3440
3871
|
}
|
|
3441
3872
|
/** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
|
|
3442
3873
|
previewMessageId(to) {
|
|
3443
|
-
if (!this.previewContacts?.isEnabled || !(0,
|
|
3874
|
+
if (!this.previewContacts?.isEnabled || !(0, import_meta_whatsapp_contracts19.isPreviewContact)(to)) return void 0;
|
|
3444
3875
|
return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
|
|
3445
3876
|
}
|
|
3446
3877
|
async translateErrors(operation) {
|
|
3447
3878
|
try {
|
|
3448
3879
|
return await operation();
|
|
3449
3880
|
} catch (error) {
|
|
3450
|
-
if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new
|
|
3881
|
+
if (error instanceof import_meta_graph_core2.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts19.WindowExpiredError();
|
|
3451
3882
|
throw error;
|
|
3452
3883
|
}
|
|
3453
3884
|
}
|
|
@@ -3550,7 +3981,7 @@ var WhatsAppChannelAdapter = class {
|
|
|
3550
3981
|
* tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
|
|
3551
3982
|
*/
|
|
3552
3983
|
async fetchMediaAsBase64(mediaId) {
|
|
3553
|
-
const uploadId = this.previewMedia?.isEnabled ? (0,
|
|
3984
|
+
const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts18.resolvePreviewUploadId)(mediaId) : void 0;
|
|
3554
3985
|
if (uploadId) {
|
|
3555
3986
|
const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
|
|
3556
3987
|
return {
|
|
@@ -3563,19 +3994,19 @@ var WhatsAppChannelAdapter = class {
|
|
|
3563
3994
|
};
|
|
3564
3995
|
|
|
3565
3996
|
// src/channel/ReceiveWebhook.use-case.ts
|
|
3566
|
-
var
|
|
3997
|
+
var import_meta_whatsapp_contracts22 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3567
3998
|
|
|
3568
3999
|
// src/channel/webhookSecurity.ts
|
|
3569
4000
|
var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
|
|
3570
|
-
var
|
|
4001
|
+
var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3571
4002
|
var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
|
|
3572
4003
|
function verifyWebhookChallenge(params) {
|
|
3573
|
-
if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new
|
|
4004
|
+
if (!(0, import_meta_graph_core3.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
3574
4005
|
return params.challenge;
|
|
3575
4006
|
}
|
|
3576
4007
|
__name(verifyWebhookChallenge, "verifyWebhookChallenge");
|
|
3577
4008
|
function verifyWebhookSignature(params) {
|
|
3578
|
-
if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new
|
|
4009
|
+
if (!(0, import_meta_graph_core3.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
3579
4010
|
}
|
|
3580
4011
|
__name(verifyWebhookSignature, "verifyWebhookSignature");
|
|
3581
4012
|
function deliveryKey(signatureHeader) {
|
|
@@ -3595,10 +4026,10 @@ async function confirmWebhookDelivery(params) {
|
|
|
3595
4026
|
__name(confirmWebhookDelivery, "confirmWebhookDelivery");
|
|
3596
4027
|
|
|
3597
4028
|
// src/channel/IngestInboundMedia.use-case.ts
|
|
3598
|
-
var
|
|
4029
|
+
var import_drizzle_orm11 = require("drizzle-orm");
|
|
3599
4030
|
|
|
3600
4031
|
// src/use-cases/TranscribeAudio.use-case.ts
|
|
3601
|
-
var
|
|
4032
|
+
var import_meta_whatsapp_contracts21 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3602
4033
|
|
|
3603
4034
|
// src/transcription.types.ts
|
|
3604
4035
|
var TRANSCRIPTION_STATUS = {
|
|
@@ -3659,7 +4090,7 @@ var TranscribeAudioUseCase = class {
|
|
|
3659
4090
|
}
|
|
3660
4091
|
if (this.dependencies.resolvePolicy) {
|
|
3661
4092
|
const policy = await this.dependencies.resolvePolicy(params.companyId);
|
|
3662
|
-
if (!policy.isEnabled) throw new
|
|
4093
|
+
if (!policy.isEnabled) throw new import_meta_whatsapp_contracts21.TranscriptionDisabledError();
|
|
3663
4094
|
}
|
|
3664
4095
|
const audio = extractAudioReference(message);
|
|
3665
4096
|
const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
|
|
@@ -3736,11 +4167,11 @@ function extractAudioReference(message) {
|
|
|
3736
4167
|
const audio = payload["audio"];
|
|
3737
4168
|
const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
|
|
3738
4169
|
if (!isAudioMimeType(mimeType) && !audio) {
|
|
3739
|
-
throw new
|
|
4170
|
+
throw new import_meta_whatsapp_contracts21.MessageNotAudioError(message.id, message.type);
|
|
3740
4171
|
}
|
|
3741
4172
|
const uploadId = payload["uploadId"];
|
|
3742
4173
|
if (typeof uploadId !== "string" || uploadId.length === 0) {
|
|
3743
|
-
throw new
|
|
4174
|
+
throw new import_meta_whatsapp_contracts21.AudioNotIngestedError(message.id);
|
|
3744
4175
|
}
|
|
3745
4176
|
return {
|
|
3746
4177
|
uploadId,
|
|
@@ -3767,7 +4198,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3767
4198
|
this.transcription = transcription;
|
|
3768
4199
|
}
|
|
3769
4200
|
async execute(params) {
|
|
3770
|
-
const [message] = await this.db.select().from(messages).where((0,
|
|
4201
|
+
const [message] = await this.db.select().from(messages).where((0, import_drizzle_orm11.and)((0, import_drizzle_orm11.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm11.eq)(messages.id, params.messageId))).limit(1);
|
|
3771
4202
|
if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
|
|
3772
4203
|
const payload = message.payload ?? {};
|
|
3773
4204
|
if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
|
|
@@ -3798,7 +4229,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3798
4229
|
};
|
|
3799
4230
|
await this.db.update(messages).set({
|
|
3800
4231
|
payload: updatedPayload
|
|
3801
|
-
}).where((0,
|
|
4232
|
+
}).where((0, import_drizzle_orm11.and)((0, import_drizzle_orm11.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm11.eq)(messages.id, params.messageId)));
|
|
3802
4233
|
await this.documentRepository?.link({
|
|
3803
4234
|
companyId: params.companyId,
|
|
3804
4235
|
sessionId: message.sessionId,
|
|
@@ -3956,8 +4387,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
|
|
|
3956
4387
|
}
|
|
3957
4388
|
__name(extractPayload, "extractPayload");
|
|
3958
4389
|
var ACCOUNT_EVENT_FIELDS = [
|
|
3959
|
-
|
|
3960
|
-
|
|
4390
|
+
import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
|
|
4391
|
+
import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
|
|
3961
4392
|
];
|
|
3962
4393
|
function isAccountEventField(field) {
|
|
3963
4394
|
return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
|
|
@@ -3999,7 +4430,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
3999
4430
|
...EMPTY_RESULT
|
|
4000
4431
|
};
|
|
4001
4432
|
const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
|
|
4002
|
-
const parsed =
|
|
4433
|
+
const parsed = import_meta_whatsapp_contracts22.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
|
|
4003
4434
|
if (!parsed.success) {
|
|
4004
4435
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4005
4436
|
field: void 0,
|
|
@@ -4032,7 +4463,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4032
4463
|
continue;
|
|
4033
4464
|
}
|
|
4034
4465
|
for (const message of change.value.messages ?? []) {
|
|
4035
|
-
const profileName = (0,
|
|
4466
|
+
const profileName = (0, import_meta_whatsapp_contracts22.resolveContactProfileName)({
|
|
4036
4467
|
contacts: change.value.contacts,
|
|
4037
4468
|
from: message.from
|
|
4038
4469
|
});
|
|
@@ -4070,8 +4501,8 @@ var ReceiveWebhookUseCase = class {
|
|
|
4070
4501
|
// Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
|
|
4071
4502
|
// tratado. O host é avisado nos dois casos, mas com `reason` diferente.
|
|
4072
4503
|
async handleAccountEvent(change) {
|
|
4073
|
-
if (change.field ===
|
|
4074
|
-
const update =
|
|
4504
|
+
if (change.field === import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
|
|
4505
|
+
const update = import_meta_whatsapp_contracts22.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
|
|
4075
4506
|
if (!update.success) {
|
|
4076
4507
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4077
4508
|
field: change.field,
|
|
@@ -4083,7 +4514,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4083
4514
|
await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
|
|
4084
4515
|
return true;
|
|
4085
4516
|
}
|
|
4086
|
-
const quality =
|
|
4517
|
+
const quality = import_meta_whatsapp_contracts22.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
|
|
4087
4518
|
if (!quality.success) {
|
|
4088
4519
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4089
4520
|
field: change.field,
|
|
@@ -4145,6 +4576,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4145
4576
|
});
|
|
4146
4577
|
if (!updated) return;
|
|
4147
4578
|
this.params.realtime?.emit(`conv:${updated.whatsappNumber}`, "message-status", {
|
|
4579
|
+
companyId,
|
|
4148
4580
|
waMessageId: status.id,
|
|
4149
4581
|
status: status.status
|
|
4150
4582
|
});
|
|
@@ -4214,7 +4646,7 @@ var StorePreviewMediaUseCase = class {
|
|
|
4214
4646
|
key
|
|
4215
4647
|
});
|
|
4216
4648
|
return {
|
|
4217
|
-
mediaId: (0,
|
|
4649
|
+
mediaId: (0, import_meta_whatsapp_contracts18.toPreviewMediaId)(uploadId),
|
|
4218
4650
|
uploadId
|
|
4219
4651
|
};
|
|
4220
4652
|
}
|
|
@@ -4246,6 +4678,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4246
4678
|
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;
|
|
4247
4679
|
const flowGraphRepository = new FlowGraphRepository(db, flowGraphCache);
|
|
4248
4680
|
const documentRepository = new DocumentRepository(db);
|
|
4681
|
+
const quickReplyRepository = new QuickReplyRepository(db);
|
|
4249
4682
|
const flowMediaRepository = new FlowMediaRepository(db);
|
|
4250
4683
|
const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
|
|
4251
4684
|
const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
|
|
@@ -4281,7 +4714,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4281
4714
|
} : {}
|
|
4282
4715
|
}) : void 0;
|
|
4283
4716
|
if (flowInterpreter && flowRunner && flowHandoff) {
|
|
4284
|
-
flowInterpreter.registerFlowAction(
|
|
4717
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
|
|
4285
4718
|
}
|
|
4286
4719
|
const receiveWebhook = new ReceiveWebhookUseCase({
|
|
4287
4720
|
appSecret: config.appSecret,
|
|
@@ -4302,7 +4735,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4302
4735
|
} : {}
|
|
4303
4736
|
});
|
|
4304
4737
|
if (flowInterpreter && providers.objectStorage?.getObject) {
|
|
4305
|
-
flowInterpreter.registerFlowAction(
|
|
4738
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
|
|
4306
4739
|
flowMediaRepository,
|
|
4307
4740
|
objectStorage: providers.objectStorage,
|
|
4308
4741
|
logMessage,
|
|
@@ -4319,7 +4752,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4319
4752
|
}));
|
|
4320
4753
|
}
|
|
4321
4754
|
if (flowInterpreter && providers.catalog && config.catalogId) {
|
|
4322
|
-
flowInterpreter.registerFlowAction(
|
|
4755
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
|
|
4323
4756
|
catalog: providers.catalog,
|
|
4324
4757
|
catalogId: config.catalogId,
|
|
4325
4758
|
logMessage,
|
|
@@ -4403,6 +4836,18 @@ function createMetaWhatsAppModule(params) {
|
|
|
4403
4836
|
} : void 0,
|
|
4404
4837
|
settings: settingsRepository,
|
|
4405
4838
|
/**
|
|
4839
|
+
* Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
|
|
4840
|
+
* `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
|
|
4841
|
+
* casos de uso daqui.
|
|
4842
|
+
*/
|
|
4843
|
+
quickReplies: {
|
|
4844
|
+
list: new ListQuickRepliesUseCase(quickReplyRepository),
|
|
4845
|
+
create: new CreateQuickReplyUseCase(quickReplyRepository),
|
|
4846
|
+
update: new UpdateQuickReplyUseCase(quickReplyRepository),
|
|
4847
|
+
delete: new DeleteQuickReplyUseCase(quickReplyRepository),
|
|
4848
|
+
repository: quickReplyRepository
|
|
4849
|
+
},
|
|
4850
|
+
/**
|
|
4406
4851
|
* `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
|
|
4407
4852
|
* ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
|
|
4408
4853
|
*/
|
|
@@ -4448,13 +4893,14 @@ function createMetaWhatsAppModule(params) {
|
|
|
4448
4893
|
// undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
|
|
4449
4894
|
runner: flowRunner,
|
|
4450
4895
|
registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
|
|
4451
|
-
if (!flowRunner) throw new
|
|
4896
|
+
if (!flowRunner) throw new import_meta_whatsapp_contracts23.ConfigMissingError("features.flowRunner");
|
|
4452
4897
|
flowRunner.registerDynamicChoiceProvider(key, provider);
|
|
4453
4898
|
}, "registerDynamicChoiceProvider"),
|
|
4454
4899
|
get: new GetFlowGraphUseCase(flowGraphRepository),
|
|
4455
4900
|
list: new ListFlowGraphsUseCase(flowGraphRepository),
|
|
4456
4901
|
create: new CreateFlowGraphUseCase(flowGraphRepository),
|
|
4457
4902
|
save: new SaveFlowGraphUseCase(flowGraphRepository),
|
|
4903
|
+
reseed: new ReseedFlowGraphUseCase(flowGraphRepository),
|
|
4458
4904
|
delete: new DeleteFlowGraphUseCase(flowGraphRepository),
|
|
4459
4905
|
livePositions: new GetLiveFlowPositionsUseCase(flowGraphRepository),
|
|
4460
4906
|
repository: flowGraphRepository,
|
|
@@ -4572,18 +5018,149 @@ async function redeemSseTicket(store, ticket) {
|
|
|
4572
5018
|
return JSON.parse(raw);
|
|
4573
5019
|
}
|
|
4574
5020
|
__name(redeemSseTicket, "redeemSseTicket");
|
|
5021
|
+
|
|
5022
|
+
// src/http/quickReplyRoutes.ts
|
|
5023
|
+
var import_meta_whatsapp_contracts24 = require("@adatechnology/meta-whatsapp-contracts");
|
|
5024
|
+
var import_module_http = require("@adatechnology/module-http");
|
|
5025
|
+
|
|
5026
|
+
// src/http/quickReplyScope.constant.ts
|
|
5027
|
+
var QUICK_REPLY_SCOPE = {
|
|
5028
|
+
WRITE: "quick-replies:write"
|
|
5029
|
+
};
|
|
5030
|
+
var DEFAULT_QUICK_REPLY_WRITE_SCOPES = [
|
|
5031
|
+
QUICK_REPLY_SCOPE.WRITE
|
|
5032
|
+
];
|
|
5033
|
+
|
|
5034
|
+
// src/http/quickReplyRoutes.ts
|
|
5035
|
+
function requireCompany(context) {
|
|
5036
|
+
if (!context.auth?.companyId) {
|
|
5037
|
+
throw new import_meta_whatsapp_contracts24.MetaWhatsAppError("Rota exige contexto autenticado.", 401, import_meta_whatsapp_contracts24.META_WHATSAPP_ERROR_CODES.CONFIG_MISSING);
|
|
5038
|
+
}
|
|
5039
|
+
return context.auth.companyId;
|
|
5040
|
+
}
|
|
5041
|
+
__name(requireCompany, "requireCompany");
|
|
5042
|
+
function requireId(context) {
|
|
5043
|
+
const id = context.params.id;
|
|
5044
|
+
if (!id) throw new import_meta_whatsapp_contracts24.QuickReplyNotFoundError("");
|
|
5045
|
+
return id;
|
|
5046
|
+
}
|
|
5047
|
+
__name(requireId, "requireId");
|
|
5048
|
+
function createMetaWhatsAppQuickReplyRoutes(params) {
|
|
5049
|
+
const { list, create, update, delete: remove } = params.module.quickReplies;
|
|
5050
|
+
const write = {
|
|
5051
|
+
scope: import_module_http.ROUTE_SCOPE.ADMIN,
|
|
5052
|
+
requiredScopes: params.scopes?.write ?? DEFAULT_QUICK_REPLY_WRITE_SCOPES
|
|
5053
|
+
};
|
|
5054
|
+
const read = {
|
|
5055
|
+
scope: import_module_http.ROUTE_SCOPE.USER,
|
|
5056
|
+
...params.scopes?.read?.length ? {
|
|
5057
|
+
requiredScopes: params.scopes.read
|
|
5058
|
+
} : {}
|
|
5059
|
+
};
|
|
5060
|
+
const routes = [
|
|
5061
|
+
{
|
|
5062
|
+
...read,
|
|
5063
|
+
method: import_module_http.HTTP_METHOD.GET,
|
|
5064
|
+
path: "/quick-replies",
|
|
5065
|
+
querySchema: import_meta_whatsapp_contracts24.listWhatsAppQuickRepliesQuerySchema,
|
|
5066
|
+
operationId: "listWhatsAppQuickReplies",
|
|
5067
|
+
summary: "Lista as respostas r\xE1pidas da empresa, na ordem de exibi\xE7\xE3o",
|
|
5068
|
+
async handler(context) {
|
|
5069
|
+
const query = context.query;
|
|
5070
|
+
const data = await list.execute({
|
|
5071
|
+
companyId: requireCompany(context),
|
|
5072
|
+
...query
|
|
5073
|
+
});
|
|
5074
|
+
return {
|
|
5075
|
+
kind: "json",
|
|
5076
|
+
status: 200,
|
|
5077
|
+
body: {
|
|
5078
|
+
data
|
|
5079
|
+
}
|
|
5080
|
+
};
|
|
5081
|
+
}
|
|
5082
|
+
},
|
|
5083
|
+
{
|
|
5084
|
+
...write,
|
|
5085
|
+
method: import_module_http.HTTP_METHOD.POST,
|
|
5086
|
+
path: "/quick-replies",
|
|
5087
|
+
bodySchema: import_meta_whatsapp_contracts24.whatsAppQuickReplyInputSchema,
|
|
5088
|
+
operationId: "createWhatsAppQuickReply",
|
|
5089
|
+
summary: "Cria uma resposta r\xE1pida (atalho \xFAnico por empresa)",
|
|
5090
|
+
async handler(context) {
|
|
5091
|
+
const input = context.body;
|
|
5092
|
+
const data = await create.execute({
|
|
5093
|
+
...input,
|
|
5094
|
+
companyId: requireCompany(context)
|
|
5095
|
+
});
|
|
5096
|
+
return {
|
|
5097
|
+
kind: "json",
|
|
5098
|
+
status: 201,
|
|
5099
|
+
body: {
|
|
5100
|
+
data
|
|
5101
|
+
}
|
|
5102
|
+
};
|
|
5103
|
+
}
|
|
5104
|
+
},
|
|
5105
|
+
{
|
|
5106
|
+
...write,
|
|
5107
|
+
method: import_module_http.HTTP_METHOD.PUT,
|
|
5108
|
+
path: "/quick-replies/:id",
|
|
5109
|
+
bodySchema: import_meta_whatsapp_contracts24.whatsAppQuickReplyInputSchema,
|
|
5110
|
+
operationId: "updateWhatsAppQuickReply",
|
|
5111
|
+
summary: "Substitui t\xEDtulo, atalho e texto de uma resposta r\xE1pida",
|
|
5112
|
+
async handler(context) {
|
|
5113
|
+
const input = context.body;
|
|
5114
|
+
const data = await update.execute({
|
|
5115
|
+
...input,
|
|
5116
|
+
companyId: requireCompany(context),
|
|
5117
|
+
id: requireId(context)
|
|
5118
|
+
});
|
|
5119
|
+
return {
|
|
5120
|
+
kind: "json",
|
|
5121
|
+
status: 200,
|
|
5122
|
+
body: {
|
|
5123
|
+
data
|
|
5124
|
+
}
|
|
5125
|
+
};
|
|
5126
|
+
}
|
|
5127
|
+
},
|
|
5128
|
+
{
|
|
5129
|
+
...write,
|
|
5130
|
+
method: import_module_http.HTTP_METHOD.DELETE,
|
|
5131
|
+
path: "/quick-replies/:id",
|
|
5132
|
+
operationId: "deleteWhatsAppQuickReply",
|
|
5133
|
+
summary: "Apaga uma resposta r\xE1pida",
|
|
5134
|
+
async handler(context) {
|
|
5135
|
+
await remove.execute({
|
|
5136
|
+
companyId: requireCompany(context),
|
|
5137
|
+
id: requireId(context)
|
|
5138
|
+
});
|
|
5139
|
+
return {
|
|
5140
|
+
kind: "empty",
|
|
5141
|
+
status: 204
|
|
5142
|
+
};
|
|
5143
|
+
}
|
|
5144
|
+
}
|
|
5145
|
+
];
|
|
5146
|
+
return routes;
|
|
5147
|
+
}
|
|
5148
|
+
__name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes");
|
|
4575
5149
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4576
5150
|
0 && (module.exports = {
|
|
4577
5151
|
CountInboundLocationsUseCase,
|
|
4578
5152
|
CreateFlowGraphUseCase,
|
|
5153
|
+
CreateQuickReplyUseCase,
|
|
4579
5154
|
DEFAULT_FALLBACK_LIST_LABEL,
|
|
4580
5155
|
DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
|
|
4581
5156
|
DEFAULT_FLOW_TEXT,
|
|
4582
5157
|
DEFAULT_MAX_INVALID_ANSWERS,
|
|
5158
|
+
DEFAULT_QUICK_REPLY_WRITE_SCOPES,
|
|
4583
5159
|
DEFAULT_START_FLOW_KEY,
|
|
4584
5160
|
DYNAMIC_CHOICE_MORE_ID,
|
|
4585
5161
|
DeleteConversationUseCase,
|
|
4586
5162
|
DeleteFlowGraphUseCase,
|
|
5163
|
+
DeleteQuickReplyUseCase,
|
|
4587
5164
|
DocumentRepository,
|
|
4588
5165
|
ExportConversationUseCase,
|
|
4589
5166
|
FLOW_RUNTIME_CONTEXT_KEY,
|
|
@@ -4606,6 +5183,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4606
5183
|
ListConversationsUseCase,
|
|
4607
5184
|
ListFlowGraphsUseCase,
|
|
4608
5185
|
ListMessagesUseCase,
|
|
5186
|
+
ListQuickRepliesUseCase,
|
|
4609
5187
|
LogMessageUseCase,
|
|
4610
5188
|
META_WHATSAPP_MIGRATIONS_TABLE,
|
|
4611
5189
|
MessageRepository,
|
|
@@ -4615,10 +5193,13 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4615
5193
|
PostgresAdvisoryFlowTurnLock,
|
|
4616
5194
|
ProcessInboundDispatchUseCase,
|
|
4617
5195
|
PurgeExpiredDocumentsUseCase,
|
|
5196
|
+
QUICK_REPLY_SCOPE,
|
|
5197
|
+
QuickReplyRepository,
|
|
4618
5198
|
ReceiveWebhookUseCase,
|
|
4619
5199
|
RedactInboundLocationsUseCase,
|
|
4620
5200
|
ReleaseConversationUseCase,
|
|
4621
5201
|
RequestHumanConversationUseCase,
|
|
5202
|
+
ReseedFlowGraphUseCase,
|
|
4622
5203
|
SaveFlowGraphUseCase,
|
|
4623
5204
|
SendMessageUseCase,
|
|
4624
5205
|
SessionRepository,
|
|
@@ -4629,6 +5210,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4629
5210
|
TRANSCRIPTION_STATUS,
|
|
4630
5211
|
TakeoverConversationUseCase,
|
|
4631
5212
|
TranscribeAudioUseCase,
|
|
5213
|
+
UpdateQuickReplyUseCase,
|
|
4632
5214
|
WEBHOOK_CLAIM_TTL_SECONDS,
|
|
4633
5215
|
WEBHOOK_NONCE_TTL_SECONDS,
|
|
4634
5216
|
WhatsAppChannelAdapter,
|
|
@@ -4637,6 +5219,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4637
5219
|
claimWebhookDelivery,
|
|
4638
5220
|
confirmWebhookDelivery,
|
|
4639
5221
|
createMetaWhatsAppModule,
|
|
5222
|
+
createMetaWhatsAppQuickReplyRoutes,
|
|
4640
5223
|
createSendMediaAction,
|
|
4641
5224
|
createSendProductListAction,
|
|
4642
5225
|
createTranscriptionPolicyResolver,
|
|
@@ -4652,16 +5235,19 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4652
5235
|
messages,
|
|
4653
5236
|
metaWhatsAppMigrationsFolder,
|
|
4654
5237
|
metaWhatsAppSchema,
|
|
5238
|
+
quickReplies,
|
|
4655
5239
|
readFlowInbound,
|
|
4656
5240
|
redeemSseTicket,
|
|
4657
5241
|
resolveFailureStatus,
|
|
4658
5242
|
resolveFlowAnswer,
|
|
5243
|
+
resolveFlowConfigText,
|
|
4659
5244
|
resolveFlowTimeZone,
|
|
4660
5245
|
resolvePreviewUploadId,
|
|
4661
5246
|
runMetaWhatsAppMigrations,
|
|
4662
5247
|
sessions,
|
|
4663
5248
|
settings,
|
|
4664
5249
|
toPreviewMediaId,
|
|
5250
|
+
toQuickReplyView,
|
|
4665
5251
|
toSessionContract,
|
|
4666
5252
|
transcriptionRetryAfterSeconds,
|
|
4667
5253
|
verifyWebhookChallenge,
|