@wirecat/cli-core 0.677.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 +31 -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/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/services/metadata.d.ts +1 -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
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();
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/dist/store/index.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogSto
|
|
|
51
51
|
export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
52
52
|
export type { ChatMetadata } from "./sqlite/chats.js";
|
|
53
53
|
export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
|
|
54
|
+
export type { ActivityFilter, ActivityTarget, ListedActivity } from "./sqlite/crm-activities.js";
|
|
55
|
+
export { type ChangeFilter, CRM_CHANGES, type CrmChange, type CrmChangeKind } from "./sqlite/crm-changes.js";
|
|
54
56
|
export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
|
|
55
57
|
export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
|
|
56
58
|
export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
|
package/dist/store/index.js
CHANGED
|
@@ -34,6 +34,7 @@ export { baseSettingKey } from "./sqlite/base-suggest.js";
|
|
|
34
34
|
export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
|
|
35
35
|
export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
36
36
|
export { crmIdentityId, } from "./sqlite/crm.js";
|
|
37
|
+
export { CRM_CHANGES } from "./sqlite/crm-changes.js";
|
|
37
38
|
export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
|
|
38
39
|
export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
|
|
39
40
|
export { EVENT_FIELDS, } from "./sqlite/event-search.js";
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import type { CrmActivity, CrmActivityKind } from "../../domain/crm.js";
|
|
1
|
+
import type { CrmActivity, CrmActivityKind, CrmKind } from "../../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../../domain/deals.js";
|
|
3
3
|
import type { CacheDatabase } from "../driver.js";
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
|
+
import { type CopyViewer } from "./copy-viewer.js";
|
|
5
6
|
import type { StoreContext } from "./open.js";
|
|
6
7
|
export declare const ACTIVITY_RECORD = "crm.activity";
|
|
7
8
|
/**
|
|
@@ -22,6 +23,40 @@ export interface StoredActivity {
|
|
|
22
23
|
createdAt: number;
|
|
23
24
|
updatedAt: number;
|
|
24
25
|
}
|
|
26
|
+
/** What `activities list` narrows by; every bound is inclusive epoch ms. */
|
|
27
|
+
export interface ActivityFilter {
|
|
28
|
+
status?: "open" | "done";
|
|
29
|
+
due?: {
|
|
30
|
+
since?: number;
|
|
31
|
+
until?: number;
|
|
32
|
+
};
|
|
33
|
+
/** Open and due before this moment. */
|
|
34
|
+
overdueAt?: number;
|
|
35
|
+
kinds?: readonly CrmActivityKind[];
|
|
36
|
+
/** On this deal, lead, contact or company, by the store's reference (`deal:12`, `person:4`, `organization:3`). */
|
|
37
|
+
on?: string;
|
|
38
|
+
/** The identity `<account>/user/<id>` it is assigned to; `null` is none. */
|
|
39
|
+
owner?: string | null;
|
|
40
|
+
/**
|
|
41
|
+
* A profile that may read only part of the copy (SEC-197): the activities on its deals and leads, and those on
|
|
42
|
+
* contacts or companies alone that are assigned to it. A hidden deal or lead is never named in `on`.
|
|
43
|
+
*/
|
|
44
|
+
viewer?: CopyViewer;
|
|
45
|
+
/** 1–500. */
|
|
46
|
+
limit: number;
|
|
47
|
+
offset: number;
|
|
48
|
+
}
|
|
49
|
+
/** One row the activity is on, with the store's reference and title when the copy holds it. */
|
|
50
|
+
export interface ActivityTarget {
|
|
51
|
+
kind: CrmKind;
|
|
52
|
+
externalId: string;
|
|
53
|
+
ref: string | null;
|
|
54
|
+
title: string | null;
|
|
55
|
+
}
|
|
56
|
+
export interface ListedActivity extends StoredActivity {
|
|
57
|
+
doneAt: number | null;
|
|
58
|
+
on: ActivityTarget[];
|
|
59
|
+
}
|
|
25
60
|
/** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
|
|
26
61
|
export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
|
|
27
62
|
export interface CrmActivitiesSaved {
|
|
@@ -32,4 +67,9 @@ export interface CrmActivitiesSaved {
|
|
|
32
67
|
export declare const crmActivitiesOver: (context: StoreContext) => {
|
|
33
68
|
save: (key: AccountKey, activities: readonly CrmActivity[]) => CrmActivitiesSaved;
|
|
34
69
|
of: (key: AccountKey, kind: DealKind, externalId: string, limit: number) => StoredActivity[];
|
|
70
|
+
list: (key: AccountKey, filter: ActivityFilter) => {
|
|
71
|
+
items: ListedActivity[];
|
|
72
|
+
hasMore: boolean;
|
|
73
|
+
};
|
|
74
|
+
count: (key: AccountKey, filter: Omit<ActivityFilter, "limit" | "offset">) => number;
|
|
35
75
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { recordFingerprint } from "../../domain/records.js";
|
|
2
2
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
3
|
-
import {
|
|
3
|
+
import { viewerSql } from "./copy-viewer.js";
|
|
4
|
+
import { crmAccountPrefix, crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
|
|
4
5
|
import { write } from "./transaction.js";
|
|
5
6
|
export const ACTIVITY_RECORD = "crm.activity";
|
|
6
7
|
/**
|
|
@@ -20,6 +21,17 @@ export const forgetActivitiesOn = (database, accountId, kind, externalIds, at) =
|
|
|
20
21
|
/** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
|
|
21
22
|
const MOST_BODY = 20_000;
|
|
22
23
|
const MOST_SUBJECT = 500;
|
|
24
|
+
const activityOf = (externalId, fields) => ({
|
|
25
|
+
externalId,
|
|
26
|
+
kind: fields.kind,
|
|
27
|
+
subject: String(fields.subject ?? ""),
|
|
28
|
+
body: fields.body ?? null,
|
|
29
|
+
dueAt: fields.due_at ?? null,
|
|
30
|
+
done: fields.done === true,
|
|
31
|
+
assignee: fields.assignee ?? null,
|
|
32
|
+
createdAt: Number(fields.created_at),
|
|
33
|
+
updatedAt: Number(fields.updated_at),
|
|
34
|
+
});
|
|
23
35
|
/** The subjects and texts of the activities on each deal or lead of a kind, by `<account id>\u0000<external id>`. */
|
|
24
36
|
export const activityTexts = (database, kind) => {
|
|
25
37
|
const found = new Map();
|
|
@@ -121,20 +133,146 @@ export const crmActivitiesOver = (context) => {
|
|
|
121
133
|
"CASE WHEN json_extract(r.fields, '$.done') THEN NULL ELSE json_extract(r.fields, '$.due_at') END ASC, " +
|
|
122
134
|
"json_extract(r.fields, '$.updated_at') DESC LIMIT ?")
|
|
123
135
|
.all(accountId, ACTIVITY_RECORD, kind, externalId, limit)
|
|
124
|
-
.map((row) =>
|
|
125
|
-
|
|
136
|
+
.map((row) => activityOf(String(row.external_id), JSON.parse(String(row.fields))));
|
|
137
|
+
};
|
|
138
|
+
/** The CRM ids of the activity targets a store reference names in this account, by kind. */
|
|
139
|
+
const targetOf = (key, accountId, ref, viewer) => {
|
|
140
|
+
const [type = "", id = ""] = ref.split(":");
|
|
141
|
+
const one = (sql, ...params) => JSON.stringify(database
|
|
142
|
+
.prepare(sql)
|
|
143
|
+
.all(...params)
|
|
144
|
+
.map((row) => String(row.id)));
|
|
145
|
+
if (type === "deal" || type === "lead") {
|
|
146
|
+
const seen = viewerSql(TABLES[type], viewer);
|
|
147
|
+
return {
|
|
148
|
+
kind: type,
|
|
149
|
+
ids: one(`SELECT external_id AS id FROM ${TABLES[type]} WHERE account_id = ? AND id = ? AND ${seen.sql}`, accountId, Number(id), ...seen.params),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
if (type === "organization")
|
|
126
153
|
return {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
body: fields.body ?? null,
|
|
131
|
-
dueAt: fields.due_at ?? null,
|
|
132
|
-
done: fields.done === true,
|
|
133
|
-
assignee: fields.assignee ?? null,
|
|
134
|
-
createdAt: Number(fields.created_at),
|
|
135
|
-
updatedAt: Number(fields.updated_at),
|
|
154
|
+
kind: type,
|
|
155
|
+
ids: one("SELECT external_id AS id FROM records WHERE account_id = ? AND type = 'organization' " +
|
|
156
|
+
"AND entity_type = 'organization' AND entity_id = ? AND deleted_at IS NULL", accountId, Number(id)),
|
|
136
157
|
};
|
|
137
|
-
}
|
|
158
|
+
const prefix = `${crmAccountPrefix(key)}contact/`;
|
|
159
|
+
return {
|
|
160
|
+
kind: "person",
|
|
161
|
+
ids: one("SELECT substr(i.external_id, ?) AS id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
162
|
+
"WHERE i.provider = ? AND substr(i.external_id, 1, ?) = ? AND l.person_id = ?", prefix.length + 1, key.provider, prefix.length, prefix, Number(id)),
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
const targets = (key, accountId, recordId, viewer) => database
|
|
166
|
+
.prepare("SELECT target_type, target_external_id FROM record_relations WHERE record_id = ? AND role = 'on'")
|
|
167
|
+
.all(recordId)
|
|
168
|
+
.map((row) => {
|
|
169
|
+
const kind = String(row.target_type);
|
|
170
|
+
const externalId = String(row.target_external_id);
|
|
171
|
+
const found = kind === "deal" || kind === "lead"
|
|
172
|
+
? database
|
|
173
|
+
.prepare(`SELECT '${kind}:' || id AS ref, title FROM ${TABLES[kind]} d WHERE account_id = ? ` +
|
|
174
|
+
`AND external_id = ? AND ${viewerSql("d", viewer).sql}`)
|
|
175
|
+
.get(accountId, externalId, ...viewerSql("d", viewer).params)
|
|
176
|
+
: kind === "organization"
|
|
177
|
+
? database
|
|
178
|
+
.prepare("SELECT 'organization:' || o.id AS ref, o.name AS title FROM records r " +
|
|
179
|
+
"JOIN organizations o ON o.id = r.entity_id WHERE r.account_id = ? AND r.type = 'organization' " +
|
|
180
|
+
"AND r.entity_type = 'organization' AND r.external_id = ?")
|
|
181
|
+
.get(accountId, externalId)
|
|
182
|
+
: database
|
|
183
|
+
.prepare("SELECT 'person:' || l.person_id AS ref, coalesce(p.name, i.name) AS title FROM identities i " +
|
|
184
|
+
"LEFT JOIN identity_links l ON l.identity_id = i.id LEFT JOIN persons p ON p.id = l.person_id " +
|
|
185
|
+
"WHERE i.provider = ? AND i.external_id = ?")
|
|
186
|
+
.get(key.provider, crmIdentityId(key, externalId));
|
|
187
|
+
return {
|
|
188
|
+
kind,
|
|
189
|
+
externalId,
|
|
190
|
+
ref: found?.ref == null ? null : String(found.ref),
|
|
191
|
+
title: found?.title == null ? null : String(found.title),
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
const field = (name) => `json_extract(r.fields, '$.${name}')`;
|
|
195
|
+
const whereOf = (key, accountId, filter) => {
|
|
196
|
+
const where = [];
|
|
197
|
+
if (filter.status)
|
|
198
|
+
where.push({ sql: `${field("done")} = ?`, params: [filter.status === "done" ? 1 : 0] });
|
|
199
|
+
if (filter.due?.since !== undefined)
|
|
200
|
+
where.push({ sql: `${field("due_at")} >= ?`, params: [filter.due.since] });
|
|
201
|
+
if (filter.due?.until !== undefined)
|
|
202
|
+
where.push({ sql: `${field("due_at")} <= ?`, params: [filter.due.until] });
|
|
203
|
+
if (filter.overdueAt !== undefined)
|
|
204
|
+
where.push({ sql: `${field("done")} = 0 AND ${field("due_at")} < ?`, params: [filter.overdueAt] });
|
|
205
|
+
if (filter.kinds?.length)
|
|
206
|
+
where.push({
|
|
207
|
+
sql: `${field("kind")} IN (SELECT value FROM json_each(?))`,
|
|
208
|
+
params: [JSON.stringify(filter.kinds)],
|
|
209
|
+
});
|
|
210
|
+
if (filter.owner !== undefined)
|
|
211
|
+
where.push(filter.owner === null
|
|
212
|
+
? { sql: `${field("assignee")} IS NULL`, params: [] }
|
|
213
|
+
: { sql: `${field("assignee")} = ?`, params: [filter.owner] });
|
|
214
|
+
if (filter.on !== undefined) {
|
|
215
|
+
const target = targetOf(key, accountId, filter.on, filter.viewer);
|
|
216
|
+
where.push({
|
|
217
|
+
sql: "EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = r.id AND rr.role = 'on' " +
|
|
218
|
+
"AND rr.target_type = ? AND rr.target_external_id IN (SELECT value FROM json_each(?)))",
|
|
219
|
+
params: [target.kind, target.ids],
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
if (filter.viewer)
|
|
223
|
+
where.push(seenSql(filter.viewer));
|
|
224
|
+
return where;
|
|
225
|
+
};
|
|
226
|
+
/** One page of the account's activities: open ones first, overdue before undated, then the rest, newest first. */
|
|
227
|
+
const list = (key, filter) => {
|
|
228
|
+
const accountId = findAccountPk(context, key);
|
|
229
|
+
if (accountId === undefined)
|
|
230
|
+
return { items: [], hasMore: false };
|
|
231
|
+
const where = whereOf(key, accountId, filter);
|
|
232
|
+
const open = `CASE WHEN ${field("done")} THEN NULL ELSE ${field("due_at")} END`;
|
|
233
|
+
const rows = database
|
|
234
|
+
.prepare("SELECT r.id, r.external_id, r.fields FROM records r WHERE r.account_id = ? AND r.type = ? " +
|
|
235
|
+
`AND r.deleted_at IS NULL ${where.map(({ sql }) => `AND ${sql}`).join(" ")} ` +
|
|
236
|
+
`ORDER BY ${field("done")} ASC, ${field("done")} = 0 AND ${field("due_at")} IS NULL, ${open} ASC, ` +
|
|
237
|
+
`${field("updated_at")} DESC, r.id DESC LIMIT ? OFFSET ?`)
|
|
238
|
+
.all(accountId, ACTIVITY_RECORD, ...where.flatMap(({ params }) => params), filter.limit + 1, filter.offset);
|
|
239
|
+
return {
|
|
240
|
+
hasMore: rows.length > filter.limit,
|
|
241
|
+
items: rows.slice(0, filter.limit).map((row) => {
|
|
242
|
+
const fields = JSON.parse(String(row.fields));
|
|
243
|
+
return {
|
|
244
|
+
...activityOf(String(row.external_id), fields),
|
|
245
|
+
doneAt: fields.done_at ?? null,
|
|
246
|
+
on: targets(key, accountId, Number(row.id), filter.viewer),
|
|
247
|
+
};
|
|
248
|
+
}),
|
|
249
|
+
};
|
|
250
|
+
};
|
|
251
|
+
/** How many activities `filter` matches, every page together. */
|
|
252
|
+
const count = (key, filter) => {
|
|
253
|
+
const accountId = findAccountPk(context, key);
|
|
254
|
+
if (accountId === undefined)
|
|
255
|
+
return 0;
|
|
256
|
+
const where = whereOf(key, accountId, filter);
|
|
257
|
+
return Number(database
|
|
258
|
+
.prepare("SELECT count(*) AS n FROM records r WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL " +
|
|
259
|
+
where.map(({ sql }) => `AND ${sql}`).join(" "))
|
|
260
|
+
.get(accountId, ACTIVITY_RECORD, ...where.flatMap(({ params }) => params))?.n ?? 0);
|
|
261
|
+
};
|
|
262
|
+
return { save, of, list, count };
|
|
263
|
+
};
|
|
264
|
+
/** An activity a viewer may read: on one of its deals or leads, or on contacts alone and assigned to it. */
|
|
265
|
+
const seenSql = (viewer) => {
|
|
266
|
+
if (viewer.assignee === null)
|
|
267
|
+
return { sql: "0", params: [] };
|
|
268
|
+
const on = (table, kind) => `EXISTS (SELECT 1 FROM record_relations rr JOIN ${table} d ON d.account_id = r.account_id ` +
|
|
269
|
+
"AND d.external_id = rr.target_external_id AND d.deleted_at IS NULL " +
|
|
270
|
+
`WHERE rr.record_id = r.id AND rr.role = 'on' AND rr.target_type = '${kind}' ` +
|
|
271
|
+
"AND json_extract(d.metadata, '$.assignee') = ?)";
|
|
272
|
+
return {
|
|
273
|
+
sql: `(${on("deals", "deal")} OR ${on("leads", "lead")} OR (NOT EXISTS (SELECT 1 FROM record_relations rr ` +
|
|
274
|
+
"WHERE rr.record_id = r.id AND rr.role = 'on' AND rr.target_type IN ('deal', 'lead')) " +
|
|
275
|
+
"AND json_extract(r.fields, '$.assignee') = ?))",
|
|
276
|
+
params: [viewer.assignee, viewer.assignee, viewer.assignee],
|
|
138
277
|
};
|
|
139
|
-
return { save, of };
|
|
140
278
|
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { CrmActivityKind, CrmKind } from "../../domain/crm.js";
|
|
2
|
+
import type { AccountKey } from "../types.js";
|
|
3
|
+
import type { CopyViewer } from "./copy-viewer.js";
|
|
4
|
+
import { type ActivityFilter, type ListedActivity } from "./crm-activities.js";
|
|
5
|
+
import type { StoreContext } from "./open.js";
|
|
6
|
+
export declare const CRM_CHANGES: readonly ["created", "moved", "won", "lost", "owner_changed", "activity_added", "activity_done", "person_added"];
|
|
7
|
+
export type CrmChangeKind = (typeof CRM_CHANGES)[number];
|
|
8
|
+
/** One thing that happened in a CRM account's copy, newest first in a page. */
|
|
9
|
+
export interface CrmChange {
|
|
10
|
+
change: CrmChangeKind;
|
|
11
|
+
at: number;
|
|
12
|
+
kind: CrmKind;
|
|
13
|
+
/** The deal, lead or contact as the store names it; `null` when the copy no longer links it. */
|
|
14
|
+
ref: string | null;
|
|
15
|
+
externalId: string;
|
|
16
|
+
title: string | null;
|
|
17
|
+
pipeline: string | null;
|
|
18
|
+
pipelineName: string | null;
|
|
19
|
+
/** A move's stages by name; an owner change's users as `<account>/user/<id>`. */
|
|
20
|
+
from: string | null;
|
|
21
|
+
to: string | null;
|
|
22
|
+
amount: string | null;
|
|
23
|
+
currency: string | null;
|
|
24
|
+
/** A move from the CRM's own stage history rather than the copy's diffs between syncs. */
|
|
25
|
+
exact: boolean;
|
|
26
|
+
/** Why a lost deal was lost, as the CRM says. */
|
|
27
|
+
reason: string | null;
|
|
28
|
+
/** The identity `<account>/user/<id>` the row is assigned to. */
|
|
29
|
+
owner: string | null;
|
|
30
|
+
activity: {
|
|
31
|
+
externalId: string;
|
|
32
|
+
kind: CrmActivityKind;
|
|
33
|
+
subject: string;
|
|
34
|
+
dueAt: number | null;
|
|
35
|
+
done: boolean;
|
|
36
|
+
} | null;
|
|
37
|
+
}
|
|
38
|
+
/** What `changes list` narrows by: `since` and `until` are inclusive epoch ms. */
|
|
39
|
+
export interface ChangeFilter {
|
|
40
|
+
since: number;
|
|
41
|
+
until: number;
|
|
42
|
+
changes?: readonly CrmChangeKind[];
|
|
43
|
+
/** The identity `<account>/user/<id>`; `null` is none. */
|
|
44
|
+
owner?: string | null;
|
|
45
|
+
/** A pipeline's store id: only the changes of its deals or leads. */
|
|
46
|
+
pipeline?: number;
|
|
47
|
+
/**
|
|
48
|
+
* A profile that may read only part of the copy (SEC-197): the deals and leads assigned to it, the activities on
|
|
49
|
+
* them, and the contacts linked to them or assigned to it.
|
|
50
|
+
*/
|
|
51
|
+
viewer?: CopyViewer;
|
|
52
|
+
limit: number;
|
|
53
|
+
offset: number;
|
|
54
|
+
}
|
|
55
|
+
/** How many changes of each kind `filter`'s window holds, every page together. */
|
|
56
|
+
export declare const crmChangeCounts: (context: StoreContext, key: AccountKey, filter: Omit<ChangeFilter, "limit" | "offset">) => Record<CrmChangeKind, number>;
|
|
57
|
+
/**
|
|
58
|
+
* Every change of an account's copy in a window, newest first, paged in SQL: deals and leads made, moved, won, lost
|
|
59
|
+
* and given another owner, activities added and done, contacts added. A move comes from the CRM's own stage history
|
|
60
|
+
* 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
|
|
61
|
+
* lost. A day the CRM gives without a time, as a closed day, is taken at its noon in UTC, the same day everywhere.
|
|
62
|
+
*/
|
|
63
|
+
export declare const crmChanges: (context: StoreContext, key: AccountKey, filter: ChangeFilter) => {
|
|
64
|
+
items: CrmChange[];
|
|
65
|
+
hasMore: boolean;
|
|
66
|
+
};
|
|
67
|
+
/** The pages `activities list`, `changes list` and the digest read of one account's copy. */
|
|
68
|
+
export interface CrmReads {
|
|
69
|
+
/** One page of the account's activities: open ones first by due time, then the rest, newest first. */
|
|
70
|
+
activities(key: AccountKey, filter: ActivityFilter): Promise<{
|
|
71
|
+
items: ListedActivity[];
|
|
72
|
+
hasMore: boolean;
|
|
73
|
+
}>;
|
|
74
|
+
/** How many activities a filter matches, every page together. */
|
|
75
|
+
activityCount(key: AccountKey, filter: Omit<ActivityFilter, "limit" | "offset">): Promise<number>;
|
|
76
|
+
/** One page of what changed in the account's copy in a window, newest first (`crmChanges`). */
|
|
77
|
+
changes(key: AccountKey, filter: ChangeFilter): Promise<{
|
|
78
|
+
items: CrmChange[];
|
|
79
|
+
hasMore: boolean;
|
|
80
|
+
}>;
|
|
81
|
+
/** How many changes of each kind a window holds (`crmChangeCounts`). */
|
|
82
|
+
changeCounts(key: AccountKey, filter: Omit<ChangeFilter, "limit" | "offset">): Promise<Record<CrmChangeKind, number>>;
|
|
83
|
+
}
|
|
84
|
+
export declare const crmReadsOver: (context: StoreContext) => CrmReads;
|