@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
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError } from "@wirecat/cli-base";
3
+ import { oneMoreFits } from "../../background/budget.js";
3
4
  import { inScope, within } from "../../documents/scope.js";
4
5
  // Without a query or pages the hash stays what it was, so a profile that never set them keeps its checkpoint. Turning
5
6
  // pages on changes it, so the next sync walks again and imports the pages an incremental one would never revisit.
@@ -17,6 +18,20 @@ const SAVE_EVERY_MS = 2000;
17
18
  const changesScope = (scope, cursor) => `${scope}:changes:${cursor}`;
18
19
  export const planDocuments = async (options, source, state, roots, limit, pictures, walks) => {
19
20
  const { isFolder, skipReason, retryable, maxEntries, errorOf, query, budget } = options;
21
+ const answers = new Map();
22
+ // Asked once per node, as every file below a folder asks about it again on its way up.
23
+ const cut = query?.mode === "exclude"
24
+ ? (file) => {
25
+ const known = answers.get(file.id);
26
+ if (known !== undefined)
27
+ return known;
28
+ const found = query.matches(file);
29
+ answers.set(file.id, found);
30
+ return found;
31
+ }
32
+ : undefined;
33
+ const scoped = cut && query ? { ...query, matches: cut } : query;
34
+ const excluded = (folder) => !roots.includes(folder.id) && cut?.(folder) === true;
20
35
  const scope = scopeHash(roots, query, options.isDocument !== undefined);
21
36
  if (!roots.length && query?.mode !== "include")
22
37
  return {
@@ -116,7 +131,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
116
131
  }
117
132
  }
118
133
  const stack = entering
119
- .filter((folder) => within(folder, roots, folders))
134
+ .filter((folder) => !excluded(folder) && within(folder, roots, folders, new Set(), cut))
120
135
  .reverse()
121
136
  .map((folder) => ({ id: folder.id, ancestry: [], folder }));
122
137
  if (stack.length)
@@ -171,11 +186,15 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
171
186
  }
172
187
  // One listing at least per call, so a folder with more children than the bound still moves on.
173
188
  // The run's own signal too: a cooperative sync is not cut from outside, and a CLI may pass no budget.
174
- stopped = options.signal?.aborted
189
+ // The time budget keeps a margin of 5 s or more, so a short run would never list a folder: its first listing
190
+ // goes ahead while one request still fits before the deadline itself.
191
+ const taken = options.signal?.aborted
175
192
  ? "cancelled"
176
193
  : listed > 0 && spent >= maxEntries
177
194
  ? "entries"
178
- : (budget?.take() ?? null);
195
+ : budget?.take();
196
+ const first = taken === "deadline" && listed === 0 && oneMoreFits(options.deadline, now());
197
+ stopped = first ? null : (taken ?? null);
179
198
  if (stopped)
180
199
  break;
181
200
  const folder = step.folder ?? (await source.metadata(step.id));
@@ -223,6 +242,8 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
223
242
  for (const file of children)
