@wirecat/cli-core 0.604.0 → 0.606.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 (141) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +2 -2
  5. package/dist/cli/index.js +2 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/cli/store-settings.js +38 -4
  15. package/dist/crm/cli/index.js +3 -1
  16. package/dist/crm/index.d.ts +2 -2
  17. package/dist/crm/index.js +1 -1
  18. package/dist/crm/source.d.ts +35 -5
  19. package/dist/crm/sync.d.ts +15 -7
  20. package/dist/crm/sync.js +169 -11
  21. package/dist/domain/crm.d.ts +41 -2
  22. package/dist/domain/deals.d.ts +5 -2
  23. package/dist/domain/deals.js +5 -2
  24. package/dist/domain/record-types.d.ts +61 -0
  25. package/dist/domain/record-types.js +26 -0
  26. package/dist/domain/records.d.ts +3 -5
  27. package/dist/domain/records.js +10 -13
  28. package/dist/domain/relations.d.ts +125 -0
  29. package/dist/domain/relations.js +107 -0
  30. package/dist/entities/contact-activity.d.ts +4 -0
  31. package/dist/entities/contact-activity.js +1 -0
  32. package/dist/entities/contact-context.d.ts +20 -0
  33. package/dist/entities/contact-context.js +2 -0
  34. package/dist/entities/deal.d.ts +2 -2
  35. package/dist/entities/deal.js +2 -1
  36. package/dist/entities/index.d.ts +39 -13
  37. package/dist/entities/relationship.d.ts +8 -2
  38. package/dist/entities/relationship.js +8 -2
  39. package/dist/entities/task-results.d.ts +10 -10
  40. package/dist/errors/failures.d.ts +17 -1
  41. package/dist/errors/failures.js +57 -1
  42. package/dist/errors/reasons.js +28 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -0
  45. package/dist/mail/cli/review.js +20 -6
  46. package/dist/mail/index.d.ts +1 -1
  47. package/dist/mail/marks.d.ts +10 -5
  48. package/dist/mail/marks.js +16 -8
  49. package/dist/mail/review.d.ts +5 -0
  50. package/dist/mcp/tool.js +2 -1
  51. package/dist/runs/recording.js +13 -4
  52. package/dist/services/deps.js +4 -6
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  55. package/dist/services/link-scorers/chat-senders.js +7 -4
  56. package/dist/services/link-scorers/mail-thread.js +1 -0
  57. package/dist/services/link-scorers/member-chats.js +1 -0
  58. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  59. package/dist/services/link-scorers/member-dialog.js +4 -3
  60. package/dist/services/link-scorers/scan.d.ts +5 -2
  61. package/dist/services/link-scorers/scan.js +100 -54
  62. package/dist/services/link-scorers/shared.d.ts +2 -2
  63. package/dist/services/link-scorers/shared.js +8 -4
  64. package/dist/services/link-scorers/types.d.ts +3 -0
  65. package/dist/services/metadata.d.ts +1 -1
  66. package/dist/services/person-context.d.ts +24 -7
  67. package/dist/services/person-context.js +45 -11
  68. package/dist/services/person-preparation.js +4 -5
  69. package/dist/services/project-status/index.js +2 -1
  70. package/dist/services/stored-project-gathering.js +4 -3
  71. package/dist/store/damage.d.ts +3 -1
  72. package/dist/store/damage.js +19 -12
  73. package/dist/store/document-transfer/index.js +7 -0
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/index.d.ts +7 -1
  77. package/dist/store/index.js +2 -0
  78. package/dist/store/marks.d.ts +57 -0
  79. package/dist/store/marks.js +121 -0
  80. package/dist/store/project-transfer/preview.js +12 -7
  81. package/dist/store/project-transfer/request.d.ts +4 -1
  82. package/dist/store/project-transfer/schema.d.ts +9 -2
  83. package/dist/store/project-transfer/schema.js +4 -0
  84. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  85. package/dist/store/recover.js +16 -1
  86. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  87. package/dist/store/sqlite/crm-settings.js +80 -0
  88. package/dist/store/sqlite/crm.d.ts +42 -2
  89. package/dist/store/sqlite/crm.js +397 -36
  90. package/dist/store/sqlite/deals.js +3 -2
  91. package/dist/store/sqlite/finance.d.ts +8 -1
  92. package/dist/store/sqlite/finance.js +10 -3
  93. package/dist/store/sqlite/involvement-queue.js +4 -3
  94. package/dist/store/sqlite/knowledge.d.ts +7 -3
  95. package/dist/store/sqlite/knowledge.js +43 -31
  96. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  97. package/dist/store/sqlite/link-kinds.js +4 -2
  98. package/dist/store/sqlite/manifest.js +5 -0
  99. package/dist/store/sqlite/memories.d.ts +1 -1
  100. package/dist/store/sqlite/memories.js +33 -7
  101. package/dist/store/sqlite/migrations.generated.js +31 -0
  102. package/dist/store/sqlite/notes.d.ts +3 -2
  103. package/dist/store/sqlite/notes.js +23 -6
  104. package/dist/store/sqlite/open-store.js +4 -1
  105. package/dist/store/sqlite/organizations.d.ts +8 -0
  106. package/dist/store/sqlite/organizations.js +14 -0
  107. package/dist/store/sqlite/own-identities.d.ts +1 -1
  108. package/dist/store/sqlite/own-identities.js +7 -5
  109. package/dist/store/sqlite/person-links.d.ts +5 -2
  110. package/dist/store/sqlite/person-links.js +24 -18
  111. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  112. package/dist/store/sqlite/person-preparation.js +3 -2
  113. package/dist/store/sqlite/person-separation.d.ts +5 -0
  114. package/dist/store/sqlite/person-separation.js +26 -0
  115. package/dist/store/sqlite/project-transfer/records.js +14 -3
  116. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  117. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  118. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  119. package/dist/store/sqlite/record-projectors.js +72 -0
  120. package/dist/store/sqlite/records.js +12 -70
  121. package/dist/store/sqlite/relation-list.d.ts +43 -0
  122. package/dist/store/sqlite/relation-list.js +133 -0
  123. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  124. package/dist/store/sqlite/relation-proposals.js +134 -10
  125. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  126. package/dist/store/sqlite/relation-reads.js +7 -0
  127. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  128. package/dist/store/sqlite/relation-roles.js +91 -0
  129. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  130. package/dist/store/sqlite/reported-relations.js +132 -0
  131. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  132. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  133. package/dist/store/sqlite/schema/links.d.ts +360 -0
  134. package/dist/store/sqlite/schema/links.js +32 -0
  135. package/dist/store/sqlite/schema.d.ts +2 -296
  136. package/dist/store/sqlite/schema.js +2 -24
  137. package/dist/store/sqlite/transaction.js +2 -5
  138. package/dist/store/store.d.ts +3 -0
  139. package/dist/store/store.js +5 -0
  140. package/dist/store/types.d.ts +5 -0
  141. package/package.json +5 -5
