@wirecat/cli-core 0.605.0 → 0.607.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 (260) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +4 -1
  12. package/dist/cli/index.js +4 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/cli/store-settings.js +38 -4
  17. package/dist/crm/cli/csv.d.ts +23 -0
  18. package/dist/crm/cli/csv.js +135 -0
  19. package/dist/crm/cli/index.d.ts +1 -1
  20. package/dist/crm/cli/index.js +36 -22
  21. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  22. package/dist/crm/cli/pipeline-view.js +36 -0
  23. package/dist/crm/index.d.ts +2 -2
  24. package/dist/crm/index.js +1 -1
  25. package/dist/crm/source.d.ts +35 -5
  26. package/dist/crm/sync.d.ts +15 -7
  27. package/dist/crm/sync.js +169 -11
  28. package/dist/crm/writes.d.ts +6 -4
  29. package/dist/crm/writes.js +17 -13
  30. package/dist/documents.d.ts +2 -0
  31. package/dist/documents.js +2 -0
  32. package/dist/domain/business.d.ts +79 -0
  33. package/dist/domain/business.js +42 -0
  34. package/dist/domain/crm.d.ts +41 -2
  35. package/dist/domain/deals.d.ts +5 -2
  36. package/dist/domain/deals.js +5 -2
  37. package/dist/domain/finance.d.ts +2 -0
  38. package/dist/domain/finance.js +2 -2
  39. package/dist/domain/google-documents.d.ts +2 -0
  40. package/dist/domain/google-documents.js +3 -1
  41. package/dist/domain/money.d.ts +2 -0
  42. package/dist/domain/money.js +11 -3
  43. package/dist/domain/providers.d.ts +36 -1
  44. package/dist/domain/providers.js +69 -7
  45. package/dist/domain/record-fields.d.ts +42 -0
  46. package/dist/domain/record-fields.js +122 -0
  47. package/dist/domain/record-types.d.ts +489 -16
  48. package/dist/domain/record-types.js +374 -7
  49. package/dist/domain/records.d.ts +96 -5
  50. package/dist/domain/records.js +178 -32
  51. package/dist/domain/ref-summaries.js +5 -0
  52. package/dist/domain/references.d.ts +1 -1
  53. package/dist/domain/references.js +5 -0
  54. package/dist/domain/relations.d.ts +125 -0
  55. package/dist/domain/relations.js +107 -0
  56. package/dist/domain/vcard.d.ts +25 -0
  57. package/dist/domain/vcard.js +267 -0
  58. package/dist/entities/deal.d.ts +16 -2
  59. package/dist/entities/deal.js +5 -1
  60. package/dist/entities/index.d.ts +29 -13
  61. package/dist/entities/relationship.d.ts +8 -2
  62. package/dist/entities/relationship.js +8 -2
  63. package/dist/entities/task-results.d.ts +10 -10
  64. package/dist/errors/reasons.js +73 -2
  65. package/dist/fetch/addresses.d.ts +5 -0
  66. package/dist/fetch/addresses.js +76 -0
  67. package/dist/fetch/page.d.ts +64 -0
  68. package/dist/fetch/page.js +256 -0
  69. package/dist/index.d.ts +7 -4
  70. package/dist/index.js +6 -3
  71. package/dist/mail/cli/review.js +20 -6
  72. package/dist/mail/index.d.ts +1 -1
  73. package/dist/mail/marks.d.ts +10 -5
  74. package/dist/mail/marks.js +16 -8
  75. package/dist/mail/review.d.ts +5 -0
  76. package/dist/meetings/calendar-text.d.ts +1 -1
  77. package/dist/meetings/calendar-text.js +4 -0
  78. package/dist/meetings/event-store.d.ts +2 -2
  79. package/dist/search/account-list.d.ts +4 -0
  80. package/dist/search/account-list.js +19 -8
  81. package/dist/search/query.js +2 -2
  82. package/dist/services/events-search.js +2 -2
  83. package/dist/services/index.d.ts +1 -1
  84. package/dist/services/index.js +1 -1
  85. package/dist/services/ingest.d.ts +56 -8
  86. package/dist/services/ingest.js +95 -61
  87. package/dist/services/link-scorers/scan.js +2 -1
  88. package/dist/services/link-scorers/shared.js +2 -1
  89. package/dist/services/messages-search.js +3 -2
  90. package/dist/services/metadata.d.ts +1 -1
  91. package/dist/services/notes-search.js +1 -0
  92. package/dist/services/project-status/index.js +2 -1
  93. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  94. package/dist/services/proposals/kinds/contracts.js +9 -0
  95. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  96. package/dist/services/proposals/kinds/finance.js +14 -35
  97. package/dist/services/proposals/kinds/orders.js +7 -30
  98. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  99. package/dist/services/proposals/kinds/shared.js +34 -0
  100. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  101. package/dist/services/proposals/kinds/source-review.js +45 -0
  102. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  103. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  104. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  105. package/dist/services/proposals/kinds/transactions.js +10 -0
  106. package/dist/services/proposals/registry.js +9 -0
  107. package/dist/services/search-all-meetings.js +2 -2
  108. package/dist/services/search-all.js +4 -3
  109. package/dist/services/search-kind.js +3 -3
  110. package/dist/services/stored-project-gathering.js +4 -3
  111. package/dist/store/decisions.js +5 -1
  112. package/dist/store/exports.d.ts +1 -0
  113. package/dist/store/exports.js +1 -0
  114. package/dist/store/index.d.ts +20 -4
  115. package/dist/store/index.js +4 -0
  116. package/dist/store/people.js +1 -1
  117. package/dist/store/project-transfer/request.d.ts +4 -1
  118. package/dist/store/project-transfer/schema.d.ts +9 -2
  119. package/dist/store/project-transfer/schema.js +4 -0
  120. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  121. package/dist/store/source-review.d.ts +64 -0
  122. package/dist/store/source-review.js +7 -0
  123. package/dist/store/sqlite/accounts.d.ts +1 -1
  124. package/dist/store/sqlite/accounts.js +24 -1
  125. package/dist/store/sqlite/added-sources.d.ts +82 -0
  126. package/dist/store/sqlite/added-sources.js +237 -0
  127. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  128. package/dist/store/sqlite/business-contracts.js +182 -0
  129. package/dist/store/sqlite/calendar-events.js +7 -3
  130. package/dist/store/sqlite/calendar-forget.js +3 -0
  131. package/dist/store/sqlite/calendar.d.ts +21 -1
  132. package/dist/store/sqlite/calendar.js +27 -7
  133. package/dist/store/sqlite/chat-rekey.js +7 -0
  134. package/dist/store/sqlite/chats.d.ts +3 -1
  135. package/dist/store/sqlite/chats.js +15 -1
  136. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  137. package/dist/store/sqlite/crm-rows.js +195 -0
  138. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  139. package/dist/store/sqlite/crm-settings.js +80 -0
  140. package/dist/store/sqlite/crm.d.ts +42 -11
  141. package/dist/store/sqlite/crm.js +402 -196
  142. package/dist/store/sqlite/deals.d.ts +4 -8
  143. package/dist/store/sqlite/deals.js +8 -5
  144. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  145. package/dist/store/sqlite/emails.js +2 -0
  146. package/dist/store/sqlite/entity-types.d.ts +14 -9
  147. package/dist/store/sqlite/entity-types.js +4 -10
  148. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  149. package/dist/store/sqlite/evidence-signature.js +349 -0
  150. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  151. package/dist/store/sqlite/evidence-sources.js +7 -3
  152. package/dist/store/sqlite/facts.d.ts +7 -2
  153. package/dist/store/sqlite/facts.js +21 -5
  154. package/dist/store/sqlite/finance.d.ts +18 -105
  155. package/dist/store/sqlite/finance.js +100 -219
  156. package/dist/store/sqlite/involvement-queue.js +4 -3
  157. package/dist/store/sqlite/knowledge.d.ts +14 -4
  158. package/dist/store/sqlite/knowledge.js +108 -102
  159. package/dist/store/sqlite/labelled.d.ts +3 -0
  160. package/dist/store/sqlite/labelled.js +11 -0
  161. package/dist/store/sqlite/link-kinds.d.ts +4 -3
  162. package/dist/store/sqlite/link-kinds.js +6 -2
  163. package/dist/store/sqlite/manifest.js +7 -0
  164. package/dist/store/sqlite/memories.d.ts +24 -10
  165. package/dist/store/sqlite/memories.js +73 -19
  166. package/dist/store/sqlite/messages.js +2 -0
  167. package/dist/store/sqlite/migrations.generated.js +134 -0
  168. package/dist/store/sqlite/money-lines.d.ts +48 -0
  169. package/dist/store/sqlite/money-lines.js +76 -0
  170. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  171. package/dist/store/sqlite/money-transactions.js +295 -0
  172. package/dist/store/sqlite/notes.d.ts +14 -4
  173. package/dist/store/sqlite/notes.js +43 -31
  174. package/dist/store/sqlite/orders.d.ts +36 -6
  175. package/dist/store/sqlite/orders.js +126 -46
  176. package/dist/store/sqlite/organizations.d.ts +8 -0
  177. package/dist/store/sqlite/organizations.js +14 -0
  178. package/dist/store/sqlite/payment-facts.js +1 -1
  179. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  180. package/dist/store/sqlite/person-preparation.js +3 -2
  181. package/dist/store/sqlite/private-people.js +2 -0
  182. package/dist/store/sqlite/products.d.ts +78 -0
  183. package/dist/store/sqlite/products.js +131 -0
  184. package/dist/store/sqlite/project-transfer/records.js +39 -3
  185. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  186. package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
  187. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  188. package/dist/store/sqlite/proposed-actions.js +24 -7
  189. package/dist/store/sqlite/providers.d.ts +0 -4
  190. package/dist/store/sqlite/providers.js +20 -2
  191. package/dist/store/sqlite/record-matching.d.ts +80 -0
  192. package/dist/store/sqlite/record-matching.js +264 -0
  193. package/dist/store/sqlite/record-projection.d.ts +89 -0
  194. package/dist/store/sqlite/record-projection.js +50 -0
  195. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  196. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  197. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  198. package/dist/store/sqlite/record-projectors-money.js +214 -0
  199. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  200. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  201. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  202. package/dist/store/sqlite/record-projectors.js +7 -67
  203. package/dist/store/sqlite/record-relations.d.ts +24 -0
  204. package/dist/store/sqlite/record-relations.js +92 -0
  205. package/dist/store/sqlite/record-remap.d.ts +12 -0
  206. package/dist/store/sqlite/record-remap.js +92 -0
  207. package/dist/store/sqlite/record-run.d.ts +71 -0
  208. package/dist/store/sqlite/record-run.js +179 -0
  209. package/dist/store/sqlite/record-settling.d.ts +9 -0
  210. package/dist/store/sqlite/record-settling.js +74 -0
  211. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  212. package/dist/store/sqlite/record-stamps.js +30 -0
  213. package/dist/store/sqlite/record-writes.d.ts +43 -0
  214. package/dist/store/sqlite/record-writes.js +307 -0
  215. package/dist/store/sqlite/records.d.ts +52 -42
  216. package/dist/store/sqlite/records.js +123 -353
  217. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  218. package/dist/store/sqlite/ref-summaries.js +60 -8
  219. package/dist/store/sqlite/refunds.d.ts +31 -0
  220. package/dist/store/sqlite/refunds.js +112 -0
  221. package/dist/store/sqlite/relation-list.d.ts +43 -0
  222. package/dist/store/sqlite/relation-list.js +133 -0
  223. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  224. package/dist/store/sqlite/relation-proposals.js +134 -10
  225. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  226. package/dist/store/sqlite/relation-reads.js +7 -0
  227. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  228. package/dist/store/sqlite/relation-roles.js +91 -0
  229. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  230. package/dist/store/sqlite/reported-relations.js +132 -0
  231. package/dist/store/sqlite/reviewed.d.ts +109 -0
  232. package/dist/store/sqlite/reviewed.js +173 -0
  233. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  234. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  235. package/dist/store/sqlite/schema/links.d.ts +360 -0
  236. package/dist/store/sqlite/schema/links.js +32 -0
  237. package/dist/store/sqlite/schema.d.ts +2769 -306
  238. package/dist/store/sqlite/schema.js +258 -25
  239. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  240. package/dist/store/sqlite/source-review-marks.js +143 -0
  241. package/dist/store/sqlite/source-review.d.ts +54 -0
  242. package/dist/store/sqlite/source-review.js +221 -0
  243. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  244. package/dist/store/sqlite/stage-amounts.js +23 -0
  245. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  246. package/dist/store/sqlite/subscriptions.js +294 -0
  247. package/dist/store/sqlite/text-input.d.ts +3 -0
  248. package/dist/store/sqlite/text-input.js +13 -0
  249. package/dist/store/sqlite/things.js +2 -9
  250. package/dist/store/sqlite/transaction.d.ts +15 -0
  251. package/dist/store/sqlite/transaction.js +57 -0
  252. package/dist/store/sqlite/wallets.d.ts +88 -0
  253. package/dist/store/sqlite/wallets.js +143 -0
  254. package/dist/store/store-errors.d.ts +1 -0
  255. package/dist/store/store-errors.js +45 -0
  256. package/dist/store/store.d.ts +19 -1
  257. package/dist/store/store.js +35 -6
  258. package/package.json +6 -3
  259. package/schemas/examples/records-business.jsonl +11 -0
  260. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -1,41 +1,28 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { DEAL_ROLES, STAGE_OUTCOMES } from "../../domain/deals.js";
