@wirecat/cli-core 0.605.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 (83) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/dist/cli/index.d.ts +1 -1
  3. package/dist/cli/index.js +1 -0
  4. package/dist/cli/store-settings.js +38 -4
  5. package/dist/crm/cli/index.js +3 -1
  6. package/dist/crm/index.d.ts +2 -2
  7. package/dist/crm/index.js +1 -1
  8. package/dist/crm/source.d.ts +35 -5
  9. package/dist/crm/sync.d.ts +15 -7
  10. package/dist/crm/sync.js +169 -11
  11. package/dist/domain/crm.d.ts +41 -2
  12. package/dist/domain/deals.d.ts +5 -2
  13. package/dist/domain/deals.js +5 -2
  14. package/dist/domain/relations.d.ts +125 -0
  15. package/dist/domain/relations.js +107 -0
  16. package/dist/entities/deal.d.ts +2 -2
  17. package/dist/entities/deal.js +2 -1
  18. package/dist/entities/index.d.ts +17 -13
  19. package/dist/entities/relationship.d.ts +8 -2
  20. package/dist/entities/relationship.js +8 -2
  21. package/dist/entities/task-results.d.ts +10 -10
  22. package/dist/errors/reasons.js +12 -0
  23. package/dist/index.d.ts +2 -1
  24. package/dist/index.js +1 -0
  25. package/dist/mail/cli/review.js +20 -6
  26. package/dist/mail/index.d.ts +1 -1
  27. package/dist/mail/marks.d.ts +10 -5
  28. package/dist/mail/marks.js +16 -8
  29. package/dist/mail/review.d.ts +5 -0
  30. package/dist/services/link-scorers/scan.js +2 -1
  31. package/dist/services/link-scorers/shared.js +2 -1
  32. package/dist/services/project-status/index.js +2 -1
  33. package/dist/services/stored-project-gathering.js +4 -3
  34. package/dist/store/exports.d.ts +1 -0
  35. package/dist/store/exports.js +1 -0
  36. package/dist/store/index.d.ts +6 -1
  37. package/dist/store/index.js +1 -0
  38. package/dist/store/project-transfer/request.d.ts +4 -1
  39. package/dist/store/project-transfer/schema.d.ts +9 -2
  40. package/dist/store/project-transfer/schema.js +4 -0
  41. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  42. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  43. package/dist/store/sqlite/crm-settings.js +80 -0
  44. package/dist/store/sqlite/crm.d.ts +42 -2
  45. package/dist/store/sqlite/crm.js +397 -36
  46. package/dist/store/sqlite/deals.js +3 -2
  47. package/dist/store/sqlite/involvement-queue.js +4 -3
  48. package/dist/store/sqlite/knowledge.d.ts +7 -3
  49. package/dist/store/sqlite/knowledge.js +43 -31
  50. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  51. package/dist/store/sqlite/link-kinds.js +4 -2
  52. package/dist/store/sqlite/manifest.js +5 -0
  53. package/dist/store/sqlite/memories.d.ts +1 -1
  54. package/dist/store/sqlite/memories.js +33 -7
  55. package/dist/store/sqlite/migrations.generated.js +31 -0
  56. package/dist/store/sqlite/notes.d.ts +3 -2
  57. package/dist/store/sqlite/notes.js +23 -6
  58. package/dist/store/sqlite/organizations.d.ts +8 -0
  59. package/dist/store/sqlite/organizations.js +14 -0
  60. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  61. package/dist/store/sqlite/person-preparation.js +3 -2
  62. package/dist/store/sqlite/project-transfer/records.js +14 -3
  63. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  64. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  65. package/dist/store/sqlite/relation-list.d.ts +43 -0
  66. package/dist/store/sqlite/relation-list.js +133 -0
  67. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  68. package/dist/store/sqlite/relation-proposals.js +134 -10
  69. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  70. package/dist/store/sqlite/relation-reads.js +7 -0
  71. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  72. package/dist/store/sqlite/relation-roles.js +91 -0
  73. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  74. package/dist/store/sqlite/reported-relations.js +132 -0
  75. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  76. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  77. package/dist/store/sqlite/schema/links.d.ts +360 -0
  78. package/dist/store/sqlite/schema/links.js +32 -0
  79. package/dist/store/sqlite/schema.d.ts +2 -296
  80. package/dist/store/sqlite/schema.js +2 -24
  81. package/dist/store/store.d.ts +3 -0
  82. package/dist/store/store.js +5 -0
  83. package/package.json +3 -3
@@ -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,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { usableLinkSql } from "../../domain/relations.js";
2
3
  /** One SELECT per way of taking part: the subject's kind, the column that holds its id, and the query. */
