@wirecat/cli-core 0.630.0 → 0.631.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 +22 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/crm/cli/index.js +22 -2
- package/dist/crm/sync.d.ts +3 -1
- package/dist/crm/sync.js +5 -0
- package/dist/domain/crm.d.ts +2 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/sqlite/accounts.d.ts +7 -0
- package/dist/store/sqlite/accounts.js +13 -5
- package/dist/store/sqlite/crm-contacts.d.ts +26 -0
- package/dist/store/sqlite/crm-contacts.js +134 -0
- package/dist/store/sqlite/crm-settings.d.ts +2 -0
- package/dist/store/sqlite/crm-settings.js +5 -0
- package/dist/store/sqlite/crm.d.ts +12 -0
- package/dist/store/sqlite/crm.js +7 -2
- package/dist/store/sqlite/manifest.js +1 -0
- package/dist/store/sqlite/migrations.generated.js +15 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,28 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
|
|
|
5
5
|
minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
|
|
6
6
|
shape of this file.
|
|
7
7
|
|
|
8
|
+
## 0.631.0 — 10.11.2026
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **A CRM copy under scope `mine` keeps only its clients' contacts.** After a sync that narrowed the copy or ran with
|
|
13
|
+
`--rescan`, and finished every kind, one transaction removes each contact that no kept deal or lead of the chosen
|
|
14
|
+
users names, and that is no contact of a kept company. The person it made goes too, unless anything else is left on
|
|
15
|
+
them: another identity such as mail, a note, an alias, a mention, the owner's link decision. A contact the owner
|
|
16
|
+
linked or unlinked himself stays. People named after a contact lose an import's `null` / `null #<id>` from their
|
|
17
|
+
name; the owner's person is never renamed. The sync answer gives the counts as `contacts_removed`. Before, a
|
|
18
|
+
narrowed copy kept every contact for good: the CRM's deletion check skips contacts.
|
|
19
|
+
- **`store apply`** does the same for the contacts already stored, for the users scope `mine` keeps (`self` and
|
|
20
|
+
`unassigned`) whatever the scope is now: counts only, unless `--yes` under scope `mine`.
|
|
21
|
+
- `CrmCopies.removeContacts`.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **Saving, changing or removing a deal's or lead's link to a person no longer reads every link to a person.**
|
|
26
|
+
Store version 64 recreates version 63's person-kind triggers on deal links and on a deal owner's moves so they look
|
|
27
|
+
a deal's people up by the deal. On a store with 118k person links, removing 635 links took 15 s and now takes
|
|
28
|
+
0.4 s.
|
|
29
|
+
|
|
8
30
|
## 0.630.0 — 10.11.2026
|
|
9
31
|
|
|
10
32
|
### Added
|
|
@@ -24,12 +24,12 @@ export interface DailyArchiveTimerInput {
|
|
|
24
24
|
}
|
|
25
25
|
export declare const dailyArchiveTimer: (input: DailyArchiveTimerInput) => DailyArchiveTimer;
|
|
26
26
|
export declare const manageDailyArchiveTimer: (plan: DailyArchiveTimer, action: "install" | "start" | "stop" | "status" | "uninstall", system: Pick<ServerSystem, "platform" | "run">, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise<{
|
|
27
|
+
action?: undefined;
|
|
27
28
|
name: string;
|
|
28
29
|
installed: boolean;
|
|
29
30
|
active: boolean;
|
|
30
31
|
servicePath: string;
|
|
31
32
|
timerPath: string;
|
|
32
|
-
action?: undefined;
|
|
33
33
|
} | {
|
|
34
34
|
active?: undefined;
|
|
35
35
|
name: string;
|
package/dist/crm/cli/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import * as v from "valibot";
|
|
|
5
5
|
import { answerEntity } from "../../cli/answer-entity.js";
|
|
6
6
|
import { environmentOf, inCommandRun, outputFor, runBudgetOf } from "../../cli/context.js";
|
|
7
7
|
import { honoursDryRun } from "../../cli/dry-run-guard.js";
|
|
8
|
-
import { FETCH, LOCAL_READ, NO_EFFECTS, REMOTE_WRITE } from "../../cli/effects.js";
|
|
8
|
+
import { FETCH, LOCAL_READ, LOCAL_WRITE, NO_EFFECTS, REMOTE_WRITE } from "../../cli/effects.js";
|
|
9
9
|
import { itemOf, listOf, renderAnswer, snakeKeys, snakeKeysKeeping } from "../../cli/envelope.js";
|
|
10
10
|
import { queryTerms, termField, unfilteredQuery, withQuery } from "../../cli/list-query.js";
|
|
11
11
|
import { terminalAsker } from "../../cli/messenger/ask.js";
|
|
@@ -14,7 +14,7 @@ import { CRM_KINDS } from "../../domain/crm.js";
|
|
|
14
14
|
import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
|
|
15
15
|
import { deal as dealEntity } from "../../entities/deal.js";
|
|
16
16
|
import { count, text } from "../../entities/fields.js";
|
|
17
|
-
import { CRM_SCOPES } from "../../store/sqlite/crm-settings.js";
|
|
17
|
+
import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
|
|
18
18
|
import { crmStatus, syncCrm } from "../sync.js";
|
|
19
19
|
import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
|
|
20
20
|
import { csvFormatOption, renderCsv } from "./csv.js";
|
|
@@ -58,6 +58,13 @@ const DEAL_UNTRUSTED = [
|
|
|
58
58
|
];
|
|
59
59
|
const PIPELINE_UNTRUSTED = ["name", "stages.name"];
|
|
60
60
|
const STAGE_UNTRUSTED = ["name", "pipeline_name"];
|
|
61
|
+
const crmContactsRemoved = v.strictObject({
|
|
62
|
+
contacts: count,
|
|
63
|
+
persons: count,
|
|
64
|
+
persons_kept: count,
|
|
65
|
+
names: count,
|
|
66
|
+
});
|
|
67
|
+
const crmContactsApplied = v.strictObject({ ...crmContactsRemoved.entries, applied: v.boolean() });
|
|
61
68
|
const crmSync = v.strictObject({
|
|
62
69
|
provider: text,
|
|
63
70
|
account: text,
|
|
@@ -68,6 +75,7 @@ const crmSync = v.strictObject({
|
|
|
68
75
|
pipelines: count,
|
|
69
76
|
users: v.optional(count),
|
|
70
77
|
skipped_owner_rejected: count,
|
|
78
|
+
contacts_removed: v.optional(crmContactsRemoved),
|
|
71
79
|
synced: v.array(v.strictObject({
|
|
72
80
|
kind: v.picklist(CRM_KINDS),
|
|
73
81
|
round: v.picklist(["full", "changes"]),
|
|
@@ -251,6 +259,18 @@ const addCrmCommandsDefinition = (program, options) => {
|
|
|
251
259
|
});
|
|
252
260
|
});
|
|
253
261
|
});
|
|
262
|
+
example(answerEntity(annotate(store.command("apply"), { effects: LOCAL_WRITE }), "crm_contacts_removed", crmContactsApplied).description("apply scope mine to the contacts already stored: remove those no deal or lead of the chosen users and no " +
|
|
263
|
+
"kept company names, and the people they leave empty; counts only unless --yes, under scope all too. A " +
|
|
264
|
+
"sync that narrows the scope, or sync --rescan under mine, does this itself"), "store apply", "store apply --yes").action(async (_opts, command) => {
|
|
265
|
+
const yes = command.optsWithGlobals().yes === true;
|
|
266
|
+
await within(command, async (run) => {
|
|
267
|
+
const scope = crmSettingKey(run.account, "scope");
|
|
268
|
+
if (yes && (await run.store.crm.scope(run.account)).mode !== "mine")
|
|
269
|
+
throw new CliError("validation_error", `scope is all, so a sync would copy these contacts again: set ${scope} to mine first`, { setting: scope });
|
|
270
|
+
const removed = await run.store.crm.removeContacts(run.account, { before: now(), dryRun: !yes });
|
|
271
|
+
return itemOf(snakeKeys({ ...removed, applied: yes }));
|
|
272
|
+
});
|
|
273
|
+
});
|
|
254
274
|
const items = (kind) => {
|
|
255
275
|
const plural = `${kind}s`;
|
|
256
276
|
const query = kind === "deal" ? DEALS_QUERY : LEADS_QUERY;
|
package/dist/crm/sync.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type BudgetStop, type RunBudget } from "../background/budget.js";
|
|
2
2
|
import { type CrmKind, type CrmScope } from "../domain/crm.js";
|
|
3
|
-
import type { CrmRelationIssue, CrmSkipped } from "../store/sqlite/crm.js";
|
|
3
|
+
import type { CrmContactsRemoved, CrmRelationIssue, CrmSkipped } from "../store/sqlite/crm.js";
|
|
4
4
|
import type { MessageStore } from "../store/store.js";
|
|
5
5
|
import type { AccountKey } from "../store/types.js";
|
|
6
6
|
import type { CrmGap, CrmSource } from "./source.js";
|
|
@@ -88,6 +88,8 @@ export interface CrmSyncReport {
|
|
|
88
88
|
scope: CrmScope;
|
|
89
89
|
/** Relationships left out because the owner removed or rejected that very one, role included. */
|
|
90
90
|
skippedOwnerRejected: number;
|
|
91
|
+
/** After a complete run that narrowed the copy or listed it again under `mine`: the contacts outside it, removed. */
|
|
92
|
+
contactsRemoved?: CrmContactsRemoved;
|
|
91
93
|
synced: CrmSyncResult[];
|
|
92
94
|
issues: CrmSyncIssue[];
|
|
93
95
|
/** Every kind finished its round and none failed. */
|
package/dist/crm/sync.js
CHANGED
|
@@ -524,6 +524,11 @@ export const syncCrm = async (source, store, account, options = {}) => {
|
|
|
524
524
|
}
|
|
525
525
|
// A relationship held back for an end a later page or kind brought is written now; it costs no request.
|
|
526
526
|
run.droppedPending += (await store.crm.retryPending(account)).dropped;
|
|
527
|
+
const narrowed = report.synced.some((one) => one.outOfScope > 0);
|
|
528
|
+
const whole = report.synced.every((one) => one.state === "complete" && one.error === undefined && !one.held && one.pass !== "held");
|
|
529
|
+
// Contacts have no scope of their own and no deletion check: they leave with the last deal or lead naming them.
|
|
530
|
+
if (scope.mode === "mine" && (options.rescan || narrowed) && whole && !stopped && kinds.includes("person"))
|
|
531
|
+
report.contactsRemoved = await store.crm.removeContacts(account, { users: scopeIds(scope) ?? [], before: now });
|
|
527
532
|
if (run.unlistedUsers)
|
|
528
533
|
report.issues.push({
|
|
529
534
|
kind: "deal",
|
package/dist/domain/crm.d.ts
CHANGED
|
@@ -155,7 +155,8 @@ export type CrmScopeSetting = {
|
|
|
155
155
|
};
|
|
156
156
|
/**
|
|
157
157
|
* Which deals and leads a sync copies: all, or those with no assignee or assigned to the sign-in's own user (`self`)
|
|
158
|
-
* or to one of `also`.
|
|
158
|
+
* or to one of `also`. Companies and contacts are what the source lists; under `mine`, a contact no kept deal, lead or
|
|
159
|
+
* company names is removed after a sync that narrowed the copy or listed it again. Ids are normalised (`normalCrmUserId`).
|
|
159
160
|
*/
|
|
160
161
|
export type CrmScope = {
|
|
161
162
|
mode: "all";
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/dist/store/index.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
|
|
|
48
48
|
export type { CatalogActor, CatalogEntry, CatalogInput, CatalogQuery, CatalogStore } from "./sqlite/catalog.js";
|
|
49
49
|
export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
50
50
|
export type { ChatMetadata } from "./sqlite/chats.js";
|
|
51
|
-
export { type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId } from "./sqlite/crm.js";
|
|
51
|
+
export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type CrmSaved, type CrmSkipped, crmIdentityId, } from "./sqlite/crm.js";
|
|
52
52
|
export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, crmSettingKey, } from "./sqlite/crm-settings.js";
|
|
53
53
|
export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
|
|
54
54
|
export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
|
package/dist/store/index.js
CHANGED
|
@@ -31,7 +31,7 @@ export { backfillNormalized, pendingNormalization } from "./sqlite/backfill.js";
|
|
|
31
31
|
export { baseSettingKey } from "./sqlite/base-suggest.js";
|
|
32
32
|
export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
|
|
33
33
|
export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
34
|
-
export { crmIdentityId } from "./sqlite/crm.js";
|
|
34
|
+
export { crmIdentityId, } from "./sqlite/crm.js";
|
|
35
35
|
export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
|
|
36
36
|
export { EVENT_FIELDS, } from "./sqlite/event-search.js";
|
|
37
37
|
export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
|
|
@@ -11,6 +11,13 @@ export declare const storedAccounts: ({ orm }: StoreContext) => StoredAccount[];
|
|
|
11
11
|
export declare const storedAccount: ({ orm }: StoreContext, { provider, account }: AccountKey) => StoredAccount;
|
|
12
12
|
/** Everything the account holds, children before parents: the foreign keys are enforced. */
|
|
13
13
|
export declare const purgeAccount: ({ orm, database, now }: StoreContext, accountKey: number) => void;
|
|
14
|
+
/** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
|
|
15
|
+
export declare const OWN: Set<string>;
|
|
16
|
+
/**
|
|
17
|
+
* Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
|
|
18
|
+
* `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
|
|
19
|
+
*/
|
|
20
|
+
export declare const referencesTo: (database: CacheDatabase, table: "identities" | "persons", skip: Set<string>, among?: string) => string;
|
|
14
21
|
export declare const unreferenced: (database: CacheDatabase, table: "identities") => Set<number>;
|
|
15
22
|
/**
|
|
16
23
|
* People only the purged account had seen go with it. An identity stays while anything else points at it
|
|
@@ -149,17 +149,25 @@ export const purgeAccount = ({ orm, database, now }, accountKey) => {
|
|
|
149
149
|
dropUnusedVectors(database, hashes);
|
|
150
150
|
};
|
|
151
151
|
/** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
|
|
152
|
-
const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
|
|
153
|
-
/**
|
|
154
|
-
|
|
152
|
+
export const OWN = new Set(["identity_links", "identity_link_events", "identity_revisions"]);
|
|
153
|
+
/**
|
|
154
|
+
* Every row that points at `table`: foreign keys and `<name>_type` pointers, read from the store so a new one counts.
|
|
155
|
+
* `among`, a subquery of ids, limits each arm to them, so each reads its index rather than its whole table.
|
|
156
|
+
*/
|
|
157
|
+
export const referencesTo = (database, table, skip, among) => {
|
|
158
|
+
const within = (column) => (among === undefined ? "" : ` ${column} IN (${among})`);
|
|
155
159
|
const keys = database
|
|
156
160
|
.prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
|
|
157
161
|
WHERE m.type = 'table' AND f."table" = ?`)
|
|
158
162
|
.all(table)
|
|
159
163
|
.filter((row) => !skip.has(String(row.tbl)))
|
|
160
|
-
.map((row) =>
|
|
164
|
+
.map((row) => {
|
|
165
|
+
const column = `"${String(row.col)}"`;
|
|
166
|
+
return `SELECT ${column} AS id FROM "${String(row.tbl)}"${among === undefined ? "" : ` WHERE${within(column)}`}`;
|
|
167
|
+
});
|
|
161
168
|
const type = table === "identities" ? "identity" : "person";
|
|
162
|
-
const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'`
|
|
169
|
+
const pointers = pointerPairs(database).map(({ table: tbl, pointer }) => `SELECT ${pointer}_id AS id FROM "${tbl}" WHERE ${pointer}_type = '${type}'` +
|
|
170
|
+
(among === undefined ? "" : ` AND${within(`${pointer}_id`)}`));
|
|
163
171
|
return [...keys, ...pointers].join(" UNION ");
|
|
164
172
|
};
|
|
165
173
|
export const unreferenced = (database, table) => new Set(database
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AccountKey } from "../types.js";
|
|
2
|
+
import type { StoreContext } from "./open.js";
|
|
3
|
+
/** What removing a CRM account's contacts outside its scope did, or would do. */
|
|
4
|
+
export interface CrmContactsRemoved {
|
|
5
|
+
/** Contacts no kept deal, lead or company names, removed with their link to a person. */
|
|
6
|
+
contacts: number;
|
|
7
|
+
/** People those contacts made, deleted because nothing else was left on them. */
|
|
8
|
+
persons: number;
|
|
9
|
+
/** People those contacts were on that stay: another identity, a note, an alias, the owner's decision, a mention. */
|
|
10
|
+
personsKept: number;
|
|
11
|
+
/** People whose name still carried a CRM import's `null #<id>`, given the name without it. */
|
|
12
|
+
names: number;
|
|
13
|
+
}
|
|
14
|
+
export declare const withoutPlaceholder: (name: string) => string | null;
|
|
15
|
+
/**
|
|
16
|
+
* Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
|
|
17
|
+
* `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
|
|
18
|
+
* about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
|
|
19
|
+
* its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
|
|
20
|
+
* after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
|
|
21
|
+
*/
|
|
22
|
+
export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
|
|
23
|
+
users?: readonly string[];
|
|
24
|
+
before: number;
|
|
25
|
+
dryRun?: boolean;
|
|
26
|
+
}) => CrmContactsRemoved;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { findAccountPk, OWN, referencesTo } from "./accounts.js";
|
|
2
|
+
import { crmAccountPrefix, crmIdentityId } from "./crm-rows.js";
|
|
3
|
+
import { write } from "./transaction.js";
|
|
4
|
+
/** A CRM import can leave `null` or `null #<id>` in a name field; no person is called that. */
|
|
5
|
+
const PLACEHOLDER = /(?:^|\s)null(?:\s+#\d+)?(?=\s|$)/gi;
|
|
6
|
+
export const withoutPlaceholder = (name) => name.replace(PLACEHOLDER, " ").replace(/\s+/g, " ").trim() || null;
|
|
7
|
+
class DryRun extends Error {
|
|
8
|
+
counts;
|
|
9
|
+
constructor(counts) {
|
|
10
|
+
super("dry run");
|
|
11
|
+
this.counts = counts;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
|
|
15
|
+
/**
|
|
16
|
+
* Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
|
|
17
|
+
* `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
|
|
18
|
+
* about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
|
|
19
|
+
* its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
|
|
20
|
+
* after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
|
|
21
|
+
*/
|
|
22
|
+
export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
|
|
23
|
+
const { database } = context;
|
|
24
|
+
const accountId = findAccountPk(context, key);
|
|
25
|
+
if (accountId === undefined)
|
|
26
|
+
return NONE;
|
|
27
|
+
const prefix = `${crmAccountPrefix(key)}contact/`;
|
|
28
|
+
const contactOf = "i.provider = ? AND substr(i.external_id, 1, ?) = ?";
|
|
29
|
+
const contact = [key.provider, prefix.length, prefix];
|
|
30
|
+
const inScope = (item) => users === undefined
|
|
31
|
+
? ""
|
|
32
|
+
: `AND (json_extract(${item}.metadata, '$.assignee') IS NULL OR ` +
|
|
33
|
+
`json_extract(${item}.metadata, '$.assignee') IN (SELECT id FROM temp.crm_scope))`;
|
|
34
|
+
const named = (table, type) => `EXISTS (SELECT 1 FROM links k JOIN ${table} d ON d.id = k.from_id WHERE k.to_type = 'person' ` +
|
|
35
|
+
`AND k.to_id = l.person_id AND k.from_type = '${type}' AND k.source = 'crm' AND k.role IS NOT 'owner' ` +
|
|
36
|
+
`AND k.deleted_at IS NULL AND d.account_id = ${accountId} AND d.deleted_at IS NULL ${inScope("d")})`;
|
|
37
|
+
const counted = () => {
|
|
38
|
+
for (const table of ["crm_scope", "crm_gone", "crm_persons", "crm_names", "crm_proposed"])
|
|
39
|
+
database.exec(`DROP TABLE IF EXISTS temp.${table}`);
|
|
40
|
+
database.exec("CREATE TEMP TABLE crm_scope (id TEXT PRIMARY KEY)");
|
|
41
|
+
database.exec("CREATE TEMP TABLE crm_gone (id INTEGER PRIMARY KEY, person INTEGER)");
|
|
42
|
+
database.exec("CREATE TEMP TABLE crm_persons (id INTEGER PRIMARY KEY)");
|
|
43
|
+
database.exec("CREATE TEMP TABLE crm_names (id INTEGER PRIMARY KEY, name TEXT)");
|
|
44
|
+
database.exec("CREATE TEMP TABLE crm_proposed (ref TEXT PRIMARY KEY, decided INTEGER NOT NULL)");
|
|
45
|
+
database
|
|
46
|
+
.prepare("INSERT INTO temp.crm_scope SELECT DISTINCT value FROM json_each(?)")
|
|
47
|
+
.run(JSON.stringify((users ?? []).map((id) => crmIdentityId(key, id, "user"))));
|
|
48
|
+
// An identity link the owner approved or rejected is his decision about this contact; one only proposed is not.
|
|
49
|
+
database.exec("INSERT INTO temp.crm_proposed SELECT ref, max(decided) FROM (" +
|
|
50
|
+
"SELECT json_extract(payload, '$.identity') AS ref, status <> 'proposed' AS decided FROM proposed_actions " +
|
|
51
|
+
"WHERE kind = 'identity_link' UNION ALL SELECT json_extract(payload, '$.with'), status <> 'proposed' " +
|
|
52
|
+
"FROM proposed_actions WHERE kind = 'identity_link') WHERE ref IS NOT NULL GROUP BY ref");
|
|
53
|
+
const identityRefs = referencesTo(database, "identities", new Set([...OWN, "account_identities", "involvements"]), "SELECT id FROM temp.crm_gone");
|
|
54
|
+
database
|
|
55
|
+
.prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
|
|
56
|
+
`LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
|
|
57
|
+
"AND i.created_at < ? AND i.updated_at < ? " +
|
|
58
|
+
`AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
|
|
59
|
+
"AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
|
|
60
|
+
"AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
|
|
61
|
+
"AND +k.to_type = 'organization' AND k.kind = 'member-of' AND k.role = 'contact' AND k.source = 'crm' " +
|
|
62
|
+
`AND k.deleted_at IS NULL AND r.account_id = ${accountId} AND r.type = 'organization' ` +
|
|
63
|
+
"AND r.deleted_at IS NULL) " +
|
|
64
|
+
"AND NOT EXISTS (SELECT 1 FROM identity_link_events e WHERE e.identity_id = i.id AND e.author = 'owner') " +
|
|
65
|
+
"AND NOT EXISTS (SELECT 1 FROM temp.crm_proposed c WHERE c.decided AND c.ref = i.provider || ':' || " +
|
|
66
|
+
"i.external_id)")
|
|
67
|
+
.run(...contact, before, before);
|
|
68
|
+
database.exec(`DELETE FROM temp.crm_gone WHERE id IN (${identityRefs})`);
|
|
69
|
+
// A same-email join left the contact's first person empty; it goes too, unless something points at it.
|
|
70
|
+
database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT person FROM temp.crm_gone WHERE person IS NOT NULL");
|
|
71
|
+
database.exec("INSERT OR IGNORE INTO temp.crm_persons SELECT from_person_id FROM identity_link_events " +
|
|
72
|
+
"WHERE identity_id IN (SELECT id FROM temp.crm_gone) AND from_person_id IS NOT NULL");
|
|
73
|
+
const names = database
|
|
74
|
+
.prepare("SELECT DISTINCT p.id, p.name, i.name AS was FROM identities i JOIN identity_links l ON l.identity_id = i.id " +
|
|
75
|
+
`JOIN persons p ON p.id = l.person_id WHERE ${contactOf} AND p.owner = 0 AND p.name LIKE '%null%'`)
|
|
76
|
+
.all(...contact)
|
|
77
|
+
.flatMap((row) => {
|
|
78
|
+
const name = String(row.name);
|
|
79
|
+
const clean = withoutPlaceholder(name);
|
|
80
|
+
const was = typeof row.was === "string" ? withoutPlaceholder(row.was) : null;
|
|
81
|
+
return clean !== name && clean === was ? [{ id: Number(row.id), name: clean }] : [];
|
|
82
|
+
});
|
|
83
|
+
database
|
|
84
|
+
.prepare("INSERT OR IGNORE INTO temp.crm_names SELECT json_extract(value, '$.id'), json_extract(value, '$.name') " +
|
|
85
|
+
"FROM json_each(?)")
|
|
86
|
+
.run(JSON.stringify(names));
|
|
87
|
+
const gone = "(SELECT id FROM temp.crm_gone)";
|
|
88
|
+
const persons = "(SELECT id FROM temp.crm_persons)";
|
|
89
|
+
database
|
|
90
|
+
.prepare(`DELETE FROM links WHERE source = 'crm' AND account_id = ? AND ((to_type = 'person' AND to_id IN ${persons} ` +
|
|
91
|
+
"AND from_type IN ('deal', 'lead') AND role IS NOT 'owner') OR (from_type = 'person' " +
|
|
92
|
+
`AND from_id IN ${persons} AND kind = 'member-of' AND role = 'contact'))`)
|
|
93
|
+
.run(accountId);
|
|
94
|
+
database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
|
|
95
|
+
`json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
|
|
96
|
+
`OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
|
|
97
|
+
for (const table of ["identity_revisions", "identity_link_events", "identity_links", "account_identities"])
|
|
98
|
+
database.exec(`DELETE FROM ${table} WHERE identity_id IN ${gone}`);
|
|
99
|
+
const contacts = database.prepare(`DELETE FROM identities WHERE id IN ${gone}`).run().changes;
|
|
100
|
+
// Involvements are worked out again from what is left; they keep no one.
|
|
101
|
+
const personRefs = referencesTo(database, "persons", new Set(["identity_links", "involvements"]), "SELECT id FROM temp.crm_persons");
|
|
102
|
+
// A proposal names its people in its payload: deleting one would leave the owner's answer about nobody.
|
|
103
|
+
const proposed = "SELECT CAST(substr(value, 8) AS INTEGER) AS id FROM proposed_actions, json_each(json_array(" +
|
|
104
|
+
"json_extract(payload, '$.from'), json_extract(payload, '$.to'))) WHERE value LIKE 'person:%' " +
|
|
105
|
+
"UNION SELECT CAST(value AS INTEGER) FROM proposed_actions, json_each(payload, '$.persons') " +
|
|
106
|
+
"WHERE json_type(payload, '$.persons') = 'array'";
|
|
107
|
+
database.exec(`DELETE FROM temp.crm_persons WHERE id IN (SELECT id FROM persons WHERE owner <> 0) ` +
|
|
108
|
+
"OR id IN (SELECT person_id FROM identity_links) " +
|
|
109
|
+
`OR id IN (${personRefs}) OR id IN (${proposed})`);
|
|
110
|
+
database.exec(`DELETE FROM involvements WHERE person_id IN ${persons}`);
|
|
111
|
+
const deleted = database.prepare(`DELETE FROM persons WHERE id IN ${persons}`).run().changes;
|
|
112
|
+
const personsKept = Number(database
|
|
113
|
+
.prepare("SELECT count(DISTINCT person) AS n FROM temp.crm_gone WHERE person IN (SELECT id FROM persons)")
|
|
114
|
+
.get()?.n);
|
|
115
|
+
const renamed = database
|
|
116
|
+
.prepare("UPDATE persons SET name = (SELECT name FROM temp.crm_names n WHERE n.id = persons.id), updated_at = ? " +
|
|
117
|
+
"WHERE id IN (SELECT id FROM temp.crm_names)")
|
|
118
|
+
.run(context.now()).changes;
|
|
119
|
+
return { contacts, persons: deleted, personsKept, names: renamed };
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
return write(database, () => {
|
|
123
|
+
const counts = counted();
|
|
124
|
+
if (dryRun)
|
|
125
|
+
throw new DryRun(counts);
|
|
126
|
+
return counts;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (error instanceof DryRun)
|
|
131
|
+
return error.counts;
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
@@ -23,6 +23,8 @@ export declare const crmLinkMode: (database: CacheDatabase, key: AccountKey) =>
|
|
|
23
23
|
export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
|
|
24
24
|
/** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
|
|
25
25
|
export declare const crmScope: (database: CacheDatabase, key: AccountKey) => CrmScopeSetting;
|
|
26
|
+
/** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
|
|
27
|
+
export declare const crmScopeUsers: (database: CacheDatabase, key: AccountKey) => string[];
|
|
26
28
|
/**
|
|
27
29
|
* `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
|
|
28
30
|
* `company-types`: `TYPE=meaning` pairs, comma-separated.
|
|
@@ -53,6 +53,11 @@ const picked = (name, text, values) => {
|
|
|
53
53
|
throw new CliError("validation_error", `a CRM account's ${name} setting is ${values.join(" or ")}`);
|
|
54
54
|
return text;
|
|
55
55
|
};
|
|
56
|
+
/** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
|
|
57
|
+
export const crmScopeUsers = (database, key) => {
|
|
58
|
+
const self = crmOwnUser(database, key);
|
|
59
|
+
return [...new Set([...(self ? [self] : []), ...userIds(stored(database, crmSettingKey(key, "unassigned")))])];
|
|
60
|
+
};
|
|
56
61
|
/**
|
|
57
62
|
* `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
|
|
58
63
|
* `company-types`: `TYPE=meaning` pairs, comma-separated.
|
|
@@ -2,6 +2,7 @@ import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type Crm
|
|
|
2
2
|
import { type DealKind } from "../../domain/deals.js";
|
|
3
3
|
import type { AccountPeople } from "../people.js";
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
|
+
import { type CrmContactsRemoved } from "./crm-contacts.js";
|
|
5
6
|
import { type CrmSkipped } from "./crm-rows.js";
|
|
6
7
|
import type { StoreContext } from "./open.js";
|
|
7
8
|
/**
|
|
@@ -88,10 +89,21 @@ export interface CrmCopies {
|
|
|
88
89
|
removeOutOfScope(key: AccountKey, kind: DealKind, userIds: readonly string[], options?: {
|
|
89
90
|
dryRun?: boolean;
|
|
90
91
|
}): Promise<number>;
|
|
92
|
+
/**
|
|
93
|
+
* Removes the contacts no kept deal, lead or company names, and the people they leave empty; see
|
|
94
|
+
* `removeCrmContacts`. A deal or lead assigned to a user outside `users` counts as gone; without `users`, outside
|
|
95
|
+
* those scope mine keeps (`self` and `unassigned`), whatever the scope is now. `dryRun` only counts.
|
|
96
|
+
*/
|
|
97
|
+
removeContacts(key: AccountKey, options: {
|
|
98
|
+
users?: readonly string[];
|
|
99
|
+
before: number;
|
|
100
|
+
dryRun?: boolean;
|
|
101
|
+
}): Promise<CrmContactsRemoved>;
|
|
91
102
|
/** How many of the kind the account holds, not deleted; every contact it ever saved. */
|
|
92
103
|
count(key: AccountKey, kind: CrmKind): Promise<number>;
|
|
93
104
|
/** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */
|
|
94
105
|
refOf(key: AccountKey, kind: DealKind, externalId: string): Promise<string | null>;
|
|
95
106
|
}
|
|
107
|
+
export type { CrmContactsRemoved } from "./crm-contacts.js";
|
|
96
108
|
export { type CrmSkipped, crmIdentityId, crmRowsOver, type ItemWriter } from "./crm-rows.js";
|
|
97
109
|
export declare const crmCopiesOver: (context: StoreContext, people: AccountPeople) => CrmCopies;
|
package/dist/store/sqlite/crm.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
-
import { isItemKind, } from "../../domain/crm.js";
|
|
2
|
+
import { isItemKind, normalCrmUserId, } from "../../domain/crm.js";
|
|
3
3
|
import { DEAL_ROLES } from "../../domain/deals.js";
|
|
4
4
|
import { recordFingerprint } from "../../domain/records.js";
|
|
5
5
|
import { accountPk, findAccountPk } from "./accounts.js";
|
|
6
6
|
import { suggestBaseStages } from "./base-suggest.js";
|
|
7
|
+
import { removeCrmContacts } from "./crm-contacts.js";
|
|
7
8
|
import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
|
|
8
|
-
import { crmCompanyTypes, crmOwnUser, crmScope, crmSettingKey, saveCrmSetting } from "./crm-settings.js";
|
|
9
|
+
import { crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, saveCrmSetting } from "./crm-settings.js";
|
|
9
10
|
import { syncReportedIn } from "./reported-relations.js";
|
|
10
11
|
import { clearState, syncStateOf, writeState } from "./sync.js";
|
|
11
12
|
import { write } from "./transaction.js";
|
|
@@ -594,6 +595,10 @@ export const crmCopiesOver = (context, people) => {
|
|
|
594
595
|
.filter((row) => row.assignee != null && !keep.has(String(row.assignee)));
|
|
595
596
|
return dryRun ? rows.length : markDeleted(key, kind, rows);
|
|
596
597
|
}),
|
|
598
|
+
removeContacts: async (key, options) => removeCrmContacts(context, key, {
|
|
599
|
+
...options,
|
|
600
|
+
users: options.users ?? crmScopeUsers(database, key).map(normalCrmUserId),
|
|
601
|
+
}),
|
|
597
602
|
count: async (key, kind) => kind === "person"
|
|
598
603
|
? Number(database
|
|
599
604
|
.prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
|
|
@@ -128,6 +128,7 @@ export const MANIFEST = [
|
|
|
128
128
|
{ name: "20261110005159_version-62-person-kinds", version: 62, minCompatible: 56 },
|
|
129
129
|
{ name: "20261110005200_version-62-person-kinds-triggers", version: 62, minCompatible: 56 },
|
|
130
130
|
{ name: "20261110020704_version-63-people-ties-messages-crm", version: 63, minCompatible: 56 },
|
|
131
|
+
{ name: "20261110084658_version-64-deal-link-triggers", version: 64, minCompatible: 56 },
|
|
131
132
|
];
|
|
132
133
|
export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
|
|
133
134
|
const migrations = [];
|
|
@@ -1306,5 +1306,20 @@ export const GENERATED = [
|
|
|
1306
1306
|
"CREATE TRIGGER person_kind_deal_owner_person_au AFTER UPDATE OF owner ON persons\nWHEN OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND d.to_type = 'person' WHERE o.to_type = 'person' AND o.role = 'owner' AND o.from_type IN ('deal', 'lead') AND (o.to_id = NEW.id OR o.to_id IN (SELECT e.from_person_id FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id WHERE l.person_id = NEW.id)));\nEND;",
|
|
1307
1307
|
"CREATE TRIGGER person_kind_message_outgoing_au AFTER UPDATE OF outgoing ON messages\nWHEN OLD.outgoing IS NOT NEW.outgoing BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT person_id FROM identity_links WHERE identity_id = NEW.sender_identity_id);\nEND;"
|
|
1308
1308
|
]
|
|
1309
|
+
},
|
|
1310
|
+
{
|
|
1311
|
+
"name": "20261110084658_version-64-deal-link-triggers",
|
|
1312
|
+
"statements": [
|
|
1313
|
+
"DROP TRIGGER IF EXISTS person_kind_deal_link_ai;",
|
|
1314
|
+
"CREATE TRIGGER person_kind_deal_link_ai AFTER INSERT ON links\nWHEN NEW.from_type IN ('deal', 'lead') AND NEW.kind = 'related-to' AND NEW.to_type = 'person' BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = NEW.from_type AND d.from_id = NEW.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' UNION SELECT NEW.to_id);\nEND;",
|
|
1315
|
+
"DROP TRIGGER IF EXISTS person_kind_deal_link_ad;",
|
|
1316
|
+
"CREATE TRIGGER person_kind_deal_link_ad AFTER DELETE ON links\nWHEN OLD.from_type IN ('deal', 'lead') AND OLD.kind = 'related-to' AND OLD.to_type = 'person' BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = OLD.from_type AND d.from_id = OLD.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' UNION SELECT OLD.to_id);\nEND;",
|
|
1317
|
+
"DROP TRIGGER IF EXISTS person_kind_deal_link_au;",
|
|
1318
|
+
"CREATE TRIGGER person_kind_deal_link_au AFTER UPDATE OF from_type, from_id, to_type, to_id, kind, role, deleted_at ON links\nWHEN (OLD.from_type IN ('deal', 'lead') AND OLD.kind = 'related-to' AND OLD.to_type = 'person' OR NEW.from_type IN ('deal', 'lead') AND NEW.kind = 'related-to' AND NEW.to_type = 'person')\n AND (OLD.to_id IS NOT NEW.to_id OR OLD.role IS NOT NEW.role OR OLD.deleted_at IS NOT NEW.deleted_at\n OR OLD.from_id IS NOT NEW.from_id OR OLD.from_type IS NOT NEW.from_type OR OLD.kind IS NOT NEW.kind OR OLD.to_type IS NOT NEW.to_type) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = OLD.from_type AND d.from_id = OLD.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' UNION SELECT OLD.to_id);\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links d WHERE d.from_type = NEW.from_type AND d.from_id = NEW.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' UNION SELECT NEW.to_id);\nEND;",
|
|
1319
|
+
"DROP TRIGGER IF EXISTS person_kind_deal_owner_moved_au;",
|
|
1320
|
+
"CREATE TRIGGER person_kind_deal_owner_moved_au AFTER UPDATE OF person_id ON identity_links\nWHEN OLD.person_id IS NOT NEW.person_id AND EXISTS (SELECT 1 FROM links o WHERE o.to_type = 'person' AND o.to_id IN (SELECT OLD.person_id UNION SELECT NEW.person_id UNION SELECT e.from_person_id FROM identity_link_events e WHERE e.identity_id = NEW.identity_id) AND o.role = 'owner' AND o.from_type IN ('deal', 'lead')) BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' WHERE o.to_type = 'person' AND o.to_id IN (SELECT OLD.person_id UNION SELECT NEW.person_id UNION SELECT e.from_person_id FROM identity_link_events e WHERE e.identity_id = NEW.identity_id) AND o.role = 'owner' AND o.from_type IN ('deal', 'lead'));\nEND;",
|
|
1321
|
+
"DROP TRIGGER IF EXISTS person_kind_deal_owner_person_au;",
|
|
1322
|
+
"CREATE TRIGGER person_kind_deal_owner_person_au AFTER UPDATE OF owner ON persons\nWHEN OLD.owner IS NOT NEW.owner BEGIN\n UPDATE persons SET kind = NULL WHERE kind IS NOT NULL AND id IN (SELECT d.to_id FROM links o JOIN links d ON d.from_type = o.from_type AND d.from_id = o.from_id AND d.kind = 'related-to' AND +d.to_type = 'person' WHERE o.to_type = 'person' AND o.role = 'owner' AND o.from_type IN ('deal', 'lead') AND o.to_id IN (SELECT NEW.id UNION SELECT e.from_person_id FROM identity_link_events e JOIN identity_links l ON l.identity_id = e.identity_id WHERE l.person_id = NEW.id));\nEND;"
|
|
1323
|
+
]
|
|
1309
1324
|
}
|
|
1310
1325
|
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.631.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"type": "module",
|
|
16
16
|
"wirecat": {
|
|
17
17
|
"store": {
|
|
18
|
-
"speaks":
|
|
18
|
+
"speaks": 64,
|
|
19
19
|
"minCompatible": 56
|
|
20
20
|
}
|
|
21
21
|
},
|