@wirecat/cli-core 0.677.0 → 0.679.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/background/budget.d.ts +2 -0
  3. package/dist/background/budget.js +2 -0
  4. package/dist/background/report/render.d.ts +3 -1
  5. package/dist/background/report/render.js +2 -2
  6. package/dist/background/report/schema.d.ts +7 -4
  7. package/dist/background/report/schema.js +23 -7
  8. package/dist/background/report/templates/morning-digest.email.en.liquid +3 -2
  9. package/dist/background/report/templates/morning-digest.email.ru.liquid +3 -2
  10. package/dist/background/report/templates/morning-digest.telegram.en.liquid +3 -2
  11. package/dist/background/report/templates/morning-digest.telegram.ru.liquid +3 -2
  12. package/dist/background/report/templates/morning-digest.text.en.liquid +3 -2
  13. package/dist/background/report/templates/morning-digest.text.ru.liquid +3 -2
  14. package/dist/background/report/view.js +2 -0
  15. package/dist/background/schedules.js +21 -11
  16. package/dist/cli/help/first-screen.js +5 -0
  17. package/dist/cli/list-query.d.ts +1 -1
  18. package/dist/cli/list-query.js +2 -2
  19. package/dist/cli/setup-command.js +26 -11
  20. package/dist/crm/cli/activities.d.ts +17 -0
  21. package/dist/crm/cli/activities.js +133 -0
  22. package/dist/crm/cli/changes.d.ts +23 -0
  23. package/dist/crm/cli/changes.js +255 -0
  24. package/dist/crm/cli/index.d.ts +1 -0
  25. package/dist/crm/cli/index.js +7 -4
  26. package/dist/crm/digest.d.ts +27 -0
  27. package/dist/crm/digest.js +166 -0
  28. package/dist/crm/stage-tasks.d.ts +1 -1
  29. package/dist/crm/stage-tasks.js +1 -1
  30. package/dist/crm/sync.d.ts +9 -0
  31. package/dist/crm/sync.js +27 -0
  32. package/dist/crm/testing/source.d.ts +5 -1
  33. package/dist/crm/testing/source.js +19 -0
  34. package/dist/crm/testing/sync-contract.d.ts +2 -0
  35. package/dist/crm/testing/sync-contract.js +56 -2
  36. package/dist/documents/scope.d.ts +3 -3
  37. package/dist/documents/scope.js +8 -4
  38. package/dist/entities/business-context.js +4 -0
  39. package/dist/entities/recorded-meeting.d.ts +1 -0
  40. package/dist/entities/recorded-meeting.js +2 -0
  41. package/dist/services/communications.d.ts +35 -0
  42. package/dist/services/communications.js +52 -2
  43. package/dist/services/documents/plan.js +27 -6
  44. package/dist/services/documents/sync.js +6 -2
  45. package/dist/services/index.d.ts +2 -1
  46. package/dist/services/index.js +1 -0
  47. package/dist/services/metadata.d.ts +1 -1
  48. package/dist/services/person-meetings.d.ts +2 -0
  49. package/dist/services/person-meetings.js +16 -1
  50. package/dist/store/index.d.ts +2 -0
  51. package/dist/store/index.js +1 -0
  52. package/dist/store/sqlite/crm-activities.d.ts +41 -1
  53. package/dist/store/sqlite/crm-activities.js +152 -14
  54. package/dist/store/sqlite/crm-changes.d.ts +84 -0
  55. package/dist/store/sqlite/crm-changes.js +199 -0
  56. package/dist/store/sqlite/crm.d.ts +2 -1
  57. package/dist/store/sqlite/crm.js +2 -0
  58. package/package.json +1 -1