@@ -1,12 +1,18 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { isItemKind, } from "../../domain/crm.js";
2
3
  import { DEAL_ROLES, STAGE_OUTCOMES } from "../../domain/deals.js";
3
4
  import { currencyOf, minorUnits } from "../../domain/money.js";
4
5
  import { recordFingerprint } from "../../domain/records.js";
5
6
  import { fold } from "../normalize.js";
6
7
  import { accountPk, findAccountPk } from "./accounts.js";
7
- import { linkKind } from "./link-kinds.js";
8
+ import { crmCompanyTypes } from "./crm-settings.js";
8
9
  import { authorActor } from "./memories.js";
10
+ import { syncReportedIn } from "./reported-relations.js";
11
+ import { clearState, syncStateOf, writeState } from "./sync.js";
9
12
  import { write } from "./transaction.js";
13
+ const PENDING = "crm:pending-relations";
14
+ const PENDING_DAYS = 30;
15
+ const PENDING_MOST = 5000;
10
16
  const TABLES = { deal: "deals", lead: "leads" };
11
17
  /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
12
18
  const SOURCE = "crm";
@@ -15,6 +21,13 @@ const SOURCE = "crm";
15
21
  * `contact:` references percent-encode it, so the `/` stays one part.
16
22
  */
17
23
  export const crmIdentityId = (key, externalId, type = "contact") => `${key.account}/${type}/${externalId}`;
24
+ const tallied = () => ({ issues: [], skippedOwnerRejected: 0, unlistedUsers: 0, droppedPending: 0 });
25
+ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPending }) => ({
26
+ ...(issues.length ? { issues } : {}),
27
+ ...(skippedOwnerRejected ? { skippedOwnerRejected } : {}),
28
+ ...(unlistedUsers ? { unlistedUsers } : {}),
29
+ ...(droppedPending ? { droppedPending } : {}),
30
+ });
18
31
  const day = (value, what) => {
19
32
  if (value === undefined || value === null || value === "")
20
33
  return null;
@@ -163,13 +176,37 @@ export const crmCopiesOver = (context, people) => {
163
176
  ...(row.options == null ? {} : { options: JSON.parse(String(row.options)) }),
164
177
  }));
165
178
  };
