@wirecat/cli-core 0.609.0 → 0.610.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 (51) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/cli/messenger/search-answers.js +12 -0
  3. package/dist/cli/search-left-out.d.ts +1 -0
  4. package/dist/cli/search-left-out.js +2 -0
  5. package/dist/domain/business.d.ts +3 -0
  6. package/dist/domain/business.js +2 -0
  7. package/dist/entities/hit.d.ts +13 -2
  8. package/dist/entities/hit.js +10 -2
  9. package/dist/entities/index.d.ts +7 -1
  10. package/dist/errors/reasons.js +4 -0
  11. package/dist/search/account-list.d.ts +3 -2
  12. package/dist/search/account-list.js +5 -4
  13. package/dist/services/link-scorers/chat-senders.d.ts +2 -1
  14. package/dist/services/link-scorers/chat-senders.js +13 -4
  15. package/dist/services/link-scorers/types.d.ts +1 -1
  16. package/dist/services/metadata.d.ts +1 -1
  17. package/dist/services/proposals/kinds/relationship.js +1 -0
  18. package/dist/services/proposals/registry.js +3 -1
  19. package/dist/services/proposals/types.d.ts +2 -0
  20. package/dist/services/search-all-business.d.ts +18 -0
  21. package/dist/services/search-all-business.js +38 -0
  22. package/dist/services/search-all-meetings.d.ts +1 -1
  23. package/dist/services/search-all-meetings.js +7 -2
  24. package/dist/services/search-all.d.ts +10 -6
  25. package/dist/services/search-all.js +18 -4
  26. package/dist/store/exports.d.ts +2 -0
  27. package/dist/store/exports.js +2 -0
  28. package/dist/store/index.d.ts +4 -1
  29. package/dist/store/index.js +2 -0
  30. package/dist/store/sqlite/business-search.d.ts +44 -0
  31. package/dist/store/sqlite/business-search.js +141 -0
  32. package/dist/store/sqlite/finance.d.ts +12 -0
  33. package/dist/store/sqlite/finance.js +38 -2
  34. package/dist/store/sqlite/involvement-queue.d.ts +2 -7
  35. package/dist/store/sqlite/involvement-queue.js +11 -14
  36. package/dist/store/sqlite/money-lines.d.ts +12 -1
  37. package/dist/store/sqlite/money-lines.js +50 -4
  38. package/dist/store/sqlite/orders.js +5 -25
  39. package/dist/store/sqlite/proposed-actions.d.ts +2 -0
  40. package/dist/store/sqlite/proposed-actions.js +4 -3
  41. package/dist/store/sqlite/records.d.ts +21 -0
  42. package/dist/store/sqlite/records.js +74 -13
  43. package/dist/store/sqlite/ref-summaries.d.ts +3 -1
  44. package/dist/store/sqlite/ref-summaries.js +4 -1
  45. package/dist/store/sqlite/reported-relations.d.ts +1 -0
  46. package/dist/store/sqlite/reported-relations.js +1 -1
  47. package/dist/store/store.d.ts +2 -0
  48. package/dist/store/store.js +4 -4
  49. package/dist/terminal/prompt.d.ts +4 -0
  50. package/dist/terminal/prompt.js +21 -2
  51. package/package.json +1 -1
@@ -1,7 +1,9 @@
1
+ export { BUSINESS_KINDS } from "../domain/business.js";
1
2
  export { registerProvider } from "./providers.js";
2
3
  export { accountGroupsOf } from "./sqlite/account-groups.js";
3
4
  export { attachmentColumns, resetAttachmentWords, } from "./sqlite/attachment-texts.js";
4
5
  export { pendingNormalization } from "./sqlite/backfill.js";
6
+ export { BUSINESS_FIND_MAX, } from "./sqlite/business-search.js";
5
7
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
6
8
  export { storeClients } from "./sqlite/clients.js";
7
9
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
@@ -1,4 +1,5 @@
1
1
  export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
2
+ export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
2
3
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
3
4
  export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
4
5
  export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
@@ -38,6 +39,8 @@ export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
38
39
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
39
40
  export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js";
40
41
  export type { Contract, ContractFields, ContractFilter, ContractInput, ContractsStore, ContractUpdate, } from "./sqlite/business-contracts.js";
42
+ export type { BusinessHit, BusinessSearch, BusinessSearchStore, BusinessSource } from "./sqlite/business-search.js";
43
+ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
41
44
  export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
42
45
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
43
46
  export type { ChatMetadata } from "./sqlite/chats.js";
@@ -72,7 +75,7 @@ export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-language
72
75
  export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
73
76
  export type { Product, ProductFilter, ProductInput, ProductsStore, ProductUpdate } from "./sqlite/products.js";
74
77
  export { assertGenericAction, PROPOSAL_STATUSES, type ProposalInput, type ProposedAction, type ProposedActionsStore, proposerOfAction, } from "./sqlite/proposed-actions.js";
