@wirecat/cli-core 0.604.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +2 -2
  5. package/dist/cli/index.js +2 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/cli/store-settings.js +38 -4
  15. package/dist/crm/cli/index.js +3 -1
  16. package/dist/crm/index.d.ts +2 -2
  17. package/dist/crm/index.js +1 -1
  18. package/dist/crm/source.d.ts +35 -5
  19. package/dist/crm/sync.d.ts +15 -7
  20. package/dist/crm/sync.js +169 -11
  21. package/dist/domain/crm.d.ts +41 -2
  22. package/dist/domain/deals.d.ts +5 -2
  23. package/dist/domain/deals.js +5 -2
  24. package/dist/domain/record-types.d.ts +61 -0
  25. package/dist/domain/record-types.js +26 -0
  26. package/dist/domain/records.d.ts +3 -5
  27. package/dist/domain/records.js +10 -13
  28. package/dist/domain/relations.d.ts +125 -0
  29. package/dist/domain/relations.js +107 -0
  30. package/dist/entities/contact-activity.d.ts +4 -0
  31. package/dist/entities/contact-activity.js +1 -0
  32. package/dist/entities/contact-context.d.ts +20 -0
  33. package/dist/entities/contact-context.js +2 -0
  34. package/dist/entities/deal.d.ts +2 -2
  35. package/dist/entities/deal.js +2 -1
  36. package/dist/entities/index.d.ts +39 -13
  37. package/dist/entities/relationship.d.ts +8 -2
  38. package/dist/entities/relationship.js +8 -2
  39. package/dist/entities/task-results.d.ts +10 -10
  40. package/dist/errors/failures.d.ts +17 -1
  41. package/dist/errors/failures.js +57 -1
  42. package/dist/errors/reasons.js +28 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -0
  45. package/dist/mail/cli/review.js +20 -6
  46. package/dist/mail/index.d.ts +1 -1
  47. package/dist/mail/marks.d.ts +10 -5
  48. package/dist/mail/marks.js +16 -8
  49. package/dist/mail/review.d.ts +5 -0
  50. package/dist/mcp/tool.js +2 -1
  51. package/dist/runs/recording.js +13 -4
  52. package/dist/services/deps.js +4 -6
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  55. package/dist/services/link-scorers/chat-senders.js +7 -4
  56. package/dist/services/link-scorers/mail-thread.js +1 -0
  57. package/dist/services/link-scorers/member-chats.js +1 -0
  58. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  59. package/dist/services/link-scorers/member-dialog.js +4 -3
  60. package/dist/services/link-scorers/scan.d.ts +5 -2
  61. package/dist/services/link-scorers/scan.js +100 -54
  62. package/dist/services/link-scorers/shared.d.ts +2 -2
  63. package/dist/services/link-scorers/shared.js +8 -4
  64. package/dist/services/link-scorers/types.d.ts +3 -0
  65. package/dist/services/metadata.d.ts +1 -1
  66. package/dist/services/person-context.d.ts +24 -7
  67. package/dist/services/person-context.js +45 -11
  68. package/dist/services/person-preparation.js +4 -5
  69. package/dist/services/project-status/index.js +2 -1
  70. package/dist/services/stored-project-gathering.js +4 -3
  71. package/dist/store/damage.d.ts +3 -1
  72. package/dist/store/damage.js +19 -12
  73. package/dist/store/document-transfer/index.js +7 -0
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/index.d.ts +7 -1
  77. package/dist/store/index.js +2 -0
  78. package/dist/store/marks.d.ts +57 -0
  79. package/dist/store/marks.js +121 -0
  80. package/dist/store/project-transfer/preview.js +12 -7
  81. package/dist/store/project-transfer/request.d.ts +4 -1
  82. package/dist/store/project-transfer/schema.d.ts +9 -2
  83. package/dist/store/project-transfer/schema.js +4 -0
  84. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  85. package/dist/store/recover.js +16 -1
  86. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  87. package/dist/store/sqlite/crm-settings.js +80 -0
  88. package/dist/store/sqlite/crm.d.ts +42 -2
  89. package/dist/store/sqlite/crm.js +397 -36
  90. package/dist/store/sqlite/deals.js +3 -2
  91. package/dist/store/sqlite/finance.d.ts +8 -1
  92. package/dist/store/sqlite/finance.js +10 -3
  93. package/dist/store/sqlite/involvement-queue.js +4 -3
  94. package/dist/store/sqlite/knowledge.d.ts +7 -3
  95. package/dist/store/sqlite/knowledge.js +43 -31
  96. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  97. package/dist/store/sqlite/link-kinds.js +4 -2
  98. package/dist/store/sqlite/manifest.js +5 -0
  99. package/dist/store/sqlite/memories.d.ts +1 -1
  100. package/dist/store/sqlite/memories.js +33 -7
  101. package/dist/store/sqlite/migrations.generated.js +31 -0
  102. package/dist/store/sqlite/notes.d.ts +3 -2
  103. package/dist/store/sqlite/notes.js +23 -6
  104. package/dist/store/sqlite/open-store.js +4 -1
  105. package/dist/store/sqlite/organizations.d.ts +8 -0
  106. package/dist/store/sqlite/organizations.js +14 -0
  107. package/dist/store/sqlite/own-identities.d.ts +1 -1
  108. package/dist/store/sqlite/own-identities.js +7 -5
  109. package/dist/store/sqlite/person-links.d.ts +5 -2
  110. package/dist/store/sqlite/person-links.js +24 -18
  111. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  112. package/dist/store/sqlite/person-preparation.js +3 -2
  113. package/dist/store/sqlite/person-separation.d.ts +5 -0
  114. package/dist/store/sqlite/person-separation.js +26 -0
  115. package/dist/store/sqlite/project-transfer/records.js +14 -3
  116. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  117. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  118. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  119. package/dist/store/sqlite/record-projectors.js +72 -0
  120. package/dist/store/sqlite/records.js +12 -70
  121. package/dist/store/sqlite/relation-list.d.ts +43 -0
  122. package/dist/store/sqlite/relation-list.js +133 -0
  123. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  124. package/dist/store/sqlite/relation-proposals.js +134 -10
  125. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  126. package/dist/store/sqlite/relation-reads.js +7 -0
  127. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  128. package/dist/store/sqlite/relation-roles.js +91 -0
  129. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  130. package/dist/store/sqlite/reported-relations.js +132 -0
  131. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  132. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  133. package/dist/store/sqlite/schema/links.d.ts +360 -0
  134. package/dist/store/sqlite/schema/links.js +32 -0
  135. package/dist/store/sqlite/schema.d.ts +2 -296
  136. package/dist/store/sqlite/schema.js +2 -24
  137. package/dist/store/sqlite/transaction.js +2 -5
  138. package/dist/store/store.d.ts +3 -0
  139. package/dist/store/store.js +5 -0
  140. package/dist/store/types.d.ts +5 -0
  141. package/package.json +5 -5