166
- const personIdOf = (key, externalId) => {
179
+ const personIdOf = (key, externalId, type = "contact") => {
167
180
  const row = database
168
181
  .prepare("SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
169
182
  "WHERE i.provider = ? AND i.external_id = ?")
170
- .get(key.provider, crmIdentityId(key, externalId));
183
+ .get(key.provider, crmIdentityId(key, externalId, type));
171
184
  return row ? Number(row.person_id) : null;
172
185
  };
186
+ /**
187
+ * How many people the contact's email belongs to; none once the owner separated this contact, who already decided.
188
+ */
189
+ const peopleSharing = (key, externalId, email) => {
190
+ const decided = database
191
+ .prepare("SELECT 1 FROM identity_link_events e JOIN identities i ON i.id = e.identity_id WHERE i.provider = ? " +
192
+ "AND i.external_id = ? AND e.author = 'owner' LIMIT 1")
193
+ .get(key.provider, crmIdentityId(key, externalId));
194
+ if (decided)
195
+ return 0;
196
+ return Number(database
197
+ .prepare("SELECT count(DISTINCT l.person_id) AS n FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
198
+ "WHERE i.email = ?")
199
+ .get(email)?.n);
200
+ };
201
+ /** A person a CRM contact or user made has no name when it joined the mail contact of its address first. */
202
+ const nameUnnamed = (key, externalId, type, name) => {
203
+ const person = personIdOf(key, externalId, type);
204
+ if (person !== null && name)
205
+ database
206
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL")
207
+ .run(name, now(), person);
208
+ return person;
209
+ };
173
210
  const organizationIdOf = (accountId, externalId) => {
174
211
  const row = database
175
212
  .prepare("SELECT entity_id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
@@ -177,7 +214,151 @@ export const crmCopiesOver = (context, people) => {
177
214
  .get(accountId, externalId);
178
215
  return row?.entity_id == null ? null : Number(row.entity_id);
179
216
  };
180
- const saveItem = (key, accountId, kind, item, at) => {
217
+ const refOf = (key, accountId, ref) => {
218
+ if (ref.type === "contact" || ref.type === "user") {
219
+ const person = personIdOf(key, ref.id, ref.type);
220
+ return person === null ? null : `person:${person}`;
221
+ }
222
+ // A row the CRM deleted is no end: a relationship waiting for it is never written.
223
+ const row = ref.type === "company"
224
+ ? database
225
+ .prepare("SELECT entity_id AS id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
226
+ "AND entity_type = 'organization' AND deleted_at IS NULL")
227
+ .get(accountId, ref.id)
228
+ : database
229
+ .prepare(`SELECT id FROM ${TABLES[ref.type]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
230
+ .get(accountId, ref.id);
231
+ if (row?.id == null)
232
+ return null;
233
+ return `${ref.type === "company" ? "organization" : ref.type}:${row.id}`;
234
+ };
235
+ const pendingBook = (accountId) => {
236
+ let byOwner;
237
+ let changed = false;
238
+ const load = () => {
239
+ if (byOwner)
240
+ return byOwner;
241
+ byOwner = new Map();
242
+ try {
243
+ const value = JSON.parse(syncStateOf(context, accountId, PENDING)?.value ?? "[]");
244
+ for (const one of Array.isArray(value) ? value : [])
245
+ byOwner.set(one.owner, [...(byOwner.get(one.owner) ?? []), { ...one, at: Number(one.at) || now() }]);
246
+ }
247
+ catch { }
248
+ return byOwner;
249
+ };
250
+ return {
251
+ replace: (owner, entries) => {
252
+ const held = load();
253
+ if (!entries.length && !held.has(owner))
254
+ return;
255
+ if (entries.length)
256
+ held.set(owner, entries);
257
+ else
258
+ held.delete(owner);
259
+ changed = true;
260
+ },
261
+ forget: (owner) => {
262
+ if (load().delete(owner))
263
+ changed = true;
264
+ },
265
+ all: () => [...load().values()].flat(),
266
+ flush: () => {
267
+ if (!byOwner)
268
+ return 0;
269
+ const all = [...byOwner.values()].flat();
270
+ const fresh = all
271
+ .filter((one) => one.at > now() - PENDING_DAYS * 86_400_000)
272
+ .sort((a, b) => b.at - a.at)
273
+ .slice(0, PENDING_MOST);
274
+ if (!changed && fresh.length === all.length)
275
+ return 0;
276
+ if (fresh.length)
277
+ writeState(context, accountId, PENDING, JSON.stringify(fresh));
278
+ else
279
+ clearState(context, accountId, PENDING);
280
+ changed = false;
281
+ return all.length - fresh.length;
282
+ },
283
+ };
284
+ };
285
+ /**
286
+ * Reports one CRM row's relationships as a diff (`relations.syncReported`) inside `scope`. One whose other end is not
287
+ * stored yet waits in the account's sync state and is tried again after the next sync, so a deal read before its
288
+ * contact still gets the contact.
289
+ */
290
+ const reportFrom = (key, accountId, owner, wanted, scope, tally, pending) => {
291
+ const name = `${owner.type}:${owner.id}`;
292
+ const relationships = [];
293
+ const waiting = [];
294
+ for (const one of wanted) {
295
+ const from = refOf(key, accountId, one.from);
296
+ const to = refOf(key, accountId, one.to);
297
+ if (from === null || to === null) {
298
+ const missing = from === null ? one.from : one.to;
299
+ if (one.pend === false) {
300
+ tally.unlistedUsers += 1;
301
+ continue;
302
+ }
303
+ const { pend: _, ...kept } = one;
304
+ waiting.push({ owner: name, ...kept, at: now() });
305
+ tally.issues.push({
306
+ externalId: owner.id,
307
+ reason: "crm.reference-unknown",
308
+ message: `${owner.type} ${owner.id} names ${missing.type} ${missing.id}, which is not stored yet; ` +
309
+ "the next sync tries again",
310
+ });
311
+ continue;
312
+ }
313
+ relationships.push({
314
+ from,
315
+ to,
316
+ kind: one.kind,
317
+ role: one.role,
318
+ ...(one.metadata ? { metadata: one.metadata } : {}),
319
+ });
320
+ }
321
+ pending.replace(name, waiting);
322
+ const done = syncReportedIn(context, key, relationships, scope, { source: SOURCE });
323
+ tally.skippedOwnerRejected += done.skippedOwnerRejected;
324
+ for (const one of done.issues)
325
+ tally.issues.push({ externalId: owner.id, reason: one.reason, message: one.message });
326
+ };
327
+ /** The pending relationships whose ends are stored now, written without withdrawing anything. */
328
+ const retryPending = (key) => write(database, () => {
329
+ const accountId = findAccountPk(context, key);
330
+ if (accountId === undefined)
331
+ return { written: 0, dropped: 0 };
332
+ const pending = pendingBook(accountId);
333
+ let written = 0;
334
+ const owners = new Map();
335
+ for (const one of pending.all())
336
+ owners.set(one.owner, [...(owners.get(one.owner) ?? []), one]);
337
+ for (const [owner, entries] of owners) {
338
+ const kept = [];
339
+ for (const one of entries) {
340
+ const from = refOf(key, accountId, one.from);
341
+ const to = refOf(key, accountId, one.to);
342
+ if (from === null || to === null) {
343
+ kept.push(one);
344
+ continue;
345
+ }
346
+ const relation = {
347
+ from,
348
+ to,
349
+ kind: one.kind,
350
+ role: one.role,
351
+ ...(one.metadata ? { metadata: one.metadata } : {}),
352
+ };
353
+ syncReportedIn(context, key, [relation], { from: [], kinds: [] }, { source: SOURCE });
354
+ written += 1;
355
+ }
356
+ if (kept.length !== entries.length)
357
+ pending.replace(owner, kept);
358
+ }
359
+ return { written, dropped: pending.flush() };
360
+ });
361
+ const saveItem = (key, accountId, kind, item, at, report) => {
181
362
  const pipeline = pipelineOf(accountId, kind, item.pipeline);
182
363
  const stage = pipeline &&
183
364
  database
@@ -246,30 +427,42 @@ export const crmCopiesOver = (context, people) => {
246
427
  `) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${kind === "lead" ? ", ?" : ""}) RETURNING id`)
247
428
  .get(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, accountId, item.externalId, actor.type, actor.id, SOURCE, values.metadata, values.created, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []))?.id);
248
429
  }
249
- database
250
- .prepare(`DELETE FROM links WHERE from_type = ? AND from_id = ? AND to_type = 'person' AND kind = ${linkKind("related-to")} ` +
251
- "AND source = ?")
252
- .run(kind, id, SOURCE);
253
- const link = database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, source, confirmed, created_at, author, " +
254
- `updated_at) VALUES (?, ?, 'person', ?, ${linkKind("related-to")}, ?, ?, 1, ?, 'rule', ?)`);
255
- const seen = new Set();
256
- for (const person of item.people ?? []) {
257
- const personId = personIdOf(key, person.externalId);
258
- const role = DEAL_ROLES.includes(person.role) ? person.role : "contact";
259
- if (personId === null || seen.has(personId))
260
- continue;
261
- seen.add(personId);
262
- link.run(kind, id, personId, role, SOURCE, at, at);
263
- }
430
+ if (item.people === undefined && item.assignee === undefined)
431
+ return null;
432
+ const self = { type: kind, id: item.externalId };
433
+ const wanted = (item.people ?? []).map((person) => ({
434
+ from: self,
435
+ to: { type: "contact", id: person.externalId },
436
+ kind: "related-to",
437
+ role: DEAL_ROLES.includes(person.role) ? person.role : "contact",
438
+ ...(person.primary ? { metadata: { primary: true } } : {}),
439
+ }));
440
+ if (item.assignee)
441
+ wanted.push({
442
+ from: self,
443
+ to: { type: "user", id: item.assignee },
444
+ kind: "related-to",
445
+ role: "owner",
446
+ ...(report.users ? {} : { pend: false }),
447
+ });
448
+ // Only what the CRM said: its contacts cover the client's roles, its assignee the owner.
449
+ const roles = [
450
+ ...(item.people === undefined ? [] : DEAL_ROLES.filter((role) => role !== "owner")),
451
+ ...(item.assignee === undefined ? [] : ["owner"]),
452
+ ];
453
+ const scope = { from: [`${kind}:${id}`], kinds: ["related-to"], roles };
454
+ reportFrom(key, accountId, self, wanted, scope, report.tally, report.pending);
264
455
  return null;
265
456
  };
266
- const saveItems = (key, kind, items) => write(database, () => {
457
+ const saveItems = (key, kind, items, users) => write(database, () => {
267
458
  const accountId = account(key);
268
459
  const at = now();
269
460
  const skipped = [];
461
+ const tally = tallied();
462
+ const pending = pendingBook(accountId);
270
463
  for (const item of items)
271
464
  try {
272
- const missing = saveItem(key, accountId, kind, item, at);
465
+ const missing = saveItem(key, accountId, kind, item, at, { tally, pending, users });
273
466
  if (missing)
274
467
  skipped.push(missing);
275
468
  }
@@ -278,7 +471,8 @@ export const crmCopiesOver = (context, people) => {
278
471
  throw error;
279
472
  skipped.push({ externalId: item.externalId, reason: "crm.item-invalid", message: error.message });
280
473
  }
281
- return { saved: items.length - skipped.length, skipped };
474
+ tally.droppedPending += pending.flush();
475
+ return { saved: items.length - skipped.length, skipped, ...relationNotes(tally) };
282
476
  });
283
477
  const saveOrganizations = (key, organizations) => write(database, () => {
284
478
  const accountId = account(key);
@@ -288,13 +482,16 @@ export const crmCopiesOver = (context, people) => {
288
482
  const fields = {
289
483
  name,
290
484
  ...(organization.url ? { url: organization.url } : {}),
485
+ ...(organization.own ? { own: true } : {}),
486
+ ...(organization.type === undefined ? {} : { type: organization.type }),
291
487
  ...(organization.metadata ?? {}),
292
488
  };
293
489
  const fingerprint = recordFingerprint(fields, []);
294
490
  const held = database
295
491
  .prepare("SELECT * FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ?")
296
492
  .get(accountId, organization.externalId);
297
- const before = held ? JSON.parse(String(held.fields)).name : undefined;
493
+ const previous = held ? JSON.parse(String(held.fields)) : {};
494
+ const before = previous.name;
298
495
  let entity = held?.entity_type === "organization" && held.entity_id != null ? Number(held.entity_id) : null;
299
496
  if (entity === null)
300
497
  entity = Number(database
@@ -306,6 +503,19 @@ export const crmCopiesOver = (context, people) => {
306
503
  database
307
504
  .prepare("UPDATE organizations SET name = ?, updated_at = ? WHERE id = ? AND name = ?")
308
505
  .run(name, at, entity, typeof before === "string" ? before : name);
506
+ // The owner's mark (`own_by: "owner"`) is his: the CRM sets and clears only its own.
507
+ if (organization.own)
508
+ database
509
+ .prepare("UPDATE organizations SET metadata = json_set(coalesce(metadata, '{}'), '$.own', json('true'), " +
510
+ "'$.own_by', 'crm'), updated_at = ? WHERE id = ? " +
511
+ "AND json_extract(coalesce(metadata, '{}'), '$.own_by') IS NOT 'owner' " +
512
+ "AND json_extract(coalesce(metadata, '{}'), '$.own') IS NOT 1")
513
+ .run(at, entity);
514
+ else if (previous.own === true)
515
+ database
516
+ .prepare("UPDATE organizations SET metadata = json_remove(metadata, '$.own', '$.own_by'), updated_at = ? " +
517
+ "WHERE id = ? AND json_extract(metadata, '$.own_by') IS 'crm'")
518
+ .run(at, entity);
309
519
  if (held)
310
520
  database
311
521
  .prepare("UPDATE records SET fields = ?, fingerprint = ?, entity_type = 'organization', entity_id = ?, " +
@@ -320,6 +530,106 @@ export const crmCopiesOver = (context, people) => {
320
530
  }
321
531
  return { saved: organizations.length, skipped: [] };
322
532
  });
533
+ const ownCompanies = (accountId) => database
534
+ .prepare("SELECT r.external_id FROM records r JOIN organizations o ON o.id = r.entity_id WHERE r.account_id = ? " +
535
+ "AND r.type = 'organization' AND r.entity_type = 'organization' AND r.deleted_at IS NULL " +
536
+ "AND json_extract(o.metadata, '$.own') = 1 ORDER BY o.id")
537
+ .all(accountId)
538
+ .map((row) => String(row.external_id));
539
+ /**
540
+ * Every stored company of the account against `crm.<provider>:<account>.company-types`, after the run read them all:
541
+ * a customer listed before the own company, or a setting made after the first sync, applies on the next sync.
542
+ */
543
+ const saveCompanyTypes = (key) => write(database, () => {
544
+ const accountId = account(key);
545
+ const tally = tallied();
546
+ const types = crmCompanyTypes(database, key);
547
+ const own = ownCompanies(accountId);
548
+ const mine = own.flatMap((id) => refOf(key, accountId, { type: "company", id }) ?? []);
549
+ const companies = database
550
+ .prepare("SELECT external_id, entity_id, json_extract(fields, '$.type') AS type FROM records WHERE account_id = ? " +
551
+ "AND type = 'organization' AND entity_type = 'organization' AND deleted_at IS NULL " +
552
+ "AND json_type(fields, '$.type') IS NOT NULL")
553
+ .all(accountId);
554
+ for (const company of companies) {
555
+ if (own.includes(String(company.external_id)))
556
+ continue;
557
+ const ref = `organization:${company.entity_id}`;
558
+ const meaning = company.type == null ? undefined : types[String(company.type)];
559
+ const relationships = mine.flatMap((other) => {
560
+ if (meaning === "customer-of")
561
+ return [{ from: ref, to: other, kind: "customer-of" }];
562
+ if (meaning === "supplier")
563
+ return [{ from: other, to: ref, kind: "customer-of" }];
564
+ if (meaning === "partner-of")
565
+ return [{ from: ref, to: other, kind: "partner-of" }];
566
+ return [];
567
+ });
568
+ const scope = { from: [ref], to: [ref], kinds: ["customer-of", "partner-of"] };
569
+ const done = syncReportedIn(context, key, relationships, scope, { source: SOURCE });
570
+ tally.skippedOwnerRejected += done.skippedOwnerRejected;
571
+ for (const one of done.issues)
572
+ tally.issues.push({ externalId: String(company.external_id), reason: one.reason, message: one.message });
573
+ }
574
+ return { saved: companies.length, skipped: [], ...relationNotes(tally) };
575
+ });
576
+ const saveUsers = (key, users, departments) => {
577
+ const accountId = account(key);
578
+ const tally = tallied();
579
+ const pending = pendingBook(accountId);
580
+ for (const user of users)
581
+ nameUnnamed(key, user.externalId, "user", textOf(user.name, 200));
582
+ const active = new Map(users.filter((user) => user.active !== false).map((user) => [user.externalId, user]));
583
+ const own = ownCompanies(accountId);
584
+ if (own.length === 0)
585
+ tally.issues.push({
586
+ reason: "crm.own-unknown",
587
+ message: "no own company of this account is stored, so no user is its employee yet",
588
+ });
589
+ const byId = new Map((departments ?? []).map((department) => [department.externalId, department]));
590
+ for (const user of users) {
591
+ const self = { type: "user", id: user.externalId };
592
+ const ref = refOf(key, accountId, self);
593
+ if (ref === null)
594
+ continue;
595
+ const working = active.has(user.externalId);
596
+ const position = textOf(user.position, 200);
597
+ if (own.length) {
598
+ const wanted = working
599
+ ? own.map((id) => ({
600
+ from: self,
601
+ to: { type: "company", id },
602
+ kind: "member-of",
603
+ role: "employee",
604
+ ...(position ? { metadata: { position } } : {}),
605
+ }))
606
+ : [];
607
+ const scope = { from: [ref], kinds: ["member-of"], roles: ["employee"] };
608
+ reportFrom(key, accountId, self, wanted, scope, tally, pending);
609
+ }
610
+ // Without departments, or without a user's own list of them, who it reports to is unknown, not none.
611
+ if (departments === undefined || user.departments === undefined)
612
+ continue;
613
+ const heads = new Set();
614
+ for (const id of working ? user.departments : []) {
615
+ const department = byId.get(id);
616
+ const head = department?.head === user.externalId ? byId.get(department.parent ?? "")?.head : department?.head;
617
+ if (head && head !== user.externalId && active.has(head))
618
+ heads.add(head);
619
+ }
620
+ const lines = [...heads].map((head) => ({
621
+ from: self,
622
+ to: { type: "user", id: head },
623
+ kind: "reports-to",
624
+ role: null,
625
+ metadata: { derived: "department-head" },
626
+ }));
627
+ const owner = { type: "user", id: `${user.externalId}/reports-to` };
628
+ reportFrom(key, accountId, owner, lines, { from: [ref], kinds: ["reports-to"] }, tally, pending);
629
+ }
630
+ tally.droppedPending += pending.flush();
631
+ return { saved: users.length, skipped: [], ...relationNotes(tally) };
632
+ };
323
633
  const stored = (key, kind) => {
324
634
  const accountId = findAccountPk(context, key);
325
635
  if (accountId === undefined || kind === "person")
@@ -333,17 +643,24 @@ export const crmCopiesOver = (context, people) => {
333
643
  .prepare(`SELECT id, external_id, updated_at FROM ${TABLES[kind]} WHERE account_id = ? AND deleted_at IS NULL`)
334
644
  .all(accountId);
335
645
  };
336
- const markDeleted = (kind, ids) => {
646
+ const markDeleted = (key, kind, rows) => {
337
647
  const table = kind === "organization" ? "records" : TABLES[kind];
338
648
  const mark = database.prepare(`UPDATE ${table} SET deleted_at = ? WHERE id = ?`);
339
649
  const at = now();
340
- for (const id of ids)
341
- mark.run(at, id);
342
- return ids.length;
650
+ for (const row of rows)
651
+ mark.run(at, Number(row.id));
652
+ const accountId = findAccountPk(context, key);
653
+ if (isItemKind(kind) && accountId !== undefined && rows.length) {
654
+ const pending = pendingBook(accountId);
655
+ for (const row of rows)
656
+ pending.forget(`${kind}:${row.external_id}`);
657
+ pending.flush();
658
+ }
659
+ return rows.length;
343
660
  };
344
661
  return {
345
662
  savePipelines: async (key, kind, pipelines) => savePipelines(key, kind, pipelines),
346
- saveItems: async (key, kind, items) => saveItems(key, kind, items),
663
+ saveItems: async (key, kind, items, options) => saveItems(key, kind, items, options?.users !== false),
347
664
  savePeople: async (key, contacts) => {
348
665
  await people.savePeople(key, contacts.map((contact) => ({
349
666
  id: crmIdentityId(key, contact.externalId),
@@ -351,23 +668,67 @@ export const crmCopiesOver = (context, people) => {
351
668
  email: textOf(contact.email, 320)?.toLowerCase() ?? null,
352
669
  phone: textOf(contact.phone, 64),
353
670
  })));
354
- return { saved: contacts.length, skipped: [] };
671
+ return write(database, () => {
672
+ const accountId = account(key);
673
+ const tally = tallied();
674
+ const pending = pendingBook(accountId);
675
+ for (const contact of contacts) {
676
+ const person = nameUnnamed(key, contact.externalId, "contact", textOf(contact.name, 200));
677
+ const email = textOf(contact.email, 320)?.toLowerCase();
678
+ const sharing = email ? peopleSharing(key, contact.externalId, email) : 0;
679
+ if (sharing > 1)
680
+ tally.issues.push({
681
+ externalId: contact.externalId,
682
+ reason: "crm.email-ambiguous",
683
+ message: `contact ${contact.externalId}'s email belongs to ${sharing} people: say which one it is`,
684
+ });
685
+ if (person === null || contact.organizations === undefined)
686
+ continue;
687
+ const self = { type: "contact", id: contact.externalId };
688
+ const position = textOf(contact.position, 200);
689
+ const wanted = contact.organizations.map((company) => {
690
+ const sourceRole = textOf(company.sourceRole, 200);
691
+ const metadata = {
692
+ ...(position ? { position } : {}),
693
+ ...(sourceRole ? { source_role: sourceRole } : {}),
694
+ ...(company.primary ? { primary: true } : {}),
695
+ };
696
+ return {
697
+ from: self,
698
+ to: { type: "company", id: company.externalId },
699
+ kind: "member-of",
700
+ role: "contact",
701
+ ...(Object.keys(metadata).length ? { metadata } : {}),
702
+ };
703
+ });
704
+ const scope = { from: [`person:${person}`], kinds: ["member-of"], roles: ["contact"] };
705
+ reportFrom(key, accountId, self, wanted, scope, tally, pending);
706
+ }
707
+ tally.droppedPending += pending.flush();
708
+ return { saved: contacts.length, skipped: [], ...relationNotes(tally) };
709
+ });
710
+ },
711
+ retryPending: async (key) => retryPending(key),
712
+ saveCompanyTypes: async (key) => saveCompanyTypes(key),
713
+ saveUsers: async (key, users, departments) => {
714
+ await people.savePeople(key, users.map((user) => ({
715
+ id: crmIdentityId(key, user.externalId, "user"),
716
+ name: textOf(user.name, 200),
717
+ email: textOf(user.email, 320)?.toLowerCase() ?? null,
718
+ })));
719
+ return write(database, () => saveUsers(key, users, departments));
355
720
  },