75
- export { type FlaggedRecord, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
78
+ export { type FlaggedRecord, type IncomingRelation, type MappedRecord, type MatchRun, type RecordKey, type RecordStore, type RecordsRun, type RunItem, type RunOptions, type SourceRecord, type SourceRecordRelation, type Unmatched, waitingPointer, } from "./sqlite/records.js";
76
79
  export type { RelationFilter, RelationList, RelationListItem } from "./sqlite/relation-list.js";
77
80
  export type { LinkDecision, RelationUpdate } from "./sqlite/relation-proposals.js";
78
81
  export type { RelationReads } from "./sqlite/relation-reads.js";
@@ -1,3 +1,4 @@
1
+ export { BUSINESS_KINDS } from "../domain/business.js";
1
2
  export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
2
3
  export { createTagRedirectIndex } from "../domain/tag-redirects.js";
3
4
  export { note } from "../entities/note.js";
@@ -25,6 +26,7 @@ export { SOURCE_REVIEW_CAUSES, SOURCE_REVIEW_KIND, } from "./source-review.js";
25
26
  export { ADDED_KINDS, addedSourceKeyOf, } from "./sqlite/added-sources.js";
26
27
  export { resetAttachmentWords } from "./sqlite/attachment-texts.js";
27
28
  export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
29
+ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
28
30
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
29
31
  export { crmIdentityId } from "./sqlite/crm.js";
30
32
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
@@ -0,0 +1,44 @@
1
+ import { type BusinessKind } from "../../domain/business.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ /** The most rows one `find` answers: a `search all` page read as deep as its offset allows, and one more. */
5
+ export declare const BUSINESS_FIND_MAX = 2001;
6
+ export interface BusinessSearch {
7
+ /** Words of a number or a name, each matched at the start of a word in any letter case; a word may be a phrase. */
8
+ words: string[];
9
+ /** A row holding any of the words matches, those holding more first; otherwise every word is needed. */
10
+ anyWord?: boolean;
11
+ /** Only what imports of these accounts made; absent, every import's and the owner's own. */
12
+ accounts?: AccountKey[];
13
+ /** 1–`BUSINESS_FIND_MAX`, 100 by default. */
14
+ limit?: number;
15
+ }
16
+ /** The source record an import made the entity from. */
17
+ export interface BusinessSource {
18
+ provider: string;
19
+ account: string;
20
+ externalId: string;
21
+ }
22
+ export interface BusinessHit {
23
+ kind: BusinessKind;
24
+ ref: string;
25
+ /** A product's or a wallet's has no review and reads `confirmed`; rejected rows are never found. */
26
+ review: "proposed" | "confirmed";
27
+ /** The import provider of a row an import made; absent for the owner's or an agent's. */
28
+ imported?: string;
29
+ /** The one record that names the row's account: the oldest live one, else the oldest deleted one. */
30
+ source?: BusinessSource;
31
+ /** The numbers and names it was found by, one line. */
32
+ text: string;
33
+ /** Epoch ms. */
34
+ updatedAt: number;
35
+ }
36
+ /** Invoices, payments, orders, contracts, subscriptions, products and wallets, found by their numbers and names. */
37
+ export interface BusinessSearchStore {
38
+ find(search: BusinessSearch): Promise<BusinessHit[]>;
39
+ /** Every account with a live record of a row the lane reads. */
40
+ accounts(): Promise<AccountKey[]>;
41
+ }
42
+ /** "get" finds "Get well" and "INV-get", never "Widget": a word is matched where a word starts. */
43
+ export declare const startsAWord: (folded: string, word: string) => boolean;
44
+ export declare const businessSearchOver: ({ database }: StoreContext) => BusinessSearchStore;
@@ -0,0 +1,141 @@
1
+ import { BUSINESS_KINDS } from "../../domain/business.js";
2
+ import { fold } from "../normalize.js";
3
+ /** The most rows one `find` answers: a `search all` page read as deep as its offset allows, and one more. */
4
+ export const BUSINESS_FIND_MAX = 2001;
5
+ const party = (kind, id, as) => `LEFT JOIN persons ${as}p ON ${kind} = 'person' AND ${as}p.id = ${id} AND ${as}p.owner = 0 ` +
6
+ `LEFT JOIN organizations ${as}o ON ${kind} = 'organization' AND ${as}o.id = ${id} ` +
7
+ `LEFT JOIN projects ${as}j ON ${kind} = 'project' AND ${as}j.id = ${id}`;
8
+ const partyName = (as) => `coalesce(${as}p.name, ${as}o.name, ${as}j.name)`;
9
+ const LIVE = "x.deleted_at IS NULL";
10
+ const DECIDED = `${LIVE} AND x.review <> 'rejected'`;
11
+ /** Each kind's searched text as columns `f1…`; a `NULL` column is left out. */
12
+ const SEARCHED = {
13
+ invoice: `SELECT x.id, x.review, x.source, x.updated_at, x.number AS f1, ${partyName("c")} AS f2 FROM invoices x ` +
14
+ `${party("x.counterparty_type", "x.counterparty_id", "c")} WHERE ${DECIDED}`,
15
+ payment: "SELECT x.id, x.review, x.source, x.updated_at, x.reference AS f1, " +
16
+ `${partyName("r")} AS f2, ${partyName("e")} AS f3 FROM payments x ` +
17
+ `${party("x.payer_type", "x.payer_id", "r")} ${party("x.payee_type", "x.payee_id", "e")} WHERE ${DECIDED}`,
18
+ order: "SELECT x.id, x.review, x.source, x.updated_at, x.number AS f1, x.supplier_name AS f2, " +
19
+ "(SELECT group_concat(description, char(10)) FROM order_lines WHERE order_id = x.id) AS f3 " +
20
+ `FROM orders x WHERE ${DECIDED}`,
21
+ contract: "SELECT x.id, x.review, x.source, x.updated_at, x.name AS f1, x.number AS f2 FROM contracts x " +
22
+ `WHERE ${DECIDED}`,
23
+ subscription: `SELECT x.id, x.review, x.source, x.updated_at, x.name AS f1 FROM subscriptions x WHERE ${DECIDED}`,
24
+ product: "SELECT x.id, 'confirmed' AS review, x.source, x.updated_at, x.name AS f1, x.sku AS f2 FROM catalog_items x " +
25
+ `WHERE ${LIVE}`,
26
+ wallet: "SELECT x.id, 'confirmed' AS review, x.source, x.updated_at, x.name AS f1, x.institution AS f2 " +
27
+ `FROM financial_accounts x WHERE ${LIVE}`,
28
+ };
29
+ const FIELDS = ["f1", "f2", "f3"];
30
+ const TEXT_CHARS = 240;
31
+ const KINDS_SQL = BUSINESS_KINDS.map((kind) => `'${kind}'`).join(", ");
32
+ const IMPORT = "import:";
33
+ const WORD_CHAR = /[\p{L}\p{N}]/u;
34
+ const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
35
+ const lineOf = (parts) => {
36
+ const line = parts.join(" · ").replace(/\s+/gu, " ").trim();
37
+ return line.length <= TEXT_CHARS ? line : `${line.slice(0, TEXT_CHARS - 1)}…`;
38
+ };
39
+ /** "get" finds "Get well" and "INV-get", never "Widget": a word is matched where a word starts. */
40
+ export const startsAWord = (folded, word) => {
41
+ for (let at = folded.indexOf(word); at !== -1; at = folded.indexOf(word, at + 1))
42
+ if (at === 0 || !WORD_CHAR.test(folded[at - 1]))
43
+ return true;
44
+ return false;
45
+ };
46
+ export const businessSearchOver = ({ database }) => {
47
+ const matchedOf = (kind, wanted, anyWord) => database
48
+ .prepare(SEARCHED[kind])
49
+ .all()
50
+ .flatMap((row) => {
51
+ const parts = FIELDS.flatMap((field) => (row[field] == null ? [] : [String(row[field])]));
52
+ // A newline between fields keeps a phrase from matching across two of them.
53
+ const folded = fold(parts.join("\n"));
54
+ const score = wanted.filter((word) => startsAWord(folded, word)).length;
55
+ if (anyWord ? score === 0 : score < wanted.length)
56
+ return [];
57
+ const source = String(row.source);
58
+ return [
59
+ {
60
+ kind,
61
+ id: Number(row.id),
62
+ review: row.review === "proposed" ? "proposed" : "confirmed",
63
+ imported: source.startsWith(IMPORT) ? source.slice(IMPORT.length) : undefined,
64
+ parts,
65
+ score,
66
+ updatedAt: Number(row.updated_at),
67
+ },
68
+ ];
69
+ });
70
+ /**
71
+ * The one record that names each imported row's account. A record the owner mapped onto the row later never moves
72
+ * it; a deleted record counts only when no live one is left.
73
+ */
74
+ const sourcesOf = (matched) => {
75
+ const sources = new Map();
76
+ for (const kind of BUSINESS_KINDS) {
77
+ const ids = matched.filter((one) => one.kind === kind && one.imported !== undefined).map(({ id }) => id);
78
+ if (!ids.length)
79
+ continue;
80
+ const rows = database
81
+ .prepare("SELECT r.entity_id, r.external_id, a.provider, a.external_id AS account FROM records r " +
82
+ "JOIN accounts a ON a.id = r.account_id " +
83
+ "WHERE r.entity_type = ? AND r.entity_id IN (SELECT value FROM json_each(?)) " +
84
+ "ORDER BY r.entity_id, (r.deleted_at IS NOT NULL), r.id")
85
+ .all(kind, JSON.stringify(ids));
86
+ for (const row of rows) {
87
+ const ref = `${kind}:${row.entity_id}`;
88
+ if (!sources.has(ref))
89
+ sources.set(ref, {
90
+ provider: String(row.provider),
91
+ account: String(row.account),
92
+ externalId: String(row.external_id),
93
+ });
94
+ }
95
+ }
96
+ return sources;
97
+ };
98
+ const find = ({ words, anyWord = false, accounts, limit }) => {
99
+ const wanted = [...new Set(words.map((word) => fold(word).trim()).filter(Boolean))];
100
+ if (!wanted.length)
101
+ return [];
102
+ const most = Math.min(Math.max(limit ?? 100, 1), BUSINESS_FIND_MAX);
103
+ const within = accounts === undefined ? undefined : new Set(accounts.map(keyOf));
104
+ // Numbers and names are short; folding them here is cheaper than an index the store would keep in step.
105
+ const matched = BUSINESS_KINDS.flatMap((kind) => matchedOf(kind, wanted, anyWord)).sort((a, b) => b.score - a.score || b.updatedAt - a.updatedAt || a.kind.localeCompare(b.kind) || b.id - a.id);
106
+ // Without a scope only the page needs its records; with one, every match is checked against it first.
107
+ const candidates = within === undefined ? matched.slice(0, most) : matched.filter((one) => one.imported);
108
+ const sources = sourcesOf(candidates);
109
+ const kept = within === undefined
110
+ ? candidates
111
+ : candidates
112
+ .filter((one) => {
113
+ const source = sources.get(`${one.kind}:${one.id}`);
114
+ return source !== undefined && within.has(keyOf(source));
115
+ })
116
+ .slice(0, most);
117
+ return kept.map((one) => {
118
+ const ref = `${one.kind}:${one.id}`;
119
+ const source = sources.get(ref);
120
+ return {
121
+ kind: one.kind,
122
+ ref,
123
+ review: one.review,
124
+ ...(one.imported === undefined ? {} : { imported: one.imported }),
125
+ ...(source === undefined ? {} : { source }),
126
+ text: lineOf(one.parts),
127
+ updatedAt: one.updatedAt,
128
+ };
129
+ });
130
+ };
131
+ const sourceAccounts = () => database
132
+ .prepare("SELECT DISTINCT a.provider, a.external_id AS account FROM records r JOIN accounts a ON a.id = r.account_id " +
133
+ `WHERE r.entity_type IN (${KINDS_SQL}) AND r.entity_id IS NOT NULL AND r.deleted_at IS NULL ` +
134
+ "ORDER BY a.provider, a.external_id")
135
+ .all()
136
+ .map((row) => ({ provider: String(row.provider), account: String(row.account) }));
137
+ return {
138
+ find: async (search) => find(search),
139
+ accounts: async () => sourceAccounts(),
140
+ };
141
+ };
@@ -120,6 +120,18 @@ export interface FinanceStore {
120
120
  /** The number printed on it, exactly. */
121
121
  number?: string;
122
122
  }): Promise<Invoice[]>;