3
- import { currencyOf, minorUnits } from "../../domain/money.js";
2
+ import { isItemKind, } from "../../domain/crm.js";
3
+ import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
- import { fold } from "../normalize.js";
6
5
  import { accountPk, findAccountPk } from "./accounts.js";
7
- import { linkKind } from "./link-kinds.js";
8
- import { authorActor } from "./memories.js";
6
+ import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
7
+ import { crmCompanyTypes } from "./crm-settings.js";
8
+ import { syncReportedIn } from "./reported-relations.js";
9
+ import { clearState, syncStateOf, writeState } from "./sync.js";
9
10
  import { write } from "./transaction.js";
10
- const TABLES = { deal: "deals", lead: "leads" };
11
- /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
12
- const SOURCE = "crm";
13
- /**
14
- * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
15
- * `contact:` references percent-encode it, so the `/` stays one part.
16
- */
17
- export const crmIdentityId = (key, externalId, type = "contact") => `${key.account}/${type}/${externalId}`;
18
- const day = (value, what) => {
19
- if (value === undefined || value === null || value === "")
20
- return null;
21
- if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(value)))
22
- throw new CliError("validation_error", `${what} is YYYY-MM-DD, not ${JSON.stringify(value)}`);
23
- return value;
24
- };
25
- const epoch = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
26
- const textOf = (value, most) => {
27
- if (typeof value !== "string")
28
- return null;
29
- const kept = value.trim().slice(0, most);
30
- return kept || null;
31
- };
11
+ const PENDING = "crm:pending-relations";
12
+ const PENDING_DAYS = 30;
13
+ const PENDING_MOST = 5000;
14
+ export { crmIdentityId, crmRowsOver } from "./crm-rows.js";
15
+ const tallied = () => ({ issues: [], skippedOwnerRejected: 0, unlistedUsers: 0, droppedPending: 0 });
16
+ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPending }) => ({
17
+ ...(issues.length ? { issues } : {}),
18
+ ...(skippedOwnerRejected ? { skippedOwnerRejected } : {}),
19
+ ...(unlistedUsers ? { unlistedUsers } : {}),
20
+ ...(droppedPending ? { droppedPending } : {}),
21
+ });
32
22
  export const crmCopiesOver = (context, people) => {
33
23
  const { database, now } = context;
34
- const author = (key) => authorActor(context, { bot: key.provider, kind: "rule" }).actor;
24
+ const { savePipeline, saveItemRow } = crmRowsOver(context);
35
25
  const account = (key) => accountPk(context, key);
36
- const pipelineOf = (accountId, kind, externalId) => database
37
- .prepare("SELECT * FROM pipelines WHERE account_id = ? AND kind = ? AND external_id = ?")
38
- .get(accountId, kind, externalId);
39
26
  /**
40
27
  * One kind's whole list: a pipeline it lacks is marked deleted, one listed again comes back. An empty list marks
41
28
  * nothing: a sign-in that lost its CRM rights lists no pipeline at all.
@@ -43,21 +30,8 @@ export const crmCopiesOver = (context, people) => {
43
30
  const savePipelines = (key, kind, pipelines) => write(database, () => {
44
31
  const accountId = account(key);
45
32
  const at = now();
46
- for (const pipeline of pipelines) {
47
- const name = textOf(pipeline.name, 80) ?? pipeline.externalId;
48
- const held = pipelineOf(accountId, kind, pipeline.externalId);
49
- const id = held
50
- ? Number(held.id)
51
- : Number(database
52
- .prepare("INSERT INTO pipelines (account_id, external_id, kind, name, name_folded, created_at, updated_at) " +
53
- "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id")
54
- .get(accountId, pipeline.externalId, kind, name, fold(name), at, at)?.id);
55
- if (held && (held.name !== name || held.deleted_at != null))
56
- database
57
- .prepare("UPDATE pipelines SET name = ?, name_folded = ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
58
- .run(name, fold(name), at, id);
59
- saveStages(id, pipeline, at);
60
- }
33
+ for (const pipeline of pipelines)
34
+ savePipeline(accountId, kind, pipeline, at);
61
35
  if (pipelines.length === 0)
62
36
  return { saved: 0, skipped: [] };
63
37
  const listed = new Set(pipelines.map(({ externalId }) => externalId));
@@ -69,51 +43,6 @@ export const crmCopiesOver = (context, people) => {
69
43
  mark.run(at, at, Number(row.id));
70
44
  return { saved: pipelines.length, skipped: [] };
71
45
  });
72
- /**
73
- * Stage names are unique in a pipeline, but a CRM may swap two, or give two stages one name: listed stages first
74
- * take a name no stage has, then their own, and a name used twice keeps the stage's id beside it.
75
- */
76
- const saveStages = (pipelineId, pipeline, at) => {
77
- const ordered = [...pipeline.stages].sort((a, b) => a.position - b.position);
78
- const counts = new Map();
79
- for (const stage of ordered)
80
- counts.set(fold(stage.name), (counts.get(fold(stage.name)) ?? 0) + 1);
81
- const wanted = ordered.map((stage, index) => {
82
- const name = textOf(stage.name, 80) ?? stage.externalId;
83
- const folded = (counts.get(fold(stage.name)) ?? 0) > 1 ? `${fold(name)} (${stage.externalId})` : fold(name);
84
- if (!STAGE_OUTCOMES.includes(stage.outcome))
85
- throw new CliError("invalid_response", `stage ${stage.externalId} has no known outcome: ${stage.outcome}`);
86
- return { ...stage, name, folded, position: index + 1 };
87
- });
88
- const held = database.prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ?").all(pipelineId);
89
- const listed = new Set(wanted.map(({ externalId }) => externalId));
90
- const taken = new Set(wanted.map(({ folded }) => folded));
91
- const rename = database.prepare("UPDATE pipeline_stages SET name_folded = ? WHERE id = ?");
92
- const gone = database.prepare("UPDATE pipeline_stages SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL");
93
- for (const row of held) {
94
- const kept = row.external_id != null && listed.has(String(row.external_id));
95
- if (kept)
96
- rename.run(`\u0000${row.id}`, Number(row.id));
97
- else if (taken.has(String(row.name_folded)))
98
- rename.run(`${row.name_folded} (${row.external_id ?? row.id})`, Number(row.id));
99
- if (!kept)
100
- gone.run(at, Number(row.id));
101
- }
102
- const byId = new Map(held.map((row) => [String(row.external_id), row]));
103
- for (const stage of wanted) {
104
- const row = byId.get(stage.externalId);
105
- if (row)
106
- database
107
- .prepare("UPDATE pipeline_stages SET name = ?, name_folded = ?, position = ?, outcome = ?, updated_at = ?, " +
108
- "deleted_at = NULL WHERE id = ?")
109
- .run(stage.name, stage.folded, stage.position, stage.outcome, at, Number(row.id));
110
- else
111
- database
112
- .prepare("INSERT INTO pipeline_stages (pipeline_id, name, name_folded, position, outcome, external_id, created_at, " +
113
- "updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
114
- .run(pipelineId, stage.name, stage.folded, stage.position, stage.outcome, stage.externalId, at, at);
115
- }
116
- };
117
46
  // Unlike pipelines, an empty list does mark every field deleted: a CRM with no custom fields is an ordinary answer.
118
47
  const saveFields = (key, kind, fields) => write(database, () => {
119
48
  const accountId = account(key);
@@ -163,113 +92,222 @@ export const crmCopiesOver = (context, people) => {
163
92
  ...(row.options == null ? {} : { options: JSON.parse(String(row.options)) }),
164
93
  }));
165
94
  };
166
- const personIdOf = (key, externalId) => {
95
+ const personIdOf = (key, externalId, type = "contact") => {
167
96
  const row = database
168
97
  .prepare("SELECT l.person_id FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
169
98
  "WHERE i.provider = ? AND i.external_id = ?")
170
- .get(key.provider, crmIdentityId(key, externalId));
99
+ .get(key.provider, crmIdentityId(key, externalId, type));
171
100
  return row ? Number(row.person_id) : null;
172
101
  };
173
- const organizationIdOf = (accountId, externalId) => {
174
- const row = database
175
- .prepare("SELECT entity_id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
176
- "AND entity_type = 'organization'")
177
- .get(accountId, externalId);
178
- return row?.entity_id == null ? null : Number(row.entity_id);
102
+ /**
103
+ * How many people the contact's email belongs to; none once the owner separated this contact, who already decided.
104
+ */
105
+ const peopleSharing = (key, externalId, email) => {
106
+ const decided = database
107
+ .prepare("SELECT 1 FROM identity_link_events e JOIN identities i ON i.id = e.identity_id WHERE i.provider = ? " +
108
+ "AND i.external_id = ? AND e.author = 'owner' LIMIT 1")
109
+ .get(key.provider, crmIdentityId(key, externalId));
110
+ if (decided)
111
+ return 0;
112
+ return Number(database
113
+ .prepare("SELECT count(DISTINCT l.person_id) AS n FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
114
+ "WHERE i.email = ?")
115
+ .get(email)?.n);
179
116
  };
180
- const saveItem = (key, accountId, kind, item, at) => {
181
- const pipeline = pipelineOf(accountId, kind, item.pipeline);
182
- const stage = pipeline &&
117
+ /** A person a CRM contact or user made has no name when it joined the mail contact of its address first. */
118
+ const nameUnnamed = (key, externalId, type, name) => {
119
+ const person = personIdOf(key, externalId, type);
120
+ if (person !== null && name)
183
121
  database
184
- .prepare("SELECT id, outcome FROM pipeline_stages WHERE pipeline_id = ? AND external_id = ?")
185
- .get(Number(pipeline.id), item.stage);
186
- if (!pipeline || !stage)
187
- return {
188
- externalId: item.externalId,
189
- reason: "crm.stage-unknown",
190
- message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
191
- };
192
- const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
193
- const given = item.amount != null && item.currency != null;
194
- const currency = given ? currencyOf(item.currency) : null;
195
- const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
196
- if (amount !== null && amount < 0)
197
- throw new CliError("validation_error", "an amount is 0 or more");
198
- if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
199
- throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
200
- const status = item.status ?? String(stage.outcome);
201
- const closed = status === "open"
202
- ? null
203
- : (day(item.closedDate, "a closed day") ?? new Date(epoch(item.updatedAt, at)).toISOString().slice(0, 10));
204
- const deal = kind === "lead" && item.deal
205
- ? database.prepare("SELECT id FROM deals WHERE account_id = ? AND external_id = ?").get(accountId, item.deal)
206
- : undefined;
207
- const metadata = {
208
- ...(item.metadata ?? {}),
209
- ...(item.url ? { url: item.url } : {}),
210
- ...(item.assignee ? { assignee: crmIdentityId(key, item.assignee, "user") } : {}),
211
- ...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
122
+ .prepare("UPDATE persons SET name = ?, updated_at = ? WHERE id = ? AND name IS NULL")
123
+ .run(name, now(), person);
124
+ return person;
125
+ };
126
+ const refOf = (key, accountId, ref) => {
127
+ if (ref.type === "contact" || ref.type === "user") {
128
+ const person = personIdOf(key, ref.id, ref.type);
129
+ return person === null ? null : `person:${person}`;
130
+ }
131
+ // A row the CRM deleted is no end: a relationship waiting for it is never written.
132
+ const row = ref.type === "company"
133
+ ? database
134
+ .prepare("SELECT entity_id AS id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
135
+ "AND entity_type = 'organization' AND deleted_at IS NULL")
136
+ .get(accountId, ref.id)
137
+ : database
138
+ .prepare(`SELECT id FROM ${TABLES[ref.type]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
139
+ .get(accountId, ref.id);
140
+ if (row?.id == null)
141
+ return null;
142
+ return `${ref.type === "company" ? "organization" : ref.type}:${row.id}`;
143
+ };
144
+ const pendingBook = (accountId) => {
145
+ let byOwner;
146
+ let changed = false;
147
+ const load = () => {
148
+ if (byOwner)
149
+ return byOwner;
150
+ byOwner = new Map();
151
+ try {
152
+ const value = JSON.parse(syncStateOf(context, accountId, PENDING)?.value ?? "[]");
153
+ for (const one of Array.isArray(value) ? value : [])
154
+ byOwner.set(one.owner, [...(byOwner.get(one.owner) ?? []), { ...one, at: Number(one.at) || now() }]);
155
+ }
156
+ catch { }
157
+ return byOwner;
212
158
  };
213
- const values = {
214
- title,
215
- organization: item.organization ? organizationIdOf(accountId, item.organization) : null,
216
- stage: Number(stage.id),
217
- status,
218
- currency,
219
- amount,
220
- close: day(item.closeDate, "an expected close day"),
221
- closed,
222
- metadata: Object.keys(metadata).length ? JSON.stringify(metadata) : null,
223
- created: epoch(item.createdAt, at),
224
- updated: epoch(item.updatedAt, at),
159
+ return {
160
+ replace: (owner, entries) => {
161
+ const held = load();
162
+ if (!entries.length && !held.has(owner))
163
+ return;
164
+ if (entries.length)
165
+ held.set(owner, entries);
166
+ else
167
+ held.delete(owner);
168
+ changed = true;
169
+ },
170
+ forget: (owner) => {
171
+ if (load().delete(owner))
172
+ changed = true;
173
+ },
174
+ all: () => [...load().values()].flat(),
175
+ flush: () => {
176
+ if (!byOwner)
177
+ return 0;
178
+ const all = [...byOwner.values()].flat();
179
+ const fresh = all
180
+ .filter((one) => one.at > now() - PENDING_DAYS * 86_400_000)
181
+ .sort((a, b) => b.at - a.at)
182
+ .slice(0, PENDING_MOST);
183
+ if (!changed && fresh.length === all.length)
184
+ return 0;
185
+ if (fresh.length)
186
+ writeState(context, accountId, PENDING, JSON.stringify(fresh));
187
+ else
188
+ clearState(context, accountId, PENDING);
189
+ changed = false;
190
+ return all.length - fresh.length;
191
+ },
225
192
  };
226
- const table = TABLES[kind];
227
- const held = database
228
- .prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
229
- .get(accountId, item.externalId);
230
- let id;
231
- if (held) {
232
- id = Number(held.id);
233
- database
234
- .prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
235
- "close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
236
- (kind === "lead" ? ", deal_id = coalesce(?, deal_id)" : "") +
237
- " WHERE id = ?")
238
- .run(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, values.metadata, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []), id);
239
- }
240
- else {
241
- const actor = author(key);
242
- id = Number(database
243
- .prepare(`INSERT INTO ${table} (title, organization_id, stage_id, status, currency, amount, close_date, closed_date, ` +
244
- `account_id, external_id, author_type, author_id, source, metadata, created_at, updated_at` +
245
- (kind === "lead" ? ", deal_id" : "") +
246
- `) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${kind === "lead" ? ", ?" : ""}) RETURNING id`)
247
- .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
- }
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))
193
+ };
194
+ /**
195
+ * Reports one CRM row's relationships as a diff (`relations.syncReported`) inside `scope`. One whose other end is not
196
+ * stored yet waits in the account's sync state and is tried again after the next sync, so a deal read before its
197
+ * contact still gets the contact.
198
+ */
199
+ const reportFrom = (key, accountId, owner, wanted, scope, tally, pending) => {
200
+ const name = `${owner.type}:${owner.id}`;
201
+ const relationships = [];
202
+ const waiting = [];
203
+ for (const one of wanted) {
204
+ const from = refOf(key, accountId, one.from);
205
+ const to = refOf(key, accountId, one.to);
206
+ if (from === null || to === null) {
207
+ const missing = from === null ? one.from : one.to;
208
+ if (one.pend === false) {
209
+ tally.unlistedUsers += 1;
210
+ continue;
211
+ }
212
+ const { pend: _, ...kept } = one;
213
+ waiting.push({ owner: name, ...kept, at: now() });
214
+ tally.issues.push({
215
+ externalId: owner.id,
216
+ reason: "crm.reference-unknown",
217
+ message: `${owner.type} ${owner.id} names ${missing.type} ${missing.id}, which is not stored yet; ` +
218
+ "the next sync tries again",
219
+ });
260
220
  continue;
261
- seen.add(personId);
262
- link.run(kind, id, personId, role, SOURCE, at, at);
221
+ }
222
+ relationships.push({
223
+ from,
224
+ to,
225
+ kind: one.kind,
226
+ role: one.role,
227
+ ...(one.metadata ? { metadata: one.metadata } : {}),
228
+ });
263
229
  }
230
+ pending.replace(name, waiting);
231
+ const done = syncReportedIn(context, key, relationships, scope, { source: SOURCE });
232
+ tally.skippedOwnerRejected += done.skippedOwnerRejected;
233
+ for (const one of done.issues)
234
+ tally.issues.push({ externalId: owner.id, reason: one.reason, message: one.message });
235
+ };
236
+ /** The pending relationships whose ends are stored now, written without withdrawing anything. */
237
+ const retryPending = (key) => write(database, () => {
238
+ const accountId = findAccountPk(context, key);
239
+ if (accountId === undefined)
240
+ return { written: 0, dropped: 0 };
241
+ const pending = pendingBook(accountId);
242
+ let written = 0;
243
+ const owners = new Map();
244
+ for (const one of pending.all())
245
+ owners.set(one.owner, [...(owners.get(one.owner) ?? []), one]);
246
+ for (const [owner, entries] of owners) {
247
+ const kept = [];
248
+ for (const one of entries) {
249
+ const from = refOf(key, accountId, one.from);
250
+ const to = refOf(key, accountId, one.to);
251
+ if (from === null || to === null) {
252
+ kept.push(one);
253
+ continue;
254
+ }
255
+ const relation = {
256
+ from,
257
+ to,
258
+ kind: one.kind,
259
+ role: one.role,
260
+ ...(one.metadata ? { metadata: one.metadata } : {}),
261
+ };
262
+ syncReportedIn(context, key, [relation], { from: [], kinds: [] }, { source: SOURCE });
263
+ written += 1;
264
+ }
265
+ if (kept.length !== entries.length)
266
+ pending.replace(owner, kept);
267
+ }
268
+ return { written, dropped: pending.flush() };
269
+ });
270
+ const saveItem = (key, accountId, kind, item, at, report) => {
271
+ const saved = saveItemRow(key, accountId, kind, item, at);
272
+ if ("reason" in saved)
273
+ return saved;
274
+ const { id } = saved;
275
+ if (item.people === undefined && item.assignee === undefined)
276
+ return null;
277
+ const self = { type: kind, id: item.externalId };
278
+ const wanted = (item.people ?? []).map((person) => ({
279
+ from: self,
280
+ to: { type: "contact", id: person.externalId },
281
+ kind: "related-to",
282
+ role: DEAL_ROLES.includes(person.role) ? person.role : "contact",
283
+ ...(person.primary ? { metadata: { primary: true } } : {}),
284
+ }));
285
+ if (item.assignee)
286
+ wanted.push({
287
+ from: self,
288
+ to: { type: "user", id: item.assignee },
289
+ kind: "related-to",
290
+ role: "owner",
291
+ ...(report.users ? {} : { pend: false }),
292
+ });
293
+ // Only what the CRM said: its contacts cover the client's roles, its assignee the owner.
294
+ const roles = [
295
+ ...(item.people === undefined ? [] : DEAL_ROLES.filter((role) => role !== "owner")),
296
+ ...(item.assignee === undefined ? [] : ["owner"]),
297
+ ];
298
+ const scope = { from: [`${kind}:${id}`], kinds: ["related-to"], roles };
299
+ reportFrom(key, accountId, self, wanted, scope, report.tally, report.pending);
264
300
  return null;
265
301
  };
266
- const saveItems = (key, kind, items) => write(database, () => {
302
+ const saveItems = (key, kind, items, users) => write(database, () => {
267
303
  const accountId = account(key);
268
304
  const at = now();
269
305
  const skipped = [];
306
+ const tally = tallied();
307
+ const pending = pendingBook(accountId);
270
308
  for (const item of items)
271
309
  try {
272
- const missing = saveItem(key, accountId, kind, item, at);
310
+ const missing = saveItem(key, accountId, kind, item, at, { tally, pending, users });
273
311
  if (missing)
274
312
  skipped.push(missing);
275
313
  }
@@ -278,7 +316,8 @@ export const crmCopiesOver = (context, people) => {
278
316
  throw error;
279
317
  skipped.push({ externalId: item.externalId, reason: "crm.item-invalid", message: error.message });
280
318
  }
281
- return { saved: items.length - skipped.length, skipped };
319
+ tally.droppedPending += pending.flush();
320
+ return { saved: items.length - skipped.length, skipped, ...relationNotes(tally) };
282
321
  });
283
322
  const saveOrganizations = (key, organizations) => write(database, () => {
284
323
  const accountId = account(key);
@@ -288,13 +327,16 @@ export const crmCopiesOver = (context, people) => {
288
327
  const fields = {
289
328
  name,
290
329
  ...(organization.url ? { url: organization.url } : {}),
330
+ ...(organization.own ? { own: true } : {}),
331
+ ...(organization.type === undefined ? {} : { type: organization.type }),
291
332
  ...(organization.metadata ?? {}),
292
333
  };
293
334
  const fingerprint = recordFingerprint(fields, []);
294
335
  const held = database
295
336
  .prepare("SELECT * FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ?")
296
337
  .get(accountId, organization.externalId);
297
- const before = held ? JSON.parse(String(held.fields)).name : undefined;
338
+ const previous = held ? JSON.parse(String(held.fields)) : {};
339
+ const before = previous.name;
298
340
  let entity = held?.entity_type === "organization" && held.entity_id != null ? Number(held.entity_id) : null;
299
341
  if (entity === null)
300
342
  entity = Number(database
@@ -306,6 +348,19 @@ export const crmCopiesOver = (context, people) => {
306
348
  database
307
349
  .prepare("UPDATE organizations SET name = ?, updated_at = ? WHERE id = ? AND name = ?")
308
350
  .run(name, at, entity, typeof before === "string" ? before : name);
351
+ // The owner's mark (`own_by: "owner"`) is his: the CRM sets and clears only its own.
352
+ if (organization.own)
353
+ database
354
+ .prepare("UPDATE organizations SET metadata = json_set(coalesce(metadata, '{}'), '$.own', json('true'), " +
355
+ "'$.own_by', 'crm'), updated_at = ? WHERE id = ? " +
356
+ "AND json_extract(coalesce(metadata, '{}'), '$.own_by') IS NOT 'owner' " +
357
+ "AND json_extract(coalesce(metadata, '{}'), '$.own') IS NOT 1")
358
+ .run(at, entity);
359
+ else if (previous.own === true)
360
+ database
361
+ .prepare("UPDATE organizations SET metadata = json_remove(metadata, '$.own', '$.own_by'), updated_at = ? " +
362
+ "WHERE id = ? AND json_extract(metadata, '$.own_by') IS 'crm'")
363
+ .run(at, entity);
309
364
  if (held)
310
365
  database
311
366
  .prepare("UPDATE records SET fields = ?, fingerprint = ?, entity_type = 'organization', entity_id = ?, " +
@@ -320,6 +375,106 @@ export const crmCopiesOver = (context, people) => {
320
375
  }
321
376
  return { saved: organizations.length, skipped: [] };
322
377
  });
378
+ const ownCompanies = (accountId) => database
379
+ .prepare("SELECT r.external_id FROM records r JOIN organizations o ON o.id = r.entity_id WHERE r.account_id = ? " +
380
+ "AND r.type = 'organization' AND r.entity_type = 'organization' AND r.deleted_at IS NULL " +
381
+ "AND json_extract(o.metadata, '$.own') = 1 ORDER BY o.id")
382
+ .all(accountId)
383
+ .map((row) => String(row.external_id));
384
+ /**
385
+ * Every stored company of the account against `crm.<provider>:<account>.company-types`, after the run read them all:
386
+ * a customer listed before the own company, or a setting made after the first sync, applies on the next sync.
387
+ */
388
+ const saveCompanyTypes = (key) => write(database, () => {
389
+ const accountId = account(key);
390
+ const tally = tallied();
391
+ const types = crmCompanyTypes(database, key);
392
+ const own = ownCompanies(accountId);
393
+ const mine = own.flatMap((id) => refOf(key, accountId, { type: "company", id }) ?? []);
394
+ const companies = database
395
+ .prepare("SELECT external_id, entity_id, json_extract(fields, '$.type') AS type FROM records WHERE account_id = ? " +
396
+ "AND type = 'organization' AND entity_type = 'organization' AND deleted_at IS NULL " +
397
+ "AND json_type(fields, '$.type') IS NOT NULL")
398
+ .all(accountId);
399
+ for (const company of companies) {
400
+ if (own.includes(String(company.external_id)))
401
+ continue;
402
+ const ref = `organization:${company.entity_id}`;
403
+ const meaning = company.type == null ? undefined : types[String(company.type)];
404
+ const relationships = mine.flatMap((other) => {
405
+ if (meaning === "customer-of")
406
+ return [{ from: ref, to: other, kind: "customer-of" }];
407
+ if (meaning === "supplier")
408
+ return [{ from: other, to: ref, kind: "customer-of" }];
409
+ if (meaning === "partner-of")
410
+ return [{ from: ref, to: other, kind: "partner-of" }];
411
+ return [];
412
+ });
413
+ const scope = { from: [ref], to: [ref], kinds: ["customer-of", "partner-of"] };
414
+ const done = syncReportedIn(context, key, relationships, scope, { source: SOURCE });
415
+ tally.skippedOwnerRejected += done.skippedOwnerRejected;
416
+ for (const one of done.issues)
417
+ tally.issues.push({ externalId: String(company.external_id), reason: one.reason, message: one.message });
418
+ }
419
+ return { saved: companies.length, skipped: [], ...relationNotes(tally) };
420
+ });
421
+ const saveUsers = (key, users, departments) => {
422
+ const accountId = account(key);
423
+ const tally = tallied();
424
+ const pending = pendingBook(accountId);
425
+ for (const user of users)
426
+ nameUnnamed(key, user.externalId, "user", textOf(user.name, 200));
427
+ const active = new Map(users.filter((user) => user.active !== false).map((user) => [user.externalId, user]));
428
+ const own = ownCompanies(accountId);
429
+ if (own.length === 0)
430
+ tally.issues.push({
431
+ reason: "crm.own-unknown",
432
+ message: "no own company of this account is stored, so no user is its employee yet",
433
+ });
434
+ const byId = new Map((departments ?? []).map((department) => [department.externalId, department]));
435
+ for (const user of users) {
436
+ const self = { type: "user", id: user.externalId };
437
+ const ref = refOf(key, accountId, self);
438
+ if (ref === null)
439
+ continue;
440
+ const working = active.has(user.externalId);
441
+ const position = textOf(user.position, 200);
442
+ if (own.length) {
443
+ const wanted = working
444
+ ? own.map((id) => ({
445
+ from: self,
446
+ to: { type: "company", id },
447
+ kind: "member-of",
448
+ role: "employee",
449
+ ...(position ? { metadata: { position } } : {}),
450
+ }))
451
+ : [];
452
+ const scope = { from: [ref], kinds: ["member-of"], roles: ["employee"] };
453
+ reportFrom(key, accountId, self, wanted, scope, tally, pending);
454
+ }
455
+ // Without departments, or without a user's own list of them, who it reports to is unknown, not none.
456
+ if (departments === undefined || user.departments === undefined)
457
+ continue;
458
+ const heads = new Set();
459
+ for (const id of working ? user.departments : []) {
460
+ const department = byId.get(id);
461
+ const head = department?.head === user.externalId ? byId.get(department.parent ?? "")?.head : department?.head;
462
+ if (head && head !== user.externalId && active.has(head))
463
+ heads.add(head);
464
+ }
465
+ const lines = [...heads].map((head) => ({
466
+ from: self,
467
+ to: { type: "user", id: head },
468
+ kind: "reports-to",
469
+ role: null,
470
+ metadata: { derived: "department-head" },
471
+ }));
472
+ const owner = { type: "user", id: `${user.externalId}/reports-to` };
473
+ reportFrom(key, accountId, owner, lines, { from: [ref], kinds: ["reports-to"] }, tally, pending);
474
+ }
475
+ tally.droppedPending += pending.flush();
476
+ return { saved: users.length, skipped: [], ...relationNotes(tally) };
477
+ };
323
478
  const stored = (key, kind) => {
324
479
  const accountId = findAccountPk(context, key);
325
480
  if (accountId === undefined || kind === "person")
@@ -333,17 +488,24 @@ export const crmCopiesOver = (context, people) => {
333
488
  .prepare(`SELECT id, external_id, updated_at FROM ${TABLES[kind]} WHERE account_id = ? AND deleted_at IS NULL`)
334
489
  .all(accountId);
335
490
  };
336
- const markDeleted = (kind, ids) => {
491
+ const markDeleted = (key, kind, rows) => {
337
492
  const table = kind === "organization" ? "records" : TABLES[kind];
338
493
  const mark = database.prepare(`UPDATE ${table} SET deleted_at = ? WHERE id = ?`);
339
494
  const at = now();
340
- for (const id of ids)
341
- mark.run(at, id);
342
- return ids.length;
495
+ for (const row of rows)
496
+ mark.run(at, Number(row.id));
497
+ const accountId = findAccountPk(context, key);
498
+ if (isItemKind(kind) && accountId !== undefined && rows.length) {
499
+ const pending = pendingBook(accountId);
500
+ for (const row of rows)
501
+ pending.forget(`${kind}:${row.external_id}`);
502
+ pending.flush();
503
+ }
504
+ return rows.length;
343
505
  };
344
506
  return {
345
507
  savePipelines: async (key, kind, pipelines) => savePipelines(key, kind, pipelines),
346
- saveItems: async (key, kind, items) => saveItems(key, kind, items),
508
+ saveItems: async (key, kind, items, options) => saveItems(key, kind, items, options?.users !== false),
347
509
  savePeople: async (key, contacts) => {
348
510
  await people.savePeople(key, contacts.map((contact) => ({
349
511
  id: crmIdentityId(key, contact.externalId),
@@ -351,28 +513,72 @@ export const crmCopiesOver = (context, people) => {
351
513
  email: textOf(contact.email, 320)?.toLowerCase() ?? null,
352
514
  phone: textOf(contact.phone, 64),
353
515
  })));
354
- return { saved: contacts.length, skipped: [] };
516
+ return write(database, () => {
517
+ const accountId = account(key);
518
+ const tally = tallied();
519
+ const pending = pendingBook(accountId);
520
+ for (const contact of contacts) {
521
+ const person = nameUnnamed(key, contact.externalId, "contact", textOf(contact.name, 200));
522
+ const email = textOf(contact.email, 320)?.toLowerCase();
523
+ const sharing = email ? peopleSharing(key, contact.externalId, email) : 0;
524
+ if (sharing > 1)
525
+ tally.issues.push({
526
+ externalId: contact.externalId,
527
+ reason: "crm.email-ambiguous",
528
+ message: `contact ${contact.externalId}'s email belongs to ${sharing} people: say which one it is`,
529
+ });
530
+ if (person === null || contact.organizations === undefined)
531
+ continue;
532
+ const self = { type: "contact", id: contact.externalId };
533
+ const position = textOf(contact.position, 200);
534
+ const wanted = contact.organizations.map((company) => {
535
+ const sourceRole = textOf(company.sourceRole, 200);
536
+ const metadata = {
537
+ ...(position ? { position } : {}),
538
+ ...(sourceRole ? { source_role: sourceRole } : {}),
539
+ ...(company.primary ? { primary: true } : {}),
540
+ };
541
+ return {
542
+ from: self,
543
+ to: { type: "company", id: company.externalId },
544
+ kind: "member-of",
545
+ role: "contact",
546
+ ...(Object.keys(metadata).length ? { metadata } : {}),
547
+ };
548
+ });
549
+ const scope = { from: [`person:${person}`], kinds: ["member-of"], roles: ["contact"] };
550
+ reportFrom(key, accountId, self, wanted, scope, tally, pending);
551
+ }
552
+ tally.droppedPending += pending.flush();
553
+ return { saved: contacts.length, skipped: [], ...relationNotes(tally) };
554
+ });
555
+ },
556
+ retryPending: async (key) => retryPending(key),
557
+ saveCompanyTypes: async (key) => saveCompanyTypes(key),
558
+ saveUsers: async (key, users, departments) => {
559
+ await people.savePeople(key, users.map((user) => ({
560
+ id: crmIdentityId(key, user.externalId, "user"),
561
+ name: textOf(user.name, 200),
562
+ email: textOf(user.email, 320)?.toLowerCase() ?? null,
563
+ })));
564
+ return write(database, () => saveUsers(key, users, departments));
355
565
  },
