@wirecat/cli-core 0.630.0 → 0.632.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 +59 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/messenger/context.d.ts +2 -0
- package/dist/cli/messenger/reply-stats-command.js +1 -1
- package/dist/cli/messenger/serve-relay.d.ts +1 -0
- package/dist/cli/messenger/stats-answers.d.ts +5 -2
- package/dist/cli/messenger/stats-answers.js +8 -2
- package/dist/cli/messenger/tasks-command.js +5 -3
- 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/domain/test-data.d.ts +15 -0
- package/dist/domain/test-data.js +18 -0
- package/dist/entities/chat-stats.d.ts +2 -0
- package/dist/entities/chat-stats.js +2 -0
- package/dist/entities/index.d.ts +1 -0
- package/dist/errors/reasons.js +9 -0
- package/dist/kit/seed.js +6 -7
- package/dist/search/lucene/registry.js +11 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/proposals/kinds/identity-split.d.ts +4 -0
- package/dist/services/proposals/kinds/identity-split.js +65 -0
- package/dist/services/proposals/registry.js +2 -0
- package/dist/services/reply-stats.js +11 -3
- package/dist/services/task-stats.d.ts +7 -2
- package/dist/services/task-stats.js +53 -20
- package/dist/services/tasks.d.ts +1 -0
- package/dist/services/tasks.js +16 -4
- package/dist/store/decisions.js +3 -1
- package/dist/store/drivers/bun-sqlite.js +2 -0
- package/dist/store/drivers/node-sqlite.js +2 -0
- package/dist/store/identity-splits.d.ts +60 -0
- package/dist/store/identity-splits.js +5 -0
- package/dist/store/index.d.ts +3 -1
- package/dist/store/index.js +3 -1
- package/dist/store/people.d.ts +23 -0
- package/dist/store/people.js +6 -0
- package/dist/store/sqlite/accounts.d.ts +7 -0
- package/dist/store/sqlite/accounts.js +17 -5
- package/dist/store/sqlite/crm-contacts.d.ts +26 -0
- package/dist/store/sqlite/crm-contacts.js +138 -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/identity-link-rows.d.ts +5 -0
- package/dist/store/sqlite/identity-link-rows.js +5 -3
- package/dist/store/sqlite/identity-split-proposals.d.ts +29 -0
- package/dist/store/sqlite/identity-split-proposals.js +195 -0
- package/dist/store/sqlite/lucene-fields.js +3 -0
- package/dist/store/sqlite/manifest.js +1 -0
- package/dist/store/sqlite/migrations.generated.js +15 -0
- package/dist/store/sqlite/person-doubts.d.ts +36 -0
- package/dist/store/sqlite/person-doubts.js +229 -0
- package/dist/store/sqlite/proposed-actions.js +6 -0
- package/dist/store/sqlite/reply-times.d.ts +3 -1
- package/dist/store/sqlite/reply-times.js +11 -6
- package/package.json +2 -2
|
@@ -0,0 +1,138 @@
|
|
|
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
|
+
// A split names the identities that would leave, an address among them: it goes with them, whatever its status.
|
|
95
|
+
database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_split' AND EXISTS (SELECT 1 FROM json_each(payload, " +
|
|
96
|
+
`'$.identities') WHERE value IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
|
|
97
|
+
database.exec("DELETE FROM proposed_actions WHERE kind = 'identity_link' AND status = 'proposed' AND (" +
|
|
98
|
+
`json_extract(payload, '$.identity') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}) ` +
|
|
99
|
+
`OR json_extract(payload, '$.with') IN (SELECT provider || ':' || external_id FROM identities WHERE id IN ${gone}))`);
|
|
100
|
+
for (const table of ["identity_revisions", "identity_link_events", "identity_links", "account_identities"])
|
|
101
|
+
database.exec(`DELETE FROM ${table} WHERE identity_id IN ${gone}`);
|
|
102
|
+
const contacts = database.prepare(`DELETE FROM identities WHERE id IN ${gone}`).run().changes;
|
|
103
|
+
// Involvements are worked out again from what is left; they keep no one.
|
|
104
|
+
const personRefs = referencesTo(database, "persons", new Set(["identity_links", "involvements"]), "SELECT id FROM temp.crm_persons");
|
|
105
|
+
// A proposal names its people in its payload: deleting one would leave the owner's answer about nobody.
|
|
106
|
+
const proposed = "SELECT CAST(substr(value, 8) AS INTEGER) AS id FROM proposed_actions, json_each(json_array(" +
|
|
107
|
+
"json_extract(payload, '$.from'), json_extract(payload, '$.to'))) WHERE value LIKE 'person:%' " +
|
|
108
|
+
"UNION SELECT CAST(value AS INTEGER) FROM proposed_actions, json_each(payload, '$.persons') " +
|
|
109
|
+
"WHERE json_type(payload, '$.persons') = 'array' " +
|
|
110
|
+
"UNION SELECT CAST(json_extract(payload, '$.person') AS INTEGER) FROM proposed_actions WHERE kind = 'identity_split'";
|
|
111
|
+
database.exec(`DELETE FROM temp.crm_persons WHERE id IN (SELECT id FROM persons WHERE owner <> 0) ` +
|
|
112
|
+
"OR id IN (SELECT person_id FROM identity_links) " +
|
|
113
|
+
`OR id IN (${personRefs}) OR id IN (${proposed})`);
|
|
114
|
+
database.exec(`DELETE FROM involvements WHERE person_id IN ${persons}`);
|
|
115
|
+
const deleted = database.prepare(`DELETE FROM persons WHERE id IN ${persons}`).run().changes;
|
|
116
|
+
const personsKept = Number(database
|
|
117
|
+
.prepare("SELECT count(DISTINCT person) AS n FROM temp.crm_gone WHERE person IN (SELECT id FROM persons)")
|
|
118
|
+
.get()?.n);
|
|
119
|
+
const renamed = database
|
|
120
|
+
.prepare("UPDATE persons SET name = (SELECT name FROM temp.crm_names n WHERE n.id = persons.id), updated_at = ? " +
|
|
121
|
+
"WHERE id IN (SELECT id FROM temp.crm_names)")
|
|
122
|
+
.run(context.now()).changes;
|
|
123
|
+
return { contacts, persons: deleted, personsKept, names: renamed };
|
|
124
|
+
};
|
|
125
|
+
try {
|
|
126
|
+
return write(database, () => {
|
|
127
|
+
const counts = counted();
|
|
128
|
+
if (dryRun)
|
|
129
|
+
throw new DryRun(counts);
|
|
130
|
+
return counts;
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (error instanceof DryRun)
|
|
135
|
+
return error.counts;
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
};
|
|
@@ -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, ?) = ?")
|
|
@@ -9,6 +9,9 @@ export interface LinkRow {
|
|
|
9
9
|
pair: [number, number] | undefined;
|
|
10
10
|
}
|
|
11
11
|
export declare const pairOf: (a: number | string, b: number | string) => string;
|
|
12
|
+
/** The identity a `provider:id` names, if the store still has it. */
|
|
13
|
+
export declare const pkOf: (database: CacheDatabase, ref: string) => number | undefined;
|
|
14
|
+
export declare const personOf: (database: CacheDatabase, identity: number | undefined) => number | undefined;
|
|
12
15
|
/** The people a proposal's identities are on now; merges since may have moved either side. */
|
|
13
16
|
export declare const currentPairOf: (database: CacheDatabase, payload: IdentityLinkPayload) => [number, number] | undefined;
|
|
14
17
|
/** The proposals that still say something: waiting for the owner, or turned down by them; a `page` is newest first. */
|
|
@@ -38,6 +41,8 @@ export declare const linkIndex: (database: CacheDatabase) => {
|
|
|
38
41
|
merged: (from: number, into: number) => void;
|
|
39
42
|
};
|
|
40
43
|
export type LinkIndex = ReturnType<typeof linkIndex>;
|
|
44
|
+
/** The identities on a person now, as one comparable string. */
|
|
45
|
+
export declare const sideOf: (database: CacheDatabase, person: number) => string;
|
|
41
46
|
export declare const sidesOf: (database: CacheDatabase, a: number, b: number) => [string, string];
|
|
42
47
|
/**
|
|
43
48
|
* Brings open proposals up to date with the people they name: one whose two people are one now, whose identity a
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import { IDENTITY_LINK_KIND } from "../identity-links.js";
|
|
2
2
|
import { currentPerson } from "./merged-persons.js";
|
|
3
3
|
export const pairOf = (a, b) => [Number(a), Number(b)].sort((x, y) => x - y).join("-");
|
|
4
|
-
|
|
4
|
+
/** The identity a `provider:id` names, if the store still has it. */
|
|
5
|
+
export const pkOf = (database, ref) => {
|
|
5
6
|
const at = ref.indexOf(":");
|
|
6
7
|
const row = database
|
|
7
8
|
.prepare("SELECT id FROM identities WHERE provider = ? AND external_id = ?")
|
|
8
9
|
.get(ref.slice(0, at), ref.slice(at + 1));
|
|
9
10
|
return row ? Number(row.id) : undefined;
|
|
10
11
|
};
|
|
11
|
-
const personOf = (database, identity) => {
|
|
12
|
+
export const personOf = (database, identity) => {
|
|
12
13
|
if (identity === undefined)
|
|
13
14
|
return undefined;
|
|
14
15
|
const row = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
|
|
@@ -96,7 +97,8 @@ export const linkIndex = (database) => {
|
|
|
96
97
|
},
|
|
97
98
|
};
|
|
98
99
|
};
|
|
99
|
-
|
|
100
|
+
/** The identities on a person now, as one comparable string. */
|
|
101
|
+
export const sideOf = (database, person) => database
|
|
100
102
|
.prepare("SELECT identity_id FROM identity_links WHERE person_id = ? ORDER BY identity_id")
|
|
101
103
|
.all(person)
|
|
102
104
|
.map(({ identity_id }) => String(identity_id))
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
|
+
import { type IdentitySplitDecision, type IdentitySplitFilter, type IdentitySplitInput, type IdentitySplitRow } from "../identity-splits.js";
|
|
3
|
+
import type { StoreContext } from "./open.js";
|
|
4
|
+
import { type ProposedAction } from "./proposed-actions.js";
|
|
5
|
+
/**
|
|
6
|
+
* The identities the owner turned a split down for, by the person they are still on: the owner said they belong there.
|
|
7
|
+
* `people doubts` leaves them out. One that moved since counts no longer.
|
|
8
|
+
*/
|
|
9
|
+
export declare const keptTogether: (database: CacheDatabase) => Map<number, Set<string>>;
|
|
10
|
+
/**
|
|
11
|
+
* Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
|
|
12
|
+
* open proposal for the same identities is given back instead of a second, brought up to date with the person as it
|
|
13
|
+
* is now and with the new evidence added, so proposing again is how a stale one is renewed; its first reason and
|
|
14
|
+
* proposer stay. An identity the owner kept on this person by turning a split down is refused.
|
|
15
|
+
*/
|
|
16
|
+
export declare const proposeIdentitySplit: (context: StoreContext, input: IdentitySplitInput) => ProposedAction;
|
|
17
|
+
/**
|
|
18
|
+
* Decides an `identity_split`, the owner's alone. Confirm carries it out as the owner's own unlink or unmerge, so no
|
|
19
|
+
* automatic match joins them again; it is refused with `identity.stale` when the person changed since it was proposed.
|
|
20
|
+
* Only a waiting proposal is carried out: one an older build approved as a plain action stays as it is.
|
|
21
|
+
*/
|
|
22
|
+
export declare const decideIdentitySplit: (context: StoreContext, id: string, decision: IdentitySplitDecision) => ProposedAction;
|
|
23
|
+
/** The `identity_split` proposals, newest first, each naming the person as they are now. */
|
|
24
|
+
export declare const identitySplitRows: (context: StoreContext, { status, limit, offset }: IdentitySplitFilter) => {
|
|
25
|
+
items: IdentitySplitRow[];
|
|
26
|
+
hasMore: boolean;
|
|
27
|
+
};
|
|
28
|
+
/** Deletes every `identity_split` that names an identity no longer in the store: its payload names the address. */
|
|
29
|
+
export declare const forgetErasedSplits: (database: CacheDatabase) => void;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { assertMayDecide, deciderAuthor } from "../decisions.js";
|
|
3
|
+
import { IDENTITY_SPLIT_KIND, } from "../identity-splits.js";
|
|
4
|
+
import { personOf, pkOf, sideOf } from "./identity-link-rows.js";
|
|
5
|
+
import { parseIdentityRef } from "./identity-proposals.js";
|
|
6
|
+
import { currentPerson } from "./merged-persons.js";
|
|
7
|
+
import { recordOf, required, unlinkIdentity } from "./person-links.js";
|
|
8
|
+
import { mergeId, merges, parseMergeId, split, undoMerge } from "./person-merges.js";
|
|
9
|
+
import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
|
|
10
|
+
import { write } from "./transaction.js";
|
|
11
|
+
const refOf = ({ provider, id }) => `${provider}:${id}`;
|
|
12
|
+
const keyOf = (split, person, identities) => `${split} ${person} ${[...identities].sort().join(" ")}`;
|
|
13
|
+
/** What the split would move, checked as the owner's own move would check it, so a proposal can be carried out. */
|
|
14
|
+
const planOf = (context, input) => {
|
|
15
|
+
if ("merge" in input) {
|
|
16
|
+
const { to, from } = parseMergeId(input.merge);
|
|
17
|
+
const id = mergeId(to, from);
|
|
18
|
+
const found = merges(context, to).find((merge) => merge.id === id);
|
|
19
|
+
if (found === undefined)
|
|
20
|
+
throw new CliError("not_found", `nothing of person:${from} is merged into person:${to}`, {
|
|
21
|
+
reason: "identity.no-merge",
|
|
22
|
+
});
|
|
23
|
+
return { split: "unmerge", person: Number(to), identities: found.identities.map(refOf), merge: id };
|
|
24
|
+
}
|
|
25
|
+
const chosen = [...new Map(input.identities.map((ref) => [refOf(ref), ref])).values()];
|
|
26
|
+
if (chosen.length === 0)
|
|
27
|
+
throw new CliError("validation_error", "name at least one identity to split off");
|
|
28
|
+
const persons = new Set(chosen.map((ref) => required(context, ref).personPk));
|
|
29
|
+
if (persons.size > 1)
|
|
30
|
+
throw new CliError("validation_error", "the identities that leave are all of one person", {
|
|
31
|
+
reason: "identity.several-persons",
|
|
32
|
+
});
|
|
33
|
+
const person = [...persons][0];
|
|
34
|
+
if (chosen.length >= recordOf(context, person).identities.length)
|
|
35
|
+
throw new CliError("validation_error", "a split leaves at least one identity with the person", {
|
|
36
|
+
reason: "identity.nothing-left",
|
|
37
|
+
});
|
|
38
|
+
return { split: "unlink", person, identities: chosen.map(refOf), merge: null };
|
|
39
|
+
};
|
|
40
|
+
const splitRows = (database, statuses, page, made) => database
|
|
41
|
+
.prepare("SELECT id, status, payload FROM proposed_actions WHERE kind = ? AND status IN (SELECT value FROM json_each(?)) " +
|
|
42
|
+
(made === undefined ? "" : `AND json_extract(result, '$.person') IS ${made ? "NOT " : ""}NULL `) +
|
|
43
|
+
`ORDER BY id DESC${page === undefined ? "" : " LIMIT ? OFFSET ?"}`)
|
|
44
|
+
.all(IDENTITY_SPLIT_KIND, JSON.stringify(statuses), ...(page === undefined ? [] : [page.limit, page.offset]))
|
|
45
|
+
.map((row) => ({
|
|
46
|
+
id: String(row.id),
|
|
47
|
+
status: String(row.status),
|
|
48
|
+
payload: JSON.parse(String(row.payload)),
|
|
49
|
+
}));
|
|
50
|
+
/**
|
|
51
|
+
* The person the proposal is about now: the one it was proposed for, or whom that person was merged into, while every
|
|
52
|
+
* identity it names is still there. `undefined` once one left, was erased or went elsewhere.
|
|
53
|
+
*/
|
|
54
|
+
const holder = (database, payload) => {
|
|
55
|
+
const person = currentPerson(database, Number(payload.person));
|
|
56
|
+
return payload.identities.every((ref) => personOf(database, pkOf(database, ref)) === person) ? person : undefined;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* The identities the owner turned a split down for, by the person they are still on: the owner said they belong there.
|
|
60
|
+
* `people doubts` leaves them out. One that moved since counts no longer.
|
|
61
|
+
*/
|
|
62
|
+
export const keptTogether = (database) => {
|
|
63
|
+
const kept = new Map();
|
|
64
|
+
for (const { payload } of splitRows(database, ["rejected"])) {
|
|
65
|
+
const person = currentPerson(database, Number(payload.person));
|
|
66
|
+
for (const ref of payload.identities) {
|
|
67
|
+
if (personOf(database, pkOf(database, ref)) !== person)
|
|
68
|
+
continue;
|
|
69
|
+
const refs = kept.get(person) ?? new Set();
|
|
70
|
+
refs.add(ref);
|
|
71
|
+
kept.set(person, refs);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return kept;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Proposes to take identities off their person, or to undo a merge, as an `identity_split` only the owner decides. An
|
|
78
|
+
* open proposal for the same identities is given back instead of a second, brought up to date with the person as it
|
|
79
|
+
* is now and with the new evidence added, so proposing again is how a stale one is renewed; its first reason and
|
|
80
|
+
* proposer stay. An identity the owner kept on this person by turning a split down is refused.
|
|
81
|
+
*/
|
|
82
|
+
export const proposeIdentitySplit = (context, input) => write(context.database, () => {
|
|
83
|
+
const reason = input.reason.trim();
|
|
84
|
+
if (!reason)
|
|
85
|
+
throw new CliError("validation_error", "a proposal to split a person says why", {
|
|
86
|
+
reason: "proposal.reason-required",
|
|
87
|
+
});
|
|
88
|
+
const plan = planOf(context, input);
|
|
89
|
+
const kept = keptTogether(context.database).get(plan.person);
|
|
90
|
+
if (plan.identities.some((ref) => kept?.has(ref)))
|
|
91
|
+
throw new CliError("conflict", "the owner kept these identities together; only the owner splits them", {
|
|
92
|
+
reason: "identity.kept-together",
|
|
93
|
+
});
|
|
94
|
+
const key = keyOf(plan.split, plan.person, plan.identities);
|
|
95
|
+
const operations = proposalOperationsOver(context);
|
|
96
|
+
const payload = {
|
|
97
|
+
split: plan.split,
|
|
98
|
+
person: String(plan.person),
|
|
99
|
+
identities: plan.identities,
|
|
100
|
+
merge: plan.merge,
|
|
101
|
+
side: sideOf(context.database, plan.person),
|
|
102
|
+
evidence: input.evidence ?? [],
|
|
103
|
+
};
|
|
104
|
+
for (const row of splitRows(context.database, ["proposed"])) {
|
|
105
|
+
const person = holder(context.database, row.payload);
|
|
106
|
+
if (person === undefined || keyOf(row.payload.split, person, row.payload.identities) !== key)
|
|
107
|
+
continue;
|
|
108
|
+
const evidence = [...new Set([...row.payload.evidence, ...payload.evidence])];
|
|
109
|
+
context.database
|
|
110
|
+
.prepare("UPDATE proposed_actions SET payload = ? WHERE id = ?")
|
|
111
|
+
.run(JSON.stringify({ ...payload, evidence }), Number(row.id));
|
|
112
|
+
return operations.get(row.id);
|
|
113
|
+
}
|
|
114
|
+
return operations.propose({ kind: IDENTITY_SPLIT_KIND, by: input.by, payload, reason });
|
|
115
|
+
});
|
|
116
|
+
/**
|
|
117
|
+
* Decides an `identity_split`, the owner's alone. Confirm carries it out as the owner's own unlink or unmerge, so no
|
|
118
|
+
* automatic match joins them again; it is refused with `identity.stale` when the person changed since it was proposed.
|
|
119
|
+
* Only a waiting proposal is carried out: one an older build approved as a plain action stays as it is.
|
|
120
|
+
*/
|
|
121
|
+
export const decideIdentitySplit = (context, id, decision) => write(context.database, () => {
|
|
122
|
+
const operations = proposalOperationsOver(context);
|
|
123
|
+
const proposal = operations.get(id);
|
|
124
|
+
if (proposal.kind !== IDENTITY_SPLIT_KIND)
|
|
125
|
+
throw new CliError("validation_error", `${id} is a ${proposal.kind} proposal, not a split of a person`);
|
|
126
|
+
assertMayDecide({ id, kind: IDENTITY_SPLIT_KIND, ownerOnly: true, proposedBy: proposerOfAction(proposal) }, decision.by, context.decisions);
|
|
127
|
+
const author = deciderAuthor(decision.by);
|
|
128
|
+
const reason = decision.reason?.trim() || undefined;
|
|
129
|
+
const noted = reason === undefined ? {} : { reason };
|
|
130
|
+
if (!decision.confirm)
|
|
131
|
+
return operations.reject(id, author, noted);
|
|
132
|
+
if (proposal.status !== "proposed")
|
|
133
|
+
throw new CliError("validation_error", `${id} is already ${proposal.status}`, { reason: "proposal.wrong-state" });
|
|
134
|
+
const payload = proposal.payload;
|
|
135
|
+
const person = Number(payload.person);
|
|
136
|
+
const refs = payload.identities.map(parseIdentityRef);
|
|
137
|
+
if (holder(context.database, payload) !== person || sideOf(context.database, person) !== payload.side)
|
|
138
|
+
throw new CliError("conflict", `the person ${id} names changed since it was proposed; propose it again`, {
|
|
139
|
+
reason: "identity.stale",
|
|
140
|
+
});
|
|
141
|
+
const owner = { method: "unlink", by: "owner" };
|
|
142
|
+
let made;
|
|
143
|
+
if (payload.split === "unmerge") {
|
|
144
|
+
const { to, from } = parseMergeId(payload.merge ?? "");
|
|
145
|
+
made = undoMerge(context, to, from, "owner");
|
|
146
|
+
}
|
|
147
|
+
else
|
|
148
|
+
made =
|
|
149
|
+
refs.length === 1
|
|
150
|
+
? unlinkIdentity(context, refs[0], owner)
|
|
151
|
+
: split(context, String(person), refs, "owner");
|
|
152
|
+
return operations.approve(id, { person: made.uid, ...noted }, author);
|
|
153
|
+
});
|
|
154
|
+
/** A split carried out records the person it made; an older build's approval as a plain action made none. */
|
|
155
|
+
const shownStatus = (status, result) => {
|
|
156
|
+
if (status === "proposed" || status === "rejected")
|
|
157
|
+
return status;
|
|
158
|
+
return typeof result?.person === "string" ? "confirmed" : "dropped";
|
|
159
|
+
};
|
|
160
|
+
const STORED = {
|
|
161
|
+
proposed: ["proposed"],
|
|
162
|
+
rejected: ["rejected"],
|
|
163
|
+
confirmed: ["approved", "executed", "failed"],
|
|
164
|
+
};
|
|
165
|
+
/** The `identity_split` proposals, newest first, each naming the person as they are now. */
|
|
166
|
+
export const identitySplitRows = (context, { status = "proposed", limit, offset }) => {
|
|
167
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
168
|
+
throw new CliError("validation_error", "a list of split proposals takes 1–500 items");
|
|
169
|
+
const statuses = status === "all" ? Object.values(STORED).flat() : STORED[status === "dropped" ? "confirmed" : status];
|
|
170
|
+
const made = status === "dropped" ? false : status === "confirmed" ? true : undefined;
|
|
171
|
+
const operations = proposalOperationsOver(context);
|
|
172
|
+
const rows = splitRows(context.database, statuses, { limit: limit + 1, offset }, made);
|
|
173
|
+
const items = rows.slice(0, limit).map((row) => {
|
|
174
|
+
const action = operations.get(row.id);
|
|
175
|
+
return {
|
|
176
|
+
id: row.id,
|
|
177
|
+
status: shownStatus(row.status, action.result),
|
|
178
|
+
split: row.payload.split,
|
|
179
|
+
person: `person:${holder(context.database, row.payload) ?? currentPerson(context.database, Number(row.payload.person))}`,
|
|
180
|
+
identities: row.payload.identities,
|
|
181
|
+
merge: row.payload.merge,
|
|
182
|
+
reason: action.reason,
|
|
183
|
+
evidence: row.payload.evidence,
|
|
184
|
+
proposedBy: proposerOfAction(action),
|
|
185
|
+
createdAt: action.createdAt,
|
|
186
|
+
};
|
|
187
|
+
});
|
|
188
|
+
return { items, hasMore: rows.length > limit };
|
|
189
|
+
};
|
|
190
|
+
/** Deletes every `identity_split` that names an identity no longer in the store: its payload names the address. */
|
|
191
|
+
export const forgetErasedSplits = (database) => {
|
|
192
|
+
for (const row of splitRows(database, ["proposed", "approved", "rejected", "executed", "failed"]))
|
|
193
|
+
if (row.payload.identities.some((ref) => pkOf(database, ref) === undefined))
|
|
194
|
+
database.prepare("DELETE FROM proposed_actions WHERE id = ?").run(Number(row.id));
|
|
195
|
+
};
|
|
@@ -347,6 +347,8 @@ const topic = messengerOnly(({ value }) => always(bound("m.thread_external_id =
|
|
|
347
347
|
/** What `kind:` matches for a chat aliased `c`: private, saved, bot, service, group, channel or unknown. */
|
|
348
348
|
export const PEER_KIND = "CASE WHEN json_extract(c.metadata,'$.peerKind') IN ('private','saved','bot','service','group','channel','unknown') THEN json_extract(c.metadata,'$.peerKind') WHEN c.kind='dialog' AND json_extract(c.metadata,'$.isBot')=1 THEN 'bot' WHEN c.kind='dialog' THEN 'private' ELSE c.kind END";
|
|
349
349
|
const kind = messengerOnly(({ value }) => always(bound(`${PEER_KIND} = ?`, value.toLowerCase())));
|
|
350
|
+
/** A chat the owner muted, until its mute runs out; a chat whose messenger keeps no mute is not muted. */
|
|
351
|
+
const muted = messengerOnly(({ value }) => always(bound(`${value.toLowerCase() === "true" ? "" : "NOT "}(coalesce(c.muted, 0) = 1 AND (c.muted_until IS NULL OR c.muted_until > ?))`, Date.now())));
|
|
350
352
|
const has = ({ value }, { corpus, mail }) => {
|
|
351
353
|
const wanted = value.toLowerCase();
|
|
352
354
|
if (wanted === "transcript")
|
|
@@ -440,6 +442,7 @@ export const FIELD_COMPILERS = {
|
|
|
440
442
|
tag,
|
|
441
443
|
topic,
|
|
442
444
|
kind,
|
|
445
|
+
muted,
|
|
443
446
|
has,
|
|
444
447
|
in: inSourceField,
|
|
445
448
|
to: recipient,
|
|
@@ -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
|
];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { StoreContext } from "./open.js";
|
|
2
|
+
/** Why a person may be wrong, most urgent first: the owner's own person holding someone else matters most. */
|
|
3
|
+
export declare const DOUBT_REASONS: readonly ["owner-other-name", "test-data", "shared-address", "mixed-names"];
|
|
4
|
+
export type DoubtReason = (typeof DOUBT_REASONS)[number];
|
|
5
|
+
export interface DoubtIdentity {
|
|
6
|
+
identity: string;
|
|
7
|
+
name: string | null;
|
|
8
|
+
/** How the identity came to this person, and who linked it. */
|
|
9
|
+
method: string;
|
|
10
|
+
by: string;
|
|
11
|
+
at: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PersonDoubt {
|
|
14
|
+
person: string;
|
|
15
|
+
name: string | null;
|
|
16
|
+
owner: boolean;
|
|
17
|
+
reason: DoubtReason;
|
|
18
|
+
/** The reason in plain words, naming what was found. */
|
|
19
|
+
why: string;
|
|
20
|
+
/** The identities in doubt, not every identity of the person. */
|
|
21
|
+
identities: DoubtIdentity[];
|
|
22
|
+
/** What the doubt rests on: the identities, a shared address, the merges that brought them. */
|
|
23
|
+
evidence: string[];
|
|
24
|
+
/** memo commands, after `memo`, that would take the doubted identities off; empty when none fits. */
|
|
25
|
+
fix: string[];
|
|
26
|
+
}
|
|
27
|
+
export interface PersonDoubts {
|
|
28
|
+
items: PersonDoubt[];
|
|
29
|
+
total: number;
|
|
30
|
+
hasMore: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** People that may be wrong, a page at a time, each with why and the owner's moves that would set it right. */
|
|
33
|
+
export declare const personDoubts: (context: StoreContext, { limit, offset }: {
|
|
34
|
+
limit: number;
|
|
35
|
+
offset: number;
|
|
36
|
+
}) => PersonDoubts;
|