@wirecat/cli-core 0.605.0 → 0.607.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 +284 -1
- package/dist/calendar/index.d.ts +1 -0
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/reads.js +5 -0
- package/dist/cli/app-mcp-command.d.ts +6 -2
- package/dist/cli/app-mcp-command.js +11 -2
- package/dist/cli/csv.d.ts +10 -0
- package/dist/cli/csv.js +22 -0
- package/dist/cli/early-refusal.d.ts +10 -0
- package/dist/cli/early-refusal.js +19 -0
- package/dist/cli/index.d.ts +4 -1
- package/dist/cli/index.js +4 -0
- package/dist/cli/profile-token.d.ts +29 -0
- package/dist/cli/profile-token.js +65 -0
- package/dist/cli/program.js +4 -2
- package/dist/cli/store-settings.js +38 -4
- package/dist/crm/cli/csv.d.ts +23 -0
- package/dist/crm/cli/csv.js +135 -0
- package/dist/crm/cli/index.d.ts +1 -1
- package/dist/crm/cli/index.js +36 -22
- package/dist/crm/cli/pipeline-view.d.ts +3 -0
- package/dist/crm/cli/pipeline-view.js +36 -0
- package/dist/crm/index.d.ts +2 -2
- package/dist/crm/index.js +1 -1
- package/dist/crm/source.d.ts +35 -5
- package/dist/crm/sync.d.ts +15 -7
- package/dist/crm/sync.js +169 -11
- package/dist/crm/writes.d.ts +6 -4
- package/dist/crm/writes.js +17 -13
- package/dist/documents.d.ts +2 -0
- package/dist/documents.js +2 -0
- package/dist/domain/business.d.ts +79 -0
- package/dist/domain/business.js +42 -0
- package/dist/domain/crm.d.ts +41 -2
- package/dist/domain/deals.d.ts +5 -2
- package/dist/domain/deals.js +5 -2
- package/dist/domain/finance.d.ts +2 -0
- package/dist/domain/finance.js +2 -2
- package/dist/domain/google-documents.d.ts +2 -0
- package/dist/domain/google-documents.js +3 -1
- package/dist/domain/money.d.ts +2 -0
- package/dist/domain/money.js +11 -3
- package/dist/domain/providers.d.ts +36 -1
- package/dist/domain/providers.js +69 -7
- package/dist/domain/record-fields.d.ts +42 -0
- package/dist/domain/record-fields.js +122 -0
- package/dist/domain/record-types.d.ts +489 -16
- package/dist/domain/record-types.js +374 -7
- package/dist/domain/records.d.ts +96 -5
- package/dist/domain/records.js +178 -32
- package/dist/domain/ref-summaries.js +5 -0
- package/dist/domain/references.d.ts +1 -1
- package/dist/domain/references.js +5 -0
- package/dist/domain/relations.d.ts +125 -0
- package/dist/domain/relations.js +107 -0
- package/dist/domain/vcard.d.ts +25 -0
- package/dist/domain/vcard.js +267 -0
- package/dist/entities/deal.d.ts +16 -2
- package/dist/entities/deal.js +5 -1
- package/dist/entities/index.d.ts +29 -13
- package/dist/entities/relationship.d.ts +8 -2
- package/dist/entities/relationship.js +8 -2
- package/dist/entities/task-results.d.ts +10 -10
- package/dist/errors/reasons.js +73 -2
- package/dist/fetch/addresses.d.ts +5 -0
- package/dist/fetch/addresses.js +76 -0
- package/dist/fetch/page.d.ts +64 -0
- package/dist/fetch/page.js +256 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +6 -3
- package/dist/mail/cli/review.js +20 -6
- package/dist/mail/index.d.ts +1 -1
- package/dist/mail/marks.d.ts +10 -5
- package/dist/mail/marks.js +16 -8
- package/dist/mail/review.d.ts +5 -0
- package/dist/meetings/calendar-text.d.ts +1 -1
- package/dist/meetings/calendar-text.js +4 -0
- package/dist/meetings/event-store.d.ts +2 -2
- package/dist/search/account-list.d.ts +4 -0
- package/dist/search/account-list.js +19 -8
- package/dist/search/query.js +2 -2
- package/dist/services/events-search.js +2 -2
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/ingest.d.ts +56 -8
- package/dist/services/ingest.js +95 -61
- package/dist/services/link-scorers/scan.js +2 -1
- package/dist/services/link-scorers/shared.js +2 -1
- package/dist/services/messages-search.js +3 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/notes-search.js +1 -0
- package/dist/services/project-status/index.js +2 -1
- package/dist/services/proposals/kinds/contracts.d.ts +4 -0
- package/dist/services/proposals/kinds/contracts.js +9 -0
- package/dist/services/proposals/kinds/finance.d.ts +4 -0
- package/dist/services/proposals/kinds/finance.js +14 -35
- package/dist/services/proposals/kinds/orders.js +7 -30
- package/dist/services/proposals/kinds/shared.d.ts +27 -1
- package/dist/services/proposals/kinds/shared.js +34 -0
- package/dist/services/proposals/kinds/source-review.d.ts +4 -0
- package/dist/services/proposals/kinds/source-review.js +45 -0
- package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
- package/dist/services/proposals/kinds/subscriptions.js +24 -0
- package/dist/services/proposals/kinds/transactions.d.ts +4 -0
- package/dist/services/proposals/kinds/transactions.js +10 -0
- package/dist/services/proposals/registry.js +9 -0
- package/dist/services/search-all-meetings.js +2 -2
- package/dist/services/search-all.js +4 -3
- package/dist/services/search-kind.js +3 -3
- package/dist/services/stored-project-gathering.js +4 -3
- package/dist/store/decisions.js +5 -1
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/index.d.ts +20 -4
- package/dist/store/index.js +4 -0
- package/dist/store/people.js +1 -1
- package/dist/store/project-transfer/request.d.ts +4 -1
- package/dist/store/project-transfer/schema.d.ts +9 -2
- package/dist/store/project-transfer/schema.js +4 -0
- package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
- package/dist/store/source-review.d.ts +64 -0
- package/dist/store/source-review.js +7 -0
- package/dist/store/sqlite/accounts.d.ts +1 -1
- package/dist/store/sqlite/accounts.js +24 -1
- package/dist/store/sqlite/added-sources.d.ts +82 -0
- package/dist/store/sqlite/added-sources.js +237 -0
- package/dist/store/sqlite/business-contracts.d.ts +90 -0
- package/dist/store/sqlite/business-contracts.js +182 -0
- package/dist/store/sqlite/calendar-events.js +7 -3
- package/dist/store/sqlite/calendar-forget.js +3 -0
- package/dist/store/sqlite/calendar.d.ts +21 -1
- package/dist/store/sqlite/calendar.js +27 -7
- package/dist/store/sqlite/chat-rekey.js +7 -0
- package/dist/store/sqlite/chats.d.ts +3 -1
- package/dist/store/sqlite/chats.js +15 -1
- package/dist/store/sqlite/crm-rows.d.ts +44 -0
- package/dist/store/sqlite/crm-rows.js +195 -0
- package/dist/store/sqlite/crm-settings.d.ts +28 -0
- package/dist/store/sqlite/crm-settings.js +80 -0
- package/dist/store/sqlite/crm.d.ts +42 -11
- package/dist/store/sqlite/crm.js +402 -196
- package/dist/store/sqlite/deals.d.ts +4 -8
- package/dist/store/sqlite/deals.js +8 -5
- package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
- package/dist/store/sqlite/emails.js +2 -0
- package/dist/store/sqlite/entity-types.d.ts +14 -9
- package/dist/store/sqlite/entity-types.js +4 -10
- package/dist/store/sqlite/evidence-signature.d.ts +114 -0
- package/dist/store/sqlite/evidence-signature.js +349 -0
- package/dist/store/sqlite/evidence-sources.d.ts +2 -1
- package/dist/store/sqlite/evidence-sources.js +7 -3
- package/dist/store/sqlite/facts.d.ts +7 -2
- package/dist/store/sqlite/facts.js +21 -5
- package/dist/store/sqlite/finance.d.ts +18 -105
- package/dist/store/sqlite/finance.js +100 -219
- package/dist/store/sqlite/involvement-queue.js +4 -3
- package/dist/store/sqlite/knowledge.d.ts +14 -4
- package/dist/store/sqlite/knowledge.js +108 -102
- package/dist/store/sqlite/labelled.d.ts +3 -0
- package/dist/store/sqlite/labelled.js +11 -0
- package/dist/store/sqlite/link-kinds.d.ts +4 -3
- package/dist/store/sqlite/link-kinds.js +6 -2
- package/dist/store/sqlite/manifest.js +7 -0
- package/dist/store/sqlite/memories.d.ts +24 -10
- package/dist/store/sqlite/memories.js +73 -19
- package/dist/store/sqlite/messages.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +134 -0
- package/dist/store/sqlite/money-lines.d.ts +48 -0
- package/dist/store/sqlite/money-lines.js +76 -0
- package/dist/store/sqlite/money-transactions.d.ts +132 -0
- package/dist/store/sqlite/money-transactions.js +295 -0
- package/dist/store/sqlite/notes.d.ts +14 -4
- package/dist/store/sqlite/notes.js +43 -31
- package/dist/store/sqlite/orders.d.ts +36 -6
- package/dist/store/sqlite/orders.js +126 -46
- package/dist/store/sqlite/organizations.d.ts +8 -0
- package/dist/store/sqlite/organizations.js +14 -0
- package/dist/store/sqlite/payment-facts.js +1 -1
- package/dist/store/sqlite/person-preparation.d.ts +1 -1
- package/dist/store/sqlite/person-preparation.js +3 -2
- package/dist/store/sqlite/private-people.js +2 -0
- package/dist/store/sqlite/products.d.ts +78 -0
- package/dist/store/sqlite/products.js +131 -0
- package/dist/store/sqlite/project-transfer/records.js +39 -3
- package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
- package/dist/store/sqlite/proposed-actions.d.ts +1 -1
- package/dist/store/sqlite/proposed-actions.js +24 -7
- package/dist/store/sqlite/providers.d.ts +0 -4
- package/dist/store/sqlite/providers.js +20 -2
- package/dist/store/sqlite/record-matching.d.ts +80 -0
- package/dist/store/sqlite/record-matching.js +264 -0
- package/dist/store/sqlite/record-projection.d.ts +89 -0
- package/dist/store/sqlite/record-projection.js +50 -0
- package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
- package/dist/store/sqlite/record-projectors-direct.js +125 -0
- package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
- package/dist/store/sqlite/record-projectors-money.js +214 -0
- package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
- package/dist/store/sqlite/record-projectors-phone.js +212 -0
- package/dist/store/sqlite/record-projectors.d.ts +3 -44
- package/dist/store/sqlite/record-projectors.js +7 -67
- package/dist/store/sqlite/record-relations.d.ts +24 -0
- package/dist/store/sqlite/record-relations.js +92 -0
- package/dist/store/sqlite/record-remap.d.ts +12 -0
- package/dist/store/sqlite/record-remap.js +92 -0
- package/dist/store/sqlite/record-run.d.ts +71 -0
- package/dist/store/sqlite/record-run.js +179 -0
- package/dist/store/sqlite/record-settling.d.ts +9 -0
- package/dist/store/sqlite/record-settling.js +74 -0
- package/dist/store/sqlite/record-stamps.d.ts +13 -0
- package/dist/store/sqlite/record-stamps.js +30 -0
- package/dist/store/sqlite/record-writes.d.ts +43 -0
- package/dist/store/sqlite/record-writes.js +307 -0
- package/dist/store/sqlite/records.d.ts +52 -42
- package/dist/store/sqlite/records.js +123 -353
- package/dist/store/sqlite/ref-summaries.d.ts +6 -5
- package/dist/store/sqlite/ref-summaries.js +60 -8
- package/dist/store/sqlite/refunds.d.ts +31 -0
- package/dist/store/sqlite/refunds.js +112 -0
- package/dist/store/sqlite/relation-list.d.ts +43 -0
- package/dist/store/sqlite/relation-list.js +133 -0
- package/dist/store/sqlite/relation-proposals.d.ts +28 -6
- package/dist/store/sqlite/relation-proposals.js +134 -10
- package/dist/store/sqlite/relation-reads.d.ts +8 -0
- package/dist/store/sqlite/relation-reads.js +7 -0
- package/dist/store/sqlite/relation-roles.d.ts +26 -0
- package/dist/store/sqlite/relation-roles.js +91 -0
- package/dist/store/sqlite/reported-relations.d.ts +63 -0
- package/dist/store/sqlite/reported-relations.js +132 -0
- package/dist/store/sqlite/reviewed.d.ts +109 -0
- package/dist/store/sqlite/reviewed.js +173 -0
- package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
- package/dist/store/sqlite/schema/link-revisions.js +11 -0
- package/dist/store/sqlite/schema/links.d.ts +360 -0
- package/dist/store/sqlite/schema/links.js +32 -0
- package/dist/store/sqlite/schema.d.ts +2769 -306
- package/dist/store/sqlite/schema.js +258 -25
- package/dist/store/sqlite/source-review-marks.d.ts +54 -0
- package/dist/store/sqlite/source-review-marks.js +143 -0
- package/dist/store/sqlite/source-review.d.ts +54 -0
- package/dist/store/sqlite/source-review.js +221 -0
- package/dist/store/sqlite/stage-amounts.d.ts +14 -0
- package/dist/store/sqlite/stage-amounts.js +23 -0
- package/dist/store/sqlite/subscriptions.d.ts +135 -0
- package/dist/store/sqlite/subscriptions.js +294 -0
- package/dist/store/sqlite/text-input.d.ts +3 -0
- package/dist/store/sqlite/text-input.js +13 -0
- package/dist/store/sqlite/things.js +2 -9
- package/dist/store/sqlite/transaction.d.ts +15 -0
- package/dist/store/sqlite/transaction.js +57 -0
- package/dist/store/sqlite/wallets.d.ts +88 -0
- package/dist/store/sqlite/wallets.js +143 -0
- package/dist/store/store-errors.d.ts +1 -0
- package/dist/store/store-errors.js +45 -0
- package/dist/store/store.d.ts +19 -1
- package/dist/store/store.js +35 -6
- package/package.json +6 -3
- package/schemas/examples/records-business.jsonl +11 -0
- package/schemas/records-envelope.v1.schema.json +1160 -5
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { standingOf } from "../../domain/relations.js";
|
|
2
3
|
import { assertMayDecide, botKey, deciderAuthor } from "../decisions.js";
|
|
3
4
|
import { actorOfOrigin, botNamed, ownerPerson } from "./actors.js";
|
|
4
5
|
import { insertLink, linkOf, purposeOf } from "./notes.js";
|
|
5
6
|
import { proposalOperationsOver, proposerOfAction } from "./proposed-actions.js";
|
|
7
|
+
import { checkStoredRole } from "./relation-roles.js";
|
|
6
8
|
import { thingOf } from "./things.js";
|
|
7
9
|
import { write } from "./transaction.js";
|
|
8
|
-
|
|
10
|
+
const isoOf = (ms) => (ms === undefined ? null : new Date(ms).toISOString());
|
|
11
|
+
export const relationOf = (link, now) => ({
|
|
9
12
|
id: link.id,
|
|
10
13
|
from: link.from,
|
|
11
14
|
to: String(link.to),
|
|
@@ -16,6 +19,10 @@ export const relationOf = (link) => ({
|
|
|
16
19
|
confirmed: link.confirmed,
|
|
17
20
|
provenance: link.provenance,
|
|
18
21
|
confidenceCategory: link.confirmed ? "owner-confirmed" : "weak",
|
|
22
|
+
standing: standingOf(link, now),
|
|
23
|
+
position: link.position ?? null,
|
|
24
|
+
startsAt: isoOf(link.startsAt),
|
|
25
|
+
endsAt: isoOf(link.endsAt),
|
|
19
26
|
createdAt: link.createdAt,
|
|
20
27
|
});
|
|
21
28
|
/** `relationship` proposals in `proposed_actions`: an agent's or a rule's, and the rejected ones a scan skips. */
|
|
@@ -39,14 +46,89 @@ export const relationProposalsOver = (context) => {
|
|
|
39
46
|
"VALUES ('relationship', ?, ?, ?, ?, 'rejected', ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
40
47
|
.run(from?.type ?? null, from?.id ?? null, JSON.stringify({ from: link.from, to: link.to, kind: link.kind, ...(link.role ? { role: link.role } : {}) }), link.evidence, proposed.type, proposed.id, decided.type, decided.id, at, JSON.stringify({ reason: why.join(": "), link: link.id }), at, at);
|
|
41
48
|
};
|
|
49
|
+
/** The role lists may have changed since a proposal was made: a role is checked when it is written. */
|
|
50
|
+
const checkedRole = (link, role) => {
|
|
51
|
+
if (typeof role !== "string")
|
|
52
|
+
return;
|
|
53
|
+
const [fromType, , toType] = fromTo(link);
|
|
54
|
+
checkStoredRole(database, link.kind, fromType, toType, role);
|
|
55
|
+
};
|
|
42
56
|
const applyUpdate = (link, input) => {
|
|
43
57
|
const changes = changesOf(input);
|
|
58
|
+
checkedRole(link, changes.role);
|
|
59
|
+
if ("role" in changes) {
|
|
60
|
+
const taken = database
|
|
61
|
+
.prepare("SELECT b.id FROM links a JOIN links b ON b.kind = a.kind AND b.from_type = a.from_type AND b.from_id = a.from_id " +
|
|
62
|
+
"AND b.to_type = a.to_type AND b.to_id = a.to_id AND b.anchor IS a.anchor AND b.account_id IS a.account_id " +
|
|
63
|
+
"AND ifnull(b.role, '') = ifnull(?, '') AND b.id <> a.id WHERE a.id = ?")
|
|
64
|
+
.get(changes.role ?? null, Number(link.id));
|
|
65
|
+
if (taken)
|
|
66
|
+
throw new CliError("validation_error", `relationship ${String(taken.id)} already holds that role`, {
|
|
67
|
+
reason: "relationship.exists",
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const startsAt = "startsAt" in changes ? (changes.startsAt ?? undefined) : link.startsAt;
|
|
71
|
+
const endsAt = "endsAt" in changes ? (changes.endsAt ?? undefined) : link.endsAt;
|
|
72
|
+
spanOf(startsAt, endsAt);
|
|
44
73
|
database
|
|
45
74
|
.prepare("UPDATE links SET role = CASE WHEN ? THEN ? ELSE role END, purpose = CASE WHEN ? THEN ? ELSE purpose END, " +
|
|
46
|
-
"
|
|
47
|
-
|
|
75
|
+
"starts_at = CASE WHEN ? THEN ? ELSE starts_at END, ends_at = CASE WHEN ? THEN ? ELSE ends_at END, " +
|
|
76
|
+
"metadata = CASE WHEN ? THEN (CASE WHEN ? IS NULL THEN json_remove(coalesce(metadata, '{}'), '$.position') " +
|
|
77
|
+
"ELSE json_set(coalesce(metadata, '{}'), '$.position', ?) END) ELSE metadata END, updated_at = ? WHERE id = ?")
|
|
78
|
+
.run(Number("role" in changes), changes.role ?? null, Number("purpose" in changes), changes.purpose ?? null, Number("startsAt" in changes), changes.startsAt ?? null, Number("endsAt" in changes), changes.endsAt ?? null, Number("position" in changes), changes.position ?? null, changes.position ?? null, now(), Number(link.id));
|
|
48
79
|
return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(link.id)));
|
|
49
80
|
};
|
|
81
|
+
/**
|
|
82
|
+
* The owner's change. On a link a source reported, the source's row stays for its sync to diff, and one owner link
|
|
83
|
+
* overrides it (`metadata.overrides`): made by the first change, changed in place by every later one. Reads show the
|
|
84
|
+
* override instead of the source's row.
|
|
85
|
+
*/
|
|
86
|
+
const ownerUpdate = (link, input) => {
|
|
87
|
+
if (link.accountId === undefined || link.confirmed)
|
|
88
|
+
return applyUpdate(link, input);
|
|
89
|
+
const held = database
|
|
90
|
+
.prepare("SELECT * FROM links WHERE kind = ? AND from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? " +
|
|
91
|
+
"AND account_id IS NULL AND json_extract(metadata, '$.overrides') = ?")
|
|
92
|
+
.get(...endsOf(link), Number(link.id));
|
|
93
|
+
if (held)
|
|
94
|
+
return applyUpdate(linkOf(database, held), input);
|
|
95
|
+
const changes = changesOf(input);
|
|
96
|
+
const pick = (key, kept) => key in changes ? changes[key] : kept;
|
|
97
|
+
const role = pick("role", link.role) ?? null;
|
|
98
|
+
const at = now();
|
|
99
|
+
const metadata = JSON.stringify({
|
|
100
|
+
overrides: Number(link.id),
|
|
101
|
+
...(link.position ? { position: link.position } : {}),
|
|
102
|
+
});
|
|
103
|
+
// An owner link of that role on the pair already (from `relate`) becomes the override rather than a second one.
|
|
104
|
+
const same = database
|
|
105
|
+
.prepare("SELECT id FROM links WHERE kind = ? AND from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? " +
|
|
106
|
+
"AND account_id IS NULL AND anchor IS NULL AND ifnull(role, '') = ?")
|
|
107
|
+
.get(...endsOf(link), role ?? "");
|
|
108
|
+
const id = same
|
|
109
|
+
? Number(same.id)
|
|
110
|
+
: Number(database
|
|
111
|
+
.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, purpose, source, metadata, confirmed, " +
|
|
112
|
+
"starts_at, ends_at, created_at, author, updated_at) " +
|
|
113
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, 'owner', ?, 1, ?, ?, ?, 'owner', ?) RETURNING id")
|
|
114
|
+
.get(...fromTo(link), link.kind, role, link.purpose, metadata, link.startsAt ?? null, link.endsAt ?? null, at, at)?.id);
|
|
115
|
+
if (same)
|
|
116
|
+
database
|
|
117
|
+
.prepare("UPDATE links SET metadata = json_set(coalesce(metadata, '{}'), '$.overrides', ?) WHERE id = ?")
|
|
118
|
+
.run(Number(link.id), id);
|
|
119
|
+
const { role: _, ...rest } = changes;
|
|
120
|
+
const owned = linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(id));
|
|
121
|
+
return Object.keys(rest).length ? applyUpdate(owned, rest) : owned;
|
|
122
|
+
};
|
|
123
|
+
const fromTo = (link) => {
|
|
124
|
+
const from = thingOf(database, link.from);
|
|
125
|
+
const to = thingOf(database, String(link.to));
|
|
126
|
+
return [from.type, from.id, to.type, to.id];
|
|
127
|
+
};
|
|
128
|
+
const endsOf = (link) => {
|
|
129
|
+
const [fromType, fromId, toType, toId] = fromTo(link);
|
|
130
|
+
return [link.kind, fromType, fromId, toType, toId];
|
|
131
|
+
};
|
|
50
132
|
/**
|
|
51
133
|
* A scan's newer score on a pending proposal, in place under the same id. A rule's own row takes the new score,
|
|
52
134
|
* signals, evidence and purpose; another proposer's row keeps its author, evidence and purpose and gains the signals.
|
|
@@ -76,7 +158,7 @@ export const relationProposalsOver = (context) => {
|
|
|
76
158
|
* Where a pair stands before a scan proposes it: a link joins it, a `relationship` proposal for it was rejected,
|
|
77
159
|
* or one is pending. A rejection is matched by the pair alone, whoever proposed it and with whatever scorer.
|
|
78
160
|
*/
|
|
79
|
-
state: (paired, {
|
|
161
|
+
state: (paired, { kind }) => {
|
|
80
162
|
let found;
|
|
81
163
|
try {
|
|
82
164
|
found = paired();
|
|
@@ -87,6 +169,7 @@ export const relationProposalsOver = (context) => {
|
|
|
87
169
|
throw error;
|
|
88
170
|
}
|
|
89
171
|
const { from, existing } = found;
|
|
172
|
+
const { to } = found.ends;
|
|
90
173
|
const rows = database
|
|
91
174
|
.prepare("SELECT id, status FROM proposed_actions WHERE kind='relationship' AND status IN ('proposed','rejected') " +
|
|
92
175
|
"AND target_type=? AND target_id=? AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=? " +
|
|
@@ -102,6 +185,7 @@ export const relationProposalsOver = (context) => {
|
|
|
102
185
|
},
|
|
103
186
|
/** The same pending pair returns the proposal already held; a scored one updates its score in place. */
|
|
104
187
|
propose: (from, input, by) => {
|
|
188
|
+
spanOf(input.startsAt, input.endsAt);
|
|
105
189
|
const evidence = input.evidence ?? [];
|
|
106
190
|
if (!Array.isArray(evidence) || evidence.length > 5 || evidence.some((ref) => typeof ref !== "string"))
|
|
107
191
|
throw new CliError("validation_error", "a relationship proposal cites up to 5 references");
|
|
@@ -109,8 +193,9 @@ export const relationProposalsOver = (context) => {
|
|
|
109
193
|
return write(database, () => {
|
|
110
194
|
const held = database
|
|
111
195
|
.prepare("SELECT id FROM proposed_actions WHERE kind='relationship' AND status='proposed' AND target_type=? AND target_id=? " +
|
|
112
|
-
"AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=?
|
|
113
|
-
|
|
196
|
+
"AND json_extract(payload,'$.to')=? AND json_extract(payload,'$.kind')=? " +
|
|
197
|
+
"AND (? IS NULL OR json_extract(payload,'$.role') IS ?) ORDER BY id LIMIT 1")
|
|
198
|
+
.get(from.type, from.id, input.to, input.kind, input.role ?? null, input.role ?? null);
|
|
114
199
|
if (held) {
|
|
115
200
|
const action = operations.get(String(held.id));
|
|
116
201
|
return scored ? rescored(action, input, scored, by) : action;
|
|
@@ -125,6 +210,9 @@ export const relationProposalsOver = (context) => {
|
|
|
125
210
|
kind: input.kind,
|
|
126
211
|
...(input.role === undefined ? {} : { role: input.role }),
|
|
127
212
|
...(input.purpose === undefined ? {} : { purpose: purposeOf(input.purpose) }),
|
|
213
|
+
...(input.position === undefined ? {} : { position: positionOf(input.position) }),
|
|
214
|
+
...(input.startsAt === undefined ? {} : { startsAt: input.startsAt }),
|
|
215
|
+
...(input.endsAt === undefined ? {} : { endsAt: input.endsAt }),
|
|
128
216
|
evidence,
|
|
129
217
|
...scored,
|
|
130
218
|
},
|
|
@@ -133,9 +221,10 @@ export const relationProposalsOver = (context) => {
|
|
|
133
221
|
});
|
|
134
222
|
},
|
|
135
223
|
rejected: (link, by, reason) => rejected(link, by, reason),
|
|
136
|
-
update: (link, input) => write(database, () =>
|
|
224
|
+
update: (link, input) => write(database, () => ownerUpdate(link, input)),
|
|
137
225
|
proposeUpdate: (link, input, by) => {
|
|
138
226
|
const changes = changesOf(input);
|
|
227
|
+
checkedRole(link, changes.role);
|
|
139
228
|
return write(database, () => {
|
|
140
229
|
const from = thingOf(database, link.from);
|
|
141
230
|
const held = database
|
|
@@ -155,7 +244,13 @@ export const relationProposalsOver = (context) => {
|
|
|
155
244
|
to: link.to,
|
|
156
245
|
kind: link.kind,
|
|
157
246
|
changes,
|
|
158
|
-
before: {
|
|
247
|
+
before: {
|
|
248
|
+
role: link.role,
|
|
249
|
+
purpose: link.purpose,
|
|
250
|
+
position: link.position ?? null,
|
|
251
|
+
startsAt: link.startsAt ?? null,
|
|
252
|
+
endsAt: link.endsAt ?? null,
|
|
253
|
+
},
|
|
159
254
|
},
|
|
160
255
|
...(input.reason === undefined ? {} : { reason: input.reason }),
|
|
161
256
|
});
|
|
@@ -174,7 +269,7 @@ export const relationProposalsOver = (context) => {
|
|
|
174
269
|
const row = database.prepare("SELECT * FROM links WHERE id = ?").get(Number(payload.relationship));
|
|
175
270
|
if (!row)
|
|
176
271
|
throw new CliError("not_found", `relationship ${payload.relationship} is gone`);
|
|
177
|
-
const link =
|
|
272
|
+
const link = ownerUpdate(linkOf(database, row), payload.changes);
|
|
178
273
|
return {
|
|
179
274
|
proposal: operations.approve(id, { relationship: link.id, ...(reason === undefined ? {} : { reason }) }, author),
|
|
180
275
|
link,
|
|
@@ -195,12 +290,18 @@ export const relationProposalsOver = (context) => {
|
|
|
195
290
|
return { proposal: operations.reject(id, author, reason === undefined ? undefined : { reason }), link: null };
|
|
196
291
|
const payload = proposal.payload;
|
|
197
292
|
const key = proposal.kind === "key_document";
|
|
293
|
+
const ends = key ? undefined : [thingOf(database, String(payload.from)), thingOf(database, String(payload.to))];
|
|
294
|
+
if (ends?.[0] && ends[1] && payload.role !== undefined)
|
|
295
|
+
checkStoredRole(database, payload.kind ?? "member-of", ends[0].type, ends[1].type, payload.role);
|
|
198
296
|
const link = insertLink(context, {
|
|
199
297
|
from: String(key ? payload.ref : payload.from),
|
|
200
298
|
to: String(key ? payload.project : payload.to),
|
|
201
299
|
kind: key ? "related-to" : (payload.kind ?? "member-of"),
|
|
202
300
|
...(key ? { role: "key" } : payload.role === undefined ? {} : { role: payload.role }),
|
|
203
301
|
...(key || payload.purpose === undefined ? {} : { purpose: payload.purpose }),
|
|
302
|
+
...(key || payload.position === undefined ? {} : { position: payload.position }),
|
|
303
|
+
...(key || payload.startsAt === undefined ? {} : { startsAt: payload.startsAt }),
|
|
304
|
+
...(key || payload.endsAt === undefined ? {} : { endsAt: payload.endsAt }),
|
|
204
305
|
...(proposal.reason === null ? {} : { evidence: proposal.reason }),
|
|
205
306
|
...decidedOrigin(decision.by),
|
|
206
307
|
});
|
|
@@ -220,6 +321,7 @@ export const relationProposalsOver = (context) => {
|
|
|
220
321
|
const link = linkOf(database, row);
|
|
221
322
|
if (!decision.confirm) {
|
|
222
323
|
rejected(link, decision.by, decision.reason);
|
|
324
|
+
database.prepare("UPDATE links SET updated_at = ? WHERE id = ?").run(now(), Number(id));
|
|
223
325
|
database.prepare("DELETE FROM links WHERE id = ?").run(Number(id));
|
|
224
326
|
return null;
|
|
225
327
|
}
|
|
@@ -245,6 +347,22 @@ const scoredOf = (input) => {
|
|
|
245
347
|
throw new CliError("validation_error", "a signal names its scorer, a weight of 0–1 and why, up to 500 characters");
|
|
246
348
|
return { score, signals: signals.map(({ scorer, weight, why }) => ({ scorer, weight, why })) };
|
|
247
349
|
};
|
|
350
|
+
const timeOf = (value, what) => {
|
|
351
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
352
|
+
throw new CliError("validation_error", `${what} is UTC milliseconds`);
|
|
353
|
+
return value;
|
|
354
|
+
};
|
|
355
|
+
/** A relationship ends after it starts. */
|
|
356
|
+
export const spanOf = (startsAt, endsAt) => {
|
|
357
|
+
if (startsAt != null && endsAt != null && endsAt <= startsAt)
|
|
358
|
+
throw new CliError("validation_error", "a relationship ends after it starts");
|
|
359
|
+
};
|
|
360
|
+
export const positionOf = (position) => {
|
|
361
|
+
const value = position.trim();
|
|
362
|
+
if (!value || value.length > 200)
|
|
363
|
+
throw new CliError("validation_error", "a position takes 1–200 characters");
|
|
364
|
+
return value;
|
|
365
|
+
};
|
|
248
366
|
/** What a relationship update sets, checked; `null` clears a field and an absent one is left alone. */
|
|
249
367
|
const changesOf = (input) => {
|
|
250
368
|
const changes = {};
|
|
@@ -252,8 +370,14 @@ const changesOf = (input) => {
|
|
|
252
370
|
changes.role = input.role === null ? null : roleOf(input.role);
|
|
253
371
|
if (input.purpose !== undefined)
|
|
254
372
|
changes.purpose = input.purpose === null ? null : purposeOf(input.purpose);
|
|
373
|
+
if (input.position !== undefined)
|
|
374
|
+
changes.position = input.position === null ? null : positionOf(input.position);
|
|
375
|
+
if (input.startsAt !== undefined)
|
|
376
|
+
changes.startsAt = input.startsAt === null ? null : timeOf(input.startsAt, "a start");
|
|
377
|
+
if (input.endsAt !== undefined)
|
|
378
|
+
changes.endsAt = input.endsAt === null ? null : timeOf(input.endsAt, "an end");
|
|
255
379
|
if (!Object.keys(changes).length)
|
|
256
|
-
throw new CliError("validation_error", "a relationship update sets a role, a purpose or
|
|
380
|
+
throw new CliError("validation_error", "a relationship update sets a role, a purpose, a position or its dates");
|
|
257
381
|
return changes;
|
|
258
382
|
};
|
|
259
383
|
const roleOf = (role) => {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { StoreContext } from "./open.js";
|
|
2
|
+
import { type RelationList } from "./relation-list.js";
|
|
3
|
+
import { type RelationRoles } from "./relation-roles.js";
|
|
4
|
+
export { checkStoredRole } from "./relation-roles.js";
|
|
5
|
+
/** The knowledge store's relationship reads: the filtered list and the role lists. */
|
|
6
|
+
export interface RelationReads extends RelationList, RelationRoles {
|
|
7
|
+
}
|
|
8
|
+
export declare const relationReadsOver: (context: StoreContext) => RelationReads;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { relationListOver } from "./relation-list.js";
|
|
2
|
+
import { relationRolesOver } from "./relation-roles.js";
|
|
3
|
+
export { checkStoredRole } from "./relation-roles.js";
|
|
4
|
+
export const relationReadsOver = (context) => ({
|
|
5
|
+
...relationListOver(context),
|
|
6
|
+
...relationRolesOver(context),
|
|
7
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type RoleList } from "../../domain/relations.js";
|
|
2
|
+
import type { CacheDatabase } from "../driver.js";
|
|
3
|
+
import type { StoreContext } from "./open.js";
|
|
4
|
+
export interface RelationRole {
|
|
5
|
+
id: string;
|
|
6
|
+
label: string | null;
|
|
7
|
+
builtIn: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface RelationRoles {
|
|
10
|
+
/** A list's roles: the built-in ones first, then the owner's, in the order he added them. */
|
|
11
|
+
roles(list: RoleList): Promise<RelationRole[]>;
|
|
12
|
+
/** Adds an owner role to a list; an id the list holds already is refused. */
|
|
13
|
+
addRole(list: RoleList, id: string, label?: string): Promise<RelationRole[]>;
|
|
14
|
+
/** Removes an owner role; a built-in one, or one a stored relationship still holds, is refused. */
|
|
15
|
+
removeRole(list: RoleList, id: string): Promise<RelationRole[]>;
|
|
16
|
+
}
|
|
17
|
+
/** The owner's roles for a list; a value this build cannot read is none. */
|
|
18
|
+
export declare const ownerRolesOf: (database: CacheDatabase, list: RoleList) => {
|
|
19
|
+
id: string;
|
|
20
|
+
label: string | null;
|
|
21
|
+
}[];
|
|
22
|
+
/** The owner's role ids a relationship of these ends may also take. */
|
|
23
|
+
export declare const extraRolesOf: (database: CacheDatabase, kind: string, from: string, to: string) => string[];
|
|
24
|
+
/** `checkRole` with the owner's own roles for the list the ends take. */
|
|
25
|
+
export declare const checkStoredRole: (database: CacheDatabase, kind: string, from: string, to: string, role: string) => string;
|
|
26
|
+
export declare const relationRolesOver: ({ database, now }: StoreContext) => RelationRoles;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { checkRole, ROLE_LISTS, roleListOf } from "../../domain/relations.js";
|
|
3
|
+
import { write } from "./transaction.js";
|
|
4
|
+
const settingOf = (list) => `relationships.roles.${list}`;
|
|
5
|
+
const isList = (list) => Object.hasOwn(ROLE_LISTS, list);
|
|
6
|
+
const listOf = (list) => {
|
|
7
|
+
if (!isList(list))
|
|
8
|
+
throw new CliError("validation_error", `a role list is one of ${Object.keys(ROLE_LISTS).join(", ")}`);
|
|
9
|
+
return list;
|
|
10
|
+
};
|
|
11
|
+
/** The owner's roles for a list; a value this build cannot read is none. */
|
|
12
|
+
export const ownerRolesOf = (database, list) => {
|
|
13
|
+
const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(settingOf(list));
|
|
14
|
+
try {
|
|
15
|
+
const value = row ? JSON.parse(String(row.value)) : [];
|
|
16
|
+
return Array.isArray(value)
|
|
17
|
+
? value.flatMap((one) => typeof one?.id === "string" ? [{ id: one.id, label: typeof one.label === "string" ? one.label : null }] : [])
|
|
18
|
+
: [];
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/** The owner's role ids a relationship of these ends may also take. */
|
|
25
|
+
export const extraRolesOf = (database, kind, from, to) => {
|
|
26
|
+
const list = roleListOf(kind, from, to);
|
|
27
|
+
return list ? ownerRolesOf(database, list).map(({ id }) => id) : [];
|
|
28
|
+
};
|
|
29
|
+
/** `checkRole` with the owner's own roles for the list the ends take. */
|
|
30
|
+
export const checkStoredRole = (database, kind, from, to, role) => checkRole(kind, from, to, role, extraRolesOf(database, kind, from, to));
|
|
31
|
+
/** The links whose role comes from this list: a person's on an organization or a project, a deal's or a lead's people. */
|
|
32
|
+
const usedBy = (database, list, role) => {
|
|
33
|
+
const links = list === "deal"
|
|
34
|
+
? "kind = 'related-to' AND from_type IN ('deal', 'lead')"
|
|
35
|
+
: `kind = 'member-of' AND from_type = 'person' AND to_type = '${list}'`;
|
|
36
|
+
// A pending proposal would make the role a relationship's once approved: it counts as a use.
|
|
37
|
+
const proposals = list === "deal"
|
|
38
|
+
? "target_type IN ('deal', 'lead') AND json_extract(payload, '$.kind') = 'related-to'"
|
|
39
|
+
: `target_type = 'person' AND json_extract(payload, '$.kind') = 'member-of' AND json_extract(payload, '$.to') LIKE '${list}:%'`;
|
|
40
|
+
return Number(database
|
|
41
|
+
.prepare(`SELECT (SELECT count(*) FROM links WHERE role = ? AND ${links}) + (SELECT count(*) FROM proposed_actions ` +
|
|
42
|
+
`WHERE status = 'proposed' AND ${proposals} AND ((kind = 'relationship' AND json_extract(payload, '$.role') = ?) ` +
|
|
43
|
+
"OR (kind = 'relationship_update' AND json_extract(payload, '$.changes.role') = ?))) AS n")
|
|
44
|
+
.get(role, role, role)?.n);
|
|
45
|
+
};
|
|
46
|
+
export const relationRolesOver = ({ database, now }) => {
|
|
47
|
+
const all = (list) => [
|
|
48
|
+
...ROLE_LISTS[list].map((id) => ({ id, label: null, builtIn: true })),
|
|
49
|
+
...ownerRolesOf(database, list).map((role) => ({ ...role, builtIn: false })),
|
|
50
|
+
];
|
|
51
|
+
const save = (list, roles) => database
|
|
52
|
+
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
53
|
+
.run(settingOf(list), JSON.stringify(roles.map(({ id, label }) => (label ? { id, label } : { id }))), now());
|
|
54
|
+
return {
|
|
55
|
+
roles: async (list) => all(listOf(list)),
|
|
56
|
+
addRole: async (name, id, label) => write(database, () => {
|
|
57
|
+
const list = listOf(name);
|
|
58
|
+
const role = id.trim();
|
|
59
|
+
if (!/^[a-z][a-z0-9-]{0,39}$/.test(role))
|
|
60
|
+
throw new CliError("validation_error", "a role id is 1–40 lowercase letters, digits and -, from a letter");
|
|
61
|
+
const text = label?.trim() || null;
|
|
62
|
+
if (text !== null && text.length > 80)
|
|
63
|
+
throw new CliError("validation_error", "a role's label takes 1–80 characters");
|
|
64
|
+
if (all(list).some((one) => one.id === role))
|
|
65
|
+
throw new CliError("validation_error", `the ${list} roles hold ${role} already`, {
|
|
66
|
+
reason: "relationship.role-exists",
|
|
67
|
+
});
|
|
68
|
+
save(list, [...ownerRolesOf(database, list), { id: role, label: text }]);
|
|
69
|
+
return all(list);
|
|
70
|
+
}),
|
|
71
|
+
removeRole: async (name, given) => write(database, () => {
|
|
72
|
+
const list = listOf(name);
|
|
73
|
+
const id = given.trim();
|
|
74
|
+
if (ROLE_LISTS[list].includes(id))
|
|
75
|
+
throw new CliError("validation_error", `${id} is a built-in ${list} role and stays`, {
|
|
76
|
+
reason: "relationship.role-built-in",
|
|
77
|
+
});
|
|
78
|
+
const owned = ownerRolesOf(database, list);
|
|
79
|
+
if (!owned.some((one) => one.id === id))
|
|
80
|
+
throw new CliError("not_found", `the ${list} roles hold no ${id}`);
|
|
81
|
+
const held = usedBy(database, list, id);
|
|
82
|
+
if (held)
|
|
83
|
+
throw new CliError("validation_error", `${held} relationship(s) still hold the ${list} role ${id}`, {
|
|
84
|
+
reason: "relationship.role-in-use",
|
|
85
|
+
count: held,
|
|
86
|
+
});
|
|
87
|
+
save(list, owned.filter((one) => one.id !== id));
|
|
88
|
+
return all(list);
|
|
89
|
+
}),
|
|
90
|
+
};
|
|
91
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type RelationKind } from "../../domain/relations.js";
|
|
2
|
+
import type { AccountKey } from "../types.js";
|
|
3
|
+
import type { Author } from "./memories.js";
|
|
4
|
+
import type { StoreContext } from "./open.js";
|
|
5
|
+
/** One relationship as a source account reports it, by the store's refs. */
|
|
6
|
+
export interface ReportedRelation {
|
|
7
|
+
from: string;
|
|
8
|
+
to: string;
|
|
9
|
+
kind: RelationKind;
|
|
10
|
+
role?: string | null;
|
|
11
|
+
/** Epoch ms; `endsAt` exclusive. Only what the source gives: never a guess. */
|
|
12
|
+
startsAt?: number | null;
|
|
13
|
+
endsAt?: number | null;
|
|
14
|
+
/** Kept on the link: the source's own role name, a job title, how it was derived. */
|
|
15
|
+
metadata?: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Which of the account's relationships a call reports completely: those from the `from` refs or to the `to` refs, of
|
|
19
|
+
* these kinds and, when given, these roles. One it holds there and the call lacks is withdrawn; nothing else is touched.
|
|
20
|
+
*/
|
|
21
|
+
export interface ReportedScope {
|
|
22
|
+
from: string[];
|
|
23
|
+
to?: string[];
|
|
24
|
+
kinds: RelationKind[];
|
|
25
|
+
roles?: string[];
|
|
26
|
+
}
|
|
27
|
+
export interface ReportedIssue {
|
|
28
|
+
reason: "relationship.reference-unknown" | "relationship.invalid";
|
|
29
|
+
message: string;
|
|
30
|
+
from: string;
|
|
31
|
+
to: string;
|
|
32
|
+
kind: RelationKind;
|
|
33
|
+
}
|
|
34
|
+
export interface ReportedSync {
|
|
35
|
+
added: number;
|
|
36
|
+
kept: number;
|
|
37
|
+
restored: number;
|
|
38
|
+
withdrawn: number;
|
|
39
|
+
/** New relationships waiting as `relationship` proposals: the account's setting is `review`. */
|
|
40
|
+
proposed: number;
|
|
41
|
+
/** Left out: the owner removed or rejected that very relationship, role included. */
|
|
42
|
+
skippedOwnerRejected: number;
|
|
43
|
+
issues: ReportedIssue[];
|
|
44
|
+
}
|
|
45
|
+
export interface ReportedOptions {
|
|
46
|
+
/** `links.source` of a link it writes; `import` when absent. */
|
|
47
|
+
source?: string;
|
|
48
|
+
/** Who proposes in `review` mode; the source's provider, as a rule, when absent. */
|
|
49
|
+
by?: Exclude<Author, "owner">;
|
|
50
|
+
}
|
|
51
|
+
export interface RelationsStore {
|
|
52
|
+
/**
|
|
53
|
+
* Writes what a source account reports as a diff keyed by the relationship's unique key. A new one is a `reported`
|
|
54
|
+
* link (a `relationship` proposal when the account's `crm.<provider>:<account>.links` is `review`); one held is
|
|
55
|
+
* kept; one inside `scope` it no longer reports is withdrawn (`deleted_at`), never deleted. A link the owner
|
|
56
|
+
* confirmed is never withdrawn, and one the owner removed or rejected, with the same role, is never written again.
|
|
57
|
+
* Another role on a pair is another relationship. A ref the store does not hold is an issue, not an error.
|
|
58
|
+
*/
|
|
59
|
+
syncReported(key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, options?: ReportedOptions): Promise<ReportedSync>;
|
|
60
|
+
}
|
|
61
|
+
/** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
|
|
62
|
+
export declare const syncReportedIn: (context: StoreContext, key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, { source, by }?: ReportedOptions) => ReportedSync;
|
|
63
|
+
export declare const relationsStoreOver: (context: StoreContext) => RelationsStore;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { checkEnds, isSymmetric } from "../../domain/relations.js";
|
|
3
|
+
import { accountPk } from "./accounts.js";
|
|
4
|
+
import { crmLinkMode } from "./crm-settings.js";
|
|
5
|
+
import { linkKind } from "./link-kinds.js";
|
|
6
|
+
import { relationProposalsOver } from "./relation-proposals.js";
|
|
7
|
+
import { checkStoredRole } from "./relation-roles.js";
|
|
8
|
+
import { referenceOfThing, thingOf } from "./things.js";
|
|
9
|
+
import { write } from "./transaction.js";
|
|
10
|
+
const metadataOf = (relation) => relation.metadata && Object.keys(relation.metadata).length ? JSON.stringify(relation.metadata) : null;
|
|
11
|
+
/** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
|
|
12
|
+
export const syncReportedIn = (context, key, relationships, scope, { source = "import", by = { bot: key.provider, kind: "rule" } } = {}) => {
|
|
13
|
+
const { database, now } = context;
|
|
14
|
+
const proposals = relationProposalsOver(context);
|
|
15
|
+
const accountId = accountPk(context, key);
|
|
16
|
+
const review = crmLinkMode(database, key) === "review";
|
|
17
|
+
const at = now();
|
|
18
|
+
const result = {
|
|
19
|
+
added: 0,
|
|
20
|
+
kept: 0,
|
|
21
|
+
restored: 0,
|
|
22
|
+
withdrawn: 0,
|
|
23
|
+
proposed: 0,
|
|
24
|
+
skippedOwnerRejected: 0,
|
|
25
|
+
issues: [],
|
|
26
|
+
};
|
|
27
|
+
const seen = new Set();
|
|
28
|
+
const issue = (relation, reason, message) => result.issues.push({ reason, message, from: relation.from, to: relation.to, kind: relation.kind });
|
|
29
|
+
const sameKey = "kind = ? AND from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND anchor IS NULL AND ifnull(role, '') = ?";
|
|
30
|
+
for (const relation of relationships) {
|
|
31
|
+
let from = thingOf(database, relation.from);
|
|
32
|
+
let to = thingOf(database, relation.to);
|
|
33
|
+
if (!from || !to) {
|
|
34
|
+
issue(relation, "relationship.reference-unknown", `${!from ? relation.from : relation.to} is not in the store`);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const role = relation.role?.trim() || null;
|
|
38
|
+
try {
|
|
39
|
+
if (from.type === to.type && from.id === to.id)
|
|
40
|
+
throw new CliError("validation_error", "a relationship needs two distinct ends");
|
|
41
|
+
checkEnds(relation.kind, from.type, to.type);
|
|
42
|
+
if (role !== null)
|
|
43
|
+
checkStoredRole(database, relation.kind, from.type, to.type, role);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (!(error instanceof CliError))
|
|
47
|
+
throw error;
|
|
48
|
+
issue(relation, "relationship.invalid", error.message);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (isSymmetric(relation.kind) && to.id < from.id)
|
|
52
|
+
[from, to] = [to, from];
|
|
53
|
+
const wanted = [relation.kind, from.type, from.id, to.type, to.id, role ?? ""];
|
|
54
|
+
// The owner's link of the same role answers for the source too, and a confirmed one is never withdrawn.
|
|
55
|
+
if (database.prepare(`SELECT 1 FROM links WHERE ${sameKey} AND confirmed = 1 LIMIT 1`).get(...wanted))
|
|
56
|
+
continue;
|
|
57
|
+
const toRef = referenceOfThing(database, to);
|
|
58
|
+
if (rejected(context, from, toRef, relation.kind, role)) {
|
|
59
|
+
result.skippedOwnerRejected += 1;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const held = database.prepare(`SELECT * FROM links WHERE ${sameKey} AND account_id = ?`).get(...wanted, accountId);
|
|
63
|
+
const startsAt = relation.startsAt ?? null;
|
|
64
|
+
const endsAt = relation.endsAt ?? null;
|
|
65
|
+
const metadata = metadataOf(relation);
|
|
66
|
+
if (held) {
|
|
67
|
+
seen.add(Number(held.id));
|
|
68
|
+
if (held.deleted_at != null)
|
|
69
|
+
result.restored += 1;
|
|
70
|
+
else
|
|
71
|
+
result.kept += 1;
|
|
72
|
+
database
|
|
73
|
+
.prepare("UPDATE links SET deleted_at = NULL, starts_at = ?, ends_at = ?, metadata = ?, updated_at = ? WHERE id = ?")
|
|
74
|
+
.run(startsAt, endsAt, metadata, at, Number(held.id));
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (review) {
|
|
78
|
+
proposals.propose(from, {
|
|
79
|
+
from: referenceOfThing(database, from),
|
|
80
|
+
to: toRef,
|
|
81
|
+
kind: relation.kind,
|
|
82
|
+
...(role === null ? {} : { role }),
|
|
83
|
+
reason: `reported by ${key.provider}:${key.account}`,
|
|
84
|
+
}, by);
|
|
85
|
+
result.proposed += 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const row = database
|
|
89
|
+
.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, source, metadata, confirmed, account_id, " +
|
|
90
|
+
"starts_at, ends_at, created_at, author, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, 'rule', ?) " +
|
|
91
|
+
"RETURNING id")
|
|
92
|
+
.get(from.type, from.id, to.type, to.id, relation.kind, role, source, metadata, accountId, startsAt, endsAt, at, at);
|
|
93
|
+
seen.add(Number(row?.id));
|
|
94
|
+
result.added += 1;
|
|
95
|
+
}
|
|
96
|
+
const withdraw = database.prepare("UPDATE links SET deleted_at = ?, updated_at = ? WHERE id = ?");
|
|
97
|
+
const kinds = scope.kinds.map(linkKind).join(", ");
|
|
98
|
+
const roles = scope.roles?.map(() => "?").join(", ");
|
|
99
|
+
const ends = [
|
|
100
|
+
...[...new Set(scope.from)].map((ref) => ["from", ref]),
|
|
101
|
+
...[...new Set(scope.to ?? [])].map((ref) => ["to", ref]),
|
|
102
|
+
];
|
|
103
|
+
for (const [end, ref] of kinds ? ends : []) {
|
|
104
|
+
const thing = thingOf(database, ref);
|
|
105
|
+
if (!thing)
|
|
106
|
+
continue;
|
|
107
|
+
// A partnership is stored once, either way round, so either end covers it.
|
|
108
|
+
const match = end === "from"
|
|
109
|
+
? `((from_type = ? AND from_id = ?) OR (kind = ${linkKind("partner-of")} AND to_type = ? AND to_id = ?))`
|
|
110
|
+
: `((to_type = ? AND to_id = ?) OR (kind = ${linkKind("partner-of")} AND from_type = ? AND from_id = ?))`;
|
|
111
|
+
const rows = database
|
|
112
|
+
.prepare(`SELECT id FROM links WHERE account_id = ? AND confirmed = 0 AND deleted_at IS NULL AND kind IN (${kinds}) ` +
|
|
113
|
+
`AND ${match}${roles ? ` AND ifnull(role, '') IN (${roles})` : ""}`)
|
|
114
|
+
.all(accountId, thing.type, thing.id, thing.type, thing.id, ...(scope.roles ?? []));
|
|
115
|
+
for (const row of rows)
|
|
116
|
+
if (!seen.has(Number(row.id))) {
|
|
117
|
+
seen.add(Number(row.id));
|
|
118
|
+
withdraw.run(at, at, Number(row.id));
|
|
119
|
+
result.withdrawn += 1;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
/** The owner rejected or removed exactly this relationship: its pair, kind and role, whoever reported it. */
|
|
125
|
+
const rejected = ({ database }, from, to, kind, role) => database
|
|
126
|
+
.prepare("SELECT 1 FROM proposed_actions WHERE kind = 'relationship' AND status = 'rejected' AND target_type = ? " +
|
|
127
|
+
"AND target_id = ? AND json_extract(payload, '$.to') = ? AND json_extract(payload, '$.kind') = ? " +
|
|
128
|
+
"AND json_extract(payload, '$.role') IS ? LIMIT 1")
|
|
129
|
+
.get(from.type, from.id, to, kind, role) !== undefined;
|
|
130
|
+
export const relationsStoreOver = (context) => ({
|
|
131
|
+
syncReported: async (key, relationships, scope, options) => write(context.database, () => syncReportedIn(context, key, relationships, scope, options)),
|
|
132
|
+
});
|