@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,3 +1,4 @@
1
+ import { contractLine, productLine, subscriptionLine, transactionLine, walletLine } from "../../domain/business.js";
1
2
  import { dealLine } from "../../domain/deals.js";
2
3
  import { invoiceLine, paymentLine } from "../../domain/finance.js";
3
4
  import { orderLine } from "../../domain/orders.js";
@@ -35,6 +36,10 @@ const byId = (kind, table, columns) => ({
35
36
  kind,
36
37
  sql: (body) => `${select(columns(body))} FROM w JOIN ${table} x ON x.id = w.k1`,
37
38
  });
39
+ /** The confirmed price in force today: the latest one already effective. */
40
+ const CURRENT_PRICE = (column) => `SELECT ${column} FROM subscription_prices WHERE subscription_id = x.id AND review = 'confirmed' ` +
41
+ "AND effective_from <= ? ORDER BY effective_from DESC LIMIT 1";
42
+ const dated = (count, reader) => ({ ...reader, dated: count });
38
43
  const crmColumns = () => ({
39
44
  title: "json_object('id', x.id, 'title', x.title, 'stage', (SELECT name FROM pipeline_stages WHERE id = x.stage_id), " +
40
45
  "'amount', x.amount, 'currency', x.currency, 'status', x.status)",
@@ -218,6 +223,43 @@ const READERS = {
218
223
  deal: byId("deal", "deals", crmColumns),
219
224
  lead: byId("lead", "leads", crmColumns),
220
225
  pipeline: byId("pipeline", "pipelines", () => ({ title: "x.name", at: "x.created_at" })),
226
+ product: byId("product", "catalog_items", () => ({
227
+ title: "json_object('name', x.name, 'kind', x.kind, 'unitPrice', x.unit_price, 'currency', x.currency, " +
228
+ "'unit', x.unit, 'archived', json(CASE WHEN x.archived_date IS NULL THEN 'false' ELSE 'true' END))",
229
+ holder: subjectName("x.supplier_type", "x.supplier_id"),
230
+ at: "x.created_at",
231
+ deleted: "x.deleted_at",
232
+ })),
233
+ contract: byId("contract", "contracts", () => ({
234
+ title: "json_object('id', x.id, 'name', x.name, 'number', x.number, 'value', x.value, 'currency', x.currency, " +
235
+ "'status', x.status, 'review', x.review)",
236
+ holder: "(SELECT name FROM projects WHERE id = x.project_id)",
237
+ at: "x.created_at",
238
+ deleted: "x.deleted_at",
239
+ })),
240
+ subscription: dated(2, byId("subscription", "subscriptions", () => ({
241
+ title: "json_object('name', x.name, 'interval', json_object('count', x.interval_count, 'unit', x.interval_unit), " +
242
+ `'price', (${CURRENT_PRICE("amount")}), 'currency', (${CURRENT_PRICE("currency")}), 'status', x.status, ` +
243
+ "'review', x.review)",
244
+ holder: "(SELECT name FROM projects WHERE id = x.project_id)",
245
+ at: "x.created_at",
246
+ deleted: "x.deleted_at",
247
+ }))),
248
+ wallet: byId("wallet", "financial_accounts", () => ({
249
+ title: "json_object('name', x.name, 'kind', x.kind, 'currency', x.currency, 'numberHint', x.number_hint, " +
250
+ "'closed', json(CASE WHEN x.closed_date IS NULL THEN 'false' ELSE 'true' END))",
251
+ holder: subjectName("x.holder_type", "x.holder_id"),
252
+ at: "x.created_at",
253
+ deleted: "x.deleted_at",
254
+ })),
255
+ transaction: byId("transaction", "financial_transactions", () => ({
256
+ title: "json_object('direction', x.direction, 'amount', x.amount, 'currency', x.currency, " +
257
+ "'label', coalesce(x.counterparty_name, x.description), 'date', x.statement_date, 'status', x.status, " +
258
+ "'review', x.review)",
259
+ holder: "(SELECT name FROM financial_accounts WHERE id = x.financial_account_id)",
260
+ at: "x.created_at",
261
+ deleted: "x.deleted_at",
262
+ })),
221
263
  };
222
264
  /** Mail saved before the mail tables existed is still messages, so a miss there is read again as a message. */
223
265
  const FALLBACK = { email: "message", email_thread: "chat" };
@@ -266,7 +308,7 @@ const kindOfReference = (reference) => reference.type === "entity"
266
308
  : reference.type === "chat" && reference.provider === "email"
267
309
  ? "email_thread"
268
310
  : reference.type;
269
- const runReader = (database, reader, wanted, body) => {
311
+ const runReader = (database, reader, wanted, body, today) => {
270
312
  const found = new Map();
271
313
  const width = wanted[0]?.keys.length ?? 0;
272
314
  const names = Array.from({ length: width }, (_, at) => `k${at + 1}`);
@@ -274,7 +316,10 @@ const runReader = (database, reader, wanted, body) => {
274
316
  const slice = wanted.slice(start, start + SLICE);
275
317
  const values = slice.map(() => `(${["?", ...names.map(() => "?")].join(", ")})`).join(", ");
276
318
  const sql = `WITH w(n, ${names.join(", ")}) AS (VALUES ${values}) ${reader.sql(body)}`;
277
- const parameters = slice.flatMap((one, at) => [start + at, ...one.keys]);
319
+ const parameters = [
320
+ ...slice.flatMap((one, at) => [start + at, ...one.keys]),
321
+ ...Array.from({ length: reader.dated ?? 0 }, () => today),
322
+ ];
278
323
  for (const row of database.prepare(sql).all(...parameters)) {
279
324
  const n = Number(row.n);
280
325
  if (found.has(n))
@@ -328,6 +373,16 @@ const titleOf = (kind, reference, found) => {
328
373
  case "deal":
329
374
  case "lead":
330
375
  return fieldsOf(found.title, dealLine);
376
+ case "product":
377
+ return fieldsOf(found.title, productLine);
378
+ case "contract":
379
+ return fieldsOf(found.title, contractLine);
380
+ case "subscription":
381
+ return fieldsOf(found.title, subscriptionLine);
382
+ case "wallet":
383
+ return fieldsOf(found.title, walletLine);
384
+ case "transaction":
385
+ return fieldsOf(found.title, transactionLine);
331
386
  case "folder":
332
387
  return reference.type === "folder" && reference.path !== null && found.title !== null
333
388
  ? `${found.title}/${reference.path}`
@@ -394,11 +449,8 @@ const parsed = (text) => {
394
449
  return undefined;
395
450
  }
396
451
  };
397
- /**
398
- * Every ref read back in one statement per kind present, keyed by the text passed and in its order. A bad ref is
399
- * `unknown` and a ref the store lacks is `unavailable`: one bad row must not fail a page of them.
400
- */
401
- export const refReadsOf = (database, texts, { excerpt = false } = {}) => {
452
+ export const refReadsOf = (database, texts, { excerpt = false, now = Date.now() } = {}) => {
453
+ const today = new Date(now).toISOString().slice(0, 10);
402
454
  const reads = new Map();
403
455
  const groups = new Map();
404
456
  for (const text of new Set(texts)) {
@@ -417,7 +469,7 @@ export const refReadsOf = (database, texts, { excerpt = false } = {}) => {
417
469
  while (pending.length > 0) {
418
470
  const [name, wanted] = pending.shift();
419
471
  const reader = READERS[name];
420
- const found = runReader(database, reader, wanted, excerpt);
472
+ const found = runReader(database, reader, wanted, excerpt, today);
421
473
  const fallback = FALLBACK[name];
422
474
  const missed = [];
423
475
  for (const [n, one] of wanted.entries()) {
@@ -0,0 +1,31 @@
1
+ import type { StoreContext } from "./open.js";
2
+ type Row = Record<string, unknown>;
3
+ declare const COUNTED: {
4
+ readonly confirmed: "np.review = 'confirmed' AND np.deleted_at IS NULL";
5
+ readonly pending: "np.deleted_at IS NULL AND (np.review = 'confirmed' OR (np.review = 'proposed' AND np.refund_of IS NULL))";
6
+ };
7
+ /**
8
+ * What is paid on `invoice`, net: payments' allocations minus their refunds'. Every sum of paid money in code reads
9
+ * this one fragment; the triggers repeat it for `confirmed`. `pending` also counts proposed payments, not proposed
10
+ * refunds. `including` counts one payment whatever its review, `excluding` leaves one out; each is an SQL expression,
11
+ * such as `?` or a column of the outer query.
12
+ */
13
+ export declare const netPaidSql: (invoice: string, { counted, including, excluding, }?: {
14
+ counted?: keyof typeof COUNTED;
15
+ including?: string;
16
+ excluding?: string;
17
+ }) => string;
18
+ /** A refund is a payment the other way with `refund_of`; these rules keep net paid at 0 or more for every payment. */
19
+ export declare const refundRulesOver: (context: StoreContext) => {
20
+ originalFor: (id: number, refund: {
21
+ direction: string;
22
+ currency: string;
23
+ amount: number;
24
+ }) => Row;
25
+ refundShare: (refund: Row, invoiceId: number, units: number) => void;
26
+ confirmable: (refund: Row) => void;
27
+ keepsRefunded: (payment: Row) => void;
28
+ keepsShare: (paymentId: number, invoiceId: number) => void;
29
+ keepsInvoice: (refund: Row, invoiceId: number) => void;
30
+ };
31
+ export {};
@@ -0,0 +1,112 @@
1
+ import { moneyLabel } from "../../domain/money.js";
2
+ import { refuse } from "./reviewed.js";
3
+ const COUNTED = {
4
+ confirmed: "np.review = 'confirmed' AND np.deleted_at IS NULL",
5
+ // A proposed refund promises nothing back yet, so it must not free room an import could then fill.
6
+ pending: "np.deleted_at IS NULL AND (np.review = 'confirmed' OR (np.review = 'proposed' AND np.refund_of IS NULL))",
7
+ };
8
+ /**
9
+ * What is paid on `invoice`, net: payments' allocations minus their refunds'. Every sum of paid money in code reads
10
+ * this one fragment; the triggers repeat it for `confirmed`. `pending` also counts proposed payments, not proposed
11
+ * refunds. `including` counts one payment whatever its review, `excluding` leaves one out; each is an SQL expression,
12
+ * such as `?` or a column of the outer query.
13
+ */
14
+ export const netPaidSql = (invoice, { counted = "confirmed", including, excluding, } = {}) => {
15
+ const which = including === undefined ? COUNTED[counted] : `((${COUNTED[counted]}) OR na.payment_id = ${including})`;
16
+ return ("(SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0) " +
17
+ "FROM payment_allocations na JOIN payments np ON np.id = na.payment_id " +
18
+ `WHERE na.invoice_id = ${invoice} AND ${which}${excluding === undefined ? "" : ` AND na.payment_id <> ${excluding}`})`);
19
+ };
20
+ /** A refund is a payment the other way with `refund_of`; these rules keep net paid at 0 or more for every payment. */
21
+ export const refundRulesOver = (context) => {
22
+ const { database } = context;
23
+ const one = (sql, ...params) => Number(database.prepare(sql).get(...params)?.n ?? 0);
24
+ const confirmedRefunds = (original, without) => one("SELECT coalesce(sum(amount), 0) AS n FROM payments WHERE refund_of = ? AND review = 'confirmed' " +
25
+ "AND deleted_at IS NULL AND id IS NOT ?", original, without ?? null);
26
+ const withinOriginal = (original, units, without) => {
27
+ const done = confirmedRefunds(Number(original.id), without);
28
+ const currency = String(original.currency);
29
+ if (done + units > Number(original.amount))
30
+ refuse(`payment:${original.id} is ${moneyLabel(Number(original.amount), currency)} and ` +
31
+ `${moneyLabel(done, currency)} of it is already refunded; ${moneyLabel(units, currency)} more is too much`, "finance.over-refund");
32
+ };
33
+ /** The payment a new refund names: live, not a refund itself, the other way and in the same currency. */
34
+ const originalFor = (id, refund) => {
35
+ const original = database.prepare("SELECT * FROM payments WHERE id = ?").get(id);
36
+ const ref = `payment:${id}`;
37
+ if (original.refund_of != null)
38
+ refuse(`${ref} is itself a refund; refund the payment it refunds`, "finance.refund");
39
+ if (original.review === "rejected" || original.deleted_at != null)
40
+ refuse(`${ref} is ${original.review === "rejected" ? "rejected" : "deleted"}; there is nothing to refund`, "finance.refund");
41
+ if (original.direction === refund.direction)
42
+ refuse(`a refund of ${ref} goes the other way: ${original.direction === "in" ? "out" : "in"}`, "finance.refund");
43
+ if (original.currency !== refund.currency)
44
+ refuse(`a refund of ${ref} is in its currency, ${String(original.currency)}`, "finance.refund");
45
+ withinOriginal(original, refund.amount);
46
+ return original;
47
+ };
48
+ /** A refund's share of an invoice: only one its payment is allocated to, and never more than that payment gave it. */
49
+ const refundShare = (refund, invoiceId, units) => {
50
+ const original = Number(refund.refund_of);
51
+ const given = database
52
+ .prepare("SELECT amount FROM payment_allocations WHERE payment_id = ? AND invoice_id = ?")
53
+ .get(original, invoiceId);
54
+ if (!given)
55
+ refuse(`payment:${refund.id} refunds payment:${original}, which is not allocated to invoice:${invoiceId}; ` +
56
+ "a refund goes back only where its payment went", "finance.refund");
57
+ const back = one("SELECT coalesce(sum(a.amount), 0) AS n FROM payment_allocations a JOIN payments r ON r.id = a.payment_id " +
58
+ "WHERE a.invoice_id = ? AND r.refund_of = ? AND ((r.review = 'confirmed' AND r.deleted_at IS NULL) OR r.id = ?)", invoiceId, original, Number(refund.id));
59
+ const currency = String(refund.currency);
60
+ if (back + units > Number(given?.amount))
61
+ refuse(`payment:${original} gave invoice:${invoiceId} ${moneyLabel(Number(given?.amount), currency)} and ` +
62
+ `${moneyLabel(back, currency)} of it is already refunded; ${moneyLabel(units, currency)} more is too much`, "finance.over-refund");
63
+ };
64
+ /** A refund is confirmed after its payment, and still within it and within each share it takes back. */
65
+ const confirmable = (refund) => {
66
+ const original = database.prepare("SELECT * FROM payments WHERE id = ?").get(Number(refund.refund_of));
67
+ if (original.review !== "confirmed" || original.deleted_at != null)
68
+ refuse(`payment:${refund.id} refunds payment:${original.id}, which is ${String(original.review)}; ` +
69
+ "confirm the payment first", "finance.refund");
70
+ withinOriginal(original, Number(refund.amount), Number(refund.id));
71
+ for (const share of database
72
+ .prepare("SELECT invoice_id, amount FROM payment_allocations WHERE payment_id = ?")
73
+ .all(Number(refund.id)))
74
+ refundShare(refund, Number(share.invoice_id), 0);
75
+ };
76
+ /**
77
+ * Taking a confirmed refund's share back gives that money to the invoice again: never beyond its total, given what
78
+ * the confirmed payments pay on it by then.
79
+ */
80
+ const keepsInvoice = (refund, invoiceId) => {
81
+ if (refund.review !== "confirmed" || refund.deleted_at != null)
82
+ return;
83
+ const row = database
84
+ .prepare(`SELECT i.total, i.currency, ${netPaidSql("i.id")} AS paid, a.amount FROM invoices i ` +
85
+ "JOIN payment_allocations a ON a.invoice_id = i.id AND a.payment_id = ? WHERE i.id = ?")
86
+ .get(Number(refund.id), invoiceId);
87
+ if (!row)
88
+ return;
89
+ const currency = String(row.currency);
90
+ if (Number(row.paid) + Number(row.amount) > Number(row.total))
91
+ refuse(`invoice:${invoiceId} totals ${moneyLabel(Number(row.total), currency)} and ${moneyLabel(Number(row.paid), currency)} ` +
92
+ `is paid on it; taking back payment:${refund.id}'s ${moneyLabel(Number(row.amount), currency)} would pay too much`, "finance.over-invoice");
93
+ };
94
+ /** A payment with a live refund stays: rejecting it would leave the refund taking back money never paid. */
95
+ const keepsRefunded = (payment) => {
96
+ const refund = database
97
+ .prepare("SELECT id FROM payments WHERE refund_of = ? AND review <> 'rejected' AND deleted_at IS NULL LIMIT 1")
98
+ .get(Number(payment.id));
99
+ if (refund)
100
+ refuse(`payment:${refund.id} refunds payment:${payment.id}; reject the refund first`, "finance.refunded");
101
+ };
102
+ /** A payment's share of an invoice stays while a refund of it takes part of that share back. */
103
+ const keepsShare = (paymentId, invoiceId) => {
104
+ const refund = database
105
+ .prepare("SELECT a.payment_id AS id FROM payment_allocations a JOIN payments r ON r.id = a.payment_id " +
106
+ "WHERE r.refund_of = ? AND a.invoice_id = ? LIMIT 1")
107
+ .get(paymentId, invoiceId);
108
+ if (refund)
109
+ refuse(`payment:${refund.id} refunds part of what payment:${paymentId} gave invoice:${invoiceId}; take that back first`, "finance.refunded");
110
+ };
111
+ return { originalFor, refundShare, confirmable, keepsRefunded, keepsShare, keepsInvoice };
112
+ };
@@ -0,0 +1,43 @@
1
+ import { type RelationKind, type Standing } from "../../domain/relations.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type KnowledgeRelation } from "./relation-proposals.js";
5
+ export interface RelationFilter {
6
+ kind?: RelationKind;
7
+ role?: string;
8
+ /** `proposed` holds the pending `relationship` proposals and the unconfirmed suggestions. */
9
+ standing?: Standing;
10
+ from?: string;
11
+ to?: string;
12
+ /** Either end; each row then says its `direction` and, read backwards, the kind's inverse label. */
13
+ about?: string;
14
+ /** Held at this time (UTC ms): started by then, or with no start, and not ended by then. */
15
+ at?: number;
16
+ /** Ended relationships are left out unless asked for, or unless `standing` is `ended`. */
17
+ includeEnded?: boolean;
18
+ /** A source's relationships only from these accounts; the owner's and agents' always. */
19
+ accounts?: AccountKey[];
20
+ /** No row with an end of these types, such as `deal` and `lead` a profile denies. */
21
+ deniedKinds?: string[];
22
+ limit?: number;
23
+ /** 1-based. */
24
+ page?: number;
25
+ }
26
+ export interface RelationListItem extends KnowledgeRelation {
27
+ /** `proposal`: a pending `relationship` proposal, decided through the review list by its `id`. */
28
+ source: "link" | "proposal";
29
+ /** With `about`: whether that ref is the relationship's `from` (`outgoing`) or its `to` (`incoming`). */
30
+ direction?: "outgoing" | "incoming";
31
+ /** With `about` and `incoming`: how it reads backwards (`manages` for `reports-to`); `null` when it has none. */
32
+ inverse?: string | null;
33
+ /** A stored role off the list its ends take, such as one written before the lists. */
34
+ custom: boolean;
35
+ }
36
+ export interface RelationList {
37
+ /** Relationships and pending relationship proposals, filtered and paged in one query (WC-CMD-20). */
38
+ listRelations(filter?: RelationFilter): Promise<{
39
+ items: RelationListItem[];
40
+ hasMore: boolean;
41
+ }>;
42
+ }
43
+ export declare const relationListOver: (context: StoreContext) => RelationList;
@@ -0,0 +1,133 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { inverseOf, notOverriddenSql, RELATION_KINDS, rolesOf, STANDINGS, } from "../../domain/relations.js";
3
+ import { linkKind } from "./link-kinds.js";
4
+ import { linkOf } from "./notes.js";
5
+ import { proposalOperationsOver } from "./proposed-actions.js";
6
+ import { relationOf } from "./relation-proposals.js";
7
+ import { thingOf } from "./things.js";
8
+ const KINDS = RELATION_KINDS.map(linkKind).join(", ");
9
+ const typeOfRef = (column) => `substr(${column}, 1, instr(${column}, ':') - 1)`;
10
+ const idOfRef = (column) => `CAST(substr(${column}, instr(${column}, ':') + 1) AS INTEGER)`;
11
+ export const relationListOver = (context) => {
12
+ const { database, now } = context;
13
+ const operations = proposalOperationsOver(context);
14
+ const thing = (ref, what) => {
15
+ const found = thingOf(database, ref);
16
+ if (!found)
17
+ throw new CliError("not_found", `${what} ${ref} is not in the local store`);
18
+ return found;
19
+ };
20
+ return {
21
+ listRelations: async (filter = {}) => {
22
+ const limit = filter.limit ?? 50;
23
+ const page = filter.page ?? 1;
24
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500 || !Number.isInteger(page) || page < 1)
25
+ throw new CliError("validation_error", "limit takes 1–500 and page starts at 1");
26
+ if (filter.standing !== undefined && !STANDINGS.includes(filter.standing))
27
+ throw new CliError("validation_error", `standing is one of ${STANDINGS.join(", ")}`);
28
+ const at = now();
29
+ const where = [];
30
+ const params = [];
31
+ const add = (sql, ...values) => {
32
+ where.push(sql);
33
+ params.push(...values);
34
+ };
35
+ const end = (side, ref) => {
36
+ const found = thing(ref, `the ${side} end`);
37
+ add(`r.${side}_type = ? AND r.${side}_id = ?`, found.type, found.id);
38
+ };
39
+ if (filter.kind !== undefined)
40
+ add("r.kind = ?", filter.kind);
41
+ if (filter.role !== undefined)
42
+ add("ifnull(r.role, '') = ?", filter.role.trim());
43
+ if (filter.from !== undefined)
44
+ end("from", filter.from);
45
+ if (filter.to !== undefined)
46
+ end("to", filter.to);
47
+ const about = filter.about === undefined ? undefined : thing(filter.about, "the reference");
48
+ if (about)
49
+ add("((r.from_type = ? AND r.from_id = ?) OR (r.to_type = ? AND r.to_id = ?))", about.type, about.id, about.type, about.id);
50
+ if (filter.at !== undefined)
51
+ add("(r.starts_at IS NULL OR r.starts_at <= ?) AND (r.ends_at IS NULL OR ? < r.ends_at)", filter.at, filter.at);
52
+ if (filter.standing !== undefined)
53
+ add("r.standing = ?", filter.standing);
54
+ else if (!filter.includeEnded)
55
+ add("r.standing <> 'ended'");
56
+ if (filter.accounts !== undefined) {
57
+ const ids = filter.accounts.flatMap((key) => {
58
+ const row = database
59
+ .prepare("SELECT id FROM accounts WHERE provider = ? AND external_id = ?")
60
+ .get(key.provider, key.account);
61
+ return row ? [Number(row.id)] : [];
62
+ });
63
+ add(`(r.account_id IS NULL OR r.account_id IN (${ids.map(() => "?").join(", ") || "NULL"}))`, ...ids);
64
+ }
65
+ if (filter.deniedKinds?.length) {
66
+ const list = filter.deniedKinds.map(() => "?").join(", ");
67
+ add(`r.from_type NOT IN (${list}) AND r.to_type NOT IN (${list})`, ...filter.deniedKinds, ...filter.deniedKinds);
68
+ }
69
+ const rows = database
70
+ .prepare(`SELECT r.source, r.id FROM (
71
+ SELECT 'link' AS source, id, from_type, from_id, to_type, to_id, kind, role, account_id, starts_at, ends_at,
72
+ created_at,
73
+ CASE WHEN ends_at IS NOT NULL AND ends_at <= ? THEN 'ended' WHEN confirmed = 1 THEN 'confirmed'
74
+ WHEN deleted_at IS NOT NULL THEN 'ended' WHEN account_id IS NOT NULL THEN 'reported'
75
+ ELSE 'proposed' END AS standing
76
+ FROM links WHERE kind IN (${KINDS}) AND to_id IS NOT NULL AND ${notOverriddenSql("links")}
77
+ UNION ALL
78
+ SELECT 'proposal', id, target_type, target_id, ${typeOfRef("json_extract(payload, '$.to')")},
79
+ ${idOfRef("json_extract(payload, '$.to')")}, json_extract(payload, '$.kind'),
80
+ json_extract(payload, '$.role'), NULL, json_extract(payload, '$.startsAt'),
81
+ json_extract(payload, '$.endsAt'), created_at, 'proposed'
82
+ FROM proposed_actions WHERE kind = 'relationship' AND status = 'proposed'
83
+ ) r${where.length ? ` WHERE ${where.join(" AND ")}` : ""}
84
+ ORDER BY r.standing = 'ended', r.created_at, r.source, r.id LIMIT ? OFFSET ?`)
85
+ .all(at, ...params, limit + 1, (page - 1) * limit);
86
+ const items = rows.slice(0, limit).map((row) => {
87
+ const item = row.source === "link" ? linkItem(Number(row.id), at) : proposalItem(String(row.id));
88
+ if (!about)
89
+ return item;
90
+ const from = thingOf(database, item.from);
91
+ const outgoing = from?.type === about.type && from.id === about.id;
92
+ return outgoing
93
+ ? { ...item, direction: "outgoing" }
94
+ : { ...item, direction: "incoming", inverse: inverseOf(item.kind) };
95
+ });
96
+ return { items, hasMore: rows.length > limit };
97
+ },
98
+ };
99
+ function custom(kind, from, to, role) {
100
+ const fromThing = thingOf(database, from);
101
+ const toThing = thingOf(database, to);
102
+ const roles = fromThing && toThing ? rolesOf(kind, fromThing.type, toThing.type) : undefined;
103
+ return role !== null && roles !== undefined && !roles.includes(role);
104
+ }
105
+ function linkItem(id, at) {
106
+ const relation = relationOf(linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(id)), at);
107
+ return { ...relation, source: "link", custom: custom(relation.kind, relation.from, relation.to, relation.role) };
108
+ }
109
+ function proposalItem(id) {
110
+ const action = operations.get(id);
111
+ const payload = action.payload;
112
+ const iso = (ms) => (ms === undefined ? null : new Date(ms).toISOString());
113
+ return {
114
+ id: action.id,
115
+ from: payload.from,
116
+ to: payload.to,
117
+ kind: payload.kind,
118
+ role: payload.role ?? null,
119
+ purpose: payload.purpose ?? null,
120
+ evidence: action.reason,
121
+ confirmed: false,
122
+ provenance: null,
123
+ confidenceCategory: "weak",
124
+ standing: "proposed",
125
+ position: payload.position ?? null,
126
+ startsAt: iso(payload.startsAt),
127
+ endsAt: iso(payload.endsAt),
128
+ createdAt: action.createdAt,
129
+ source: "proposal",
130
+ custom: custom(payload.kind, payload.from, payload.to, payload.role ?? null),
131
+ };
132
+ }
133
+ };
@@ -1,5 +1,5 @@
1
+ import { type RelationKind, type Standing } from "../../domain/relations.js";
1
2
  import { type Decider } from "../decisions.js";
2
- import type { RELATION_KINDS } from "./link-kinds.js";
3
3
  import type { Author } from "./memories.js";
4
4
  import { type Link } from "./notes.js";
5
5
  import type { StoreContext } from "./open.js";
@@ -10,7 +10,7 @@ export interface KnowledgeRelation {
10
10
  id: string;
11
11
  from: string;
12
12
  to: string;
13
- kind: (typeof RELATION_KINDS)[number];
13
+ kind: RelationKind;
14
14
  role: string | null;
15
15
  /** What a chat is for in the project, from the purposes memo's config lists; `null` means `work`. */
16
16
  purpose: string | null;
@@ -18,6 +18,13 @@ export interface KnowledgeRelation {
18
18
  confirmed: boolean;
19
19
  provenance: string | null;
20
20
  confidenceCategory: "owner-confirmed" | "weak";
21
+ /** Derived from the link: the owner's, a source's nobody confirmed, a suggestion, or one that ended. */
22
+ standing: Standing;
23
+ /** A job title beside the relationship, never its role. */
24
+ position: string | null;
25
+ /** When it held, as ISO times; `endsAt` exclusive; `null` when nobody said. */
26
+ startsAt: string | null;
27
+ endsAt: string | null;
21
28
  createdAt: string;
22
29
  }
23
30
  export interface RelateInput {
@@ -29,8 +36,12 @@ export interface RelateInput {
29
36
  evidence?: string;
30
37
  confirmed?: boolean;
31
38
  provenance?: string;
39
+ position?: string;
40
+ /** UTC ms; `endsAt` exclusive and after `startsAt`. */
41
+ startsAt?: number;
42
+ endsAt?: number;
32
43
  }
33
- export declare const relationOf: (link: Link) => KnowledgeRelation;
44
+ export declare const relationOf: (link: Link, now: number) => KnowledgeRelation;
34
45
  /** `relationship` proposals in `proposed_actions`: an agent's or a rule's, and the rejected ones a scan skips. */
35
46
  export declare const relationProposalsOver: (context: StoreContext) => {
36
47
  /**
@@ -40,8 +51,10 @@ export declare const relationProposalsOver: (context: StoreContext) => {
40
51
  state: (paired: () => {
41
52
  from: Thing;
42
53
  existing: Row | undefined;
43
- }, { to, kind }: {
44
- to: string;
54
+ ends: {
55
+ to: string;
56
+ };
57
+ }, { kind }: {
45
58
  kind: string;
46
59
  }) => {
47
60
  linked: boolean;
@@ -56,6 +69,9 @@ export declare const relationProposalsOver: (context: StoreContext) => {
56
69
  kind: string;
57
70
  role?: string;
58
71
  purpose?: string;
72
+ position?: string;
73
+ startsAt?: number;
74
+ endsAt?: number;
59
75
  evidence?: string[];
60
76
  reason?: string;
61
77
  } & Scored, by: Exclude<Author, "owner">) => ProposedAction;
@@ -88,11 +104,17 @@ export interface Scored {
88
104
  why: string;
89
105
  }[];
90
106
  }
91
- /** A relationship's role and purpose to set; `null` clears one. */
107
+ /** What to set on a relationship; `null` clears one. Times are UTC ms, `endsAt` exclusive. */
92
108
  export interface RelationUpdate {
93
109
  role?: string | null;
94
110
  purpose?: string | null;
111
+ position?: string | null;
112
+ startsAt?: number | null;
113
+ endsAt?: number | null;
95
114
  }
115
+ /** A relationship ends after it starts. */
116
+ export declare const spanOf: (startsAt: number | null | undefined, endsAt: number | null | undefined) => void;
117
+ export declare const positionOf: (position: string) => string;
96
118
  export interface LinkDecision {
97
119
  confirm: boolean;
98
120
  by: Decider;