@wirecat/cli-core 0.675.0 → 0.676.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 +88 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/index.d.ts +1 -1
  6. package/dist/cli/list-query.d.ts +3 -2
  7. package/dist/cli/list-query.js +5 -2
  8. package/dist/cli/setup-command.js +9 -3
  9. package/dist/crm/cli/index.d.ts +7 -1
  10. package/dist/crm/cli/index.js +104 -20
  11. package/dist/crm/cli/pipeline-view.js +15 -1
  12. package/dist/crm/cli/records.js +11 -3
  13. package/dist/crm/cli/search-all.d.ts +5 -2
  14. package/dist/crm/cli/search-all.js +15 -3
  15. package/dist/crm/source.d.ts +3 -2
  16. package/dist/crm/stage-tasks.js +1 -1
  17. package/dist/crm/sync.js +13 -11
  18. package/dist/crm/testing/write-contract.js +5 -1
  19. package/dist/crm/viewer.d.ts +28 -0
  20. package/dist/crm/viewer.js +63 -0
  21. package/dist/crm/writer.d.ts +3 -0
  22. package/dist/crm/writes.d.ts +7 -2
  23. package/dist/crm/writes.js +24 -14
  24. package/dist/domain/crm.d.ts +9 -9
  25. package/dist/domain/moment.d.ts +2 -0
  26. package/dist/domain/moment.js +2 -0
  27. package/dist/entities/business-context.js +1 -1
  28. package/dist/entities/deal.d.ts +86 -39
  29. package/dist/entities/deal.js +45 -4
  30. package/dist/entities/index.d.ts +20 -32
  31. package/dist/errors/reasons.js +1 -0
  32. package/dist/meetings/mcp/index.d.ts +15 -15
  33. package/dist/services/search-all.d.ts +3 -1
  34. package/dist/services/search-all.js +1 -0
  35. package/dist/setup/define.d.ts +17 -2
  36. package/dist/store/exports.d.ts +1 -0
  37. package/dist/store/exports.js +1 -0
  38. package/dist/store/sqlite/copy-viewer.d.ts +16 -0
  39. package/dist/store/sqlite/copy-viewer.js +11 -0
  40. package/dist/store/sqlite/crm-activities.d.ts +7 -1
  41. package/dist/store/sqlite/crm-activities.js +32 -5
  42. package/dist/store/sqlite/crm-contacts.d.ts +5 -2
  43. package/dist/store/sqlite/crm-contacts.js +30 -14
  44. package/dist/store/sqlite/crm-rows.d.ts +7 -0
  45. package/dist/store/sqlite/crm-rows.js +37 -5
  46. package/dist/store/sqlite/crm-settings.d.ts +2 -1
  47. package/dist/store/sqlite/crm-settings.js +3 -2
  48. package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
  49. package/dist/store/sqlite/crm-stage-entries.js +77 -18
  50. package/dist/store/sqlite/crm.d.ts +14 -4
  51. package/dist/store/sqlite/crm.js +59 -7
  52. package/dist/store/sqlite/deals.d.ts +47 -29
  53. package/dist/store/sqlite/deals.js +64 -76
  54. package/dist/store/sqlite/pipeline-period.d.ts +85 -0
  55. package/dist/store/sqlite/pipeline-period.js +199 -0
  56. package/dist/store/sqlite/stage-amounts.d.ts +6 -2
  57. package/dist/store/sqlite/stage-amounts.js +8 -5
  58. package/package.json +3 -3
@@ -0,0 +1,16 @@
1
+ import type { AccountKey } from "../types.js";
2
+ /**
3
+ * A profile that may read only part of one CRM account's copy (SEC-197): the deals and leads assigned to `assignee`,
4
+ * the identity `<account>/user/<id>`, or none when it is `null`.
5
+ */
6
+ export interface CopyViewer {
7
+ account: AccountKey;
8
+ assignee: string | null;
9
+ }
10
+ /** The condition on a deal or lead row `alias` of the viewer's account, with its parameters. */
11
+ export declare const viewerSql: (alias: string, viewer: CopyViewer | undefined) => {
12
+ sql: string;
13
+ params: string[];
14
+ };
15
+ /** Whether a deal or lead row, with its account's `provider` and `account` and its `assignee`, is the viewer's to read. */
16
+ export declare const seenBy: (viewer: CopyViewer | undefined, row: Record<string, unknown>) => boolean;
@@ -0,0 +1,11 @@
1
+ /** The condition on a deal or lead row `alias` of the viewer's account, with its parameters. */
2
+ export const viewerSql = (alias, viewer) => viewer === undefined
3
+ ? { sql: "1", params: [] }
4
+ : viewer.assignee === null
5
+ ? { sql: "0", params: [] }
6
+ : { sql: `json_extract(${alias}.metadata, '$.assignee') = ?`, params: [viewer.assignee] };
7
+ /** Whether a deal or lead row, with its account's `provider` and `account` and its `assignee`, is the viewer's to read. */
8
+ export const seenBy = (viewer, row) => viewer === undefined ||
9
+ row.provider !== viewer.account.provider ||
10
+ row.account !== viewer.account.account ||
11
+ (viewer.assignee !== null && row.assignee === viewer.assignee);
@@ -1,8 +1,14 @@
1
1
  import type { CrmActivity, CrmActivityKind } from "../../domain/crm.js";
