@wirecat/cli-core 0.640.0 → 0.642.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 +80 -0
- package/dist/analysis/provider.d.ts +1 -1
- package/dist/analysis/provider.js +2 -1
- package/dist/attachments/gateway-ocr.js +13 -8
- package/dist/background/schedules.d.ts +5 -1
- package/dist/background/schedules.js +28 -3
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/ai-model-command.js +6 -3
- package/dist/cli/analysis-choice.js +20 -4
- package/dist/cli/enrichment-consents-command.js +2 -0
- package/dist/cli/local-only-command.d.ts +10 -0
- package/dist/cli/local-only-command.js +103 -0
- package/dist/cli/messenger/backfill-command.js +16 -1
- package/dist/cli/messenger/conversations-command.js +1 -1
- package/dist/cli/messenger/replies-consents-command.js +12 -6
- package/dist/cli/messenger/search-answers.js +2 -0
- package/dist/cli/model-catalogue-command.js +2 -0
- package/dist/cli/search-harder-consents-command.js +16 -1
- package/dist/cli/store-settings.d.ts +4 -1
- package/dist/cli/store-settings.js +26 -9
- package/dist/crm/cli/csv.js +2 -0
- package/dist/crm/cli/index.js +8 -2
- package/dist/crm/cli/search-all.js +4 -4
- package/dist/crm/stage-tasks.d.ts +8 -0
- package/dist/crm/stage-tasks.js +42 -0
- package/dist/documents.d.ts +1 -1
- package/dist/documents.js +1 -1
- package/dist/domain/crm.d.ts +6 -0
- package/dist/embeddings/remote.d.ts +2 -1
- package/dist/embeddings/remote.js +5 -3
- package/dist/entities/deal.d.ts +6 -0
- package/dist/entities/deal.js +3 -0
- package/dist/entities/index.d.ts +4 -0
- package/dist/errors/reasons.js +8 -0
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/models/ai.d.ts +16 -3
- package/dist/models/ai.js +19 -13
- package/dist/models/endpoint.d.ts +5 -0
- package/dist/models/endpoint.js +13 -0
- package/dist/models/index.d.ts +4 -0
- package/dist/models/index.js +9 -1
- package/dist/models/local-only.d.ts +17 -0
- package/dist/models/local-only.js +42 -0
- package/dist/models/purpose.d.ts +24 -0
- package/dist/models/purpose.js +26 -0
- package/dist/replies/rendering.js +10 -10
- package/dist/runs/events.d.ts +9 -1
- package/dist/runs/events.js +5 -1
- package/dist/runs/log-events.js +2 -0
- package/dist/services/deal-context.js +17 -0
- package/dist/services/embeddings-maintenance.js +4 -1
- package/dist/services/enrichment.d.ts +1 -1
- package/dist/services/enrichment.js +27 -0
- package/dist/services/meeting-model.js +1 -1
- package/dist/services/message-resolution.d.ts +1 -1
- package/dist/services/message-resolution.js +2 -2
- package/dist/services/messages-search.js +12 -5
- package/dist/services/search-all.d.ts +10 -3
- package/dist/services/search-all.js +10 -4
- package/dist/services/search-harder.d.ts +11 -1
- package/dist/services/search-harder.js +38 -5
- package/dist/speech/openai.js +2 -0
- package/dist/speech/transcribe.d.ts +5 -2
- package/dist/speech/transcribe.js +14 -5
- package/dist/store/index.d.ts +1 -1
- package/dist/store/sqlite/crm-rows.js +2 -0
- package/dist/store/sqlite/crm-settings.d.ts +26 -1
- package/dist/store/sqlite/crm-settings.js +104 -1
- package/dist/store/sqlite/crm.d.ts +12 -0
- package/dist/store/sqlite/crm.js +4 -1
- package/dist/store/sqlite/deals.d.ts +28 -5
- package/dist/store/sqlite/deals.js +158 -14
- package/dist/store/sqlite/lucene-fields.js +56 -3
- package/dist/store/sqlite/tasks.js +9 -8
- package/dist/tasks/model.d.ts +6 -2
- package/dist/tasks/service.d.ts +2 -0
- package/package.json +1 -1
|
@@ -6,7 +6,7 @@ export const CRM_LINK_MODES = ["reported", "review"];
|
|
|
6
6
|
export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
|
|
7
7
|
/** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
|
|
8
8
|
export const CRM_SCOPES = ["mine", "all"];
|
|
9
|
-
const NAMES = ["links", "company-types", "scope", "unassigned", "self"];
|
|
9
|
+
const NAMES = ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"];
|
|
10
10
|
const SETTING = new RegExp(`^crm\\.([a-z0-9-]+):(.+)\\.(${NAMES.join("|")})$`);
|
|
11
11
|
export const crmSettingKey = (key, name) => `crm.${key.provider}:${key.account}.${name}`;
|
|
12
12
|
/** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
|
|
@@ -67,8 +67,98 @@ export const crmOwnUser = (database, key) => {
|
|
|
67
67
|
const value = stored(database, crmSettingKey(key, "self"));
|
|
68
68
|
return typeof value === "string" && value ? value : undefined;
|
|
69
69
|
};
|
|
70
|
+
const STAGE_TASK_FIELDS = ["title", "due_days"];
|
|
71
|
+
const MAX_DUE_DAYS = 3650;
|
|
72
|
+
const stageTaskRule = (value) => {
|
|
73
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
74
|
+
return undefined;
|
|
75
|
+
const { title, due_days: dueDays } = value;
|
|
76
|
+
if (Object.keys(value).some((field) => !STAGE_TASK_FIELDS.includes(field)))
|
|
77
|
+
return undefined;
|
|
78
|
+
if (typeof title !== "string" || !title.trim() || title.trim().length > 300)
|
|
79
|
+
return undefined;
|
|
80
|
+
if (!Number.isSafeInteger(dueDays) || dueDays < 0 || dueDays > MAX_DUE_DAYS)
|
|
81
|
+
return undefined;
|
|
82
|
+
return { title: title.trim(), dueDays: dueDays };
|
|
83
|
+
};
|
|
84
|
+
/** A bare stage id is a deal's, as most CRMs name deal stages; `lead:<stage>` is a lead's, whose ids may be the same. */
|
|
85
|
+
const stageOf = (stage) => stage.startsWith("lead:") ? ["lead", stage.slice(5)] : ["deal", stage.startsWith("deal:") ? stage.slice(5) : stage];
|
|
86
|
+
/** Only the owner's rules open a task on a stage change; an entry this build cannot read opens none. */
|
|
87
|
+
export const crmStageTasks = (database, key) => {
|
|
88
|
+
const value = stored(database, crmSettingKey(key, "stage-tasks"));
|
|
89
|
+
const rules = { deal: {}, lead: {} };
|
|
90
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
91
|
+
return rules;
|
|
92
|
+
for (const [stage, entry] of Object.entries(value)) {
|
|
93
|
+
const rule = stageTaskRule(entry);
|
|
94
|
+
const [kind, id] = stageOf(stage);
|
|
95
|
+
if (rule && id)
|
|
96
|
+
rules[kind][id] = rule;
|
|
97
|
+
}
|
|
98
|
+
return rules;
|
|
99
|
+
};
|
|
100
|
+
const parseStageTasks = (text) => {
|
|
101
|
+
const refuse = (why) => {
|
|
102
|
+
throw new CliError("validation_error", `stage-tasks takes JSON: {"<stage id>": {"title": "<task title>", "due_days": <days>}}, a lead's stage as ` +
|
|
103
|
+
`"lead:<stage id>": ${why}`);
|
|
104
|
+
};
|
|
105
|
+
let value;
|
|
106
|
+
try {
|
|
107
|
+
value = JSON.parse(text);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return refuse("not JSON");
|
|
111
|
+
}
|
|
112
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
113
|
+
return refuse("not an object");
|
|
114
|
+
const rules = {};
|
|
115
|
+
for (const [stage, entry] of Object.entries(value)) {
|
|
116
|
+
const rule = stageTaskRule(entry);
|
|
117
|
+
if (!stageOf(stage.trim())[1])
|
|
118
|
+
return refuse(`"${stage}" names no stage`);
|
|
119
|
+
if (!rule)
|
|
120
|
+
return refuse(`the rule of "${stage}" needs a title of up to 300 characters and due_days from 0 to ${MAX_DUE_DAYS}, nothing else`);
|
|
121
|
+
rules[stage.trim()] = { title: rule.title, due_days: rule.dueDays };
|
|
122
|
+
}
|
|
123
|
+
return rules;
|
|
124
|
+
};
|
|
125
|
+
/** The last stage change the account's stage tasks have seen; not a setting, so `config` never lists it. */
|
|
126
|
+
const stageTasksMark = (setting) => `${setting}.after`;
|
|
127
|
+
/** After the mark, oldest first: each stage a deal or lead of the account entered from another one, and the newest id read. */
|
|
128
|
+
export const crmStageMoves = (database, key, accountId) => {
|
|
129
|
+
const through = Number(database.prepare("SELECT coalesce(max(id), 0) AS id FROM pipeline_stage_changes").get()?.id);
|
|
130
|
+
const mark = stored(database, stageTasksMark(crmSettingKey(key, "stage-tasks")));
|
|
131
|
+
// With no mark, every move so far happened before the rules: none of them opens a task.
|
|
132
|
+
if (typeof mark !== "number" || accountId === undefined)
|
|
133
|
+
return { moves: [], through };
|
|
134
|
+
const moves = database
|
|
135
|
+
.prepare("SELECT c.id, c.item_type, c.item_id, s.external_id AS stage, s.name AS stage_name, p.name AS pipeline_name " +
|
|
136
|
+
"FROM pipeline_stage_changes c JOIN pipeline_stages s ON s.id = c.to_stage_id " +
|
|
137
|
+
"JOIN pipelines p ON p.id = c.pipeline_id " +
|
|
138
|
+
"LEFT JOIN deals d ON c.item_type = 'deal' AND d.id = c.item_id " +
|
|
139
|
+
"LEFT JOIN leads l ON c.item_type = 'lead' AND l.id = c.item_id " +
|
|
140
|
+
"WHERE c.id > ? AND c.id <= ? AND c.from_stage_id IS NOT NULL AND s.external_id IS NOT NULL " +
|
|
141
|
+
"AND coalesce(d.account_id, l.account_id) = ? AND coalesce(d.deleted_at, l.deleted_at) IS NULL ORDER BY c.id")
|
|
142
|
+
.all(mark, through, accountId)
|
|
143
|
+
.map((row) => ({
|
|
144
|
+
id: Number(row.id),
|
|
145
|
+
kind: row.item_type,
|
|
146
|
+
ref: `${String(row.item_type)}:${String(row.item_id)}`,
|
|
147
|
+
stage: String(row.stage),
|
|
148
|
+
stageName: String(row.stage_name),
|
|
149
|
+
pipelineName: String(row.pipeline_name),
|
|
150
|
+
}));
|
|
151
|
+
return { moves, through };
|
|
152
|
+
};
|
|
153
|
+
export const saveStageMovesMark = (database, key, through, now) => {
|
|
154
|
+
database
|
|
155
|
+
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
156
|
+
.run(stageTasksMark(crmSettingKey(key, "stage-tasks")), JSON.stringify(through), now);
|
|
157
|
+
};
|
|
70
158
|
export const parseCrmSettingValue = (name, value) => {
|
|
71
159
|
const text = value.trim();
|
|
160
|
+
if (name === "stage-tasks")
|
|
161
|
+
return parseStageTasks(text);
|
|
72
162
|
if (name === "links")
|
|
73
163
|
return picked(name, text, CRM_LINK_MODES);
|
|
74
164
|
if (name === "scope")
|
|
@@ -105,6 +195,17 @@ export const saveCrmSetting = (database, setting, value, now) => {
|
|
|
105
195
|
database
|
|
106
196
|
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
107
197
|
.run(setting, JSON.stringify(value), now);
|
|
198
|
+
if (parseCrmSetting(setting)?.name !== "stage-tasks")
|
|
199
|
+
return;
|
|
200
|
+
const mark = stageTasksMark(setting);
|
|
201
|
+
// Rules apply from the moment they are first set: moves made before, however many, open no task.
|
|
202
|
+
if (value === undefined)
|
|
203
|
+
database.prepare("DELETE FROM store_settings WHERE key = ?").run(mark);
|
|
204
|
+
else
|
|
205
|
+
database
|
|
206
|
+
.prepare("INSERT OR IGNORE INTO store_settings (key, value, at) " +
|
|
207
|
+
"SELECT ?, coalesce(max(id), 0), ? FROM pipeline_stage_changes")
|
|
208
|
+
.run(mark, now);
|
|
108
209
|
};
|
|
109
210
|
const settingValue = (database, key, name) => {
|
|
110
211
|
if (name === "links")
|
|
@@ -115,6 +216,8 @@ const settingValue = (database, key, name) => {
|
|
|
115
216
|
return crmScope(database, key).mode;
|
|
116
217
|
if (name === "self")
|
|
117
218
|
return crmOwnUser(database, key) ?? null;
|
|
219
|
+
if (name === "stage-tasks")
|
|
220
|
+
return stored(database, crmSettingKey(key, name)) ?? {};
|
|
118
221
|
return userIds(stored(database, crmSettingKey(key, name)));
|
|
119
222
|
};
|
|
120
223
|
export const crmSettingsOf = (database) => database
|
|
@@ -4,6 +4,7 @@ import type { AccountPeople } from "../people.js";
|
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
5
|
import { type CrmContactsRemoved } from "./crm-contacts.js";
|
|
6
6
|
import { type CrmSkipped } from "./crm-rows.js";
|
|
7
|
+
import { type CrmStageMove, type CrmStageTasks } from "./crm-settings.js";
|
|
7
8
|
import type { StoreContext } from "./open.js";
|
|
8
9
|
/**
|
|
9
10
|
* A relationship the CRM reported that the store did not write: a contact, company or user not synced yet (tried
|
|
@@ -82,6 +83,17 @@ export interface CrmCopies {
|
|
|
82
83
|
/** The CRM user whose copy this is (`self` setting); none before the first sync of a source that names one. */
|
|
83
84
|
ownUser(key: AccountKey): Promise<string | undefined>;
|
|
84
85
|
saveOwnUser(key: AccountKey, userId: string): Promise<void>;
|
|
86
|
+
/** The owner's `stage-tasks` rules, by kind and the CRM's stage id. */
|
|
87
|
+
stageTasks(key: AccountKey): Promise<CrmStageTasks>;
|
|
88
|
+
/**
|
|
89
|
+
* Each stage a deal or lead of the account entered from another one since `markStageMoves` last ran, oldest first;
|
|
90
|
+
* a new row's first stage is no move. `through` is what to mark once they are handled.
|
|
91
|
+
*/
|
|
92
|
+
stageMoves(key: AccountKey): Promise<{
|
|
93
|
+
moves: CrmStageMove[];
|
|
94
|
+
through: number;
|
|
95
|
+
}>;
|
|
96
|
+
markStageMoves(key: AccountKey, through: number): Promise<void>;
|
|
85
97
|
/**
|
|
86
98
|
* Marks deleted every stored deal or lead of the kind assigned to a user outside `userIds`; one with no assignee
|
|
87
99
|
* stays. Reads only the store. Answers how many; `dryRun` only counts them.
|
package/dist/store/sqlite/crm.js
CHANGED
|
@@ -6,7 +6,7 @@ import { accountPk, findAccountPk } from "./accounts.js";
|
|
|
6
6
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
7
7
|
import { removeCrmContacts } from "./crm-contacts.js";
|
|
8
8
|
import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
|
|
9
|
-
import { crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, saveCrmSetting } from "./crm-settings.js";
|
|
9
|
+
import { crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
|
|
10
10
|
import { syncReportedIn } from "./reported-relations.js";
|
|
11
11
|
import { clearState, syncStateOf, writeState } from "./sync.js";
|
|
12
12
|
import { write } from "./transaction.js";
|
|
@@ -588,6 +588,9 @@ export const crmCopiesOver = (context, people) => {
|
|
|
588
588
|
scope: async (key) => crmScope(database, key),
|
|
589
589
|
ownUser: async (key) => crmOwnUser(database, key),
|
|
590
590
|
saveOwnUser: async (key, userId) => saveCrmSetting(database, crmSettingKey(key, "self"), userId, now()),
|
|
591
|
+
stageTasks: async (key) => crmStageTasks(database, key),
|
|
592
|
+
stageMoves: async (key) => crmStageMoves(database, key, findAccountPk(context, key)),
|
|
593
|
+
markStageMoves: async (key, through) => saveStageMovesMark(database, key, through, now()),
|
|
591
594
|
removeOutOfScope: async (key, kind, userIds, { dryRun } = {}) => write(database, () => {
|
|
592
595
|
const keep = new Set(userIds.map((id) => crmIdentityId(key, id, "user")));
|
|
593
596
|
const accountId = findAccountPk(context, key);
|
|
@@ -78,6 +78,9 @@ export interface Deal {
|
|
|
78
78
|
} | null;
|
|
79
79
|
status: DealStatus;
|
|
80
80
|
organization: Party | null;
|
|
81
|
+
/** A CRM copy's own person and company as the CRM keeps them on the item, linked or not; `null` on the owner's own. */
|
|
82
|
+
contactName: string | null;
|
|
83
|
+
companyName: string | null;
|
|
81
84
|
/** Both `null` when no amount is expected yet. */
|
|
82
85
|
currency: string | null;
|
|
83
86
|
amount: string | null;
|
|
@@ -161,10 +164,15 @@ export interface DealFilter {
|
|
|
161
164
|
offset?: number;
|
|
162
165
|
}
|
|
163
166
|
export interface DealSearch {
|
|
164
|
-
/**
|
|
167
|
+
/**
|
|
168
|
+
* Words of the title, the company or a contact's name, e-mail or phone, each in any letter case; a word may be a
|
|
169
|
+
* phrase, whose words must follow each other.
|
|
170
|
+
*/
|
|
165
171
|
words: string[];
|
|
166
|
-
/** A
|
|
172
|
+
/** A row holding any of the words matches, those holding more first; otherwise every word is needed. */
|
|
167
173
|
anyWord?: boolean;
|
|
174
|
+
/** Only whole words as typed: no other form of a word, no word it begins, no spelling correction. */
|
|
175
|
+
exact?: boolean;
|
|
168
176
|
/** Only the copies of these CRM accounts; absent, every account's and the owner's own. */
|
|
169
177
|
accounts?: AccountKey[];
|
|
170
178
|
/** Only these kinds; absent, deals and leads. */
|
|
@@ -172,6 +180,17 @@ export interface DealSearch {
|
|
|
172
180
|
/** 1–500, 100 by default. */
|
|
173
181
|
limit?: number;
|
|
174
182
|
}
|
|
183
|
+
/** Where a deal's or a lead's words are searched: its title, its company, the people on it. */
|
|
184
|
+
export type DealPart = "title" | "company" | "contact";
|
|
185
|
+
export interface FoundDeal extends Deal {
|
|
186
|
+
/** Where the query's words were found, in the order of `DealPart`. */
|
|
187
|
+
matched: DealPart[];
|
|
188
|
+
/** Set when nothing matched as typed: each query word that was corrected, and the stored words it became. */
|
|
189
|
+
corrections?: {
|
|
190
|
+
from: string;
|
|
191
|
+
to: string[];
|
|
192
|
+
}[];
|
|
193
|
+
}
|
|
175
194
|
export interface PipelineInput {
|
|
176
195
|
name: string;
|
|
177
196
|
/** `deal` when left out. */
|
|
@@ -206,8 +225,12 @@ export interface DealsStore {
|
|
|
206
225
|
/** Every stage it entered, in the order it entered them: a CRM's own stamps may run out of order. */
|
|
207
226
|
stages(reference: string): Promise<StageChange[]>;
|
|
208
227
|
list(filter?: DealFilter): Promise<Deal[]>;
|
|
209
|
-
/**
|
|
210
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Deals and leads together, by the words of their title, company and contacts: a query word matches a stored word
|
|
230
|
+
* it begins or one of the same stem. The most words matched first, then the latest changed. When nothing matches,
|
|
231
|
+
* a misspelt word is corrected to the stored words nearest to it, once.
|
|
232
|
+
*/
|
|
233
|
+
find(search: DealSearch): Promise<FoundDeal[]>;
|
|
211
234
|
/**
|
|
212
235
|
* The project it belongs to; `null` clears it. A CRM copy takes it too: the project is the store's own field, which
|
|
213
236
|
* a CRM has none of and its sync never writes.
|
|
@@ -244,7 +267,7 @@ export declare const dealOperationsOver: (context: StoreContext) => {
|
|
|
244
267
|
get: (reference: string) => Deal;
|
|
245
268
|
stages: (reference: string) => StageChange[];
|
|
246
269
|
list: (filter?: DealFilter) => Deal[];
|
|
247
|
-
find: ({ words, anyWord, accounts, kinds, limit }: DealSearch) =>
|
|
270
|
+
find: ({ words, anyWord, exact, accounts, kinds, limit }: DealSearch) => Promise<FoundDeal[]>;
|
|
248
271
|
setProject: (reference: string, { project, by }: {
|
|
249
272
|
project: string | null;
|
|
250
273
|
by: Author;
|
|
@@ -2,9 +2,12 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
import { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, dealLine, STAGE_OUTCOMES, } from "../../domain/deals.js";
|
|
3
3
|
import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
|
|
4
4
|
import { notOverriddenSql } from "../../domain/relations.js";
|
|
5
|
+
import { correctWords } from "../../search/correct.js";
|
|
6
|
+
import { createStemmer, DEFAULT_STEMMERS } from "../../search/stem.js";
|
|
5
7
|
import { fold } from "../normalize.js";
|
|
6
8
|
import { proposedBySql } from "./actors.js";
|
|
7
9
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
10
|
+
import { crmAccountPrefix } from "./crm-rows.js";
|
|
8
11
|
import { linkKind } from "./link-kinds.js";
|
|
9
12
|
import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
|
|
10
13
|
import { requiredThing } from "./notes.js";
|
|
@@ -44,6 +47,41 @@ const providerMetadataOf = (metadata) => {
|
|
|
44
47
|
}
|
|
45
48
|
};
|
|
46
49
|
const accountOf = (provider, external) => provider == null ? null : { provider: String(provider), account: String(external) };
|
|
50
|
+
const DEAL_PARTS = ["title", "company", "contact"];
|
|
51
|
+
const TOKEN = /[\p{L}\p{N}\p{M}]+/gu;
|
|
52
|
+
/** A query word shorter than this matches only a whole word: «с» or "a" begins half the words of any title. */
|
|
53
|
+
const SHORTEST_BEGINNING = 4;
|
|
54
|
+
const stemmer = createStemmer(DEFAULT_STEMMERS, { cacheLimit: 20_000 });
|
|
55
|
+
const stemsOf = (token) => stemmer.stemSequences(token).flat();
|
|
56
|
+
const probeOf = (token) => ({ literal: fold(token), stems: stemsOf(token) });
|
|
57
|
+
const tokensOf = (text) => text.normalize("NFC").toLowerCase().match(TOKEN) ?? [];
|
|
58
|
+
const wordMatches = (probe, word, exact) => {
|
|
59
|
+
if (word.literal === probe.literal)
|
|
60
|
+
return true;
|
|
61
|
+
if (exact)
|
|
62
|
+
return false;
|
|
63
|
+
if (probe.literal.length >= SHORTEST_BEGINNING && word.literal.startsWith(probe.literal))
|
|
64
|
+
return true;
|
|
65
|
+
// A stem begins its word, so a word that does not start like the stem needs no stemming.
|
|
66
|
+
return (probe.stems.some((stem) => word.literal.startsWith(stem.slice(0, 3))) &&
|
|
67
|
+
stemsOf(word.token).some((stem) => probe.stems.includes(stem)));
|
|
68
|
+
};
|
|
69
|
+
/** A clause of several words, `КТП-630` or an e-mail, matches only where they follow each other. */
|
|
70
|
+
const clauseIn = (clause, words, exact) => words.some((_, at) => clause.every((alternatives, offset) => {
|
|
71
|
+
const word = words[at + offset];
|
|
72
|
+
return word !== undefined && alternatives.some((probe) => wordMatches(probe, word, exact));
|
|
73
|
+
}));
|
|
74
|
+
const listOf = (json) => {
|
|
75
|
+
if (typeof json !== "string")
|
|
76
|
+
return [];
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(json);
|
|
79
|
+
return Array.isArray(parsed) ? parsed.map(String) : [];
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
};
|
|
47
85
|
export const dealOperationsOver = (context) => {
|
|
48
86
|
const { database, now } = context;
|
|
49
87
|
const { partyOf, partyThing } = reviewedRowsOver(context);
|
|
@@ -78,6 +116,8 @@ export const dealOperationsOver = (context) => {
|
|
|
78
116
|
: { ref: `stage:${row.base_stage_ref_id}`, name: String(row.base_stage_name) },
|
|
79
117
|
status: fields.status,
|
|
80
118
|
organization: partyOf(row.organization_id == null ? null : "organization", row.organization_id),
|
|
119
|
+
contactName: jsonField(row.metadata, "contact_name"),
|
|
120
|
+
companyName: jsonField(row.metadata, "company_name"),
|
|
81
121
|
currency,
|
|
82
122
|
amount: amount === null || currency === null ? null : formatDecimal(amount, scaleOf(currency)),
|
|
83
123
|
closeDate: row.close_date == null ? null : String(row.close_date),
|
|
@@ -395,29 +435,133 @@ export const dealOperationsOver = (context) => {
|
|
|
395
435
|
.all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit, Math.max(0, Math.trunc(filter.offset ?? 0)))
|
|
396
436
|
.map(itemOf(kind));
|
|
397
437
|
},
|
|
398
|
-
find: ({ words, anyWord, accounts, kinds = DEAL_KINDS, limit }) => {
|
|
399
|
-
const
|
|
400
|
-
|
|
438
|
+
find: async ({ words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit }) => {
|
|
439
|
+
const seen = new Set();
|
|
440
|
+
const clauses = words
|
|
441
|
+
.map((word) => tokensOf(word).filter((token) => fold(token)))
|
|
442
|
+
.filter((tokens) => {
|
|
443
|
+
const key = tokens.map(fold).join(" ");
|
|
444
|
+
if (!tokens.length || seen.has(key))
|
|
445
|
+
return false;
|
|
446
|
+
seen.add(key);
|
|
447
|
+
return true;
|
|
448
|
+
});
|
|
449
|
+
if (!clauses.length)
|
|
401
450
|
return [];
|
|
402
451
|
const most = Math.min(Math.max(limit ?? 100, 1), 500);
|
|
403
452
|
const within = accounts?.map(({ provider, account }) => `${provider}\u0000${account}`);
|
|
404
|
-
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
453
|
+
const stored = new Map();
|
|
454
|
+
const wordsOf = (text) => tokensOf(text).flatMap((token) => {
|
|
455
|
+
let word = stored.get(token);
|
|
456
|
+
if (word === undefined) {
|
|
457
|
+
word = { token, literal: fold(token) };
|
|
458
|
+
stored.set(token, word);
|
|
459
|
+
}
|
|
460
|
+
return word.literal ? [word] : [];
|
|
461
|
+
});
|
|
462
|
+
// A CRM holds thousands of rows, not millions: reading their words here is cheaper than an index kept in step.
|
|
463
|
+
const records = kinds.flatMap((kind) => {
|
|
464
|
+
const contacts = new Map();
|
|
465
|
+
// `+` keeps SQLite off the index by `to_type`: a store holds far more links to people than links from deals.
|
|
466
|
+
for (const row of database
|
|
467
|
+
.prepare("SELECT k.from_id, a.provider AS account_provider, a.external_id AS account, p.name, i.provider, " +
|
|
468
|
+
"i.external_id, i.name AS identity, i.email, i.phone, " +
|
|
469
|
+
"CASE WHEN json_valid(i.metadata) THEN json_extract(i.metadata, '$.emails') END AS emails, " +
|
|
470
|
+
"CASE WHEN json_valid(i.metadata) THEN json_extract(i.metadata, '$.phones') END AS phones " +
|
|
471
|
+
`FROM links k JOIN ${TABLES[kind]} d ON d.id = k.from_id JOIN persons p ON p.id = k.to_id ` +
|
|
472
|
+
"LEFT JOIN accounts a ON a.id = d.account_id LEFT JOIN identity_links l ON l.person_id = p.id " +
|
|
473
|
+
"LEFT JOIN identities i ON i.id = l.identity_id " +
|
|
474
|
+
`WHERE k.from_type = ? AND d.deleted_at IS NULL AND k.kind = ${linkKind("related-to")} ` +
|
|
475
|
+
"AND +k.to_type = 'person' AND k.deleted_at IS NULL AND k.role IS NOT 'owner' " +
|
|
476
|
+
`AND ${notOverriddenSql("k")}`)
|
|
477
|
+
.all(kind)) {
|
|
478
|
+
const texts = contacts.get(Number(row.from_id)) ?? new Set();
|
|
479
|
+
contacts.set(Number(row.from_id), texts);
|
|
480
|
+
if (typeof row.name === "string" && row.name)
|
|
481
|
+
texts.add(row.name);
|
|
482
|
+
// A CRM copy is found only by what its CRM holds: a locked profile never learns a person's other accounts.
|
|
483
|
+
const own = row.account_provider == null ||
|
|
484
|
+
(row.provider === row.account_provider &&
|
|
485
|
+
String(row.external_id).startsWith(crmAccountPrefix({ provider: String(row.account_provider), account: String(row.account) })));
|
|
486
|
+
if (!own)
|
|
487
|
+
continue;
|
|
488
|
+
const phones = [row.phone, ...listOf(row.phones)].filter((one) => typeof one === "string");
|
|
489
|
+
for (const text of [row.identity, row.email, ...listOf(row.emails), ...phones])
|
|
490
|
+
if (typeof text === "string" && text)
|
|
491
|
+
texts.add(text);
|
|
492
|
+
// `+7 916 123-45-67` is one number to whoever types `79161234567`.
|
|
493
|
+
for (const phone of phones)
|
|
494
|
+
texts.add(phone.replace(/\D/g, ""));
|
|
495
|
+
}
|
|
496
|
+
return database
|
|
497
|
+
.prepare(`SELECT d.id, d.title, d.updated_at, a.provider, a.external_id AS account, o.name AS company, ` +
|
|
498
|
+
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.company_name') END AS own_company, " +
|
|
499
|
+
"CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact " +
|
|
500
|
+
`FROM ${TABLES[kind]} d LEFT JOIN accounts a ON a.id = d.account_id ` +
|
|
501
|
+
"LEFT JOIN organizations o ON o.id = d.organization_id WHERE d.deleted_at IS NULL")
|
|
502
|
+
.all()
|
|
503
|
+
.filter((row) => within === undefined || within.includes(`${row.provider}\u0000${row.account}`))
|
|
504
|
+
.map((row) => ({
|
|
505
|
+
kind,
|
|
506
|
+
row,
|
|
507
|
+
parts: [
|
|
508
|
+
{ part: "title", words: wordsOf(String(row.title)) },
|
|
509
|
+
...[row.company, row.own_company]
|
|
510
|
+
.filter((text) => typeof text === "string")
|
|
511
|
+
.map((text) => ({ part: "company", words: wordsOf(text) })),
|
|
512
|
+
...[row.own_contact, ...(contacts.get(Number(row.id)) ?? [])]
|
|
513
|
+
.filter((text) => typeof text === "string")
|
|
514
|
+
.map((text) => ({ part: "contact", words: wordsOf(text) })),
|
|
515
|
+
],
|
|
516
|
+
}));
|
|
517
|
+
});
|
|
518
|
+
const search = (query) => records
|
|
519
|
+
.map((record) => {
|
|
520
|
+
const matched = new Set();
|
|
521
|
+
const score = query.filter((clause) => {
|
|
522
|
+
const where = record.parts.filter(({ words: held }) => clauseIn(clause, held, exact));
|
|
523
|
+
for (const { part } of where)
|
|
524
|
+
matched.add(part);
|
|
525
|
+
return where.length > 0;
|
|
526
|
+
}).length;
|
|
527
|
+
return { ...record, score, matched: DEAL_PARTS.filter((part) => matched.has(part)) };
|
|
413
528
|
})
|
|
414
|
-
.filter(({ score }) => (anyWord ? score > 0 : score ===
|
|
529
|
+
.filter(({ score }) => (anyWord ? score > 0 : score === query.length));
|
|
530
|
+
const probes = clauses.map((clause) => clause.map(probeOf));
|
|
531
|
+
const queryWith = (fixes) => probes.map((clause) => clause.map((probe) => [probe, ...(fixes.get(probe.literal) ?? []).map(probeOf)]));
|
|
532
|
+
let found = search(queryWith(new Map()));
|
|
533
|
+
let corrections;
|
|
534
|
+
if (!found.length && !exact) {
|
|
535
|
+
const docs = new Map();
|
|
536
|
+
for (const { parts } of records)
|
|
537
|
+
for (const literal of new Set(parts.flatMap(({ words: held }) => held.map((word) => word.literal))))
|
|
538
|
+
docs.set(literal, (docs.get(literal) ?? 0) + 1);
|
|
539
|
+
const vocabulary = {
|
|
540
|
+
knownTerms: async (terms) => new Set(terms.filter((term) => docs.has(term))),
|
|
541
|
+
termCandidates: async (_, { shortest, longest }) => [...docs]
|
|
542
|
+
.filter(([term]) => term.length >= shortest && term.length <= longest)
|
|
543
|
+
.map(([term, count]) => ({ term, docs: count })),
|
|
544
|
+
};
|
|
545
|
+
const unmatched = probes
|
|
546
|
+
.flat()
|
|
547
|
+
.filter((probe) => ![...stored.values()].some((word) => wordMatches(probe, word, false)))
|
|
548
|
+
.map(({ literal }) => literal);
|
|
549
|
+
const fixes = unmatched.length ? await correctWords(vocabulary, [...new Set(unmatched)]) : new Map();
|
|
550
|
+
if (fixes.size) {
|
|
551
|
+
corrections = [...fixes].map(([from, to]) => ({ from, to }));
|
|
552
|
+
found = search(queryWith(fixes));
|
|
553
|
+
}
|
|
554
|
+
}
|
|
415
555
|
return found
|
|
416
556
|
.sort((a, b) => b.score - a.score ||
|
|
417
557
|
Number(b.row.updated_at) - Number(a.row.updated_at) ||
|
|
418
558
|
Number(b.row.id) - Number(a.row.id))
|
|
419
559
|
.slice(0, most)
|
|
420
|
-
.map(({ kind, row }) =>
|
|
560
|
+
.map(({ kind, row, matched }) => ({
|
|
561
|
+
...read(`${kind}:${row.id}`),
|
|
562
|
+
matched,
|
|
563
|
+
...(corrections ? { corrections } : {}),
|
|
564
|
+
}));
|
|
421
565
|
},
|
|
422
566
|
setProject: (reference, { project, by }) => {
|
|
423
567
|
authorActor(context, by);
|
|
@@ -61,12 +61,14 @@ export const wordMatch = (corpus, match) => ({
|
|
|
61
61
|
fts: match,
|
|
62
62
|
});
|
|
63
63
|
// The vocabulary is the whole store's, so a chat or date filter does not shorten it.
|
|
64
|
-
const tooManyWords = ({ field, operator, value, span }, alone, prefix) => {
|
|
64
|
+
const tooManyWords = ({ field, operator, value, span }, alone, prefix, mail) => {
|
|
65
65
|
const term = `${field}:${operator === "regex" ? `/${value}/` : value}`;
|
|
66
66
|
const spelled = operator === "wildcard" ? value.replace(/[*?]+/gu, " ").trim().split(/\s+/u)[0] : "";
|
|
67
67
|
// Measured on a synthetic 1M-word vocabulary: reading every word takes 1-2 s, the whole search's time.
|
|
68
68
|
const instead = !prefix && spelled
|
|
69
|
-
?
|
|
69
|
+
? mail
|
|
70
|
+
? `a pattern that starts with * reads every indexed word — write the start of the word: ${spelled}* (it also finds the word's other forms)`
|
|
71
|
+
: `a pattern without three letters in a row reads every indexed word — write three or more between the stars, or the start of the word: ${spelled}*`
|
|
70
72
|
: "use a longer prefix, or body:/…/ inside one chat";
|
|
71
73
|
throw new CliError("validation_error", `search: ${term}${alone ? " matches" : " and the patterns before it match"} more than ${QUERY_LIMITS.expansions} indexed words, the term expansions budget — ${instead}`, {
|
|
72
74
|
reason: "query.too-large",
|
|
@@ -164,6 +166,52 @@ const stemmedText = (node, scope) => {
|
|
|
164
166
|
})
|
|
165
167
|
: bound("0"));
|
|
166
168
|
};
|
|
169
|
+
/** A wildcard value's literal parts, split at its unescaped `*` and `?`. */
|
|
170
|
+
const literalRuns = (value) => {
|
|
171
|
+
const runs = [""];
|
|
172
|
+
const chars = [...value];
|
|
173
|
+
for (let at = 0; at < chars.length; at++) {
|
|
174
|
+
const c = chars[at];
|
|
175
|
+
if (c === "\\")
|
|
176
|
+
runs[runs.length - 1] += chars[++at] ?? "";
|
|
177
|
+
else if (c === "*" || c === "?")
|
|
178
|
+
runs.push("");
|
|
179
|
+
else
|
|
180
|
+
runs[runs.length - 1] += c;
|
|
181
|
+
}
|
|
182
|
+
return runs.filter(Boolean);
|
|
183
|
+
};
|
|
184
|
+
const MOST_YO_SPELLINGS = 64;
|
|
185
|
+
/** Every spelling of `run` with each е or ё as either: the trigram index keeps the text as written. */
|
|
186
|
+
const yoSpellings = (run) => {
|
|
187
|
+
let spellings = [""];
|
|
188
|
+
for (const c of run) {
|
|
189
|
+
spellings = spellings.flatMap((start) => (c === "е" || c === "ё" ? [`${start}е`, `${start}ё`] : [`${start}${c}`]));
|
|
190
|
+
if (spellings.length > MOST_YO_SPELLINGS)
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
return spellings;
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* A pattern with no start to read the word list from (`*договор*`, `*ость`), in chat messages: the trigram index of
|
|
197
|
+
* their text finds where its longest part occurs, so a large store does not refuse it: the whole search took 0.5–1 s at
|
|
198
|
+
* 1M messages (cli-testing performance/search/infix-chat-text). `*part*` is answered by the index alone; any other shape is
|
|
199
|
+
* checked word by word. It folds case, not accents: the part matches as typed, ё and е either way.
|
|
200
|
+
*/
|
|
201
|
+
const insideWords = (node, automaton, scope) => {
|
|
202
|
+
const typed = node.value.normalize("NFC").toLowerCase();
|
|
203
|
+
const [longest = ""] = literalRuns(typed).sort((a, b) => [...b].length - [...a].length);
|
|
204
|
+
const spellings = [...longest].length >= 3 ? yoSpellings(longest) : undefined;
|
|
205
|
+
if (!spellings)
|
|
206
|
+
return undefined;
|
|
207
|
+
const fragment = bound("m.id IN (SELECT rowid FROM messages_fts WHERE messages_fts MATCH ?)", spellings.map(quoted).join(" OR "));
|
|
208
|
+
if (/^\*+[\p{L}\p{N}]+\*+$/u.test(typed))
|
|
209
|
+
return always(fragment);
|
|
210
|
+
return {
|
|
211
|
+
fragment: { ...fragment, exact: false },
|
|
212
|
+
test: (text) => (normalize(text).match(/[\p{L}\p{N}]+/gu) ?? []).some((word) => automaton.test(word, scope.budget)),
|
|
213
|
+
};
|
|
214
|
+
};
|
|
167
215
|
const words = (node, scope) => {
|
|
168
216
|
const { operator, value } = node;
|
|
169
217
|
const { corpus } = scope;
|
|
@@ -187,11 +235,16 @@ const words = (node, scope) => {
|
|
|
187
235
|
if (cached)
|
|
188
236
|
return { node, fragment: widened(cached) };
|
|
189
237
|
const prefix = prefixOf(pattern);
|
|
238
|
+
if (!scope.mail && operator === "wildcard" && [...prefix].length < 3) {
|
|
239
|
+
const inside = insideWords(node, automaton, scope);
|
|
240
|
+
if (inside)
|
|
241
|
+
return inside;
|
|
242
|
+
}
|
|
190
243
|
const terms = scope.database
|
|
191
244
|
.prepare(`SELECT term FROM ${corpus.vocab} WHERE col='normalized_text'${prefix ? " AND term>=? AND term<=?" : ""} ORDER BY term LIMIT ?`)
|
|
192
245
|
.all(...(prefix ? [prefix, `${prefix}\u{10ffff}`] : []), QUERY_LIMITS.expansions + 1);
|
|
193
246
|
if (scope.expand(terms.length) > QUERY_LIMITS.expansions)
|
|
194
|
-
tooManyWords(node, terms.length > QUERY_LIMITS.expansions, prefix);
|
|
247
|
+
tooManyWords(node, terms.length > QUERY_LIMITS.expansions, prefix, scope.mail);
|
|
195
248
|
const matches = terms.flatMap(({ term }) => {
|
|
196
249
|
scope.check();
|
|
197
250
|
return automaton.test(String(term), scope.budget) ? [quoted(String(term))] : [];
|
|
@@ -178,17 +178,18 @@ export const taskStoreOver = (context) => {
|
|
|
178
178
|
const key = typedKey(database, task.kind);
|
|
179
179
|
const author = actorOfOrigin(database, task.origin);
|
|
180
180
|
const closedBy = task.closedBy ? actorOfOrigin(database, task.closedBy) : undefined;
|
|
181
|
-
const title =
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
181
|
+
const title = task.title ??
|
|
182
|
+
displayTitleOf(database, {
|
|
183
|
+
type: task.kind,
|
|
184
|
+
title: `${task.kind} — ${task.source}`,
|
|
185
|
+
source_locator: task.source,
|
|
186
|
+
});
|
|
186
187
|
const made = database
|
|
187
188
|
.prepare("INSERT INTO tasks (project_id, number, key, title, type, status, due_at, closed_at, closed_by_type, closed_by_id, " +
|
|
188
189
|
"close_reason, author_type, author_id, source, package_id, source_locator, source_kind, source_group, created_at, updated_at, " +
|
|
189
|
-
"title_folded, close_reason_folded, category) " +
|
|
190
|
-
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
191
|
-
.get(project, number, key, title, task.kind, task.state, time(task.dueAt), time(task.closedAt), closedBy?.type ?? null, closedBy?.id ?? null, task.reason ?? null, author.type, author.id, task.origin, task.id, task.source, task.sourceKind, task.group, task.createdAt.getTime(), now(), folded(title), folded(task.reason), task.category ?? null);
|
|
190
|
+
"title_folded, close_reason_folded, category, description) " +
|
|
191
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
192
|
+
.get(project, number, key, title, task.kind, task.state, time(task.dueAt), time(task.closedAt), closedBy?.type ?? null, closedBy?.id ?? null, task.reason ?? null, author.type, author.id, task.origin, task.id, task.source, task.sourceKind, task.group, task.createdAt.getTime(), now(), folded(title), folded(task.reason), task.category ?? null, task.description ?? null);
|
|
192
193
|
recordTaskEvent(database, Number(made?.id), author, "created", null, task.createdAt.getTime());
|
|
193
194
|
});
|
|
194
195
|
},
|
package/dist/tasks/model.d.ts
CHANGED
|
@@ -11,8 +11,9 @@ export type TaskVerdict = (typeof TASK_VERDICTS)[number];
|
|
|
11
11
|
export type ClosedState = (typeof CLOSED_STATES)[number];
|
|
12
12
|
export declare const isClosedState: (state: string) => state is ClosedState;
|
|
13
13
|
/**
|
|
14
|
-
* A task points at what it is about and never
|
|
15
|
-
*
|
|
14
|
+
* A task points at what it is about and never copies its source's text: `source` is a locator the host resolves
|
|
15
|
+
* (`msg:…` for a message), so a deleted message leaves nothing behind here. Only a rule that wrote its own `title` and
|
|
16
|
+
* `description`, such as an owner's stage rule naming a deal, stores text with it.
|
|
16
17
|
*/
|
|
17
18
|
export interface Task {
|
|
18
19
|
id: string;
|
|
@@ -32,6 +33,9 @@ export interface Task {
|
|
|
32
33
|
key?: string;
|
|
33
34
|
/** One name from the host's category list; a host without one leaves it unset. */
|
|
34
35
|
category?: string;
|
|
36
|
+
/** Given by a rule that knows what to do, such as an owner's stage rule; a found task's comes from its source. */
|
|
37
|
+
title?: string;
|
|
38
|
+
description?: string;
|
|
35
39
|
/** Who works on it now, until `claimedUntil`; a lapsed claim holds nothing. */
|
|
36
40
|
claimedBy?: string;
|
|
37
41
|
claimedUntil?: Date;
|
package/dist/tasks/service.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.642.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",
|