@wirecat/cli-core 0.675.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 (58) hide show
  1. package/CHANGELOG.md +88 -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/setup-command.js +9 -3
  9. package/dist/crm/cli/index.d.ts +7 -1
  10. package/dist/crm/cli/index.js +104 -20
  11. package/dist/crm/cli/pipeline-view.js +15 -1
  12. package/dist/crm/cli/records.js +11 -3
  13. package/dist/crm/cli/search-all.d.ts +5 -2
  14. package/dist/crm/cli/search-all.js +15 -3
  15. package/dist/crm/source.d.ts +3 -2
  16. package/dist/crm/stage-tasks.js +1 -1
  17. package/dist/crm/sync.js +13 -11
  18. package/dist/crm/testing/write-contract.js +5 -1
  19. package/dist/crm/viewer.d.ts +28 -0
  20. package/dist/crm/viewer.js +63 -0
  21. package/dist/crm/writer.d.ts +3 -0
  22. package/dist/crm/writes.d.ts +7 -2
  23. package/dist/crm/writes.js +24 -14
  24. package/dist/domain/crm.d.ts +9 -9
  25. package/dist/domain/moment.d.ts +2 -0
  26. package/dist/domain/moment.js +2 -0
  27. package/dist/entities/business-context.js +1 -1
  28. package/dist/entities/deal.d.ts +86 -39
  29. package/dist/entities/deal.js +45 -4
  30. package/dist/entities/index.d.ts +20 -32
  31. package/dist/errors/reasons.js +1 -0
  32. package/dist/meetings/mcp/index.d.ts +15 -15
  33. package/dist/services/search-all.d.ts +3 -1
  34. package/dist/services/search-all.js +1 -0
  35. package/dist/setup/define.d.ts +17 -2
  36. package/dist/store/exports.d.ts +1 -0
  37. package/dist/store/exports.js +1 -0
  38. package/dist/store/sqlite/copy-viewer.d.ts +16 -0
  39. package/dist/store/sqlite/copy-viewer.js +11 -0
  40. package/dist/store/sqlite/crm-activities.d.ts +7 -1
  41. package/dist/store/sqlite/crm-activities.js +32 -5
  42. package/dist/store/sqlite/crm-contacts.d.ts +5 -2
  43. package/dist/store/sqlite/crm-contacts.js +30 -14
  44. package/dist/store/sqlite/crm-rows.d.ts +7 -0
  45. package/dist/store/sqlite/crm-rows.js +37 -5
  46. package/dist/store/sqlite/crm-settings.d.ts +2 -1
  47. package/dist/store/sqlite/crm-settings.js +3 -2
  48. package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
  49. package/dist/store/sqlite/crm-stage-entries.js +77 -18
  50. package/dist/store/sqlite/crm.d.ts +14 -4
  51. package/dist/store/sqlite/crm.js +59 -7
  52. package/dist/store/sqlite/deals.d.ts +47 -29
  53. package/dist/store/sqlite/deals.js +64 -76
  54. package/dist/store/sqlite/pipeline-period.d.ts +85 -0
  55. package/dist/store/sqlite/pipeline-period.js +199 -0
  56. package/dist/store/sqlite/stage-amounts.d.ts +6 -2
  57. package/dist/store/sqlite/stage-amounts.js +8 -5
  58. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -5,6 +5,94 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.676.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **`pipelines show --since-time <time> --until-time <time>`** answers the funnel over the deals or leads made in the
