@wirecat/cli-core 0.605.0 → 0.607.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +4 -1
  12. package/dist/cli/index.js +4 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/cli/store-settings.js +38 -4
  17. package/dist/crm/cli/csv.d.ts +23 -0
  18. package/dist/crm/cli/csv.js +135 -0
  19. package/dist/crm/cli/index.d.ts +1 -1
  20. package/dist/crm/cli/index.js +36 -22
  21. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  22. package/dist/crm/cli/pipeline-view.js +36 -0
  23. package/dist/crm/index.d.ts +2 -2
  24. package/dist/crm/index.js +1 -1
  25. package/dist/crm/source.d.ts +35 -5
  26. package/dist/crm/sync.d.ts +15 -7
  27. package/dist/crm/sync.js +169 -11
  28. package/dist/crm/writes.d.ts +6 -4
  29. package/dist/crm/writes.js +17 -13
  30. package/dist/documents.d.ts +2 -0
  31. package/dist/documents.js +2 -0
  32. package/dist/domain/business.d.ts +79 -0
  33. package/dist/domain/business.js +42 -0
  34. package/dist/domain/crm.d.ts +41 -2
  35. package/dist/domain/deals.d.ts +5 -2
  36. package/dist/domain/deals.js +5 -2
  37. package/dist/domain/finance.d.ts +2 -0
  38. package/dist/domain/finance.js +2 -2
  39. package/dist/domain/google-documents.d.ts +2 -0
  40. package/dist/domain/google-documents.js +3 -1
  41. package/dist/domain/money.d.ts +2 -0
  42. package/dist/domain/money.js +11 -3
  43. package/dist/domain/providers.d.ts +36 -1
  44. package/dist/domain/providers.js +69 -7
  45. package/dist/domain/record-fields.d.ts +42 -0
  46. package/dist/domain/record-fields.js +122 -0
  47. package/dist/domain/record-types.d.ts +489 -16
  48. package/dist/domain/record-types.js +374 -7
  49. package/dist/domain/records.d.ts +96 -5
  50. package/dist/domain/records.js +178 -32
  51. package/dist/domain/ref-summaries.js +5 -0
  52. package/dist/domain/references.d.ts +1 -1
  53. package/dist/domain/references.js +5 -0
  54. package/dist/domain/relations.d.ts +125 -0
  55. package/dist/domain/relations.js +107 -0
  56. package/dist/domain/vcard.d.ts +25 -0
  57. package/dist/domain/vcard.js +267 -0
  58. package/dist/entities/deal.d.ts +16 -2
  59. package/dist/entities/deal.js +5 -1
  60. package/dist/entities/index.d.ts +29 -13
  61. package/dist/entities/relationship.d.ts +8 -2
  62. package/dist/entities/relationship.js +8 -2
  63. package/dist/entities/task-results.d.ts +10 -10
  64. package/dist/errors/reasons.js +73 -2
  65. package/dist/fetch/addresses.d.ts +5 -0
  66. package/dist/fetch/addresses.js +76 -0
  67. package/dist/fetch/page.d.ts +64 -0
  68. package/dist/fetch/page.js +256 -0
  69. package/dist/index.d.ts +7 -4
  70. package/dist/index.js +6 -3
  71. package/dist/mail/cli/review.js +20 -6
  72. package/dist/mail/index.d.ts +1 -1
  73. package/dist/mail/marks.d.ts +10 -5
  74. package/dist/mail/marks.js +16 -8
  75. package/dist/mail/review.d.ts +5 -0
  76. package/dist/meetings/calendar-text.d.ts +1 -1
  77. package/dist/meetings/calendar-text.js +4 -0
  78. package/dist/meetings/event-store.d.ts +2 -2
  79. package/dist/search/account-list.d.ts +4 -0
  80. package/dist/search/account-list.js +19 -8
  81. package/dist/search/query.js +2 -2
  82. package/dist/services/events-search.js +2 -2
  83. package/dist/services/index.d.ts +1 -1
  84. package/dist/services/index.js +1 -1
  85. package/dist/services/ingest.d.ts +56 -8
  86. package/dist/services/ingest.js +95 -61
  87. package/dist/services/link-scorers/scan.js +2 -1
  88. package/dist/services/link-scorers/shared.js +2 -1
  89. package/dist/services/messages-search.js +3 -2
  90. package/dist/services/metadata.d.ts +1 -1
  91. package/dist/services/notes-search.js +1 -0
  92. package/dist/services/project-status/index.js +2 -1
  93. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  94. package/dist/services/proposals/kinds/contracts.js +9 -0
  95. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  96. package/dist/services/proposals/kinds/finance.js +14 -35
  97. package/dist/services/proposals/kinds/orders.js +7 -30
  98. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  99. package/dist/services/proposals/kinds/shared.js +34 -0
  100. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  101. package/dist/services/proposals/kinds/source-review.js +45 -0
  102. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  103. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  104. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  105. package/dist/services/proposals/kinds/transactions.js +10 -0
  106. package/dist/services/proposals/registry.js +9 -0
  107. package/dist/services/search-all-meetings.js +2 -2
  108. package/dist/services/search-all.js +4 -3
  109. package/dist/services/search-kind.js +3 -3
  110. package/dist/services/stored-project-gathering.js +4 -3
  111. package/dist/store/decisions.js +5 -1
  112. package/dist/store/exports.d.ts +1 -0
  113. package/dist/store/exports.js +1 -0
  114. package/dist/store/index.d.ts +20 -4
  115. package/dist/store/index.js +4 -0
  116. package/dist/store/people.js +1 -1
  117. package/dist/store/project-transfer/request.d.ts +4 -1
  118. package/dist/store/project-transfer/schema.d.ts +9 -2
  119. package/dist/store/project-transfer/schema.js +4 -0
  120. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  121. package/dist/store/source-review.d.ts +64 -0
  122. package/dist/store/source-review.js +7 -0
  123. package/dist/store/sqlite/accounts.d.ts +1 -1
  124. package/dist/store/sqlite/accounts.js +24 -1
  125. package/dist/store/sqlite/added-sources.d.ts +82 -0
  126. package/dist/store/sqlite/added-sources.js +237 -0
  127. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  128. package/dist/store/sqlite/business-contracts.js +182 -0
  129. package/dist/store/sqlite/calendar-events.js +7 -3
  130. package/dist/store/sqlite/calendar-forget.js +3 -0
  131. package/dist/store/sqlite/calendar.d.ts +21 -1
  132. package/dist/store/sqlite/calendar.js +27 -7
  133. package/dist/store/sqlite/chat-rekey.js +7 -0
  134. package/dist/store/sqlite/chats.d.ts +3 -1
  135. package/dist/store/sqlite/chats.js +15 -1
  136. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  137. package/dist/store/sqlite/crm-rows.js +195 -0
  138. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  139. package/dist/store/sqlite/crm-settings.js +80 -0
  140. package/dist/store/sqlite/crm.d.ts +42 -11
  141. package/dist/store/sqlite/crm.js +402 -196
  142. package/dist/store/sqlite/deals.d.ts +4 -8
  143. package/dist/store/sqlite/deals.js +8 -5
  144. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  145. package/dist/store/sqlite/emails.js +2 -0
  146. package/dist/store/sqlite/entity-types.d.ts +14 -9
  147. package/dist/store/sqlite/entity-types.js +4 -10
  148. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  149. package/dist/store/sqlite/evidence-signature.js +349 -0
  150. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  151. package/dist/store/sqlite/evidence-sources.js +7 -3
  152. package/dist/store/sqlite/facts.d.ts +7 -2
  153. package/dist/store/sqlite/facts.js +21 -5
  154. package/dist/store/sqlite/finance.d.ts +18 -105
  155. package/dist/store/sqlite/finance.js +100 -219
  156. package/dist/store/sqlite/involvement-queue.js +4 -3
  157. package/dist/store/sqlite/knowledge.d.ts +14 -4
  158. package/dist/store/sqlite/knowledge.js +108 -102
  159. package/dist/store/sqlite/labelled.d.ts +3 -0
  160. package/dist/store/sqlite/labelled.js +11 -0
  161. package/dist/store/sqlite/link-kinds.d.ts +4 -3
  162. package/dist/store/sqlite/link-kinds.js +6 -2
  163. package/dist/store/sqlite/manifest.js +7 -0
  164. package/dist/store/sqlite/memories.d.ts +24 -10
  165. package/dist/store/sqlite/memories.js +73 -19
  166. package/dist/store/sqlite/messages.js +2 -0
  167. package/dist/store/sqlite/migrations.generated.js +134 -0
  168. package/dist/store/sqlite/money-lines.d.ts +48 -0
  169. package/dist/store/sqlite/money-lines.js +76 -0
  170. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  171. package/dist/store/sqlite/money-transactions.js +295 -0
  172. package/dist/store/sqlite/notes.d.ts +14 -4
  173. package/dist/store/sqlite/notes.js +43 -31
  174. package/dist/store/sqlite/orders.d.ts +36 -6
  175. package/dist/store/sqlite/orders.js +126 -46
  176. package/dist/store/sqlite/organizations.d.ts +8 -0
  177. package/dist/store/sqlite/organizations.js +14 -0
  178. package/dist/store/sqlite/payment-facts.js +1 -1
  179. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  180. package/dist/store/sqlite/person-preparation.js +3 -2
  181. package/dist/store/sqlite/private-people.js +2 -0
  182. package/dist/store/sqlite/products.d.ts +78 -0
  183. package/dist/store/sqlite/products.js +131 -0
  184. package/dist/store/sqlite/project-transfer/records.js +39 -3
  185. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  186. package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
  187. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  188. package/dist/store/sqlite/proposed-actions.js +24 -7
  189. package/dist/store/sqlite/providers.d.ts +0 -4
  190. package/dist/store/sqlite/providers.js +20 -2
  191. package/dist/store/sqlite/record-matching.d.ts +80 -0
  192. package/dist/store/sqlite/record-matching.js +264 -0
  193. package/dist/store/sqlite/record-projection.d.ts +89 -0
  194. package/dist/store/sqlite/record-projection.js +50 -0
  195. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  196. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  197. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  198. package/dist/store/sqlite/record-projectors-money.js +214 -0
  199. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  200. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  201. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  202. package/dist/store/sqlite/record-projectors.js +7 -67
  203. package/dist/store/sqlite/record-relations.d.ts +24 -0
  204. package/dist/store/sqlite/record-relations.js +92 -0
  205. package/dist/store/sqlite/record-remap.d.ts +12 -0
  206. package/dist/store/sqlite/record-remap.js +92 -0
  207. package/dist/store/sqlite/record-run.d.ts +71 -0
  208. package/dist/store/sqlite/record-run.js +179 -0
  209. package/dist/store/sqlite/record-settling.d.ts +9 -0
  210. package/dist/store/sqlite/record-settling.js +74 -0
  211. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  212. package/dist/store/sqlite/record-stamps.js +30 -0
  213. package/dist/store/sqlite/record-writes.d.ts +43 -0
  214. package/dist/store/sqlite/record-writes.js +307 -0
  215. package/dist/store/sqlite/records.d.ts +52 -42
  216. package/dist/store/sqlite/records.js +123 -353
  217. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  218. package/dist/store/sqlite/ref-summaries.js +60 -8
  219. package/dist/store/sqlite/refunds.d.ts +31 -0
  220. package/dist/store/sqlite/refunds.js +112 -0
  221. package/dist/store/sqlite/relation-list.d.ts +43 -0
  222. package/dist/store/sqlite/relation-list.js +133 -0
  223. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  224. package/dist/store/sqlite/relation-proposals.js +134 -10
  225. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  226. package/dist/store/sqlite/relation-reads.js +7 -0
  227. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  228. package/dist/store/sqlite/relation-roles.js +91 -0
  229. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  230. package/dist/store/sqlite/reported-relations.js +132 -0
  231. package/dist/store/sqlite/reviewed.d.ts +109 -0
  232. package/dist/store/sqlite/reviewed.js +173 -0
  233. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  234. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  235. package/dist/store/sqlite/schema/links.d.ts +360 -0
  236. package/dist/store/sqlite/schema/links.js +32 -0
  237. package/dist/store/sqlite/schema.d.ts +2769 -306
  238. package/dist/store/sqlite/schema.js +258 -25
  239. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  240. package/dist/store/sqlite/source-review-marks.js +143 -0
  241. package/dist/store/sqlite/source-review.d.ts +54 -0
  242. package/dist/store/sqlite/source-review.js +221 -0
  243. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  244. package/dist/store/sqlite/stage-amounts.js +23 -0
  245. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  246. package/dist/store/sqlite/subscriptions.js +294 -0
  247. package/dist/store/sqlite/text-input.d.ts +3 -0
  248. package/dist/store/sqlite/text-input.js +13 -0
  249. package/dist/store/sqlite/things.js +2 -9
  250. package/dist/store/sqlite/transaction.d.ts +15 -0
  251. package/dist/store/sqlite/transaction.js +57 -0
  252. package/dist/store/sqlite/wallets.d.ts +88 -0
  253. package/dist/store/sqlite/wallets.js +143 -0
  254. package/dist/store/store-errors.d.ts +1 -0
  255. package/dist/store/store-errors.js +45 -0
  256. package/dist/store/store.d.ts +19 -1
  257. package/dist/store/store.js +35 -6
  258. package/package.json +6 -3
  259. package/schemas/examples/records-business.jsonl +11 -0
  260. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -1,41 +1,11 @@
