@wirecat/cli-core 0.668.0 → 0.670.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 +125 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/catalog.js +3 -14
- package/dist/cli/documents/sync.d.ts +21 -5
- package/dist/cli/documents/sync.js +39 -8
- package/dist/cli/documents/testing/source-contract.d.ts +9 -0
- package/dist/cli/documents/testing/source-contract.js +12 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/store-settings.js +5 -3
- package/dist/crm/cli/csv.d.ts +1 -1
- package/dist/crm/cli/csv.js +2 -2
- package/dist/crm/cli/index.d.ts +11 -1
- package/dist/crm/cli/index.js +11 -5
- package/dist/crm/cli/records.d.ts +94 -0
- package/dist/crm/cli/records.js +412 -0
- package/dist/crm/foreign-contacts.d.ts +34 -0
- package/dist/crm/foreign-contacts.js +104 -0
- package/dist/crm/index.d.ts +9 -3
- package/dist/crm/index.js +7 -1
- package/dist/crm/provider-call.d.ts +23 -0
- package/dist/crm/provider-call.js +49 -0
- package/dist/crm/query.d.ts +32 -0
- package/dist/crm/query.js +122 -0
- package/dist/crm/source.d.ts +41 -4
- package/dist/crm/sync.d.ts +1 -1
- package/dist/crm/sync.js +13 -7
- package/dist/crm/testing/source-contract.d.ts +5 -0
- package/dist/crm/testing/source-contract.js +39 -0
- package/dist/crm/testing/source.d.ts +9 -3
- package/dist/crm/testing/source.js +109 -10
- package/dist/crm/testing/write-contract.d.ts +2 -2
- package/dist/crm/testing/write-contract.js +41 -2
- package/dist/crm/values.d.ts +33 -0
- package/dist/crm/values.js +75 -0
- package/dist/crm/walk.d.ts +18 -0
- package/dist/crm/walk.js +23 -0
- package/dist/crm/writer.d.ts +41 -6
- package/dist/crm/writer.js +16 -10
- package/dist/crm/writes.d.ts +38 -2
- package/dist/crm/writes.js +163 -9
- package/dist/documents/model.d.ts +4 -0
- package/dist/domain/crm.d.ts +41 -5
- package/dist/entities/deal.d.ts +8 -2
- package/dist/entities/deal.js +4 -1
- package/dist/errors/reasons.js +23 -2
- package/dist/oauth/index.d.ts +1 -1
- package/dist/oauth/index.js +1 -1
- package/dist/oauth/keeper.js +4 -0
- package/dist/oauth/storage.d.ts +21 -0
- package/dist/oauth/storage.js +32 -1
- package/dist/services/documents/ingestion.d.ts +3 -0
- package/dist/services/documents/ingestion.js +9 -2
- package/dist/services/documents/plan.d.ts +16 -1
- package/dist/services/documents/plan.js +163 -103
- package/dist/services/documents/ports.d.ts +13 -0
- package/dist/services/documents/sync.d.ts +11 -0
- package/dist/services/documents/sync.js +41 -3
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/sqlite/catalog.d.ts +2 -1
- package/dist/store/sqlite/catalog.js +4 -1
- package/dist/store/sqlite/crm-contacts.d.ts +5 -4
- package/dist/store/sqlite/crm-contacts.js +8 -4
- package/dist/store/sqlite/crm-rows.d.ts +1 -0
- package/dist/store/sqlite/crm-rows.js +37 -7
- package/dist/store/sqlite/crm-settings.d.ts +2 -2
- package/dist/store/sqlite/crm-settings.js +4 -3
- package/dist/store/sqlite/crm.d.ts +5 -3
- package/dist/store/sqlite/crm.js +20 -3
- package/dist/store/sqlite/note-search.d.ts +10 -1
- package/dist/store/sqlite/note-search.js +35 -1
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import type { Deadline } from "../../background/budget.js";
|
|
2
3
|
import type { DocumentSource, SourceFile, SourceIndex, SourceSkip, SourceStatePort } from "../../documents/model.js";
|
|
3
4
|
import type { SourceQuery } from "../../documents/scope.js";
|
|
4
5
|
export interface SyncOptions<M extends SourceFile> {
|
|
@@ -10,8 +11,20 @@ export interface SyncOptions<M extends SourceFile> {
|
|
|
10
11
|
query?: SourceQuery<M>;
|
|
11
12
|
textLimit: number;
|
|
12
13
|
max: number;
|
|
14
|
+
/**
|
|
15
|
+
* The entries one call walks, each folder listing counted as one too; the walk saves where it stopped and the next
|
|
16
|
+
* sync goes on from there, so a tree of any size is synced over several calls.
|
|
17
|
+
*/
|
|
13
18
|
maxEntries: number;
|
|
19
|
+
/** @deprecated No longer used: a walk past `maxEntries` stops and goes on in the next sync instead of failing. */
|
|
14
20
|
limitError?(): CliError;
|
|
21
|
+
/** Asked before each folder listing and each file read: a stop ends the call with its work saved. */
|
|
22
|
+
budget?: {
|
|
23
|
+
take(): "requests" | "deadline" | "cancelled" | null;
|
|
24
|
+
readonly stopped?: string | null;
|
|
25
|
+
};
|
|
26
|
+
/** The run's hard limit: the word index at the end of a sync stops before it, less its margin. */
|
|
27
|
+
deadline?: Deadline;
|
|
15
28
|
isFolder(file: M): boolean;
|
|
16
29
|
/**
|
|
17
30
|
* A folder that is a document too, such as a wiki page with sub-pages: walked for its children and imported
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SourceFile } from "../../documents/model.js";
|
|
2
|
+
import { type WalkStop } from "./plan.js";
|
|
2
3
|
import type { SyncOptions } from "./ports.js";
|
|
3
4
|
export interface SyncResult {
|
|
4
5
|
saved: number;
|
|
@@ -19,5 +20,15 @@ export interface SyncResult {
|
|
|
19
20
|
message: string;
|
|
20
21
|
}[];
|
|
21
22
|
coverage: string;
|
|
23
|
+
/** The pass is done: the folder walk finished and no operation is left for another sync. */
|
|
24
|
+
complete: boolean;
|
|
25
|
+
/** Why this call stopped before the pass's end: its entry bound (`maxEntries`) or its request budget. */
|
|
26
|
+
stopped?: WalkStop;
|
|
27
|
+
/** A folder walk still under way; the next sync goes on from where this one stopped. */
|
|
28
|
+
walk?: {
|
|
29
|
+
folders_left: number;
|
|
30
|
+
entries: number;
|
|
31
|
+
listed: number;
|
|
32
|
+
};
|
|
22
33
|
}
|
|
23
34
|
export declare const syncDocuments: <M extends SourceFile>(options: SyncOptions<M>) => Promise<SyncResult>;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
3
|
+
import { deadlineMargin } from "../../background/budget.js";
|
|
3
4
|
import { catalogFiles } from "../../documents/catalog.js";
|
|
4
5
|
import { inScope } from "../../documents/scope.js";
|
|
5
6
|
import { changedSince, planDocuments, scopeHash } from "./plan.js";
|
|
6
7
|
const MAX_PICTURE_BYTES = 25 * 1024 * 1024;
|
|
7
8
|
const SAVE_EVERY_MS = 2000;
|
|
8
9
|
const SAVE_EVERY_ITEMS = 25;
|
|
10
|
+
const SETTLE_MS = 10_000;
|
|
9
11
|
const isPicture = (file) => file.mime.startsWith("image/") && file.canDownload;
|
|
10
12
|
const hashText = (text) => createHash("sha256").update(text).digest("hex");
|
|
11
13
|
export const syncDocuments = async (options) => {
|
|
@@ -25,6 +27,7 @@ export const syncDocuments = async (options) => {
|
|
|
25
27
|
pending: 0,
|
|
26
28
|
skipped: [],
|
|
27
29
|
errors: [],
|
|
30
|
+
complete: true,
|
|
28
31
|
coverage: query?.mode === "include"
|
|
29
32
|
? "selected folders and the files a saved query finds; unsupported files are reported"
|
|
30
33
|
: query?.mode === "exclude"
|
|
@@ -44,18 +47,37 @@ export const syncDocuments = async (options) => {
|
|
|
44
47
|
if (state.principal !== principal)
|
|
45
48
|
throw new CliError("configuration_error", "sync state belongs to another source account");
|
|
46
49
|
const currentScope = scopeHash(profile.roots, query, options.isDocument !== undefined);
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
if (state.pending && (state.pending.scope !== currentScope || rescan)) {
|
|
51
|
+
// Work the new plan cannot see: a file saved to the index before its state was.
|
|
52
|
+
for (const job of state.pending.jobs)
|
|
53
|
+
if (!state.documents[job.id]) {
|
|
54
|
+
await index.remove(profile.principal, job.id);
|
|
55
|
+
statePort.removeSnapshot(job.id);
|
|
56
|
+
}
|
|
49
57
|
delete state.pending;
|
|
58
|
+
// Saved at once: a call the walk cuts short would otherwise find the old batch again and repeat these removals.
|
|
59
|
+
statePort.save(state);
|
|
60
|
+
}
|
|
61
|
+
// A rescan starts the walk over, a saved one included; the cursor is dropped on disk, so the syncs after it
|
|
62
|
+
// continue the walk until it ends.
|
|
50
63
|
if (rescan) {
|
|
51
64
|
delete state.cursor;
|
|
52
65
|
statePort.removeWalk();
|
|
66
|
+
statePort.save(state);
|
|
53
67
|
}
|
|
54
68
|
if (!state.pending) {
|
|
55
|
-
|
|
69
|
+
const plan = await planDocuments(options, source, state, profile.roots, limit, profile.picture_search ?? false, {
|
|
56
70
|
read: (scope) => statePort.readWalk(scope),
|
|
57
71
|
save: (walk) => statePort.saveWalk(walk),
|
|
58
72
|
});
|
|
73
|
+
if ("walk" in plan) {
|
|
74
|
+
result.complete = false;
|
|
75
|
+
result.stopped = plan.walk.stopped;
|
|
76
|
+
result.walk = { folders_left: plan.walk.folders_left, entries: plan.walk.entries, listed: plan.walk.listed };
|
|
77
|
+
result.skipped = state.skipped.map(({ id, reason }) => ({ id, reason }));
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
state.pending = plan.pending;
|
|
59
81
|
state.skipped = state.pending.skipped;
|
|
60
82
|
statePort.save(state);
|
|
61
83
|
statePort.removeWalk();
|
|
@@ -144,6 +166,11 @@ export const syncDocuments = async (options) => {
|
|
|
144
166
|
else {
|
|
145
167
|
if (!source)
|
|
146
168
|
throw new CliError("configuration_error", "a pending save requires source sign-in");
|
|
169
|
+
const stop = options.budget?.take();
|
|
170
|
+
if (stop) {
|
|
171
|
+
result.stopped = stop;
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
147
174
|
const content = await source.content(job.id, limit);
|
|
148
175
|
const listed = query?.mode === "include" && (pending.matched?.includes(job.id) ?? query.matches(content.metadata));
|
|
149
176
|
if (!listed && !inScope(content.metadata, profile.roots, pending.folders, new Set(), query)) {
|
|
@@ -205,6 +232,7 @@ export const syncDocuments = async (options) => {
|
|
|
205
232
|
}
|
|
206
233
|
flush();
|
|
207
234
|
result.pending = pending.jobs.length;
|
|
235
|
+
result.complete = !pending.jobs.length;
|
|
208
236
|
if (!pending.jobs.length) {
|
|
209
237
|
state.cursor = pending.cursor;
|
|
210
238
|
state.scope = pending.scope;
|
|
@@ -217,6 +245,16 @@ export const syncDocuments = async (options) => {
|
|
|
217
245
|
state.lastSync = new Date(now()).toISOString();
|
|
218
246
|
statePort.save(state);
|
|
219
247
|
}
|
|
248
|
+
// A reader that cannot write finds the text by its words only once it is indexed; a search that can write does it
|
|
249
|
+
// itself, so what this bound leaves, or a failure here, is indexed by the next one. Skipped after a stop, and kept
|
|
250
|
+
// inside the run's deadline less its margin, so the partial answer and its next step still reach the caller.
|
|
251
|
+
// Real time: `now` may be fixed.
|
|
252
|
+
const settleFrom = Date.now();
|
|
253
|
+
const settleUntil = Math.min(settleFrom + SETTLE_MS, options.deadline ? options.deadline.endsAt - deadlineMargin(options.deadline) : Number.POSITIVE_INFINITY);
|
|
254
|
+
if (!result.stopped && !options.budget?.stopped && settleUntil > settleFrom)
|
|
255
|
+
await index
|
|
256
|
+
.settle?.({ until: () => signal?.aborted === true || Date.now() >= settleUntil })
|
|
257
|
+
.catch(() => undefined);
|
|
220
258
|
return result;
|
|
221
259
|
}
|
|
222
260
|
finally {
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
|
@@ -30,7 +30,8 @@ export interface CatalogEntry extends CatalogInput {
|
|
|
30
30
|
export declare const CATALOG_QUERY: import("@wirecat/cli-base/query").QueryRegistry;
|
|
31
31
|
export interface CatalogQuery {
|
|
32
32
|
ast?: QueryAst;
|
|
33
|
-
parent
|
|
33
|
+
/** A direct parent's external ID, or several: an entry under any of them. */
|
|
34
|
+
parent?: string | string[];
|
|
34
35
|
kind?: CatalogInput["kind"];
|
|
35
36
|
mime?: string;
|
|
36
37
|
search?: string;
|
|
@@ -205,7 +205,10 @@ export const catalogStoreOver = ({ database, now }) => {
|
|
|
205
205
|
const actorSql = "json_each(d.metadata, '$.catalog.folded.people')";
|
|
206
206
|
const tagSql = "SELECT 1 FROM taggings g JOIN resolved_tags t ON t.id=g.tag_id WHERE g.taggable_type='document' AND g.taggable_id=d.id AND t.name=?";
|
|
207
207
|
const tag = (name) => canonicalTagNamed(database, name)?.name ?? normalizeTag(name);
|
|
208
|
-
|
|
208
|
+
// Several parents in one json_each per entry: an OR of one EXISTS each read the entry's parents once per parent.
|
|
209
|
+
if (Array.isArray(query.parent))
|
|
210
|
+
add("EXISTS(SELECT 1 FROM json_each(d.metadata, '$.catalog.parents') WHERE value IN (SELECT value FROM json_each(?)))", JSON.stringify(query.parent.map((parent) => field(parent))));
|
|
211
|
+
else if (query.parent !== undefined)
|
|
209
212
|
add("EXISTS(SELECT 1 FROM json_each(d.metadata, '$.catalog.parents') WHERE value=?)", query.parent);
|
|
210
213
|
if (query.kind !== undefined)
|
|
211
214
|
add("json_extract(d.metadata, '$.catalog.kind')=?", query.kind);
|
|
@@ -14,10 +14,11 @@ export interface CrmContactsRemoved {
|
|
|
14
14
|
export declare const withoutPlaceholder: (name: string) => string | null;
|
|
15
15
|
/**
|
|
16
16
|
* Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
|
|
17
|
-
* `users` when given) names in a client's role,
|
|
18
|
-
* about, or one anything else points at, stays; so does one
|
|
19
|
-
* its way. A person the removed contacts leave empty is
|
|
20
|
-
* after a contact keep that name without the import's
|
|
17
|
+
* `users` when given) names in a client's role, that is no contact of a kept company, and that the CRM does not
|
|
18
|
+
* assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
|
|
19
|
+
* saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
|
|
20
|
+
* deleted unless anything still points at them. People named after a contact keep that name without the import's
|
|
21
|
+
* `null #<id>`; the owner's person is never renamed.
|
|
21
22
|
*/
|
|
22
23
|
export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
|
|
23
24
|
users?: readonly string[];
|
|
@@ -14,10 +14,11 @@ class DryRun extends Error {
|
|
|
14
14
|
const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
|
|
15
15
|
/**
|
|
16
16
|
* Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
|
|
17
|
-
* `users` when given) names in a client's role,
|
|
18
|
-
* about, or one anything else points at, stays; so does one
|
|
19
|
-
* its way. A person the removed contacts leave empty is
|
|
20
|
-
* after a contact keep that name without the import's
|
|
17
|
+
* `users` when given) names in a client's role, that is no contact of a kept company, and that the CRM does not
|
|
18
|
+
* assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
|
|
19
|
+
* saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
|
|
20
|
+
* deleted unless anything still points at them. People named after a contact keep that name without the import's
|
|
21
|
+
* `null #<id>`; the owner's person is never renamed.
|
|
21
22
|
*/
|
|
22
23
|
export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
|
|
23
24
|
const { database } = context;
|
|
@@ -55,6 +56,9 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
|
|
|
55
56
|
.prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
|
|
56
57
|
`LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
|
|
57
58
|
"AND i.created_at < ? AND i.updated_at < ? " +
|
|
59
|
+
(users === undefined
|
|
60
|
+
? ""
|
|
61
|
+
: "AND coalesce(json_extract(i.metadata, '$.assignee'), '') NOT IN (SELECT id FROM temp.crm_scope) ") +
|
|
58
62
|
`AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
|
|
59
63
|
"AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
|
|
60
64
|
"AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
|
|
@@ -40,5 +40,6 @@ export declare const crmRowsOver: (context: StoreContext) => {
|
|
|
40
40
|
savePipeline: (accountId: number, kind: DealKind, pipeline: CrmPipeline, at: number) => number;
|
|
41
41
|
saveItemRow: (key: AccountKey, accountId: number, kind: DealKind, item: CrmItem, at: number, writer?: ItemWriter) => CrmSkipped | {
|
|
42
42
|
id: number;
|
|
43
|
+
amountNote?: string;
|
|
43
44
|
};
|
|
44
45
|
};
|
|
@@ -1,9 +1,42 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { STAGE_OUTCOMES } from "../../domain/deals.js";
|
|
3
|
-
import { currencyOf, minorUnits } from "../../domain/money.js";
|
|
3
|
+
import { currencyOf, minorUnits, scaleOf } from "../../domain/money.js";
|
|
4
4
|
import { fold } from "../normalize.js";
|
|
5
5
|
import { authorActor } from "./memories.js";
|
|
6
6
|
export const TABLES = { deal: "deals", lead: "leads" };
|
|
7
|
+
const MONEY_REFUSALS = ["money.currency", "money.amount"];
|
|
8
|
+
const amountFault = (item, code) => {
|
|
9
|
+
const text = String(item.amount).trim();
|
|
10
|
+
const decimal = /^\d+(?:\.(\d+))?$/.exec(text);
|
|
11
|
+
if (text.startsWith("-"))
|
|
12
|
+
return "it is below zero";
|
|
13
|
+
if (!decimal)
|
|
14
|
+
return "it is not a decimal number";
|
|
15
|
+
if ((decimal[1] ?? "").length > scaleOf(String(code)))
|
|
16
|
+
return `it has more decimals than ${code} has`;
|
|
17
|
+
return "it is too large to keep exactly";
|
|
18
|
+
};
|
|
19
|
+
/** A deal is never dropped over its money: what the store cannot hold is left out, and the deal says why. */
|
|
20
|
+
const moneyOf = (item) => {
|
|
21
|
+
if (item.amount == null || item.currency == null)
|
|
22
|
+
return { currency: null, amount: null, amountNote: null };
|
|
23
|
+
try {
|
|
24
|
+
const currency = currencyOf(item.currency);
|
|
25
|
+
return { currency, amount: minorUnits(String(item.amount), currency), amountNote: null };
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
const reason = error instanceof CliError ? error.details?.reason : undefined;
|
|
29
|
+
if (!MONEY_REFUSALS.includes(reason))
|
|
30
|
+
throw error;
|
|
31
|
+
const code = textOf(String(item.currency), 10);
|
|
32
|
+
const why = reason === "money.currency" ? `the store keeps no amounts in ${code}` : amountFault(item, code);
|
|
33
|
+
return {
|
|
34
|
+
currency: null,
|
|
35
|
+
amount: null,
|
|
36
|
+
amountNote: `the CRM's amount ${textOf(String(item.amount), 40)} ${code} is not kept: ${why}`,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
};
|
|
7
40
|
/** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
|
|
8
41
|
export const SOURCE = "crm";
|
|
9
42
|
/**
|
|
@@ -123,11 +156,7 @@ export const crmRowsOver = (context) => {
|
|
|
123
156
|
message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
|
|
124
157
|
};
|
|
125
158
|
const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
|
|
126
|
-
const
|
|
127
|
-
const currency = given ? currencyOf(item.currency) : null;
|
|
128
|
-
const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
|
|
129
|
-
if (amount !== null && amount < 0)
|
|
130
|
-
throw new CliError("validation_error", "an amount is 0 or more");
|
|
159
|
+
const { currency, amount, amountNote } = moneyOf(item);
|
|
131
160
|
if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
|
|
132
161
|
throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
|
|
133
162
|
const status = item.status ?? String(stage.outcome);
|
|
@@ -148,6 +177,7 @@ export const crmRowsOver = (context) => {
|
|
|
148
177
|
...(textOf(item.contactName, 200) ? { contact_name: textOf(item.contactName, 200) } : {}),
|
|
149
178
|
...(textOf(item.companyName, 200) ? { company_name: textOf(item.companyName, 200) } : {}),
|
|
150
179
|
...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
|
|
180
|
+
...(amountNote ? { amount_note: { label: "Amount not kept", value: amountNote } } : {}),
|
|
151
181
|
};
|
|
152
182
|
const values = {
|
|
153
183
|
title,
|
|
@@ -191,7 +221,7 @@ export const crmRowsOver = (context) => {
|
|
|
191
221
|
}
|
|
192
222
|
if (writer.project !== undefined)
|
|
193
223
|
database.prepare(`UPDATE ${table} SET project_id = ? WHERE id = ?`).run(writer.project, id);
|
|
194
|
-
return { id };
|
|
224
|
+
return { id, ...(amountNote ? { amountNote } : {}) };
|
|
195
225
|
};
|
|
196
226
|
return { savePipeline, saveItemRow };
|
|
197
227
|
};
|
|
@@ -8,7 +8,7 @@ export type CrmLinkMode = (typeof CRM_LINK_MODES)[number];
|
|
|
8
8
|
/** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
|
|
9
9
|
export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier", "partner-of"];
|
|
10
10
|
export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
|
|
11
|
-
/** `mine`: only the deals and leads of the sign-in's own user
|
|
11
|
+
/** `mine`: only the deals and leads of the `unassigned` users, else of the sign-in's own user; `all`: every one. */
|
|
12
12
|
export declare const CRM_SCOPES: readonly ["mine", "all"];
|
|
13
13
|
/** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
|
|
14
14
|
export declare const CRM_ACTIVITIES: readonly ["on", "off"];
|
|
@@ -28,7 +28,7 @@ export declare const crmActivitiesOn: (database: CacheDatabase, key: AccountKey)
|
|
|
28
28
|
export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
|
|
29
29
|
/** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
|
|
30
30
|
export declare const crmScope: (database: CacheDatabase, key: AccountKey) => CrmScopeSetting;
|
|
31
|
-
/** The users whose deals and leads scope mine keeps, whatever the scope is now:
|
|
31
|
+
/** The users whose deals and leads scope mine keeps, whatever the scope is now: the `unassigned` list, else `self`. */
|
|
32
32
|
export declare const crmScopeUsers: (database: CacheDatabase, key: AccountKey) => string[];
|
|
33
33
|
/**
|
|
34
34
|
* `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
|
|
@@ -4,7 +4,7 @@ import { isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
|
|
|
4
4
|
export const CRM_LINK_MODES = ["reported", "review"];
|
|
5
5
|
/** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
|
|
6
6
|
export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
|
|
7
|
-
/** `mine`: only the deals and leads of the sign-in's own user
|
|
7
|
+
/** `mine`: only the deals and leads of the `unassigned` users, else of the sign-in's own user; `all`: every one. */
|
|
8
8
|
export const CRM_SCOPES = ["mine", "all"];
|
|
9
9
|
/** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
|
|
10
10
|
export const CRM_ACTIVITIES = ["on", "off"];
|
|
@@ -57,10 +57,11 @@ const picked = (name, text, values) => {
|
|
|
57
57
|
throw new CliError("validation_error", `a CRM account's ${name} setting is ${values.join(" or ")}`);
|
|
58
58
|
return text;
|
|
59
59
|
};
|
|
60
|
-
/** The users whose deals and leads scope mine keeps, whatever the scope is now:
|
|
60
|
+
/** The users whose deals and leads scope mine keeps, whatever the scope is now: the `unassigned` list, else `self`. */
|
|
61
61
|
export const crmScopeUsers = (database, key) => {
|
|
62
62
|
const self = crmOwnUser(database, key);
|
|
63
|
-
|
|
63
|
+
const chosen = userIds(stored(database, crmSettingKey(key, "unassigned")));
|
|
64
|
+
return [...new Set(chosen.length ? chosen : self ? [self] : [])];
|
|
64
65
|
};
|
|
65
66
|
/**
|
|
66
67
|
* `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
|
|
@@ -15,7 +15,7 @@ import type { StoreContext } from "./open.js";
|
|
|
15
15
|
export interface CrmRelationIssue {
|
|
16
16
|
/** The CRM row it came from; absent for the account as a whole. */
|
|
17
17
|
externalId?: string;
|
|
18
|
-
reason: "crm.reference-unknown" | "crm.own-unknown" | "crm.email-ambiguous" | "relationship.reference-unknown" | "relationship.invalid";
|
|
18
|
+
reason: "crm.reference-unknown" | "crm.own-unknown" | "crm.email-ambiguous" | "crm.amount-unkept" | "relationship.reference-unknown" | "relationship.invalid";
|
|
19
19
|
message: string;
|
|
20
20
|
}
|
|
21
21
|
export interface CrmSaved {
|
|
@@ -74,10 +74,12 @@ export interface CrmCopies {
|
|
|
74
74
|
/**
|
|
75
75
|
* After a complete list of the kind's ids: marks deleted every stored one the list lacks that the CRM has not
|
|
76
76
|
* changed since `before` (epoch ms), so a row made while the list was read is never taken for a deleted one.
|
|
77
|
-
* `
|
|
77
|
+
* With `users`, only a deal or lead with no assignee or assigned to one of them: a list read under that scope
|
|
78
|
+
* names no other. `dryRun` only counts them.
|
|
78
79
|
*/
|
|
79
80
|
removeUnlisted(key: AccountKey, kind: CrmKind, listed: string[], before: number, options?: {
|
|
80
81
|
dryRun?: boolean;
|
|
82
|
+
users?: readonly string[];
|
|
81
83
|
}): Promise<number>;
|
|
82
84
|
/** Which deals and leads the account's sync copies: its `scope` and `unassigned` settings. */
|
|
83
85
|
scope(key: AccountKey): Promise<CrmScopeSetting>;
|
|
@@ -118,7 +120,7 @@ export interface CrmCopies {
|
|
|
118
120
|
/**
|
|
119
121
|
* Removes the contacts no kept deal, lead or company names, and the people they leave empty; see
|
|
120
122
|
* `removeCrmContacts`. A deal or lead assigned to a user outside `users` counts as gone; without `users`, outside
|
|
121
|
-
* those scope mine keeps (`
|
|
123
|
+
* those scope mine keeps (`unassigned`, else `self`), whatever the scope is now. `dryRun` only counts.
|
|
122
124
|
*/
|
|
123
125
|
removeContacts(key: AccountKey, options: {
|
|
124
126
|
users?: readonly string[];
|
package/dist/store/sqlite/crm.js
CHANGED
|
@@ -283,6 +283,8 @@ export const crmCopiesOver = (context, people) => {
|
|
|
283
283
|
const saved = saveItemRow(key, accountId, kind, item, at);
|
|
284
284
|
if ("reason" in saved)
|
|
285
285
|
return saved;
|
|
286
|
+
if (saved.amountNote)
|
|
287
|
+
report.tally.issues.push({ externalId: item.externalId, reason: "crm.amount-unkept", message: saved.amountNote });
|
|
286
288
|
const { id } = saved;
|
|
287
289
|
if (item.people === undefined && item.assignee === undefined)
|
|
288
290
|
return null;
|
|
@@ -311,6 +313,15 @@ export const crmCopiesOver = (context, people) => {
|
|
|
311
313
|
reportFrom(key, accountId, self, wanted, scope, report.tally, report.pending);
|
|
312
314
|
return null;
|
|
313
315
|
};
|
|
316
|
+
/** Kept in the identity's metadata, as a deal keeps its own, so the contact cleanup under `mine` can read it. */
|
|
317
|
+
const assignContact = (key, externalId, assignee) => {
|
|
318
|
+
const user = assignee ? crmIdentityId(key, normalCrmUserId(assignee), "user") : null;
|
|
319
|
+
database
|
|
320
|
+
.prepare("UPDATE identities SET metadata = CASE WHEN ? IS NULL THEN json_remove(metadata, '$.assignee') " +
|
|
321
|
+
"ELSE json_set(coalesce(metadata, '{}'), '$.assignee', ?) END " +
|
|
322
|
+
"WHERE provider = ? AND external_id = ? AND json_extract(metadata, '$.assignee') IS NOT ?")
|
|
323
|
+
.run(user, user, key.provider, crmIdentityId(key, externalId), user);
|
|
324
|
+
};
|
|
314
325
|
const saveItems = (key, kind, items, users) => write(database, () => {
|
|
315
326
|
const accountId = account(key);
|
|
316
327
|
const at = now();
|
|
@@ -497,7 +508,8 @@ export const crmCopiesOver = (context, people) => {
|
|
|
497
508
|
"AND deleted_at IS NULL")
|
|
498
509
|
.all(accountId)
|
|
499
510
|
: database
|
|
500
|
-
.prepare(`SELECT id, external_id, updated_at FROM ${TABLES[kind]}
|
|
511
|
+
.prepare(`SELECT id, external_id, updated_at, json_extract(metadata, '$.assignee') AS assignee FROM ${TABLES[kind]} ` +
|
|
512
|
+
"WHERE account_id = ? AND deleted_at IS NULL")
|
|
501
513
|
.all(accountId);
|
|
502
514
|
};
|
|
503
515
|
const markDeleted = (key, kind, rows) => {
|
|
@@ -532,6 +544,8 @@ export const crmCopiesOver = (context, people) => {
|
|
|
532
544
|
const tally = tallied();
|
|
533
545
|
const pending = pendingBook(accountId);
|
|
534
546
|
for (const contact of contacts) {
|
|
547
|
+
if (contact.assignee !== undefined)
|
|
548
|
+
assignContact(key, contact.externalId, contact.assignee);
|
|
535
549
|
const person = nameUnnamed(key, contact.externalId, "contact", textOf(contact.name, 200));
|
|
536
550
|
const email = textOf(contact.email, 320)?.toLowerCase();
|
|
537
551
|
const sharing = email ? peopleSharing(key, contact.externalId, email) : 0;
|
|
@@ -584,9 +598,12 @@ export const crmCopiesOver = (context, people) => {
|
|
|
584
598
|
const gone = new Set(externalIds);
|
|
585
599
|
return markDeleted(key, kind, stored(key, kind).filter((row) => gone.has(String(row.external_id))));
|
|
586
600
|
}),
|
|
587
|
-
removeUnlisted: async (key, kind, listed, before, { dryRun } = {}) => write(database, () => {
|
|
601
|
+
removeUnlisted: async (key, kind, listed, before, { dryRun, users } = {}) => write(database, () => {
|
|
588
602
|
const held = new Set(listed);
|
|
589
|
-
const
|
|
603
|
+
const scope = users && new Set(users.map((id) => crmIdentityId(key, id, "user")));
|
|
604
|
+
const gone = stored(key, kind).filter((row) => !held.has(String(row.external_id)) &&
|
|
605
|
+
Number(row.updated_at) < before &&
|
|
606
|
+
(!scope || row.assignee == null || scope.has(String(row.assignee))));
|
|
590
607
|
return dryRun ? gone.length : markDeleted(key, kind, gone);
|
|
591
608
|
}),
|
|
592
609
|
scope: async (key) => crmScope(database, key),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ResolvedNode } from "../../search/lucene/resolved.js";
|
|
2
2
|
import type { Stemmer } from "../../search/stem.js";
|
|
3
|
-
import type
|
|
3
|
+
import { type SqlValue } from "../driver.js";
|
|
4
4
|
import { type DocumentPictureStore } from "./document-pictures.js";
|
|
5
5
|
import { type NoteIndexState } from "./note-index.js";
|
|
6
6
|
import { type Note } from "./notes.js";
|
|
@@ -112,6 +112,15 @@ export interface NoteSearch extends DocumentPictureStore {
|
|
|
112
112
|
hasMore: boolean;
|
|
113
113
|
}>;
|
|
114
114
|
indexState(): Promise<NoteIndexState | undefined>;
|
|
115
|
+
/**
|
|
116
|
+
* Indexes the documents and notes written since the last search, so a reader that cannot write finds them by their
|
|
117
|
+
* words. The queue is the store's own, shared by every tool that writes to it, not only the caller's rows. Works a
|
|
118
|
+
* batch of 50 at a time and yields between batches, so `until` (a deadline, a signal) is asked often; 0 under a
|
|
119
|
+
* read-only store.
|
|
120
|
+
*/
|
|
121
|
+
indexWritten(options?: {
|
|
122
|
+
until?: () => boolean;
|
|
123
|
+
}): Promise<number>;
|
|
115
124
|
/** Live notes' chunks with no vector of `model`, by hash from `after`, each with its text cut again. */
|
|
116
125
|
chunksToEmbed(model: string, options: {
|
|
117
126
|
after?: string;
|
|
@@ -4,13 +4,14 @@ import { fuseRanked } from "../../search/fusion.js";
|
|
|
4
4
|
import { compileAutomaton, foldRegex, wildcardPattern, } from "../../search/lucene/automaton.js";
|
|
5
5
|
import { isStemmed } from "../../search/lucene/resolved.js";
|
|
6
6
|
import { exhausted, outOfTime, QUERY_LIMITS, searchError } from "../../search/lucene/types.js";
|
|
7
|
+
import { isQueryOnly } from "../driver.js";
|
|
7
8
|
import { normalize } from "../normalize.js";
|
|
8
9
|
import { contextDocumentTime } from "./context-document-source.js";
|
|
9
10
|
import { documentPicturesOver } from "./document-pictures.js";
|
|
10
11
|
import { ENRICHMENT_POSITION, enrichmentText } from "./enrichments.js";
|
|
11
12
|
import { linkKind } from "./link-kinds.js";
|
|
12
13
|
import { prefixOf } from "./lucene.js";
|
|
13
|
-
import { drainNoteIndex, noteIndexState, noteIndexText } from "./note-index.js";
|
|
14
|
+
import { drainCorpus, drainNoteIndex, fillTrigrams, CORPORA as INDEXED, noteIndexState, noteIndexText, } from "./note-index.js";
|
|
14
15
|
import { documentOf, noteOf } from "./notes.js";
|
|
15
16
|
import { stemmerCache } from "./stems.js";
|
|
16
17
|
import { canonicalTagNamed } from "./tags.js";
|
|
@@ -336,6 +337,7 @@ export const searchCorpus = (context, query, corpus) => {
|
|
|
336
337
|
});
|
|
337
338
|
};
|
|
338
339
|
const SCAN_PAGE = 5_000;
|
|
340
|
+
const SETTLE_BATCH = 50;
|
|
339
341
|
/** The live documents and notes of a chunk scan, narrowed by folder and source. */
|
|
340
342
|
const LIVE = "((k.chunkable_type = 'document' AND EXISTS (SELECT 1 FROM documents d WHERE d.id = k.chunkable_id AND d.deleted_at IS NULL AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1)=1 " +
|
|
341
343
|
"AND (? IS NULL OR d.account_id IN (SELECT CAST(value AS INTEGER) FROM json_each(?))))) " +
|
|
@@ -367,6 +369,38 @@ export const noteSearchOver = (context) => {
|
|
|
367
369
|
return matchingNoteRefs(context, query);
|
|
368
370
|
},
|
|
369
371
|
indexState: async () => noteIndexState(database),
|
|
372
|
+
indexWritten: async ({ until = () => false } = {}) => {
|
|
373
|
+
if (isQueryOnly(database))
|
|
374
|
+
return 0;
|
|
375
|
+
// One batch per step: a step's own `until` lets it run once, so every corpus moves on each round.
|
|
376
|
+
const once = () => {
|
|
377
|
+
let ran = false;
|
|
378
|
+
return () => {
|
|
379
|
+
const stop = ran;
|
|
380
|
+
ran = true;
|
|
381
|
+
return stop;
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
const steps = [
|
|
385
|
+
() => drainCorpus(database, INDEXED.document, stemmerFor, { batch: SETTLE_BATCH, until: once() }),
|
|
386
|
+
() => drainCorpus(database, INDEXED.note, stemmerFor, { batch: SETTLE_BATCH, until: once() }),
|
|
387
|
+
() => fillTrigrams(database, { batch: SETTLE_BATCH, until: once() }),
|
|
388
|
+
];
|
|
389
|
+
let total = 0;
|
|
390
|
+
for (;;) {
|
|
391
|
+
let done = 0;
|
|
392
|
+
for (const step of steps) {
|
|
393
|
+
if (until())
|
|
394
|
+
return total;
|
|
395
|
+
done += step();
|
|
396
|
+
}
|
|
397
|
+
total += done;
|
|
398
|
+
if (done === 0)
|
|
399
|
+
return total;
|
|
400
|
+
// A synchronous drain would hide an abort or a timer until it ends.
|
|
401
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
402
|
+
}
|
|
403
|
+
},
|
|
370
404
|
chunksToEmbed: async (model, { after, limit }) => {
|
|
371
405
|
drain();
|
|
372
406
|
const scope = live(undefined, undefined);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.670.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|