@wirecat/cli-core 0.676.0 → 0.678.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 +47 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/background/report/render.d.ts +3 -1
- package/dist/background/report/render.js +2 -2
- package/dist/background/report/schema.d.ts +7 -4
- package/dist/background/report/schema.js +23 -7
- package/dist/background/report/templates/morning-digest.email.en.liquid +3 -2
- package/dist/background/report/templates/morning-digest.email.ru.liquid +3 -2
- package/dist/background/report/templates/morning-digest.telegram.en.liquid +3 -2
- package/dist/background/report/templates/morning-digest.telegram.ru.liquid +3 -2
- package/dist/background/report/templates/morning-digest.text.en.liquid +3 -2
- package/dist/background/report/templates/morning-digest.text.ru.liquid +3 -2
- package/dist/background/report/view.js +2 -0
- package/dist/background/schedules.js +21 -11
- package/dist/cli/command-runs.d.ts +2 -0
- package/dist/cli/command-runs.js +2 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/list-query.d.ts +1 -1
- package/dist/cli/list-query.js +2 -2
- package/dist/cli/setup-command.js +5 -2
- package/dist/crm/cli/activities.d.ts +17 -0
- package/dist/crm/cli/activities.js +133 -0
- package/dist/crm/cli/changes.d.ts +23 -0
- package/dist/crm/cli/changes.js +255 -0
- package/dist/crm/cli/index.d.ts +1 -0
- package/dist/crm/cli/index.js +7 -4
- package/dist/crm/digest.d.ts +27 -0
- package/dist/crm/digest.js +166 -0
- package/dist/crm/stage-tasks.d.ts +1 -1
- package/dist/crm/stage-tasks.js +1 -1
- package/dist/crm/sync.d.ts +9 -0
- package/dist/crm/sync.js +27 -0
- package/dist/crm/testing/source.d.ts +5 -1
- package/dist/crm/testing/source.js +19 -0
- package/dist/crm/testing/sync-contract.d.ts +2 -0
- package/dist/crm/testing/sync-contract.js +56 -2
- package/dist/errors/reasons.js +1 -0
- package/dist/store/identity-links.d.ts +73 -0
- package/dist/store/identity-links.js +14 -0
- package/dist/store/index.d.ts +3 -1
- package/dist/store/index.js +2 -1
- package/dist/store/people.d.ts +23 -1
- package/dist/store/people.js +12 -1
- package/dist/store/sqlite/agent-links.d.ts +34 -0
- package/dist/store/sqlite/agent-links.js +184 -0
- package/dist/store/sqlite/crm-activities.d.ts +41 -1
- package/dist/store/sqlite/crm-activities.js +152 -14
- package/dist/store/sqlite/crm-changes.d.ts +84 -0
- package/dist/store/sqlite/crm-changes.js +199 -0
- package/dist/store/sqlite/crm.d.ts +2 -1
- package/dist/store/sqlite/crm.js +2 -0
- package/dist/store/sqlite/identity-proposals.d.ts +2 -0
- package/dist/store/sqlite/identity-proposals.js +2 -0
- package/dist/store/sqlite/person-match-scan.d.ts +29 -0
- package/dist/store/sqlite/person-match-scan.js +4 -4
- package/dist/store/sqlite/person-merges.d.ts +3 -0
- package/package.json +1 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { annotate } from "@wirecat/cli-base/commands";
|
|
3
|
+
import { timezoneOf } from "@wirecat/cli-base/query";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import { answerEntity } from "../../cli/answer-entity.js";
|
|
6
|
+
import { LOCAL_READ, NO_EFFECTS } from "../../cli/effects.js";
|
|
7
|
+
import { listOf } from "../../cli/envelope.js";
|
|
8
|
+
import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds, typedQuery, withQuery, } from "../../cli/list-query.js";
|
|
9
|
+
import { CRM_ACTIVITY_KINDS, CRM_KINDS } from "../../domain/crm.js";
|
|
10
|
+
import { text, time } from "../../entities/fields.js";
|
|
11
|
+
import { crmSettingKey } from "../../store/sqlite/crm-settings.js";
|
|
12
|
+
import { viewerOf } from "../viewer.js";
|
|
13
|
+
import { integer } from "./records.js";
|
|
14
|
+
const MOST = 500;
|
|
15
|
+
const nullableText = v.nullable(text);
|
|
16
|
+
const REFS = ["deal", "lead", "person", "organization"];
|
|
17
|
+
export const ACTIVITIES_QUERY = {
|
|
18
|
+
entity: "crm_activity",
|
|
19
|
+
backend: "native",
|
|
20
|
+
fields: [
|
|
21
|
+
termField("status", "enum", "status:done", { values: ["open", "done"] }),
|
|
22
|
+
nativeField({
|
|
23
|
+
name: "due",
|
|
24
|
+
type: "time",
|
|
25
|
+
operators: ["term", "range"],
|
|
26
|
+
example: "due:today",
|
|
27
|
+
relation: "due in this time",
|
|
28
|
+
}),
|
|
29
|
+
termField("overdue", "bool", "overdue:true", { relation: "open and due before now" }),
|
|
30
|
+
termField("kind", "enum", "kind:call", { values: CRM_ACTIVITY_KINDS }),
|
|
31
|
+
termField("deal", "ref", "deal:12", { relation: "on this deal" }),
|
|
32
|
+
termField("lead", "ref", "lead:4", { relation: "on this lead" }),
|
|
33
|
+
termField("person", "ref", "person:7", { relation: "on this contact" }),
|
|
34
|
+
termField("organization", "ref", "organization:3", { relation: "on this company" }),
|
|
35
|
+
termField("owner", "kw", "owner:me", {
|
|
36
|
+
relation: "the CRM user it is assigned to: me (the sign-in's own), none, or the CRM's user id",
|
|
37
|
+
}),
|
|
38
|
+
],
|
|
39
|
+
};
|
|
40
|
+
const crmActivity = v.strictObject({
|
|
41
|
+
external_id: text,
|
|
42
|
+
kind: v.picklist(CRM_ACTIVITY_KINDS),
|
|
43
|
+
subject: text,
|
|
44
|
+
body: nullableText,
|
|
45
|
+
due_at: v.nullable(time),
|
|
46
|
+
done: v.boolean(),
|
|
47
|
+
done_at: v.nullable(time),
|
|
48
|
+
/** The identity `<account>/user/<id>` responsible for it. */
|
|
49
|
+
assignee: nullableText,
|
|
50
|
+
created_at: time,
|
|
51
|
+
updated_at: time,
|
|
52
|
+
on: v.array(v.strictObject({ kind: v.picklist(CRM_KINDS), external_id: text, ref: nullableText, title: nullableText })),
|
|
53
|
+
untrusted: v.array(text),
|
|
54
|
+
});
|
|
55
|
+
const UNTRUSTED = ["subject", "body", "on.title"];
|
|
56
|
+
const iso = (at) => (at === null ? null : new Date(at).toISOString());
|
|
57
|
+
const itemOf = (one) => ({
|
|
58
|
+
external_id: one.externalId,
|
|
59
|
+
kind: one.kind,
|
|
60
|
+
subject: one.subject,
|
|
61
|
+
body: one.body,
|
|
62
|
+
due_at: iso(one.dueAt),
|
|
63
|
+
done: one.done,
|
|
64
|
+
done_at: iso(one.doneAt),
|
|
65
|
+
assignee: one.assignee,
|
|
66
|
+
created_at: new Date(one.createdAt).toISOString(),
|
|
67
|
+
updated_at: new Date(one.updatedAt).toISOString(),
|
|
68
|
+
on: one.on.map(({ kind, externalId, ref, title }) => ({ kind, external_id: externalId, ref, title })),
|
|
69
|
+
untrusted: UNTRUSTED,
|
|
70
|
+
});
|
|
71
|
+
/** `activities list`: the copy's CRM activities and tasks, mounted when the CLI copies them (WC-ARCH-5). */
|
|
72
|
+
export const addCrmActivityCommands = (program, options) => {
|
|
73
|
+
const { within, example, now, ownerOf, pathOf } = options;
|
|
74
|
+
const group = annotate(program.command("activities"), { effects: NO_EFFECTS }).description("the CRM's activities and tasks on deals, leads, contacts and companies, as last synced");
|
|
75
|
+
example(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), "crm_activity", crmActivity)
|
|
76
|
+
.description("activities copied from the CRM, open ones first by due time, then the rest newest first; status:open " +
|
|
77
|
+
"unless a status is given; the activities setting must be on")
|
|
78
|
+
.option("--limit <n>", `activities per page, 1–${MOST}`, integer(MOST), 50)
|
|
79
|
+
.option("--page <n>", "which page, starting at 1", integer(1_000_000), 1), ACTIVITIES_QUERY), "activities list overdue:true", "activities list due:today --json", "activities list deal:12 status:done").action(async (words, opts, command) => {
|
|
80
|
+
const name = "activities list";
|
|
81
|
+
const terms = queryTerms(words, ACTIVITIES_QUERY, name, ["due"]);
|
|
82
|
+
const clock = now();
|
|
83
|
+
const due = timeBounds(nativeTerms(listQuery(typedQuery(words), ACTIVITIES_QUERY, name), name).get("due"), timezoneOf(), clock);
|
|
84
|
+
const refs = REFS.filter((kind) => terms.has(kind));
|
|
85
|
+
if (refs.length > 1)
|
|
86
|
+
throw new CliError("validation_error", `name one of ${refs.join(", ")}: an activity list is on one row`, {
|
|
87
|
+
reason: "query.unsupported-placement",
|
|
88
|
+
});
|
|
89
|
+
const ref = refs[0];
|
|
90
|
+
await within(command, async (run) => {
|
|
91
|
+
const paged = { limit: opts.limit, page: opts.page, ...(words.length ? { args: { query: words } } : {}) };
|
|
92
|
+
if (!(await run.store.crm.activitiesOn(run.account)))
|
|
93
|
+
return listOf(pathOf(command).join(" "), {
|
|
94
|
+
items: [],
|
|
95
|
+
...paged,
|
|
96
|
+
has_more: false,
|
|
97
|
+
missing: [
|
|
98
|
+
{
|
|
99
|
+
field: "activities",
|
|
100
|
+
why: `the activities setting is off: config set ${crmSettingKey(run.account, "activities")} on, then sync`,
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
});
|
|
104
|
+
const found = await run.store.crm.activities(run.account, {
|
|
105
|
+
status: terms.get("status") ??
|
|
106
|
+
(terms.get("overdue") === "true" ? undefined : "open"),
|
|
107
|
+
...(due.since === undefined && due.until === undefined
|
|
108
|
+
? {}
|
|
109
|
+
: {
|
|
110
|
+
due: {
|
|
111
|
+
...(due.since === undefined ? {} : { since: due.since }),
|
|
112
|
+
...(due.until === undefined ? {} : { until: due.until }),
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
...(terms.get("overdue") === "true" ? { overdueAt: clock } : {}),
|
|
116
|
+
viewer: await viewerOf(run),
|
|
117
|
+
...(terms.has("kind") ? { kinds: [terms.get("kind")] } : {}),
|
|
118
|
+
...(ref ? { on: refOf(ref, terms.get(ref)) } : {}),
|
|
119
|
+
...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
|
|
120
|
+
limit: opts.limit,
|
|
121
|
+
offset: (opts.page - 1) * opts.limit,
|
|
122
|
+
});
|
|
123
|
+
return listOf(pathOf(command).join(" "), {
|
|
124
|
+
items: found.items.map(itemOf),
|
|
125
|
+
...paged,
|
|
126
|
+
has_more: found.hasMore,
|
|
127
|
+
...(due.meta ? { meta: due.meta } : {}),
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
/** `deal:12` as typed, or a bare id for the field it was given to. */
|
|
133
|
+
const refOf = (kind, value) => (value.includes(":") ? value : `${kind}:${value}`);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Command } from "commander";
|
|
2
|
+
import type { AppIdentity } from "../../ports/app.js";
|
|
3
|
+
import type { CrmRun, CrmWithin } from "./index.js";
|
|
4
|
+
export declare const CHANGES_QUERY: {
|
|
5
|
+
readonly entity: "crm_change";
|
|
6
|
+
readonly backend: "native";
|
|
7
|
+
readonly fields: readonly [import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec];
|
|
8
|
+
};
|
|
9
|
+
export interface CrmChangeCommandOptions {
|
|
10
|
+
within: CrmWithin;
|
|
11
|
+
example: (command: Command, ...lines: string[]) => Command;
|
|
12
|
+
open: (command: Command, access: {
|
|
13
|
+
readOnly: boolean;
|
|
14
|
+
}) => Promise<CrmRun>;
|
|
15
|
+
app: AppIdentity;
|
|
16
|
+
now: () => number;
|
|
17
|
+
ownerOf: (run: CrmRun, owner: string) => Promise<string | null>;
|
|
18
|
+
pathOf: (command: Command) => string[];
|
|
19
|
+
/** Also mount `activities list`, for a CLI that copies the CRM's activities. */
|
|
20
|
+
activities?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** `changes list`: what happened in the copy in a window, newest first; `--format report` is the morning digest. */
|
|
23
|
+
export declare const addCrmChangeCommands: (program: Command, options: CrmChangeCommandOptions) => void;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { annotate, annotateOption } from "@wirecat/cli-base/commands";
|
|
3
|
+
import { timezoneOf } from "@wirecat/cli-base/query";
|
|
4
|
+
import { Option } from "commander";
|
|
5
|
+
import * as v from "valibot";
|
|
6
|
+
import { answerEntity } from "../../cli/answer-entity.js";
|
|
7
|
+
import { inCommandRun, outputFor } from "../../cli/context.js";
|
|
8
|
+
import { LOCAL_READ, NO_EFFECTS } from "../../cli/effects.js";
|
|
9
|
+
import { listOf } from "../../cli/envelope.js";
|
|
10
|
+
import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds, typedQuery, withQuery, } from "../../cli/list-query.js";
|
|
11
|
+
import { ownerLanguageOf } from "../../cli/schedule/schedule-command.js";
|
|
12
|
+
import { CRM_ACTIVITY_KINDS, CRM_KINDS } from "../../domain/crm.js";
|
|
13
|
+
import { text, time } from "../../entities/fields.js";
|
|
14
|
+
import { foldName } from "../../resolve.js";
|
|
15
|
+
import { CRM_CHANGES } from "../../store/sqlite/crm-changes.js";
|
|
16
|
+
import { crmDigest } from "../digest.js";
|
|
17
|
+
import { SYNCED_FROM } from "../sync.js";
|
|
18
|
+
import { shortened, viewerOf } from "../viewer.js";
|
|
19
|
+
import { addCrmActivityCommands } from "./activities.js";
|
|
20
|
+
import { csvColumnPaths, printCsv, refuseCsvConflict } from "./csv.js";
|
|
21
|
+
import { integer } from "./records.js";
|
|
22
|
+
const MOST = 500;
|
|
23
|
+
const DAY = 86_400_000;
|
|
24
|
+
const nullableText = v.nullable(text);
|
|
25
|
+
export const CHANGES_QUERY = {
|
|
26
|
+
entity: "crm_change",
|
|
27
|
+
backend: "native",
|
|
28
|
+
fields: [
|
|
29
|
+
nativeField({
|
|
30
|
+
name: "at",
|
|
31
|
+
type: "time",
|
|
32
|
+
operators: ["term", "range"],
|
|
33
|
+
example: "at>=1d",
|
|
34
|
+
relation: "when it happened; the last day when left out",
|
|
35
|
+
}),
|
|
36
|
+
termField("change", "enum", "change:won", { values: CRM_CHANGES }),
|
|
37
|
+
termField("owner", "kw", "owner:me", {
|
|
38
|
+
relation: "the CRM user its deal, lead or contact is assigned to: me, none, or the CRM's user id",
|
|
39
|
+
}),
|
|
40
|
+
termField("pipeline", "kw", "pipeline:Sales", { relation: "pipeline:<id>, or a name only one pipeline has" }),
|
|
41
|
+
],
|
|
42
|
+
};
|
|
43
|
+
const crmChange = v.strictObject({
|
|
44
|
+
change: v.picklist(CRM_CHANGES),
|
|
45
|
+
at: time,
|
|
46
|
+
kind: v.picklist(CRM_KINDS),
|
|
47
|
+
ref: nullableText,
|
|
48
|
+
external_id: text,
|
|
49
|
+
account: v.strictObject({ provider: text, account: text }),
|
|
50
|
+
title: nullableText,
|
|
51
|
+
pipeline: nullableText,
|
|
52
|
+
pipeline_name: nullableText,
|
|
53
|
+
from: nullableText,
|
|
54
|
+
to: nullableText,
|
|
55
|
+
amount: nullableText,
|
|
56
|
+
currency: nullableText,
|
|
57
|
+
exact: v.boolean(),
|
|
58
|
+
reason: nullableText,
|
|
59
|
+
owner: nullableText,
|
|
60
|
+
activity: v.nullable(v.strictObject({
|
|
61
|
+
external_id: text,
|
|
62
|
+
kind: v.picklist(CRM_ACTIVITY_KINDS),
|
|
63
|
+
subject: text,
|
|
64
|
+
due_at: v.nullable(time),
|
|
65
|
+
done: v.boolean(),
|
|
66
|
+
})),
|
|
67
|
+
untrusted: v.array(text),
|
|
68
|
+
});
|
|
69
|
+
const UNTRUSTED = ["title", "from", "to", "pipeline_name", "reason", "activity.subject"];
|
|
70
|
+
const CSV_COLUMNS = [
|
|
71
|
+
"change",
|
|
72
|
+
"at",
|
|
73
|
+
"kind",
|
|
74
|
+
"ref",
|
|
75
|
+
"title",
|
|
76
|
+
"from",
|
|
77
|
+
"to",
|
|
78
|
+
"amount",
|
|
79
|
+
"currency",
|
|
80
|
+
"reason",
|
|
81
|
+
"owner",
|
|
82
|
+
"activity.subject",
|
|
83
|
+
];
|
|
84
|
+
const itemOf = (run, one) => ({
|
|
85
|
+
change: one.change,
|
|
86
|
+
at: new Date(one.at).toISOString(),
|
|
87
|
+
kind: one.kind,
|
|
88
|
+
ref: one.ref,
|
|
89
|
+
external_id: one.externalId,
|
|
90
|
+
account: { provider: run.account.provider, account: run.account.account },
|
|
91
|
+
title: one.title,
|
|
92
|
+
pipeline: one.pipeline,
|
|
93
|
+
pipeline_name: one.pipelineName,
|
|
94
|
+
from: one.from,
|
|
95
|
+
to: one.to,
|
|
96
|
+
amount: one.amount,
|
|
97
|
+
currency: one.currency,
|
|
98
|
+
exact: one.exact,
|
|
99
|
+
reason: one.reason,
|
|
100
|
+
owner: one.owner,
|
|
101
|
+
activity: one.activity && {
|
|
102
|
+
external_id: one.activity.externalId,
|
|
103
|
+
kind: one.activity.kind,
|
|
104
|
+
subject: one.activity.subject,
|
|
105
|
+
due_at: one.activity.dueAt === null ? null : new Date(one.activity.dueAt).toISOString(),
|
|
106
|
+
done: one.activity.done,
|
|
107
|
+
},
|
|
108
|
+
untrusted: UNTRUSTED,
|
|
109
|
+
});
|
|
110
|
+
const cursorOf = (at) => Buffer.from(JSON.stringify(at)).toString("base64url");
|
|
111
|
+
const positionOf = (cursor) => {
|
|
112
|
+
try {
|
|
113
|
+
const at = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
114
|
+
if ([at.since, at.until, at.offset].every((one) => Number.isSafeInteger(one)))
|
|
115
|
+
return at;
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
118
|
+
throw new CliError("validation_error", "--cursor is not one a changes list answer gave", {
|
|
119
|
+
reason: "input.invalid",
|
|
120
|
+
});
|
|
121
|
+
};
|
|
122
|
+
/** The sync state a scheduled digest keeps the end of its last window in, so the next one starts there. */
|
|
123
|
+
const digestState = (schedule) => `crm:digest:${schedule}`;
|
|
124
|
+
/** `changes list`: what happened in the copy in a window, newest first; `--format report` is the morning digest. */
|
|
125
|
+
export const addCrmChangeCommands = (program, options) => {
|
|
126
|
+
const { within, example, now, ownerOf, pathOf } = options;
|
|
127
|
+
if (options.activities)
|
|
128
|
+
addCrmActivityCommands(program, { within, example, now, ownerOf, pathOf });
|
|
129
|
+
const group = annotate(program.command("changes"), { effects: NO_EFFECTS }).description("what changed in the CRM's deals, leads, activities and contacts, as the syncs copied it");
|
|
130
|
+
example(withQuery(answerEntity(annotate(group.command("list"), { effects: LOCAL_READ }), "crm_change", crmChange)
|
|
131
|
+
.description("deals and leads made, moved, won, lost and given another owner, activities added and done, and contacts " +
|
|
132
|
+
"added, newest first; the last day unless at: says otherwise")
|
|
133
|
+
.option("--limit <n>", `changes per page, 1–${MOST}`, integer(MOST), 50)
|
|
134
|
+
.option("--cursor <cursor>", "the next page, as the last answer's page.next gave it")
|
|
135
|
+
.addOption(annotateOption(new Option("--format <format>", "csv: this page as a table; report: the window as a morning digest document, for schedule command. " +
|
|
136
|
+
"Run by a schedule, the report starts where that schedule's last one ended").choices(["csv", "report"]), { mcp: false })), CHANGES_QUERY), 'changes list "at>=1d"', "changes list change:won at>=7d --json", 'changes list "at>=1d" --format report').action(async (words, opts, command) => {
|
|
137
|
+
const name = "changes list";
|
|
138
|
+
const terms = queryTerms(words, CHANGES_QUERY, name, ["at"]);
|
|
139
|
+
const zone = timezoneOf();
|
|
140
|
+
const clock = now();
|
|
141
|
+
const at = timeBounds(nativeTerms(listQuery(typedQuery(words), CHANGES_QUERY, name), name).get("at"), zone, clock);
|
|
142
|
+
const until = at.until ?? clock;
|
|
143
|
+
const position = opts.cursor ? positionOf(opts.cursor) : { since: at.since ?? until - DAY, until, offset: 0 };
|
|
144
|
+
const filterOf = async (run, window) => ({
|
|
145
|
+
...window,
|
|
146
|
+
viewer: await viewerOf(run),
|
|
147
|
+
...(terms.has("change") ? { changes: [terms.get("change")] } : {}),
|
|
148
|
+
...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
|
|
149
|
+
...(terms.has("pipeline") ? { pipeline: await pipelineOf(run, terms.get("pipeline")) } : {}),
|
|
150
|
+
});
|
|
151
|
+
const read = async (run) => {
|
|
152
|
+
const found = await run.store.crm.changes(run.account, {
|
|
153
|
+
...(await filterOf(run, position)),
|
|
154
|
+
limit: opts.limit,
|
|
155
|
+
offset: position.offset,
|
|
156
|
+
});
|
|
157
|
+
const next = found.hasMore ? cursorOf({ ...position, offset: position.offset + opts.limit }) : undefined;
|
|
158
|
+
return { items: found.items.map((one) => itemOf(run, one)), next };
|
|
159
|
+
};
|
|
160
|
+
const noted = (run) => {
|
|
161
|
+
const note = shortened.get(run);
|
|
162
|
+
if (note)
|
|
163
|
+
outputFor(command).renderer.note(note);
|
|
164
|
+
return note;
|
|
165
|
+
};
|
|
166
|
+
if (opts.format === "report") {
|
|
167
|
+
if (terms.size)
|
|
168
|
+
throw new CliError("validation_error", "--format report takes only at: — the digest covers every change", {
|
|
169
|
+
reason: "query.unsupported-placement",
|
|
170
|
+
});
|
|
171
|
+
const env = { ...process.env };
|
|
172
|
+
const schedule = env[`${options.app.envPrefix}_SCHEDULED`];
|
|
173
|
+
return inCommandRun(command, async () => {
|
|
174
|
+
const run = await options.open(command, { readOnly: schedule === undefined });
|
|
175
|
+
let printed = false;
|
|
176
|
+
try {
|
|
177
|
+
const last = schedule && (await run.store.sync.syncState(run.account, digestState(schedule)))?.value;
|
|
178
|
+
// A change the CRM made before the last complete sync started is in the copy; a later one may not be yet.
|
|
179
|
+
const synced = Number((await run.store.sync.syncState(run.account, SYNCED_FROM))?.value || Number.NaN);
|
|
180
|
+
const end = Math.min(last ? clock : position.until, Number.isNaN(synced) ? clock : synced);
|
|
181
|
+
const since = last ? Number(last) + 1 : position.since;
|
|
182
|
+
const window = { since, until: Math.max(since, end) };
|
|
183
|
+
const document = await crmDigest(run.store, run.account, {
|
|
184
|
+
...window,
|
|
185
|
+
now: clock,
|
|
186
|
+
zone,
|
|
187
|
+
language: await ownerLanguageOf(run.env ?? env),
|
|
188
|
+
profile: run.profile,
|
|
189
|
+
viewer: await viewerOf(run),
|
|
190
|
+
...(shortened.has(run) ? { hidden: true } : {}),
|
|
191
|
+
});
|
|
192
|
+
outputFor(command).streams.data(`${JSON.stringify(document)}\n`);
|
|
193
|
+
noted(run);
|
|
194
|
+
// Moved only once the report is out, so a run that fails before then shows its window next time.
|
|
195
|
+
if (schedule)
|
|
196
|
+
await run.store.sync.setSyncState(run.account, digestState(schedule), String(Math.max(since - 1, end)));
|
|
197
|
+
printed = true;
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
// Once the report is out and its window spent, a failed close must not fail the run: it would go unsent.
|
|
201
|
+
await run.close?.().catch((error) => {
|
|
202
|
+
if (!printed)
|
|
203
|
+
throw error;
|
|
204
|
+
outputFor(command).renderer.note(`the store did not close cleanly: ${String(error)}`);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (opts.format === "csv") {
|
|
210
|
+
refuseCsvConflict(command);
|
|
211
|
+
return inCommandRun(command, async () => {
|
|
212
|
+
const run = await options.open(command, { readOnly: true });
|
|
213
|
+
try {
|
|
214
|
+
const found = await read(run);
|
|
215
|
+
printCsv(command, { items: found.items, fields: [], page: 1, hasMore: false }, csvColumnPaths(command, CSV_COLUMNS));
|
|
216
|
+
noted(run);
|
|
217
|
+
if (found.next)
|
|
218
|
+
outputFor(command).renderer.note(`→ more rows: run it again with --cursor ${found.next}`);
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
await run.close?.();
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
await within(command, async (run) => {
|
|
226
|
+
const found = await read(run);
|
|
227
|
+
return listOf(pathOf(command).join(" "), {
|
|
228
|
+
items: found.items,
|
|
229
|
+
limit: opts.limit,
|
|
230
|
+
has_more: found.next !== undefined,
|
|
231
|
+
paging: "cursor",
|
|
232
|
+
...(found.next ? { cursor: found.next } : {}),
|
|
233
|
+
...(words.length ? { args: { query: words } } : {}),
|
|
234
|
+
meta: {
|
|
235
|
+
timezone: zone,
|
|
236
|
+
window: { since: new Date(position.since).toISOString(), until: new Date(position.until).toISOString() },
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
/** `pipeline:` as a store id: `pipeline:<id>`, or the name only one of the account's pipelines has. */
|
|
243
|
+
const pipelineOf = async (run, value) => {
|
|
244
|
+
const all = await run.store.deals.pipelines({ account: run.account, viewer: await viewerOf(run) });
|
|
245
|
+
const found = /^pipeline:\d+$/.test(value)
|
|
246
|
+
? all.filter((one) => one.ref === value)
|
|
247
|
+
: all.filter((one) => foldName(one.name) === foldName(value));
|
|
248
|
+
if (found.length === 1)
|
|
249
|
+
return Number(found[0]?.id);
|
|
250
|
+
throw found.length
|
|
251
|
+
? new CliError("validation_error", `more than one pipeline is named ${value}; name one by its reference`, {
|
|
252
|
+
reason: "pipeline.ambiguous",
|
|
253
|
+
})
|
|
254
|
+
: new CliError("not_found", `no pipeline ${value} in this account`, { reason: "pipeline.not-found" });
|
|
255
|
+
};
|
package/dist/crm/cli/index.d.ts
CHANGED
|
@@ -54,6 +54,7 @@ export interface CrmCommandOptions {
|
|
|
54
54
|
* `source.list`/`get`, `user` mounts `users` list/show over `source.users`. None when absent.
|
|
55
55
|
*/
|
|
56
56
|
live?: readonly CrmLiveRecord[];
|
|
57
|
+
activities?: boolean;
|
|
57
58
|
now?: () => number;
|
|
58
59
|
}
|
|
59
60
|
/** What `deals list` and `leads list` narrow by, the same in memo and every CRM CLI (WC-OUT-11). */
|
package/dist/crm/cli/index.js
CHANGED
|
@@ -23,9 +23,10 @@ import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
|
|
|
23
23
|
import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
|
|
24
24
|
import { seenBy } from "../../store/store.js";
|
|
25
25
|
import { openStageTasks } from "../stage-tasks.js";
|
|
26
|
-
import { crmStatus,
|
|
26
|
+
import { crmStatus, syncRecorded } from "../sync.js";
|
|
27
27
|
import { shortened, viewerOf } from "../viewer.js";
|
|
28
28
|
import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
|
|
29
|
+
import { addCrmChangeCommands } from "./changes.js";
|
|
29
30
|
import { csvFormatOption, renderCsv } from "./csv.js";
|
|
30
31
|
import { pipelineView } from "./pipeline-view.js";
|
|
31
32
|
import { addCrmRecordCommands, integer } from "./records.js";
|
|
@@ -240,13 +241,14 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
240
241
|
const { signal } = environmentOf(command);
|
|
241
242
|
await within(command, async (run) => {
|
|
242
243
|
const source = run.source();
|
|
243
|
-
const
|
|
244
|
-
|
|
244
|
+
const started = now();
|
|
245
|
+
const report = await syncRecorded(source, run.store, run.account, {
|
|
246
|
+
now: started,
|
|
245
247
|
budget: runBudgetOf(command, opts.maxPages),
|
|
246
248
|
...(signal ? { signal } : {}),
|
|
247
249
|
...(opts.rescan ? { rescan: true } : {}),
|
|
248
250
|
});
|
|
249
|
-
const stageTasks = await openStageTasks(run.store, run.account,
|
|
251
|
+
const stageTasks = await openStageTasks(run.store, run.account, started, {
|
|
250
252
|
history: source.stageHistory !== undefined,
|
|
251
253
|
});
|
|
252
254
|
const failed = report.synced.filter((one) => one.error !== undefined);
|
|
@@ -649,6 +651,7 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
649
651
|
...(writes ? { writes } : {}),
|
|
650
652
|
now,
|
|
651
653
|
});
|
|
654
|
+
addCrmChangeCommands(program, { ...options, within, example, now, ownerOf, pathOf });
|
|
652
655
|
const fieldKinds = Object.keys(FIELD_KINDS).filter((word) => word !== "leads" || options.leads !== false);
|
|
653
656
|
const fields = annotate(program.command("fields"), { effects: NO_EFFECTS }).description("the CRM's own fields on deals, leads, people and organizations, as last synced");
|
|
654
657
|
example(withQuery(answerEntity(annotate(fields.command("list"), { effects: LOCAL_READ }), "crm_field", crmField)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type CopyViewer } from "../store/sqlite/copy-viewer.js";
|
|
2
|
+
import type { MessageStore } from "../store/store.js";
|
|
3
|
+
import type { AccountKey } from "../store/types.js";
|
|
4
|
+
export interface CrmDigestOptions {
|
|
5
|
+
/** The window, both ends inclusive, epoch ms. */
|
|
6
|
+
since: number;
|
|
7
|
+
until: number;
|
|
8
|
+
now: number;
|
|
9
|
+
/** The owner's zone: the end of today. */
|
|
10
|
+
zone: string;
|
|
11
|
+
/** The owner's language, `ru` or `en`, for the few words the digest writes itself. */
|
|
12
|
+
language: string;
|
|
13
|
+
/** The profile's name, for the sync's age. */
|
|
14
|
+
profile: string;
|
|
15
|
+
/** A profile that may read only part of the copy (SEC-197). */
|
|
16
|
+
viewer?: CopyViewer;
|
|
17
|
+
/** The viewer's rule hid rows it should not have: the summary says so. */
|
|
18
|
+
hidden?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A CRM account's morning digest as a `wirecat.report/1` document: one `crm` section. Deals won and lost come first
|
|
22
|
+
* and are never pushed out; then overdue CRM tasks, those due today, stage moves, new deals, owner changes, new
|
|
23
|
+
* contacts as one count, and the tasks the stage rules opened. Each kind is read with its own small limit and counted
|
|
24
|
+
* in SQL, so `more` counts every row left out. Only an activity's subject is shown, never its text. `health` names a
|
|
25
|
+
* last sync that failed or one older than a day.
|
|
26
|
+
*/
|
|
27
|
+
export declare const crmDigest: (store: MessageStore, account: AccountKey, options: CrmDigestOptions) => Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { zonedMoment } from "@wirecat/cli-base/query";
|
|
2
|
+
import { REPORT_FORMAT } from "../background/report/schema.js";
|
|
3
|
+
import { SECTION_CAPS } from "../background/report/view.js";
|
|
4
|
+
import { dayIn } from "../domain/moment.js";
|
|
5
|
+
import { taskAccount } from "../services/task-rules.js";
|
|
6
|
+
import { viewerSql } from "../store/sqlite/copy-viewer.js";
|
|
7
|
+
import { crmStatus, SYNC_FAILED } from "./sync.js";
|
|
8
|
+
const HOUR = 3_600_000;
|
|
9
|
+
const STALE_HOURS = 24;
|
|
10
|
+
const WORDS = {
|
|
11
|
+
en: {
|
|
12
|
+
won: "won",
|
|
13
|
+
lost: "lost",
|
|
14
|
+
newDeal: "new",
|
|
15
|
+
newOwner: "new owner",
|
|
16
|
+
contacts: "new contacts",
|
|
17
|
+
hidden: "Part of the CRM copy is hidden from this profile: see the command's note",
|
|
18
|
+
},
|
|
19
|
+
ru: {
|
|
20
|
+
won: "выиграна",
|
|
21
|
+
lost: "проиграна",
|
|
22
|
+
newDeal: "новая",
|
|
23
|
+
newOwner: "новый ответственный",
|
|
24
|
+
contacts: "новые контакты",
|
|
25
|
+
hidden: "Часть копии CRM скрыта от этого профиля: см. примечание команды",
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
const iso = (at) => (at === null ? null : new Date(at).toISOString());
|
|
29
|
+
/** The last moment of `now`'s day in `zone`. */
|
|
30
|
+
const endOfDay = (now, zone) => {
|
|
31
|
+
const day = dayIn(now, zone);
|
|
32
|
+
return zonedMoment(day, zone, { start: 0, end: day.length }, { end: true });
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* A CRM account's morning digest as a `wirecat.report/1` document: one `crm` section. Deals won and lost come first
|
|
36
|
+
* and are never pushed out; then overdue CRM tasks, those due today, stage moves, new deals, owner changes, new
|
|
37
|
+
* contacts as one count, and the tasks the stage rules opened. Each kind is read with its own small limit and counted
|
|
38
|
+
* in SQL, so `more` counts every row left out. Only an activity's subject is shown, never its text. `health` names a
|
|
39
|
+
* last sync that failed or one older than a day.
|
|
40
|
+
*/
|
|
41
|
+
export const crmDigest = async (store, account, options) => {
|
|
42
|
+
const { since, until, now, zone, viewer } = options;
|
|
43
|
+
const words = options.language === "ru" ? WORDS.ru : WORDS.en;
|
|
44
|
+
const cap = SECTION_CAPS.crm;
|
|
45
|
+
const window = { since, until, ...(viewer ? { viewer } : {}) };
|
|
46
|
+
const counts = await store.crm.changeCounts(account, window);
|
|
47
|
+
const changesOf = async (kind) => counts[kind] ? (await store.crm.changes(account, { ...window, changes: [kind], limit: cap, offset: 0 })).items : [];
|
|
48
|
+
const activitiesOn = await store.crm.activitiesOn(account);
|
|
49
|
+
const tasks = async (filter) => {
|
|
50
|
+
if (!activitiesOn)
|
|
51
|
+
return { items: [], count: 0 };
|
|
52
|
+
const wanted = { status: "open", ...filter, ...(viewer ? { viewer } : {}) };
|
|
53
|
+
return {
|
|
54
|
+
items: (await store.crm.activities(account, { ...wanted, limit: cap, offset: 0 })).items,
|
|
55
|
+
count: await store.crm.activityCount(account, wanted),
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
const overdue = await tasks({ overdueAt: now });
|
|
59
|
+
const today = await tasks({ due: { since: now, until: endOfDay(now, zone) } });
|
|
60
|
+
const task = (high) => (one) => {
|
|
61
|
+
const on = one.on.find((target) => target.ref !== null);
|
|
62
|
+
return {
|
|
63
|
+
type: "task",
|
|
64
|
+
topic: one.subject || one.kind,
|
|
65
|
+
who: on?.title ?? null,
|
|
66
|
+
due: iso(one.dueAt),
|
|
67
|
+
priority: high ? "high" : "normal",
|
|
68
|
+
channel: "crm",
|
|
69
|
+
refs: on?.ref ? [on.ref] : [],
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
const fact = (change, detail) => ({
|
|
73
|
+
type: "fact",
|
|
74
|
+
topic: change.title ?? change.externalId,
|
|
75
|
+
detail,
|
|
76
|
+
time: iso(change.at),
|
|
77
|
+
channel: "crm",
|
|
78
|
+
refs: change.ref ? [change.ref] : [],
|
|
79
|
+
});
|
|
80
|
+
const won = (await changesOf("won")).map((change) => change.amount !== null && change.currency !== null
|
|
81
|
+
? {
|
|
82
|
+
type: "money",
|
|
83
|
+
who: change.title ?? change.externalId,
|
|
84
|
+
topic: words.won,
|
|
85
|
+
amount: { value: Number(change.amount), currency: change.currency, direction: "in" },
|
|
86
|
+
channel: "crm",
|
|
87
|
+
refs: change.ref ? [change.ref] : [],
|
|
88
|
+
}
|
|
89
|
+
: fact(change, words.won));
|
|
90
|
+
const lost = (await changesOf("lost")).map((change) => fact(change, change.reason ? `${words.lost}: ${change.reason}` : words.lost));
|
|
91
|
+
const people = counts.person_added;
|
|
92
|
+
const seen = viewerSql("d", viewer);
|
|
93
|
+
const opened = await store.tasks.find({
|
|
94
|
+
where: {
|
|
95
|
+
sql: "t.source = 'rule' AND t.source_kind IN ('deal', 'lead') AND t.created_at BETWEEN ? AND ? " +
|
|
96
|
+
"AND t.project_id IN (SELECT id FROM projects WHERE name = ?) " +
|
|
97
|
+
// A rule task names its deal or lead: a viewer reads it only on one of its own.
|
|
98
|
+
`AND (EXISTS (SELECT 1 FROM deals d WHERE 'deal:' || d.id = t.source_group AND ${seen.sql}) ` +
|
|
99
|
+
`OR EXISTS (SELECT 1 FROM leads d WHERE 'lead:' || d.id = t.source_group AND ${seen.sql}))`,
|
|
100
|
+
params: [since, until, taskAccount(account), ...seen.params, ...seen.params],
|
|
101
|
+
},
|
|
102
|
+
limit: cap,
|
|
103
|
+
});
|
|
104
|
+
const rest = [
|
|
105
|
+
...overdue.items.map(task(true)),
|
|
106
|
+
...today.items.map(task(false)),
|
|
107
|
+
...(await changesOf("moved")).map((change) => fact(change, `${change.from ?? "?"} → ${change.to ?? "?"}`)),
|
|
108
|
+
...(await changesOf("created")).map((change) => fact(change, words.newDeal)),
|
|
109
|
+
...(await changesOf("owner_changed")).map((change) => fact(change, words.newOwner)),
|
|
110
|
+
...(people ? [{ type: "fact", topic: words.contacts, detail: String(people), count: people, refs: [] }] : []),
|
|
111
|
+
...opened.items.map((one) => ({ type: "task", topic: one.title, due: one.dueAt ?? null, channel: "crm", refs: [one.ref] })),
|
|
112
|
+
];
|
|
113
|
+
const closed = [...won, ...lost];
|
|
114
|
+
const shown = [...closed.slice(0, cap), ...rest.slice(0, Math.max(0, cap - closed.length))];
|
|
115
|
+
const total = counts.won +
|
|
116
|
+
counts.lost +
|
|
117
|
+
overdue.count +
|
|
118
|
+
today.count +
|
|
119
|
+
counts.moved +
|
|
120
|
+
counts.created +
|
|
121
|
+
counts.owner_changed +
|
|
122
|
+
(people ? 1 : 0) +
|
|
123
|
+
opened.items.length +
|
|
124
|
+
(opened.hasMore ? 1 : 0);
|
|
125
|
+
return {
|
|
126
|
+
format: REPORT_FORMAT,
|
|
127
|
+
kind: "morning-digest",
|
|
128
|
+
date: dayIn(now, zone),
|
|
129
|
+
summary: options.hidden ? words.hidden : null,
|
|
130
|
+
sections: shown.length ? [{ kind: "crm", items: shown.map(masked), more: Math.max(0, total - shown.length) }] : [],
|
|
131
|
+
health: await healthOf(store, account, options),
|
|
132
|
+
scope: {
|
|
133
|
+
from: new Date(since).toISOString(),
|
|
134
|
+
to: new Date(until).toISOString(),
|
|
135
|
+
sources: [{ kind: "crm", accounts: 1 }],
|
|
136
|
+
counts: { chats: 0, mail: 0, tasks: opened.items.length, meetings: 0 },
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
const EMAIL = /[\p{L}\p{N}._%+-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)+/gu;
|
|
141
|
+
/** Nine digits or more, or a `+` and seven: a phone, never a date or an amount. */
|
|
142
|
+
const PHONE = /\+?\d[\d\s().-]{5,}\d/g;
|
|
143
|
+
const maskText = (text) => text.replace(EMAIL, "[e-mail]").replace(PHONE, (found) => {
|
|
144
|
+
const digits = found.replace(/\D/g, "").length;
|
|
145
|
+
return digits >= 9 || (found.startsWith("+") && digits >= 7) ? "[phone]" : found;
|
|
146
|
+
});
|
|
147
|
+
/** A digest goes to messengers: no CRM text in it carries a phone number or an e-mail address. */
|
|
148
|
+
const masked = (item) => Object.fromEntries(Object.entries(item).map(([key, value]) => [
|
|
149
|
+
key,
|
|
150
|
+
typeof value === "string" && key !== "due" && key !== "time" ? maskText(value) : value,
|
|
151
|
+
]));
|
|
152
|
+
/** A last sync that failed, else a copy whose oldest kind is more than a day old; a copy never synced is neither. */
|
|
153
|
+
const healthOf = async (store, account, { now, profile }) => {
|
|
154
|
+
const named = { source: account.provider, account: account.account, refs: [] };
|
|
155
|
+
const failed = (await store.sync.syncState(account, SYNC_FAILED))?.value;
|
|
156
|
+
if (failed) {
|
|
157
|
+
const at = Number(JSON.parse(failed).at);
|
|
158
|
+
return [{ ...named, reason: "sync-failed", ...(Number.isFinite(at) ? { since: iso(at) } : {}), stale_hours: 0 }];
|
|
159
|
+
}
|
|
160
|
+
const status = await crmStatus(store, account, { profile, now });
|
|
161
|
+
const synced = status.items.map((one) => (one.updated_at ? Date.parse(one.updated_at) : 0)).filter((at) => at > 0);
|
|
162
|
+
if (!synced.length)
|
|
163
|
+
return [];
|
|
164
|
+
const stale = (now - synced.reduce((oldest, at) => Math.min(oldest, at), now)) / HOUR;
|
|
165
|
+
return stale > STALE_HOURS ? [{ ...named, stale_hours: Math.floor(stale) }] : [];
|
|
166
|
+
};
|
|
@@ -3,7 +3,7 @@ import type { AccountKey } from "../store/types.js";
|
|
|
3
3
|
/**
|
|
4
4
|
* Opens the owner's task for each stage a deal or lead of the account entered that its `stage-tasks` setting names:
|
|
5
5
|
* one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
|
|
6
|
-
* Answers how many it opened.
|
|
6
|
+
* Answers how many it opened. `now` is the sync's start: the tasks then fall in the digest window that sync closes.
|
|
7
7
|
*/
|
|
8
8
|
export declare const openStageTasks: (store: MessageStore, account: AccountKey, now: number, { history }?: {
|
|
9
9
|
history?: boolean;
|