1
1
  import { type FinanceReview, type InvoiceDirection, type InvoiceStatus, type MoneyDirection } from "../../domain/finance.js";
2
2
  import { type Money } from "../../domain/money.js";
3
- import { RECORD_TYPES } from "../../domain/record-types.js";
4
- import { type Decider } from "../decisions.js";
5
- import { type Actor, type ProposedByFilter } from "./actors.js";
3
+ import type { Decider } from "../decisions.js";
4
+ import { type ProposedByFilter } from "./actors.js";
6
5
  import { type Author } from "./memories.js";
6
+ import { type MoneyLine, type MoneyLineInput } from "./money-lines.js";
7
7
  import type { StoreContext } from "./open.js";
8
- /** A `person:` or `organization:` on an invoice or a payment, with its name so a list needs no lookup. */
9
- export interface Party {
10
- ref: string;
11
- name: string | null;
12
- /** The owner's own person row. */
13
- owner: boolean;
14
- }
15
- export interface Reviewed {
16
- review: FinanceReview;
17
- /** `name` is a bot's handle and `kind` whether it is an agent or a rule; both `null` for a person. */
18
- author: {
19
- type: Actor["type"];
20
- id: string;
21
- name: string | null;
22
- kind: "agent" | "rule" | null;
23
- };
24
- model: string | null;
25
- confirmedBy: {
26
- type: Actor["type"];
27
- id: string;
28
- } | null;
29
- source: string;
30
- /** Why an agent or an import proposed it. */
31
- reason: string | null;
32
- /** What it was read from: the messages, documents or notes an agent or the owner cited. */
33
- evidence: string[];
34
- project: string | null;
35
- projectName: string | null;
36
- createdAt: string;
37
- updatedAt: string;
38
- }
8
+ import { type Party, type Reviewed, type Written } from "./reviewed.js";
39
9
  export interface Invoice extends Reviewed {
40
10
  id: string;
41
11
  ref: string;
@@ -47,21 +17,17 @@ export interface Invoice extends Reviewed {
47
17
  counterparty: Party;
48
18
  currency: string;
49
19
  total: string;
50
- /** Settled by confirmed payments. */
20
+ /** Settled by confirmed payments, net of their confirmed refunds. */
51
21
  paid: string;
52
22
  /** Still owed: `total − paid`. */
53
23
  open: string;
54
24
  issueDate: string | null;
55
25
  dueDate: string | null;
56
26
  status: InvoiceStatus;
27
+ contract: string | null;
28
+ subscription: string | null;
57
29
  }
58
- export interface InvoiceLine {
59
- position: number;
60
- description: string;
61
- quantity: string;
62
- unitPrice: string | null;
63
- amount: string;
64
- }
30
+ export type InvoiceLine = MoneyLine;
65
31
  export interface Allocation {
66
32
  payment: string;
67
33
  invoice: string;
@@ -88,29 +54,14 @@ export interface Payment extends Reviewed {
88
54
  /** Allocated to invoices, confirmed or not. */
89
55
  allocated: string;
90
56
  unallocated: string;
57
+ /** The payment this refunds: the other direction, the same currency, never more than it. */
58
+ refundOf: string | null;
59
+ subscription: string | null;
91
60
  }
92
61
  export interface PaymentDetail extends Payment {
93
62
  allocations: Allocation[];
94
63
  }
95
- export interface Written {
96
- /** The owner's entry is confirmed at once; a bot's waits as proposed for the owner. */
97
- by: Author;
98
- project?: string;
99
- /** Where a bot's row came from, such as `agent` or an importer's name; the owner's is always `owner`. */
100
- source?: string;
101
- /** Why a bot proposes it, kept for the reviewer. */
102
- reason?: string;
103
- /** References it was read from, linked as `evidence`. */
104
- evidence?: string[];
105
- }
106
- export interface InvoiceLineInput {
107
- description: string;
108
- /** A decimal string; `1` when not given. */
109
- quantity?: string;
110
- /** Decimal strings in the invoice's currency. Give either or both: both must agree, quantity × unit price. */
111
- unitPrice?: string;
112
- amount?: string;
113
- }
64
+ export type InvoiceLineInput = MoneyLineInput;
114
65
  export interface InvoiceInput extends Written {
115
66
  direction: InvoiceDirection;
116
67
  number?: string;
@@ -126,6 +77,9 @@ export interface InvoiceInput extends Written {
126
77
  lines: InvoiceLineInput[];
127
78
  /** The total printed on the invoice: refused when it is not the sum of the lines. */
128
79
  total?: string;
80
+ contract?: string;
81
+ /** The subscription whose period it bills. */
82
+ subscription?: string;
129
83
  }
130
84
  export interface PaymentInput extends Written {
131
85
  direction: MoneyDirection;
@@ -140,6 +94,9 @@ export interface PaymentInput extends Written {
140
94
  invoice: string;
141
95
  amount: string;
142
96
  }[];
97
+ /** The payment it refunds: it then goes the other way, and is allocated only to invoices that payment settles. */
98
+ refundOf?: string;
99
+ subscription?: string;
143
100
  }
144
101
  interface ListFilter {
145
102
  project?: string;
@@ -207,50 +164,6 @@ export interface FinanceStore {
207
164
  payable: OpenTotal[];
208
165
  }>;
209
166
  }
210
- type Row = Record<string, unknown>;
211
- /** The types `decide` settles money for; other proposal types get their own route. */
212
- declare const FINANCE_TYPES: readonly ["invoice", "payment"];
213
- type FinanceType = (typeof FINANCE_TYPES)[number];
214
- type FinanceTable = (typeof RECORD_TYPES)[FinanceType]["table"];
215
- /** One article, for the first prefix only: `an invoice: or payment:`. */
216
- export declare const prefixesText: (types: readonly string[]) => string;
217
- export declare const refuse: (message: string, reason: string, code?: "validation_error" | "permission_error") => never;
218
- export declare const oneOf: <T extends string>(value: unknown, allowed: readonly T[], what: string) => T;
219
- export declare const text: (value: unknown, what: string, limit: number) => string | null;
220
- export declare const isoDate: (value: unknown, what: string) => string | null;
221
- export declare const iso: (value: unknown) => string;
222
- /** What invoices, payments and orders share: their parties, who wrote them, and how the owner decides them. */
223
- export declare const reviewedRowsOver: (context: StoreContext) => {
224
- partyOf: (type: unknown, id: unknown) => Party | null;
225
- partyThing: (reference: string | undefined, what: string) => import("./things.js").Thing | undefined;
226
- reviewedOf: (row: Row, type: "invoice" | "payment" | "order" | "deal") => Reviewed;
227
- written: (input: Written) => {
228
- owner: boolean;
229
- actor: Actor;
230
- model: string | null;
231
- source: string;
232
- review: string;
233
- confirmedType: "bot" | "person" | null;
234
- confirmedId: number | null;
235
- metadata: string | null;
236
- project: number | null;
237
- evidence: string[];
238
- };
239
- keepEvidence: (type: "invoice" | "payment" | "order" | "deal", id: number, by: ReturnType<(input: Written) => {
240
- owner: boolean;
241
- actor: Actor;
242
- model: string | null;
243
- source: string;
244
- review: string;
245
- confirmedType: "bot" | "person" | null;
246
- confirmedId: number | null;
247
- metadata: string | null;
248
- project: number | null;
249
- evidence: string[];
250
- }>) => void;
251
- ownerOnly: (by: Author, what: string) => void;
252
- keepDecision: (table: FinanceTable | "orders", id: number, by: Decider, reason?: string) => void;
253
- };
254
167
  type FinanceOperations = {
255
168
  [K in keyof FinanceStore]: FinanceStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
256
169
  };
@@ -1,139 +1,29 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, invoiceTitle, MONEY_DIRECTIONS, paymentEntryTitle, settledStatus, } from "../../domain/finance.js";
3
- import { currencyOf, formatDecimal, lineUnits, minorUnits, moneyLabel, moneyOf, quantityOf, scaleOf, } from "../../domain/money.js";
4
- import { RECORD_TYPES } from "../../domain/record-types.js";
5
- import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
6
- import { proposedBySql, proposerOf } from "./actors.js";
7
- import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf, subjectOf, } from "./memories.js";
3
+ import { currencyOf, formatDecimal, minorUnits, moneyLabel, moneyOf, scaleOf } from "../../domain/money.js";
4
+ import { proposedBySql } from "./actors.js";
5
+ import { authorActor, projectId } from "./memories.js";
6
+ import { moneyLinesOver } from "./money-lines.js";
8
7
  import { requiredThing } from "./notes.js";
8
+ import { netPaidSql, refundRulesOver } from "./refunds.js";
9
+ import { iso, isoDate, limitOf, oneOf, prefixesText, refuse, reviewedRowsOver, text, } from "./reviewed.js";
9
10
  import { write } from "./transaction.js";
10
11
  /** The types `decide` settles money for; other proposal types get their own route. */
11
12
  const FINANCE_TYPES = ["invoice", "payment"];
12
13
  const isFinanceType = (type) => FINANCE_TYPES.includes(type);
13
- const article = (word) => (/^[aeiou]/.test(word) ? "an" : "a");
14
- /** One article, for the first prefix only: `an invoice: or payment:`. */
15
- export const prefixesText = (types) => `${article(types[0] ?? "")} ${types.map((type) => `${type}:`).join(" or ")}`;
16
- export const refuse = (message, reason, code = "validation_error") => {
17
- throw new CliError(code, message, { reason });
18
- };
19
- export const oneOf = (value, allowed, what) => {
20
- if (typeof value !== "string" || !allowed.includes(value))
21
- return refuse(`${what} is one of ${allowed.join(", ")}`, "finance.field");
22
- return value;
23
- };
24
- export const text = (value, what, limit) => {
25
- if (value === undefined || value === null)
26
- return null;
27
- if (typeof value !== "string" || !value.trim() || value.length > limit || value.includes("\0"))
28
- return refuse(`${what} takes 1–${limit} characters`, "finance.field");
29
- return value.trim();
30
- };
31
- export const isoDate = (value, what) => {
32
- if (value === undefined || value === null)
33
- return null;
34
- const date = typeof value === "string" ? value.trim() : "";
35
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)
36
- return refuse(`${what} is a date such as 2026-11-15`, "finance.field");
37
- return date;
38
- };
39
- export const iso = (value) => new Date(Number(value)).toISOString();
40
- const evidenceList = (value) => {
41
- if (value === undefined)
42
- return [];
43
- if (!Array.isArray(value) || value.length > 8 || value.some((one) => typeof one !== "string" || !one.trim()))
44
- return refuse("evidence is a list of at most 8 references", "finance.field");
45
- return [...new Set(value.map((one) => one.trim()))];
46
- };
47
14
  const MAX_LINES = 500;
