@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
@@ -0,0 +1,294 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { intervalOf, SUBSCRIPTION_STATUSES, subscriptionLine, } from "../../domain/business.js";
3
+ import { FINANCE_REVIEWS, INVOICE_DIRECTIONS } from "../../domain/finance.js";
4
+ import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
5
+ import { ownerPerson, proposedBySql } from "./actors.js";
6
+ import { authorOf, projectId } from "./memories.js";
7
+ import { requiredThing } from "./notes.js";
8
+ import { iso, isoDate, limitOf, oneOf, reasonOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
9
+ import { write } from "./transaction.js";
10
+ const SUBSCRIPTIONS = "SELECT s.*, b.name AS author_name, b.kind AS author_kind FROM subscriptions s " +
11
+ "LEFT JOIN bots b ON s.author_type = 'bot' AND b.id = s.author_id";
12
+ const PRICES = "SELECT p.*, b.name AS author_name, b.kind AS author_kind FROM subscription_prices p " +
13
+ "LEFT JOIN bots b ON p.author_type = 'bot' AND b.id = p.author_id";
14
+ const PRICE_REF = /^subscription_price:([1-9]\d{0,15})$/;
15
+ export const subscriptionOperationsOver = (context) => {
16
+ const { database, now } = context;
17
+ const { partyOf, partyThing, reviewedOf, written, keepEvidence, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
18
+ const today = () => new Date(now()).toISOString().slice(0, 10);
19
+ const priceOf = (row) => {
20
+ const currency = String(row.currency);
21
+ const amount = formatDecimal(Number(row.amount), scaleOf(currency));
22
+ const subscription = `subscription:${row.subscription_id}`;
23
+ return {
24
+ id: String(row.id),
25
+ ref: `subscription_price:${row.id}`,
26
+ title: `Price of ${subscription}: ${amount} ${currency} from ${row.effective_from}`,
27
+ subscription,
28
+ amount,
29
+ currency,
30
+ effectiveFrom: String(row.effective_from),
31
+ review: row.review,
32
+ author: authorOf(row),
33
+ reason: reasonOf(row.metadata),
34
+ project: null,
35
+ createdAt: iso(row.created_at),
36
+ };
37
+ };
38
+ const pricesOf = (id) => database.prepare(`${PRICES} WHERE p.subscription_id = ? ORDER BY p.effective_from, p.id`).all(id).map(priceOf);
39
+ const subscriptionOf = (row) => {
40
+ const interval = { count: Number(row.interval_count), unit: row.interval_unit };
41
+ const current = database
42
+ .prepare(`${PRICES} WHERE p.subscription_id = ? AND p.review = 'confirmed' AND p.effective_from <= ? ` +
43
+ "ORDER BY p.effective_from DESC LIMIT 1")
44
+ .get(Number(row.id), today());
45
+ const currentPrice = current ? priceOf(current) : null;
46
+ const fields = {
47
+ name: String(row.name),
48
+ interval,
49
+ price: current ? Number(current.amount) : null,
50
+ currency: currentPrice?.currency ?? null,
51
+ status: row.status,
52
+ review: row.review,
53
+ };
54
+ return {
55
+ id: String(row.id),
56
+ ref: `subscription:${row.id}`,
57
+ title: `Subscription ${subscriptionLine(fields)}`,
58
+ name: fields.name,
59
+ direction: row.direction,
60
+ supplier: partyOf(row.supplier_type, row.supplier_id),
61
+ customer: partyOf(row.customer_type, row.customer_id),
62
+ product: row.catalog_item_id == null ? null : `product:${row.catalog_item_id}`,
63
+ contract: row.contract_id == null ? null : `contract:${row.contract_id}`,
64
+ status: fields.status,
65
+ interval,
66
+ startDate: String(row.start_date),
67
+ trialEndDate: row.trial_end_date == null ? null : String(row.trial_end_date),
68
+ nextRenewalDate: row.next_renewal_date == null ? null : String(row.next_renewal_date),
69
+ cancelledDate: row.cancelled_date == null ? null : String(row.cancelled_date),
70
+ endDate: row.end_date == null ? null : String(row.end_date),
71
+ currentPrice,
72
+ ...reviewedOf(row, "subscription"),
73
+ };
74
+ };
75
+ const rowOf = (reference) => {
76
+ const thing = requiredThing(database, reference.includes(":") ? reference : `subscription:${reference}`, "the subscription");
77
+ if (thing.type !== "subscription")
78
+ return refuse(`${reference} is not a subscription`, "subscription.ref");
79
+ return database.prepare(`${SUBSCRIPTIONS} WHERE s.id = ?`).get(thing.id);
80
+ };
81
+ const priceRowOf = (reference) => {
82
+ const match = PRICE_REF.exec(reference.trim());
83
+ const row = match ? database.prepare(`${PRICES} WHERE p.id = ?`).get(Number(match[1])) : undefined;
84
+ if (!row)
85
+ throw new CliError("not_found", `no subscription price ${reference}`, { reason: "subscription.no-price" });
86
+ return row;
87
+ };
88
+ const detailOf = (reference) => {
89
+ const row = rowOf(reference);
90
+ return { ...subscriptionOf(row), prices: pricesOf(Number(row.id)) };
91
+ };
92
+ /** The columns a subscription's fields set, checked; a field left out keeps `base`'s value. Runs in a write. */
93
+ const columnsOf = (fields, base) => {
94
+ const kept = (given, column, read) => given === undefined ? (base[column] ?? null) : read(given);
95
+ const day = (given, column, what) => kept(given, column, (value) => isoDate(value, what));
96
+ const direction = kept(fields.direction, "direction", (value) => oneOf(value, INVOICE_DIRECTIONS, "a subscription's direction"));
97
+ const interval = fields.every === undefined
98
+ ? { count: Number(base.interval_count), unit: base.interval_unit }
99
+ : intervalOf(fields.every);
100
+ const start = day(fields.startDate, "start_date", "a subscription's start") ??
101
+ refuse("a subscription starts on a day", "subscription.field");
102
+ const trial = day(fields.trialEndDate, "trial_end_date", "a trial's end");
103
+ const status = kept(fields.status, "status", (value) => oneOf(value, SUBSCRIPTION_STATUSES, "a subscription's status"));
104
+ const settled = status ?? (trial === null ? "active" : "trial");
105
+ const cancelled = fields.cancelledDate === undefined && settled === "cancelled" && base.cancelled_date == null
106
+ ? today()
107
+ : day(fields.cancelledDate, "cancelled_date", "the day it was cancelled");
108
+ const end = day(fields.endDate, "end_date", "a subscription's end");
109
+ if (trial !== null && trial < start)
110
+ refuse("a trial ends on or after the subscription starts", "subscription.field");
111
+ if (end !== null && end < start)
112
+ refuse("a subscription ends on or after it starts", "subscription.field");
113
+ if (settled === "trial" && trial === null)
114
+ refuse("a subscription in trial has a trial end", "subscription.field");
115
+ if (settled === "cancelled" && cancelled === null)
116
+ refuse("a cancelled subscription has the day it was cancelled", "subscription.field");
117
+ const owner = ownerPerson(database);
118
+ const party = (given, type, id, ownerSide, what) => given !== undefined
119
+ ? partyThing(given, what)
120
+ : base[type] != null
121
+ ? { type: String(base[type]), id: Number(base[id]) }
122
+ : ownerSide
123
+ ? owner
124
+ : refuse("a subscription names its supplier and its customer, a person: or organization:", "subscription.field");
125
+ const supplier = party(fields.supplier, "supplier_type", "supplier_id", direction === "receivable", "the supplier");
126
+ const customer = party(fields.customer, "customer_type", "customer_id", direction === "payable", "the customer");
127
+ const linked = (given, type, column) => given === undefined
128
+ ? (base[column] ?? null)
129
+ : given === null
130
+ ? null
131
+ : linkedId(given, type, "subscription.ref");
132
+ const product = linked(fields.product, "product", "catalog_item_id");
133
+ const productName = product === null
134
+ ? null
135
+ : String(database.prepare("SELECT name FROM catalog_items WHERE id = ?").get(product)?.name);
136
+ const name = kept(fields.name, "name", (value) => text(value, "a subscription's name", 200)) ??
137
+ productName ??
138
+ refuse("a subscription needs a name, or a product to take it from", "subscription.field");
139
+ return {
140
+ name: String(name),
141
+ direction,
142
+ supplier_type: supplier.type,
143
+ supplier_id: supplier.id,
144
+ customer_type: customer.type,
145
+ customer_id: customer.id,
146
+ catalog_item_id: product,
147
+ contract_id: linked(fields.contract, "contract", "contract_id"),
148
+ status: settled,
149
+ interval_count: interval.count,
150
+ interval_unit: interval.unit,
151
+ start_date: start,
152
+ trial_end_date: trial,
153
+ next_renewal_date: day(fields.nextRenewalDate, "next_renewal_date", "the next renewal"),
154
+ cancelled_date: cancelled,
155
+ end_date: end,
156
+ };
157
+ };
158
+ const insertPrice = (subscriptionId, price, start, by) => {
159
+ const currency = currencyOf(price.currency);
160
+ const amount = minorUnits(price.amount, currency, "a subscription's price");
161
+ const from = isoDate(price.effectiveFrom, "the price's first day") ?? start;
162
+ if (database
163
+ .prepare("SELECT 1 FROM subscription_prices WHERE subscription_id = ? AND effective_from = ? AND review <> 'rejected'")
164
+ .get(subscriptionId, from))
165
+ refuse(`subscription:${subscriptionId} already has a price from ${from}; reject it to correct it`, "subscription.price");
166
+ const at = now();
167
+ return Number(database
168
+ .prepare("INSERT INTO subscription_prices (subscription_id, amount, currency, effective_from, review, author_type, " +
169
+ "author_id, model, confirmed_by_type, confirmed_by_id, source, metadata, created_at, updated_at) " +
170
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
171
+ .get(subscriptionId, amount, currency, from, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
172
+ };
173
+ const decidePrice = (reference, by, reason, confirm) => {
174
+ const price = priceRowOf(reference);
175
+ const parent = rowOf(`subscription:${price.subscription_id}`);
176
+ decideRow("subscription_price", price, { by, reason, confirm }, {
177
+ before: () => {
178
+ if (confirm && parent.review !== "confirmed")
179
+ refuse(`subscription:${parent.id} is ${String(parent.review)}; confirm the subscription before its price`, "subscription.price");
180
+ },
181
+ });
182
+ return detailOf(`subscription:${parent.id}`);
183
+ };
184
+ const decide = (reference, by, reason, confirm) => {
185
+ if (PRICE_REF.test(reference.trim()))
186
+ return decidePrice(reference, by, reason, confirm);
187
+ const row = rowOf(reference);
188
+ decideRow("subscription", row, { by, reason, confirm }, {
189
+ // The prices still proposed came with the subscription: they go with its decision.
190
+ after: (confirmer) => database
191
+ .prepare("UPDATE subscription_prices SET review = ?, confirmed_by_type = ?, confirmed_by_id = ?, updated_at = ? " +
192
+ "WHERE subscription_id = ? AND review = 'proposed'")
193
+ .run(confirmer ? "confirmed" : "rejected", confirmer?.type ?? null, confirmer?.id ?? null, now(), Number(row.id)),
194
+ });
195
+ return detailOf(`subscription:${row.id}`);
196
+ };
197
+ const writable = (row, by) => {
198
+ const ref = `subscription:${row.id}`;
199
+ if (row.review === "rejected" || row.deleted_at != null)
200
+ refuse(`${ref} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "subscription.ref");
201
+ mayChangeParts(row, by, `only the owner changes ${ref}; a bot changes only a subscription it proposed that is still proposed`);
202
+ };
203
+ return {
204
+ add: (input) => {
205
+ if (input.prices !== undefined && (!Array.isArray(input.prices) || input.prices.length > 100))
206
+ refuse("a subscription takes at most 100 prices", "subscription.field");
207
+ const id = write(database, () => {
208
+ const columns = columnsOf(input, {});
209
+ const by = written(input);
210
+ const at = now();
211
+ const made = Number(database
212
+ .prepare("INSERT INTO subscriptions (name, direction, supplier_type, supplier_id, customer_type, customer_id, " +
213
+ "catalog_item_id, contract_id, project_id, status, interval_count, interval_unit, start_date, trial_end_date, " +
214
+ "next_renewal_date, cancelled_date, end_date, review, author_type, author_id, model, confirmed_by_type, " +
215
+ "confirmed_by_id, source, metadata, created_at, updated_at) " +
216
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
217
+ .get(columns.name, columns.direction, columns.supplier_type, columns.supplier_id, columns.customer_type, columns.customer_id, columns.catalog_item_id, columns.contract_id, by.project, columns.status, columns.interval_count, columns.interval_unit, columns.start_date, columns.trial_end_date, columns.next_renewal_date, columns.cancelled_date, columns.end_date, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
218
+ for (const price of input.prices ?? [])
219
+ insertPrice(made, price, columns.start_date, by);
220
+ keepEvidence("subscription", made, by);
221
+ return made;
222
+ });
223
+ return detailOf(`subscription:${id}`);
224
+ },
225
+ get: (reference) => detailOf(reference),
226
+ list: (filter = {}) => {
227
+ const project = filter.project === undefined ? null : projectId(database, filter.project);
228
+ const supplier = partyThing(filter.supplier, "the supplier");
229
+ const customer = partyThing(filter.customer, "the customer");
230
+ const status = filter.status === undefined ? null : oneOf(filter.status, SUBSCRIPTION_STATUSES, "a status");
231
+ const direction = filter.direction === undefined ? null : oneOf(filter.direction, INVOICE_DIRECTIONS, "a direction");
232
+ const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
233
+ const renews = isoDate(filter.renewsBy, "the last renewal day");
234
+ const by = proposedBySql("s.author_type", "s.author_id", filter.proposedBy);
235
+ return database
236
+ .prepare(`${SUBSCRIPTIONS} WHERE s.deleted_at IS NULL AND (? IS NULL OR s.status = ?) AND (? IS NULL OR s.direction = ?) ` +
237
+ "AND (? IS NULL OR s.review = ?) AND (? IS NULL OR s.project_id = ?) " +
238
+ "AND (? IS NULL OR (s.supplier_type = ? AND s.supplier_id = ?)) " +
239
+ "AND (? IS NULL OR (s.customer_type = ? AND s.customer_id = ?)) " +
240
+ `AND (? IS NULL OR s.next_renewal_date <= ?) AND ${by.sql} ORDER BY s.created_at DESC, s.id DESC LIMIT ?`)
241
+ .all(status, status, direction, direction, review, review, project, project, supplier?.type ?? null, supplier?.type ?? null, supplier?.id ?? null, customer?.type ?? null, customer?.type ?? null, customer?.id ?? null, renews, renews, ...by.params, limitOf(filter.limit))
242
+ .map(subscriptionOf);
243
+ },
244
+ update: (reference, { by, ...fields }) => {
245
+ const row = rowOf(reference);
246
+ writable(row, by);
247
+ write(database, () => {
248
+ const columns = columnsOf(fields, row);
249
+ database
250
+ .prepare("UPDATE subscriptions SET name = ?, direction = ?, supplier_type = ?, supplier_id = ?, customer_type = ?, " +
251
+ "customer_id = ?, catalog_item_id = ?, contract_id = ?, status = ?, interval_count = ?, interval_unit = ?, " +
252
+ "start_date = ?, trial_end_date = ?, next_renewal_date = ?, cancelled_date = ?, end_date = ?, updated_at = ? " +
253
+ "WHERE id = ?")
254
+ .run(columns.name, columns.direction, columns.supplier_type, columns.supplier_id, columns.customer_type, columns.customer_id, columns.catalog_item_id, columns.contract_id, columns.status, columns.interval_count, columns.interval_unit, columns.start_date, columns.trial_end_date, columns.next_renewal_date, columns.cancelled_date, columns.end_date, now(), Number(row.id));
255
+ });
256
+ return detailOf(`subscription:${row.id}`);
257
+ },
258
+ addPrice: (reference, input) => {
259
+ const row = rowOf(reference);
260
+ if (row.review === "rejected" || row.deleted_at != null)
261
+ refuse(`subscription:${row.id} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "subscription.ref");
262
+ // A price on a proposed subscription is part of that proposal, so only its author or the owner adds one.
263
+ if (row.review === "proposed")
264
+ writable(row, input.by);
265
+ const id = write(database, () => insertPrice(Number(row.id), input, String(row.start_date), written(input)));
266
+ return priceOf(database.prepare(`${PRICES} WHERE p.id = ?`).get(id));
267
+ },
268
+ confirm: (reference, by, reason) => decide(reference, by, reason, true),
269
+ reject: (reference, by, reason) => decide(reference, by, reason, false),
270
+ price: (reference) => priceOf(priceRowOf(reference)),
271
+ prices: (filter = {}) => {
272
+ const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
273
+ const by = proposedBySql("p.author_type", "p.author_id", filter.proposedBy);
274
+ return database
275
+ .prepare(`${PRICES} WHERE (? IS NULL OR p.review = ?) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
276
+ .all(review, review, ...by.params, limitOf(filter.limit))
277
+ .map(priceOf);
278
+ },
279
+ };
280
+ };
281
+ export const subscriptionsStoreOver = (context) => {
282
+ const operations = subscriptionOperationsOver(context);
283
+ return {
284
+ add: async (input) => operations.add(input),
285
+ get: async (reference) => operations.get(reference),
286
+ list: async (filter) => operations.list(filter),
287
+ update: async (reference, input) => operations.update(reference, input),
288
+ addPrice: async (reference, input) => operations.addPrice(reference, input),
289
+ confirm: async (reference, by, reason) => operations.confirm(reference, by, reason),
290
+ reject: async (reference, by, reason) => operations.reject(reference, by, reason),
291
+ price: async (reference) => operations.price(reference),
292
+ prices: async (filter) => operations.prices(filter),
293
+ };
294
+ };
@@ -0,0 +1,3 @@
1
+ /** Trimmed text of 1–`max` characters, or 0–`max` when empty is allowed. */
2
+ export declare const textOf: (text: string, what: string, max?: number, allowEmpty?: boolean) => string;
3
+ export declare const oneOf: <T extends string>(value: string, allowed: readonly T[], what: string) => T;
@@ -0,0 +1,13 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** Trimmed text of 1–`max` characters, or 0–`max` when empty is allowed. */
3
+ export const textOf = (text, what, max = 100_000, allowEmpty = false) => {
4
+ const value = text.trim();
5
+ if ((!value && !allowEmpty) || value.length > max)
6
+ throw new CliError("validation_error", `${what} takes ${allowEmpty ? 0 : 1}–${max} characters`);
7
+ return value;
8
+ };
9
+ export const oneOf = (value, allowed, what) => {
10
+ if (!allowed.includes(value))
11
+ throw new CliError("validation_error", `${what} is one of ${allowed.join(", ")}`);
12
+ return value;
13
+ };
@@ -1,5 +1,6 @@
1
1
  import { formatLocator } from "../../domain/locator.js";
2
2
  import { filesAccountSql } from "../../domain/providers.js";
3
+ import { RECORD_TYPES } from "../../domain/record-types.js";
3
4
  import { formatReference, parseReference } from "../../domain/references.js";
4
5
  import { formatMeetingReference } from "../../meetings/index.js";
5
6
  import { ENTITY_TABLES, isEntityType } from "./entity-types.js";
@@ -7,22 +8,14 @@ import { ENTITY_TABLES, isEntityType } from "./entity-types.js";
7
8
  export const storedThing = (type, id) => ({ type: String(type), id: Number(id) });
8
9
  /** Types a simple reference names by id, and whether a row can be marked gone. */
9
10
  const REFERABLE = {
11
+ ...Object.fromEntries(Object.entries(RECORD_TYPES).map(([type, { tombstone }]) => [type, { tombstone }])),
10
12
  note: { tombstone: true },
11
13
  document: { tombstone: true },
12
- person: { tombstone: false },
13
- organization: { tombstone: true },
14
- project: { tombstone: true },
15
14
  task: { tombstone: true },
16
15
  memory: { tombstone: true },
17
16
  fact: { tombstone: true },
18
17
  bot: { tombstone: false },
19
18
  event: { tombstone: true },
20
- invoice: { tombstone: true },
21
- payment: { tombstone: true },
22
- order: { tombstone: true },
23
- deal: { tombstone: true },
24
- lead: { tombstone: true },
25
- pipeline: { tombstone: false },
26
19
  message: { tombstone: true },
27
20
  email: { tombstone: true },
28
21
  email_thread: { tombstone: true },
@@ -16,5 +16,20 @@ export declare const write: <T>(database: CacheDatabase, body: () => T, { before
16
16
  * process's `write` a gap of microseconds, and it misses that gap until its 5 s wait runs out.
17
17
  */
18
18
  export declare const writeBatch: <T>(database: CacheDatabase, body: () => T) => T;
19
+ /** Whether a dry run holds a connection of this process now. */
20
+ export declare const rehearsing: () => boolean;
21
+ /** Calls `call` outside any dry run: a statement it runs is refused while one holds the connection. */
22
+ export declare const outsideRehearsal: <T>(call: () => T) => T;
23
+ /**
24
+ * Async work in one write transaction that is always rolled back: a dry run over a stream, whose later chunks must see
25
+ * what earlier ones would write. Writes inside become savepoints. It holds the write lock for the whole run, and any
26
+ * statement from outside its own async work meanwhile is refused (`store.dry-run`): on the `CacheDatabase` seam and on
27
+ * the SQLite client under it, which Drizzle queries go through. Not a second connection: this process's other writers
28
+ * would then wait on the lock with the event loop blocked, and the dry run could not go on meanwhile.
29
+ */
30
+ export declare const rehearse: <T>({ database, client }: {
31
+ database: CacheDatabase;
32
+ client?: unknown;
33
+ }, body: () => Promise<T>) => Promise<T>;
19
34
  /** Several queries that must see one state of the file. Never drains: that is the outer write's work, or nobody's. */
20
35
  export declare const read: <T>(database: CacheDatabase, body: () => T) => T;
@@ -1,7 +1,10 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { CliError } from "@wirecat/cli-base";
1
3
  import { sqliteCode } from "../../errors/failures.js";
2
4
  import { drainInvolvementQueue } from "./involvement-queue.js";
3
5
  import { drainMentions } from "./mention-drain.js";
4
6
  import { drainStems, stemmerCache } from "./stems.js";
7
+ const rehearsal = new AsyncLocalStorage();
5
8
  const SQLITE_BUSY = 5;
6
9
  const pause = new Int32Array(new SharedArrayBuffer(4));
7
10
  export const isBusy = (error) => sqliteCode(error) === SQLITE_BUSY;
@@ -92,6 +95,60 @@ const transact = (database, body, drain, beforeCommit) => {
92
95
  connection.depth -= 1;
93
96
  }
94
97
  };
98
+ let rehearsals = 0;
99
+ /** Whether a dry run holds a connection of this process now. */
100
+ export const rehearsing = () => rehearsals > 0;
101
+ /** Calls `call` outside any dry run: a statement it runs is refused while one holds the connection. */
102
+ export const outsideRehearsal = (call) => rehearsal.exit(call);
103
+ /**
104
+ * Async work in one write transaction that is always rolled back: a dry run over a stream, whose later chunks must see
105
+ * what earlier ones would write. Writes inside become savepoints. It holds the write lock for the whole run, and any
106
+ * statement from outside its own async work meanwhile is refused (`store.dry-run`): on the `CacheDatabase` seam and on
107
+ * the SQLite client under it, which Drizzle queries go through. Not a second connection: this process's other writers
108
+ * would then wait on the lock with the event loop blocked, and the dry run could not go on meanwhile.
109
+ */
110
+ export const rehearse = async ({ database, client }, body) => {
111
+ const connection = connectionOf(database);
112
+ if (connection.depth > 0 || connection.reading)
113
+ throw new Error("a rehearsal starts outside any transaction");
114
+ // Anything else on the connection would land inside the dry run: its write rolled back with it, its read seeing
115
+ // rows that never exist.
116
+ const kept = [];
117
+ const guard = (target, names) => {
118
+ for (const name of names) {
119
+ const call = target[name];
120
+ if (typeof call !== "function")
121
+ continue;
122
+ kept.push([target, name, call, Object.hasOwn(target, name)]);
123
+ target[name] = function (...args) {
124
+ if (rehearsal.getStore() !== database)
125
+ throw new CliError("conflict", "a dry run of an import holds the store; try again once it ends", {
126
+ reason: "store.dry-run",
127
+ });
128
+ return call.apply(this, args);
129
+ };
130
+ }
131
+ };
132
+ beginImmediate(database);
133
+ connection.depth += 1;
134
+ guard(database, ["prepare", "exec"]);
135
+ if (client !== undefined && client !== null)
136
+ guard(client, ["prepare", "exec", "query", "run"]);
137
+ rehearsals += 1;
138
+ try {
139
+ return await rehearsal.run(database, body);
140
+ }
141
+ finally {
142
+ rehearsals -= 1;
143
+ for (const [target, name, call, own] of kept.reverse())
144
+ if (own)
145
+ target[name] = call;
146
+ else
147
+ delete target[name];
148
+ connection.depth -= 1;
149
+ database.exec("ROLLBACK");
150
+ }
151
+ };
95
152
  /** Several queries that must see one state of the file. Never drains: that is the outer write's work, or nobody's. */
96
153
  export const read = (database, body) => {
97
154
  const connection = connectionOf(database);
@@ -0,0 +1,88 @@
1
+ import { type WalletKind } from "../../domain/business.js";
2
+ import { type Money } from "../../domain/money.js";
3
+ import { type Author } from "./memories.js";
4
+ import type { StoreContext } from "./open.js";
5
+ import { type AuthorInfo, type Party } from "./reviewed.js";
6
+ export interface Wallet {
7
+ id: string;
8
+ ref: string;
9
+ /** One line, as a list prints it. */
10
+ title: string;
11
+ name: string;
12
+ kind: WalletKind;
13
+ currency: string;
14
+ institution: string | null;
15
+ /** The last 4 characters of its number. */
16
+ numberHint: string | null;
17
+ /** Whose it is, when not the owner's. */
18
+ holder: Party | null;
19
+ /** Signed; both `null` until the owner sets them. */
20
+ openingBalance: string | null;
21
+ openingDate: string | null;
22
+ closedDate: string | null;
23
+ /**
24
+ * The opening balance plus confirmed, booked transactions after the opening day and up to `until`: computed each
25
+ * time, never stored.
26
+ */
27
+ balance: Money;
28
+ /** `YYYY-MM-DD`: the last day the balance counts. */
29
+ until: string;
30
+ /** Pending or proposed transactions up to `until`, signed: shown beside the balance, never in it. */
31
+ pending: Money;
32
+ author: AuthorInfo;
33
+ model: string | null;
34
+ source: string;
35
+ createdAt: string;
36
+ updatedAt: string;
37
+ }
38
+ export interface WalletInput {
39
+ /** The owner and an agent write alike, except the opening balance: only the owner sets it. */
40
+ by: Author;
41
+ name: string;
42
+ /** One currency per wallet: a bank account in two currencies is two wallets. */
43
+ currency: string;
44
+ /** `bank` when left out. */
45
+ kind?: WalletKind;
46
+ institution?: string;
47
+ /** The last 4 characters of the number; a whole IBAN or card number is refused. */
48
+ numberHint?: string;
49
+ holder?: string;
50
+ /** A signed decimal string, with its day; give both or neither. */
51
+ openingBalance?: string;
52
+ openingDate?: string;
53
+ source?: string;
54
+ }
55
+ export interface WalletUpdate {
56
+ by: Author;
57
+ name?: string;
58
+ institution?: string | null;
59
+ numberHint?: string | null;
60
+ closedDate?: string | null;
61
+ /** The owner's only. Give both, or `null` for both to clear them. */
62
+ openingBalance?: string | null;
63
+ openingDate?: string | null;
64
+ }
65
+ export interface WalletFilter {
66
+ kind?: WalletKind;
67
+ currency?: string;
68
+ /** `true` only closed ones, `false` only open ones; both when left out. */
69
+ closed?: boolean;
70
+ /** 1–500, 100 by default; by name. */
71
+ limit?: number;
72
+ }
73
+ /** Bank accounts, cards, cash and wallets (`wallet:<id>`), written directly; their balances are computed. */
74
+ export interface WalletsStore {
75
+ add(input: WalletInput): Promise<Wallet>;
76
+ /** `until` is `YYYY-MM-DD`, today when left out. */
77
+ get(reference: string, options?: {
78
+ until?: string;
79
+ }): Promise<Wallet>;
80
+ list(filter?: WalletFilter): Promise<Wallet[]>;
81
+ update(reference: string, input: WalletUpdate): Promise<Wallet>;
82
+ }
83
+ type WalletOperations = {
84
+ [K in keyof WalletsStore]: WalletsStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
85
+ };
86
+ export declare const walletOperationsOver: (context: StoreContext) => WalletOperations;
87
+ export declare const walletsStoreOver: (context: StoreContext) => WalletsStore;
88
+ export {};