356
721
  saveOrganizations: async (key, organizations) => saveOrganizations(key, organizations),
357
722
  saveFields: async (key, kind, fields) => saveFields(key, kind, fields),
358
723
  fields: async (key, kind) => fieldsOf(key, kind),
359
724
  remove: async (key, kind, externalIds) => write(database, () => {
360
725
  const gone = new Set(externalIds);
361
- return markDeleted(kind, stored(key, kind)
362
- .filter((row) => gone.has(String(row.external_id)))
363
- .map((row) => Number(row.id)));
726
+ return markDeleted(key, kind, stored(key, kind).filter((row) => gone.has(String(row.external_id))));
364
727
  }),
365
728
  removeUnlisted: async (key, kind, listed, before, { dryRun } = {}) => write(database, () => {
366
729
  const held = new Set(listed);
367
- const gone = stored(key, kind)
368
- .filter((row) => !held.has(String(row.external_id)) && Number(row.updated_at) < before)
369
- .map((row) => Number(row.id));
370
- return dryRun ? gone.length : markDeleted(kind, gone);
730
+ const gone = stored(key, kind).filter((row) => !held.has(String(row.external_id)) && Number(row.updated_at) < before);
731
+ return dryRun ? gone.length : markDeleted(key, kind, gone);
371
732
  }),
