@wirecat/cli-core 0.669.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 +76 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/calendar/mcp/index.d.ts +12 -12
- 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/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/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/package.json +1 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CrmField, CrmValue } from "../domain/crm.js";
|
|
2
|
+
/** A JSON object as a CRM sends one; anything else is not read as a record. */
|
|
3
|
+
export type CrmRaw = Record<string, unknown>;
|
|
4
|
+
export declare const isRaw: (value: unknown) => value is CrmRaw;
|
|
5
|
+
export declare const fieldOf: (value: unknown, key: string) => unknown;
|
|
6
|
+
export declare const rawsOf: (value: unknown) => CrmRaw[];
|
|
7
|
+
/** A string or a number as trimmed text; an empty one, and anything else, is null. */
|
|
8
|
+
export declare const text: (value: unknown) => string | null;
|
|
9
|
+
/** CRMs send `0` for "no link" (Bitrix24's `companyId`, Kommo's `responsible_user_id` of nobody). */
|
|
10
|
+
export declare const id: (value: unknown) => string | null;
|
|
11
|
+
export declare const ids: (value: unknown) => string[];
|
|
12
|
+
export declare const number: (value: unknown) => number | null;
|
|
13
|
+
/**
|
|
14
|
+
* A time as UTC ISO (WC-OUT-13), from an ISO string with any offset or epoch seconds, as Kommo sends them; a number
|
|
15
|
+
* above 1e11 is read as milliseconds.
|
|
16
|
+
*/
|
|
17
|
+
export declare const time: (value: unknown) => string | null;
|
|
18
|
+
/** Epoch milliseconds, as the CRM port keeps times. */
|
|
19
|
+
export declare const epoch: (value: unknown) => number | null;
|
|
20
|
+
/**
|
|
21
|
+
* Money as a decimal string in its currency, both or neither; `0` is no amount, as CRMs that give every deal a
|
|
22
|
+
* currency send it. A string amount is kept as sent: `toFixed` would add the double's error from about 1e10.
|
|
23
|
+
*/
|
|
24
|
+
export declare const amountOf: (value: unknown, currency: unknown) => {
|
|
25
|
+
amount: string | null;
|
|
26
|
+
currency: string | null;
|
|
27
|
+
};
|
|
28
|
+
export declare const fullName: (...parts: unknown[]) => string | null;
|
|
29
|
+
/**
|
|
30
|
+
* A record's custom values, by code, as the port keeps them: each with its field's label, and a list field's option
|
|
31
|
+
* ids turned into their labels with `option_id` beside (both lists on a multiple field).
|
|
32
|
+
*/
|
|
33
|
+
export declare const crmValuesOf: (values: Readonly<Record<string, unknown>>, fields: readonly CrmField[]) => Record<string, CrmValue>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export const isRaw = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2
|
+
export const fieldOf = (value, key) => (isRaw(value) ? value[key] : undefined);
|
|
3
|
+
export const rawsOf = (value) => (Array.isArray(value) ? value.filter(isRaw) : []);
|
|
4
|
+
/** A string or a number as trimmed text; an empty one, and anything else, is null. */
|
|
5
|
+
export const text = (value) => {
|
|
6
|
+
if (typeof value !== "string" && typeof value !== "number")
|
|
7
|
+
return null;
|
|
8
|
+
const trimmed = String(value).trim();
|
|
9
|
+
return trimmed === "" ? null : trimmed;
|
|
10
|
+
};
|
|
11
|
+
/** CRMs send `0` for "no link" (Bitrix24's `companyId`, Kommo's `responsible_user_id` of nobody). */
|
|
12
|
+
export const id = (value) => {
|
|
13
|
+
const found = text(value);
|
|
14
|
+
return found === null || found === "0" ? null : found;
|
|
15
|
+
};
|
|
16
|
+
export const ids = (value) => Array.isArray(value) ? value.map(id).filter((one) => one !== null) : [];
|
|
17
|
+
export const number = (value) => {
|
|
18
|
+
if (value === null || value === undefined || value === "")
|
|
19
|
+
return null;
|
|
20
|
+
const found = Number(value);
|
|
21
|
+
return Number.isFinite(found) ? found : null;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A time as UTC ISO (WC-OUT-13), from an ISO string with any offset or epoch seconds, as Kommo sends them; a number
|
|
25
|
+
* above 1e11 is read as milliseconds.
|
|
26
|
+
*/
|
|
27
|
+
export const time = (value) => {
|
|
28
|
+
if (typeof value === "number") {
|
|
29
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
30
|
+
return null;
|
|
31
|
+
return new Date(value > 1e11 ? value : value * 1000).toISOString();
|
|
32
|
+
}
|
|
33
|
+
const found = text(value);
|
|
34
|
+
if (found === null)
|
|
35
|
+
return null;
|
|
36
|
+
const parsed = new Date(found);
|
|
37
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
|
|
38
|
+
};
|
|
39
|
+
/** Epoch milliseconds, as the CRM port keeps times. */
|
|
40
|
+
export const epoch = (value) => {
|
|
41
|
+
const found = time(value);
|
|
42
|
+
return found === null ? null : Date.parse(found);
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Money as a decimal string in its currency, both or neither; `0` is no amount, as CRMs that give every deal a
|
|
46
|
+
* currency send it. A string amount is kept as sent: `toFixed` would add the double's error from about 1e10.
|
|
47
|
+
*/
|
|
48
|
+
export const amountOf = (value, currency) => {
|
|
49
|
+
const found = number(value);
|
|
50
|
+
const code = text(currency)?.toUpperCase() ?? null;
|
|
51
|
+
if (found === null || found <= 0 || code === null)
|
|
52
|
+
return { amount: null, currency: null };
|
|
53
|
+
return { amount: typeof value === "string" ? value.trim() : String(found), currency: code };
|
|
54
|
+
};
|
|
55
|
+
export const fullName = (...parts) => parts
|
|
56
|
+
.map(text)
|
|
57
|
+
.filter((part) => part !== null)
|
|
58
|
+
.join(" ") || null;
|
|
59
|
+
const optionLabel = (field, option) => field.options?.find(({ id }) => id === String(option))?.label ?? String(option);
|
|
60
|
+
/**
|
|
61
|
+
* A record's custom values, by code, as the port keeps them: each with its field's label, and a list field's option
|
|
62
|
+
* ids turned into their labels with `option_id` beside (both lists on a multiple field).
|
|
63
|
+
*/
|
|
64
|
+
export const crmValuesOf = (values, fields) => {
|
|
65
|
+
const byCode = new Map(fields.map((field) => [field.code, field]));
|
|
66
|
+
return Object.fromEntries(Object.entries(values).map(([code, value]) => {
|
|
67
|
+
const field = byCode.get(code);
|
|
68
|
+
const label = field?.label ?? null;
|
|
69
|
+
if (!field?.options)
|
|
70
|
+
return [code, { label, value }];
|
|
71
|
+
if (Array.isArray(value))
|
|
72
|
+
return [code, { label, value: value.map((one) => optionLabel(field, one)), option_id: value.map(String) }];
|
|
73
|
+
return [code, { label, value: optionLabel(field, value), option_id: String(value) }];
|
|
74
|
+
}));
|
|
75
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CrmLiveQuery, CrmPage } from "./source.js";
|
|
2
|
+
/** One page as the CRM gave it, and whether it said more come after. */
|
|
3
|
+
export interface CrmRows<T> {
|
|
4
|
+
rows: T[];
|
|
5
|
+
more: boolean;
|
|
6
|
+
}
|
|
7
|
+
/** Which rows an answer page holds: `limit` rows after `offset`. */
|
|
8
|
+
export interface CrmWindow {
|
|
9
|
+
offset: number;
|
|
10
|
+
limit: number;
|
|
11
|
+
}
|
|
12
|
+
/** The rows a live query's page asks for: its page number, from 1, and its size. */
|
|
13
|
+
export declare const crmWindowOf: (query: Pick<CrmLiveQuery, "limit" | "page">) => CrmWindow;
|
|
14
|
+
/**
|
|
15
|
+
* For a CRM that pages by offset only. The rows of one answer page, read from the CRM in its own page sizes, up to `largest` a request: one more than asked,
|
|
16
|
+
* so `hasMore` is known without a total, which many CRMs do not give.
|
|
17
|
+
*/
|
|
18
|
+
export declare const walk: <T>(window: CrmWindow, largest: number, fetchPage: (offset: number, size: number) => Promise<CrmRows<T>>) => Promise<CrmPage<T>>;
|
package/dist/crm/walk.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The rows a live query's page asks for: its page number, from 1, and its size. */
|
|
2
|
+
export const crmWindowOf = (query) => {
|
|
3
|
+
const page = query.page ?? 1;
|
|
4
|
+
return { offset: (Number.isSafeInteger(page) && page > 1 ? page - 1 : 0) * query.limit, limit: query.limit };
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* For a CRM that pages by offset only. The rows of one answer page, read from the CRM in its own page sizes, up to `largest` a request: one more than asked,
|
|
8
|
+
* so `hasMore` is known without a total, which many CRMs do not give.
|
|
9
|
+
*/
|
|
10
|
+
export const walk = async (window, largest, fetchPage) => {
|
|
11
|
+
const want = window.limit + 1;
|
|
12
|
+
const rows = [];
|
|
13
|
+
let at = window.offset;
|
|
14
|
+
while (rows.length < want) {
|
|
15
|
+
const page = await fetchPage(at, Math.min(largest, want - rows.length));
|
|
16
|
+
for (const row of page.rows)
|
|
17
|
+
rows.push(row);
|
|
18
|
+
at += page.rows.length;
|
|
19
|
+
if (!page.more || page.rows.length === 0)
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
return { items: rows.slice(0, window.limit), hasMore: rows.length > window.limit };
|
|
23
|
+
};
|
package/dist/crm/writer.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { ConditionalKey } from "../cli/permission-keys.js";
|
|
2
|
-
import type { CrmItem } from "../domain/crm.js";
|
|
2
|
+
import type { CrmItem, CrmKind, CrmRecords } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind, DealRole } from "../domain/deals.js";
|
|
4
4
|
import type { Level, PermissionKey } from "../sends/permissions.js";
|
|
5
5
|
export declare const CRM_VERBS: readonly ["create", "update", "move", "close", "remove"];
|
|
6
6
|
export type CrmVerb = (typeof CRM_VERBS)[number];
|
|
7
7
|
export interface CrmWriteCapabilities {
|
|
8
|
-
/** The kinds the CRM takes writes for
|
|
9
|
-
kinds: readonly
|
|
8
|
+
/** The kinds the CRM takes writes for; a contact or a company takes only `create` and `update`. */
|
|
9
|
+
kinds: readonly CrmKind[];
|
|
10
10
|
verbs: readonly CrmVerb[];
|
|
11
11
|
/**
|
|
12
12
|
* The CRM answers a repeat of an `operationId` from its record instead of doing the write again. Only then may the
|
|
@@ -43,6 +43,41 @@ export interface CrmFields {
|
|
|
43
43
|
export type CrmDraft = CrmFields & {
|
|
44
44
|
title: string;
|
|
45
45
|
};
|
|
46
|
+
/** A contact's fields; `null` clears one. Each list replaces the whole list. */
|
|
47
|
+
export interface CrmPersonFields {
|
|
48
|
+
/** The whole name, for a CRM that keeps one; a CRM with parts splits it. */
|
|
49
|
+
name?: string;
|
|
50
|
+
firstName?: string | null;
|
|
51
|
+
lastName?: string | null;
|
|
52
|
+
position?: string | null;
|
|
53
|
+
emails?: string[];
|
|
54
|
+
phones?: string[];
|
|
55
|
+
/** The CRM user it is assigned to. */
|
|
56
|
+
owner?: string | null;
|
|
57
|
+
custom?: Record<string, string | string[] | null>;
|
|
58
|
+
}
|
|
59
|
+
/** A company's fields; `null` clears one. */
|
|
60
|
+
export interface CrmOrganizationFields {
|
|
61
|
+
name?: string;
|
|
62
|
+
owner?: string | null;
|
|
63
|
+
custom?: Record<string, string | string[] | null>;
|
|
64
|
+
}
|
|
65
|
+
/** What a write of each kind sends. */
|
|
66
|
+
export interface CrmWriteFields {
|
|
67
|
+
deal: CrmFields;
|
|
68
|
+
lead: CrmFields;
|
|
69
|
+
person: CrmPersonFields;
|
|
70
|
+
organization: CrmOrganizationFields;
|
|
71
|
+
}
|
|
72
|
+
/** What a create of each kind sends: a deal its title, a company its name, a contact a name or one of its parts. */
|
|
73
|
+
export interface CrmDrafts {
|
|
74
|
+
deal: CrmDraft;
|
|
75
|
+
lead: CrmDraft;
|
|
76
|
+
person: CrmPersonFields;
|
|
77
|
+
organization: CrmOrganizationFields & {
|
|
78
|
+
name: string;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
46
81
|
export interface CrmWriteOptions {
|
|
47
82
|
/** Journaled before the call; an idempotent CRM gets it as its idempotency key. */
|
|
48
83
|
operationId: string;
|
|
@@ -56,8 +91,8 @@ export interface CrmWriteOptions {
|
|
|
56
91
|
export interface CrmWriter {
|
|
57
92
|
readonly provider: string;
|
|
58
93
|
readonly capabilities: CrmWriteCapabilities;
|
|
59
|
-
create(kind:
|
|
60
|
-
update(kind:
|
|
94
|
+
create<K extends CrmKind>(kind: K, draft: CrmDrafts[K], options: CrmWriteOptions): Promise<CrmRecords[K]>;
|
|
95
|
+
update<K extends CrmKind>(kind: K, externalId: string, patch: CrmWriteFields[K], options: CrmWriteOptions): Promise<CrmRecords[K]>;
|
|
61
96
|
/** To `stage`, a stage of the item's own pipeline. */
|
|
62
97
|
move(kind: DealKind, externalId: string, stage: string, options: CrmWriteOptions): Promise<CrmItem>;
|
|
63
98
|
/**
|
|
@@ -78,7 +113,7 @@ export declare const CRM_WRITE_KEYS: readonly PermissionKey[];
|
|
|
78
113
|
* `--dry-run` names each: a stage implies the move key and a won or lost one the close key, an owner other than the
|
|
79
114
|
* sign-in's `crm.assign-others`, and `also` the CLI's own (the same `CrmWrites.alsoChecks` the real run checks).
|
|
80
115
|
*/
|
|
81
|
-
export declare const crmAlsoChecks: (also?: (kind:
|
|
116
|
+
export declare const crmAlsoChecks: (also?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[]) => (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
|
|
82
117
|
/**
|
|
83
118
|
* Built in, and only ever tightening (WC-PERM-7): an ordinary change goes ahead, a deletion asks, and a record is not
|
|
84
119
|
* given to somebody else until the owner allows it.
|
package/dist/crm/writer.js
CHANGED
|
@@ -3,7 +3,12 @@ export const CRM_VERBS = ["create", "update", "move", "close", "remove"];
|
|
|
3
3
|
export const CRM_ASSIGN_OTHERS_KEY = "crm.assign-others";
|
|
4
4
|
/** The keys the CRM writes check beyond their command paths, for a CLI's `commandPermissions({ extra })`. */
|
|
5
5
|
export const CRM_WRITE_KEYS = [CRM_ASSIGN_OTHERS_KEY];
|
|
6
|
-
const PLURALS = {
|
|
6
|
+
const PLURALS = {
|
|
7
|
+
deals: "deal",
|
|
8
|
+
leads: "lead",
|
|
9
|
+
people: "person",
|
|
10
|
+
organizations: "organization",
|
|
11
|
+
};
|
|
7
12
|
const VERB_OF = {
|
|
8
13
|
create: "create",
|
|
9
14
|
update: "update",
|
|
@@ -23,15 +28,16 @@ export const crmAlsoChecks = (also) => (path) => {
|
|
|
23
28
|
if (path.length !== 2 || kind === undefined || verb === undefined)
|
|
24
29
|
return [];
|
|
25
30
|
const close = { key: `${noun}.close`, when: "a won or lost stage" };
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
const assign = { key: CRM_ASSIGN_OTHERS_KEY, when: "--owner other than the sign-in's user" };
|
|
32
|
+
const implied = kind === "person" || kind === "organization"
|
|
33
|
+
? verb === "create" || verb === "update"
|
|
34
|
+
? [assign]
|
|
35
|
+
: []
|
|
36
|
+
: verb === "create" || verb === "update"
|
|
37
|
+
? [{ key: `${noun}.move`, when: "--stage" }, close, assign]
|
|
38
|
+
: verb === "move"
|
|
39
|
+
? [close]
|
|
40
|
+
: [];
|
|
35
41
|
return [...implied, ...(also?.(kind, verb) ?? [])];
|
|
36
42
|
};
|
|
37
43
|
/**
|
package/dist/crm/writes.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import type { CrmField } from "../domain/crm.js";
|
|
2
|
+
import type { CrmField, CrmKind, CrmOrganization, CrmPerson } from "../domain/crm.js";
|
|
3
3
|
import type { DealKind } from "../domain/deals.js";
|
|
4
4
|
import type { AppIdentity } from "../ports/app.js";
|
|
5
5
|
import type { Warn } from "../runs/events.js";
|
|
@@ -27,7 +27,7 @@ export interface CrmWrites {
|
|
|
27
27
|
* The CLI's own keys a write also checks, such as Bitrix24's `api.crm.deal.update`; pass the same function to
|
|
28
28
|
* `crmAlsoChecks` so `--dry-run` names them.
|
|
29
29
|
*/
|
|
30
|
-
alsoChecks?: (kind:
|
|
30
|
+
alsoChecks?: (kind: CrmKind, verb: CrmVerb) => readonly PermissionKey[];
|
|
31
31
|
}
|
|
32
32
|
export interface CrmWriteContext {
|
|
33
33
|
store: MessageStore;
|
|
@@ -74,6 +74,11 @@ export declare const fieldNamed: <F extends NamedField>(fields: readonly F[], na
|
|
|
74
74
|
export declare const optionOf: (field: NamedField, value: string, param?: string) => string;
|
|
75
75
|
/** `--field` pairs as typed, split at the first `=`; a pair with no key before it is refused. */
|
|
76
76
|
export declare const fieldPairsOf: (typed: readonly string[]) => [string, string][];
|
|
77
|
+
/**
|
|
78
|
+
* `--field` pairs by the CRM's field definitions: a label to its code, an option to its id, a multiple field's repeats
|
|
79
|
+
* into a list, an empty value to `null`. With no definitions, codes are taken as typed.
|
|
80
|
+
*/
|
|
81
|
+
export declare const crmCustomValues: (fields: readonly CrmField[], pairs: readonly (readonly [name: string, value: string])[]) => Record<string, string | string[] | null>;
|
|
77
82
|
export interface CrmWritten {
|
|
78
83
|
operationId: string;
|
|
79
84
|
item: Deal;
|
|
@@ -98,3 +103,34 @@ export declare const removeCrmItem: (context: CrmWriteContext, kind: DealKind, r
|
|
|
98
103
|
ref: string;
|
|
99
104
|
removed: number;
|
|
100
105
|
}>;
|
|
106
|
+
/** The kinds a contact-or-company write takes. */
|
|
107
|
+
export type CrmRecordKind = "person" | "organization";
|
|
108
|
+
/** A contact's or company's fields as typed; an empty text clears a part of a name or the position. */
|
|
109
|
+
export interface CrmRecordInput {
|
|
110
|
+
name?: string;
|
|
111
|
+
firstName?: string;
|
|
112
|
+
lastName?: string;
|
|
113
|
+
position?: string;
|
|
114
|
+
/** Each list replaces the CRM's whole list; one empty value clears it. */
|
|
115
|
+
emails?: readonly string[];
|
|
116
|
+
phones?: readonly string[];
|
|
117
|
+
owner?: string;
|
|
118
|
+
custom?: CrmFieldsInput["custom"];
|
|
119
|
+
}
|
|
120
|
+
export interface CrmRecordWritten<K extends CrmRecordKind> {
|
|
121
|
+
operationId: string;
|
|
122
|
+
/** The CRM's answer; one that is not the sign-in's client comes without its phones and e-mails (NEED-2487). */
|
|
123
|
+
record: K extends "person" ? CrmPerson : CrmOrganization;
|
|
124
|
+
/** Whether the copy keeps it: only the sign-in's own clients are stored (NEED-2661). */
|
|
125
|
+
stored: boolean;
|
|
126
|
+
}
|
|
127
|
+
/** A CRM id as a list prints it; shared with the commands, not exported from the package. */
|
|
128
|
+
export declare const RECORD_ID: RegExp;
|
|
129
|
+
/** A new contact or company in the CRM, through the guarded path; the CRM's answer is stored as a sync stores it. */
|
|
130
|
+
export declare const createCrmRecord: <K extends CrmRecordKind>(context: CrmWriteContext, kind: K, input: CrmRecordInput, options?: {
|
|
131
|
+
operationId?: string;
|
|
132
|
+
}) => Promise<CrmRecordWritten<K>>;
|
|
133
|
+
/** A change to a contact or company by the CRM's id, as `people list` prints it; what is left out keeps its value. */
|
|
134
|
+
export declare const updateCrmRecord: <K extends CrmRecordKind>(context: CrmWriteContext, kind: K, externalId: string, input: CrmRecordInput, options?: {
|
|
135
|
+
operationId?: string;
|
|
136
|
+
}) => Promise<CrmRecordWritten<K>>;
|
package/dist/crm/writes.js
CHANGED
|
@@ -1,12 +1,29 @@
|
|
|
1
1
|
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { currencyOf, minorUnits } from "../domain/money.js";
|
|
2
3
|
import { foldName } from "../resolve.js";
|
|
3
4
|
import { guardFor } from "../sends/guard.js";
|
|
4
5
|
import { guardedWrite } from "../sends/guarded.js";
|
|
5
6
|
import { keyedGuard } from "../sends/keyed-guard.js";
|
|
6
7
|
import { DEFAULT_PERMISSIONS, levelFor } from "../sends/permissions.js";
|
|
7
8
|
import { newOperationId } from "../sends/send-id.js";
|
|
9
|
+
import { foreignContacts } from "./foreign-contacts.js";
|
|
8
10
|
import { CRM_ASSIGN_OTHERS_KEY, CRM_WRITE_DEFAULTS, } from "./writer.js";
|
|
9
|
-
const
|
|
11
|
+
const moneyChecked = (check, param) => {
|
|
12
|
+
try {
|
|
13
|
+
check();
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (isCliError(error))
|
|
17
|
+
throw new CliError(error.code, error.message, { ...error.details, param });
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const PLURAL = {
|
|
22
|
+
deal: "deals",
|
|
23
|
+
lead: "leads",
|
|
24
|
+
person: "people",
|
|
25
|
+
organization: "organizations",
|
|
26
|
+
};
|
|
10
27
|
const COMMAND = {
|
|
11
28
|
create: "create",
|
|
12
29
|
update: "update",
|
|
@@ -110,6 +127,9 @@ const fieldsOf = (input, pipeline, currency) => {
|
|
|
110
127
|
throw invalid("--amount is a decimal such as 1500.50", "--amount");
|
|
111
128
|
if (!CURRENCY.test(code))
|
|
112
129
|
throw invalid("--amount needs --currency, an ISO 4217 code such as EUR", "--currency");
|
|
130
|
+
// The CRM's answer is stored in minor units: money the store refuses would be written and then not kept.
|
|
131
|
+
moneyChecked(() => currencyOf(code), "--currency");
|
|
132
|
+
moneyChecked(() => minorUnits(input.amount, code, "--amount"), "--amount");
|
|
113
133
|
fields.amount = input.amount;
|
|
114
134
|
fields.currency = code;
|
|
115
135
|
}
|
|
@@ -162,8 +182,16 @@ export const optionOf = (field, value, param = "--field") => {
|
|
|
162
182
|
if (!field.options)
|
|
163
183
|
return value;
|
|
164
184
|
const want = foldFieldName(value);
|
|
165
|
-
const
|
|
166
|
-
|
|
185
|
+
const byId = field.options.find((option) => option.id === value.trim());
|
|
186
|
+
const named = byId ? [] : field.options.filter((option) => foldFieldName(option.label) === want);
|
|
187
|
+
if (named.length > 1)
|
|
188
|
+
throw new CliError("validation_error", `${field.label ?? field.code} has ${named.length} options named ${value}; name one by its id`, {
|
|
189
|
+
reason: "field.ambiguous-option",
|
|
190
|
+
param,
|
|
191
|
+
field: field.code,
|
|
192
|
+
candidates: named,
|
|
193
|
+
});
|
|
194
|
+
const found = byId ?? named[0];
|
|
167
195
|
if (!found)
|
|
168
196
|
throw new CliError("validation_error", `${field.label ?? field.code} has no option ${value}`, {
|
|
169
197
|
reason: "field.unknown-option",
|
|
@@ -181,13 +209,10 @@ export const fieldPairsOf = (typed) => typed.map((one) => {
|
|
|
181
209
|
return [one.slice(0, at), one.slice(at + 1)];
|
|
182
210
|
});
|
|
183
211
|
/**
|
|
184
|
-
* `--field` pairs by the
|
|
185
|
-
*
|
|
212
|
+
* `--field` pairs by the CRM's field definitions: a label to its code, an option to its id, a multiple field's repeats
|
|
213
|
+
* into a list, an empty value to `null`. With no definitions, codes are taken as typed.
|
|
186
214
|
*/
|
|
187
|
-
const
|
|
188
|
-
if (!pairs?.length)
|
|
189
|
-
return undefined;
|
|
190
|
-
const fields = await context.store.crm.fields(context.account, kind);
|
|
215
|
+
export const crmCustomValues = (fields, pairs) => {
|
|
191
216
|
const values = new Map();
|
|
192
217
|
for (const [name, value] of pairs) {
|
|
193
218
|
const field = fields.length ? fieldNamed(fields, name) : null;
|
|
@@ -211,6 +236,8 @@ const customOf = async (context, kind, pairs) => {
|
|
|
211
236
|
return [code, all[0] ?? null];
|
|
212
237
|
}));
|
|
213
238
|
};
|
|
239
|
+
/** `--field` pairs by the field definitions the last sync stored. */
|
|
240
|
+
const customOf = async (context, kind, pairs) => pairs?.length ? crmCustomValues(await context.store.crm.fields(context.account, kind), pairs) : undefined;
|
|
214
241
|
/** Every key the write checks: its own, and each action its fields also take (WC-PERM-22). */
|
|
215
242
|
const keysOf = (context, kind, verb, { stage, owner }) => {
|
|
216
243
|
const extra = [];
|
|
@@ -347,3 +374,130 @@ export const removeCrmItem = async (context, kind, reference, options = {}) => {
|
|
|
347
374
|
const removed = await context.store.crm.remove(context.account, kind, [copy.externalId]);
|
|
348
375
|
return { operationId, ref: copy.ref, removed };
|
|
349
376
|
};
|
|
377
|
+
const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}$/u;
|
|
378
|
+
/** A CRM id as a list prints it; shared with the commands, not exported from the package. */
|
|
379
|
+
export const RECORD_ID = /^[\w.:-]{1,100}$/u;
|
|
380
|
+
const PERSON_ONLY = ["firstName", "lastName", "position", "emails", "phones"];
|
|
381
|
+
const recordInvalid = (message, param) => new CliError("validation_error", message, { reason: "crm.record-field", ...(param ? { param } : {}) });
|
|
382
|
+
const cleared = (value) => (value === undefined ? undefined : value.trim() || null);
|
|
383
|
+
const listed = (values, param, valid) => {
|
|
384
|
+
if (values === undefined)
|
|
385
|
+
return undefined;
|
|
386
|
+
const all = values.map((one) => one.trim());
|
|
387
|
+
if (all.length === 1 && all[0] === "")
|
|
388
|
+
return [];
|
|
389
|
+
for (const one of all)
|
|
390
|
+
if (one === "" || one.length > 320 || (valid && !valid.test(one)))
|
|
391
|
+
throw recordInvalid(`${param} got ${one}`, param);
|
|
392
|
+
return all;
|
|
393
|
+
};
|
|
394
|
+
/** Typed fields into the port's; a company takes only a name, an owner and its own fields. */
|
|
395
|
+
const recordFieldsOf = (kind, input) => {
|
|
396
|
+
if (kind === "organization") {
|
|
397
|
+
const given = PERSON_ONLY.find((one) => input[one] !== undefined);
|
|
398
|
+
if (given)
|
|
399
|
+
throw recordInvalid(`a company has no ${given}`);
|
|
400
|
+
}
|
|
401
|
+
const fields = {};
|
|
402
|
+
if (input.name !== undefined) {
|
|
403
|
+
if (!input.name.trim())
|
|
404
|
+
throw recordInvalid("--name is never empty", "--name");
|
|
405
|
+
fields.name = input.name.trim();
|
|
406
|
+
}
|
|
407
|
+
const parts = { firstName: cleared(input.firstName), lastName: cleared(input.lastName) };
|
|
408
|
+
const position = cleared(input.position);
|
|
409
|
+
if (parts.firstName !== undefined)
|
|
410
|
+
fields.firstName = parts.firstName;
|
|
411
|
+
if (parts.lastName !== undefined)
|
|
412
|
+
fields.lastName = parts.lastName;
|
|
413
|
+
if (position !== undefined)
|
|
414
|
+
fields.position = position;
|
|
415
|
+
const emails = listed(input.emails, "--email", EMAIL);
|
|
416
|
+
const phones = listed(input.phones, "--phone");
|
|
417
|
+
if (emails)
|
|
418
|
+
fields.emails = emails;
|
|
419
|
+
if (phones)
|
|
420
|
+
fields.phones = phones;
|
|
421
|
+
if (input.owner !== undefined) {
|
|
422
|
+
if (!input.owner.trim())
|
|
423
|
+
throw recordInvalid("--owner is the CRM user's id", "--owner");
|
|
424
|
+
fields.owner = input.owner.trim();
|
|
425
|
+
}
|
|
426
|
+
return fields;
|
|
427
|
+
};
|
|
428
|
+
/** The CRM's answer into the store, as a sync saves it; a failure names the record, which the CRM has written. */
|
|
429
|
+
const keptRecord = async (context, kind, record) => {
|
|
430
|
+
try {
|
|
431
|
+
const saved = kind === "person"
|
|
432
|
+
? await context.store.crm.savePeople(context.account, [record])
|
|
433
|
+
: await context.store.crm.saveOrganizations(context.account, [record]);
|
|
434
|
+
const [skipped] = saved.skipped;
|
|
435
|
+
if (skipped)
|
|
436
|
+
throw new Error(skipped.message);
|
|
437
|
+
}
|
|
438
|
+
catch (error) {
|
|
439
|
+
throw new CliError("invalid_response", `the CRM wrote ${kind} ${record.externalId}, but the local store did not keep it ` +
|
|
440
|
+
`(${error instanceof Error ? error.message : String(error)}); sync to store it — do not write it again`, { external_id: record.externalId, sent: true });
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
/**
|
|
444
|
+
* A company the update gave to someone else leaves the copy (NEED-2661), as `removeCrmItem` removes a deal. A contact
|
|
445
|
+
* stays until a sync's scope removes it: the store has no removal of one contact by id, and its identity keeps the
|
|
446
|
+
* phones and e-mails it was saved with.
|
|
447
|
+
*/
|
|
448
|
+
const forgotten = async (context, kind, record) => {
|
|
449
|
+
if (kind === "organization")
|
|
450
|
+
await context.store.crm.remove(context.account, kind, [record.externalId]);
|
|
451
|
+
};
|
|
452
|
+
const writeRecord = async (context, kind, verb, fields, operationId, act) => {
|
|
453
|
+
if (!context.source)
|
|
454
|
+
throw new CliError("configuration_error", "a contact or company write needs the CRM source to tell your clients");
|
|
455
|
+
const rule = foreignContacts(context.source(), undefined);
|
|
456
|
+
const record = await written(context, keysOf(context, kind, verb, { owner: fields.owner }), operationId, act);
|
|
457
|
+
const stored = await rule.own(kind, record);
|
|
458
|
+
try {
|
|
459
|
+
if (stored)
|
|
460
|
+
await keptRecord(context, kind, record);
|
|
461
|
+
else if (verb === "update")
|
|
462
|
+
await forgotten(context, kind, record);
|
|
463
|
+
}
|
|
464
|
+
catch (error) {
|
|
465
|
+
if (isCliError(error))
|
|
466
|
+
throw new CliError(error.code, error.message, { ...error.details, operation_id: operationId });
|
|
467
|
+
throw error;
|
|
468
|
+
}
|
|
469
|
+
const [shown] = stored ? [record] : await rule.strip(kind, [record]);
|
|
470
|
+
return { operationId, record: shown, stored };
|
|
471
|
+
};
|
|
472
|
+
/** A new contact or company in the CRM, through the guarded path; the CRM's answer is stored as a sync stores it. */
|
|
473
|
+
export const createCrmRecord = async (context, kind, input, options = {}) => {
|
|
474
|
+
const { writer } = context.writes;
|
|
475
|
+
supported(writer, kind, "create");
|
|
476
|
+
const fields = recordFieldsOf(kind, input);
|
|
477
|
+
if (kind === "organization" && fields.name === undefined)
|
|
478
|
+
throw recordInvalid("a new company needs --name", "--name");
|
|
479
|
+
if (kind === "person" && !fields.name && !fields.firstName && !fields.lastName)
|
|
480
|
+
throw recordInvalid("a new contact needs --name, --first-name or --last-name", "--name");
|
|
481
|
+
const custom = await customOf(context, kind, input.custom);
|
|
482
|
+
if (custom)
|
|
483
|
+
fields.custom = custom;
|
|
484
|
+
const operationId = operationOf(context, options.operationId);
|
|
485
|
+
return writeRecord(context, kind, "create", fields, operationId, () => writer.create(kind, fields, { operationId }));
|
|
486
|
+
};
|
|
487
|
+
/** A change to a contact or company by the CRM's id, as `people list` prints it; what is left out keeps its value. */
|
|
488
|
+
export const updateCrmRecord = async (context, kind, externalId, input, options = {}) => {
|
|
489
|
+
const { writer } = context.writes;
|
|
490
|
+
supported(writer, kind, "update");
|
|
491
|
+
if (!RECORD_ID.test(externalId))
|
|
492
|
+
throw new CliError("validation_error", `name the ${kind} by the CRM's id, as a list prints it`, {
|
|
493
|
+
reason: "ref.malformed",
|
|
494
|
+
});
|
|
495
|
+
const fields = recordFieldsOf(kind, input);
|
|
496
|
+
const custom = await customOf(context, kind, input.custom);
|
|
497
|
+
if (custom)
|
|
498
|
+
fields.custom = custom;
|
|
499
|
+
if (Object.keys(fields).length === 0)
|
|
500
|
+
throw recordInvalid("nothing to change: name a field");
|
|
501
|
+
const operationId = operationOf(context, options.operationId);
|
|
502
|
+
return writeRecord(context, kind, "update", fields, operationId, () => writer.update(kind, externalId, fields, { operationId }));
|
|
503
|
+
};
|
package/dist/domain/crm.d.ts
CHANGED
|
@@ -99,6 +99,21 @@ export interface CrmPerson {
|
|
|
99
99
|
primary?: boolean;
|
|
100
100
|
sourceRole?: string | null;
|
|
101
101
|
}[];
|
|
102
|
+
firstName?: string | null;
|
|
103
|
+
lastName?: string | null;
|
|
104
|
+
/** The CRM user the contact is assigned to: under `mine`, one assigned to a user in scope stays with no deal. */
|
|
105
|
+
assignee?: string | null;
|
|
106
|
+
/**
|
|
107
|
+
* What a live read (`CrmSource.list`, `get`) and a write answer give beside the copy's fields; the store keeps only
|
|
108
|
+
* `assignee` of them. Times are epoch ms; `url` is the CRM's own page for it.
|
|
109
|
+
*/
|
|
110
|
+
createdAt?: number | null;
|
|
111
|
+
updatedAt?: number | null;
|
|
112
|
+
url?: string | null;
|
|
113
|
+
/** The CRM's own fields' values by code; never a phone or e-mail of a foreign client. */
|
|
114
|
+
metadata?: Record<string, CrmValue>;
|
|
115
|
+
/** A live read's kind of each phone and address, by the value: `WORK`, `MOB`, as the CRM names them. */
|
|
116
|
+
contactTypes?: Record<string, string>;
|
|
102
117
|
}
|
|
103
118
|
/** A CRM company: it becomes an organization of its own, never one matched by name. */
|
|
104
119
|
export interface CrmOrganization {
|
|
@@ -109,7 +124,21 @@ export interface CrmOrganization {
|
|
|
109
124
|
own?: boolean;
|
|
110
125
|
/** The CRM's company type code; `crm.<provider>:<account>.company-types` says what one means, nothing by default. */
|
|
111
126
|
type?: string | null;
|
|
112
|
-
|
|
127
|
+
/** The CRM's own fields' values by code; never a phone or e-mail of a foreign client. */
|
|
128
|
+
metadata?: Record<string, CrmValue>;
|
|
129
|
+
phones?: string[];
|
|
130
|
+
emails?: string[];
|
|
131
|
+
/** A live read's kind of each phone and address, by the value, as on a contact. */
|
|
132
|
+
contactTypes?: Record<string, string>;
|
|
133
|
+
/** A live read's contacts of the company, by their id. */
|
|
134
|
+
people?: string[];
|
|
135
|
+
/**
|
|
136
|
+
* What a live read (`CrmSource.list`, `get`) and a write answer give beside the copy's fields; the store does not keep
|
|
137
|
+
* them. `assignee` is the CRM user it is assigned to; times are epoch ms; `url` the CRM's own page for it.
|
|
138
|
+
*/
|
|
139
|
+
assignee?: string | null;
|
|
140
|
+
createdAt?: number | null;
|
|
141
|
+
updatedAt?: number | null;
|
|
113
142
|
}
|
|
114
143
|
/**
|
|
115
144
|
* A CRM user: someone of the owner's own company, such as a deal's owner. It becomes an identity of the CRM's provider,
|
|
@@ -147,6 +176,11 @@ export interface CrmField {
|
|
|
147
176
|
id: string;
|
|
148
177
|
label: string;
|
|
149
178
|
}[];
|
|
179
|
+
/**
|
|
180
|
+
* The field holds phones or e-mails: a foreign record's value is stripped (NEED-2487). amoCRM sets it for a
|
|
181
|
+
* `multitext` field whose `field_code` is `PHONE` or `EMAIL`, Bitrix24 for its phone and e-mail field types.
|
|
182
|
+
*/
|
|
183
|
+
holds?: "phone" | "email";
|
|
150
184
|
}
|
|
151
185
|
export interface CrmRecords {
|
|
152
186
|
deal: CrmItem;
|
|
@@ -181,7 +215,7 @@ export interface CrmActivity {
|
|
|
181
215
|
externalId: string;
|
|
182
216
|
}[];
|
|
183
217
|
}
|
|
184
|
-
/** The account's scope settings: `also` are the users whose deals
|
|
218
|
+
/** The account's scope settings: `also` are the users whose deals `mine` copies, in place of the sign-in's own. */
|
|
185
219
|
export type CrmScopeSetting = {
|
|
186
220
|
mode: "all";
|
|
187
221
|
} | {
|
|
@@ -190,9 +224,11 @@ export type CrmScopeSetting = {
|
|
|
190
224
|
explicit: boolean;
|
|
191
225
|
};
|
|
192
226
|
/**
|
|
193
|
-
* Which deals and leads a sync copies: all, or those with no assignee or assigned to
|
|
194
|
-
*
|
|
195
|
-
*
|
|
227
|
+
* Which deals and leads a sync copies: all, or those with no assignee or assigned to one of `also`, or to the
|
|
228
|
+
* sign-in's own user (`self`) when `also` is empty: a chosen list leaves `self` out unless it names it. Companies and
|
|
229
|
+
* contacts are what the source lists; under `mine`, a contact no kept deal, lead or company names, and not assigned
|
|
230
|
+
* to a user in scope, is removed after a sync that narrowed the copy or listed it again. Ids are normalised
|
|
231
|
+
* (`normalCrmUserId`).
|
|
196
232
|
*/
|
|
197
233
|
export type CrmScope = {
|
|
198
234
|
mode: "all";
|
package/dist/entities/deal.d.ts
CHANGED
|
@@ -56,7 +56,10 @@ export declare const deal: v.StrictObjectSchema<{
|
|
|
56
56
|
readonly external_id: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
57
57
|
/** A CRM copy's assignee, the identity `<account>/user/<id>`. */
|
|
58
58
|
readonly assignee: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
59
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
|
|
61
|
+
* WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
|
|
62
|
+
*/
|
|
60
63
|
readonly provider_metadata: v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
|
|
61
64
|
readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
62
65
|
readonly value: v.UnknownSchema;
|
|
@@ -129,7 +132,10 @@ export declare const lead: v.StrictObjectSchema<{
|
|
|
129
132
|
readonly external_id: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
130
133
|
/** A CRM copy's assignee, the identity `<account>/user/<id>`. */
|
|
131
134
|
readonly assignee: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
132
|
-
/**
|
|
135
|
+
/**
|
|
136
|
+
* A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
|
|
137
|
+
* WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
|
|
138
|
+
*/
|
|
133
139
|
readonly provider_metadata: v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
|
|
134
140
|
readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
135
141
|
readonly value: v.UnknownSchema;
|