@adatechnology/meta-whatsapp-module 0.11.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 +64 -0
- package/dist/index.cjs +520 -100
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +303 -3
- package/dist/index.d.ts +303 -3
- package/dist/index.js +434 -25
- 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.js
CHANGED
|
@@ -215,6 +215,14 @@ var flowGraphs = metaWhatsAppSchema.table("flow_graphs", {
|
|
|
215
215
|
menuOptionLabel: varchar("menu_option_label", {
|
|
216
216
|
length: 64
|
|
217
217
|
}),
|
|
218
|
+
// 'seed' | 'edited' (FLOW_GRAPH_ORIGIN). Linha anterior ao campo vira 'edited': sem como saber se
|
|
219
|
+
// alguém mexeu, o reseed do produto não pode sobrescrevê-la.
|
|
220
|
+
origin: varchar("origin", {
|
|
221
|
+
length: 16
|
|
222
|
+
}).notNull().default("edited"),
|
|
223
|
+
seedVersion: varchar("seed_version", {
|
|
224
|
+
length: 64
|
|
225
|
+
}),
|
|
218
226
|
createdAt: timestamp("created_at", {
|
|
219
227
|
withTimezone: true
|
|
220
228
|
}).notNull().defaultNow(),
|
|
@@ -272,6 +280,29 @@ var flowMedia = metaWhatsAppSchema.table("flow_media", {
|
|
|
272
280
|
// receberia o documento repetido.
|
|
273
281
|
uniqueIndex("idx_flow_media_node_upload").on(table.companyId, table.flowKey, table.nodeId, table.uploadId)
|
|
274
282
|
]);
|
|
283
|
+
var quickReplies = metaWhatsAppSchema.table("quick_replies", {
|
|
284
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
285
|
+
companyId: uuid("company_id").notNull(),
|
|
286
|
+
title: varchar("title", {
|
|
287
|
+
length: 40
|
|
288
|
+
}).notNull(),
|
|
289
|
+
shortcut: varchar("shortcut", {
|
|
290
|
+
length: 20
|
|
291
|
+
}).notNull(),
|
|
292
|
+
body: varchar("body", {
|
|
293
|
+
length: 1e3
|
|
294
|
+
}).notNull(),
|
|
295
|
+
sortOrder: integer("sort_order").notNull().default(0),
|
|
296
|
+
createdAt: timestamp("created_at", {
|
|
297
|
+
withTimezone: true
|
|
298
|
+
}).notNull().defaultNow(),
|
|
299
|
+
updatedAt: timestamp("updated_at", {
|
|
300
|
+
withTimezone: true
|
|
301
|
+
}).notNull().defaultNow()
|
|
302
|
+
}, (table) => [
|
|
303
|
+
uniqueIndex("idx_quick_replies_company_shortcut").on(table.companyId, table.shortcut),
|
|
304
|
+
index("idx_quick_replies_company_order").on(table.companyId, table.sortOrder)
|
|
305
|
+
]);
|
|
275
306
|
var settings = metaWhatsAppSchema.table("settings", {
|
|
276
307
|
companyId: uuid("company_id").primaryKey(),
|
|
277
308
|
templateName: varchar("template_name", {
|
|
@@ -728,6 +759,7 @@ var MessageRepository = class {
|
|
|
728
759
|
// src/repositories/FlowGraphRepository.ts
|
|
729
760
|
import { and as and3, eq as eq3, isNotNull, sql as sql4 } from "drizzle-orm";
|
|
730
761
|
import { flowGraphNodesSchema } from "@adatechnology/meta-whatsapp-contracts";
|
|
762
|
+
import { FLOW_GRAPH_ORIGIN } from "@adatechnology/meta-whatsapp-contracts";
|
|
731
763
|
var InvalidFlowGraphError = class extends Error {
|
|
732
764
|
static {
|
|
733
765
|
__name(this, "InvalidFlowGraphError");
|
|
@@ -746,10 +778,18 @@ function toContractGraph(row) {
|
|
|
746
778
|
label: row.label,
|
|
747
779
|
startNodeId: row.startNodeId,
|
|
748
780
|
version: row.version,
|
|
749
|
-
nodes: parsed.data
|
|
781
|
+
nodes: parsed.data,
|
|
782
|
+
origin: toOrigin(row.origin),
|
|
783
|
+
...row.seedVersion ? {
|
|
784
|
+
seedVersion: row.seedVersion
|
|
785
|
+
} : {}
|
|
750
786
|
};
|
|
751
787
|
}
|
|
752
788
|
__name(toContractGraph, "toContractGraph");
|
|
789
|
+
function toOrigin(value) {
|
|
790
|
+
return value === FLOW_GRAPH_ORIGIN.SEED ? FLOW_GRAPH_ORIGIN.SEED : FLOW_GRAPH_ORIGIN.EDITED;
|
|
791
|
+
}
|
|
792
|
+
__name(toOrigin, "toOrigin");
|
|
753
793
|
var OptimisticLockError = class extends Error {
|
|
754
794
|
static {
|
|
755
795
|
__name(this, "OptimisticLockError");
|
|
@@ -788,7 +828,11 @@ var FlowGraphRepository = class {
|
|
|
788
828
|
nodeCount: Object.keys(row.nodes).length,
|
|
789
829
|
showInMenu: row.showInMenu,
|
|
790
830
|
menuOptionLabel: row.menuOptionLabel ?? void 0,
|
|
791
|
-
updatedAt: row.updatedAt.toISOString()
|
|
831
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
832
|
+
origin: toOrigin(row.origin),
|
|
833
|
+
...row.seedVersion ? {
|
|
834
|
+
seedVersion: row.seedVersion
|
|
835
|
+
} : {}
|
|
792
836
|
}));
|
|
793
837
|
}
|
|
794
838
|
// Valida antes de gravar: aceitar um grafo malformado e só reclamar na leitura empurraria a
|
|
@@ -806,7 +850,10 @@ var FlowGraphRepository = class {
|
|
|
806
850
|
startNodeId: graph.startNodeId,
|
|
807
851
|
nodes: graph.nodes,
|
|
808
852
|
showInMenu: graph.showInMenu ?? false,
|
|
809
|
-
menuOptionLabel: graph.menuOptionLabel
|
|
853
|
+
menuOptionLabel: graph.menuOptionLabel,
|
|
854
|
+
// Quem informa `seedVersion` é o produto semeando; criado pelo editor não traz e fica `edited`.
|
|
855
|
+
origin: graph.seedVersion ? FLOW_GRAPH_ORIGIN.SEED : FLOW_GRAPH_ORIGIN.EDITED,
|
|
856
|
+
seedVersion: graph.seedVersion ?? null
|
|
810
857
|
}).returning();
|
|
811
858
|
const createdGraph = toContractGraph(created);
|
|
812
859
|
await this.cache?.invalidate(companyId, createdGraph.key);
|
|
@@ -820,6 +867,8 @@ var FlowGraphRepository = class {
|
|
|
820
867
|
label: graph.label,
|
|
821
868
|
startNodeId: graph.startNodeId,
|
|
822
869
|
nodes: graph.nodes,
|
|
870
|
+
// Salvar é sempre edição humana, mesmo que o editor devolva `origin: 'seed'` do grafo que carregou.
|
|
871
|
+
origin: FLOW_GRAPH_ORIGIN.EDITED,
|
|
823
872
|
version: expectedVersion + 1,
|
|
824
873
|
updatedAt: /* @__PURE__ */ new Date()
|
|
825
874
|
}).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, graph.key), eq3(flowGraphs.version, expectedVersion))).returning();
|
|
@@ -827,6 +876,38 @@ var FlowGraphRepository = class {
|
|
|
827
876
|
await this.cache?.invalidate(companyId, graph.key);
|
|
828
877
|
return toContractGraph(rows[0]);
|
|
829
878
|
}
|
|
879
|
+
/**
|
|
880
|
+
* Atualiza um grafo semeado que ninguém editou. A condição `origin = 'seed'` vai no próprio UPDATE:
|
|
881
|
+
* se uma pessoa salvar pelo editor entre a leitura e a escrita, o grafo vira `edited` e este update
|
|
882
|
+
* não casa nenhuma linha — a edição nunca é sobrescrita. Idempotente por `seedVersion`.
|
|
883
|
+
*/
|
|
884
|
+
async reseed(params) {
|
|
885
|
+
this.assertValidNodes(params.key, params.content.nodes);
|
|
886
|
+
const rows = await this.db.update(flowGraphs).set({
|
|
887
|
+
label: params.content.label,
|
|
888
|
+
startNodeId: params.content.startNodeId,
|
|
889
|
+
nodes: params.content.nodes,
|
|
890
|
+
seedVersion: params.seedVersion,
|
|
891
|
+
version: sql4`${flowGraphs.version} + 1`,
|
|
892
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
893
|
+
}).where(and3(eq3(flowGraphs.companyId, params.companyId), eq3(flowGraphs.key, params.key), eq3(flowGraphs.origin, FLOW_GRAPH_ORIGIN.SEED), sql4`${flowGraphs.seedVersion} is distinct from ${params.seedVersion}`)).returning();
|
|
894
|
+
if (rows.length > 0) {
|
|
895
|
+
await this.cache?.invalidate(params.companyId, params.key);
|
|
896
|
+
return {
|
|
897
|
+
status: "updated",
|
|
898
|
+
graph: toContractGraph(rows[0])
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
const [existing] = await this.db.select({
|
|
902
|
+
origin: flowGraphs.origin
|
|
903
|
+
}).from(flowGraphs).where(and3(eq3(flowGraphs.companyId, params.companyId), eq3(flowGraphs.key, params.key))).limit(1);
|
|
904
|
+
if (!existing) return {
|
|
905
|
+
status: "missing"
|
|
906
|
+
};
|
|
907
|
+
return {
|
|
908
|
+
status: existing.origin === FLOW_GRAPH_ORIGIN.SEED ? "current" : "edited"
|
|
909
|
+
};
|
|
910
|
+
}
|
|
830
911
|
async delete(companyId, key) {
|
|
831
912
|
await this.db.delete(flowGraphs).where(and3(eq3(flowGraphs.companyId, companyId), eq3(flowGraphs.key, key)));
|
|
832
913
|
await this.cache?.invalidate(companyId, key);
|
|
@@ -1815,6 +1896,169 @@ var DocumentRepository = class {
|
|
|
1815
1896
|
}
|
|
1816
1897
|
};
|
|
1817
1898
|
|
|
1899
|
+
// src/repositories/QuickReplyRepository.ts
|
|
1900
|
+
import { and as and5, asc as asc2, count as count3, eq as eq6, ilike as ilike2, max, ne, or as or2, sql as sql5 } from "drizzle-orm";
|
|
1901
|
+
import { QuickReplyLimitReachedError, QuickReplyNotFoundError, QuickReplyShortcutTakenError, QUICK_REPLY_LIMITS } from "@adatechnology/meta-whatsapp-contracts";
|
|
1902
|
+
var UNIQUE_VIOLATION_SQLSTATE = "23505";
|
|
1903
|
+
function hasUniqueViolationState(error) {
|
|
1904
|
+
const state = error;
|
|
1905
|
+
return state?.code === UNIQUE_VIOLATION_SQLSTATE || state?.errno === UNIQUE_VIOLATION_SQLSTATE;
|
|
1906
|
+
}
|
|
1907
|
+
__name(hasUniqueViolationState, "hasUniqueViolationState");
|
|
1908
|
+
function isUniqueViolation(error) {
|
|
1909
|
+
return hasUniqueViolationState(error) || hasUniqueViolationState(error?.cause);
|
|
1910
|
+
}
|
|
1911
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
1912
|
+
function escapeLikePattern(text2) {
|
|
1913
|
+
return text2.replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
1914
|
+
}
|
|
1915
|
+
__name(escapeLikePattern, "escapeLikePattern");
|
|
1916
|
+
var QuickReplyRepository = class {
|
|
1917
|
+
static {
|
|
1918
|
+
__name(this, "QuickReplyRepository");
|
|
1919
|
+
}
|
|
1920
|
+
db;
|
|
1921
|
+
constructor(db) {
|
|
1922
|
+
this.db = db;
|
|
1923
|
+
}
|
|
1924
|
+
async list(params) {
|
|
1925
|
+
const filters = [
|
|
1926
|
+
eq6(quickReplies.companyId, params.companyId)
|
|
1927
|
+
];
|
|
1928
|
+
if (params.search) {
|
|
1929
|
+
const pattern = `%${escapeLikePattern(params.search)}%`;
|
|
1930
|
+
const matches = or2(ilike2(quickReplies.title, pattern), ilike2(quickReplies.shortcut, pattern), ilike2(quickReplies.body, pattern));
|
|
1931
|
+
if (matches) filters.push(matches);
|
|
1932
|
+
}
|
|
1933
|
+
return this.db.select().from(quickReplies).where(and5(...filters)).orderBy(asc2(quickReplies.sortOrder), asc2(quickReplies.title), asc2(quickReplies.id));
|
|
1934
|
+
}
|
|
1935
|
+
async get(companyId, id) {
|
|
1936
|
+
const [row] = await this.db.select().from(quickReplies).where(and5(eq6(quickReplies.companyId, companyId), eq6(quickReplies.id, id))).limit(1);
|
|
1937
|
+
return row;
|
|
1938
|
+
}
|
|
1939
|
+
async create(params) {
|
|
1940
|
+
const [totals] = await this.db.select({
|
|
1941
|
+
total: count3(),
|
|
1942
|
+
highestOrder: max(quickReplies.sortOrder)
|
|
1943
|
+
}).from(quickReplies).where(eq6(quickReplies.companyId, params.companyId));
|
|
1944
|
+
if ((totals?.total ?? 0) >= QUICK_REPLY_LIMITS.MAX_PER_COMPANY) {
|
|
1945
|
+
throw new QuickReplyLimitReachedError(QUICK_REPLY_LIMITS.MAX_PER_COMPANY);
|
|
1946
|
+
}
|
|
1947
|
+
try {
|
|
1948
|
+
const [row] = await this.db.insert(quickReplies).values({
|
|
1949
|
+
companyId: params.companyId,
|
|
1950
|
+
title: params.title,
|
|
1951
|
+
shortcut: params.shortcut,
|
|
1952
|
+
body: params.body,
|
|
1953
|
+
// Sem ordem explícita vai para o fim da lista.
|
|
1954
|
+
sortOrder: params.sortOrder ?? (totals?.highestOrder ?? -1) + 1
|
|
1955
|
+
}).returning();
|
|
1956
|
+
return row;
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
if (isUniqueViolation(error)) throw new QuickReplyShortcutTakenError(params.shortcut);
|
|
1959
|
+
throw error;
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
async update(params) {
|
|
1963
|
+
const [taken] = await this.db.select({
|
|
1964
|
+
id: quickReplies.id
|
|
1965
|
+
}).from(quickReplies).where(and5(eq6(quickReplies.companyId, params.companyId), eq6(quickReplies.shortcut, params.shortcut), ne(quickReplies.id, params.id))).limit(1);
|
|
1966
|
+
if (taken) throw new QuickReplyShortcutTakenError(params.shortcut);
|
|
1967
|
+
try {
|
|
1968
|
+
const [row] = await this.db.update(quickReplies).set({
|
|
1969
|
+
title: params.title,
|
|
1970
|
+
shortcut: params.shortcut,
|
|
1971
|
+
body: params.body,
|
|
1972
|
+
...params.sortOrder !== void 0 ? {
|
|
1973
|
+
sortOrder: params.sortOrder
|
|
1974
|
+
} : {},
|
|
1975
|
+
updatedAt: sql5`now()`
|
|
1976
|
+
}).where(and5(eq6(quickReplies.companyId, params.companyId), eq6(quickReplies.id, params.id))).returning();
|
|
1977
|
+
if (!row) throw new QuickReplyNotFoundError(params.id);
|
|
1978
|
+
return row;
|
|
1979
|
+
} catch (error) {
|
|
1980
|
+
if (isUniqueViolation(error)) throw new QuickReplyShortcutTakenError(params.shortcut);
|
|
1981
|
+
throw error;
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
async delete(companyId, id) {
|
|
1985
|
+
const rows = await this.db.delete(quickReplies).where(and5(eq6(quickReplies.companyId, companyId), eq6(quickReplies.id, id))).returning({
|
|
1986
|
+
id: quickReplies.id
|
|
1987
|
+
});
|
|
1988
|
+
return rows.length > 0;
|
|
1989
|
+
}
|
|
1990
|
+
};
|
|
1991
|
+
|
|
1992
|
+
// src/use-cases/QuickReply.use-cases.ts
|
|
1993
|
+
import { QuickReplyNotFoundError as QuickReplyNotFoundError2 } from "@adatechnology/meta-whatsapp-contracts";
|
|
1994
|
+
function toQuickReplyView(row) {
|
|
1995
|
+
return {
|
|
1996
|
+
id: row.id,
|
|
1997
|
+
title: row.title,
|
|
1998
|
+
shortcut: row.shortcut,
|
|
1999
|
+
body: row.body,
|
|
2000
|
+
sortOrder: row.sortOrder,
|
|
2001
|
+
createdAt: row.createdAt.toISOString(),
|
|
2002
|
+
updatedAt: row.updatedAt.toISOString()
|
|
2003
|
+
};
|
|
2004
|
+
}
|
|
2005
|
+
__name(toQuickReplyView, "toQuickReplyView");
|
|
2006
|
+
var ListQuickRepliesUseCase = class {
|
|
2007
|
+
static {
|
|
2008
|
+
__name(this, "ListQuickRepliesUseCase");
|
|
2009
|
+
}
|
|
2010
|
+
repository;
|
|
2011
|
+
constructor(repository) {
|
|
2012
|
+
this.repository = repository;
|
|
2013
|
+
}
|
|
2014
|
+
async execute(params) {
|
|
2015
|
+
const rows = await this.repository.list({
|
|
2016
|
+
companyId: params.companyId,
|
|
2017
|
+
...params.search ? {
|
|
2018
|
+
search: params.search
|
|
2019
|
+
} : {}
|
|
2020
|
+
});
|
|
2021
|
+
return rows.map(toQuickReplyView);
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
var CreateQuickReplyUseCase = class {
|
|
2025
|
+
static {
|
|
2026
|
+
__name(this, "CreateQuickReplyUseCase");
|
|
2027
|
+
}
|
|
2028
|
+
repository;
|
|
2029
|
+
constructor(repository) {
|
|
2030
|
+
this.repository = repository;
|
|
2031
|
+
}
|
|
2032
|
+
async execute(params) {
|
|
2033
|
+
return toQuickReplyView(await this.repository.create(params));
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
var UpdateQuickReplyUseCase = class {
|
|
2037
|
+
static {
|
|
2038
|
+
__name(this, "UpdateQuickReplyUseCase");
|
|
2039
|
+
}
|
|
2040
|
+
repository;
|
|
2041
|
+
constructor(repository) {
|
|
2042
|
+
this.repository = repository;
|
|
2043
|
+
}
|
|
2044
|
+
async execute(params) {
|
|
2045
|
+
return toQuickReplyView(await this.repository.update(params));
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
var DeleteQuickReplyUseCase = class {
|
|
2049
|
+
static {
|
|
2050
|
+
__name(this, "DeleteQuickReplyUseCase");
|
|
2051
|
+
}
|
|
2052
|
+
repository;
|
|
2053
|
+
constructor(repository) {
|
|
2054
|
+
this.repository = repository;
|
|
2055
|
+
}
|
|
2056
|
+
async execute(params) {
|
|
2057
|
+
const wasDeleted = await this.repository.delete(params.companyId, params.id);
|
|
2058
|
+
if (!wasDeleted) throw new QuickReplyNotFoundError2(params.id);
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
2061
|
+
|
|
1818
2062
|
// src/use-cases/ExportConversation.use-case.ts
|
|
1819
2063
|
import { SessionNotFoundError as SessionNotFoundError5 } from "@adatechnology/meta-whatsapp-contracts";
|
|
1820
2064
|
var ExportConversationUseCase = class {
|
|
@@ -1881,6 +2125,18 @@ var SaveFlowGraphUseCase = class {
|
|
|
1881
2125
|
return this.flowGraphRepository.save(params.companyId, params.graph, params.expectedVersion);
|
|
1882
2126
|
}
|
|
1883
2127
|
};
|
|
2128
|
+
var ReseedFlowGraphUseCase = class {
|
|
2129
|
+
static {
|
|
2130
|
+
__name(this, "ReseedFlowGraphUseCase");
|
|
2131
|
+
}
|
|
2132
|
+
flowGraphRepository;
|
|
2133
|
+
constructor(flowGraphRepository) {
|
|
2134
|
+
this.flowGraphRepository = flowGraphRepository;
|
|
2135
|
+
}
|
|
2136
|
+
async execute(params) {
|
|
2137
|
+
return this.flowGraphRepository.reseed(params);
|
|
2138
|
+
}
|
|
2139
|
+
};
|
|
1884
2140
|
var DeleteFlowGraphUseCase = class {
|
|
1885
2141
|
static {
|
|
1886
2142
|
__name(this, "DeleteFlowGraphUseCase");
|
|
@@ -2307,7 +2563,7 @@ var FlowQuestionRenderer = class {
|
|
|
2307
2563
|
...params.variables
|
|
2308
2564
|
};
|
|
2309
2565
|
const body = this.interpolate(node.question ?? this.config.choicePrompt ?? DEFAULT_FLOW_TEXT.CHOICE_PROMPT, variables);
|
|
2310
|
-
const listButtonLabel = node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL;
|
|
2566
|
+
const listButtonLabel = this.interpolate(node.listButtonLabel ?? this.config.listButtonLabel ?? DEFAULT_FLOW_TEXT.LIST_BUTTON_LABEL, variables);
|
|
2311
2567
|
if (node.type === "dynamic_choice") {
|
|
2312
2568
|
const options = await this.loadDynamicOptions(params);
|
|
2313
2569
|
const shown = options.map((option) => [
|
|
@@ -3147,7 +3403,7 @@ var FlowHandoff = class {
|
|
|
3147
3403
|
};
|
|
3148
3404
|
|
|
3149
3405
|
// src/flows/flowTurnLock.ts
|
|
3150
|
-
import { sql as
|
|
3406
|
+
import { sql as sql6 } from "drizzle-orm";
|
|
3151
3407
|
function lockName(key) {
|
|
3152
3408
|
return `meta_whatsapp_flow:${key.companyId}:${key.whatsappNumber}`;
|
|
3153
3409
|
}
|
|
@@ -3162,7 +3418,7 @@ var PostgresAdvisoryFlowTurnLock = class {
|
|
|
3162
3418
|
}
|
|
3163
3419
|
withLock(key, work) {
|
|
3164
3420
|
return this.db.transaction(async (transaction) => {
|
|
3165
|
-
await transaction.execute(
|
|
3421
|
+
await transaction.execute(sql6`select pg_advisory_xact_lock(hashtext(${lockName(key)}))`);
|
|
3166
3422
|
return work();
|
|
3167
3423
|
});
|
|
3168
3424
|
}
|
|
@@ -3350,7 +3606,7 @@ async function listAvailableProducts(params) {
|
|
|
3350
3606
|
__name(listAvailableProducts, "listAvailableProducts");
|
|
3351
3607
|
|
|
3352
3608
|
// src/repositories/FlowMediaRepository.ts
|
|
3353
|
-
import { and as
|
|
3609
|
+
import { and as and6, asc as asc3, eq as eq7, sql as sql7 } from "drizzle-orm";
|
|
3354
3610
|
var FlowMediaRepository = class {
|
|
3355
3611
|
static {
|
|
3356
3612
|
__name(this, "FlowMediaRepository");
|
|
@@ -3360,18 +3616,18 @@ var FlowMediaRepository = class {
|
|
|
3360
3616
|
this.db = db;
|
|
3361
3617
|
}
|
|
3362
3618
|
locationFilter(location) {
|
|
3363
|
-
return
|
|
3619
|
+
return and6(eq7(flowMedia.companyId, location.companyId), eq7(flowMedia.flowKey, location.flowKey), eq7(flowMedia.nodeId, location.nodeId));
|
|
3364
3620
|
}
|
|
3365
3621
|
// O que o nó realmente envia, na ordem de envio. `active` filtrado aqui e não no chamador:
|
|
3366
3622
|
// é a razão de a coluna existir, e um chamador que esquecesse do filtro mandaria ao cliente
|
|
3367
3623
|
// justamente o material que alguém desligou.
|
|
3368
3624
|
async listActive(location) {
|
|
3369
|
-
return this.db.select().from(flowMedia).where(
|
|
3625
|
+
return this.db.select().from(flowMedia).where(and6(this.locationFilter(location), eq7(flowMedia.active, true))).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
|
|
3370
3626
|
}
|
|
3371
3627
|
// Inclui os desligados — é a visão do editor, onde desligar precisa continuar visível para
|
|
3372
3628
|
// poder ser religado.
|
|
3373
3629
|
async listAll(location) {
|
|
3374
|
-
return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(
|
|
3630
|
+
return this.db.select().from(flowMedia).where(this.locationFilter(location)).orderBy(asc3(flowMedia.sortOrder), asc3(flowMedia.createdAt));
|
|
3375
3631
|
}
|
|
3376
3632
|
/**
|
|
3377
3633
|
* Anexa um arquivo já existente no storage ao nó.
|
|
@@ -3402,7 +3658,7 @@ var FlowMediaRepository = class {
|
|
|
3402
3658
|
caption: params.caption ?? null,
|
|
3403
3659
|
sortOrder: params.sortOrder ?? 0,
|
|
3404
3660
|
active: true,
|
|
3405
|
-
updatedAt:
|
|
3661
|
+
updatedAt: sql7`now()`
|
|
3406
3662
|
}
|
|
3407
3663
|
}).returning();
|
|
3408
3664
|
return row;
|
|
@@ -3418,8 +3674,8 @@ var FlowMediaRepository = class {
|
|
|
3418
3674
|
...params.active !== void 0 ? {
|
|
3419
3675
|
active: params.active
|
|
3420
3676
|
} : {},
|
|
3421
|
-
updatedAt:
|
|
3422
|
-
}).where(
|
|
3677
|
+
updatedAt: sql7`now()`
|
|
3678
|
+
}).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id))).returning();
|
|
3423
3679
|
return row;
|
|
3424
3680
|
}
|
|
3425
3681
|
/**
|
|
@@ -3428,17 +3684,17 @@ var FlowMediaRepository = class {
|
|
|
3428
3684
|
* host, que é dono da biblioteca de arquivos.
|
|
3429
3685
|
*/
|
|
3430
3686
|
async detach(params) {
|
|
3431
|
-
await this.db.delete(flowMedia).where(
|
|
3687
|
+
await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.id, params.id)));
|
|
3432
3688
|
}
|
|
3433
3689
|
// Chamado ao salvar o grafo: nós apagados no editor deixam linhas que nada mais alcança.
|
|
3434
3690
|
async detachRemovedNodes(params) {
|
|
3435
|
-
const condition = params.existingNodeIds.length === 0 ? void 0 :
|
|
3436
|
-
await this.db.delete(flowMedia).where(
|
|
3691
|
+
const condition = params.existingNodeIds.length === 0 ? void 0 : sql7`${flowMedia.nodeId} NOT IN ${params.existingNodeIds}`;
|
|
3692
|
+
await this.db.delete(flowMedia).where(and6(eq7(flowMedia.companyId, params.companyId), eq7(flowMedia.flowKey, params.flowKey), condition));
|
|
3437
3693
|
}
|
|
3438
3694
|
};
|
|
3439
3695
|
|
|
3440
3696
|
// src/repositories/FlowMediaIdRepository.ts
|
|
3441
|
-
import { eq as
|
|
3697
|
+
import { eq as eq8, sql as sql8 } from "drizzle-orm";
|
|
3442
3698
|
var FlowMediaIdRepository = class {
|
|
3443
3699
|
static {
|
|
3444
3700
|
__name(this, "FlowMediaIdRepository");
|
|
@@ -3450,7 +3706,7 @@ var FlowMediaIdRepository = class {
|
|
|
3450
3706
|
async get(params) {
|
|
3451
3707
|
const rows = await this.db.select({
|
|
3452
3708
|
ids: flowMedia.metaMediaIds
|
|
3453
|
-
}).from(flowMedia).where(
|
|
3709
|
+
}).from(flowMedia).where(eq8(flowMedia.id, params.flowMediaId)).limit(1);
|
|
3454
3710
|
return rows[0]?.ids?.[params.senderKey];
|
|
3455
3711
|
}
|
|
3456
3712
|
/**
|
|
@@ -3462,14 +3718,14 @@ var FlowMediaIdRepository = class {
|
|
|
3462
3718
|
*/
|
|
3463
3719
|
async set(params) {
|
|
3464
3720
|
await this.db.update(flowMedia).set({
|
|
3465
|
-
metaMediaIds:
|
|
3466
|
-
}).where(
|
|
3721
|
+
metaMediaIds: sql8`jsonb_set(${flowMedia.metaMediaIds}, ARRAY[${params.senderKey}::text], to_jsonb(${params.mediaId}::text), true)`
|
|
3722
|
+
}).where(eq8(flowMedia.id, params.flowMediaId));
|
|
3467
3723
|
}
|
|
3468
3724
|
/** Remove só a chave deste número — o id do outro número continua válido. */
|
|
3469
3725
|
async clear(params) {
|
|
3470
3726
|
await this.db.update(flowMedia).set({
|
|
3471
|
-
metaMediaIds:
|
|
3472
|
-
}).where(
|
|
3727
|
+
metaMediaIds: sql8`${flowMedia.metaMediaIds} - ${params.senderKey}::text`
|
|
3728
|
+
}).where(eq8(flowMedia.id, params.flowMediaId));
|
|
3473
3729
|
}
|
|
3474
3730
|
};
|
|
3475
3731
|
|
|
@@ -3650,7 +3906,7 @@ async function confirmWebhookDelivery(params) {
|
|
|
3650
3906
|
__name(confirmWebhookDelivery, "confirmWebhookDelivery");
|
|
3651
3907
|
|
|
3652
3908
|
// src/channel/IngestInboundMedia.use-case.ts
|
|
3653
|
-
import { eq as
|
|
3909
|
+
import { eq as eq9, and as and7 } from "drizzle-orm";
|
|
3654
3910
|
|
|
3655
3911
|
// src/use-cases/TranscribeAudio.use-case.ts
|
|
3656
3912
|
import { AudioNotIngestedError, MessageNotAudioError, TranscriptionDisabledError } from "@adatechnology/meta-whatsapp-contracts";
|
|
@@ -3822,7 +4078,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3822
4078
|
this.transcription = transcription;
|
|
3823
4079
|
}
|
|
3824
4080
|
async execute(params) {
|
|
3825
|
-
const [message] = await this.db.select().from(messages).where(
|
|
4081
|
+
const [message] = await this.db.select().from(messages).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId))).limit(1);
|
|
3826
4082
|
if (!message) throw new Error(`Mensagem ${params.messageId} n\xE3o encontrada para ingest\xE3o de m\xEDdia`);
|
|
3827
4083
|
const payload = message.payload ?? {};
|
|
3828
4084
|
if (payload["uploadId"] && payload["sourceMediaId"] === params.sourceMediaId) {
|
|
@@ -3853,7 +4109,7 @@ var IngestInboundMediaUseCase = class {
|
|
|
3853
4109
|
};
|
|
3854
4110
|
await this.db.update(messages).set({
|
|
3855
4111
|
payload: updatedPayload
|
|
3856
|
-
}).where(
|
|
4112
|
+
}).where(and7(eq9(messages.companyId, params.companyId), eq9(messages.id, params.messageId)));
|
|
3857
4113
|
await this.documentRepository?.link({
|
|
3858
4114
|
companyId: params.companyId,
|
|
3859
4115
|
sessionId: message.sessionId,
|
|
@@ -4302,6 +4558,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4302
4558
|
const flowGraphCache = flowGraphCacheFeature && providers.cache ? new FlowGraphCache(providers.cache, typeof flowGraphCacheFeature === "object" ? flowGraphCacheFeature.ttlSeconds ?? DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS : DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS) : void 0;
|
|
4303
4559
|
const flowGraphRepository = new FlowGraphRepository(db, flowGraphCache);
|
|
4304
4560
|
const documentRepository = new DocumentRepository(db);
|
|
4561
|
+
const quickReplyRepository = new QuickReplyRepository(db);
|
|
4305
4562
|
const flowMediaRepository = new FlowMediaRepository(db);
|
|
4306
4563
|
const logMessage = new LogMessageUseCase(sessionRepository, messageRepository, providers.realtime, providers.moderator);
|
|
4307
4564
|
const sendMessage = new SendMessageUseCase(channel, sessionRepository, logMessage, providers.objectStorage, documentRepository);
|
|
@@ -4459,6 +4716,18 @@ function createMetaWhatsAppModule(params) {
|
|
|
4459
4716
|
} : void 0,
|
|
4460
4717
|
settings: settingsRepository,
|
|
4461
4718
|
/**
|
|
4719
|
+
* Respostas rápidas por empresa (o `/atalho` do composer). Só texto. As rotas HTTP saem de
|
|
4720
|
+
* `createMetaWhatsAppQuickReplyRoutes({ module })`; o host que prefere as próprias usa os
|
|
4721
|
+
* casos de uso daqui.
|
|
4722
|
+
*/
|
|
4723
|
+
quickReplies: {
|
|
4724
|
+
list: new ListQuickRepliesUseCase(quickReplyRepository),
|
|
4725
|
+
create: new CreateQuickReplyUseCase(quickReplyRepository),
|
|
4726
|
+
update: new UpdateQuickReplyUseCase(quickReplyRepository),
|
|
4727
|
+
delete: new DeleteQuickReplyUseCase(quickReplyRepository),
|
|
4728
|
+
repository: quickReplyRepository
|
|
4729
|
+
},
|
|
4730
|
+
/**
|
|
4462
4731
|
* `undefined` quando o recurso não está ligado (ou falta storage legível). O host consulta a
|
|
4463
4732
|
* ausência para não registrar a rota de upload — e o preview, sem a rota, esconde o microfone.
|
|
4464
4733
|
*/
|
|
@@ -4511,6 +4780,7 @@ function createMetaWhatsAppModule(params) {
|
|
|
4511
4780
|
list: new ListFlowGraphsUseCase(flowGraphRepository),
|
|
4512
4781
|
create: new CreateFlowGraphUseCase(flowGraphRepository),
|
|
4513
4782
|
save: new SaveFlowGraphUseCase(flowGraphRepository),
|
|
4783
|
+
reseed: new ReseedFlowGraphUseCase(flowGraphRepository),
|
|
4514
4784
|
delete: new DeleteFlowGraphUseCase(flowGraphRepository),
|
|
4515
4785
|
livePositions: new GetLiveFlowPositionsUseCase(flowGraphRepository),
|
|
4516
4786
|
repository: flowGraphRepository,
|
|
@@ -4628,17 +4898,148 @@ async function redeemSseTicket(store, ticket) {
|
|
|
4628
4898
|
return JSON.parse(raw);
|
|
4629
4899
|
}
|
|
4630
4900
|
__name(redeemSseTicket, "redeemSseTicket");
|
|
4901
|
+
|
|
4902
|
+
// src/http/quickReplyRoutes.ts
|
|
4903
|
+
import { QuickReplyNotFoundError as QuickReplyNotFoundError3, MetaWhatsAppError, META_WHATSAPP_ERROR_CODES, listWhatsAppQuickRepliesQuerySchema, whatsAppQuickReplyInputSchema } from "@adatechnology/meta-whatsapp-contracts";
|
|
4904
|
+
import { HTTP_METHOD, ROUTE_SCOPE } from "@adatechnology/module-http";
|
|
4905
|
+
|
|
4906
|
+
// src/http/quickReplyScope.constant.ts
|
|
4907
|
+
var QUICK_REPLY_SCOPE = {
|
|
4908
|
+
WRITE: "quick-replies:write"
|
|
4909
|
+
};
|
|
4910
|
+
var DEFAULT_QUICK_REPLY_WRITE_SCOPES = [
|
|
4911
|
+
QUICK_REPLY_SCOPE.WRITE
|
|
4912
|
+
];
|
|
4913
|
+
|
|
4914
|
+
// src/http/quickReplyRoutes.ts
|
|
4915
|
+
function requireCompany(context) {
|
|
4916
|
+
if (!context.auth?.companyId) {
|
|
4917
|
+
throw new MetaWhatsAppError("Rota exige contexto autenticado.", 401, META_WHATSAPP_ERROR_CODES.CONFIG_MISSING);
|
|
4918
|
+
}
|
|
4919
|
+
return context.auth.companyId;
|
|
4920
|
+
}
|
|
4921
|
+
__name(requireCompany, "requireCompany");
|
|
4922
|
+
function requireId(context) {
|
|
4923
|
+
const id = context.params.id;
|
|
4924
|
+
if (!id) throw new QuickReplyNotFoundError3("");
|
|
4925
|
+
return id;
|
|
4926
|
+
}
|
|
4927
|
+
__name(requireId, "requireId");
|
|
4928
|
+
function createMetaWhatsAppQuickReplyRoutes(params) {
|
|
4929
|
+
const { list, create, update, delete: remove } = params.module.quickReplies;
|
|
4930
|
+
const write = {
|
|
4931
|
+
scope: ROUTE_SCOPE.ADMIN,
|
|
4932
|
+
requiredScopes: params.scopes?.write ?? DEFAULT_QUICK_REPLY_WRITE_SCOPES
|
|
4933
|
+
};
|
|
4934
|
+
const read = {
|
|
4935
|
+
scope: ROUTE_SCOPE.USER,
|
|
4936
|
+
...params.scopes?.read?.length ? {
|
|
4937
|
+
requiredScopes: params.scopes.read
|
|
4938
|
+
} : {}
|
|
4939
|
+
};
|
|
4940
|
+
const routes = [
|
|
4941
|
+
{
|
|
4942
|
+
...read,
|
|
4943
|
+
method: HTTP_METHOD.GET,
|
|
4944
|
+
path: "/quick-replies",
|
|
4945
|
+
querySchema: listWhatsAppQuickRepliesQuerySchema,
|
|
4946
|
+
operationId: "listWhatsAppQuickReplies",
|
|
4947
|
+
summary: "Lista as respostas r\xE1pidas da empresa, na ordem de exibi\xE7\xE3o",
|
|
4948
|
+
async handler(context) {
|
|
4949
|
+
const query = context.query;
|
|
4950
|
+
const data = await list.execute({
|
|
4951
|
+
companyId: requireCompany(context),
|
|
4952
|
+
...query
|
|
4953
|
+
});
|
|
4954
|
+
return {
|
|
4955
|
+
kind: "json",
|
|
4956
|
+
status: 200,
|
|
4957
|
+
body: {
|
|
4958
|
+
data
|
|
4959
|
+
}
|
|
4960
|
+
};
|
|
4961
|
+
}
|
|
4962
|
+
},
|
|
4963
|
+
{
|
|
4964
|
+
...write,
|
|
4965
|
+
method: HTTP_METHOD.POST,
|
|
4966
|
+
path: "/quick-replies",
|
|
4967
|
+
bodySchema: whatsAppQuickReplyInputSchema,
|
|
4968
|
+
operationId: "createWhatsAppQuickReply",
|
|
4969
|
+
summary: "Cria uma resposta r\xE1pida (atalho \xFAnico por empresa)",
|
|
4970
|
+
async handler(context) {
|
|
4971
|
+
const input = context.body;
|
|
4972
|
+
const data = await create.execute({
|
|
4973
|
+
...input,
|
|
4974
|
+
companyId: requireCompany(context)
|
|
4975
|
+
});
|
|
4976
|
+
return {
|
|
4977
|
+
kind: "json",
|
|
4978
|
+
status: 201,
|
|
4979
|
+
body: {
|
|
4980
|
+
data
|
|
4981
|
+
}
|
|
4982
|
+
};
|
|
4983
|
+
}
|
|
4984
|
+
},
|
|
4985
|
+
{
|
|
4986
|
+
...write,
|
|
4987
|
+
method: HTTP_METHOD.PUT,
|
|
4988
|
+
path: "/quick-replies/:id",
|
|
4989
|
+
bodySchema: whatsAppQuickReplyInputSchema,
|
|
4990
|
+
operationId: "updateWhatsAppQuickReply",
|
|
4991
|
+
summary: "Substitui t\xEDtulo, atalho e texto de uma resposta r\xE1pida",
|
|
4992
|
+
async handler(context) {
|
|
4993
|
+
const input = context.body;
|
|
4994
|
+
const data = await update.execute({
|
|
4995
|
+
...input,
|
|
4996
|
+
companyId: requireCompany(context),
|
|
4997
|
+
id: requireId(context)
|
|
4998
|
+
});
|
|
4999
|
+
return {
|
|
5000
|
+
kind: "json",
|
|
5001
|
+
status: 200,
|
|
5002
|
+
body: {
|
|
5003
|
+
data
|
|
5004
|
+
}
|
|
5005
|
+
};
|
|
5006
|
+
}
|
|
5007
|
+
},
|
|
5008
|
+
{
|
|
5009
|
+
...write,
|
|
5010
|
+
method: HTTP_METHOD.DELETE,
|
|
5011
|
+
path: "/quick-replies/:id",
|
|
5012
|
+
operationId: "deleteWhatsAppQuickReply",
|
|
5013
|
+
summary: "Apaga uma resposta r\xE1pida",
|
|
5014
|
+
async handler(context) {
|
|
5015
|
+
await remove.execute({
|
|
5016
|
+
companyId: requireCompany(context),
|
|
5017
|
+
id: requireId(context)
|
|
5018
|
+
});
|
|
5019
|
+
return {
|
|
5020
|
+
kind: "empty",
|
|
5021
|
+
status: 204
|
|
5022
|
+
};
|
|
5023
|
+
}
|
|
5024
|
+
}
|
|
5025
|
+
];
|
|
5026
|
+
return routes;
|
|
5027
|
+
}
|
|
5028
|
+
__name(createMetaWhatsAppQuickReplyRoutes, "createMetaWhatsAppQuickReplyRoutes");
|
|
4631
5029
|
export {
|
|
4632
5030
|
CountInboundLocationsUseCase,
|
|
4633
5031
|
CreateFlowGraphUseCase,
|
|
5032
|
+
CreateQuickReplyUseCase,
|
|
4634
5033
|
DEFAULT_FALLBACK_LIST_LABEL,
|
|
4635
5034
|
DEFAULT_FLOW_GRAPH_CACHE_TTL_SECONDS,
|
|
4636
5035
|
DEFAULT_FLOW_TEXT,
|
|
4637
5036
|
DEFAULT_MAX_INVALID_ANSWERS,
|
|
5037
|
+
DEFAULT_QUICK_REPLY_WRITE_SCOPES,
|
|
4638
5038
|
DEFAULT_START_FLOW_KEY,
|
|
4639
5039
|
DYNAMIC_CHOICE_MORE_ID,
|
|
4640
5040
|
DeleteConversationUseCase,
|
|
4641
5041
|
DeleteFlowGraphUseCase,
|
|
5042
|
+
DeleteQuickReplyUseCase,
|
|
4642
5043
|
DocumentRepository,
|
|
4643
5044
|
ExportConversationUseCase,
|
|
4644
5045
|
FLOW_RUNTIME_CONTEXT_KEY,
|
|
@@ -4661,6 +5062,7 @@ export {
|
|
|
4661
5062
|
ListConversationsUseCase,
|
|
4662
5063
|
ListFlowGraphsUseCase,
|
|
4663
5064
|
ListMessagesUseCase,
|
|
5065
|
+
ListQuickRepliesUseCase,
|
|
4664
5066
|
LogMessageUseCase,
|
|
4665
5067
|
META_WHATSAPP_MIGRATIONS_TABLE,
|
|
4666
5068
|
MessageRepository,
|
|
@@ -4670,10 +5072,13 @@ export {
|
|
|
4670
5072
|
PostgresAdvisoryFlowTurnLock,
|
|
4671
5073
|
ProcessInboundDispatchUseCase,
|
|
4672
5074
|
PurgeExpiredDocumentsUseCase,
|
|
5075
|
+
QUICK_REPLY_SCOPE,
|
|
5076
|
+
QuickReplyRepository,
|
|
4673
5077
|
ReceiveWebhookUseCase,
|
|
4674
5078
|
RedactInboundLocationsUseCase,
|
|
4675
5079
|
ReleaseConversationUseCase,
|
|
4676
5080
|
RequestHumanConversationUseCase,
|
|
5081
|
+
ReseedFlowGraphUseCase,
|
|
4677
5082
|
SaveFlowGraphUseCase,
|
|
4678
5083
|
SendMessageUseCase,
|
|
4679
5084
|
SessionRepository,
|
|
@@ -4684,6 +5089,7 @@ export {
|
|
|
4684
5089
|
TRANSCRIPTION_STATUS,
|
|
4685
5090
|
TakeoverConversationUseCase,
|
|
4686
5091
|
TranscribeAudioUseCase,
|
|
5092
|
+
UpdateQuickReplyUseCase,
|
|
4687
5093
|
WEBHOOK_CLAIM_TTL_SECONDS,
|
|
4688
5094
|
WEBHOOK_NONCE_TTL_SECONDS,
|
|
4689
5095
|
WhatsAppChannelAdapter,
|
|
@@ -4692,6 +5098,7 @@ export {
|
|
|
4692
5098
|
claimWebhookDelivery,
|
|
4693
5099
|
confirmWebhookDelivery,
|
|
4694
5100
|
createMetaWhatsAppModule,
|
|
5101
|
+
createMetaWhatsAppQuickReplyRoutes,
|
|
4695
5102
|
createSendMediaAction,
|
|
4696
5103
|
createSendProductListAction,
|
|
4697
5104
|
createTranscriptionPolicyResolver,
|
|
@@ -4707,6 +5114,7 @@ export {
|
|
|
4707
5114
|
messages,
|
|
4708
5115
|
metaWhatsAppMigrationsFolder,
|
|
4709
5116
|
metaWhatsAppSchema,
|
|
5117
|
+
quickReplies,
|
|
4710
5118
|
readFlowInbound,
|
|
4711
5119
|
redeemSseTicket,
|
|
4712
5120
|
resolveFailureStatus,
|
|
@@ -4718,6 +5126,7 @@ export {
|
|
|
4718
5126
|
sessions,
|
|
4719
5127
|
settings,
|
|
4720
5128
|
toPreviewMediaId,
|
|
5129
|
+
toQuickReplyView,
|
|
4721
5130
|
toSessionContract,
|
|
4722
5131
|
transcriptionRetryAfterSeconds,
|
|
4723
5132
|
verifyWebhookChallenge,
|