@@ -0,0 +1,199 @@
1
+ import { formatDecimal, scaleOf } from "../../domain/money.js";
2
+ import { findAccountPk } from "./accounts.js";
3
+ import { ACTIVITY_RECORD, crmActivitiesOver } from "./crm-activities.js";
4
+ import { crmAccountPrefix, OWNER_CHANGE_RECORD, PERSON_RECORD } from "./crm-rows.js";
5
+ import { STAGE_ENTRY_RECORD } from "./crm-stage-entries.js";
6
+ export const CRM_CHANGES = [
7
+ "created",
8
+ "moved",
9
+ "won",
10
+ "lost",
11
+ "owner_changed",
12
+ "activity_added",
13
+ "activity_done",
14
+ "person_added",
15
+ ];
16
+ const HALF_DAY = 43_200_000;
17
+ const DAY = 86_400_000;
18
+ const utcDay = (at) => new Date(at).toISOString().slice(0, 10);
19
+ /** The SQL of every change in `filter`'s window, unordered, and its numbered parameters (`?13`, `?14` page it). */
20
+ const changesQuery = (context, key, filter) => {
21
+ const accountId = findAccountPk(context, key);
22
+ if (accountId === undefined)
23
+ return undefined;
24
+ // ?15 is set when a viewer limits the read, ?16 its assignee; `= NULL` then hides every row.
25
+ const items = (table, kind) => `SELECT '${kind}' AS kind, d.id, d.external_id, d.status, d.created_at, d.closed_date, ` +
26
+ `json_extract(d.metadata, '$.assignee') AS owner, s.pipeline_id FROM ${table} d ` +
27
+ "JOIN pipeline_stages s ON s.id = d.stage_id WHERE d.account_id = ?1 AND d.deleted_at IS NULL " +
28
+ "AND (?15 IS NULL OR json_extract(d.metadata, '$.assignee') = ?16)";
29
+ const entries = "SELECT r.id AS record, i.kind, i.id AS item, i.owner, i.pipeline_id, " +
30
+ "CAST(json_extract(r.fields, '$.at') AS INTEGER) AS at, CAST(json_extract(r.fields, '$.stage_id') AS INTEGER) AS stage, " +
31
+ "lag(CAST(json_extract(r.fields, '$.stage_id') AS INTEGER)) OVER (PARTITION BY i.kind, i.id " +
32
+ "ORDER BY json_extract(r.fields, '$.at'), r.id) AS before FROM records r " +
33
+ "JOIN record_relations rr ON rr.record_id = r.id AND rr.role = 'on' " +
34
+ "JOIN items i ON i.kind = rr.target_type AND i.external_id = rr.target_external_id " +
35
+ "WHERE r.account_id = ?1 AND r.type = ?2 AND r.deleted_at IS NULL";
36
+ const closing = "(SELECT outcome FROM pipeline_stages WHERE id = m.stage) IN ('won', 'lost')";
37
+ const itemOf = (record) => "(SELECT i.kind || ':' || i.id FROM record_relations rr JOIN items i ON i.kind = rr.target_type " +
38
+ `AND i.external_id = rr.target_external_id WHERE rr.record_id = ${record} AND rr.role = 'on' LIMIT 1)`;
39
+ const closedAt = "(SELECT max(m.at) FROM entries m WHERE m.kind = i.kind AND m.item = i.id " +
40
+ "AND (SELECT outcome FROM pipeline_stages WHERE id = m.stage) = i.status)";
41
+ const onDealOrLead = "EXISTS (SELECT 1 FROM record_relations x WHERE x.record_id = a.id AND x.role = 'on' " +
42
+ "AND x.target_type IN ('deal', 'lead'))";
43
+ const linkedToSeen = "EXISTS (SELECT 1 FROM identities n JOIN identity_links l ON l.identity_id = n.id " +
44
+ "JOIN links k ON k.to_type = 'person' AND k.to_id = l.person_id AND k.deleted_at IS NULL " +
45
+ "JOIN items v ON v.kind = k.from_type AND v.id = k.from_id WHERE n.provider = ?17 AND n.external_id = ?18 || r.external_id)";
46
+ const parts = [
47
+ "SELECT 'created' AS change, created_at AS at, kind, id AS item, NULL AS record, NULL AS from_id, NULL AS to_id, " +
48
+ "0 AS exact, owner, pipeline_id FROM items",
49
+ `SELECT 'moved', m.at, m.kind, m.item, m.record, m.before, m.stage, 1, m.owner, m.pipeline_id FROM entries m ` +
50
+ `WHERE m.before IS NOT NULL AND NOT ${closing}`,
51
+ "SELECT 'moved', c.changed_at, i.kind, i.id, NULL, c.from_stage_id, c.to_stage_id, 0, i.owner, i.pipeline_id " +
52
+ "FROM pipeline_stage_changes c JOIN items i ON i.kind = c.item_type AND i.id = c.item_id " +
53
+ "WHERE c.from_stage_id IS NOT NULL AND c.changed_at BETWEEN ?6 AND ?7 " +
54
+ "AND (SELECT outcome FROM pipeline_stages WHERE id = c.to_stage_id) NOT IN ('won', 'lost') " +
55
+ // The CRM's own entry of this move replaces it; an entry with no earlier one in the copy cannot say where from.
56
+ "AND NOT EXISTS (SELECT 1 FROM entries e WHERE e.kind = i.kind AND e.item = i.id " +
57
+ "AND e.stage = c.to_stage_id AND e.before IS NOT NULL)",
58
+ // The closed day only narrows the rows; the window is checked on `at`, so a deal is listed in one window only.
59
+ `SELECT i.status, coalesce(${closedAt}, CAST(strftime('%s', i.closed_date) AS INTEGER) * 1000 + ${HALF_DAY}), ` +
60
+ `i.kind, i.id, NULL, NULL, NULL, ${closedAt} IS NOT NULL, i.owner, i.pipeline_id FROM items i ` +
61
+ "WHERE i.status IN ('won', 'lost') AND i.closed_date BETWEEN ?8 AND ?9",
62
+ "SELECT 'owner_changed', CAST(json_extract(r.fields, '$.at') AS INTEGER), i.kind, i.id, r.id, NULL, NULL, 0, " +
63
+ "json_extract(r.fields, '$.to'), i.pipeline_id FROM records r " +
64
+ "JOIN record_relations rr ON rr.record_id = r.id AND rr.role = 'on' " +
65
+ "JOIN items i ON i.kind = rr.target_type AND i.external_id = rr.target_external_id " +
66
+ "WHERE r.account_id = ?1 AND r.type = ?3 AND r.deleted_at IS NULL " +
67
+ "AND json_extract(r.fields, '$.at') BETWEEN ?6 AND ?7",
68
+ ...["created_at", "done_at"].map((field) => `SELECT '${field === "created_at" ? "activity_added" : "activity_done"}', ` +
69
+ `CAST(json_extract(a.fields, '$.${field}') AS INTEGER), coalesce(substr(a.item, 1, instr(a.item, ':') - 1), a.target), ` +
70
+ "CAST(substr(a.item, instr(a.item, ':') + 1) AS INTEGER), a.id, NULL, NULL, 0, " +
71
+ "coalesce((SELECT owner FROM items i WHERE i.kind || ':' || i.id = a.item), " +
72
+ "json_extract(a.fields, '$.assignee')), (SELECT pipeline_id FROM items i WHERE i.kind || ':' || i.id = a.item) " +
73
+ `FROM (SELECT r.id, r.fields, ${itemOf("r.id")} AS item, (SELECT target_type FROM record_relations ` +
74
+ "WHERE record_id = r.id AND role = 'on' LIMIT 1) AS target FROM records r WHERE r.account_id = ?1 " +
75
+ `AND r.type = ?4 AND r.deleted_at IS NULL AND json_extract(r.fields, '$.${field}') ` +
76
+ "BETWEEN ?6 AND ?7) a " +
77
+ // A viewer reads an activity on its own deal or lead, or one on contacts alone that is assigned to it.
78
+ `WHERE ?15 IS NULL OR a.item IS NOT NULL OR (NOT ${onDealOrLead} AND json_extract(a.fields, '$.assignee') = ?16)`),
79
+ "SELECT 'person_added', CAST(json_extract(r.fields, '$.created_at') AS INTEGER), 'person', NULL, r.id, NULL, " +
80
+ "NULL, 0, json_extract(r.fields, '$.assignee'), NULL FROM records r WHERE r.account_id = ?1 " +
81
+ "AND r.type = ?5 AND r.deleted_at IS NULL AND json_extract(r.fields, '$.created_at') BETWEEN ?6 AND ?7 " +
82
+ `AND (?15 IS NULL OR json_extract(r.fields, '$.assignee') = ?16 OR ${linkedToSeen})`,
83
+ ];
84
+ const where = [
85
+ "at BETWEEN ?6 AND ?7",
86
+ ...(filter.changes?.length ? ["change IN (SELECT value FROM json_each(?10))"] : []),
87
+ ...(filter.owner === undefined ? [] : [filter.owner === null ? "owner IS NULL" : "owner = ?11"]),
88
+ ...(filter.pipeline === undefined ? [] : ["pipeline_id = ?12"]),
89
+ ];
90
+ return {
91
+ sql: `WITH items AS (${items("deals", "deal")} UNION ALL ${items("leads", "lead")}), entries AS (${entries}) ` +
92
+ `SELECT * FROM (${parts.join(" UNION ALL ")}) WHERE ${where.join(" AND ")}`,
93
+ params: [
94
+ accountId,
95
+ STAGE_ENTRY_RECORD,
96
+ OWNER_CHANGE_RECORD,
97
+ ACTIVITY_RECORD,
98
+ PERSON_RECORD,
99
+ filter.since,
100
+ filter.until,
101
+ // A day without a time is taken at its noon in UTC, which is never more than a day from the window's days.
102
+ utcDay(filter.since - DAY),
103
+ utcDay(filter.until + DAY),
104
+ filter.changes?.length ? JSON.stringify(filter.changes) : null,
105
+ filter.owner ?? null,
106
+ filter.pipeline ?? null,
107
+ filter.limit + 1,
108
+ filter.offset,
109
+ filter.viewer ? 1 : null,
110
+ filter.viewer?.assignee ?? null,
111
+ key.provider,
112
+ `${crmAccountPrefix(key)}contact/`,
113
+ ],
114
+ };
115
+ };
116
+ /** How many changes of each kind `filter`'s window holds, every page together. */
117
+ export const crmChangeCounts = (context, key, filter) => {
118
+ const counts = Object.fromEntries(CRM_CHANGES.map((one) => [one, 0]));
119
+ const query = changesQuery(context, key, { ...filter, limit: 0, offset: 0 });
120
+ if (!query)
121
+ return counts;
122
+ for (const row of context.database
123
+ .prepare(`SELECT change, count(*) AS n FROM (${query.sql}) GROUP BY change`)
124
+ .all(...query.params))
125
+ counts[row.change] = Number(row.n);
126
+ return counts;
127
+ };
128
+ /**
129
+ * Every change of an account's copy in a window, newest first, paged in SQL: deals and leads made, moved, won, lost
130
+ * and given another owner, activities added and done, contacts added. A move comes from the CRM's own stage history
131
+ * where a row has any, else from the copy's changes, never both; a move into a won or lost stage is listed as won or
132
+ * lost. A day the CRM gives without a time, as a closed day, is taken at its noon in UTC, the same day everywhere.
133
+ */
134
+ export const crmChanges = (context, key, filter) => {
135
+ const { database } = context;
136
+ const query = changesQuery(context, key, filter);
137
+ if (!query)
138
+ return { items: [], hasMore: false };
139
+ const rows = database
140
+ .prepare(`${query.sql} ORDER BY at DESC, change, kind, item DESC, record DESC LIMIT ?13 OFFSET ?14`)
141
+ .all(...query.params);
142
+ const stageName = database.prepare("SELECT name FROM pipeline_stages WHERE id = ?");
143
+ const nameOf = (id) => id == null ? null : (stageName.get(Number(id))?.name ?? null);
144
+ const itemStatements = Object.fromEntries(["deal", "lead"].map((kind) => [
145
+ kind,
146
+ database.prepare("SELECT d.external_id, d.title, d.currency, d.amount, json_extract(d.metadata, '$.closed_reason') AS reason, " +
147
+ `p.id AS pipeline, p.name AS pipeline_name FROM ${kind === "deal" ? "deals" : "leads"} d ` +
148
+ "JOIN pipeline_stages s ON s.id = d.stage_id JOIN pipelines p ON p.id = s.pipeline_id WHERE d.id = ?"),
149
+ ]));
150
+ const itemRow = (kind, id) => id == null || (kind !== "deal" && kind !== "lead") ? undefined : itemStatements[kind]?.get(Number(id));
151
+ const recordRow = database.prepare("SELECT external_id, fields FROM records WHERE id = ?");
152
+ return {
153
+ hasMore: rows.length > filter.limit,
154
+ items: rows.slice(0, filter.limit).map((row) => {
155
+ const change = row.change;
156
+ const item = itemRow(String(row.kind), row.item);
157
+ const record = row.record == null ? undefined : recordRow.get(Number(row.record));
158
+ const fields = record ? JSON.parse(String(record.fields)) : {};
159
+ const activity = change === "activity_added" || change === "activity_done";
160
+ const person = change === "person_added";
161
+ const currency = item?.currency ?? null;
162
+ return {
163
+ change,
164
+ at: Number(row.at),
165
+ kind: row.kind,
166
+ ref: item ? `${String(row.kind)}:${String(row.item)}` : null,
167
+ externalId: String(item?.external_id ?? record?.external_id ?? ""),
168
+ title: item ? String(item.title) : person ? (fields.name ?? null) : null,
169
+ pipeline: item ? `pipeline:${String(item.pipeline)}` : null,
170
+ pipelineName: item ? String(item.pipeline_name) : null,
171
+ from: change === "owner_changed" ? (fields.from ?? null) : nameOf(row.from_id),
172
+ to: change === "owner_changed" ? (fields.to ?? null) : nameOf(row.to_id),
173
+ amount: item?.amount == null || currency === null ? null : formatDecimal(Number(item.amount), scaleOf(currency)),
174
+ currency,
175
+ exact: row.exact === 1,
176
+ reason: change === "lost" ? (item?.reason ?? null) : null,
177
+ owner: row.owner ?? null,
178
+ activity: activity
179
+ ? {
180
+ externalId: String(record?.external_id),
181
+ kind: fields.kind,
182
+ subject: String(fields.subject ?? ""),
183
+ dueAt: fields.due_at ?? null,
184
+ done: fields.done === true,
185
+ }
186
+ : null,
187
+ };
188
+ }),
189
+ };
190
+ };
191
+ export const crmReadsOver = (context) => {
192
+ const activities = crmActivitiesOver(context);
193
+ return {
194
+ activities: async (key, filter) => activities.list(key, filter),
195
+ activityCount: async (key, filter) => activities.count(key, filter),
196
+ changes: async (key, filter) => crmChanges(context, key, filter),
197
+ changeCounts: async (key, filter) => crmChangeCounts(context, key, filter),
198
+ };
199
+ };
@@ -3,6 +3,7 @@ import { type DealKind } from "../../domain/deals.js";
3
3
  import type { AccountPeople } from "../people.js";