2
2
  import type { DealKind } from "../../domain/deals.js";
3
+ import type { CacheDatabase } from "../driver.js";
3
4
  import type { AccountKey } from "../types.js";
4
5
  import type { StoreContext } from "./open.js";
5
6
  export declare const ACTIVITY_RECORD = "crm.activity";
7
+ /**
8
+ * Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
9
+ * the rows they were on. Answers how many.
10
+ */
11
+ export declare const forgetActivitiesOn: (database: CacheDatabase, accountId: number, kind: "person" | "organization", externalIds: readonly string[], at: number) => number;
6
12
  /** One activity as `deals show` lists it. */
7
13
  export interface StoredActivity {
8
14
  externalId: string;
@@ -20,7 +26,7 @@ export interface StoredActivity {
20
26
  export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
21
27
  export interface CrmActivitiesSaved {
22
28
  saved: number;
23
- /** On no deal or lead this copy keeps, so not stored. */
29
+ /** On no deal, lead, contact or company this copy keeps, so not stored. */
24
30
  outOfScope: number;
25
31
  }
26
32
  export declare const crmActivitiesOver: (context: StoreContext) => {
@@ -3,6 +3,20 @@ import { accountPk, findAccountPk } from "./accounts.js";
3
3
  import { crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
4
4
  import { write } from "./transaction.js";
5
5
  export const ACTIVITY_RECORD = "crm.activity";
6
+ /**
7
+ * Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
8
+ * the rows they were on. Answers how many.
9
+ */
10
+ export const forgetActivitiesOn = (database, accountId, kind, externalIds, at) => {
11
+ const removed = "rr.target_type = ? AND rr.target_external_id IN (SELECT value FROM json_each(?))";
12
+ const ids = JSON.stringify(externalIds);
13
+ return database
14
+ .prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
15
+ `AND EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' AND ${removed}) ` +
16
+ "AND NOT EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' " +
17
+ `AND NOT (${removed}))`)
18
+ .run(at, accountId, ACTIVITY_RECORD, kind, ids, kind, ids).changes;
19
+ };
6
20
  /** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
7
21
  const MOST_BODY = 20_000;
8
22
  const MOST_SUBJECT = 500;
@@ -25,18 +39,29 @@ export const activityTexts = (database, kind) => {
25
39
  };
26
40
  export const crmActivitiesOver = (context) => {
27
41
  const { database, now } = context;
28
- const kept = (accountId, kind, externalId) => database
29
- .prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
30
- .get(accountId, externalId) !== undefined;
42
+ /** A deal or lead the copy keeps, a contact it holds, or a company it keeps. */
43
+ const kept = (key, accountId, kind, externalId) => (kind === "person"
44
+ ? database
45
+ .prepare("SELECT 1 FROM identities WHERE provider = ? AND external_id = ?")
46
+ .get(key.provider, crmIdentityId(key, externalId))
47
+ : kind === "organization"
48
+ ? database
49
+ .prepare("SELECT 1 FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
50
+ "AND deleted_at IS NULL")
51
+ .get(accountId, externalId)
52
+ : database
53
+ .prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
54
+ .get(accountId, externalId)) !== undefined;
31
55
  const save = (key, activities) => write(database, () => {
32
56
  const accountId = accountPk(context, key);
33
57
  const at = now();
34
58
  let saved = 0;
35
59
  let outOfScope = 0;
36
60
  for (const activity of activities) {
37
- const on = activity.on.filter((one) => kept(accountId, one.kind, one.externalId));
61
+ const on = activity.on.filter((one) => kept(key, accountId, one.kind, one.externalId));
38
62
  const held = database
39
- .prepare("SELECT id FROM records WHERE account_id = ? AND type = ? AND external_id = ?")
63
+ .prepare("SELECT id, json_extract(fields, '$.done') AS done, json_extract(fields, '$.done_at') AS done_at " +
64
+ "FROM records WHERE account_id = ? AND type = ? AND external_id = ?")
40
65
  .get(accountId, ACTIVITY_RECORD, activity.externalId);
41
66
  if (on.length === 0) {
42
67
  // It left every kept deal: one stored before goes with it.
@@ -51,6 +76,8 @@ export const crmActivitiesOver = (context) => {
51
76
  body: textOf(activity.body, MOST_BODY),
52
77
  due_at: activity.dueAt ?? null,
53
78
  done: activity.done,
79
+ // When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen.
80
+ done_at: activity.done ? (held?.done ? (held.done_at ?? null) : activity.updatedAt) : null,
54
81
  assignee: activity.assignee ? crmIdentityId(key, activity.assignee, "user") : null,
55
82
  created_at: activity.createdAt,
56
83
  updated_at: activity.updatedAt,
@@ -18,10 +18,13 @@ export declare const withoutPlaceholder: (name: string) => string | null;
18
18
  * assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
19
19
  * saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
20
20
  * deleted unless anything still points at them. People named after a contact keep that name without the import's
21
- * `null #<id>`; the owner's person is never renamed.
21
+ * `null #<id>`; the owner's person is never renamed. `only` removes just these contacts, by the CRM's id, whenever they
22
+ * were saved and whatever company names them, unless a kept deal or lead does. Activities on nothing but a removed
23
+ * contact are marked deleted.
22
24
  */
23
- export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
25
+ export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun, only, }: {
24
26
  users?: readonly string[];
25
27
  before: number;
26
28
  dryRun?: boolean;
29
+ only?: readonly string[];
27
30
  }) => CrmContactsRemoved;
@@ -1,5 +1,6 @@
1
1
  import { findAccountPk, OWN, referencesTo } from "./accounts.js";
2
- import { crmAccountPrefix, crmIdentityId } from "./crm-rows.js";
2
+ import { forgetActivitiesOn } from "./crm-activities.js";
3
+ import { crmAccountPrefix, crmIdentityId, PERSON_RECORD } from "./crm-rows.js";
3
4
  import { write } from "./transaction.js";
4
5
  /** A CRM import can leave `null` or `null #<id>` in a name field; no person is called that. */
5
6
  const PLACEHOLDER = /(?:^|\s)null(?:\s+#\d+)?(?=\s|$)/gi;
@@ -18,9 +19,11 @@ const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
18
19
  * assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
19
20
  * saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
20
21
  * deleted unless anything still points at them. People named after a contact keep that name without the import's
21
- * `null #<id>`; the owner's person is never renamed.
22
+ * `null #<id>`; the owner's person is never renamed. `only` removes just these contacts, by the CRM's id, whenever they
23
+ * were saved and whatever company names them, unless a kept deal or lead does. Activities on nothing but a removed
24
+ * contact are marked deleted.
22
25
  */
23
- export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
26
+ export const removeCrmContacts = (context, key, { users, before, dryRun = false, only, }) => {
24
27
  const { database } = context;
25
28
  const accountId = findAccountPk(context, key);
26
29
  if (accountId === undefined)
@@ -55,20 +58,24 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
55
58
  database
56
59
  .prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
57
60
  `LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
58
- "AND i.created_at < ? AND i.updated_at < ? " +
59
- (users === undefined
60
- ? ""
61
- : "AND coalesce(json_extract(i.metadata, '$.assignee'), '') NOT IN (SELECT id FROM temp.crm_scope) ") +
62
- `AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
63
- "AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
64
- "AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
65
- "AND +k.to_type = 'organization' AND k.kind = 'member-of' AND k.role = 'contact' AND k.source = 'crm' " +
66
- `AND k.deleted_at IS NULL AND r.account_id = ${accountId} AND r.type = 'organization' ` +
67
- "AND r.deleted_at IS NULL) " +
61
+ (only === undefined
62
+ ? "AND i.created_at < ? AND i.updated_at < ? " +
63
+ (users === undefined
64
+ ? ""
65
+ : "AND coalesce(json_extract(i.metadata, '$.assignee'), '') NOT IN (SELECT id FROM temp.crm_scope) ") +
66
+ `AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
67
+ "AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
68
+ "AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
69
+ "AND +k.to_type = 'organization' AND k.kind = 'member-of' AND k.role = 'contact' AND k.source = 'crm' " +
70
+ `AND k.deleted_at IS NULL AND r.account_id = ${accountId} AND r.type = 'organization' ` +
71
+ "AND r.deleted_at IS NULL) "
72
+ : "AND i.external_id IN (SELECT value FROM json_each(?)) " +
73
+ // A contact on the owner's own deal stays: the next sync would copy it back from that deal.
74
+ `AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} `) +
68
75
  "AND NOT EXISTS (SELECT 1 FROM identity_link_events e WHERE e.identity_id = i.id AND e.author = 'owner') " +
69
76
  "AND NOT EXISTS (SELECT 1 FROM temp.crm_proposed c WHERE c.decided AND c.ref = i.provider || ':' || " +
70
77
  "i.external_id)")
71
- .run(...contact, before, before);
78
+ .run(...contact, ...(only === undefined ? [before, before] : [JSON.stringify(only.map((id) => crmIdentityId(key, id)))]));
72
79
  database.exec(`DELETE FROM temp.crm_gone WHERE id IN (${identityRefs})`);
73
80
  // A same-email join left the contact's first person empty; it goes too, unless something points at it.
74
81
  database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT person FROM temp.crm_gone WHERE person IS NOT NULL");
@@ -101,6 +108,15 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
101
108
  database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
102
109
  `json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
103
110
  `OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
111
+ // The contact's own fields go with it, marked deleted as the CRM's other rows are (WC-DATA-7).
112
+ database
113
+ .prepare(`UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL AND external_id IN ` +
114
+ `(SELECT substr(external_id, ?) FROM identities WHERE id IN ${gone})`)
115
+ .run(context.now(), accountId, PERSON_RECORD, prefix.length + 1);
116
+ forgetActivitiesOn(database, accountId, "person", database
117
+ .prepare(`SELECT substr(external_id, ?) AS id FROM identities WHERE id IN ${gone}`)
118
+ .all(prefix.length + 1)
119
+ .map((row) => String(row.id)), context.now());
104
120
  for (const table of ["identity_revisions", "identity_link_events", "identity_links", "account_identities"])
105
121
  database.exec(`DELETE FROM ${table} WHERE identity_id IN ${gone}`);
106
122
  const contacts = database.prepare(`DELETE FROM identities WHERE id IN ${gone}`).run().changes;
@@ -14,6 +14,13 @@ export declare const TABLES: {
14
14
  };
15
15
  /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
16
16
  export declare const SOURCE = "crm";
17
+ /** A deal or lead given to another CRM user, as the sync saw it. */
18
+ export declare const OWNER_CHANGE_RECORD = "crm.owner-change";
19
+ /**
20
+ * A contact's own fields beside its identity: who it is assigned to, when the CRM made and changed it, its page and
21
+ * its custom values. Not `person`: a records import's `person` without an entity is matched into people.
22
+ */
23
+ export declare const PERSON_RECORD = "crm.person";
17
24
  /**
18
25
  * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
19
26
  * `contact:` references percent-encode it, so the `/` stays one part.
@@ -1,5 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { STAGE_OUTCOMES } from "../../domain/deals.js";
4
+ import { dayIn } from "../../domain/moment.js";
3
5
  import { currencyOf, minorUnits, scaleOf } from "../../domain/money.js";
4
6
  import { fold } from "../normalize.js";
5
7
  import { authorActor } from "./memories.js";
@@ -39,6 +41,13 @@ const moneyOf = (item) => {
39
41
  };
40
42
  /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
41
43
  export const SOURCE = "crm";
44
+ /** A deal or lead given to another CRM user, as the sync saw it. */
45
+ export const OWNER_CHANGE_RECORD = "crm.owner-change";
46
+ /**
47
+ * A contact's own fields beside its identity: who it is assigned to, when the CRM made and changed it, its page and
48
+ * its custom values. Not `person`: a records import's `person` without an entity is matched into people.
49
+ */
50
+ export const PERSON_RECORD = "crm.person";
42
51
  /**
43
52
  * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
44
53
  * `contact:` references percent-encode it, so the `/` stays one part.
@@ -142,6 +151,21 @@ export const crmRowsOver = (context) => {
142
151
  .get(accountId, externalId);
143
152
  return row?.entity_id == null ? null : Number(row.entity_id);
144
153
  };
154
+ /** Who a deal or lead went from and to, as `crm.owner-change` on it: a CRM's users are often not listed. */
155
+ const ownerChanged = (accountId, kind, item, change, at) => {
156
+ const when = epoch(item.updatedAt, at);
157
+ const externalId = `${kind}/${item.externalId}/${when}`;
158
+ const fields = { kind, ...change, at: when };
159
+ const inserted = database
160
+ .prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, updated_at) " +
161
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING id")
162
+ .get(accountId, OWNER_CHANGE_RECORD, externalId, JSON.stringify(fields), externalId, SOURCE, at, at);
163
+ if (inserted)
164
+ database
165
+ .prepare("INSERT INTO record_relations (record_id, role, target_type, target_external_id, created_at) " +
166
+ "VALUES (?, 'on', ?, ?, ?)")
167
+ .run(Number(inserted.id), kind, item.externalId, at);
168
+ };
145
169
  /** The deal or lead row of `(account, external id)`; `writer` gives what another writer than CRM sync resolved. */
146
170
  const saveItemRow = (key, accountId, kind, item, at, writer = {}) => {
147
171
  const pipeline = pipelineOf(accountId, kind, item.pipeline);
@@ -160,9 +184,18 @@ export const crmRowsOver = (context) => {
160
184
  if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
161
185
  throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
162
186
  const status = item.status ?? String(stage.outcome);
187
+ const table = TABLES[kind];
188
+ const held = database
189
+ .prepare(`SELECT id, status, closed_date, json_extract(metadata, '$.assignee') AS assignee FROM ${table} ` +
190
+ "WHERE account_id = ? AND external_id = ?")
191
+ .get(accountId, item.externalId);
192
+ // A CRM that gives no closed day: the owner's day it was first seen so closed, never that of a later edit (BUG-8).
163
193
  const closed = status === "open"
164
194
  ? null
165
- : (day(item.closedDate, "a closed day") ?? new Date(epoch(item.updatedAt, at)).toISOString().slice(0, 10));
195
+ : (day(item.closedDate, "a closed day") ??
196
+ (held && held.status === status && held.closed_date != null
197
+ ? String(held.closed_date)
198
+ : dayIn(epoch(item.updatedAt, at), timezoneOf())));
166
199
  const deal = writer.deal !== undefined
167
200
  ? writer.deal === null
168
201
  ? undefined
@@ -196,13 +229,12 @@ export const crmRowsOver = (context) => {
196
229
  created: epoch(item.createdAt, at),
197
230
  updated: epoch(item.updatedAt, at),
198
231
  };
199
- const table = TABLES[kind];
200
- const held = database
201
- .prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
202
- .get(accountId, item.externalId);
203
232
  let id;
204
233
  if (held) {
205
234
  id = Number(held.id);
235
+ const owner = item.assignee === undefined ? undefined : (metadata.assignee ?? null);
236
+ if (owner !== undefined && owner !== (held.assignee ?? null))
237
+ ownerChanged(accountId, kind, item, { from: held.assignee ?? null, to: owner }, at);
206
238
  database
207
239
  .prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
208
240
  "close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
@@ -61,8 +61,9 @@ export interface CrmStageMove {
61
61
  stageName: string;
62
62
  pipelineName: string;
63
63
  }
64
- /** When stage tasks were last opened, or the rules first set: where the CRM's stage history is first read from. */
64
+ /** When the stage-task rules were first set: a stage entered before then opens no task. */
65
65
  export declare const crmStageTasksSince: (database: CacheDatabase, key: AccountKey) => number | null;
66
+ /** `at` stays when the rules were first set: the stage history counts from then, whenever the history arrives. */
66
67
  export declare const saveStageMovesMark: (database: CacheDatabase, key: AccountKey, through: number, now: number) => void;
67
68
  export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
68
69
  export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
@@ -156,16 +156,17 @@ export const crmStageMoves = (database, key, accountId) => {
156
156
  }));
157
157
  return { moves, through };
158
158
  };
159
- /** When stage tasks were last opened, or the rules first set: where the CRM's stage history is first read from. */
159
+ /** When the stage-task rules were first set: a stage entered before then opens no task. */
160
160
  export const crmStageTasksSince = (database, key) => {
161
161
  const row = database
162
162
  .prepare("SELECT at FROM store_settings WHERE key = ?")
163
163
  .get(stageTasksMark(crmSettingKey(key, "stage-tasks")));
164
164
  return row ? Number(row.at) : null;
165
165
  };
166
+ /** `at` stays when the rules were first set: the stage history counts from then, whenever the history arrives. */
166
167
  export const saveStageMovesMark = (database, key, through, now) => {
167
168
  database
168
- .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
169
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
169
170
  .run(stageTasksMark(crmSettingKey(key, "stage-tasks")), JSON.stringify(through), now);
170
171
  };
171
172
  export const parseCrmSettingValue = (name, value) => {
@@ -1,15 +1,35 @@
1
1
  import type { CrmStageEntry } from "../../domain/crm.js";
2
+ import type { DealKind } from "../../domain/deals.js";
3
+ import type { CacheDatabase } from "../driver.js";
2
4
  import type { AccountKey } from "../types.js";
3
5
  import type { CrmStageMove } from "./crm-settings.js";
4
6
  import type { StoreContext } from "./open.js";
5
7
  export declare const STAGE_ENTRY_RECORD = "crm.stage-entry";
8
+ /** An entry whose deal never reached the copy is dropped after this long: the history is read this far back. */
9
+ export declare const STAGE_ENTRY_DAYS = 90;
10
+ /** One stage a deal or lead entered, from the CRM's own history (`exact`) or from the copy's diffs between syncs. */
11
+ export interface StageEntry {
12
+ itemId: number;
13
+ toStageId: number;
14
+ at: number;
15
+ exact: boolean;
16
+ }
6
17
  /**
7
- * The CRM's own record of each stage a deal or lead entered, kept until its stage task is handled: a run stopped
8
- * between reading the history and opening the tasks opens them next time. A handled entry stays, marked deleted, so
9
- * reading the same history again opens nothing.
18
+ * Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
19
+ * where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
20
+ */
21
+ export declare const stageEntriesOf: (database: CacheDatabase, kind: DealKind, filter: {
22
+ pipeline: number;
23
+ } | {
24
+ item: number;
25
+ }) => StageEntry[];
26
+ /**
27
+ * The CRM's own record of each stage a deal or lead entered, read on every sync. An entry waits for its stage task
28
+ * until it is handled; one on a deal the copy does not hold yet is kept, and counts once the deal arrives.
10
29
  */
11
30
  export declare const crmStageEntriesOver: (context: StoreContext) => {
12
31
  save: (key: AccountKey, entries: readonly CrmStageEntry[]) => number;
13
- pending: (key: AccountKey) => CrmStageMove[];
32
+ pending: (key: AccountKey, since: number, at: number) => CrmStageMove[];
14
33
  handled: (ids: readonly number[]) => void;
34
+ expire: (key: AccountKey) => number;
15
35
  };
@@ -2,33 +2,65 @@ import { accountPk, findAccountPk } from "./accounts.js";
2
2
  import { SOURCE, TABLES } from "./crm-rows.js";
3
3
  import { write } from "./transaction.js";
4
4
  export const STAGE_ENTRY_RECORD = "crm.stage-entry";
5
+ /** An entry whose deal never reached the copy is dropped after this long: the history is read this far back. */
6
+ export const STAGE_ENTRY_DAYS = 90;
7
+ /** A stage entered longer ago than this opens no task: the copy missed the deal for more than a sync or two. */
8
+ const STAGE_TASK_DAYS = 7;
9
+ const DAY = 86_400_000;
5
10
  /**
6
- * The CRM's own record of each stage a deal or lead entered, kept until its stage task is handled: a run stopped
7
- * between reading the history and opening the tasks opens them next time. A handled entry stays, marked deleted, so
8
- * reading the same history again opens nothing.
11
+ * Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
12
+ * where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
13
+ */
14
+ export const stageEntriesOf = (database, kind, filter) => {
15
+ const one = "item" in filter;
16
+ const exact = database
17
+ .prepare(`SELECT d.id AS item_id, s.id AS stage_id, json_extract(r.fields, '$.at') AS at FROM records r ` +
18
+ "JOIN record_relations rr ON rr.record_id = r.id AND rr.role = 'on' AND rr.target_type = ? " +
19
+ `JOIN ${TABLES[kind]} d ON d.account_id = r.account_id AND d.external_id = rr.target_external_id ` +
20
+ "JOIN pipeline_stages s ON s.id = json_extract(r.fields, '$.stage_id') WHERE r.type = ? " +
21
+ (one
22
+ ? `AND rr.target_external_id = (SELECT external_id FROM ${TABLES[kind]} WHERE id = ?) AND d.id = ? `
23
+ : "AND s.pipeline_id = ? ") +
24
+ "ORDER BY d.id, json_extract(r.fields, '$.at'), r.id")
25
+ .all(kind, STAGE_ENTRY_RECORD, ...(one ? [filter.item, filter.item] : [filter.pipeline]))
26
+ .map((row) => ({ itemId: Number(row.item_id), toStageId: Number(row.stage_id), at: Number(row.at), exact: true }));
27
+ const withHistory = new Set(exact.map(({ itemId }) => itemId));
28
+ const copied = database
29
+ .prepare("SELECT item_id, to_stage_id, changed_at FROM pipeline_stage_changes WHERE item_type = ? " +
30
+ `AND ${one ? "item_id" : "pipeline_id"} = ? ORDER BY item_id, id`)
31
+ .all(kind, one ? filter.item : filter.pipeline)
32
+ .filter((row) => !withHistory.has(Number(row.item_id)))
33
+ .map((row) => ({
34
+ itemId: Number(row.item_id),
35
+ toStageId: Number(row.to_stage_id),
36
+ at: Number(row.changed_at),
37
+ exact: false,
38
+ }));
39
+ return [...exact, ...copied];
40
+ };
41
+ /**
42
+ * The CRM's own record of each stage a deal or lead entered, read on every sync. An entry waits for its stage task
43
+ * until it is handled; one on a deal the copy does not hold yet is kept, and counts once the deal arrives.
9
44
  */
10
45
  export const crmStageEntriesOver = (context) => {
11
46
  const { database, now } = context;
12
- /** Answers how many were new; an entry on a deal or lead the copy does not hold, or into an unknown stage, is not. */
47
+ /** Answers how many were new; an entry into a stage the copy does not hold is not kept. */
13
48
  const save = (key, entries) => write(database, () => {
14
49
  const accountId = accountPk(context, key);
15
50
  const at = now();
16
51
  let saved = 0;
17
52
  for (const entry of entries) {
18
- const item = database
19
- .prepare(`SELECT id FROM ${TABLES[entry.kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
20
- .get(accountId, entry.item);
21
53
  const stage = database
22
54
  .prepare("SELECT s.id FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id " +
23
55
  "WHERE p.account_id = ? AND p.kind = ? AND p.external_id = ? AND s.external_id = ?")
24
56
  .get(accountId, entry.kind, entry.pipeline, entry.stage);
25
- if (!item || !stage)
57
+ if (!stage)
26
58
  continue;
27
59
  const externalId = `${entry.kind}/${entry.externalId}`;
28
60
  const inserted = database
29
61
  .prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, updated_at) " +
30
62
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING id")
31
- .get(accountId, STAGE_ENTRY_RECORD, externalId, JSON.stringify({ kind: entry.kind, item_id: Number(item.id), stage_id: Number(stage.id), at: entry.at }), externalId, SOURCE, at, at);
63
+ .get(accountId, STAGE_ENTRY_RECORD, externalId, JSON.stringify({ kind: entry.kind, item: entry.item, stage_id: Number(stage.id), at: entry.at }), externalId, SOURCE, at, at);
32
64
  if (!inserted)
33
65
  continue;
34
66
  database
@@ -39,19 +71,27 @@ export const crmStageEntriesOver = (context) => {
39
71
  }
40
72
  return saved;
41
73
  });
42
- /** The entries not handled yet, oldest first, as stage moves whose task source names the CRM's history row. */
43
- const pending = (key) => {
74
+ /**
75
+ * The entries on rows the copy holds whose stage task is not handled yet, made at or after `since` and within
76
+ * `STAGE_TASK_DAYS` of `at`, oldest first, as stage moves whose task source names the CRM's history row.
77
+ */
78
+ const pending = (key, since, at) => {
44
79
  const accountId = findAccountPk(context, key);
45
80
  if (accountId === undefined)
46
81
  return [];
47
82
  return database
48
- .prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, " +
49
- "json_extract(r.fields, '$.item_id') AS item_id, s.external_id AS stage, s.name AS stage_name, " +
50
- "p.name AS pipeline_name FROM records r " +
83
+ .prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, coalesce(d.id, l.id) AS item_id, " +
84
+ "s.external_id AS stage, s.name AS stage_name, p.name AS pipeline_name FROM records r " +
85
+ "JOIN record_relations rr ON rr.record_id = r.id AND rr.role = 'on' " +
86
+ "LEFT JOIN deals d ON rr.target_type = 'deal' AND d.account_id = r.account_id " +
87
+ "AND d.external_id = rr.target_external_id AND d.deleted_at IS NULL " +
88
+ "LEFT JOIN leads l ON rr.target_type = 'lead' AND l.account_id = r.account_id " +
89
+ "AND l.external_id = rr.target_external_id AND l.deleted_at IS NULL " +
51
90
  "JOIN pipeline_stages s ON s.id = json_extract(r.fields, '$.stage_id') JOIN pipelines p ON p.id = s.pipeline_id " +
52
- "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL " +
91
+ "WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL AND coalesce(d.id, l.id) IS NOT NULL " +
92
+ "AND json_extract(r.fields, '$.handled') IS NULL AND json_extract(r.fields, '$.at') >= ? " +
53
93
  "ORDER BY json_extract(r.fields, '$.at'), r.id")
54
- .all(accountId, STAGE_ENTRY_RECORD)
94
+ .all(accountId, STAGE_ENTRY_RECORD, Math.max(since, at - STAGE_TASK_DAYS * DAY))
55
95
  .map((row) => {
56
96
  const ref = `${String(row.kind)}:${String(row.item_id)}`;
57
97
  return {
@@ -68,7 +108,26 @@ export const crmStageEntriesOver = (context) => {
68
108
  const handled = (ids) => write(database, () => {
69
109
  const at = now();
70
110
  for (const id of ids)
71
- database.prepare("UPDATE records SET deleted_at = ? WHERE id = ?").run(at, id);
111
+ database
112
+ .prepare("UPDATE records SET fields = json_set(fields, '$.handled', 1), updated_at = ? WHERE id = ?")
113
+ .run(at, id);
114
+ });
115
+ /** Entries no stored row has claimed for `STAGE_ENTRY_DAYS`: their deal is outside the copy for good. */
116
+ const expire = (key) => write(database, () => {
117
+ const accountId = findAccountPk(context, key);
118
+ if (accountId === undefined)
119
+ return 0;
120
+ const at = now();
121
+ return database
122
+ .prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
123
+ "AND json_extract(fields, '$.handled') IS NULL AND json_extract(fields, '$.at') < ? " +
124
+ "AND NOT EXISTS (SELECT 1 FROM record_relations rr JOIN deals d ON rr.target_type = 'deal' " +
125
+ "AND d.account_id = records.account_id AND d.external_id = rr.target_external_id " +
126
+ "WHERE rr.record_id = records.id) " +
127
+ "AND NOT EXISTS (SELECT 1 FROM record_relations rr JOIN leads l ON rr.target_type = 'lead' " +
128
+ "AND l.account_id = records.account_id AND l.external_id = rr.target_external_id " +
129
+ "WHERE rr.record_id = records.id)")
130
+ .run(at, accountId, STAGE_ENTRY_RECORD, at - STAGE_ENTRY_DAYS * DAY).changes;
72
131
  });
73
- return { save, pending, handled };
132
+ return { save, pending, handled, expire };
74
133
  };
@@ -97,13 +97,18 @@ export interface CrmCopies {
97
97
  through: number;
98
98
  }>;
99
99
  markStageMoves(key: AccountKey, through: number): Promise<void>;
100
- /** When stage tasks were last opened, or the rules first set; null without rules. */
100
+ /** When the stage-task rules were first set; null without rules. */
101
101
  stageTasksSince(key: AccountKey): Promise<number | null>;
102
- /** Entries from the CRM's stage history on kept deals and leads; answers how many were new. */
102
+ /** Entries from the CRM's stage history, on deals and leads stored or not yet; answers how many were new. */
103
103
  saveStageEntries(key: AccountKey, entries: readonly CrmStageEntry[]): Promise<number>;
104
- /** The stored history entries whose stage task is not handled yet, oldest first. */
105
- stageEntries(key: AccountKey): Promise<CrmStageMove[]>;
104
+ /**
105
+ * The history entries on stored rows whose task is not handled yet, made since the rules were first set and within
106
+ * `STAGE_TASK_DAYS` of `now`: a deal that joins the copy late opens tasks for its recent moves only.
107
+ */
108
+ stageEntries(key: AccountKey, now: number): Promise<CrmStageMove[]>;
106
109
  handleStageEntries(ids: readonly number[]): Promise<void>;
110
+ /** Drops the history entries no stored row claimed within `STAGE_ENTRY_DAYS`; answers how many. */
111
+ expireStageEntries(key: AccountKey): Promise<number>;
107
112
  /** Whether the owner turned on reading activities and tasks (`activities` setting). */
108
113
  activitiesOn(key: AccountKey): Promise<boolean>;
109
114
  /** Activities and tasks, each on the kept deals and leads it names; one on none of them is not stored. */
@@ -127,6 +132,11 @@ export interface CrmCopies {
127
132
  before: number;
128
133
  dryRun?: boolean;
129
134
  }): Promise<CrmContactsRemoved>;
135
+ /**
136
+ * Removes one contact from the copy, as `removeContacts` removes those outside the scope: a write made it another
137
+ * user's client, which the copy does not keep (NEED-2661). Answers what went.
138
+ */
139
+ removeContact(key: AccountKey, externalId: string): Promise<CrmContactsRemoved>;
130
140
  /** How many of the kind the account holds, not deleted; every contact it ever saved. */
131
141
  count(key: AccountKey, kind: CrmKind): Promise<number>;
132
142
  /** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */