@wirecat/cli-core 0.605.0 → 0.606.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 +98 -0
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +1 -0
- package/dist/cli/store-settings.js +38 -4
- package/dist/crm/cli/index.js +3 -1
- 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/domain/crm.d.ts +41 -2
- package/dist/domain/deals.d.ts +5 -2
- package/dist/domain/deals.js +5 -2
- package/dist/domain/relations.d.ts +125 -0
- package/dist/domain/relations.js +107 -0
- package/dist/entities/deal.d.ts +2 -2
- package/dist/entities/deal.js +2 -1
- package/dist/entities/index.d.ts +17 -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 +12 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- 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/services/link-scorers/scan.js +2 -1
- package/dist/services/link-scorers/shared.js +2 -1
- package/dist/services/project-status/index.js +2 -1
- package/dist/services/stored-project-gathering.js +4 -3
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/index.d.ts +6 -1
- package/dist/store/index.js +1 -0
- 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/sqlite/crm-settings.d.ts +28 -0
- package/dist/store/sqlite/crm-settings.js +80 -0
- package/dist/store/sqlite/crm.d.ts +42 -2
- package/dist/store/sqlite/crm.js +397 -36
- package/dist/store/sqlite/deals.js +3 -2
- package/dist/store/sqlite/involvement-queue.js +4 -3
- package/dist/store/sqlite/knowledge.d.ts +7 -3
- package/dist/store/sqlite/knowledge.js +43 -31
- package/dist/store/sqlite/link-kinds.d.ts +2 -3
- package/dist/store/sqlite/link-kinds.js +4 -2
- package/dist/store/sqlite/manifest.js +5 -0
- package/dist/store/sqlite/memories.d.ts +1 -1
- package/dist/store/sqlite/memories.js +33 -7
- package/dist/store/sqlite/migrations.generated.js +31 -0
- package/dist/store/sqlite/notes.d.ts +3 -2
- package/dist/store/sqlite/notes.js +23 -6
- package/dist/store/sqlite/organizations.d.ts +8 -0
- package/dist/store/sqlite/organizations.js +14 -0
- package/dist/store/sqlite/person-preparation.d.ts +1 -1
- package/dist/store/sqlite/person-preparation.js +3 -2
- package/dist/store/sqlite/project-transfer/records.js +14 -3
- package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +6 -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/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 +2 -296
- package/dist/store/sqlite/schema.js +2 -24
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +3 -3
|
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
import { walkQuery } from "@wirecat/cli-base/query";
|
|
3
3
|
import { parseLocator } from "../../domain/locator.js";
|
|
4
4
|
import { formatReference, parseReference } from "../../domain/references.js";
|
|
5
|
+
import { checkEnds, isSymmetric, notOverriddenSql } from "../../domain/relations.js";
|
|
5
6
|
import { normalizeTag } from "../../domain/tags.js";
|
|
6
7
|
import { normalizeVocabularyName } from "../../domain/vocabulary.js";
|
|
7
8
|
import { formatMeetingReference } from "../../meetings/index.js";
|
|
@@ -16,7 +17,8 @@ import { holdingText } from "./note-index.js";
|
|
|
16
17
|
import { insertLink, linkOf } from "./notes.js";
|
|
17
18
|
import { organizationOf, organizationsStoreOver } from "./organizations.js";
|
|
18
19
|
import { queryFilter } from "./query-filter.js";
|
|
19
|
-
import { relationOf, relationProposalsOver, } from "./relation-proposals.js";
|
|
20
|
+
import { relationOf as relationAt, relationProposalsOver, } from "./relation-proposals.js";
|
|
21
|
+
import { checkStoredRole, relationReadsOver } from "./relation-reads.js";
|
|
20
22
|
import { addTags as addThingTags, canonicalTagNamed, createTag, labelsOf, liveTagging, removeTags as removeThingTags, setMainTopic, } from "./tags.js";
|
|
21
23
|
import { INBOX_KEY_LENGTH, TASK_KEY_PREFIXES } from "./task-keys.js";
|
|
22
24
|
import { inboxKey, taskAccountOf, taskIdOf, taskRowOf } from "./tasks.js";
|
|
@@ -54,8 +56,9 @@ const oneOf = (value, allowed, what) => {
|
|
|
54
56
|
throw new CliError("validation_error", `${what} is one of ${allowed.join(", ")}`);
|
|
55
57
|
return value;
|
|
56
58
|
};
|
|
57
|
-
/** What a relationship may connect. */
|
|
59
|
+
/** What a relationship may connect; a deal or a lead only as the end its people hang from. */
|
|
58
60
|
const RELATED = ["person", "organization", "project", "task"];
|
|
61
|
+
const DEALS = ["deal", "lead"];
|
|
59
62
|
/** What a label without an account may sit on; a chat, contact or message is the messenger's tag. */
|
|
60
63
|
const LABELLED = {
|
|
61
64
|
note: "note",
|
|
@@ -221,6 +224,7 @@ export const knowledgeStoreOver = (context) => {
|
|
|
221
224
|
createdAt: iso(row.created_at),
|
|
222
225
|
});
|
|
223
226
|
const proposals = relationProposalsOver(context);
|
|
227
|
+
const relationOf = (link) => relationAt(link, now());
|
|
224
228
|
const RELATIONS = `SELECT * FROM links WHERE kind IN (${RELATION_KINDS.map(linkKind).join(",")}) AND to_id IS NOT NULL`;
|
|
225
229
|
const relation = (id) => {
|
|
226
230
|
const row = /^\d+$/.test(id) ? database.prepare(`${RELATIONS} AND id = ?`).get(Number(id)) : undefined;
|
|
@@ -228,26 +232,33 @@ export const knowledgeStoreOver = (context) => {
|
|
|
228
232
|
throw new CliError("not_found", "no relationship with that id");
|
|
229
233
|
return row;
|
|
230
234
|
};
|
|
231
|
-
/** The two ends
|
|
235
|
+
/** The two ends, checked by the registry, in stored order (a symmetric pair's lower id first), and their link. */
|
|
232
236
|
const pair = (key, input) => {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (
|
|
236
|
-
throw new CliError("validation_error", "a relationship needs distinct references
|
|
237
|
-
|
|
238
|
-
|
|
237
|
+
let from = related(key, input.from, true);
|
|
238
|
+
let to = related(key, input.to);
|
|
239
|
+
if (from.type === to.type && from.id === to.id)
|
|
240
|
+
throw new CliError("validation_error", "a relationship needs two distinct references");
|
|
241
|
+
checkEnds(input.kind, from.type, to.type);
|
|
242
|
+
if (input.role !== undefined)
|
|
243
|
+
checkStoredRole(database, input.kind, from.type, to.type, input.role.trim());
|
|
244
|
+
let ends = { from: input.from, to: input.to };
|
|
245
|
+
if (isSymmetric(input.kind) && to.id < from.id)
|
|
246
|
+
[from, to, ends] = [to, from, { from: input.to, to: input.from }];
|
|
247
|
+
const role = input.role === undefined ? null : input.role.trim();
|
|
239
248
|
const existing = database
|
|
240
|
-
.prepare(`${RELATIONS} AND from_type=? AND from_id=? AND to_type=? AND to_id=? AND kind
|
|
241
|
-
|
|
242
|
-
|
|
249
|
+
.prepare(`${RELATIONS} AND from_type=? AND from_id=? AND to_type=? AND to_id=? AND kind=? AND account_id IS NULL ` +
|
|
250
|
+
"AND (? IS NULL OR ifnull(role, '') = ?)")
|
|
251
|
+
.get(from.type, from.id, to.type, to.id, input.kind, role, role);
|
|
252
|
+
return { from, to, existing, ends };
|
|
243
253
|
};
|
|
244
254
|
/** A chat may only be the member: its reference names its own account, so it is never another account's. */
|
|
245
255
|
const related = (key, reference, member = false) => {
|
|
246
256
|
checked(key);
|
|
247
257
|
const thing = thingOf(database, reference);
|
|
248
258
|
const chat = member && (thing?.type === "chat" || thing?.type === "email_thread");
|
|
249
|
-
|
|
250
|
-
|
|
259
|
+
const end = thing && (RELATED.includes(thing.type) || chat || (member && DEALS.includes(thing.type)));
|
|
260
|
+
if (!thing || !end || stateOfThing(database, thing) !== "available")
|
|
261
|
+
throw new CliError("not_found", `reference needs a stored person:, organization:, project:${member ? ", task:, deal:, lead: or chat:" : " or task:"}`);
|
|
251
262
|
if (chat && key !== null) {
|
|
252
263
|
const parsed = parseReference(reference);
|
|
253
264
|
if (parsed.provider !== key.provider || parsed.account !== key.account)
|
|
@@ -292,6 +303,7 @@ export const knowledgeStoreOver = (context) => {
|
|
|
292
303
|
...vocabularyStoreOver(context),
|
|
293
304
|
...organizationsStoreOver(context),
|
|
294
305
|
...meetingProjectsStoreOver(context),
|
|
306
|
+
...relationReadsOver(context),
|
|
295
307
|
taskIds: async (key, options = {}) => {
|
|
296
308
|
const { limit, offset } = bounded(options.limit, options.offset);
|
|
297
309
|
if (options.state !== undefined && !["open", "done", "dismissed"].includes(options.state))
|
|
@@ -518,36 +530,26 @@ export const knowledgeStoreOver = (context) => {
|
|
|
518
530
|
throw new CliError("validation_error", "a relationship names who writes it: the owner or an agent", {
|
|
519
531
|
reason: "proposal.decider-required",
|
|
520
532
|
});
|
|
521
|
-
const { from, existing } = pair(key, input);
|
|
533
|
+
const { from, existing, ends } = pair(key, input);
|
|
522
534
|
if (input.by !== "owner") {
|
|
523
535
|
if (existing)
|
|
524
536
|
throw new CliError("validation_error", `relationship ${String(existing.id)} already links them`, {
|
|
525
537
|
reason: "relationship.exists",
|
|
526
538
|
});
|
|
527
|
-
return proposals.propose(from, { ...input, ...(input.evidence === undefined ? {} : { reason: input.evidence }), evidence: [] }, input.by);
|
|
539
|
+
return proposals.propose(from, { ...input, ...ends, ...(input.evidence === undefined ? {} : { reason: input.evidence }), evidence: [] }, input.by);
|
|
528
540
|
}
|
|
529
541
|
if (existing)
|
|
530
542
|
return relationOf(linkOf(database, existing));
|
|
531
543
|
const confirmed = input.confirmed !== false;
|
|
532
|
-
return relationOf(write(database, () => insertLink(context, {
|
|
533
|
-
from: input.from,
|
|
534
|
-
to: input.to,
|
|
535
|
-
kind: input.kind,
|
|
536
|
-
origin: confirmed ? "owner" : "suggested",
|
|
537
|
-
confirmed,
|
|
538
|
-
...(input.role === undefined ? {} : { role: input.role }),
|
|
539
|
-
...(input.purpose === undefined ? {} : { purpose: input.purpose }),
|
|
540
|
-
...(input.evidence === undefined ? {} : { evidence: input.evidence }),
|
|
541
|
-
...(input.provenance === undefined ? {} : { provenance: input.provenance }),
|
|
542
|
-
})));
|
|
544
|
+
return relationOf(write(database, () => insertLink(context, { ...input, ...ends, by: "owner", origin: confirmed ? "owner" : "suggested", confirmed })));
|
|
543
545
|
}),
|
|
544
546
|
proposeRelation: async (key, input, by) => {
|
|
545
|
-
const { from, existing } = pair(key, input);
|
|
547
|
+
const { from, existing, ends } = pair(key, input);
|
|
546
548
|
if (existing)
|
|
547
549
|
throw new CliError("validation_error", `relationship ${String(existing.id)} already links them`, {
|
|
548
550
|
reason: "relationship.exists",
|
|
549
551
|
});
|
|
550
|
-
return proposals.propose(from, input, by);
|
|
552
|
+
return proposals.propose(from, { ...input, ...ends }, by);
|
|
551
553
|
},
|
|
552
554
|
relationState: async (key, input) => proposals.state(() => pair(key, input), input),
|
|
553
555
|
updateRelation: (async (key, id, input) => {
|
|
@@ -557,6 +559,13 @@ export const knowledgeStoreOver = (context) => {
|
|
|
557
559
|
return relationOf(proposals.update(link, input));
|
|
558
560
|
return proposals.proposeUpdate(link, input, input.by);
|
|
559
561
|
}),
|
|
562
|
+
endRelation: (async (key, id, at, by) => {
|
|
563
|
+
checked(key);
|
|
564
|
+
const link = linkOf(database, relation(id));
|
|
565
|
+
if (by === "owner")
|
|
566
|
+
return relationOf(proposals.update(link, { endsAt: at }));
|
|
567
|
+
return proposals.proposeUpdate(link, { endsAt: at }, by);
|
|
568
|
+
}),
|
|
560
569
|
decideRelationUpdate: async (id, decision) => {
|
|
561
570
|
const { proposal, link } = proposals.decideUpdate(id, decision);
|
|
562
571
|
return { proposal, relation: link && relationOf(link) };
|
|
@@ -569,7 +578,9 @@ export const knowledgeStoreOver = (context) => {
|
|
|
569
578
|
if (reference !== undefined && !thing)
|
|
570
579
|
return [];
|
|
571
580
|
return database
|
|
572
|
-
.prepare(
|
|
581
|
+
.prepare(
|
|
582
|
+
// Live ones first: a long history of withdrawn links never pushes them past the cap.
|
|
583
|
+
`${RELATIONS} AND ${notOverriddenSql("links")} AND (? IS NULL OR (from_type=? AND from_id=?) OR (to_type=? AND to_id=?)) ORDER BY deleted_at IS NOT NULL, created_at, id LIMIT 500`)
|
|
573
584
|
.all(thing?.type ?? null, thing?.type ?? null, thing?.id ?? null, thing?.type ?? null, thing?.id ?? null)
|
|
574
585
|
.map((row) => relationOf(linkOf(database, row)));
|
|
575
586
|
},
|
|
@@ -579,8 +590,9 @@ export const knowledgeStoreOver = (context) => {
|
|
|
579
590
|
const link = linkOf(database, row);
|
|
580
591
|
assertMayDecide({ id: `link:${id}`, proposedBy: UNVERIFIED }, by, context.decisions);
|
|
581
592
|
write(database, () => {
|
|
582
|
-
if (
|
|
593
|
+
if (link.overrides === undefined)
|
|
583
594
|
proposals.rejected(link, by);
|
|
595
|
+
database.prepare("UPDATE links SET updated_at = ? WHERE id = ?").run(now(), Number(id));
|
|
584
596
|
database.prepare("DELETE FROM links WHERE id = ?").run(Number(id));
|
|
585
597
|
});
|
|
586
598
|
return { id, removed: true };
|
|
@@ -2,13 +2,12 @@
|
|
|
2
2
|
* Every kind a `links` row may have. The schema doc's description of `links` names exactly these
|
|
3
3
|
* (`schema.test.ts` checks it); a writer that needs a new kind adds it here first.
|
|
4
4
|
*/
|
|
5
|
-
export declare const LINK_KINDS: readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "assigned-to", "attached"];
|
|
5
|
+
export declare const LINK_KINDS: readonly ["links-to", "blocked-by", "follow-up-of", "about", "member-of", "labelled", "answered-by", "evidence", "created-from", "duplicate-of", "related-to", "reports-to", "customer-of", "partner-of", "assigned-to", "attached"];
|
|
6
6
|
export type LinkKind = (typeof LINK_KINDS)[number];
|
|
7
7
|
/** Where a caller may say a link came from. */
|
|
8
8
|
export declare const LINK_ORIGINS: readonly ["file", "owner", "suggested", "message"];
|
|
9
9
|
/** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
|
|
10
10
|
export declare const LINK_SOURCES: readonly ["file", "owner", "suggested", "message", "calendar"];
|
|
11
|
-
|
|
12
|
-
export declare const RELATION_KINDS: readonly ["member-of", "related-to"];
|
|
11
|
+
export { RELATION_KINDS } from "../../domain/relations.js";
|
|
13
12
|
/** A kind as an SQL literal, so a kind written into a query is checked against the list. */
|
|
14
13
|
export declare const linkKind: (kind: LinkKind) => string;
|
|
@@ -14,6 +14,9 @@ export const LINK_KINDS = [
|
|
|
14
14
|
"created-from",
|
|
15
15
|
"duplicate-of",
|
|
16
16
|
"related-to",
|
|
17
|
+
"reports-to",
|
|
18
|
+
"customer-of",
|
|
19
|
+
"partner-of",
|
|
17
20
|
"assigned-to",
|
|
18
21
|
"attached",
|
|
19
22
|
];
|
|
@@ -21,7 +24,6 @@ export const LINK_KINDS = [
|
|
|
21
24
|
export const LINK_ORIGINS = ["file", "owner", "suggested", "message"];
|
|
22
25
|
/** Where a stored link came from: an origin a caller gives, or `calendar`, which only the store writes. */
|
|
23
26
|
export const LINK_SOURCES = [...LINK_ORIGINS, "calendar"];
|
|
24
|
-
|
|
25
|
-
export const RELATION_KINDS = ["member-of", "related-to"];
|
|
27
|
+
export { RELATION_KINDS } from "../../domain/relations.js";
|
|
26
28
|
/** A kind as an SQL literal, so a kind written into a query is checked against the list. */
|
|
27
29
|
export const linkKind = (kind) => `'${kind}'`;
|
|
@@ -28,6 +28,8 @@ const V31_TABLES = [
|
|
|
28
28
|
"syncs",
|
|
29
29
|
"taggings",
|
|
30
30
|
];
|
|
31
|
+
/** Version 56 rewrites CRM links and folds duplicates, which an older build would write again. */
|
|
32
|
+
const V56_TABLES = ["links", "proposed_actions"];
|
|
31
33
|
/** One migration creates the whole schema; every later one is added as the next version. */
|
|
32
34
|
export const MANIFEST = [
|
|
33
35
|
{ name: "20261010184427_initial", version: 1, minCompatible: 1 },
|
|
@@ -113,6 +115,9 @@ export const MANIFEST = [
|
|
|
113
115
|
{ name: "20261106225547_version-54-crm-fields", version: 54, minCompatible: 34 },
|
|
114
116
|
{ name: "20261107032742_version-55-decision-requests", version: 55, minCompatible: 34 },
|
|
115
117
|
{ name: "20261107043407_version-55-decision-requests-index", version: 55, minCompatible: 34 },
|
|
118
|
+
{ name: "20261107162427_version-56-relationship-links", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
119
|
+
{ name: "20261107162448_version-56-relationship-links-history", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
120
|
+
{ name: "20261107163245_version-56-relationship-links-key", version: 56, minCompatible: 56, tables: V56_TABLES },
|
|
116
121
|
];
|
|
117
122
|
export const generatedMigrations = (manifest = MANIFEST, generated = GENERATED) => {
|
|
118
123
|
const migrations = [];
|
|
@@ -54,7 +54,7 @@ export interface MemoryInput {
|
|
|
54
54
|
project?: string;
|
|
55
55
|
confidence?: number;
|
|
56
56
|
status?: "proposed" | "confirmed";
|
|
57
|
-
/** The memory this one replaces; it becomes `superseded
|
|
57
|
+
/** The memory this one replaces; it becomes `superseded` once this one is confirmed. */
|
|
58
58
|
supersedes?: string;
|
|
59
59
|
}
|
|
60
60
|
export interface MemoriesStore {
|
|
@@ -155,10 +155,26 @@ export const memoriesStoreOver = (context) => {
|
|
|
155
155
|
throw new CliError("not_found", `${reference} is a fact now: store.facts holds it`);
|
|
156
156
|
return row;
|
|
157
157
|
};
|
|
158
|
-
const decided = (reference, by) => {
|
|
158
|
+
const decided = (reference, by, ownerOnly = false) => {
|
|
159
159
|
const row = rowOf(reference);
|
|
160
|
-
assertMayDecide({ id: `memory:${row.id}`, proposedBy: proposerOf(database, row.author_type, row.author_id) }, by, context.decisions);
|
|
160
|
+
assertMayDecide({ id: `memory:${row.id}`, proposedBy: proposerOf(database, row.author_type, row.author_id), ownerOnly }, by, context.decisions);
|
|
161
161
|
};
|
|
162
|
+
const alreadySuperseded = (id) => new CliError("validation_error", `memory:${id} is already superseded; correct the one that replaced it`, {
|
|
163
|
+
reason: "memory.already-superseded",
|
|
164
|
+
});
|
|
165
|
+
const replaceable = (reference) => {
|
|
166
|
+
const row = rowOf(reference);
|
|
167
|
+
if (row.status === "superseded")
|
|
168
|
+
throw alreadySuperseded(row.id);
|
|
169
|
+
return row;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* A correction retired the memory if it was ever confirmed. An older store let an agent's proposal retire it at
|
|
173
|
+
* once, so a memory superseded only by the one being confirmed is not refused.
|
|
174
|
+
*/
|
|
175
|
+
const retiredByAnother = (replaced, by) => database
|
|
176
|
+
.prepare("SELECT 1 FROM memories WHERE supersedes_id = ? AND id <> ? AND last_verified_at IS NOT NULL LIMIT 1")
|
|
177
|
+
.get(replaced, by) !== undefined;
|
|
162
178
|
const setStatus = (reference, status, verified) => {
|
|
163
179
|
const row = rowOf(reference);
|
|
164
180
|
const at = now();
|
|
@@ -193,7 +209,7 @@ export const memoriesStoreOver = (context) => {
|
|
|
193
209
|
const { actor, model } = authorActor(context, input.author);
|
|
194
210
|
const subject = input.subject === undefined ? undefined : requiredThing(database, input.subject, "the subject");
|
|
195
211
|
const project = input.project === undefined ? null : projectId(database, input.project);
|
|
196
|
-
const replaced = input.supersedes === undefined ? undefined : Number(
|
|
212
|
+
const replaced = input.supersedes === undefined ? undefined : Number(replaceable(input.supersedes).id);
|
|
197
213
|
const at = now();
|
|
198
214
|
const made = Number(database
|
|
199
215
|
.prepare("INSERT INTO memories (id, kind, body, subject_type, subject_id, author_type, author_id, model, confidence, status, " +
|
|
@@ -201,16 +217,26 @@ export const memoriesStoreOver = (context) => {
|
|
|
201
217
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
202
218
|
.get(nextId(database, "memories"), kind, body, subject?.type ?? null, subject?.id ?? null, actor.type, actor.id, model, input.confidence ?? null, status, status === "confirmed" ? at : null, replaced ?? null, scope, project, at, at)?.id);
|
|
203
219
|
linkEvidence(context, { type: "memory", id: made }, input.evidence, input.author === "owner" ? "owner" : "agent");
|
|
204
|
-
if (replaced !== undefined)
|
|
220
|
+
if (replaced !== undefined && status === "confirmed")
|
|
205
221
|
database.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?").run(at, replaced);
|
|
206
222
|
return made;
|
|
207
223
|
});
|
|
208
224
|
return memoryOf(rowOf(`memory:${id}`));
|
|
209
225
|
};
|
|
210
|
-
|
|
211
|
-
|
|
226
|
+
/** Applies a pending correction; only the owner retires a confirmed memory, whatever `agent_decisions` says. */
|
|
227
|
+
const confirmNow = (reference, by) => write(database, () => {
|
|
228
|
+
const row = rowOf(reference);
|
|
229
|
+
const replaced = row.status === "confirmed" || row.supersedes_id == null ? undefined : rowOf(`memory:${row.supersedes_id}`);
|
|
230
|
+
decided(reference, by, replaced?.status === "confirmed");
|
|
231
|
+
if (replaced !== undefined) {
|
|
232
|
+
if (retiredByAnother(Number(replaced.id), Number(row.id)))
|
|
233
|
+
throw alreadySuperseded(replaced.id);
|
|
234
|
+
database
|
|
235
|
+
.prepare("UPDATE memories SET status = 'superseded', updated_at = ? WHERE id = ?")
|
|
236
|
+
.run(now(), Number(replaced.id));
|
|
237
|
+
}
|
|
212
238
|
return setStatus(reference, "confirmed", true);
|
|
213
|
-
};
|
|
239
|
+
});
|
|
214
240
|
return {
|
|
215
241
|
addNow,
|
|
216
242
|
confirmNow,
|
|
@@ -1060,5 +1060,36 @@ export const GENERATED = [
|
|
|
1060
1060
|
"statements": [
|
|
1061
1061
|
"CREATE INDEX `decision_requests_by_channel_bot_profile_chat_id_message_id` ON `decision_requests` (`channel`,`bot_profile`,`chat_id`,`message_id`);"
|
|
1062
1062
|
]
|
|
1063
|
+
},
|
|
1064
|
+
{
|
|
1065
|
+
"name": "20261107162427_version-56-relationship-links",
|
|
1066
|
+
"statements": [
|
|
1067
|
+
"CREATE TABLE `link_revisions` (\n\t`id` integer PRIMARY KEY,\n\t`link_id` integer NOT NULL,\n\t`change` text NOT NULL,\n\t`before` text,\n\t`after` text,\n\t`author` text,\n\t`account_id` integer,\n\t`created_at` integer NOT NULL\n);",
|
|
1068
|
+
"ALTER TABLE `links` ADD `account_id` integer;",
|
|
1069
|
+
"ALTER TABLE `links` ADD `starts_at` integer;",
|
|
1070
|
+
"ALTER TABLE `links` ADD `ends_at` integer;",
|
|
1071
|
+
"ALTER TABLE `links` ADD `deleted_at` integer;",
|
|
1072
|
+
"CREATE INDEX `link_revisions_by_link_id_created_at` ON `link_revisions` (`link_id`,`created_at`);"
|
|
1073
|
+
]
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
"name": "20261107162448_version-56-relationship-links-history",
|
|
1077
|
+
"statements": [
|
|
1078
|
+
"-- A CRM's deal and lead people were stored as the owner's (confirmed = 1): they are the CRM account's report.\nUPDATE links SET confirmed = 0, account_id = (SELECT d.account_id FROM deals d WHERE d.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'deal';",
|
|
1079
|
+
"UPDATE links SET confirmed = 0, account_id = (SELECT l.account_id FROM leads l WHERE l.id = links.from_id)\n WHERE source = 'crm' AND kind = 'related-to' AND from_type = 'lead';",
|
|
1080
|
+
"-- The unique key below needs one row per relationship. Of duplicates the owner's row stays, then a confirmed one,\n-- then the oldest; it takes the others' metadata where its own has none, and proposals naming a dropped row name it.\nWITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE links SET metadata = json_patch(\n (SELECT json_group_object(j.key, CASE WHEN j.type IN ('object', 'array') THEN json(j.value) ELSE j.value END)\n FROM link_fold f JOIN links d ON d.id = f.drop_id, json_each(d.metadata) j\n WHERE f.keep_id = links.id AND json_valid(d.metadata)),\n coalesce(links.metadata, '{}'))\n WHERE id IN (SELECT f.keep_id FROM link_fold f JOIN links d ON d.id = f.drop_id\n WHERE d.metadata IS NOT NULL AND json_valid(d.metadata));",
|
|
1081
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET payload = json_set(payload, '$.relationship',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(payload, '$.relationship')))\n WHERE kind = 'relationship_update'\n AND json_extract(payload, '$.relationship') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1082
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nUPDATE proposed_actions SET result = json_set(result, '$.link',\n (SELECT CAST(f.keep_id AS TEXT) FROM link_fold f WHERE CAST(f.drop_id AS TEXT) = json_extract(result, '$.link')))\n WHERE json_valid(result) AND json_extract(result, '$.link') IN (SELECT CAST(drop_id AS TEXT) FROM link_fold);",
|
|
1083
|
+
"WITH link_fold AS (\n SELECT keep_id, id AS drop_id FROM (\n SELECT id, first_value(id) OVER (\n PARTITION BY kind, from_type, from_id, to_type, to_id, ifnull(anchor, ''), ifnull(role, ''), ifnull(account_id, 0)\n ORDER BY source = 'owner' DESC, confirmed DESC, id\n ) AS keep_id\n FROM links WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL\n ) WHERE id <> keep_id\n)\nDELETE FROM links WHERE id IN (SELECT drop_id FROM link_fold);",
|
|
1084
|
+
"CREATE TRIGGER link_revisions_ai AFTER INSERT ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id, 'added', NULL,\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1085
|
+
"-- Only a change a reader sees: a sync that touches `updated_at` alone writes no revision.\nCREATE TRIGGER link_revisions_au AFTER UPDATE OF role, confirmed, account_id, starts_at, ends_at, deleted_at ON links\n WHEN new.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND new.to_id IS NOT NULL\n AND (old.role IS NOT new.role OR old.confirmed IS NOT new.confirmed OR old.account_id IS NOT new.account_id\n OR old.starts_at IS NOT new.starts_at OR old.ends_at IS NOT new.ends_at OR old.deleted_at IS NOT new.deleted_at) BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (new.id,\n CASE\n WHEN old.deleted_at IS NULL AND new.deleted_at IS NOT NULL THEN 'withdrawn'\n WHEN old.deleted_at IS NOT NULL AND new.deleted_at IS NULL THEN 'restored'\n WHEN old.confirmed = 0 AND new.confirmed = 1 THEN 'confirmed'\n WHEN old.ends_at IS NULL AND new.ends_at IS NOT NULL THEN 'ended'\n ELSE 'changed'\n END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n json_object('role', new.role, 'confirmed', new.confirmed, 'account_id', new.account_id, 'starts_at', new.starts_at,\n 'ends_at', new.ends_at, 'deleted_at', new.deleted_at),\n new.author, new.account_id, new.updated_at);\nEND;",
|
|
1086
|
+
"CREATE TRIGGER link_revisions_ad AFTER DELETE ON links\n WHEN old.kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND old.to_id IS NOT NULL BEGIN\n INSERT INTO link_revisions (link_id, change, before, after, author, account_id, created_at)\n VALUES (old.id,\n -- The store records the rejection, then sets updated_at, then deletes: an older rejection the fold re-pointed is not this one.\n CASE WHEN old.confirmed = 0 AND EXISTS (SELECT 1 FROM proposed_actions p WHERE p.kind = 'relationship'\n AND p.status = 'rejected' AND p.decided_at >= old.updated_at AND json_valid(p.result)\n AND json_extract(p.result, '$.link') = CAST(old.id AS TEXT))\n THEN 'rejected' ELSE 'removed' END,\n json_object('role', old.role, 'confirmed', old.confirmed, 'account_id', old.account_id, 'starts_at', old.starts_at,\n 'ends_at', old.ends_at, 'deleted_at', old.deleted_at),\n NULL, old.author, old.account_id, old.updated_at);\nEND;"
|
|
1087
|
+
]
|
|
1088
|
+
},
|
|
1089
|
+
{
|
|
1090
|
+
"name": "20261107163245_version-56-relationship-links-key",
|
|
1091
|
+
"statements": [
|
|
1092
|
+
"CREATE UNIQUE INDEX `links_relationship_key` ON `links` (`kind`,`from_type`,`from_id`,`to_type`,`to_id`,ifnull(\"anchor\", ''),ifnull(\"role\", ''),ifnull(\"account_id\", 0)) WHERE kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL;"
|
|
1093
|
+
]
|
|
1063
1094
|
}
|
|
1064
1095
|
];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RelationshipColumns } from "../../domain/relations.js";
|
|
1
2
|
import type { Section } from "../../readers/types.js";
|
|
2
3
|
import { type Decider } from "../decisions.js";
|
|
3
4
|
import type { CacheDatabase } from "../driver.js";
|
|
@@ -51,7 +52,7 @@ export interface Note {
|
|
|
51
52
|
updatedAt: string;
|
|
52
53
|
deletedAt: string | null;
|
|
53
54
|
}
|
|
54
|
-
export interface Link {
|
|
55
|
+
export interface Link extends RelationshipColumns {
|
|
55
56
|
id: string;
|
|
56
57
|
from: string;
|
|
57
58
|
/** `null` while the link names nobody the store knows, or more than one. */
|
|
@@ -78,7 +79,7 @@ export interface LinkListFilter {
|
|
|
78
79
|
origin?: Link["origin"];
|
|
79
80
|
confirmed?: boolean;
|
|
80
81
|
}
|
|
81
|
-
export interface LinkInput {
|
|
82
|
+
export interface LinkInput extends Pick<RelationshipColumns, "position" | "startsAt" | "endsAt"> {
|
|
82
83
|
from: string;
|
|
83
84
|
to?: string;
|
|
84
85
|
targetText?: string;
|
|
@@ -3,6 +3,7 @@ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
|
|
|
3
3
|
import { googleDocumentLinks } from "../../domain/google-documents.js";
|
|
4
4
|
import { DOCUMENT_ACCOUNT_PROVIDERS, filesAccountSql, folderProviderOf, folderProviderSql, isDocumentAccountProvider, } from "../../domain/providers.js";
|
|
5
5
|
import { parseReference } from "../../domain/references.js";
|
|
6
|
+
import { isRelationKind } from "../../domain/relations.js";
|
|
6
7
|
import { normalizeTag } from "../../domain/tags.js";
|
|
7
8
|
import { assertMayWithdraw } from "../decisions.js";
|
|
8
9
|
import { fold } from "../normalize.js";
|
|
@@ -80,7 +81,9 @@ export const noteRowOf = (database, reference) => {
|
|
|
80
81
|
};
|
|
81
82
|
const thingRef = (database, type, id) => type == null || id == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? null);
|
|
82
83
|
export const linkOf = (database, row) => {
|
|
83
|
-
const metadata = row.metadata == null
|
|
84
|
+
const metadata = row.metadata == null
|
|
85
|
+
? {}
|
|
86
|
+
: JSON.parse(String(row.metadata));
|
|
84
87
|
return {
|
|
85
88
|
id: String(row.id),
|
|
86
89
|
from: thingRef(database, row.from_type, row.from_id),
|
|
@@ -95,6 +98,12 @@ export const linkOf = (database, row) => {
|
|
|
95
98
|
provenance: metadata.provenance ?? null,
|
|
96
99
|
confirmed: Number(row.confirmed) === 1,
|
|
97
100
|
createdAt: iso(row.created_at),
|
|
101
|
+
...(row.account_id == null ? {} : { accountId: Number(row.account_id) }),
|
|
102
|
+
...(row.starts_at == null ? {} : { startsAt: Number(row.starts_at) }),
|
|
103
|
+
...(row.ends_at == null ? {} : { endsAt: Number(row.ends_at) }),
|
|
104
|
+
...(row.deleted_at == null ? {} : { deletedAt: Number(row.deleted_at) }),
|
|
105
|
+
...(typeof metadata.position === "string" ? { position: metadata.position } : {}),
|
|
106
|
+
...(typeof metadata.overrides === "number" ? { overrides: metadata.overrides } : {}),
|
|
98
107
|
};
|
|
99
108
|
};
|
|
100
109
|
/** The row a reference names, refused when the store holds none. */
|
|
@@ -183,19 +192,27 @@ export const insertLink = (context, input) => {
|
|
|
183
192
|
if (to === null && targetText === null)
|
|
184
193
|
throw new CliError("validation_error", "a link needs a target");
|
|
185
194
|
if (to !== null) {
|
|
195
|
+
// A relationship's key holds its role and its source account: the owner's link with another role is another one.
|
|
196
|
+
const relationship = isRelationKind(kind);
|
|
197
|
+
const role = relationship && input.role !== undefined ? input.role.trim() : null;
|
|
186
198
|
const existing = database
|
|
187
|
-
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?"
|
|
188
|
-
|
|
199
|
+
.prepare("SELECT * FROM links WHERE from_type = ? AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ? AND anchor IS ?" +
|
|
200
|
+
(relationship ? " AND account_id IS NULL AND (? IS NULL OR ifnull(role, '') = ?)" : ""))
|
|
201
|
+
.get(from.type, from.id, to.type, to.id, kind, input.anchor ?? null, ...(relationship ? [role, role] : []));
|
|
189
202
|
if (existing)
|
|
190
203
|
return linkOf(database, existing);
|
|
191
204
|
}
|
|
192
205
|
const at = now();
|
|
193
206
|
const provenance = input.provenance === undefined ? undefined : textOf(input.provenance, "provenance", 2000);
|
|
207
|
+
const position = input.position === undefined ? undefined : textOf(input.position, "a position", 200);
|
|
208
|
+
if (input.startsAt !== undefined && input.endsAt !== undefined && input.endsAt <= input.startsAt)
|
|
209
|
+
throw new CliError("validation_error", "a relationship ends after it starts");
|
|
210
|
+
const metadata = provenance === undefined && position === undefined ? null : JSON.stringify({ provenance, position });
|
|
194
211
|
const row = database
|
|
195
212
|
.prepare("INSERT INTO links (from_type, from_id, to_type, to_id, kind, anchor, source, target_text, target_folded, role, evidence, " +
|
|
196
|
-
"metadata, confirmed, created_at, author, updated_at, purpose
|
|
197
|
-
"RETURNING id")
|
|
198
|
-
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000),
|
|
213
|
+
"metadata, confirmed, created_at, author, updated_at, purpose, starts_at, ends_at) " +
|
|
214
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
215
|
+
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, kind, input.anchor ?? null, origin, targetText, targetText === null ? null : targetKey(targetText), input.role === undefined ? null : textOf(input.role, "a role", 200), input.evidence === undefined ? null : textOf(input.evidence, "evidence", 2000), metadata, input.confirmed === false ? 0 : 1, at, origin === "owner" ? "owner" : null, at, input.purpose === undefined ? null : purposeOf(input.purpose), input.startsAt ?? null, input.endsAt ?? null);
|
|
199
216
|
if (to === null && targetText !== null)
|
|
200
217
|
resolveKey(database, targetKey(targetText));
|
|
201
218
|
return linkOf(database, database.prepare("SELECT * FROM links WHERE id = ?").get(Number(row?.id)));
|
|
@@ -9,6 +9,14 @@ export interface OrganizationsStore {
|
|
|
9
9
|
updateOrganization(organization: string, input: {
|
|
10
10
|
name: string;
|
|
11
11
|
}): Promise<Organization>;
|
|
12
|
+
/**
|
|
13
|
+
* The owner says whether an organization is one of his own; a CRM sync never changes his word. `null` hands it back
|
|
14
|
+
* to the CRM's own-company flag.
|
|
15
|
+
*/
|
|
16
|
+
setOwnOrganization(organization: string, own: boolean | null): Promise<{
|
|
17
|
+
ref: string;
|
|
18
|
+
own: boolean;
|
|
19
|
+
}>;
|
|
12
20
|
}
|
|
13
21
|
export declare const organizationsStoreOver: ({ database, now }: StoreContext) => OrganizationsStore;
|
|
14
22
|
export {};
|
|
@@ -45,4 +45,18 @@ export const organizationsStoreOver = ({ database, now }) => ({
|
|
|
45
45
|
throw new CliError("not_found", `no organization ${organization}`);
|
|
46
46
|
return organizationOf(row);
|
|
47
47
|
}),
|
|
48
|
+
setOwnOrganization: async (organization, own) => write(database, () => {
|
|
49
|
+
const thing = thingOf(database, organization.includes(":") ? organization : `organization:${organization}`);
|
|
50
|
+
const set = own === null
|
|
51
|
+
? "json_remove(coalesce(metadata, '{}'), '$.own', '$.own_by')"
|
|
52
|
+
: `json_set(coalesce(metadata, '{}'), '$.own', json('${own}'), '$.own_by', 'owner')`;
|
|
53
|
+
const row = thing?.type === "organization" &&
|
|
54
|
+
database
|
|
55
|
+
.prepare(`UPDATE organizations SET metadata = ${set}, updated_at = ? WHERE id = ? AND deleted_at IS NULL RETURNING id, metadata`)
|
|
56
|
+
.get(now(), thing.id);
|
|
57
|
+
if (!row)
|
|
58
|
+
throw new CliError("not_found", `no organization ${organization}`);
|
|
59
|
+
const metadata = JSON.parse(String(row.metadata ?? "{}"));
|
|
60
|
+
return { ref: `organization:${row.id}`, own: metadata.own === true };
|
|
61
|
+
}),
|
|
48
62
|
});
|
|
@@ -42,7 +42,7 @@ export interface PersonPreparationRead {
|
|
|
42
42
|
* The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
|
|
43
43
|
* account's: its facts never come along, and its tasks only when `accounts` holds it.
|
|
44
44
|
*/
|
|
45
|
-
export declare const personPreparation: ({ database }: Pick<StoreContext, "database">, uid: string, { accounts, limit }: {
|
|
45
|
+
export declare const personPreparation: ({ database, now }: Pick<StoreContext, "database" | "now">, uid: string, { accounts, limit }: {
|
|
46
46
|
accounts: readonly AccountKey[];
|
|
47
47
|
limit: number;
|
|
48
48
|
}) => PersonPreparationRead;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { notOverriddenSql, usableLinkSql } from "../../domain/relations.js";
|
|
2
3
|
import { linkKind } from "./link-kinds.js";
|
|
3
4
|
import { taskIdOf } from "./things.js";
|
|
4
5
|
import { read } from "./transaction.js";
|
|
@@ -8,14 +9,14 @@ const iso = (value) => (value == null ? null : new Date(Number(value)).toISOStri
|
|
|
8
9
|
* The accepted facts, the owner's notes and the open tasks about one person. A project bound to an account is that
|
|
9
10
|
* account's: its facts never come along, and its tasks only when `accounts` holds it.
|
|
10
11
|
*/
|
|
11
|
-
export const personPreparation = ({ database }, uid, { accounts, limit }) => {
|
|
12
|
+
export const personPreparation = ({ database, now }, uid, { accounts, limit }) => {
|
|
12
13
|
const person = Number(uid);
|
|
13
14
|
if (!/^[1-9]\d*$/.test(uid) || !Number.isSafeInteger(person) || !Number.isSafeInteger(limit) || limit < 1)
|
|
14
15
|
throw new CliError("validation_error", "person preparation takes a person id and a positive limit");
|
|
15
16
|
const page = (rows) => ({ items: rows.slice(0, limit), hasMore: rows.length > limit });
|
|
16
17
|
return read(database, () => {
|
|
17
18
|
const projects = `SELECT l.to_id FROM links l WHERE l.from_type='person' AND l.from_id=? AND l.to_type='project'
|
|
18
|
-
AND l.kind=${linkKind("member-of")} AND l
|
|
19
|
+
AND l.kind=${linkKind("member-of")} AND ${usableLinkSql("l", now())} AND ${notOverriddenSql("l")} AND l.to_id IN (${GLOBAL_PROJECT})`;
|
|
19
20
|
const facts = database
|
|
20
21
|
.prepare(`SELECT f.id,f.type,f.statement,f.subject_type,f.subject_id,f.project_id,f.updated_at FROM facts f
|
|
21
22
|
WHERE f.status='accepted' AND f.deleted_at IS NULL
|
|
@@ -43,11 +43,22 @@ export const restoreAnnotationRecords = (database, projectId, snapshot, bindings
|
|
|
43
43
|
const from = resolve(link.from), to = resolve(link.to);
|
|
44
44
|
if (!from)
|
|
45
45
|
throw new CliError("validation_error", "project annotation link source is required");
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
.
|
|
46
|
+
// A relationship the store already holds under its unique key keeps that row: the snapshot maps onto it.
|
|
47
|
+
const made = database
|
|
48
|
+
.prepare("INSERT INTO links(from_type,from_id,to_type,to_id,kind,anchor,source,target_text,target_folded,role,evidence,metadata,confirmed,created_at,author,updated_at,starts_at,ends_at,deleted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING RETURNING id")
|
|
49
|
+
.get(from.type, from.id, to?.type ?? null, to?.id ?? null, link.kind, link.anchor, link.origin, link.target_text, link.target_text === null ? null : fold(link.target_text), link.role, link.evidence, link.provenance === null ? null : JSON.stringify({ provenance: link.provenance }), Number(link.confirmed), link.created_at, link.author, link.updated_at, link.starts_at ?? null, link.ends_at ?? null, link.deleted_at ?? null);
|
|
50
|
+
const row = made ??
|
|
51
|
+
database
|
|
52
|
+
.prepare("SELECT id FROM links WHERE kind=? AND from_type=? AND from_id=? AND to_type IS ? AND to_id IS ? " +
|
|
53
|
+
"AND ifnull(anchor,'')=ifnull(?,'') AND ifnull(role,'')=ifnull(?,'') AND account_id IS NULL")
|
|
54
|
+
.get(link.kind, from.type, from.id, to?.type ?? null, to?.id ?? null, link.anchor, link.role);
|
|
49
55
|
if (!row)
|
|
50
56
|
throw new CliError("configuration_error", "project annotation link insertion failed");
|
|
57
|
+
// The owner confirmed it where the snapshot was taken: the row it maps onto says so too.
|
|
58
|
+
if (!made && link.confirmed)
|
|
59
|
+
database
|
|
60
|
+
.prepare("UPDATE links SET confirmed = 1, updated_at = max(updated_at, ?) WHERE id = ? AND confirmed = 0")
|
|
61
|
+
.run(link.updated_at, Number(row.id));
|
|
51
62
|
mappings[link.ref] = `link:${row.id}`;
|
|
52
63
|
}
|
|
53
64
|
return mappings;
|
|
@@ -23,7 +23,7 @@ export declare const projectAnnotationSnapshot: (database: CacheDatabase, projec
|
|
|
23
23
|
ref: string;
|
|
24
24
|
from: string;
|
|
25
25
|
to: string | null;
|
|
26
|
-
kind: "about" | "answered-by" | "assigned-to" | "attached" | "blocked-by" | "created-from" | "duplicate-of" | "evidence" | "follow-up-of" | "labelled" | "links-to" | "member-of" | "related-to";
|
|
26
|
+
kind: "about" | "answered-by" | "assigned-to" | "attached" | "blocked-by" | "created-from" | "customer-of" | "duplicate-of" | "evidence" | "follow-up-of" | "labelled" | "links-to" | "member-of" | "partner-of" | "related-to" | "reports-to";
|
|
27
27
|
origin: "file" | "message" | "owner" | "suggested";
|
|
28
28
|
anchor: string | null;
|
|
29
29
|
target_text: string | null;
|
|
@@ -34,6 +34,9 @@ export declare const projectAnnotationSnapshot: (database: CacheDatabase, projec
|
|
|
34
34
|
created_at: number;
|
|
35
35
|
updated_at: number;
|
|
36
36
|
author: string | null;
|
|
37
|
+
starts_at?: number | undefined;
|
|
38
|
+
ends_at?: number | undefined;
|
|
39
|
+
deleted_at?: number | undefined;
|
|
37
40
|
}[];
|
|
38
41
|
external: {
|
|
39
42
|
ref: string;
|
|
@@ -107,6 +107,9 @@ export const projectAnnotationSnapshot = (database, projectId, budget) => read(d
|
|
|
107
107
|
"author",
|
|
108
108
|
"created_at",
|
|
109
109
|
"updated_at",
|
|
110
|
+
"starts_at",
|
|
111
|
+
"ends_at",
|
|
112
|
+
"deleted_at",
|
|
110
113
|
], [projectId, projectId, projectId, projectId]);
|
|
111
114
|
const projectRef = `project:${projectId}`;
|
|
112
115
|
const owned = new Set([projectRef, ...facts.map((row) => `fact:${row.id}`)]);
|
|
@@ -176,6 +179,9 @@ export const projectAnnotationSnapshot = (database, projectId, budget) => read(d
|
|
|
176
179
|
created_at: row.created_at,
|
|
177
180
|
updated_at: row.updated_at,
|
|
178
181
|
author: nullableText(row.author),
|
|
182
|
+
...(row.starts_at == null ? {} : { starts_at: row.starts_at }),
|
|
183
|
+
...(row.ends_at == null ? {} : { ends_at: row.ends_at }),
|
|
184
|
+
...(row.deleted_at == null ? {} : { deleted_at: row.deleted_at }),
|
|
179
185
|
})),
|
|
180
186
|
};
|
|
181
187
|
const snapshot = decodeProjectAnnotationSnapshot(JSON.stringify({ ...data, external: sources.external(owned) }));
|