123
+ /**
124
+ * A line at the end, and the total follows. The owner changes any invoice's lines but a void one's, a bot only those
125
+ * of an invoice it proposed that is still proposed; the total never falls below what confirmed payments settled.
126
+ */
127
+ addInvoiceLine(reference: string, input: InvoiceLineInput & {
128
+ by: Author;
129
+ }): Promise<InvoiceDetail>;
130
+ /** Under the same rules as `addInvoiceLine`; an invoice keeps at least one line. */
131
+ removeInvoiceLine(reference: string, input: {
132
+ position: number;
133
+ by: Author;
134
+ }): Promise<InvoiceDetail>;
123
135
  /** The owner sends a draft: its status then follows its allocations. */
124
136
  issueInvoice(reference: string, by: Author): Promise<InvoiceDetail>;
125
137
  /** The owner cancels an invoice no confirmed payment is allocated to; proposed allocations to it go. */
@@ -3,7 +3,7 @@ import { FINANCE_REVIEWS, INVOICE_DIRECTIONS, INVOICE_STATUSES, invoiceTitle, MO
3
3
  import { currencyOf, formatDecimal, minorUnits, moneyLabel, moneyOf, scaleOf } from "../../domain/money.js";
4
4
  import { proposedBySql } from "./actors.js";
5
5
  import { authorActor, projectId } from "./memories.js";
6
- import { moneyLinesOver } from "./money-lines.js";
6
+ import { MAX_LINES, moneyLinesOver } from "./money-lines.js";
7
7
  import { requiredThing } from "./notes.js";
8
8
  import { netPaidSql, refundRulesOver } from "./refunds.js";
9
9
  import { iso, isoDate, limitOf, oneOf, prefixesText, refuse, reviewedRowsOver, text, } from "./reviewed.js";
@@ -11,7 +11,6 @@ import { write } from "./transaction.js";
11
11
  /** The types `decide` settles money for; other proposal types get their own route. */
12
12
  const FINANCE_TYPES = ["invoice", "payment"];
13
13
  const isFinanceType = (type) => FINANCE_TYPES.includes(type);
14
- const MAX_LINES = 500;
15
14
  /** Money settled by confirmed payments only: a proposed payment promises nothing yet. */
16
15
  const PAID = netPaidSql("i.id");
17
16
  const INVOICES = `SELECT i.*, ${PAID} AS paid, b.name AS author_name, b.kind AS author_kind FROM invoices i ` +
@@ -234,6 +233,30 @@ export const financeOperationsOver = (context) => {
234
233
  `(SELECT id FROM payments WHERE refund_of IS ${refund ? "NOT " : ""}NULL${which})`)
235
234
  .run(invoiceId);
236
235
  };
