@wirecat/cli-core 0.674.0 → 0.676.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 (62) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/index.d.ts +1 -1
  6. package/dist/cli/list-query.d.ts +3 -2
  7. package/dist/cli/list-query.js +5 -2
  8. package/dist/cli/messenger/search-command.js +3 -1
  9. package/dist/cli/option-hints.d.ts +2 -0
  10. package/dist/cli/option-hints.js +4 -2
  11. package/dist/cli/setup-command.js +9 -3
  12. package/dist/crm/cli/index.d.ts +7 -1
  13. package/dist/crm/cli/index.js +104 -20
  14. package/dist/crm/cli/pipeline-view.js +15 -1
  15. package/dist/crm/cli/records.js +11 -3
  16. package/dist/crm/cli/search-all.d.ts +5 -2
  17. package/dist/crm/cli/search-all.js +15 -3
  18. package/dist/crm/source.d.ts +3 -2
  19. package/dist/crm/stage-tasks.js +1 -1
  20. package/dist/crm/sync.js +13 -11
  21. package/dist/crm/testing/write-contract.js +5 -1
  22. package/dist/crm/viewer.d.ts +28 -0
  23. package/dist/crm/viewer.js +63 -0
  24. package/dist/crm/writer.d.ts +3 -0
  25. package/dist/crm/writes.d.ts +7 -2
  26. package/dist/crm/writes.js +24 -14
  27. package/dist/domain/crm.d.ts +9 -9
  28. package/dist/domain/moment.d.ts +2 -0
  29. package/dist/domain/moment.js +2 -0
  30. package/dist/entities/business-context.js +1 -1
  31. package/dist/entities/deal.d.ts +86 -39
  32. package/dist/entities/deal.js +45 -4
  33. package/dist/entities/index.d.ts +20 -32
  34. package/dist/errors/reasons.js +1 -0
  35. package/dist/meetings/mcp/index.d.ts +15 -15
  36. package/dist/services/search-all.d.ts +3 -1
  37. package/dist/services/search-all.js +1 -0
  38. package/dist/setup/define.d.ts +17 -2
  39. package/dist/store/exports.d.ts +1 -0
  40. package/dist/store/exports.js +1 -0
  41. package/dist/store/sqlite/copy-viewer.d.ts +16 -0
  42. package/dist/store/sqlite/copy-viewer.js +11 -0
  43. package/dist/store/sqlite/crm-activities.d.ts +7 -1
  44. package/dist/store/sqlite/crm-activities.js +32 -5
  45. package/dist/store/sqlite/crm-contacts.d.ts +5 -2
  46. package/dist/store/sqlite/crm-contacts.js +30 -14
  47. package/dist/store/sqlite/crm-rows.d.ts +7 -0
  48. package/dist/store/sqlite/crm-rows.js +37 -5
  49. package/dist/store/sqlite/crm-settings.d.ts +2 -1
  50. package/dist/store/sqlite/crm-settings.js +3 -2
  51. package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
  52. package/dist/store/sqlite/crm-stage-entries.js +77 -18
  53. package/dist/store/sqlite/crm.d.ts +14 -4
  54. package/dist/store/sqlite/crm.js +59 -7
  55. package/dist/store/sqlite/deals.d.ts +47 -29
  56. package/dist/store/sqlite/deals.js +64 -76
  57. package/dist/store/sqlite/pipeline-period.d.ts +85 -0
  58. package/dist/store/sqlite/pipeline-period.js +199 -0
  59. package/dist/store/sqlite/stage-amounts.d.ts +6 -2
  60. package/dist/store/sqlite/stage-amounts.js +8 -5
  61. package/dist/store/sqlite/vectors.js +5 -3
  62. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { annotate, metaOf, sharedCommand } from "@wirecat/cli-base/commands";
3
+ import { timezoneOf } from "@wirecat/cli-base/query";
3
4
  import { Argument, InvalidArgumentError } from "commander";
4
5
  import * as v from "valibot";
5
6
  import { answerEntity } from "../../cli/answer-entity.js";
@@ -7,19 +8,23 @@ import { environmentOf, inCommandRun, outputFor, runBudgetOf } from "../../cli/c
7
8
  import { honoursDryRun } from "../../cli/dry-run-guard.js";
8
9
  import { FETCH, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS, REMOTE_WRITE } from "../../cli/effects.js";
9
10
  import { itemOf, listOf, renderAnswer, snakeKeys, snakeKeysKeeping } from "../../cli/envelope.js";
10
- import { queryTerms, termField, unfilteredQuery, withQuery } from "../../cli/list-query.js";
11
+ import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds, typedQuery, unfilteredQuery, withQuery, } from "../../cli/list-query.js";
11
12
  import { terminalAsker } from "../../cli/messenger/ask.js";
12
13
  import { addStoreMaintenanceCommands } from "../../cli/messenger/store-maintenance-command.js";
13
14
  import { lineOf } from "../../cli/steps.js";