372
733
  count: async (key, kind) => kind === "person"
373
734
  ? Number(database
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, dealLine, STAGE_OUTCOMES, } from "../../domain/deals.js";
3
3
  import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
4
+ import { notOverriddenSql } from "../../domain/relations.js";
4
5
  import { fold } from "../normalize.js";
5
6
  import { proposedBySql } from "./actors.js";
6
7
  import { isoDate, oneOf, refuse, reviewedRowsOver, text } from "./finance.js";
@@ -45,7 +46,7 @@ export const dealOperationsOver = (context) => {
45
46
  const today = () => new Date(now()).toISOString().slice(0, 10);
46
47
  const peopleOf = (kind, id) => database
47
48
  .prepare(`SELECT to_id, role FROM links WHERE from_type = ? AND from_id = ? AND kind = ${linkKind("related-to")} ` +
48
- "AND to_type = 'person' AND to_id IS NOT NULL ORDER BY id")
49
+ `AND to_type = 'person' AND to_id IS NOT NULL AND deleted_at IS NULL AND ${notOverriddenSql("links")} ORDER BY id`)
49
50
  .all(kind, id)
50
51
  .map((row) => ({ ...partyOf("person", row.to_id), role: row.role }));
51
52
  const itemOf = (kind) => (row) => {
@@ -334,7 +335,7 @@ export const dealOperationsOver = (context) => {
334
335
  "close_date, closed_date, author_type, author_id, model, source, metadata, created_at, updated_at) " +
335
336
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
336
337
  .get(title, organization?.id ?? null, input.project === undefined ? null : projectId(database, input.project), Number(stage.id), status, currency, amount, closeDate, status === "open" ? null : today(), actor.type, actor.id, model, source, reason === null ? null : JSON.stringify({ reason }), at, at)?.id);
337
- const link = database.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, source, confirmed, created_at, author, " +
338
+ const link = database.prepare("INSERT OR IGNORE INTO links (from_type, from_id, to_type, to_id, kind, role, source, confirmed, created_at, author, " +
338
339
  `updated_at) VALUES (?, ?, 'person', ?, ${linkKind("related-to")}, ?, ?, 1, ?, ?, ?)`);
339
340
  for (const person of persons)
340
341
  link.run(kind, made, person.id, person.role, owner ? "owner" : "suggested", at, owner ? "owner" : "agent", at);
@@ -1,5 +1,6 @@
1
1
  import { type FinanceReview, type InvoiceDirection, type InvoiceStatus, type MoneyDirection } from "../../domain/finance.js";
2
2
  import { type Money } from "../../domain/money.js";
3
+ import { RECORD_TYPES } from "../../domain/record-types.js";
3
4
  import { type Decider } from "../decisions.js";
4
5
  import { type Actor, type ProposedByFilter } from "./actors.js";
5
6
  import { type Author } from "./memories.js";
@@ -207,6 +208,12 @@ export interface FinanceStore {
207
208
  }>;
208
209
  }