48
- const reasonOf = (metadata) => {
49
- if (metadata == null)
50
- return null;
51
- try {
52
- const { reason } = JSON.parse(String(metadata));
53
- return typeof reason === "string" ? reason : null;
54
- }
55
- catch {
56
- return null;
57
- }
58
- };
59
15
  /** Money settled by confirmed payments only: a proposed payment promises nothing yet. */
60
- const PAID = "(SELECT coalesce(sum(a.amount), 0) FROM payment_allocations a JOIN payments p ON p.id = a.payment_id " +
61
- "WHERE a.invoice_id = i.id AND p.review = 'confirmed' AND p.deleted_at IS NULL)";
16
+ const PAID = netPaidSql("i.id");
62
17
  const INVOICES = `SELECT i.*, ${PAID} AS paid, b.name AS author_name, b.kind AS author_kind FROM invoices i ` +
63
18
  "LEFT JOIN bots b ON i.author_type = 'bot' AND b.id = i.author_id";
64
19
  const PAYMENTS = "SELECT p.*, (SELECT coalesce(sum(amount), 0) FROM payment_allocations WHERE payment_id = p.id) AS allocated, " +
65
20
  "b.name AS author_name, b.kind AS author_kind FROM payments p LEFT JOIN bots b ON p.author_type = 'bot' AND b.id = p.author_id";
