@wirecat/amo-cli 0.0.0-stage → 0.1.1
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/CHANGELOG.md +70 -0
- package/LICENSE +204 -0
- package/README.md +265 -2
- package/contracts/wirecat.json +1356 -0
- package/dist/amo/account.d.ts +18 -0
- package/dist/amo/account.d.ts.map +1 -0
- package/dist/amo/account.js +48 -0
- package/dist/amo/account.js.map +1 -0
- package/dist/amo/allow-list.d.ts +31 -0
- package/dist/amo/allow-list.d.ts.map +1 -0
- package/dist/amo/allow-list.js +106 -0
- package/dist/amo/allow-list.js.map +1 -0
- package/dist/amo/errors.d.ts +12 -0
- package/dist/amo/errors.d.ts.map +1 -0
- package/dist/amo/errors.js +72 -0
- package/dist/amo/errors.js.map +1 -0
- package/dist/amo/json.d.ts +3 -0
- package/dist/amo/json.d.ts.map +1 -0
- package/dist/amo/json.js +3 -0
- package/dist/amo/json.js.map +1 -0
- package/dist/amo/oauth.d.ts +55 -0
- package/dist/amo/oauth.d.ts.map +1 -0
- package/dist/amo/oauth.js +189 -0
- package/dist/amo/oauth.js.map +1 -0
- package/dist/amo/operation.d.ts +45 -0
- package/dist/amo/operation.d.ts.map +1 -0
- package/dist/amo/operation.js +119 -0
- package/dist/amo/operation.js.map +1 -0
- package/dist/amo/operations.d.ts +3 -0
- package/dist/amo/operations.d.ts.map +1 -0
- package/dist/amo/operations.js +1407 -0
- package/dist/amo/operations.js.map +1 -0
- package/dist/amo/routes.d.ts +67 -0
- package/dist/amo/routes.d.ts.map +1 -0
- package/dist/amo/routes.js +65 -0
- package/dist/amo/routes.js.map +1 -0
- package/dist/amo/transport.d.ts +62 -0
- package/dist/amo/transport.d.ts.map +1 -0
- package/dist/amo/transport.js +282 -0
- package/dist/amo/transport.js.map +1 -0
- package/dist/api-keys.d.ts +47 -0
- package/dist/api-keys.d.ts.map +1 -0
- package/dist/api-keys.js +224 -0
- package/dist/api-keys.js.map +1 -0
- package/dist/bin/amo.d.ts +3 -0
- package/dist/bin/amo.d.ts.map +1 -0
- package/dist/bin/amo.js +40 -0
- package/dist/bin/amo.js.map +1 -0
- package/dist/bundle/all-profiles-3KQVWDV4.js +278 -0
- package/dist/bundle/amo.js +198 -0
- package/dist/bundle/anthropic-N5NOX7K7.js +90 -0
- package/dist/bundle/app-server-2MST5EZ5.js +245 -0
- package/dist/bundle/bun-4NHWOFX2.js +169 -0
- package/dist/bundle/bun-sqlite-DRSXPWPR.js +75 -0
- package/dist/bundle/chunk-2B24PDH7.js +1718 -0
- package/dist/bundle/chunk-2I5UVMLW.js +3232 -0
- package/dist/bundle/chunk-3IRJDH2U.js +731 -0
- package/dist/bundle/chunk-4ZAK773N.js +100 -0
- package/dist/bundle/chunk-5D4AEUVA.js +24783 -0
- package/dist/bundle/chunk-5D4Z2B5B.js +334 -0
- package/dist/bundle/chunk-5E5R65CA.js +54 -0
- package/dist/bundle/chunk-5HGGG3QO.js +73 -0
- package/dist/bundle/chunk-5RLUHTK6.js +23 -0
- package/dist/bundle/chunk-5SBLU7D7.js +63 -0
- package/dist/bundle/chunk-5Z5PEEKP.js +206 -0
- package/dist/bundle/chunk-63F65DHU.js +29 -0
- package/dist/bundle/chunk-6RS7OYTD.js +64 -0
- package/dist/bundle/chunk-73CXFE36.js +88 -0
- package/dist/bundle/chunk-7GTUZY7M.js +170 -0
- package/dist/bundle/chunk-7PKFYX7V.js +189 -0
- package/dist/bundle/chunk-7U5HJEPZ.js +1400 -0
- package/dist/bundle/chunk-A33TIM5D.js +4172 -0
- package/dist/bundle/chunk-ADEWU4P4.js +38 -0
- package/dist/bundle/chunk-ADLS6FVG.js +24600 -0
- package/dist/bundle/chunk-AHJ4W2IL.js +106 -0
- package/dist/bundle/chunk-AUBB72VF.js +2572 -0
- package/dist/bundle/chunk-BVMNXI53.js +1266 -0
- package/dist/bundle/chunk-CDY2NJFE.js +136 -0
- package/dist/bundle/chunk-CHUKWON6.js +244 -0
- package/dist/bundle/chunk-CUZRHF34.js +230 -0
- package/dist/bundle/chunk-D72URWJE.js +532 -0
- package/dist/bundle/chunk-DAY6TSPF.js +786 -0
- package/dist/bundle/chunk-DFDN6AUB.js +21 -0
- package/dist/bundle/chunk-DJD7TBYG.js +2791 -0
- package/dist/bundle/chunk-DOSJONCX.js +1197 -0
- package/dist/bundle/chunk-DQV2IKCF.js +72 -0
- package/dist/bundle/chunk-DXGGCGRP.js +218 -0
- package/dist/bundle/chunk-EH6ZEJGT.js +932 -0
- package/dist/bundle/chunk-EPOV5UIO.js +185 -0
- package/dist/bundle/chunk-EQ7A6NA6.js +53 -0
- package/dist/bundle/chunk-EQUKVVHX.js +353 -0
- package/dist/bundle/chunk-EROSAUNP.js +133 -0
- package/dist/bundle/chunk-ESZSMZKT.js +82 -0
- package/dist/bundle/chunk-FKR3M62D.js +407 -0
- package/dist/bundle/chunk-GNTJMB6X.js +142 -0
- package/dist/bundle/chunk-GQ7VFIYM.js +316 -0
- package/dist/bundle/chunk-JH3UOHRE.js +161 -0
- package/dist/bundle/chunk-JMDLPBXK.js +1068 -0
- package/dist/bundle/chunk-JR6TSMFX.js +9435 -0
- package/dist/bundle/chunk-L6AFE73L.js +18 -0
- package/dist/bundle/chunk-LDEBZ3IX.js +238 -0
- package/dist/bundle/chunk-LGQXGOPJ.js +58 -0
- package/dist/bundle/chunk-LJQUYECN.js +6848 -0
- package/dist/bundle/chunk-LRBPT7LQ.js +95 -0
- package/dist/bundle/chunk-LSND5QYI.js +460 -0
- package/dist/bundle/chunk-NC76INB2.js +27955 -0
- package/dist/bundle/chunk-NHXJYS4R.js +1334 -0
- package/dist/bundle/chunk-NJYAL3UW.js +92 -0
- package/dist/bundle/chunk-O2UCU52O.js +4065 -0
- package/dist/bundle/chunk-ODNQU7DH.js +1028 -0
- package/dist/bundle/chunk-P3WQRTYZ.js +24 -0
- package/dist/bundle/chunk-P5LYZRKW.js +63373 -0
- package/dist/bundle/chunk-PFO76YFP.js +2003 -0
- package/dist/bundle/chunk-PM77PRB6.js +12269 -0
- package/dist/bundle/chunk-Q2VNBY4Y.js +38109 -0
- package/dist/bundle/chunk-QDMXZZG4.js +604 -0
- package/dist/bundle/chunk-QRQYUHCZ.js +761 -0
- package/dist/bundle/chunk-RPWAJYI6.js +2336 -0
- package/dist/bundle/chunk-SMSTGO2G.js +58 -0
- package/dist/bundle/chunk-SZ2V62HB.js +72 -0
- package/dist/bundle/chunk-T2UDLX76.js +259 -0
- package/dist/bundle/chunk-TGEQNS6G.js +16 -0
- package/dist/bundle/chunk-TNUFLULO.js +2333 -0
- package/dist/bundle/chunk-TZSUZGWM.js +25 -0
- package/dist/bundle/chunk-U7RLVJ34.js +274 -0
- package/dist/bundle/chunk-UBRREVLJ.js +72 -0
- package/dist/bundle/chunk-ULXQ5MJM.js +76 -0
- package/dist/bundle/chunk-UMVRT7VQ.js +46 -0
- package/dist/bundle/chunk-V77XNPXG.js +360 -0
- package/dist/bundle/chunk-VVHRQ46X.js +193 -0
- package/dist/bundle/chunk-VX37MPTJ.js +7 -0
- package/dist/bundle/chunk-WCYCUTSK.js +362 -0
- package/dist/bundle/chunk-XEFAMLSD.js +288 -0
- package/dist/bundle/chunk-XQL7FEF4.js +721 -0
- package/dist/bundle/chunk-XRTD2GCU.js +627 -0
- package/dist/bundle/chunk-Y37A3232.js +804 -0
- package/dist/bundle/chunk-Y5E2WNWB.js +35 -0
- package/dist/bundle/chunk-ZM7I52EP.js +78 -0
- package/dist/bundle/chunk-ZVVMGPBJ.js +50 -0
- package/dist/bundle/cli-QVWTXADI.js +1193 -0
- package/dist/bundle/command-contract-QBUQBXH7.js +39 -0
- package/dist/bundle/command-server-entry-5VL5U5EE.js +168 -0
- package/dist/bundle/decode-SQ5WGNDX.js +296 -0
- package/dist/bundle/dispatch-LA4DFXJD.js +411 -0
- package/dist/bundle/dist-T54K3FJV.js +7577 -0
- package/dist/bundle/echarts-25Z3RINX.js +42501 -0
- package/dist/bundle/embed-BNOTNXMA.js +37 -0
- package/dist/bundle/embedder-BCUT7KKV.js +110 -0
- package/dist/bundle/failure-PKAC6XCT.js +24 -0
- package/dist/bundle/first-run-EO5K5GME.js +28 -0
- package/dist/bundle/first-screen-GMN3T6RW.js +39 -0
- package/dist/bundle/instructions-VLM3QAYB.js +11 -0
- package/dist/bundle/mcp-7ILNMJH5.js +167 -0
- package/dist/bundle/meeting-combined-LAMF7S2B.js +24 -0
- package/dist/bundle/meeting-model-GHMMUQ34.js +24 -0
- package/dist/bundle/meeting-semantic-BMP6323L.js +21 -0
- package/dist/bundle/node-CT3N3TNL.js +176 -0
- package/dist/bundle/node-P4E63KXA.js +2340 -0
- package/dist/bundle/node-TLZSIHIJ.js +21 -0
- package/dist/bundle/node-sqlite-MELD2SBX.js +73 -0
- package/dist/bundle/oauth-YBH5OKC2.js +19 -0
- package/dist/bundle/open-WNSBWTAG.js +22 -0
- package/dist/bundle/openai-XSNMNLW6.js +237 -0
- package/dist/bundle/process-I2QKOMM7.js +91 -0
- package/dist/bundle/program-DV73CIGP.js +4940 -0
- package/dist/bundle/prompt-SOG4AKPM.js +16 -0
- package/dist/bundle/recognize-WMQLWMXH.js +25 -0
- package/dist/bundle/remote-4BTFOLFY.js +30 -0
- package/dist/bundle/rerank-LJ3TWRNV.js +51 -0
- package/dist/bundle/serve-B6UANKXN.js +198 -0
- package/dist/bundle/server-S6XD6V6E.js +77 -0
- package/dist/bundle/server-YRH6GJ5Z.js +206 -0
- package/dist/bundle/source-DGFTA2TN.js +42 -0
- package/dist/bundle/sqlite-runtime-R7QFWFE7.js +19 -0
- package/dist/bundle/state-DIJ5YUOE.js +35 -0
- package/dist/bundle/store-6WFWW7EC.js +294 -0
- package/dist/bundle/store-FJCNZULV.js +32 -0
- package/dist/bundle/store-MYTYDV6A.js +177 -0
- package/dist/bundle/store-maintenance-command-B5TMKFMG.js +68 -0
- package/dist/bundle/writer-GP7VIMAU.js +44 -0
- package/dist/commands/account.d.ts +3 -0
- package/dist/commands/account.d.ts.map +1 -0
- package/dist/commands/account.js +86 -0
- package/dist/commands/account.js.map +1 -0
- package/dist/commands/api.d.ts +3 -0
- package/dist/commands/api.d.ts.map +1 -0
- package/dist/commands/api.js +224 -0
- package/dist/commands/api.js.map +1 -0
- package/dist/commands/crm-shared.d.ts +8 -0
- package/dist/commands/crm-shared.d.ts.map +1 -0
- package/dist/commands/crm-shared.js +111 -0
- package/dist/commands/crm-shared.js.map +1 -0
- package/dist/commands/schedule.d.ts +3 -0
- package/dist/commands/schedule.d.ts.map +1 -0
- package/dist/commands/schedule.js +9 -0
- package/dist/commands/schedule.js.map +1 -0
- package/dist/commands/session.d.ts +18 -0
- package/dist/commands/session.d.ts.map +1 -0
- package/dist/commands/session.js +265 -0
- package/dist/commands/session.js.map +1 -0
- package/dist/commands/write.d.ts +14 -0
- package/dist/commands/write.d.ts.map +1 -0
- package/dist/commands/write.js +36 -0
- package/dist/commands/write.js.map +1 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +29 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +62 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +97 -0
- package/dist/context.js.map +1 -0
- package/dist/crm/activities.d.ts +32 -0
- package/dist/crm/activities.d.ts.map +1 -0
- package/dist/crm/activities.js +196 -0
- package/dist/crm/activities.js.map +1 -0
- package/dist/crm/records.d.ts +20 -0
- package/dist/crm/records.d.ts.map +1 -0
- package/dist/crm/records.js +175 -0
- package/dist/crm/records.js.map +1 -0
- package/dist/crm/source.d.ts +41 -0
- package/dist/crm/source.d.ts.map +1 -0
- package/dist/crm/source.js +673 -0
- package/dist/crm/source.js.map +1 -0
- package/dist/crm/writer.d.ts +14 -0
- package/dist/crm/writer.d.ts.map +1 -0
- package/dist/crm/writer.js +247 -0
- package/dist/crm/writer.js.map +1 -0
- package/dist/identity.d.ts +7 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +33 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/program.d.ts +6 -0
- package/dist/program.d.ts.map +1 -0
- package/dist/program.js +91 -0
- package/dist/program.js.map +1 -0
- package/dist/reasons.d.ts +10 -0
- package/dist/reasons.d.ts.map +1 -0
- package/dist/reasons.js +35 -0
- package/dist/reasons.js.map +1 -0
- package/dist/setup/flow.d.ts +2 -0
- package/dist/setup/flow.d.ts.map +1 -0
- package/dist/setup/flow.js +127 -0
- package/dist/setup/flow.js.map +1 -0
- package/dist/setup/texts.en.json +25 -0
- package/dist/setup/texts.es.json +25 -0
- package/dist/setup/texts.ru.json +25 -0
- package/dist/store.d.ts +15 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +16 -0
- package/dist/store.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/dist/wcat.d.ts +3 -0
- package/dist/wcat.d.ts.map +1 -0
- package/dist/wcat.js +4 -0
- package/dist/wcat.js.map +1 -0
- package/dist/whoami.d.ts +24 -0
- package/dist/whoami.d.ts.map +1 -0
- package/dist/whoami.js +33 -0
- package/dist/whoami.js.map +1 -0
- package/package.json +85 -4
- package/skills/amo-cli/SKILL.md +116 -0
- package/skills/amo-cli/references/mcp.md +38 -0
- package/skills/amo-cli/references/output.md +42 -0
- package/skills/amo-cli/references/reading.md +77 -0
- package/skills/amo-cli/references/setup.md +59 -0
- package/skills/amo-cli/references/writing.md +86 -0
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { crmValues, } from "@wirecat/cli-core/crm";
|
|
3
|
+
import { matchOperation } from "../amo/operation.js";
|
|
4
|
+
import { ENTITIES, ROUTES } from "../amo/routes.js";
|
|
5
|
+
import { readActivities } from "./activities.js";
|
|
6
|
+
import { fieldOfRaw, toDeal, toOrganization, toPerson, toPipeline, toUser } from "./records.js";
|
|
7
|
+
const { fieldOf, id, isRaw, rawsOf, text } = crmValues;
|
|
8
|
+
/**
|
|
9
|
+
* Re-read before the last cursor: rows amoCRM saved while the round ran, and this computer's clock running ahead of
|
|
10
|
+
* the account's. A row read twice is only saved twice.
|
|
11
|
+
*/
|
|
12
|
+
const OVERLAP_MS = 10 * 60_000;
|
|
13
|
+
/** The largest page of leads, contacts, companies and users (leads-api, contacts-api, companies-api, users-api). */
|
|
14
|
+
const PAGE = 250;
|
|
15
|
+
/** events-and-notes says 100 on the ru page, Kommo 250: the smaller. */
|
|
16
|
+
const EVENTS_PAGE = 100;
|
|
17
|
+
/** Ids in one `filter[id][]`: amoCRM recommends 50 records a request (amocrm.ru "Рекомендации"). */
|
|
18
|
+
const CHUNK = 50;
|
|
19
|
+
const seconds = (ms) => Math.floor(ms / 1000);
|
|
20
|
+
/** One list page: its rows in `_embedded.<name>`, and whether `_links.next` says more come (leads-api). 204 is empty. */
|
|
21
|
+
const listPage = async (caller, route, name, query) => {
|
|
22
|
+
const { body } = await caller.request({ route, query });
|
|
23
|
+
if (body === undefined)
|
|
24
|
+
return { rows: [], more: false };
|
|
25
|
+
const rows = fieldOf(fieldOf(body, "_embedded"), name);
|
|
26
|
+
// A list answer without its rows would read as an empty page and end the round.
|
|
27
|
+
if (!Array.isArray(rows))
|
|
28
|
+
throw new CliError("invalid_response", `amoCRM answered ${route} without its ${name}`);
|
|
29
|
+
return { rows: rows.filter(isRaw), more: fieldOf(fieldOf(body, "_links"), "next") !== undefined };
|
|
30
|
+
};
|
|
31
|
+
const readAll = async (caller, route, name, query = {}) => {
|
|
32
|
+
const all = [];
|
|
33
|
+
for (let page = 1;; page++) {
|
|
34
|
+
const { rows, more } = await listPage(caller, route, name, { ...query, limit: PAGE, page });
|
|
35
|
+
for (const raw of rows)
|
|
36
|
+
all.push(raw);
|
|
37
|
+
if (!more || rows.length === 0)
|
|
38
|
+
return all;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const readOne = async (caller, route, externalId, query = {}) => {
|
|
42
|
+
if (!/^\d{1,20}$/.test(externalId))
|
|
43
|
+
return null;
|
|
44
|
+
try {
|
|
45
|
+
const { body } = await caller.request({ route, ids: { id: externalId }, query });
|
|
46
|
+
return isRaw(body) ? body : null;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (isCliError(error) && error.code === "not_found")
|
|
50
|
+
return null;
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const spotOf = (page, now) => {
|
|
55
|
+
const found = /^([a-z])(\d+)\.(\d+)(?:\.(\d+))?(?:~(\d+))?@(\d+)$/.exec(page ?? "");
|
|
56
|
+
if (!found)
|
|
57
|
+
return { spot: null, started: now };
|
|
58
|
+
const spot = { ph: found[1] ?? "", p: Number(found[2]), o: Number(found[3]) };
|
|
59
|
+
if (found[4] !== undefined)
|
|
60
|
+
spot.l = Number(found[4]);
|
|
61
|
+
if (found[5] !== undefined)
|
|
62
|
+
spot.k = found[5];
|
|
63
|
+
return { spot, started: Number(found[6]) };
|
|
64
|
+
};
|
|
65
|
+
const keyOf = (spot) => `${spot.ph}${spot.p}.${spot.o}${spot.l === undefined ? "" : `.${spot.l}`}${spot.k === undefined ? "" : `~${spot.k}`}`;
|
|
66
|
+
const byNumber = (ids) => [...new Set(ids)].sort((a, b) => Number(a) - Number(b));
|
|
67
|
+
/** The run's budget said no inside a call: the call answers what it has read so far. */
|
|
68
|
+
class Cut extends Error {
|
|
69
|
+
}
|
|
70
|
+
/** The users whose deals a `mine` scope copies: the chosen ones, else the signed-in user (b24's ruling 2026-11-12). */
|
|
71
|
+
const chosenOf = (context) => {
|
|
72
|
+
const scope = context?.scope;
|
|
73
|
+
if (scope?.mode !== "mine")
|
|
74
|
+
return null;
|
|
75
|
+
return [...(scope.also.length ? scope.also : [scope.self])];
|
|
76
|
+
};
|
|
77
|
+
const ownerOf = (raw) => id(raw.responsible_user_id) ?? "";
|
|
78
|
+
const linkedIds = (raw, key) => rawsOf(fieldOf(raw._embedded, key)).flatMap((one) => id(one.id) ?? []);
|
|
79
|
+
const WITH = { deal: "contacts,loss_reason", person: "leads", organization: "leads,contacts" };
|
|
80
|
+
/** A live list's conditions as amoCRM's `filter[…]` (filters-api); one the operation does not declare is refused. */
|
|
81
|
+
const filtersOf = (kind, conditions, self) => {
|
|
82
|
+
const declared = new Set(matchOperation(ENTITIES[kind].list).operation.query);
|
|
83
|
+
const query = {};
|
|
84
|
+
const set = (name, value) => {
|
|
85
|
+
if (!declared.has(name))
|
|
86
|
+
throw new CliError("validation_error", `amoCRM cannot filter ${ENTITIES[kind].name} by ${name}`, {
|
|
87
|
+
reason: "crm.record-field",
|
|
88
|
+
});
|
|
89
|
+
query[name] = value;
|
|
90
|
+
};
|
|
91
|
+
for (const { field, op, value } of conditions) {
|
|
92
|
+
if (field === "assigned_to" && (op === "=" || op === "in")) {
|
|
93
|
+
const users = (Array.isArray(value) ? value : [value]).map((one) => (one === "me" ? self : String(one)));
|
|
94
|
+
for (const user of users)
|
|
95
|
+
if (!user || !/^[1-9][0-9]*$/.test(user))
|
|
96
|
+
throw new CliError("validation_error", "assigned_to takes me or an amoCRM user id, such as 7", {
|
|
97
|
+
reason: "crm.owner-unknown",
|
|
98
|
+
});
|
|
99
|
+
set("filter[responsible_user_id][]", users.map(Number));
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if ((field === "created_at" || field === "updated_at") && typeof value === "number" && op !== "!=" && op !== "in") {
|
|
103
|
+
const ms = value;
|
|
104
|
+
// amoCRM keeps whole seconds: `=` names the second the time falls in.
|
|
105
|
+
if (op === "=" || op === ">=" || op === ">")
|
|
106
|
+
set(`filter[${field}][from]`, op === ">" ? seconds(ms) + 1 : op === "=" ? seconds(ms) : Math.ceil(ms / 1000));
|
|
107
|
+
if (op === "=" || op === "<=" || op === "<")
|
|
108
|
+
set(`filter[${field}][to]`, op === "<" ? Math.ceil(ms / 1000) - 1 : seconds(ms));
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
throw new CliError("validation_error", `amoCRM cannot filter ${ENTITIES[kind].name} by ${field} ${op}`, {
|
|
112
|
+
reason: "crm.record-field",
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return query;
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* The account's CRM for core's sync: leads, contacts and companies by `filter[updated_at]` when the account has the
|
|
119
|
+
* API filter add-on, else by `order[updated_at]=desc` down to the last round (research §3, §9.5); deletions and
|
|
120
|
+
* stage moves from the events list. A `mine` round copies the chosen users' leads and their clients only.
|
|
121
|
+
*/
|
|
122
|
+
export const amoCrmSource = (account, options = {}) => {
|
|
123
|
+
const now = options.now ?? Date.now;
|
|
124
|
+
const size = options.page ?? PAGE;
|
|
125
|
+
const asked = options.asked ?? (async () => ({ mode: "mine", setting: "scope", chosen: "unassigned" }));
|
|
126
|
+
/**
|
|
127
|
+
* core paid for a call's first request; each further one is spent from the run's budget. With `cut`, a spent budget
|
|
128
|
+
* is a `Cut` the call catches, and `spent()` the reason it rethrows when it read nothing.
|
|
129
|
+
*/
|
|
130
|
+
const metered = (context, cut = false) => {
|
|
131
|
+
let paid = false;
|
|
132
|
+
let spent;
|
|
133
|
+
const caller = {
|
|
134
|
+
request: (request) => {
|
|
135
|
+
if (paid && context)
|
|
136
|
+
try {
|
|
137
|
+
context.spend();
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (!cut)
|
|
141
|
+
throw error;
|
|
142
|
+
spent = error;
|
|
143
|
+
throw new Cut();
|
|
144
|
+
}
|
|
145
|
+
paid = true;
|
|
146
|
+
return account().request(request);
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
return Object.assign(caller, { spent: () => spent });
|
|
150
|
+
};
|
|
151
|
+
let about;
|
|
152
|
+
const accountOf = (caller = account()) => (about ??= caller
|
|
153
|
+
.request({ route: ROUTES.account, query: { with: "is_api_filter_enabled,datetime_settings" } })
|
|
154
|
+
.then(({ body }) => ({
|
|
155
|
+
userId: id(fieldOf(body, "current_user_id")) ?? "",
|
|
156
|
+
filters: fieldOf(body, "is_api_filter_enabled") === true,
|
|
157
|
+
currency: text(fieldOf(body, "currency")),
|
|
158
|
+
timeZone: text(fieldOf(fieldOf(fieldOf(body, "_embedded"), "datetime_settings"), "timezone")),
|
|
159
|
+
})));
|
|
160
|
+
const loaded = new Map();
|
|
161
|
+
const fields = (kind, caller = account()) => {
|
|
162
|
+
let found = loaded.get(kind);
|
|
163
|
+
if (!found) {
|
|
164
|
+
if (kind === "lead")
|
|
165
|
+
return Promise.resolve([]);
|
|
166
|
+
found = readAll(caller, ENTITIES[kind].fields, "custom_fields").then((rows) => rows.map(fieldOfRaw).filter((one) => one !== null));
|
|
167
|
+
found.catch(() => loaded.delete(kind));
|
|
168
|
+
loaded.set(kind, found);
|
|
169
|
+
}
|
|
170
|
+
return found;
|
|
171
|
+
};
|
|
172
|
+
const mapped = async (kind, rows, caller) => {
|
|
173
|
+
const defined = await fields(kind, caller);
|
|
174
|
+
const { currency, timeZone } = await accountOf(caller);
|
|
175
|
+
const map = { deal: toDeal, lead: toDeal, person: toPerson, organization: toOrganization }[kind];
|
|
176
|
+
return rows.map((raw) => map(raw, defined, currency, timeZone));
|
|
177
|
+
};
|
|
178
|
+
/** Each lead's responsible user, as far as a round has seen; one not seen yet is read by id. */
|
|
179
|
+
const owners = new Map();
|
|
180
|
+
const remember = (rows) => {
|
|
181
|
+
for (const raw of rows) {
|
|
182
|
+
const lead = id(raw.id);
|
|
183
|
+
if (lead)
|
|
184
|
+
owners.set(lead, ownerOf(raw));
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
/** Reads by id: `filter[id][]` with the add-on, else one record a request. */
|
|
188
|
+
const byIds = async (caller, kind, ids, query) => {
|
|
189
|
+
const { filters } = await accountOf(caller);
|
|
190
|
+
const rows = [];
|
|
191
|
+
for (let at = 0; at < ids.length; at += CHUNK) {
|
|
192
|
+
const chunk = ids.slice(at, at + CHUNK);
|
|
193
|
+
if (filters) {
|
|
194
|
+
const page = await listPage(caller, ENTITIES[kind].list, ENTITIES[kind].name, {
|
|
195
|
+
...query,
|
|
196
|
+
"filter[id][]": chunk.map(Number),
|
|
197
|
+
limit: CHUNK,
|
|
198
|
+
});
|
|
199
|
+
for (const raw of page.rows)
|
|
200
|
+
rows.push(raw);
|
|
201
|
+
}
|
|
202
|
+
else
|
|
203
|
+
for (const externalId of chunk) {
|
|
204
|
+
const raw = await readOne(caller, ENTITIES[kind].one, externalId, query);
|
|
205
|
+
if (raw)
|
|
206
|
+
rows.push(raw);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return rows;
|
|
210
|
+
};
|
|
211
|
+
const ownersOf = async (caller, leads) => {
|
|
212
|
+
const missing = [...new Set(leads)].filter((lead) => !owners.has(lead));
|
|
213
|
+
remember(await byIds(caller, "deal", missing, {}));
|
|
214
|
+
for (const lead of missing)
|
|
215
|
+
if (!owners.has(lead))
|
|
216
|
+
owners.set(lead, "");
|
|
217
|
+
};
|
|
218
|
+
/** One request's worth of records by id: a `filter[id][]` chunk with the add-on, else one record. */
|
|
219
|
+
const readSome = async (caller, kind, ids, query) => {
|
|
220
|
+
const { filters } = await accountOf(caller);
|
|
221
|
+
const chunk = ids.slice(0, filters ? CHUNK : 1);
|
|
222
|
+
return { read: chunk.length, rows: await byIds(caller, kind, chunk, query) };
|
|
223
|
+
};
|
|
224
|
+
/** One request towards the owners of leads no page has shown yet; false when none is left to read. */
|
|
225
|
+
const resolveOwners = async (caller, leads) => {
|
|
226
|
+
const missing = [...new Set(leads)].filter((lead) => !owners.has(lead));
|
|
227
|
+
if (missing.length === 0)
|
|
228
|
+
return false;
|
|
229
|
+
const { read, rows } = await readSome(caller, "deal", missing, {});
|
|
230
|
+
remember(rows);
|
|
231
|
+
for (const lead of missing.slice(0, read))
|
|
232
|
+
if (!owners.has(lead))
|
|
233
|
+
owners.set(lead, "");
|
|
234
|
+
return true;
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* Leads of one round, oldest id first; or, after a cursor, changed since `from`: by `filter[updated_at][from]` with
|
|
238
|
+
* the add-on, else newest first until a row older than `from` (the order is documented on each entity page).
|
|
239
|
+
*/
|
|
240
|
+
const round = async (caller, kind, at, from, extra = {}) => {
|
|
241
|
+
const { filters } = await accountOf(caller);
|
|
242
|
+
const base = { with: WITH[kind], limit: size, page: at, ...extra };
|
|
243
|
+
const entity = ENTITIES[kind];
|
|
244
|
+
if (from === null || filters) {
|
|
245
|
+
const query = from === null ? base : { ...base, "filter[updated_at][from]": from };
|
|
246
|
+
return listPage(caller, entity.list, entity.name, { ...query, "order[id]": "asc" });
|
|
247
|
+
}
|
|
248
|
+
const { rows, more } = await listPage(caller, entity.list, entity.name, { ...base, "order[updated_at]": "desc" });
|
|
249
|
+
const recent = rows.filter((raw) => Number(raw.updated_at) >= from);
|
|
250
|
+
return { rows: recent, more: more && recent.length === rows.length };
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Page `at` and the page before it, read again after it: a row gone from an earlier page between two page reads
|
|
254
|
+
* moves every later row up one place, and the one that moved onto the page before would be skipped. A row already
|
|
255
|
+
* answered in this process is left out by the caller; one answered by an earlier run is saved again, harmlessly.
|
|
256
|
+
*/
|
|
257
|
+
const overlapped = async (read, at) => {
|
|
258
|
+
const page = await read(at);
|
|
259
|
+
if (at === 1)
|
|
260
|
+
return page;
|
|
261
|
+
const on = new Set(page.rows.map((raw) => id(raw.id)));
|
|
262
|
+
const before = (await read(at - 1)).rows.filter((raw) => !on.has(id(raw.id)));
|
|
263
|
+
return { rows: [...before, ...page.rows], more: page.more };
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* One page of the leads a round reads: in a full `mine` round only the chosen users' (narrowed by the add-on, else
|
|
267
|
+
* kept from every lead), after a cursor every changed one, as core drops a lead given away by its assignee. The
|
|
268
|
+
* clients' rounds of a full round walk the same pages before the deals', so it lists each lead page once (research §4
|
|
269
|
+
* counts an account enumerated over and over as a cause of a block).
|
|
270
|
+
*/
|
|
271
|
+
const leadPages = new Map();
|
|
272
|
+
const leadPage = (caller, at, from, chosen) => {
|
|
273
|
+
const key = `${at}|${from ?? ""}|${chosen?.join(",") ?? ""}`;
|
|
274
|
+
const kept = leadPages.get(key);
|
|
275
|
+
if (kept && now() - kept.at < OVERLAP_MS)
|
|
276
|
+
return kept.page;
|
|
277
|
+
const page = (async () => {
|
|
278
|
+
const { filters } = await accountOf(caller);
|
|
279
|
+
const narrow = from === null && chosen && filters ? { "filter[responsible_user_id][]": chosen.map(Number) } : {};
|
|
280
|
+
const { rows, more } = await overlapped((one) => round(caller, "deal", one, from, narrow), at);
|
|
281
|
+
remember(rows);
|
|
282
|
+
return { rows: from === null && chosen ? rows.filter((raw) => chosen.includes(ownerOf(raw))) : rows, more };
|
|
283
|
+
})();
|
|
284
|
+
page.catch(() => leadPages.delete(key));
|
|
285
|
+
leadPages.set(key, { at: now(), page });
|
|
286
|
+
return page;
|
|
287
|
+
};
|
|
288
|
+
/** The clients of a round already read in this process, so one on many leads is read once. */
|
|
289
|
+
const seen = new Map();
|
|
290
|
+
const seenOf = (kind, started) => {
|
|
291
|
+
const key = `${kind}@${started}`;
|
|
292
|
+
const found = seen.get(key) ?? new Set();
|
|
293
|
+
seen.set(key, found);
|
|
294
|
+
return found;
|
|
295
|
+
};
|
|
296
|
+
/**
|
|
297
|
+
* The event types to list: Kommo's events-list takes a comma string in `filter[type]`, amoCRM.ru's events-and-notes
|
|
298
|
+
* an array; neither page names a form both take, so each host gets its own reference's.
|
|
299
|
+
*/
|
|
300
|
+
const typesOf = (types) => new URL(account().origin).hostname.endsWith(".amocrm.ru")
|
|
301
|
+
? { "filter[type][]": types }
|
|
302
|
+
: { "filter[type]": types.join(",") };
|
|
303
|
+
const isAdmin = () => account().isAdmin();
|
|
304
|
+
return {
|
|
305
|
+
provider: "amocrm",
|
|
306
|
+
traits: { kinds: ["organization", "person", "deal"], removedInChanges: true },
|
|
307
|
+
account: () => accountOf(),
|
|
308
|
+
// As b24 (owner's ruling 2026-11-10): a copy is never the whole account, an administrator's included.
|
|
309
|
+
async self() {
|
|
310
|
+
const { mode, setting, chosen } = await asked();
|
|
311
|
+
if (mode === "mine")
|
|
312
|
+
return (await accountOf()).userId;
|
|
313
|
+
throw new CliError("configuration_error", `${setting} is all, and amo never copies the whole CRM: "config set ${setting} mine" copies the deals of ` +
|
|
314
|
+
`the users you choose in ${chosen}, and their clients. Find any other client with "people list" or ` +
|
|
315
|
+
'"organizations list"', { setting, reason: "amo.scope-all-refused" });
|
|
316
|
+
},
|
|
317
|
+
// Only an administrator may copy a colleague's deals: anyone else cannot list the users to tell who is who.
|
|
318
|
+
async unassigned(users) {
|
|
319
|
+
if (await isAdmin())
|
|
320
|
+
return { kept: [...users] };
|
|
321
|
+
const self = (await accountOf()).userId;
|
|
322
|
+
return {
|
|
323
|
+
kept: users.filter((user) => user === self),
|
|
324
|
+
message: "another user; only an amoCRM administrator may copy a colleague's deals",
|
|
325
|
+
};
|
|
326
|
+
},
|
|
327
|
+
async pipelines(_kind, context) {
|
|
328
|
+
const rows = await listPage(metered(context), ROUTES.pipelines, "pipelines", {});
|
|
329
|
+
return rows.rows.map(toPipeline).filter((one) => one !== null);
|
|
330
|
+
},
|
|
331
|
+
fields: (kind, context) => fields(kind, metered(context)),
|
|
332
|
+
async changes(kind, cursor, page, context) {
|
|
333
|
+
const since = cursor === null ? null : Date.parse(cursor);
|
|
334
|
+
if (since !== null && Number.isNaN(since))
|
|
335
|
+
return { reset: true };
|
|
336
|
+
if (kind === "lead")
|
|
337
|
+
return { items: [], hasMore: false, cursor: null };
|
|
338
|
+
const amoKind = kind;
|
|
339
|
+
const caller = metered(context, true);
|
|
340
|
+
const { spot: given, started } = spotOf(page, now());
|
|
341
|
+
const from = since === null ? null : seconds(since - OVERLAP_MS);
|
|
342
|
+
const chosen = chosenOf(context);
|
|
343
|
+
const client = amoKind === "deal" ? null : amoKind;
|
|
344
|
+
const first = { ph: client === null ? "d" : !chosen ? "a" : from === null ? "w" : "c", p: 1, o: 0 };
|
|
345
|
+
let spot = given ?? first;
|
|
346
|
+
// A cut call that moved nothing refuses: core would see the same page twice.
|
|
347
|
+
let progressed = false;
|
|
348
|
+
const rows = [];
|
|
349
|
+
const removed = new Set();
|
|
350
|
+
const kept = seenOf(kind, started);
|
|
351
|
+
const answered = seenOf(`${kind} answered`, started);
|
|
352
|
+
const fresh = (found) => found.filter((raw) => {
|
|
353
|
+
const one = id(raw.id) ?? "";
|
|
354
|
+
if (answered.has(one))
|
|
355
|
+
return false;
|
|
356
|
+
answered.add(one);
|
|
357
|
+
return true;
|
|
358
|
+
});
|
|
359
|
+
// A fixed window keeps an events page's offsets put across runs (events-list's filter[created_at][to]).
|
|
360
|
+
const window = { "filter[created_at][from]": from ?? 0, "filter[created_at][to]": seconds(started) };
|
|
361
|
+
const answer = async (done) => ({
|
|
362
|
+
items: await mapped(kind, rows, caller),
|
|
363
|
+
...(removed.size ? { removed: [...removed] } : {}),
|
|
364
|
+
hasMore: !done,
|
|
365
|
+
...(done ? { cursor: new Date(started).toISOString() } : { nextCursor: `${keyOf(spot)}@${started}` }),
|
|
366
|
+
});
|
|
367
|
+
const after = (more, next) => {
|
|
368
|
+
spot = more ? { ph: spot.ph, p: spot.p + 1, o: 0 } : { ph: next, p: 1, o: 0 };
|
|
369
|
+
progressed = true;
|
|
370
|
+
return more;
|
|
371
|
+
};
|
|
372
|
+
let from_page;
|
|
373
|
+
/**
|
|
374
|
+
* Puts a resumed spot after its row, or on it while its `sub` is read. A row not on the page is looked for on
|
|
375
|
+
* the page before; one gone from every page restarts a page before the one it was on. False: read the new page.
|
|
376
|
+
*/
|
|
377
|
+
const settle = (ids) => {
|
|
378
|
+
if (spot.k === undefined)
|
|
379
|
+
return true;
|
|
380
|
+
const at = ids.indexOf(spot.k);
|
|
381
|
+
if (at >= 0) {
|
|
382
|
+
spot = spot.l === undefined ? { ph: spot.ph, p: spot.p, o: at + 1, k: spot.k } : { ...spot, o: at };
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
from_page ??= spot.p;
|
|
386
|
+
progressed = true;
|
|
387
|
+
if (spot.p > 1) {
|
|
388
|
+
spot = { ...spot, p: spot.p - 1, o: 0 };
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
const restart = Math.max(1, from_page - 1);
|
|
392
|
+
spot = { ph: spot.ph, p: restart, o: 0 };
|
|
393
|
+
return restart === 1;
|
|
394
|
+
};
|
|
395
|
+
/** The sub-offset of the row `externalId`: kept only while the spot is still on that row. */
|
|
396
|
+
const subOf = (externalId) => (spot.k === externalId && spot.l !== undefined ? spot.l : 0);
|
|
397
|
+
try {
|
|
398
|
+
for (;;) {
|
|
399
|
+
if (spot.ph === "")
|
|
400
|
+
return await answer(true);
|
|
401
|
+
if (spot.ph === "d") {
|
|
402
|
+
const { rows: leads, more } = await leadPage(caller, spot.p, from, chosen);
|
|
403
|
+
for (const raw of fresh(leads))
|
|
404
|
+
rows.push(raw);
|
|
405
|
+
if (after(more, from === null ? "" : "r"))
|
|
406
|
+
return await answer(false);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (spot.ph === "a" && client) {
|
|
410
|
+
const { rows: found, more } = await overlapped((one) => round(caller, client, one, from), spot.p);
|
|
411
|
+
for (const raw of fresh(found))
|
|
412
|
+
rows.push(raw);
|
|
413
|
+
if (after(more && found.length > 0, from === null ? "" : "r"))
|
|
414
|
+
return await answer(false);
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if ((spot.ph === "w" || spot.ph === "n") && client && chosen) {
|
|
418
|
+
const { rows: leads, more } = await leadPage(caller, spot.p, from, chosen);
|
|
419
|
+
const own = leads.filter((raw) => chosen.includes(ownerOf(raw)));
|
|
420
|
+
if (!settle(own.map((raw) => id(raw.id) ?? "")))
|
|
421
|
+
continue;
|
|
422
|
+
while (spot.o < own.length) {
|
|
423
|
+
const lead = own[spot.o];
|
|
424
|
+
const leadId = id(lead.id) ?? "";
|
|
425
|
+
const names = byNumber(linkedIds(lead, client === "person" ? "contacts" : "companies"));
|
|
426
|
+
let done = subOf(leadId);
|
|
427
|
+
for (;;) {
|
|
428
|
+
const left = names.filter((one) => Number(one) > done && !kept.has(one));
|
|
429
|
+
if (left.length === 0)
|
|
430
|
+
break;
|
|
431
|
+
spot = { ...spot, l: done, k: leadId };
|
|
432
|
+
const { read, rows: found } = await readSome(caller, client, left, { with: WITH[client] });
|
|
433
|
+
for (const raw of found)
|
|
434
|
+
rows.push(raw);
|
|
435
|
+
for (const one of left.slice(0, read))
|
|
436
|
+
kept.add(one);
|
|
437
|
+
done = Number(left[read - 1]);
|
|
438
|
+
spot = { ...spot, l: done, k: leadId };
|
|
439
|
+
progressed = true;
|
|
440
|
+
// A page saved now is kept if the process ends before the next answer.
|
|
441
|
+
if (rows.length >= CHUNK)
|
|
442
|
+
return await answer(false);
|
|
443
|
+
}
|
|
444
|
+
spot = { ph: spot.ph, p: spot.p, o: spot.o + 1, k: leadId };
|
|
445
|
+
progressed = true;
|
|
446
|
+
}
|
|
447
|
+
if (after(more, spot.ph === "w" ? "" : "r"))
|
|
448
|
+
return await answer(false);
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (spot.ph === "c" && client && chosen && from !== null) {
|
|
452
|
+
const { rows: changed, more } = await round(caller, client, spot.p, from);
|
|
453
|
+
if (!settle(changed.map((raw) => id(raw.id) ?? "")))
|
|
454
|
+
continue;
|
|
455
|
+
while (spot.o < changed.length) {
|
|
456
|
+
const raw = changed[spot.o];
|
|
457
|
+
const externalId = id(raw.id) ?? "";
|
|
458
|
+
const leads = byNumber(linkedIds(raw, "leads"));
|
|
459
|
+
const ours = () => chosen.includes(ownerOf(raw)) || leads.some((lead) => chosen.includes(owners.get(lead) ?? ""));
|
|
460
|
+
let done = subOf(externalId);
|
|
461
|
+
for (const lead of leads) {
|
|
462
|
+
if (ours())
|
|
463
|
+
break;
|
|
464
|
+
if (Number(lead) <= done)
|
|
465
|
+
continue;
|
|
466
|
+
if (!owners.has(lead)) {
|
|
467
|
+
spot = { ...spot, l: done, k: externalId };
|
|
468
|
+
await resolveOwners(caller, leads.filter((one) => Number(one) >= Number(lead)));
|
|
469
|
+
progressed = true;
|
|
470
|
+
}
|
|
471
|
+
done = Number(lead);
|
|
472
|
+
}
|
|
473
|
+
// A colleague's client on none of the chosen leads stays out of the copy.
|
|
474
|
+
if (ours()) {
|
|
475
|
+
rows.push(raw);
|
|
476
|
+
kept.add(externalId);
|
|
477
|
+
}
|
|
478
|
+
spot = { ph: spot.ph, p: spot.p, o: spot.o + 1, k: externalId };
|
|
479
|
+
progressed = true;
|
|
480
|
+
}
|
|
481
|
+
if (after(more, "n"))
|
|
482
|
+
return await answer(false);
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
if (spot.ph === "r" && from !== null) {
|
|
486
|
+
const { rows: events, more } = await listPage(caller, ROUTES.events, "events", {
|
|
487
|
+
...typesOf([`${ENTITIES[amoKind].event}_deleted`]),
|
|
488
|
+
...window,
|
|
489
|
+
limit: EVENTS_PAGE,
|
|
490
|
+
page: spot.p,
|
|
491
|
+
});
|
|
492
|
+
for (const raw of events) {
|
|
493
|
+
const entity = id(raw.entity_id);
|
|
494
|
+
if (entity)
|
|
495
|
+
removed.add(entity);
|
|
496
|
+
}
|
|
497
|
+
// Its own answer: core saves an answer's items before it removes its removed, and restores come next.
|
|
498
|
+
after(more && events.length > 0, "s");
|
|
499
|
+
return await answer(false);
|
|
500
|
+
}
|
|
501
|
+
if (spot.ph === "s" && from !== null) {
|
|
502
|
+
// The events list has no documented order (events-and-notes, events-list): a record restored in the
|
|
503
|
+
// window is read as it is now, after every deletion this round named, so the newest state wins.
|
|
504
|
+
const { rows: events, more } = await listPage(caller, ROUTES.events, "events", {
|
|
505
|
+
...typesOf([`${ENTITIES[amoKind].event}_restored`]),
|
|
506
|
+
...window,
|
|
507
|
+
limit: EVENTS_PAGE,
|
|
508
|
+
page: spot.p,
|
|
509
|
+
});
|
|
510
|
+
const back = byNumber(events.flatMap((raw) => id(raw.entity_id) ?? []));
|
|
511
|
+
let done = Number(spot.k ?? 0);
|
|
512
|
+
for (;;) {
|
|
513
|
+
const left = back.filter((one) => Number(one) > done);
|
|
514
|
+
if (left.length === 0)
|
|
515
|
+
break;
|
|
516
|
+
const { read, rows: found } = await readSome(caller, amoKind, left, { with: WITH[amoKind] });
|
|
517
|
+
const alive = new Set();
|
|
518
|
+
for (const raw of found) {
|
|
519
|
+
if (raw.is_deleted === true)
|
|
520
|
+
continue;
|
|
521
|
+
alive.add(id(raw.id) ?? "");
|
|
522
|
+
if (!client || !chosen || chosen.includes(ownerOf(raw)))
|
|
523
|
+
rows.push(raw);
|
|
524
|
+
}
|
|
525
|
+
for (const one of left.slice(0, read))
|
|
526
|
+
if (!alive.has(one))
|
|
527
|
+
removed.add(one);
|
|
528
|
+
done = Number(left[read - 1]);
|
|
529
|
+
spot = { ...spot, k: String(done) };
|
|
530
|
+
progressed = true;
|
|
531
|
+
}
|
|
532
|
+
if (after(more && events.length > 0, ""))
|
|
533
|
+
return await answer(false);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
return { reset: true };
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
catch (error) {
|
|
540
|
+
if (!(error instanceof Cut))
|
|
541
|
+
throw error;
|
|
542
|
+
if (!progressed)
|
|
543
|
+
throw caller.spent();
|
|
544
|
+
return answer(false);
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
async stageHistory(_kind, since, after, context) {
|
|
548
|
+
const caller = metered(context, true);
|
|
549
|
+
const chosen = chosenOf(context);
|
|
550
|
+
// `h<from>.<page>.<offset>.<latest>` inside a span; the latest time read once the span is done.
|
|
551
|
+
const inside = /^h(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(after ?? "");
|
|
552
|
+
const resumed = inside ? 0 : Number(after ?? 0) || 0;
|
|
553
|
+
// An event written late with an earlier time is still read; the store keeps each entry once by its id.
|
|
554
|
+
const from = inside ? Number(inside[1]) : resumed ? resumed - seconds(OVERLAP_MS) : seconds(since);
|
|
555
|
+
let at = inside ? { p: Number(inside[2]), o: Number(inside[3]) } : { p: 1, o: 0 };
|
|
556
|
+
let last = inside ? Number(inside[4]) : resumed || from;
|
|
557
|
+
const start = `${at.p}.${at.o}`;
|
|
558
|
+
const items = [];
|
|
559
|
+
const named = new Set();
|
|
560
|
+
const answer = (done) => {
|
|
561
|
+
items.sort((a, b) => a.at - b.at);
|
|
562
|
+
return done
|
|
563
|
+
? { items, hasMore: false, cursor: String(last) }
|
|
564
|
+
: { items, hasMore: true, nextCursor: `h${from}.${at.p}.${at.o}.${last}` };
|
|
565
|
+
};
|
|
566
|
+
try {
|
|
567
|
+
for (;;) {
|
|
568
|
+
const { rows, more } = await listPage(caller, ROUTES.events, "events", {
|
|
569
|
+
...typesOf(["lead_status_changed"]),
|
|
570
|
+
"filter[created_at][from]": from,
|
|
571
|
+
limit: EVENTS_PAGE,
|
|
572
|
+
page: at.p,
|
|
573
|
+
});
|
|
574
|
+
while (at.o < rows.length) {
|
|
575
|
+
const raw = rows[at.o];
|
|
576
|
+
// Kommo events-list: `value_after: [{lead_status: {id, pipeline_id}}]`.
|
|
577
|
+
const status = fieldOf(rawsOf(raw.value_after)[0], "lead_status");
|
|
578
|
+
const externalId = text(raw.id);
|
|
579
|
+
const item = id(raw.entity_id);
|
|
580
|
+
const stage = id(fieldOf(status, "id"));
|
|
581
|
+
const pipeline = id(fieldOf(status, "pipeline_id"));
|
|
582
|
+
const when = Number(raw.created_at);
|
|
583
|
+
// Under `mine` only the scope's deals: the events list cannot be narrowed by owner (events-and-notes).
|
|
584
|
+
if (chosen && item)
|
|
585
|
+
while (await resolveOwners(caller, [item])) { }
|
|
586
|
+
if (externalId &&
|
|
587
|
+
item &&
|
|
588
|
+
stage &&
|
|
589
|
+
pipeline &&
|
|
590
|
+
when > 0 &&
|
|
591
|
+
(!chosen || chosen.includes(owners.get(item) ?? "")) &&
|
|
592
|
+
!named.has(externalId)) {
|
|
593
|
+
named.add(externalId);
|
|
594
|
+
items.push({ externalId, kind: "deal", item, pipeline, stage, at: when * 1000 });
|
|
595
|
+
}
|
|
596
|
+
// Past every event read, kept or not: a span of colleagues' moves is not read again.
|
|
597
|
+
if (when > 0)
|
|
598
|
+
last = Math.max(last, when);
|
|
599
|
+
at = { ...at, o: at.o + 1 };
|
|
600
|
+
}
|
|
601
|
+
if (!more || rows.length === 0)
|
|
602
|
+
return answer(true);
|
|
603
|
+
at = { p: at.p + 1, o: 0 };
|
|
604
|
+
// The event order is not documented: each page is saved, and the store keeps an entry once.
|
|
605
|
+
return answer(false);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
if (!(error instanceof Cut))
|
|
610
|
+
throw error;
|
|
611
|
+
if (`${at.p}.${at.o}` === start)
|
|
612
|
+
throw caller.spent();
|
|
613
|
+
return answer(false);
|
|
614
|
+
}
|
|
615
|
+
},
|
|
616
|
+
// Read only when the account's activities setting is on; core keeps those on the deals and clients the copy holds.
|
|
617
|
+
activities(since, page, context) {
|
|
618
|
+
const caller = metered(context);
|
|
619
|
+
return readActivities((route, name, query) => listPage(caller, route, name, query), { since, now: now(), size, types: typesOf, ...(page === undefined ? {} : { page }) }, context);
|
|
620
|
+
},
|
|
621
|
+
async users(context) {
|
|
622
|
+
return (await readAll(metered(context), ROUTES.users, "users")).flatMap((raw) => toUser(raw) ?? []);
|
|
623
|
+
},
|
|
624
|
+
async list(kind, query, context) {
|
|
625
|
+
const caller = metered(context);
|
|
626
|
+
const me = query.conditions.some((one) => one.field === "assigned_to" && [one.value].flat().includes("me"));
|
|
627
|
+
const filters = filtersOf(kind, query.conditions, me ? (await accountOf(caller)).userId : undefined);
|
|
628
|
+
if (Object.keys(filters).length && !(await accountOf(caller)).filters)
|
|
629
|
+
throw new CliError("validation_error", "this account has no API filter add-on (is_api_filter_enabled is off), so amoCRM cannot narrow the list " +
|
|
630
|
+
"by owner or time; search by name instead", { reason: "amo.filters-off" });
|
|
631
|
+
const entity = ENTITIES[kind];
|
|
632
|
+
const { rows, more } = await listPage(caller, entity.list, entity.name, {
|
|
633
|
+
...filters,
|
|
634
|
+
...(query.text ? { query: query.text } : {}),
|
|
635
|
+
...(kind === "organization" ? { with: "contacts" } : {}),
|
|
636
|
+
"order[updated_at]": "desc",
|
|
637
|
+
limit: query.limit,
|
|
638
|
+
page: query.page ?? 1,
|
|
639
|
+
});
|
|
640
|
+
return { items: await mapped(kind, rows, caller), hasMore: more && rows.length > 0 };
|
|
641
|
+
},
|
|
642
|
+
async get(kind, externalId, context) {
|
|
643
|
+
const caller = metered(context);
|
|
644
|
+
const raw = await readOne(caller, ENTITIES[kind].one, externalId, kind === "organization" ? { with: "contacts" } : {});
|
|
645
|
+
return raw ? ((await mapped(kind, [raw], caller))[0] ?? null) : null;
|
|
646
|
+
},
|
|
647
|
+
isAdmin,
|
|
648
|
+
// A client is the sign-in's own when it is assigned to its user or on one of its user's leads.
|
|
649
|
+
async ownClients(kind, ids) {
|
|
650
|
+
const caller = account();
|
|
651
|
+
const self = (await accountOf(caller)).userId;
|
|
652
|
+
const rows = await byIds(caller, kind, ids, { with: "leads" });
|
|
653
|
+
await ownersOf(caller, rows.flatMap((raw) => linkedIds(raw, "leads")));
|
|
654
|
+
return new Set(rows
|
|
655
|
+
.filter((raw) => ownerOf(raw) === self || linkedIds(raw, "leads").some((lead) => owners.get(lead) === self))
|
|
656
|
+
.flatMap((raw) => id(raw.id) ?? []));
|
|
657
|
+
},
|
|
658
|
+
async item(externalId) {
|
|
659
|
+
const raw = await readOne(account(), ROUTES.lead, externalId, { with: WITH.deal });
|
|
660
|
+
if (!raw)
|
|
661
|
+
throw new CliError("not_found", `amoCRM has no deal ${externalId}`);
|
|
662
|
+
return (await mapped("deal", [raw], account()))[0];
|
|
663
|
+
},
|
|
664
|
+
async lossReasons() {
|
|
665
|
+
const { rows } = await listPage(account(), ROUTES.lossReasons, "loss_reasons", {});
|
|
666
|
+
return rows.flatMap((raw) => {
|
|
667
|
+
const reason = id(raw.id);
|
|
668
|
+
return reason ? [{ id: reason, name: text(raw.name) ?? reason }] : [];
|
|
669
|
+
});
|
|
670
|
+
},
|
|
671
|
+
};
|
|
672
|
+
};
|
|
673
|
+
//# sourceMappingURL=source.js.map
|