14
- import { CRM_KINDS } from "../../domain/crm.js";
15
+ import { CRM_KINDS, isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
15
16
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
16
17
  import { deal as dealEntity } from "../../entities/deal.js";
17
18
  import { count, text } from "../../entities/fields.js";
19
+ import { dateWindow } from "../../services/moment.js";
18
20
  import { readableAccounts } from "../../services/person-context.js";
19
21
  import { personMeetings } from "../../services/person-meetings.js";
22
+ import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
20
23
  import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
24
+ import { seenBy } from "../../store/store.js";
21
25
  import { openStageTasks } from "../stage-tasks.js";
22
26
  import { crmStatus, syncCrm } from "../sync.js";
27
+ import { shortened, viewerOf } from "../viewer.js";
23
28
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
24
29
  import { csvFormatOption, renderCsv } from "./csv.js";
25
30
  import { pipelineView } from "./pipeline-view.js";
@@ -31,11 +36,19 @@ export { openCrmStore } from "./store.js";
31
36
  const MOST = 500;
32
37
  /** A stage by the store's reference, as memo's `stages list` and a deal's `base_stage` name it. */
33
38
  const STAGE_REF = /^stage:\d+$/;
39
+ const timeField = (name, example, relation) => nativeField({ name, type: "time", operators: ["term", "range"], example, relation });
40
+ const TIME_FIELDS = ["updated", "created", "closed"];
34
41
  const DEAL_FIELDS = [
35
42
  termField("status", "enum", "status:open", { values: DEAL_STATUSES }),
36
43
  termField("stage", "kw", 'stage:"Quote sent"', { relation: "a stage's name, in any letter case" }),
37
44
  termField("pipeline", "kw", "pipeline:Sales", { relation: "pipeline:<id>, or a name only one pipeline has" }),
38
45
  termField("organization", "ref", 'organization:"organization:3"'),
46
+ timeField("updated", "updated:>=1d", "changed in the CRM in this time"),
47
+ timeField("created", "created:>=30d", "made in the CRM in this time"),
48
+ timeField("closed", "closed:>=7d", "won or lost on a day in this time, in your time zone"),
49
+ termField("owner", "kw", "owner:me", {
50
+ relation: "the CRM user it is assigned to: me (the sign-in's own), none, or the CRM's user id",
51
+ }),
39
52
  ];
40
53
  /** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
41
54
  export const DEALS_QUERY = { entity: "deal", backend: "native", fields: DEAL_FIELDS };
@@ -173,6 +186,25 @@ const collect = (value, previous = []) => {
173
186
  throw new InvalidArgumentError("expected key=value");
174
187
  return [...previous, value];
175
188
  };
189
+ /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
190
+ const ownerOf = async (run, owner) => {
191
+ if (owner === "none")
192
+ return null;
193
+ if (owner === "me") {
194
+ const self = run.user ?? (await run.store.crm.ownUser(run.account));
195
+ if (!self)
196
+ throw new CliError("validation_error", "this CRM names no user for the sign-in: use owner:<user id>", {
197
+ reason: "crm.owner-unknown",
198
+ });
199
+ return crmIdentityId(run.account, normalCrmUserId(self), "user");
200
+ }
201
+ if (!isCrmUserId(owner))
202
+ throw new CliError("validation_error", `owner takes me, none or the CRM's user id, not ${owner}`, {
203
+ reason: "crm.owner-unknown",
204
+ });
205
+ return crmIdentityId(run.account, normalCrmUserId(owner), "user");
206
+ };
207
+ /** Whose deals and leads of the copy this profile reads offline; undefined is every one. */
176
208
  /** The words below the program, as `page.next` and `sync`'s next step run it again. */
177
209
  const pathOf = (command) => command.parent?.parent ? [...pathOf(command.parent), command.name()] : [command.name()];
178
210
  /** A CRM's own field codes are its keys, never ours to rename. */
@@ -189,6 +221,11 @@ const addCrmCommandsDefinition = (program, options) => {
189
221
  finally {
190
222
  await run.close?.();
191
223
  }
224
+ const note = shortened.get(run);
225
+ if (note) {
226
+ outputFor(command).renderer.note(note);
227
+ body = { ...body, meta: { ...body.meta, complete: false } };
228
+ }
192
229
  renderAnswer(command, outputFor(command), body, view);
193
230
  });