209
210
  type Row = Record<string, unknown>;
211
+ /** The types `decide` settles money for; other proposal types get their own route. */
212
+ declare const FINANCE_TYPES: readonly ["invoice", "payment"];
213
+ type FinanceType = (typeof FINANCE_TYPES)[number];
214
+ type FinanceTable = (typeof RECORD_TYPES)[FinanceType]["table"];
215
+ /** One article, for the first prefix only: `an invoice: or payment:`. */
216
+ export declare const prefixesText: (types: readonly string[]) => string;
210
217
  export declare const refuse: (message: string, reason: string, code?: "validation_error" | "permission_error") => never;
211
218
  export declare const oneOf: <T extends string>(value: unknown, allowed: readonly T[], what: string) => T;
212
219
  export declare const text: (value: unknown, what: string, limit: number) => string | null;
@@ -242,7 +249,7 @@ export declare const reviewedRowsOver: (context: StoreContext) => {
242
249
  evidence: string[];
243
250
  }>) => void;
244
251
  ownerOnly: (by: Author, what: string) => void;
245
- keepDecision: (table: "invoices" | "payments" | "orders" | "opportunities", id: number, by: Decider, reason?: string) => void;
252
+ keepDecision: (table: FinanceTable | "orders", id: number, by: Decider, reason?: string) => void;
246
253
  };