236
+ const mayChangeLines = (row, by) => {
237
+ mayChangeParts(row, by, `only the owner changes the lines of invoice:${row.id}; ` +
238
+ "a bot changes only an invoice it proposed that is still proposed");
239
+ if (row.deleted_at != null || row.review === "rejected" || row.status === "void")
240
+ refuse(`invoice:${row.id} is ${row.deleted_at != null ? "deleted" : row.review === "rejected" ? "rejected" : "void"}`, "finance.status");
241
+ };
242
+ /** Checked here before the trigger, which only aborts without saying why. */
243
+ const relined = (row, change) => {
244
+ const [id, currency] = [Number(row.id), String(row.currency)];
245
+ write(database, () => {
246
+ change(id);
247
+ const total = lines.sumOf("invoice", id);
248
+ if (!Number.isSafeInteger(total))
249
+ refuse("an invoice's total is too large", "finance.total");
250
+ if (total <= 0)
251
+ refuse("an invoice totals more than 0", "finance.total");
252
+ const paid = Number(database.prepare(`SELECT ${netPaidSql("?")} AS n`).get(id)?.n);
253
+ if (total < paid)
254
+ refuse(`${moneyLabel(paid, currency)} is paid on invoice:${id}; its lines cannot total ${moneyLabel(total, currency)}`, "finance.below-paid");
255
+ lines.retotal("invoice", id, now());
256
+ settle(id);
257
+ });
258
+ return invoiceDetail(`invoice:${id}`);
259
+ };
237
260
  const mayAllocate = (row, by) => mayChangeParts(row, by, `only the owner allocates payment:${row.id}; a bot allocates only from a payment it proposed that is still proposed`);