@@ -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 ? Object.keys(SCRIPTS) : [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`];
37
- export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS;
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(","),
@@ -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),
@@ -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";
@@ -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
  }
@@ -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
- kind: CrmKind;
48
- reason: CrmSkipped["reason"] | "crm.unlisted-held";
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 contacts, companies,
91
- * deals and leads, each from its cursor or listed in full, a page at a time, each page saved with the round's place in
92
- * the cursor, so a run the budget stops, or one that fails, goes on from there. Deletions come from `changes()`, or
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
- let { saved, skipped } = await store.crm.saveItems(account, kind, items);
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 contacts, companies,
199
- * deals and leads, each from its cursor or listed in full, a page at a time, each page saved with the round's place in
200
- * the cursor, so a run the budget stops, or one that fails, goes on from there. Deletions come from `changes()`, or
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),
@@ -40,10 +40,14 @@ export interface CrmItem {
40
40
  closedReason?: string | null;
41
41
  /** A company's id. */
42
42
  organization?: string | null;
43
- /** Contacts on it, by their id, and the part each plays. */
43
+ /**
44
+ * Contacts on it, by their id, the part each plays and whether the CRM marks one its main contact. Left out, the CRM
45
+ * did not say who is on it, and the people stored stay.
46
+ */
44
47
  people?: {
45
48
  externalId: string;
46
49
  role: DealRole;
50
+ primary?: boolean;
47
51
  }[];
48
52
  /** A lead's: the deal it became. */
49
53
  deal?: string | null;
@@ -52,7 +56,7 @@ export interface CrmItem {
52
56
  updatedAt?: number | null;
53
57
  /** The CRM's own page for it, http or https. */
54
58
  url?: string | null;
55
- /** The CRM user it is assigned to, by the user's id: never a contact's. */
59
+ /** The CRM user it is assigned to, by the user's id: never a contact's. It makes that user's person its `owner`. */
56
60
  assignee?: string | null;
57
61
  /**
58
62
  * What the CRM sends that has no column; never a secret. Its own fields' values are here by code as `CrmValue`,
@@ -75,14 +79,49 @@ export interface CrmPerson {
75
79
  name: string | null;
76
80
  email?: string | null;
77
81
  phone?: string | null;
82
+ /** The job title as the CRM writes it: kept beside the relationship, never a role. */
83
+ position?: string | null;
84
+ /**
85
+ * The companies the contact represents, by their id; each becomes `member-of` with role `contact`. Left out, the CRM
86
+ * did not say, and the relationships stored stay.
87
+ */
88
+ organizations?: {
89
+ externalId: string;
90
+ primary?: boolean;
91
+ sourceRole?: string | null;
92
+ }[];
78
93
  }
79
94
  /** A CRM company: it becomes an organization of its own, never one matched by name. */
80
95
  export interface CrmOrganization {
81
96
  externalId: string;
82
97
  name: string;
83
98
  url?: string | null;
99
+ /** One of the account's own companies, the owner's side of every deal, not a client. */
100
+ own?: boolean;
101
+ /** The CRM's company type code; `crm.<provider>:<account>.company-types` says what one means, nothing by default. */
102
+ type?: string | null;
84
103
  metadata?: Record<string, unknown>;
85
104
  }
105
+ /**
106
+ * A CRM user: someone of the owner's own company, such as a deal's owner. It becomes an identity of the CRM's provider,
107
+ * `<account>/user/<id>`, joined to a person by exact email only, and `member-of` the own company as an `employee`
108
+ * while it is active.
109
+ */
110
+ export interface CrmUser {
111
+ externalId: string;
112
+ name: string | null;
113
+ email?: string | null;
114
+ position?: string | null;
115
+ departments?: string[];
116
+ active?: boolean;
117
+ }
118
+ /** A department of the own company: a user reports to its head, a head to the head of the parent. */
119
+ export interface CrmDepartment {
120
+ externalId: string;
121
+ name: string;
122
+ parent?: string | null;
123
+ head?: string | null;
124
+ }
86
125
  /** One of a CRM account's own fields on a kind: what the code a row's `metadata` is keyed by means. */
87
126
  export interface CrmField {
88
127
  /** The CRM's key for it, unique in its kind. */
@@ -4,8 +4,11 @@ export declare const DEAL_KINDS: readonly ["deal", "lead"];
4
4
  export declare const DEAL_STATUSES: readonly ["open", "won", "lost"];
5
5
  /** What reaching a stage means, as a CRM marks it: still open, or won or lost. */
6
6
  export declare const STAGE_OUTCOMES: readonly ["open", "won", "lost"];
7
- /** The part a person plays on a deal: the owner's side runs it, the client's side talks or decides. */
8
- export declare const DEAL_ROLES: readonly ["owner", "contact", "decision-maker"];
7
+ /**
8
+ * The part a person plays on a deal: the owner's side runs it (`owner`, the CRM's "responsible"), the client's side
9
+ * talks, decides or sways the decision.
10
+ */
11
+ export declare const DEAL_ROLES: readonly ["owner", "contact", "decision-maker", "influencer"];
9
12
  export type DealKind = (typeof DEAL_KINDS)[number];
10
13
  export type DealStatus = (typeof DEAL_STATUSES)[number];
11
14
  export type StageOutcome = DealStatus;
@@ -5,8 +5,11 @@ export const DEAL_KINDS = ["deal", "lead"];
5
5
  export const DEAL_STATUSES = ["open", "won", "lost"];
6
6
  /** What reaching a stage means, as a CRM marks it: still open, or won or lost. */
7
7
  export const STAGE_OUTCOMES = DEAL_STATUSES;
8
- /** The part a person plays on a deal: the owner's side runs it, the client's side talks or decides. */
9
- export const DEAL_ROLES = ["owner", "contact", "decision-maker"];
8
+ /**
9
+ * The part a person plays on a deal: the owner's side runs it (`owner`, the CRM's "responsible"), the client's side
10
+ * talks, decides or sways the decision.
11
+ */
12
+ export const DEAL_ROLES = ["owner", "contact", "decision-maker", "influencer"];
10
13
  /** "Site redesign · Proposal, 500 000.00 RUB (won)": a ref summary's title, which `refLabel` prefixes. */
11
14
  export const dealLine = (deal) => {
12
15
  const money = deal.amount === null || deal.currency === null ? "" : `, ${moneyLabel(deal.amount, deal.currency)}`;