@wirecat/cli-core 0.675.0 → 0.677.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 +104 -0
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/command-runs.d.ts +2 -0
- package/dist/cli/command-runs.js +2 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/index.d.ts +2 -2
- package/dist/cli/index.js +1 -1
- package/dist/cli/list-query.d.ts +3 -2
- package/dist/cli/list-query.js +5 -2
- package/dist/cli/setup-command.js +9 -3
- package/dist/crm/cli/index.d.ts +7 -1
- package/dist/crm/cli/index.js +104 -20
- package/dist/crm/cli/pipeline-view.js +15 -1
- package/dist/crm/cli/records.js +11 -3
- package/dist/crm/cli/search-all.d.ts +5 -2
- package/dist/crm/cli/search-all.js +15 -3
- package/dist/crm/source.d.ts +3 -2
- package/dist/crm/stage-tasks.js +1 -1
- package/dist/crm/sync.js +13 -11
- package/dist/crm/testing/write-contract.js +5 -1
- package/dist/crm/viewer.d.ts +28 -0
- package/dist/crm/viewer.js +63 -0
- package/dist/crm/writer.d.ts +3 -0
- package/dist/crm/writes.d.ts +7 -2
- package/dist/crm/writes.js +24 -14
- package/dist/domain/crm.d.ts +9 -9
- package/dist/domain/moment.d.ts +2 -0
- package/dist/domain/moment.js +2 -0
- package/dist/entities/business-context.js +1 -1
- package/dist/entities/deal.d.ts +86 -39
- package/dist/entities/deal.js +45 -4
- package/dist/entities/index.d.ts +20 -32
- package/dist/errors/reasons.js +2 -0
- package/dist/meetings/mcp/index.d.ts +15 -15
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/search-all.d.ts +3 -1
- package/dist/services/search-all.js +1 -0
- package/dist/setup/define.d.ts +17 -2
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/identity-links.d.ts +73 -0
- package/dist/store/identity-links.js +14 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/people.d.ts +23 -1
- package/dist/store/people.js +12 -1
- package/dist/store/sqlite/agent-links.d.ts +34 -0
- package/dist/store/sqlite/agent-links.js +184 -0
- package/dist/store/sqlite/copy-viewer.d.ts +16 -0
- package/dist/store/sqlite/copy-viewer.js +11 -0
- package/dist/store/sqlite/crm-activities.d.ts +7 -1
- package/dist/store/sqlite/crm-activities.js +32 -5
- package/dist/store/sqlite/crm-contacts.d.ts +5 -2
- package/dist/store/sqlite/crm-contacts.js +30 -14
- package/dist/store/sqlite/crm-rows.d.ts +7 -0
- package/dist/store/sqlite/crm-rows.js +37 -5
- package/dist/store/sqlite/crm-settings.d.ts +2 -1
- package/dist/store/sqlite/crm-settings.js +3 -2
- package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
- package/dist/store/sqlite/crm-stage-entries.js +77 -18
- package/dist/store/sqlite/crm.d.ts +14 -4
- package/dist/store/sqlite/crm.js +59 -7
- package/dist/store/sqlite/deals.d.ts +47 -29
- package/dist/store/sqlite/deals.js +64 -76
- package/dist/store/sqlite/identity-proposals.d.ts +2 -0
- package/dist/store/sqlite/identity-proposals.js +2 -0
- package/dist/store/sqlite/person-match-scan.d.ts +29 -0
- package/dist/store/sqlite/person-match-scan.js +4 -4
- package/dist/store/sqlite/person-merges.d.ts +3 -0
- package/dist/store/sqlite/pipeline-period.d.ts +85 -0
- package/dist/store/sqlite/pipeline-period.js +199 -0
- package/dist/store/sqlite/stage-amounts.d.ts +6 -2
- package/dist/store/sqlite/stage-amounts.js +8 -5
- package/package.json +3 -3
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { isNoReplyAddress, isRoleAddress } from "../../domain/addresses.js";
|
|
3
|
+
import { isMobilePhone } from "../../domain/phones.js";
|
|
4
|
+
import { IDENTITY_LINK_KIND, } from "../identity-links.js";
|
|
5
|
+
import { rejectedEvidence, sidesOf } from "./identity-link-rows.js";
|
|
6
|
+
import { openIdentityLink } from "./identity-proposals.js";
|
|
7
|
+
import { isOwner, mergePerson, recordOf, required, survivorOf } from "./person-links.js";
|
|
8
|
+
import { emailHolders, phoneHolders, phonePairJoins, sharedLine, } from "./person-match-scan.js";
|
|
9
|
+
import { mergeId, merges } from "./person-merges.js";
|
|
10
|
+
import { resolvePersonLinks } from "./person-resolution.js";
|
|
11
|
+
import { separated } from "./person-separation.js";
|
|
12
|
+
import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
|
|
13
|
+
import { write } from "./transaction.js";
|
|
14
|
+
/** An agent's merge moves identities as `agent:<name>`, never as a bare name an agent could set to `owner`. */
|
|
15
|
+
const AGENT_METHOD = "agent";
|
|
16
|
+
const personsOf = ({ database }) => new Map(database
|
|
17
|
+
.prepare("SELECT identity_id, person_id FROM identity_links")
|
|
18
|
+
.all()
|
|
19
|
+
.map((row) => [Number(row.identity_id), Number(row.person_id)]));
|
|
20
|
+
const weaknessOf = (context, kind, value, holders, sides, others) => {
|
|
21
|
+
if (kind === "email" && isNoReplyAddress(value))
|
|
22
|
+
return "no-reply";
|
|
23
|
+
if (kind === "email" && isRoleAddress(value))
|
|
24
|
+
return "role-address";
|
|
25
|
+
if (sharedLine(context, holders))
|
|
26
|
+
return "company";
|
|
27
|
+
if (others > 0)
|
|
28
|
+
return "shared";
|
|
29
|
+
if (kind === "phone" && !isMobilePhone(value))
|
|
30
|
+
return "landline";
|
|
31
|
+
const [one, other] = sides;
|
|
32
|
+
if (!one.some((a) => other.some((b) => a.provider !== b.provider)))
|
|
33
|
+
return "one-source";
|
|
34
|
+
if (kind === "phone" && !phonePairJoins(value, holders))
|
|
35
|
+
return "not-own-number";
|
|
36
|
+
return null;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Reads every phone and address once, then answers for any number of pairs of people: what they share, and whether it
|
|
40
|
+
* is strong enough for an agent to merge them.
|
|
41
|
+
*/
|
|
42
|
+
export const linkEvidenceOver = (context) => {
|
|
43
|
+
let read;
|
|
44
|
+
return (a, b) => {
|
|
45
|
+
read ??= {
|
|
46
|
+
holders: [
|
|
47
|
+
["phone", phoneHolders(context.database)],
|
|
48
|
+
["email", emailHolders(context.database)],
|
|
49
|
+
],
|
|
50
|
+
persons: personsOf(context),
|
|
51
|
+
};
|
|
52
|
+
const { holders: all, persons } = read;
|
|
53
|
+
const facts = [];
|
|
54
|
+
for (const [kind, holders] of all)
|
|
55
|
+
for (const [value, held] of holders) {
|
|
56
|
+
const on = (person) => held.filter(({ identity }) => persons.get(identity) === person);
|
|
57
|
+
const sides = [on(a), on(b)];
|
|
58
|
+
if (sides[0].length === 0 || sides[1].length === 0)
|
|
59
|
+
continue;
|
|
60
|
+
const people = new Set(held.map(({ identity }) => persons.get(identity)).filter((p) => p !== undefined));
|
|
61
|
+
const others = people.size - 2;
|
|
62
|
+
const weak = weaknessOf(context, kind, value, held, sides, others);
|
|
63
|
+
const refs = (side) => side.map(({ provider, externalId }) => `${provider}:${externalId}`);
|
|
64
|
+
facts.push({ kind, value, holders: [refs(sides[0]), refs(sides[1])], others, strong: weak === null, weak });
|
|
65
|
+
}
|
|
66
|
+
facts.sort((x, y) => Number(y.strong) - Number(x.strong));
|
|
67
|
+
const strong = facts.some((fact) => fact.strong);
|
|
68
|
+
return {
|
|
69
|
+
persons: [`person:${a}`, `person:${b}`],
|
|
70
|
+
strong,
|
|
71
|
+
facts,
|
|
72
|
+
weak: strong ? null : (facts[0]?.weak ?? "nothing-shared"),
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
const held = (evidence, weak) => ({ ...evidence, strong: false, weak });
|
|
77
|
+
/**
|
|
78
|
+
* An agent's link: merged at once on strong evidence the store finds itself, recorded as an `identity_link` decided by
|
|
79
|
+
* the agent, with the evidence, its reason and its run; otherwise it waits for the owner as a proposal, which says why
|
|
80
|
+
* it is not strong. Refused over the owner's separation, as any agent's link is.
|
|
81
|
+
*/
|
|
82
|
+
export const agentLink = (context, input) => write(context.database, () => {
|
|
83
|
+
const bot = input.bot.trim();
|
|
84
|
+
if (!bot || bot === "owner")
|
|
85
|
+
throw new CliError("validation_error", "an agent's link names the agent", { reason: "identity.agent-unnamed" });
|
|
86
|
+
const identity = required(context, input.identity);
|
|
87
|
+
const other = required(context, input.with);
|
|
88
|
+
const [from, to] = [identity.personPk, other.personPk];
|
|
89
|
+
if (from === to)
|
|
90
|
+
throw new CliError("validation_error", "those identities are one person already", { reason: "identity.same" });
|
|
91
|
+
if (separated(context, from, to))
|
|
92
|
+
throw new CliError("conflict", "the owner separated these people; only the owner links them again", {
|
|
93
|
+
reason: "identity.separated",
|
|
94
|
+
});
|
|
95
|
+
const found = linkEvidenceOver(context)(from, to);
|
|
96
|
+
const hold = !input.apply
|
|
97
|
+
? "propose-only"
|
|
98
|
+
: isOwner(context, from) || isOwner(context, to)
|
|
99
|
+
? "owner"
|
|
100
|
+
: rejectedEvidence(context.database, from, to) !== undefined
|
|
101
|
+
? "rejected"
|
|
102
|
+
: undefined;
|
|
103
|
+
const evidence = hold === undefined || !found.strong ? found : held(found, hold);
|
|
104
|
+
const run = input.run?.trim() ? { run: input.run.trim() } : {};
|
|
105
|
+
const by = { bot, kind: "agent" };
|
|
106
|
+
const operations = proposalOperationsOver(context);
|
|
107
|
+
if (!evidence.strong) {
|
|
108
|
+
const opened = openIdentityLink(context, {
|
|
109
|
+
identity: identity.pk,
|
|
110
|
+
with: other.pk,
|
|
111
|
+
from,
|
|
112
|
+
to,
|
|
113
|
+
joins: "person",
|
|
114
|
+
signal: "agent",
|
|
115
|
+
by,
|
|
116
|
+
reason: input.reason,
|
|
117
|
+
evidence: evidence.facts.map(({ value }) => value),
|
|
118
|
+
strength: evidence,
|
|
119
|
+
...run,
|
|
120
|
+
});
|
|
121
|
+
if (opened.outcome === "skipped")
|
|
122
|
+
throw new CliError("conflict", opened.reason === "identity.rejected"
|
|
123
|
+
? "the owner rejected linking these people on this evidence; only new evidence proposes them again"
|
|
124
|
+
: "those identities are one person already", { reason: opened.reason });
|
|
125
|
+
return { outcome: "proposed", proposal: opened.action.id, evidence };
|
|
126
|
+
}
|
|
127
|
+
const [fact] = evidence.facts;
|
|
128
|
+
const kept = survivorOf(context, from, to);
|
|
129
|
+
const merge = mergeId(kept, kept === to ? from : to);
|
|
130
|
+
const payload = {
|
|
131
|
+
identity: `${input.identity.provider}:${input.identity.id}`,
|
|
132
|
+
with: `${input.with.provider}:${input.with.id}`,
|
|
133
|
+
persons: [String(from), String(to)],
|
|
134
|
+
sides: sidesOf(context.database, from, to),
|
|
135
|
+
joins: "person",
|
|
136
|
+
signal: fact.kind,
|
|
137
|
+
score: null,
|
|
138
|
+
evidence: [fact.value],
|
|
139
|
+
strength: evidence,
|
|
140
|
+
applied: "agent",
|
|
141
|
+
...run,
|
|
142
|
+
};
|
|
143
|
+
const proposal = operations.propose({ kind: IDENTITY_LINK_KIND, by, payload, reason: input.reason });
|
|
144
|
+
operations.approve(proposal.id, { person: String(kept), merge }, by);
|
|
145
|
+
mergePerson(context, from, to, { method: AGENT_METHOD, by: `agent:${bot}` });
|
|
146
|
+
resolvePersonLinks(context.database, recordOf(context, kept).identities.flatMap(({ name, username }) => [name, username]));
|
|
147
|
+
return { outcome: "merged", person: `person:${kept}`, merge, proposal: proposal.id, evidence };
|
|
148
|
+
});
|
|
149
|
+
/** Who merged, why and in which run, for a merge an agent made; `undefined` for any other. */
|
|
150
|
+
export const agentMergeOf = (context, merge) => {
|
|
151
|
+
const row = context.database
|
|
152
|
+
.prepare("SELECT id FROM proposed_actions WHERE kind = ? AND status = 'approved' " +
|
|
153
|
+
"AND json_extract(payload, '$.applied') = 'agent' AND json_extract(result, '$.merge') = ? ORDER BY id DESC LIMIT 1")
|
|
154
|
+
.get(IDENTITY_LINK_KIND, merge);
|
|
155
|
+
if (!row)
|
|
156
|
+
return undefined;
|
|
157
|
+
const action = proposalOperationsOver(context).get(String(row.id));
|
|
158
|
+
const payload = action.payload;
|
|
159
|
+
const proposer = proposerOfAction(action);
|
|
160
|
+
return {
|
|
161
|
+
proposal: action.id,
|
|
162
|
+
bot: proposer.type === "bot" ? proposer.name : "unknown",
|
|
163
|
+
run: payload.run ?? null,
|
|
164
|
+
reason: action.reason,
|
|
165
|
+
evidence: payload.strength ?? null,
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
/** The merges agents made that are still in place, newest first: what the owner may want to undo. */
|
|
169
|
+
export const agentMerges = (context, { limit, offset }) => {
|
|
170
|
+
const rows = context.database
|
|
171
|
+
.prepare("SELECT json_extract(result, '$.merge') AS merge FROM proposed_actions WHERE kind = ? AND status = 'approved' " +
|
|
172
|
+
"AND json_extract(payload, '$.applied') = 'agent' ORDER BY id DESC")
|
|
173
|
+
.all(IDENTITY_LINK_KIND);
|
|
174
|
+
const found = [];
|
|
175
|
+
for (const { merge } of rows) {
|
|
176
|
+
const [, to] = /^merge:(\d+)-\d+$/.exec(String(merge)) ?? [];
|
|
177
|
+
if (to === undefined)
|
|
178
|
+
continue;
|
|
179
|
+
const inPlace = merges(context, to).find((one) => one.id === merge && one.method === AGENT_METHOD);
|
|
180
|
+
if (inPlace)
|
|
181
|
+
found.push({ ...inPlace, agent: agentMergeOf(context, inPlace.id) });
|
|
182
|
+
}
|
|
183
|
+
return { items: found.slice(offset, offset + limit), hasMore: found.length > offset + limit };
|
|
184
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AccountKey } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* A profile that may read only part of one CRM account's copy (SEC-197): the deals and leads assigned to `assignee`,
|
|
4
|
+
* the identity `<account>/user/<id>`, or none when it is `null`.
|
|
5
|
+
*/
|
|
6
|
+
export interface CopyViewer {
|
|
7
|
+
account: AccountKey;
|
|
8
|
+
assignee: string | null;
|
|
9
|
+
}
|
|
10
|
+
/** The condition on a deal or lead row `alias` of the viewer's account, with its parameters. */
|
|
11
|
+
export declare const viewerSql: (alias: string, viewer: CopyViewer | undefined) => {
|
|
12
|
+
sql: string;
|
|
13
|
+
params: string[];
|
|
14
|
+
};
|
|
15
|
+
/** Whether a deal or lead row, with its account's `provider` and `account` and its `assignee`, is the viewer's to read. */
|
|
16
|
+
export declare const seenBy: (viewer: CopyViewer | undefined, row: Record<string, unknown>) => boolean;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The condition on a deal or lead row `alias` of the viewer's account, with its parameters. */
|
|
2
|
+
export const viewerSql = (alias, viewer) => viewer === undefined
|
|
3
|
+
? { sql: "1", params: [] }
|
|
4
|
+
: viewer.assignee === null
|
|
5
|
+
? { sql: "0", params: [] }
|
|
6
|
+
: { sql: `json_extract(${alias}.metadata, '$.assignee') = ?`, params: [viewer.assignee] };
|
|
7
|
+
/** Whether a deal or lead row, with its account's `provider` and `account` and its `assignee`, is the viewer's to read. */
|
|
8
|
+
export const seenBy = (viewer, row) => viewer === undefined ||
|
|
9
|
+
row.provider !== viewer.account.provider ||
|
|
10
|
+
row.account !== viewer.account.account ||
|
|
11
|
+
(viewer.assignee !== null && row.assignee === viewer.assignee);
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { CrmActivity, CrmActivityKind } from "../../domain/crm.js";
|
|
2
2
|
import type { DealKind } from "../../domain/deals.js";
|
|
3
|
+
import type { CacheDatabase } from "../driver.js";
|
|
3
4
|
import type { AccountKey } from "../types.js";
|
|
4
5
|
import type { StoreContext } from "./open.js";
|
|
5
6
|
export declare const ACTIVITY_RECORD = "crm.activity";
|
|
7
|
+
/**
|
|
8
|
+
* Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
|
|
9
|
+
* the rows they were on. Answers how many.
|
|
10
|
+
*/
|
|
11
|
+
export declare const forgetActivitiesOn: (database: CacheDatabase, accountId: number, kind: "person" | "organization", externalIds: readonly string[], at: number) => number;
|
|
6
12
|
/** One activity as `deals show` lists it. */
|
|
7
13
|
export interface StoredActivity {
|
|
8
14
|
externalId: string;
|
|
@@ -20,7 +26,7 @@ export interface StoredActivity {
|
|
|
20
26
|
export declare const activityTexts: (database: StoreContext["database"], kind: DealKind) => Map<string, string[]>;
|
|
21
27
|
export interface CrmActivitiesSaved {
|
|
22
28
|
saved: number;
|
|
23
|
-
/** On no deal or
|
|
29
|
+
/** On no deal, lead, contact or company this copy keeps, so not stored. */
|
|
24
30
|
outOfScope: number;
|
|
25
31
|
}
|
|
26
32
|
export declare const crmActivitiesOver: (context: StoreContext) => {
|
|
@@ -3,6 +3,20 @@ import { accountPk, findAccountPk } from "./accounts.js";
|
|
|
3
3
|
import { crmIdentityId, SOURCE, TABLES, textOf } from "./crm-rows.js";
|
|
4
4
|
import { write } from "./transaction.js";
|
|
5
5
|
export const ACTIVITY_RECORD = "crm.activity";
|
|
6
|
+
/**
|
|
7
|
+
* Marks deleted the activities on nothing but these contacts or companies: their subject and body leave the copy with
|
|
8
|
+
* the rows they were on. Answers how many.
|
|
9
|
+
*/
|
|
10
|
+
export const forgetActivitiesOn = (database, accountId, kind, externalIds, at) => {
|
|
11
|
+
const removed = "rr.target_type = ? AND rr.target_external_id IN (SELECT value FROM json_each(?))";
|
|
12
|
+
const ids = JSON.stringify(externalIds);
|
|
13
|
+
return database
|
|
14
|
+
.prepare("UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL " +
|
|
15
|
+
`AND EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' AND ${removed}) ` +
|
|
16
|
+
"AND NOT EXISTS (SELECT 1 FROM record_relations rr WHERE rr.record_id = records.id AND rr.role = 'on' " +
|
|
17
|
+
`AND NOT (${removed}))`)
|
|
18
|
+
.run(at, accountId, ACTIVITY_RECORD, kind, ids, kind, ids).changes;
|
|
19
|
+
};
|
|
6
20
|
/** A CRM's text field holds what people typed or pasted, a whole e-mail thread too. */
|
|
7
21
|
const MOST_BODY = 20_000;
|
|
8
22
|
const MOST_SUBJECT = 500;
|
|
@@ -25,18 +39,29 @@ export const activityTexts = (database, kind) => {
|
|
|
25
39
|
};
|
|
26
40
|
export const crmActivitiesOver = (context) => {
|
|
27
41
|
const { database, now } = context;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
42
|
+
/** A deal or lead the copy keeps, a contact it holds, or a company it keeps. */
|
|
43
|
+
const kept = (key, accountId, kind, externalId) => (kind === "person"
|
|
44
|
+
? database
|
|
45
|
+
.prepare("SELECT 1 FROM identities WHERE provider = ? AND external_id = ?")
|
|
46
|
+
.get(key.provider, crmIdentityId(key, externalId))
|
|
47
|
+
: kind === "organization"
|
|
48
|
+
? database
|
|
49
|
+
.prepare("SELECT 1 FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
|
|
50
|
+
"AND deleted_at IS NULL")
|
|
51
|
+
.get(accountId, externalId)
|
|
52
|
+
: database
|
|
53
|
+
.prepare(`SELECT 1 FROM ${TABLES[kind]} WHERE account_id = ? AND external_id = ? AND deleted_at IS NULL`)
|
|
54
|
+
.get(accountId, externalId)) !== undefined;
|
|
31
55
|
const save = (key, activities) => write(database, () => {
|
|
32
56
|
const accountId = accountPk(context, key);
|
|
33
57
|
const at = now();
|
|
34
58
|
let saved = 0;
|
|
35
59
|
let outOfScope = 0;
|
|
36
60
|
for (const activity of activities) {
|
|
37
|
-
const on = activity.on.filter((one) => kept(accountId, one.kind, one.externalId));
|
|
61
|
+
const on = activity.on.filter((one) => kept(key, accountId, one.kind, one.externalId));
|
|
38
62
|
const held = database
|
|
39
|
-
.prepare("SELECT id
|
|
63
|
+
.prepare("SELECT id, json_extract(fields, '$.done') AS done, json_extract(fields, '$.done_at') AS done_at " +
|
|
64
|
+
"FROM records WHERE account_id = ? AND type = ? AND external_id = ?")
|
|
40
65
|
.get(accountId, ACTIVITY_RECORD, activity.externalId);
|
|
41
66
|
if (on.length === 0) {
|
|
42
67
|
// It left every kept deal: one stored before goes with it.
|
|
@@ -51,6 +76,8 @@ export const crmActivitiesOver = (context) => {
|
|
|
51
76
|
body: textOf(activity.body, MOST_BODY),
|
|
52
77
|
due_at: activity.dueAt ?? null,
|
|
53
78
|
done: activity.done,
|
|
79
|
+
// When it was done, as near as the copy can tell: the CRM's change that closed it, kept once seen.
|
|
80
|
+
done_at: activity.done ? (held?.done ? (held.done_at ?? null) : activity.updatedAt) : null,
|
|
54
81
|
assignee: activity.assignee ? crmIdentityId(key, activity.assignee, "user") : null,
|
|
55
82
|
created_at: activity.createdAt,
|
|
56
83
|
updated_at: activity.updatedAt,
|
|
@@ -18,10 +18,13 @@ export declare const withoutPlaceholder: (name: string) => string | null;
|
|
|
18
18
|
* assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
|
|
19
19
|
* saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
|
|
20
20
|
* deleted unless anything still points at them. People named after a contact keep that name without the import's
|
|
21
|
-
* `null #<id>`; the owner's person is never renamed.
|
|
21
|
+
* `null #<id>`; the owner's person is never renamed. `only` removes just these contacts, by the CRM's id, whenever they
|
|
22
|
+
* were saved and whatever company names them, unless a kept deal or lead does. Activities on nothing but a removed
|
|
23
|
+
* contact are marked deleted.
|
|
22
24
|
*/
|
|
23
|
-
export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
|
|
25
|
+
export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun, only, }: {
|
|
24
26
|
users?: readonly string[];
|
|
25
27
|
before: number;
|
|
26
28
|
dryRun?: boolean;
|
|
29
|
+
only?: readonly string[];
|
|
27
30
|
}) => CrmContactsRemoved;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findAccountPk, OWN, referencesTo } from "./accounts.js";
|
|
2
|
-
import {
|
|
2
|
+
import { forgetActivitiesOn } from "./crm-activities.js";
|
|
3
|
+
import { crmAccountPrefix, crmIdentityId, PERSON_RECORD } from "./crm-rows.js";
|
|
3
4
|
import { write } from "./transaction.js";
|
|
4
5
|
/** A CRM import can leave `null` or `null #<id>` in a name field; no person is called that. */
|
|
5
6
|
const PLACEHOLDER = /(?:^|\s)null(?:\s+#\d+)?(?=\s|$)/gi;
|
|
@@ -18,9 +19,11 @@ const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
|
|
|
18
19
|
* assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
|
|
19
20
|
* saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
|
|
20
21
|
* deleted unless anything still points at them. People named after a contact keep that name without the import's
|
|
21
|
-
* `null #<id>`; the owner's person is never renamed.
|
|
22
|
+
* `null #<id>`; the owner's person is never renamed. `only` removes just these contacts, by the CRM's id, whenever they
|
|
23
|
+
* were saved and whatever company names them, unless a kept deal or lead does. Activities on nothing but a removed
|
|
24
|
+
* contact are marked deleted.
|
|
22
25
|
*/
|
|
23
|
-
export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
|
|
26
|
+
export const removeCrmContacts = (context, key, { users, before, dryRun = false, only, }) => {
|
|
24
27
|
const { database } = context;
|
|
25
28
|
const accountId = findAccountPk(context, key);
|
|
26
29
|
if (accountId === undefined)
|
|
@@ -55,20 +58,24 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
|
|
|
55
58
|
database
|
|
56
59
|
.prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
|
|
57
60
|
`LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
(only === undefined
|
|
62
|
+
? "AND i.created_at < ? AND i.updated_at < ? " +
|
|
63
|
+
(users === undefined
|
|
64
|
+
? ""
|
|
65
|
+
: "AND coalesce(json_extract(i.metadata, '$.assignee'), '') NOT IN (SELECT id FROM temp.crm_scope) ") +
|
|
66
|
+
`AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
|
|
67
|
+
"AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
|
|
68
|
+
"AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
|
|
69
|
+
"AND +k.to_type = 'organization' AND k.kind = 'member-of' AND k.role = 'contact' AND k.source = 'crm' " +
|
|
70
|
+
`AND k.deleted_at IS NULL AND r.account_id = ${accountId} AND r.type = 'organization' ` +
|
|
71
|
+
"AND r.deleted_at IS NULL) "
|
|
72
|
+
: "AND i.external_id IN (SELECT value FROM json_each(?)) " +
|
|
73
|
+
// A contact on the owner's own deal stays: the next sync would copy it back from that deal.
|
|
74
|
+
`AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} `) +
|
|
68
75
|
"AND NOT EXISTS (SELECT 1 FROM identity_link_events e WHERE e.identity_id = i.id AND e.author = 'owner') " +
|
|
69
76
|
"AND NOT EXISTS (SELECT 1 FROM temp.crm_proposed c WHERE c.decided AND c.ref = i.provider || ':' || " +
|
|
70
77
|
"i.external_id)")
|
|
71
|
-
.run(...contact, before, before);
|
|
78
|
+
.run(...contact, ...(only === undefined ? [before, before] : [JSON.stringify(only.map((id) => crmIdentityId(key, id)))]));
|
|
72
79
|
database.exec(`DELETE FROM temp.crm_gone WHERE id IN (${identityRefs})`);
|
|
73
80
|
// A same-email join left the contact's first person empty; it goes too, unless something points at it.
|
|
74
81
|
database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT person FROM temp.crm_gone WHERE person IS NOT NULL");
|
|
@@ -101,6 +108,15 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
|
|
|
101
108
|
database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
|
|
102
109
|
`json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
|
|
103
110
|
`OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
|
|
111
|
+
// The contact's own fields go with it, marked deleted as the CRM's other rows are (WC-DATA-7).
|
|
112
|
+
database
|
|
113
|
+
.prepare(`UPDATE records SET deleted_at = ? WHERE account_id = ? AND type = ? AND deleted_at IS NULL AND external_id IN ` +
|
|
114
|
+
`(SELECT substr(external_id, ?) FROM identities WHERE id IN ${gone})`)
|
|
115
|
+
.run(context.now(), accountId, PERSON_RECORD, prefix.length + 1);
|
|
116
|
+
forgetActivitiesOn(database, accountId, "person", database
|
|
117
|
+
.prepare(`SELECT substr(external_id, ?) AS id FROM identities WHERE id IN ${gone}`)
|
|
118
|
+
.all(prefix.length + 1)
|
|
119
|
+
.map((row) => String(row.id)), context.now());
|
|
104
120
|
for (const table of ["identity_revisions", "identity_link_events", "identity_links", "account_identities"])
|
|
105
121
|
database.exec(`DELETE FROM ${table} WHERE identity_id IN ${gone}`);
|
|
106
122
|
const contacts = database.prepare(`DELETE FROM identities WHERE id IN ${gone}`).run().changes;
|
|
@@ -14,6 +14,13 @@ export declare const TABLES: {
|
|
|
14
14
|
};
|
|
15
15
|
/** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
|
|
16
16
|
export declare const SOURCE = "crm";
|
|
17
|
+
/** A deal or lead given to another CRM user, as the sync saw it. */
|
|
18
|
+
export declare const OWNER_CHANGE_RECORD = "crm.owner-change";
|
|
19
|
+
/**
|
|
20
|
+
* A contact's own fields beside its identity: who it is assigned to, when the CRM made and changed it, its page and
|
|
21
|
+
* its custom values. Not `person`: a records import's `person` without an entity is matched into people.
|
|
22
|
+
*/
|
|
23
|
+
export declare const PERSON_RECORD = "crm.person";
|
|
17
24
|
/**
|
|
18
25
|
* A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
|
|
19
26
|
* `contact:` references percent-encode it, so the `/` stays one part.
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { timezoneOf } from "@wirecat/cli-base/query";
|
|
2
3
|
import { STAGE_OUTCOMES } from "../../domain/deals.js";
|
|
4
|
+
import { dayIn } from "../../domain/moment.js";
|
|
3
5
|
import { currencyOf, minorUnits, scaleOf } from "../../domain/money.js";
|
|
4
6
|
import { fold } from "../normalize.js";
|
|
5
7
|
import { authorActor } from "./memories.js";
|
|
@@ -39,6 +41,13 @@ const moneyOf = (item) => {
|
|
|
39
41
|
};
|
|
40
42
|
/** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
|
|
41
43
|
export const SOURCE = "crm";
|
|
44
|
+
/** A deal or lead given to another CRM user, as the sync saw it. */
|
|
45
|
+
export const OWNER_CHANGE_RECORD = "crm.owner-change";
|
|
46
|
+
/**
|
|
47
|
+
* A contact's own fields beside its identity: who it is assigned to, when the CRM made and changed it, its page and
|
|
48
|
+
* its custom values. Not `person`: a records import's `person` without an entity is matched into people.
|
|
49
|
+
*/
|
|
50
|
+
export const PERSON_RECORD = "crm.person";
|
|
42
51
|
/**
|
|
43
52
|
* A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
|
|
44
53
|
* `contact:` references percent-encode it, so the `/` stays one part.
|
|
@@ -142,6 +151,21 @@ export const crmRowsOver = (context) => {
|
|
|
142
151
|
.get(accountId, externalId);
|
|
143
152
|
return row?.entity_id == null ? null : Number(row.entity_id);
|
|
144
153
|
};
|
|
154
|
+
/** Who a deal or lead went from and to, as `crm.owner-change` on it: a CRM's users are often not listed. */
|
|
155
|
+
const ownerChanged = (accountId, kind, item, change, at) => {
|
|
156
|
+
const when = epoch(item.updatedAt, at);
|
|
157
|
+
const externalId = `${kind}/${item.externalId}/${when}`;
|
|
158
|
+
const fields = { kind, ...change, at: when };
|
|
159
|
+
const inserted = database
|
|
160
|
+
.prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, updated_at) " +
|
|
161
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING id")
|
|
162
|
+
.get(accountId, OWNER_CHANGE_RECORD, externalId, JSON.stringify(fields), externalId, SOURCE, at, at);
|
|
163
|
+
if (inserted)
|
|
164
|
+
database
|
|
165
|
+
.prepare("INSERT INTO record_relations (record_id, role, target_type, target_external_id, created_at) " +
|
|
166
|
+
"VALUES (?, 'on', ?, ?, ?)")
|
|
167
|
+
.run(Number(inserted.id), kind, item.externalId, at);
|
|
168
|
+
};
|
|
145
169
|
/** The deal or lead row of `(account, external id)`; `writer` gives what another writer than CRM sync resolved. */
|
|
146
170
|
const saveItemRow = (key, accountId, kind, item, at, writer = {}) => {
|
|
147
171
|
const pipeline = pipelineOf(accountId, kind, item.pipeline);
|
|
@@ -160,9 +184,18 @@ export const crmRowsOver = (context) => {
|
|
|
160
184
|
if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
|
|
161
185
|
throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
|
|
162
186
|
const status = item.status ?? String(stage.outcome);
|
|
187
|
+
const table = TABLES[kind];
|
|
188
|
+
const held = database
|
|
189
|
+
.prepare(`SELECT id, status, closed_date, json_extract(metadata, '$.assignee') AS assignee FROM ${table} ` +
|
|
190
|
+
"WHERE account_id = ? AND external_id = ?")
|
|
191
|
+
.get(accountId, item.externalId);
|
|
192
|
+
// A CRM that gives no closed day: the owner's day it was first seen so closed, never that of a later edit (BUG-8).
|
|
163
193
|
const closed = status === "open"
|
|
164
194
|
? null
|
|
165
|
-
: (day(item.closedDate, "a closed day") ??
|
|
195
|
+
: (day(item.closedDate, "a closed day") ??
|
|
196
|
+
(held && held.status === status && held.closed_date != null
|
|
197
|
+
? String(held.closed_date)
|
|
198
|
+
: dayIn(epoch(item.updatedAt, at), timezoneOf())));
|
|
166
199
|
const deal = writer.deal !== undefined
|
|
167
200
|
? writer.deal === null
|
|
168
201
|
? undefined
|
|
@@ -196,13 +229,12 @@ export const crmRowsOver = (context) => {
|
|
|
196
229
|
created: epoch(item.createdAt, at),
|
|
197
230
|
updated: epoch(item.updatedAt, at),
|
|
198
231
|
};
|
|
199
|
-
const table = TABLES[kind];
|
|
200
|
-
const held = database
|
|
201
|
-
.prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
|
|
202
|
-
.get(accountId, item.externalId);
|
|
203
232
|
let id;
|
|
204
233
|
if (held) {
|
|
205
234
|
id = Number(held.id);
|
|
235
|
+
const owner = item.assignee === undefined ? undefined : (metadata.assignee ?? null);
|
|
236
|
+
if (owner !== undefined && owner !== (held.assignee ?? null))
|
|
237
|
+
ownerChanged(accountId, kind, item, { from: held.assignee ?? null, to: owner }, at);
|
|
206
238
|
database
|
|
207
239
|
.prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
|
|
208
240
|
"close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
|
|
@@ -61,8 +61,9 @@ export interface CrmStageMove {
|
|
|
61
61
|
stageName: string;
|
|
62
62
|
pipelineName: string;
|
|
63
63
|
}
|
|
64
|
-
/** When stage
|
|
64
|
+
/** When the stage-task rules were first set: a stage entered before then opens no task. */
|
|
65
65
|
export declare const crmStageTasksSince: (database: CacheDatabase, key: AccountKey) => number | null;
|
|
66
|
+
/** `at` stays when the rules were first set: the stage history counts from then, whenever the history arrives. */
|
|
66
67
|
export declare const saveStageMovesMark: (database: CacheDatabase, key: AccountKey, through: number, now: number) => void;
|
|
67
68
|
export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
|
|
68
69
|
export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
|
|
@@ -156,16 +156,17 @@ export const crmStageMoves = (database, key, accountId) => {
|
|
|
156
156
|
}));
|
|
157
157
|
return { moves, through };
|
|
158
158
|
};
|
|
159
|
-
/** When stage
|
|
159
|
+
/** When the stage-task rules were first set: a stage entered before then opens no task. */
|
|
160
160
|
export const crmStageTasksSince = (database, key) => {
|
|
161
161
|
const row = database
|
|
162
162
|
.prepare("SELECT at FROM store_settings WHERE key = ?")
|
|
163
163
|
.get(stageTasksMark(crmSettingKey(key, "stage-tasks")));
|
|
164
164
|
return row ? Number(row.at) : null;
|
|
165
165
|
};
|
|
166
|
+
/** `at` stays when the rules were first set: the stage history counts from then, whenever the history arrives. */
|
|
166
167
|
export const saveStageMovesMark = (database, key, through, now) => {
|
|
167
168
|
database
|
|
168
|
-
.prepare("INSERT
|
|
169
|
+
.prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
|
|
169
170
|
.run(stageTasksMark(crmSettingKey(key, "stage-tasks")), JSON.stringify(through), now);
|
|
170
171
|
};
|
|
171
172
|
export const parseCrmSettingValue = (name, value) => {
|
|
@@ -1,15 +1,35 @@
|
|
|
1
1
|
import type { CrmStageEntry } from "../../domain/crm.js";
|
|
2
|
+
import type { DealKind } from "../../domain/deals.js";
|
|
3
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
4
|
import type { AccountKey } from "../types.js";
|
|
3
5
|
import type { CrmStageMove } from "./crm-settings.js";
|
|
4
6
|
import type { StoreContext } from "./open.js";
|
|
5
7
|
export declare const STAGE_ENTRY_RECORD = "crm.stage-entry";
|
|
8
|
+
/** An entry whose deal never reached the copy is dropped after this long: the history is read this far back. */
|
|
9
|
+
export declare const STAGE_ENTRY_DAYS = 90;
|
|
10
|
+
/** One stage a deal or lead entered, from the CRM's own history (`exact`) or from the copy's diffs between syncs. */
|
|
11
|
+
export interface StageEntry {
|
|
12
|
+
itemId: number;
|
|
13
|
+
toStageId: number;
|
|
14
|
+
at: number;
|
|
15
|
+
exact: boolean;
|
|
16
|
+
}
|
|
6
17
|
/**
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
|
|
18
|
+
* Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
|
|
19
|
+
* where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
|
|
20
|
+
*/
|
|
21
|
+
export declare const stageEntriesOf: (database: CacheDatabase, kind: DealKind, filter: {
|
|
22
|
+
pipeline: number;
|
|
23
|
+
} | {
|
|
24
|
+
item: number;
|
|
25
|
+
}) => StageEntry[];
|
|
26
|
+
/**
|
|
27
|
+
* The CRM's own record of each stage a deal or lead entered, read on every sync. An entry waits for its stage task
|
|
28
|
+
* until it is handled; one on a deal the copy does not hold yet is kept, and counts once the deal arrives.
|
|
10
29
|
*/
|
|
11
30
|
export declare const crmStageEntriesOver: (context: StoreContext) => {
|
|
12
31
|
save: (key: AccountKey, entries: readonly CrmStageEntry[]) => number;
|
|
13
|
-
pending: (key: AccountKey) => CrmStageMove[];
|
|
32
|
+
pending: (key: AccountKey, since: number, at: number) => CrmStageMove[];
|
|
14
33
|
handled: (ids: readonly number[]) => void;
|
|
34
|
+
expire: (key: AccountKey) => number;
|
|
15
35
|
};
|