@wirecat/cli-core 0.618.0 → 0.619.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 (274) hide show
  1. package/CHANGELOG.md +339 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/daily-archive-timer.d.ts +1 -1
  5. package/dist/background/deliver.d.ts +5 -2
  6. package/dist/background/deliver.js +30 -12
  7. package/dist/background/report/render.d.ts +3 -1
  8. package/dist/background/report/render.js +3 -1
  9. package/dist/calendar/cli/answers.d.ts +1 -0
  10. package/dist/calendar/cli/answers.js +6 -1
  11. package/dist/calendar/cli/index.js +2 -14
  12. package/dist/calendar/cli/people-link.d.ts +3 -0
  13. package/dist/calendar/cli/people-link.js +23 -0
  14. package/dist/calendar/index.d.ts +1 -1
  15. package/dist/calendar/index.js +1 -1
  16. package/dist/calendar/mcp/index.d.ts +12 -12
  17. package/dist/cli/base-stages-command.d.ts +22 -0
  18. package/dist/cli/base-stages-command.js +174 -0
  19. package/dist/cli/command-runs.d.ts +2 -0
  20. package/dist/cli/command-runs.js +3 -1
  21. package/dist/cli/config-command.js +6 -1
  22. package/dist/cli/context.js +1 -0
  23. package/dist/cli/group-lock.d.ts +42 -0
  24. package/dist/cli/group-lock.js +130 -0
  25. package/dist/cli/index.d.ts +7 -2
  26. package/dist/cli/index.js +7 -2
  27. package/dist/cli/messenger/backfill-command.js +27 -15
  28. package/dist/cli/messenger/contacts-command.js +10 -3
  29. package/dist/cli/messenger/context.js +1 -0
  30. package/dist/cli/messenger/doctor-command.js +3 -1
  31. package/dist/cli/messenger/models-command.js +1 -1
  32. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  33. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  34. package/dist/cli/model-catalogue-command.d.ts +3 -1
  35. package/dist/cli/model-catalogue-command.js +46 -2
  36. package/dist/cli/profile.d.ts +8 -0
  37. package/dist/cli/profile.js +25 -0
  38. package/dist/cli/program.js +2 -0
  39. package/dist/cli/runs/search-query.d.ts +1 -1
  40. package/dist/cli/runs/search-query.js +4 -0
  41. package/dist/cli/runs/search.d.ts +5 -1
  42. package/dist/cli/runs/search.js +12 -1
  43. package/dist/cli/search-left-out.d.ts +6 -1
  44. package/dist/cli/search-left-out.js +9 -4
  45. package/dist/cli/settings.d.ts +8 -0
  46. package/dist/cli/settings.js +17 -2
  47. package/dist/cli/shared-command-exports.d.ts +16 -0
  48. package/dist/cli/store-recover.d.ts +3 -3
  49. package/dist/cli/store-recover.js +26 -26
  50. package/dist/cli/store-settings.d.ts +2 -0
  51. package/dist/cli/store-settings.js +37 -9
  52. package/dist/crm/cli/index.js +38 -6
  53. package/dist/crm/group-hint.d.ts +8 -0
  54. package/dist/crm/group-hint.js +13 -0
  55. package/dist/crm/source.d.ts +12 -1
  56. package/dist/crm/sync.d.ts +31 -2
  57. package/dist/crm/sync.js +110 -3
  58. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  59. package/dist/crm/testing/acme-scenario.js +170 -0
  60. package/dist/crm/testing/index.d.ts +1 -0
  61. package/dist/crm/testing/index.js +1 -0
  62. package/dist/crm/testing/source-contract.js +12 -0
  63. package/dist/crm/testing/source.d.ts +2 -0
  64. package/dist/crm/testing/source.js +1 -0
  65. package/dist/domain/addresses.d.ts +13 -0
  66. package/dist/domain/addresses.js +63 -0
  67. package/dist/domain/categories.d.ts +3 -0
  68. package/dist/domain/categories.js +2 -0
  69. package/dist/domain/crm.d.ts +23 -0
  70. package/dist/domain/crm.js +7 -0
  71. package/dist/domain/mentions.d.ts +2 -12
  72. package/dist/domain/mentions.js +2 -19
  73. package/dist/domain/orders.d.ts +8 -1
  74. package/dist/domain/orders.js +6 -2
  75. package/dist/domain/phones.d.ts +26 -0
  76. package/dist/domain/phones.js +48 -0
  77. package/dist/domain/record-types.d.ts +1 -1
  78. package/dist/domain/record-types.js +1 -0
  79. package/dist/domain/records.d.ts +5 -0
  80. package/dist/domain/ref-summaries.d.ts +39 -0
  81. package/dist/domain/ref-summaries.js +51 -3
  82. package/dist/domain/relations.d.ts +12 -2
  83. package/dist/domain/relations.js +14 -3
  84. package/dist/domain/vcard.d.ts +2 -2
  85. package/dist/domain/vcard.js +4 -10
  86. package/dist/embeddings/models.d.ts +11 -3
  87. package/dist/embeddings/models.js +28 -4
  88. package/dist/entities/business-context.d.ts +149 -0
  89. package/dist/entities/business-context.js +192 -0
  90. package/dist/entities/contact-activity.d.ts +2 -0
  91. package/dist/entities/contact-activity.js +7 -1
  92. package/dist/entities/contact-context.d.ts +157 -0
  93. package/dist/entities/contact-context.js +2 -0
  94. package/dist/entities/deal.d.ts +10 -0
  95. package/dist/entities/deal.js +2 -0
  96. package/dist/entities/index.d.ts +23 -3
  97. package/dist/entities/index.js +5 -0
  98. package/dist/entities/mention.d.ts +4 -3
  99. package/dist/entities/mention.js +2 -1
  100. package/dist/entities/message-transfer.d.ts +4 -2
  101. package/dist/entities/message-transfer.js +2 -2
  102. package/dist/entities/model.d.ts +2 -2
  103. package/dist/entities/model.js +1 -1
  104. package/dist/entities/relationship.d.ts +4 -0
  105. package/dist/entities/relationship.js +4 -0
  106. package/dist/errors/reasons.js +37 -4
  107. package/dist/fetch/page.js +2 -1
  108. package/dist/index.d.ts +3 -2
  109. package/dist/index.js +3 -2
  110. package/dist/meetings/context-store.d.ts +2 -0
  111. package/dist/meetings/findings-rules.d.ts +4 -0
  112. package/dist/meetings/findings-rules.js +5 -2
  113. package/dist/meetings/result-items.d.ts +1 -0
  114. package/dist/meetings/result-items.js +1 -0
  115. package/dist/models/index.js +22 -5
  116. package/dist/runs/events.d.ts +11 -1
  117. package/dist/runs/events.js +3 -1
  118. package/dist/runs/log-attributes.js +4 -0
  119. package/dist/runs/log-events.js +2 -0
  120. package/dist/runs/recording.d.ts +3 -0
  121. package/dist/runs/recording.js +36 -12
  122. package/dist/runs/run.d.ts +12 -3
  123. package/dist/runs/run.js +32 -13
  124. package/dist/search/account-list.d.ts +6 -0
  125. package/dist/search/account-list.js +9 -3
  126. package/dist/search/groups.d.ts +68 -0
  127. package/dist/search/groups.js +172 -0
  128. package/dist/services/account-groups.d.ts +28 -0
  129. package/dist/services/account-groups.js +89 -0
  130. package/dist/services/archive.d.ts +7 -1
  131. package/dist/services/archive.js +19 -3
  132. package/dist/services/business-context.d.ts +113 -0
  133. package/dist/services/business-context.js +156 -0
  134. package/dist/services/communications.d.ts +50 -0
  135. package/dist/services/communications.js +140 -0
  136. package/dist/services/deal-context.d.ts +90 -0
  137. package/dist/services/deal-context.js +131 -0
  138. package/dist/services/deps.d.ts +2 -0
  139. package/dist/services/enrichment.d.ts +7 -2
  140. package/dist/services/enrichment.js +46 -5
  141. package/dist/services/events-search.js +2 -1
  142. package/dist/services/group-guard.d.ts +28 -0
  143. package/dist/services/group-guard.js +131 -0
  144. package/dist/services/index.d.ts +15 -2
  145. package/dist/services/index.js +9 -2
  146. package/dist/services/ingest.d.ts +12 -0
  147. package/dist/services/ingest.js +4 -0
  148. package/dist/services/meaning-model.d.ts +7 -0
  149. package/dist/services/meaning-model.js +20 -0
  150. package/dist/services/meeting-context.d.ts +6 -1
  151. package/dist/services/meeting-context.js +12 -5
  152. package/dist/services/message-resolution.js +2 -3
  153. package/dist/services/messages-meaning.js +4 -5
  154. package/dist/services/messages-search.d.ts +5 -1
  155. package/dist/services/messages-search.js +1 -1
  156. package/dist/services/model-downloads.d.ts +1 -1
  157. package/dist/services/model-downloads.js +6 -4
  158. package/dist/services/money-context.d.ts +73 -0
  159. package/dist/services/money-context.js +77 -0
  160. package/dist/services/notes-search.d.ts +4 -1
  161. package/dist/services/notes-search.js +19 -7
  162. package/dist/services/organization-context.d.ts +80 -0
  163. package/dist/services/organization-context.js +154 -0
  164. package/dist/services/people.d.ts +22 -6
  165. package/dist/services/people.js +38 -8
  166. package/dist/services/person-business.d.ts +43 -0
  167. package/dist/services/person-business.js +67 -0
  168. package/dist/services/person-context.d.ts +9 -1
  169. package/dist/services/person-context.js +5 -3
  170. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  171. package/dist/services/proposals/kinds/identity-link.js +48 -0
  172. package/dist/services/proposals/kinds/orders.js +1 -1
  173. package/dist/services/proposals/registry.js +2 -0
  174. package/dist/services/search-kind.d.ts +12 -5
  175. package/dist/services/search-kind.js +49 -10
  176. package/dist/services/text-model-choice.js +1 -1
  177. package/dist/store/accounts.d.ts +18 -0
  178. package/dist/store/accounts.js +18 -3
  179. package/dist/store/damage.d.ts +43 -10
  180. package/dist/store/damage.js +119 -36
  181. package/dist/store/decisions.js +3 -1
  182. package/dist/store/evidence-findings.d.ts +14 -0
  183. package/dist/store/evidence-findings.js +2 -0
  184. package/dist/store/exports.d.ts +2 -1
  185. package/dist/store/identity-links.d.ts +92 -0
  186. package/dist/store/identity-links.js +6 -0
  187. package/dist/store/index.d.ts +11 -5
  188. package/dist/store/index.js +5 -2
  189. package/dist/store/journal.d.ts +10 -0
  190. package/dist/store/journal.js +33 -0
  191. package/dist/store/marks.d.ts +19 -1
  192. package/dist/store/marks.js +23 -1
  193. package/dist/store/people.d.ts +22 -0
  194. package/dist/store/people.js +15 -1
  195. package/dist/store/sqlite/accounts.js +2 -0
  196. package/dist/store/sqlite/base-stages.d.ts +122 -0
  197. package/dist/store/sqlite/base-stages.js +443 -0
  198. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  199. package/dist/store/sqlite/base-suggest.js +62 -0
  200. package/dist/store/sqlite/business-contracts.js +10 -1
  201. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  202. package/dist/store/sqlite/crm-settings.js +56 -13
  203. package/dist/store/sqlite/crm.d.ts +13 -1
  204. package/dist/store/sqlite/crm.js +20 -4
  205. package/dist/store/sqlite/deals.d.ts +33 -0
  206. package/dist/store/sqlite/deals.js +42 -4
  207. package/dist/store/sqlite/decision-requests.js +7 -3
  208. package/dist/store/sqlite/email-index.js +8 -4
  209. package/dist/store/sqlite/evidence-findings.js +29 -5
  210. package/dist/store/sqlite/findings-core.js +4 -2
  211. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  212. package/dist/store/sqlite/identity-link-rows.js +146 -0
  213. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  214. package/dist/store/sqlite/identity-proposals.js +234 -0
  215. package/dist/store/sqlite/knowledge.js +2 -2
  216. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  217. package/dist/store/sqlite/link-kinds.js +1 -0
  218. package/dist/store/sqlite/link-row.d.ts +6 -0
  219. package/dist/store/sqlite/link-row.js +35 -0
  220. package/dist/store/sqlite/link-source.d.ts +10 -0
  221. package/dist/store/sqlite/link-source.js +16 -0
  222. package/dist/store/sqlite/manifest.js +1 -0
  223. package/dist/store/sqlite/meeting-context-links.js +9 -6
  224. package/dist/store/sqlite/memories.js +9 -7
  225. package/dist/store/sqlite/mentions.d.ts +4 -1
  226. package/dist/store/sqlite/mentions.js +14 -9
  227. package/dist/store/sqlite/migrations.generated.js +8 -0
  228. package/dist/store/sqlite/notes.d.ts +1 -2
  229. package/dist/store/sqlite/notes.js +4 -29
  230. package/dist/store/sqlite/open-store.js +3 -0
  231. package/dist/store/sqlite/open.js +11 -2
  232. package/dist/store/sqlite/orders.d.ts +2 -0
  233. package/dist/store/sqlite/orders.js +9 -3
  234. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  235. package/dist/store/sqlite/organization-categories.js +34 -0
  236. package/dist/store/sqlite/organizations.d.ts +5 -1
  237. package/dist/store/sqlite/organizations.js +14 -4
  238. package/dist/store/sqlite/person-links.d.ts +19 -4
  239. package/dist/store/sqlite/person-links.js +49 -11
  240. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  241. package/dist/store/sqlite/person-match-scan.js +251 -0
  242. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  243. package/dist/store/sqlite/person-matcher.js +32 -0
  244. package/dist/store/sqlite/proposed-actions.js +6 -0
  245. package/dist/store/sqlite/record-matching.d.ts +2 -8
  246. package/dist/store/sqlite/record-matching.js +8 -40
  247. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  248. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  249. package/dist/store/sqlite/record-relationships.js +243 -0
  250. package/dist/store/sqlite/record-run.d.ts +5 -0
  251. package/dist/store/sqlite/record-run.js +62 -2
  252. package/dist/store/sqlite/record-writes.d.ts +1 -1
  253. package/dist/store/sqlite/record-writes.js +4 -2
  254. package/dist/store/sqlite/records.js +27 -2
  255. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  256. package/dist/store/sqlite/ref-accounts.js +117 -0
  257. package/dist/store/sqlite/ref-summaries.js +5 -1
  258. package/dist/store/sqlite/relation-list.d.ts +4 -1
  259. package/dist/store/sqlite/relation-list.js +18 -2
  260. package/dist/store/sqlite/relation-proposals.d.ts +6 -0
  261. package/dist/store/sqlite/relation-proposals.js +3 -0
  262. package/dist/store/sqlite/relation-roles.js +12 -6
  263. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  264. package/dist/store/sqlite/reported-relations.js +59 -18
  265. package/dist/store/sqlite/schema.d.ts +32 -0
  266. package/dist/store/sqlite/schema.js +3 -0
  267. package/dist/store/sqlite/transaction.js +11 -1
  268. package/dist/store/store.d.ts +3 -0
  269. package/dist/store/store.js +5 -0
  270. package/dist/store/write-events.d.ts +18 -0
  271. package/dist/store/write-events.js +88 -0
  272. package/package.json +3 -3
  273. package/parity.json +11 -4
  274. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -14,6 +14,7 @@ import { CRM_KINDS } from "../../domain/crm.js";
