@wirecat/cli-core 0.609.0 → 0.611.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 +68 -0
- package/dist/cli/messenger/search-answers.js +12 -0
- package/dist/cli/search-left-out.d.ts +1 -0
- package/dist/cli/search-left-out.js +2 -0
- package/dist/domain/business.d.ts +3 -0
- package/dist/domain/business.js +2 -0
- package/dist/entities/hit.d.ts +13 -2
- package/dist/entities/hit.js +10 -2
- package/dist/entities/index.d.ts +7 -1
- package/dist/errors/reasons.js +4 -0
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/search/account-list.d.ts +3 -2
- package/dist/search/account-list.js +5 -4
- package/dist/services/link-scorers/chat-senders.d.ts +2 -1
- package/dist/services/link-scorers/chat-senders.js +13 -4
- package/dist/services/link-scorers/types.d.ts +1 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/proposals/kinds/relationship.js +1 -0
- package/dist/services/proposals/registry.js +3 -1
- package/dist/services/proposals/types.d.ts +2 -0
- package/dist/services/search-all-business.d.ts +18 -0
- package/dist/services/search-all-business.js +38 -0
- package/dist/services/search-all-meetings.d.ts +1 -1
- package/dist/services/search-all-meetings.js +7 -2
- package/dist/services/search-all.d.ts +10 -6
- package/dist/services/search-all.js +26 -10
- package/dist/store/exports.d.ts +2 -0
- package/dist/store/exports.js +2 -0
- package/dist/store/index.d.ts +4 -1
- package/dist/store/index.js +2 -0
- package/dist/store/sqlite/business-search.d.ts +44 -0
- package/dist/store/sqlite/business-search.js +141 -0
- package/dist/store/sqlite/finance.d.ts +12 -0
- package/dist/store/sqlite/finance.js +38 -2
- package/dist/store/sqlite/involvement-queue.d.ts +2 -7
- package/dist/store/sqlite/involvement-queue.js +11 -14
- package/dist/store/sqlite/money-lines.d.ts +12 -1
- package/dist/store/sqlite/money-lines.js +50 -4
- package/dist/store/sqlite/orders.js +5 -25
- package/dist/store/sqlite/proposed-actions.d.ts +2 -0
- package/dist/store/sqlite/proposed-actions.js +4 -3
- package/dist/store/sqlite/records.d.ts +21 -0
- package/dist/store/sqlite/records.js +74 -13
- package/dist/store/sqlite/ref-summaries.d.ts +3 -1
- package/dist/store/sqlite/ref-summaries.js +4 -1
- package/dist/store/sqlite/reported-relations.d.ts +1 -0
- package/dist/store/sqlite/reported-relations.js +1 -1
- package/dist/store/store.d.ts +2 -0
- package/dist/store/store.js +4 -4
- package/dist/terminal/prompt.d.ts +4 -0
- package/dist/terminal/prompt.js +21 -2
- package/package.json +3 -3
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { INTERNAL_NOTES } from "../domain/providers.js";
|
|
2
|
+
import { BUSINESS_FIND_MAX } from "../store/store.js";
|
|
3
|
+
/** The account a hit of the owner's own invoice, product or wallet names: no import made it. */
|
|
4
|
+
export const OWN_BUSINESS = { provider: "business", account: INTERNAL_NOTES };
|
|
5
|
+
export const BUSINESS_WORDS_ONLY = "invoices, payments, orders, contracts, subscriptions, products and wallets are found by the words of their " +
|
|
6
|
+
"numbers and names only";
|
|
7
|
+
/**
|
|
8
|
+
* A hit's account is its source record's. An imported row whose records all moved to other entities keeps its import
|
|
9
|
+
* provider with no account, so it is never taken for the owner's own.
|
|
10
|
+
*/
|
|
11
|
+
const placeOf = ({ source, imported }) => source ?? (imported === undefined ? OWN_BUSINESS : { provider: imported, account: "" });
|
|
12
|
+
/** The `business` lane: numbers and names folded in memory, each hit titled as its ref reads everywhere else. */
|
|
13
|
+
export const searchBusiness = async (store, { words, anyWord, window, accounts, }) => {
|
|
14
|
+
const asked = Math.min(window + 1, BUSINESS_FIND_MAX);
|
|
15
|
+
const found = await store.business.find({
|
|
16
|
+
words,
|
|
17
|
+
anyWord,
|
|
18
|
+
limit: asked,
|
|
19
|
+
...(accounts === undefined ? {} : { accounts }),
|
|
20
|
+
});
|
|
21
|
+
const page = found.slice(0, window);
|
|
22
|
+
const titles = await store.refs.summaries(page.map(({ ref }) => ref));
|
|
23
|
+
return {
|
|
24
|
+
items: page.map((hit) => ({
|
|
25
|
+
kind: hit.kind,
|
|
26
|
+
ref: hit.ref,
|
|
27
|
+
...placeOf(hit),
|
|
28
|
+
title: titles.get(hit.ref)?.title ?? null,
|
|
29
|
+
timestamp: new Date(hit.updatedAt).toISOString(),
|
|
30
|
+
text: hit.text,
|
|
31
|
+
review: hit.review,
|
|
32
|
+
...(hit.source === undefined ? {} : { sourceRecord: hit.source }),
|
|
33
|
+
foundBy: ["title"],
|
|
34
|
+
})),
|
|
35
|
+
hasMore: found.length > window || (asked < window + 1 && found.length === asked),
|
|
36
|
+
read: accounts ?? [...(await store.business.accounts()), OWN_BUSINESS],
|
|
37
|
+
};
|
|
38
|
+
};
|
|
@@ -3,7 +3,7 @@ import type { AccountKey, MessageStore } from "../store/store.js";
|
|
|
3
3
|
import type { SearchFound, SearchQuery } from "./messages.js";
|
|
4
4
|
import type { MeaningLane } from "./messages-discovery.js";
|
|
5
5
|
import { type SearchAllFound, type SearchAllItem, type SearchAllMessenger, type SearchAllRequest, type Skipped } from "./search-all.js";
|
|
6
|
-
export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "meetings"];
|
|
6
|
+
export declare const RESOURCES_SEARCHED_WITH_MEETINGS: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
|
|
7
7
|
export type ResourceWithMeetings = (typeof RESOURCES_SEARCHED_WITH_MEETINGS)[number];
|
|
8
8
|
export interface MeetingSearchItem {
|
|
9
9
|
kind: "meeting";
|
|
@@ -243,14 +243,18 @@ const holdingMeetings = async (store, named) => {
|
|
|
243
243
|
}
|
|
244
244
|
return holding.length ? holding : named;
|
|
245
245
|
};
|
|
246
|
+
const keyOf = ({ provider, account }) => `${provider}\u0000${account}`;
|
|
246
247
|
const searchAllOfSource = async (store, account, source, request, messenger, searchMessages, meaning) => {
|
|
247
248
|
const only = request.only ?? RESOURCES_SEARCHED_WITH_MEETINGS;
|
|
248
249
|
const entries = entriesOfList(source, await listContextOf(store, account, messenger.app));
|
|
249
|
-
|
|
250
|
+
// Any provider's import may write business data, so its accounts are the ones that hold some, whatever their kind.
|
|
251
|
+
const imported = only.includes("business") ? new Set((await store.business.accounts()).map(keyOf)) : new Set();
|
|
252
|
+
const holdsBusiness = (one) => imported.has(keyOf(one));
|
|
253
|
+
const { skipped } = fitting(entries, only.filter((one) => one !== "business"), "search all", (kind) => `--only leaves ${kind} out`, holdsBusiness);
|
|
250
254
|
const named = (resource) => [
|
|
251
255
|
...new Map(entries
|
|
252
256
|
.flatMap(({ accounts }) => accounts)
|
|
253
|
-
.filter((one) => listedHolds(one, resource))
|
|
257
|
+
.filter((one) => (resource === "business" ? holdsBusiness(one) : listedHolds(one, resource)))
|
|
254
258
|
.map(({ provider, account }) => [`${provider}\u0000${account}`, { provider, account }])).values(),
|
|
255
259
|
];
|
|
256
260
|
const meetings = await holdingMeetings(store, named("meetings"));
|
|
@@ -275,6 +279,7 @@ const searchAllOfSource = async (store, account, source, request, messenger, sea
|
|
|
275
279
|
notes: named("notes"),
|
|
276
280
|
events: named("events"),
|
|
277
281
|
crm: named("crm"),
|
|
282
|
+
business: named("business"),
|
|
278
283
|
},
|
|
279
284
|
...(meetings[0] ? { meetingAccount: meetings[0] } : {}),
|
|
280
285
|
}, messenger, searchMessages, meaning);
|
|
@@ -3,16 +3,16 @@ import { type HitFile } from "../domain/attachments.js";
|
|
|
3
3
|
import type { DealKind } from "../domain/deals.js";
|
|
4
4
|
import { type MailFields } from "../domain/models.js";
|
|
5
5
|
import type { MessengerTraits } from "../ports/traits.js";
|
|
6
|
-
import type { AccountKey, MessageStore } from "../store/store.js";
|
|
6
|
+
import type { AccountKey, BusinessKind, BusinessSource, MessageStore } from "../store/store.js";
|
|
7
7
|
import type { SearchFound, SearchQuery } from "./messages.js";
|
|
8
8
|
import { type MeaningLane, type MeaningSkipped } from "./messages-discovery.js";
|
|
9
9
|
import type { SearchCoverage } from "./messages-search.js";
|
|
10
10
|
import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
|
|
11
|
-
export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm"];
|
|
11
|
+
export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business"];
|
|
12
12
|
export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
|
|
13
13
|
export interface SearchAllItem {
|
|
14
|
-
kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead";
|
|
15
|
-
/** `msg:…` for a message or a mail, `note
|
|
14
|
+
kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | BusinessKind;
|
|
15
|
+
/** `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, or a business ref: `invoice:…`. */
|
|
16
16
|
ref: string;
|
|
17
17
|
provider: string;
|
|
18
18
|
/** The account it was found in; a note's folder id, or `internal` for a note written in memo. */
|
|
@@ -36,6 +36,10 @@ export interface SearchAllItem {
|
|
|
36
36
|
attachments?: HitFile[];
|
|
37
37
|
/** Which search found it: words, meaning or both. */
|
|
38
38
|
foundBy: ("title" | "words" | "meaning")[];
|
|
39
|
+
/** A business hit's: whether the owner confirmed it, or it waits for him. */
|
|
40
|
+
review?: "proposed" | "confirmed";
|
|
41
|
+
/** A business hit's source record, when an import made it. */
|
|
42
|
+
sourceRecord?: BusinessSource;
|
|
39
43
|
}
|
|
40
44
|
/** One account a search read, by the kind it was read for: the shape memo's `search all` answers too. */
|
|
41
45
|
export interface SearchedAccount {
|
|
@@ -127,14 +131,14 @@ export type SearchAllMessenger = Partial<Pick<MessengerTraits, "savedChatId" | "
|
|
|
127
131
|
* What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
|
|
128
132
|
* refused, so `search all` skips deals with the reason instead of matching a field they do not have.
|
|
129
133
|
*/
|
|
130
|
-
export declare const titleWords: (text: string) => {
|
|
134
|
+
export declare const titleWords: (text: string, refused?: string) => {
|
|
131
135
|
words: string[];
|
|
132
136
|
anyWord: boolean;
|
|
133
137
|
};
|
|
134
138
|
/** The accounts of every CRM the store holds copies of. */
|
|
135
139
|
export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>;
|
|
136
140
|
/**
|
|
137
|
-
* `search all`: messages, mail, notes, calendar events
|
|
141
|
+
* `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
|
|
138
142
|
* server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
|
|
139
143
|
* resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
|
|
140
144
|
*/
|
|
@@ -14,7 +14,8 @@ import { excerpt } from "./excerpt.js";
|
|
|
14
14
|
import { MAX_SEARCH_OFFSET, searchStore } from "./messages-archive-search.js";
|
|
15
15
|
import { nearEligible } from "./messages-discovery.js";
|
|
16
16
|
import { notesScopeOf, RRF_K, searchNotes } from "./notes-search.js";
|
|
17
|
-
|
|
17
|
+
import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
|
|
18
|
+
export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business"];
|
|
18
19
|
const refusal = (error, text) => {
|
|
19
20
|
const { reason, span } = (error.details ?? {});
|
|
20
21
|
const why = typeof reason === "string" ? reason : undefined;
|
|
@@ -43,7 +44,7 @@ const filtersBeside = (text) => {
|
|
|
43
44
|
* What a deal or a lead is found by: words or phrases of its title, all of them, or any with OR. Anything else is
|
|
44
45
|
* refused, so `search all` skips deals with the reason instead of matching a field they do not have.
|
|
45
46
|
*/
|
|
46
|
-
export const titleWords = (text) => {
|
|
47
|
+
export const titleWords = (text, refused = "deals and leads are found by the words of their title only") => {
|
|
47
48
|
const { root } = parseLucene(text, SEARCH_QUERY);
|
|
48
49
|
const clauses = root.kind === "boolean" ? root.clauses : [{ node: root, occur: "must" }];
|
|
49
50
|
const words = clauses.map(({ node, occur }) => occur !== "must_not" &&
|
|
@@ -53,7 +54,7 @@ export const titleWords = (text) => {
|
|
|
53
54
|
? // A title holds "invoice", not the question mark of "invoice?".
|
|
54
55
|
node.value.replace(/\?+$/u, "") || node.value
|
|
55
56
|
: (() => {
|
|
56
|
-
throw new CliError("validation_error",
|
|
57
|
+
throw new CliError("validation_error", refused);
|
|
57
58
|
})());
|
|
58
59
|
return { words, anyWord: clauses.length > 1 && clauses.every(({ occur }) => occur === "should") };
|
|
59
60
|
};
|
|
@@ -73,7 +74,7 @@ const strictWords = (text) => {
|
|
|
73
74
|
/** The accounts of every CRM the store holds copies of. */
|
|
74
75
|
export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
|
|
75
76
|
/**
|
|
76
|
-
* `search all`: messages, mail, notes, calendar events
|
|
77
|
+
* `search all`: messages, mail, notes, calendar events, CRM deals and leads, and business data from the local store — messages also from the messenger's
|
|
77
78
|
* server, as `search messages` asks it — each list best first, merged by reciprocal rank so no
|
|
78
79
|
* resource's own scores have to be compared with another's. Events are read only when the store holds a calendar.
|
|
79
80
|
*/
|
|
@@ -300,6 +301,19 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
300
301
|
for (const { provider, account } of read)
|
|
301
302
|
accounts.push({ resource, provider, account });
|
|
302
303
|
}
|
|
304
|
+
else if (resource === "business") {
|
|
305
|
+
const { words, anyWord } = titleWords(request.text, BUSINESS_WORDS_ONLY);
|
|
306
|
+
const found = await searchBusiness(store, {
|
|
307
|
+
words,
|
|
308
|
+
anyWord: anyWord || discover,
|
|
309
|
+
window,
|
|
310
|
+
accounts: request.scope?.business,
|
|
311
|
+
});
|
|
312
|
+
hasMore ||= found.hasMore;
|
|
313
|
+
lists.push(found.items);
|
|
314
|
+
for (const { provider, account } of found.read)
|
|
315
|
+
accounts.push({ resource, provider, account });
|
|
316
|
+
}
|
|
303
317
|
else
|
|
304
318
|
lists.push(await messagesOf(resource));
|
|
305
319
|
searched.push(resource);
|
|
@@ -344,20 +358,22 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
|
|
|
344
358
|
/**
|
|
345
359
|
* Every source's hits as one list: each source's best hit first, then every other hit by cosine, then by its rank in
|
|
346
360
|
* its source. Taking turns by rank (MEMO-37) gave each of two sources half of a ten-hit page however weak its hits;
|
|
347
|
-
* one model scores every source, so cosine compares across them (IDEA-249). A hit
|
|
348
|
-
*
|
|
361
|
+
* one model scores every source, so cosine compares across them (IDEA-249). A hit only words found takes the cosine of
|
|
362
|
+
* the hit above it in its source: its source ranked it there, and with none it would follow every hit meaning found.
|
|
349
363
|
*/
|
|
350
364
|
const oneList = (lists, cosines) => {
|
|
351
365
|
const place = new Map();
|
|
352
|
-
for (const list of lists)
|
|
366
|
+
for (const list of lists) {
|
|
367
|
+
let above = Number.NEGATIVE_INFINITY;
|
|
353
368
|
list.forEach((item, rank) => {
|
|
369
|
+
above = cosines.get(item.ref) ?? above;
|
|
354
370
|
const held = place.get(item.ref);
|
|
355
371
|
if (!held || rank < held.rank)
|
|
356
|
-
place.set(item.ref, { item, rank });
|
|
372
|
+
place.set(item.ref, { item, rank, cosine: above });
|
|
357
373
|
});
|
|
358
|
-
|
|
374
|
+
}
|
|
359
375
|
const head = (rank) => Math.min(rank, 1);
|
|
360
376
|
return [...place.values()]
|
|
361
|
-
.sort((a, b) => head(a.rank) - head(b.rank) ||
|
|
377
|
+
.sort((a, b) => head(a.rank) - head(b.rank) || b.cosine - a.cosine || a.rank - b.rank)
|
|
362
378
|
.map(({ item }) => item);
|
|
363
379
|
};
|
package/dist/store/exports.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
|
|
1
2
|
export type { CounterField, CounterObservations, CounterState } from "../domain/counters.js";
|
|
2
3
|
export type { RetentionOptions } from "../domain/retention.js";
|
|
3
4
|
export type { AccountAccounts, AccountsStore } from "./accounts.js";
|
|
@@ -17,6 +18,7 @@ export { accountGroupsOf } from "./sqlite/account-groups.js";
|
|
|
17
18
|
export type { AdminStoreRequest, AdminStoreResult } from "./sqlite/admin-statistics.js";
|
|
18
19
|
export { type AttachmentTextEntry, type AttachmentView, attachmentColumns, type FileAttachment, resetAttachmentWords, type TextOrigin, } from "./sqlite/attachment-texts.js";
|
|
19
20
|
export { pendingNormalization } from "./sqlite/backfill.js";
|
|
21
|
+
export { BUSINESS_FIND_MAX, type BusinessHit, type BusinessSearch, type BusinessSearchStore, type BusinessSource, } from "./sqlite/business-search.js";
|
|
20
22
|
export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
|
|
21
23
|
export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
|
|
22
24
|
export { storeClients } from "./sqlite/clients.js";
|
package/dist/store/exports.js
CHANGED
|
@@ -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";
|
package/dist/store/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/store/index.js
CHANGED
|
@@ -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
|
-
/**
|
|
3
|
-
|
|
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
|
-
|
|
104
|
-
|
|
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(
|
|
107
|
-
throw new CliError("configuration_error", `the involvement queue holds ${
|
|
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}
|
|
112
|
-
linkArm(`from_type='${type}' AND from_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
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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;
|