66
- /** What invoices, payments and orders share: their parties, who wrote them, and how the owner decides them. */
67
- export const reviewedRowsOver = (context) => {
68
- const { database } = context;
69
- const partyOf = (type, id) => {
70
- if (type == null)
71
- return null;
72
- const { subject, subjectName, subjectIsOwner } = subjectOf(database, { subject_type: type, subject_id: id });
73
- return subject === null ? null : { ref: subject, name: subjectName, owner: subjectIsOwner };
74
- };
75
- const partyThing = (reference, what) => {
76
- if (reference === undefined)
77
- return undefined;
78
- const thing = requiredThing(database, reference, what);
79
- if (thing.type !== "person" && thing.type !== "organization")
80
- return refuse(`${what} is a person: or organization: reference, not ${reference}`, "finance.party");
81
- return thing;
82
- };
83
- const reviewedOf = (row, type) => ({
84
- review: row.review,
85
- author: authorOf(row),
86
- model: row.model == null ? null : String(row.model),
87
- confirmedBy: row.confirmed_by_type == null
88
- ? null
89
- : { type: row.confirmed_by_type, id: String(row.confirmed_by_id) },
90
- source: String(row.source),
91
- reason: reasonOf(row.metadata),
92
- evidence: evidenceOf(context, { type, id: Number(row.id) }),
93
- ...projectOf(database, row),
94
- createdAt: iso(row.created_at),
95
- updatedAt: iso(row.updated_at),
96
- });
97
- const written = (input) => {
98
- const owner = input.by === "owner";
99
- const { actor, model } = authorActor(context, input.by);
100
- const source = owner ? "owner" : (text(input.source, "a source", 80) ?? "agent");
101
- const reason = owner ? null : text(input.reason, "a reason", 2000);
102
- return {
103
- owner,
104
- actor,
105
- model,
106
- source,
107
- review: owner ? "confirmed" : "proposed",
108
- confirmedType: owner ? actor.type : null,
109
- confirmedId: owner ? actor.id : null,
110
- metadata: reason === null ? null : JSON.stringify({ reason }),
111
- project: input.project === undefined ? null : projectId(database, input.project),
112
- evidence: evidenceList(input.evidence),
113
- };
114
- };
115
- const keepEvidence = (type, id, by) => {
116
- if (by.evidence.length)
117
- linkEvidence(context, { type, id }, by.evidence, by.owner ? "owner" : "agent");
118
- };
119
- const ownerOnly = (by, what) => {
120
- if (by !== "owner")
121
- refuse(`only the owner ${what}`, "finance.owner-only", "permission_error");
122
- };
123
- const keepDecision = (table, id, by, reason) => {
124
- const why = [by === "owner" ? undefined : by.reason.trim(), reason?.trim() || undefined].filter(Boolean).join(": ");
125
- if (by === "owner" && !why)
126
- return;
127
- const decision = by === "owner" ? { by: "owner", reason: why } : { by: "agent", bot: by.bot, reason: why };
128
- database
129
- .prepare(`UPDATE ${table} SET metadata = json_set(coalesce(metadata, '{}'), '$.decision', json(?)) WHERE id = ?`)
130
- .run(JSON.stringify(decision), id);
131
- };
132
- return { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, keepDecision };
133
- };
134
21
  export const financeOperationsOver = (context) => {
135
22
  const { database, now } = context;
136
- const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, keepDecision } = reviewedRowsOver(context);
23
+ const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
24
+ const refunds = refundRulesOver(context);
25
+ const lines = moneyLinesOver(context);
26
+ const refOf = (type, id) => (id == null ? null : `${type}:${id}`);
137
27
  const invoiceOf = (row) => {
138
28
  const currency = String(row.currency);
139
29
  const scale = scaleOf(currency);
@@ -165,6 +55,8 @@ export const financeOperationsOver = (context) => {
165
55
  issueDate: row.issue_date == null ? null : String(row.issue_date),
166
56
  dueDate: fields.dueDate,
167
57
  status: fields.status,
58
+ contract: refOf("contract", row.contract_id),
59
+ subscription: refOf("subscription", row.subscription_id),
168
60
  ...reviewedOf(row, "invoice"),
169
61
  };
170
62
  };