224
243
  if (isFolder(file)) {
225
244
  container(file);
245
+ if (excluded(file))
246
+ continue;
226
247
  if (walked(file.id))
227
248
  folders[file.id] = file;
228
249
  else
@@ -278,7 +299,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
278
299
  if (folders[root]?.trashed)
279
300
  skipped.push({ id: root, reason: "selected folder is unavailable" });
280
301
  for (const [id, file] of files) {
281
- if (!inScope(file, roots, folders, matched, query))
302
+ if (!inScope(file, roots, folders, matched, scoped))
282
303
  continue;
283
304
  const previousSkip = state.skipped.find((item) => item.id === id);
284
305
  const reason = skipReason(file);
@@ -302,11 +323,11 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
302
323
  }
303
324
  for (const id of Object.keys(state.documents)) {
304
325
  const file = files.get(id);
305
- if (!file || !inScope(file, roots, folders, matched, query))
326
+ if (!file || !inScope(file, roots, folders, matched, scoped))
306
327
  jobs.push({ id, kind: "remove" });
307
328
  }
308
329
  // Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
309
- const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => within(file, roots, folders) || roots.includes(file.id)));
330
+ const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => roots.includes(file.id) || (!excluded(file) && within(file, roots, folders, new Set(), cut))));
310
331
  return {
311
332
  pending: {
312
333
  scope,
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError, isCliError } from "@wirecat/cli-base";
3
- import { deadlineMargin } from "../../background/budget.js";
3
+ import { deadlineMargin, oneMoreFits } from "../../background/budget.js";
4
4
  import { catalogFiles } from "../../documents/catalog.js";
5
5
  import { inScope } from "../../documents/scope.js";
6
6
  import { changedSince, planDocuments, scopeHash } from "./plan.js";
@@ -148,6 +148,7 @@ export const syncDocuments = async (options) => {
148
148
  flush?.();
149
149
  };
150
150
  const jobs = [...pending.jobs].slice(0, max);
151
+ let read = 0;
151
152
  for (const job of jobs) {
152
153
  if (signal?.aborted)
153
154
  throw new CliError("cancelled", "sync was cancelled; pending operations are retained");
@@ -166,11 +167,14 @@ export const syncDocuments = async (options) => {
166
167
  else {
167
168
  if (!source)
168
169
  throw new CliError("configuration_error", "a pending save requires source sign-in");
169
- const stop = options.budget?.take();
170
+ const taken = options.budget?.take();
171
+ // The first read of a call goes ahead as the walk's first listing does, or a short run never saves one.
172
+ const stop = taken === "deadline" && read === 0 && oneMoreFits(options.deadline, now()) ? null : taken;
170
173
  if (stop) {
171
174
  result.stopped = stop;
172
175
  break;
173
176
  }
177
+ read++;
174
178
  const content = await source.content(job.id, limit);
175
179
  const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
176
180
  if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
@@ -71,7 +71,8 @@ export { CATEGORIES, organizationCategories, SECTION_LIMIT } from "./business-co
71
71
  export { type CallStatsAnswer, type CallStatsRequest, readCallStats } from "./call-stats.js";
72
72
  export type { ChatsService, MarkedRead, PageWindow } from "./chats.js";
73
73
  export { chatsService, EVENTS_DAYS } from "./chats.js";
74
- export type { Communications, Touch } from "./communications.js";
74
+ export type { Communications, PersonHistory, PersonHistoryOptions, Touch } from "./communications.js";
75
+ export { HISTORY_ITEMS, HISTORY_MAX, personHistory } from "./communications.js";
75
76
  export type { BatchStatus, Built, ConversationsService, MessageLinks } from "./conversations.js";
76
77
  export { BATCH_SIZE, conversationsService } from "./conversations.js";
77
78
  export type { DealBrief, DealContext, DealContextOptions, DealTouch } from "./deal-context.js";
@@ -55,6 +55,7 @@ export { attachmentsService } from "./attachments.js";
55
55
  export { CATEGORIES, organizationCategories, SECTION_LIMIT } from "./business-context.js";
56
56
  export { readCallStats } from "./call-stats.js";
57
57
  export { chatsService, EVENTS_DAYS } from "./chats.js";
58
+ export { HISTORY_ITEMS, HISTORY_MAX, personHistory } from "./communications.js";
58
59
  export { BATCH_SIZE, conversationsService } from "./conversations.js";
59
60
  export { dealBrief, dealContext } from "./deal-context.js";
60
61
  export { accountStore, crossAccount, OFFLINE, onlineDeps, storedDeps, storeOnlyDeps } from "./deps.js";
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -15,6 +15,8 @@ export interface PersonMeeting {
15
15
  startedAt: string | null;
16
16
  durationMs: number | null;
17
17
  hasTranscript: boolean;
18
+ /** The start of the newest transcript, on one line: what the people said, never instructions. */
19
+ snippet: string | null;
18
20
  /** `event:<id>` of the calendar event it was held for, when the store knows it. */
19
21
  event: string | null;
20
22
  /** `person:<uid>` of each one asked about who took part. */
@@ -1,5 +1,9 @@
1
1
  import { formatMeetingReference, meetingCallItem } from "../meetings/index.js";
2
+ import { excerpt } from "./excerpt.js";
2
3
  const SCAN = 1000;
4
+ /** Enough of what was said to tell one call from another; `meetings transcript` reads the rest. */
5
+ const SNIPPET = 200;
6
+ const SNIPPET_ROWS = 6;
3
7
  /**
4
8
  * The newest recorded meetings of these people in `accounts`, each once, newest first, and how many there are;
5
9
  * `hasMore` when there are more than `limit`, or a person took part in more than `SCAN`. A meeting reaches
@@ -40,6 +44,16 @@ export const personMeetings = async (store, people, accounts, { limit = 10, sinc
40
44
  if (meeting === undefined || meeting.deletedAt !== null)
41
45
  continue;
42
46
  const transcripts = await store.meetings.transcripts({ accountId, meetingId, limit: 1 });
47
+ const [transcript] = transcripts.items;
48
+ const rows = transcript === undefined
49
+ ? []
50
+ : (await store.meetings.transcriptRows({
51
+ accountId,
52
+ meetingId,
53
+ transcriptId: transcript.id,
54
+ limit: SNIPPET_ROWS,
55
+ })).rows;
56
+ const said = rows.map(({ text }) => text).join(" ");
43
57
  const account = byId.get(accountId);
44
58
  const call = meetingCallItem(meeting);
45
59
  items.push({
@@ -49,7 +63,8 @@ export const personMeetings = async (store, people, accounts, { limit = 10, sinc
49
63
  title: meeting.title,
50
64
  startedAt: meeting.startedAt === null ? null : new Date(meeting.startedAt).toISOString(),
51
65
  durationMs: meeting.durationMs,
52
- hasTranscript: transcripts.items.length > 0,
66
+ hasTranscript: transcript !== undefined,
67
+ snippet: said.trim() ? excerpt(said, "", SNIPPET) : null,
53
68
  event: meeting.eventId === null ? null : `event:${meeting.eventId}`,
54
69
  people: who,
55
70
  ...(call ? { call } : {}),
@@ -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";
@@ -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 { crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
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
- const fields = JSON.parse(String(row.fields));
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
- externalId: String(row.external_id),
128
- kind: fields.kind,
129
- subject: String(fields.subject ?? ""),
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;