238
261
  return {
239
262
  addInvoice: (input) => {
@@ -276,6 +299,17 @@ export const financeOperationsOver = (context) => {
276
299
  return invoiceDetail(`invoice:${id}`);
277
300
  },
278
301
  invoice: (reference) => invoiceDetail(reference),
302
+ addInvoiceLine: (reference, { by, ...line }) => {
303
+ const row = rowOf(reference, "invoice");
304
+ mayChangeLines(row, by);
305
+ const [priced] = lines.linesOf("invoice", [line], String(row.currency));
306
+ return relined(row, (id) => lines.appendLine("invoice", id, priced, now()));
307
+ },
308
+ removeInvoiceLine: (reference, { position, by }) => {
309
+ const row = rowOf(reference, "invoice");
310
+ mayChangeLines(row, by);
311
+ return relined(row, (id) => lines.deleteLine("invoice", id, position));
312
+ },
279
313
  invoices: (filter = {}) => {
280
314
  const project = filter.project === undefined ? null : projectId(database, filter.project);
281
315
  const counterparty = partyThing(filter.counterparty, "the counterparty");
@@ -432,6 +466,8 @@ export const financeStoreOver = (context) => {
432
466
  return {
433
467
  addInvoice: async (input) => operations.addInvoice(input),
434
468
  invoice: async (reference) => operations.invoice(reference),
469
+ addInvoiceLine: async (reference, input) => operations.addInvoiceLine(reference, input),
470
+ removeInvoiceLine: async (reference, input) => operations.removeInvoiceLine(reference, input),
435
471
  invoices: async (filter) => operations.invoices(filter),
436
472
  issueInvoice: async (reference, by) => operations.issueInvoice(reference, by),
437
473
  voidInvoice: async (reference, by) => operations.voidInvoice(reference, by),
@@ -1,10 +1,6 @@
1
1
  import type { CacheDatabase } from "../driver.js";
2
- /** A thing whose rows are recomputed: its kind as `involvement_pending` names it, and its id. */
3
- interface Subject {
4
- type: string;
5
- id: number;
6
- }
7
- export declare const sourcesOf: (subject?: Subject) => string;
2
+ /** Every way of taking part, or, given a subject's kind, only the ones about the id bound at each `?`. */
3
+ export declare const sourcesOf: (type?: string) => string;
8
4
  export declare const INSERT = "INSERT INTO involvements (person_id, identity_id, subject_type, subject_id, role, occurred_at, scope, account_id, project_id, created_at)";
9
5
  /** Most a write recomputes before it commits; a change larger than this, such as an account's scope, waits for the next write. */
10
6
  export declare const QUEUE_CAP = 10000;
@@ -13,4 +9,3 @@ export declare const QUEUE_CAP = 10000;
13
9
  * commits. `write` in `transaction.ts` calls it on every outermost commit; reads never do.
14
10
  */
15
11
  export declare const drainInvolvementQueue: (database: CacheDatabase, cap?: number) => number;
16
- export {};
@@ -93,23 +93,19 @@ const linkArm = (linkFrom, linkTo) => `
93
93
  LEFT JOIN accounts a ON a.id=coalesce(m.account_id,c.account_id,e.account_id,mt.account_id,d.account_id)
94
94
  WHERE l.to_type IN ('person','identity') AND l.to_id IS NOT NULL AND ${usableLinkSql("l")} AND (l.from_type<>'message' OR m.deleted_at IS NULL) AND (l.from_type<>'email' OR e.deleted_at IS NULL) AND (l.from_type<>'meeting' OR mt.deleted_at IS NULL) AND (l.from_type<>'task' OR t.deleted_at IS NULL) AND (l.from_type<>'document' OR d.deleted_at IS NULL)
95
95
  `;
96
- /**
97
- * Every way of taking part, or only the ones about `subject`, each filtered by its own key so SQLite reads
98
- * that one row by index. The kind and id are checked before they are written into the SQL.
99
- */
100
96
  /** Names the columns once: a UNION takes them from its first SELECT, and a subject's own arms may not lead. */
101
97
  const COLUMNS = "SELECT NULL AS person_id, NULL AS identity_id, NULL AS subject_type, NULL AS subject_id, NULL AS role, " +
102
98
  "NULL AS occurred_at, NULL AS scope, NULL AS account_id, NULL AS project_id WHERE 0";
103
- export const sourcesOf = (subject) => {
104
- if (subject === undefined)
99
+ /** Every way of taking part, or, given a subject's kind, only the ones about the id bound at each `?`. */
100
+ export const sourcesOf = (type) => {
101
+ if (type === undefined)
105
102
  return [COLUMNS, ...ARMS.map(([, , sql]) => sql), linkArm("1", "1")].join(" UNION ");
106
- if (!/^[a-z_]+$/.test(subject.type) || !Number.isSafeInteger(subject.id))
107
- throw new CliError("configuration_error", `the involvement queue holds ${subject.type} ${subject.id}`);
108
- const { type, id } = subject;
103
+ if (!/^[a-z_]+$/.test(type))
104
+ throw new CliError("configuration_error", `the involvement queue holds a ${type}`);
109
105
  return [
110
106
  COLUMNS,
111
- ...ARMS.filter(([of]) => of === type).map(([, key, sql]) => `${sql} AND ${key}=${id}`),
112
- linkArm(`from_type='${type}' AND from_id=${id}`, `to_type='${type}' AND to_id=${id}`),
107
+ ...ARMS.filter(([of]) => of === type).map(([, key, sql]) => `${sql} AND ${key}=?`),
108
+ linkArm(`from_type='${type}' AND from_id=?`, `to_type='${type}' AND to_id=?`),
113
109
  ].join(" UNION ");
114
110
  };
115
111
  export const INSERT = "INSERT INTO involvements (person_id, identity_id, subject_type, subject_id, role, occurred_at, scope, account_id, project_id, created_at)";
@@ -131,9 +127,10 @@ export const drainInvolvementQueue = (database, cap = QUEUE_CAP) => {
131
127
  break;
132
128
  for (const subject of subjects) {
133
129
  drop.run(subject.type, subject.id);
134
- database
135
- .prepare(`${INSERT} SELECT s.*, ? FROM (${sourcesOf(subject)}) s JOIN persons p ON p.id=s.person_id`)
136
- .run(at);
130
+ // One `?` per use of the id: Node 22.16's node:sqlite cannot bind a numbered `?2` by position.
131
+ const sql = `${INSERT} SELECT s.*, ? FROM (${sourcesOf(subject.type)}) s JOIN persons p ON p.id=s.person_id`;
132
+ const ids = Array(sql.split("?").length - 2).fill(subject.id);
133
+ database.prepare(sql).run(at, ...ids);
137
134
  done.run(subject.type, subject.id);
138
135
  }
139
136
  recomputed += subjects.length;
@@ -25,17 +25,24 @@ export interface PricedLine {
25
25
  amount: number;
26
26
  productId: number | null;
27
27
  }
28
- /** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
28
+ export declare const MAX_LINES = 500;
29
+ /** Where each parent keeps its lines, and the reasons its line errors carry. */
29
30
  declare const PARENTS: {
30
31
  readonly invoice: {
32
+ readonly parents: "invoices";
31
33
  readonly table: "invoice_lines";
32
34
  readonly column: "invoice_id";
33
35
  readonly reasons: "finance";
36
+ readonly full: "finance.lines";
37
+ readonly instead: "reject or void the invoice instead";
34
38
  };
35
39
  readonly order: {
40
+ readonly parents: "orders";
36
41
  readonly table: "order_lines";
37
42
  readonly column: "order_id";
38
43
  readonly reasons: "order";
44
+ readonly full: "order.field";
45
+ readonly instead: "reject or cancel the order instead";
39
46
  };
40
47
  };
41
48
  export type LineParent = keyof typeof PARENTS;
@@ -44,5 +51,9 @@ export declare const moneyLinesOver: ({ database }: StoreContext) => {
44
51
  linesOf: (parent: LineParent, lines: MoneyLineInput[], currency: string) => PricedLine[];
45
52
  insertLines: (parent: LineParent, id: number, lines: PricedLine[], from: number, at: number) => void;
46
53
  shownLines: (parent: LineParent, id: number, currency: string) => MoneyLine[];
54
+ appendLine: (parent: LineParent, id: number, line: PricedLine, at: number) => void;
55
+ deleteLine: (parent: LineParent, id: number, position: number) => void;
56
+ sumOf: (parent: LineParent, id: number) => number;
57
+ retotal: (parent: LineParent, id: number, at: number) => void;
47
58
  };
48
59
  export {};
@@ -1,10 +1,26 @@
1
+ import { CliError } from "@wirecat/cli-base";
1
2
  import { formatDecimal, lineUnits, minorUnits, moneyLabel, quantityOf, scaleOf } from "../../domain/money.js";
2
3
  import { requiredThing } from "./notes.js";
3
4
  import { refuse, text } from "./reviewed.js";
4
- /** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
5
+ export const MAX_LINES = 500;
6
+ /** Where each parent keeps its lines, and the reasons its line errors carry. */
5
7
  const PARENTS = {
6
- invoice: { table: "invoice_lines", column: "invoice_id", reasons: "finance" },
7
- order: { table: "order_lines", column: "order_id", reasons: "order" },
8
+ invoice: {
9
+ parents: "invoices",
10
+ table: "invoice_lines",
11
+ column: "invoice_id",
12
+ reasons: "finance",
13
+ full: "finance.lines",
14
+ instead: "reject or void the invoice instead",
15
+ },
16
+ order: {
17
+ parents: "orders",
18
+ table: "order_lines",
19
+ column: "order_id",
20
+ reasons: "order",
21
+ full: "order.field",
22
+ instead: "reject or cancel the order instead",
23
+ },
8
24
  };
9
25
  /** Invoice and order lines: quantity × unit price, in the parent's currency, a product's name and price copied. */
10
26
  export const moneyLinesOver = ({ database }) => {
@@ -72,5 +88,35 @@ export const moneyLinesOver = ({ database }) => {
72
88
  product: line.catalog_item_id == null ? null : `product:${line.catalog_item_id}`,
73
89
  }));
74
90
  };
75
- return { linesOf, insertLines, shownLines };
91
+ /** Writes a line after the last one; the caller retotals the parent in the same write. */
92
+ const appendLine = (parent, id, line, at) => {
93
+ const { table, column, full } = PARENTS[parent];
94
+ const last = Number(database.prepare(`SELECT coalesce(max(position), 0) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
95
+ if (last >= MAX_LINES)
96
+ refuse(`an ${parent} has at most ${MAX_LINES} lines`, full);
97
+ insertLines(parent, id, [line], last + 1, at);
98
+ };
99
+ /** Removes one line, never the last; the caller retotals the parent in the same write. */
100
+ const deleteLine = (parent, id, position) => {
101
+ const { table, column, reasons, instead } = PARENTS[parent];
102
+ const lines = Number(database.prepare(`SELECT count(*) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
103
+ const gone = database.prepare(`DELETE FROM ${table} WHERE ${column} = ? AND position = ?`).run(id, position);
104
+ if (gone.changes === 0)
105
+ throw new CliError("not_found", `${parent}:${id} has no line ${position}`, { reason: `${reasons}.no-line` });
106
+ if (lines === 1)
107
+ refuse(`line ${position} is the last of ${parent}:${id}; ${instead}`, `${reasons}.line`);
108
+ };
109
+ const sumOf = (parent, id) => {
110
+ const { table, column } = PARENTS[parent];
111
+ return Number(database.prepare(`SELECT coalesce(sum(amount), 0) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
112
+ };
113
+ /** The parent's total follows its lines: orders' trigger checks the sum when the order changes. */
114
+ const retotal = (parent, id, at) => {
115
+ const { parents, table, column } = PARENTS[parent];
116
+ database
117
+ .prepare(`UPDATE ${parents} SET total = coalesce((SELECT sum(amount) FROM ${table} WHERE ${column} = ?), total), ` +
118
+ "updated_at = ? WHERE id = ?")
119
+ .run(id, at, id);
120
+ };
121
+ return { linesOf, insertLines, shownLines, appendLine, deleteLine, sumOf, retotal };
76
122
  };
@@ -7,11 +7,10 @@ import { ORDER_PURPOSES, ORDER_STATUSES, orderTitle } from "../../domain/orders.
7
7
  import { fold } from "../normalize.js";
8
8
  import { ownerPerson, proposedBySql } from "./actors.js";
9
9
  import { projectId } from "./memories.js";
10
- import { moneyLinesOver } from "./money-lines.js";
10
+ import { MAX_LINES, moneyLinesOver } from "./money-lines.js";
11
11
  import { requiredThing } from "./notes.js";
12
12
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
13
13
  import { write } from "./transaction.js";
14
- const MAX_LINES = 500;
15
14
  const ORDERS = "SELECT o.*, b.name AS author_name, b.kind AS author_kind FROM orders o " +
16
15
  "LEFT JOIN bots b ON o.author_type = 'bot' AND b.id = o.author_id";
17
16
  export const orderOperationsOver = (context) => {
@@ -57,13 +56,6 @@ export const orderOperationsOver = (context) => {
57
56
  ...orderOf(row),
58
57
  lines: row.currency == null ? [] : moneyLines.shownLines("order", Number(row.id), String(row.currency)),
59
58
  });
60
- /** The order's total follows its lines in the same write: the trigger checks the sum when the order changes. */
61
- const retotal = (orderId) => {
62
- database
63
- .prepare("UPDATE orders SET total = coalesce((SELECT sum(amount) FROM order_lines WHERE order_id = ?), total), " +
64
- "updated_at = ? WHERE id = ?")
65
- .run(orderId, now(), orderId);
66
- };
67
59
  const mayChangeLines = (row, by) => {
68
60
  mayChangeParts(row, by, `only the owner changes the lines of order:${row.id}; a bot changes only an order it proposed that is still proposed`, "order.owner-only");
69
61
  if (row.review === "rejected" || row.deleted_at != null)
@@ -208,13 +200,8 @@ export const orderOperationsOver = (context) => {
208
200
  refuse(`order:${row.id} has no currency; a line needs one`, "order.total");
209
201
  const [priced] = moneyLines.linesOf("order", [line], String(row.currency));
210
202
  write(database, () => {
211
- const last = Number(database
212
- .prepare("SELECT coalesce(max(position), 0) AS n FROM order_lines WHERE order_id = ?")
213
- .get(Number(row.id))?.n);
214
- if (last >= MAX_LINES)
215
- refuse(`an order has at most ${MAX_LINES} lines`, "order.field");
216
- moneyLines.insertLines("order", Number(row.id), [priced], last + 1, now());
217
- retotal(Number(row.id));
203
+ moneyLines.appendLine("order", Number(row.id), priced, now());
204
+ moneyLines.retotal("order", Number(row.id), now());
218
205
  });
219
206
  return detailOf(rowOf(`order:${row.id}`));
220
207
  },
@@ -222,15 +209,8 @@ export const orderOperationsOver = (context) => {
222
209
  const row = rowOf(reference);
223
210
  mayChangeLines(row, by);
224
211
  write(database, () => {
225
- const lines = Number(database.prepare("SELECT count(*) AS n FROM order_lines WHERE order_id = ?").get(Number(row.id))?.n);
226
- const gone = database
227
- .prepare("DELETE FROM order_lines WHERE order_id = ? AND position = ?")
228
- .run(Number(row.id), position);
229
- if (gone.changes === 0)
230
- throw new CliError("not_found", `order:${row.id} has no line ${position}`, { reason: "order.no-line" });
231
- if (lines === 1)
232
- refuse(`line ${position} is the last of order:${row.id}; reject or cancel the order instead`, "order.line");
233
- retotal(Number(row.id));
212
+ moneyLines.deleteLine("order", Number(row.id), position);
213
+ moneyLines.retotal("order", Number(row.id), now());
234
214
  });
235
215
  return detailOf(rowOf(`order:${row.id}`));
236
216
  },
@@ -61,6 +61,8 @@ export interface ProposedActionsStore {
61
61
  proposedBy?: ProposedByFilter;
62
62
  /** A `project:<id>` the action targets or its payload names as `to`, `from` or `project`. */
63
63
  project?: string;
64
+ /** A reference the payload's `evidence` holds. */
65
+ evidence?: string;
64
66
  }): Promise<ProposedAction[]>;
65
67
  /** `result` records what the approval made, such as the task it became. `by` must be allowed to decide it. */
66
68
  approve(id: string, by: Decider, result?: unknown): Promise<ProposedAction>;
@@ -131,7 +131,7 @@ export const proposalOperationsOver = (context) => {
131
131
  .prepare(`${NAMED} WHERE p.status = 'proposed' ORDER BY p.created_at, p.id LIMIT ?`)
132
132
  .all(Math.min(Math.max(limit, 1), 500))
133
133
  .map(actionOf),
134
- list: ({ status, limit = 100, kinds, except, proposedBy, project } = {}) => {
134
+ list: ({ status, limit = 100, kinds, except, proposedBy, project, evidence } = {}) => {
135
135
  if (status !== undefined && !PROPOSAL_STATUSES.includes(status))
136
136
  throw new CliError("validation_error", `a status is one of ${PROPOSAL_STATUSES.join(", ")}`);
137
137
  const by = proposedBySql("p.proposed_by_type", "p.proposed_by_id", proposedBy);
@@ -139,8 +139,9 @@ export const proposalOperationsOver = (context) => {
139
139
  .prepare(`${NAMED} WHERE (? IS NULL OR ${STATUS} = ?) AND (? IS NULL OR p.kind IN (SELECT value FROM json_each(?))) ` +
140
140
  "AND p.kind NOT IN (SELECT value FROM json_each(?)) AND (? IS NULL OR (p.target_type = 'project' AND " +
141
141
  "'project:' || p.target_id = ?) OR json_extract(p.payload, '$.to') = ? OR json_extract(p.payload, '$.from') = ? " +
142
- `OR json_extract(p.payload, '$.project') = ?) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
143
- .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), ...by.params, Math.min(Math.max(limit, 1), 500))
142
+ `OR json_extract(p.payload, '$.project') = ?) AND (? IS NULL OR EXISTS (SELECT 1 FROM json_each(p.payload, '$.evidence') ` +
143
+ `WHERE value = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
144
+ .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, Math.min(Math.max(limit, 1), 500))
144
145
  .map(actionOf);
145
146
  },
146
147
  approve: (id, result, by) => decide(id, "approved", result, by),
@@ -44,6 +44,13 @@ export interface MappedRecord extends SourceRecord {
44
44
  /** Records that waited on it whose entity was still refused. */
45
45
  errors: IngestError[];
46
46
  }
47
+ export interface IncomingRelation {
48
+ /** The live record whose relation points at the target. */
49
+ record: RecordKey;
50
+ role: string;
51
+ as: string | null;
52
+ amount: string | null;
53
+ }
47
54
  export interface MatchRun {
48
55
  linked: number;
49
56
  created: number;
@@ -74,9 +81,23 @@ export interface RecordStore {
74
81
  /** Only persons, organizations and projects whose identifiers point at more than one entity. */
75
82
  unmatched?: boolean;
76
83
  flagged?: boolean;
84
+ /** A ref such as `person:4`: the records mapped to that entity. */
85
+ entity?: string;
86
+ batch?: string;
87
+ /** `true`: only deleted records; `false`: only live ones; left out, both. */
88
+ deleted?: boolean;
77
89
  /** 1–500, 100 by default. */
78
90
  limit?: number;
79
91
  }): Promise<SourceRecord[]>;
92
+ /**
93
+ * The relations of live records that point at a record of the account, or at an entity: by its ref, or through a
94
+ * record mapped to it. An entity's are read across every account, and each names its own. Oldest relation first.
95
+ */
96
+ incoming(target: RecordKey | {
97
+ entity: string;
98
+ }, options?: {
99
+ limit?: number;
100
+ }): Promise<IncomingRelation[]>;
80
101
  /**
81
102
  * The owner says which entity a record is: `person:4` for a payer a sheet names. Never done by name. Records that
82
103
  * waited for it get their entity, as proposals. A record whose entity the import made moves, with every record of