@@ -196,6 +88,8 @@ export const financeOperationsOver = (context) => {
196
88
  reference: row.reference == null ? null : String(row.reference),
197
89
  allocated: formatDecimal(allocated, scale),
198
90
  unallocated: formatDecimal(amount - allocated, scale),
91
+ refundOf: refOf("payment", row.refund_of),
92
+ subscription: refOf("subscription", row.subscription_id),
199
93
  ...reviewedOf(row, "payment"),
200
94
  };
201
95
  };
@@ -218,18 +112,11 @@ export const financeOperationsOver = (context) => {
218
112
  };
219
113
  const invoiceDetail = (reference) => {
220
114
  const row = rowOf(reference, "invoice");
221
- const scale = scaleOf(String(row.currency));
222
- const lines = database
223
- .prepare("SELECT * FROM invoice_lines WHERE invoice_id = ? ORDER BY position")
224
- .all(Number(row.id))
225
- .map((line) => ({
226
- position: Number(line.position),
227
- description: String(line.description),
228
- quantity: String(line.quantity),
229
- unitPrice: line.unit_price == null ? null : formatDecimal(Number(line.unit_price), scale),
230
- amount: formatDecimal(Number(line.amount), scale),
231
- }));
232
- return { ...invoiceOf(row), lines, allocations: allocationsWhere("invoice_id", Number(row.id)) };
115
+ return {
116
+ ...invoiceOf(row),
117
+ lines: lines.shownLines("invoice", Number(row.id), String(row.currency)),
118
+ allocations: allocationsWhere("invoice_id", Number(row.id)),
119
+ };
233
120
  };
