@wirecat/cli-core 0.606.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 (209) hide show
  1. package/CHANGELOG.md +186 -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 +3 -0
  12. package/dist/cli/index.js +3 -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/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +61 -2
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -1,26 +1,17 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { isItemKind, } from "../../domain/crm.js";
3
- import { DEAL_ROLES, STAGE_OUTCOMES } from "../../domain/deals.js";
4
- import { currencyOf, minorUnits } from "../../domain/money.js";
3
+ import { DEAL_ROLES } from "../../domain/deals.js";
5
4
  import { recordFingerprint } from "../../domain/records.js";
6
- import { fold } from "../normalize.js";
7
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
+ import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
8
7
  import { crmCompanyTypes } from "./crm-settings.js";
9
- import { authorActor } from "./memories.js";
10
8
  import { syncReportedIn } from "./reported-relations.js";
11
9
  import { clearState, syncStateOf, writeState } from "./sync.js";
12
10
  import { write } from "./transaction.js";
13
11
  const PENDING = "crm:pending-relations";
14
12
  const PENDING_DAYS = 30;
15
13
  const PENDING_MOST = 5000;
16
- const TABLES = { deal: "deals", lead: "leads" };
17
- /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
18
- const SOURCE = "crm";
19
- /**
20
- * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
21
- * `contact:` references percent-encode it, so the `/` stays one part.
22
- */
23
- export const crmIdentityId = (key, externalId, type = "contact") => `${key.account}/${type}/${externalId}`;
14
+ export { crmIdentityId, crmRowsOver } from "./crm-rows.js";
24
15
  const tallied = () => ({ issues: [], skippedOwnerRejected: 0, unlistedUsers: 0, droppedPending: 0 });
25
16
  const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPending }) => ({
26
17
  ...(issues.length ? { issues } : {}),
@@ -28,27 +19,10 @@ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPen
28
19
  ...(unlistedUsers ? { unlistedUsers } : {}),
29
20
  ...(droppedPending ? { droppedPending } : {}),
30
21
  });
