@wirecat/cli-core 0.639.0 → 0.641.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 +83 -0
- package/dist/cli/messenger/backfill-command.js +16 -1
- package/dist/cli/messenger/search-answers.js +2 -0
- 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/domain/crm.d.ts +9 -0
- package/dist/domain/name-variants.d.ts +2 -0
- package/dist/domain/name-variants.js +107 -0
- package/dist/domain/person-kinds.d.ts +6 -3
- package/dist/domain/person-kinds.js +5 -2
- package/dist/entities/contact-activity.d.ts +3 -0
- package/dist/entities/contact-activity.js +3 -0
- package/dist/entities/contact-context.d.ts +6 -0
- package/dist/entities/deal.d.ts +6 -0
- package/dist/entities/deal.js +3 -0
- package/dist/entities/index.d.ts +10 -0
- package/dist/errors/reasons.js +2 -1
- package/dist/resolve.d.ts +8 -0
- package/dist/resolve.js +48 -6
- 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/search/lucene/registry.js +17 -15
- package/dist/services/deal-context.js +17 -0
- package/dist/services/message-resolution.d.ts +13 -1
- package/dist/services/message-resolution.js +44 -3
- package/dist/services/messages-search.js +41 -20
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-all.d.ts +10 -3
- package/dist/services/search-all.js +10 -4
- package/dist/store/index.d.ts +2 -2
- package/dist/store/people.d.ts +10 -3
- package/dist/store/people.js +2 -1
- package/dist/store/sqlite/accounts.js +2 -0
- 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 +9 -1
- package/dist/store/sqlite/deals.d.ts +28 -5
- package/dist/store/sqlite/deals.js +158 -14
- package/dist/store/sqlite/hit-places.js +19 -6
- package/dist/store/sqlite/identities.js +21 -1
- package/dist/store/sqlite/lucene-fields.d.ts +2 -1
- package/dist/store/sqlite/lucene-fields.js +129 -16
- package/dist/store/sqlite/lucene.js +8 -8
- package/dist/store/sqlite/note-search.js +9 -0
- package/dist/store/sqlite/people-list.js +14 -8
- package/dist/store/sqlite/person-doubts.d.ts +13 -3
- package/dist/store/sqlite/person-doubts.js +92 -48
- package/dist/store/sqlite/person-links.js +15 -2
- package/dist/store/sqlite/tasks.js +9 -8
- package/dist/store/sqlite/test-people.d.ts +24 -0
- package/dist/store/sqlite/test-people.js +92 -0
- package/dist/store/types.d.ts +6 -0
- package/dist/tasks/model.d.ts +6 -2
- package/dist/tasks/service.d.ts +2 -0
- package/docs/search/recipes.json +3 -0
- package/package.json +1 -1
package/dist/store/index.d.ts
CHANGED
|
@@ -50,7 +50,7 @@ export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogSto
|
|
|
50
50
|
export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
51
51
|
export type { ChatMetadata } from "./sqlite/chats.js";
|
|
52
52
|
export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
|
|
53
|
-
export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
|
|
53
|
+
export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
|
|
54
54
|
export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
|
|
55
55
|
export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
|
|
56
56
|
export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
|
|
@@ -80,7 +80,7 @@ export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from ".
|
|
|
80
80
|
export type { OrganizationFilter } from "./sqlite/organization-categories.js";
|
|
81
81
|
export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
|
|
82
82
|
export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
|
|
83
|
-
export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, } from "./sqlite/person-doubts.js";
|
|
83
|
+
export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
|
|
84
84
|
export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
|
|
85
85
|
export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
|
|
86
86
|
export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
|
package/dist/store/people.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { IdentitySplitDecision, IdentitySplitFilter, IdentitySplitInput, Id
|
|
|
7
7
|
import type { ContactFilter } from "./sqlite/identities.js";
|
|
8
8
|
import type { StoreContext } from "./sqlite/open.js";
|
|
9
9
|
import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
|
|
10
|
-
import { type KeptPerson, type PersonDoubts } from "./sqlite/person-doubts.js";
|
|
10
|
+
import { type KeptPerson, type PersonDoubts, type TestDataPerson } from "./sqlite/person-doubts.js";
|
|
11
11
|
import type { PersonMerge } from "./sqlite/person-merges.js";
|
|
12
12
|
import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
|
|
13
13
|
import { type ShownBecause } from "./sqlite/person-ties.js";
|
|
@@ -130,9 +130,15 @@ export interface PeopleStore extends AccountPeople {
|
|
|
130
130
|
}): Promise<PersonDoubts>;
|
|
131
131
|
/**
|
|
132
132
|
* The owner says a person in doubt is right as they are: the identities in doubt stop being listed until one of them
|
|
133
|
-
* moves
|
|
133
|
+
* moves, and what looked like test data is a real contact, shown again even when memo hid it. The owner's alone;
|
|
134
|
+
* refused with `person.no-doubt` when nothing about the person is in doubt or hidden.
|
|
134
135
|
*/
|
|
135
136
|
keep(person: string, by: Decider): Promise<KeptPerson>;
|
|
137
|
+
/**
|
|
138
|
+
* The owner says a person is test data: hidden from every list, `list({ kind: "test" })` lists them, until `keep`.
|
|
139
|
+
* The owner's alone; refused for the owner's own person.
|
|
140
|
+
*/
|
|
141
|
+
markTestData(person: string, by: Decider): Promise<TestDataPerson>;
|
|
136
142
|
/** The identity, and everyone linked with it, is the owner. */
|
|
137
143
|
linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
|
|
138
144
|
/** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
|
|
@@ -143,7 +149,8 @@ export interface PeopleStore extends AccountPeople {
|
|
|
143
149
|
* People of one kind with their shown name, contact, interactions and ties, a page at a time. `person` (the default)
|
|
144
150
|
* is the owner, people added by hand, task assignees, and named people with a tie (a one-to-one chat, a small group,
|
|
145
151
|
* mail the owner wrote, a meeting, a CRM, the address book); `automated`, `organization`, `stranger` (a
|
|
146
|
-
* name, no tie) and `unsorted` (nothing to show as a name) hold the rest.
|
|
152
|
+
* name, no tie) and `unsorted` (nothing to show as a name) hold the rest. `test` holds what a test run left: a seed
|
|
153
|
+
* id, an address at a reserved domain, or what the owner called test data; `all` and every other kind leave it out.
|
|
147
154
|
*/
|
|
148
155
|
list(options: PeopleListOptions): Promise<PeopleList>;
|
|
149
156
|
/** How many people of each kind match a name or username, or the whole store: `list`'s `counts` without a page. */
|
package/dist/store/people.js
CHANGED
|
@@ -6,7 +6,7 @@ import * as identityProposals from "./sqlite/identity-proposals.js";
|
|
|
6
6
|
import * as identitySplits from "./sqlite/identity-split-proposals.js";
|
|
7
7
|
import { linkToOwner } from "./sqlite/own-identities.js";
|
|
8
8
|
import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
|
|
9
|
-
import { keepPerson, personDoubts } from "./sqlite/person-doubts.js";
|
|
9
|
+
import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
|
|
10
10
|
import * as personLinks from "./sqlite/person-links.js";
|
|
11
11
|
import { PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
|
|
12
12
|
import * as personMerges from "./sqlite/person-merges.js";
|
|
@@ -136,6 +136,7 @@ export const peopleStoreOver = (context, keyed) => {
|
|
|
136
136
|
splitProposals: async (filter) => identitySplits.identitySplitRows(context, filter),
|
|
137
137
|
doubts: async (page) => personDoubts(context, page),
|
|
138
138
|
keep: async (person, by) => write(database, () => keepPerson(context, person, by)),
|
|
139
|
+
markTestData: async (person, by) => write(database, () => markTestData(context, person, by)),
|
|
139
140
|
linkToOwner: async (identity) => linkToOwner(context, identity),
|
|
140
141
|
list: async (options) => listPeople(database, options),
|
|
141
142
|
counts: async (query) => countPeople(database, query),
|
|
@@ -6,6 +6,7 @@ import { forgetErasedLinks } from "./identity-link-rows.js";
|
|
|
6
6
|
import { forgetErasedSplits } from "./identity-split-proposals.js";
|
|
7
7
|
import { mergeSql } from "./merged-persons.js";
|
|
8
8
|
import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
|
|
9
|
+
import { forgetErasedTestData } from "./test-people.js";
|
|
9
10
|
import { dropUnusedVectors } from "./vector-index.js";
|
|
10
11
|
/**
|
|
11
12
|
* An account's row, made on first sight; a name only replaces what was known when there is one. `startScope` is the
|
|
@@ -249,6 +250,7 @@ export const dropOrphanPeople = (database, unseenBefore) => {
|
|
|
249
250
|
database.prepare("DELETE FROM identities WHERE id IN (SELECT value FROM json_each(?))").run(gone);
|
|
250
251
|
forgetErasedLinks(database);
|
|
251
252
|
forgetErasedSplits(database);
|
|
253
|
+
forgetErasedTestData(database);
|
|
252
254
|
database
|
|
253
255
|
.prepare(`DELETE FROM persons WHERE id IN (SELECT value FROM json_each(?)) AND owner = 0
|
|
254
256
|
AND NOT EXISTS (SELECT 1 FROM identity_links l WHERE l.person_id = persons.id)
|
|
@@ -145,6 +145,8 @@ export const crmRowsOver = (context) => {
|
|
|
145
145
|
...(item.metadata ?? {}),
|
|
146
146
|
...(item.url ? { url: item.url } : {}),
|
|
147
147
|
...(item.assignee ? { assignee: crmIdentityId(key, item.assignee, "user") } : {}),
|
|
148
|
+
...(textOf(item.contactName, 200) ? { contact_name: textOf(item.contactName, 200) } : {}),
|
|
149
|
+
...(textOf(item.companyName, 200) ? { company_name: textOf(item.companyName, 200) } : {}),
|
|
148
150
|
...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
|
|
149
151
|
};
|
|
150
152
|
const values = {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type CrmScopeSetting } from "../../domain/crm.js";
|
|
2
|
+
import type { DealKind } from "../../domain/deals.js";
|
|
2
3
|
import type { CacheDatabase } from "../driver.js";
|
|
3
4
|
import type { AccountKey } from "../types.js";
|
|
4
5
|
/** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
|
|
@@ -9,7 +10,7 @@ export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier",
|
|
|
9
10
|
export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
|
|
10
11
|
/** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
|
|
11
12
|
export declare const CRM_SCOPES: readonly ["mine", "all"];
|
|
12
|
-
declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self"];
|
|
13
|
+
declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self", "stage-tasks"];
|
|
13
14
|
type CrmSettingName = (typeof NAMES)[number];
|
|
14
15
|
export declare const crmSettingKey: (key: AccountKey, name: CrmSettingName) => string;
|
|
15
16
|
/** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
|
|
@@ -31,6 +32,30 @@ export declare const crmScopeUsers: (database: CacheDatabase, key: AccountKey) =
|
|
|
31
32
|
*/
|
|
32
33
|
/** The CRM user whose deals the account's copy holds: the first sync's sign-in, until the owner unsets it. */
|
|
33
34
|
export declare const crmOwnUser: (database: CacheDatabase, key: AccountKey) => string | undefined;
|
|
35
|
+
/** What a deal or lead entering the stage opens: a task of this title, due this many days later. */
|
|
36
|
+
export interface StageTaskRule {
|
|
37
|
+
title: string;
|
|
38
|
+
dueDays: number;
|
|
39
|
+
}
|
|
40
|
+
export type CrmStageTasks = Record<DealKind, Record<string, StageTaskRule>>;
|
|
41
|
+
/** Only the owner's rules open a task on a stage change; an entry this build cannot read opens none. */
|
|
42
|
+
export declare const crmStageTasks: (database: CacheDatabase, key: AccountKey) => CrmStageTasks;
|
|
43
|
+
/** After the mark, oldest first: each stage a deal or lead of the account entered from another one, and the newest id read. */
|
|
44
|
+
export declare const crmStageMoves: (database: CacheDatabase, key: AccountKey, accountId: number | undefined) => {
|
|
45
|
+
moves: CrmStageMove[];
|
|
46
|
+
through: number;
|
|
47
|
+
};
|
|
48
|
+
export interface CrmStageMove {
|
|
49
|
+
/** The stage change's own id: one task per entry into a stage, never two. */
|
|
50
|
+
id: number;
|
|
51
|
+
kind: DealKind;
|
|
52
|
+
ref: string;
|
|
53
|
+
/** The CRM's id of the stage entered. */
|
|
54
|
+
stage: string;
|
|
55
|
+
stageName: string;
|
|
56
|
+
pipelineName: string;
|
|
57
|
+
}
|
|
58
|
+
export declare const saveStageMovesMark: (database: CacheDatabase, key: AccountKey, through: number, now: number) => void;
|
|
34
59
|
export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
|
|
35
60
|
export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
|
|
36
61
|
export declare const crmSettingsOf: (database: CacheDatabase) => {
|
|
@@ -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";
|
|
@@ -21,6 +21,9 @@ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPen
|
|
|
21
21
|
...(unlistedUsers ? { unlistedUsers } : {}),
|
|
22
22
|
...(droppedPending ? { droppedPending } : {}),
|
|
23
23
|
});
|
|
24
|
+
/** At most this many of a contact's phones or addresses: a CRM field holds what people typed into it. */
|
|
25
|
+
const MOST_CONTACTS = 20;
|
|
26
|
+
const listOf = (values, most) => values.flatMap((value) => textOf(value, most) ?? []).slice(0, MOST_CONTACTS);
|
|
24
27
|
export const crmCopiesOver = (context, people) => {
|
|
25
28
|
const { database, now } = context;
|
|
26
29
|
const { savePipeline, saveItemRow } = crmRowsOver(context);
|
|
@@ -517,6 +520,8 @@ export const crmCopiesOver = (context, people) => {
|
|
|
517
520
|
name: textOf(contact.name, 200),
|
|
518
521
|
email: textOf(contact.email, 320)?.toLowerCase() ?? null,
|
|
519
522
|
phone: textOf(contact.phone, 64),
|
|
523
|
+
...(contact.phones === undefined ? {} : { phones: listOf(contact.phones, 64) }),
|
|
524
|
+
...(contact.emails === undefined ? {} : { emails: listOf(contact.emails, 320) }),
|
|
520
525
|
})));
|
|
521
526
|
return write(database, () => {
|
|
522
527
|
const accountId = account(key);
|
|
@@ -583,6 +588,9 @@ export const crmCopiesOver = (context, people) => {
|
|
|
583
588
|
scope: async (key) => crmScope(database, key),
|
|
584
589
|
ownUser: async (key) => crmOwnUser(database, key),
|
|
585
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()),
|
|
586
594
|
removeOutOfScope: async (key, kind, userIds, { dryRun } = {}) => write(database, () => {
|
|
587
595
|
const keep = new Set(userIds.map((id) => crmIdentityId(key, id, "user")));
|
|
588
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);
|