14
14
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
15
15
  import { deal as dealEntity } from "../../entities/deal.js";
16
16
  import { count, text } from "../../entities/fields.js";
17
+ import { CRM_SCOPES } from "../../store/sqlite/crm-settings.js";
17
18
  import { crmStatus, syncCrm } from "../sync.js";
18
19
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
19
20
  import { csvFormatOption, renderCsv } from "./csv.js";
@@ -21,6 +22,8 @@ import { pipelineView } from "./pipeline-view.js";
21
22
  import { addCrmSearchAll } from "./search-all.js";
22
23
  export { csvColumnPaths, csvFormatOption, DEAL_CSV_COLUMNS, printCsv, refuseCsvConflict, } from "./csv.js";
23
24
  const MOST = 500;
25
+ /** A stage by the store's reference, as memo's `stages list` and a deal's `base_stage` name it. */
26
+ const STAGE_REF = /^stage:\d+$/;
24
27
  const DEAL_FIELDS = [
25
28
  termField("status", "enum", "status:open", { values: DEAL_STATUSES }),
26
29
  termField("stage", "kw", 'stage:"Quote sent"', { relation: "a stage's name, in any letter case" }),
@@ -58,6 +61,10 @@ const STAGE_UNTRUSTED = ["name", "pipeline_name"];
58
61
  const crmSync = v.strictObject({
59
62
  provider: text,
60
63
  account: text,
64
+ scope: v.variant("mode", [
65
+ v.strictObject({ mode: v.literal("all") }),
66
+ v.strictObject({ mode: v.literal("mine"), self: text, also: v.array(text) }),
67
+ ]),
61
68
  pipelines: count,
62
69
  users: v.optional(count),
63
70
  skipped_owner_rejected: count,
@@ -69,8 +76,11 @@ const crmSync = v.strictObject({
69
76
  saved: count,
70
77
  removed: count,
71
78
  unlisted: count,
79
+ out_of_scope: count,
80
+ held: v.optional(v.literal(true)),
72
81
  pass: v.optional(v.picklist(["complete", "partial", "held"])),
73
82
  error: v.optional(text),
83
+ setting: v.optional(text),
74
84
  })),
75
85
  issues: v.array(v.strictObject({
76
86
  kind: v.picklist([...CRM_KINDS, "user"]),
@@ -83,12 +93,22 @@ const crmSync = v.strictObject({
83
93
  stopped: v.optional(v.picklist(["requests", "deadline", "cancelled"])),
84
94
  progress: v.strictObject({ requests: count, saved: count, steps: count }),
85
95
  hint: v.optional(text),
96
+ group_hint: v.optional(text),
86
97
  });
87
98
  const crmSyncProgress = v.strictObject({
88
99
  kind: v.picklist(CRM_KINDS),
89
100
  round: v.nullable(v.picklist(["full", "changes"])),
90
101
  id_pass: v.nullable(text),
91
102
  stored: count,
103
+ scope: v.optional(v.strictObject({
104
+ setting: v.picklist(CRM_SCOPES),
105
+ explicit: v.boolean(),
106
+ held: v.optional(v.literal(true)),
107
+ applied: v.nullable(v.variant("mode", [
108
+ v.strictObject({ mode: v.literal("all") }),
109
+ v.strictObject({ mode: v.literal("mine"), users: v.array(text) }),
110
+ ])),
111
+ })),
92
112
  job: text,
93
113
  profile: text,
94
114
  done: count,
@@ -169,17 +189,20 @@ const addCrmCommandsDefinition = (program, options) => {
169
189
  ...(opts.rescan ? { rescan: true } : {}),
170
190
  });
171
191
  const failed = report.synced.filter((one) => one.error !== undefined);
192
+ // A kind that failed on a setting fails the same way again until the owner changes it: no retry is offered.
193
+ const retried = failed.filter((one) => one.setting === undefined);
194
+ const settings = [...new Set(failed.flatMap((one) => one.setting ?? []))];
172
195
  const timeout = command.optsWithGlobals().timeout;
173
196
  // The same command again, never --rescan: that would drop the round this run leaves in progress.
174
197
  const stuck = report.state === "partial" && report.progress.steps === 0 && failed.length === 0;
175
- const next = failed.length || (report.state === "partial" && !stuck)
198
+ const next = retried.length || (report.state === "partial" && !stuck && failed.length === 0)
176
199
  ? [
177
200
  {
178
201
  kind: "command",
179
202
  step: "crm.sync",
180
203
  command: "sync",
181
204
  args: Object.fromEntries(Object.entries({ max_pages: opts.maxPages, timeout }).filter(([, value]) => value !== undefined)),
182
- why: failed.length
205
+ why: retried.length
183
206
  ? "a kind failed to sync; running sync again retries it"
184
207
  : "the sync stopped before its end to answer in time; running it again goes on from there",
185
208
  safe_to_auto_execute: true,
@@ -187,8 +210,9 @@ const addCrmCommandsDefinition = (program, options) => {
187
210
  ]
188
211
  : undefined;
189
212
  const progressAt = lineOf(command, "store status");
213
+ const fixes = settings.map((setting) => lineOf(command, `config set ${setting} <value>`));
190
214
  const hint = failed.length
191
- ? `${failed.map((one) => `${one.kind}: ${one.error}`).join("; ")} — run sync again to retry`
215
+ ? `${failed.map((one) => `${one.kind}: ${one.error}`).join("; ")} — ${fixes.length ? `fix the setting: ${fixes.join("; ")}` : "run sync again to retry"}`
192
216
  : stuck
193
217
  ? `this run moved nothing on: raise --timeout or --max-pages, then run sync again; see progress: ${progressAt}`
194
218
  : report.state === "partial"
@@ -198,7 +222,7 @@ const addCrmCommandsDefinition = (program, options) => {
198
222
  // What the healthy kinds brought is saved and answered; each failure and each item not kept is an issue.
199
223
  const issues = [
200
224
  ...failed.map((one) => ({
201
- code: "provider_error",
225
+ code: one.setting === undefined ? "provider_error" : "validation_error",
202
226
  reason: "sync.partial",
203
227
  source: `crm:${one.kind}`,
204
228
  })),
@@ -358,9 +382,17 @@ const addCrmCommandsDefinition = (program, options) => {
358
382
  });
359
383
  const move = write("move", "move", `move a ${kind} to another stage of its pipeline; a won or lost stage checks the close key too`);
360
384
  if (move)
361
- example(reference(move).argument("<stage>", "the stage, by the CRM's id or a name only one stage of its pipeline has"), `${plural} move ${kind}:12 "Quote sent"`).action(async (ref, stage, opts, command) => {
385
+ example(reference(move).argument("<stage>", "the stage, by the CRM's id or a name only one stage of its pipeline has; or a stage:<id>, of its pipeline " +
386
+ "or of the owner's base set, which moves it to the one stage of its pipeline mapped there and refuses " +
387
+ "several (with the candidates) or none"), `${plural} move ${kind}:12 "Quote sent"`, `${plural} move ${kind}:12 stage:5`).action(async (ref, stage, opts, command) => {
362
388
  await run(command, async (context) => {
363
- const done = await moveCrmItem(context, kind, ref, stage, idOf(opts));
389
+ let target = stage;
390
+ if (STAGE_REF.test(stage.trim())) {
391
+ // Checked first: another account's pipeline and stage names stay out of the refusal.
392
+ await ownCopy(context, kind, ref);
393
+ target = (await context.store.baseStages.resolve(ref, stage.trim())).stage.externalId ?? stage;
394
+ }
395
+ const done = await moveCrmItem(context, kind, ref, target, idOf(opts));
364
396
  return answered(done.operationId, done.item);
365
397
  });
366
398
  });
@@ -0,0 +1,8 @@
1
+ import type { MessageStore } from "../store/store.js";
2
+ import type { AccountKey } from "../store/types.js";
3
+ export declare const workGroupHint: (key: AccountKey) => string;
4
+ /**
5
+ * A CRM account no saved group lists is reachable only by reading everything (WC-ACCT-13); this says how to put
6
+ * it in a work group, and never asks.
7
+ */
8
+ export declare const ungroupedHint: (store: MessageStore, key: AccountKey) => Promise<string | undefined>;
@@ -0,0 +1,13 @@
1
+ import { sameAs } from "../search/account-list.js";
2
+ import { ALL } from "../search/groups.js";
3
+ import { listContextOf } from "../services/search-kind.js";
4
+ export const workGroupHint = (key) => `add it to a work group: \`memo groups add work ${key.provider}:${key.account}\``;
5
+ /**
6
+ * A CRM account no saved group lists is reachable only by reading everything (WC-ACCT-13); this says how to put
7
+ * it in a work group, and never asks.
8
+ */
9
+ export const ungroupedHint = async (store, key) => {
10
+ const { groups } = (await listContextOf(store, key, undefined)).membership;
11
+ const grouped = Object.entries(groups).some(([name, members]) => name !== ALL && members.some(sameAs(key)));
12
+ return grouped ? undefined : workGroupHint(key);
13
+ };
@@ -1,4 +1,4 @@
1
- import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmUser } from "../domain/crm.js";
1
+ import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, 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. */
@@ -51,12 +51,23 @@ export interface CrmCallContext {
51
51
  message: string;
52
52
  scope?: string;
53
53
  }): void;
54
+ /**
55
+ * Which deals and leads the engine keeps; absent, every one. The engine applies it to what a source lists, so a
56
+ * source may also filter by it to read less, and must still list every assignee's changes.
57
+ */
58
+ scope?: CrmScope;
54
59
  }
55
60
  /** One CRM account, as an adapter reads it. The engine never sees a provider word. */
56
61
  export interface CrmSource {
57
62
  /** The registry name: `bitrix24`, `pipedrive`, `hubspot`, `amocrm`. */
58
63
  readonly provider: string;
59
64
  readonly traits: CrmSourceTraits;
65
+ /**
66
+ * The sign-in's own user id in the CRM, what a `mine` scope keeps besides `unassigned`. A source with it fills every
67
+ * deal's and lead's `assignee`, since `mine` keeps one without as nobody's; a source without it is copied whole. One
68
+ * account's copy belongs to one user: another sign-in's user is refused.
69
+ */
70
+ self?(): string | Promise<string>;
60
71
  /** One kind's pipelines with their stages; a CRM whose leads have no pipelines answers one of its own making. */
61
72
  pipelines(kind: DealKind, context?: CrmCallContext): Promise<CrmPipeline[]>;
62
73
  /**
@@ -1,5 +1,5 @@
1
1
  import { type BudgetStop, type RunBudget } from "../background/budget.js";
2
- import { type CrmKind } from "../domain/crm.js";
2
+ import { type CrmKind, type CrmScope } from "../domain/crm.js";
3
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";
@@ -28,6 +28,10 @@ export interface CrmCursor {
28
28
  pass: PendingPass | null;
29
29
  /** When the last complete id pass started; 0 before the first. */
30
30
  passAt: number;
31
+ /** Of a deal or lead: the scope the copy is read under, `all` or `mine:<user ids>`; absent, `all`, as before scopes. */
32
+ scope?: string;
33
+ /** The copy still holds stored rows outside `scope`: a held narrowing, done once the owner sets the scope. */
34
+ narrowing?: true;
31
35
  }
32
36
  export declare const parseCrmCursor: (value: string | null | undefined) => CrmCursor | null;
33
37
  export declare const cursorName: (kind: CrmKind) => string;
@@ -46,7 +50,7 @@ export interface CrmSyncOptions {
46
50
  export interface CrmSyncIssue {
47
51
  /** `user`: the account's users and departments. */
48
52
  kind: CrmKind | "user";
49
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.not-reported" | "crm.pending-dropped";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.not-reported" | "crm.pending-dropped";
50
54
  message: string;
51
55
  externalId?: string;
52
56
  }
@@ -62,10 +66,16 @@ export interface CrmSyncResult {
62
66
  removed: number;
63
67
  /** Rows a complete id pass did not list, now marked deleted. */
64
68
  unlisted: number;
69
+ /** Rows that changed and left the scope, such as a deal given to another user, now marked deleted. */
70
+ outOfScope: number;
71
+ /** A narrowing waits for the owner: rows outside the scope are not saved, and the stored ones are kept. */
72
+ held?: true;
65
73
  /** `complete`: a full list of ids arrived; `partial`: it stopped and goes on next run; `held`: it would mark too many. */
66
74
  pass?: "complete" | "partial" | "held";
67
75
  /** Set when the kind failed; its cursor stays at its last saved page. */
68
76
  error?: string;
77
+ /** Set when the kind failed on this setting's value: changing it, not running sync again, fixes it. */
78
+ setting?: string;
69
79
  }
70
80
  export interface CrmSyncReport {
71
81
  provider: string;
@@ -74,6 +84,8 @@ export interface CrmSyncReport {
74
84
  pipelines: number;
75
85
  /** Users read this run; absent when the CRM cannot list them. */
76
86
  users?: number;
87
+ /** The deals and leads this run copied, with the sign-in's own user; `all` too when the CRM names none. */
88
+ scope: CrmScope;
77
89
  /** Relationships left out because the owner removed or rejected that very one, role included. */
78
90
  skippedOwnerRejected: number;
79
91
  synced: CrmSyncResult[];
@@ -90,6 +102,11 @@ export interface CrmSyncReport {
90
102
  steps: number;
91
103
  };
92
104
  hint?: string;
105
+ /**
106
+ * On the first sync of an account no saved group lists: how to add it to a work group. Not `next`, which in an answer
107
+ * is the list of steps to run.
108
+ */
109
+ groupHint?: string;
93
110
  }
94
111
  /** The gaps the account's last sync recorded; none before its first. */
95
112
  export declare const crmGapsOf: (store: MessageStore, account: AccountKey) => Promise<CrmGap[]>;
@@ -121,6 +138,18 @@ export declare const crmStatus: (store: MessageStore, account: AccountKey, { pro
121
138
  round: string | null;
122
139
  id_pass: string | null;
123
140
  stored: number;
141
+ scope?: {
142
+ setting: "all" | "mine";
143
+ explicit: boolean;
144
+ applied: {
145
+ mode: "all";
146
+ users?: undefined;
147
+ } | {
148
+ mode: "mine";
149
+ users: string[];
150
+ } | null;
151
+ held?: boolean | undefined;
152
+ } | undefined;
124
153
  line: string;
125
154
  }[];
126
155
  page: number;
package/dist/crm/sync.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { runBudget } from "../background/budget.js";
3
3
  import { progressLine, progressOf } from "../background/checkpoints.js";
4
- import { CRM_KINDS, isItemKind } from "../domain/crm.js";
4
+ import { CRM_KINDS, isCrmUserId, isItemKind, normalCrmUserId, } from "../domain/crm.js";
5
5
  import { DEAL_KINDS } from "../domain/deals.js";
6
6
  import { isCliFailure } from "../errors/failures.js";
7
+ import { crmSettingKey } from "../store/sqlite/crm-settings.js";
8
+ import { ungroupedHint } from "./group-hint.js";
7
9
  const DAY = 86_400_000;
8
10
  /** A row the CRM changed this close to the id pass's start may be newer than the list, by the two clocks' skew. */
9
11
  const CLOCK_MARGIN = 60 * 60_000;
@@ -37,6 +39,8 @@ export const parseCrmCursor = (value) => {
37
39
  updatedAt: typeof cursor.updatedAt === "number" ? cursor.updatedAt : null,
38
40
  pass: pass ?? null,
39
41
  passAt: typeof cursor.passAt === "number" ? cursor.passAt : 0,
42
+ ...(typeof cursor.scope === "string" ? { scope: cursor.scope } : {}),
43
+ ...(cursor.narrowing === true ? { narrowing: true } : {}),
40
44
  };
41
45
  }
42
46
  catch {
@@ -205,12 +209,67 @@ const savePage = async (run, kind, page) => {
205
209
  run.report.issues.push({ kind, ...one });
206
210
  return { saved, stop };
207
211
  };
212
+ const scopeIds = (scope) => scope.mode === "all" ? null : [...new Set([scope.self, ...scope.also])].sort();
213
+ const scopeKey = (scope) => {
214
+ const ids = scopeIds(scope);
215
+ return ids ? `mine:${ids.join(",")}` : "all";
216
+ };
217
+ const idsOfKey = (key) => (key.startsWith("mine:") ? key.slice(5).split(",") : null);
218
+ /** The scope new pages are read under; `null` before the first sync. A held narrowing is `held`, not this. */
219
+ const appliedScope = (cursor) => {
220
+ if (cursor === null)
221
+ return null;
222
+ const users = idsOfKey(cursor.scope ?? "all");
223
+ return users === null ? { mode: "all" } : { mode: "mine", users };
224
+ };
225
+ /** Under `mine`, a row with no assignee is nobody's, so it is in scope. */
226
+ const inScope = (ids, item) => ids === null || item.assignee == null || ids.includes(item.assignee);
227
+ const normalAssignee = (item) => item.assignee == null ? item : { ...item, assignee: normalCrmUserId(item.assignee) };
208
228
  const syncKind = async (run, kind, options, result) => {
209
229
  const { source, store, account, now, budget, signal } = run;
210
230
  const name = cursorName(kind);
211
231
  let cursor = parseCrmCursor((await store.sync.syncState(account, name))?.value) ?? fresh();
212
232
  if (options.rescan)
213
233
  cursor = { ...cursor, round: { from: null, page: null, reset: false }, done: 0, pass: null, passAt: 0 };
234
+ const scope = scopeKey(run.scope);
235
+ const ids = isItemKind(kind) ? scopeIds(run.scope) : null;
236
+ const listedUnder = cursor.scope ?? "all";
237
+ const before = idsOfKey(listedUnder);
238
+ const changed = isItemKind(kind) && listedUnder !== scope;
239
+ let held = false;
240
+ // Narrowing is done here, by each stored row's assignee, so no list from the CRM can empty the copy.
241
+ if (isItemKind(kind) &&
242
+ ids &&
243
+ (cursor.narrowing === true || (changed && (before === null || before.some((id) => !ids.includes(id)))))) {
244
+ const leaving = await store.crm.removeOutOfScope(account, kind, ids, { dryRun: true });
245
+ const stored = await store.crm.count(account, kind);
246
+ // A default `mine` whose own user holds few of the copy's rows is more likely a wrong sign-in than the owner's
247
+ // wish: the stored rows wait for the owner to set the scope. New pages are still read under `mine`.
248
+ held = !run.scopeSet && leaving > stored * MOST_UNLISTED;
249
+ if (held) {
250
+ result.held = true;
251
+ run.report.issues.push({
252
+ kind,
253
+ reason: "crm.narrowing-held",
254
+ message: `scope mine keeps the ${kind}s of user ${ids.join(", ")}: ${leaving} of the ${stored} stored would be ` +
255
+ `marked deleted; none was, and none will be until the owner sets ${crmSettingKey(account, "scope")} ` +
256
+ "to mine or all",
257
+ });
258
+ }
259
+ else
260
+ result.outOfScope += await store.crm.removeOutOfScope(account, kind, ids);
261
+ }
262
+ if (changed || cursor.narrowing) {
263
+ // The cursor takes the new scope even while held: pages are read under it, so a later wider scope lists in full.
264
+ const widened = changed && before !== null && (ids === null || ids.some((id) => !before.includes(id)));
265
+ const { narrowing: _done, ...rest } = cursor;
266
+ cursor = {
267
+ ...rest,
268
+ ...(widened ? { round: { from: null, page: null, reset: false }, done: 0 } : {}),
269
+ scope,
270
+ ...(held ? { narrowing: true } : {}),
271
+ };
272
+ }
214
273
  let round = cursor.round ?? { from: cursor.token, page: null, reset: false };
215
274
  if (cursor.round === null)
216
275
  cursor = { ...cursor, done: 0 };
@@ -244,11 +303,17 @@ const syncKind = async (run, kind, options, result) => {
244
303
  await save();
245
304
  continue;
246
305
  }
247
- const { saved, stop } = await savePage(run, kind, page);
306
+ const items = isItemKind(kind) ? page.items.map(normalAssignee) : page.items;
307
+ const kept = isItemKind(kind) ? items.filter((item) => inScope(ids, item)) : items;
308
+ const { saved, stop } = await savePage(run, kind, { ...page, items: kept });
248
309
  result.saved += saved;
249
310
  cursor = { ...cursor, done: cursor.done + saved };
250
311
  if (page.removed?.length)
251
312
  result.removed += await store.crm.remove(account, kind, page.removed);
313
+ if (kept.length < items.length && !held) {
314
+ const left = items.filter((item) => !inScope(ids, item)).map(({ externalId }) => externalId);
315
+ result.outOfScope += await store.crm.remove(account, kind, left);
316
+ }
252
317
  run.moved();
253
318
  if (page.nextPage === undefined) {
254
319
  listed = true;
@@ -287,7 +352,8 @@ const syncKind = async (run, kind, options, result) => {
287
352
  const before = pass.startedAt - CLOCK_MARGIN;
288
353
  const stored = await store.crm.count(account, kind);
289
354
  const unlisted = await store.crm.removeUnlisted(account, kind, pass.seen, before, { dryRun: true });
290
- if (!options.rescan && stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED) {
355
+ const emptied = pass.seen.length === 0 && unlisted > 0;
356
+ if (!options.rescan && (emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED))) {
291
357
  result.pass = "held";
292
358
  run.report.issues.push({
293
359
  kind,
@@ -316,9 +382,28 @@ const syncKind = async (run, kind, options, result) => {
316
382
  export const syncCrm = async (source, store, account, options = {}) => {
317
383
  const now = options.now ?? Date.now();
318
384
  const budget = options.budget ?? runBudget();
385
+ const setting = await store.crm.scope(account);
386
+ const self = source.self ? normalCrmUserId(await source.self()) : undefined;
387
+ if (self !== undefined && !isCrmUserId(self))
388
+ throw new CliError("invalid_response", `${source.provider} named its sign-in's user as "${self}", not a user id`);
389
+ if (self !== undefined) {
390
+ const owner = await store.crm.ownUser(account);
391
+ if (owner === undefined)
392
+ await store.crm.saveOwnUser(account, self);
393
+ else if (owner !== self) {
394
+ const setting = crmSettingKey(account, "self");
395
+ throw new CliError("validation_error", `this account's copy is user ${owner}'s, and this sign-in is user ${self}: one copy holds one user's ` +
396
+ `deals, under scope all too, since ${setting} decides whose deals a later scope mine keeps; ` +
397
+ `"config unset ${setting}" gives the copy to this sign-in`, { setting });
398
+ }
399
+ }
400
+ const scope = self !== undefined && setting.mode === "mine"
401
+ ? { mode: "mine", self, also: setting.also.map(normalCrmUserId) }
402
+ : { mode: "all" };
319
403
  const report = {
320
404
  provider: source.provider,
321
405
  account: account.account,
406
+ scope,
322
407
  pipelines: 0,
323
408
  skippedOwnerRejected: 0,
324
409
  synced: [],
@@ -330,6 +415,8 @@ export const syncCrm = async (source, store, account, options = {}) => {
330
415
  let steps = 0;
331
416
  const run = {
332
417
  source,
418
+ scope,
419
+ scopeSet: setting.mode === "mine" && setting.explicit,
333
420
  store,
334
421
  account,
335
422
  now,
@@ -352,11 +439,15 @@ export const syncCrm = async (source, store, account, options = {}) => {
352
439
  throw new BudgetSpent(why);
353
440
  },
354
441
  gap: ({ kind, message, scope }) => run.gaps.push({ kind, reason: "partial", message, ...(scope ? { scope } : {}) }),
442
+ scope,
355
443
  },
356
444
  unlistedUsers: 0,
357
445
  droppedPending: 0,
358
446
  };
359
447
  const kinds = CRM_KINDS.filter((kind) => source.traits.kinds.includes(kind));
448
+ const cursors = await Promise.all(kinds.map((kind) => store.sync.syncState(account, cursorName(kind))));
449
+ const first = cursors.every((cursor) => cursor === undefined);
450
+ const malformed = scope.mode === "mine" && setting.mode === "mine" ? setting.also.find((id) => !isCrmUserId(id)) : undefined;
360
451
  let stopped = null;
361
452
  for (const kind of DEAL_KINDS)
362
453
  if (!stopped && kinds.includes(kind)) {
@@ -386,10 +477,18 @@ export const syncCrm = async (source, store, account, options = {}) => {
386
477
  saved: 0,
387
478
  removed: 0,
388
479
  unlisted: 0,
480
+ outOfScope: 0,
389
481
  };
390
482
  report.synced.push(result);
391
483
  if (stopped)
392
484
  continue;
485
+ if (malformed !== undefined && isItemKind(kind)) {
486
+ Object.assign(result, {
487
+ error: `unassigned holds "${malformed}", not a numeric user id: no ${kind} was read`,
488
+ setting: crmSettingKey(account, "unassigned"),
489
+ });
490
+ continue;
491
+ }
393
492
  try {
394
493
  stopped = await syncKind(run, kind, options, result);
395
494
  // After every company of the run is stored, so one listed before the own company still gets its meaning.
@@ -439,10 +538,15 @@ export const syncCrm = async (source, store, account, options = {}) => {
439
538
  report.complete = false;
440
539
  report.hint = CONTINUE;
441
540
  }
541
+ const groupHint = first ? await ungroupedHint(store, account) : undefined;
542
+ if (groupHint)
543
+ report.groupHint = groupHint;
442
544
  return report;
443
545
  };
444
546
  /** Each kind's sync in the WC-LIFE-14 shape: `cursor_age_ms` growing on a `partial` one means nothing moves it. */
445
547
  export const crmStatus = async (store, account, { profile, now, kinds = CRM_KINDS }) => {
548
+ const saved = await store.crm.scope(account);
549
+ const setting = { setting: saved.mode, explicit: saved.mode === "all" || saved.explicit };
446
550
  const items = [];
447
551
  for (const kind of kinds) {
448
552
  const cursor = parseCrmCursor((await store.sync.syncState(account, cursorName(kind)))?.value);
@@ -459,6 +563,9 @@ export const crmStatus = async (store, account, { profile, now, kinds = CRM_KIND
459
563
  round: cursor?.round ? (cursor.round.from === null ? "full" : "changes") : null,
460
564
  id_pass: cursor?.pass ? "partial" : cursor?.passAt ? new Date(cursor.passAt).toISOString() : null,
461
565
  stored: await store.crm.count(account, kind),
566
+ ...(isItemKind(kind)
567
+ ? { scope: { ...setting, applied: appliedScope(cursor), ...(cursor?.narrowing ? { held: true } : {}) } }
568
+ : {}),
462
569
  ...progress,
463
570
  line: progressLine(progress),
464
571
  });
@@ -0,0 +1,40 @@
1
+ import type { AccountKey, MessageStore } from "../../store/store.js";
2
+ import { type CrmSyncReport } from "../index.js";
3
+ import { type FakeCrmSource } from "./source.js";
4
+ /** The CRM portal of the owner's own company, Northstar Consulting. */
5
+ export declare const ACME_PORTAL: AccountKey;
6
+ export declare const ACME_TELEGRAM: AccountKey;
7
+ export declare const ACME_MAIL: AccountKey;
8
+ export declare const ACME_CALENDAR: AccountKey;
9
+ /** The deal opens on this day; every message, mail and meeting falls within its first month. */
10
+ export declare const ACME_OPENED: number;
11
+ export declare const ACME_NOW: number;
12
+ export interface AcmeScenario {
13
+ store: MessageStore;
14
+ /** The portal: change a row with `crm.put` or `crm.delete`, then `sync()` again. */
15
+ crm: FakeCrmSource;
16
+ sync: () => Promise<CrmSyncReport>;
17
+ refs: {
18
+ owner: string;
19
+ /** Northstar Consulting, the owner's own company. */
20
+ own: string;
21
+ acme: string;
22
+ alice: string;
23
+ bob: string;
24
+ emma: string;
25
+ deal: string;
26
+ project: string;
27
+ invoice: string;
28
+ task: string;
29
+ event: string;
30
+ };
31
+ }
32
+ /**
33
+ * Plan §8's scenario, synthetic: Northstar Consulting is the owner's own company and its CRM portal, Acme Ltd its
34
+ * customer. Alice and Bob are Acme's CRM contacts; Emma is a portal user, Northstar's sales owner and the deal's owner.
35
+ * The deal "Acme renewal" has Alice as contact (CRM), Bob as decision-maker (the owner's) and project Atlas (the
36
+ * owner's, on the CRM copy). The owner has a Telegram dialog with Alice, a mail with Bob, a Zoom meeting with all three, an invoice to
37
+ * Acme with no payment and an open follow-up task. Everything is written through the store's and the CRM sync's own
38
+ * calls; the store is the caller's, and no real account is touched.
39
+ */
40
+ export declare const acmeScenario: (store: MessageStore) => Promise<AcmeScenario>;