@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
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Predicate, type QueryRegistry } from "@wirecat/cli-base/query";
|
|
2
|
+
import type { CrmField } from "../domain/crm.js";
|
|
3
|
+
import type { CrmCondition } from "./source.js";
|
|
4
|
+
/** How one query field reaches the CRM: the name the condition carries, and how its values read. */
|
|
5
|
+
export interface CrmQueryField {
|
|
6
|
+
field: string;
|
|
7
|
+
kind: "id" | "number" | "time" | "text";
|
|
8
|
+
}
|
|
9
|
+
/** A CRM's own words for a value: a time as its filter takes it, and which custom field types are numbers. */
|
|
10
|
+
export interface CrmConditionHooks {
|
|
11
|
+
/** Epoch ms when absent. */
|
|
12
|
+
time?: (ms: number) => string | number;
|
|
13
|
+
/** Whether a custom field's values go as numbers; none does when absent. */
|
|
14
|
+
numeric?: (field: CrmField) => boolean;
|
|
15
|
+
}
|
|
16
|
+
/** The query's terms as conditions, AND-ed: `nativeTerms` has already refused anything the CRM cannot ask. */
|
|
17
|
+
export declare const conditionsOf: (terms: ReadonlyMap<string, Predicate>, fields: Readonly<Record<string, CrmQueryField>>, hooks?: CrmConditionHooks) => CrmCondition[];
|
|
18
|
+
/** The field names a query uses that the list's own fields do not have: the CRM's custom fields, if any. */
|
|
19
|
+
export declare const customNames: (text: string, registry: QueryRegistry, command: string, defaultField?: string) => string[];
|
|
20
|
+
/** The custom fields a query names, each as typed, refused unless the CRM can filter a list by it. */
|
|
21
|
+
export declare const filterableFields: (fields: readonly CrmField[], names: readonly string[]) => [string, CrmField][];
|
|
22
|
+
/** The list's query fields and the custom ones, each a whole value, so cli-base validates the query as it is. */
|
|
23
|
+
export declare const withCustomFields: (registry: QueryRegistry, chosen: readonly [string, CrmField][]) => QueryRegistry;
|
|
24
|
+
/** The custom terms as conditions on their codes, taken out of `terms` so the rest map by `conditionsOf`. */
|
|
25
|
+
export declare const customConditions: (terms: Map<string, Predicate>, chosen: readonly [string, CrmField][], hooks?: CrmConditionHooks) => CrmCondition[];
|
|
26
|
+
/**
|
|
27
|
+
* The custom fields `--json` names, as `provider_metadata.<code>`, or every one for a bare `provider_metadata`;
|
|
28
|
+
* undefined when it names none.
|
|
29
|
+
*/
|
|
30
|
+
export declare const wantedCodes: (paths: string | undefined) => string[] | "all" | undefined;
|
|
31
|
+
/** The codes `wanted` names, each one the CRM lists: a CRM may refuse a whole call over one unknown name. */
|
|
32
|
+
export declare const selectedCodes: (fields: readonly CrmField[], wanted: string[] | "all" | undefined) => string[];
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { parseLucene, walkQuery } from "@wirecat/cli-base/query";
|
|
3
|
+
import { LIST_QUERY_GUIDE, timeBounds } from "../cli/list-query.js";
|
|
4
|
+
import { fieldNamed, optionOf, unknownField } from "./writes.js";
|
|
5
|
+
const valueFor = (kind, raw, name) => {
|
|
6
|
+
if (kind === "id") {
|
|
7
|
+
if (!/^[\w.:-]{1,100}$/u.test(raw))
|
|
8
|
+
throw new CliError("validation_error", `${name} takes an id; got ${raw}`, { reason: "query.bad-value" });
|
|
9
|
+
return raw;
|
|
10
|
+
}
|
|
11
|
+
if (kind !== "number")
|
|
12
|
+
return raw;
|
|
13
|
+
const found = Number(raw);
|
|
14
|
+
if (raw.trim() === "" || !Number.isFinite(found))
|
|
15
|
+
throw new CliError("validation_error", `${name} takes a number; got ${raw}`, { reason: "query.bad-value" });
|
|
16
|
+
return found;
|
|
17
|
+
};
|
|
18
|
+
const range = (node, map, name) => [
|
|
19
|
+
...(node.value === "*"
|
|
20
|
+
? []
|
|
21
|
+
: [
|
|
22
|
+
{
|
|
23
|
+
field: map.field,
|
|
24
|
+
op: node.lower_inclusive === false ? ">" : ">=",
|
|
25
|
+
value: valueFor(map.kind, node.value, name),
|
|
26
|
+
},
|
|
27
|
+
]),
|
|
28
|
+
...(node.upper === undefined || node.upper === "*"
|
|
29
|
+
? []
|
|
30
|
+
: [
|
|
31
|
+
{
|
|
32
|
+
field: map.field,
|
|
33
|
+
op: node.upper_inclusive === false ? "<" : "<=",
|
|
34
|
+
value: valueFor(map.kind, node.upper, name),
|
|
35
|
+
},
|
|
36
|
+
]),
|
|
37
|
+
];
|
|
38
|
+
/** The query's terms as conditions, AND-ed: `nativeTerms` has already refused anything the CRM cannot ask. */
|
|
39
|
+
export const conditionsOf = (terms, fields, hooks = {}) => [...terms].flatMap(([name, node]) => {
|
|
40
|
+
const map = fields[name];
|
|
41
|
+
if (!map)
|
|
42
|
+
throw new CliError("validation_error", `the CRM cannot filter by ${name}`, { reason: "query.unsupported-field" });
|
|
43
|
+
if (map.kind === "time") {
|
|
44
|
+
const at = hooks.time ?? ((ms) => ms);
|
|
45
|
+
const { since, until } = timeBounds(node);
|
|
46
|
+
return [
|
|
47
|
+
...(since === undefined ? [] : [{ field: map.field, op: ">=", value: at(since) }]),
|
|
48
|
+
...(until === undefined ? [] : [{ field: map.field, op: "<=", value: at(until) }]),
|
|
49
|
+
];
|
|
50
|
+
}
|
|
51
|
+
if (node.operator === "range")
|
|
52
|
+
return range(node, map, name);
|
|
53
|
+
return [{ field: map.field, op: "=", value: valueFor(map.kind, node.value, name) }];
|
|
54
|
+
});
|
|
55
|
+
/** The field names a query uses that the list's own fields do not have: the CRM's custom fields, if any. */
|
|
56
|
+
export const customNames = (text, registry, command, defaultField = "none") => {
|
|
57
|
+
if (text.trim() === "")
|
|
58
|
+
return [];
|
|
59
|
+
const known = new Set(registry.fields.map((field) => field.name));
|
|
60
|
+
const named = walkQuery(parseLucene(text, { defaultField, command, guide: LIST_QUERY_GUIDE }).root)
|
|
61
|
+
.filter((term) => !term.implicit)
|
|
62
|
+
.map((term) => term.field);
|
|
63
|
+
return [...new Set(named.filter((name) => !known.has(name)))];
|
|
64
|
+
};
|
|
65
|
+
/** The custom fields a query names, each as typed, refused unless the CRM can filter a list by it. */
|
|
66
|
+
export const filterableFields = (fields, names) => names.map((name) => {
|
|
67
|
+
const field = fieldNamed(fields, name, "--query");
|
|
68
|
+
if (!field.filterable)
|
|
69
|
+
throw new CliError("validation_error", `the CRM cannot filter a list by ${field.label ?? field.code}`, {
|
|
70
|
+
reason: "field.not-filterable",
|
|
71
|
+
field: field.code,
|
|
72
|
+
});
|
|
73
|
+
return [name, field];
|
|
74
|
+
});
|
|
75
|
+
/** The list's query fields and the custom ones, each a whole value, so cli-base validates the query as it is. */
|
|
76
|
+
export const withCustomFields = (registry, chosen) => ({
|
|
77
|
+
...registry,
|
|
78
|
+
fields: [
|
|
79
|
+
...registry.fields,
|
|
80
|
+
...chosen.map(([name]) => ({ name, type: "kw", operators: ["term", "phrase"], example: `${name}:x`, native: true })),
|
|
81
|
+
],
|
|
82
|
+
});
|
|
83
|
+
const customValue = (field, typed, hooks) => {
|
|
84
|
+
const value = field.options ? optionOf(field, typed, "--query") : typed;
|
|
85
|
+
const number = Number(value);
|
|
86
|
+
return hooks.numeric?.(field) && value.trim() !== "" && Number.isFinite(number) ? number : value;
|
|
87
|
+
};
|
|
88
|
+
/** The custom terms as conditions on their codes, taken out of `terms` so the rest map by `conditionsOf`. */
|
|
89
|
+
export const customConditions = (terms, chosen, hooks = {}) => chosen.flatMap(([name, field]) => {
|
|
90
|
+
const term = terms.get(name);
|
|
91
|
+
terms.delete(name);
|
|
92
|
+
return term ? [{ field: field.code, op: "=", value: customValue(field, term.value, hooks) }] : [];
|
|
93
|
+
});
|
|
94
|
+
/**
|
|
95
|
+
* The custom fields `--json` names, as `provider_metadata.<code>`, or every one for a bare `provider_metadata`;
|
|
96
|
+
* undefined when it names none.
|
|
97
|
+
*/
|
|
98
|
+
export const wantedCodes = (paths) => {
|
|
99
|
+
if (!paths)
|
|
100
|
+
return undefined;
|
|
101
|
+
const parts = paths.split(",").map((path) => path
|
|
102
|
+
.trim()
|
|
103
|
+
.replace(/^items\./, "")
|
|
104
|
+
.split("."));
|
|
105
|
+
const metadata = parts.filter(([top]) => top === "provider_metadata");
|
|
106
|
+
if (metadata.some((part) => part.length === 1))
|
|
107
|
+
return "all";
|
|
108
|
+
const codes = metadata.flatMap(([, code]) => (code ? [code] : []));
|
|
109
|
+
return codes.length ? [...new Set(codes)] : undefined;
|
|
110
|
+
};
|
|
111
|
+
/** The codes `wanted` names, each one the CRM lists: a CRM may refuse a whole call over one unknown name. */
|
|
112
|
+
export const selectedCodes = (fields, wanted) => {
|
|
113
|
+
if (wanted === undefined)
|
|
114
|
+
return [];
|
|
115
|
+
if (wanted === "all")
|
|
116
|
+
return fields.map((field) => field.code);
|
|
117
|
+
return wanted.map((code) => {
|
|
118
|
+
if (!fields.some((field) => field.code === code))
|
|
119
|
+
throw unknownField(fields, code, "--json");
|
|
120
|
+
return code;
|
|
121
|
+
});
|
|
122
|
+
};
|
package/dist/crm/source.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { CrmActivity, CrmDepartment, CrmField, CrmKind, CrmPipeline, CrmRecords, CrmScope, CrmStageEntry, CrmUser } from "../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../domain/deals.js";
|
|
3
|
+
/** The kinds a CRM is read live for, by `list` and `get`. */
|
|
4
|
+
export type CrmLiveKind = "person" | "organization";
|
|
3
5
|
export interface CrmSourceTraits {
|
|
4
6
|
/** What this CRM has: one without leads leaves `lead` out. Contacts and companies come before the items on them. */
|
|
5
7
|
kinds: readonly CrmKind[];
|
|
@@ -40,6 +42,26 @@ export interface CrmGap {
|
|
|
40
42
|
scope?: string;
|
|
41
43
|
message: string;
|
|
42
44
|
}
|
|
45
|
+
/** One condition of a live list, in the shared output's field names (`assigned_to`, `created_at`) or a custom code. */
|
|
46
|
+
export interface CrmCondition {
|
|
47
|
+
field: string;
|
|
48
|
+
op: "=" | "!=" | ">" | ">=" | "<" | "<=" | "in";
|
|
49
|
+
value: string | number | (string | number)[];
|
|
50
|
+
}
|
|
51
|
+
/** A live list of contacts or companies, as `people list` and `organizations list` ask the CRM. */
|
|
52
|
+
export interface CrmLiveQuery {
|
|
53
|
+
/** AND-ed; times are epoch ms, ids and option ids strings, numbers numbers (`conditionsOf`). */
|
|
54
|
+
conditions: CrmCondition[];
|
|
55
|
+
/** The free words and `name:` terms, stars taken off: a CRM's own search by name. */
|
|
56
|
+
text?: string;
|
|
57
|
+
/** Rows on the page. */
|
|
58
|
+
limit: number;
|
|
59
|
+
/**
|
|
60
|
+
* The page number from 1; absent is the first. A CRM that pages by offset turns it into one with `crmWindowOf`;
|
|
61
|
+
* one that pages by number passes it on.
|
|
62
|
+
*/
|
|
63
|
+
page?: number;
|
|
64
|
+
}
|
|
43
65
|
/** What the engine hands every source call; a source that ignores it works as before. */
|
|
44
66
|
export interface CrmCallContext {
|
|
45
67
|
/**
|
|
@@ -65,13 +87,13 @@ export interface CrmSource {
|
|
|
65
87
|
readonly provider: string;
|
|
66
88
|
readonly traits: CrmSourceTraits;
|
|
67
89
|
/**
|
|
68
|
-
* The sign-in's own user id in the CRM, what a `mine` scope keeps
|
|
69
|
-
* deal's and lead's `assignee`, since `mine` keeps one without as nobody's; a source without it is copied
|
|
70
|
-
* account's copy belongs to one user: another sign-in's user is refused.
|
|
90
|
+
* The sign-in's own user id in the CRM, what a `mine` scope keeps while `unassigned` is empty. A source with it fills
|
|
91
|
+
* every deal's and lead's `assignee`, since `mine` keeps one without as nobody's; a source without it is copied
|
|
92
|
+
* whole. One account's copy belongs to one user: another sign-in's user is refused.
|
|
71
93
|
*/
|
|
72
94
|
self?(): string | Promise<string>;
|
|
73
95
|
/**
|
|
74
|
-
* Which of the `unassigned` users this sign-in may
|
|
96
|
+
* Which of the `unassigned` users this sign-in may choose, asked at every sync under `mine`; absent, all
|
|
75
97
|
* of them. The engine copies no deal or lead of a user left out, and names them with `message`, the CRM's reason.
|
|
76
98
|
*/
|
|
77
99
|
unassigned?(users: readonly string[]): Promise<{
|
|
@@ -94,6 +116,21 @@ export interface CrmSource {
|
|
|
94
116
|
ids?(kind: CrmKind, page?: string, context?: CrmCallContext): Promise<CrmIdPage>;
|
|
95
117
|
/** Every user of the account, active or not; a CRM that cannot list them leaves it out, and its users stay. */
|
|
96
118
|
users?(context?: CrmCallContext): Promise<CrmUser[]>;
|
|
119
|
+
/**
|
|
120
|
+
* Contacts or companies read live from the CRM, newest first: the copy holds only the owner's own (NEED-2661), so
|
|
121
|
+
* `people list` finds another client here. Each record carries its custom values in `metadata` (`crmValuesOf`).
|
|
122
|
+
*/
|
|
123
|
+
list?<K extends CrmLiveKind>(kind: K, query: CrmLiveQuery, context?: CrmCallContext): Promise<CrmPage<CrmRecords[K]>>;
|
|
124
|
+
/** One contact or company by the CRM's id, read live; null when the CRM has none or the sign-in cannot see it. */
|
|
125
|
+
get?<K extends CrmLiveKind>(kind: K, id: string, context?: CrmCallContext): Promise<CrmRecords[K] | null>;
|
|
126
|
+
/**
|
|
127
|
+
* Whether the sign-in is the CRM's administrator. With it, anyone else sees the phones and e-mails only of their own
|
|
128
|
+
* clients and at most `DAILY_FOREIGN_CONTACTS` other contacts or companies a day (NEED-2487, `foreignContacts`);
|
|
129
|
+
* left out, the rule does not apply.
|
|
130
|
+
*/
|
|
131
|
+
isAdmin?(): Promise<boolean>;
|
|
132
|
+
/** Which of these contacts or companies are the sign-in's own clients: on a deal or lead assigned to its user. */
|
|
133
|
+
ownClients?(kind: CrmLiveKind, ids: readonly string[]): Promise<Set<string>>;
|
|
97
134
|
/** Every department; left out, reporting lines are unknown and none stored is withdrawn. */
|
|
98
135
|
departments?(context?: CrmCallContext): Promise<CrmDepartment[]>;
|
|
99
136
|
/**
|
package/dist/crm/sync.d.ts
CHANGED
|
@@ -84,7 +84,7 @@ export interface CrmSyncReport {
|
|
|
84
84
|
pipelines: number;
|
|
85
85
|
/** Users read this run; absent when the CRM cannot list them. */
|
|
86
86
|
users?: number;
|
|
87
|
-
/** The deals and leads this run copied
|
|
87
|
+
/** The deals and leads this run copied: `also` when it names anyone, else `self`; `all` when the CRM names none. */
|
|
88
88
|
scope: CrmScope;
|
|
89
89
|
/** Relationships left out because the owner removed or rejected that very one, role included. */
|
|
90
90
|
skippedOwnerRejected: number;
|
package/dist/crm/sync.js
CHANGED
|
@@ -306,7 +306,8 @@ const savePage = async (run, kind, page) => {
|
|
|
306
306
|
run.report.issues.push({ kind, ...one });
|
|
307
307
|
return { saved, stop };
|
|
308
308
|
};
|
|
309
|
-
|
|
309
|
+
/** A chosen `unassigned` list replaces the sign-in's own user, which stays only when named (as b24's `chosenOf`). */
|
|
310
|
+
const scopeIds = (scope) => scope.mode === "all" ? null : [...new Set(scope.also.length ? scope.also : [scope.self])].sort();
|
|
310
311
|
const scopeKey = (scope) => {
|
|
311
312
|
const ids = scopeIds(scope);
|
|
312
313
|
return ids ? `mine:${ids.join(",")}` : "all";
|
|
@@ -404,7 +405,6 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
404
405
|
const kept = isItemKind(kind) ? items.filter((item) => inScope(ids, item)) : items;
|
|
405
406
|
const { saved, stop } = await savePage(run, kind, { ...page, items: kept });
|
|
406
407
|
result.saved += saved;
|
|
407
|
-
cursor = { ...cursor, done: cursor.done + saved };
|
|
408
408
|
if (page.removed?.length)
|
|
409
409
|
result.removed += await store.crm.remove(account, kind, page.removed);
|
|
410
410
|
if (kept.length < items.length && !held) {
|
|
@@ -412,6 +412,12 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
412
412
|
result.outOfScope += await store.crm.remove(account, kind, left);
|
|
413
413
|
}
|
|
414
414
|
run.moved();
|
|
415
|
+
// The page's skipped rows wait for the pipelines the budget refused: the next run reads the same page again.
|
|
416
|
+
if (stop) {
|
|
417
|
+
await save();
|
|
418
|
+
return stop;
|
|
419
|
+
}
|
|
420
|
+
cursor = { ...cursor, done: cursor.done + saved };
|
|
415
421
|
if (!page.hasMore) {
|
|
416
422
|
listed = true;
|
|
417
423
|
await save({ token: page.cursor ?? null });
|
|
@@ -424,11 +430,11 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
424
430
|
pages.add(page.nextCursor);
|
|
425
431
|
round = { ...round, page: page.nextCursor };
|
|
426
432
|
await save();
|
|
427
|
-
if (stop)
|
|
428
|
-
return stop;
|
|
429
433
|
}
|
|
430
434
|
const passes = source.ids && !source.traits.removedInChanges && kind !== "person";
|
|
431
435
|
const due = cursor.pass !== null || now - cursor.passAt >= (options.passEvery ?? DAY);
|
|
436
|
+
// A held narrowing keeps the stored rows outside the scope, and a source's list under mine names none of them.
|
|
437
|
+
const listedOf = held && ids ? { users: ids } : {};
|
|
432
438
|
if (passes && due) {
|
|
433
439
|
const ids = source.ids;
|
|
434
440
|
let pass = cursor.pass ?? { page: null, startedAt: now, seen: [] };
|
|
@@ -452,7 +458,7 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
452
458
|
}
|
|
453
459
|
const before = pass.startedAt - CLOCK_MARGIN;
|
|
454
460
|
const stored = await store.crm.count(account, kind);
|
|
455
|
-
const unlisted = await store.crm.removeUnlisted(account, kind, pass.seen, before, { dryRun: true });
|
|
461
|
+
const unlisted = await store.crm.removeUnlisted(account, kind, pass.seen, before, { ...listedOf, dryRun: true });
|
|
456
462
|
const emptied = pass.seen.length === 0 && unlisted > 0;
|
|
457
463
|
if (!options.rescan && (emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED))) {
|
|
458
464
|
result.pass = "held";
|
|
@@ -464,7 +470,7 @@ const syncKind = async (run, kind, options, result) => {
|
|
|
464
470
|
});
|
|
465
471
|
}
|
|
466
472
|
else {
|
|
467
|
-
result.unlisted = await store.crm.removeUnlisted(account, kind, pass.seen, before);
|
|
473
|
+
result.unlisted = await store.crm.removeUnlisted(account, kind, pass.seen, before, listedOf);
|
|
468
474
|
result.pass = "complete";
|
|
469
475
|
}
|
|
470
476
|
await save({ pass: null, passAt: pass.startedAt });
|
|
@@ -522,7 +528,7 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
522
528
|
report.issues.push({
|
|
523
529
|
kind: "deal",
|
|
524
530
|
reason: "crm.unassigned-dropped",
|
|
525
|
-
message: `${crmSettingKey(account, "unassigned")} names user ${dropped.join(", ")}, not
|
|
531
|
+
message: `${crmSettingKey(account, "unassigned")} names user ${dropped.join(", ")}, not chosen: ` +
|
|
526
532
|
`${allowed.message ?? `${source.provider} refused them`}; their deals and leads are not copied`,
|
|
527
533
|
});
|
|
528
534
|
let steps = 0;
|
|
@@ -7,6 +7,11 @@ import type { CrmSource } from "../source.js";
|
|
|
7
7
|
*/
|
|
8
8
|
export interface CrmSourceFixture {
|
|
9
9
|
source: CrmSource;
|
|
10
|
+
/**
|
|
11
|
+
* The ids of every contact and company the fixture holds, required when the source has `list`: a live list must give
|
|
12
|
+
* back each of them.
|
|
13
|
+
*/
|
|
14
|
+
live?: Partial<Record<"person" | "organization", readonly string[]>>;
|
|
10
15
|
/** A cursor the CRM refuses; absent skips that case. */
|
|
11
16
|
deadCursor?: {
|
|
12
17
|
kind: CrmKind;
|
|
@@ -164,6 +164,45 @@ export const crmSourceContract = (make) => {
|
|
|
164
164
|
},
|
|
165
165
|
},
|
|
166
166
|
];
|
|
167
|
+
cases.push({
|
|
168
|
+
name: "list and get: live pages of contacts and companies, each row once, has_more on every page but the last",
|
|
169
|
+
async run() {
|
|
170
|
+
const { source, live } = await make();
|
|
171
|
+
if (!source.list)
|
|
172
|
+
return;
|
|
173
|
+
const list = source.list.bind(source);
|
|
174
|
+
for (const kind of ["person", "organization"].filter((one) => source.traits.kinds.includes(one))) {
|
|
175
|
+
const whole = await list(kind, { conditions: [], limit: 250 });
|
|
176
|
+
assert.ok(whole.items.length > 0, `${kind}: the fixture lists at least one live`);
|
|
177
|
+
const seeded = live?.[kind];
|
|
178
|
+
assert.ok(seeded, `${kind}: a fixture whose source has list names every record it holds in live`);
|
|
179
|
+
assert.deepEqual(whole.items.map(({ externalId }) => externalId).sort(), [...seeded].sort(), `${kind}: every record the fixture holds is listed, none lost between the CRM's pages`);
|
|
180
|
+
for (const item of whole.items) {
|
|
181
|
+
const record = item;
|
|
182
|
+
const contacts = [record.email, record.phone, ...(record.emails ?? []), ...(record.phones ?? [])];
|
|
183
|
+
const metadata = JSON.stringify(record.metadata ?? {});
|
|
184
|
+
for (const one of contacts.filter((text) => !!text))
|
|
185
|
+
assert.ok(!metadata.includes(one), `${kind} ${record.externalId}: provider_metadata repeats a phone or e-mail, which the foreign rule ` +
|
|
186
|
+
"strips only from emails and phones");
|
|
187
|
+
}
|
|
188
|
+
const seen = [];
|
|
189
|
+
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
|
190
|
+
const answer = await list(kind, { conditions: [], limit: 1, page });
|
|
191
|
+
assert.ok(answer.items.length <= 1, `${kind}: a page holds at most its limit`);
|
|
192
|
+
seen.push(...answer.items.map(({ externalId }) => externalId));
|
|
193
|
+
if (!answer.hasMore)
|
|
194
|
+
break;
|
|
195
|
+
assert.equal(answer.items.length, 1, `${kind}: a page with more after it is full`);
|
|
196
|
+
}
|
|
197
|
+
assert.deepEqual(seen, whole.items.map(({ externalId }) => externalId), `${kind}: pages add up to the list`);
|
|
198
|
+
if (!source.get)
|
|
199
|
+
continue;
|
|
200
|
+
const first = whole.items[0];
|
|
201
|
+
assert.equal((await source.get(kind, first.externalId))?.externalId, first.externalId, `${kind}: get by id`);
|
|
202
|
+
assert.equal(await source.get(kind, "contract-missing-0"), null, `${kind}: no such id is null, not a throw`);
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
});
|
|
167
206
|
return [
|
|
168
207
|
...cases,
|
|
169
208
|
{
|
|
@@ -1,20 +1,24 @@
|
|
|
1
1
|
import type { CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords } from "../../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../../domain/deals.js";
|
|
3
|
-
import type { CrmSource, CrmSourceTraits } from "../source.js";
|
|
3
|
+
import type { CrmLiveKind, CrmSource, CrmSourceTraits } from "../source.js";
|
|
4
4
|
import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
|
|
5
5
|
export interface FakeCrmSourceOptions {
|
|
6
6
|
traits?: Partial<CrmSourceTraits>;
|
|
7
7
|
/** Rows per page of `changes()` and `ids()`; 2 when absent, so every list has several pages. */
|
|
8
8
|
pageSize?: number;
|
|
9
|
-
/** What the write side takes: every verb on
|
|
9
|
+
/** What the write side takes: every verb on every kind, not idempotent, when absent. */
|
|
10
10
|
capabilities?: Partial<CrmWriteCapabilities>;
|
|
11
11
|
/** The sign-in's own user, as `self()` answers it; absent, the fake names none and is copied whole. */
|
|
12
12
|
self?: string;
|
|
13
|
+
/** Gives the fake `isAdmin()`, so the daily limit on foreign contacts applies unless it answers true. */
|
|
14
|
+
admin?: boolean;
|
|
15
|
+
/** The contacts and companies `ownClients()` counts as the sign-in's own; with it, the fake has `ownClients`. */
|
|
16
|
+
ownClients?: Partial<Record<CrmLiveKind, readonly string[]>>;
|
|
13
17
|
}
|
|
14
18
|
/** One write the fake CRM was sent, in order. */
|
|
15
19
|
export interface FakeCrmWrite {
|
|
16
20
|
verb: CrmVerb;
|
|
17
|
-
kind:
|
|
21
|
+
kind: CrmKind;
|
|
18
22
|
externalId: string | null;
|
|
19
23
|
operationId: string;
|
|
20
24
|
}
|
|
@@ -45,6 +49,8 @@ export interface FakeCrmSource extends CrmSource, CrmWriter {
|
|
|
45
49
|
fields: number;
|
|
46
50
|
changes: number;
|
|
47
51
|
ids: number;
|
|
52
|
+
list: number;
|
|
53
|
+
get: number;
|
|
48
54
|
};
|
|
49
55
|
/** Writes sent, refused ones included. */
|
|
50
56
|
readonly writes: FakeCrmWrite[];
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import {
|
|
2
|
+
import { foldName } from "../../resolve.js";
|
|
3
|
+
import { crmWindowOf, walk } from "../walk.js";
|
|
4
|
+
import { CRM_VERBS, } from "../writer.js";
|
|
3
5
|
/** Custom codes the fake refuses: each is a neutral field under another name. */
|
|
4
6
|
export const FAKE_CRM_ALIASES = ["stage", "pipeline", "owner", "status"];
|
|
5
7
|
/** When the fake CRM's changes happened: well before any `now` a contract syncs at. */
|
|
@@ -48,9 +50,9 @@ export const fakeCrmSource = (options = {}) => {
|
|
|
48
50
|
let version = 0;
|
|
49
51
|
const expired = new Map();
|
|
50
52
|
let hidden = false;
|
|
51
|
-
const calls = { pipelines: 0, fields: 0, changes: 0, ids: 0 };
|
|
53
|
+
const calls = { pipelines: 0, fields: 0, changes: 0, ids: 0, list: 0, get: 0 };
|
|
52
54
|
const capabilities = {
|
|
53
|
-
kinds: ["deal", "lead"],
|
|
55
|
+
kinds: ["deal", "lead", "person", "organization"],
|
|
54
56
|
verbs: CRM_VERBS,
|
|
55
57
|
idempotent: false,
|
|
56
58
|
...options.capabilities,
|
|
@@ -142,6 +144,66 @@ export const fakeCrmSource = (options = {}) => {
|
|
|
142
144
|
fake.put(kind, item);
|
|
143
145
|
return held(kind, item.externalId);
|
|
144
146
|
};
|
|
147
|
+
const liveRecord = (kind, externalId) => {
|
|
148
|
+
const found = of(kind).get(externalId);
|
|
149
|
+
if (!found || found.deleted)
|
|
150
|
+
throw new CliError("not_found", `the CRM has no ${kind} ${externalId}`);
|
|
151
|
+
return found.record;
|
|
152
|
+
};
|
|
153
|
+
/** A contact's or company's fields onto its record, as the CRM answers it whole. */
|
|
154
|
+
const recordApplied = (kind, record, given) => {
|
|
155
|
+
const { custom, owner, emails, phones, name, firstName, lastName, position } = given;
|
|
156
|
+
const metadata = { ...record.metadata };
|
|
157
|
+
for (const [code, value] of Object.entries(custom ?? {}))
|
|
158
|
+
if (value === null)
|
|
159
|
+
delete metadata[code];
|
|
160
|
+
else
|
|
161
|
+
metadata[code] = customValue(kind, code, value);
|
|
162
|
+
const parts = { ...(firstName === undefined ? {} : { firstName }), ...(lastName === undefined ? {} : { lastName }) };
|
|
163
|
+
const next = { ...record, ...parts };
|
|
164
|
+
const whole = [next.firstName, next.lastName].filter(Boolean).join(" ") || null;
|
|
165
|
+
return {
|
|
166
|
+
...next,
|
|
167
|
+
...(name !== undefined ? { name } : firstName !== undefined || lastName !== undefined ? { name: whole } : {}),
|
|
168
|
+
...(position === undefined ? {} : { position }),
|
|
169
|
+
...(emails === undefined ? {} : { emails, email: emails[0] ?? null }),
|
|
170
|
+
...(phones === undefined ? {} : { phones, phone: phones[0] ?? null }),
|
|
171
|
+
...(owner === undefined ? {} : { assignee: owner }),
|
|
172
|
+
metadata,
|
|
173
|
+
updatedAt: STAMPED_FROM + (version + 1) * 1000,
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
const putLive = (kind, record) => {
|
|
177
|
+
fake.put(kind, record);
|
|
178
|
+
return liveRecord(kind, record.externalId);
|
|
179
|
+
};
|
|
180
|
+
/** Strict: a condition the shared commands never send fails the test instead of matching everything. */
|
|
181
|
+
const holds = (kind, record, { field, op, value }) => {
|
|
182
|
+
const metadataValue = record.metadata?.[field];
|
|
183
|
+
const had = field === "assigned_to"
|
|
184
|
+
? record.assignee
|
|
185
|
+
: field === "type"
|
|
186
|
+
? record.type
|
|
187
|
+
: field === "created_at"
|
|
188
|
+
? record.createdAt
|
|
189
|
+
: field === "updated_at"
|
|
190
|
+
? record.updatedAt
|
|
191
|
+
: metadataValue
|
|
192
|
+
? (metadataValue.option_id ?? metadataValue.value)
|
|
193
|
+
: fields[kind].some((one) => one.code === field)
|
|
194
|
+
? undefined
|
|
195
|
+
: unknownCondition(field);
|
|
196
|
+
if (op === "=")
|
|
197
|
+
return Array.isArray(had) ? had.map(String).includes(String(value)) : String(had) === String(value);
|
|
198
|
+
if (typeof had !== "number" || typeof value !== "number")
|
|
199
|
+
return false;
|
|
200
|
+
return op === ">=" ? had >= value : op === "<=" ? had <= value : op === ">" ? had > value : had < value;
|
|
201
|
+
};
|
|
202
|
+
const unknownCondition = (field) => {
|
|
203
|
+
throw new CliError("validation_error", `the fake CRM cannot filter by ${field}`, {
|
|
204
|
+
reason: "query.unsupported-field",
|
|
205
|
+
});
|
|
206
|
+
};
|
|
145
207
|
const fake = {
|
|
146
208
|
provider: "example-crm",
|
|
147
209
|
traits,
|
|
@@ -157,20 +219,57 @@ export const fakeCrmSource = (options = {}) => {
|
|
|
157
219
|
},
|
|
158
220
|
async create(kind, draft, { operationId }) {
|
|
159
221
|
refuseAliases(draft);
|
|
160
|
-
|
|
161
|
-
const { pipeline, stage } = placed(kind, draft.pipeline, draft.stage);
|
|
222
|
+
const answer = write("create", kind, null, operationId, () => {
|
|
162
223
|
made += 1;
|
|
163
|
-
const
|
|
164
|
-
|
|
224
|
+
const externalId = `${kind}-new-${made}`;
|
|
225
|
+
if (kind === "person" || kind === "organization") {
|
|
226
|
+
const blank = { externalId, name: null, createdAt: STAMPED_FROM + (version + 1) * 1000 };
|
|
227
|
+
return putLive(kind, recordApplied(kind, blank, draft));
|
|
228
|
+
}
|
|
229
|
+
const deal = draft;
|
|
230
|
+
const { pipeline, stage } = placed(kind, deal.pipeline, deal.stage);
|
|
231
|
+
const blank = { externalId, title: deal.title, pipeline, stage };
|
|
232
|
+
return saved(kind, applied(kind, blank, { ...deal, pipeline, stage }));
|
|
165
233
|
});
|
|
234
|
+
return answer;
|
|
166
235
|
},
|
|
167
236
|
async update(kind, externalId, patch, { operationId }) {
|
|
168
237
|
refuseAliases(patch);
|
|
169
|
-
|
|
238
|
+
const answer = write("update", kind, externalId, operationId, () => {
|
|
239
|
+
if (kind === "person" || kind === "organization")
|
|
240
|
+
return putLive(kind, recordApplied(kind, liveRecord(kind, externalId), patch));
|
|
241
|
+
const fields = patch;
|
|
170
242
|
const item = held(kind, externalId);
|
|
171
|
-
const at =
|
|
172
|
-
return saved(kind, applied(kind, item, { ...
|
|
243
|
+
const at = fields.stage === undefined ? {} : placed(kind, fields.pipeline ?? item.pipeline, fields.stage);
|
|
244
|
+
return saved(kind, applied(kind, item, { ...fields, ...at }));
|
|
173
245
|
});
|
|
246
|
+
return answer;
|
|
247
|
+
},
|
|
248
|
+
...(options.admin === undefined ? {} : { isAdmin: async () => options.admin }),
|
|
249
|
+
...(options.ownClients === undefined
|
|
250
|
+
? {}
|
|
251
|
+
: {
|
|
252
|
+
ownClients: async (kind, ids) => new Set(ids.filter((id) => options.ownClients?.[kind]?.includes(id))),
|
|
253
|
+
}),
|
|
254
|
+
async list(kind, query) {
|
|
255
|
+
calls.list += 1;
|
|
256
|
+
const want = query.text ? foldName(query.text) : undefined;
|
|
257
|
+
const found = [...of(kind).values()]
|
|
258
|
+
.filter((one) => !one.deleted)
|
|
259
|
+
.sort((a, b) => b.version - a.version)
|
|
260
|
+
.map((one) => one.record)
|
|
261
|
+
.filter((one) => want === undefined || foldName(one.name ?? "").includes(want))
|
|
262
|
+
.filter((one) => query.conditions.every((condition) => holds(kind, one, condition)));
|
|
263
|
+
// Pages of `size` rows, so a page the command asks for is read over several of the fake's own.
|
|
264
|
+
return walk(crmWindowOf(query), size, async (offset, count) => ({
|
|
265
|
+
rows: found.slice(offset, offset + count),
|
|
266
|
+
more: offset + count < found.length,
|
|
267
|
+
}));
|
|
268
|
+
},
|
|
269
|
+
async get(kind, externalId) {
|
|
270
|
+
calls.get += 1;
|
|
271
|
+
const found = of(kind).get(externalId);
|
|
272
|
+
return (found && !found.deleted ? found.record : null);
|
|
174
273
|
},
|
|
175
274
|
async move(kind, externalId, stage, { operationId }) {
|
|
176
275
|
return write("move", kind, externalId, operationId, () => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import {
|
|
1
|
+
import { type CrmPipeline } from "../../domain/crm.js";
|
|
2
|
+
import type { DealKind } from "../../domain/deals.js";
|
|
3
3
|
import type { ContractCase } from "../../meetings/index.js";
|
|
4
4
|
import { type CrmWriter } from "../writer.js";
|
|
5
5
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { isCliError } from "@wirecat/cli-base";
|
|
3
|
-
import {
|
|
3
|
+
import { CRM_KINDS } from "../../domain/crm.js";
|
|
4
4
|
import { CRM_VERBS } from "../writer.js";
|
|
5
5
|
let operations = 0;
|
|
6
6
|
const operation = () => {
|
|
@@ -41,7 +41,7 @@ export const crmWriteContract = (make) => {
|
|
|
41
41
|
async run() {
|
|
42
42
|
const { writer } = await make();
|
|
43
43
|
const { kinds, verbs, idempotent } = writer.capabilities;
|
|
44
|
-
assert.ok(kinds.length > 0 && kinds.every((kind) =>
|
|
44
|
+
assert.ok(kinds.length > 0 && kinds.every((kind) => CRM_KINDS.includes(kind)));
|
|
45
45
|
assert.ok(verbs.length > 0 && verbs.every((verb) => CRM_VERBS.includes(verb)));
|
|
46
46
|
assert.equal(typeof idempotent, "boolean");
|
|
47
47
|
},
|
|
@@ -110,6 +110,45 @@ export const crmWriteContract = (make) => {
|
|
|
110
110
|
assert.equal(fixture.requests(), before + 1, "one request");
|
|
111
111
|
},
|
|
112
112
|
},
|
|
113
|
+
{
|
|
114
|
+
name: "a contact's or company's create answers the whole record, and an update of one field keeps the rest",
|
|
115
|
+
async run() {
|
|
116
|
+
const { writer } = await make();
|
|
117
|
+
for (const kind of ["person", "organization"].filter((one) => writer.capabilities.kinds.includes(one))) {
|
|
118
|
+
const made = kind === "person"
|
|
119
|
+
? await writer.create(kind, { firstName: "Anna", lastName: "Example", emails: ["anna@example.com"] }, operation())
|
|
120
|
+
: await writer.create(kind, { name: "Example contract company" }, operation());
|
|
121
|
+
assert.ok(made.externalId, `${kind}: an id`);
|
|
122
|
+
assert.ok(made.name, `${kind}: a name`);
|
|
123
|
+
if (!writer.capabilities.verbs.includes("update"))
|
|
124
|
+
continue;
|
|
125
|
+
const changed = kind === "person"
|
|
126
|
+
? (await writer.update(kind, made.externalId, { position: "Buyer" }, operation()))
|
|
127
|
+
: await writer.update(kind, made.externalId, { name: "Example renamed company" }, operation());
|
|
128
|
+
assert.equal(changed.externalId, made.externalId);
|
|
129
|
+
if (kind === "person") {
|
|
130
|
+
assert.equal(changed.position, "Buyer");
|
|
131
|
+
assert.equal(changed.name, made.name, "name kept");
|
|
132
|
+
assert.deepEqual([changed.email, ...(changed.emails ?? [])].filter(Boolean)[0], "anna@example.com", "e-mail kept");
|
|
133
|
+
}
|
|
134
|
+
else
|
|
135
|
+
assert.equal(changed.name, "Example renamed company");
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: "a contact's write whose answer was lost is outcome_unknown after one request",
|
|
141
|
+
async run() {
|
|
142
|
+
const fixture = await make();
|
|
143
|
+
const kind = ["person", "organization"].find((one) => fixture.writer.capabilities.kinds.includes(one));
|
|
144
|
+
if (!kind)
|
|
145
|
+
return;
|
|
146
|
+
const before = fixture.requests();
|
|
147
|
+
fixture.loseNextAnswer();
|
|
148
|
+
await refusedWith("outcome_unknown", () => fixture.writer.create(kind, { name: "Example lost" }, operation()));
|
|
149
|
+
assert.equal(fixture.requests(), before + 1, "one request");
|
|
150
|
+
},
|
|
151
|
+
},
|
|
113
152
|
{
|
|
114
153
|
name: "an idempotent CRM answers a repeated operation id from its record",
|
|
115
154
|
async run() {
|