13
+ window and, beside it, `window`, `closed` (won, lost, win rate and won amounts per currency of the rows closed on a
14
+ day in the window, in your time zone), `cycle` (the median days from made to won), `owners` (the window's rows by
15
+ their CRM assignee), `lost_reasons` (the ten most common) and `history` (how many rows had the CRM's own stage
16
+ history). Each stage gains `median_days`, the median stay before a row moved on. The terminal view adds the closed,
17
+ cycle and owner lines.
18
+ - **`deals list` and `leads list` take `updated:`, `created:`, `closed:` and `owner:`**: `updated:>=1d`,
19
+ `created:>=30d`, `closed:[2026-11-01 TO 2026-11-07]` (the day it was won or lost, in your time zone), `owner:me` (the
20
+ sign-in's user, the `self` setting; refused with `crm.owner-unknown` when the CRM names none), `owner:none` and
21
+ `owner:<user id>`. With a time term the answer's `meta` names the time zone and the window.
22
+ - **`deals show` answers `stage_history`**: every stage the deal entered, oldest first, `exact` when the CRM's own
23
+ history gave it.
24
+ - **`stages list` answers `stage_task`** per stage: the title and `due_days` of the task its `stage-tasks` rule
25
+ opens, or `null`.
26
+ - **`people create|update` and `organizations create|update` take `--email <address>` and `--phone <phone>`**, each
27
+ repeated for more, replacing the record's whole list; an empty value clears it. A phone is taken only in
28
+ international form (`+…`) and sent as E.164; anything else is refused with `crm.record-field`.
29
+ - **The copy keeps more of what the CRM says**: a contact's owner, times, page and custom values, a company's owner
30
+ and times, each change of a deal's or lead's owner, and when an activity was done.
31
+ - **An update that gives one of your contacts or companies to another CRM user removes it from the copy**, with its
32
+ phones, e-mails and the activities on it alone. The answer's `removed` says whether it went: `false` when one of
33
+ your deals still names the contact, or you decided about it.
34
+ - **`pipelines show` answers `meta.timezone`**, the zone of its closed days, and `meta.window` with a window.
35
+ `deals list` with two time terms names only the zone.
36
+ - **A setup flow's check can say what `apply` keeps.** The check's result may carry `keep: { secrets, account }`:
37
+ the value kept for a secret the answers gave (amo keeps its account address beside the token, as its
38
+ `session start` does) and the account the profile is. Left out, `apply` keeps the secrets as typed and the
39
+ profile's name, as before. `keep` is never printed.
40
+
41
+ ### Changed — may break callers
42
+
43
+ - **The CRM's stage history is read on every sync**, 90 days back at first, whatever the `stage-tasks` rules: the
44
+ funnel, `deals.stages` and `deals show` count it (`stageEntriesOf`: the CRM's entries for a row that has any, else the
45
+ copy's own changes). An entry on a deal the copy does not hold yet is kept and counts once the deal arrives. A stage
46
+ task opens for an entry made after the rules were first set (the mark beside the setting keeps that time) and in the
47
+ last 7 days, so a deal the copy missed for a sync still gets its task, and one that joins the copy later opens none
48
+ for its older moves. A handled entry is marked in its fields; an entry no stored deal claimed for 90 days is marked
49
+ deleted.
50
+ - **The copy stores a `crm.person` record per contact and a `crm.owner-change` record per owner change**, and an
51
+ activity's record gains `done_at`. `store.crm.removeContact(key, id)` removes one contact by the CRM's id;
52
+ `CrmRecordWritten` gains `removed`.
53
+ - **`createCrmRecord` and `updateCrmRecord` refuse a phone without `+`** that they passed on before.
54
+ - **`pipelines list`, `stages list` and `pipelines show` leave out a stage the CRM removed** unless a row stands in
55
+ it: a caller that reads stages by position sees fewer.
56
+ - **`deal_context.stages[]` gains `exact`** in its strict schema.
57
+ - **`PipelineReport` gains `window`, `closed`, `cycle`, `owners`, `lost_reasons` and `history`**, and
58
+ `deals.pipeline(ref, options)` takes `since` and `until` as a `YYYY-MM-DD` day or an ISO time and `zone`
59
+ (`PipelineOptions`). `StageChange` gains `exact`; its `from` is `null` for the first entry the CRM's history names.
60
+ - **`CrmActivity.on` takes any `CrmKind`**: an activity on a contact or company the copy holds is stored.
61
+ - **`CrmOrganizationFields` has `emails` and `phones`**: a writer maps them; `crmWriteContract` checks a company's
62
+ phone and e-mail.
63
+ - **`queryTerms` takes the fields its caller reads with `nativeTerms`** as a fourth argument.
64
+ - **`CrmRun.user` is required**: the sign-in's own CRM user, read from its sign-in entry without the network (b24 and
65
+ amo: `signInOf(command).userId`), or `null` when the sign-in names none or the CRM limits nobody. Set it in the
66
+ change that bumps this version. With `null`, a CRM that limits its users shows the profile none of the copy's deals
67
+ and leads offline; a copy no sync of this version recorded shows only the profile's own until its next `sync`. Both
68
+ answers say why in a note and carry `complete: false`. A source with `self()` and no `isAdmin()` counts nobody as
69
+ the administrator: give it `isAdmin()` so its administrator reads the whole copy again.
70
+ - **`owner:me` in `deals list` and `leads list` is the profile's own user** (`CrmRun.user`), and the copy's `self`
71
+ setting only when the CLI passes none.
72
+
73
+ ### Fixed
74
+
75
+ - **The funnel counted a deal first synced already lost in no stage**: such a row now reached the first stage,
76
+ so a fresh copy of a CRM no longer overstates the first stage's conversion. A stage the CRM removed leaves pipelines
77
+ and the funnel unless a row stands in it.
78
+ - **A closed deal's `closed_date` moved with every later edit** when the CRM gives no closed day: the day first
79
+ stored stays, until the deal turns from won to lost or back. A first closed day is your day of the CRM's last edit,
80
+ not the UTC one.
81
+ - **A `YYYY-MM-DD` bound of `deals.pipeline` was a UTC day**: it is now the day in `zone`.
82
+ - **A sync whose activities or stage history stop on the run's budget still removes the contacts outside the scope.**
83
+
84
+ ### Security
85
+
86
+ - **A profile reads offline only its own part of another profile's copy.** The copy is kept per CRM account, so a
87
+ profile signed in as an ordinary user on the same account as the administrator read every deal the administrator
88
+ synced, and `search all` found them by their contacts' e-mails and phones. Now `deals list|show`, `leads list|show`,
89
+ `pipelines list|show`, `stages list` and `search all` show such a profile only the deals and leads assigned to its
90
+ user: another one's, or an unassigned one, is `not_found`, and the reports count only its own. `search all` of such a
91
+ profile reads no other CRM account's copy; anyone else's reads each other copy as that copy's owner may, and one with
92
+ no owner not at all. `store status` says its counts are the whole copy's. The CRM's administrator, as the last `sync`
93
+ of that sign-in found, and a CRM that limits nobody read the whole copy as before. See "Offline reads of the copy" in
94
+ `docs/dev/CRM.md`.
95
+
8
96
  ## 0.675.0 — 16.11.2026
9
97
 
10
98
  ### Fixed
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
24
24
  }
