advisers 0.3.2 → 0.4.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 (44) hide show
  1. package/README-zh.md +13 -14
  2. package/README.md +32 -23
  3. package/THIRD-PARTY-NOTICES.md +1 -1
  4. package/bin/advisers.js +2180 -92
  5. package/index.js +1 -1
  6. package/lib/brief-archive.js +267 -0
  7. package/lib/client-pack.js +1016 -0
  8. package/lib/consent.js +390 -0
  9. package/lib/credentials.js +195 -0
  10. package/lib/error-codes.js +516 -7
  11. package/lib/evidence.js +697 -113
  12. package/lib/kb-extract.js +626 -0
  13. package/lib/kb-facts.js +429 -0
  14. package/lib/kb-pages.js +1084 -0
  15. package/lib/kb.js +1036 -0
  16. package/lib/mail-errors.js +46 -0
  17. package/lib/mail-extract.js +351 -0
  18. package/lib/mail-imap.js +446 -0
  19. package/lib/mail-import.js +176 -0
  20. package/lib/mail-parse.js +223 -0
  21. package/lib/mail-store.js +731 -0
  22. package/lib/mail.js +506 -0
  23. package/lib/mcp-server.js +196 -10
  24. package/lib/notify.js +265 -7
  25. package/lib/policy/decision.js +315 -0
  26. package/lib/policy/egress.js +268 -0
  27. package/lib/policy/errors.js +71 -0
  28. package/lib/policy/index.js +99 -0
  29. package/lib/policy/rules.js +468 -0
  30. package/lib/policy/surfaces.js +141 -0
  31. package/lib/receipt-verify.js +199 -19
  32. package/lib/receivables.js +1653 -0
  33. package/lib/scheduler.js +453 -9
  34. package/lib/shell.js +1406 -0
  35. package/lib/source.js +98 -3
  36. package/lib/sqlite.js +366 -49
  37. package/lib/tos/index.js +2 -2
  38. package/lib/tos/manifest.json +6 -6
  39. package/lib/tos/privacy.zh-CN.md +33 -20
  40. package/lib/tos/safety.zh-CN.md +7 -6
  41. package/lib/tos/summary.zh-CN.md +3 -2
  42. package/lib/tos/terms.zh-CN.md +31 -16
  43. package/lib/urgency.js +467 -0
  44. package/package.json +4 -4
