@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,132 @@
1
+ import { type TransactionStatus } from "../../domain/business.js";
2
+ import { type FinanceReview, type MoneyDirection } from "../../domain/finance.js";
3
+ import { type Money } from "../../domain/money.js";
4
+ import type { Decider } from "../decisions.js";
5
+ import { type ProposedByFilter } from "./actors.js";
6
+ import { type Author } from "./memories.js";
7
+ import type { StoreContext } from "./open.js";
8
+ import { type Party, type Reviewed, type Written } from "./reviewed.js";
9
+ export interface TransactionSplit {
10
+ position: number;
11
+ category: string;
12
+ amount: string;
13
+ project: string | null;
14
+ note: string | null;
15
+ }
16
+ export interface MoneyTransaction extends Reviewed {
17
+ id: string;
18
+ ref: string;
19
+ /** One line, as a list or the review inbox prints it. */
20
+ title: string;
21
+ wallet: string;
22
+ walletName: string;
23
+ direction: MoneyDirection;
24
+ amount: string;
25
+ currency: string;
26
+ status: TransactionStatus;
27
+ /** `YYYY-MM-DD`: the day the statement shows. */
28
+ statementDate: string;
29
+ /** Set once booked. */
30
+ bookedDate: string | null;
31
+ description: string | null;
32
+ /** As the statement names the other side. */
33
+ counterpartyName: string | null;
34
+ counterparty: Party | null;
35
+ reference: string | null;
36
+ /** The payment it settles, of the same currency, direction and amount. */
37
+ payment: string | null;
38
+ splits: TransactionSplit[];
39
+ /** What no split categorizes. */
40
+ uncategorized: string;
41
+ }
42
+ export interface SplitInput {
43
+ /** A decimal string in the transaction's currency. */
44
+ amount: string;
45
+ category: string;
46
+ project?: string;
47
+ note?: string;
48
+ }
49
+ export interface TransactionInput extends Written {
50
+ wallet: string;
51
+ direction: MoneyDirection;
52
+ /** A decimal string above 0, in the wallet's currency. */
53
+ amount: string;
54
+ /** The wallet's; refused when it differs. */
55
+ currency?: string;
56
+ /** `booked` when left out. */
57
+ status?: TransactionStatus;
58
+ statementDate: string;
59
+ /** A booked transaction's day; its `statementDate` when left out. */
60
+ bookedDate?: string;
61
+ description?: string;
62
+ counterpartyName?: string;
63
+ counterparty?: string;
64
+ reference?: string;
65
+ payment?: string;
66
+ splits?: SplitInput[];
67
+ }
68
+ /** The owner changes any transaction; a bot only one it proposed that is still proposed. */
69
+ export interface TransactionUpdate {
70
+ by: Author;
71
+ direction?: MoneyDirection;
72
+ /** Refused below its splits, or when a linked payment no longer matches. */
73
+ amount?: string;
74
+ status?: TransactionStatus;
75
+ statementDate?: string;
76
+ bookedDate?: string;
77
+ description?: string | null;
78
+ counterpartyName?: string | null;
79
+ /** `null` takes the link back. */
80
+ payment?: string | null;
81
+ counterparty?: string | null;
82
+ reference?: string | null;
83
+ }
84
+ export interface TransactionFilter {
85
+ wallet?: string;
86
+ direction?: MoneyDirection;
87
+ status?: TransactionStatus;
88
+ /** A split's category, in any letter case. */
89
+ category?: string;
90
+ project?: string;
91
+ review?: FinanceReview;
92
+ proposedBy?: ProposedByFilter;
93
+ /** Only those with an amount no split categorizes. */
94
+ uncategorized?: boolean;
95
+ /** 1–500, 100 by default; latest statement day first. */
96
+ limit?: number;
97
+ }
98
+ export interface CategoryTotal extends Money {
99
+ /** `null` for what no split categorizes. */
100
+ category: string | null;
101
+ }
102
+ /**
103
+ * What statements say moved on the owner's wallets (`transaction:<id>`). An agent's or an import's waits as proposed;
104
+ * a payment is linked only when currency, direction and amount agree, one transaction per payment.
105
+ */
106
+ export interface TransactionsStore {
107
+ add(input: TransactionInput): Promise<MoneyTransaction>;
108
+ get(reference: string): Promise<MoneyTransaction>;
109
+ list(filter?: TransactionFilter): Promise<MoneyTransaction[]>;
110
+ update(reference: string, input: TransactionUpdate): Promise<MoneyTransaction>;
111
+ addSplit(reference: string, input: SplitInput & {
112
+ by: Author;
113
+ }): Promise<MoneyTransaction>;
114
+ removeSplit(reference: string, input: {
115
+ position: number;
116
+ by: Author;
117
+ }): Promise<MoneyTransaction>;
118
+ /** Totals per category and currency over confirmed, booked transactions; nothing is converted. */
119
+ categories(filter?: {
120
+ wallet?: string;
121
+ from?: string;
122
+ until?: string;
123
+ }): Promise<CategoryTotal[]>;
124
+ confirm(reference: string, by: Decider, reason?: string): Promise<MoneyTransaction>;
125
+ reject(reference: string, by: Decider, reason?: string): Promise<MoneyTransaction>;
126
+ }
127
+ type TransactionOperations = {
128
+ [K in keyof TransactionsStore]: TransactionsStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
129
+ };
130
+ export declare const transactionOperationsOver: (context: StoreContext) => TransactionOperations;
131
+ export declare const transactionsStoreOver: (context: StoreContext) => TransactionsStore;
132
+ export {};
@@ -0,0 +1,295 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { TRANSACTION_STATUSES, transactionLine } from "../../domain/business.js";
3
+ import { FINANCE_REVIEWS, MONEY_DIRECTIONS } from "../../domain/finance.js";
4
+ import { formatDecimal, minorUnits, moneyLabel, moneyOf, scaleOf } from "../../domain/money.js";
5
+ import { fold } from "../normalize.js";
6
+ import { proposedBySql } from "./actors.js";
7
+ import { projectId } from "./memories.js";
8
+ import { requiredThing } from "./notes.js";
9
+ import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
10
+ import { write } from "./transaction.js";
11
+ const TRANSACTIONS = "SELECT t.*, w.name AS wallet_name, b.name AS author_name, b.kind AS author_kind, " +
12
+ "(SELECT coalesce(sum(amount), 0) FROM transaction_splits WHERE transaction_id = t.id) AS split " +
13
+ "FROM financial_transactions t JOIN financial_accounts w ON w.id = t.financial_account_id " +
14
+ "LEFT JOIN bots b ON t.author_type = 'bot' AND b.id = t.author_id";
15
+ const MAX_SPLITS = 100;
16
+ export const transactionOperationsOver = (context) => {
17
+ const { database, now } = context;
18
+ const { partyOf, partyThing, reviewedOf, written, keepEvidence, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
19
+ const splitsOf = (id, currency) => database
20
+ .prepare("SELECT * FROM transaction_splits WHERE transaction_id = ? ORDER BY position")
21
+ .all(id)
22
+ .map((row) => ({
23
+ position: Number(row.position),
24
+ category: String(row.category),
25
+ amount: formatDecimal(Number(row.amount), scaleOf(currency)),
26
+ project: row.project_id == null ? null : `project:${row.project_id}`,
27
+ note: row.note == null ? null : String(row.note),
28
+ }));
29
+ const transactionOf = (row) => {
30
+ const currency = String(row.currency);
31
+ const scale = scaleOf(currency);
32
+ const amount = Number(row.amount);
33
+ const fields = {
34
+ direction: row.direction,
35
+ amount,
36
+ currency,
37
+ label: (row.counterparty_name ?? row.description ?? null),
38
+ date: String(row.statement_date),
39
+ status: row.status,
40
+ review: row.review,
41
+ };
42
+ return {
43
+ id: String(row.id),
44
+ ref: `transaction:${row.id}`,
45
+ title: `Transaction · ${transactionLine(fields)}`,
46
+ wallet: `wallet:${row.financial_account_id}`,
47
+ walletName: String(row.wallet_name),
48
+ direction: fields.direction,
49
+ amount: formatDecimal(amount, scale),
50
+ currency,
51
+ status: fields.status,
52
+ statementDate: fields.date,
53
+ bookedDate: row.booked_date == null ? null : String(row.booked_date),
54
+ description: row.description == null ? null : String(row.description),
55
+ counterpartyName: row.counterparty_name == null ? null : String(row.counterparty_name),
56
+ counterparty: partyOf(row.counterparty_type, row.counterparty_id),
57
+ reference: row.reference == null ? null : String(row.reference),
58
+ payment: row.payment_id == null ? null : `payment:${row.payment_id}`,
59
+ splits: splitsOf(Number(row.id), currency),
60
+ uncategorized: formatDecimal(amount - Number(row.split), scale),
61
+ ...reviewedOf(row, "transaction"),
62
+ };
63
+ };
64
+ const rowOf = (reference) => {
65
+ const thing = requiredThing(database, reference.includes(":") ? reference : `transaction:${reference}`, "the transaction");
66
+ if (thing.type !== "transaction")
67
+ return refuse(`${reference} is not a transaction`, "transaction.ref");
68
+ return database.prepare(`${TRANSACTIONS} WHERE t.id = ?`).get(thing.id);
69
+ };
70
+ /** A statement line meets the settlement it records only when both say the same: currency, direction, amount. */
71
+ const paymentFor = (reference, moved, except) => {
72
+ if (reference == null)
73
+ return null;
74
+ const id = linkedId(reference, "payment", "transaction.payment");
75
+ const payment = database.prepare("SELECT * FROM payments WHERE id = ?").get(id);
76
+ const ref = `payment:${id}`;
77
+ if (payment.review === "rejected" || payment.deleted_at != null)
78
+ refuse(`${ref} is ${payment.review === "rejected" ? "rejected" : "deleted"}`, "transaction.payment");
79
+ if (payment.currency !== moved.currency ||
80
+ payment.direction !== moved.direction ||
81
+ Number(payment.amount) !== moved.amount)
82
+ refuse(`${ref} is ${moneyLabel(Number(payment.amount), String(payment.currency))} ${String(payment.direction)}; ` +
83
+ `the transaction is ${moneyLabel(moved.amount, moved.currency)} ${moved.direction}: they are not the same money`, "transaction.payment");
84
+ const taken = database
85
+ .prepare("SELECT id FROM financial_transactions WHERE payment_id = ? AND deleted_at IS NULL AND id IS NOT ?")
86
+ .get(id, except);
87
+ if (taken)
88
+ refuse(`${ref} is already the payment of transaction:${taken.id}`, "transaction.payment");
89
+ return id;
90
+ };
91
+ const splitRows = (splits, currency, amount, already) => {
92
+ if (!Array.isArray(splits) || splits.length > MAX_SPLITS)
93
+ refuse(`a transaction has at most ${MAX_SPLITS} splits`, "transaction.split");
94
+ const rows = splits.map((split, at) => {
95
+ const what = `split ${at + 1}`;
96
+ const units = minorUnits(split.amount, currency, `${what}'s amount`);
97
+ if (units <= 0)
98
+ refuse(`${what}'s amount is more than 0`, "money.amount");
99
+ return {
100
+ units,
101
+ category: text(split.category, `${what}'s category`, 200) ?? refuse(`${what} needs a category`, "transaction.split"),
102
+ project: split.project === undefined ? null : projectId(database, split.project),
103
+ note: text(split.note, `${what}'s note`, 2000),
104
+ };
105
+ });
106
+ const total = already + rows.reduce((sum, row) => sum + row.units, 0);
107
+ if (total > amount)
108
+ refuse(`the splits come to ${moneyLabel(total, currency)}, more than the transaction's ${moneyLabel(amount, currency)}`, "transaction.split");
109
+ return rows;
110
+ };
111
+ const insertSplits = (id, rows, from) => {
112
+ const at = now();
113
+ const insert = database.prepare("INSERT INTO transaction_splits (transaction_id, position, category, category_folded, amount, project_id, note, " +
114
+ "created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
115
+ for (const [index, row] of rows.entries())
116
+ insert.run(id, from + index, row.category, fold(row.category), row.units, row.project, row.note, at, at);
117
+ };
118
+ const mayChange = (row, by) => {
119
+ mayChangeParts(row, by, `only the owner changes transaction:${row.id}; a bot changes only a transaction it proposed that is still proposed`);
120
+ if (row.review === "rejected" || row.deleted_at != null)
121
+ refuse(`transaction:${row.id} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "transaction.ref");
122
+ };
123
+ const bookingOf = (status, booked, date) => {
124
+ if (status === "pending" && booked != null)
125
+ refuse("a pending transaction has no booking day yet", "transaction.field");
126
+ return status === "pending" ? null : (isoDate(booked, "the booking day") ?? date);
127
+ };
128
+ const decide = (reference, by, reason, confirm) => {
129
+ const row = rowOf(reference);
130
+ decideRow("transaction", row, { by, reason, confirm });
131
+ return transactionOf(rowOf(`transaction:${row.id}`));
132
+ };
133
+ return {
134
+ add: (input) => {
135
+ const direction = oneOf(input.direction, MONEY_DIRECTIONS, "a transaction's direction");
136
+ const status = input.status === undefined ? "booked" : oneOf(input.status, TRANSACTION_STATUSES, "a status");
137
+ const date = isoDate(input.statementDate, "a transaction's day") ?? refuse("a transaction has a day", "transaction.field");
138
+ const bookedDate = bookingOf(status, input.bookedDate, date);
139
+ const id = write(database, () => {
140
+ const walletId = linkedId(input.wallet, "wallet", "transaction.ref");
141
+ const wallet = database.prepare("SELECT * FROM financial_accounts WHERE id = ?").get(walletId);
142
+ if (wallet.deleted_at != null)
143
+ refuse(`wallet:${walletId} is deleted`, "transaction.ref");
144
+ const currency = String(wallet.currency);
145
+ if (input.currency !== undefined && input.currency.trim().toUpperCase() !== currency)
146
+ refuse(`wallet:${walletId} is in ${currency}; a transaction is in its wallet's currency`, "money.currency");
147
+ const amount = minorUnits(input.amount, currency, "a transaction's amount");
148
+ if (amount <= 0)
149
+ refuse("a transaction's amount is more than 0", "money.amount");
150
+ const splits = splitRows(input.splits ?? [], currency, amount, 0);
151
+ const payment = paymentFor(input.payment, { direction, amount, currency }, null);
152
+ const counterparty = partyThing(input.counterparty, "the counterparty");
153
+ const by = written(input);
154
+ const at = now();
155
+ const made = Number(database
156
+ .prepare("INSERT INTO financial_transactions (financial_account_id, direction, amount, currency, status, statement_date, " +
157
+ "booked_date, description, counterparty_name, counterparty_type, counterparty_id, reference, payment_id, " +
158
+ "project_id, review, author_type, author_id, model, confirmed_by_type, confirmed_by_id, source, metadata, " +
159
+ "created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
160
+ "RETURNING id")
161
+ .get(walletId, direction, amount, currency, status, date, bookedDate, text(input.description, "a transaction's description", 2000), text(input.counterpartyName, "the counterparty's name", 200), counterparty?.type ?? null, counterparty?.id ?? null, text(input.reference, "a transaction's reference", 500), payment, by.project, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
162
+ insertSplits(made, splits, 1);
163
+ keepEvidence("transaction", made, by);
164
+ return made;
165
+ });
166
+ return transactionOf(rowOf(`transaction:${id}`));
167
+ },
168
+ get: (reference) => transactionOf(rowOf(reference)),
169
+ list: (filter = {}) => {
170
+ const wallet = filter.wallet === undefined ? null : linkedId(filter.wallet, "wallet", "transaction.ref");
171
+ const project = filter.project === undefined ? null : projectId(database, filter.project);
172
+ const direction = filter.direction === undefined ? null : oneOf(filter.direction, MONEY_DIRECTIONS, "a direction");
173
+ const status = filter.status === undefined ? null : oneOf(filter.status, TRANSACTION_STATUSES, "a status");
174
+ const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
175
+ const category = filter.category === undefined ? null : fold(filter.category.trim());
176
+ const by = proposedBySql("t.author_type", "t.author_id", filter.proposedBy);
177
+ return database
178
+ .prepare(`${TRANSACTIONS} WHERE t.deleted_at IS NULL AND (? IS NULL OR t.financial_account_id = ?) ` +
179
+ "AND (? IS NULL OR t.direction = ?) AND (? IS NULL OR t.status = ?) AND (? IS NULL OR t.review = ?) " +
180
+ "AND (? IS NULL OR t.project_id = ? OR EXISTS (SELECT 1 FROM transaction_splits s WHERE s.transaction_id = t.id " +
181
+ "AND s.project_id = ?)) AND (? IS NULL OR EXISTS (SELECT 1 FROM transaction_splits s " +
182
+ "WHERE s.transaction_id = t.id AND s.category_folded = ?)) " +
183
+ `${filter.uncategorized ? "AND split < t.amount " : ""}AND ${by.sql} ` +
184
+ "ORDER BY t.statement_date DESC, t.id DESC LIMIT ?")
185
+ .all(wallet, wallet, direction, direction, status, status, review, review, project, project, project, category, category, ...by.params, limitOf(filter.limit))
186
+ .map(transactionOf);
187
+ },
188
+ update: (reference, input) => {
189
+ const row = rowOf(reference);
190
+ const ref = `transaction:${row.id}`;
191
+ mayChange(row, input.by);
192
+ const currency = String(row.currency);
193
+ const direction = input.direction === undefined ? String(row.direction) : oneOf(input.direction, MONEY_DIRECTIONS, "a direction");
194
+ const amount = input.amount === undefined ? Number(row.amount) : minorUnits(input.amount, currency, "a transaction's amount");
195
+ if (amount <= 0)
196
+ refuse("a transaction's amount is more than 0", "money.amount");
197
+ if (amount < Number(row.split))
198
+ refuse(`the splits of ${ref} come to ${moneyLabel(Number(row.split), currency)}, more than ${moneyLabel(amount, currency)}`, "transaction.split");
199
+ const status = input.status === undefined
200
+ ? row.status
201
+ : oneOf(input.status, TRANSACTION_STATUSES, "a status");
202
+ const date = input.statementDate === undefined
203
+ ? String(row.statement_date)
204
+ : isoDate(input.statementDate, "a transaction's day");
205
+ const bookedDate = input.status === undefined && input.bookedDate === undefined
206
+ ? row.booked_date
207
+ : bookingOf(status, input.bookedDate, date);
208
+ const kept = (given, column, what, limit) => given === undefined ? (row[column] ?? null) : text(given, what, limit);
209
+ write(database, () => {
210
+ const moved = { direction, amount, currency };
211
+ const linked = input.payment === undefined ? (row.payment_id == null ? null : `payment:${row.payment_id}`) : input.payment;
212
+ const payment = paymentFor(linked, moved, Number(row.id));
213
+ const counterparty = input.counterparty === undefined
214
+ ? { type: row.counterparty_type, id: row.counterparty_id }
215
+ : input.counterparty === null
216
+ ? { type: null, id: null }
217
+ : partyThing(input.counterparty, "the counterparty");
218
+ database
219
+ .prepare("UPDATE financial_transactions SET direction = ?, amount = ?, status = ?, statement_date = ?, booked_date = ?, " +
220
+ "description = ?, counterparty_name = ?, counterparty_type = ?, counterparty_id = ?, reference = ?, " +
221
+ "payment_id = ?, updated_at = ? WHERE id = ?")
222
+ .run(direction, amount, status, date, bookedDate, kept(input.description, "description", "a transaction's description", 2000), kept(input.counterpartyName, "counterparty_name", "the counterparty's name", 200), counterparty.type, counterparty.id, kept(input.reference, "reference", "a transaction's reference", 500), payment, now(), Number(row.id));
223
+ });
224
+ return transactionOf(rowOf(ref));
225
+ },
226
+ addSplit: (reference, { by, ...split }) => {
227
+ const row = rowOf(reference);
228
+ mayChange(row, by);
229
+ write(database, () => {
230
+ const rows = splitRows([split], String(row.currency), Number(row.amount), Number(row.split));
231
+ const last = Number(database
232
+ .prepare("SELECT coalesce(max(position), 0) AS n FROM transaction_splits WHERE transaction_id = ?")
233
+ .get(Number(row.id))?.n);
234
+ if (last >= MAX_SPLITS)
235
+ refuse(`a transaction has at most ${MAX_SPLITS} splits`, "transaction.split");
236
+ insertSplits(Number(row.id), rows, last + 1);
237
+ });
238
+ return transactionOf(rowOf(`transaction:${row.id}`));
239
+ },
240
+ removeSplit: (reference, { position, by }) => {
241
+ const row = rowOf(reference);
242
+ mayChange(row, by);
243
+ const gone = database
244
+ .prepare("DELETE FROM transaction_splits WHERE transaction_id = ? AND position = ?")
245
+ .run(Number(row.id), position);
246
+ if (gone.changes === 0)
247
+ throw new CliError("not_found", `transaction:${row.id} has no split ${position}`, {
248
+ reason: "transaction.no-split",
249
+ });
250
+ return transactionOf(rowOf(`transaction:${row.id}`));
251
+ },
252
+ categories: (filter = {}) => {
253
+ const wallet = filter.wallet === undefined ? null : linkedId(filter.wallet, "wallet", "transaction.ref");
254
+ const from = isoDate(filter.from, "the first day counted");
255
+ const until = isoDate(filter.until, "the last day counted");
256
+ const where = "t.review = 'confirmed' AND t.status = 'booked' AND t.deleted_at IS NULL AND (? IS NULL OR t.financial_account_id = ?) " +
257
+ "AND (? IS NULL OR t.booked_date >= ?) AND (? IS NULL OR t.booked_date <= ?)";
258
+ const params = [wallet, wallet, from, from, until, until];
259
+ const split = database
260
+ .prepare("SELECT min(s.category) AS category, s.category_folded, t.currency, sum(s.amount) AS units FROM transaction_splits s " +
261
+ `JOIN financial_transactions t ON t.id = s.transaction_id WHERE ${where} ` +
262
+ "GROUP BY s.category_folded, t.currency ORDER BY s.category_folded, t.currency")
263
+ .all(...params);
264
+ const rest = database
265
+ .prepare("SELECT t.currency, sum(t.amount - (SELECT coalesce(sum(amount), 0) FROM transaction_splits " +
266
+ `WHERE transaction_id = t.id)) AS units FROM financial_transactions t WHERE ${where} GROUP BY t.currency`)
267
+ .all(...params);
268
+ return [
269
+ ...split.map((row) => ({
270
+ category: String(row.category),
271
+ ...moneyOf(Number(row.units), String(row.currency)),
272
+ })),
273
+ ...rest
274
+ .filter((row) => Number(row.units) > 0)
275
+ .map((row) => ({ category: null, ...moneyOf(Number(row.units), String(row.currency)) })),
276
+ ];
277
+ },
278
+ confirm: (reference, by, reason) => decide(reference, by, reason, true),
279
+ reject: (reference, by, reason) => decide(reference, by, reason, false),
280
+ };
281
+ };
282
+ export const transactionsStoreOver = (context) => {
283
+ const operations = transactionOperationsOver(context);
284
+ return {
285
+ add: async (input) => operations.add(input),
286
+ get: async (reference) => operations.get(reference),
287
+ list: async (filter) => operations.list(filter),
288
+ update: async (reference, input) => operations.update(reference, input),
289
+ addSplit: async (reference, input) => operations.addSplit(reference, input),
290
+ removeSplit: async (reference, input) => operations.removeSplit(reference, input),
291
+ categories: async (filter) => operations.categories(filter),
292
+ confirm: async (reference, by, reason) => operations.confirm(reference, by, reason),
293
+ reject: async (reference, by, reason) => operations.reject(reference, by, reason),
294
+ };
295
+ };
@@ -1,6 +1,8 @@
1
+ import { type RelationshipColumns } from "../../domain/relations.js";
1
2
  import type { Section } from "../../readers/types.js";
2
3
  import { type Decider } from "../decisions.js";
3
4
  import type { CacheDatabase } from "../driver.js";
5
+ import type { AddedSources } from "./added-sources.js";
4
6
  import { type DocumentMetadata } from "./document-metadata.js";
5
7
  import { type ImportedDocuments } from "./imported-documents.js";
6
8
  import { LINK_KINDS, LINK_ORIGINS, type LINK_SOURCES } from "./link-kinds.js";
@@ -51,7 +53,7 @@ export interface Note {
51
53
  updatedAt: string;
52
54
  deletedAt: string | null;
53
55
  }
54
- export interface Link {
56
+ export interface Link extends RelationshipColumns {
55
57
  id: string;
56
58
  from: string;
57
59
  /** `null` while the link names nobody the store knows, or more than one. */
@@ -78,7 +80,7 @@ export interface LinkListFilter {
78
80
  origin?: Link["origin"];
79
81
  confirmed?: boolean;
80
82
  }
81
- export interface LinkInput {
83
+ export interface LinkInput extends Pick<RelationshipColumns, "position" | "startsAt" | "endsAt"> {
82
84
  from: string;
83
85
  to?: string;
84
86
  targetText?: string;
@@ -112,7 +114,7 @@ export interface MessageDocument {
112
114
  reference: string;
113
115
  fileId: string;
114
116
  }
115
- export interface NotesStore extends NoteSearch, ImportedDocuments {
117
+ export interface NotesStore extends NoteSearch, ImportedDocuments, AddedSources {
116
118
  addFolder(input: {
117
119
  name: string;
118
120
  format?: NoteFolder["format"];
@@ -202,6 +204,7 @@ export declare const documentOf: (row: Row) => Note;
202
204
  export declare const noteOf: (row: Row) => Note;
203
205
  /** A document or note row by its typed reference, or `undefined`. */
204
206
  export declare const noteRowOf: (database: CacheDatabase, reference: string) => Note | undefined;
207
+ export declare const thingRef: (database: CacheDatabase, type: unknown, id: unknown) => string | null;
205
208
  export declare const linkOf: (database: CacheDatabase, row: Row) => Link;
206
209
  /** The row a reference names, refused when the store holds none. */
207
210
  export declare const requiredThing: (database: CacheDatabase, reference: string, what?: string) => Thing;
@@ -214,4 +217,11 @@ export declare const resolvePersonLinks: (database: CacheDatabase, names: (strin
214
217
  export declare const purposeOf: (purpose: string) => string;
215
218
  /** Writes one link; an identical resolved link is answered instead of doubled. */
216
219
  export declare const insertLink: (context: StoreContext, input: LinkInput) => Link;
217
- export declare const notesStoreOver: (context: StoreContext) => Omit<NotesStore, keyof NoteSearch>;
220
+ /** A folder's `accounts` row; its format lives in `settings`. */
221
+ export declare const folderOf: (row: Row) => NoteFolder;
222
+ export declare const pathParts: (path: string) => {
223
+ location: string | null;
224
+ fileName: string;
225
+ extension: string | null;
226
+ };
227
+ export declare const notesStoreOver: (context: StoreContext) => Omit<NotesStore, keyof NoteSearch | keyof AddedSources>;