247
254
  type FinanceOperations = {
248
255
  [K in keyof FinanceStore]: FinanceStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
@@ -1,11 +1,18 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, invoiceTitle, MONEY_DIRECTIONS, paymentEntryTitle, settledStatus, } from "../../domain/finance.js";
3
3
  import { currencyOf, formatDecimal, lineUnits, minorUnits, moneyLabel, moneyOf, quantityOf, scaleOf, } from "../../domain/money.js";
4
+ import { RECORD_TYPES } from "../../domain/record-types.js";
4
5
  import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
5
6
  import { proposedBySql, proposerOf } from "./actors.js";
6
7
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf, subjectOf, } from "./memories.js";
7
8
  import { requiredThing } from "./notes.js";
8
9
  import { write } from "./transaction.js";
10
+ /** The types `decide` settles money for; other proposal types get their own route. */
11
+ const FINANCE_TYPES = ["invoice", "payment"];
12
+ const isFinanceType = (type) => FINANCE_TYPES.includes(type);
13
+ const article = (word) => (/^[aeiou]/.test(word) ? "an" : "a");
14
+ /** One article, for the first prefix only: `an invoice: or payment:`. */
15
+ export const prefixesText = (types) => `${article(types[0] ?? "")} ${types.map((type) => `${type}:`).join(" or ")}`;
9
16
  export const refuse = (message, reason, code = "validation_error") => {
10
17
  throw new CliError(code, message, { reason });
11
18
  };
@@ -287,10 +294,10 @@ export const financeOperationsOver = (context) => {
287
294
  };
288
295
  const decide = (reference, by, reason, confirm) => {
289
296
  const thing = requiredThing(database, reference, "the proposal");
290
- if (thing.type !== "invoice" && thing.type !== "payment")
291
- return refuse(`${reference} is not an invoice: or payment:`, "finance.ref");
297
+ if (!isFinanceType(thing.type))
298
+ return refuse(`${reference} is not ${prefixesText(FINANCE_TYPES)}`, "finance.ref");
292
299
  const type = thing.type;
293
- const table = type === "invoice" ? "invoices" : "payments";
300
+ const table = RECORD_TYPES[type].table;
294
301
  const row = rowOf(reference, type);
295
302
  const ref = `${type}:${row.id}`;
296
303
  assertMayDecide({ id: ref, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly: true }, by, context.decisions);