@@ -0,0 +1,1653 @@
1
+ /**
2
+ * Receivables and payments (0.4.0, schema v22; design 48-customer-v2 sections
3
+ * 3.2/3.3).
4
+ *
5
+ * A receivable is a MONEY SIDECAR, not a fourth ledger:
6
+ *
7
+ * commitments (the ledger's single "who owes whom" record)
8
+ * - receivables 1:1 (amount / currency / memo / tombstone, schema v22)
9
+ * - payments 1:N (cash events; commitment_id NULL = unmatched prepay)
10
+ *
11
+ * Creating a receivable creates its follow-up commitment ("回款跟进") in the
12
+ * same transaction, so reminders/today/who/due-date rules work with zero new
13
+ * tables. The amount never enters the commitment action or evidence quote:
14
+ * reminder payloads, ICS, webhooks and the wire ledger stay amount-free.
15
+ *
16
+ * Rules this module owns:
17
+ * - integer minor units via BigInt: decimal STRING in, two decimals out, max
18
+ * 1e12 minor units (10,000,000,000.00). No float math, no locale formatting.
19
+ * - exactly four currencies (CNY/USD/EUR/HKD); no FX, no cross-currency
20
+ * totals, no automatic rounding of a remainder.
21
+ * - partial / multiple / over-payment are valid; a payment's currency must
22
+ * equal the receivable's currency; payments without a receivable are
23
+ * unmatched prepayments and never reduce an outstanding balance.
24
+ * - state is DERIVED from tombstone + written-off + amount + due date, never
25
+ * stored, so it cannot fight the commitment status.
26
+ * - full payment completes the follow-up commitment in the same transaction
27
+ * (core.completeCommitment, manual evidence "payment <id>") and records
28
+ * closed_by_payment_id; payment void reopens it only when it was closed by
29
+ * money and the outstanding balance is positive again. Evidence history is
30
+ * never rewritten.
31
+ * - no hard deletes: void = tombstone. A receivable with active payments
32
+ * cannot be voided (void the payments first) and its amount cannot be edited
33
+ * while payments exist.
34
+ * - clearance = max(client.secrecyDefault, matter.secrecy); hidden rows are
35
+ * only counted (protectedExcluded) and never leak an id/name/label.
36
+ * - one audited transaction per write; audit reasons contain ids/counts only,
37
+ * never an amount, a name, a memo or a free-form reason.
38
+ *
39
+ * Out of scope by design: invoices, receipts, statements of account, dunning
40
+ * letters, bank/payment-channel reconciliation, FX rates. This module records
41
+ * operator-entered local bookkeeping; it never moves money.
42
+ *
43
+ * The CLI wiring is owned by bin/advisers.js; this file is the whole store
44
+ * layer (bin only parses flags / renders text and calls these functions).
45
+ */
46
+
47
+ import { createHash, randomUUID } from 'node:crypto'
48
+ import { readFileSync } from 'node:fs'
49
+
50
+ import { entityError } from './sqlite.js'
51
+ import { normalizeReminderOffsets } from './remind.js'
52
+
53
+ // The core ledger operations are the frozen commitment contract (one evidence
54
+ // rule, one done transition). Same fallback ladder as bin/advisers.js so
55
+ // ADVISERS_CORE_LOCAL works in a checkout without a published package.
56
+ let core
57
+ if (process.env.ADVISERS_CORE_LOCAL === '1') {
58
+ core = await import('../../core/dist/index.js')
59
+ } else {
60
+ try {
61
+ core = await import('advisers-core')
62
+ } catch {
63
+ core = await import('../../core/dist/index.js')
64
+ }
65
+ }
66
+ const { createCommitment, completeCommitment } = core
67
+
68
+ /* -------------------------------------------------------------------------- */
69
+ /* constants */
70
+ /* -------------------------------------------------------------------------- */
71
+
72
+ const LF = String.fromCharCode(10)
73
+ const BS = String.fromCharCode(92)
74
+ const NUL = String.fromCharCode(0)
75
+
76
+ /** Currencies accepted by the money sidecar (same set as the quote templates). */
77
+ export const CURRENCIES = Object.freeze(['CNY', 'USD', 'EUR', 'HKD'])
78
+ /** Default currency when the caller omits it. */
79
+ export const DEFAULT_CURRENCY = 'CNY'
80
+ /** Hard per-amount cap: 1e12 minor units = 10,000,000,000.00. */
81
+ export const MAX_AMOUNT_MINOR = 1_000_000_000_000n
82
+ /** Allowed receivable kinds (operator self-reported, never inferred). */
83
+ export const RECEIVABLE_KINDS = Object.freeze(['quote', 'milestone', 'retainer', 'other'])
84
+ /** Allowed payment methods (operator self-reported, never verified). */
85
+ export const PAYMENT_METHODS = Object.freeze(['bank', 'wechat', 'alipay', 'cash', 'other'])
86
+ /** Derived receivable states. Only written_off/void come from stored columns. */
87
+ export const RECEIVABLE_STATES = Object.freeze(['open', 'partial', 'overdue', 'settled', 'written_off', 'void'])
88
+ /** Local CLI default clearance (docs/CLIENTS.md section 4); external surfaces pass 0. */
89
+ export const DEFAULT_CLEARANCE = 3
90
+ /** receivable ls page defaults (same family as the customer list limits). */
91
+ export const RECEIVABLE_LIST_LIMIT = 50
92
+ export const RECEIVABLE_LIST_LIMIT_MAX = 500
93
+ /** payment ls page defaults. */
94
+ export const PAYMENT_LIST_LIMIT = 50
95
+ export const PAYMENT_LIST_LIMIT_MAX = 500
96
+ /** Follow-up matter title used when no matter/project anchors the receivable. */
97
+ export const RECEIVABLE_MATTER_TITLE = '回款'
98
+ /** Currency symbol map used by human views (never by the JSON view here). */
99
+ const CURRENCY_SYMBOLS = Object.freeze({ CNY: '¥', USD: '$', EUR: '€', HKD: 'HK$' })
100
+
101
+ const DAY_MS = 86_400_000
102
+ const SHANGHAI_OFFSET_MS = 8 * 3600_000
103
+ const LABEL_MAX = 200
104
+ const MEMO_MAX = 200
105
+ const REASON_MAX = 200
106
+ const AGG_KEY_SEP = NUL
107
+
108
+ /* -------------------------------------------------------------------------- */
109
+ /* small pure helpers */
110
+ /* -------------------------------------------------------------------------- */
111
+
112
+ function invalid(message, hint) {
113
+ return entityError('E_RECEIVABLE_INVALID', message, hint)
114
+ }
115
+
116
+ function invalidPayment(message, hint) {
117
+ return entityError('E_PAYMENT_INVALID', message, hint)
118
+ }
119
+
120
+ function nowIso(value) {
121
+ if (value === undefined || value === null) return new Date().toISOString()
122
+ const date = value instanceof Date ? value : new Date(String(value))
123
+ if (!Number.isFinite(date.getTime())) throw invalid('now must be a valid Date/ISO instant')
124
+ return date.toISOString()
125
+ }
126
+
127
+ function newId(prefix) {
128
+ return prefix + '_' + randomUUID().replace(/-/g, '').slice(0, 16)
129
+ }
130
+
131
+ function isDigitCode(code) {
132
+ return code >= 48 && code <= 57
133
+ }
134
+
135
+ function isAsciiLetterCode(code) {
136
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
137
+ }
138
+
139
+ function isHexLowerCode(code) {
140
+ return (code >= 48 && code <= 57) || (code >= 97 && code <= 102)
141
+ }
142
+
143
+ function isDateOnly(text) {
144
+ if (typeof text !== 'string' || text.length !== 10) return false
145
+ for (let i = 0; i < 10; i += 1) {
146
+ const code = text.charCodeAt(i)
147
+ if (i === 4 || i === 7) { if (code !== 45) return false } else if (!isDigitCode(code)) return false
148
+ }
149
+ return true
150
+ }
151
+
152
+ /** YYYY-MM-DD{ |T}HH:MM[:SS[.mmm]] (no zone). */
153
+ function isLocalDateTime(text) {
154
+ if (typeof text !== 'string' || text.length < 16) return false
155
+ if (!isDateOnly(text.slice(0, 10))) return false
156
+ const sep = text.charCodeAt(10)
157
+ if (sep !== 84 && sep !== 32) return false
158
+ if (text.charCodeAt(13) !== 58) return false
159
+ for (let i = 11; i < 16; i += 1) {
160
+ if (i === 13) continue
161
+ if (!isDigitCode(text.charCodeAt(i))) return false
162
+ }
163
+ if (text.length === 16) return true
164
+ if (text.charCodeAt(16) !== 58) return false
165
+ for (let i = 17; i < 19; i += 1) if (!isDigitCode(text.charCodeAt(i))) return false
166
+ if (text.length === 19) return true
167
+ if (text.charCodeAt(19) !== 46) return false
168
+ const fraction = text.slice(20)
169
+ if (fraction.length < 1 || fraction.length > 3) return false
170
+ for (let i = 0; i < fraction.length; i += 1) if (!isDigitCode(fraction.charCodeAt(i))) return false
171
+ return true
172
+ }
173
+
174
+ /** Decimal string: digits, optionally one dot followed by 1+ digits. */
175
+ function isDecimalString(text) {
176
+ if (typeof text !== 'string' || !text) return false
177
+ let dot = -1
178
+ for (let i = 0; i < text.length; i += 1) {
179
+ const code = text.charCodeAt(i)
180
+ if (code === 46) {
181
+ if (dot !== -1 || i === 0 || i === text.length - 1) return false
182
+ dot = i
183
+ } else if (!isDigitCode(code)) return false
184
+ }
185
+ return true
186
+ }
187
+
188
+ function hasControlOrNewline(text) {
189
+ for (let i = 0; i < text.length; i += 1) {
190
+ const code = text.charCodeAt(i)
191
+ if (code === LF || code === 13) return true
192
+ if (code < 32 || code === 127) return true
193
+ }
194
+ return false
195
+ }
196
+
197
+ /** Reject absolute-path-looking free text without leaking it anywhere. */
198
+ function looksLikeAbsolutePath(text) {
199
+ if (!text) return false
200
+ if (text.startsWith('/') || text.startsWith(BS)) return true
201
+ if (text.includes(':/') || text.includes(':' + BS)) return true
202
+ for (let i = 0; i + 2 < text.length; i += 1) {
203
+ if (!isAsciiLetterCode(text.charCodeAt(i))) continue
204
+ if (text.charCodeAt(i + 1) !== 58) continue
205
+ const third = text.charCodeAt(i + 2)
206
+ if (third === 47 || third === 92) return true
207
+ }
208
+ return false
209
+ }
210
+
211
+ /** Single-line operator text (label/memo/reason): no control chars, no paths. */
212
+ function normalizeOperatorText(field, value, max) {
213
+ if (value === undefined || value === null) return undefined
214
+ if (typeof value !== 'string') throw invalid(field + ' must be a string')
215
+ const text = value.trim()
216
+ if (!text) return undefined
217
+ if (hasControlOrNewline(text)) throw invalid(field + ' must be a single line without control characters')
218
+ if (Array.from(text).length > max) throw invalid(field + ' is longer than ' + max + ' characters')
219
+ if (looksLikeAbsolutePath(text)) throw invalid(field + ' must not contain an absolute file path')
220
+ return text
221
+ }
222
+
223
+ /* ------------------------------- money ----------------------------------- */
224
+
225
+ /** Price text -> BigInt minor units. Accepts a decimal string (or a BigInt). */
226
+ export function parseAmountToMinor(value, options = {}) {
227
+ const field = options.field ?? 'amount'
228
+ const code = options.code ?? 'E_RECEIVABLE_INVALID'
229
+ const fail = (message, hint) => entityError(code, message, hint)
230
+ if (typeof value === 'bigint') {
231
+ if (value <= 0n) throw fail(field + ' must be greater than 0')
232
+ if (value > MAX_AMOUNT_MINOR) throw fail(field + ' is out of range (max ' + formatMinorAmount(MAX_AMOUNT_MINOR) + ')')
233
+ return value
234
+ }
235
+ if (typeof value !== 'string') throw fail(field + ' must be a decimal string like "8000.00"')
236
+ const text = value.trim()
237
+ if (!isDecimalString(text)) throw fail(field + ' must be a decimal string like "8000.00" (no sign, comma, exponent or currency symbol)')
238
+ const dot = text.indexOf('.')
239
+ const whole = dot === -1 ? text : text.slice(0, dot)
240
+ const fraction = dot === -1 ? '' : text.slice(dot + 1)
241
+ if (fraction.length > 2) throw fail(field + ' has more than 2 decimal places')
242
+ if (whole.length > 13) throw fail(field + ' is out of range (max ' + formatMinorAmount(MAX_AMOUNT_MINOR) + ')')
243
+ const minor = BigInt(whole) * 100n + BigInt((fraction + '00').slice(0, 2))
244
+ if (minor <= 0n) throw fail(field + ' must be greater than 0')
245
+ if (minor > MAX_AMOUNT_MINOR) throw fail(field + ' is out of range (max ' + formatMinorAmount(MAX_AMOUNT_MINOR) + ')')
246
+ return minor
247
+ }
248
+
249
+ /** BigInt/number minor units -> plain "8000.00" (no thousands separators). */
250
+ export function formatMinorAmount(minor) {
251
+ let value
252
+ if (typeof minor === 'bigint') value = minor
253
+ else if (typeof minor === 'number' && Number.isFinite(minor)) value = BigInt(Math.trunc(minor))
254
+ else throw new TypeError('minor units must be a BigInt or finite number')
255
+ const negative = value < 0n
256
+ const absolute = negative ? -value : value
257
+ const whole = absolute / 100n
258
+ const fraction = absolute % 100n
259
+ return (negative ? '-' : '') + whole.toString() + '.' + fraction.toString().padStart(2, '0')
260
+ }
261
+
262
+ /** JSON-safe number for a BigInt minor amount known to be below 2^53. */
263
+ function minorToNumber(value) {
264
+ const number = Number(value)
265
+ if (!Number.isSafeInteger(number)) throw new Error('money amount exceeded Number.MAX_SAFE_INTEGER; refusing to serialise an unsafe integer')
266
+ return number
267
+ }
268
+
269
+ function minorAdd(left, right) {
270
+ return minorToNumber(BigInt(left) + BigInt(right))
271
+ }
272
+
273
+ /** Currency code validation/normalisation (uppercase, four currencies). */
274
+ export function parseCurrency(value, options = {}) {
275
+ const code = options.code ?? 'E_RECEIVABLE_INVALID'
276
+ if (value === undefined || value === null || value === '') return DEFAULT_CURRENCY
277
+ if (typeof value !== 'string') throw entityError(code, 'currency must be one of ' + CURRENCIES.join(', '))
278
+ const text = value.trim().toUpperCase()
279
+ if (!CURRENCIES.includes(text)) throw entityError(code, 'currency must be one of ' + CURRENCIES.join(', ') + ' (got ' + value.trim() + ')')
280
+ return text
281
+ }
282
+
283
+ function parseKind(value) {
284
+ if (value === undefined || value === null || value === '') return 'other'
285
+ if (typeof value !== 'string') throw invalid('kind must be one of ' + RECEIVABLE_KINDS.join(', '))
286
+ const text = value.trim()
287
+ if (!RECEIVABLE_KINDS.includes(text)) throw invalid('kind must be one of ' + RECEIVABLE_KINDS.join(', ') + ' (got ' + text + ')')
288
+ return text
289
+ }
290
+
291
+ function parseMethod(value) {
292
+ if (value === undefined || value === null || value === '') return 'other'
293
+ if (typeof value !== 'string') throw invalidPayment('method must be one of ' + PAYMENT_METHODS.join(', '))
294
+ const text = value.trim()
295
+ if (!PAYMENT_METHODS.includes(text)) throw invalidPayment('method must be one of ' + PAYMENT_METHODS.join(', ') + ' (got ' + text + ')')
296
+ return text
297
+ }
298
+
299
+ function parseId(value, field) {
300
+ if (typeof value !== 'string' || !value.trim()) throw invalid(field + ' is required')
301
+ return value.trim()
302
+ }
303
+
304
+ /** First defined option among camelCase / CLI-flag spellings. */
305
+ function pickOption(options, names) {
306
+ if (!options || typeof options !== 'object') return undefined
307
+ for (const name of names) {
308
+ if (options[name] !== undefined && options[name] !== null) return options[name]
309
+ }
310
+ return undefined
311
+ }
312
+
313
+ /* ------------------------------- dates ----------------------------------- */
314
+
315
+ function shanghaiDayEndInstant(day) {
316
+ const parts = day.split('-').map(Number)
317
+ return Date.UTC(parts[0], parts[1] - 1, parts[2]) - SHANGHAI_OFFSET_MS + DAY_MS - 1
318
+ }
319
+
320
+ /**
321
+ * Resolve a stored/entered due date to an absolute instant, same rule as the
322
+ * CLI: YYYY-MM-DD -> end of that Asia/Shanghai day, local ISO without zone ->
323
+ * +08:00, anything with Z/offset -> its absolute instant, otherwise null.
324
+ */
325
+ export function receivableDueInstant(value) {
326
+ if (value === undefined || value === null) return null
327
+ const text = String(value).trim()
328
+ if (!text) return null
329
+ if (isDateOnly(text)) {
330
+ const parts = text.split('-').map(Number)
331
+ if (parts[1] < 1 || parts[1] > 12 || parts[2] < 1 || parts[2] > 31) return null
332
+ const ms = shanghaiDayEndInstant(text)
333
+ return Number.isFinite(ms) ? ms : null
334
+ }
335
+ if (isLocalDateTime(text)) {
336
+ const normalized = text.replace(' ', 'T')
337
+ const withSeconds = normalized.length >= 19 ? normalized : normalized + ':00'
338
+ const withMs = withSeconds.includes('.') ? withSeconds : withSeconds + '.000'
339
+ const ms = Date.parse(withMs + '+08:00')
340
+ return Number.isFinite(ms) ? ms : null
341
+ }
342
+ const ms = Date.parse(text)
343
+ return Number.isFinite(ms) ? ms : null
344
+ }
345
+
346
+ /** Validate an operator-entered due date and keep its original spelling. */
347
+ function normalizeDueAt(value, eventCode = 'E_RECEIVABLE_INVALID', field = 'due date') {
348
+ if (value === undefined || value === null || value === '') return undefined
349
+ if (typeof value !== 'string') throw entityError(eventCode, field + ' must be a string (YYYY-MM-DD or ISO)')
350
+ const text = value.trim()
351
+ if (!text) return undefined
352
+ const ms = receivableDueInstant(text)
353
+ if (ms === null) throw entityError(eventCode, field + ' is not a valid date: ' + text.slice(0, 40))
354
+ return text
355
+ }
356
+
357
+ /** Normalise an entered payment instant to an explicit-offset ISO string. */
358
+ function normalizePaidAt(value, nowMs) {
359
+ const source = value === undefined || value === null || value === '' ? new Date(nowMs) : value
360
+ let ms = null
361
+ let text = null
362
+ if (source instanceof Date) {
363
+ ms = source.getTime()
364
+ } else if (typeof source === 'string') {
365
+ const raw = source.trim()
366
+ if (!raw) throw invalidPayment('paid-at must be a valid date')
367
+ if (isDateOnly(raw)) {
368
+ const parts = raw.split('-').map(Number)
369
+ ms = Date.UTC(parts[0], parts[1] - 1, parts[2]) - SHANGHAI_OFFSET_MS
370
+ text = raw + 'T00:00:00.000+08:00'
371
+ } else if (isLocalDateTime(raw)) {
372
+ const normalized = raw.replace(' ', 'T')
373
+ const withSeconds = normalized.length >= 19 ? normalized : normalized + ':00'
374
+ const withMs = withSeconds.includes('.') ? withSeconds : withSeconds + '.000'
375
+ text = withMs + '+08:00'
376
+ ms = Date.parse(text)
377
+ } else {
378
+ ms = Date.parse(raw)
379
+ text = Number.isFinite(ms) ? new Date(ms).toISOString() : null
380
+ }
381
+ } else {
382
+ throw invalidPayment('paid-at must be a string (YYYY-MM-DD or ISO instant)')
383
+ }
384
+ if (!Number.isFinite(ms)) throw invalidPayment('paid-at is not a valid date')
385
+ if (ms > nowMs + DAY_MS) throw invalidPayment('paid-at is more than a day in the future; record the actual payment date')
386
+ return text ?? new Date(ms).toISOString()
387
+ }
388
+
389
+ function instantOf(value) {
390
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
391
+ if (typeof value !== 'string') return null
392
+ const ms = Date.parse(value)
393
+ return Number.isFinite(ms) ? ms : null
394
+ }
395
+
396
+ /** UTC instant -> Asia/Shanghai ISO with an explicit +08:00 offset. */
397
+ function toShanghaiIso(ms) {
398
+ return new Date(ms + SHANGHAI_OFFSET_MS).toISOString().replace('Z', '+08:00')
399
+ }
400
+
401
+ function normalizeClearance(value, fallback = DEFAULT_CLEARANCE) {
402
+ if (value === undefined || value === null || value === '') return fallback
403
+ const number = Number(value)
404
+ if (!Number.isFinite(number)) return fallback
405
+ return Math.min(3, Math.max(0, Math.trunc(number)))
406
+ }
407
+
408
+ function normalizeLimit(value, fallback, max) {
409
+ if (value === undefined || value === null || value === '') return fallback
410
+ const number = Number(value)
411
+ if (!Number.isFinite(number) || number < 1) throw invalid('limit must be a positive integer')
412
+ return Math.min(max, Math.trunc(number))
413
+ }
414
+
415
+ function normalizeDueWithin(value, nowMs) {
416
+ if (value === undefined || value === null || value === '') return null
417
+ if (typeof value === 'number') {
418
+ if (!Number.isFinite(value) || value < 0) throw invalid('due-within must be a relative window like 7d/30d or a date')
419
+ return nowMs + Math.trunc(value) * DAY_MS
420
+ }
421
+ if (typeof value !== 'string') throw invalid('due-within must be a relative window like 7d/30d or a date')
422
+ const text = value.trim()
423
+ const unit = text.charAt(text.length - 1)
424
+ const digits = unit === 'd' || unit === 'h' ? text.slice(0, -1) : null
425
+ if (digits !== null && digits.length > 0 && [...digits].every((char) => isDigitCode(char.charCodeAt(0)))) {
426
+ const amount = Number(digits)
427
+ if (!Number.isFinite(amount) || amount < 0) throw invalid('due-within must be a relative window like 7d/30d or a date')
428
+ return nowMs + amount * (unit === 'd' ? DAY_MS : 3600_000)
429
+ }
430
+ const ms = receivableDueInstant(text)
431
+ if (ms === null) throw invalid('due-within must be a relative window like 7d/30d or a date')
432
+ return ms
433
+ }
434
+
435
+ function normalizeSince(value, nowMs) {
436
+ if (value === undefined || value === null || value === '') return null
437
+ if (typeof value === 'number') return nowMs - Math.trunc(value)
438
+ const text = String(value).trim()
439
+ const unit = text.charAt(text.length - 1)
440
+ const digits = unit === 'd' || unit === 'h' ? text.slice(0, -1) : null
441
+ if (digits !== null && digits.length > 0 && [...digits].every((char) => isDigitCode(char.charCodeAt(0)))) {
442
+ const amount = Number(digits)
443
+ if (!Number.isFinite(amount) || amount < 0) throw invalidPayment('since must be a relative window like 90d or an ISO instant')
444
+ return nowMs - amount * (unit === 'd' ? DAY_MS : 3600_000)
445
+ }
446
+ const ms = instantOf(text)
447
+ if (ms === null) throw invalidPayment('since must be a relative window like 90d or an ISO instant')
448
+ return ms
449
+ }
450
+
451
+ function resolveReminderOffsets(value) {
452
+ if (value === undefined || value === null) return undefined
453
+ let list
454
+ if (typeof value === 'string') list = value.split(',')
455
+ else if (Array.isArray(value)) list = value
456
+ else throw invalid('reminder offsets must be an array of offset strings or a comma-separated string')
457
+ try {
458
+ const normalized = normalizeReminderOffsets(list.map((entry) => String(entry).trim()).filter(Boolean))
459
+ return normalized.length ? normalized : []
460
+ } catch (error) {
461
+ throw invalid('invalid reminder offsets: ' + String(error?.message ?? error), 'e.g. "-3d,-1d"')
462
+ }
463
+ }
464
+
465
+ function advisersVersion() {
466
+ try {
467
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
468
+ return typeof pkg.version === 'string' && pkg.version ? pkg.version : null
469
+ } catch {
470
+ return null
471
+ }
472
+ }
473
+
474
+ function sha256HexText(text) {
475
+ return createHash('sha256').update(String(text), 'utf8').digest('hex')
476
+ }
477
+
478
+ /** Honest operator-entered evidence; never contains the amount. */
479
+ function manualEvidence(quote, command, now) {
480
+ const text = String(quote ?? '')
481
+ const version = advisersVersion()
482
+ return {
483
+ kind: 'manual',
484
+ type: 'manual',
485
+ source: 'operator',
486
+ quote: text,
487
+ quoteSha256: sha256HexText(text),
488
+ capturedAt: now,
489
+ capturedBy: 'local',
490
+ command,
491
+ ...(version ? { cliVersion: version } : {}),
492
+ }
493
+ }
494
+
495
+ /* -------------------------------------------------------------------------- */
496
+ /* store access */
497
+ /* -------------------------------------------------------------------------- */
498
+
499
+ function assertStore(store) {
500
+ if (!store || typeof store !== 'object' || !store.db || typeof store.db.prepare !== 'function'
501
+ || typeof store.read !== 'function' || typeof store.getClient !== 'function') {
502
+ throw new TypeError('receivables requires an opened SqliteStore (money sidecars are SQLite-only; ADVISERS_STORE=json has no money tables)')
503
+ }
504
+ }
505
+
506
+ function requireClientRow(store, clientId, operation = 'receivable') {
507
+ const row = store.db.prepare('SELECT * FROM clients WHERE id = ?').get(clientId)
508
+ if (!row) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + clientId, 'advisers client list')
509
+ if (row.deleted_at != null || row.status !== 'active') {
510
+ throw entityError('E_CLIENT_ARCHIVED', 'client is archived: ' + clientId + ' (' + operation + ')', 'advisers client list')
511
+ }
512
+ return row
513
+ }
514
+
515
+ const RECEIVABLE_SELECT = 'SELECT r.*, ' +
516
+ 'c.name AS client_name, c.secrecy_default AS client_secrecy, c.status AS client_status, c.deleted_at AS client_deleted_at, ' +
517
+ 'm.secrecy AS matter_secrecy, m.status AS matter_status, ' +
518
+ 'cm.action AS commitment_action, cm.status AS commitment_status, cm.due_at AS commitment_due_at, ' +
519
+ 'cm.reminder_offsets AS commitment_reminder_offsets, cm.done_at AS commitment_done_at ' +
520
+ 'FROM receivables r ' +
521
+ 'LEFT JOIN clients c ON c.id = r.client_id ' +
522
+ 'LEFT JOIN matters m ON m.id = r.matter_id ' +
523
+ 'LEFT JOIN commitments cm ON cm.id = r.commitment_id '
524
+
525
+ function selectReceivableRows(store, { clientId = null, projectId = null, currency = null } = {}) {
526
+ const where = []
527
+ const params = []
528
+ if (clientId) { where.push('r.client_id = ?'); params.push(clientId) }
529
+ if (projectId) { where.push('r.project_id = ?'); params.push(projectId) }
530
+ if (currency) { where.push('r.currency = ?'); params.push(currency) }
531
+ const sql = RECEIVABLE_SELECT + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ' ORDER BY r.created_at DESC, r.id ASC'
532
+ return store.db.prepare(sql).all(...params)
533
+ }
534
+
535
+ function selectReceivableRow(store, id) {
536
+ return store.db.prepare(RECEIVABLE_SELECT + ' WHERE r.id = ?').get(id)
537
+ }
538
+
539
+ function selectPayments(store, { clientId = null, commitmentIds = null } = {}) {
540
+ let sql = 'SELECT * FROM payments WHERE 1 = 1'
541
+ const params = []
542
+ if (clientId) { sql += ' AND client_id = ?'; params.push(clientId) }
543
+ if (commitmentIds) {
544
+ if (!commitmentIds.length) return []
545
+ sql += ' AND commitment_id IN (' + commitmentIds.map(() => '?').join(',') + ')'
546
+ params.push(...commitmentIds)
547
+ }
548
+ sql += ' ORDER BY paid_at DESC, created_at DESC, id ASC'
549
+ return store.db.prepare(sql).all(...params)
550
+ }
551
+
552
+ function activePaymentsForCommitments(store, commitmentIds, { includeVoided = false } = {}) {
553
+ if (!commitmentIds.length) return []
554
+ const placeholders = commitmentIds.map(() => '?').join(',')
555
+ const sql = 'SELECT * FROM payments WHERE commitment_id IN (' + placeholders + ')' + (includeVoided ? '' : ' AND deleted_at IS NULL') + ' ORDER BY paid_at DESC, created_at DESC, id ASC'
556
+ return store.db.prepare(sql).all(...commitmentIds)
557
+ }
558
+
559
+ function paymentAggregatesByCommitment(payments) {
560
+ const byKey = new Map()
561
+ for (const payment of payments) {
562
+ if (!payment.commitment_id) continue
563
+ const key = payment.commitment_id + AGG_KEY_SEP + payment.currency
564
+ let aggregate = byKey.get(key)
565
+ if (!aggregate) {
566
+ aggregate = { minor: 0n, count: 0, lastPaidAt: null, lastMs: null }
567
+ byKey.set(key, aggregate)
568
+ }
569
+ aggregate.minor += BigInt(payment.amount_minor)
570
+ aggregate.count += 1
571
+ const ms = instantOf(payment.paid_at) ?? instantOf(payment.created_at)
572
+ if (ms !== null && (aggregate.lastMs === null || ms > aggregate.lastMs)) {
573
+ aggregate.lastMs = ms
574
+ aggregate.lastPaidAt = payment.paid_at
575
+ }
576
+ }
577
+ return byKey
578
+ }
579
+
580
+ /* --------------------------- row projection ------------------------------- */
581
+
582
+ function effectiveSecrecy(clientSecrecy, matterSecrecy) {
583
+ const clientLevel = Number(clientSecrecy ?? 0)
584
+ const matterLevel = matterSecrecy === undefined || matterSecrecy === null ? 0 : Number(matterSecrecy)
585
+ if (!Number.isFinite(clientLevel) || !Number.isFinite(matterLevel)) return Number.POSITIVE_INFINITY
586
+ return Math.max(clientLevel, matterLevel)
587
+ }
588
+
589
+ function deriveState(row, paidMinor, dueMs, nowMs) {
590
+ if (row.deleted_at) return 'void'
591
+ if (row.written_off_at) return 'written_off'
592
+ if (paidMinor >= BigInt(row.amount_minor)) return 'settled'
593
+ if (dueMs !== null && dueMs < nowMs) return 'overdue'
594
+ if (paidMinor > 0n) return 'partial'
595
+ return 'open'
596
+ }
597
+
598
+ function overdueDaysOf(dueMs, nowMs) {
599
+ if (dueMs === null || dueMs >= nowMs) return null
600
+ return Math.max(0, Math.floor((nowMs - dueMs) / DAY_MS))
601
+ }
602
+
603
+ function agingBucketOf(state, dueMs, nowMs) {
604
+ if (state !== 'open' && state !== 'partial' && state !== 'overdue') return null
605
+ if (dueMs === null) return 'noDue'
606
+ if (dueMs >= nowMs) return 'notDue'
607
+ const days = Math.floor((nowMs - dueMs) / DAY_MS)
608
+ if (days <= 30) return '0_30'
609
+ if (days <= 60) return '31_60'
610
+ if (days <= 90) return '61_90'
611
+ return '90plus'
612
+ }
613
+
614
+ function parseJsonArray(value) {
615
+ if (typeof value !== 'string' || !value) return undefined
616
+ try {
617
+ const parsed = JSON.parse(value)
618
+ return Array.isArray(parsed) && parsed.every((entry) => typeof entry === 'string') ? parsed : undefined
619
+ } catch {
620
+ return undefined
621
+ }
622
+ }
623
+
624
+ function receivableRowProjection(row, aggregate, { nowMs, clearance }) {
625
+ // Missing client / matter / commitment rows mean dangling data: treat as
626
+ // protected (count only) so no id or label can leak through a broken link.
627
+ if (row.client_name === undefined || row.client_name === null) return { hidden: true }
628
+ if (row.matter_id && row.matter_secrecy === undefined) return { hidden: true }
629
+ if (!row.commitment_action) return { hidden: true }
630
+ const secrecy = effectiveSecrecy(row.client_secrecy, row.matter_id ? row.matter_secrecy : null)
631
+ if (secrecy > clearance) return { hidden: true }
632
+
633
+ const amountMinor = BigInt(row.amount_minor)
634
+ const paidMinor = aggregate ? aggregate.minor : 0n
635
+ const dueMs = receivableDueInstant(row.commitment_due_at)
636
+ const state = deriveState(row, paidMinor, dueMs, nowMs)
637
+ const rawOutstanding = amountMinor > paidMinor ? amountMinor - paidMinor : 0n
638
+ const outstandingMinor = state === 'void' || state === 'written_off' ? 0n : rawOutstanding
639
+ const overpaidMinor = paidMinor > amountMinor ? paidMinor - amountMinor : 0n
640
+ const reminderOffsets = parseJsonArray(row.commitment_reminder_offsets)
641
+
642
+ const receivable = {
643
+ id: row.id,
644
+ commitmentId: row.commitment_id,
645
+ label: String(row.commitment_action ?? ''),
646
+ kind: row.kind,
647
+ ...(row.memo ? { memo: row.memo } : {}),
648
+ clientId: row.client_id,
649
+ clientName: String(row.client_name ?? ''),
650
+ ...(row.project_id ? { projectId: row.project_id } : {}),
651
+ ...(row.matter_id ? { matterId: row.matter_id } : {}),
652
+ ...(row.delivery_id ? { deliveryId: row.delivery_id } : {}),
653
+ amountMinor: minorToNumber(amountMinor),
654
+ amount: formatMinorAmount(amountMinor),
655
+ currency: row.currency,
656
+ paidMinor: minorToNumber(paidMinor),
657
+ paid: formatMinorAmount(paidMinor),
658
+ outstandingMinor: minorToNumber(outstandingMinor),
659
+ outstanding: formatMinorAmount(outstandingMinor),
660
+ ...(overpaidMinor > 0n ? { overpaidMinor: minorToNumber(overpaidMinor), overpaid: formatMinorAmount(overpaidMinor) } : {}),
661
+ state,
662
+ dueAt: row.commitment_due_at ?? null,
663
+ overdueDays: state === 'overdue' ? overdueDaysOf(dueMs, nowMs) : null,
664
+ payments: {
665
+ count: aggregate ? aggregate.count : 0,
666
+ ...(aggregate?.lastPaidAt ? { lastPaidAt: aggregate.lastPaidAt } : {}),
667
+ },
668
+ ...(reminderOffsets ? { reminderOffsets } : {}),
669
+ createdAt: row.created_at,
670
+ ...(row.updated_at && row.updated_at !== row.created_at ? { updatedAt: row.updated_at } : {}),
671
+ ...(row.written_off_at ? { writtenOffAt: row.written_off_at } : {}),
672
+ ...(row.deleted_at ? { deletedAt: row.deleted_at } : {}),
673
+ ...(row.closed_by_payment_id ? { closedByPaymentId: row.closed_by_payment_id } : {}),
674
+ }
675
+ return { hidden: false, receivable, dueMs, amountMinor, paidMinor, outstandingMinor, overpaidMinor, aging: agingBucketOf(state, dueMs, nowMs) }
676
+ }
677
+
678
+ /* ------------------------------ collector --------------------------------- */
679
+
680
+ function emptyTotals(currency) {
681
+ return {
682
+ currency,
683
+ amountMinor: 0,
684
+ paidMinor: 0,
685
+ outstandingMinor: 0,
686
+ overdueMinor: 0,
687
+ overpaidMinor: 0,
688
+ unmatchedMinor: 0,
689
+ count: 0,
690
+ unsettledCount: 0,
691
+ settledCount: 0,
692
+ overdueCount: 0,
693
+ writtenOffCount: 0,
694
+ voidCount: 0,
695
+ aging: { notDue: 0, '0_30': 0, '31_60': 0, '61_90': 0, '90plus': 0, noDue: 0 },
696
+ }
697
+ }
698
+
699
+ function currencyRank(currency) {
700
+ const index = CURRENCIES.indexOf(currency)
701
+ return index === -1 ? CURRENCIES.length : index
702
+ }
703
+
704
+ function compareReceivableRows(left, right) {
705
+ const leftOverdue = left.receivable.state === 'overdue' ? 0 : 1
706
+ const rightOverdue = right.receivable.state === 'overdue' ? 0 : 1
707
+ if (leftOverdue !== rightOverdue) return leftOverdue - rightOverdue
708
+ const leftDue = left.projection.dueMs
709
+ const rightDue = right.projection.dueMs
710
+ if (leftDue !== rightDue) {
711
+ if (leftDue === null) return 1
712
+ if (rightDue === null) return -1
713
+ return leftDue - rightDue
714
+ }
715
+ const leftCreated = left.receivable.createdAt ?? ''
716
+ const rightCreated = right.receivable.createdAt ?? ''
717
+ if (leftCreated !== rightCreated) return leftCreated < rightCreated ? 1 : -1
718
+ return left.receivable.id < right.receivable.id ? -1 : left.receivable.id > right.receivable.id ? 1 : 0
719
+ }
720
+
721
+ /**
722
+ * One read snapshot: select candidate rows + their payments, apply clearance,
723
+ * derive state, apply the caller's filters, then derive per-currency totals and
724
+ * aging. Paging happens afterwards in receivableList.
725
+ */
726
+ function collectReceivables(store, options = {}) {
727
+ assertStore(store)
728
+ const nowMs = Date.parse(nowIso(options.now))
729
+ const clearance = normalizeClearance(options.clearance)
730
+ const clientIdValue = pickOption(options, ['clientId', 'client'])
731
+ const clientId = clientIdValue === undefined ? null : String(clientIdValue).trim()
732
+ const projectIdValue = pickOption(options, ['projectId', 'project'])
733
+ const projectId = projectIdValue === undefined ? null : String(projectIdValue).trim()
734
+ const currencyValue = pickOption(options, ['currency'])
735
+ const currencyFilter = currencyValue === undefined ? null : parseCurrency(currencyValue)
736
+ const statusValue = pickOption(options, ['status'])
737
+ const status = statusValue === undefined ? 'active' : String(statusValue).trim()
738
+ const allowedStatuses = new Set([...RECEIVABLE_STATES, 'active', 'all', 'unsettled'])
739
+ if (!allowedStatuses.has(status)) throw invalid('status must be one of open, partial, overdue, settled, written_off, void, active, all, unsettled')
740
+ const dueWithinMs = normalizeDueWithin(pickOption(options, ['dueWithin', 'due-within']), nowMs)
741
+
742
+ return store.read(() => {
743
+ const candidates = selectReceivableRows(store, { clientId, projectId, currency: currencyFilter })
744
+ const commitmentIds = [...new Set(candidates.map((row) => row.commitment_id).filter(Boolean))]
745
+ let payments
746
+ if (projectId) payments = activePaymentsForCommitments(store, commitmentIds)
747
+ else if (clientId) payments = selectPayments(store, { clientId })
748
+ else payments = selectPayments(store)
749
+ const aggregates = paymentAggregatesByCommitment(payments)
750
+ const unmatched = new Map()
751
+ if (!projectId) {
752
+ for (const payment of payments) {
753
+ if (payment.commitment_id) continue
754
+ const agg = unmatched.get(payment.currency) ?? { minor: 0n, count: 0 }
755
+ agg.minor += BigInt(payment.amount_minor)
756
+ agg.count += 1
757
+ unmatched.set(payment.currency, agg)
758
+ }
759
+ }
760
+
761
+ const rows = []
762
+ let protectedExcluded = 0
763
+ for (const candidate of candidates) {
764
+ const aggregate = aggregates.get(candidate.commitment_id + AGG_KEY_SEP + candidate.currency) ?? null
765
+ const projection = receivableRowProjection(candidate, aggregate, { nowMs, clearance })
766
+ if (projection.hidden) { protectedExcluded += 1; continue }
767
+ const receivable = projection.receivable
768
+ // Filters run after clearance and before totals/paging.
769
+ if (status === 'active') {
770
+ if (receivable.state === 'void') continue
771
+ } else if (status === 'unsettled') {
772
+ if (!(receivable.state === 'open' || receivable.state === 'partial' || receivable.state === 'overdue')) continue
773
+ } else if (status !== 'all' && receivable.state !== status) {
774
+ continue
775
+ }
776
+ if (dueWithinMs !== null) {
777
+ if (projection.dueMs === null || projection.dueMs > dueWithinMs) continue
778
+ }
779
+ rows.push({ receivable, projection })
780
+ }
781
+
782
+ rows.sort(compareReceivableRows)
783
+
784
+ const totalsByCurrency = new Map()
785
+ const ensureTotals = (currency) => {
786
+ let totals = totalsByCurrency.get(currency)
787
+ if (!totals) { totals = emptyTotals(currency); totalsByCurrency.set(currency, totals) }
788
+ return totals
789
+ }
790
+ for (const currency of CURRENCIES) ensureTotals(currency)
791
+ for (const { receivable, projection } of rows) {
792
+ const totals = ensureTotals(receivable.currency)
793
+ totals.count += 1
794
+ if (receivable.state === 'void') totals.voidCount += 1
795
+ else totals.amountMinor = minorAdd(totals.amountMinor, receivable.amountMinor)
796
+ if (receivable.state === 'settled') totals.settledCount += 1
797
+ else if (receivable.state === 'open' || receivable.state === 'partial' || receivable.state === 'overdue') totals.unsettledCount += 1
798
+ if (receivable.state === 'written_off') totals.writtenOffCount += 1
799
+ if (receivable.state === 'overdue') totals.overdueCount += 1
800
+ totals.paidMinor = minorAdd(totals.paidMinor, receivable.paidMinor)
801
+ totals.outstandingMinor = minorAdd(totals.outstandingMinor, receivable.outstandingMinor)
802
+ totals.overpaidMinor = minorAdd(totals.overpaidMinor, receivable.overpaidMinor ?? 0)
803
+ if (receivable.state === 'overdue') totals.overdueMinor = minorAdd(totals.overdueMinor, receivable.outstandingMinor)
804
+ if (projection.aging) totals.aging[projection.aging] += 1
805
+ }
806
+ for (const [currency, agg] of unmatched) {
807
+ const totals = ensureTotals(currency)
808
+ totals.unmatchedMinor = minorAdd(totals.unmatchedMinor, minorToNumber(agg.minor))
809
+ }
810
+ const totals = [...totalsByCurrency.values()]
811
+ .filter((entry) => entry.count > 0 || entry.paidMinor > 0 || entry.unmatchedMinor > 0 || entry.overpaidMinor > 0)
812
+ .sort((left, right) => currencyRank(left.currency) - currencyRank(right.currency))
813
+
814
+ let nextDueMs = null
815
+ for (const { receivable, projection } of rows) {
816
+ if (receivable.state !== 'open' && receivable.state !== 'partial' && receivable.state !== 'overdue') continue
817
+ if (projection.dueMs === null) continue
818
+ if (nextDueMs === null || projection.dueMs < nextDueMs) nextDueMs = projection.dueMs
819
+ }
820
+
821
+ const unsettled = rows.filter(({ receivable }) => receivable.state === 'open' || receivable.state === 'partial' || receivable.state === 'overdue').length
822
+ return {
823
+ rows,
824
+ totals,
825
+ unmatchedPayments: [...unmatched.entries()]
826
+ .map(([currency, agg]) => ({ currency, amountMinor: minorToNumber(agg.minor), amount: formatMinorAmount(agg.minor), count: agg.count }))
827
+ .sort((left, right) => currencyRank(left.currency) - currencyRank(right.currency)),
828
+ protectedExcluded,
829
+ clearance,
830
+ nextDueAt: nextDueMs === null ? null : toShanghaiIso(nextDueMs),
831
+ counts: {
832
+ total: rows.length,
833
+ unsettled,
834
+ settled: rows.filter(({ receivable }) => receivable.state === 'settled').length,
835
+ overdue: rows.filter(({ receivable }) => receivable.state === 'overdue').length,
836
+ writtenOff: rows.filter(({ receivable }) => receivable.state === 'written_off').length,
837
+ void: rows.filter(({ receivable }) => receivable.state === 'void').length,
838
+ },
839
+ }
840
+ })
841
+ }
842
+
843
+ /* -------------------------------------------------------------------------- */
844
+ /* writes */
845
+ /* -------------------------------------------------------------------------- */
846
+
847
+ function commitmentPorts(now) {
848
+ return {
849
+ clock: { now: () => now },
850
+ ids: { next: (prefix) => newId(prefix) },
851
+ }
852
+ }
853
+
854
+ function mapMatter(row) {
855
+ return {
856
+ id: row.id,
857
+ title: row.title,
858
+ status: row.status,
859
+ domain: row.domain,
860
+ secrecy: row.secrecy,
861
+ summary: row.summary ?? undefined,
862
+ participants: safeJson(row.participants, []),
863
+ deadlines: safeJson(row.deadlines, []),
864
+ openQuestions: safeJson(row.open_questions, []),
865
+ createdAt: row.created_at,
866
+ updatedAt: row.updated_at,
867
+ ...(row.client_id == null ? {} : { clientId: row.client_id }),
868
+ ...(row.project_id == null ? {} : { projectId: row.project_id }),
869
+ }
870
+ }
871
+
872
+ function safeJson(value, fallback) {
873
+ if (!value) return fallback
874
+ try { return JSON.parse(value) } catch { return fallback }
875
+ }
876
+
877
+ function createReceivableMatter(store, { client, projectId, now }) {
878
+ const matter = {
879
+ id: newId('matter'),
880
+ title: RECEIVABLE_MATTER_TITLE,
881
+ status: 'active',
882
+ domain: 'customer',
883
+ secrecy: Number(client.secrecy_default ?? 0),
884
+ participants: [],
885
+ deadlines: [],
886
+ openQuestions: [],
887
+ createdAt: now,
888
+ updatedAt: now,
889
+ clientId: client.id,
890
+ ...(projectId ? { projectId } : {}),
891
+ }
892
+ store.insertMatter(matter)
893
+ return matter
894
+ }
895
+
896
+ function validateProjectForClient(store, projectId, clientId) {
897
+ if (!projectId) return null
898
+ const project = store.getProject(projectId)
899
+ if (!project) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + projectId, 'advisers project list --client ' + clientId)
900
+ if (project.clientId !== clientId) throw entityError('E_PROJECT_CLIENT_MISMATCH', 'project ' + projectId + ' does not belong to client ' + clientId)
901
+ return project
902
+ }
903
+
904
+ function resolveMatterForReceivable(store, { client, clientId, projectId, matterId, now }) {
905
+ let project = null
906
+ if (projectId) {
907
+ project = store.getProject(projectId)
908
+ if (!project) throw entityError('E_PROJECT_NOT_FOUND', 'unknown project: ' + projectId, 'advisers project list --client ' + clientId)
909
+ if (project.clientId !== clientId) throw entityError('E_PROJECT_CLIENT_MISMATCH', 'project ' + projectId + ' does not belong to client ' + clientId)
910
+ if (project.status !== 'active' || project.deletedAt) throw entityError('E_PROJECT_ARCHIVED', 'project is archived: ' + projectId, 'advisers project list --client ' + clientId)
911
+ }
912
+ if (matterId) {
913
+ const matter = store.getMatter(matterId)
914
+ if (!matter) throw entityError('E_MATTER_NOT_FOUND', 'unknown matter: ' + matterId, 'advisers matter ls')
915
+ if (matter.status !== 'active') throw entityError('E_MATTER_ARCHIVED', 'matter is archived: ' + matterId, 'advisers matter ls')
916
+ if (matter.clientId !== clientId) throw entityError('E_MATTER_CLIENT_MISMATCH', 'matter ' + matterId + ' does not belong to client ' + clientId)
917
+ if (project && matter.projectId && matter.projectId !== project.id) {
918
+ throw invalid('matter ' + matterId + ' belongs to project ' + matter.projectId + ', not ' + project.id)
919
+ }
920
+ const derivedProjectId = project?.id ?? matter.projectId ?? null
921
+ validateProjectForClient(store, derivedProjectId, clientId)
922
+ return { matter, projectId: derivedProjectId, createdMatter: false }
923
+ }
924
+ if (project) {
925
+ if (project.defaultMatterId) {
926
+ const candidate = store.getMatter(project.defaultMatterId)
927
+ if (candidate && candidate.status === 'active' && candidate.clientId === clientId) {
928
+ return { matter: candidate, projectId: project.id, createdMatter: false }
929
+ }
930
+ }
931
+ const existing = store.db.prepare("SELECT * FROM matters WHERE client_id = ? AND title = ? AND status = 'active' AND project_id = ? ORDER BY rowid LIMIT 1").get(clientId, RECEIVABLE_MATTER_TITLE, project.id)
932
+ if (existing) return { matter: mapMatter(existing), projectId: project.id, createdMatter: false }
933
+ return { matter: createReceivableMatter(store, { client, projectId: project.id, now }), projectId: project.id, createdMatter: true }
934
+ }
935
+ const activeMatters = store.db.prepare("SELECT * FROM matters WHERE client_id = ? AND status = 'active' ORDER BY created_at ASC, rowid ASC").all(clientId)
936
+ if (activeMatters.length === 1) {
937
+ const only = mapMatter(activeMatters[0])
938
+ validateProjectForClient(store, only.projectId ?? null, clientId)
939
+ return { matter: only, projectId: only.projectId ?? null, createdMatter: false }
940
+ }
941
+ const existing = store.db.prepare("SELECT * FROM matters WHERE client_id = ? AND title = ? AND status = 'active' AND project_id IS NULL ORDER BY rowid LIMIT 1").get(clientId, RECEIVABLE_MATTER_TITLE)
942
+ if (existing) return { matter: mapMatter(existing), projectId: null, createdMatter: false }
943
+ return { matter: createReceivableMatter(store, { client, projectId: null, now }), projectId: null, createdMatter: true }
944
+ }
945
+
946
+ function validateDeliveryLineage(store, { deliveryId, clientId, matterId }) {
947
+ if (!deliveryId) return
948
+ const delivery = store.db.prepare('SELECT * FROM deliveries WHERE id = ?').get(deliveryId)
949
+ if (!delivery) throw entityError('E_DELIVERY_INVALID', 'unknown delivery: ' + deliveryId, 'advisers deliveries --json')
950
+ if (delivery.client_id != null && delivery.client_id !== clientId) {
951
+ throw invalid('delivery ' + deliveryId + ' belongs to another client')
952
+ }
953
+ if (delivery.matter_id != null) {
954
+ const matter = store.getMatter(delivery.matter_id)
955
+ if (!matter || matter.clientId !== clientId) throw invalid('delivery ' + deliveryId + ' belongs to a matter outside client ' + clientId)
956
+ if (matterId && delivery.matter_id !== matterId) throw invalid('delivery ' + deliveryId + ' belongs to matter ' + delivery.matter_id + ', not ' + matterId)
957
+ }
958
+ }
959
+
960
+ function insertReceivable(store, row) {
961
+ store.db.prepare('INSERT INTO receivables(id, commitment_id, client_id, project_id, matter_id, delivery_id, amount_minor, currency, kind, memo, closed_by_payment_id, written_off_at, created_at, updated_at, deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(
962
+ row.id,
963
+ row.commitmentId,
964
+ row.clientId,
965
+ row.projectId ?? null,
966
+ row.matterId ?? null,
967
+ row.deliveryId ?? null,
968
+ row.amountMinor,
969
+ row.currency,
970
+ row.kind,
971
+ row.memo ?? null,
972
+ row.closedByPaymentId ?? null,
973
+ row.writtenOffAt ?? null,
974
+ row.createdAt,
975
+ row.updatedAt,
976
+ row.deletedAt ?? null,
977
+ )
978
+ }
979
+
980
+ function readReceivableResult(store, id, { nowMs, clearance = DEFAULT_CLEARANCE, includeVoidedPayments = false } = {}) {
981
+ if (!id) return null
982
+ const row = selectReceivableRow(store, id)
983
+ if (!row) return null
984
+ const payments = activePaymentsForCommitments(store, [row.commitment_id], { includeVoided: includeVoidedPayments })
985
+ const active = includeVoidedPayments ? payments.filter((payment) => payment.deleted_at === null) : payments
986
+ const aggregate = paymentAggregatesByCommitment(active).get(row.commitment_id + AGG_KEY_SEP + row.currency) ?? null
987
+ const projection = receivableRowProjection(row, aggregate, { nowMs, clearance })
988
+ return { row, payments, projection }
989
+ }
990
+
991
+ /**
992
+ * Create a receivable and its follow-up commitment in one audited transaction.
993
+ *
994
+ * @param {object} store opened writable SqliteStore
995
+ * @param {object} input
996
+ * @param {string} input.clientId live client id
997
+ * @param {string} input.label one-line action ("尾款 12 月"), never an amount
998
+ * @param {string|bigint} input.amount decimal string ("8000.00") or BigInt minor units
999
+ * @param {string} [input.currency=CNY] CNY|USD|EUR|HKD
1000
+ * @param {string} [input.dueAt] YYYY-MM-DD or ISO instant (date-only = end of Shanghai day)
1001
+ * @param {string} [input.projectId] optional project owned by the client
1002
+ * @param {string} [input.matterId] optional active matter owned by the client
1003
+ * @param {string} [input.deliveryId] optional delivery owned by the client
1004
+ * @param {string} [input.kind=other] quote|milestone|retainer|other
1005
+ * @param {string} [input.memo] <=200 chars, single line, no absolute paths
1006
+ * @param {string[]|string} [input.reminderOffsets] e.g. ['-3d','-1d'] or "-3d,-1d"
1007
+ * @param {boolean} [input.noRemind] do not write reminder offsets
1008
+ * @param {string|Date} [input.now] injectable clock
1009
+ * @returns {{receivable: object|null, commitment: object, createdMatter: boolean}}
1010
+ */
1011
+ export function receivableAdd(store, input = {}) {
1012
+ assertStore(store)
1013
+ if (typeof store.mutate !== 'function') throw new TypeError('receivableAdd requires a writable SqliteStore')
1014
+ const options = input && typeof input === 'object' ? input : {}
1015
+ const now = nowIso(options.now)
1016
+ const clientId = parseId(options.clientId, 'clientId')
1017
+ const label = normalizeOperatorText('label', options.label, LABEL_MAX)
1018
+ if (!label) throw invalid('a receivable label is required')
1019
+ const amountMinor = parseAmountToMinor(options.amount)
1020
+ const currency = parseCurrency(options.currency)
1021
+ const kind = parseKind(options.kind)
1022
+ const memo = normalizeOperatorText('memo', options.memo, MEMO_MAX)
1023
+ const dueAt = normalizeDueAt(pickOption(options, ['dueAt', 'due']))
1024
+ const optionalId = (...names) => {
1025
+ const value = pickOption(options, names)
1026
+ if (value === undefined) return null
1027
+ const text = String(value).trim()
1028
+ return text || null
1029
+ }
1030
+ const projectId = optionalId('projectId', 'project')
1031
+ const matterId = optionalId('matterId', 'matter')
1032
+ const deliveryId = optionalId('deliveryId', 'delivery')
1033
+ const noRemind = pickOption(options, ['noRemind', 'no-remind']) === true
1034
+ const reminderOffsets = noRemind ? undefined : resolveReminderOffsets(pickOption(options, ['reminderOffsets', 'remindOffsets', 'remind-offsets']))
1035
+ const receivableId = newId('rcv')
1036
+ const audit = { actor: 'local', action: 'receivable.add', allowed: true, reason: receivableId }
1037
+ const made = store.mutate((s) => {
1038
+ const client = requireClientRow(s, clientId, 'receivableAdd')
1039
+ const resolved = resolveMatterForReceivable(s, { client, clientId, projectId, matterId, now })
1040
+ validateDeliveryLineage(s, { deliveryId, clientId, matterId: resolved.matter.id })
1041
+ const commitment = createCommitment(commitmentPorts(now), {
1042
+ matterId: resolved.matter.id,
1043
+ debtor: 'third:' + String(client.name ?? ''),
1044
+ creditor: 'me',
1045
+ action: label,
1046
+ ...(dueAt ? { dueAt } : {}),
1047
+ timezone: 'Asia/Shanghai',
1048
+ capability: 'todo',
1049
+ evidence: [manualEvidence('receivable ' + receivableId, 'receivable add', now)],
1050
+ ...(reminderOffsets && reminderOffsets.length ? { reminderOffsets } : {}),
1051
+ })
1052
+ s.insertCommitment(commitment)
1053
+ insertReceivable(s, {
1054
+ id: receivableId,
1055
+ commitmentId: commitment.id,
1056
+ clientId,
1057
+ projectId: resolved.projectId,
1058
+ matterId: resolved.matter.id,
1059
+ deliveryId,
1060
+ amountMinor: minorToNumber(amountMinor),
1061
+ currency,
1062
+ kind,
1063
+ memo,
1064
+ createdAt: now,
1065
+ updatedAt: now,
1066
+ })
1067
+ audit.reason = receivableId + ' ' + commitment.id + ' client ' + clientId
1068
+ return { resolved, commitment, amountMinor }
1069
+ }, audit)
1070
+ const result = readReceivableResult(store, receivableId, { nowMs: Date.parse(now) })
1071
+ return {
1072
+ receivable: result && !result.projection.hidden ? result.projection.receivable : null,
1073
+ commitment: made.result.commitment,
1074
+ createdMatter: made.result.resolved.createdMatter,
1075
+ }
1076
+ }
1077
+
1078
+ /**
1079
+ * Edit mutable receivable fields (amount, due date, memo, kind, label/reminders).
1080
+ * The amount cannot change while active payments exist (void them first): a
1081
+ * silent re-baseline would make every historical payment ambiguous.
1082
+ *
1083
+ * @param {object} store writable store
1084
+ * @param {string} id receivable id
1085
+ * @param {{amount?: string|bigint, dueAt?: string, memo?: string|null, kind?: string,
1086
+ * label?: string, reminderOffsets?: string[]|string, noRemind?: boolean}} patch
1087
+ * @param {{now?: string|Date}} [options]
1088
+ * @returns {{receivable: object|null, commitment: object}}
1089
+ */
1090
+ export function receivableEdit(store, id, patch = {}, options = {}) {
1091
+ assertStore(store)
1092
+ if (typeof store.mutate !== 'function') throw new TypeError('receivableEdit requires a writable SqliteStore')
1093
+ const receivableId = parseId(id, 'receivable id')
1094
+ const source = patch && typeof patch === 'object' ? patch : {}
1095
+ const requested = { ...source }
1096
+ // CLI spellings that differ from the stored field names.
1097
+ if (requested.dueAt === undefined && requested.due !== undefined) requested.dueAt = requested.due
1098
+ if (requested.reminderOffsets === undefined && requested['remind-offsets'] !== undefined) requested.reminderOffsets = requested['remind-offsets']
1099
+ if (requested.noRemind === undefined && requested['no-remind'] !== undefined) requested.noRemind = requested['no-remind']
1100
+ const now = nowIso(options.now ?? requested.now)
1101
+ const fields = []
1102
+ if (requested.amount !== undefined) fields.push('amount')
1103
+ if (requested.dueAt !== undefined) fields.push('dueAt')
1104
+ if (requested.memo !== undefined) fields.push('memo')
1105
+ if (requested.kind !== undefined) fields.push('kind')
1106
+ if (requested.label !== undefined) fields.push('label')
1107
+ if (requested.reminderOffsets !== undefined || requested.noRemind === true) fields.push('reminders')
1108
+ if (!fields.length) throw invalid('nothing to edit (amount, due, memo, kind, label, reminders)')
1109
+ const amountMinor = requested.amount === undefined ? undefined : parseAmountToMinor(requested.amount)
1110
+ const kind = requested.kind === undefined ? undefined : parseKind(requested.kind)
1111
+ const memoProvided = requested.memo !== undefined
1112
+ const memo = memoProvided ? normalizeOperatorText('memo', requested.memo, MEMO_MAX) : undefined
1113
+ const dueProvided = requested.dueAt !== undefined
1114
+ const dueAt = dueProvided ? normalizeDueAt(requested.dueAt) : undefined
1115
+ if (dueProvided && !dueAt) throw invalid('due date must not be empty')
1116
+ const label = requested.label === undefined ? undefined : normalizeOperatorText('label', requested.label, LABEL_MAX)
1117
+ if (requested.label !== undefined && !label) throw invalid('label must not be empty')
1118
+ let reminderOffsets
1119
+ if (requested.noRemind === true) reminderOffsets = null
1120
+ else if (requested.reminderOffsets !== undefined) {
1121
+ const normalized = resolveReminderOffsets(requested.reminderOffsets)
1122
+ reminderOffsets = normalized && normalized.length ? normalized : null
1123
+ }
1124
+ const audit = { actor: 'local', action: 'receivable.edit', allowed: true, reason: receivableId + ' fields=' + fields.join(',') }
1125
+ const made = store.mutate((s) => {
1126
+ const row = s.db.prepare('SELECT * FROM receivables WHERE id = ?').get(receivableId)
1127
+ if (!row) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1128
+ if (row.deleted_at) throw invalid('receivable is void: ' + receivableId + '; a void record is immutable')
1129
+ const commitment = s.getCommitment(row.commitment_id)
1130
+ if (!commitment) throw invalid('receivable ' + receivableId + ' points at a missing commitment ' + row.commitment_id)
1131
+ const rowPatch = { updated_at: now }
1132
+ const commitmentPatch = {}
1133
+ if (amountMinor !== undefined) {
1134
+ const active = s.db.prepare('SELECT COUNT(*) AS n FROM payments WHERE commitment_id = ? AND deleted_at IS NULL').get(row.commitment_id)
1135
+ if (Number(active?.n ?? 0) > 0) {
1136
+ throw invalid('cannot change the amount of ' + receivableId + ' while ' + Number(active.n) + ' payment(s) exist', 'advisers payment ls --receivable ' + receivableId)
1137
+ }
1138
+ rowPatch.amount_minor = minorToNumber(amountMinor)
1139
+ }
1140
+ if (kind !== undefined) rowPatch.kind = kind
1141
+ if (memoProvided) rowPatch.memo = memo ?? null
1142
+ if (dueProvided) commitmentPatch.dueAt = dueAt ?? null
1143
+ if (label !== undefined) commitmentPatch.action = label
1144
+ if (reminderOffsets !== undefined) commitmentPatch.reminderOffsets = reminderOffsets
1145
+ const sets = Object.keys(rowPatch)
1146
+ s.db.prepare('UPDATE receivables SET ' + sets.map((field) => field + ' = ?').join(', ') + ' WHERE id = ?')
1147
+ .run(...sets.map((field) => rowPatch[field]), receivableId)
1148
+ if (Object.keys(commitmentPatch).length) s.updateCommitment(row.commitment_id, commitmentPatch)
1149
+ return { commitment }
1150
+ }, audit)
1151
+ const result = readReceivableResult(store, receivableId, { nowMs: Date.parse(now) })
1152
+ return {
1153
+ receivable: result && !result.projection.hidden ? result.projection.receivable : null,
1154
+ commitment: made.result.commitment,
1155
+ }
1156
+ }
1157
+
1158
+ /**
1159
+ * Void a receivable (tombstone). Fail closed while active payments exist: void
1160
+ * the payments first so the reopening chain stays exact. The follow-up
1161
+ * commitment is dropped when it is still pending; an auto-completed one is
1162
+ * reopened when the void removes its closed_by_payment_id link.
1163
+ *
1164
+ * @param {object} store writable store
1165
+ * @param {string} id receivable id
1166
+ * @param {{reason?: string, now?: string|Date}} [options]
1167
+ * @returns {{receivable: object|null, alreadyVoid: boolean, reopenedCommitment: boolean,
1168
+ * droppedCommitment: boolean, reason?: string}}
1169
+ */
1170
+ export function receivableVoid(store, id, options = {}) {
1171
+ assertStore(store)
1172
+ if (typeof store.mutate !== 'function') throw new TypeError('receivableVoid requires a writable SqliteStore')
1173
+ const receivableId = parseId(id, 'receivable id')
1174
+ const now = nowIso(options.now)
1175
+ const reason = normalizeOperatorText('reason', options.reason, REASON_MAX)
1176
+ const audit = { actor: 'local', action: 'receivable.void', allowed: true, reason: receivableId }
1177
+ const made = store.mutate((s) => {
1178
+ const row = s.db.prepare('SELECT * FROM receivables WHERE id = ?').get(receivableId)
1179
+ if (!row) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1180
+ if (row.deleted_at) return { alreadyVoid: true, reopenedCommitment: false, droppedCommitment: false }
1181
+ const active = s.db.prepare('SELECT COUNT(*) AS n FROM payments WHERE commitment_id = ? AND deleted_at IS NULL').get(row.commitment_id)
1182
+ if (Number(active?.n ?? 0) > 0) {
1183
+ throw invalid('receivable ' + receivableId + ' still has ' + Number(active.n) + ' active payment(s)', 'advisers payment ls --receivable ' + receivableId + ' (void them first)')
1184
+ }
1185
+ let reopenedCommitment = false
1186
+ let droppedCommitment = false
1187
+ const commitment = s.getCommitment(row.commitment_id)
1188
+ if (row.closed_by_payment_id) {
1189
+ if (commitment && commitment.status === 'done') {
1190
+ s.updateCommitment(row.commitment_id, { status: 'open', doneAt: null })
1191
+ reopenedCommitment = true
1192
+ } else if (commitment && (commitment.status === 'open' || commitment.status === 'snoozed')) {
1193
+ s.updateCommitment(row.commitment_id, { status: 'dropped' })
1194
+ droppedCommitment = true
1195
+ }
1196
+ } else if (commitment && (commitment.status === 'open' || commitment.status === 'snoozed')) {
1197
+ s.updateCommitment(row.commitment_id, { status: 'dropped' })
1198
+ droppedCommitment = true
1199
+ }
1200
+ s.db.prepare('UPDATE receivables SET deleted_at = ?, updated_at = ?, closed_by_payment_id = NULL WHERE id = ?').run(now, now, receivableId)
1201
+ return { alreadyVoid: false, reopenedCommitment, droppedCommitment }
1202
+ }, audit)
1203
+ const result = readReceivableResult(store, receivableId, { nowMs: Date.parse(now), includeVoidedPayments: true })
1204
+ return {
1205
+ receivable: result && !result.projection.hidden ? result.projection.receivable : null,
1206
+ alreadyVoid: made.result.alreadyVoid,
1207
+ reopenedCommitment: made.result.reopenedCommitment,
1208
+ droppedCommitment: made.result.droppedCommitment,
1209
+ ...(reason ? { reason } : {}),
1210
+ }
1211
+ }
1212
+
1213
+ function insertPayment(store, row) {
1214
+ store.db.prepare('INSERT INTO payments(id, client_id, commitment_id, amount_minor, currency, paid_at, method, memo, created_at, updated_at, deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?,NULL)').run(
1215
+ row.id,
1216
+ row.clientId,
1217
+ row.commitmentId ?? null,
1218
+ row.amountMinor,
1219
+ row.currency,
1220
+ row.paidAt,
1221
+ row.method,
1222
+ row.memo ?? null,
1223
+ row.createdAt,
1224
+ row.updatedAt,
1225
+ )
1226
+ }
1227
+
1228
+ /**
1229
+ * Record a payment. With a receivable the currency/client must match, the
1230
+ * outstanding balance is recomputed from the rows, and a full payment completes
1231
+ * the follow-up commitment in the same transaction (unless noComplete).
1232
+ * Without a receivable the payment is an unmatched prepayment.
1233
+ *
1234
+ * @param {object} store writable store
1235
+ * @param {{clientId: string, amount: string|bigint, currency?: string, paidAt?: string,
1236
+ * method?: string, memo?: string, receivableId?: string, commitmentId?: string,
1237
+ * noComplete?: boolean, now?: string|Date}} input
1238
+ * @returns {{payment: object, receivable: object|null, commitment: object|null,
1239
+ * completedCommitment: boolean}}
1240
+ */
1241
+ export function paymentAdd(store, input = {}) {
1242
+ assertStore(store)
1243
+ if (typeof store.mutate !== 'function') throw new TypeError('paymentAdd requires a writable SqliteStore')
1244
+ const options = input && typeof input === 'object' ? input : {}
1245
+ const now = nowIso(options.now)
1246
+ const nowMs = Date.parse(now)
1247
+ const clientId = parseId(options.clientId, 'clientId')
1248
+ const amountMinor = parseAmountToMinor(options.amount, { code: 'E_PAYMENT_INVALID' })
1249
+ // A payment linked to a receivable infers its currency from that receivable;
1250
+ // an unmatched prepayment defaults to CNY. An explicit --currency always wins.
1251
+ const currencyInput = options.currency === undefined || options.currency === null || options.currency === '' ? null : parseCurrency(options.currency, { code: 'E_PAYMENT_INVALID' })
1252
+ const paidAt = normalizePaidAt(pickOption(options, ['paidAt', 'paid-at']), nowMs)
1253
+ const method = parseMethod(options.method)
1254
+ const memo = normalizeOperatorText('memo', options.memo, MEMO_MAX)
1255
+ const noCompleteValue = pickOption(options, ['noComplete', 'no-complete'])
1256
+ if (noCompleteValue !== undefined && typeof noCompleteValue !== 'boolean') throw invalidPayment('noComplete must be a boolean')
1257
+ const noComplete = noCompleteValue === true
1258
+ const optionalId = (...names) => {
1259
+ const value = pickOption(options, names)
1260
+ if (value === undefined) return null
1261
+ const text = String(value).trim()
1262
+ return text || null
1263
+ }
1264
+ const receivableId = optionalId('receivableId', 'receivable')
1265
+ const explicitCommitmentId = optionalId('commitmentId', 'commitment')
1266
+ const paymentId = newId('pay')
1267
+ const audit = { actor: 'local', action: 'payment.add', allowed: true, reason: paymentId }
1268
+ const made = store.mutate((s) => {
1269
+ requireClientRow(s, clientId, 'paymentAdd')
1270
+ let receivableRow = null
1271
+ let commitmentId = explicitCommitmentId
1272
+ if (receivableId) {
1273
+ receivableRow = s.db.prepare('SELECT * FROM receivables WHERE id = ?').get(receivableId)
1274
+ if (!receivableRow) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1275
+ if (receivableRow.deleted_at) throw invalidPayment('receivable is void: ' + receivableId)
1276
+ if (receivableRow.written_off_at) throw invalidPayment('receivable is written off: ' + receivableId)
1277
+ if (receivableRow.client_id !== clientId) throw invalidPayment('receivable ' + receivableId + ' belongs to client ' + receivableRow.client_id + ', not ' + clientId)
1278
+ if (currencyInput && receivableRow.currency !== currencyInput) throw invalidPayment('payment currency ' + currencyInput + ' does not match receivable currency ' + receivableRow.currency + ' (no FX conversion)')
1279
+ if (commitmentId && commitmentId !== receivableRow.commitment_id) throw invalidPayment('receivable ' + receivableId + ' is linked to commitment ' + receivableRow.commitment_id + ', not ' + commitmentId)
1280
+ commitmentId = receivableRow.commitment_id
1281
+ }
1282
+ const currency = currencyInput ?? (receivableRow ? receivableRow.currency : DEFAULT_CURRENCY)
1283
+ let commitment = commitmentId ? s.getCommitment(commitmentId) : null
1284
+ if (commitmentId && !commitment) throw invalidPayment('unknown commitment: ' + commitmentId)
1285
+ if (!receivableRow && commitment) {
1286
+ const matter = s.getMatter(commitment.matterId)
1287
+ if (matter && matter.clientId && matter.clientId !== clientId) throw invalidPayment('commitment ' + commitmentId + ' belongs to another client')
1288
+ }
1289
+ insertPayment(s, {
1290
+ id: paymentId,
1291
+ clientId,
1292
+ commitmentId,
1293
+ amountMinor: minorToNumber(amountMinor),
1294
+ currency,
1295
+ paidAt,
1296
+ method,
1297
+ memo,
1298
+ createdAt: now,
1299
+ updatedAt: now,
1300
+ })
1301
+ let completedCommitment = false
1302
+ if (receivableRow) {
1303
+ const total = s.db.prepare('SELECT COALESCE(SUM(amount_minor), 0) AS paid FROM payments WHERE commitment_id = ? AND deleted_at IS NULL AND currency = ?').get(receivableRow.commitment_id, receivableRow.currency)
1304
+ const paidMinor = BigInt(total?.paid ?? 0)
1305
+ const amount = BigInt(receivableRow.amount_minor)
1306
+ if (!noComplete && paidMinor >= amount && !receivableRow.closed_by_payment_id && commitment && commitment.status !== 'done' && commitment.status !== 'dropped') {
1307
+ const completed = completeCommitment(commitment, [manualEvidence('payment ' + paymentId, 'payment add', now)], now)
1308
+ s.updateCommitment(commitment.id, { status: completed.status, doneAt: completed.doneAt, evidence: completed.evidence })
1309
+ s.db.prepare('UPDATE receivables SET closed_by_payment_id = ?, updated_at = ? WHERE id = ?').run(paymentId, now, receivableRow.id)
1310
+ completedCommitment = true
1311
+ commitment = s.getCommitment(commitment.id)
1312
+ }
1313
+ }
1314
+ audit.reason = paymentId + (receivableRow ? ' ' + receivableRow.id : '') + ' client ' + clientId + ' method=' + method
1315
+ return { commitment, completedCommitment, receivableId: receivableRow ? receivableRow.id : null }
1316
+ }, audit)
1317
+ const result = made.result.receivableId ? readReceivableResult(store, made.result.receivableId, { nowMs }) : null
1318
+ return {
1319
+ payment: paymentFromDb(store.db.prepare('SELECT * FROM payments WHERE id = ?').get(paymentId)),
1320
+ receivable: result && !result.projection.hidden ? result.projection.receivable : null,
1321
+ commitment: made.result.commitment,
1322
+ completedCommitment: made.result.completedCommitment,
1323
+ }
1324
+ }
1325
+
1326
+ function paymentFromDb(row) {
1327
+ return {
1328
+ id: row.id,
1329
+ clientId: row.client_id,
1330
+ ...(row.commitment_id ? { commitmentId: row.commitment_id } : {}),
1331
+ amountMinor: Number(row.amount_minor),
1332
+ amount: formatMinorAmount(BigInt(row.amount_minor)),
1333
+ currency: row.currency,
1334
+ paidAt: row.paid_at,
1335
+ method: row.method,
1336
+ ...(row.memo ? { memo: row.memo } : {}),
1337
+ ...(row.deleted_at ? { deletedAt: row.deleted_at } : {}),
1338
+ createdAt: row.created_at,
1339
+ ...(row.updated_at && row.updated_at !== row.created_at ? { updatedAt: row.updated_at } : {}),
1340
+ }
1341
+ }
1342
+
1343
+ /**
1344
+ * Void a payment (tombstone). When the void drops a settled receivable below its
1345
+ * amount, the follow-up commitment that this money completed is reopened; the
1346
+ * evidence history stays in place. Voiding an overpayment on an already-done
1347
+ * receivable leaves it settled and re-points closed_by_payment_id at a remaining
1348
+ * active payment so a later void still reopens correctly.
1349
+ *
1350
+ * @param {object} store writable store
1351
+ * @param {string} id payment id
1352
+ * @param {{reason?: string, now?: string|Date}} [options]
1353
+ * @returns {{payment: object, receivable: object|null, alreadyVoid: boolean,
1354
+ * reopenedCommitment: boolean, reason?: string}}
1355
+ */
1356
+ export function paymentVoid(store, id, options = {}) {
1357
+ assertStore(store)
1358
+ if (typeof store.mutate !== 'function') throw new TypeError('paymentVoid requires a writable SqliteStore')
1359
+ const paymentId = parseId(id, 'payment id')
1360
+ const now = nowIso(options.now)
1361
+ const reason = normalizeOperatorText('reason', options.reason, REASON_MAX)
1362
+ const audit = { actor: 'local', action: 'payment.void', allowed: true, reason: paymentId }
1363
+ const made = store.mutate((s) => {
1364
+ const payment = s.db.prepare('SELECT * FROM payments WHERE id = ?').get(paymentId)
1365
+ if (!payment) throw entityError('E_PAYMENT_NOT_FOUND', 'unknown payment: ' + paymentId, 'advisers payment ls')
1366
+ if (payment.deleted_at) return { alreadyVoid: true, reopenedCommitment: false, receivableId: null }
1367
+ s.db.prepare('UPDATE payments SET deleted_at = ?, updated_at = ? WHERE id = ?').run(now, now, paymentId)
1368
+ let reopenedCommitment = false
1369
+ let receivableId = null
1370
+ if (payment.commitment_id) {
1371
+ const receivable = s.db.prepare('SELECT * FROM receivables WHERE commitment_id = ?').get(payment.commitment_id)
1372
+ if (receivable && !receivable.deleted_at) {
1373
+ receivableId = receivable.id
1374
+ const total = s.db.prepare('SELECT COALESCE(SUM(amount_minor), 0) AS paid FROM payments WHERE commitment_id = ? AND deleted_at IS NULL AND currency = ?').get(receivable.commitment_id, receivable.currency)
1375
+ const paidMinor = BigInt(total?.paid ?? 0)
1376
+ const amount = BigInt(receivable.amount_minor)
1377
+ if (receivable.closed_by_payment_id) {
1378
+ if (paidMinor >= amount) {
1379
+ const remaining = s.db.prepare('SELECT id FROM payments WHERE commitment_id = ? AND deleted_at IS NULL AND currency = ? ORDER BY paid_at DESC, created_at DESC, id ASC LIMIT 1').get(receivable.commitment_id, receivable.currency)
1380
+ s.db.prepare('UPDATE receivables SET closed_by_payment_id = ?, updated_at = ? WHERE id = ?').run(remaining?.id ?? paymentId, now, receivable.id)
1381
+ } else {
1382
+ const commitment = s.getCommitment(receivable.commitment_id)
1383
+ if (commitment && commitment.status === 'done') {
1384
+ s.updateCommitment(receivable.commitment_id, { status: 'open', doneAt: null })
1385
+ reopenedCommitment = true
1386
+ }
1387
+ s.db.prepare('UPDATE receivables SET closed_by_payment_id = NULL, updated_at = ? WHERE id = ?').run(now, receivable.id)
1388
+ }
1389
+ }
1390
+ }
1391
+ }
1392
+ audit.reason = paymentId + ' reopen=' + (reopenedCommitment ? '1' : '0') + (receivableId ? ' ' + receivableId : '')
1393
+ return { alreadyVoid: false, reopenedCommitment, receivableId }
1394
+ }, audit)
1395
+ const result = made.result.receivableId ? readReceivableResult(store, made.result.receivableId, { nowMs: Date.parse(now), includeVoidedPayments: true }) : null
1396
+ return {
1397
+ payment: paymentFromDb(store.db.prepare('SELECT * FROM payments WHERE id = ?').get(paymentId)),
1398
+ receivable: result && !result.projection.hidden ? result.projection.receivable : null,
1399
+ alreadyVoid: made.result.alreadyVoid,
1400
+ reopenedCommitment: made.result.reopenedCommitment,
1401
+ ...(reason ? { reason } : {}),
1402
+ }
1403
+ }
1404
+
1405
+ /* -------------------------------------------------------------------------- */
1406
+ /* reads */
1407
+ /* -------------------------------------------------------------------------- */
1408
+
1409
+ /**
1410
+ * Page of receivable rows plus per-currency reconciliation totals.
1411
+ *
1412
+ * @param {object} store opened store (read-only stores are fine)
1413
+ * @param {{clientId?:string, projectId?:string, status?:string, currency?:string,
1414
+ * dueWithin?:string|number, clearance?:0|1|2|3, limit?:number,
1415
+ * now?:string|Date}} [options]
1416
+ * @returns {{ok:boolean, command:string, receivables:object[], totals:object[],
1417
+ * total:number, truncated:boolean, limit:number, clearance:number,
1418
+ * protectedExcluded:number}}
1419
+ */
1420
+ export function receivableList(store, options = {}) {
1421
+ const limit = normalizeLimit(options?.limit, RECEIVABLE_LIST_LIMIT, RECEIVABLE_LIST_LIMIT_MAX)
1422
+ const collected = collectReceivables(store, options)
1423
+ const page = collected.rows.slice(0, limit).map(({ receivable }) => receivable)
1424
+ return {
1425
+ ok: true,
1426
+ command: 'receivable ls',
1427
+ receivables: page,
1428
+ totals: collected.totals,
1429
+ total: collected.rows.length,
1430
+ truncated: collected.rows.length > page.length,
1431
+ limit,
1432
+ clearance: collected.clearance,
1433
+ protectedExcluded: collected.protectedExcluded,
1434
+ }
1435
+ }
1436
+
1437
+ /**
1438
+ * Reconciliation summary (amounts, aging, overdue) for a client/project scope.
1439
+ * No row ids are returned; it is the additive client-show aggregation and the
1440
+ * standalone receivables aging/totals view.
1441
+ */
1442
+ export function receivablesSummary(store, options = {}) {
1443
+ const collected = collectReceivables(store, options)
1444
+ return {
1445
+ ok: true,
1446
+ command: 'receivable summary',
1447
+ currency: options?.currency ? parseCurrency(options.currency) : null,
1448
+ ...collected.counts,
1449
+ totals: collected.totals,
1450
+ unmatchedPayments: collected.unmatchedPayments,
1451
+ nextDueAt: collected.nextDueAt,
1452
+ clearance: collected.clearance,
1453
+ protectedExcluded: collected.protectedExcluded,
1454
+ }
1455
+ }
1456
+
1457
+ /**
1458
+ * Additive client show --json block: {count, overdueCount, totals[],
1459
+ * nextDueAt, protectedExcluded}. Counts only unsettled receivables.
1460
+ */
1461
+ export function clientReceivablesBlock(store, clientId, options = {}) {
1462
+ const summary = receivablesSummary(store, { ...(options ?? {}), clientId })
1463
+ return {
1464
+ count: summary.unsettled,
1465
+ overdueCount: summary.overdue,
1466
+ totals: summary.totals,
1467
+ nextDueAt: summary.nextDueAt,
1468
+ protectedExcluded: summary.protectedExcluded,
1469
+ }
1470
+ }
1471
+
1472
+ /**
1473
+ * One receivable with every payment row (voided payments included and marked),
1474
+ * all in one read snapshot. Rows above the clearance fail closed with
1475
+ * E_RECEIVABLE_NOT_FOUND instead of leaking an id.
1476
+ */
1477
+ export function receivableShow(store, id, options = {}) {
1478
+ assertStore(store)
1479
+ const receivableId = parseId(id, 'receivable id')
1480
+ const now = nowIso(options?.now)
1481
+ const clearance = normalizeClearance(options?.clearance)
1482
+ return store.read(() => {
1483
+ const row = selectReceivableRow(store, receivableId)
1484
+ if (!row) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1485
+ const payments = activePaymentsForCommitments(store, [row.commitment_id], { includeVoided: true })
1486
+ const active = payments.filter((payment) => payment.deleted_at === null)
1487
+ const aggregate = paymentAggregatesByCommitment(active).get(row.commitment_id + AGG_KEY_SEP + row.currency) ?? null
1488
+ const projection = receivableRowProjection(row, aggregate, { nowMs: Date.parse(now), clearance })
1489
+ if (projection.hidden) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1490
+ return {
1491
+ ok: true,
1492
+ command: 'receivable show',
1493
+ receivable: projection.receivable,
1494
+ payments: payments.map(paymentFromDb),
1495
+ clearance,
1496
+ protectedExcluded: 0,
1497
+ }
1498
+ })
1499
+ }
1500
+
1501
+ /**
1502
+ * Page of payment rows (active only), optionally scoped to one client or one
1503
+ * receivable. Clearance mirrors the linked receivable/matter.
1504
+ */
1505
+ export function paymentList(store, options = {}) {
1506
+ assertStore(store)
1507
+ const now = nowIso(options?.now)
1508
+ const nowMs = Date.parse(now)
1509
+ const clearance = normalizeClearance(options?.clearance)
1510
+ const limit = normalizeLimit(options?.limit, PAYMENT_LIST_LIMIT, PAYMENT_LIST_LIMIT_MAX)
1511
+ const clientValue = pickOption(options, ['clientId', 'client'])
1512
+ const clientId = clientValue === undefined ? null : String(clientValue).trim()
1513
+ const receivableValue = pickOption(options, ['receivableId', 'receivable'])
1514
+ const receivableId = receivableValue === undefined ? null : String(receivableValue).trim()
1515
+ const sinceMs = normalizeSince(pickOption(options, ['since']), nowMs)
1516
+ return store.read(() => {
1517
+ let commitmentId = null
1518
+ if (receivableId) {
1519
+ const receivable = store.db.prepare('SELECT * FROM receivables WHERE id = ?').get(receivableId)
1520
+ if (!receivable) throw entityError('E_RECEIVABLE_NOT_FOUND', 'unknown receivable: ' + receivableId, 'advisers receivable ls')
1521
+ commitmentId = receivable.commitment_id
1522
+ }
1523
+ const rows = selectPayments(store, { clientId, commitmentIds: commitmentId ? [commitmentId] : null })
1524
+ .filter((payment) => payment.deleted_at === null)
1525
+ const receivablesByCommitment = new Map()
1526
+ const commitmentIds = [...new Set(rows.map((row) => row.commitment_id).filter(Boolean))]
1527
+ if (commitmentIds.length) {
1528
+ const placeholders = commitmentIds.map(() => '?').join(',')
1529
+ for (const row of store.db.prepare('SELECT * FROM receivables WHERE commitment_id IN (' + placeholders + ')').all(...commitmentIds)) {
1530
+ receivablesByCommitment.set(row.commitment_id, row)
1531
+ }
1532
+ }
1533
+ const visible = []
1534
+ let protectedExcluded = 0
1535
+ for (const payment of rows) {
1536
+ if (sinceMs !== null) {
1537
+ const paidMs = instantOf(payment.paid_at)
1538
+ if (paidMs === null || paidMs < sinceMs) continue
1539
+ }
1540
+ const receivable = payment.commitment_id ? receivablesByCommitment.get(payment.commitment_id) ?? null : null
1541
+ const clientRow = store.db.prepare('SELECT * FROM clients WHERE id = ?').get(payment.client_id)
1542
+ if (!clientRow) { protectedExcluded += 1; continue }
1543
+ let secrecy = Number(clientRow.secrecy_default ?? 0)
1544
+ if (receivable && receivable.matter_id) {
1545
+ const matter = store.getMatter(receivable.matter_id)
1546
+ if (!matter) { protectedExcluded += 1; continue }
1547
+ secrecy = Math.max(secrecy, Number(matter.secrecy ?? 0))
1548
+ }
1549
+ if (!Number.isFinite(secrecy) || secrecy > clearance) { protectedExcluded += 1; continue }
1550
+ visible.push({ payment, receivable })
1551
+ }
1552
+ visible.sort((left, right) => {
1553
+ const leftMs = instantOf(left.payment.paid_at) ?? 0
1554
+ const rightMs = instantOf(right.payment.paid_at) ?? 0
1555
+ if (leftMs !== rightMs) return rightMs - leftMs
1556
+ if (left.payment.created_at !== right.payment.created_at) return left.payment.created_at < right.payment.created_at ? 1 : -1
1557
+ return left.payment.id < right.payment.id ? -1 : 1
1558
+ })
1559
+ const page = visible.slice(0, limit).map(({ payment, receivable }) => ({
1560
+ ...paymentFromDb(payment),
1561
+ ...(receivable ? { receivableId: receivable.id } : {}),
1562
+ }))
1563
+ return {
1564
+ ok: true,
1565
+ command: 'payment ls',
1566
+ payments: page,
1567
+ total: visible.length,
1568
+ truncated: visible.length > page.length,
1569
+ limit,
1570
+ clearance,
1571
+ protectedExcluded,
1572
+ }
1573
+ })
1574
+ }
1575
+
1576
+ /* -------------------------------------------------------------------------- */
1577
+ /* integration helpers (bin wiring / merge / archive preconditions) */
1578
+ /* -------------------------------------------------------------------------- */
1579
+
1580
+ /**
1581
+ * Active row counts for status --json (additive keys). Voided tombstones are
1582
+ * excluded; a settled receivable/payment still counts as an existing row.
1583
+ */
1584
+ export function moneyTableCounts(store) {
1585
+ assertStore(store)
1586
+ const receivables = Number(store.db.prepare('SELECT COUNT(*) AS n FROM receivables WHERE deleted_at IS NULL').get()?.n ?? 0)
1587
+ const payments = Number(store.db.prepare('SELECT COUNT(*) AS n FROM payments WHERE deleted_at IS NULL').get()?.n ?? 0)
1588
+ return { receivables, payments }
1589
+ }
1590
+
1591
+ /**
1592
+ * Number of unsettled (outstanding > 0, not written off, not void) receivables
1593
+ * for one client. client archive uses this to fail closed with
1594
+ * E_CLIENT_HAS_OPEN_RECEIVABLES before archiving.
1595
+ */
1596
+ export function openReceivablesCount(store, clientId, options = {}) {
1597
+ assertStore(store)
1598
+ const id = parseId(clientId, 'clientId')
1599
+ const collected = collectReceivables(store, { ...(options ?? {}), clientId: id, clearance: DEFAULT_CLEARANCE, status: 'unsettled' })
1600
+ return collected.rows.length
1601
+ }
1602
+
1603
+ /**
1604
+ * Re-point a merged client's money rows at the merge target. Call INSIDE the
1605
+ * merge transaction AFTER matters/projects were re-pointed: the receivable's
1606
+ * project_id is re-derived from its (already moved) matter, so a merged project
1607
+ * and a re-linked matter stay consistent. Returns the moved row counts used in
1608
+ * the merge JSON summary.
1609
+ */
1610
+ export function moveClientMoneyRows(store, fromId, intoId, options = {}) {
1611
+ assertStore(store)
1612
+ const from = parseId(fromId, 'from client id')
1613
+ const into = parseId(intoId, 'into client id')
1614
+ if (from === into) throw entityError('E_CLIENT_MERGE_SELF', 'cannot merge a client into itself')
1615
+ if (!store.getClient(from)) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + from, 'advisers client list')
1616
+ if (!store.getClient(into)) throw entityError('E_CLIENT_NOT_FOUND', 'unknown client: ' + into, 'advisers client list')
1617
+ const now = nowIso(options.now)
1618
+ const movedReceivables = Number(store.db.prepare('UPDATE receivables SET client_id = ?, project_id = (SELECT project_id FROM matters WHERE matters.id = receivables.matter_id), updated_at = ? WHERE client_id = ?').run(into, now, from).changes)
1619
+ const movedPayments = Number(store.db.prepare('UPDATE payments SET client_id = ?, updated_at = ? WHERE client_id = ?').run(into, now, from).changes)
1620
+ return { movedReceivables, movedPayments }
1621
+ }
1622
+
1623
+ export default Object.freeze({
1624
+ CURRENCIES,
1625
+ DEFAULT_CURRENCY,
1626
+ MAX_AMOUNT_MINOR,
1627
+ RECEIVABLE_KINDS,
1628
+ PAYMENT_METHODS,
1629
+ RECEIVABLE_STATES,
1630
+ DEFAULT_CLEARANCE,
1631
+ RECEIVABLE_LIST_LIMIT,
1632
+ RECEIVABLE_LIST_LIMIT_MAX,
1633
+ PAYMENT_LIST_LIMIT,
1634
+ PAYMENT_LIST_LIMIT_MAX,
1635
+ RECEIVABLE_MATTER_TITLE,
1636
+ parseAmountToMinor,
1637
+ formatMinorAmount,
1638
+ parseCurrency,
1639
+ receivableDueInstant,
1640
+ receivableAdd,
1641
+ receivableEdit,
1642
+ receivableVoid,
1643
+ receivableList,
1644
+ receivableShow,
1645
+ receivablesSummary,
1646
+ clientReceivablesBlock,
1647
+ paymentAdd,
1648
+ paymentList,
1649
+ paymentVoid,
1650
+ moneyTableCounts,
1651
+ openReceivablesCount,
1652
+ moveClientMoneyRows,
1653
+ })