@wirecat/cli-core 0.606.0 → 0.608.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.
- package/CHANGELOG.md +196 -0
- package/dist/calendar/index.d.ts +1 -0
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/reads.js +5 -0
- package/dist/cli/app-mcp-command.d.ts +6 -2
- package/dist/cli/app-mcp-command.js +11 -2
- package/dist/cli/csv.d.ts +10 -0
- package/dist/cli/csv.js +22 -0
- package/dist/cli/early-refusal.d.ts +10 -0
- package/dist/cli/early-refusal.js +19 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.js +3 -0
- package/dist/cli/profile-token.d.ts +29 -0
- package/dist/cli/profile-token.js +65 -0
- package/dist/cli/program.js +4 -2
- package/dist/crm/cli/csv.d.ts +23 -0
- package/dist/crm/cli/csv.js +135 -0
- package/dist/crm/cli/index.d.ts +1 -1
- package/dist/crm/cli/index.js +33 -21
- package/dist/crm/cli/pipeline-view.d.ts +3 -0
- package/dist/crm/cli/pipeline-view.js +36 -0
- package/dist/crm/writes.d.ts +6 -4
- package/dist/crm/writes.js +17 -13
- package/dist/documents.d.ts +2 -0
- package/dist/documents.js +2 -0
- package/dist/domain/business.d.ts +79 -0
- package/dist/domain/business.js +42 -0
- package/dist/domain/finance.d.ts +2 -0
- package/dist/domain/finance.js +2 -2
- package/dist/domain/google-documents.d.ts +2 -0
- package/dist/domain/google-documents.js +3 -1
- package/dist/domain/money.d.ts +2 -0
- package/dist/domain/money.js +11 -3
- package/dist/domain/providers.d.ts +36 -1
- package/dist/domain/providers.js +69 -7
- package/dist/domain/record-fields.d.ts +42 -0
- package/dist/domain/record-fields.js +122 -0
- package/dist/domain/record-types.d.ts +489 -16
- package/dist/domain/record-types.js +374 -7
- package/dist/domain/records.d.ts +96 -5
- package/dist/domain/records.js +178 -32
- package/dist/domain/ref-summaries.js +5 -0
- package/dist/domain/references.d.ts +1 -1
- package/dist/domain/references.js +5 -0
- package/dist/domain/vcard.d.ts +25 -0
- package/dist/domain/vcard.js +267 -0
- package/dist/entities/deal.d.ts +14 -0
- package/dist/entities/deal.js +3 -0
- package/dist/entities/index.d.ts +12 -0
- package/dist/errors/reasons.js +63 -4
- package/dist/fetch/addresses.d.ts +5 -0
- package/dist/fetch/addresses.js +76 -0
- package/dist/fetch/page.d.ts +64 -0
- package/dist/fetch/page.js +256 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -3
- package/dist/meetings/calendar-text.d.ts +1 -1
- package/dist/meetings/calendar-text.js +4 -0
- package/dist/meetings/event-store.d.ts +2 -2
- package/dist/search/account-list.d.ts +4 -0
- package/dist/search/account-list.js +19 -8
- package/dist/search/query.js +2 -2
- package/dist/services/events-search.js +2 -2
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/ingest.d.ts +56 -8
- package/dist/services/ingest.js +95 -61
- package/dist/services/messages-search.js +3 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/notes-search.js +1 -0
- package/dist/services/proposals/kinds/contracts.d.ts +4 -0
- package/dist/services/proposals/kinds/contracts.js +9 -0
- package/dist/services/proposals/kinds/finance.d.ts +4 -0
- package/dist/services/proposals/kinds/finance.js +14 -35
- package/dist/services/proposals/kinds/orders.js +7 -30
- package/dist/services/proposals/kinds/shared.d.ts +27 -1
- package/dist/services/proposals/kinds/shared.js +34 -0
- package/dist/services/proposals/kinds/source-review.d.ts +4 -0
- package/dist/services/proposals/kinds/source-review.js +45 -0
- package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
- package/dist/services/proposals/kinds/subscriptions.js +24 -0
- package/dist/services/proposals/kinds/transactions.d.ts +4 -0
- package/dist/services/proposals/kinds/transactions.js +10 -0
- package/dist/services/proposals/registry.js +9 -0
- package/dist/services/search-all-meetings.js +2 -2
- package/dist/services/search-all.js +4 -3
- package/dist/services/search-kind.js +3 -3
- package/dist/store/decisions.js +5 -1
- package/dist/store/index.d.ts +14 -3
- package/dist/store/index.js +3 -0
- package/dist/store/people.js +1 -1
- package/dist/store/source-review.d.ts +64 -0
- package/dist/store/source-review.js +7 -0
- package/dist/store/sqlite/accounts.d.ts +1 -1
- package/dist/store/sqlite/accounts.js +24 -1
- package/dist/store/sqlite/added-sources.d.ts +82 -0
- package/dist/store/sqlite/added-sources.js +237 -0
- package/dist/store/sqlite/business-contracts.d.ts +90 -0
- package/dist/store/sqlite/business-contracts.js +182 -0
- package/dist/store/sqlite/calendar-events.js +7 -3
- package/dist/store/sqlite/calendar-forget.js +3 -0
- package/dist/store/sqlite/calendar.d.ts +21 -1
- package/dist/store/sqlite/calendar.js +27 -7
- package/dist/store/sqlite/chat-rekey.js +7 -0
- package/dist/store/sqlite/chats.d.ts +3 -1
- package/dist/store/sqlite/chats.js +15 -1
- package/dist/store/sqlite/crm-rows.d.ts +44 -0
- package/dist/store/sqlite/crm-rows.js +195 -0
- package/dist/store/sqlite/crm.d.ts +2 -11
- package/dist/store/sqlite/crm.js +11 -166
- package/dist/store/sqlite/deals.d.ts +4 -8
- package/dist/store/sqlite/deals.js +5 -3
- package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
- package/dist/store/sqlite/emails.js +2 -0
- package/dist/store/sqlite/entity-types.d.ts +14 -9
- package/dist/store/sqlite/entity-types.js +4 -10
- package/dist/store/sqlite/evidence-signature.d.ts +114 -0
- package/dist/store/sqlite/evidence-signature.js +349 -0
- package/dist/store/sqlite/evidence-sources.d.ts +2 -1
- package/dist/store/sqlite/evidence-sources.js +7 -3
- package/dist/store/sqlite/facts.d.ts +7 -2
- package/dist/store/sqlite/facts.js +21 -5
- package/dist/store/sqlite/finance.d.ts +18 -105
- package/dist/store/sqlite/finance.js +100 -219
- package/dist/store/sqlite/knowledge.d.ts +8 -2
- package/dist/store/sqlite/knowledge.js +65 -71
- package/dist/store/sqlite/labelled.d.ts +3 -0
- package/dist/store/sqlite/labelled.js +11 -0
- package/dist/store/sqlite/link-kinds.d.ts +2 -0
- package/dist/store/sqlite/link-kinds.js +2 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/memories.d.ts +23 -9
- package/dist/store/sqlite/memories.js +41 -13
- package/dist/store/sqlite/messages.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +103 -0
- package/dist/store/sqlite/money-lines.d.ts +48 -0
- package/dist/store/sqlite/money-lines.js +76 -0
- package/dist/store/sqlite/money-transactions.d.ts +132 -0
- package/dist/store/sqlite/money-transactions.js +295 -0
- package/dist/store/sqlite/notes.d.ts +11 -2
- package/dist/store/sqlite/notes.js +20 -25
- package/dist/store/sqlite/orders.d.ts +36 -6
- package/dist/store/sqlite/orders.js +126 -46
- package/dist/store/sqlite/payment-facts.js +1 -1
- package/dist/store/sqlite/private-people.js +2 -0
- package/dist/store/sqlite/products.d.ts +78 -0
- package/dist/store/sqlite/products.js +131 -0
- package/dist/store/sqlite/project-transfer/records.js +26 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
- package/dist/store/sqlite/proposed-actions.d.ts +1 -1
- package/dist/store/sqlite/proposed-actions.js +24 -7
- package/dist/store/sqlite/providers.d.ts +0 -4
- package/dist/store/sqlite/providers.js +20 -2
- package/dist/store/sqlite/record-matching.d.ts +80 -0
- package/dist/store/sqlite/record-matching.js +264 -0
- package/dist/store/sqlite/record-projection.d.ts +89 -0
- package/dist/store/sqlite/record-projection.js +50 -0
- package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
- package/dist/store/sqlite/record-projectors-direct.js +125 -0
- package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
- package/dist/store/sqlite/record-projectors-money.js +214 -0
- package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
- package/dist/store/sqlite/record-projectors-phone.js +212 -0
- package/dist/store/sqlite/record-projectors.d.ts +3 -44
- package/dist/store/sqlite/record-projectors.js +7 -67
- package/dist/store/sqlite/record-relations.d.ts +24 -0
- package/dist/store/sqlite/record-relations.js +92 -0
- package/dist/store/sqlite/record-remap.d.ts +12 -0
- package/dist/store/sqlite/record-remap.js +92 -0
- package/dist/store/sqlite/record-run.d.ts +71 -0
- package/dist/store/sqlite/record-run.js +179 -0
- package/dist/store/sqlite/record-settling.d.ts +9 -0
- package/dist/store/sqlite/record-settling.js +74 -0
- package/dist/store/sqlite/record-stamps.d.ts +13 -0
- package/dist/store/sqlite/record-stamps.js +30 -0
- package/dist/store/sqlite/record-writes.d.ts +43 -0
- package/dist/store/sqlite/record-writes.js +307 -0
- package/dist/store/sqlite/records.d.ts +52 -42
- package/dist/store/sqlite/records.js +123 -353
- package/dist/store/sqlite/ref-summaries.d.ts +6 -5
- package/dist/store/sqlite/ref-summaries.js +60 -8
- package/dist/store/sqlite/refunds.d.ts +31 -0
- package/dist/store/sqlite/refunds.js +112 -0
- package/dist/store/sqlite/reviewed.d.ts +109 -0
- package/dist/store/sqlite/reviewed.js +173 -0
- package/dist/store/sqlite/schema.d.ts +2840 -83
- package/dist/store/sqlite/schema.js +256 -1
- package/dist/store/sqlite/source-review-marks.d.ts +54 -0
- package/dist/store/sqlite/source-review-marks.js +143 -0
- package/dist/store/sqlite/source-review.d.ts +54 -0
- package/dist/store/sqlite/source-review.js +221 -0
- package/dist/store/sqlite/stage-amounts.d.ts +14 -0
- package/dist/store/sqlite/stage-amounts.js +23 -0
- package/dist/store/sqlite/subscriptions.d.ts +135 -0
- package/dist/store/sqlite/subscriptions.js +294 -0
- package/dist/store/sqlite/text-input.d.ts +3 -0
- package/dist/store/sqlite/text-input.js +13 -0
- package/dist/store/sqlite/things.js +2 -9
- package/dist/store/sqlite/transaction.d.ts +15 -0
- package/dist/store/sqlite/transaction.js +57 -0
- package/dist/store/sqlite/wallets.d.ts +88 -0
- package/dist/store/sqlite/wallets.js +143 -0
- package/dist/store/store-errors.d.ts +1 -0
- package/dist/store/store-errors.js +45 -0
- package/dist/store/store.d.ts +16 -1
- package/dist/store/store.js +30 -6
- package/package.json +5 -2
- package/schemas/examples/records-business.jsonl +11 -0
- package/schemas/records-envelope.v1.schema.json +1160 -5
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { contractLine, productLine, subscriptionLine, transactionLine, walletLine } from "../../domain/business.js";
|
|
1
2
|
import { dealLine } from "../../domain/deals.js";
|
|
2
3
|
import { invoiceLine, paymentLine } from "../../domain/finance.js";
|
|
3
4
|
import { orderLine } from "../../domain/orders.js";
|
|
@@ -35,6 +36,10 @@ const byId = (kind, table, columns) => ({
|
|
|
35
36
|
kind,
|
|
36
37
|
sql: (body) => `${select(columns(body))} FROM w JOIN ${table} x ON x.id = w.k1`,
|
|
37
38
|
});
|
|
39
|
+
/** The confirmed price in force today: the latest one already effective. */
|
|
40
|
+
const CURRENT_PRICE = (column) => `SELECT ${column} FROM subscription_prices WHERE subscription_id = x.id AND review = 'confirmed' ` +
|
|
41
|
+
"AND effective_from <= ? ORDER BY effective_from DESC LIMIT 1";
|
|
42
|
+
const dated = (count, reader) => ({ ...reader, dated: count });
|
|
38
43
|
const crmColumns = () => ({
|
|
39
44
|
title: "json_object('id', x.id, 'title', x.title, 'stage', (SELECT name FROM pipeline_stages WHERE id = x.stage_id), " +
|
|
40
45
|
"'amount', x.amount, 'currency', x.currency, 'status', x.status)",
|
|
@@ -218,6 +223,43 @@ const READERS = {
|
|
|
218
223
|
deal: byId("deal", "deals", crmColumns),
|
|
219
224
|
lead: byId("lead", "leads", crmColumns),
|
|
220
225
|
pipeline: byId("pipeline", "pipelines", () => ({ title: "x.name", at: "x.created_at" })),
|
|
226
|
+
product: byId("product", "catalog_items", () => ({
|
|
227
|
+
title: "json_object('name', x.name, 'kind', x.kind, 'unitPrice', x.unit_price, 'currency', x.currency, " +
|
|
228
|
+
"'unit', x.unit, 'archived', json(CASE WHEN x.archived_date IS NULL THEN 'false' ELSE 'true' END))",
|
|
229
|
+
holder: subjectName("x.supplier_type", "x.supplier_id"),
|
|
230
|
+
at: "x.created_at",
|
|
231
|
+
deleted: "x.deleted_at",
|
|
232
|
+
})),
|
|
233
|
+
contract: byId("contract", "contracts", () => ({
|
|
234
|
+
title: "json_object('id', x.id, 'name', x.name, 'number', x.number, 'value', x.value, 'currency', x.currency, " +
|
|
235
|
+
"'status', x.status, 'review', x.review)",
|
|
236
|
+
holder: "(SELECT name FROM projects WHERE id = x.project_id)",
|
|
237
|
+
at: "x.created_at",
|
|
238
|
+
deleted: "x.deleted_at",
|
|
239
|
+
})),
|
|
240
|
+
subscription: dated(2, byId("subscription", "subscriptions", () => ({
|
|
241
|
+
title: "json_object('name', x.name, 'interval', json_object('count', x.interval_count, 'unit', x.interval_unit), " +
|
|
242
|
+
`'price', (${CURRENT_PRICE("amount")}), 'currency', (${CURRENT_PRICE("currency")}), 'status', x.status, ` +
|
|
243
|
+
"'review', x.review)",
|
|
244
|
+
holder: "(SELECT name FROM projects WHERE id = x.project_id)",
|
|
245
|
+
at: "x.created_at",
|
|
246
|
+
deleted: "x.deleted_at",
|
|
247
|
+
}))),
|
|
248
|
+
wallet: byId("wallet", "financial_accounts", () => ({
|
|
249
|
+
title: "json_object('name', x.name, 'kind', x.kind, 'currency', x.currency, 'numberHint', x.number_hint, " +
|
|
250
|
+
"'closed', json(CASE WHEN x.closed_date IS NULL THEN 'false' ELSE 'true' END))",
|
|
251
|
+
holder: subjectName("x.holder_type", "x.holder_id"),
|
|
252
|
+
at: "x.created_at",
|
|
253
|
+
deleted: "x.deleted_at",
|
|
254
|
+
})),
|
|
255
|
+
transaction: byId("transaction", "financial_transactions", () => ({
|
|
256
|
+
title: "json_object('direction', x.direction, 'amount', x.amount, 'currency', x.currency, " +
|
|
257
|
+
"'label', coalesce(x.counterparty_name, x.description), 'date', x.statement_date, 'status', x.status, " +
|
|
258
|
+
"'review', x.review)",
|
|
259
|
+
holder: "(SELECT name FROM financial_accounts WHERE id = x.financial_account_id)",
|
|
260
|
+
at: "x.created_at",
|
|
261
|
+
deleted: "x.deleted_at",
|
|
262
|
+
})),
|
|
221
263
|
};
|
|
222
264
|
/** Mail saved before the mail tables existed is still messages, so a miss there is read again as a message. */
|
|
223
265
|
const FALLBACK = { email: "message", email_thread: "chat" };
|
|
@@ -266,7 +308,7 @@ const kindOfReference = (reference) => reference.type === "entity"
|
|
|
266
308
|
: reference.type === "chat" && reference.provider === "email"
|
|
267
309
|
? "email_thread"
|
|
268
310
|
: reference.type;
|
|
269
|
-
const runReader = (database, reader, wanted, body) => {
|
|
311
|
+
const runReader = (database, reader, wanted, body, today) => {
|
|
270
312
|
const found = new Map();
|
|
271
313
|
const width = wanted[0]?.keys.length ?? 0;
|
|
272
314
|
const names = Array.from({ length: width }, (_, at) => `k${at + 1}`);
|
|
@@ -274,7 +316,10 @@ const runReader = (database, reader, wanted, body) => {
|
|
|
274
316
|
const slice = wanted.slice(start, start + SLICE);
|
|
275
317
|
const values = slice.map(() => `(${["?", ...names.map(() => "?")].join(", ")})`).join(", ");
|
|
276
318
|
const sql = `WITH w(n, ${names.join(", ")}) AS (VALUES ${values}) ${reader.sql(body)}`;
|
|
277
|
-
const parameters =
|
|
319
|
+
const parameters = [
|
|
320
|
+
...slice.flatMap((one, at) => [start + at, ...one.keys]),
|
|
321
|
+
...Array.from({ length: reader.dated ?? 0 }, () => today),
|
|
322
|
+
];
|
|
278
323
|
for (const row of database.prepare(sql).all(...parameters)) {
|
|
279
324
|
const n = Number(row.n);
|
|
280
325
|
if (found.has(n))
|
|
@@ -328,6 +373,16 @@ const titleOf = (kind, reference, found) => {
|
|
|
328
373
|
case "deal":
|
|
329
374
|
case "lead":
|
|
330
375
|
return fieldsOf(found.title, dealLine);
|
|
376
|
+
case "product":
|
|
377
|
+
return fieldsOf(found.title, productLine);
|
|
378
|
+
case "contract":
|
|
379
|
+
return fieldsOf(found.title, contractLine);
|
|
380
|
+
case "subscription":
|
|
381
|
+
return fieldsOf(found.title, subscriptionLine);
|
|
382
|
+
case "wallet":
|
|
383
|
+
return fieldsOf(found.title, walletLine);
|
|
384
|
+
case "transaction":
|
|
385
|
+
return fieldsOf(found.title, transactionLine);
|
|
331
386
|
case "folder":
|
|
332
387
|
return reference.type === "folder" && reference.path !== null && found.title !== null
|
|
333
388
|
? `${found.title}/${reference.path}`
|
|
@@ -394,11 +449,8 @@ const parsed = (text) => {
|
|
|
394
449
|
return undefined;
|
|
395
450
|
}
|
|
396
451
|
};
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
* `unknown` and a ref the store lacks is `unavailable`: one bad row must not fail a page of them.
|
|
400
|
-
*/
|
|
401
|
-
export const refReadsOf = (database, texts, { excerpt = false } = {}) => {
|
|
452
|
+
export const refReadsOf = (database, texts, { excerpt = false, now = Date.now() } = {}) => {
|
|
453
|
+
const today = new Date(now).toISOString().slice(0, 10);
|
|
402
454
|
const reads = new Map();
|
|
403
455
|
const groups = new Map();
|
|
404
456
|
for (const text of new Set(texts)) {
|
|
@@ -417,7 +469,7 @@ export const refReadsOf = (database, texts, { excerpt = false } = {}) => {
|
|
|
417
469
|
while (pending.length > 0) {
|
|
418
470
|
const [name, wanted] = pending.shift();
|
|
419
471
|
const reader = READERS[name];
|
|
420
|
-
const found = runReader(database, reader, wanted, excerpt);
|
|
472
|
+
const found = runReader(database, reader, wanted, excerpt, today);
|
|
421
473
|
const fallback = FALLBACK[name];
|
|
422
474
|
const missed = [];
|
|
423
475
|
for (const [n, one] of wanted.entries()) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { StoreContext } from "./open.js";
|
|
2
|
+
type Row = Record<string, unknown>;
|
|
3
|
+
declare const COUNTED: {
|
|
4
|
+
readonly confirmed: "np.review = 'confirmed' AND np.deleted_at IS NULL";
|
|
5
|
+
readonly pending: "np.deleted_at IS NULL AND (np.review = 'confirmed' OR (np.review = 'proposed' AND np.refund_of IS NULL))";
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* What is paid on `invoice`, net: payments' allocations minus their refunds'. Every sum of paid money in code reads
|
|
9
|
+
* this one fragment; the triggers repeat it for `confirmed`. `pending` also counts proposed payments, not proposed
|
|
10
|
+
* refunds. `including` counts one payment whatever its review, `excluding` leaves one out; each is an SQL expression,
|
|
11
|
+
* such as `?` or a column of the outer query.
|
|
12
|
+
*/
|
|
13
|
+
export declare const netPaidSql: (invoice: string, { counted, including, excluding, }?: {
|
|
14
|
+
counted?: keyof typeof COUNTED;
|
|
15
|
+
including?: string;
|
|
16
|
+
excluding?: string;
|
|
17
|
+
}) => string;
|
|
18
|
+
/** A refund is a payment the other way with `refund_of`; these rules keep net paid at 0 or more for every payment. */
|
|
19
|
+
export declare const refundRulesOver: (context: StoreContext) => {
|
|
20
|
+
originalFor: (id: number, refund: {
|
|
21
|
+
direction: string;
|
|
22
|
+
currency: string;
|
|
23
|
+
amount: number;
|
|
24
|
+
}) => Row;
|
|
25
|
+
refundShare: (refund: Row, invoiceId: number, units: number) => void;
|
|
26
|
+
confirmable: (refund: Row) => void;
|
|
27
|
+
keepsRefunded: (payment: Row) => void;
|
|
28
|
+
keepsShare: (paymentId: number, invoiceId: number) => void;
|
|
29
|
+
keepsInvoice: (refund: Row, invoiceId: number) => void;
|
|
30
|
+
};
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { moneyLabel } from "../../domain/money.js";
|
|
2
|
+
import { refuse } from "./reviewed.js";
|
|
3
|
+
const COUNTED = {
|
|
4
|
+
confirmed: "np.review = 'confirmed' AND np.deleted_at IS NULL",
|
|
5
|
+
// A proposed refund promises nothing back yet, so it must not free room an import could then fill.
|
|
6
|
+
pending: "np.deleted_at IS NULL AND (np.review = 'confirmed' OR (np.review = 'proposed' AND np.refund_of IS NULL))",
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* What is paid on `invoice`, net: payments' allocations minus their refunds'. Every sum of paid money in code reads
|
|
10
|
+
* this one fragment; the triggers repeat it for `confirmed`. `pending` also counts proposed payments, not proposed
|
|
11
|
+
* refunds. `including` counts one payment whatever its review, `excluding` leaves one out; each is an SQL expression,
|
|
12
|
+
* such as `?` or a column of the outer query.
|
|
13
|
+
*/
|
|
14
|
+
export const netPaidSql = (invoice, { counted = "confirmed", including, excluding, } = {}) => {
|
|
15
|
+
const which = including === undefined ? COUNTED[counted] : `((${COUNTED[counted]}) OR na.payment_id = ${including})`;
|
|
16
|
+
return ("(SELECT coalesce(sum(CASE WHEN np.refund_of IS NULL THEN na.amount ELSE -na.amount END), 0) " +
|
|
17
|
+
"FROM payment_allocations na JOIN payments np ON np.id = na.payment_id " +
|
|
18
|
+
`WHERE na.invoice_id = ${invoice} AND ${which}${excluding === undefined ? "" : ` AND na.payment_id <> ${excluding}`})`);
|
|
19
|
+
};
|
|
20
|
+
/** A refund is a payment the other way with `refund_of`; these rules keep net paid at 0 or more for every payment. */
|
|
21
|
+
export const refundRulesOver = (context) => {
|
|
22
|
+
const { database } = context;
|
|
23
|
+
const one = (sql, ...params) => Number(database.prepare(sql).get(...params)?.n ?? 0);
|
|
24
|
+
const confirmedRefunds = (original, without) => one("SELECT coalesce(sum(amount), 0) AS n FROM payments WHERE refund_of = ? AND review = 'confirmed' " +
|
|
25
|
+
"AND deleted_at IS NULL AND id IS NOT ?", original, without ?? null);
|
|
26
|
+
const withinOriginal = (original, units, without) => {
|
|
27
|
+
const done = confirmedRefunds(Number(original.id), without);
|
|
28
|
+
const currency = String(original.currency);
|
|
29
|
+
if (done + units > Number(original.amount))
|
|
30
|
+
refuse(`payment:${original.id} is ${moneyLabel(Number(original.amount), currency)} and ` +
|
|
31
|
+
`${moneyLabel(done, currency)} of it is already refunded; ${moneyLabel(units, currency)} more is too much`, "finance.over-refund");
|
|
32
|
+
};
|
|
33
|
+
/** The payment a new refund names: live, not a refund itself, the other way and in the same currency. */
|
|
34
|
+
const originalFor = (id, refund) => {
|
|
35
|
+
const original = database.prepare("SELECT * FROM payments WHERE id = ?").get(id);
|
|
36
|
+
const ref = `payment:${id}`;
|
|
37
|
+
if (original.refund_of != null)
|
|
38
|
+
refuse(`${ref} is itself a refund; refund the payment it refunds`, "finance.refund");
|
|
39
|
+
if (original.review === "rejected" || original.deleted_at != null)
|
|
40
|
+
refuse(`${ref} is ${original.review === "rejected" ? "rejected" : "deleted"}; there is nothing to refund`, "finance.refund");
|
|
41
|
+
if (original.direction === refund.direction)
|
|
42
|
+
refuse(`a refund of ${ref} goes the other way: ${original.direction === "in" ? "out" : "in"}`, "finance.refund");
|
|
43
|
+
if (original.currency !== refund.currency)
|
|
44
|
+
refuse(`a refund of ${ref} is in its currency, ${String(original.currency)}`, "finance.refund");
|
|
45
|
+
withinOriginal(original, refund.amount);
|
|
46
|
+
return original;
|
|
47
|
+
};
|
|
48
|
+
/** A refund's share of an invoice: only one its payment is allocated to, and never more than that payment gave it. */
|
|
49
|
+
const refundShare = (refund, invoiceId, units) => {
|
|
50
|
+
const original = Number(refund.refund_of);
|
|
51
|
+
const given = database
|
|
52
|
+
.prepare("SELECT amount FROM payment_allocations WHERE payment_id = ? AND invoice_id = ?")
|
|
53
|
+
.get(original, invoiceId);
|
|
54
|
+
if (!given)
|
|
55
|
+
refuse(`payment:${refund.id} refunds payment:${original}, which is not allocated to invoice:${invoiceId}; ` +
|
|
56
|
+
"a refund goes back only where its payment went", "finance.refund");
|
|
57
|
+
const back = one("SELECT coalesce(sum(a.amount), 0) AS n FROM payment_allocations a JOIN payments r ON r.id = a.payment_id " +
|
|
58
|
+
"WHERE a.invoice_id = ? AND r.refund_of = ? AND ((r.review = 'confirmed' AND r.deleted_at IS NULL) OR r.id = ?)", invoiceId, original, Number(refund.id));
|
|
59
|
+
const currency = String(refund.currency);
|
|
60
|
+
if (back + units > Number(given?.amount))
|
|
61
|
+
refuse(`payment:${original} gave invoice:${invoiceId} ${moneyLabel(Number(given?.amount), currency)} and ` +
|
|
62
|
+
`${moneyLabel(back, currency)} of it is already refunded; ${moneyLabel(units, currency)} more is too much`, "finance.over-refund");
|
|
63
|
+
};
|
|
64
|
+
/** A refund is confirmed after its payment, and still within it and within each share it takes back. */
|
|
65
|
+
const confirmable = (refund) => {
|
|
66
|
+
const original = database.prepare("SELECT * FROM payments WHERE id = ?").get(Number(refund.refund_of));
|
|
67
|
+
if (original.review !== "confirmed" || original.deleted_at != null)
|
|
68
|
+
refuse(`payment:${refund.id} refunds payment:${original.id}, which is ${String(original.review)}; ` +
|
|
69
|
+
"confirm the payment first", "finance.refund");
|
|
70
|
+
withinOriginal(original, Number(refund.amount), Number(refund.id));
|
|
71
|
+
for (const share of database
|
|
72
|
+
.prepare("SELECT invoice_id, amount FROM payment_allocations WHERE payment_id = ?")
|
|
73
|
+
.all(Number(refund.id)))
|
|
74
|
+
refundShare(refund, Number(share.invoice_id), 0);
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Taking a confirmed refund's share back gives that money to the invoice again: never beyond its total, given what
|
|
78
|
+
* the confirmed payments pay on it by then.
|
|
79
|
+
*/
|
|
80
|
+
const keepsInvoice = (refund, invoiceId) => {
|
|
81
|
+
if (refund.review !== "confirmed" || refund.deleted_at != null)
|
|
82
|
+
return;
|
|
83
|
+
const row = database
|
|
84
|
+
.prepare(`SELECT i.total, i.currency, ${netPaidSql("i.id")} AS paid, a.amount FROM invoices i ` +
|
|
85
|
+
"JOIN payment_allocations a ON a.invoice_id = i.id AND a.payment_id = ? WHERE i.id = ?")
|
|
86
|
+
.get(Number(refund.id), invoiceId);
|
|
87
|
+
if (!row)
|
|
88
|
+
return;
|
|
89
|
+
const currency = String(row.currency);
|
|
90
|
+
if (Number(row.paid) + Number(row.amount) > Number(row.total))
|
|
91
|
+
refuse(`invoice:${invoiceId} totals ${moneyLabel(Number(row.total), currency)} and ${moneyLabel(Number(row.paid), currency)} ` +
|
|
92
|
+
`is paid on it; taking back payment:${refund.id}'s ${moneyLabel(Number(row.amount), currency)} would pay too much`, "finance.over-invoice");
|
|
93
|
+
};
|
|
94
|
+
/** A payment with a live refund stays: rejecting it would leave the refund taking back money never paid. */
|
|
95
|
+
const keepsRefunded = (payment) => {
|
|
96
|
+
const refund = database
|
|
97
|
+
.prepare("SELECT id FROM payments WHERE refund_of = ? AND review <> 'rejected' AND deleted_at IS NULL LIMIT 1")
|
|
98
|
+
.get(Number(payment.id));
|
|
99
|
+
if (refund)
|
|
100
|
+
refuse(`payment:${refund.id} refunds payment:${payment.id}; reject the refund first`, "finance.refunded");
|
|
101
|
+
};
|
|
102
|
+
/** A payment's share of an invoice stays while a refund of it takes part of that share back. */
|
|
103
|
+
const keepsShare = (paymentId, invoiceId) => {
|
|
104
|
+
const refund = database
|
|
105
|
+
.prepare("SELECT a.payment_id AS id FROM payment_allocations a JOIN payments r ON r.id = a.payment_id " +
|
|
106
|
+
"WHERE r.refund_of = ? AND a.invoice_id = ? LIMIT 1")
|
|
107
|
+
.get(paymentId, invoiceId);
|
|
108
|
+
if (refund)
|
|
109
|
+
refuse(`payment:${refund.id} refunds part of what payment:${paymentId} gave invoice:${invoiceId}; take that back first`, "finance.refunded");
|
|
110
|
+
};
|
|
111
|
+
return { originalFor, refundShare, confirmable, keepsRefunded, keepsShare, keepsInvoice };
|
|
112
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { FinanceReview } from "../../domain/finance.js";
|
|
2
|
+
import { type DecidedTable, type DecidedType } from "../../domain/record-types.js";
|
|
3
|
+
import { type Decider } from "../decisions.js";
|
|
4
|
+
import { type Actor } from "./actors.js";
|
|
5
|
+
import { type Author, type Memory } from "./memories.js";
|
|
6
|
+
import type { StoreContext } from "./open.js";
|
|
7
|
+
type Row = Record<string, unknown>;
|
|
8
|
+
/** Who wrote a row: `name` is a bot's handle and `kind` whether it is an agent or a rule; both `null` for a person. */
|
|
9
|
+
export type AuthorInfo = Memory["author"];
|
|
10
|
+
/** A `person:` or `organization:` on an invoice or a payment, with its name so a list needs no lookup. */
|
|
11
|
+
export interface Party {
|
|
12
|
+
ref: string;
|
|
13
|
+
name: string | null;
|
|
14
|
+
/** The owner's own person row. */
|
|
15
|
+
owner: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface Reviewed {
|
|
18
|
+
review: FinanceReview;
|
|
19
|
+
/** `name` is a bot's handle and `kind` whether it is an agent or a rule; both `null` for a person. */
|
|
20
|
+
author: AuthorInfo;
|
|
21
|
+
model: string | null;
|
|
22
|
+
confirmedBy: {
|
|
23
|
+
type: Actor["type"];
|
|
24
|
+
id: string;
|
|
25
|
+
} | null;
|
|
26
|
+
source: string;
|
|
27
|
+
/** Why an agent or an import proposed it. */
|
|
28
|
+
reason: string | null;
|
|
29
|
+
/** What it was read from: the messages, documents or notes an agent or the owner cited. */
|
|
30
|
+
evidence: string[];
|
|
31
|
+
project: string | null;
|
|
32
|
+
projectName: string | null;
|
|
33
|
+
createdAt: string;
|
|
34
|
+
updatedAt: string;
|
|
35
|
+
}
|
|
36
|
+
export interface Written {
|
|
37
|
+
/** The owner's entry is confirmed at once; a bot's waits as proposed for the owner. */
|
|
38
|
+
by: Author;
|
|
39
|
+
project?: string;
|
|
40
|
+
/** Where a bot's row came from, such as `agent` or an importer's name; the owner's is always `owner`. */
|
|
41
|
+
source?: string;
|
|
42
|
+
/** Why a bot proposes it, kept for the reviewer. */
|
|
43
|
+
reason?: string;
|
|
44
|
+
/** References it was read from, linked as `evidence`. */
|
|
45
|
+
evidence?: string[];
|
|
46
|
+
}
|
|
47
|
+
/** One article, for the first prefix only: `an invoice: or payment:`. */
|
|
48
|
+
export declare const prefixesText: (types: readonly string[]) => string;
|
|
49
|
+
export declare const refuse: (message: string, reason: string, code?: "validation_error" | "permission_error") => never;
|
|
50
|
+
export declare const oneOf: <T extends string>(value: unknown, allowed: readonly T[], what: string) => T;
|
|
51
|
+
export declare const text: (value: unknown, what: string, limit: number, reason?: string) => string | null;
|
|
52
|
+
export declare const isoDate: (value: unknown, what: string) => string | null;
|
|
53
|
+
export declare const iso: (value: unknown) => string;
|
|
54
|
+
export declare const reasonOf: (metadata: unknown) => string | null;
|
|
55
|
+
/** A list's page size: 1–500, 100 when left out. */
|
|
56
|
+
export declare const limitOf: (limit: number | undefined) => number;
|
|
57
|
+
export interface Decision {
|
|
58
|
+
by: Decider;
|
|
59
|
+
reason?: string;
|
|
60
|
+
confirm: boolean;
|
|
61
|
+
}
|
|
62
|
+
/** A reviewed row the owner decides; its `author_name` comes from the bots join every reviewed query makes. */
|
|
63
|
+
export declare const decisionsOver: (context: StoreContext) => {
|
|
64
|
+
keepDecision: (table: DecidedTable, id: number, by: Decider, reason?: string) => void;
|
|
65
|
+
decideRow: (type: DecidedType, row: Row, { by, reason, confirm }: Decision, within?: {
|
|
66
|
+
before?: () => void;
|
|
67
|
+
after?: (confirmer: Actor | null) => void;
|
|
68
|
+
}) => void;
|
|
69
|
+
mayChangeParts: (row: Row, by: Author, message: string, reason?: string) => void;
|
|
70
|
+
};
|
|
71
|
+
/** What invoices, payments and orders share: their parties, who wrote them, and how the owner decides them. */
|
|
72
|
+
export declare const reviewedRowsOver: (context: StoreContext) => {
|
|
73
|
+
keepDecision: (table: DecidedTable, id: number, by: Decider, reason?: string) => void;
|
|
74
|
+
decideRow: (type: DecidedType, row: Row, { by, reason, confirm }: Decision, within?: {
|
|
75
|
+
before?: () => void;
|
|
76
|
+
after?: (confirmer: Actor | null) => void;
|
|
77
|
+
}) => void;
|
|
78
|
+
mayChangeParts: (row: Row, by: Author, message: string, reason?: string) => void;
|
|
79
|
+
partyOf: (type: unknown, id: unknown) => Party | null;
|
|
80
|
+
partyThing: (reference: string | undefined, what: string) => import("./things.js").Thing | undefined;
|
|
81
|
+
reviewedOf: (row: Row, type: DecidedType | "deal") => Reviewed;
|
|
82
|
+
written: (input: Written) => {
|
|
83
|
+
owner: boolean;
|
|
84
|
+
actor: Actor;
|
|
85
|
+
model: string | null;
|
|
86
|
+
source: string;
|
|
87
|
+
review: string;
|
|
88
|
+
confirmedType: "bot" | "person" | null;
|
|
89
|
+
confirmedId: number | null;
|
|
90
|
+
metadata: string | null;
|
|
91
|
+
project: number | null;
|
|
92
|
+
evidence: string[];
|
|
93
|
+
};
|
|
94
|
+
keepEvidence: (type: DecidedType | "deal", id: number, by: ReturnType<(input: Written) => {
|
|
95
|
+
owner: boolean;
|
|
96
|
+
actor: Actor;
|
|
97
|
+
model: string | null;
|
|
98
|
+
source: string;
|
|
99
|
+
review: string;
|
|
100
|
+
confirmedType: "bot" | "person" | null;
|
|
101
|
+
confirmedId: number | null;
|
|
102
|
+
metadata: string | null;
|
|
103
|
+
project: number | null;
|
|
104
|
+
evidence: string[];
|
|
105
|
+
}>) => void;
|
|
106
|
+
ownerOnly: (by: Author, what: string) => void;
|
|
107
|
+
linkedId: <T extends string>(reference: string | undefined, type: T, reason: string) => number | null;
|
|
108
|
+
};
|
|
109
|
+
export {};
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { article, DECIDED_TABLES } from "../../domain/record-types.js";
|
|
3
|
+
import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
|
|
4
|
+
import { proposerOf } from "./actors.js";
|
|
5
|
+
import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf, subjectOf, } from "./memories.js";
|
|
6
|
+
import { requiredThing } from "./notes.js";
|
|
7
|
+
import { write } from "./transaction.js";
|
|
8
|
+
/** One article, for the first prefix only: `an invoice: or payment:`. */
|
|
9
|
+
export const prefixesText = (types) => `${article(types[0] ?? "")} ${types.map((type) => `${type}:`).join(" or ")}`;
|
|
10
|
+
export const refuse = (message, reason, code = "validation_error") => {
|
|
11
|
+
throw new CliError(code, message, { reason });
|
|
12
|
+
};
|
|
13
|
+
export const oneOf = (value, allowed, what) => {
|
|
14
|
+
if (typeof value !== "string" || !allowed.includes(value))
|
|
15
|
+
return refuse(`${what} is one of ${allowed.join(", ")}`, "finance.field");
|
|
16
|
+
return value;
|
|
17
|
+
};
|
|
18
|
+
export const text = (value, what, limit, reason = "finance.field") => {
|
|
19
|
+
if (value === undefined || value === null)
|
|
20
|
+
return null;
|
|
21
|
+
if (typeof value !== "string" || !value.trim() || value.length > limit || value.includes("\0"))
|
|
22
|
+
return refuse(`${what} takes 1–${limit} characters`, reason);
|
|
23
|
+
return value.trim();
|
|
24
|
+
};
|
|
25
|
+
export const isoDate = (value, what) => {
|
|
26
|
+
if (value === undefined || value === null)
|
|
27
|
+
return null;
|
|
28
|
+
const date = typeof value === "string" ? value.trim() : "";
|
|
29
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)
|
|
30
|
+
return refuse(`${what} is a date such as 2026-11-15`, "finance.field");
|
|
31
|
+
return date;
|
|
32
|
+
};
|
|
33
|
+
export const iso = (value) => new Date(Number(value)).toISOString();
|
|
34
|
+
const evidenceList = (value) => {
|
|
35
|
+
if (value === undefined)
|
|
36
|
+
return [];
|
|
37
|
+
if (!Array.isArray(value) || value.length > 8 || value.some((one) => typeof one !== "string" || !one.trim()))
|
|
38
|
+
return refuse("evidence is a list of at most 8 references", "finance.field");
|
|
39
|
+
return [...new Set(value.map((one) => one.trim()))];
|
|
40
|
+
};
|
|
41
|
+
export const reasonOf = (metadata) => {
|
|
42
|
+
if (metadata == null)
|
|
43
|
+
return null;
|
|
44
|
+
try {
|
|
45
|
+
const { reason } = JSON.parse(String(metadata));
|
|
46
|
+
return typeof reason === "string" ? reason : null;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
/** A list's page size: 1–500, 100 when left out. */
|
|
53
|
+
export const limitOf = (limit) => Math.min(Math.max(limit ?? 100, 1), 500);
|
|
54
|
+
/** A reviewed row the owner decides; its `author_name` comes from the bots join every reviewed query makes. */
|
|
55
|
+
export const decisionsOver = (context) => {
|
|
56
|
+
const { database, now } = context;
|
|
57
|
+
const keepDecision = (table, id, by, reason) => {
|
|
58
|
+
const why = [by === "owner" ? undefined : by.reason.trim(), reason?.trim() || undefined].filter(Boolean).join(": ");
|
|
59
|
+
if (by === "owner" && !why)
|
|
60
|
+
return;
|
|
61
|
+
const decision = by === "owner" ? { by: "owner", reason: why } : { by: "agent", bot: by.bot, reason: why };
|
|
62
|
+
database
|
|
63
|
+
.prepare(`UPDATE ${table} SET metadata = json_set(coalesce(metadata, '{}'), '$.decision', json(?)) WHERE id = ?`)
|
|
64
|
+
.run(JSON.stringify(decision), id);
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Confirms or rejects a proposed row; only the owner decides money. `before` runs the checks that may still refuse
|
|
68
|
+
* and `after` what follows from the decision, both in its transaction.
|
|
69
|
+
*/
|
|
70
|
+
const decideRow = (type, row, { by, reason, confirm }, within = {}) => {
|
|
71
|
+
const ref = `${type}:${row.id}`;
|
|
72
|
+
assertMayDecide({ id: ref, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly: true }, by, context.decisions);
|
|
73
|
+
if (row.review !== "proposed")
|
|
74
|
+
throw new CliError("validation_error", `${ref} is already ${String(row.review)}`, {
|
|
75
|
+
reason: "proposal.wrong-state",
|
|
76
|
+
});
|
|
77
|
+
const table = DECIDED_TABLES[type];
|
|
78
|
+
const id = Number(row.id);
|
|
79
|
+
write(database, () => {
|
|
80
|
+
within.before?.();
|
|
81
|
+
const at = now();
|
|
82
|
+
const confirmer = confirm ? authorActor(context, deciderAuthor(by)).actor : null;
|
|
83
|
+
if (confirmer)
|
|
84
|
+
database
|
|
85
|
+
.prepare(`UPDATE ${table} SET review = 'confirmed', confirmed_by_type = ?, confirmed_by_id = ?, updated_at = ? WHERE id = ?`)
|
|
86
|
+
.run(confirmer.type, confirmer.id, at, id);
|
|
87
|
+
else
|
|
88
|
+
database.prepare(`UPDATE ${table} SET review = 'rejected', updated_at = ? WHERE id = ?`).run(at, id);
|
|
89
|
+
keepDecision(table, id, by, reason);
|
|
90
|
+
within.after?.(confirmer);
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The one rule for changing a reviewed row or its lines, allocations and splits: the owner changes any; a bot only
|
|
95
|
+
* a row it proposed that is still proposed, as its own draft. A confirmed row is the owner's.
|
|
96
|
+
*/
|
|
97
|
+
const mayChangeParts = (row, by, message, reason = "finance.owner-only") => {
|
|
98
|
+
if (by === "owner")
|
|
99
|
+
return;
|
|
100
|
+
const own = row.author_type === "bot" && row.author_name != null && botKey(String(row.author_name)) === botKey(by.bot);
|
|
101
|
+
if (row.review !== "proposed" || !own)
|
|
102
|
+
throw new CliError("permission_error", message, { reason });
|
|
103
|
+
};
|
|
104
|
+
return { keepDecision, decideRow, mayChangeParts };
|
|
105
|
+
};
|
|
106
|
+
/** What invoices, payments and orders share: their parties, who wrote them, and how the owner decides them. */
|
|
107
|
+
export const reviewedRowsOver = (context) => {
|
|
108
|
+
const { database } = context;
|
|
109
|
+
const partyOf = (type, id) => {
|
|
110
|
+
if (type == null)
|
|
111
|
+
return null;
|
|
112
|
+
const { subject, subjectName, subjectIsOwner } = subjectOf(database, { subject_type: type, subject_id: id });
|
|
113
|
+
return subject === null ? null : { ref: subject, name: subjectName, owner: subjectIsOwner };
|
|
114
|
+
};
|
|
115
|
+
const partyThing = (reference, what) => {
|
|
116
|
+
if (reference === undefined)
|
|
117
|
+
return undefined;
|
|
118
|
+
const thing = requiredThing(database, reference, what);
|
|
119
|
+
if (thing.type !== "person" && thing.type !== "organization")
|
|
120
|
+
return refuse(`${what} is a person: or organization: reference, not ${reference}`, "finance.party");
|
|
121
|
+
return thing;
|
|
122
|
+
};
|
|
123
|
+
const reviewedOf = (row, type) => ({
|
|
124
|
+
review: row.review,
|
|
125
|
+
author: authorOf(row),
|
|
126
|
+
model: row.model == null ? null : String(row.model),
|
|
127
|
+
confirmedBy: row.confirmed_by_type == null
|
|
128
|
+
? null
|
|
129
|
+
: { type: row.confirmed_by_type, id: String(row.confirmed_by_id) },
|
|
130
|
+
source: String(row.source),
|
|
131
|
+
reason: reasonOf(row.metadata),
|
|
132
|
+
evidence: evidenceOf(context, { type, id: Number(row.id) }),
|
|
133
|
+
...projectOf(database, row),
|
|
134
|
+
createdAt: iso(row.created_at),
|
|
135
|
+
updatedAt: iso(row.updated_at),
|
|
136
|
+
});
|
|
137
|
+
const written = (input) => {
|
|
138
|
+
const owner = input.by === "owner";
|
|
139
|
+
const { actor, model } = authorActor(context, input.by);
|
|
140
|
+
const source = owner ? "owner" : (text(input.source, "a source", 80) ?? "agent");
|
|
141
|
+
const reason = owner ? null : text(input.reason, "a reason", 2000);
|
|
142
|
+
return {
|
|
143
|
+
owner,
|
|
144
|
+
actor,
|
|
145
|
+
model,
|
|
146
|
+
source,
|
|
147
|
+
review: owner ? "confirmed" : "proposed",
|
|
148
|
+
confirmedType: owner ? actor.type : null,
|
|
149
|
+
confirmedId: owner ? actor.id : null,
|
|
150
|
+
metadata: reason === null ? null : JSON.stringify({ reason }),
|
|
151
|
+
project: input.project === undefined ? null : projectId(database, input.project),
|
|
152
|
+
evidence: evidenceList(input.evidence),
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
const keepEvidence = (type, id, by) => {
|
|
156
|
+
if (by.evidence.length)
|
|
157
|
+
linkEvidence(context, { type, id }, by.evidence, by.owner ? "owner" : "agent");
|
|
158
|
+
};
|
|
159
|
+
const ownerOnly = (by, what) => {
|
|
160
|
+
if (by !== "owner")
|
|
161
|
+
refuse(`only the owner ${what}`, "finance.owner-only", "permission_error");
|
|
162
|
+
};
|
|
163
|
+
/** A typed ref of one kind, as its row id; `undefined` passes through. */
|
|
164
|
+
const linkedId = (reference, type, reason) => {
|
|
165
|
+
if (reference === undefined)
|
|
166
|
+
return null;
|
|
167
|
+
const thing = requiredThing(database, reference, `the ${type}`);
|
|
168
|
+
if (thing.type !== type)
|
|
169
|
+
return refuse(`${reference} is not ${prefixesText([type])} reference`, reason);
|
|
170
|
+
return thing.id;
|
|
171
|
+
};
|
|
172
|
+
return { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, ...decisionsOver(context) };
|
|
173
|
+
};
|