3
4
  const ARMS = [
4
5
  [
@@ -79,8 +80,8 @@ const ARMS = [
79
80
  const linkArm = (linkFrom, linkTo) => `
80
81
  SELECT CASE WHEN l.to_type='person' THEN l.to_id ELSE il.person_id END AS person_id, CASE WHEN l.to_type='identity' THEN l.to_id END AS identity_id, l.from_type AS subject_type, l.from_id AS subject_id, coalesce(l.role,'linked') AS role, l.created_at AS occurred_at,
81
82
  coalesce(c.scope,a.scope,p.scope,'personal') AS scope, coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id) AS account_id, p.id AS project_id
82
- FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed FROM links WHERE ${linkFrom}
83
- UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
83
+ FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE ${linkFrom}
84
+ UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
84
85
  LEFT JOIN identity_links il ON l.to_type='identity' AND il.identity_id=l.to_id
85
86
  LEFT JOIN messages m ON l.from_type='message' AND m.id=l.from_id
86
87
  LEFT JOIN chats c ON c.id=CASE WHEN l.from_type='chat' THEN l.from_id ELSE m.chat_id END
@@ -90,7 +91,7 @@ const linkArm = (linkFrom, linkTo) => `
90
91
  LEFT JOIN tasks t ON l.from_type='task' AND t.id=l.from_id
91
92
  LEFT JOIN projects p ON p.id=CASE WHEN l.from_type='project' THEN l.from_id ELSE t.project_id END
92
93
  LEFT JOIN accounts a ON a.id=coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id)
93
- WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND l.confirmed=1 AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
94
+ WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND ${usableLinkSql("l")} AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
94
95
  `;
95
96
  /**
96
97
  * Every way of taking part, or only the ones about `subject`, each filtered by its own key so SQLite reads
@@ -8,6 +8,7 @@ import type { StoreContext } from "./open.js";
8
8
  import { type OrganizationsStore } from "./organizations.js";
9
9
  import type { ProposedAction } from "./proposed-actions.js";
10
10
  import { type KnowledgeRelation, type LinkDecision, type RelateInput, type RelationUpdate, type Scored } from "./relation-proposals.js";
11
+ import { type RelationReads } from "./relation-reads.js";
11
12
  import type { TagCreationOptions } from "./tag-creation.js";
12
13
  import { type Label, type TagKind, type TagRow } from "./tags.js";
13
14
  import { type ThingState } from "./things.js";
@@ -101,7 +102,7 @@ export interface Reminder {
101
102
  receipt: string | null;
102
103
  }
103
104
  export type LabelledType = "note" | "document" | "person" | "organization" | "project" | "task" | "meeting" | "folder";
104
- export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, OrganizationsStore {
105
+ export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, OrganizationsStore, RelationReads {
105
106
  taskIds(key: AccountKey, options?: {
106
107
  state?: "open" | "done" | "dismissed";
107
108
  limit?: number;
@@ -214,6 +215,9 @@ export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, O
214
215
  by: Exclude<Author, "owner">;
215
216
  reason?: string;
216
217
  }): Promise<ProposedAction>;
218
+ /** Ends it at `at` (UTC ms) without removing it; an agent's end is a `relationship_update` proposal. */
219
+ endRelation(key: KnowledgeScope, id: string, at: number, by: "owner"): Promise<KnowledgeRelation>;
220
+ endRelation(key: KnowledgeScope, id: string, at: number, by: Exclude<Author, "owner">): Promise<ProposedAction>;
217
221
  /** Decides a `relationship_update` proposal; a confirmed one changes the relationship in the same transaction. */
218
222
  decideRelationUpdate(id: string, decision: LinkDecision): Promise<{
219
223
  proposal: ProposedAction;
@@ -228,8 +232,8 @@ export interface KnowledgeStore extends VocabularyStore, MeetingProjectsStore, O
228
232
  decideSuggestedLink(id: string, decision: LinkDecision): Promise<Link | null>;
229
233
  relations(key: KnowledgeScope, reference?: string): Promise<KnowledgeRelation[]>;
230
234
  /**
231
- * Removing an unconfirmed relationship rejects it, so `by` must be allowed to decide it. Removing a link to a
232
- * project, or rejecting any suggestion, leaves a rejected `relationship` proposal so a scan never proposes it again.
235
+ * Removing an unconfirmed relationship rejects it, so `by` must be allowed to decide it. Every removal leaves a
236
+ * rejected `relationship` proposal, so neither a scan nor a source's sync brings the pair back.
233
237
  */
234
238
  removeRelation(key: KnowledgeScope, id: string, by: Decider): Promise<{
235
239
  id: string;