25
25
  export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
26
26
  export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
27
+ action?: undefined;
27
28
  name: string;
28
29
  installed: boolean;
29
30
  active: boolean;
30
31
  servicePath: string;
31
32
  timerPath: string;
32
- action?: undefined;
33
33
  } | {
34
34
  active?: undefined;
35
35
  name: string;
@@ -10,13 +10,13 @@ export declare const calendarTools: ({
10
10
  inputSchema: {
11
11
  type: string;
12
12
  properties: {
13
- limit?: undefined;
14
13
  account_id: {
15
14
  type: string;
16
15
  minimum: number;
17
16
  };
18
17
  query?: undefined;
19
18
  timezone?: undefined;
19
+ limit?: undefined;
20
20
  page?: undefined;
21
21
  event?: undefined;
22
22
  } | {
@@ -45,9 +45,9 @@ export declare const calendarTools: ({
45
45
  };
46
46
  event?: undefined;
47
47
  } | {
48
- limit?: undefined;
49
48
  query?: undefined;
50
49
  timezone?: undefined;
50
+ limit?: undefined;
51
51
  page?: undefined;
52
52
  event: {
53
53
  type: string;
@@ -58,9 +58,9 @@ export declare const calendarTools: ({
58
58
  minimum: number;
59
59
  };
60
60
  } | {
61
- limit?: undefined;
62
61
  query?: undefined;
63
62
  timezone?: undefined;
63
+ limit?: undefined;
64
64
  page?: undefined;
65
65
  event?: undefined;
66
66
  account_id?: undefined;
@@ -80,13 +80,13 @@ export declare const calendarTools: ({
80
80
  inputSchema: {
81
81
  type: string;
82
82
  properties: {
83
- limit?: undefined;
84
83
  account_id: {
85
84
  type: string;
86
85
  minimum: number;
87
86
  };
88
87
  query?: undefined;
89
88
  timezone?: undefined;
89
+ limit?: undefined;
90
90
  page?: undefined;
91
91
  event?: undefined;
92
92
  } | {
@@ -115,9 +115,9 @@ export declare const calendarTools: ({
115
115
  };
116
116
  event?: undefined;
117
117
  } | {
118
- limit?: undefined;
119
118
  query?: undefined;
120
119
  timezone?: undefined;
120
+ limit?: undefined;
121
121
  page?: undefined;
122
122
  event: {
123
123
  type: string;
@@ -128,9 +128,9 @@ export declare const calendarTools: ({
128
128
  minimum: number;
129
129
  };
130
130
  } | {
131
- limit?: undefined;
132
131
  query?: undefined;
133
132
  timezone?: undefined;
133
+ limit?: undefined;
134
134
  page?: undefined;
135
135
  event?: undefined;
136
136
  account_id?: undefined;
@@ -150,13 +150,13 @@ export declare const calendarTools: ({
150
150
  inputSchema: {
151
151
  type: string;
152
152
  properties: {
153
- limit?: undefined;
154
153
  account_id: {
155
154
  type: string;
156
155
  minimum: number;
157
156
  };
158
157
  query?: undefined;
159
158
  timezone?: undefined;
159
+ limit?: undefined;
160
160
  page?: undefined;
161
161
  event?: undefined;
162
162
  } | {
@@ -185,9 +185,9 @@ export declare const calendarTools: ({
185
185
  };
186
186
  event?: undefined;
187
187
  } | {
188
- limit?: undefined;
189
188
  query?: undefined;
190
189
  timezone?: undefined;
190
+ limit?: undefined;
191
191
  page?: undefined;
192
192
  event: {
193
193
  type: string;
@@ -198,9 +198,9 @@ export declare const calendarTools: ({
198
198
  minimum: number;
199
199
  };
200
200
  } | {
201
- limit?: undefined;
202
201
  query?: undefined;
203
202
  timezone?: undefined;
203
+ limit?: undefined;
204
204
  page?: undefined;
205
205
  event?: undefined;
206
206
  account_id?: undefined;
@@ -220,13 +220,13 @@ export declare const calendarTools: ({
220
220
  inputSchema: {
221
221
  type: string;
222
222
  properties: {
223
- limit?: undefined;
224
223
  account_id: {
225
224
  type: string;
226
225
  minimum: number;
227
226
  };
228
227
  query?: undefined;
229
228
  timezone?: undefined;
229
+ limit?: undefined;
230
230
  page?: undefined;
231
231
  event?: undefined;
232
232
  } | {
@@ -255,9 +255,9 @@ export declare const calendarTools: ({
255
255
  };
256
256
  event?: undefined;
257
257
  } | {
258
- limit?: undefined;
259
258
  query?: undefined;
260
259
  timezone?: undefined;
260
+ limit?: undefined;
261
261
  page?: undefined;
262
262
  event: {
263
263
  type: string;
@@ -268,9 +268,9 @@ export declare const calendarTools: ({
268
268
  minimum: number;
269
269
  };
270
270
  } | {
271
- limit?: undefined;
272
271
  query?: undefined;
273
272
  timezone?: undefined;
273
+ limit?: undefined;
274
274
  page?: undefined;
275
275
  event?: undefined;
276
276
  account_id?: undefined;
@@ -56,9 +56,9 @@ export interface CopyAge {
56
56
  }
57
57
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
58
58
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
59
+ next?: undefined;
59
60
  readonly missing?: undefined;
60
61
  meta?: undefined;
61
- next?: undefined;
62
62
  } | {
63
63
  missing: {
64
64
  field: string;
@@ -45,7 +45,7 @@ export { withoutPhone } from "../services/people.js";
45
45
  export { unanswered } from "../services/questions.js";
46
46
  export { openRequestTask } from "../services/task-rules.js";
47
47
  export { TASK_PAIR_QUERY, TASK_QUERY } from "../services/tasks.js";
48
- export { defineSetup, type Setup, type SetupCheck, type SetupCheckInput, type SetupDefinition, setupProblems, } from "../setup/define.js";
48
+ export { defineSetup, type Setup, type SetupCheck, type SetupCheckInput, type SetupDefinition, type SetupKeep, setupProblems, } from "../setup/define.js";
49
49
  export { type Asset as SetupAsset, BLOCK_ROLES, BLOCK_TYPES, type Block as SetupBlock, BUILT_IN_ACTIONS, type Condition as SetupCondition, DISPLAY_CLASSES, INPUT_KINDS, SETUP_FORMAT, SETUP_LIMITS, SETUP_PATTERNS, SETUP_VERSION, type SetupDocument, type Step as SetupStep, setupDocumentSchema, setupJsonSchema, } from "../setup/document.js";
50
50
  export { answerStdinOption, type Need, type SignInSteps, type SignInStepsOptions, signInSteps, } from "../terminal/sign-in-steps.js";
51
51
  export { type AccountRemoval, type AccountRemovalContext, type AccountRemoveOptions, type AccountSecrets, accountRemoveCommand, mayRevoke, type SignedOut, } from "./account-remove.js";
@@ -51,9 +51,10 @@ export declare const nativeTerms: (ast: QueryAst | undefined, command: string) =
51
51
  export declare const nativeTermLists: (ast: QueryAst | undefined, command: string, repeatable?: readonly string[], negatable?: readonly string[]) => Map<string, Predicate[]>;
52
52
  /**
53
53
  * A store that compares whole values: each field's `field:value` or `field:"two words"`, enum values lowercased
54
- * as validation already accepts them. A range or wildcard is refused rather than read as a value.
54
+ * as validation already accepts them. A range or wildcard is refused rather than read as a value. `ranged` are fields
55
+ * the caller reads itself, with `nativeTerms`: they are left out.
55
56
  */
56
- export declare const queryTerms: (words: QueryWords, registry: QueryRegistry, command: string) => Map<string, string>;
57
+ export declare const queryTerms: (words: QueryWords, registry: QueryRegistry, command: string, ranged?: readonly string[]) => Map<string, string>;
57
58
  /**
58
59
  * A `time` term as epoch ms bounds: `time>=7d`, `time:[2026-10-01 TO 2026-10-07]`, `time:today`, and the `meta`
59
60
  * an answer reports them by: the zone calendar words and bare dates were read in, and the bounds in UTC.
@@ -147,11 +147,14 @@ export const nativeTermLists = (ast, command, repeatable = [], negatable = []) =
147
147
  };
148
148
  /**
149
149
  * A store that compares whole values: each field's `field:value` or `field:"two words"`, enum values lowercased
150
- * as validation already accepts them. A range or wildcard is refused rather than read as a value.
150
+ * as validation already accepts them. A range or wildcard is refused rather than read as a value. `ranged` are fields
151
+ * the caller reads itself, with `nativeTerms`: they are left out.
151
152
  */
152
- export const queryTerms = (words, registry, command) => {
153
+ export const queryTerms = (words, registry, command, ranged = []) => {
153
154
  const terms = new Map();
154
155
  for (const [field, node] of nativeTerms(listQuery(typedQuery(words), registry, command), command)) {
156
+ if (ranged.includes(field))
157
+ continue;
155
158
  if (node.operator !== "term" && node.operator !== "phrase")
156
159
  queryError("query.unsupported-placement", node.span, `${field} takes one whole value here`, {
157
160
  command,
@@ -134,7 +134,7 @@ export const setupCommand = (setup) => {
134
134
  for (const [setting, value] of Object.entries(path.settings))
135
135
  refuseGuardedKey(setting, String(value), ownerOnly);
136
136
  steps.progress("check", `checking ${profile}'s settings`);
137
- const checked = (await check?.({
137
+ const { keep = {}, ...checked } = (await check?.({
138
138
  command,
139
139
  profile,
140
140
  settings: { ...settings, configured: { ...settings.configured, ...path.settings } },
@@ -142,11 +142,17 @@ export const setupCommand = (setup) => {
142
142
  answers: path.kept,
143
143
  steps,
144
144
  })) ?? {};
145
+ const secrets = { ...path.secrets };
146
+ for (const [name, secret] of Object.entries(keep.secrets ?? {})) {
147
+ if (!(name in secrets))
148
+ throw new Error(`the flow's check keeps secret ${name}, which the answers did not give`);
149
+ secrets[name] = secret;
150
+ }
145
151
  for (const [setting, value] of Object.entries(path.settings))
146
152
  configuration.changeSetting(settings.configPath, { profile, setting, value: JSON.stringify(value) });
147
153
  const store = storeFor(command, context.renderer.warn);
148
- const kept = Object.entries(path.secrets).map(([name, secret]) => name === "token" ? store.write(profile, secret) : store.writeSecret(profile, name, secret));
149
- rememberAccount(app, profile, profile, env);
154
+ const kept = Object.entries(secrets).map(([name, secret]) => name === "token" ? store.write(profile, secret) : store.writeSecret(profile, name, secret));
155
+ rememberAccount(app, profile, keep.account ?? profile, env);
150
156
  return {
151
157
  outcome: "ok",
152
158
  ...told,
@@ -1,7 +1,7 @@
1
1
  import { type Command } from "commander";
2
2
  import { type Body } from "../../cli/envelope.js";
3
3
  import type { AppIdentity } from "../../ports/app.js";
4
- import type { MessageStore } from "../../store/store.js";
4
+ import { type MessageStore } from "../../store/store.js";
5
5
  import type { AccountKey } from "../../store/types.js";
6
6
  import type { CrmSource } from "../source.js";
7
7
  import type { CrmWriteCapabilities } from "../writer.js";
@@ -22,6 +22,12 @@ export interface CrmRun {
22
22
  store: MessageStore;
23
23
  /** The CRM, built on first use: a command that only reads the store never reads the sign-in. */
24
24
  source: () => CrmSource;
25
+ /**
26
+ * The sign-in's own user id in the CRM, as the sign-in entry keeps it, read without the network. The copy's deals
27
+ * and leads read offline are only this user's unless a sync found it the CRM's administrator; `null`, a CRM that
28
+ * limits its users shows none of them (SEC-197). A CRM that limits nobody passes `null`.
29
+ */
30
+ user: string | null;
25
31
  /** A profile lock pins the process (WC-ACCT-5): `search all` then reads only this account's deals. */
26
32
  locked?: boolean;
27
33
  /** The CRM's writer and the profile's levels, built on first use; needed by every write command. */
@@ -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
  };