@wirecat/cli-core 0.645.0 → 0.647.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,42 @@ 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.647.0 — 12.11.2026
9
+
10
+ ### Added
11
+
12
+ - **A CRM's activities and tasks, read by sync and listed by `show`.** `CrmSource.activities(since, page, context)`
13
+ (optional) gives the calls, e-mails, meetings, to-dos, tasks and comments on deals and leads changed since a time;
14
+ `sync` reads them after the deals and leads when the owner-only setting `crm.<provider>:<account>.activities` is
15
+ `on` (off by default), from 90 days back on the first run, and stores each as a `crm.activity` record bound to the
16
+ kept deals and leads it names; one on none of them is not stored. `deals show` and `leads show` add `activities`,
17
+ open ones first, at most 20. The sync answer adds `activities: { saved, out_of_scope, state }`; a source refusal is
18
+ a gap of kind `activities`. `CrmActivity`, `CrmActivityKind` and `CRM_ACTIVITY_KINDS` are exported. No migration.
19
+
20
+ ### Fixed
21
+
22
+ - **`doctor reports` declares that it has no effects.** A CLI whose test demands effects on every group no longer
23
+ needs its own override for it (zoom, drive).
24
+ - **A command that runs itself beside its subcommands keeps its help lines.** `doctor` (and `commands`) lost Returns
25
+ and Example in `--help` and `docs/commands.md` once `doctor reports` was added; both lists now include it.
26
+ - **`doctor reports show` and `create` say what they return.** Returns no longer repeats the one-line description.
27
+ - **Parity: `pnpm generate` breaks the downstream check when it fails.** The tests read the contracts it writes, so a
28
+ failed generate showed up as a misleading test failure; only `docs:check` still warns.
29
+ - **`bin/release --app-ref <branch>` builds an app without that branch on its main** and says so in a warning,
30
+ instead of failing the release for an app that needed no adoption.
31
+
32
+ ## 0.646.0 — 12.11.2026
33
+
34
+ ### Added
35
+
36
+ - **`decideLink` answers a match whose two people are a company's mailboxes.** `organization: { organization?, name?,
37
+ all? }` with `confirm: false` gives every address of the match's identities to one organization (the one named, else
38
+ one holding an address or the company domain, else one of `name`, else a new company named after the people's
39
+ shared name or the domain; free mail needs a name). A person who is only those addresses becomes the company's and
40
+ is listed as an organization; one who holds more keeps the rest and stays a person. The match closes, `all` closes
41
+ every match on those addresses, and the result names `organization`, `mailboxes`, `people` and `closed`. No
42
+ migration.
43
+
8
44
  ## 0.645.0 — 12.11.2026
9
45
 
10
46
  ### Added
@@ -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;
@@ -179,9 +179,10 @@ const INCLUDES = [
179
179
  const EXCLUDES = ["what the tool reads or writes", "names", "e-mail addresses", "phone numbers", "the sign-in"];
180
180
  /** `doctor reports`: one file for the author, as a messenger's `doctor reports` writes it, without the send journal. */
181
181
  const reportsCommand = (app, configuration, options) => {
182
- const reports = new Command("reports").description("problem reports");
182
+ const reports = annotate(new Command("reports"), { effects: NO_EFFECTS }).description("problem reports");
183
183
  annotate(reports.command("show"), { effects: NO_EFFECTS, examples: [`${app.command} doctor reports show`] })
184
184
  .description("what a problem report holds; writes nothing")
185
+ .summary("what a report holds and never holds, and where to send it; writes nothing")
185
186
  .action(function () {
186
187
  const create = lineOf(this, "doctor reports create");
187
188
  renderAnswer(this, outputFor(this), itemOf({ includes: INCLUDES, excludes: EXCLUDES, ...(app.issues ? { send_to: app.issues } : {}) }, { next: [nextStep("doctor.report-create", { args: {} })] }), () => [
@@ -201,6 +202,7 @@ const reportsCommand = (app, configuration, options) => {
201
202
  examples: [`${app.command} doctor reports create --output ./problem-report.json`],
202
203
  }))
203
204
  .description("write a problem report to a file, and say where to send it")
205
+ .summary("the report file written: its path, the run it is about, and where to send it")
204
206
  .option("--run <id>", "the run the report is about; the newest failed one if not given")
205
207
  .option("--output <file>", "where to write it; a new file in this directory if not given")
206
208
  .action(function () {
@@ -86,9 +86,11 @@ export const nextUsually = (command, choice) => {
86
86
  return command;
87
87
  };
88
88
  const kindOfArgument = (argument) => ARGUMENT_KINDS[argument.name()];
89
+ /** A group like `doctor` that also runs on its own: its help and docs keep their own lines beside its subcommands'. */
90
+ const runsItself = (command) => command._actionHandler != null;
89
91
  const leaves = (command) => command.commands
90
92
  .filter((child) => !child._hidden)
91
- .flatMap((child) => (child.commands.length === 0 ? [child] : leaves(child)));
93
+ .flatMap((child) => child.commands.length === 0 ? [child] : [...(runsItself(child) ? [child] : []), ...leaves(child)]);
92
94
  const rootOf = (command) => {
93
95
  let at = command;
94
96
  while (at.parent)
@@ -228,7 +230,7 @@ export const commandHelpText = (command) => {
228
230
  /** The same, as Markdown lines for `docs/commands.md`: hand it to cli-base's `commandsPage` per command. */
229
231
  export const commandHelpMarkdown = (root, path) => {
230
232
  const command = commandAt(root, path.join(" "));
231
- if (!command || command.commands.length > 0)
233
+ if (!command || (command.commands.length > 0 && !runsItself(command)))
232
234
  return [];
233
235
  const { returns, next, examples } = commandHelp(command);
234
236
  const code = (values) => values.map((value) => `\`${value}\``).join(", ");
