@adatechnology/meta-whatsapp-module 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -0
- package/dist/index.cjs +607 -116
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +345 -3
- package/dist/index.d.ts +345 -3
- package/dist/index.js +513 -34
- 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 +4 -3
package/dist/index.cjs
CHANGED
|
@@ -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,14 +83,16 @@ __export(index_exports, {
|
|
|
76
83
|
TRANSCRIPTION_STATUS: () => TRANSCRIPTION_STATUS,
|
|
77
84
|
TakeoverConversationUseCase: () => TakeoverConversationUseCase,
|
|
78
85
|
TranscribeAudioUseCase: () => TranscribeAudioUseCase,
|
|
79
|
-
|
|
80
|
-
|
|
86
|
+
UpdateQuickReplyUseCase: () => UpdateQuickReplyUseCase,
|
|
87
|
+
WEBHOOK_CLAIM_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS,
|
|
88
|
+
WEBHOOK_NONCE_TTL_SECONDS: () => import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS,
|
|
81
89
|
WhatsAppChannelAdapter: () => WhatsAppChannelAdapter,
|
|
82
90
|
buildFlowChoiceMessage: () => buildFlowChoiceMessage,
|
|
83
91
|
buildInboundJobId: () => buildInboundJobId,
|
|
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,
|
|
@@ -94,22 +103,25 @@ __export(index_exports, {
|
|
|
94
103
|
isAudioMimeType: () => isAudioMimeType,
|
|
95
104
|
isChoiceNode: () => isChoiceNode,
|
|
96
105
|
isRetriableTranscriptionError: () => isRetriableTranscriptionError,
|
|
106
|
+
isTransientSendError: () => isTransientSendError,
|
|
97
107
|
isUnsupportedTranscriptionError: () => isUnsupportedTranscriptionError,
|
|
98
108
|
issueSseTicket: () => issueSseTicket,
|
|
99
109
|
messages: () => messages,
|
|
100
110
|
metaWhatsAppMigrationsFolder: () => metaWhatsAppMigrationsFolder,
|
|
101
111
|
metaWhatsAppSchema: () => metaWhatsAppSchema,
|
|
112
|
+
quickReplies: () => quickReplies,
|
|
102
113
|
readFlowInbound: () => readFlowInbound,
|
|
103
114
|
redeemSseTicket: () => redeemSseTicket,
|
|
104
115
|
resolveFailureStatus: () => resolveFailureStatus,
|
|
105
116
|
resolveFlowAnswer: () => resolveFlowAnswer,
|
|
106
117
|
resolveFlowConfigText: () => resolveFlowConfigText,
|
|
107
118
|
resolveFlowTimeZone: () => resolveFlowTimeZone,
|
|
108
|
-
resolvePreviewUploadId: () =>
|
|
119
|
+
resolvePreviewUploadId: () => import_meta_whatsapp_contracts18.resolvePreviewUploadId,
|
|
109
120
|
runMetaWhatsAppMigrations: () => runMetaWhatsAppMigrations,
|
|
110
121
|
sessions: () => sessions,
|
|
111
122
|
settings: () => settings,
|
|
112
|
-
toPreviewMediaId: () =>
|
|
123
|
+
toPreviewMediaId: () => import_meta_whatsapp_contracts18.toPreviewMediaId,
|
|
124
|
+
toQuickReplyView: () => toQuickReplyView,
|
|
113
125
|
toSessionContract: () => toSessionContract,
|
|
114
126
|
transcriptionRetryAfterSeconds: () => transcriptionRetryAfterSeconds,
|
|
115
127
|
verifyWebhookChallenge: () => verifyWebhookChallenge,
|
|
@@ -120,7 +132,7 @@ module.exports = __toCommonJS(index_exports);
|
|
|
120
132
|
// src/createMetaWhatsAppModule.ts
|
|
121
133
|
var import_meta_whatsapp_provider = require("@adatechnology/meta-whatsapp-provider");
|
|
122
134
|
var import_testing = require("@adatechnology/meta-whatsapp-contracts/testing");
|
|
123
|
-
var
|
|
135
|
+
var import_meta_whatsapp_contracts23 = require("@adatechnology/meta-whatsapp-contracts");
|
|
124
136
|
|
|
125
137
|
// src/repositories/SessionRepository.ts
|
|
126
138
|
var import_drizzle_orm2 = require("drizzle-orm");
|
|
@@ -324,6 +336,14 @@ var flowGraphs = metaWhatsAppSchema.table("flow_graphs", {
|
|
|
324
336
|
menuOptionLabel: (0, import_pg_core.varchar)("menu_option_label", {
|
|
325
337
|
length: 64
|
|
326
338
|
}),
|
|
339
|
+
// 'seed' | 'edited' (FLOW_GRAPH_ORIGIN). Linha anterior ao campo vira 'edited': sem como saber se
|
|
340
|
+
// alguém mexeu, o reseed do produto não pode sobrescrevê-la.
|
|
341
|
+
origin: (0, import_pg_core.varchar)("origin", {
|
|
342
|
+
length: 16
|
|
343
|
+
}).notNull().default("edited"),
|
|
344
|
+
seedVersion: (0, import_pg_core.varchar)("seed_version", {
|
|
345
|
+
length: 64
|
|
346
|
+
}),
|
|
327
347
|
createdAt: (0, import_pg_core.timestamp)("created_at", {
|
|
328
348
|
withTimezone: true
|
|
329
349
|
}).notNull().defaultNow(),
|
|
@@ -381,6 +401,29 @@ var flowMedia = metaWhatsAppSchema.table("flow_media", {
|
|
|
381
401
|
// receberia o documento repetido.
|
|
382
402
|
(0, import_pg_core.uniqueIndex)("idx_flow_media_node_upload").on(table.companyId, table.flowKey, table.nodeId, table.uploadId)
|
|
383
403
|
]);
|
|
404
|
+
var quickReplies = metaWhatsAppSchema.table("quick_replies", {
|
|
405
|
+
id: (0, import_pg_core.uuid)("id").primaryKey().defaultRandom(),
|
|
406
|
+
companyId: (0, import_pg_core.uuid)("company_id").notNull(),
|
|
407
|
+
title: (0, import_pg_core.varchar)("title", {
|
|
408
|
+
length: 40
|
|
409
|
+
}).notNull(),
|
|
410
|
+
shortcut: (0, import_pg_core.varchar)("shortcut", {
|
|
411
|
+
length: 20
|
|
412
|
+
}).notNull(),
|
|
413
|
+
body: (0, import_pg_core.varchar)("body", {
|
|
414
|
+
length: 1e3
|
|
415
|
+
}).notNull(),
|
|
416
|
+
sortOrder: (0, import_pg_core.integer)("sort_order").notNull().default(0),
|
|
417
|
+
createdAt: (0, import_pg_core.timestamp)("created_at", {
|
|
418
|
+
withTimezone: true
|
|
419
|
+
}).notNull().defaultNow(),
|
|
420
|
+
updatedAt: (0, import_pg_core.timestamp)("updated_at", {
|
|
421
|
+
withTimezone: true
|
|
422
|
+
}).notNull().defaultNow()
|
|
423
|
+
}, (table) => [
|
|
424
|
+
(0, import_pg_core.uniqueIndex)("idx_quick_replies_company_shortcut").on(table.companyId, table.shortcut),
|
|
425
|
+
(0, import_pg_core.index)("idx_quick_replies_company_order").on(table.companyId, table.sortOrder)
|
|
426
|
+
]);
|
|
384
427
|
var settings = metaWhatsAppSchema.table("settings", {
|
|
385
428
|
companyId: (0, import_pg_core.uuid)("company_id").primaryKey(),
|
|
386
429
|
templateName: (0, import_pg_core.varchar)("template_name", {
|
|
@@ -837,6 +880,7 @@ var MessageRepository = class {
|
|
|
837
880
|
// src/repositories/FlowGraphRepository.ts
|
|
838
881
|
var import_drizzle_orm4 = require("drizzle-orm");
|
|
839
882
|
var import_meta_whatsapp_contracts = require("@adatechnology/meta-whatsapp-contracts");
|
|
883
|
+
var import_meta_whatsapp_contracts2 = require("@adatechnology/meta-whatsapp-contracts");
|
|
840
884
|
var InvalidFlowGraphError = class extends Error {
|
|
841
885
|
static {
|
|
842
886
|
__name(this, "InvalidFlowGraphError");
|
|
@@ -855,10 +899,18 @@ function toContractGraph(row) {
|
|
|
855
899
|
label: row.label,
|
|
856
900
|
startNodeId: row.startNodeId,
|
|
857
901
|
version: row.version,
|
|
858
|
-
nodes: parsed.data
|
|
902
|
+
nodes: parsed.data,
|
|
903
|
+
origin: toOrigin(row.origin),
|
|
904
|
+
...row.seedVersion ? {
|
|
905
|
+
seedVersion: row.seedVersion
|
|
906
|
+
} : {}
|
|
859
907
|
};
|
|
860
908
|
}
|
|
861
909
|
__name(toContractGraph, "toContractGraph");
|
|
910
|
+
function toOrigin(value) {
|
|
911
|
+
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;
|
|
912
|
+
}
|
|
913
|
+
__name(toOrigin, "toOrigin");
|
|
862
914
|
var OptimisticLockError = class extends Error {
|
|
863
915
|
static {
|
|
864
916
|
__name(this, "OptimisticLockError");
|
|
@@ -897,7 +949,11 @@ var FlowGraphRepository = class {
|
|
|
897
949
|
nodeCount: Object.keys(row.nodes).length,
|
|
898
950
|
showInMenu: row.showInMenu,
|
|
899
951
|
menuOptionLabel: row.menuOptionLabel ?? void 0,
|
|
900
|
-
updatedAt: row.updatedAt.toISOString()
|
|
952
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
953
|
+
origin: toOrigin(row.origin),
|
|
954
|
+
...row.seedVersion ? {
|
|
955
|
+
seedVersion: row.seedVersion
|
|
956
|
+
} : {}
|
|
901
957
|
}));
|
|
902
958
|
}
|
|
903
959
|
// Valida antes de gravar: aceitar um grafo malformado e só reclamar na leitura empurraria a
|
|
@@ -915,7 +971,10 @@ var FlowGraphRepository = class {
|
|
|
915
971
|
startNodeId: graph.startNodeId,
|
|
916
972
|
nodes: graph.nodes,
|
|
917
973
|
showInMenu: graph.showInMenu ?? false,
|
|
918
|
-
menuOptionLabel: graph.menuOptionLabel
|
|
974
|
+
menuOptionLabel: graph.menuOptionLabel,
|
|
975
|
+
// Quem informa `seedVersion` é o produto semeando; criado pelo editor não traz e fica `edited`.
|
|
976
|
+
origin: graph.seedVersion ? import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED : import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.EDITED,
|
|
977
|
+
seedVersion: graph.seedVersion ?? null
|
|
919
978
|
}).returning();
|
|
920
979
|
const createdGraph = toContractGraph(created);
|
|
921
980
|
await this.cache?.invalidate(companyId, createdGraph.key);
|
|
@@ -929,6 +988,8 @@ var FlowGraphRepository = class {
|
|
|
929
988
|
label: graph.label,
|
|
930
989
|
startNodeId: graph.startNodeId,
|
|
931
990
|
nodes: graph.nodes,
|
|
991
|
+
// Salvar é sempre edição humana, mesmo que o editor devolva `origin: 'seed'` do grafo que carregou.
|
|
992
|
+
origin: import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.EDITED,
|
|
932
993
|
version: expectedVersion + 1,
|
|
933
994
|
updatedAt: /* @__PURE__ */ new Date()
|
|
934
995
|
}).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();
|
|
@@ -936,6 +997,38 @@ var FlowGraphRepository = class {
|
|
|
936
997
|
await this.cache?.invalidate(companyId, graph.key);
|
|
937
998
|
return toContractGraph(rows[0]);
|
|
938
999
|
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Atualiza um grafo semeado que ninguém editou. A condição `origin = 'seed'` vai no próprio UPDATE:
|
|
1002
|
+
* se uma pessoa salvar pelo editor entre a leitura e a escrita, o grafo vira `edited` e este update
|
|
1003
|
+
* não casa nenhuma linha — a edição nunca é sobrescrita. Idempotente por `seedVersion`.
|
|
1004
|
+
*/
|
|
1005
|
+
async reseed(params) {
|
|
1006
|
+
this.assertValidNodes(params.key, params.content.nodes);
|
|
1007
|
+
const rows = await this.db.update(flowGraphs).set({
|
|
1008
|
+
label: params.content.label,
|
|
1009
|
+
startNodeId: params.content.startNodeId,
|
|
1010
|
+
nodes: params.content.nodes,
|
|
1011
|
+
seedVersion: params.seedVersion,
|
|
1012
|
+
version: import_drizzle_orm4.sql`${flowGraphs.version} + 1`,
|
|
1013
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1014
|
+
}).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();
|
|
1015
|
+
if (rows.length > 0) {
|
|
1016
|
+
await this.cache?.invalidate(params.companyId, params.key);
|
|
1017
|
+
return {
|
|
1018
|
+
status: "updated",
|
|
1019
|
+
graph: toContractGraph(rows[0])
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
const [existing] = await this.db.select({
|
|
1023
|
+
origin: flowGraphs.origin
|
|
1024
|
+
}).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);
|
|
1025
|
+
if (!existing) return {
|
|
1026
|
+
status: "missing"
|
|
1027
|
+
};
|
|
1028
|
+
return {
|
|
1029
|
+
status: existing.origin === import_meta_whatsapp_contracts2.FLOW_GRAPH_ORIGIN.SEED ? "current" : "edited"
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
939
1032
|
async delete(companyId, key) {
|
|
940
1033
|
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)));
|
|
941
1034
|
await this.cache?.invalidate(companyId, key);
|
|
@@ -1137,7 +1230,7 @@ var LogMessageUseCase = class {
|
|
|
1137
1230
|
};
|
|
1138
1231
|
|
|
1139
1232
|
// src/use-cases/SendMessage.use-case.ts
|
|
1140
|
-
var
|
|
1233
|
+
var import_meta_whatsapp_contracts3 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1141
1234
|
var WHATSAPP_WINDOW_HOURS = 24;
|
|
1142
1235
|
var DEFAULT_FALLBACK_LIST_LABEL = "Op\xE7\xF5es";
|
|
1143
1236
|
var SendMessageUseCase = class {
|
|
@@ -1158,8 +1251,8 @@ var SendMessageUseCase = class {
|
|
|
1158
1251
|
}
|
|
1159
1252
|
async assertWithinWindow(companyId, whatsappNumber) {
|
|
1160
1253
|
const hours = await this.sessionRepository.hoursSinceLastInbound(companyId, whatsappNumber);
|
|
1161
|
-
if (hours === void 0) throw new
|
|
1162
|
-
if (hours >= WHATSAPP_WINDOW_HOURS) throw new
|
|
1254
|
+
if (hours === void 0) throw new import_meta_whatsapp_contracts3.WindowExpiredError();
|
|
1255
|
+
if (hours >= WHATSAPP_WINDOW_HOURS) throw new import_meta_whatsapp_contracts3.WindowExpiredError(hours);
|
|
1163
1256
|
}
|
|
1164
1257
|
async sendText(params) {
|
|
1165
1258
|
await this.assertWithinWindow(params.companyId, params.whatsappNumber);
|
|
@@ -1233,7 +1326,7 @@ var SendMessageUseCase = class {
|
|
|
1233
1326
|
* títulos das opções) em `payload.interactive`, para o histórico mostrar o que foi oferecido.
|
|
1234
1327
|
*/
|
|
1235
1328
|
async sendInteractive(params) {
|
|
1236
|
-
(0,
|
|
1329
|
+
(0, import_meta_whatsapp_contracts3.assertInteractiveWithinLimits)(params.interactive);
|
|
1237
1330
|
await this.assertWithinWindow(params.companyId, params.whatsappNumber);
|
|
1238
1331
|
const { externalMessageId } = await this.sendInteractiveThroughChannel(params);
|
|
1239
1332
|
return this.logMessage.execute({
|
|
@@ -1383,7 +1476,7 @@ var ReleaseConversationUseCase = class {
|
|
|
1383
1476
|
};
|
|
1384
1477
|
|
|
1385
1478
|
// src/use-cases/RequestHumanConversation.use-case.ts
|
|
1386
|
-
var
|
|
1479
|
+
var import_meta_whatsapp_contracts4 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1387
1480
|
|
|
1388
1481
|
// src/channel/inboundDispatch.ts
|
|
1389
1482
|
var import_meta_graph_core = require("@adatechnology/meta-graph-core");
|
|
@@ -1510,7 +1603,7 @@ var RequestHumanConversationUseCase = class {
|
|
|
1510
1603
|
async execute(params) {
|
|
1511
1604
|
await this.sessionRepository.requestHuman(params.companyId, params.whatsappNumber);
|
|
1512
1605
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1513
|
-
if (!session) throw new
|
|
1606
|
+
if (!session) throw new import_meta_whatsapp_contracts4.SessionNotFoundError(params.whatsappNumber);
|
|
1514
1607
|
this.realtime?.emit(`conv:${params.whatsappNumber}`, "human-requested", {
|
|
1515
1608
|
companyId: params.companyId,
|
|
1516
1609
|
humanRequestedAt: session.humanRequestedAt?.toISOString() ?? null
|
|
@@ -1548,7 +1641,7 @@ var ListConversationsUseCase = class {
|
|
|
1548
1641
|
};
|
|
1549
1642
|
|
|
1550
1643
|
// src/use-cases/ListMessages.use-case.ts
|
|
1551
|
-
var
|
|
1644
|
+
var import_meta_whatsapp_contracts5 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1552
1645
|
var ListMessagesUseCase = class {
|
|
1553
1646
|
static {
|
|
1554
1647
|
__name(this, "ListMessagesUseCase");
|
|
@@ -1561,7 +1654,7 @@ var ListMessagesUseCase = class {
|
|
|
1561
1654
|
}
|
|
1562
1655
|
async execute(params) {
|
|
1563
1656
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1564
|
-
if (!session) throw new
|
|
1657
|
+
if (!session) throw new import_meta_whatsapp_contracts5.SessionNotFoundError(params.whatsappNumber);
|
|
1565
1658
|
const repoParams = {
|
|
1566
1659
|
companyId: params.companyId,
|
|
1567
1660
|
sessionId: session.id,
|
|
@@ -1573,7 +1666,7 @@ var ListMessagesUseCase = class {
|
|
|
1573
1666
|
};
|
|
1574
1667
|
|
|
1575
1668
|
// src/use-cases/ListConversationDocuments.use-case.ts
|
|
1576
|
-
var
|
|
1669
|
+
var import_meta_whatsapp_contracts6 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1577
1670
|
var ListConversationDocumentsUseCase = class {
|
|
1578
1671
|
static {
|
|
1579
1672
|
__name(this, "ListConversationDocumentsUseCase");
|
|
@@ -1586,7 +1679,7 @@ var ListConversationDocumentsUseCase = class {
|
|
|
1586
1679
|
}
|
|
1587
1680
|
async execute(params) {
|
|
1588
1681
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1589
|
-
if (!session) throw new
|
|
1682
|
+
if (!session) throw new import_meta_whatsapp_contracts6.SessionNotFoundError(params.whatsappNumber);
|
|
1590
1683
|
const { rows, total } = await this.documentRepository.listByConversation({
|
|
1591
1684
|
companyId: params.companyId,
|
|
1592
1685
|
sessionId: session.id,
|
|
@@ -1664,7 +1757,7 @@ var ListCompanyDocumentsUseCase = class {
|
|
|
1664
1757
|
};
|
|
1665
1758
|
|
|
1666
1759
|
// src/use-cases/DeleteConversation.use-case.ts
|
|
1667
|
-
var
|
|
1760
|
+
var import_meta_whatsapp_contracts7 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1668
1761
|
var DeleteConversationUseCase = class {
|
|
1669
1762
|
static {
|
|
1670
1763
|
__name(this, "DeleteConversationUseCase");
|
|
@@ -1679,7 +1772,7 @@ var DeleteConversationUseCase = class {
|
|
|
1679
1772
|
}
|
|
1680
1773
|
async execute(params) {
|
|
1681
1774
|
const session = await this.sessionRepository.getContext(params.companyId, params.whatsappNumber);
|
|
1682
|
-
if (!session) throw new
|
|
1775
|
+
if (!session) throw new import_meta_whatsapp_contracts7.SessionNotFoundError(params.whatsappNumber);
|
|
1683
1776
|
const uploadIds = await this.documentRepository.listUploadIdsBySession(params.companyId, session.id);
|
|
1684
1777
|
if (uploadIds.length > 0 && !this.objectStorage?.delete) {
|
|
1685
1778
|
throw new Error("storage_delete_unsupported: a conversa tem arquivos e o storage injetado n\xE3o implementa delete");
|
|
@@ -1924,8 +2017,171 @@ var DocumentRepository = class {
|
|
|
1924
2017
|
}
|
|
1925
2018
|
};
|
|
1926
2019
|
|
|
2020
|
+
// src/repositories/QuickReplyRepository.ts
|
|
2021
|
+
var import_drizzle_orm7 = require("drizzle-orm");
|
|
2022
|
+
var import_meta_whatsapp_contracts8 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2023
|
+
var UNIQUE_VIOLATION_SQLSTATE = "23505";
|
|
2024
|
+
function hasUniqueViolationState(error) {
|
|
2025
|
+
const state = error;
|
|
2026
|
+
return state?.code === UNIQUE_VIOLATION_SQLSTATE || state?.errno === UNIQUE_VIOLATION_SQLSTATE;
|
|
2027
|
+
}
|
|
2028
|
+
__name(hasUniqueViolationState, "hasUniqueViolationState");
|
|
2029
|
+
function isUniqueViolation(error) {
|
|
2030
|
+
return hasUniqueViolationState(error) || hasUniqueViolationState(error?.cause);
|
|
2031
|
+
}
|
|
2032
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
2033
|
+
function escapeLikePattern(text2) {
|
|
2034
|
+
return text2.replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
2035
|
+
}
|
|
2036
|
+
__name(escapeLikePattern, "escapeLikePattern");
|
|
2037
|
+
var QuickReplyRepository = class {
|
|
2038
|
+
static {
|
|
2039
|
+
__name(this, "QuickReplyRepository");
|
|
2040
|
+
}
|
|
2041
|
+
db;
|
|
2042
|
+
constructor(db) {
|
|
2043
|
+
this.db = db;
|
|
2044
|
+
}
|
|
2045
|
+
async list(params) {
|
|
2046
|
+
const filters = [
|
|
2047
|
+
(0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId)
|
|
2048
|
+
];
|
|
2049
|
+
if (params.search) {
|
|
2050
|
+
const pattern = `%${escapeLikePattern(params.search)}%`;
|
|
2051
|
+
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));
|
|
2052
|
+
if (matches) filters.push(matches);
|
|
2053
|
+
}
|
|
2054
|
+
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));
|
|
2055
|
+
}
|
|
2056
|
+
async get(companyId, id) {
|
|
2057
|
+
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);
|
|
2058
|
+
return row;
|
|
2059
|
+
}
|
|
2060
|
+
async create(params) {
|
|
2061
|
+
const [totals] = await this.db.select({
|
|
2062
|
+
total: (0, import_drizzle_orm7.count)(),
|
|
2063
|
+
highestOrder: (0, import_drizzle_orm7.max)(quickReplies.sortOrder)
|
|
2064
|
+
}).from(quickReplies).where((0, import_drizzle_orm7.eq)(quickReplies.companyId, params.companyId));
|
|
2065
|
+
if ((totals?.total ?? 0) >= import_meta_whatsapp_contracts8.QUICK_REPLY_LIMITS.MAX_PER_COMPANY) {
|
|
2066
|
+
throw new import_meta_whatsapp_contracts8.QuickReplyLimitReachedError(import_meta_whatsapp_contracts8.QUICK_REPLY_LIMITS.MAX_PER_COMPANY);
|
|
2067
|
+
}
|
|
2068
|
+
try {
|
|
2069
|
+
const [row] = await this.db.insert(quickReplies).values({
|
|
2070
|
+
companyId: params.companyId,
|
|
2071
|
+
title: params.title,
|
|
2072
|
+
shortcut: params.shortcut,
|
|
2073
|
+
body: params.body,
|
|
2074
|
+
// Sem ordem explícita vai para o fim da lista.
|
|
2075
|
+
sortOrder: params.sortOrder ?? (totals?.highestOrder ?? -1) + 1
|
|
2076
|
+
}).returning();
|
|
2077
|
+
return row;
|
|
2078
|
+
} catch (error) {
|
|
2079
|
+
if (isUniqueViolation(error)) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2080
|
+
throw error;
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
async update(params) {
|
|
2084
|
+
const [taken] = await this.db.select({
|
|
2085
|
+
id: quickReplies.id
|
|
2086
|
+
}).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);
|
|
2087
|
+
if (taken) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2088
|
+
try {
|
|
2089
|
+
const [row] = await this.db.update(quickReplies).set({
|
|
2090
|
+
title: params.title,
|
|
2091
|
+
shortcut: params.shortcut,
|
|
2092
|
+
body: params.body,
|
|
2093
|
+
...params.sortOrder !== void 0 ? {
|
|
2094
|
+
sortOrder: params.sortOrder
|
|
2095
|
+
} : {},
|
|
2096
|
+
updatedAt: import_drizzle_orm7.sql`now()`
|
|
2097
|
+
}).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();
|
|
2098
|
+
if (!row) throw new import_meta_whatsapp_contracts8.QuickReplyNotFoundError(params.id);
|
|
2099
|
+
return row;
|
|
2100
|
+
} catch (error) {
|
|
2101
|
+
if (isUniqueViolation(error)) throw new import_meta_whatsapp_contracts8.QuickReplyShortcutTakenError(params.shortcut);
|
|
2102
|
+
throw error;
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
async delete(companyId, id) {
|
|
2106
|
+
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({
|
|
2107
|
+
id: quickReplies.id
|
|
2108
|
+
});
|
|
2109
|
+
return rows.length > 0;
|
|
2110
|
+
}
|
|
2111
|
+
};
|
|
2112
|
+
|
|
2113
|
+
// src/use-cases/QuickReply.use-cases.ts
|
|
2114
|
+
var import_meta_whatsapp_contracts9 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2115
|
+
function toQuickReplyView(row) {
|
|
2116
|
+
return {
|
|
2117
|
+
id: row.id,
|
|
2118
|
+
title: row.title,
|
|
2119
|
+
shortcut: row.shortcut,
|
|
2120
|
+
body: row.body,
|
|
2121
|
+
sortOrder: row.sortOrder,
|
|
2122
|
+
createdAt: row.createdAt.toISOString(),
|
|
2123
|
+
updatedAt: row.updatedAt.toISOString()
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
__name(toQuickReplyView, "toQuickReplyView");
|
|
2127
|
+
var ListQuickRepliesUseCase = class {
|
|
2128
|
+
static {
|
|
2129
|
+
__name(this, "ListQuickRepliesUseCase");
|
|
2130
|
+
}
|
|
2131
|
+
repository;
|
|
2132
|
+
constructor(repository) {
|
|
2133
|
+
this.repository = repository;
|
|
2134
|
+
}
|
|
2135
|
+
async execute(params) {
|
|
2136
|
+
const rows = await this.repository.list({
|
|
2137
|
+
companyId: params.companyId,
|
|
2138
|
+
...params.search ? {
|
|
2139
|
+
search: params.search
|
|
2140
|
+
} : {}
|
|
2141
|
+
});
|
|
2142
|
+
return rows.map(toQuickReplyView);
|
|
2143
|
+
}
|
|
2144
|
+
};
|
|
2145
|
+
var CreateQuickReplyUseCase = class {
|
|
2146
|
+
static {
|
|
2147
|
+
__name(this, "CreateQuickReplyUseCase");
|
|
2148
|
+
}
|
|
2149
|
+
repository;
|
|
2150
|
+
constructor(repository) {
|
|
2151
|
+
this.repository = repository;
|
|
2152
|
+
}
|
|
2153
|
+
async execute(params) {
|
|
2154
|
+
return toQuickReplyView(await this.repository.create(params));
|
|
2155
|
+
}
|
|
2156
|
+
};
|
|
2157
|
+
var UpdateQuickReplyUseCase = class {
|
|
2158
|
+
static {
|
|
2159
|
+
__name(this, "UpdateQuickReplyUseCase");
|
|
2160
|
+
}
|
|
2161
|
+
repository;
|
|
2162
|
+
constructor(repository) {
|
|
2163
|
+
this.repository = repository;
|
|
2164
|
+
}
|
|
2165
|
+
async execute(params) {
|
|
2166
|
+
return toQuickReplyView(await this.repository.update(params));
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
var DeleteQuickReplyUseCase = class {
|
|
2170
|
+
static {
|
|
2171
|
+
__name(this, "DeleteQuickReplyUseCase");
|
|
2172
|
+
}
|
|
2173
|
+
repository;
|
|
2174
|
+
constructor(repository) {
|
|
2175
|
+
this.repository = repository;
|
|
2176
|
+
}
|
|
2177
|
+
async execute(params) {
|
|
2178
|
+
const wasDeleted = await this.repository.delete(params.companyId, params.id);
|
|
2179
|
+
if (!wasDeleted) throw new import_meta_whatsapp_contracts9.QuickReplyNotFoundError(params.id);
|
|
2180
|
+
}
|
|
2181
|
+
};
|
|
2182
|
+
|
|
1927
2183
|
// src/use-cases/ExportConversation.use-case.ts
|
|
1928
|
-
var
|
|
2184
|
+
var import_meta_whatsapp_contracts10 = require("@adatechnology/meta-whatsapp-contracts");
|
|
1929
2185
|
var ExportConversationUseCase = class {
|
|
1930
2186
|
static {
|
|
1931
2187
|
__name(this, "ExportConversationUseCase");
|
|
@@ -1936,7 +2192,7 @@ var ExportConversationUseCase = class {
|
|
|
1936
2192
|
}
|
|
1937
2193
|
async execute(params) {
|
|
1938
2194
|
const result = await this.sessionRepository.exportConversation(params.companyId, params.whatsappNumber);
|
|
1939
|
-
if (!result) throw new
|
|
2195
|
+
if (!result) throw new import_meta_whatsapp_contracts10.SessionNotFoundError(params.whatsappNumber);
|
|
1940
2196
|
return result;
|
|
1941
2197
|
}
|
|
1942
2198
|
};
|
|
@@ -1990,6 +2246,18 @@ var SaveFlowGraphUseCase = class {
|
|
|
1990
2246
|
return this.flowGraphRepository.save(params.companyId, params.graph, params.expectedVersion);
|
|
1991
2247
|
}
|
|
1992
2248
|
};
|
|
2249
|
+
var ReseedFlowGraphUseCase = class {
|
|
2250
|
+
static {
|
|
2251
|
+
__name(this, "ReseedFlowGraphUseCase");
|
|
2252
|
+
}
|
|
2253
|
+
flowGraphRepository;
|
|
2254
|
+
constructor(flowGraphRepository) {
|
|
2255
|
+
this.flowGraphRepository = flowGraphRepository;
|
|
2256
|
+
}
|
|
2257
|
+
async execute(params) {
|
|
2258
|
+
return this.flowGraphRepository.reseed(params);
|
|
2259
|
+
}
|
|
2260
|
+
};
|
|
1993
2261
|
var DeleteFlowGraphUseCase = class {
|
|
1994
2262
|
static {
|
|
1995
2263
|
__name(this, "DeleteFlowGraphUseCase");
|
|
@@ -2016,7 +2284,7 @@ var GetLiveFlowPositionsUseCase = class {
|
|
|
2016
2284
|
};
|
|
2017
2285
|
|
|
2018
2286
|
// src/flows/FlowInterpreter.ts
|
|
2019
|
-
var
|
|
2287
|
+
var import_meta_whatsapp_contracts11 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2020
2288
|
var DEFAULT_MAX_STEPS = 50;
|
|
2021
2289
|
function evaluateCondition(node, context) {
|
|
2022
2290
|
if (!node.conditionContextKey || !node.conditionOperator || !node.conditionValue) return false;
|
|
@@ -2119,9 +2387,9 @@ var FlowInterpreter = class {
|
|
|
2119
2387
|
kind: "terminal",
|
|
2120
2388
|
context: input.context
|
|
2121
2389
|
};
|
|
2122
|
-
if ((0,
|
|
2390
|
+
if ((0, import_meta_whatsapp_contracts11.isCrossFlowTarget)(nextNodeId)) return {
|
|
2123
2391
|
kind: "cross-flow",
|
|
2124
|
-
flowKey: (0,
|
|
2392
|
+
flowKey: (0, import_meta_whatsapp_contracts11.crossFlowKey)(nextNodeId),
|
|
2125
2393
|
context: input.context
|
|
2126
2394
|
};
|
|
2127
2395
|
if (!input.graph.nodes[nextNodeId]) return {
|
|
@@ -2181,15 +2449,18 @@ var FlowInterpreter = class {
|
|
|
2181
2449
|
};
|
|
2182
2450
|
|
|
2183
2451
|
// src/flows/FlowRunner.ts
|
|
2184
|
-
var
|
|
2452
|
+
var import_meta_whatsapp_contracts16 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2185
2453
|
|
|
2186
2454
|
// src/flows/resolveFlowAnswer.ts
|
|
2187
|
-
var
|
|
2455
|
+
var import_meta_whatsapp_contracts12 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2188
2456
|
|
|
2189
2457
|
// src/flows/flowRunner.constant.ts
|
|
2190
2458
|
var DEFAULT_START_FLOW_KEY = "main";
|
|
2191
2459
|
var DEFAULT_MAX_INVALID_ANSWERS = 2;
|
|
2192
2460
|
var DEFAULT_MAX_CROSS_FLOW_JUMPS = 5;
|
|
2461
|
+
var DEFAULT_SEND_RETRY_MAX_ATTEMPTS = 3;
|
|
2462
|
+
var DEFAULT_SEND_RETRY_BASE_DELAY_MS = 500;
|
|
2463
|
+
var DEFAULT_SEND_RETRY_MAX_DELAY_MS = 5e3;
|
|
2193
2464
|
var DEFAULT_FLOW_TEXT = {
|
|
2194
2465
|
FALLBACK: "N\xE3o entendi. Pode responder de novo?",
|
|
2195
2466
|
CHOICE_PROMPT: "Escolha uma op\xE7\xE3o:",
|
|
@@ -2210,12 +2481,12 @@ function isChoiceNode(node) {
|
|
|
2210
2481
|
__name(isChoiceNode, "isChoiceNode");
|
|
2211
2482
|
function keywordRoute(node, answer, isInteractiveReply) {
|
|
2212
2483
|
if (isInteractiveReply || typeof node.next !== "object" || !node.next.byKeyword) return void 0;
|
|
2213
|
-
return (0,
|
|
2484
|
+
return (0, import_meta_whatsapp_contracts12.matchFlowKeywordRoute)(answer, node.next.byKeyword);
|
|
2214
2485
|
}
|
|
2215
2486
|
__name(keywordRoute, "keywordRoute");
|
|
2216
2487
|
function matchOption(answer, options, isInteractiveReply) {
|
|
2217
2488
|
if (isInteractiveReply) return options.some(([id]) => id === answer) ? answer : void 0;
|
|
2218
|
-
return (0,
|
|
2489
|
+
return (0, import_meta_whatsapp_contracts12.matchFlowChoice)(answer, options);
|
|
2219
2490
|
}
|
|
2220
2491
|
__name(matchOption, "matchOption");
|
|
2221
2492
|
function resolveChoice(params, answer) {
|
|
@@ -2257,7 +2528,7 @@ function resolveQuestion(params, answer) {
|
|
|
2257
2528
|
kind: "jump",
|
|
2258
2529
|
target
|
|
2259
2530
|
};
|
|
2260
|
-
const result = (0,
|
|
2531
|
+
const result = (0, import_meta_whatsapp_contracts12.validateFlowAnswer)({
|
|
2261
2532
|
node: params.node,
|
|
2262
2533
|
answer,
|
|
2263
2534
|
context: params.context,
|
|
@@ -2285,10 +2556,10 @@ function resolveFlowAnswer(params) {
|
|
|
2285
2556
|
__name(resolveFlowAnswer, "resolveFlowAnswer");
|
|
2286
2557
|
|
|
2287
2558
|
// src/flows/FlowQuestionRenderer.ts
|
|
2288
|
-
var
|
|
2559
|
+
var import_meta_whatsapp_contracts14 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2289
2560
|
|
|
2290
2561
|
// src/flows/buildFlowChoiceMessage.ts
|
|
2291
|
-
var
|
|
2562
|
+
var import_meta_whatsapp_contracts13 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2292
2563
|
function groupSections(options) {
|
|
2293
2564
|
const sections = [];
|
|
2294
2565
|
for (const option of options) {
|
|
@@ -2321,7 +2592,7 @@ function asNumberedText(params) {
|
|
|
2321
2592
|
const description = option.description ? ` \u2014 ${option.description}` : "";
|
|
2322
2593
|
return `${index2 + 1}. ${option.title}${description}`;
|
|
2323
2594
|
});
|
|
2324
|
-
const limit =
|
|
2595
|
+
const limit = import_meta_whatsapp_contracts13.WHATSAPP_CHOICE_LIMIT.TEXT_BODY_LENGTH;
|
|
2325
2596
|
const full = `${params.body}
|
|
2326
2597
|
|
|
2327
2598
|
${lines.join("\n")}`;
|
|
@@ -2348,7 +2619,7 @@ ${line}`;
|
|
|
2348
2619
|
__name(asNumberedText, "asNumberedText");
|
|
2349
2620
|
function buildFlowChoiceMessage(params) {
|
|
2350
2621
|
const isPlain = params.options.every((option) => !option.description && !option.section);
|
|
2351
|
-
if (isPlain && params.options.length <=
|
|
2622
|
+
if (isPlain && params.options.length <= import_meta_whatsapp_contracts13.WHATSAPP_CHOICE_LIMIT.BUTTONS) {
|
|
2352
2623
|
const buttons = {
|
|
2353
2624
|
kind: "buttons",
|
|
2354
2625
|
body: params.body,
|
|
@@ -2357,7 +2628,7 @@ function buildFlowChoiceMessage(params) {
|
|
|
2357
2628
|
title: option.title
|
|
2358
2629
|
}))
|
|
2359
2630
|
};
|
|
2360
|
-
if ((0,
|
|
2631
|
+
if ((0, import_meta_whatsapp_contracts13.listInteractiveLimitViolations)(buttons).length === 0) return {
|
|
2361
2632
|
kind: "interactive",
|
|
2362
2633
|
interactive: buttons
|
|
2363
2634
|
};
|
|
@@ -2368,7 +2639,7 @@ function buildFlowChoiceMessage(params) {
|
|
|
2368
2639
|
buttonLabel: params.listButtonLabel,
|
|
2369
2640
|
sections: groupSections(params.options)
|
|
2370
2641
|
};
|
|
2371
|
-
if ((0,
|
|
2642
|
+
if ((0, import_meta_whatsapp_contracts13.listInteractiveLimitViolations)(list).length === 0) return {
|
|
2372
2643
|
kind: "interactive",
|
|
2373
2644
|
interactive: list
|
|
2374
2645
|
};
|
|
@@ -2405,7 +2676,7 @@ var FlowQuestionRenderer = class {
|
|
|
2405
2676
|
this.providers.set(key, provider);
|
|
2406
2677
|
}
|
|
2407
2678
|
interpolate(text2, variables) {
|
|
2408
|
-
return (0,
|
|
2679
|
+
return (0, import_meta_whatsapp_contracts14.interpolateFlowText)(text2, variables, this.config.formatValue ? {
|
|
2409
2680
|
formatValue: this.config.formatValue
|
|
2410
2681
|
} : {});
|
|
2411
2682
|
}
|
|
@@ -2416,7 +2687,7 @@ var FlowQuestionRenderer = class {
|
|
|
2416
2687
|
...params.variables
|
|
2417
2688
|
};
|
|
2418
2689
|
const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
|
|
2419
|
-
const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
|
|
2690
|
+
const listButtonLabel = this.interpolate(node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL, variables);
|
|
2420
2691
|
if (node.type === "dynamic_choice") {
|
|
2421
2692
|
const options = await this.loadDynamicOptions(params);
|
|
2422
2693
|
const shown = options.map((option) => [
|
|
@@ -2477,8 +2748,8 @@ var FlowQuestionRenderer = class {
|
|
|
2477
2748
|
async loadDynamicOptions(params) {
|
|
2478
2749
|
const { node } = params;
|
|
2479
2750
|
const provider = node.choiceProvider ? this.providers.get(node.choiceProvider) : void 0;
|
|
2480
|
-
if (!provider) throw new
|
|
2481
|
-
const pageSize =
|
|
2751
|
+
if (!provider) throw new import_meta_whatsapp_contracts14.FlowRunnerError("provider-missing", node.choiceProvider ?? node.id);
|
|
2752
|
+
const pageSize = import_meta_whatsapp_contracts14.WHATSAPP_CHOICE_LIMIT.LIST_ROWS - 1;
|
|
2482
2753
|
const result = await provider({
|
|
2483
2754
|
node,
|
|
2484
2755
|
session: params.session,
|
|
@@ -2526,16 +2797,16 @@ function readFlowInbound(message) {
|
|
|
2526
2797
|
__name(readFlowInbound, "readFlowInbound");
|
|
2527
2798
|
|
|
2528
2799
|
// src/flows/matchGlobalKeyword.ts
|
|
2529
|
-
var
|
|
2800
|
+
var import_meta_whatsapp_contracts15 = require("@adatechnology/meta-whatsapp-contracts");
|
|
2530
2801
|
function matchGlobalKeyword(text2, entries) {
|
|
2531
|
-
const normalized = (0,
|
|
2802
|
+
const normalized = (0, import_meta_whatsapp_contracts15.normalizeFlowText)(text2);
|
|
2532
2803
|
if (normalized.length === 0) return void 0;
|
|
2533
2804
|
const padded = ` ${normalized} `;
|
|
2534
2805
|
let best;
|
|
2535
2806
|
for (const entry of entries) {
|
|
2536
2807
|
const isWordMatch = entry.match === "word";
|
|
2537
2808
|
for (const keyword of entry.keywords) {
|
|
2538
|
-
const normalizedKeyword = (0,
|
|
2809
|
+
const normalizedKeyword = (0, import_meta_whatsapp_contracts15.normalizeFlowText)(keyword);
|
|
2539
2810
|
if (normalizedKeyword.length === 0) continue;
|
|
2540
2811
|
const isMatch = isWordMatch ? padded.includes(` ${normalizedKeyword} `) : normalizedKeyword === normalized;
|
|
2541
2812
|
if (isMatch && (!best || normalizedKeyword.length > best.length)) {
|
|
@@ -2570,6 +2841,47 @@ async function resolveFlowConfigText(params) {
|
|
|
2570
2841
|
}
|
|
2571
2842
|
__name(resolveFlowConfigText, "resolveFlowConfigText");
|
|
2572
2843
|
|
|
2844
|
+
// src/flows/sendWithRetry.ts
|
|
2845
|
+
var import_meta_graph_core2 = require("@adatechnology/meta-graph-core");
|
|
2846
|
+
function isTransientSendError(error) {
|
|
2847
|
+
return error instanceof import_meta_graph_core2.WhatsAppConnectionError;
|
|
2848
|
+
}
|
|
2849
|
+
__name(isTransientSendError, "isTransientSendError");
|
|
2850
|
+
var sleepFor = /* @__PURE__ */ __name((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)), "sleepFor");
|
|
2851
|
+
var SendRetriesExhausted = class {
|
|
2852
|
+
static {
|
|
2853
|
+
__name(this, "SendRetriesExhausted");
|
|
2854
|
+
}
|
|
2855
|
+
error;
|
|
2856
|
+
attempts;
|
|
2857
|
+
isTransient;
|
|
2858
|
+
constructor(error, attempts, isTransient) {
|
|
2859
|
+
this.error = error;
|
|
2860
|
+
this.attempts = attempts;
|
|
2861
|
+
this.isTransient = isTransient;
|
|
2862
|
+
}
|
|
2863
|
+
};
|
|
2864
|
+
async function sendWithRetry(send, config = {}) {
|
|
2865
|
+
const maxAttempts = Math.max(1, config.maxAttempts ?? DEFAULT_SEND_RETRY_MAX_ATTEMPTS);
|
|
2866
|
+
const baseDelay = config.baseDelayMs ?? DEFAULT_SEND_RETRY_BASE_DELAY_MS;
|
|
2867
|
+
const maxDelay = config.maxDelayMs ?? DEFAULT_SEND_RETRY_MAX_DELAY_MS;
|
|
2868
|
+
const shouldRetry = config.shouldRetry ?? isTransientSendError;
|
|
2869
|
+
const sleep = config.sleep ?? sleepFor;
|
|
2870
|
+
for (let attempt = 1; ; attempt++) {
|
|
2871
|
+
try {
|
|
2872
|
+
await send();
|
|
2873
|
+
return {
|
|
2874
|
+
attempts: attempt
|
|
2875
|
+
};
|
|
2876
|
+
} catch (error) {
|
|
2877
|
+
const isTransient = shouldRetry(error);
|
|
2878
|
+
if (!isTransient || attempt >= maxAttempts) throw new SendRetriesExhausted(error, attempt, isTransient);
|
|
2879
|
+
await sleep(Math.min(baseDelay * 2 ** (attempt - 1), maxDelay));
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
__name(sendWithRetry, "sendWithRetry");
|
|
2884
|
+
|
|
2573
2885
|
// src/flows/FlowRunner.ts
|
|
2574
2886
|
function contactVariables(profileName) {
|
|
2575
2887
|
if (!profileName) return {};
|
|
@@ -2582,7 +2894,7 @@ __name(contactVariables, "contactVariables");
|
|
|
2582
2894
|
function resolveFlowTimeZone(config) {
|
|
2583
2895
|
const businessHours = config.handoff?.businessHours;
|
|
2584
2896
|
const timeZone = config.timeZone ?? (typeof businessHours === "object" ? businessHours.timeZone : void 0);
|
|
2585
|
-
if (!timeZone) throw new
|
|
2897
|
+
if (!timeZone) throw new import_meta_whatsapp_contracts16.ConfigMissingError("features.flowRunner.timeZone");
|
|
2586
2898
|
new Intl.DateTimeFormat("en-US", {
|
|
2587
2899
|
timeZone
|
|
2588
2900
|
});
|
|
@@ -2599,6 +2911,8 @@ var FlowRunner = class {
|
|
|
2599
2911
|
// Variáveis da mensagem em curso, por sessão: é como a action `handoff` (que só recebe a sessão)
|
|
2600
2912
|
// enxerga o nome do contato sem que ele precise ir para o contexto gravado.
|
|
2601
2913
|
turnVariables = /* @__PURE__ */ new WeakMap();
|
|
2914
|
+
// Erro de envio já sem retentativa → o que se tentou, para `report` entregar ao host sem trocar o erro.
|
|
2915
|
+
sendFailures = /* @__PURE__ */ new WeakMap();
|
|
2602
2916
|
constructor(dependencies) {
|
|
2603
2917
|
this.dependencies = dependencies;
|
|
2604
2918
|
this.renderer = new FlowQuestionRenderer(dependencies.config);
|
|
@@ -2687,7 +3001,7 @@ var FlowRunner = class {
|
|
|
2687
3001
|
const graph = savedGraph ?? (isStale ? await this.loadGraph(turn.companyId, this.startFlowKey()) : void 0);
|
|
2688
3002
|
if (!graph) return "no-flow";
|
|
2689
3003
|
await this.claim(turn);
|
|
2690
|
-
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new
|
|
3004
|
+
if (isStale) await this.report(turn, savedFlowKey, turn.session.currentNodeId, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("flow-not-found", savedFlowKey));
|
|
2691
3005
|
const node = !isStale && turn.session.currentNodeId ? graph.nodes[turn.session.currentNodeId] : void 0;
|
|
2692
3006
|
const context = {
|
|
2693
3007
|
...turn.session.context
|
|
@@ -2765,7 +3079,7 @@ var FlowRunner = class {
|
|
|
2765
3079
|
const { config } = this.dependencies;
|
|
2766
3080
|
return {
|
|
2767
3081
|
now: config.now?.() ?? /* @__PURE__ */ new Date(),
|
|
2768
|
-
locale: config.dateLocale ??
|
|
3082
|
+
locale: config.dateLocale ?? import_meta_whatsapp_contracts16.FLOW_DATE_LOCALE_PT_BR,
|
|
2769
3083
|
timeZone: this.timeZone
|
|
2770
3084
|
};
|
|
2771
3085
|
}
|
|
@@ -2800,7 +3114,7 @@ var FlowRunner = class {
|
|
|
2800
3114
|
await this.handOff(turn, context);
|
|
2801
3115
|
return "handled";
|
|
2802
3116
|
}
|
|
2803
|
-
const flowKey = target === "restart" ? this.startFlowKey() : (0,
|
|
3117
|
+
const flowKey = target === "restart" ? this.startFlowKey() : (0, import_meta_whatsapp_contracts16.crossFlowKey)(target);
|
|
2804
3118
|
const graph = await this.loadGraph(turn.companyId, flowKey);
|
|
2805
3119
|
if (!graph) return "no-flow";
|
|
2806
3120
|
await this.claim(turn);
|
|
@@ -2986,8 +3300,8 @@ var FlowRunner = class {
|
|
|
2986
3300
|
});
|
|
2987
3301
|
}
|
|
2988
3302
|
async jumpTo(turn, graph, target, context) {
|
|
2989
|
-
if ((0,
|
|
2990
|
-
const targetGraph = await this.loadGraph(turn.companyId, (0,
|
|
3303
|
+
if ((0, import_meta_whatsapp_contracts16.isCrossFlowTarget)(target)) {
|
|
3304
|
+
const targetGraph = await this.loadGraph(turn.companyId, (0, import_meta_whatsapp_contracts16.crossFlowKey)(target));
|
|
2991
3305
|
if (!targetGraph) return this.reportMissingFlow(turn, graph.key, target, context);
|
|
2992
3306
|
return this.runFrom(turn, {
|
|
2993
3307
|
graph: targetGraph,
|
|
@@ -3045,7 +3359,7 @@ var FlowRunner = class {
|
|
|
3045
3359
|
nodeId: null,
|
|
3046
3360
|
context: result.context
|
|
3047
3361
|
});
|
|
3048
|
-
return this.report(turn, params.graph.key, null, "max-steps", new
|
|
3362
|
+
return this.report(turn, params.graph.key, null, "max-steps", new import_meta_whatsapp_contracts16.FlowRunnerError("cycle", result.visited.join(" -> ")));
|
|
3049
3363
|
}
|
|
3050
3364
|
const target = await this.loadGraph(turn.companyId, result.flowKey);
|
|
3051
3365
|
if (!target) return this.reportMissingFlow(turn, params.graph.key, result.flowKey, result.context);
|
|
@@ -3061,7 +3375,7 @@ var FlowRunner = class {
|
|
|
3061
3375
|
nodeId: null,
|
|
3062
3376
|
context: params.context
|
|
3063
3377
|
});
|
|
3064
|
-
return this.report(turn, params.graph.key, null, "cross-flow", new
|
|
3378
|
+
return this.report(turn, params.graph.key, null, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("too-many-jumps", params.graph.key));
|
|
3065
3379
|
}
|
|
3066
3380
|
/** Grava a posição no nó e pergunta. Para `dynamic_choice`, busca a página antes de gravar. */
|
|
3067
3381
|
async awaitAnswer(turn, graph, node, context, page) {
|
|
@@ -3093,6 +3407,10 @@ var FlowRunner = class {
|
|
|
3093
3407
|
body
|
|
3094
3408
|
});
|
|
3095
3409
|
}
|
|
3410
|
+
/**
|
|
3411
|
+
* Cada mensagem é retentada sozinha (ver `sendWithRetry`): o que já saiu neste turno não é reenviado.
|
|
3412
|
+
* Esgotadas as tentativas, o erro original sobe como antes e o `report` ganha `details.send`.
|
|
3413
|
+
*/
|
|
3096
3414
|
async send(turn, message) {
|
|
3097
3415
|
const common = {
|
|
3098
3416
|
companyId: turn.companyId,
|
|
@@ -3100,14 +3418,29 @@ var FlowRunner = class {
|
|
|
3100
3418
|
sender: "bot",
|
|
3101
3419
|
startState: this.dependencies.startState
|
|
3102
3420
|
};
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3421
|
+
const deliver = /* @__PURE__ */ __name(async () => {
|
|
3422
|
+
if (message.kind === "text") await this.dependencies.sendMessage.sendText({
|
|
3423
|
+
...common,
|
|
3424
|
+
body: message.body
|
|
3425
|
+
});
|
|
3426
|
+
else await this.dependencies.sendMessage.sendInteractive({
|
|
3427
|
+
...common,
|
|
3428
|
+
interactive: message.interactive
|
|
3429
|
+
});
|
|
3430
|
+
}, "deliver");
|
|
3431
|
+
try {
|
|
3432
|
+
await sendWithRetry(deliver, this.dependencies.config.sendRetry);
|
|
3433
|
+
} catch (failure) {
|
|
3434
|
+
if (!(failure instanceof SendRetriesExhausted)) throw failure;
|
|
3435
|
+
if (typeof failure.error === "object" && failure.error !== null) {
|
|
3436
|
+
this.sendFailures.set(failure.error, {
|
|
3437
|
+
attempts: failure.attempts,
|
|
3438
|
+
messageKind: message.kind,
|
|
3439
|
+
isTransient: failure.isTransient
|
|
3440
|
+
});
|
|
3441
|
+
}
|
|
3442
|
+
throw failure.error;
|
|
3443
|
+
}
|
|
3111
3444
|
}
|
|
3112
3445
|
save(turn, progress) {
|
|
3113
3446
|
const runtime = runtimeOf(progress.context);
|
|
@@ -3127,7 +3460,7 @@ var FlowRunner = class {
|
|
|
3127
3460
|
nodeId: null,
|
|
3128
3461
|
context
|
|
3129
3462
|
});
|
|
3130
|
-
await this.report(turn, fromFlowKey, null, "cross-flow", new
|
|
3463
|
+
await this.report(turn, fromFlowKey, null, "cross-flow", new import_meta_whatsapp_contracts16.FlowRunnerError("flow-not-found", target));
|
|
3131
3464
|
}
|
|
3132
3465
|
/**
|
|
3133
3466
|
* Nunca relança: só é chamado depois de o turno ter sido gravado, e relançar faria a fila repetir
|
|
@@ -3135,12 +3468,16 @@ var FlowRunner = class {
|
|
|
3135
3468
|
* ponto gravado e a próxima mensagem do cliente segue dali); gancho que falha também não derruba.
|
|
3136
3469
|
*/
|
|
3137
3470
|
async report(turn, flowKey, nodeId, stage, error) {
|
|
3471
|
+
const send = typeof error === "object" && error !== null ? this.sendFailures.get(error) : void 0;
|
|
3138
3472
|
const details = {
|
|
3139
3473
|
companyId: turn.companyId,
|
|
3140
3474
|
whatsappNumber: turn.session.whatsappNumber,
|
|
3141
3475
|
flowKey,
|
|
3142
3476
|
nodeId,
|
|
3143
|
-
stage
|
|
3477
|
+
stage,
|
|
3478
|
+
...send ? {
|
|
3479
|
+
send
|
|
3480
|
+
} : {}
|
|
3144
3481
|
};
|
|
3145
3482
|
try {
|
|
3146
3483
|
await this.dependencies.hooks?.onFlowRunnerError?.(error, details);
|
|
@@ -3150,7 +3487,7 @@ var FlowRunner = class {
|
|
|
3150
3487
|
};
|
|
3151
3488
|
|
|
3152
3489
|
// src/flows/FlowHandoff.ts
|
|
3153
|
-
var
|
|
3490
|
+
var import_meta_whatsapp_contracts17 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3154
3491
|
function readParam(node, key) {
|
|
3155
3492
|
const value = node?.actionParams?.[key];
|
|
3156
3493
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
@@ -3180,7 +3517,7 @@ var FlowHandoff = class {
|
|
|
3180
3517
|
await sendMessage.sendText({
|
|
3181
3518
|
companyId: params.companyId,
|
|
3182
3519
|
whatsappNumber: params.whatsappNumber,
|
|
3183
|
-
body: (0,
|
|
3520
|
+
body: (0, import_meta_whatsapp_contracts17.interpolateFlowText)(template, params.variables, interpolation),
|
|
3184
3521
|
sender: "bot",
|
|
3185
3522
|
startState
|
|
3186
3523
|
});
|
|
@@ -3223,7 +3560,7 @@ var FlowHandoff = class {
|
|
|
3223
3560
|
async isWithinHours(companyId) {
|
|
3224
3561
|
const source = this.dependencies.config.businessHours;
|
|
3225
3562
|
const hours = typeof source === "function" ? await source(companyId) : source;
|
|
3226
|
-
return hours ? (0,
|
|
3563
|
+
return hours ? (0, import_meta_whatsapp_contracts17.isWithinBusinessHours)(hours, this.dependencies.now()) : true;
|
|
3227
3564
|
}
|
|
3228
3565
|
async messageFor(isWithinHours, params) {
|
|
3229
3566
|
const { config } = this.dependencies;
|
|
@@ -3256,7 +3593,7 @@ var FlowHandoff = class {
|
|
|
3256
3593
|
};
|
|
3257
3594
|
|
|
3258
3595
|
// src/flows/flowTurnLock.ts
|
|
3259
|
-
var
|
|
3596
|
+
var import_drizzle_orm8 = require("drizzle-orm");
|
|
3260
3597
|
function lockName(key) {
|
|
3261
3598
|
return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
|
|
3262
3599
|
}
|
|
@@ -3271,7 +3608,7 @@ var PostgresAdvisoryFlowTurnLock = class {
|
|
|
3271
3608
|
}
|
|
3272
3609
|
withLock(key, work) {
|
|
3273
3610
|
return this.db.transaction(async (transaction) => {
|
|
3274
|
-
await transaction.execute(
|
|
3611
|
+
await transaction.execute(import_drizzle_orm8.sql`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
|
|
3275
3612
|
return work();
|
|
3276
3613
|
});
|
|
3277
3614
|
}
|
|
@@ -3459,7 +3796,7 @@ async function listAvailableProducts(params) {
|
|
|
3459
3796
|
__name(listAvailableProducts, "listAvailableProducts");
|
|
3460
3797
|
|
|
3461
3798
|
// src/repositories/FlowMediaRepository.ts
|
|
3462
|
-
var
|
|
3799
|
+
var import_drizzle_orm9 = require("drizzle-orm");
|
|
3463
3800
|
var FlowMediaRepository = class {
|
|
3464
3801
|
static {
|
|
3465
3802
|
__name(this, "FlowMediaRepository");
|
|
@@ -3469,18 +3806,18 @@ var FlowMediaRepository = class {
|
|
|
3469
3806
|
this.db = db;
|
|
3470
3807
|
}
|
|
3471
3808
|
locationFilter(location) {
|
|
3472
|
-
return (0,
|
|
3809
|
+
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));
|
|
3473
3810
|
}
|
|
3474
3811
|
// O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
|
|
3475
3812
|
// é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
|
|
3476
3813
|
// justamente o material que alguém desligou.
|
|
3477
3814
|
async listActive(location) {
|
|
3478
|
-
return this.db.select().from(flowMedia).where((0,
|
|
3815
|
+
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));
|
|
3479
3816
|
}
|
|
3480
3817
|
// Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
|
|
3481
3818
|
// poder ser religado.
|
|
3482
3819
|
async listAll(location) {
|
|
3483
|
-
return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy((0,
|
|
3820
|
+
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));
|
|
3484
3821
|
}
|
|
3485
3822
|
/**
|
|
3486
3823
|
* Anexa um arquivo já existente no storage ao nó.
|
|
@@ -3511,7 +3848,7 @@ var FlowMediaRepository = class {
|
|
|
3511
3848
|
caption: params.caption ?? null,
|
|
3512
3849
|
sortOrder: params.sortOrder ?? 0,
|
|
3513
3850
|
active: true,
|
|
3514
|
-
updatedAt:
|
|
3851
|
+
updatedAt: import_drizzle_orm9.sql`now()`
|
|
3515
3852
|
}
|
|
3516
3853
|
}).returning();
|
|
3517
3854
|
return row;
|
|
@@ -3527,8 +3864,8 @@ var FlowMediaRepository = class {
|
|
|
3527
3864
|
...params.active !== void 0 ? {
|
|
3528
3865
|
active: params.active
|
|
3529
3866
|
} : {},
|
|
3530
|
-
updatedAt:
|
|
3531
|
-
}).where((0,
|
|
3867
|
+
updatedAt: import_drizzle_orm9.sql`now()`
|
|
3868
|
+
}).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();
|
|
3532
3869
|
return row;
|
|
3533
3870
|
}
|
|
3534
3871
|
/**
|
|
@@ -3537,17 +3874,17 @@ var FlowMediaRepository = class {
|
|
|
3537
3874
|
* host, que é dono da biblioteca de arquivos.
|
|
3538
3875
|
*/
|
|
3539
3876
|
async detach(params) {
|
|
3540
|
-
await this.db.delete(flowMedia).where((0,
|
|
3877
|
+
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)));
|
|
3541
3878
|
}
|
|
3542
3879
|
// Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
|
|
3543
3880
|
async detachRemovedNodes(params) {
|
|
3544
|
-
const condition = params.existingNodeIds.length === 0 ? void 0 :
|
|
3545
|
-
await this.db.delete(flowMedia).where((0,
|
|
3881
|
+
const condition = params.existingNodeIds.length === 0 ? void 0 : import_drizzle_orm9.sql`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
|
|
3882
|
+
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));
|
|
3546
3883
|
}
|
|
3547
3884
|
};
|
|
3548
3885
|
|
|
3549
3886
|
// src/repositories/FlowMediaIdRepository.ts
|
|
3550
|
-
var
|
|
3887
|
+
var import_drizzle_orm10 = require("drizzle-orm");
|
|
3551
3888
|
var FlowMediaIdRepository = class {
|
|
3552
3889
|
static {
|
|
3553
3890
|
__name(this, "FlowMediaIdRepository");
|
|
@@ -3559,7 +3896,7 @@ var FlowMediaIdRepository = class {
|
|
|
3559
3896
|
async get(params) {
|
|
3560
3897
|
const rows = await this.db.select({
|
|
3561
3898
|
ids: flowMedia.metaMediaIds
|
|
3562
|
-
}).from(flowMedia).where((0,
|
|
3899
|
+
}).from(flowMedia).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId)).limit(1);
|
|
3563
3900
|
return rows[0]?.ids?.[params.senderKey];
|
|
3564
3901
|
}
|
|
3565
3902
|
/**
|
|
@@ -3571,23 +3908,23 @@ var FlowMediaIdRepository = class {
|
|
|
3571
3908
|
*/
|
|
3572
3909
|
async set(params) {
|
|
3573
3910
|
await this.db.update(flowMedia).set({
|
|
3574
|
-
metaMediaIds:
|
|
3575
|
-
}).where((0,
|
|
3911
|
+
metaMediaIds: import_drizzle_orm10.sql`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
|
|
3912
|
+
}).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId));
|
|
3576
3913
|
}
|
|
3577
3914
|
/** Remove só a chave deste número — o id do outro número continua válido. */
|
|
3578
3915
|
async clear(params) {
|
|
3579
3916
|
await this.db.update(flowMedia).set({
|
|
3580
|
-
metaMediaIds:
|
|
3581
|
-
}).where((0,
|
|
3917
|
+
metaMediaIds: import_drizzle_orm10.sql`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
|
|
3918
|
+
}).where((0, import_drizzle_orm10.eq)(flowMedia.id, params.flowMediaId));
|
|
3582
3919
|
}
|
|
3583
3920
|
};
|
|
3584
3921
|
|
|
3585
3922
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3586
|
-
var
|
|
3587
|
-
var
|
|
3923
|
+
var import_meta_graph_core3 = require("@adatechnology/meta-graph-core");
|
|
3924
|
+
var import_meta_whatsapp_contracts19 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3588
3925
|
|
|
3589
3926
|
// src/channel/previewMedia.ts
|
|
3590
|
-
var
|
|
3927
|
+
var import_meta_whatsapp_contracts18 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3591
3928
|
|
|
3592
3929
|
// src/channel/WhatsAppChannelAdapter.ts
|
|
3593
3930
|
var WhatsAppChannelAdapter = class {
|
|
@@ -3604,14 +3941,14 @@ var WhatsAppChannelAdapter = class {
|
|
|
3604
3941
|
}
|
|
3605
3942
|
/** `preview.<uuid>` quando o destino é contato do simulador e o recurso está ligado. */
|
|
3606
3943
|
previewMessageId(to) {
|
|
3607
|
-
if (!this.previewContacts?.isEnabled || !(0,
|
|
3944
|
+
if (!this.previewContacts?.isEnabled || !(0, import_meta_whatsapp_contracts19.isPreviewContact)(to)) return void 0;
|
|
3608
3945
|
return `preview.${this.previewContacts.generateId?.() ?? globalThis.crypto.randomUUID()}`;
|
|
3609
3946
|
}
|
|
3610
3947
|
async translateErrors(operation) {
|
|
3611
3948
|
try {
|
|
3612
3949
|
return await operation();
|
|
3613
3950
|
} catch (error) {
|
|
3614
|
-
if (error instanceof
|
|
3951
|
+
if (error instanceof import_meta_graph_core3.WhatsAppWindowExpiredError) throw new import_meta_whatsapp_contracts19.WindowExpiredError();
|
|
3615
3952
|
throw error;
|
|
3616
3953
|
}
|
|
3617
3954
|
}
|
|
@@ -3714,7 +4051,7 @@ var WhatsAppChannelAdapter = class {
|
|
|
3714
4051
|
* tentar buscá-lo lá renderia um 404 confuso em vez do áudio que o operador acabou de gravar.
|
|
3715
4052
|
*/
|
|
3716
4053
|
async fetchMediaAsBase64(mediaId) {
|
|
3717
|
-
const uploadId = this.previewMedia?.isEnabled ? (0,
|
|
4054
|
+
const uploadId = this.previewMedia?.isEnabled ? (0, import_meta_whatsapp_contracts18.resolvePreviewUploadId)(mediaId) : void 0;
|
|
3718
4055
|
if (uploadId) {
|
|
3719
4056
|
const buffer = await this.previewMedia.objectStorage.getObject(uploadId);
|
|
3720
4057
|
return {
|
|
@@ -3727,42 +4064,42 @@ var WhatsAppChannelAdapter = class {
|
|
|
3727
4064
|
};
|
|
3728
4065
|
|
|
3729
4066
|
// src/channel/ReceiveWebhook.use-case.ts
|
|
3730
|
-
var
|
|
4067
|
+
var import_meta_whatsapp_contracts22 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3731
4068
|
|
|
3732
4069
|
// src/channel/webhookSecurity.ts
|
|
3733
|
-
var
|
|
3734
|
-
var
|
|
4070
|
+
var import_meta_graph_core4 = require("@adatechnology/meta-graph-core");
|
|
4071
|
+
var import_meta_whatsapp_contracts20 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3735
4072
|
var WEBHOOK_NONCE_NAMESPACE = "meta-whatsapp";
|
|
3736
4073
|
function verifyWebhookChallenge(params) {
|
|
3737
|
-
if (!(0,
|
|
4074
|
+
if (!(0, import_meta_graph_core4.isValidWebhookChallenge)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
3738
4075
|
return params.challenge;
|
|
3739
4076
|
}
|
|
3740
4077
|
__name(verifyWebhookChallenge, "verifyWebhookChallenge");
|
|
3741
4078
|
function verifyWebhookSignature(params) {
|
|
3742
|
-
if (!(0,
|
|
4079
|
+
if (!(0, import_meta_graph_core4.isValidWebhookSignature)(params)) throw new import_meta_whatsapp_contracts20.InvalidWebhookSignatureError();
|
|
3743
4080
|
}
|
|
3744
4081
|
__name(verifyWebhookSignature, "verifyWebhookSignature");
|
|
3745
4082
|
function deliveryKey(signatureHeader) {
|
|
3746
|
-
return (0,
|
|
4083
|
+
return (0, import_meta_graph_core4.buildWebhookDeliveryKey)({
|
|
3747
4084
|
namespace: WEBHOOK_NONCE_NAMESPACE,
|
|
3748
4085
|
signatureHeader
|
|
3749
4086
|
});
|
|
3750
4087
|
}
|
|
3751
4088
|
__name(deliveryKey, "deliveryKey");
|
|
3752
4089
|
async function claimWebhookDelivery(params) {
|
|
3753
|
-
return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ??
|
|
4090
|
+
return params.nonceStore.setIfAbsent(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_CLAIM_TTL_SECONDS);
|
|
3754
4091
|
}
|
|
3755
4092
|
__name(claimWebhookDelivery, "claimWebhookDelivery");
|
|
3756
4093
|
async function confirmWebhookDelivery(params) {
|
|
3757
|
-
await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ??
|
|
4094
|
+
await params.nonceStore.confirm?.(deliveryKey(params.signatureHeader), params.ttlSeconds ?? import_meta_graph_core4.WEBHOOK_NONCE_TTL_SECONDS);
|
|
3758
4095
|
}
|
|
3759
4096
|
__name(confirmWebhookDelivery, "confirmWebhookDelivery");
|
|
3760
4097
|
|
|
3761
4098
|
// src/channel/IngestInboundMedia.use-case.ts
|
|
3762
|
-
var
|
|
4099
|
+
var import_drizzle_orm11 = require("drizzle-orm");
|
|
3763
4100
|
|
|
3764
4101
|
// src/use-cases/TranscribeAudio.use-case.ts
|
|
3765
|
-
var
|
|
4102
|
+
var import_meta_whatsapp_contracts21 = require("@adatechnology/meta-whatsapp-contracts");
|
|
3766
4103
|
|
|
3767
4104
|
// src/transcription.types.ts
|
|
3768
4105
|
var TRANSCRIPTION_STATUS = {
|
|
@@ -3823,7 +4160,7 @@ var TranscribeAudioUseCase = class {
|
|
|
3823
4160
|
}
|
|
3824
4161
|
if (this.dependencies.resolvePolicy) {
|
|
3825
4162
|
const policy = await this.dependencies.resolvePolicy(params.companyId);
|
|
3826
|
-
if (!policy.isEnabled) throw new
|
|
4163
|
+
if (!policy.isEnabled) throw new import_meta_whatsapp_contracts21.TranscriptionDisabledError();
|
|
3827
4164
|
}
|
|
3828
4165
|
const audio = extractAudioReference(message);
|
|
3829
4166
|
const buffer = await this.dependencies.objectStorage.getObject(audio.uploadId);
|
|
@@ -3900,11 +4237,11 @@ function extractAudioReference(message) {
|
|
|
3900
4237
|
const audio = payload["audio"];
|
|
3901
4238
|
const mimeType = typeof payload["mimeType"] === "string" ? payload["mimeType"] : audio?.mime_type;
|
|
3902
4239
|
if (!isAudioMimeType(mimeType) && !audio) {
|
|
3903
|
-
throw new
|
|
4240
|
+
throw new import_meta_whatsapp_contracts21.MessageNotAudioError(message.id, message.type);
|
|
3904
4241
|
}
|
|
3905
4242
|
const uploadId = payload["uploadId"];
|
|
3906
4243
|
if (typeof uploadId !== "string" || uploadId.length === 0) {
|
|
3907
|
-
throw new
|
|
4244
|
+
throw new import_meta_whatsapp_contracts21.AudioNotIngestedError(message.id);
|
|
3908
4245
|
}
|
|
3909
4246
|
return {
|
|
3910
4247
|
uploadId,
|
|
@@ -3931,7 +4268,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3931
4268
|
this.transcription = transcription;
|
|
3932
4269
|
}
|
|
3933
4270
|
async execute(params) {
|
|
3934
|
-
const [message] = await this.db.select().from(messages).where((0,
|
|
4271
|
+
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);
|
|
3935
4272
|
if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
|
|
3936
4273
|
const payload = message.payload ?? {};
|
|
3937
4274
|
if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
|
|
@@ -3962,7 +4299,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3962
4299
|
};
|
|
3963
4300
|
await this.db.update(messages).set({
|
|
3964
4301
|
payload: updatedPayload
|
|
3965
|
-
}).where((0,
|
|
4302
|
+
}).where((0, import_drizzle_orm11.and)((0, import_drizzle_orm11.eq)(messages.companyId, params.companyId), (0, import_drizzle_orm11.eq)(messages.id, params.messageId)));
|
|
3966
4303
|
await this.documentRepository?.link({
|
|
3967
4304
|
companyId: params.companyId,
|
|
3968
4305
|
sessionId: message.sessionId,
|
|
@@ -4120,8 +4457,8 @@ function extractPayload(message, { isLocationRedacted } = DEFAULT_EXTRACTION_OPT
|
|
|
4120
4457
|
}
|
|
4121
4458
|
__name(extractPayload, "extractPayload");
|
|
4122
4459
|
var ACCOUNT_EVENT_FIELDS = [
|
|
4123
|
-
|
|
4124
|
-
|
|
4460
|
+
import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE,
|
|
4461
|
+
import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.PHONE_NUMBER_QUALITY_UPDATE
|
|
4125
4462
|
];
|
|
4126
4463
|
function isAccountEventField(field) {
|
|
4127
4464
|
return field !== void 0 && ACCOUNT_EVENT_FIELDS.includes(field);
|
|
@@ -4163,7 +4500,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4163
4500
|
...EMPTY_RESULT
|
|
4164
4501
|
};
|
|
4165
4502
|
const rawText = typeof input.rawBody === "string" ? input.rawBody : input.rawBody.toString("utf8");
|
|
4166
|
-
const parsed =
|
|
4503
|
+
const parsed = import_meta_whatsapp_contracts22.whatsAppWebhookPayloadSchema.safeParse(JSON.parse(rawText));
|
|
4167
4504
|
if (!parsed.success) {
|
|
4168
4505
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4169
4506
|
field: void 0,
|
|
@@ -4196,7 +4533,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4196
4533
|
continue;
|
|
4197
4534
|
}
|
|
4198
4535
|
for (const message of change.value.messages ?? []) {
|
|
4199
|
-
const profileName = (0,
|
|
4536
|
+
const profileName = (0, import_meta_whatsapp_contracts22.resolveContactProfileName)({
|
|
4200
4537
|
contacts: change.value.contacts,
|
|
4201
4538
|
from: message.from
|
|
4202
4539
|
});
|
|
@@ -4234,8 +4571,8 @@ var ReceiveWebhookUseCase = class {
|
|
|
4234
4571
|
// Devolve `false` quando o corpo não bate com o schema do field — o chamador conta como não
|
|
4235
4572
|
// tratado. O host é avisado nos dois casos, mas com `reason` diferente.
|
|
4236
4573
|
async handleAccountEvent(change) {
|
|
4237
|
-
if (change.field ===
|
|
4238
|
-
const update =
|
|
4574
|
+
if (change.field === import_meta_whatsapp_contracts22.WHATSAPP_WEBHOOK_FIELDS.TEMPLATE_STATUS_UPDATE) {
|
|
4575
|
+
const update = import_meta_whatsapp_contracts22.whatsAppTemplateStatusUpdateSchema.safeParse(change.value);
|
|
4239
4576
|
if (!update.success) {
|
|
4240
4577
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4241
4578
|
field: change.field,
|
|
@@ -4247,7 +4584,7 @@ var ReceiveWebhookUseCase = class {
|
|
|
4247
4584
|
await this.params.hooks?.onTemplateStatusUpdate?.(update.data);
|
|
4248
4585
|
return true;
|
|
4249
4586
|
}
|
|
4250
|
-
const quality =
|
|
4587
|
+
const quality = import_meta_whatsapp_contracts22.whatsAppPhoneNumberQualityUpdateSchema.safeParse(change.value);
|
|
4251
4588
|
if (!quality.success) {
|
|
4252
4589
|
await this.params.hooks?.onUnhandledWebhookEvent?.({
|
|
4253
4590
|
field: change.field,
|
|
@@ -4379,7 +4716,7 @@ var StorePreviewMediaUseCase = class {
|
|
|
4379
4716
|
key
|
|
4380
4717
|
});
|
|
4381
4718
|
return {
|
|
4382
|
-
mediaId: (0,
|
|
4719
|
+
mediaId: (0, import_meta_whatsapp_contracts18.toPreviewMediaId)(uploadId),
|
|
4383
4720
|
uploadId
|
|
4384
4721
|
};
|
|
4385
4722
|
}
|
|
@@ -4411,6 +4748,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4411
4748
|
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;
|
|
4412
4749
|
const flowGraphRepository = new FlowGraphRepository(db, flowGraphCache);
|
|
4413
4750
|
const documentRepository = new DocumentRepository(db);
|
|
4751
|
+
const quickReplyRepository = new QuickReplyRepository(db);
|
|
4414
4752
|
const flowMediaRepository = new FlowMediaRepository(db);
|
|
4415
4753
|
const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
|
|
4416
4754
|
const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
|
|
@@ -4446,7 +4784,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4446
4784
|
} : {}
|
|
4447
4785
|
}) : void 0;
|
|
4448
4786
|
if (flowInterpreter && flowRunner && flowHandoff) {
|
|
4449
|
-
flowInterpreter.registerFlowAction(
|
|
4787
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.HANDOFF, flowHandoff.createActionHandler((turn) => flowRunner.variablesFor(turn)));
|
|
4450
4788
|
}
|
|
4451
4789
|
const receiveWebhook = new ReceiveWebhookUseCase({
|
|
4452
4790
|
appSecret: config.appSecret,
|
|
@@ -4467,7 +4805,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4467
4805
|
} : {}
|
|
4468
4806
|
});
|
|
4469
4807
|
if (flowInterpreter && providers.objectStorage?.getObject) {
|
|
4470
|
-
flowInterpreter.registerFlowAction(
|
|
4808
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.SEND_MEDIA, createSendMediaAction({
|
|
4471
4809
|
flowMediaRepository,
|
|
4472
4810
|
objectStorage: providers.objectStorage,
|
|
4473
4811
|
logMessage,
|
|
@@ -4484,7 +4822,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4484
4822
|
}));
|
|
4485
4823
|
}
|
|
4486
4824
|
if (flowInterpreter && providers.catalog && config.catalogId) {
|
|
4487
|
-
flowInterpreter.registerFlowAction(
|
|
4825
|
+
flowInterpreter.registerFlowAction(import_meta_whatsapp_contracts23.FLOW_ACTION_KIND.SEND_PRODUCT_LIST, createSendProductListAction({
|
|
4488
4826
|
catalog: providers.catalog,
|
|
4489
4827
|
catalogId: config.catalogId,
|
|
4490
4828
|
logMessage,
|
|
@@ -4568,6 +4906,18 @@ function createMetaWhatsAppModule(params) {
|
|
|
4568
4906
|
} : void 0,
|
|
4569
4907
|
settings: settingsRepository,
|
|
4570
4908
|
/**
|
|
4909
|
+
* Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
|
|
4910
|
+
* `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
|
|
4911
|
+
* casos de uso daqui.
|
|
4912
|
+
*/
|
|
4913
|
+
quickReplies: {
|
|
4914
|
+
list: new ListQuickRepliesUseCase(quickReplyRepository),
|
|
4915
|
+
create: new CreateQuickReplyUseCase(quickReplyRepository),
|
|
4916
|
+
update: new UpdateQuickReplyUseCase(quickReplyRepository),
|
|
4917
|
+
delete: new DeleteQuickReplyUseCase(quickReplyRepository),
|
|
4918
|
+
repository: quickReplyRepository
|
|
4919
|
+
},
|
|
4920
|
+
/**
|
|
4571
4921
|
* `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
|
|
4572
4922
|
* ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
|
|
4573
4923
|
*/
|
|
@@ -4613,13 +4963,14 @@ function createMetaWhatsAppModule(params) {
|
|
|
4613
4963
|
// undefined quando `features.flowRunner` está desligado — o host dirige a conversa.
|
|
4614
4964
|
runner: flowRunner,
|
|
4615
4965
|
registerDynamicChoiceProvider: /* @__PURE__ */ __name((key, provider) => {
|
|
4616
|
-
if (!flowRunner) throw new
|
|
4966
|
+
if (!flowRunner) throw new import_meta_whatsapp_contracts23.ConfigMissingError("features.flowRunner");
|
|
4617
4967
|
flowRunner.registerDynamicChoiceProvider(key, provider);
|
|
4618
4968
|
}, "registerDynamicChoiceProvider"),
|
|
4619
4969
|
get: new GetFlowGraphUseCase(flowGraphRepository),
|
|
4620
4970
|
list: new ListFlowGraphsUseCase(flowGraphRepository),
|
|
4621
4971
|
create: new CreateFlowGraphUseCase(flowGraphRepository),
|
|
4622
4972
|
save: new SaveFlowGraphUseCase(flowGraphRepository),
|
|
4973
|
+
reseed: new ReseedFlowGraphUseCase(flowGraphRepository),
|
|
4623
4974
|
delete: new DeleteFlowGraphUseCase(flowGraphRepository),
|
|
4624
4975
|
livePositions: new GetLiveFlowPositionsUseCase(flowGraphRepository),
|
|
4625
4976
|
repository: flowGraphRepository,
|
|
@@ -4737,18 +5088,149 @@ async function redeemSseTicket(store, ticket) {
|
|
|
4737
5088
|
return JSON.parse(raw);
|
|
4738
5089
|
}
|
|
4739
5090
|
__name(redeemSseTicket, "redeemSseTicket");
|
|
5091
|
+
|
|
5092
|
+
// src/http/quickReplyRoutes.ts
|
|
5093
|
+
var import_meta_whatsapp_contracts24 = require("@adatechnology/meta-whatsapp-contracts");
|
|
5094
|
+
var import_module_http = require("@adatechnology/module-http");
|
|
5095
|
+
|
|
5096
|
+
// src/http/quickReplyScope.constant.ts
|
|
5097
|
+
var QUICK_REPLY_SCOPE = {
|
|
5098
|
+
WRITE: "quick-replies:write"
|
|
5099
|
+
};
|
|
5100
|
+
var DEFAULT_QUICK_REPLY_WRITE_SCOPES = [
|
|
5101
|
+
QUICK_REPLY_SCOPE.WRITE
|
|
5102
|
+
];
|
|
5103
|
+
|
|
5104
|
+
// src/http/quickReplyRoutes.ts
|
|
5105
|
+
function requireCompany(context) {
|
|
5106
|
+
if (!context.auth?.companyId) {
|
|
5107
|
+
throw new import_meta_whatsapp_contracts24.MetaWhatsAppError("Rota exige contexto autenticado.", 401, import_meta_whatsapp_contracts24.META_WHATSAPP_ERROR_CODES.CONFIG_MISSING);
|
|
5108
|
+
}
|
|
5109
|
+
return context.auth.companyId;
|
|
5110
|
+
}
|
|
5111
|
+
__name(requireCompany, "requireCompany");
|
|
5112
|
+
function requireId(context) {
|
|
5113
|
+
const id = context.params.id;
|
|
5114
|
+
if (!id) throw new import_meta_whatsapp_contracts24.QuickReplyNotFoundError("");
|
|
5115
|
+
return id;
|
|
5116
|
+
}
|
|
5117
|
+
__name(requireId, "requireId");
|
|
5118
|
+
function createMetaWhatsAppQuickReplyRoutes(params) {
|
|
5119
|
+
const { list, create, update, delete: remove } = params.module.quickReplies;
|
|
5120
|
+
const write = {
|
|
5121
|
+
scope: import_module_http.ROUTE_SCOPE.ADMIN,
|
|
5122
|
+
requiredScopes: params.scopes?.write ?? DEFAULT_QUICK_REPLY_WRITE_SCOPES
|
|
5123
|
+
};
|
|
5124
|
+
const read = {
|
|
5125
|
+
scope: import_module_http.ROUTE_SCOPE.USER,
|
|
5126
|
+
...params.scopes?.read?.length ? {
|
|
5127
|
+
requiredScopes: params.scopes.read
|
|
5128
|
+
} : {}
|
|
5129
|
+
};
|
|
5130
|
+
const routes = [
|
|
5131
|
+
{
|
|
5132
|
+
...read,
|
|
5133
|
+
method: import_module_http.HTTP_METHOD.GET,
|
|
5134
|
+
path: "/quick-replies",
|
|
5135
|
+
querySchema: import_meta_whatsapp_contracts24.listWhatsAppQuickRepliesQuerySchema,
|
|
5136
|
+
operationId: "listWhatsAppQuickReplies",
|
|
5137
|
+
summary: "Lista as respostas r\xE1pidas da empresa, na ordem de exibi\xE7\xE3o",
|
|
5138
|
+
async handler(context) {
|
|
5139
|
+
const query = context.query;
|
|
5140
|
+
const data = await list.execute({
|
|
5141
|
+
companyId: requireCompany(context),
|
|
5142
|
+
...query
|
|
5143
|
+
});
|
|
5144
|
+
return {
|
|
5145
|
+
kind: "json",
|
|
5146
|
+
status: 200,
|
|
5147
|
+
body: {
|
|
5148
|
+
data
|
|
5149
|
+
}
|
|
5150
|
+
};
|
|
5151
|
+
}
|
|
5152
|
+
},
|
|
5153
|
+
{
|
|
5154
|
+
...write,
|
|
5155
|
+
method: import_module_http.HTTP_METHOD.POST,
|
|
5156
|
+
path: "/quick-replies",
|
|
5157
|
+
bodySchema: import_meta_whatsapp_contracts24.whatsAppQuickReplyInputSchema,
|
|
5158
|
+
operationId: "createWhatsAppQuickReply",
|
|
5159
|
+
summary: "Cria uma resposta r\xE1pida (atalho \xFAnico por empresa)",
|
|
5160
|
+
async handler(context) {
|
|
5161
|
+
const input = context.body;
|
|
5162
|
+
const data = await create.execute({
|
|
5163
|
+
...input,
|
|
5164
|
+
companyId: requireCompany(context)
|
|
5165
|
+
});
|
|
5166
|
+
return {
|
|
5167
|
+
kind: "json",
|
|
5168
|
+
status: 201,
|
|
5169
|
+
body: {
|
|
5170
|
+
data
|
|
5171
|
+
}
|
|
5172
|
+
};
|
|
5173
|
+
}
|
|
5174
|
+
},
|
|
5175
|
+
{
|
|
5176
|
+
...write,
|
|
5177
|
+
method: import_module_http.HTTP_METHOD.PUT,
|
|
5178
|
+
path: "/quick-replies/:id",
|
|
5179
|
+
bodySchema: import_meta_whatsapp_contracts24.whatsAppQuickReplyInputSchema,
|
|
5180
|
+
operationId: "updateWhatsAppQuickReply",
|
|
5181
|
+
summary: "Substitui t\xEDtulo, atalho e texto de uma resposta r\xE1pida",
|
|
5182
|
+
async handler(context) {
|
|
5183
|
+
const input = context.body;
|
|
5184
|
+
const data = await update.execute({
|
|
5185
|
+
...input,
|
|
5186
|
+
companyId: requireCompany(context),
|
|
5187
|
+
id: requireId(context)
|
|
5188
|
+
});
|
|
5189
|
+
return {
|
|
5190
|
+
kind: "json",
|
|
5191
|
+
status: 200,
|
|
5192
|
+
body: {
|
|
5193
|
+
data
|
|
5194
|
+
}
|
|
5195
|
+
};
|
|
5196
|
+
}
|
|
5197
|
+
},
|
|
5198
|
+
{
|
|
5199
|
+
...write,
|
|
5200
|
+
method: import_module_http.HTTP_METHOD.DELETE,
|
|
5201
|
+
path: "/quick-replies/:id",
|
|
5202
|
+
operationId: "deleteWhatsAppQuickReply",
|
|
5203
|
+
summary: "Apaga uma resposta r\xE1pida",
|
|
5204
|
+
async handler(context) {
|
|
5205
|
+
await remove.execute({
|
|
5206
|
+
companyId: requireCompany(context),
|
|
5207
|
+
id: requireId(context)
|
|
5208
|
+
});
|
|
5209
|
+
return {
|
|
5210
|
+
kind: "empty",
|
|
5211
|
+
status: 204
|
|
5212
|
+
};
|
|
5213
|
+
}
|
|
5214
|
+
}
|
|
5215
|
+
];
|
|
5216
|
+
return routes;
|
|
5217
|
+
}
|
|
5218
|
+
__name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes");
|
|
4740
5219
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4741
5220
|
0 && (module.exports = {
|
|
4742
5221
|
CountInboundLocationsUseCase,
|
|
4743
5222
|
CreateFlowGraphUseCase,
|
|
5223
|
+
CreateQuickReplyUseCase,
|
|
4744
5224
|
DEFAULT_FALLBACK_LIST_LABEL,
|
|
4745
5225
|
DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
|
|
4746
5226
|
DEFAULT_FLOW_TEXT,
|
|
4747
5227
|
DEFAULT_MAX_INVALID_ANSWERS,
|
|
5228
|
+
DEFAULT_QUICK_REPLY_WRITE_SCOPES,
|
|
4748
5229
|
DEFAULT_START_FLOW_KEY,
|
|
4749
5230
|
DYNAMIC_CHOICE_MORE_ID,
|
|
4750
5231
|
DeleteConversationUseCase,
|
|
4751
5232
|
DeleteFlowGraphUseCase,
|
|
5233
|
+
DeleteQuickReplyUseCase,
|
|
4752
5234
|
DocumentRepository,
|
|
4753
5235
|
ExportConversationUseCase,
|
|
4754
5236
|
FLOW_RUNTIME_CONTEXT_KEY,
|
|
@@ -4771,6 +5253,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4771
5253
|
ListConversationsUseCase,
|
|
4772
5254
|
ListFlowGraphsUseCase,
|
|
4773
5255
|
ListMessagesUseCase,
|
|
5256
|
+
ListQuickRepliesUseCase,
|
|
4774
5257
|
LogMessageUseCase,
|
|
4775
5258
|
META_WHATSAPP_MIGRATIONS_TABLE,
|
|
4776
5259
|
MessageRepository,
|
|
@@ -4780,10 +5263,13 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4780
5263
|
PostgresAdvisoryFlowTurnLock,
|
|
4781
5264
|
ProcessInboundDispatchUseCase,
|
|
4782
5265
|
PurgeExpiredDocumentsUseCase,
|
|
5266
|
+
QUICK_REPLY_SCOPE,
|
|
5267
|
+
QuickReplyRepository,
|
|
4783
5268
|
ReceiveWebhookUseCase,
|
|
4784
5269
|
RedactInboundLocationsUseCase,
|
|
4785
5270
|
ReleaseConversationUseCase,
|
|
4786
5271
|
RequestHumanConversationUseCase,
|
|
5272
|
+
ReseedFlowGraphUseCase,
|
|
4787
5273
|
SaveFlowGraphUseCase,
|
|
4788
5274
|
SendMessageUseCase,
|
|
4789
5275
|
SessionRepository,
|
|
@@ -4794,6 +5280,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4794
5280
|
TRANSCRIPTION_STATUS,
|
|
4795
5281
|
TakeoverConversationUseCase,
|
|
4796
5282
|
TranscribeAudioUseCase,
|
|
5283
|
+
UpdateQuickReplyUseCase,
|
|
4797
5284
|
WEBHOOK_CLAIM_TTL_SECONDS,
|
|
4798
5285
|
WEBHOOK_NONCE_TTL_SECONDS,
|
|
4799
5286
|
WhatsAppChannelAdapter,
|
|
@@ -4802,6 +5289,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4802
5289
|
claimWebhookDelivery,
|
|
4803
5290
|
confirmWebhookDelivery,
|
|
4804
5291
|
createMetaWhatsAppModule,
|
|
5292
|
+
createMetaWhatsAppQuickReplyRoutes,
|
|
4805
5293
|
createSendMediaAction,
|
|
4806
5294
|
createSendProductListAction,
|
|
4807
5295
|
createTranscriptionPolicyResolver,
|
|
@@ -4812,11 +5300,13 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4812
5300
|
isAudioMimeType,
|
|
4813
5301
|
isChoiceNode,
|
|
4814
5302
|
isRetriableTranscriptionError,
|
|
5303
|
+
isTransientSendError,
|
|
4815
5304
|
isUnsupportedTranscriptionError,
|
|
4816
5305
|
issueSseTicket,
|
|
4817
5306
|
messages,
|
|
4818
5307
|
metaWhatsAppMigrationsFolder,
|
|
4819
5308
|
metaWhatsAppSchema,
|
|
5309
|
+
quickReplies,
|
|
4820
5310
|
readFlowInbound,
|
|
4821
5311
|
redeemSseTicket,
|
|
4822
5312
|
resolveFailureStatus,
|
|
@@ -4828,6 +5318,7 @@ __name(redeemSseTicket, "redeemSseTicket");
|
|
|
4828
5318
|
sessions,
|
|
4829
5319
|
settings,
|
|
4830
5320
|
toPreviewMediaId,
|
|
5321
|
+
toQuickReplyView,
|
|
4831
5322
|
toSessionContract,
|
|
4832
5323
|
transcriptionRetryAfterSeconds,
|
|
4833
5324
|
verifyWebhookChallenge,
|