advisers 0.3.1 → 0.3.2
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.
- package/README-zh.md +8 -9
- package/README.md +15 -14
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +561 -63
- package/index.js +1 -1
- package/lib/customer-read.js +524 -0
- package/lib/evidence.js +233 -9
- package/lib/ledger-read.js +109 -1
- package/lib/mcp-server.js +202 -2
- package/lib/receipt-verify.js +84 -7
- package/lib/sqlite.js +135 -0
- package/lib/tui/labels.js +1 -1
- package/lib/tui/render.js +1 -1
- package/package.json +4 -4
package/index.js
CHANGED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Customer read projection (0.3.2 M3): pure, read-only views over an ALREADY
|
|
3
|
+
* OPENED SqliteStore.
|
|
4
|
+
*
|
|
5
|
+
* This module is the single place that derives the customer list/status shapes
|
|
6
|
+
* used by the MCP server (advisers_clients + advisers://clients) and the DSH
|
|
7
|
+
* adapter. It performs no writes, no migrations and no HOME handling; the
|
|
8
|
+
* caller owns the connection (MCP: the long-lived store; DSH: the read-only
|
|
9
|
+
* facade in lib/ledger-read.js).
|
|
10
|
+
*
|
|
11
|
+
* Frozen rules (0.3.0 schema v21 customer entities, docs/CLIENTS.md):
|
|
12
|
+
* - one store.read() snapshot per call: every SELECT below sees the same WAL
|
|
13
|
+
* snapshot, so a concurrent writer can never make counts disagree with rows;
|
|
14
|
+
* - every query is scoped by the client's own matter ids (or by the delivery
|
|
15
|
+
* lineage snapshot client_id), never a full-table read followed by an
|
|
16
|
+
* in-memory filter of another client's rows;
|
|
17
|
+
* - effective secrecy of a matter = max(client.secrecyDefault, matter.secrecy);
|
|
18
|
+
* rows above the clearance are filtered BEFORE counting, paging and limiting
|
|
19
|
+
* and are only counted in protectedExcluded (no id/title/name is returned);
|
|
20
|
+
* - notes are counted, never returned (this projection has no note-body field
|
|
21
|
+
* at all); no conversation/turn text is ever read;
|
|
22
|
+
* - the timeline only contains delivery/commitment rows (never note bodies),
|
|
23
|
+
* ordered by instant DESC, then delivery > commitment, then id ASC;
|
|
24
|
+
* - a delivery whose matter cannot be resolved inside the visible scope (for
|
|
25
|
+
* example a generation-time client snapshot whose matter was re-linked, or a
|
|
26
|
+
* dangling matter id) is treated as protected: it is counted, never returned.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** Client-row list page default (the MCP resource/tool default is 20). */
|
|
30
|
+
export const CUSTOMER_LIST_LIMIT = 50
|
|
31
|
+
/** Hard cap for one client-row page. */
|
|
32
|
+
export const CUSTOMER_LIST_LIMIT_MAX = 200
|
|
33
|
+
/** Timeline page default. */
|
|
34
|
+
export const CUSTOMER_TIMELINE_LIMIT = 20
|
|
35
|
+
/** Hard cap for one timeline page. */
|
|
36
|
+
export const CUSTOMER_TIMELINE_LIMIT_MAX = 200
|
|
37
|
+
/** Open mine/waiting list default. */
|
|
38
|
+
export const CUSTOMER_OPEN_LIMIT = 20
|
|
39
|
+
/** Hard cap for one open list. */
|
|
40
|
+
export const CUSTOMER_OPEN_LIMIT_MAX = 200
|
|
41
|
+
|
|
42
|
+
const TITLE_MAX = 120
|
|
43
|
+
const DAY_MS = 86400_000
|
|
44
|
+
const SHANGHAI_OFFSET_MS = 8 * 3600_000
|
|
45
|
+
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/
|
|
46
|
+
const LOCAL_TIME_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/
|
|
47
|
+
/** Kind order used by the frozen timeline sort (delivery before commitment). */
|
|
48
|
+
const KIND_RANK = Object.freeze({ delivery: 0, commitment: 1 })
|
|
49
|
+
|
|
50
|
+
/* -------------------------------------------------------------------------- */
|
|
51
|
+
/* small pure helpers */
|
|
52
|
+
/* -------------------------------------------------------------------------- */
|
|
53
|
+
|
|
54
|
+
function finiteNumber(value, fallback = 0) {
|
|
55
|
+
const number = Number(value)
|
|
56
|
+
return Number.isFinite(number) ? number : fallback
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeClearance(value) {
|
|
60
|
+
const number = Number(value)
|
|
61
|
+
if (!Number.isFinite(number) || number < 0) return 0
|
|
62
|
+
return Math.floor(number)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function clampLimit(value, def, max) {
|
|
66
|
+
if (value === undefined || value === null) return def
|
|
67
|
+
const number = Number(value)
|
|
68
|
+
if (!Number.isInteger(number) || number < 1) return def
|
|
69
|
+
return Math.min(number, max)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** max(client.secrecyDefault, matter.secrecy); a dirty value fails closed. */
|
|
73
|
+
function effectiveMatterSecrecy(client, matter) {
|
|
74
|
+
const clientLevel = client?.secrecyDefault === undefined || client?.secrecyDefault === null
|
|
75
|
+
? 0
|
|
76
|
+
: finiteNumber(client.secrecyDefault, Number.POSITIVE_INFINITY)
|
|
77
|
+
const matterLevel = matter?.secrecy === undefined || matter?.secrecy === null
|
|
78
|
+
? 0
|
|
79
|
+
: finiteNumber(matter.secrecy, Number.POSITIVE_INFINITY)
|
|
80
|
+
if (!Number.isFinite(clientLevel) || !Number.isFinite(matterLevel)) return Number.POSITIVE_INFINITY
|
|
81
|
+
return Math.max(clientLevel, matterLevel)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function clientDefaultSecrecy(client) {
|
|
85
|
+
return finiteNumber(client?.secrecyDefault, Number.POSITIVE_INFINITY)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Single-line display title (max 120 chars), never a file path. */
|
|
89
|
+
function timelineTitle(value) {
|
|
90
|
+
const text = String(value ?? '').replace(/\s+/gu, ' ').trim()
|
|
91
|
+
if (!text) return ''
|
|
92
|
+
const chars = Array.from(text)
|
|
93
|
+
if (chars.length <= TITLE_MAX) return text
|
|
94
|
+
return chars.slice(0, TITLE_MAX - 1).join('') + '\u2026'
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Parse a stored ISO/epoch timestamp; null when it cannot be trusted. */
|
|
98
|
+
function instantOf(value) {
|
|
99
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : null
|
|
100
|
+
if (typeof value !== 'string') return null
|
|
101
|
+
const text = value.trim()
|
|
102
|
+
if (!text) return null
|
|
103
|
+
const ms = Date.parse(text)
|
|
104
|
+
return Number.isFinite(ms) ? ms : null
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function agendaDayEndInstant(day) {
|
|
108
|
+
if (!DATE_ONLY_RE.test(day)) return null
|
|
109
|
+
const parts = day.split('-').map(Number)
|
|
110
|
+
return Date.UTC(parts[0], parts[1] - 1, parts[2]) - SHANGHAI_OFFSET_MS + DAY_MS - 1
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Resolve a stored dueAt to an absolute instant (same rule as the CLI):
|
|
115
|
+
* YYYY-MM-DD -> end of that Shanghai day, local ISO without zone -> +08:00,
|
|
116
|
+
* anything with Z/offset -> its absolute instant. Null for dirty data.
|
|
117
|
+
*/
|
|
118
|
+
function dueInstantOf(value) {
|
|
119
|
+
if (value === undefined || value === null) return null
|
|
120
|
+
const text = String(value).trim()
|
|
121
|
+
if (!text) return null
|
|
122
|
+
if (DATE_ONLY_RE.test(text)) return agendaDayEndInstant(text)
|
|
123
|
+
if (LOCAL_TIME_RE.test(text)) {
|
|
124
|
+
const ms = Date.parse(text.replace(' ', 'T') + '+08:00')
|
|
125
|
+
return Number.isFinite(ms) ? ms : null
|
|
126
|
+
}
|
|
127
|
+
const ms = Date.parse(text)
|
|
128
|
+
return Number.isFinite(ms) ? ms : null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** UTC instant -> Shanghai wall-clock ISO string with an explicit +08:00 offset. */
|
|
132
|
+
function toShanghaiIso(ms) {
|
|
133
|
+
return new Date(ms + SHANGHAI_OFFSET_MS).toISOString().replace('Z', '+08:00')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function nextDueAt(openRows) {
|
|
137
|
+
let next = null
|
|
138
|
+
for (const row of openRows) {
|
|
139
|
+
const ms = dueInstantOf(row.due_at)
|
|
140
|
+
if (ms !== null && (next === null || ms < next)) next = ms
|
|
141
|
+
}
|
|
142
|
+
return next === null ? null : toShanghaiIso(next)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function overdueCount(openRows) {
|
|
146
|
+
const nowMs = Date.now()
|
|
147
|
+
let count = 0
|
|
148
|
+
for (const row of openRows) {
|
|
149
|
+
const ms = dueInstantOf(row.due_at)
|
|
150
|
+
if (ms !== null && ms < nowMs) count += 1
|
|
151
|
+
}
|
|
152
|
+
return count
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function stringList(value) {
|
|
156
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : []
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function assertStore(store) {
|
|
160
|
+
if (!store || typeof store.read !== 'function' || !store.db || typeof store.db.prepare !== 'function'
|
|
161
|
+
|| typeof store.listMattersByClient !== 'function' || typeof store.listClients !== 'function'
|
|
162
|
+
|| typeof store.getClient !== 'function') {
|
|
163
|
+
throw new TypeError('customer-read requires an opened SqliteStore (customer tables are SQLite-only)')
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/* -------------------------------------------------------------------------- */
|
|
168
|
+
/* SQL helpers (table names are internal constants, never caller input) */
|
|
169
|
+
/* -------------------------------------------------------------------------- */
|
|
170
|
+
|
|
171
|
+
const COUNT_TABLES = new Set(['commitments', 'deliveries'])
|
|
172
|
+
|
|
173
|
+
function matterPlaceholders(ids) {
|
|
174
|
+
return ids.map(() => '?').join(',')
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Exact COUNT(*) on one client-scoped table. */
|
|
178
|
+
function countByMatter(store, table, ids) {
|
|
179
|
+
if (!COUNT_TABLES.has(table)) throw new TypeError('unexpected customer count table: ' + String(table))
|
|
180
|
+
if (!ids.length) return 0
|
|
181
|
+
const row = store.db.prepare('SELECT COUNT(*) AS n FROM ' + table + ' WHERE matter_id IN (' + matterPlaceholders(ids) + ')').get(...ids)
|
|
182
|
+
return Number(row?.n ?? 0)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Open commitments on the client's visible matters, insertion order. */
|
|
186
|
+
function openCommitmentRows(store, ids) {
|
|
187
|
+
if (!ids.length) return []
|
|
188
|
+
return store.db.prepare(
|
|
189
|
+
'SELECT id, matter_id, action, debtor, creditor, due_at FROM commitments WHERE status = ? AND matter_id IN (' + matterPlaceholders(ids) + ') ORDER BY rowid',
|
|
190
|
+
).all('open', ...ids)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Note counts grouped by (project, matter) for one client; never the body. */
|
|
194
|
+
function noteGroups(store, clientId) {
|
|
195
|
+
const rows = store.db.prepare(
|
|
196
|
+
'SELECT project_id, matter_id, COUNT(*) AS n FROM client_notes WHERE client_id = ? AND deleted_at IS NULL GROUP BY project_id, matter_id',
|
|
197
|
+
).all(clientId)
|
|
198
|
+
return rows.map((row) => ({
|
|
199
|
+
projectId: row.project_id === null || row.project_id === undefined ? undefined : row.project_id,
|
|
200
|
+
matterId: row.matter_id === null || row.matter_id === undefined ? undefined : row.matter_id,
|
|
201
|
+
n: Number(row.n ?? 0),
|
|
202
|
+
}))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Client-level visible note count + withheld client-level notes (no bodies). */
|
|
206
|
+
function clientNoteStats(client, groups, allowedIds, clearance) {
|
|
207
|
+
const clientLevel = clientDefaultSecrecy(client)
|
|
208
|
+
let count = 0
|
|
209
|
+
let withheld = 0
|
|
210
|
+
for (const group of groups) {
|
|
211
|
+
if (group.matterId === undefined) {
|
|
212
|
+
if (clientLevel <= clearance) count += group.n
|
|
213
|
+
else withheld += group.n
|
|
214
|
+
} else if (allowedIds.has(group.matterId)) {
|
|
215
|
+
count += group.n
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { count, withheld }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Project-scoped visible note count (explicit project id OR one of its matters). */
|
|
222
|
+
function projectNoteStats(client, groups, projectId, projectAllowedIds, clearance) {
|
|
223
|
+
const clientLevel = clientDefaultSecrecy(client)
|
|
224
|
+
let count = 0
|
|
225
|
+
for (const group of groups) {
|
|
226
|
+
const viaProject = group.projectId === projectId
|
|
227
|
+
const viaMatter = group.matterId !== undefined && projectAllowedIds.has(group.matterId)
|
|
228
|
+
if (!viaProject && !viaMatter) continue
|
|
229
|
+
if (group.matterId === undefined) {
|
|
230
|
+
if (clientLevel <= clearance) count += group.n
|
|
231
|
+
} else if (projectAllowedIds.has(group.matterId)) {
|
|
232
|
+
count += group.n
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return count
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/* -------------------------------------------------------------------------- */
|
|
239
|
+
/* open-commitment split */
|
|
240
|
+
/* -------------------------------------------------------------------------- */
|
|
241
|
+
|
|
242
|
+
function isWaitingOnClient(row) {
|
|
243
|
+
return typeof row?.debtor === 'string' && row.debtor.startsWith('third:')
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function openRowView(row, matterById, client) {
|
|
247
|
+
const view = {
|
|
248
|
+
id: String(row.id),
|
|
249
|
+
action: String(row.action ?? ''),
|
|
250
|
+
debtor: String(row.debtor ?? ''),
|
|
251
|
+
creditor: String(row.creditor ?? ''),
|
|
252
|
+
status: 'open',
|
|
253
|
+
}
|
|
254
|
+
if (row.matter_id !== null && row.matter_id !== undefined) view.matterId = String(row.matter_id)
|
|
255
|
+
if (row.due_at !== null && row.due_at !== undefined) view.dueAt = String(row.due_at)
|
|
256
|
+
const matter = view.matterId === undefined ? undefined : matterById.get(view.matterId)
|
|
257
|
+
if (matter?.projectId !== undefined && matter.projectId !== null) view.projectId = String(matter.projectId)
|
|
258
|
+
view.secrecy = matter ? effectiveMatterSecrecy(client, matter) : clientDefaultSecrecy(client)
|
|
259
|
+
return view
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function byDueThenId(a, b) {
|
|
263
|
+
const aMs = dueInstantOf(a.dueAt)
|
|
264
|
+
const bMs = dueInstantOf(b.dueAt)
|
|
265
|
+
if (aMs === null && bMs === null) return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
|
|
266
|
+
if (aMs === null) return 1
|
|
267
|
+
if (bMs === null) return -1
|
|
268
|
+
if (aMs !== bMs) return aMs - bMs
|
|
269
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function splitOpenRows(rows, matterById, client) {
|
|
273
|
+
const mine = []
|
|
274
|
+
const waiting = []
|
|
275
|
+
for (const row of rows) {
|
|
276
|
+
const view = openRowView(row, matterById, client)
|
|
277
|
+
if (isWaitingOnClient(row)) waiting.push(view)
|
|
278
|
+
else mine.push(view)
|
|
279
|
+
}
|
|
280
|
+
mine.sort(byDueThenId)
|
|
281
|
+
waiting.sort(byDueThenId)
|
|
282
|
+
return { mine, waiting }
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/* -------------------------------------------------------------------------- */
|
|
286
|
+
/* shared per-client projection */
|
|
287
|
+
/* -------------------------------------------------------------------------- */
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* One client's visible read model, inside the caller's store.read() snapshot.
|
|
291
|
+
* The caller owns the snapshot: this helper performs the SELECTs directly.
|
|
292
|
+
*/
|
|
293
|
+
function projectClient(store, client, clearance) {
|
|
294
|
+
const matters = store.listMattersByClient(client.id)
|
|
295
|
+
const visibleMatters = []
|
|
296
|
+
let protectedMatters = 0
|
|
297
|
+
for (const matter of matters) {
|
|
298
|
+
if (effectiveMatterSecrecy(client, matter) <= clearance) visibleMatters.push(matter)
|
|
299
|
+
else protectedMatters += 1
|
|
300
|
+
}
|
|
301
|
+
const allowedIds = new Set(visibleMatters.map((matter) => matter.id))
|
|
302
|
+
const matterById = new Map(visibleMatters.map((matter) => [matter.id, matter]))
|
|
303
|
+
const groups = noteGroups(store, client.id)
|
|
304
|
+
const notes = clientNoteStats(client, groups, allowedIds, clearance)
|
|
305
|
+
const ids = [...allowedIds]
|
|
306
|
+
const openRows = openCommitmentRows(store, ids)
|
|
307
|
+
const split = splitOpenRows(openRows, matterById, client)
|
|
308
|
+
const counts = {
|
|
309
|
+
matters: visibleMatters.length,
|
|
310
|
+
mattersArchived: visibleMatters.filter((matter) => matter.status === 'archived').length,
|
|
311
|
+
deliveries: countByMatter(store, 'deliveries', ids),
|
|
312
|
+
notes: notes.count,
|
|
313
|
+
commitments: countByMatter(store, 'commitments', ids),
|
|
314
|
+
openMine: split.mine.length,
|
|
315
|
+
openWaiting: split.waiting.length,
|
|
316
|
+
overdue: overdueCount(openRows),
|
|
317
|
+
}
|
|
318
|
+
return { client, visibleMatters, matterById, allowedIds, ids, groups, notes, openRows, split, counts, protectedMatters }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/* -------------------------------------------------------------------------- */
|
|
322
|
+
/* timeline (delivery + commitment only; notes are counted, never shown) */
|
|
323
|
+
/* -------------------------------------------------------------------------- */
|
|
324
|
+
|
|
325
|
+
function buildTimeline(store, client, projection, timelineLimit) {
|
|
326
|
+
const { ids, matterById } = projection
|
|
327
|
+
const fetchLimit = timelineLimit + 20
|
|
328
|
+
const items = []
|
|
329
|
+
let protectedDeliveries = 0
|
|
330
|
+
let deliveryRows = []
|
|
331
|
+
if (ids.length) {
|
|
332
|
+
deliveryRows = store.db.prepare(
|
|
333
|
+
'SELECT id, matter_id, title, tool, created_at FROM deliveries WHERE matter_id IN (' + matterPlaceholders(ids) + ') OR client_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?',
|
|
334
|
+
).all(...ids, client.id, fetchLimit)
|
|
335
|
+
} else {
|
|
336
|
+
deliveryRows = store.db.prepare(
|
|
337
|
+
'SELECT id, matter_id, title, tool, created_at FROM deliveries WHERE client_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?',
|
|
338
|
+
).all(client.id, fetchLimit)
|
|
339
|
+
}
|
|
340
|
+
for (const row of deliveryRows) {
|
|
341
|
+
const matter = row.matter_id === null || row.matter_id === undefined ? undefined : matterById.get(row.matter_id)
|
|
342
|
+
if (!matter) { protectedDeliveries += 1; continue }
|
|
343
|
+
const at = String(row.created_at ?? '')
|
|
344
|
+
const ms = instantOf(at)
|
|
345
|
+
if (ms === null) continue
|
|
346
|
+
items.push({
|
|
347
|
+
at,
|
|
348
|
+
kind: 'delivery',
|
|
349
|
+
title: timelineTitle(row.title) || timelineTitle(row.tool) || String(row.id),
|
|
350
|
+
ref: { kind: 'delivery', id: String(row.id) },
|
|
351
|
+
matterId: String(matter.id),
|
|
352
|
+
secrecy: effectiveMatterSecrecy(client, matter),
|
|
353
|
+
_ms: ms,
|
|
354
|
+
})
|
|
355
|
+
}
|
|
356
|
+
if (ids.length) {
|
|
357
|
+
const commitmentRows = store.db.prepare(
|
|
358
|
+
"SELECT id, matter_id, action, created_at FROM commitments WHERE matter_id IN (" + matterPlaceholders(ids) + ") AND created_at IS NOT NULL AND created_at != '' ORDER BY created_at DESC, rowid DESC LIMIT ?",
|
|
359
|
+
).all(...ids, fetchLimit)
|
|
360
|
+
for (const row of commitmentRows) {
|
|
361
|
+
const matter = matterById.get(row.matter_id)
|
|
362
|
+
if (!matter) continue
|
|
363
|
+
const at = String(row.created_at ?? '')
|
|
364
|
+
const ms = instantOf(at)
|
|
365
|
+
if (ms === null) continue
|
|
366
|
+
items.push({
|
|
367
|
+
at,
|
|
368
|
+
kind: 'commitment',
|
|
369
|
+
title: timelineTitle(row.action) || String(row.id),
|
|
370
|
+
ref: { kind: 'commitment', id: String(row.id) },
|
|
371
|
+
matterId: String(matter.id),
|
|
372
|
+
secrecy: effectiveMatterSecrecy(client, matter),
|
|
373
|
+
_ms: ms,
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const deliveryTotal = countByMatter(store, 'deliveries', ids)
|
|
378
|
+
let commitmentTotal = 0
|
|
379
|
+
if (ids.length) {
|
|
380
|
+
commitmentTotal = Number(store.db.prepare(
|
|
381
|
+
"SELECT COUNT(*) AS n FROM commitments WHERE matter_id IN (" + matterPlaceholders(ids) + ") AND created_at IS NOT NULL AND created_at != ''",
|
|
382
|
+
).get(...ids)?.n ?? 0)
|
|
383
|
+
}
|
|
384
|
+
items.sort((a, b) => (b._ms - a._ms) || (KIND_RANK[a.kind] - KIND_RANK[b.kind]) || (a.ref.id < b.ref.id ? -1 : a.ref.id > b.ref.id ? 1 : 0))
|
|
385
|
+
const page = items.slice(0, timelineLimit).map(({ _ms, ...item }) => item)
|
|
386
|
+
const total = deliveryTotal + commitmentTotal
|
|
387
|
+
return { items: page, total, truncated: total > page.length, protectedDeliveries }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/* -------------------------------------------------------------------------- */
|
|
391
|
+
/* public API */
|
|
392
|
+
/* -------------------------------------------------------------------------- */
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* List customer rows (active by default; archived only with includeArchived).
|
|
396
|
+
*
|
|
397
|
+
* Pagination happens AFTER the per-client secrecy filter/count derivation, so
|
|
398
|
+
* a truncated page never changes the meaning of a row's counts. `total` is the
|
|
399
|
+
* post-filter client count; `protectedExcluded` counts the protected matters
|
|
400
|
+
* and client-level notes of the returned rows.
|
|
401
|
+
*
|
|
402
|
+
* @param {object} store opened SqliteStore
|
|
403
|
+
* @param {{clearance?:number, limit?:number, includeArchived?:boolean}} [options]
|
|
404
|
+
* @returns {{rows:Array<object>, total:number, limit:number, clearance:number, protectedExcluded:number}}
|
|
405
|
+
*/
|
|
406
|
+
export function listClientRows(store, { clearance = 0, limit = CUSTOMER_LIST_LIMIT, includeArchived = false } = {}) {
|
|
407
|
+
assertStore(store)
|
|
408
|
+
const level = normalizeClearance(clearance)
|
|
409
|
+
const pageLimit = clampLimit(limit, CUSTOMER_LIST_LIMIT, CUSTOMER_LIST_LIMIT_MAX)
|
|
410
|
+
const archived = includeArchived === true
|
|
411
|
+
return store.read(() => {
|
|
412
|
+
const where = archived ? '' : " WHERE status = 'active' AND deleted_at IS NULL"
|
|
413
|
+
const total = Number(store.db.prepare('SELECT COUNT(*) AS n FROM clients' + where).get()?.n ?? 0)
|
|
414
|
+
const clients = store.listClients({
|
|
415
|
+
status: archived ? 'all' : 'active',
|
|
416
|
+
includeDeleted: archived,
|
|
417
|
+
limit: pageLimit,
|
|
418
|
+
})
|
|
419
|
+
const rows = []
|
|
420
|
+
let protectedExcluded = 0
|
|
421
|
+
for (const client of clients) {
|
|
422
|
+
const projection = projectClient(store, client, level)
|
|
423
|
+
const withheld = projection.protectedMatters + projection.notes.withheld
|
|
424
|
+
protectedExcluded += withheld
|
|
425
|
+
rows.push({
|
|
426
|
+
id: String(client.id),
|
|
427
|
+
name: String(client.name ?? ''),
|
|
428
|
+
status: String(client.status ?? ''),
|
|
429
|
+
aliases: stringList(client.aliases),
|
|
430
|
+
secrecyDefault: finiteNumber(client.secrecyDefault, 0),
|
|
431
|
+
tags: stringList(client.tags),
|
|
432
|
+
counts: projection.counts,
|
|
433
|
+
nextDueAt: nextDueAt(projection.openRows),
|
|
434
|
+
clearance: level,
|
|
435
|
+
protectedExcluded: withheld,
|
|
436
|
+
})
|
|
437
|
+
}
|
|
438
|
+
return { rows, total, limit: pageLimit, clearance: level, protectedExcluded }
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* One client status view: identity (no notes body), project summaries, exact
|
|
444
|
+
* counts, open mine/waiting items and a derived delivery/commitment timeline.
|
|
445
|
+
* Returns null for an unknown client id (the caller decides how to map that;
|
|
446
|
+
* the store itself is not the error source).
|
|
447
|
+
*
|
|
448
|
+
* @param {object} store opened SqliteStore
|
|
449
|
+
* @param {string} id client id
|
|
450
|
+
* @param {{clearance?:number, timelineLimit?:number, openLimit?:number}} [options]
|
|
451
|
+
* @returns {object|null}
|
|
452
|
+
*/
|
|
453
|
+
export function readClientStatus(store, id, { clearance = 0, timelineLimit = CUSTOMER_TIMELINE_LIMIT, openLimit = CUSTOMER_OPEN_LIMIT } = {}) {
|
|
454
|
+
assertStore(store)
|
|
455
|
+
const key = typeof id === 'string' ? id.trim() : ''
|
|
456
|
+
if (!key) return null
|
|
457
|
+
const level = normalizeClearance(clearance)
|
|
458
|
+
const timelinePage = clampLimit(timelineLimit, CUSTOMER_TIMELINE_LIMIT, CUSTOMER_TIMELINE_LIMIT_MAX)
|
|
459
|
+
const openPage = clampLimit(openLimit, CUSTOMER_OPEN_LIMIT, CUSTOMER_OPEN_LIMIT_MAX)
|
|
460
|
+
return store.read(() => {
|
|
461
|
+
const client = store.getClient(key)
|
|
462
|
+
if (!client) return null
|
|
463
|
+
const projection = projectClient(store, client, level)
|
|
464
|
+
const timeline = buildTimeline(store, client, projection, timelinePage)
|
|
465
|
+
const projects = store.listProjects({ clientId: client.id, status: 'all', includeDeleted: true, limit: 1000 }).map((project) => {
|
|
466
|
+
const projectMatters = projection.visibleMatters.filter((matter) => matter.projectId === project.id)
|
|
467
|
+
const projectIds = projectMatters.map((matter) => matter.id)
|
|
468
|
+
const projectAllowed = new Set(projectIds)
|
|
469
|
+
const projectOpen = projection.openRows.filter((row) => row.matter_id !== null && row.matter_id !== undefined && projectAllowed.has(row.matter_id))
|
|
470
|
+
const projectSplit = splitOpenRows(projectOpen, projection.matterById, client)
|
|
471
|
+
return {
|
|
472
|
+
id: String(project.id),
|
|
473
|
+
name: String(project.name ?? ''),
|
|
474
|
+
status: String(project.status ?? ''),
|
|
475
|
+
counts: {
|
|
476
|
+
matters: projectMatters.length,
|
|
477
|
+
mattersArchived: projectMatters.filter((matter) => matter.status === 'archived').length,
|
|
478
|
+
deliveries: countByMatter(store, 'deliveries', projectIds),
|
|
479
|
+
notes: projectNoteStats(client, projection.groups, project.id, projectAllowed, level),
|
|
480
|
+
commitments: countByMatter(store, 'commitments', projectIds),
|
|
481
|
+
openMine: projectSplit.mine.length,
|
|
482
|
+
openWaiting: projectSplit.waiting.length,
|
|
483
|
+
overdue: overdueCount(projectOpen),
|
|
484
|
+
},
|
|
485
|
+
nextDueAt: nextDueAt(projectOpen),
|
|
486
|
+
}
|
|
487
|
+
})
|
|
488
|
+
return {
|
|
489
|
+
client: {
|
|
490
|
+
id: String(client.id),
|
|
491
|
+
name: String(client.name ?? ''),
|
|
492
|
+
status: String(client.status ?? ''),
|
|
493
|
+
aliases: stringList(client.aliases),
|
|
494
|
+
tags: stringList(client.tags),
|
|
495
|
+
secrecyDefault: finiteNumber(client.secrecyDefault, 0),
|
|
496
|
+
},
|
|
497
|
+
projects,
|
|
498
|
+
counts: projection.counts,
|
|
499
|
+
open: {
|
|
500
|
+
mine: projection.split.mine.slice(0, openPage),
|
|
501
|
+
waiting: projection.split.waiting.slice(0, openPage),
|
|
502
|
+
mineTotal: projection.split.mine.length,
|
|
503
|
+
waitingTotal: projection.split.waiting.length,
|
|
504
|
+
},
|
|
505
|
+
nextDueAt: nextDueAt(projection.openRows),
|
|
506
|
+
timeline: timeline.items,
|
|
507
|
+
timelineTotal: timeline.total,
|
|
508
|
+
timelineTruncated: timeline.truncated,
|
|
509
|
+
clearance: level,
|
|
510
|
+
protectedExcluded: projection.protectedMatters + projection.notes.withheld + timeline.protectedDeliveries,
|
|
511
|
+
}
|
|
512
|
+
})
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export default Object.freeze({
|
|
516
|
+
CUSTOMER_LIST_LIMIT,
|
|
517
|
+
CUSTOMER_LIST_LIMIT_MAX,
|
|
518
|
+
CUSTOMER_TIMELINE_LIMIT,
|
|
519
|
+
CUSTOMER_TIMELINE_LIMIT_MAX,
|
|
520
|
+
CUSTOMER_OPEN_LIMIT,
|
|
521
|
+
CUSTOMER_OPEN_LIMIT_MAX,
|
|
522
|
+
listClientRows,
|
|
523
|
+
readClientStatus,
|
|
524
|
+
})
|