4
4
  import type { AccountKey } from "../types.js";
5
5
  import { type CrmActivitiesSaved, type StoredActivity } from "./crm-activities.js";
6
+ import { type CrmReads } from "./crm-changes.js";
6
7
  import { type CrmContactsRemoved } from "./crm-contacts.js";
7
8
  import { type CrmSkipped } from "./crm-rows.js";
8
9
  import { type CrmStageMove, type CrmStageTasks } from "./crm-settings.js";
@@ -35,7 +36,7 @@ export interface CrmSaved {
35
36
  * nothing is ever matched by name (WC-DATA-6). Rows the CRM no longer has are marked deleted, never removed
36
37
  * (WC-DATA-7). Every write is one transaction per call.
37
38
  */
38
- export interface CrmCopies {
39
+ export interface CrmCopies extends CrmReads {
39
40
  /** One kind's pipelines and their stages, by the CRM's ids. A stage the CRM dropped stays: deals may stand in it. */
40
41
  savePipelines(key: AccountKey, kind: DealKind, pipelines: CrmPipeline[]): Promise<CrmSaved>;
41
42
  /** Deals or leads; one whose stage is not stored, or whose fields the store refuses, is skipped and named. */
@@ -5,6 +5,7 @@ import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
7
  import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
8
+ import { crmReadsOver } from "./crm-changes.js";
8
9
  import { removeCrmContacts } from "./crm-contacts.js";
9
10
  import { crmAccountPrefix, crmIdentityId, crmRowsOver, PERSON_RECORD, SOURCE, TABLES, textOf, } from "./crm-rows.js";
10
11
  import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, crmStageTasksSince, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
@@ -670,6 +671,7 @@ export const crmCopiesOver = (context, people) => {
670
671
  activitiesOn: async (key) => crmActivitiesOn(database, key),
671
672
  saveActivities: async (key, activities) => activityStore.save(key, activities),
672
673
  activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
674
+ ...crmReadsOver(context),
673
675
  removeOutOfScope: async (key, kind, userIds, { dryRun } = {}) => write(database, () => {
674
676
  const keep = new Set(userIds.map((id) => crmIdentityId(key, id, "user")));
675
677
  const accountId = findAccountPk(context, key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.677.0",
3
+ "version": "0.679.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",