@wirecat/cli-core 0.605.0 → 0.606.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/CHANGELOG.md +98 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -0
- package/dist/cli/store-settings.js +38 -4
- package/dist/crm/cli/index.js +3 -1
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +1 -1
- package/dist/crm/source.d.ts +35 -5
- package/dist/crm/sync.d.ts +15 -7
- package/dist/crm/sync.js +169 -11
- package/dist/domain/crm.d.ts +41 -2
- package/dist/domain/deals.d.ts +5 -2
- package/dist/domain/deals.js +5 -2
- package/dist/domain/relations.d.ts +125 -0
- package/dist/domain/relations.js +107 -0
- package/dist/entities/deal.d.ts +2 -2
- package/dist/entities/deal.js +2 -1
- package/dist/entities/index.d.ts +17 -13
- package/dist/entities/relationship.d.ts +8 -2
- package/dist/entities/relationship.js +8 -2
- package/dist/entities/task-results.d.ts +10 -10
- package/dist/errors/reasons.js +12 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/mail/cli/review.js +20 -6
- package/dist/mail/index.d.ts +1 -1
- package/dist/mail/marks.d.ts +10 -5
- package/dist/mail/marks.js +16 -8
- package/dist/mail/review.d.ts +5 -0
- package/dist/services/link-scorers/scan.js +2 -1
- package/dist/services/link-scorers/shared.js +2 -1
- package/dist/services/project-status/index.js +2 -1
- package/dist/services/stored-project-gathering.js +4 -3
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/index.d.ts +6 -1
- package/dist/store/index.js +1 -0
- package/dist/store/project-transfer/request.d.ts +4 -1
- package/dist/store/project-transfer/schema.d.ts +9 -2
- package/dist/store/project-transfer/schema.js +4 -0
- package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
- package/dist/store/sqlite/crm-settings.d.ts +28 -0
- package/dist/store/sqlite/crm-settings.js +80 -0
- package/dist/store/sqlite/crm.d.ts +42 -2
- package/dist/store/sqlite/crm.js +397 -36
- package/dist/store/sqlite/deals.js +3 -2
- package/dist/store/sqlite/involvement-queue.js +4 -3
- package/dist/store/sqlite/knowledge.d.ts +7 -3
- package/dist/store/sqlite/knowledge.js +43 -31
- package/dist/store/sqlite/link-kinds.d.ts +2 -3
- package/dist/store/sqlite/link-kinds.js +4 -2
- package/dist/store/sqlite/manifest.js +5 -0
- package/dist/store/sqlite/memories.d.ts +1 -1
- package/dist/store/sqlite/memories.js +33 -7
- package/dist/store/sqlite/migrations.generated.js +31 -0
- package/dist/store/sqlite/notes.d.ts +3 -2
- package/dist/store/sqlite/notes.js +23 -6
- package/dist/store/sqlite/organizations.d.ts +8 -0
- package/dist/store/sqlite/organizations.js +14 -0
- package/dist/store/sqlite/person-preparation.d.ts +1 -1
- package/dist/store/sqlite/person-preparation.js +3 -2
- package/dist/store/sqlite/project-transfer/records.js +14 -3
- package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
- package/dist/store/sqlite/relation-list.d.ts +43 -0
- package/dist/store/sqlite/relation-list.js +133 -0
- package/dist/store/sqlite/relation-proposals.d.ts +28 -6
- package/dist/store/sqlite/relation-proposals.js +134 -10
- package/dist/store/sqlite/relation-reads.d.ts +8 -0
- package/dist/store/sqlite/relation-reads.js +7 -0
- package/dist/store/sqlite/relation-roles.d.ts +26 -0
- package/dist/store/sqlite/relation-roles.js +91 -0
- package/dist/store/sqlite/reported-relations.d.ts +63 -0
- package/dist/store/sqlite/reported-relations.js +132 -0
- package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
- package/dist/store/sqlite/schema/link-revisions.js +11 -0
- package/dist/store/sqlite/schema/links.d.ts +360 -0
- package/dist/store/sqlite/schema/links.js +32 -0
- package/dist/store/sqlite/schema.d.ts +2 -296
- package/dist/store/sqlite/schema.js +2 -24
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,104 @@ shape of this file.
|
|
|
7
7
|
|
|
8
8
|
## Unreleased
|
|
9
9
|
|
|
10
|
+
## 0.606.0 — 08.11.2026
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Business relationships: `reports-to`, `customer-of` and `partner-of`, role lists, and a `standing` on every
|
|
15
|
+
relationship.** `knowledge.relate` takes a person reporting to a person, a person or organization buying from an
|
|
16
|
+
organization, and two partner organizations (stored once, the lower id first, whichever way they are named). A deal
|
|
17
|
+
or a lead may be a relationship's `from`, so its people are relationships too, and `influencer` joins the deal roles.
|
|
18
|
+
Each relationship answers `standing`: `confirmed`, `reported` (a source's, nobody confirmed it), `proposed` or
|
|
19
|
+
`ended`. The kinds, their ends and roles are one registry, `RELATIONS` (`src/domain/relations.ts`), exported with
|
|
20
|
+
`ORGANIZATION_ROLES`, `PROJECT_ROLES`, `standingOf` and `usableLink`.
|
|
21
|
+
- **`review --holder` gives each email the cursor and findings key that end the batch at it** (`email.cursor`,
|
|
22
|
+
`email.findings_key`). A reader that cuts the batch to fit, such as an agent's input, acknowledges the last email it
|
|
23
|
+
showed instead of the batch's end, so the mark never moves past mail it did not show. Held emails, older than
|
|
24
|
+
the mark, end the batch at the mark with a key of their own (`<holder>:<mark>-h<highest held id>`).
|
|
25
|
+
- **`@wirecat/cli-core/cli` exports `AGENT_INPUT_MAX_CHARS`**, the 60,000-character cut of an agent's input, so a
|
|
26
|
+
host that builds the input can stay under it and cut at its own boundaries.
|
|
27
|
+
|
|
28
|
+
- **Relationship links know the account that reported them, when they held, and their history (store version 56).**
|
|
29
|
+
`links` gains `account_id`, `starts_at`, `ends_at` and `deleted_at`; `link_revisions` keeps one row per change of a
|
|
30
|
+
relationship link (`added`, `changed`, `ended`, `confirmed`, `withdrawn`, `restored`, `rejected`, `removed`),
|
|
31
|
+
written by triggers, never for a change of `updated_at` alone and never for links of other kinds. A unique key on
|
|
32
|
+
relationship links (kind, ends, anchor, role, account) lets one pair hold several roles and keeps a source's claim
|
|
33
|
+
apart from the owner's; the migration folds duplicates onto the owner's row, keeps their metadata and re-points the
|
|
34
|
+
proposals that named a dropped row.
|
|
35
|
+
|
|
36
|
+
- **A CRM sync keeps the relationships the CRM reports, as a diff.** Contacts become `member-of` their companies (role
|
|
37
|
+
`contact`, the job title beside it), a deal's contacts keep their deal roles and its `assignee` is its `owner`, the
|
|
38
|
+
account's users are `member-of` its own companies as `employee` and, from the departments, `reports-to` their head.
|
|
39
|
+
What the CRM stops reporting is withdrawn, not deleted; a link the owner confirmed is never withdrawn, and one the
|
|
40
|
+
owner removed or rejected, role included, is not written again (`skipped_owner_rejected`). A deal that names a
|
|
41
|
+
contact not synced yet gets it on a later run. `CrmPerson.organizations`/`position`, `CrmItem.people[].primary`,
|
|
42
|
+
`CrmOrganization.own`/`type`, `CrmUser`, `CrmDepartment` and `CrmSource.users()`/`departments()` carry them, all
|
|
43
|
+
optional. The same diff is `store.relations.syncReported` for any source. The store settings
|
|
44
|
+
`crm.<provider>:<account>.links` (`reported` or `review`: new relationships wait as proposals) and
|
|
45
|
+
`crm.<provider>:<account>.company-types` (a company type means `customer-of`, `supplier` or `partner-of` the own
|
|
46
|
+
company) are offered by every CLI's `config`. `knowledge.setOwnOrganization` records the owner's own-company
|
|
47
|
+
mark, which no sync changes; `crmGapsOf` reads what the account's last sync could not list (`{ kind, reason, code?, scope?, message }`).
|
|
48
|
+
Every `CrmSource` call takes an optional `CrmCallContext`: `spend()` takes one budget unit per extra request and
|
|
49
|
+
stops the run as `partial` when it is spent; `gap()` reports what a call could not read without failing it.
|
|
50
|
+
- **A relationship keeps a job title and when it held.** `relate` and `updateRelation` take `position`, `startsAt`
|
|
51
|
+
and `endsAt` (UTC ms, the end after the start); relationships answer `position`, `startsAt` and `endsAt`.
|
|
52
|
+
`knowledge.endRelation(key, id, at, by)` ends one without removing it (standing `ended` from then); an agent's end
|
|
53
|
+
is a `relationship_update` proposal.
|
|
54
|
+
- **The owner adds his own roles to the organization, project and deal role lists.** `knowledge.roles(list)`,
|
|
55
|
+
`addRole(list, id, label?)` and `removeRole(list, id)`, kept in the store setting `relationships.roles.<list>`; a
|
|
56
|
+
role id is lowercase letters, digits and `-`. Built-in roles stay; a role a relationship still holds is not removed
|
|
57
|
+
(`relationship.role-in-use` with the count).
|
|
58
|
+
- **`knowledge.listRelations(filter)` filters and pages relationships and pending relationship proposals in SQL.**
|
|
59
|
+
By `kind`, `role`, `standing`, `from`, `to`, `about` (both ways, each row with `direction` and the inverse label),
|
|
60
|
+
`at`, `includeEnded`, `accounts` (a source's rows only from these; the owner's always) and `deniedKinds`; `limit`
|
|
61
|
+
and `page` with `hasMore`. Each row says its `source` (`link` or `proposal`) and `custom` for a stored role off its
|
|
62
|
+
list.
|
|
63
|
+
|
|
64
|
+
### Changed — may break callers
|
|
65
|
+
|
|
66
|
+
- **Store version 56 raises `minCompatible` to 56: a build from before it refuses the store and asks to be upgraded.**
|
|
67
|
+
A build that knows no account on a link would write a CRM's people as the owner's again, or fail on the new unique
|
|
68
|
+
key. Bump every CLI the same day as this release.
|
|
69
|
+
|
|
70
|
+
- **A person's role on an organization, a project, a deal or a lead must be one of that relationship's roles.**
|
|
71
|
+
`relate` and `updateRelation` refuse any other with `relationship.role-unknown`, naming the roles it takes; a role
|
|
72
|
+
between other ends stays free text, and roles already stored are read as they are. `member-of` now joins only to an
|
|
73
|
+
organization or a project. What to do: map a free-text role to the closest listed one (a job title goes in
|
|
74
|
+
`metadata.position`, never in the role); memo's `author`, `lead` and `cto` examples and tests need it.
|
|
75
|
+
- **`KnowledgeRelation.standing` and the `relationship` entity's `standing` are required.** A caller that builds one
|
|
76
|
+
by hand adds it; `standingOf` derives it from the link.
|
|
77
|
+
- **A CRM's deal and lead people are `confirmed: false`, `standing: reported` (store version 56).** They were stored
|
|
78
|
+
confirmed, as if the owner had said so. They still count wherever confirmed relationships count (`usableLink`), and
|
|
79
|
+
a deal still lists them; a view that reads `confirmed: false` as "proposed" (memo's relationships list) should read
|
|
80
|
+
`standing` instead.
|
|
81
|
+
- **The owner's change to a relationship a CRM reported overrides it.** The first `updateRelation`, `endRelation` or
|
|
82
|
+
confirmed `relationship_update` on a reported link makes one owner link that overrides it (`metadata.overrides`);
|
|
83
|
+
later changes change that link in place. Reads show the override instead of the CRM's row, which its sync keeps
|
|
84
|
+
diffing; removing the override shows the CRM's row again. A role is checked against the current role lists when a
|
|
85
|
+
proposal is approved, and a role a pending proposal holds counts as in use.
|
|
86
|
+
- **`relate` with a role the pair does not hold yet makes a second relationship**, since one pair may hold several
|
|
87
|
+
roles; without a role it answers the pair's link as before. `updateRelation` to a role the pair already holds is
|
|
88
|
+
refused with `relationship.exists`.
|
|
89
|
+
- **Removing any relationship leaves a rejected proposal**, so neither a scan nor a source's sync brings it back; it
|
|
90
|
+
was so only for a link to a project or a suggestion.
|
|
91
|
+
- **A memory written as `proposed` with `supersedes` no longer retires the old one until it is confirmed**, the
|
|
92
|
+
owner's included. `store.memories.add` and `confirm` refuse superseding a memory that is already superseded
|
|
93
|
+
(`memory.already-superseded`), so two corrections of one memory cannot both stand. drive-cli writes every memory
|
|
94
|
+
`proposed`, so its `memories add --supersedes` now retires the old memory only when that memory's correction is
|
|
95
|
+
confirmed.
|
|
96
|
+
|
|
97
|
+
### Fixed
|
|
98
|
+
|
|
99
|
+
- **The person a CRM contact or user makes takes its name.** Joined to the mail contact of its address first, it was
|
|
100
|
+
left with no name.
|
|
101
|
+
- **A holder's batch of held emails only no longer reuses the findings key of the run that set the mark**, which
|
|
102
|
+
refused its staging (`key-used`): it takes `-h<highest held id>`.
|
|
103
|
+
- **An agent's correction no longer retires the memory it corrects.** `store.memories.add({ supersedes })` marked the
|
|
104
|
+
old memory `superseded` as soon as the new one was written, even while the new one only waited as proposed. Now
|
|
105
|
+
`confirm` of the correction retires it; rejecting or removing the correction leaves it as it was. Retiring a
|
|
106
|
+
confirmed memory is the owner's alone, whatever `agent_decisions` says.
|
|
107
|
+
|
|
10
108
|
## 0.605.0 — 07.11.2026
|
|
11
109
|
|
|
12
110
|
### Added
|
package/dist/cli/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { AI_ENTRIES, AI_SETTING_KEYS, type AISettings, resolveAISettings } from "../analysis/settings.js";
|
|
2
|
-
export type
|
|
2
|
+
export { AGENT_INPUT_MAX_CHARS, type AgentCli, type AgentInput } from "../background/schedules.js";
|
|
3
3
|
export { parseDuration } from "../domain/duration.js";
|
|
4
4
|
export { openOf, PROFILE_PLACEHOLDER, type ProfilesFor, type RefOpen, type RefSummary, refLabel, } from "../domain/ref-summaries.js";
|
|
5
5
|
export { botTemplate } from "../entities/list-results.js";
|
package/dist/cli/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { AI_ENTRIES, AI_SETTING_KEYS, resolveAISettings } from "../analysis/settings.js";
|
|
2
|
+
export { AGENT_INPUT_MAX_CHARS } from "../background/schedules.js";
|
|
2
3
|
export { parseDuration } from "../domain/duration.js";
|
|
3
4
|
export { openOf, PROFILE_PLACEHOLDER, refLabel, } from "../domain/ref-summaries.js";
|
|
4
5
|
export { botTemplate } from "../entities/list-results.js";
|
|
@@ -8,7 +8,7 @@ import { DEFAULT_STEMMERS, parseStemmers } from "../search/stem.js";
|
|
|
8
8
|
import { openCache } from "../store/open.js";
|
|
9
9
|
import { storePath } from "../store/path.js";
|
|
10
10
|
import { applyTaskCategoryEdits, editsFrom, readTaskCategoryEdits, sharedConfigPath, writeTaskCategoryEdits, } from "../store/shared-config.js";
|
|
11
|
-
import { accountGroupsOf, DEFAULT_AGENT_CLOSE, DEFAULT_FIRST_PASS_PER_CHAT, firstPassPerChatOf, openStore, savedAgentClose, savedFirstPassPerChat, savedPhoneCountries, savedStemmers, savedTaskCategories, saveStorePhoneCountries, stemmersOrigin, } from "../store/store.js";
|
|
11
|
+
import { accountGroupsOf, crmSettingsOf, DEFAULT_AGENT_CLOSE, DEFAULT_FIRST_PASS_PER_CHAT, firstPassPerChatOf, openStore, parseCrmSetting, parseCrmSettingValue, saveCrmSetting, savedAgentClose, savedFirstPassPerChat, savedPhoneCountries, savedStemmers, savedTaskCategories, saveStorePhoneCountries, stemmersOrigin, } from "../store/store.js";
|
|
12
12
|
const SCRIPTS = {
|
|
13
13
|
"search_stemmers.cyrillic": "cyrillic",
|
|
14
14
|
"search_stemmers.latin": "latin",
|
|
@@ -29,12 +29,16 @@ export const STORE_SETTINGS = [
|
|
|
29
29
|
FIRST_PASS,
|
|
30
30
|
];
|
|
31
31
|
const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
|
|
32
|
+
/** A CRM account's: whether what it reports is a relationship or waits for review, and what its company types mean. */
|
|
33
|
+
const CRM_SETTINGS = ["crm.<provider>:<account>.links", "crm.<provider>:<account>.company-types"];
|
|
32
34
|
/**
|
|
33
35
|
* The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
|
|
34
36
|
* not a messenger would change them for tg and MAX without reading them itself.
|
|
35
37
|
*/
|
|
36
|
-
export const storeSettingsOf = (app) => app.messenger === false
|
|
37
|
-
|
|
38
|
+
export const storeSettingsOf = (app) => app.messenger === false
|
|
39
|
+
? [...Object.keys(SCRIPTS), ...CRM_SETTINGS]
|
|
40
|
+
: [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`, ...CRM_SETTINGS];
|
|
41
|
+
export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS || parseCrmSetting(setting) !== undefined;
|
|
38
42
|
export const isStoreSetting = (setting) => setting in SCRIPTS ||
|
|
39
43
|
setting === PHONE_COUNTRIES ||
|
|
40
44
|
setting === TASK_CATEGORIES ||
|
|
@@ -42,10 +46,13 @@ export const isStoreSetting = (setting) => setting in SCRIPTS ||
|
|
|
42
46
|
setting === AGENT_CLOSE ||
|
|
43
47
|
setting === AGENT_CLOSE_MIN ||
|
|
44
48
|
setting === FIRST_PASS ||
|
|
45
|
-
setting.startsWith(GROUP_PREFIX)
|
|
49
|
+
setting.startsWith(GROUP_PREFIX) ||
|
|
50
|
+
parseCrmSetting(setting) !== undefined;
|
|
46
51
|
export const changeStoreSetting = async (app, env, setting, value) => {
|
|
47
52
|
if (setting.startsWith(GROUP_PREFIX))
|
|
48
53
|
return changeGroup(app, env, setting, value);
|
|
54
|
+
if (parseCrmSetting(setting))
|
|
55
|
+
return changeCrm(env, setting, value);
|
|
49
56
|
if (setting === PHONE_COUNTRIES)
|
|
50
57
|
return changePhoneCountries(app, env, value);
|
|
51
58
|
if (setting === TASK_CATEGORIES || setting.startsWith(CATEGORY_PREFIX))
|
|
@@ -213,6 +220,30 @@ const changeGroup = async (app, env, setting, value) => {
|
|
|
213
220
|
await store.close();
|
|
214
221
|
}
|
|
215
222
|
};
|
|
223
|
+
const crmValueText = (value) => typeof value === "string"
|
|
224
|
+
? value
|
|
225
|
+
: Object.entries(value)
|
|
226
|
+
.map(([type, meaning]) => `${type}=${meaning}`)
|
|
227
|
+
.join(",");
|
|
228
|
+
const changeCrm = async (env, setting, value) => {
|
|
229
|
+
const { name } = parseCrmSetting(setting);
|
|
230
|
+
const parsed = value === undefined ? undefined : parseCrmSettingValue(name, value);
|
|
231
|
+
await (await openStore({ env })).close();
|
|
232
|
+
const database = await openCache(storePath(env));
|
|
233
|
+
try {
|
|
234
|
+
saveCrmSetting(database, setting, parsed, Date.now());
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
database.close();
|
|
238
|
+
}
|
|
239
|
+
const now = parsed ?? (name === "links" ? "reported" : {});
|
|
240
|
+
return {
|
|
241
|
+
result: { store: storePath(env), scope: "store", setting, value: crmValueText(now) },
|
|
242
|
+
note: name === "links"
|
|
243
|
+
? `store-wide — the next sync of that account writes what it reports as ${now === "review" ? "proposals for the owner to review" : "reported relationships"}; relationships already stored stay`
|
|
244
|
+
: "store-wide — a company of a mapped type becomes a customer, supplier or partner of the own company",
|
|
245
|
+
};
|
|
246
|
+
};
|
|
216
247
|
/** Each category as `config show` lists it, and where it comes from: the shared file, an older store's list, the default. */
|
|
217
248
|
const categoryRows = (saved, file) => {
|
|
218
249
|
let edits;
|
|
@@ -249,6 +280,7 @@ export const storeSettings = async (env) => {
|
|
|
249
280
|
let categories;
|
|
250
281
|
let agentClose = {};
|
|
251
282
|
let firstPass;
|
|
283
|
+
let crm = [];
|
|
252
284
|
if (existsSync(path)) {
|
|
253
285
|
try {
|
|
254
286
|
const database = await openCache(path);
|
|
@@ -261,6 +293,7 @@ export const storeSettings = async (env) => {
|
|
|
261
293
|
categories = table ? savedTaskCategories(database) : undefined;
|
|
262
294
|
agentClose = table ? savedAgentClose(database) : {};
|
|
263
295
|
firstPass = table ? savedFirstPassPerChat(database) : undefined;
|
|
296
|
+
crm = table ? crmSettingsOf(database) : [];
|
|
264
297
|
}
|
|
265
298
|
finally {
|
|
266
299
|
database.close();
|
|
@@ -316,6 +349,7 @@ export const storeSettings = async (env) => {
|
|
|
316
349
|
scope: "store",
|
|
317
350
|
},
|
|
318
351
|
]),
|
|
352
|
+
...crm.map(({ setting, value }) => ({ setting, value: crmValueText(value), from: "store", scope: "store" })),
|
|
319
353
|
...Object.entries(groups).map(([name, members]) => ({
|
|
320
354
|
setting: `${GROUP_PREFIX}${name}`,
|
|
321
355
|
value: members.join(","),
|
package/dist/crm/cli/index.js
CHANGED
|
@@ -56,6 +56,8 @@ const crmSync = v.strictObject({
|
|
|
56
56
|
provider: text,
|
|
57
57
|
account: text,
|
|
58
58
|
pipelines: count,
|
|
59
|
+
users: v.optional(count),
|
|
60
|
+
skipped_owner_rejected: count,
|
|
59
61
|
synced: v.array(v.strictObject({
|
|
60
62
|
kind: v.picklist(CRM_KINDS),
|
|
61
63
|
round: v.picklist(["full", "changes"]),
|
|
@@ -68,7 +70,7 @@ const crmSync = v.strictObject({
|
|
|
68
70
|
error: v.optional(text),
|
|
69
71
|
})),
|
|
70
72
|
issues: v.array(v.strictObject({
|
|
71
|
-
kind: v.picklist(CRM_KINDS),
|
|
73
|
+
kind: v.picklist([...CRM_KINDS, "user"]),
|
|
72
74
|
reason: text,
|
|
73
75
|
message: text,
|
|
74
76
|
external_id: v.optional(text),
|
package/dist/crm/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { CrmChanges, CrmIdPage, CrmPage, CrmSource, CrmSourceTraits } from "./source.js";
|
|
2
|
-
export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
|
|
1
|
+
export type { CrmCallContext, CrmChanges, CrmGap, CrmIdPage, CrmPage, CrmSource, CrmSourceTraits, } from "./source.js";
|
|
2
|
+
export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
|
|
3
3
|
export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
|
|
4
4
|
export { type CrmFieldsInput, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
|
package/dist/crm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
|
|
1
|
+
export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
|
|
2
2
|
export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
|
|
3
3
|
export { closeCrmItem, createCrmItem, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, } from "./writes.js";
|
package/dist/crm/source.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CrmField, CrmKind, CrmPipeline, CrmRecords } from "../domain/crm.js";
|
|
1
|
+
import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmUser } from "../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../domain/deals.js";
|
|
3
3
|
export interface CrmSourceTraits {
|
|
4
4
|
/** What this CRM has: one without leads leaves `lead` out. Contacts and companies come before the items on them. */
|
|
@@ -26,23 +26,53 @@ export interface CrmIdPage {
|
|
|
26
26
|
ids: string[];
|
|
27
27
|
nextPage?: string;
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* What a CRM account did not report in the last sync, so an answer can name it: a kind it has not, users or departments
|
|
31
|
+
* it does not list, a list the sign-in's scope refused (`code`, and the `scope` the adapter named), or a part a source
|
|
32
|
+
* said it could not read.
|
|
33
|
+
*/
|
|
34
|
+
export interface CrmGap {
|
|
35
|
+
kind: CrmKind | "users" | "departments";
|
|
36
|
+
reason: "not-listed" | "refused" | "partial";
|
|
37
|
+
code?: string;
|
|
38
|
+
scope?: string;
|
|
39
|
+
message: string;
|
|
40
|
+
}
|
|
41
|
+
/** What the engine hands every source call; a source that ignores it works as before. */
|
|
42
|
+
export interface CrmCallContext {
|
|
43
|
+
/**
|
|
44
|
+
* Takes one request from the run's budget, for each request beyond the one the engine takes before the call (a
|
|
45
|
+
* source that pages internally). Throws once the budget is spent: the run stops there as `partial`.
|
|
46
|
+
*/
|
|
47
|
+
spend(): void;
|
|
48
|
+
/** Says what the call could not read without failing it, such as e-mails a missing scope hides. */
|
|
49
|
+
gap(gap: {
|
|
50
|
+
kind: CrmGap["kind"];
|
|
51
|
+
message: string;
|
|
52
|
+
scope?: string;
|
|
53
|
+
}): void;
|
|
54
|
+
}
|
|
29
55
|
/** One CRM account, as an adapter reads it. The engine never sees a provider word. */
|
|
30
56
|
export interface CrmSource {
|
|
31
57
|
/** The registry name: `bitrix24`, `pipedrive`, `hubspot`, `amocrm`. */
|
|
32
58
|
readonly provider: string;
|
|
33
59
|
readonly traits: CrmSourceTraits;
|
|
34
60
|
/** One kind's pipelines with their stages; a CRM whose leads have no pipelines answers one of its own making. */
|
|
35
|
-
pipelines(kind: DealKind): Promise<CrmPipeline[]>;
|
|
61
|
+
pipelines(kind: DealKind, context?: CrmCallContext): Promise<CrmPipeline[]>;
|
|
36
62
|
/**
|
|
37
63
|
* What changed since `cursor`, a page at a time; `cursor: null` lists everything. A CRM without a change feed
|
|
38
64
|
* reads by its own modified time, with an overlap, and gives that time back as the cursor.
|
|
39
65
|
*/
|
|
40
|
-
changes<K extends CrmKind>(kind: K, cursor: string | null, page?: string): Promise<CrmChanges<CrmRecords[K]>>;
|
|
66
|
+
changes<K extends CrmKind>(kind: K, cursor: string | null, page?: string, context?: CrmCallContext): Promise<CrmChanges<CrmRecords[K]>>;
|
|
41
67
|
/**
|
|
42
68
|
* The CRM's own fields on one kind, in its order: what the codes in a row's `metadata` mean. Read every sync; a CRM
|
|
43
69
|
* without custom fields leaves it out, and one that has none on a kind answers `[]`.
|
|
44
70
|
*/
|
|
45
|
-
fields?(kind: CrmKind): Promise<CrmField[]>;
|
|
71
|
+
fields?(kind: CrmKind, context?: CrmCallContext): Promise<CrmField[]>;
|
|
46
72
|
/** Every id the CRM holds of the kind, a page at a time: how deletions are found when `removedInChanges` is false. */
|
|
47
|
-
ids?(kind: CrmKind, page?: string): Promise<CrmIdPage>;
|
|
73
|
+
ids?(kind: CrmKind, page?: string, context?: CrmCallContext): Promise<CrmIdPage>;
|
|
74
|
+
/** Every user of the account, active or not; a CRM that cannot list them leaves it out, and its users stay. */
|
|
75
|
+
users?(context?: CrmCallContext): Promise<CrmUser[]>;
|
|
76
|
+
/** Every department; left out, reporting lines are unknown and none stored is withdrawn. */
|
|
77
|
+
departments?(context?: CrmCallContext): Promise<CrmDepartment[]>;
|
|
48
78
|
}
|
package/dist/crm/sync.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { type BudgetStop, type RunBudget } from "../background/budget.js";
|
|
2
2
|
import { type CrmKind } from "../domain/crm.js";
|
|
3
|
-
import type { CrmSkipped } from "../store/sqlite/crm.js";
|
|
3
|
+
import type { CrmRelationIssue, CrmSkipped } from "../store/sqlite/crm.js";
|
|
4
4
|
import type { MessageStore } from "../store/store.js";
|
|
5
5
|
import type { AccountKey } from "../store/types.js";
|
|
6
|
-
import type { CrmSource } from "./source.js";
|
|
6
|
+
import type { CrmGap, CrmSource } from "./source.js";
|
|
7
7
|
/** A round of changes that stopped before its last page: the next run goes on from its page with the same cursor. */
|
|
8
8
|
interface PendingRound {
|
|
9
9
|
from: string | null;
|
|
@@ -44,8 +44,9 @@ export interface CrmSyncOptions {
|
|
|
44
44
|
}
|
|
45
45
|
/** Something a run could not do that the owner should know: an item not kept, or a deletion held back. */
|
|
46
46
|
export interface CrmSyncIssue {
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
/** `user`: the account's users and departments. */
|
|
48
|
+
kind: CrmKind | "user";
|
|
49
|
+
reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.not-reported" | "crm.pending-dropped";
|
|
49
50
|
message: string;
|
|
50
51
|
externalId?: string;
|
|
51
52
|
}
|
|
@@ -71,6 +72,10 @@ export interface CrmSyncReport {
|
|
|
71
72
|
account: string;
|
|
72
73
|
/** Pipelines read this run, both kinds. */
|
|
73
74
|
pipelines: number;
|
|
75
|
+
/** Users read this run; absent when the CRM cannot list them. */
|
|
76
|
+
users?: number;
|
|
77
|
+
/** Relationships left out because the owner removed or rejected that very one, role included. */
|
|
78
|
+
skippedOwnerRejected: number;
|
|
74
79
|
synced: CrmSyncResult[];
|
|
75
80
|
issues: CrmSyncIssue[];
|
|
76
81
|
/** Every kind finished its round and none failed. */
|
|
@@ -86,10 +91,13 @@ export interface CrmSyncReport {
|
|
|
86
91
|
};
|
|
87
92
|
hint?: string;
|
|
88
93
|
}
|
|
94
|
+
/** The gaps the account's last sync recorded; none before its first. */
|
|
95
|
+
export declare const crmGapsOf: (store: MessageStore, account: AccountKey) => Promise<CrmGap[]>;
|
|
89
96
|
/**
|
|
90
|
-
* Brings one CRM account's copy up to date: both kinds' pipelines and each kind's fields, then
|
|
91
|
-
* deals and leads, each from its cursor or listed in full, a page at a time,
|
|
92
|
-
* the cursor, so a run the budget stops, or one that fails, goes on from
|
|
97
|
+
* Brings one CRM account's copy up to date: both kinds' pipelines and each kind's fields, then companies, contacts,
|
|
98
|
+
* the account's users and departments, deals and leads, each from its cursor or listed in full, a page at a time,
|
|
99
|
+
* each page saved with the round's place in the cursor, so a run the budget stops, or one that fails, goes on from
|
|
100
|
+
* there. Relationships held back for an end not stored yet are written at the end of the run. Deletions come from `changes()`, or
|
|
93
101
|
* from a list of every id that marks only after its last page arrived, and never more than half of a kind without
|
|
94
102
|
* `--rescan`.
|
|
95
103
|
*/
|
package/dist/crm/sync.js
CHANGED
|
@@ -46,22 +46,128 @@ export const parseCrmCursor = (value) => {
|
|
|
46
46
|
export const cursorName = (kind) => `crm:${kind}`;
|
|
47
47
|
const CONTINUE = "run sync again to continue";
|
|
48
48
|
const fresh = () => ({ v: 1, token: null, round: null, done: 0, updatedAt: null, pass: null, passAt: 0 });
|
|
49
|
+
const GAPS = "crm:gaps";
|
|
50
|
+
/** The gaps the account's last sync recorded; none before its first. */
|
|
51
|
+
export const crmGapsOf = async (store, account) => {
|
|
52
|
+
try {
|
|
53
|
+
const value = JSON.parse((await store.sync.syncState(account, GAPS))?.value ?? "[]");
|
|
54
|
+
return Array.isArray(value) ? value : [];
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
/** Thrown by `CrmCallContext.spend` when the budget is spent; the engine turns it into a `partial` stop. */
|
|
61
|
+
class BudgetSpent extends Error {
|
|
62
|
+
why;
|
|
63
|
+
constructor(why) {
|
|
64
|
+
super(`the run's budget is spent: ${why}`);
|
|
65
|
+
this.why = why;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** The scope a refusal names, when the adapter put one in its details. */
|
|
69
|
+
const scopeOf = (error) => {
|
|
70
|
+
const scope = error instanceof CliError ? error.details?.scope : undefined;
|
|
71
|
+
return typeof scope === "string" && scope ? scope : undefined;
|
|
72
|
+
};
|
|
73
|
+
const refusal = (kind, consequence, error, provider) => {
|
|
74
|
+
// The adapter's own text may carry a request; only its failure code and scope are copied.
|
|
75
|
+
const code = error instanceof CliError ? error.code : "error";
|
|
76
|
+
const scope = scopeOf(error);
|
|
77
|
+
const message = scope
|
|
78
|
+
? `${scope} scope missing: ${consequence}`
|
|
79
|
+
: `${provider} did not list ${kind} (${code}): ${consequence}`;
|
|
80
|
+
return { kind, reason: "refused", code, ...(scope ? { scope } : {}), message };
|
|
81
|
+
};
|
|
49
82
|
const readPipelines = async (run, kind) => {
|
|
50
83
|
const why = run.budget.take();
|
|
51
84
|
if (why)
|
|
52
85
|
return why;
|
|
53
|
-
const pipelines = await run.source.pipelines(kind);
|
|
86
|
+
const pipelines = await run.source.pipelines(kind, run.context);
|
|
54
87
|
const { saved, skipped } = await run.store.crm.savePipelines(run.account, kind, pipelines);
|
|
55
88
|
run.report.pipelines += saved;
|
|
56
89
|
for (const one of skipped)
|
|
57
90
|
run.report.issues.push({ kind, ...one });
|
|
58
91
|
return null;
|
|
59
92
|
};
|
|
93
|
+
const noted = (run, kind, saved) => {
|
|
94
|
+
for (const { externalId, ...one } of saved.issues ?? [])
|
|
95
|
+
run.report.issues.push({ kind, ...one, ...(externalId ? { externalId } : {}) });
|
|
96
|
+
run.report.skippedOwnerRejected += saved.skippedOwnerRejected ?? 0;
|
|
97
|
+
run.unlistedUsers += saved.unlistedUsers ?? 0;
|
|
98
|
+
run.droppedPending += saved.droppedPending ?? 0;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* The account's users and departments, listed whole each run: before deals, so a deal's owner is a person. A CRM that
|
|
102
|
+
* cannot list departments says so, and no reporting line is touched.
|
|
103
|
+
*/
|
|
104
|
+
const readUsers = async (run) => {
|
|
105
|
+
const { source } = run;
|
|
106
|
+
const gap = (one) => {
|
|
107
|
+
run.gaps.push(one);
|
|
108
|
+
run.report.issues.push({ kind: "user", reason: "crm.not-reported", message: one.message });
|
|
109
|
+
};
|
|
110
|
+
if (!source.users) {
|
|
111
|
+
run.gaps.push({
|
|
112
|
+
kind: "users",
|
|
113
|
+
reason: "not-listed",
|
|
114
|
+
message: `${source.provider} lists no users: deal owners, employees and reporting lines are unknown`,
|
|
115
|
+
});
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const why = run.budget.take();
|
|
119
|
+
if (why)
|
|
120
|
+
return why;
|
|
121
|
+
let users;
|
|
122
|
+
try {
|
|
123
|
+
users = await source.users(run.context);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
if (run.signal?.aborted || error instanceof BudgetSpent)
|
|
127
|
+
throw error;
|
|
128
|
+
gap(refusal("users", "nothing stored about them changed", error, source.provider));
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
let departments;
|
|
132
|
+
if (!source.departments)
|
|
133
|
+
gap({
|
|
134
|
+
kind: "departments",
|
|
135
|
+
reason: "not-listed",
|
|
136
|
+
message: `${source.provider} lists no departments: who reports to whom is unknown`,
|
|
137
|
+
});
|
|
138
|
+
else {
|
|
139
|
+
const stop = run.budget.take();
|
|
140
|
+
if (stop)
|
|
141
|
+
return stop;
|
|
142
|
+
try {
|
|
143
|
+
departments = await source.departments(run.context);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
if (run.signal?.aborted || error instanceof BudgetSpent)
|
|
147
|
+
throw error;
|
|
148
|
+
gap(refusal("departments", "reporting lines unknown", error, source.provider));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
noted(run, "user", await run.store.crm.saveUsers(run.account, users, departments));
|
|
152
|
+
run.report.users = users.length;
|
|
153
|
+
return null;
|
|
154
|
+
};
|
|
155
|
+
/** Runs a step whose source call may spend the budget mid-way: a spent budget is a stop, not a failure. */
|
|
156
|
+
const stopping = async (step) => {
|
|
157
|
+
try {
|
|
158
|
+
return await step();
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (error instanceof BudgetSpent)
|
|
162
|
+
return error.why;
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
60
166
|
const readFields = async (run, kind) => {
|
|
61
167
|
const why = run.budget.take();
|
|
62
168
|
if (why)
|
|
63
169
|
return why;
|
|
64
|
-
const fields = await run.source.fields.call(run.source, kind);
|
|
170
|
+
const fields = await run.source.fields.call(run.source, kind, run.context);
|
|
65
171
|
const { skipped } = await run.store.crm.saveFields(run.account, kind, fields);
|
|
66
172
|
for (const one of skipped)
|
|
67
173
|
run.report.issues.push({ kind, ...one });
|
|
@@ -74,17 +180,22 @@ const savePage = async (run, kind, page) => {
|
|
|
74
180
|
const saved = kind === "person"
|
|
75
181
|
? await store.crm.savePeople(account, page.items)
|
|
76
182
|
: await store.crm.saveOrganizations(account, page.items);
|
|
183
|
+
noted(run, kind, saved);
|
|
77
184
|
return { saved: saved.saved, stop: null };
|
|
78
185
|
}
|
|
79
186
|
const items = page.items;
|
|
80
|
-
|
|
187
|
+
const users = { users: run.source.users !== undefined };
|
|
188
|
+
const first = await store.crm.saveItems(account, kind, items, users);
|
|
189
|
+
noted(run, kind, first);
|
|
190
|
+
let { saved, skipped } = first;
|
|
81
191
|
let stop = null;
|
|
82
192
|
if (skipped.some(({ reason }) => reason === "crm.stage-unknown") && !run.pipelinesReread.has(kind)) {
|
|
83
193
|
run.pipelinesReread.add(kind);
|
|
84
194
|
stop = await readPipelines(run, kind);
|
|
85
195
|
if (!stop) {
|
|
86
196
|
const again = new Set(skipped.filter(({ reason }) => reason === "crm.stage-unknown").map(({ externalId }) => externalId));
|
|
87
|
-
const retried = await store.crm.saveItems(account, kind, items.filter(({ externalId }) => again.has(externalId)));
|
|
197
|
+
const retried = await store.crm.saveItems(account, kind, items.filter(({ externalId }) => again.has(externalId)), users);
|
|
198
|
+
noted(run, kind, retried);
|
|
88
199
|
saved += retried.saved;
|
|
89
200
|
skipped = [...skipped.filter(({ reason }) => reason !== "crm.stage-unknown"), ...retried.skipped];
|
|
90
201
|
}
|
|
@@ -116,7 +227,7 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
116
227
|
const why = budget.take();
|
|
117
228
|
if (why)
|
|
118
229
|
return why;
|
|
119
|
-
const page = await source.changes(kind, round.from, round.page ?? undefined);
|
|
230
|
+
const page = await source.changes(kind, round.from, round.page ?? undefined, run.context);
|
|
120
231
|
if (signal?.aborted)
|
|
121
232
|
return "cancelled";
|
|
122
233
|
if ("reset" in page) {
|
|
@@ -164,7 +275,7 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
164
275
|
await save({ pass });
|
|
165
276
|
return why;
|
|
166
277
|
}
|
|
167
|
-
const page = await ids.call(source, kind, pass.page ?? undefined);
|
|
278
|
+
const page = await ids.call(source, kind, pass.page ?? undefined, run.context);
|
|
168
279
|
if (signal?.aborted)
|
|
169
280
|
return "cancelled";
|
|
170
281
|
pass = { ...pass, seen: [...pass.seen, ...page.ids], page: page.nextPage ?? null };
|
|
@@ -195,9 +306,10 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
195
306
|
return null;
|
|
196
307
|
};
|
|
197
308
|
/**
|
|
198
|
-
* Brings one CRM account's copy up to date: both kinds' pipelines and each kind's fields, then
|
|
199
|
-
* deals and leads, each from its cursor or listed in full, a page at a time,
|
|
200
|
-
* the cursor, so a run the budget stops, or one that fails, goes on from
|
|
309
|
+
* Brings one CRM account's copy up to date: both kinds' pipelines and each kind's fields, then companies, contacts,
|
|
310
|
+
* the account's users and departments, deals and leads, each from its cursor or listed in full, a page at a time,
|
|
311
|
+
* each page saved with the round's place in the cursor, so a run the budget stops, or one that fails, goes on from
|
|
312
|
+
* there. Relationships held back for an end not stored yet are written at the end of the run. Deletions come from `changes()`, or
|
|
201
313
|
* from a list of every id that marks only after its last page arrived, and never more than half of a kind without
|
|
202
314
|
* `--rescan`.
|
|
203
315
|
*/
|
|
@@ -208,6 +320,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
208
320
|
provider: source.provider,
|
|
209
321
|
account: account.account,
|
|
210
322
|
pipelines: 0,
|
|
323
|
+
skippedOwnerRejected: 0,
|
|
211
324
|
synced: [],
|
|
212
325
|
issues: [],
|
|
213
326
|
complete: true,
|
|
@@ -227,23 +340,44 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
227
340
|
moved: () => {
|
|
228
341
|
steps += 1;
|
|
229
342
|
},
|
|
343
|
+
gaps: CRM_KINDS.filter((kind) => !source.traits.kinds.includes(kind)).map((kind) => ({
|
|
344
|
+
kind,
|
|
345
|
+
reason: "not-listed",
|
|
346
|
+
message: `${source.provider} has no ${kind}s`,
|
|
347
|
+
})),
|
|
348
|
+
context: {
|
|
349
|
+
spend: () => {
|
|
350
|
+
const why = budget.take();
|
|
351
|
+
if (why)
|
|
352
|
+
throw new BudgetSpent(why);
|
|
353
|
+
},
|
|
354
|
+
gap: ({ kind, message, scope }) => run.gaps.push({ kind, reason: "partial", message, ...(scope ? { scope } : {}) }),
|
|
355
|
+
},
|
|
356
|
+
unlistedUsers: 0,
|
|
357
|
+
droppedPending: 0,
|
|
230
358
|
};
|
|
231
359
|
const kinds = CRM_KINDS.filter((kind) => source.traits.kinds.includes(kind));
|
|
232
360
|
let stopped = null;
|
|
233
361
|
for (const kind of DEAL_KINDS)
|
|
234
362
|
if (!stopped && kinds.includes(kind)) {
|
|
235
|
-
stopped = await readPipelines(run, kind);
|
|
363
|
+
stopped = await stopping(() => readPipelines(run, kind));
|
|
236
364
|
if (options.signal?.aborted)
|
|
237
365
|
stopped = "cancelled";
|
|
238
366
|
}
|
|
239
367
|
if (run.source.fields)
|
|
240
368
|
for (const kind of kinds)
|
|
241
369
|
if (!stopped) {
|
|
242
|
-
stopped = await readFields(run, kind);
|
|
370
|
+
stopped = await stopping(() => readFields(run, kind));
|
|
243
371
|
if (options.signal?.aborted)
|
|
244
372
|
stopped = "cancelled";
|
|
245
373
|
}
|
|
374
|
+
let usersRead = false;
|
|
246
375
|
for (const kind of kinds) {
|
|
376
|
+
if (!usersRead && isItemKind(kind)) {
|
|
377
|
+
usersRead = true;
|
|
378
|
+
if (!stopped)
|
|
379
|
+
stopped = await stopping(() => readUsers(run));
|
|
380
|
+
}
|
|
247
381
|
const result = {
|
|
248
382
|
kind,
|
|
249
383
|
round: "changes",
|
|
@@ -258,16 +392,40 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
258
392
|
continue;
|
|
259
393
|
try {
|
|
260
394
|
stopped = await syncKind(run, kind, options, result);
|
|
395
|
+
// After every company of the run is stored, so one listed before the own company still gets its meaning.
|
|
396
|
+
if (kind === "organization")
|
|
397
|
+
noted(run, kind, await store.crm.saveCompanyTypes(account));
|
|
261
398
|
}
|
|
262
399
|
catch (error) {
|
|
263
400
|
if (options.signal?.aborted) {
|
|
264
401
|
stopped = "cancelled";
|
|
265
402
|
continue;
|
|
266
403
|
}
|
|
404
|
+
if (error instanceof BudgetSpent) {
|
|
405
|
+
stopped = error.why;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (scopeOf(error))
|
|
409
|
+
run.gaps.push(refusal(kind, `no ${kind} was read`, error, source.provider));
|
|
267
410
|
// An adapter's own failure says what went wrong; anything else may carry a request URL with a secret in it.
|
|
268
411
|
result.error = isCliFailure(error) ? error.message : `the ${kind} copy could not be synced`;
|
|
269
412
|
}
|
|
270
413
|
}
|
|
414
|
+
// A relationship held back for an end a later page or kind brought is written now; it costs no request.
|
|
415
|
+
run.droppedPending += (await store.crm.retryPending(account)).dropped;
|
|
416
|
+
if (run.unlistedUsers)
|
|
417
|
+
report.issues.push({
|
|
418
|
+
kind: "deal",
|
|
419
|
+
reason: "crm.not-reported",
|
|
420
|
+
message: `${run.unlistedUsers} deal owner(s) are ${source.provider} users this CRM does not list; no owner was stored for them`,
|
|
421
|
+
});
|
|
422
|
+
if (run.droppedPending)
|
|
423
|
+
report.issues.push({
|
|
424
|
+
kind: "deal",
|
|
425
|
+
reason: "crm.pending-dropped",
|
|
426
|
+
message: `${run.droppedPending} relationship(s) waited too long for a contact, user or company that never came and were dropped`,
|
|
427
|
+
});
|
|
428
|
+
await store.sync.setSyncState(account, GAPS, JSON.stringify(run.gaps));
|
|
271
429
|
report.progress = {
|
|
272
430
|
requests: budget.used,
|
|
273
431
|
saved: report.synced.reduce((sum, one) => sum + one.saved, 0),
|