234
121
  const paymentDetail = (reference) => {
235
122
  const row = rowOf(reference, "payment");
@@ -262,13 +149,16 @@ export const financeOperationsOver = (context) => {
262
149
  if (fromPayment + units > Number(payment.amount))
263
150
  refuse(`${paymentRef} is ${moneyLabel(Number(payment.amount), currency)} and ` +
264
151
  `${moneyLabel(fromPayment, currency)} of it is already allocated; ${moneyLabel(units, currency)} more is too much`, "finance.over-payment");
265
- const toInvoice = Number(database
266
- .prepare("SELECT coalesce(sum(a.amount), 0) AS n FROM payment_allocations a JOIN payments p ON p.id = a.payment_id " +
267
- "WHERE a.invoice_id = ? AND ((p.review = 'confirmed' AND p.deleted_at IS NULL) OR a.payment_id = ?)")
268
- .get(Number(invoice.id), Number(payment.id))?.n);
269
- if (toInvoice + units > Number(invoice.total))
270
- refuse(`${invoiceRef} totals ${moneyLabel(Number(invoice.total), currency)} and ` +
271
- `${moneyLabel(toInvoice, currency)} is already allocated to it; ${moneyLabel(units, currency)} more is too much`, "finance.over-invoice");
152
+ if (payment.refund_of != null)
153
+ refunds.refundShare(payment, Number(invoice.id), units);
154
+ else {
155
+ const toInvoice = Number(database
156
+ .prepare(`SELECT ${netPaidSql("?", { including: "?" })} AS n`)
157
+ .get(Number(invoice.id), Number(payment.id))?.n);
158
+ if (toInvoice + units > Number(invoice.total))
159
+ refuse(`${invoiceRef} totals ${moneyLabel(Number(invoice.total), currency)} and ` +
160
+ `${moneyLabel(toInvoice, currency)} is already allocated to it; ${moneyLabel(units, currency)} more is too much`, "finance.over-invoice");
161
+ }
272
162
  const at = now();
273
163
  database
274
164
  .prepare("INSERT INTO payment_allocations (payment_id, invoice_id, amount, author_type, author_id, created_at, updated_at) " +
@@ -280,10 +170,9 @@ export const financeOperationsOver = (context) => {
280
170
  /** A proposed payment's allocations count once confirmed; by then other confirmed payments may cover the invoice. */
281
171
  const coveredElsewhere = (paymentId) => {
282
172
  const over = database
283
- .prepare("SELECT a.invoice_id, a.amount, i.total, i.currency, (SELECT coalesce(sum(o.amount), 0) FROM payment_allocations o " +
284
- "JOIN payments p ON p.id = o.payment_id WHERE o.invoice_id = a.invoice_id AND o.payment_id <> a.payment_id " +
285
- "AND p.review = 'confirmed' AND p.deleted_at IS NULL) AS others FROM payment_allocations a " +
286
- "JOIN invoices i ON i.id = a.invoice_id WHERE a.payment_id = ? AND a.amount + others > i.total LIMIT 1")
173
+ .prepare(`SELECT a.invoice_id, a.amount, i.total, i.currency, ${netPaidSql("a.invoice_id", { excluding: "a.payment_id" })} ` +
174
+ "AS others FROM payment_allocations a JOIN invoices i ON i.id = a.invoice_id " +
175
+ "WHERE a.payment_id = ? AND a.amount + others > i.total LIMIT 1")
287
176
  .get(paymentId);
288
177
  if (!over)
289
178
  return;
@@ -297,75 +186,63 @@ export const financeOperationsOver = (context) => {
297
186
  if (!isFinanceType(thing.type))
298
187
  return refuse(`${reference} is not ${prefixesText(FINANCE_TYPES)}`, "finance.ref");
299
188
  const type = thing.type;
300
- const table = RECORD_TYPES[type].table;
301
189
  const row = rowOf(reference, type);
302
190
  const ref = `${type}:${row.id}`;
303
- assertMayDecide({ id: ref, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly: true }, by, context.decisions);
304
- if (row.review !== "proposed")
305
- refuse(`${ref} is already ${String(row.review)}`, "proposal.wrong-state");
306
191
  const id = Number(row.id);
307
- write(database, () => {
308
- const at = now();
309
- if (confirm && type === "payment")
310
- coveredElsewhere(id);
311
- if (confirm) {
312
- const { actor } = authorActor(context, deciderAuthor(by));
313
- database
314
- .prepare(`UPDATE ${table} SET review = 'confirmed', confirmed_by_type = ?, confirmed_by_id = ?, updated_at = ? WHERE id = ?`)
315
- .run(actor.type, actor.id, at, id);
316
- }
317
- else
318
- database.prepare(`UPDATE ${table} SET review = 'rejected', updated_at = ? WHERE id = ?`).run(at, id);
319
- keepDecision(table, id, by, reason);
320
- const touched = type === "invoice"
321
- ? [id]
322
- : database
323
- .prepare("SELECT invoice_id FROM payment_allocations WHERE payment_id = ?")
324
- .all(id)
325
- .map((one) => Number(one.invoice_id));
326
- if (!confirm)
327
- database
328
- .prepare(`DELETE FROM payment_allocations WHERE ${type === "invoice" ? "invoice_id" : "payment_id"} = ?`)
329
- .run(id);
330
- for (const invoice of touched)
331
- settle(invoice);
192
+ const payment = type === "payment";
193
+ decideRow(type, row, { by, reason, confirm }, {
194
+ before: () => {
195
+ if (payment && confirm && row.refund_of != null)
196
+ refunds.confirmable(row);
197
+ else if (payment && confirm)
198
+ coveredElsewhere(id);
199
+ if (payment && !confirm) {
200
+ refunds.keepsRefunded(row);
201
+ keepsTransaction(id);
202
+ }
203
+ },
204
+ after: () => {
205
+ const touched = payment
206
+ ? database
207
+ .prepare("SELECT invoice_id FROM payment_allocations WHERE payment_id = ?")
208
+ .all(id)
209
+ .map((one) => Number(one.invoice_id))
210
+ : [id];
211
+ if (!confirm && payment)
212
+ database.prepare("DELETE FROM payment_allocations WHERE payment_id = ?").run(id);
213
+ if (!confirm && !payment)
214
+ dropAllocations(id, "");
215
+ for (const invoice of touched)
216
+ settle(invoice);
217
+ },
332
218
  });
333
- return type === "invoice" ? invoiceDetail(ref) : paymentDetail(ref);
219
+ return payment ? paymentDetail(ref) : invoiceDetail(ref);
334
220
  };
335
- const mayAllocate = (row, by) => {
336
- if (by === "owner")
337
- return;
338
- const own = row.author_type === "bot" && row.author_name != null && botKey(String(row.author_name)) === botKey(by.bot);
339
- if (row.review !== "proposed" || !own)
340
- refuse(`only the owner allocates payment:${row.id}; a bot allocates only from a payment it proposed that is still proposed`, "finance.owner-only", "permission_error");
221
+ /** A statement line records this payment: it stays until the link is taken back on the transaction. */
222
+ const keepsTransaction = (paymentId) => {
223
+ const linked = database
224
+ .prepare("SELECT id FROM financial_transactions WHERE payment_id = ? AND deleted_at IS NULL LIMIT 1")
225
+ .get(paymentId);
226
+ if (linked)
227
+ refuse(`payment:${paymentId} is the payment of transaction:${linked.id}; take the link back there first`, "transaction.payment");
341
228
  };
342
- const limitOf = (limit) => Math.min(Math.max(limit ?? 100, 1), 500);
229
+ /** Refunds' shares go first: a payment's share stays while a refund of it takes part of it back. */
230
+ const dropAllocations = (invoiceId, which) => {
231
+ for (const refund of [true, false])
232
+ database
233
+ .prepare("DELETE FROM payment_allocations WHERE invoice_id = ? AND payment_id IN " +
234
+ `(SELECT id FROM payments WHERE refund_of IS ${refund ? "NOT " : ""}NULL${which})`)
235
+ .run(invoiceId);
236
+ };
237
+ const mayAllocate = (row, by) => mayChangeParts(row, by, `only the owner allocates payment:${row.id}; a bot allocates only from a payment it proposed that is still proposed`);
343
238
  return {
344
239
  addInvoice: (input) => {
345
240
  const direction = oneOf(input.direction, INVOICE_DIRECTIONS, "an invoice's direction");
346
241
  const currency = currencyOf(input.currency);
347
242
  if (!Array.isArray(input.lines) || input.lines.length === 0 || input.lines.length > MAX_LINES)
348
243
  refuse(`an invoice has 1–${MAX_LINES} lines`, "finance.lines");
349
- const lines = input.lines.map((line, at) => {
350
- const what = `line ${at + 1}`;
351
- const quantity = quantityOf(line.quantity ?? "1");
352
- const unitPrice = line.unitPrice === undefined ? null : minorUnits(line.unitPrice, currency, `${what}'s unit price`);
353
- const computed = unitPrice === null ? null : lineUnits(quantity.thousandths, unitPrice);
354
- const amount = line.amount === undefined ? computed : minorUnits(line.amount, currency, `${what}'s amount`);
355
- if (amount === null)
356
- return refuse(`${what} takes a unit price, an amount or both`, "finance.lines");
357
- if (computed !== null && computed !== amount)
358
- refuse(`${what}: ${quantity.text} × ${moneyLabel(unitPrice, currency)} is ` +
359
- `${moneyLabel(computed, currency)}, not ${moneyLabel(amount, currency)}`, "finance.line-amount");
360
- return {
361
- description: text(line.description, `${what}'s description`, 500) ??
362
- refuse(`${what} needs a description`, "finance.lines"),
363
- quantity: quantity.text,
364
- unitPrice: unitPrice ?? (quantity.thousandths === 1000n ? amount : null),
365
- amount,
366
- };
367
- });
368
- const total = lines.reduce((sum, line) => sum + line.amount, 0);
244
+ const priced = lines.linesOf("invoice", input.lines, currency);
245
+ const total = priced.reduce((sum, line) => sum + line.amount, 0);
369
246
  if (!Number.isSafeInteger(total))
370
247
  refuse("an invoice's total is too large", "finance.total");
371
248
  if (total <= 0)
@@ -382,18 +259,17 @@ export const financeOperationsOver = (context) => {
382
259
  const issuer = partyThing(input.issuer, "the issuer");
383
260
  const counterparty = partyThing(input.counterparty, "the counterparty") ??
384
261
  refuse("an invoice names its counterparty, a person: or organization:", "finance.party");
262
+ const contract = linkedId(input.contract, "contract", "finance.ref");
263
+ const subscription = linkedId(input.subscription, "subscription", "finance.ref");
385
264
  const by = written(input);
386
265
  const at = now();
387
266
  const made = Number(database
388
267
  .prepare("INSERT INTO invoices (direction, number, issuer_type, issuer_id, counterparty_type, counterparty_id, project_id, " +
389
268
  "currency, total, issue_date, due_date, status, review, author_type, author_id, model, confirmed_by_type, " +
390
- "confirmed_by_id, source, metadata, created_at, updated_at) " +
391
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
392
- .get(direction, number, issuer?.type ?? null, issuer?.id ?? null, counterparty.type, counterparty.id, by.project, currency, total, issueDate, dueDate, input.draft ? "draft" : "issued", by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
393
- const insert = database.prepare("INSERT INTO invoice_lines (invoice_id, position, description, quantity, unit_price, amount, created_at, updated_at) " +
394
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
395
- for (const [index, line] of lines.entries())
396
- insert.run(made, index + 1, line.description, line.quantity, line.unitPrice, line.amount, at, at);
269
+ "confirmed_by_id, source, metadata, created_at, updated_at, contract_id, subscription_id) " +
270
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
271
+ .get(direction, number, issuer?.type ?? null, issuer?.id ?? null, counterparty.type, counterparty.id, by.project, currency, total, issueDate, dueDate, input.draft ? "draft" : "issued", by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at, contract, subscription)?.id);
272
+ lines.insertLines("invoice", made, priced, 1, at);
397
273
  keepEvidence("invoice", made, by);
398
274
  return made;
399
275
  });
@@ -433,17 +309,11 @@ export const financeOperationsOver = (context) => {
433
309
  const row = rowOf(reference, "invoice");
434
310
  if (row.status === "void")
435
311
  refuse(`invoice:${row.id} is already void`, "finance.status");
436
- const allocated = database
437
- .prepare("SELECT 1 FROM payment_allocations a JOIN payments p ON p.id = a.payment_id " +
438
- "WHERE a.invoice_id = ? AND p.review = 'confirmed' AND p.deleted_at IS NULL LIMIT 1")
439
- .get(Number(row.id));
440
- if (allocated)
312
+ const paid = Number(database.prepare(`SELECT ${netPaidSql("?")} AS n`).get(Number(row.id))?.n);
313
+ if (paid > 0)
441
314
  refuse(`payments are allocated to invoice:${row.id}; a paid invoice is not voided`, "finance.status");
442
315
  write(database, () => {
443
- database
444
- .prepare("DELETE FROM payment_allocations WHERE invoice_id = ? " +
445
- "AND payment_id IN (SELECT id FROM payments WHERE review = 'proposed')")
446
- .run(Number(row.id));
316
+ dropAllocations(Number(row.id), " AND review = 'proposed'");
447
317
  database.prepare("UPDATE invoices SET status = 'void', updated_at = ? WHERE id = ?").run(now(), Number(row.id));
448
318
  });
449
319
  return invoiceDetail(`invoice:${row.id}`);
@@ -463,13 +333,18 @@ export const financeOperationsOver = (context) => {
463
333
  const id = write(database, () => {
464
334
  const payer = partyThing(input.payer, "the payer");
465
335
  const payee = partyThing(input.payee, "the payee");
336
+ const refundOf = linkedId(input.refundOf, "payment", "finance.refund");
337
+ if (refundOf !== null)
338
+ refunds.originalFor(refundOf, { direction, currency, amount });
339
+ const subscription = linkedId(input.subscription, "subscription", "finance.ref");
466
340
  const by = written(input);
467
341
  const at = now();
468
342
  const made = database
469
343
  .prepare("INSERT INTO payments (direction, payer_type, payer_id, payee_type, payee_id, amount, currency, payment_date, " +
470
344
  "reference, project_id, review, author_type, author_id, model, confirmed_by_type, confirmed_by_id, source, " +
471
- "metadata, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *")
472
- .get(direction, payer?.type ?? null, payer?.id ?? null, payee?.type ?? null, payee?.id ?? null, amount, currency, date, reference, by.project, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at);
345
+ "metadata, created_at, updated_at, refund_of, subscription_id) " +
346
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *")
347
+ .get(direction, payer?.type ?? null, payer?.id ?? null, payee?.type ?? null, payee?.id ?? null, amount, currency, date, reference, by.project, by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at, refundOf, subscription);
473
348
  keepEvidence("payment", Number(made.id), by);
474
349
  const touched = allocations.map(({ invoice, units }) => allocateRow(made, invoice, units, by.actor));
475
350
  for (const invoice of touched)
@@ -518,6 +393,12 @@ export const financeOperationsOver = (context) => {
518
393
  refuse(`${ref} is ${row.deleted_at != null ? "deleted" : "rejected"}; only a proposed or confirmed payment's ` +
519
394
  "allocations are taken back", "finance.unallocate");
520
395
  const target = rowOf(invoice, "invoice");
396
+ if (target.status === "void")
397
+ refuse(`invoice:${target.id} is void; its allocations stay as they were`, "finance.unallocate");
398
+ if (row.refund_of == null)
399
+ refunds.keepsShare(Number(row.id), Number(target.id));
400
+ else
401
+ refunds.keepsInvoice(row, Number(target.id));
521
402
  write(database, () => {
522
403
  const gone = database
523
404
  .prepare("DELETE FROM payment_allocations WHERE payment_id = ? AND invoice_id = ?")
@@ -1,4 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { usableLinkSql } from "../../domain/relations.js";
2
3
  /** One SELECT per way of taking part: the subject's kind, the column that holds its id, and the query. */
3
4
  const ARMS = [
4
5
  [
@@ -79,8 +80,8 @@ const ARMS = [
79
80
  const linkArm = (linkFrom, linkTo) => `
80
81
  SELECT CASE WHEN l.to_type='person' THEN l.to_id ELSE il.person_id END AS person_id, CASE WHEN l.to_type='identity' THEN l.to_id END AS identity_id, l.from_type AS subject_type, l.from_id AS subject_id, coalesce(l.role,'linked') AS role, l.created_at AS occurred_at,
81
82
  coalesce(c.scope,a.scope,p.scope,'personal') AS scope, coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id) AS account_id, p.id AS project_id
82
- FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed FROM links WHERE ${linkFrom}
83
- UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
83
+ FROM (SELECT from_type,from_id,to_type,to_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE ${linkFrom}
84
+ UNION ALL SELECT to_type,to_id,from_type,from_id,role,created_at,confirmed,account_id,deleted_at FROM links WHERE from_type IN ('person','identity') AND to_id IS NOT NULL AND ${linkTo}) l
84
85
  LEFT JOIN identity_links il ON l.to_type='identity' AND il.identity_id=l.to_id
85
86
  LEFT JOIN messages m ON l.from_type='message' AND m.id=l.from_id
86
87
  LEFT JOIN chats c ON c.id=CASE WHEN l.from_type='chat' THEN l.from_id ELSE m.chat_id END
@@ -90,7 +91,7 @@ const linkArm = (linkFrom, linkTo) => `
90
91
  LEFT JOIN tasks t ON l.from_type='task' AND t.id=l.from_id
91
92
  LEFT JOIN projects p ON p.id=CASE WHEN l.from_type='project' THEN l.from_id ELSE t.project_id END
92
93
  LEFT JOIN accounts a ON a.id=coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id)
93
- WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND l.confirmed=1 AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
94
+ WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND ${usableLinkSql("l")} AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
94
95
  `;
95
96
  /**
96
97
  * Every way of taking part, or only the ones about `subject`, each filtered by its own key so SQLite reads