@@ -86,12 +86,13 @@ const INCLUDES = [
86
86
  const EXCLUDES = ["message text", "chat titles", "names", "phone numbers", "the session", "the app credentials"];
87
87
  const reportCommand = (messenger) => {
88
88
  const { app } = messenger;
89
- const report = new Command("reports").description("problem reports");
89
+ const report = annotate(new Command("reports"), { effects: NO_EFFECTS }).description("problem reports");
90
90
  annotate(report.command("show"), {
91
91
  effects: NO_EFFECTS,
92
92
  examples: [`${app.command} doctor reports show`],
93
93
  })
94
94
  .description("what a problem report holds; writes nothing")
95
+ .summary("what a report holds and never holds, and where to send it; writes nothing")
95
96
  .action(function () {
96
97
  const output = outputFor(this);
97
98
  const create = lineOf(this, "doctor reports create");
@@ -112,6 +113,7 @@ const reportCommand = (messenger) => {
112
113
  examples: [`${app.command} personal doctor reports create --output ./problem-report.json`],
113
114
  }))
114
115
  .description("write a problem report to a file, and say where to send it")
116
+ .summary("the report file written: its path, the run it is about, and where to send it")
115
117
  .option("--run <id>", "the run the report is about; the newest failed one if not given")
116
118
  .option("--output <file>", "where to write it; a new file in this directory if not given")
117
119
  .action(async function () {
@@ -8,8 +8,8 @@ export declare const STORE_SETTINGS: string[];
8
8
  export declare const storeSettingsOf: (app: Pick<AppIdentity, "messenger">) => string[];
9
9
  export declare const offersStoreSetting: (app: Pick<AppIdentity, "messenger">, setting: string) => boolean;
10
10
  /**
11
- * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
12
- * changing them by mistake.
11
+ * Whose deals a CRM copy holds, what opens the owner's tasks and whether clients' activities are copied: the owner's
12
+ * to set; an agent's run is stopped from changing them by mistake.
13
13
  */
14
14
  export declare const isOwnerOnlyStoreSetting: (setting: string) => boolean;
15
15
  export declare const isStoreSetting: (setting: string) => boolean;
@@ -34,9 +34,9 @@ export const STORE_SETTINGS = [
34
34
  const GROUP_PREFIX = `${ACCOUNT_GROUPS_SETTING}.`;
35
35
  /**
36
36
  * A CRM account's: whether what it reports is a relationship or waits for review, what its company types mean, whose
37
- * deals and leads its sync copies, and which stages open a task.
37
+ * deals and leads its sync copies, which stages open a task, and whether activities and tasks are read.
38
38
  */
39
- const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"].map((name) => `crm.<provider>:<account>.${name}`);
39
+ const CRM_SETTINGS = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"].map((name) => `crm.<provider>:<account>.${name}`);
40
40
  /**
41
41
  * The store settings a CLI offers. Phone countries, task rules and account groups belong to messages; a CLI that is
42
42
  * not a messenger would change them for tg and MAX without reading them itself.
@@ -46,12 +46,12 @@ export const storeSettingsOf = (app) => app.messenger === false
46
46
  : [...STORE_SETTINGS, `${GROUP_PREFIX}<name>`, ...CRM_SETTINGS];
47
47
  export const offersStoreSetting = (app, setting) => app.messenger !== false || setting in SCRIPTS || setting === OWNER_LANGUAGES || parseCrmSetting(setting) !== undefined;
48
48
  /**
49
- * Whose deals a CRM copy holds and what opens the owner's tasks: the owner's to set; an agent's run is stopped from
50
- * changing them by mistake.
49
+ * Whose deals a CRM copy holds, what opens the owner's tasks and whether clients' activities are copied: the owner's
50
+ * to set; an agent's run is stopped from changing them by mistake.
51
51
  */
52
52
  export const isOwnerOnlyStoreSetting = (setting) => {
53
53
  const name = parseCrmSetting(setting)?.name;
54
- return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks";
54
+ return name === "scope" || name === "self" || name === "unassigned" || name === "stage-tasks" || name === "activities";
55
55
  };
56
56
  export const isStoreSetting = (setting) => setting in SCRIPTS ||
57
57
  setting === OWNER_LANGUAGES ||
@@ -276,6 +276,7 @@ const CRM_DEFAULTS = {
276
276
  unassigned: [],
277
277
  self: "",
278
278
  "stage-tasks": {},
279
+ activities: "off",
279
280
  };
280
281
  const crmNote = (name, now) => {
281
282
  if (name === "links")
@@ -289,6 +290,11 @@ const crmNote = (name, now) => {
289
290
  "of the unassigned users, and marks the others deleted here; contacts and companies stay whole";
290
291
  if (name === "unassigned")
291
292
  return "store-wide — with scope mine, the next sync also copies the deals and leads of these users";
293
+ if (name === "activities")
294
+ return now === "on"
295
+ ? "store-wide — the next sync also reads the activities and tasks on the deals and leads it keeps, from the " +
296
+ "last 90 days on its first run; `deals show` lists them"
297
+ : "store-wide — no activity or task is read; those already stored stay";
292
298
  if (name === "stage-tasks")
293
299
  return Object.keys(now).length === 0
294
300
  ? "store-wide — no stage opens a task"
@@ -61,6 +61,8 @@ const DEAL_UNTRUSTED = [
61
61
  "people.name",
62
62
  "provider_metadata",
63
63
  ];
64
+ /** `show` lists this many of a deal's activities: the open ones come first, so a long history does not hide them. */
65
+ const SHOWN_ACTIVITIES = 20;
64
66
  const PIPELINE_UNTRUSTED = ["name", "stages.name"];
65
67
  const STAGE_UNTRUSTED = ["name", "pipeline_name"];
66
68
  const crmContactsRemoved = v.strictObject({
@@ -82,6 +84,7 @@ const crmSync = v.strictObject({
82
84
  skipped_owner_rejected: count,
83
85
  contacts_removed: v.optional(crmContactsRemoved),
84
86
  stage_tasks: count,
87
+ activities: v.optional(v.strictObject({ saved: count, out_of_scope: count, state: v.picklist(["partial", "complete"]) })),
85
88
  synced: v.array(v.strictObject({
86
89
  kind: v.picklist(CRM_KINDS),
87
90
  round: v.picklist(["full", "changes"]),
@@ -190,8 +193,9 @@ const addCrmCommandsDefinition = (program, options) => {
190
193
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
191
194
  example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync).description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
192
195
  "changed since the last sync, or everything with --rescan; a run stops before its deadline or --max-pages " +
193
- "and the next one goes on from there. Then each deal or lead that moved into a stage the stage-tasks setting " +
194
- "names opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
196
+ "and the next one goes on from there. With the activities setting on, also the activities and tasks on the " +
197
+ "deals and leads it keeps. Then each deal or lead that moved into a stage the stage-tasks setting names " +
198
+ "opens a local task, once per move"), "sync", "sync --rescan", "sync --max-pages 20")
195
199
  .option("--rescan", "list everything again, every id too, dropping a round in progress")
196
200
  .option("--max-pages <pages>", "at most this many requests to the CRM in this run", integer(100_000))
197
201
  .action(async (opts, command) => {
@@ -323,11 +327,29 @@ const addCrmCommandsDefinition = (program, options) => {
323
327
  });
324
328
  });
325
329
  example(annotate(group.command("show"), { effects: LOCAL_READ, output: { entity: kind } })
326
- .description(`one ${kind} with its pipeline, stage, status, amount and the people on it`)
330
+ .description(`one ${kind} with its pipeline, stage, status, amount and the people on it; with the activities setting ` +
331
+ "on, its activities and tasks too")
327
332
  .argument(`<${kind}>`, `${kind}:<id>, as a list shows it`), `${plural} show ${kind}:12`).action(async (reference, _opts, command) => {
328
333
  await within(command, async (run) => {
329
334
  const found = await ownCopy(run, kind, reference);
330
- return itemOf({ ...dealKeys(found), untrusted: DEAL_UNTRUSTED });
335
+ const activities = found.externalId !== null && (await run.store.crm.activitiesOn(run.account))
336
+ ? (await run.store.crm.activitiesOf(run.account, kind, found.externalId, SHOWN_ACTIVITIES)).map((one) => ({
337
+ external_id: one.externalId,
338
+ kind: one.kind,
339
+ subject: one.subject,
340
+ body: one.body,
341
+ due_at: one.dueAt === null ? null : new Date(one.dueAt).toISOString(),
342
+ done: one.done,
343
+ assignee: one.assignee,
344
+ created_at: new Date(one.createdAt).toISOString(),
345
+ updated_at: new Date(one.updatedAt).toISOString(),
346
+ }))
347
+ : undefined;
348
+ return itemOf({
349
+ ...dealKeys(found),
350
+ ...(activities ? { activities } : {}),
351
+ untrusted: activities ? [...DEAL_UNTRUSTED, "activities.subject", "activities.body"] : DEAL_UNTRUSTED,
352
+ });
331
353
  });
332
354
  });
333
355
  addWrites(group, kind);
@@ -1,4 +1,4 @@
1
- import type { CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmUser } from "../domain/crm.js";
1
+ import type { CrmActivity, 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. */
@@ -34,7 +34,7 @@ export interface CrmIdPage {
34
34
  * said it could not read.
35
35
  */
36
36
  export interface CrmGap {
37
- kind: CrmKind | "users" | "departments";
37
+ kind: CrmKind | "users" | "departments" | "activities";
38
38
  reason: "not-listed" | "refused" | "partial";
39
39
  code?: string;
40
40
  scope?: string;
@@ -96,4 +96,10 @@ export interface CrmSource {
96
96
  users?(context?: CrmCallContext): Promise<CrmUser[]>;
97
97
  /** Every department; left out, reporting lines are unknown and none stored is withdrawn. */
98
98
  departments?(context?: CrmCallContext): Promise<CrmDepartment[]>;
99
+ /**
100
+ * Activities and tasks on deals and leads changed after `since` (epoch ms), a page at a time; the last page's `cursor`
101
+ * is the time the next sync reads after. Read only when the account's `activities` setting is on; a CRM without
102
+ * them leaves it out. A list the sign-in may not read is a `gap`, and the others are still read.
103
+ */
104
+ activities?(since: number, page?: string, context?: CrmCallContext): Promise<CrmPage<CrmActivity>>;
99
105
  }
@@ -50,7 +50,7 @@ export interface CrmSyncOptions {
50
50
  export interface CrmSyncIssue {
51
51
  /** `user`: the account's users and departments. */
52
52
  kind: CrmKind | "user";
53
- reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped";
53
+ reason: CrmSkipped["reason"] | CrmRelationIssue["reason"] | "crm.unlisted-held" | "crm.narrowing-held" | "crm.unassigned-dropped" | "crm.not-reported" | "crm.pending-dropped" | "crm.activities-failed";
54
54
  message: string;
55
55
  externalId?: string;
56
56
  }
@@ -103,6 +103,12 @@ export interface CrmSyncReport {
103
103
  /** Pages saved: 0 means this run moved nothing on. */
104
104
  steps: number;
105
105
  };
106
+ /** With the `activities` setting on: what this run read of the activities and tasks on kept deals and leads. */
107
+ activities?: {
108
+ saved: number;
109
+ outOfScope: number;
110
+ state: "partial" | "complete";
111
+ };
106
112
  hint?: string;
107
113
  /**
108
114
  * 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
package/dist/crm/sync.js CHANGED
@@ -156,6 +156,64 @@ const readUsers = async (run) => {
156
156
  run.report.users = users.length;
157
157
  return null;
158
158
  };
159
+ const ACTIVITIES = "crm:activities";
160
+ /** A first read goes this far back: older calls and e-mails rarely matter, and a busy portal holds years of them. */
161
+ const ACTIVITY_DAYS = 90;
162
+ const activityCursor = (value) => {
163
+ try {
164
+ const parsed = value === undefined ? undefined : JSON.parse(value);
165
+ return typeof parsed?.since === "number" ? parsed : undefined;
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ };
171
+ /**
172
+ * Activities and tasks changed since the last read, after every deal and lead of the run is stored: each is kept only
173
+ * on the deals and leads this copy holds. Pages go on from where a stopped run left them.
174
+ */
175
+ const readActivities = async (run) => {
176
+ const { source, store, account } = run;
177
+ if (!source.activities || !(await store.crm.activitiesOn(account)))
178
+ return null;
179
+ const read = { saved: 0, outOfScope: 0, state: "partial" };
180
+ run.report.activities = read;
181
+ const saved = activityCursor((await store.sync.syncState(account, ACTIVITIES))?.value);
182
+ const cursor = saved ?? { since: run.now - ACTIVITY_DAYS * DAY, newest: 0 };
183
+ for (;;) {
184
+ const why = run.budget.take();
185
+ if (why)
186
+ return why;
187
+ let page;
188
+ try {
189
+ page = await source.activities.call(source, cursor.since, cursor.page, run.context);
190
+ }
191
+ catch (error) {
192
+ if (run.signal?.aborted || error instanceof BudgetSpent)
193
+ throw error;
194
+ if (!scopeOf(error))
195
+ throw error;
196
+ run.gaps.push(refusal("activities", "no activity or task was read", error, source.provider));
197
+ return null;
198
+ }
199
+ const done = await store.crm.saveActivities(account, page.items);
200
+ read.saved += done.saved;
201
+ read.outOfScope += done.outOfScope;
202
+ cursor.newest = Math.max(cursor.newest, ...page.items.map((one) => one.updatedAt));
203
+ run.moved();
204
+ if (page.hasMore && page.nextCursor !== undefined) {
205
+ cursor.page = page.nextCursor;
206
+ await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify(cursor));
207
+ if (run.signal?.aborted)
208
+ return "cancelled";
209
+ continue;
210
+ }
211
+ const next = page.cursor != null ? Number(page.cursor) : cursor.newest || cursor.since;
212
+ await store.sync.setSyncState(account, ACTIVITIES, JSON.stringify({ since: next, newest: 0 }));
213
+ read.state = "complete";
214
+ return null;
215
+ }
216
+ };
159
217
  /** Runs a step whose source call may spend the budget mid-way: a spent budget is a stop, not a failure. */
160
218
  const stopping = async (step) => {
161
219
  try {
@@ -528,6 +586,21 @@ export const syncCrm = async (source, store, account, options = {}) => {
528
586
  }
529
587
  // A relationship held back for an end a later page or kind brought is written now; it costs no request.
530
588
  run.droppedPending += (await store.crm.retryPending(account)).dropped;
589
+ if (!stopped && kinds.some(isItemKind)) {
590
+ try {
591
+ stopped = await stopping(() => readActivities(run));
592
+ }
593
+ catch (error) {
594
+ if (options.signal?.aborted)
595
+ stopped = "cancelled";
596
+ else
597
+ report.issues.push({
598
+ kind: "deal",
599
+ reason: "crm.activities-failed",
600
+ message: isCliFailure(error) ? error.message : "the activities could not be read",
601
+ });
602
+ }
603
+ }
531
604
  const narrowed = report.synced.some((one) => one.outOfScope > 0);
532
605
  const whole = report.synced.every((one) => one.state === "complete" && one.error === undefined && !one.held && one.pass !== "held");
533
606
  // Contacts have no scope of their own and no deletion check: they leave with the last deal or lead naming them.
@@ -154,6 +154,33 @@ export interface CrmRecords {
154
154
  person: CrmPerson;
155
155
  organization: CrmOrganization;
156
156
  }
157
+ /** What a CRM activity is: a call, an e-mail, a meeting, a to-do, a task of the CRM's task tracker, or a comment. */
158
+ export declare const CRM_ACTIVITY_KINDS: readonly ["call", "email", "meeting", "todo", "task", "comment", "other"];
159
+ export type CrmActivityKind = (typeof CRM_ACTIVITY_KINDS)[number];
160
+ /**
161
+ * An activity on the CRM's deals and leads, as the CRM has it. `externalId` is unique among the account's activities
162
+ * of every kind (a source with separate lists prefixes them). Contact data the CRM keeps on it, such as a call's
163
+ * phone number, is never part of it: it would bypass the limits on reading clients' contacts.
164
+ */
165
+ export interface CrmActivity {
166
+ externalId: string;
167
+ kind: CrmActivityKind;
168
+ subject: string;
169
+ /** The text: an e-mail's body, a comment, a task's description; `null` when it has none. */
170
+ body?: string | null;
171
+ /** Epoch milliseconds. */
172
+ dueAt?: number | null;
173
+ done: boolean;
174
+ /** The CRM user responsible for it, by the CRM's id. */
175
+ assignee?: string | null;
176
+ createdAt: number;
177
+ updatedAt: number;
178
+ /** The deals and leads it is on, by the CRM's ids; one on neither is not stored. */
179
+ on: {
180
+ kind: DealKind;
181
+ externalId: string;
182
+ }[];
183
+ }
157
184
  /** The account's scope settings: `also` are the users whose deals the owner counts as nobody's. */
158
185
  export type CrmScopeSetting = {
159
186
  mode: "all";
@@ -1,5 +1,7 @@
1
1
  /** What a CRM holds that the store copies: its deals and leads, and the contacts and companies on them. */
2
2
  export const CRM_KINDS = ["organization", "person", "deal", "lead"];
3
+ /** What a CRM activity is: a call, an e-mail, a meeting, a to-do, a task of the CRM's task tracker, or a comment. */
4
+ export const CRM_ACTIVITY_KINDS = ["call", "email", "meeting", "todo", "task", "comment", "other"];
3
5
  /** A CRM's user id as `unassigned` takes it: digits, as every CRM core syncs numbers its users. */
4
6
  export const isCrmUserId = (id) => /^\d{1,20}$/.test(id);
5
7
  /** One spelling per user id, so `015`, ` 15` and `15` are one user wherever they come from. */
@@ -1,4 +1,17 @@
1
1
  import * as v from "valibot";
2
+ import { type CrmActivityKind } from "../domain/crm.js";
3
+ /** A call, e-mail, meeting, to-do, task or comment the CRM keeps on a deal or lead: what `show` lists. */
4
+ export interface DealActivity {
5
+ external_id: string;
6
+ kind: CrmActivityKind;
7
+ subject: string;
8
+ body: string | null;
9
+ due_at: string | null;
10
+ done: boolean;
11
+ assignee: string | null;
12
+ created_at: string;
13
+ updated_at: string;
14
+ }
2
15
  /**
3
16
  * A deal (`deal:<id>`), the owner's own or a CRM's copy: one shape for memo and every CRM CLI. Money is a decimal
4
17
  * string in its currency, both `null` when no amount is expected.
@@ -69,6 +82,8 @@ export declare const deal: v.StrictObjectSchema<{
69
82
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
70
83
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
71
84
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
85
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
86
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<DealActivity>, undefined>, undefined>;
72
87
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
73
88
  }, undefined>;
74
89
  /** A lead (`lead:<id>`): a deal's shape, in a lead pipeline. */
@@ -138,6 +153,8 @@ export declare const lead: v.StrictObjectSchema<{
138
153
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
139
154
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
140
155
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
156
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
157
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<DealActivity>, undefined>, undefined>;
141
158
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
142
159
  }, undefined>;
143
160
  /** A pipeline (`pipeline:<id>`) with its stages in order; `pipelines show` adds the funnel. */
@@ -1,4 +1,5 @@
1
1
  import * as v from "valibot";
2
+ import { CRM_ACTIVITY_KINDS } from "../domain/crm.js";
2
3
  import { DEAL_ROLES } from "../domain/deals.js";
3
4
  import { count, id, reference, text, time, untrusted } from "./fields.js";
4
5
  const nullableText = v.nullable(text);
@@ -6,6 +7,19 @@ const party = v.strictObject({ ref: reference, name: nullableText, owner: v.bool
6
7
  const outcome = v.picklist(["open", "won", "lost"]);
7
8
  const crmAccount = v.nullable(v.strictObject({ provider: text, account: text }));
8
9
  const day = v.nullable(v.pipe(v.string(), v.regex(/^\d{4}-\d{2}-\d{2}$/)));
10
+ // Typed by name: inferred, it makes every entity map that holds a deal too long for the compiler to write out.
11
+ const activity = v.strictObject({
12
+ external_id: text,
13
+ kind: v.picklist(CRM_ACTIVITY_KINDS),
14
+ subject: text,
15
+ body: nullableText,
16
+ due_at: v.nullable(time),
17
+ done: v.boolean(),
18
+ /** The identity `<account>/user/<id>` responsible for it. */
19
+ assignee: nullableText,
20
+ created_at: time,
21
+ updated_at: time,
22
+ });
9
23
  /**
10
24
  * A deal (`deal:<id>`), the owner's own or a CRM's copy: one shape for memo and every CRM CLI. Money is a decimal
11
25
  * string in its currency, both `null` when no amount is expected.
@@ -61,6 +75,8 @@ export const deal = v.strictObject({
61
75
  project_name: nullableText,
62
76
  created_at: time,
63
77
  updated_at: time,
78
+ /** `show` of a CRM copy whose `activities` setting is on: its activities and tasks, open ones first. */
79
+ activities: v.optional(v.array(activity)),
64
80
  untrusted,
65
81
  });
66
82
  /** A lead (`lead:<id>`): a deal's shape, in a lead pipeline. */
@@ -296,6 +296,7 @@ export declare const ENTITIES: {
296
296
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
297
297
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
298
298
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
299
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<import("./deal.js").DealActivity>, undefined>, undefined>;
299
300
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
300
301
  }, undefined>;
301
302
  readonly lead: v.StrictObjectSchema<{
@@ -357,6 +358,7 @@ export declare const ENTITIES: {
357
358
  readonly project_name: v.NullableSchema<v.StringSchema<undefined>, undefined>;
358
359
  readonly created_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
359
360
  readonly updated_at: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.IsoTimestampAction<string, "an ISO 8601 time in UTC">, v.EndsWithAction<string, "Z", "an ISO 8601 time in UTC, ending in `Z`">]>;
361
+ readonly activities: v.OptionalSchema<v.ArraySchema<v.GenericSchema<import("./deal.js").DealActivity>, undefined>, undefined>;
360
362
  readonly untrusted: v.OptionalSchema<v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>;
361
363
  }, undefined>;
362
364
  readonly pipeline: v.StrictObjectSchema<{
@@ -375,6 +375,7 @@ const OTHERS = [
375
375
  validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
376
376
  validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
377
377
  validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
378
+ validation("crm.activities-failed", "the activities and tasks could not be read; the deals and leads were synced"),
378
379
  validation("crm.email-ambiguous", "a CRM contact's email belongs to more than one person; the owner decides"),
379
380
  validation("crm.own-unknown", "no own company of the CRM account is stored, so its users are no one's employees yet"),
380
381
  validation("relationship.reference-unknown", "a reported relationship names something the store does not hold"),
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export { CATALOG_KINDS, type CatalogKind, CONTRACT_KINDS, CONTRACT_STATUSES, typ
3
3
  export { bareCheck, type CheckWords, checkWords } from "./domain/checks.js";
4
4
  export type { CounterField, CounterObservation, CounterObservations, CounterState } from "./domain/counters.js";
5
5
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
6
- export { CRM_KINDS, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmScope, type CrmScopeSetting, type CrmStage, type CrmUser, type CrmValue, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
6
+ export { CRM_ACTIVITY_KINDS, CRM_KINDS, type CrmActivity, type CrmActivityKind, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmRecords, type CrmScope, type CrmScopeSetting, type CrmStage, type CrmUser, type CrmValue, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
7
7
  export { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, type DealKind, type DealRole, type DealStatus, STAGE_OUTCOMES, type StageOutcome, } from "./domain/deals.js";
8
8
  export { displayName, type NameFallbacks, nameKey } from "./domain/display-names.js";
9
9
  export { FINANCE_REVIEWS, type FinanceReview, INVOICE_DIRECTIONS, INVOICE_STATUSES, type InvoiceDirection, type InvoiceStatus, MONEY_DIRECTIONS, type MoneyDirection, } from "./domain/finance.js";
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ export { isNoReplyAddress, isRoleAddress, ROLE_ADDRESS_WORDS } from "./domain/ad
2
2
  export { CATALOG_KINDS, CONTRACT_KINDS, CONTRACT_STATUSES, intervalOf, intervalText, ORDER_DIRECTIONS, PERIOD_UNITS, SUBSCRIPTION_STATUSES, TRANSACTION_STATUSES, WALLET_KINDS, } from "./domain/business.js";
3
3
  export { bareCheck, checkWords } from "./domain/checks.js";
4
4
  export { COUNTER_FIELDS, counterValue, observedCounters } from "./domain/counters.js";
5
- export { CRM_KINDS, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
5
+ export { CRM_ACTIVITY_KINDS, CRM_KINDS, isCrmUserId, isItemKind, normalCrmUserId, } from "./domain/crm.js";
6
6
  export { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, STAGE_OUTCOMES, } from "./domain/deals.js";
7
7
  export { displayName, nameKey } from "./domain/display-names.js";
8
8
  export { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, MONEY_DIRECTIONS, } from "./domain/finance.js";
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -60,6 +60,19 @@ export interface IdentityLinkDecision {
60
60
  all?: boolean;
61
61
  mailbox?: string;
62
62
  };
63
+ /**
64
+ * With `confirm: false`: the two "people" are a company's mailboxes. Every address of the match's identities goes to
65
+ * one organization: `organization`, else the one holding an address or its company domain, else one of `name`, else
66
+ * a new company named after the people's shared name (a match by name) or the domain. A person who is only those
67
+ * addresses becomes the company's; one who holds more keeps the rest and stays a person. `all` closes every open
68
+ * proposal on those addresses. The result names `organization`, `mailboxes`, `people` (who became the company's)
69
+ * and `closed`.
70
+ */
71
+ organization?: {
72
+ organization?: number;
73
+ name?: string;
74
+ all?: boolean;
75
+ };
63
76
  }
64
77
  /** One `identity_link`, naming the people as they are now, not as they were when it was proposed. */
65
78
  export interface IdentityLinkRow {
@@ -88,7 +88,8 @@ export interface PeopleStore extends AccountPeople {
88
88
  proposeLink(input: IdentityLinkInput): Promise<ProposedAction>;
89
89
  /**
90
90
  * The owner's decision on an `identity_link`; confirm is refused with `identity.stale` when either person changed.
91
- * `company` turns down a shared-mailbox proposal and gives its address to an organization (NEED-2528).
91
+ * `company` turns down a shared-mailbox proposal and gives its address to an organization (NEED-2528);
92
+ * `organization` turns down a match whose two sides are a company's mailboxes and gives them all to it (NEED-2573).
92
93
  */
93
94
  decideLink(id: string, decision: IdentityLinkDecision): Promise<ProposedAction>;
94
95
  /**
@@ -0,0 +1,27 @@
1
+ import type { CrmActivity, CrmActivityKind } from "../../domain/crm.js";
2
+ import type { DealKind } from "../../domain/deals.js";
3
+ import type { AccountKey } from "../types.js";
4
+ import type { StoreContext } from "./open.js";
5
+ export declare const ACTIVITY_RECORD = "crm.activity";
6
+ /** One activity as `deals show` lists it. */
7
+ export interface StoredActivity {
8
+ externalId: string;
9
+ kind: CrmActivityKind;
10
+ subject: string;
11
+ body: string | null;
12
+ dueAt: number | null;
13
+ done: boolean;
14
+ /** The identity `<account>/user/<id>`, as a deal's assignee. */
15
+ assignee: string | null;
16
+ createdAt: number;
17
+ updatedAt: number;
18
+ }
19
+ export interface CrmActivitiesSaved {
20
+ saved: number;
21
+ /** On no deal or lead this copy keeps, so not stored. */
22
+ outOfScope: number;
23
+ }
24
+ export declare const crmActivitiesOver: (context: StoreContext) => {
25
+ save: (key: AccountKey, activities: readonly CrmActivity[]) => CrmActivitiesSaved;
26
+ of: (key: AccountKey, kind: DealKind, externalId: string, limit: number) => StoredActivity[];
27
+ };
@@ -0,0 +1,96 @@
1
+ import { recordFingerprint } from "../../domain/records.js";
2
+ import { accountPk, findAccountPk } from "./accounts.js";
3
+ import { crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
4
+ import { write } from "./transaction.js";
5
+ export const ACTIVITY_RECORD = "crm.activity";
6
+ /** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
7
+ const MOST_BODY = 20_000;
8
+ const MOST_SUBJECT = 500;
9
+ export const crmActivitiesOver = (context) => {
10
+ const { database, now } = context;
11
+ const kept = (accountId, kind, externalId) => database
12
+ .prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
13
+ .get(accountId, externalId) !== undefined;
14
+ const save = (key, activities) => write(database, () => {
15
+ const accountId = accountPk(context, key);
16
+ const at = now();
17
+ let saved = 0;
18
+ let outOfScope = 0;
19
+ for (const activity of activities) {
20
+ const on = activity.on.filter((one) => kept(accountId, one.kind, one.externalId));
21
+ const held = database
22
+ .prepare("SELECT id FROM records WHERE account_id = ? AND type = ? AND external_id = ?")
23
+ .get(accountId, ACTIVITY_RECORD, activity.externalId);
24
+ if (on.length === 0) {
25
+ // It left every kept deal: one stored before goes with it.
26
+ if (held)
27
+ database.prepare("UPDATE records SET deleted_at = ? WHERE id = ?").run(at, Number(held.id));
28
+ outOfScope += 1;
29
+ continue;
30
+ }
31
+ const fields = {
32
+ kind: activity.kind,
33
+ subject: textOf(activity.subject, MOST_SUBJECT) ?? "",
34
+ body: textOf(activity.body, MOST_BODY),
35
+ due_at: activity.dueAt ?? null,
36
+ done: activity.done,
37
+ assignee: activity.assignee ? crmIdentityId(key, activity.assignee, "user") : null,
38
+ created_at: activity.createdAt,
39
+ updated_at: activity.updatedAt,
40
+ };
41
+ const relations = on.map((one) => ({ role: "on", type: one.kind, external_id: one.externalId }));
42
+ const fingerprint = recordFingerprint(fields, relations);
43
+ let id;
44
+ if (held) {
45
+ id = Number(held.id);
46
+ database
47
+ .prepare("UPDATE records SET fields = ?, fingerprint = ?, batch_id = ?, updated_at = ?, deleted_at = NULL " +
48
+ "WHERE id = ?")
49
+ .run(JSON.stringify(fields), fingerprint, SOURCE, at, id);
50
+ database.prepare("DELETE FROM record_relations WHERE record_id = ?").run(id);
51
+ }
52
+ else
53
+ id = Number(database
54
+ .prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, " +
55
+ "updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
56
+ .get(accountId, ACTIVITY_RECORD, activity.externalId, JSON.stringify(fields), fingerprint, SOURCE, at, at)
57
+ ?.id);
58
+ for (const one of on)
59
+ database
60
+ .prepare("INSERT INTO record_relations (record_id, role, target_type, target_external_id, created_at) " +
61
+ "VALUES (?, 'on', ?, ?, ?)")
62
+ .run(id, one.kind, one.externalId, at);
63
+ saved += 1;
64
+ }
65
+ return { saved, outOfScope };
66
+ });
67
+ /** The activities on one deal or lead: open ones first by due time, then the rest, newest first. */
68
+ const of = (key, kind, externalId, limit) => {
69
+ const accountId = findAccountPk(context, key);
70
+ if (accountId === undefined)
71
+ return [];
72
+ return database
73
+ .prepare("SELECT r.external_id, r.fields FROM records r JOIN record_relations rr ON rr.record_id = r.id " +
74
+ "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL AND rr.role = 'on' " +
75
+ "AND rr.target_type = ? AND rr.target_external_id = ? " +
76
+ "ORDER BY json_extract(r.fields, '$.done') ASC, " +
77
+ "CASE WHEN json_extract(r.fields, '$.done') THEN NULL ELSE json_extract(r.fields, '$.due_at') END ASC, " +
78
+ "json_extract(r.fields, '$.updated_at') DESC LIMIT ?")
79
+ .all(accountId, ACTIVITY_RECORD, kind, externalId, limit)
80
+ .map((row) => {
81
+ const fields = JSON.parse(String(row.fields));
82
+ return {
83
+ externalId: String(row.external_id),
84
+ kind: fields.kind,
85
+ subject: String(fields.subject ?? ""),
86
+ body: fields.body ?? null,
87
+ dueAt: fields.due_at ?? null,
88
+ done: fields.done === true,
89
+ assignee: fields.assignee ?? null,
90
+ createdAt: Number(fields.created_at),
91
+ updatedAt: Number(fields.updated_at),
92
+ };
93
+ });
94
+ };
95
+ return { save, of };
96
+ };
@@ -10,7 +10,9 @@ export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier",
10
10
  export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
11
11
  /** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
12
12
  export declare const CRM_SCOPES: readonly ["mine", "all"];
13
- declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"];
13
+ /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
14
+ export declare const CRM_ACTIVITIES: readonly ["on", "off"];
15
+ declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"];
14
16
  type CrmSettingName = (typeof NAMES)[number];
15
17
  export declare const crmSettingKey: (key: AccountKey, name: CrmSettingName) => string;
16
18
  /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
@@ -20,6 +22,8 @@ export declare const parseCrmSetting: (setting: string) => {
20
22
  } | undefined;
21
23
  /** A value this build cannot read is the default: the CRM's relationships stay reported. */
22
24
  export declare const crmLinkMode: (database: CacheDatabase, key: AccountKey) => CrmLinkMode;
25
+ /** Activities and tasks hold what clients wrote and said: read only once the owner turns them on. */
26
+ export declare const crmActivitiesOn: (database: CacheDatabase, key: AccountKey) => boolean;
23
27
  /** Only the owner's mapping gives a company type a meaning; none by default. */
24
28
  export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
25
29
  /** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
@@ -6,7 +6,9 @@ export const CRM_LINK_MODES = ["reported", "review"];
6
6
  export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
7
7
  /** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
8
8
  export const CRM_SCOPES = ["mine", "all"];
9
- const NAMES = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"];
9
+ /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
10
+ export const CRM_ACTIVITIES = ["on", "off"];
11
+ const NAMES = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks", "activities"];
10
12
  const SETTING = new RegExp(`^crm\\.([a-z0-9-]+):(.+)\\.(${NAMES.join("|")})$`);
11
13
  export const crmSettingKey = (key, name) => `crm.${key.provider}:${key.account}.${name}`;
12
14
  /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
@@ -32,6 +34,8 @@ export const crmLinkMode = (database, key) => {
32
34
  const value = stored(database, crmSettingKey(key, "links"));
33
35
  return value === "review" ? "review" : "reported";
34
36
  };
37
+ /** Activities and tasks hold what clients wrote and said: read only once the owner turns them on. */
38
+ export const crmActivitiesOn = (database, key) => stored(database, crmSettingKey(key, "activities")) === "on";
35
39
  /** Only the owner's mapping gives a company type a meaning; none by default. */
36
40
  export const crmCompanyTypes = (database, key) => {
37
41
  const value = stored(database, crmSettingKey(key, "company-types"));
@@ -163,6 +167,8 @@ export const parseCrmSettingValue = (name, value) => {
163
167
  return picked(name, text, CRM_LINK_MODES);
164
168
  if (name === "scope")
165
169
  return picked(name, text, CRM_SCOPES);
170
+ if (name === "activities")
171
+ return picked(name, text, CRM_ACTIVITIES);
166
172
  if (name === "self") {
167
173
  if (!isCrmUserId(text))
168
174
  throw new CliError("validation_error", `self takes the CRM's numeric user id: not "${text}"`);
@@ -218,6 +224,8 @@ const settingValue = (database, key, name) => {
218
224
  return crmOwnUser(database, key) ?? null;
219
225
  if (name === "stage-tasks")
220
226
  return stored(database, crmSettingKey(key, name)) ?? {};
227
+ if (name === "activities")
228
+ return crmActivitiesOn(database, key) ? "on" : "off";
221
229
  return userIds(stored(database, crmSettingKey(key, name)));
222
230
  };
223
231
  export const crmSettingsOf = (database) => database
@@ -1,7 +1,8 @@
1
- import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmUser } from "../../domain/crm.js";
1
+ import { type CrmActivity, type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type CrmOrganization, type CrmPerson, type CrmPipeline, type CrmScopeSetting, type CrmUser } from "../../domain/crm.js";
2
2
  import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
5
+ import { type CrmActivitiesSaved, type StoredActivity } from "./crm-activities.js";
5
6
  import { type CrmContactsRemoved } from "./crm-contacts.js";
6
7
  import { type CrmSkipped } from "./crm-rows.js";
7
8
  import { type CrmStageMove, type CrmStageTasks } from "./crm-settings.js";
@@ -94,6 +95,12 @@ export interface CrmCopies {
94
95
  through: number;
95
96
  }>;
96
97
  markStageMoves(key: AccountKey, through: number): Promise<void>;
98
+ /** Whether the owner turned on reading activities and tasks (`activities` setting). */
99
+ activitiesOn(key: AccountKey): Promise<boolean>;
100
+ /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
101
+ saveActivities(key: AccountKey, activities: readonly CrmActivity[]): Promise<CrmActivitiesSaved>;
102
+ /** One deal's or lead's activities, open ones first. */
103
+ activitiesOf(key: AccountKey, kind: DealKind, externalId: string, limit: number): Promise<StoredActivity[]>;
97
104
  /**
98
105
  * Marks deleted every stored deal or lead of the kind assigned to a user outside `userIds`; one with no assignee
99
106
  * stays. Reads only the store. Answers how many; `dryRun` only counts them.
@@ -116,6 +123,7 @@ export interface CrmCopies {
116
123
  /** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */
117
124
  refOf(key: AccountKey, kind: DealKind, externalId: string): Promise<string | null>;
118
125
  }
126
+ export type { CrmActivitiesSaved, StoredActivity } from "./crm-activities.js";
119
127
  export type { CrmContactsRemoved } from "./crm-contacts.js";
120
128
  export { type CrmSkipped, crmIdentityId, crmRowsOver, type ItemWriter } from "./crm-rows.js";
121
129
  export declare const crmCopiesOver: (context: StoreContext, people: AccountPeople) => CrmCopies;
@@ -4,9 +4,10 @@ import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
+ import { crmActivitiesOver } from "./crm-activities.js";
7
8
  import { removeCrmContacts } from "./crm-contacts.js";
8
9
  import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
9
- import { crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
10
+ import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
10
11
  import { syncReportedIn } from "./reported-relations.js";
11
12
  import { clearState, syncStateOf, writeState } from "./sync.js";
12
13
  import { write } from "./transaction.js";
@@ -28,6 +29,7 @@ export const crmCopiesOver = (context, people) => {
28
29
  const { database, now } = context;
29
30
  const { savePipeline, saveItemRow } = crmRowsOver(context);
30
31
  const account = (key) => accountPk(context, key);
32
+ const activityStore = crmActivitiesOver(context);
31
33
  /**
32
34
  * One kind's whole list: a pipeline it lacks is marked deleted, one listed again comes back. An empty list marks
33
35
  * nothing: a sign-in that lost its CRM rights lists no pipeline at all.
@@ -591,6 +593,9 @@ export const crmCopiesOver = (context, people) => {
591
593
  stageTasks: async (key) => crmStageTasks(database, key),
592
594
  stageMoves: async (key) => crmStageMoves(database, key, findAccountPk(context, key)),
593
595
  markStageMoves: async (key, through) => saveStageMovesMark(database, key, through, now()),
596
+ activitiesOn: async (key) => crmActivitiesOn(database, key),
597
+ saveActivities: async (key, activities) => activityStore.save(key, activities),
598
+ activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
594
599
  removeOutOfScope: async (key, kind, userIds, { dryRun } = {}) => write(database, () => {
595
600
  const keep = new Set(userIds.map((id) => crmIdentityId(key, id, "user")));
596
601
  const accountId = findAccountPk(context, key);
@@ -7,7 +7,7 @@ import { holdAddress, organizationOfAddress } from "./address-organization.js";
7
7
  import { ensurePerson } from "./identities.js";
8
8
  import { evidenceKeyOf, linkIndex, linkRows, settleLinks, sidesOf, } from "./identity-link-rows.js";
9
9
  import { currentPerson } from "./merged-persons.js";
10
- import { linkIdentityToPerson, mergePerson, move, recordOf, required, survivorOf } from "./person-links.js";
10
+ import { isOwner, linkIdentityToPerson, mergePerson, move, recordOf, required, survivorOf, unlinkIdentity, } from "./person-links.js";
11
11
  import { resolvePersonLinks } from "./person-resolution.js";
12
12
  import { identitySeparated, separated } from "./person-separation.js";
13
13
  import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
@@ -244,6 +244,132 @@ const toCompany = (context, proposal, company, author, noted) => {
244
244
  settleMentions(context, payload, "found");
245
245
  return rejected;
246
246
  };
247
+ /** The match's own identities as they are now, each with the address it is (`email`) or carries. */
248
+ const identitiesOfMatch = ({ database }, payload) => [payload.identity, payload.with].flatMap((ref) => {
249
+ if (ref === null)
250
+ return [];
251
+ const { provider, id } = parseIdentityRef(ref);
252
+ const row = database
253
+ .prepare("SELECT i.id, l.person_id, lower(trim(coalesce(CASE WHEN i.provider = 'email' THEN i.external_id END, i.email))) " +
254
+ "AS address FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
255
+ "WHERE i.provider = ? AND i.external_id = ?")
256
+ .get(provider, id);
257
+ if (row === undefined)
258
+ return [];
259
+ const address = typeof row.address === "string" && isEmailAddress(row.address) ? row.address : null;
260
+ return [{ pk: Number(row.id), provider, id, person: Number(row.person_id), address }];
261
+ });
262
+ /** The one organization that already holds any of the addresses, else none; two are refused. */
263
+ const holderOf = ({ database }, addresses) => {
264
+ const found = [
265
+ ...new Set(database
266
+ .prepare("SELECT DISTINCT o.id FROM organizations o JOIN organization_identities oi ON oi.organization_id = o.id " +
267
+ "JOIN identities i ON i.id = oi.identity_id WHERE o.deleted_at IS NULL AND i.provider = 'email' " +
268
+ "AND lower(i.external_id) IN (SELECT value FROM json_each(?)) ORDER BY o.id")
269
+ .all(JSON.stringify(addresses))
270
+ .map(({ id }) => Number(id))),
271
+ ];
272
+ if (found.length > 1)
273
+ throw new CliError("validation_error", `${found.length} organizations hold these addresses (${found.map((id) => `organization:${id}`).join(", ")}); ` +
274
+ "name the one meant as a reference", { reason: "organization.ambiguous" });
275
+ return found[0];
276
+ };
277
+ /**
278
+ * NEED-2573 A: the two "people" are the company's mailboxes. Every address of the match's identities goes to one
279
+ * organization. A person who is nothing but those addresses becomes the company's (an organization holds all their
280
+ * identities, so they are listed as an organization, not a person); one who also holds something else keeps it and
281
+ * stays a person, their address identity moved off them. Nobody is joined and the match is turned down.
282
+ */
283
+ const toOrganization = (context, proposal, asked, author, noted) => {
284
+ const payload = proposal.payload;
285
+ if (proposal.status !== "proposed")
286
+ throw new CliError("validation_error", `${proposal.id} is already ${proposal.status}`, {
287
+ reason: "proposal.wrong-state",
288
+ });
289
+ const matched = identitiesOfMatch(context, payload);
290
+ const addresses = [
291
+ ...new Set([...matched.flatMap(({ address }) => address ?? []), ...(payload.mailbox ? [payload.mailbox] : [])]),
292
+ ].sort();
293
+ if (addresses.length === 0)
294
+ throw new CliError("validation_error", `${proposal.id} names no mail address to give to an organization`, {
295
+ reason: "identity.not-shared",
296
+ });
297
+ const persons = [...new Set(matched.map(({ person }) => person))];
298
+ if (persons.some((person) => isOwner(context, person)))
299
+ throw new CliError("validation_error", `${proposal.id} names the owner; the owner's address is no company's`, {
300
+ reason: "identity.owner",
301
+ });
302
+ const name = asked.name?.trim() || undefined;
303
+ const company = addresses.find((address) => !FREE_MAIL.has(address.split("@")[1] ?? ""));
304
+ const how = { method: CONFIRMED, author: "owner" };
305
+ let organization;
306
+ if (asked.organization !== undefined) {
307
+ if (!organizationExists(context, asked.organization))
308
+ throw new CliError("not_found", `no organization:${asked.organization}`, { reason: "organization.not-found" });
309
+ organization = asked.organization;
310
+ }
311
+ else {
312
+ if (name === undefined && company === undefined)
313
+ throw new CliError("validation_error", `${addresses.join(", ")} ${addresses.length > 1 ? "are free mailboxes" : "is a free mailbox"}; ` +
314
+ "name the company or its organization", { reason: "organization.unnamed" });
315
+ const shared = payload.signal === "name"
316
+ ? context.database
317
+ .prepare("SELECT coalesce(p.name, i.name) AS name FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
318
+ "JOIN persons p ON p.id = l.person_id WHERE i.id = ?")
319
+ .get(matched[0]?.pk ?? 0)?.name
320
+ : undefined;
321
+ organization =
322
+ holderOf(context, addresses) ??
323
+ organizationOfAddress(context, {
324
+ name: name ?? (typeof shared === "string" && shared.trim() ? shared.trim() : ((company ?? "").split("@")[1] ?? "")),
325
+ ...(company === undefined ? {} : { email: company }),
326
+ ...how,
327
+ reason: "organization.ambiguous",
328
+ });
329
+ }
330
+ for (const address of addresses)
331
+ holdAddress(context, organization, address, how);
332
+ const held = context.database.prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
333
+ "VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING");
334
+ const people = [];
335
+ for (const person of persons) {
336
+ const theirs = matched.filter((one) => one.person === person && one.address !== null);
337
+ const all = context.database
338
+ .prepare("SELECT lower(trim(coalesce(CASE WHEN i.provider = 'email' THEN i.external_id END, i.email, ''))) AS address " +
339
+ "FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ?")
340
+ .all(person)
341
+ .map(({ address }) => String(address));
342
+ if (all.every((address) => addresses.includes(address))) {
343
+ const at = context.now();
344
+ for (const one of theirs)
345
+ held.run(one.pk, organization, how.method, how.author, at, at);
346
+ people.push(`person:${person}`);
347
+ }
348
+ else
349
+ for (const one of theirs)
350
+ if (one.provider === "email")
351
+ unlinkIdentity(context, { provider: one.provider, id: one.id }, { method: "unlink", by: "owner" });
352
+ }
353
+ const operations = proposalOperationsOver(context);
354
+ const refs = addresses.map((address) => `email:${address}`);
355
+ const others = asked.all
356
+ ? context.database
357
+ .prepare("SELECT id FROM proposed_actions WHERE kind = ? AND status = 'proposed' AND id <> ? AND (" +
358
+ "json_extract(payload, '$.mailbox') IN (SELECT value FROM json_each(?)) " +
359
+ "OR json_extract(payload, '$.identity') IN (SELECT value FROM json_each(?)) " +
360
+ "OR json_extract(payload, '$.with') IN (SELECT value FROM json_each(?))) ORDER BY id")
361
+ .all(IDENTITY_LINK_KIND, Number(proposal.id), JSON.stringify(addresses), JSON.stringify(refs), JSON.stringify(refs))
362
+ .map((row) => String(row.id))
363
+ : [];
364
+ const result = { dismissed: true, organization: `organization:${organization}`, mailboxes: addresses, ...noted };
365
+ for (const other of others) {
366
+ const closed = operations.reject(other, author, { ...result, with: proposal.id });
367
+ settleMentions(context, closed.payload, "found");
368
+ }
369
+ const rejected = operations.reject(proposal.id, author, { ...result, people, closed: [proposal.id, ...others] });
370
+ settleMentions(context, payload, "found");
371
+ return rejected;
372
+ };
247
373
  /**
248
374
  * Decides an `identity_link`, the owner's alone. Confirm links the two people as the owner's link, refused with
249
375
  * `identity.stale` when either person changed since it was proposed; reject keeps them apart, and only new evidence
@@ -258,6 +384,11 @@ export const decideIdentityLink = (context, id, decision) => write(context.datab
258
384
  const author = deciderAuthor(decision.by);
259
385
  const reason = decision.reason?.trim() || undefined;
260
386
  const noted = reason === undefined ? {} : { reason };
387
+ if (decision.organization !== undefined) {
388
+ if (decision.confirm || decision.company !== undefined)
389
+ throw new CliError("validation_error", "the company's mailboxes keep the two apart; it is not a confirm");
390
+ return toOrganization(context, proposal, decision.organization, author, noted);
391
+ }
261
392
  if (decision.company !== undefined) {
262
393
  if (decision.confirm)
263
394
  throw new CliError("validation_error", "a company's mailbox keeps the two people apart; it is not a confirm");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.645.0",
3
+ "version": "0.647.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",