31
- const day = (value, what) => {
32
- if (value === undefined || value === null || value === "")
33
- return null;
34
- if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(value)))
35
- throw new CliError("validation_error", `${what} is YYYY-MM-DD, not ${JSON.stringify(value)}`);
36
- return value;
37
- };
38
- const epoch = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
39
- const textOf = (value, most) => {
40
- if (typeof value !== "string")
41
- return null;
42
- const kept = value.trim().slice(0, most);
43
- return kept || null;
44
- };
45
22
  export const crmCopiesOver = (context, people) => {
46
23
  const { database, now } = context;
47
- const author = (key) => authorActor(context, { bot: key.provider, kind: "rule" }).actor;
24
+ const { savePipeline, saveItemRow } = crmRowsOver(context);
48
25
  const account = (key) => accountPk(context, key);
49
- const pipelineOf = (accountId, kind, externalId) => database
50
- .prepare("SELECT * FROM pipelines WHERE account_id = ? AND kind = ? AND external_id = ?")
51
- .get(accountId, kind, externalId);
52
26
  /**
53
27
  * One kind's whole list: a pipeline it lacks is marked deleted, one listed again comes back. An empty list marks
54
28
  * nothing: a sign-in that lost its CRM rights lists no pipeline at all.
@@ -56,21 +30,8 @@ export const crmCopiesOver = (context, people) => {
56
30
  const savePipelines = (key, kind, pipelines) => write(database, () => {
57
31
  const accountId = account(key);
58
32
  const at = now();
59
- for (const pipeline of pipelines) {
60
- const name = textOf(pipeline.name, 80) ?? pipeline.externalId;
61
- const held = pipelineOf(accountId, kind, pipeline.externalId);
62
- const id = held
63
- ? Number(held.id)
64
- : Number(database
65
- .prepare("INSERT INTO pipelines (account_id, external_id, kind, name, name_folded, created_at, updated_at) " +
66
- "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id")
67
- .get(accountId, pipeline.externalId, kind, name, fold(name), at, at)?.id);
68
- if (held && (held.name !== name || held.deleted_at != null))
69
- database
70
- .prepare("UPDATE pipelines SET name = ?, name_folded = ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
71
- .run(name, fold(name), at, id);
72
- saveStages(id, pipeline, at);
73
- }
33
+ for (const pipeline of pipelines)
34
+ savePipeline(accountId, kind, pipeline, at);
74
35
  if (pipelines.length === 0)
75
36
  return { saved: 0, skipped: [] };
76
37
  const listed = new Set(pipelines.map(({ externalId }) => externalId));
@@ -82,51 +43,6 @@ export const crmCopiesOver = (context, people) => {
82
43
  mark.run(at, at, Number(row.id));
83
44
  return { saved: pipelines.length, skipped: [] };
84
45
  });
85
- /**
86
- * Stage names are unique in a pipeline, but a CRM may swap two, or give two stages one name: listed stages first
87
- * take a name no stage has, then their own, and a name used twice keeps the stage's id beside it.
88
- */
89
- const saveStages = (pipelineId, pipeline, at) => {
90
- const ordered = [...pipeline.stages].sort((a, b) => a.position - b.position);
91
- const counts = new Map();
92
- for (const stage of ordered)
93
- counts.set(fold(stage.name), (counts.get(fold(stage.name)) ?? 0) + 1);
94
- const wanted = ordered.map((stage, index) => {
95
- const name = textOf(stage.name, 80) ?? stage.externalId;
96
- const folded = (counts.get(fold(stage.name)) ?? 0) > 1 ? `${fold(name)} (${stage.externalId})` : fold(name);
97
- if (!STAGE_OUTCOMES.includes(stage.outcome))
98
- throw new CliError("invalid_response", `stage ${stage.externalId} has no known outcome: ${stage.outcome}`);
99
- return { ...stage, name, folded, position: index + 1 };
100
- });
101
- const held = database.prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ?").all(pipelineId);
102
- const listed = new Set(wanted.map(({ externalId }) => externalId));
103
- const taken = new Set(wanted.map(({ folded }) => folded));
104
- const rename = database.prepare("UPDATE pipeline_stages SET name_folded = ? WHERE id = ?");
105
- const gone = database.prepare("UPDATE pipeline_stages SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL");
106
- for (const row of held) {
107
- const kept = row.external_id != null && listed.has(String(row.external_id));
108
- if (kept)
109
- rename.run(`\u0000${row.id}`, Number(row.id));
110
- else if (taken.has(String(row.name_folded)))
111
- rename.run(`${row.name_folded} (${row.external_id ?? row.id})`, Number(row.id));
112
- if (!kept)
113
- gone.run(at, Number(row.id));
114
- }
115
- const byId = new Map(held.map((row) => [String(row.external_id), row]));
116
- for (const stage of wanted) {
117
- const row = byId.get(stage.externalId);
118
- if (row)
119
- database
120
- .prepare("UPDATE pipeline_stages SET name = ?, name_folded = ?, position = ?, outcome = ?, updated_at = ?, " +
121
- "deleted_at = NULL WHERE id = ?")
122
- .run(stage.name, stage.folded, stage.position, stage.outcome, at, Number(row.id));
123
- else
124
- database
125
- .prepare("INSERT INTO pipeline_stages (pipeline_id, name, name_folded, position, outcome, external_id, created_at, " +
126
- "updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
127
- .run(pipelineId, stage.name, stage.folded, stage.position, stage.outcome, stage.externalId, at, at);
128
- }
129
- };
130
46
  // Unlike pipelines, an empty list does mark every field deleted: a CRM with no custom fields is an ordinary answer.
131
47
  const saveFields = (key, kind, fields) => write(database, () => {
132
48
  const accountId = account(key);
@@ -207,13 +123,6 @@ export const crmCopiesOver = (context, people) => {
207
123
  .run(name, now(), person);
208
124
  return person;
209
125
  };
210
- const organizationIdOf = (accountId, externalId) => {
211
- const row = database
212
- .prepare("SELECT entity_id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
213
- "AND entity_type = 'organization'")
214
- .get(accountId, externalId);
215
- return row?.entity_id == null ? null : Number(row.entity_id);
216
- };
217
126
  const refOf = (key, accountId, ref) => {
218
127
  if (ref.type === "contact" || ref.type === "user") {
219
128
  const person = personIdOf(key, ref.id, ref.type);
@@ -359,74 +268,10 @@ export const crmCopiesOver = (context, people) => {
359
268
  return { written, dropped: pending.flush() };
360
269
  });
361
270
  const saveItem = (key, accountId, kind, item, at, report) => {
362
- const pipeline = pipelineOf(accountId, kind, item.pipeline);
363
- const stage = pipeline &&
364
- database
365
- .prepare("SELECT id, outcome FROM pipeline_stages WHERE pipeline_id = ? AND external_id = ?")
366
- .get(Number(pipeline.id), item.stage);
367
- if (!pipeline || !stage)
368
- return {
369
- externalId: item.externalId,
370
- reason: "crm.stage-unknown",
371
- message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
372
- };
373
- const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
374
- const given = item.amount != null && item.currency != null;
375
- const currency = given ? currencyOf(item.currency) : null;
376
- const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
377
- if (amount !== null && amount < 0)
378
- throw new CliError("validation_error", "an amount is 0 or more");
379
- if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
380
- throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
381
- const status = item.status ?? String(stage.outcome);
382
- const closed = status === "open"
383
- ? null
384
- : (day(item.closedDate, "a closed day") ?? new Date(epoch(item.updatedAt, at)).toISOString().slice(0, 10));
385
- const deal = kind === "lead" && item.deal
386
- ? database.prepare("SELECT id FROM deals WHERE account_id = ? AND external_id = ?").get(accountId, item.deal)
387
- : undefined;
388
- const metadata = {
389
- ...(item.metadata ?? {}),
390
- ...(item.url ? { url: item.url } : {}),
391
- ...(item.assignee ? { assignee: crmIdentityId(key, item.assignee, "user") } : {}),
392
- ...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
393
- };
394
- const values = {
395
- title,
396
- organization: item.organization ? organizationIdOf(accountId, item.organization) : null,
397
- stage: Number(stage.id),
398
- status,
399
- currency,
400
- amount,
401
- close: day(item.closeDate, "an expected close day"),
402
- closed,
403
- metadata: Object.keys(metadata).length ? JSON.stringify(metadata) : null,
404
- created: epoch(item.createdAt, at),
405
- updated: epoch(item.updatedAt, at),
406
- };
407
- const table = TABLES[kind];
408
- const held = database
409
- .prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
410
- .get(accountId, item.externalId);
411
- let id;
412
- if (held) {
413
- id = Number(held.id);
414
- database
415
- .prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
416
- "close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
417
- (kind === "lead" ? ", deal_id = coalesce(?, deal_id)" : "") +
418
- " WHERE id = ?")
419
- .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);
420
- }
421
- else {
422
- const actor = author(key);
423
- id = Number(database
424
- .prepare(`INSERT INTO ${table} (title, organization_id, stage_id, status, currency, amount, close_date, closed_date, ` +
425
- `account_id, external_id, author_type, author_id, source, metadata, created_at, updated_at` +
426
- (kind === "lead" ? ", deal_id" : "") +
427
- `) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${kind === "lead" ? ", ?" : ""}) RETURNING id`)
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);
429
- }
271
+ const saved = saveItemRow(key, accountId, kind, item, at);
272
+ if ("reason" in saved)
273
+ return saved;
274
+ const { id } = saved;
430
275
  if (item.people === undefined && item.assignee === undefined)
431
276
  return null;
432
277
  const self = { type: kind, id: item.externalId };
@@ -733,7 +578,7 @@ export const crmCopiesOver = (context, people) => {
733
578
  count: async (key, kind) => kind === "person"
734
579
  ? Number(database
735
580
  .prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
736
- .get(key.provider, key.account.length + 1, `${key.account}/`)?.n)
581
+ .get(key.provider, crmAccountPrefix(key).length, crmAccountPrefix(key))?.n)
737
582
  : stored(key, kind).length,
738
583
  refOf: async (key, kind, externalId) => {
739
584
  const accountId = findAccountPk(context, key);
@@ -2,9 +2,10 @@ import type { CrmValue } from "../../domain/crm.js";
2
2
  import { type DealKind, type DealRole, type DealStatus, type StageOutcome } from "../../domain/deals.js";
3
3
  import type { AccountKey } from "../types.js";
4
4
  import { type ProposedByFilter } from "./actors.js";
5
- import { type Party } from "./finance.js";
6
5
  import { type Author } from "./memories.js";
7
6
  import type { StoreContext } from "./open.js";
7
+ import { type AuthorInfo, type Party } from "./reviewed.js";
8
+ import { type StageAmounts } from "./stage-amounts.js";
8
9
  export interface PipelineStage {
9
10
  name: string;
10
11
  position: number;
@@ -27,7 +28,7 @@ export interface Pipeline {
27
28
  stages: PipelineStage[];
28
29
  createdAt: string;
29
30
  }
30
- export interface FunnelStage extends PipelineStage {
31
+ export interface FunnelStage extends PipelineStage, StageAmounts {
31
32
  /** Rows that got this far: entered this stage or a later one that is not lost, or were won. */
32
33
  reached: number;
33
34
  /** `reached` of the next stage that is not lost over this stage's, 0–1; `null` for the last or an empty one. */
@@ -83,12 +84,7 @@ export interface Deal {
83
84
  /** A CRM copy's own fields by code, as the CRM labels them; empty on the owner's own. */
84
85
  providerMetadata: Record<string, CrmValue>;
85
86
  people: DealPerson[];
86
- author: {
87
- type: "person" | "bot";
88
- id: string;
89
- name: string | null;
90
- kind: "agent" | "rule" | null;
91
- };
87
+ author: AuthorInfo;
92
88
  model: string | null;
93
89
  source: string;
94
90
  reason: string | null;
@@ -4,10 +4,11 @@ import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/mon
4
4
  import { notOverriddenSql } from "../../domain/relations.js";
5
5
  import { fold } from "../normalize.js";
6
6
  import { proposedBySql } from "./actors.js";
7
- import { isoDate, oneOf, refuse, reviewedRowsOver, text } from "./finance.js";
8
7
  import { linkKind } from "./link-kinds.js";
9
8
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
10
9
  import { requiredThing } from "./notes.js";
10
+ import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
11
+ import { stageAmountsOf } from "./stage-amounts.js";
11
12
  import { write } from "./transaction.js";
12
13
  const TABLES = { deal: "deals", lead: "leads" };
13
14
  const itemsSql = (kind) => "SELECT d.*, s.name AS stage_name, s.pipeline_id, p.name AS pipeline_name, b.name AS author_name, " +
@@ -197,6 +198,7 @@ export const dealOperationsOver = (context) => {
197
198
  .prepare("SELECT id, position, outcome FROM pipeline_stages WHERE pipeline_id = ? ORDER BY position, id")
198
199
  .all(Number(pipeline.id));
199
200
  const order = new Map(stages.map((stage, at) => [Number(stage.id), at]));
201
+ const standing = stageAmountsOf(context, kind, stages.map((stage) => Number(stage.id)), cutoff);
200
202
  const lostStage = new Set(stages.filter((stage) => stage.outcome === "lost").map((stage) => Number(stage.id)));
201
203
  const entered = new Map();
202
204
  for (const change of database
@@ -222,7 +224,7 @@ export const dealOperationsOver = (context) => {
222
224
  const conversion = lostStage.has(Number(stages[at]?.id)) || next === -1 || reached === 0
223
225
  ? null
224
226
  : Math.round((reachedAt(next) / reached) * 1000) / 1000;
225
- return { ...stage, reached, conversion };
227
+ return { ...stage, reached, conversion, ...standing[at] };
226
228
  });
227
229
  const won = items.filter((item) => item.status === "won").length;
228
230
  return {
@@ -358,7 +360,7 @@ export const dealOperationsOver = (context) => {
358
360
  const own = scope === "own" ? 1 : 0;
359
361
  const provider = scope === undefined || scope === "own" ? null : scope.provider;
360
362
  const account = scope === undefined || scope === "own" ? null : scope.account;
361
- const limit = Math.min(Math.max(filter.limit ?? 100, 1), 500);
363
+ const limit = limitOf(filter.limit);
362
364
  return database
363
365
  .prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL AND (? IS NULL OR d.status = ?) ` +
364
366
  "AND (? IS NULL OR d.project_id = ?) AND (? IS NULL OR s.name_folded = ?) AND (? IS NULL OR p.id = ?) " +
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { filesAccountSql } from "../../../domain/providers.js";
2
+ import { ADDED_PROVIDER, filesAccountSql } from "../../../domain/providers.js";
3
3
  import { digest } from "../../document-transfer/digest.js";
4
4
  import { referenceOfThing, storedThing } from "../things.js";
5
5
  import { read } from "../transaction.js";
@@ -165,7 +165,7 @@ export const transferSnapshot = (database, collection) => read(database, () => {
165
165
  }
166
166
  if (thing.type === "document") {
167
167
  const doc = database
168
- .prepare(`SELECT a.provider,a.external_id AS account,a.name,d.external_id,d.body,d.content_hash,d.deleted_at FROM documents d JOIN accounts a ON a.id=d.account_id WHERE d.id=? AND ${filesAccountSql("a.provider")}`)
168
+ .prepare(`SELECT a.provider,a.external_id AS account,a.name,d.external_id,d.body,d.content_hash,d.deleted_at FROM documents d JOIN accounts a ON a.id=d.account_id WHERE d.id=? AND ${filesAccountSql("a.provider")} AND a.provider<>'${ADDED_PROVIDER}'`)
169
169
  .get(thing.id);
170
170
  if (doc) {
171
171
  item.collection = collectionNameOf({ provider: doc.provider, external_id: doc.account, name: doc.name });
@@ -143,6 +143,8 @@ const addressIdentity = (database, orm, accountId, { address, name }, now) => {
143
143
  return id;
144
144
  };
145
145
  const identityOf = (database, { address, name }, now) => {
146
+ // Every writer of an e-mail identity (and of identities.email) stores trim().toLowerCase(): the records import
147
+ // matches addresses by plain equality on it, through the index.
146
148
  const key = address.trim().toLowerCase();
147
149
  const found = database
148
150
  .prepare("SELECT id, name FROM identities WHERE provider = 'email' AND external_id = ?")
@@ -4,13 +4,26 @@ import type { CacheDatabase } from "../driver.js";
4
4
  * a new type adds it here first; `entity-types.test.ts` holds every literal in the store's SQL to this list.
5
5
  */
6
6
  export declare const ENTITY_TABLES: {
7
+ readonly invoice: "invoices";
8
+ readonly payment: "payments";
9
+ readonly person: "persons";
10
+ readonly organization: "organizations";
11
+ readonly project: "projects";
12
+ readonly order: "orders";
13
+ readonly product: "catalog_items";
14
+ readonly contract: "contracts";
15
+ readonly subscription: "subscriptions";
16
+ readonly wallet: "financial_accounts";
17
+ readonly transaction: "financial_transactions";
18
+ readonly deal: "deals";
19
+ readonly lead: "leads";
20
+ readonly pipeline: "pipelines";
7
21
  readonly account: "accounts";
8
22
  readonly attachment: "attachments";
9
23
  readonly bot: "bots";
10
24
  readonly calendar_entry: "calendar_entries";
11
25
  readonly chat: "chats";
12
26
  readonly conversation: "conversations";
13
- readonly deal: "deals";
14
27
  readonly document: "documents";
15
28
  readonly document_picture: "documents";
16
29
  readonly email: "emails";
@@ -21,21 +34,13 @@ export declare const ENTITY_TABLES: {
21
34
  readonly file: "files";
22
35
  readonly identity: "identities";
23
36
  readonly image: "attachments";
24
- readonly invoice: "invoices";
25
- readonly lead: "leads";
26
37
  readonly meeting: "meetings";
27
38
  readonly meeting_transcript: "meeting_transcripts";
28
39
  readonly meeting_transcript_row: "meeting_transcript_rows";
29
40
  readonly memory: "memories";
30
41
  readonly message: "messages";
31
42
  readonly note: "notes";
32
- readonly order: "orders";
33
- readonly organization: "organizations";
34
- readonly payment: "payments";
35
- readonly person: "persons";
36
- readonly pipeline: "pipelines";
37
43
  readonly place: "places";
38
- readonly project: "projects";
39
44
  readonly tag: "canonical_tags";
40
45
  readonly task: "tasks";
41
46
  };
@@ -1,15 +1,16 @@
1
+ import { RECORD_TABLES } from "../../domain/record-types.js";
1
2
  /**
2
3
  * Every type a `<name>_type` pointer may hold, and the table its `<name>_id` names. A writer that needs
3
4
  * a new type adds it here first; `entity-types.test.ts` holds every literal in the store's SQL to this list.
4
5
  */
5
6
  export const ENTITY_TABLES = {
7
+ ...RECORD_TABLES,
6
8
  account: "accounts",
7
9
  attachment: "attachments",
8
10
  bot: "bots",
9
11
  calendar_entry: "calendar_entries",
10
12
  chat: "chats",
11
13
  conversation: "conversations",
12
- deal: "deals",
13
14
  document: "documents",
14
15
  document_picture: "documents",
15
16
  email: "emails",
@@ -20,21 +21,13 @@ export const ENTITY_TABLES = {
20
21
  file: "files",
21
22
  identity: "identities",
22
23
  image: "attachments",
23
- invoice: "invoices",
24
- lead: "leads",
25
24
  meeting: "meetings",
26
25
  meeting_transcript: "meeting_transcripts",
27
26
  meeting_transcript_row: "meeting_transcript_rows",
28
27
  memory: "memories",
29
28
  message: "messages",
30
29
  note: "notes",
31
- order: "orders",
32
- organization: "organizations",
33
- payment: "payments",
34
- person: "persons",
35
- pipeline: "pipelines",
36
30
  place: "places",
37
- project: "projects",
38
31
  tag: "canonical_tags",
39
32
  task: "tasks",
40
33
  };
@@ -43,7 +36,8 @@ export const isEntityType = (type) => Object.hasOwn(ENTITY_TABLES, type);
43
36
  export const pointerPairs = (database) => database
44
37
  .prepare("SELECT m.name AS tbl, substr(c.name, 1, length(c.name) - 5) AS pointer FROM sqlite_master m " +
45
38
  "JOIN pragma_table_info(m.name) c ON c.name LIKE '%\\_type' ESCAPE '\\' " +
46
- "WHERE m.type = 'table' AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) i " +
39
+ // record_relations' target_type and target_id name a record of a source, not an entity.
40
+ "WHERE m.type = 'table' AND m.name <> 'record_relations' AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) i " +
47
41
  "WHERE i.name = substr(c.name, 1, length(c.name) - 5) || '_id') ORDER BY m.name, c.cid")
48
42
  .all()
49
43
  .map((row) => ({ table: String(row.tbl), pointer: String(row.pointer) }));
@@ -0,0 +1,114 @@
1
+ import type { CacheDatabase, SqlValue } from "../driver.js";
2
+ import { type Thing } from "./things.js";
3
+ /**
4
+ * What a cited source looks like now, read from its columns only, never its text. `sig` differs whenever the source
5
+ * changed or was deleted in a way this store can see. `rev` finds a version later: for a note or a document its
6
+ * `revision`, whose older body `*_revisions` keeps under that number; for a message or a calendar event the highest id
7
+ * in its `*_revisions` table at the time (`0` for none), so that version's text is the first revision above it, or the
8
+ * current text when there is none; `null` where the store keeps no history.
9
+ */
10
+ export interface EvidenceSignature {
11
+ sig: string;
12
+ rev: number | null;
13
+ /** Deleted at its source, or the row is gone from the store. */
14
+ deleted: boolean;
15
+ /** The latest change or deletion the store dated; `null` when it dates none, or the row is gone. */
16
+ changedAt: number | null;
17
+ }
18
+ /** What `links.metadata` holds on an `evidence` row. */
19
+ export interface EvidenceMetadata {
20
+ v: 1;
21
+ sig: string;
22
+ /** The version last signed. */
23
+ rev: number | null;
24
+ /** The version cited; it never changes after the link is written. */
25
+ cited_rev: number | null;
26
+ quote?: string;
27
+ checked_at: number;
28
+ /** The cited row was deleted for good: the link keeps no pointer, only the kind it named. */
29
+ gone?: string;
30
+ }
31
+ /** A cited reference, with the words of it the claim rests on. */
32
+ export type EvidenceInput = string | {
33
+ ref: string;
34
+ quote?: string;
35
+ };
36
+ export declare const QUOTE_LIMIT = 500;
37
+ /** How one kind of source is signed, searched for a quote, and read back as it was cited. */
38
+ interface SourceKind {
39
+ signature(database: CacheDatabase, id: number): EvidenceSignature | undefined;
40
+ /** Whether the text holds the quote now; absent where the store keeps no text for the kind. */
41
+ holds?(database: CacheDatabase, id: number, quote: string): boolean;
42
+ /** The text at version `rev`; absent where the store keeps no history for the kind. */
43
+ textAt?(database: CacheDatabase, id: number, rev: number): string | undefined;
44
+ }
45
+ /**
46
+ * The quote still stands in the text word for word, whatever the spacing and line breaks. Case and accents count:
47
+ * the search normalizer folds them, and a changed letter here may be the change that matters.
48
+ */
49
+ export declare const quoteKept: (quote: string, text: string) => boolean;
50
+ /**
51
+ * Every kind of source a memory or fact may cite, by its `links.to_type`. An email, a meeting, a person and a project
52
+ * are checked for existence only; any other row an import made from a record follows that record.
53
+ */
54
+ export declare const SOURCE_KINDS: Partial<Record<string, SourceKind>>;
55
+ export declare const sourceKindOf: (type: string) => SourceKind | undefined;
56
+ /** The signature of a cited row as it is now; a row the store no longer holds is `deleted`. */
57
+ export declare const evidenceSignature: (database: CacheDatabase, thing: Thing) => EvidenceSignature;
58
+ /** Whether a cited row's text holds the quote now; `undefined` where the store keeps no text for its kind. */
59
+ export declare const sourceHolds: (database: CacheDatabase, thing: Thing, quote: string) => boolean | undefined;
60
+ /** The text of a cited row at version `rev`, from its history; `undefined` where there is none. */
61
+ export declare const sourceTextAt: (database: CacheDatabase, thing: Thing, rev: number) => string | undefined;
62
+ /** The reference and quote of one cited source, refusing a quote too long or empty. */
63
+ export declare const evidenceInputOf: (input: EvidenceInput) => {
64
+ ref: string;
65
+ quote?: string;
66
+ };
67
+ /** Refuses a quote the cited source's text does not hold: a claim may rest only on words the source said. */
68
+ export declare const assertQuoted: (database: CacheDatabase, thing: Thing, ref: string, quote: string | undefined) => void;
69
+ /** A new link's metadata: the version cited is the version signed. */
70
+ export declare const evidenceMetadata: (signature: EvidenceSignature, at: number, quote: string | undefined) => EvidenceMetadata;
71
+ /** The stored signature of an `evidence` link, or `undefined` for one written before signatures. */
72
+ export declare const storedEvidenceMetadata: (metadata: unknown) => EvidenceMetadata | undefined;
73
+ /**
74
+ * Signs an `evidence` link again. It keeps the quote and the version cited, and the link's own `updated_at` stays, as
75
+ * nothing about the link changed. A link written before signatures takes the version it is signed at as cited.
76
+ */
77
+ export declare const resignEvidence: (database: CacheDatabase, link: number, signature: EvidenceSignature, at: number, previous: EvidenceMetadata | undefined) => void;
78
+ /** An evidence link whose source went, as `forgetEvidenceTo` left it. */
79
+ export interface ForgottenEvidence {
80
+ link: number;
81
+ from: Thing;
82
+ /** The reference the link named before its source went. */
83
+ ref: string | null;
84
+ citedRev: number | null;
85
+ /** The link was already signed as deleted, so a check reported it then. */
86
+ reported: boolean;
87
+ }
88
+ /**
89
+ * Before cited rows go, or a message's text is erased: each evidence link to them drops its quote, which holds the
90
+ * source's words. `ids` is SQL naming the row ids. A row deleted for good also loses its pointer, so the link still
91
+ * says that a source was cited and is gone, and never names another row that takes the same id later; its old
92
+ * reference stays only as `target_text`, which nothing resolves since `target_folded` is empty. A tombstone
93
+ * (`keepPointer`) keeps it, signed as deleted. A memory or fact that still holds gets a `deleted` review in the same
94
+ * write, since the check will not meet a link with no pointer, nor one already signed as deleted; a link already
95
+ * signed as deleted was reported when the check met it.
96
+ */
97
+ export declare const forgetEvidenceTo: (database: CacheDatabase, type: string, ids: {
98
+ sql: string;
99
+ params: SqlValue[];
100
+ }, at: number, { keepPointer }?: {
101
+ keepPointer?: boolean;
102
+ }) => ForgottenEvidence[];
103
+ /** `forgetEvidenceTo` for one row. */
104
+ export declare const forgetEvidenceToRow: (database: CacheDatabase, thing: Thing, at: number, options?: {
105
+ keepPointer?: boolean;
106
+ }) => ForgottenEvidence[];
107
+ /**
108
+ * After a purge, in its write: forgets evidence still pointing at a row of any citable type that is no longer there,
109
+ * so a kind the purge did not name is not missed. The purge names what it can beforehand, while references resolve.
110
+ */
111
+ export declare const forgetDanglingEvidence: (database: CacheDatabase, at: number) => ForgottenEvidence[];
112
+ /** Deletes a document row after forgetting the evidence that cites it, so no link is left pointing at a reused id. */
113
+ export declare const deleteDocumentRow: (database: CacheDatabase, id: number, at: number) => void;
114
+ export {};