194
231
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
@@ -267,6 +304,8 @@ const addCrmCommandsDefinition = (program, options) => {
267
304
  example(answerEntity(annotate(store.command("status"), { effects: LOCAL_READ }), "crm_sync_progress", crmSyncProgress).description("how far each kind's sync is: rows saved, partial or complete, when it last moved, how many are stored"), "store status --json").action(async (_opts, command) => {
268
305
  await within(command, async (run) => {
269
306
  const status = await crmStatus(run.store, run.account, { profile: run.profile, now: now() });
307
+ if (await viewerOf(run))
308
+ outputFor(command).renderer.note("stored counts the whole copy, more than the deals and leads you may read");
270
309
  return listOf(pathOf(command).join(" "), {
271
310
  items: status.items,
272
311
  limit: status.limit,
@@ -300,14 +339,26 @@ const addCrmCommandsDefinition = (program, options) => {
300
339
  .option("--limit <n>", `${plural} per page, 1–${MOST}`, integer(MOST), 50)
301
340
  .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1)
302
341
  .addOption(csvFormatOption()), `${plural} list status:open --json`, `${plural} list stage:"Quote sent"`, `${plural} list status:open --format csv > ${plural}.csv`).action(async (words, opts, command) => {
303
- const terms = queryTerms(words, query, `${plural} list`);
304
- const read = (run) => run.store.deals.list({
342
+ const name = `${plural} list`;
343
+ const terms = queryTerms(words, query, name, TIME_FIELDS);
344
+ const times = nativeTerms(listQuery(typedQuery(words), query, name), name);
345
+ const bounds = Object.fromEntries(TIME_FIELDS.map((field) => [field, timeBounds(times.get(field))]));
346
+ const metas = Object.values(bounds).flatMap((one) => (one.meta ? [one.meta] : []));
347
+ const timezone = metas.find((one) => one.timezone)?.timezone;
348
+ // One window names one field's bounds; with two time terms it would name only the first.
349
+ const window = metas.length === 1 ? metas[0] : timezone ? { timezone } : undefined;
350
+ const read = async (run) => run.store.deals.list({
305
351
  kind,
306
352
  account: run.account,
353
+ viewer: await viewerOf(run),
307
354
  ...(terms.has("status") ? { status: terms.get("status") } : {}),
308
355
  ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
309
356
  ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
310
357
  ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
358
+ ...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
359
+ ...(times.has("updated") ? { updated: bounds.updated } : {}),
360
+ ...(times.has("created") ? { created: bounds.created } : {}),
361
+ ...(times.has("closed") ? { closed: bounds.closed, zone: window?.timezone } : {}),
311
362
  limit: Math.min(opts.limit, MOST),
312
363
  offset: (opts.page - 1) * opts.limit,
313
364
  });
@@ -329,6 +380,7 @@ const addCrmCommandsDefinition = (program, options) => {
329
380
  page: opts.page,
330
381
  has_more: found.hasMore,
331
382
  ...(words.length ? { args: { query: words } } : {}),
383
+ ...(window ? { meta: window } : {}),
332
384
  });
333
385
  });
334
386
  });
@@ -338,7 +390,7 @@ const addCrmCommandsDefinition = (program, options) => {
338
390
  "activities and tasks too")
339
391
  .argument(`<${kind}>`, `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
340
392
  await within(command, async (run) => {
341
- const found = await ownCopy(run, kind, reference);
393
+ const found = await readableCopy(run, kind, reference);
342
394
  const activities = found.externalId !== null && (await run.store.crm.activitiesOn(run.account))
343
395
  ? (await run.store.crm.activitiesOf(run.account, kind, found.externalId, SHOWN_ACTIVITIES)).map((one) => ({
344
396
  external_id: one.externalId,
@@ -365,13 +417,17 @@ const addCrmCommandsDefinition = (program, options) => {
365
417
  people: one.people,
366
418
  ...(one.call ? { call: one.call } : {}),
367
419
  }));
420
+ const stageHistory = (await run.store.deals.stages(found.ref)).map(({ pipeline: _, ...entry }) => entry);
368
421
  return itemOf({
369
422
  ...dealKeys(found),
370
423
  meetings,
371
424
  ...(activities ? { activities } : {}),
425
+ stage_history: stageHistory,
372
426
  untrusted: [
373
427
  ...DEAL_UNTRUSTED,
374
428
  "meetings.title",
429
+ "stage_history.from",
430
+ "stage_history.to",
375
431
  ...(activities ? ["activities.subject", "activities.body"] : []),
376
432
  ],
377
433
  });
@@ -390,6 +446,14 @@ const addCrmCommandsDefinition = (program, options) => {
390
446
  throw new CliError("not_found", `${reference} is not a copy from this profile's CRM account`);
391
447
  return found;
392
448
  };
449
+ /** A row this profile may read: one assigned to another user is not found, as another account's is not. */
450
+ const readableCopy = async (run, kind, reference) => {
451
+ const found = await ownCopy(run, kind, reference);
452
+ const viewer = await viewerOf(run);
453
+ if (!seenBy(viewer, { ...run.account, assignee: found.assignee }))
454
+ throw new CliError("not_found", `${reference} is not a copy this profile may read${shortened.has(run) ? `: ${shortened.get(run)}` : ""}`);
455
+ return found;
456
+ };
393
457
  const writes = options.writes;
394
458
  const addWrites = (group, kind) => {
395
459
  if (!writes?.kinds.includes(kind))
@@ -503,6 +567,7 @@ const addCrmCommandsDefinition = (program, options) => {
503
567
  await within(command, async (run) => {
504
568
  const found = await run.store.deals.pipelines({
505
569
  account: run.account,
570
+ viewer: await viewerOf(run),
506
571
  ...(terms.has("kind") ? { kind: terms.get("kind") } : {}),
507
572
  });
508
573
  return listOf(pathOf(command).join(" "), {
@@ -517,10 +582,22 @@ const addCrmCommandsDefinition = (program, options) => {
517
582
  example(annotate(pipelines.command("show"), { effects: LOCAL_READ, output: { entity: "pipeline" } })
518
583
  .description("one pipeline as a board and a funnel: how many stand in each stage and their sum per currency, never " +
519
584
  "converted, how many reached it and went on, and the win rate; won and lost stages are marked by outcome")
520
- .argument("[pipeline]", "pipeline:<id>, or a name only one of the CRM's pipelines has; needed unless the CRM has one pipeline in all"), "pipelines show pipeline:3", "pipelines show Sales --json").action(async (reference, _opts, command) => {
585
+ .argument("[pipeline]", "pipeline:<id>, or a name only one of the CRM's pipelines has; needed unless the CRM has one pipeline in all"), "pipelines show pipeline:3", "pipelines show Sales --since-time 30d --json")
586
+ .option("--since-time <time>", "count the rows made at or after this date or time (ISO 8601, or 30d ago)")
587
+ .option("--until-time <time>", "count the rows made at or before this date or time; a date alone is that whole day")
588
+ .action(async (reference, opts, command) => {
589
+ const zone = timezoneOf();
590
+ const { since, until, meta } = dateWindow({ ...opts, zone, now: now() });
521
591
  await within(command, async (run) => {
522
- const report = await pipelineOf(run, undefined, reference, "pipeline");
523
- return itemOf({ ...snakeKeys(report), untrusted: PIPELINE_UNTRUSTED });
592
+ const report = await pipelineOf(run, undefined, reference, "pipeline", {
593
+ viewer: await viewerOf(run),
594
+ ...(since === undefined ? {} : { since: new Date(since).toISOString() }),
595
+ ...(until === undefined ? {} : { until: new Date(until).toISOString() }),
596
+ zone,
597
+ });
598
+ return itemOf({ ...snakeKeys(report), untrusted: PIPELINE_UNTRUSTED },
599
+ // The closed counts take their days in this zone, whatever the window.
600
+ { meta: { ...meta, timezone: zone } });
524
601
  }, (body) => pipelineView(body, outputFor(command).color));
525
602
  });
526
603
  const stages = annotate(program.command("stages"), { effects: NO_EFFECTS }).description("the stages of the CRM's pipelines, as last synced");
@@ -528,25 +605,32 @@ const addCrmCommandsDefinition = (program, options) => {
528
605
  const terms = queryTerms(words, STAGES_QUERY, "stages list");
529
606
  await within(command, async (run) => {
530
607
  const kind = terms.has("kind") ? terms.get("kind") : undefined;
531
- const all = await run.store.deals.pipelines({ account: run.account, ...(kind ? { kind } : {}) });
608
+ const viewer = await viewerOf(run);
609
+ const all = await run.store.deals.pipelines({ account: run.account, viewer, ...(kind ? { kind } : {}) });
532
610
  const chosen = terms.has("pipeline")
533
611
  ? [
534
612
  await run.store.deals.pipeline(terms.get("pipeline"), {
535
613
  account: run.account,
614
+ viewer,
536
615
  ...(kind ? { kind } : {}),
537
616
  }),
538
617
  ]
539
618
  : all;
540
- const found = chosen.flatMap((pipeline) => pipeline.stages.map(({ name, position, outcome, externalId, open }) => ({
541
- name,
542
- position,
543
- outcome,
544
- externalId,
545
- open,
546
- pipeline: pipeline.ref,
547
- pipelineName: pipeline.name,
548
- kind: pipeline.kind,
549
- })));
619
+ const rules = await run.store.crm.stageTasks(run.account);
620
+ const found = chosen.flatMap((pipeline) => pipeline.stages.map(({ name, position, outcome, externalId, open }) => {
621
+ const rule = externalId === null ? undefined : rules[pipeline.kind][externalId];
622
+ return {
623
+ name,
624
+ position,
625
+ outcome,
626
+ externalId,
627
+ open,
628
+ pipeline: pipeline.ref,
629
+ pipelineName: pipeline.name,
630
+ kind: pipeline.kind,
631
+ stageTask: rule ? { title: rule.title, dueDays: rule.dueDays } : null,
632
+ };
633
+ }));
550
634
  return listOf(pathOf(command).join(" "), {
551
635
  items: marked(found, STAGE_UNTRUSTED),
552
636
  limit: Math.max(1, found.length),
@@ -596,7 +680,7 @@ const addCrmCommandsDefinition = (program, options) => {
596
680
  });
597
681
  const search = program.commands.find((one) => one.name() === "search") ??
598
682
  annotate(program.command("search"), { effects: NO_EFFECTS }).description("search what the local store holds");
599
- addCrmSearchAll(search, { within, app: options.app, example });
683
+ addCrmSearchAll(search, { within, app: options.app, example, viewerOf });
600
684
  };
601
685
  // honoursDryRun: a host program other than `run` would otherwise let a write through under --dry-run.
602
686
  export const addCrmCommands = honoursDryRun(sharedCommand(addCrmCommandsDefinition));
@@ -28,9 +28,23 @@ export const pipelineView = (body, color) => {
28
28
  "went on": percent(stage.conversion),
29
29
  }));
30
30
  const { won, lost, win_rate } = pipeline.totals;
31
+ const { closed, cycle, window, owners = [] } = pipeline;
32
+ // Without a window every closed row is in the totals already.
33
+ const windowed = Boolean(window?.since || window?.until);
34
+ const outcomes = [
35
+ `won: ${won} · lost: ${lost} · win rate ${percent(win_rate)}`,
36
+ ...(closed && windowed
37
+ ? [
38
+ `closed in the window: won ${closed.won} (${sumOf(closed.won_amounts)}) · lost ${closed.lost} · ` +
39
+ `win rate ${percent(closed.win_rate)}`,
40
+ ]
41
+ : []),
42
+ ...(cycle?.median_days == null ? [] : [`days to win: ${cycle.median_days} (median of ${cycle.items})`]),
43
+ ...owners.map((one) => `${one.name ?? one.assignee ?? "no owner"}: ${one.open} open · ${one.won} won · ${one.lost} lost`),
44
+ ];
31
45
  return [
32
46
  `${pipeline.name} (${pipeline.ref})`,
33
47
  renderPretty(rows, { color }),
34
- `${openStages(pipeline.stages)}\nwon: ${won} · lost: ${lost} · win rate ${percent(win_rate)}`,
48
+ `${openStages(pipeline.stages)}\n${outcomes.join("\n")}`,
35
49
  ].join("\n\n");
36
50
  };
@@ -340,6 +340,7 @@ const users = (program, { within, example }) => {
340
340
  const crmRecordWrite = v.strictObject({
341
341
  operation_id: v.string(),
342
342
  stored: v.boolean(),
343
+ removed: v.optional(v.boolean()),
343
344
  person: v.optional(crmPersonSchema),
344
345
  organization: v.optional(crmOrganizationSchema),
345
346
  untrusted,
@@ -356,7 +357,11 @@ const addRecordWrites = (group, noun, { within, example, writes }) => {
356
357
  .option("--first-name <name>", "the first name; empty clears it")
357
358
  .option("--last-name <name>", "the last name; empty clears it")
358
359
  .option("--position <title>", "the job title; empty clears it");
360
+ const repeated = (value, previous = []) => [...previous, value];
359
361
  command
362
+ .option("--email <address>", "an e-mail address to give it; repeat it for more; replaces its list, and an empty one clears it", repeated)
363
+ .option("--phone <phone>", "a phone number to give it, in international form starting with +; repeat it for more; replaces its list, " +
364
+ "and an empty one clears it", repeated)
360
365
  .option("--owner <user>", "the CRM user it is assigned to; anyone but the sign-in's own user checks crm.assign-others")
361
366
  .option("--field <key=value>", "one of the CRM's own fields, by its code or label as `fields list` prints them, and its value; a list " +
362
367
  "field takes its option's label or id; repeat it for more fields, or for each value of a multiple field; " +
@@ -369,8 +374,10 @@ const addRecordWrites = (group, noun, { within, example, writes }) => {
369
374
  command.option("--operation-id <id>", "the operation_id a write that ended in outcome_unknown named: the CRM answers the repeat from its record");
370
375
  return command;
371
376
  };
372
- const inputOf = ({ field, operationId: _id, ...rest }) => ({
377
+ const inputOf = ({ field, email, phone, operationId: _id, ...rest }) => ({
373
378
  ...Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== undefined)),
379
+ ...(email ? { emails: email } : {}),
380
+ ...(phone ? { phones: phone } : {}),
374
381
  ...(field?.length ? { custom: fieldPairsOf(field) } : {}),
375
382
  });
376
383
  const contextOf = (run, command) => {
@@ -385,15 +392,16 @@ const addRecordWrites = (group, noun, { within, example, writes }) => {
385
392
  names: { id: "--operation-id" },
386
393
  };
387
394
  };
388
- const answered = ({ operationId, record, stored }) => itemOf({
395
+ const answered = ({ operationId, record, stored, removed }) => itemOf({
389
396
  operation_id: operationId,
390
397
  stored,
398
+ ...(removed === undefined ? {} : { removed }),
391
399
  [noun.kind]: noun.of(record),
392
400
  untrusted: (person ? PERSON_UNTRUSTED : ORGANIZATION_UNTRUSTED).map((one) => `${noun.kind}.${one}`),
393
401
  });
394
402
  const command = (name, description) => answerEntity(annotate(group.command(name), { effects: REMOTE_WRITE, offline: false }), "crm_record_write", crmRecordWrite).description(description);
395
403
  if (writes.verbs.includes("create"))
396
- example(fields(command("create", `make a ${noun.kind} in the CRM, then store the CRM's copy of it`)), person
404
+ example(fields(command("create", `make ${noun.kind === "organization" ? "an" : "a"} ${noun.kind} in the CRM, then store the CRM's copy of it`)), person
397
405
  ? `${noun.noun} create --first-name Anna --last-name Example --position Buyer`
398
406
  : `${noun.noun} create --name "Example LLC"`).action(async (opts, leaf) => {
399
407
  await within(leaf, async (run) => {
@@ -1,12 +1,15 @@
1
1
  import { Command } from "commander";
2
2
  import type { AppIdentity } from "../../ports/app.js";
3
- import type { CrmWithin } from "./index.js";
3
+ import type { CopyViewer } from "../../store/store.js";
4
+ import type { CrmRun, CrmWithin } from "./index.js";
4
5
  /**
5
6
  * `search all` in a CRM CLI: the shared search over the store, its own deals and leads beside the messages, notes and
6
7
  * events other WireCat tools stored. A locked profile reads only its own account's deals.
7
8
  */
8
- export declare const addCrmSearchAll: (searches: Command, { within, app, example, }: {
9
+ export declare const addCrmSearchAll: (searches: Command, { within, app, example, viewerOf, }: {
9
10
  within: CrmWithin;
10
11
  app: AppIdentity;
11
12
  example: (command: Command, ...lines: string[]) => Command;
13
+ /** This profile's rule over its own account's copy, as the other reads of the copy take it. */
14
+ viewerOf: (run: CrmRun) => Promise<CopyViewer | undefined>;
12
15
  }) => void;
@@ -11,7 +11,8 @@ import { commandAt, rootOf } from "../../cli/steps.js";
11
11
  import { DEAL_KINDS } from "../../domain/deals.js";
12
12
  import { SAVE_HELP } from "../../meetings/index.js";
13
13
  import { meaningLane } from "../../services/messages-meaning.js";
14
- import { searchAll } from "../../services/search-all.js";
14
+ import { crmAccounts, searchAll } from "../../services/search-all.js";
15
+ import { crmViewerOf } from "../viewer.js";
15
16
  /** What a CRM CLI's `search all` reads: its deals and leads first, then what the other tools stored. */
16
17
  const SEARCHED = ["crm", ...SOURCE_SEARCHED];
17
18
  const DEFAULT_LIMIT = 20;
@@ -19,7 +20,7 @@ const DEFAULT_LIMIT = 20;
19
20
  * `search all` in a CRM CLI: the shared search over the store, its own deals and leads beside the messages, notes and
20
21
  * events other WireCat tools stored. A locked profile reads only its own account's deals.
21
22
  */
22
- export const addCrmSearchAll = (searches, { within, app, example, }) => {
23
+ export const addCrmSearchAll = (searches, { within, app, example, viewerOf, }) => {
23
24
  const all = annotate(new Command("all"), { effects: LOCAL_READ, partial: true, output: { entity: "hit" } })
24
25
  .summary("search stored deals and leads, messages, notes, calendar events and meetings")
25
26
  .description("search the CRM's deals and leads by the words of their title, company, contacts and activities, and the " +
@@ -47,6 +48,16 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
47
48
  const limit = opts.limit ?? DEFAULT_LIMIT;
48
49
  const offset = offsetOf(opts.page, limit);
49
50
  const env = run.env ?? process.env;
51
+ const own = await viewerOf(run);
52
+ // A profile limited on its own account reads no other copy; anyone else reads each as its owner's sign-in may.
53
+ const alone = run.locked === true || own !== undefined;
54
+ const others = alone
55
+ ? []
56
+ : (await crmAccounts(run.store)).filter((one) => one.provider !== run.account.provider || one.account !== run.account.account);
57
+ const viewers = [
58
+ ...(own ? [own] : []),
59
+ ...(await Promise.all(others.map(async (one) => (await crmViewerOf(run.store, one, (await run.store.crm.ownUser(one)) ?? null)).viewer))).filter((one) => one !== undefined),
60
+ ];
50
61
  const found = await searchAll(run.store, run.account, {
51
62
  text: words.join(" "),
52
63
  limit,
@@ -57,8 +68,9 @@ export const addCrmSearchAll = (searches, { within, app, example, }) => {
57
68
  only,
58
69
  ...(opts.only?.includes("meetings") ? { meetingsAsked: true } : {}),
59
70
  ...(crmKinds.length < DEAL_KINDS.length ? { crmKinds } : {}),
71
+ ...(viewers.length ? { crmViewers: viewers } : {}),
60
72
  ...(opts.source === undefined ? {} : { source: opts.source }),
61
- ...(run.locked ? { scope: { crm: [run.account] } } : {}),
73
+ ...(alone ? { scope: { crm: [run.account] } } : {}),
62
74
  }, { app, hintCommand: commandAt(rootOf(leaf), "models download") ? app.command : null }, undefined, meaningLane({ env, messenger: { app }, store: async () => run.store }));
63
75
  const note = (text) => outputFor(leaf).renderer.note(text);
64
76
  for (const { why } of denied)
@@ -142,8 +142,9 @@ export interface CrmSource {
142
142
  /**
143
143
  * The kind's entries into a stage that the CRM's own history recorded, oldest first, a page at a time: after the
144
144
  * entry `after` (its `externalId`), or from `since` (epoch ms) without it; the last page's `cursor` is the last entry
145
- * read, or `after` when none came. With it, stage tasks open on each stage entered, one passed between two syncs too.
146
- * Read only while the account has `stage-tasks` rules for the kind.
145
+ * read, or `after` when none came. Read on every sync, 90 days back at first: the funnel and the changes count each
146
+ * stage entered, one passed between two syncs too, and stage tasks open on them. An entry on a deal outside the copy
147
+ * is kept and counts once the deal arrives.
147
148
  */
148
149
  stageHistory?(kind: DealKind, since: number, after?: string, context?: CrmCallContext): Promise<CrmPage<CrmStageEntry>>;
149
150
  }
@@ -12,7 +12,7 @@ export const openStageTasks = async (store, account, now, { history = false } =
12
12
  return 0;
13
13
  const changes = await store.crm.stageMoves(account);
14
14
  // A CRM with a stage history names every stage entered; the copy's own changes miss one passed between two syncs.
15
- const moves = history ? await store.crm.stageEntries(account) : changes.moves;
15
+ const moves = history ? await store.crm.stageEntries(account, now) : changes.moves;
16
16
  // Every deal entering a stage gets the same title, so the duplicate review would pair tasks of different deals.
17
17
  const { reviewDuplicates: _review, ...tasks } = store.tasks;
18
18
  const service = createTaskService({ store: tasks, now: () => new Date(now) });
package/dist/crm/sync.js CHANGED
@@ -6,6 +6,7 @@ import { DEAL_KINDS } from "../domain/deals.js";
6
6
  import { isCliFailure } from "../errors/failures.js";
7
7
  import { crmSettingKey } from "../store/sqlite/crm-settings.js";
8
8
  import { ungroupedHint } from "./group-hint.js";
9
+ import { recordCrmViewer } from "./viewer.js";
9
10
  const DAY = 86_400_000;
10
11
  /** A row the CRM changed this close to the id pass's start may be newer than the list, by the two clocks' skew. */
11
12
  const CLOCK_MARGIN = 60 * 60_000;
@@ -215,23 +216,19 @@ const readActivities = async (run) => {
215
216
  }
216
217
  };
217
218
  const STAGE_HISTORY = "crm:stage-history:";
219
+ /** As far back as activities: the funnel and the changes of the last quarter count exact moves. */
220
+ const HISTORY_DAYS = ACTIVITY_DAYS;
218
221
  /**
219
- * The CRM's own stage history of each kind with `stage-tasks` rules, after the last entry read: the first read goes
220
- * from when stage tasks were last opened, so no entry is missed and none before the rules counts. Without rules the
221
- * history is not read, and its place is dropped, so rules set again later start from then.
222
+ * The CRM's own stage history of each kind, after the last entry read, on every sync: the funnel and the stage
223
+ * tasks count it. A first read goes `HISTORY_DAYS` back.
222
224
  */
223
225
  const readStageHistory = async (run) => {
224
226
  const { source, store, account } = run;
225
227
  if (!source.stageHistory)
226
228
  return null;
227
- const rules = await store.crm.stageTasks(account);
228
- const since = await store.crm.stageTasksSince(account);
229
- for (const kind of DEAL_KINDS) {
229
+ const since = run.now - HISTORY_DAYS * DAY;
230
+ for (const kind of DEAL_KINDS.filter((one) => source.traits.kinds.includes(one))) {
230
231
  const key = `${STAGE_HISTORY}${kind}`;
231
- if (since === null || Object.keys(rules[kind]).length === 0) {
232
- await store.sync.clearSyncState(account, key);
233
- continue;
234
- }
235
232
  let after = (await store.sync.syncState(account, key))?.value;
236
233
  for (;;) {
237
234
  const why = run.budget.take();
@@ -251,6 +248,7 @@ const readStageHistory = async (run) => {
251
248
  return "cancelled";
252
249
  }
253
250
  }
251
+ await store.crm.expireStageEntries(account);
254
252
  return null;
255
253
  };
256
254
  /** Runs a step whose source call may spend the budget mid-way: a spent budget is a stop, not a failure. */
@@ -493,6 +491,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
493
491
  const self = source.self ? normalCrmUserId(await source.self()) : undefined;
494
492
  if (self !== undefined && !isCrmUserId(self))
495
493
  throw new CliError("invalid_response", `${source.provider} named its sign-in's user as "${self}", not a user id`);
494
+ await recordCrmViewer(source, store, account, self);
496
495
  if (self !== undefined) {
497
496
  const owner = await store.crm.ownUser(account);
498
497
  if (owner === undefined)
@@ -631,6 +630,9 @@ export const syncCrm = async (source, store, account, options = {}) => {
631
630
  }
632
631
  // A relationship held back for an end a later page or kind brought is written now; it costs no request.
633
632
  run.droppedPending += (await store.crm.retryPending(account)).dropped;
633
+ // Activities and the stage history name no contact: their stop leaves the rows whole, and their catch-up may take
634
+ // several runs.
635
+ const rowsStopped = stopped;
634
636
  if (!stopped && kinds.some(isItemKind)) {
635
637
  try {
636
638
  stopped = await stopping(() => readActivities(run));
@@ -664,7 +666,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
664
666
  const narrowed = report.synced.some((one) => one.outOfScope > 0);
665
667
  const whole = report.synced.every((one) => one.state === "complete" && one.error === undefined && !one.held && one.pass !== "held");
666
668
  // Contacts have no scope of their own and no deletion check: they leave with the last deal or lead naming them.
667
- if (scope.mode === "mine" && (options.rescan || narrowed) && whole && !stopped && kinds.includes("person"))
669
+ if (scope.mode === "mine" && (options.rescan || narrowed) && whole && !rowsStopped && kinds.includes("person"))
668
670
  report.contactsRemoved = await store.crm.removeContacts(account, { users: scopeIds(scope) ?? [], before: now });
669
671
  if (run.unlistedUsers)
670
672
  report.issues.push({
@@ -117,9 +117,13 @@ export const crmWriteContract = (make) => {
117
117
  for (const kind of ["person", "organization"].filter((one) => writer.capabilities.kinds.includes(one))) {
118
118
  const made = kind === "person"
119
119
  ? await writer.create(kind, { firstName: "Anna", lastName: "Example", emails: ["anna@example.com"] }, operation())
120
- : await writer.create(kind, { name: "Example contract company" }, operation());
120
+ : await writer.create(kind, { name: "Example contract company", phones: ["+34600000003"], emails: ["company@example.com"] }, operation());
121
121
  assert.ok(made.externalId, `${kind}: an id`);
122
122
  assert.ok(made.name, `${kind}: a name`);
123
+ if (kind === "organization") {
124
+ assert.ok((made.phones ?? []).includes("+34600000003"), "organization: its phone");
125
+ assert.ok((made.emails ?? []).includes("company@example.com"), "organization: its e-mail");
126
+ }
123
127
  if (!writer.capabilities.verbs.includes("update"))
124
128
  continue;
125
129
  const changed = kind === "person"
@@ -0,0 +1,28 @@
1
+ import type { CopyViewer, MessageStore } from "../store/store.js";
2
+ import type { AccountKey } from "../store/types.js";
3
+ import type { CrmSource } from "./source.js";
4
+ /**
5
+ * What the sync's sign-in may read of the copy offline, asked while the sync is online anyway. Saved before the copy's
6
+ * owner is checked, so another administrator's refused sync still records it; a failed answer records no.
7
+ */
8
+ export declare const recordCrmViewer: (source: CrmSource, store: MessageStore, account: AccountKey, self: string | undefined) => Promise<void>;
9
+ export interface CrmViewing {
10
+ /** Undefined: the whole copy. */
11
+ viewer: CopyViewer | undefined;
12
+ /** Why the profile sees less than its rule would give it, and what to do; the answer is then incomplete. */
13
+ note?: string;
14
+ }
15
+ /**
16
+ * Whose deals and leads of the copy a profile reads offline (SEC-197): every one when the CRM limits nobody or a sync
17
+ * found `user` its administrator; otherwise, a copy no sync recorded the rule of too, only those assigned to `user`,
18
+ * and none when `user` is unknown. The network is never asked.
19
+ */
20
+ export declare const crmViewerOf: (store: MessageStore, account: AccountKey, user: string | null) => Promise<CrmViewing>;
21
+ /** What a command says beside an answer the viewer rule left short, by the run it read for. */
22
+ export declare const shortened: WeakMap<object, string>;
23
+ /** `crmViewerOf` for one command's run; its note waits in `shortened` for the answer. */
24
+ export declare const viewerOf: (run: {
25
+ store: MessageStore;
26
+ account: AccountKey;
27
+ user: string | null;
28
+ }) => Promise<CopyViewer | undefined>;
@@ -0,0 +1,63 @@
1
+ import { normalCrmUserId } from "../domain/crm.js";
2
+ import { crmIdentityId } from "../store/sqlite/crm-rows.js";
3
+ // A sync state, not a CRM setting: `config set` must never make a profile the administrator.
4
+ const VIEWERS = "crm:viewers";
5
+ const viewersOf = async (store, account) => {
6
+ try {
7
+ const found = JSON.parse((await store.sync.syncState(account, VIEWERS))?.value ?? "null");
8
+ if (!found || typeof found.limited !== "boolean")
9
+ return undefined;
10
+ return { limited: found.limited, admins: typeof found.admins === "object" && found.admins ? found.admins : {} };
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ };
16
+ /**
17
+ * What the sync's sign-in may read of the copy offline, asked while the sync is online anyway. Saved before the copy's
18
+ * owner is checked, so another administrator's refused sync still records it; a failed answer records no.
19
+ */
20
+ export const recordCrmViewer = async (source, store, account, self) => {
21
+ const limited = self !== undefined || source.isAdmin !== undefined;
22
+ const known = await viewersOf(store, account);
23
+ const admins = { ...(known?.admins ?? {}) };
24
+ if (self !== undefined)
25
+ admins[self] = source.isAdmin ? await source.isAdmin().catch(() => false) : false;
26
+ await store.sync.setSyncState(account, VIEWERS, JSON.stringify({ limited, admins }));
27
+ };
28
+ /**
29
+ * Whose deals and leads of the copy a profile reads offline (SEC-197): every one when the CRM limits nobody or a sync
30
+ * found `user` its administrator; otherwise, a copy no sync recorded the rule of too, only those assigned to `user`,
31
+ * and none when `user` is unknown. The network is never asked.
32
+ */
33
+ export const crmViewerOf = async (store, account, user) => {
34
+ const known = await viewersOf(store, account);
35
+ if (known?.limited === false)
36
+ return { viewer: undefined };
37
+ const id = user === null ? undefined : normalCrmUserId(user);
38
+ if (id !== undefined && known?.admins[id] === true)
39
+ return { viewer: undefined };
40
+ if (id === undefined)
41
+ return {
42
+ viewer: { account, assignee: null },
43
+ note: "this profile's sign-in names no CRM user, so offline reads show none of the copy's deals and leads: sign in " +
44
+ "again (session start) so the sign-in keeps its user",
45
+ };
46
+ const viewer = { account, assignee: crmIdentityId(account, id, "user") };
47
+ return known
48
+ ? { viewer }
49
+ : {
50
+ viewer,
51
+ note: "no sync of this version recorded who may read this copy, so offline reads show only your own deals and " +
52
+ "leads: run sync once",
53
+ };
54
+ };
55
+ /** What a command says beside an answer the viewer rule left short, by the run it read for. */
56
+ export const shortened = new WeakMap();
57
+ /** `crmViewerOf` for one command's run; its note waits in `shortened` for the answer. */
58
+ export const viewerOf = async (run) => {
59
+ const { viewer, note } = await crmViewerOf(run.store, run.account, run.user);
60
+ if (note)
61
+ shortened.set(run, note);
62
+ return viewer;
63
+ };
@@ -59,6 +59,9 @@ export interface CrmPersonFields {
59
59
  /** A company's fields; `null` clears one. */
60
60
  export interface CrmOrganizationFields {
61
61
  name?: string;
62
+ /** Each list replaces the CRM's whole list. */
63
+ emails?: string[];
64
+ phones?: string[];
62
65
  owner?: string | null;
63
66
  custom?: Record<string, string | string[] | null>;
64
67
  }