356
566
  saveOrganizations: async (key, organizations) => saveOrganizations(key, organizations),
357
567
  saveFields: async (key, kind, fields) => saveFields(key, kind, fields),
358
568
  fields: async (key, kind) => fieldsOf(key, kind),
359
569
  remove: async (key, kind, externalIds) => write(database, () => {
360
570
  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)));
571
+ return markDeleted(key, kind, stored(key, kind).filter((row) => gone.has(String(row.external_id))));
364
572
  }),
365
573
  removeUnlisted: async (key, kind, listed, before, { dryRun } = {}) => write(database, () => {
366
574
  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);
575
+ const gone = stored(key, kind).filter((row) => !held.has(String(row.external_id)) && Number(row.updated_at) < before);
576
+ return dryRun ? gone.length : markDeleted(key, kind, gone);
371
577
  }),
372
578
  count: async (key, kind) => kind === "person"
373
579
  ? Number(database
374
580
  .prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
375
- .get(key.provider, key.account.length + 1, `${key.account}/`)?.n)
581
+ .get(key.provider, crmAccountPrefix(key).length, crmAccountPrefix(key))?.n)
376
582
  : stored(key, kind).length,
377
583
  refOf: async (key, kind, externalId) => {
378
584
  const accountId = findAccountPk(context, key);