@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.
- package/CHANGELOG.md +68 -0
- package/dist/background/budget.d.ts +2 -0
- package/dist/background/budget.js +2 -0
- 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/help/first-screen.js +5 -0
- package/dist/cli/list-query.d.ts +1 -1
- package/dist/cli/list-query.js +2 -2
- package/dist/cli/setup-command.js +26 -11
- 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/documents/scope.d.ts +3 -3
- package/dist/documents/scope.js +8 -4
- package/dist/entities/business-context.js +4 -0
- package/dist/entities/recorded-meeting.d.ts +1 -0
- package/dist/entities/recorded-meeting.js +2 -0
- package/dist/services/communications.d.ts +35 -0
- package/dist/services/communications.js +52 -2
- package/dist/services/documents/plan.js +27 -6
- package/dist/services/documents/sync.js +6 -2
- package/dist/services/index.d.ts +2 -1
- package/dist/services/index.js +1 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/person-meetings.d.ts +2 -0
- package/dist/services/person-meetings.js +16 -1
- package/dist/store/index.d.ts +2 -0
- package/dist/store/index.js +1 -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/package.json +1 -1
|
@@ -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;
|
package/dist/crm/stage-tasks.js
CHANGED
|
@@ -4,7 +4,7 @@ const DAY = 86_400_000;
|
|
|
4
4
|
/**
|
|
5
5
|
* Opens the owner's task for each stage a deal or lead of the account entered that its `stage-tasks` setting names:
|
|
6
6
|
* one per entry, so a dismissed task never comes back and a later entry into the same stage opens a new one.
|
|
7
|
-
* Answers how many it opened.
|
|
7
|
+
* Answers how many it opened. `now` is the sync's start: the tasks then fall in the digest window that sync closes.
|
|
8
8
|
*/
|
|
9
9
|
export const openStageTasks = async (store, account, now, { history = false } = {}) => {
|
|
10
10
|
const rules = await store.crm.stageTasks(account);
|
package/dist/crm/sync.d.ts
CHANGED
|
@@ -127,6 +127,15 @@ export declare const crmGapsOf: (store: MessageStore, account: AccountKey) => Pr
|
|
|
127
127
|
* `--rescan`.
|
|
128
128
|
*/
|
|
129
129
|
export declare const syncCrm: (source: CrmSource, store: MessageStore, account: AccountKey, options?: CrmSyncOptions) => Promise<CrmSyncReport>;
|
|
130
|
+
/** The sync state the last failed `sync` leaves, `{ at, kinds }`; a sync with no failed kind clears it. */
|
|
131
|
+
export declare const SYNC_FAILED = "crm:sync-failed";
|
|
132
|
+
/**
|
|
133
|
+
* The sync state holding when the last complete `sync` started: everything the CRM changed before it is in the copy,
|
|
134
|
+
* so the digest's window ends there.
|
|
135
|
+
*/
|
|
136
|
+
export declare const SYNCED_FROM = "crm:synced-from";
|
|
137
|
+
/** `syncCrm`, leaving how it ended for the digest's health: the kinds that failed, or none. */
|
|
138
|
+
export declare const syncRecorded: (...args: Parameters<typeof syncCrm>) => ReturnType<typeof syncCrm>;
|
|
130
139
|
/** Each kind's sync in the WC-LIFE-14 shape: `cursor_age_ms` growing on a `partial` one means nothing moves it. */
|
|
131
140
|
export declare const crmStatus: (store: MessageStore, account: AccountKey, { profile, now, kinds }: {
|
|
132
141
|
profile: string;
|
package/dist/crm/sync.js
CHANGED
|
@@ -699,6 +699,33 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
699
699
|
report.groupHint = groupHint;
|
|
700
700
|
return report;
|
|
701
701
|
};
|
|
702
|
+
/** The sync state the last failed `sync` leaves, `{ at, kinds }`; a sync with no failed kind clears it. */
|
|
703
|
+
export const SYNC_FAILED = "crm:sync-failed";
|
|
704
|
+
/**
|
|
705
|
+
* The sync state holding when the last complete `sync` started: everything the CRM changed before it is in the copy,
|
|
706
|
+
* so the digest's window ends there.
|
|
707
|
+
*/
|
|
708
|
+
export const SYNCED_FROM = "crm:synced-from";
|
|
709
|
+
/** `syncCrm`, leaving how it ended for the digest's health: the kinds that failed, or none. */
|
|
710
|
+
export const syncRecorded = async (...args) => {
|
|
711
|
+
const [, store, account, options] = args;
|
|
712
|
+
const at = options?.now ?? Date.now();
|
|
713
|
+
const record = (kinds) => store.sync
|
|
714
|
+
.setSyncState(account, SYNC_FAILED, kinds.length ? JSON.stringify({ at, kinds }) : "")
|
|
715
|
+
.catch(() => undefined);
|
|
716
|
+
try {
|
|
717
|
+
const report = await syncCrm(...args);
|
|
718
|
+
const failed = report.synced.filter((one) => one.error !== undefined).map((one) => one.kind);
|
|
719
|
+
await record(failed);
|
|
720
|
+
if (report.state === "complete" && !failed.length)
|
|
721
|
+
await store.sync.setSyncState(account, SYNCED_FROM, String(at));
|
|
722
|
+
return report;
|
|
723
|
+
}
|
|
724
|
+
catch (error) {
|
|
725
|
+
await record(["all"]);
|
|
726
|
+
throw error;
|
|
727
|
+
}
|
|
728
|
+
};
|
|
702
729
|
/** Each kind's sync in the WC-LIFE-14 shape: `cursor_age_ms` growing on a `partial` one means nothing moves it. */
|
|
703
730
|
export const crmStatus = async (store, account, { profile, now, kinds = CRM_KINDS }) => {
|
|
704
731
|
const saved = await store.crm.scope(account);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords } from "../../domain/crm.js";
|
|
1
|
+
import type { CrmActivity, CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords, CrmStageEntry } from "../../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../../domain/deals.js";
|
|
3
3
|
import type { CrmLiveKind, CrmSource, CrmSourceTraits } from "../source.js";
|
|
4
4
|
import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
|
|
@@ -14,6 +14,10 @@ export interface FakeCrmSourceOptions {
|
|
|
14
14
|
admin?: boolean;
|
|
15
15
|
/** The contacts and companies `ownClients()` counts as the sign-in's own; with it, the fake has `ownClients`. */
|
|
16
16
|
ownClients?: Partial<Record<CrmLiveKind, readonly string[]>>;
|
|
17
|
+
/** Gives the fake `stageHistory()` over these entries, the array read on each call so a test may add to it. */
|
|
18
|
+
stageHistory?: CrmStageEntry[];
|
|
19
|
+
/** Gives the fake `activities()` over these, the array read on each call, by `updatedAt` after `since`. */
|
|
20
|
+
activities?: CrmActivity[];
|
|
17
21
|
}
|
|
18
22
|
/** One write the fake CRM was sent, in order. */
|
|
19
23
|
export interface FakeCrmWrite {
|
|
@@ -246,6 +246,25 @@ export const fakeCrmSource = (options = {}) => {
|
|
|
246
246
|
return answer;
|
|
247
247
|
},
|
|
248
248
|
...(options.admin === undefined ? {} : { isAdmin: async () => options.admin }),
|
|
249
|
+
...(options.stageHistory === undefined
|
|
250
|
+
? {}
|
|
251
|
+
: {
|
|
252
|
+
stageHistory: async (kind, since, after) => {
|
|
253
|
+
const all = options.stageHistory;
|
|
254
|
+
const from = after === undefined ? -1 : all.findIndex((one) => one.externalId === after);
|
|
255
|
+
const items = all.filter((one, at) => one.kind === kind && at > from && (after !== undefined || one.at >= since));
|
|
256
|
+
return { items, hasMore: false, cursor: items.at(-1)?.externalId ?? after ?? null };
|
|
257
|
+
},
|
|
258
|
+
}),
|
|
259
|
+
...(options.activities === undefined
|
|
260
|
+
? {}
|
|
261
|
+
: {
|
|
262
|
+
activities: async (since) => {
|
|
263
|
+
const items = options.activities.filter((one) => one.updatedAt > since);
|
|
264
|
+
const newest = Math.max(since, ...items.map((one) => one.updatedAt));
|
|
265
|
+
return { items, hasMore: false, cursor: String(newest) };
|
|
266
|
+
},
|
|
267
|
+
}),
|
|
249
268
|
...(options.ownClients === undefined
|
|
250
269
|
? {}
|
|
251
270
|
: {
|
|
@@ -6,6 +6,8 @@ import type { CrmSourceTraits } from "../source.js";
|
|
|
6
6
|
export interface CrmSyncFixture {
|
|
7
7
|
store: MessageStore;
|
|
8
8
|
account: AccountKey;
|
|
9
|
+
/** Turns the account's `activities` setting on, as `config set` does; without it the activity case is left out. */
|
|
10
|
+
activitiesOn?: () => Promise<void>;
|
|
9
11
|
}
|
|
10
12
|
/** Both ways a CRM may report deletions: the engine must handle each. */
|
|
11
13
|
export declare const CRM_TRAIT_COMBINATIONS: readonly Pick<CrmSourceTraits, "removedInChanges">[];
|
|
@@ -12,12 +12,12 @@ const DAY = 86_400_000;
|
|
|
12
12
|
export const crmSyncContract = (make) => CRM_TRAIT_COMBINATIONS.flatMap((traits) => {
|
|
13
13
|
const label = traits.removedInChanges ? "(deletions in changes)" : "(deletions by id pass)";
|
|
14
14
|
let now = Date.now();
|
|
15
|
-
const test = (name, check) => ({
|
|
15
|
+
const test = (name, check, fake = {}) => ({
|
|
16
16
|
name: `${name} ${label}`,
|
|
17
17
|
async run() {
|
|
18
18
|
now = Date.now();
|
|
19
19
|
const fixture = await make();
|
|
20
|
-
const source = fakeCrmSource({ traits });
|
|
20
|
+
const source = fakeCrmSource({ traits, ...fake });
|
|
21
21
|
const sync = (options = {}) => syncCrm(source, fixture.store, fixture.account, { now, ...options });
|
|
22
22
|
const deals = async () => (await fixture.store.deals.list({ account: fixture.account, kind: "deal" })).items
|
|
23
23
|
.map(({ externalId }) => externalId)
|
|
@@ -169,6 +169,60 @@ export const crmSyncContract = (make) => CRM_TRAIT_COMBINATIONS.flatMap((traits)
|
|
|
169
169
|
const person = await store.people.personOf({ provider: "email", id: "person@example.com" });
|
|
170
170
|
assert.equal(deal?.people[0]?.ref, `person:${person?.uid}`);
|
|
171
171
|
}),
|
|
172
|
+
test("a stage entry on a deal the copy does not hold yet counts once the deal arrives", async ({ source, sync, store, account }) => {
|
|
173
|
+
await sync();
|
|
174
|
+
source.put("deal", exampleDeal("d9", { stage: "won" }));
|
|
175
|
+
await sync();
|
|
176
|
+
const { items: [deal], } = await store.deals.list({ account });
|
|
177
|
+
assert.deepEqual((await store.deals.stages(deal?.ref)).map(({ to, exact }) => [to, exact]), [["Quote sent", true]]);
|
|
178
|
+
}, {
|
|
179
|
+
stageHistory: [
|
|
180
|
+
{
|
|
181
|
+
externalId: "h1",
|
|
182
|
+
kind: "deal",
|
|
183
|
+
item: "d9",
|
|
184
|
+
pipeline: SALES_PIPELINE.externalId,
|
|
185
|
+
stage: "quote",
|
|
186
|
+
at: Date.now() - DAY,
|
|
187
|
+
},
|
|
188
|
+
],
|
|
189
|
+
}),
|
|
190
|
+
test("an activity on a contact the copy holds is kept, and one on a contact it does not hold is not", async ({ source, sync, store, account, activitiesOn }) => {
|
|
191
|
+
if (!activitiesOn)
|
|
192
|
+
return;
|
|
193
|
+
await activitiesOn();
|
|
194
|
+
source.put("person", examplePerson("p1"));
|
|
195
|
+
await sync();
|
|
196
|
+
const { items } = await store.crm.activities(account, { limit: 10, offset: 0 });
|
|
197
|
+
assert.deepEqual(items.map(({ externalId, on }) => [externalId, on.map((one) => one.kind)]), [["a1", ["person"]]]);
|
|
198
|
+
}, {
|
|
199
|
+
activities: [
|
|
200
|
+
{
|
|
201
|
+
externalId: "a1",
|
|
202
|
+
kind: "call",
|
|
203
|
+
subject: "Example call",
|
|
204
|
+
body: null,
|
|
205
|
+
dueAt: null,
|
|
206
|
+
done: false,
|
|
207
|
+
assignee: null,
|
|
208
|
+
createdAt: 1,
|
|
209
|
+
updatedAt: Date.now(),
|
|
210
|
+
on: [{ kind: "person", externalId: "p1" }],
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
externalId: "a2",
|
|
214
|
+
kind: "call",
|
|
215
|
+
subject: "Example call elsewhere",
|
|
216
|
+
body: null,
|
|
217
|
+
dueAt: null,
|
|
218
|
+
done: false,
|
|
219
|
+
assignee: null,
|
|
220
|
+
createdAt: 1,
|
|
221
|
+
updatedAt: Date.now(),
|
|
222
|
+
on: [{ kind: "person", externalId: "elsewhere" }],
|
|
223
|
+
},
|
|
224
|
+
],
|
|
225
|
+
}),
|
|
172
226
|
test("a cancelled run stops and keeps what it saved", async ({ source, sync, deals }) => {
|
|
173
227
|
seeded(source, 4);
|
|
174
228
|
const controller = new AbortController();
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { SourceFile } from "./model.js";
|
|
2
|
-
export declare const within: (file:
|
|
2
|
+
export declare const within: <F extends SourceFile>(file: F, roots: string[], folders: Record<string, F>, seen?: Set<string>, cut?: (folder: F) => boolean) => boolean;
|
|
3
3
|
/**
|
|
4
4
|
* A saved query beside the selected folders: `include` adds the files it finds wherever they sit, `exclude` keeps the
|
|
5
|
-
* files it matches out even inside a selected folder.
|
|
5
|
+
* files it matches out even inside a selected folder, and everything below a folder or page it matches.
|
|
6
6
|
*/
|
|
7
7
|
export interface SourceQuery<M extends SourceFile = SourceFile> {
|
|
8
8
|
/** Part of the sync's scope: a changed query or mode plans the sync again from the start. */
|
|
@@ -12,4 +12,4 @@ export interface SourceQuery<M extends SourceFile = SourceFile> {
|
|
|
12
12
|
/** Every file the query finds, read on each sync: a file shared by another owner may never reach the change feed. */
|
|
13
13
|
list?(): Promise<M[]>;
|
|
14
14
|
}
|
|
15
|
-
export declare const inScope: <M extends SourceFile>(file: M, roots: string[], folders: Record<string,
|
|
15
|
+
export declare const inScope: <M extends SourceFile>(file: M, roots: string[], folders: Record<string, M>, matched?: ReadonlySet<string>, query?: SourceQuery<M>) => boolean;
|
package/dist/documents/scope.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
export const within = (file, roots, folders, seen = new Set()) => {
|
|
2
|
+
export const within = (file, roots, folders, seen = new Set(), cut) => {
|
|
3
3
|
if (file.trashed)
|
|
4
4
|
return false;
|
|
5
5
|
if (roots.includes(file.id))
|
|
@@ -9,13 +9,17 @@ export const within = (file, roots, folders, seen = new Set()) => {
|
|
|
9
9
|
const next = new Set([...seen, file.id]);
|
|
10
10
|
return file.parents.some((id) => {
|
|
11
11
|
const folder = folders[id];
|
|
12
|
-
|
|
12
|
+
if (!folder)
|
|
13
|
+
return roots.includes(id);
|
|
14
|
+
// A selected folder is never cut: the owner chose it, so an exclude that matches it drops only its own row.
|
|
15
|
+
return (roots.includes(id) || !cut?.(folder)) && within(folder, roots, folders, next, cut);
|
|
13
16
|
});
|
|
14
17
|
};
|
|
15
18
|
export const inScope = (file, roots, folders, matched = new Set(), query) => {
|
|
16
19
|
if (file.trashed)
|
|
17
20
|
return false;
|
|
18
|
-
|
|
21
|
+
const excluded = query?.mode === "exclude" ? query.matches : undefined;
|
|
22
|
+
if (excluded?.(file))
|
|
19
23
|
return false;
|
|
20
|
-
return matched.has(file.id) || within(file, roots, folders);
|
|
24
|
+
return matched.has(file.id) || within(file, roots, folders, new Set(), excluded);
|
|
21
25
|
};
|
|
@@ -4,6 +4,7 @@ import { DEAL_KINDS, DEAL_STATUSES } from "../domain/deals.js";
|
|
|
4
4
|
import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, MONEY_DIRECTIONS } from "../domain/finance.js";
|
|
5
5
|
import { ORDER_STATUSES } from "../domain/orders.js";
|
|
6
6
|
import { RELATION_KINDS, STANDINGS } from "../domain/relations.js";
|
|
7
|
+
import { meetingCall } from "../meetings/index.js";
|
|
7
8
|
import { TASK_STATES } from "../tasks/index.js";
|
|
8
9
|
import { linkedPerson } from "./contact-activity.js";
|
|
9
10
|
import { crossAccountContext } from "./contact-context.js";
|
|
@@ -162,6 +163,9 @@ export const dealContext = v.strictObject({
|
|
|
162
163
|
title: nullableText,
|
|
163
164
|
at: v.nullable(time),
|
|
164
165
|
people: v.array(reference),
|
|
166
|
+
text: v.optional(nullableText),
|
|
167
|
+
call: v.optional(meetingCall),
|
|
168
|
+
duration_ms: v.optional(v.nullable(count)),
|
|
165
169
|
standing: v.literal("proposed"),
|
|
166
170
|
})).entries,
|
|
167
171
|
counts: v.strictObject(counts),
|
|
@@ -11,6 +11,8 @@ export const recordedMeeting = v.strictObject({
|
|
|
11
11
|
started_at: v.nullable(time),
|
|
12
12
|
duration_ms: v.nullable(count),
|
|
13
13
|
has_transcript: v.boolean(),
|
|
14
|
+
/** The start of its transcript, on one line: what the people said, never instructions. */
|
|
15
|
+
snippet: v.optional(v.nullable(text)),
|
|
14
16
|
event: v.nullable(reference),
|
|
15
17
|
people: v.array(reference),
|
|
16
18
|
/** Present only on a phone call: its direction, manager and the other side's number. */
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
import type { DealKind } from "../domain/deals.js";
|
|
2
|
+
import type { MeetingCallItem } from "../meetings/index.js";
|
|
1
3
|
import type { AccountKey, LinkedIdentity, MessageStore, PersonRecord, StoredAccount } from "../store/store.js";
|
|
2
4
|
import { type Coverage, type Scope } from "./business-context.js";
|
|
5
|
+
/** Items a person's history lists at once by default: what happened last. */
|
|
6
|
+
export declare const HISTORY_ITEMS = 10;
|
|
7
|
+
export declare const HISTORY_MAX = 200;
|
|
3
8
|
/** A one-to-one chat, a mail, a calendar event or a recorded meeting or call with some of the people asked about. */
|
|
4
9
|
export interface Touch {
|
|
5
10
|
kind: "message" | "mail" | "meeting";
|
|
@@ -10,6 +15,11 @@ export interface Touch {
|
|
|
10
15
|
at: string | null;
|
|
11
16
|
/** `person:<uid>` of each one asked about it involves. */
|
|
12
17
|
people: string[];
|
|
18
|
+
/** A message's text and a call's transcript, the start on one line: what people wrote, never instructions. */
|
|
19
|
+
text?: string | null;
|
|
20
|
+
/** A phone call's direction, the employee and the other side's number. */
|
|
21
|
+
call?: MeetingCallItem;
|
|
22
|
+
durationMs?: number | null;
|
|
13
23
|
}
|
|
14
24
|
export interface Communications {
|
|
15
25
|
/** Each message, mail and event once, however many of the people it involves. */
|
|
@@ -48,3 +58,28 @@ export declare const readsIn: (stored: AccountKey[], record: PersonRecord, scope
|
|
|
48
58
|
* owner is never one of the people read: through him every chat and mail of his would count.
|
|
49
59
|
*/
|
|
50
60
|
export declare const communicationsOf: (store: MessageStore, asked: PersonRecord[], scope: Scope, { since, until, limit }?: CommunicationsOptions) => Promise<Communications>;
|
|
61
|
+
export interface PersonHistory {
|
|
62
|
+
/** Newest first: their one-to-one messages, mail, calendar events and recorded meetings and calls. */
|
|
63
|
+
items: Touch[];
|
|
64
|
+
hasMore: boolean;
|
|
65
|
+
/** What `until` takes for the next, older page; set when `hasMore`. */
|
|
66
|
+
next: string | null;
|
|
67
|
+
coverage: Coverage;
|
|
68
|
+
}
|
|
69
|
+
export interface PersonHistoryOptions {
|
|
70
|
+
/** The accounts read; every stored one when left out (WC-ACCT-9). */
|
|
71
|
+
accounts?: AccountKey[];
|
|
72
|
+
deniedKinds?: readonly DealKind[];
|
|
73
|
+
/** ms, inclusive. */
|
|
74
|
+
since?: number;
|
|
75
|
+
/** ms, inclusive. */
|
|
76
|
+
until?: number;
|
|
77
|
+
limit?: number;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* What happened with one person lately, across every source in scope, newest first: the same reads a deal's and an
|
|
81
|
+
* organization's context make, for the identities linked to this one person. A page ends at `limit`; `next` is the
|
|
82
|
+
* `until` of the page before it. Items of one millisecond across a page's end may be cut, which a time of messages,
|
|
83
|
+
* mail and calls from separate sources almost never shares.
|
|
84
|
+
*/
|
|
85
|
+
export declare const personHistory: (store: MessageStore, reference: string, { accounts, deniedKinds, since, until, limit }?: PersonHistoryOptions) => Promise<PersonHistory>;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
1
2
|
import { formatLocator } from "../domain/locator.js";
|
|
2
3
|
import { kindIn } from "../domain/providers.js";
|
|
3
|
-
import { keyOf, newestFirst } from "./business-context.js";
|
|
4
|
+
import { keyOf, newestFirst, scopeOf } from "./business-context.js";
|
|
5
|
+
import { excerpt } from "./excerpt.js";
|
|
4
6
|
import { eventsOnce } from "./person-context.js";
|
|
5
7
|
import { personMeetings } from "./person-meetings.js";
|
|
6
8
|
/** Mail read per address when counting: past it the count says `hasMore`. */
|
|
@@ -8,6 +10,11 @@ const MAIL_ROWS = 500;
|
|
|
8
10
|
const EVENT_ROWS = 1000;
|
|
9
11
|
/** Recorded meetings and calls listed: past it the count still counts each, and the read says `hasMore`. */
|
|
10
12
|
const RECORDED_ROWS = 100;
|
|
13
|
+
/** Characters of a message's text in a touch: enough to know what it was about. */
|
|
14
|
+
const TEXT = 200;
|
|
15
|
+
/** Items a person's history lists at once by default: what happened last. */
|
|
16
|
+
export const HISTORY_ITEMS = 10;
|
|
17
|
+
export const HISTORY_MAX = 200;
|
|
11
18
|
/** The stored accounts that hold a calendar: what a person's events are read from. */
|
|
12
19
|
export const calendarsOf = async (store, stored) => {
|
|
13
20
|
const held = [];
|
|
@@ -112,6 +119,7 @@ export const communicationsOf = async (store, asked, scope, { since, until, limi
|
|
|
112
119
|
ref: formatLocator({ ...key, chat: chat.id, message: message.id }),
|
|
113
120
|
title: chat.title,
|
|
114
121
|
at: message.timestamp,
|
|
122
|
+
text: message.text ? excerpt(message.text, "", TEXT) : null,
|
|
115
123
|
}, person.uid);
|
|
116
124
|
}
|
|
117
125
|
}
|
|
@@ -141,7 +149,14 @@ export const communicationsOf = async (store, asked, scope, { since, until, limi
|
|
|
141
149
|
for (const meeting of recorded.items) {
|
|
142
150
|
read.add(keyOf(meeting.account));
|
|
143
151
|
const event = meeting.event === null ? undefined : Number(meeting.event.slice("event:".length));
|
|
144
|
-
|
|
152
|
+
const recording = {
|
|
153
|
+
text: meeting.snippet,
|
|
154
|
+
durationMs: meeting.durationMs,
|
|
155
|
+
...(meeting.call ? { call: meeting.call } : {}),
|
|
156
|
+
};
|
|
157
|
+
const calendar = event === undefined ? undefined : meetings.get(event);
|
|
158
|
+
if (calendar) {
|
|
159
|
+
Object.assign(calendar, recording);
|
|
145
160
|
held++;
|
|
146
161
|
continue;
|
|
147
162
|
}
|
|
@@ -151,6 +166,7 @@ export const communicationsOf = async (store, asked, scope, { since, until, limi
|
|
|
151
166
|
title: meeting.title,
|
|
152
167
|
at: meeting.startedAt,
|
|
153
168
|
people: meeting.people,
|
|
169
|
+
...recording,
|
|
154
170
|
});
|
|
155
171
|
}
|
|
156
172
|
return {
|
|
@@ -160,3 +176,37 @@ export const communicationsOf = async (store, asked, scope, { since, until, limi
|
|
|
160
176
|
coverage: coverageOf(people, read, calendars.length > 0),
|
|
161
177
|
};
|
|
162
178
|
};
|
|
179
|
+
/**
|
|
180
|
+
* What happened with one person lately, across every source in scope, newest first: the same reads a deal's and an
|
|
181
|
+
* organization's context make, for the identities linked to this one person. A page ends at `limit`; `next` is the
|
|
182
|
+
* `until` of the page before it. Items of one millisecond across a page's end may be cut, which a time of messages,
|
|
183
|
+
* mail and calls from separate sources almost never shares.
|
|
184
|
+
*/
|
|
185
|
+
export const personHistory = async (store, reference, { accounts, deniedKinds, since, until, limit = HISTORY_ITEMS } = {}) => {
|
|
186
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > HISTORY_MAX)
|
|
187
|
+
throw new CliError("validation_error", `the history's limit takes 1–${HISTORY_MAX}`);
|
|
188
|
+
if (since !== undefined && until !== undefined && since > until)
|
|
189
|
+
throw new CliError("validation_error", "the start of the range is after its end");
|
|
190
|
+
const uid = /^person:(\d+)$/.exec(reference.trim())?.[1];
|
|
191
|
+
if (uid === undefined)
|
|
192
|
+
throw new CliError("validation_error", "a person is person:<id>");
|
|
193
|
+
const record = await store.people.personByUid(uid);
|
|
194
|
+
if (!record)
|
|
195
|
+
throw new CliError("not_found", `no person:${uid} in the store`);
|
|
196
|
+
const talks = await communicationsOf(store, [record], scopeOf(accounts, deniedKinds), {
|
|
197
|
+
...(since === undefined ? {} : { since }),
|
|
198
|
+
...(until === undefined ? {} : { until }),
|
|
199
|
+
// One past the page per chat: a dialog alone may hold the next page's first message.
|
|
200
|
+
limit: limit + 1,
|
|
201
|
+
});
|
|
202
|
+
const dated = talks.items.filter((item) => item.at !== null);
|
|
203
|
+
const items = dated.slice(0, limit);
|
|
204
|
+
const last = items.at(-1);
|
|
205
|
+
const hasMore = dated.length > limit;
|
|
206
|
+
return {
|
|
207
|
+
items,
|
|
208
|
+
hasMore,
|
|
209
|
+
next: hasMore && last?.at ? new Date(Date.parse(last.at) - 1).toISOString() : null,
|
|
210
|
+
coverage: talks.coverage,
|
|
211
|
+
};
|
|
212
|
+
};
|