@wirecat/cli-core 0.604.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/calendar/prepare.d.ts +4 -2
  3. package/dist/calendar/prepare.js +8 -8
  4. package/dist/cli/index.d.ts +2 -2
  5. package/dist/cli/index.js +2 -1
  6. package/dist/cli/messenger/contacts-command.js +3 -2
  7. package/dist/cli/messenger/doctor-command.js +14 -7
  8. package/dist/cli/messenger/store-maintenance-command.d.ts +34 -2
  9. package/dist/cli/messenger/store-maintenance-command.js +31 -4
  10. package/dist/cli/program.js +11 -2
  11. package/dist/cli/steps.js +9 -1
  12. package/dist/cli/store-recover.d.ts +10 -2
  13. package/dist/cli/store-recover.js +18 -4
  14. package/dist/cli/store-settings.js +38 -4
  15. package/dist/crm/cli/index.js +3 -1
  16. package/dist/crm/index.d.ts +2 -2
  17. package/dist/crm/index.js +1 -1
  18. package/dist/crm/source.d.ts +35 -5
  19. package/dist/crm/sync.d.ts +15 -7
  20. package/dist/crm/sync.js +169 -11
  21. package/dist/domain/crm.d.ts +41 -2
  22. package/dist/domain/deals.d.ts +5 -2
  23. package/dist/domain/deals.js +5 -2
  24. package/dist/domain/record-types.d.ts +61 -0
  25. package/dist/domain/record-types.js +26 -0
  26. package/dist/domain/records.d.ts +3 -5
  27. package/dist/domain/records.js +10 -13
  28. package/dist/domain/relations.d.ts +125 -0
  29. package/dist/domain/relations.js +107 -0
  30. package/dist/entities/contact-activity.d.ts +4 -0
  31. package/dist/entities/contact-activity.js +1 -0
  32. package/dist/entities/contact-context.d.ts +20 -0
  33. package/dist/entities/contact-context.js +2 -0
  34. package/dist/entities/deal.d.ts +2 -2
  35. package/dist/entities/deal.js +2 -1
  36. package/dist/entities/index.d.ts +39 -13
  37. package/dist/entities/relationship.d.ts +8 -2
  38. package/dist/entities/relationship.js +8 -2
  39. package/dist/entities/task-results.d.ts +10 -10
  40. package/dist/errors/failures.d.ts +17 -1
  41. package/dist/errors/failures.js +57 -1
  42. package/dist/errors/reasons.js +28 -0
  43. package/dist/index.d.ts +2 -1
  44. package/dist/index.js +1 -0
  45. package/dist/mail/cli/review.js +20 -6
  46. package/dist/mail/index.d.ts +1 -1
  47. package/dist/mail/marks.d.ts +10 -5
  48. package/dist/mail/marks.js +16 -8
  49. package/dist/mail/review.d.ts +5 -0
  50. package/dist/mcp/tool.js +2 -1
  51. package/dist/runs/recording.js +13 -4
  52. package/dist/services/deps.js +4 -6
  53. package/dist/services/index.d.ts +1 -1
  54. package/dist/services/link-scorers/chat-senders.d.ts +3 -2
  55. package/dist/services/link-scorers/chat-senders.js +7 -4
  56. package/dist/services/link-scorers/mail-thread.js +1 -0
  57. package/dist/services/link-scorers/member-chats.js +1 -0
  58. package/dist/services/link-scorers/member-dialog.d.ts +1 -1
  59. package/dist/services/link-scorers/member-dialog.js +4 -3
  60. package/dist/services/link-scorers/scan.d.ts +5 -2
  61. package/dist/services/link-scorers/scan.js +100 -54
  62. package/dist/services/link-scorers/shared.d.ts +2 -2
  63. package/dist/services/link-scorers/shared.js +8 -4
  64. package/dist/services/link-scorers/types.d.ts +3 -0
  65. package/dist/services/metadata.d.ts +1 -1
  66. package/dist/services/person-context.d.ts +24 -7
  67. package/dist/services/person-context.js +45 -11
  68. package/dist/services/person-preparation.js +4 -5
  69. package/dist/services/project-status/index.js +2 -1
  70. package/dist/services/stored-project-gathering.js +4 -3
  71. package/dist/store/damage.d.ts +3 -1
  72. package/dist/store/damage.js +19 -12
  73. package/dist/store/document-transfer/index.js +7 -0
  74. package/dist/store/exports.d.ts +1 -0
  75. package/dist/store/exports.js +1 -0
  76. package/dist/store/index.d.ts +7 -1
  77. package/dist/store/index.js +2 -0
  78. package/dist/store/marks.d.ts +57 -0
  79. package/dist/store/marks.js +121 -0
  80. package/dist/store/project-transfer/preview.js +12 -7
  81. package/dist/store/project-transfer/request.d.ts +4 -1
  82. package/dist/store/project-transfer/schema.d.ts +9 -2
  83. package/dist/store/project-transfer/schema.js +4 -0
  84. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  85. package/dist/store/recover.js +16 -1
  86. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  87. package/dist/store/sqlite/crm-settings.js +80 -0
  88. package/dist/store/sqlite/crm.d.ts +42 -2
  89. package/dist/store/sqlite/crm.js +397 -36
  90. package/dist/store/sqlite/deals.js +3 -2
  91. package/dist/store/sqlite/finance.d.ts +8 -1
  92. package/dist/store/sqlite/finance.js +10 -3
  93. package/dist/store/sqlite/involvement-queue.js +4 -3
  94. package/dist/store/sqlite/knowledge.d.ts +7 -3
  95. package/dist/store/sqlite/knowledge.js +43 -31
  96. package/dist/store/sqlite/link-kinds.d.ts +2 -3
  97. package/dist/store/sqlite/link-kinds.js +4 -2
  98. package/dist/store/sqlite/manifest.js +5 -0
  99. package/dist/store/sqlite/memories.d.ts +1 -1
  100. package/dist/store/sqlite/memories.js +33 -7
  101. package/dist/store/sqlite/migrations.generated.js +31 -0
  102. package/dist/store/sqlite/notes.d.ts +3 -2
  103. package/dist/store/sqlite/notes.js +23 -6
  104. package/dist/store/sqlite/open-store.js +4 -1
  105. package/dist/store/sqlite/organizations.d.ts +8 -0
  106. package/dist/store/sqlite/organizations.js +14 -0
  107. package/dist/store/sqlite/own-identities.d.ts +1 -1
  108. package/dist/store/sqlite/own-identities.js +7 -5
  109. package/dist/store/sqlite/person-links.d.ts +5 -2
  110. package/dist/store/sqlite/person-links.js +24 -18
  111. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  112. package/dist/store/sqlite/person-preparation.js +3 -2
  113. package/dist/store/sqlite/person-separation.d.ts +5 -0
  114. package/dist/store/sqlite/person-separation.js +26 -0
  115. package/dist/store/sqlite/project-transfer/records.js +14 -3
  116. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  117. package/dist/store/sqlite/project-transfer/snapshot.js +6 -0
  118. package/dist/store/sqlite/record-projectors.d.ts +44 -0
  119. package/dist/store/sqlite/record-projectors.js +72 -0
  120. package/dist/store/sqlite/records.js +12 -70
  121. package/dist/store/sqlite/relation-list.d.ts +43 -0
  122. package/dist/store/sqlite/relation-list.js +133 -0
  123. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  124. package/dist/store/sqlite/relation-proposals.js +134 -10
  125. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  126. package/dist/store/sqlite/relation-reads.js +7 -0
  127. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  128. package/dist/store/sqlite/relation-roles.js +91 -0
  129. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  130. package/dist/store/sqlite/reported-relations.js +132 -0
  131. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  132. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  133. package/dist/store/sqlite/schema/links.d.ts +360 -0
  134. package/dist/store/sqlite/schema/links.js +32 -0
  135. package/dist/store/sqlite/schema.d.ts +2 -296
  136. package/dist/store/sqlite/schema.js +2 -24
  137. package/dist/store/sqlite/transaction.js +2 -5
  138. package/dist/store/store.d.ts +3 -0
  139. package/dist/store/store.js +5 -0
  140. package/dist/store/types.d.ts +5 -0
  141. package/package.json +5 -5
@@ -5,7 +5,10 @@ import type { StoreContext } from "./open.js";
5
5
  export declare const personByUid: (context: StoreContext, uid: string) => PersonRecord | undefined;
6
6
  /** The person an identity belongs to, with every identity linked to them. */
7
7
  export declare const personOf: (context: StoreContext, ref: IdentityRef) => PersonRecord | undefined;
8
- /** A reviewed meeting participant association moves only its selected identity. */
8
+ /**
9
+ * A reviewed meeting participant association moves only its selected identity. Only the owner may move it back
10
+ * over a separation the owner made.
11
+ */
9
12
  export declare const linkIdentityToPerson: (context: StoreContext, identityPk: number, target: number, options: LinkOptions) => void;
10
13
  /**
11
14
  * Makes `other` and everyone already linked to it the same person as `person`. Never inferred from a
@@ -17,7 +20,7 @@ export declare const mergePerson: (context: StoreContext, from: number, to: numb
17
20
  /**
18
21
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
19
22
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
20
- * no one's mail correspondent. An owner's unlink wins: two identities the owner separated stay apart.
23
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
21
24
  */
22
25
  export declare const joinByAddress: (context: StoreContext, ref: IdentityRef, address: string, by: string) => void;
23
26
  /** Gives the identity a person of its own again; the ones left keep theirs. */
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { and, eq, inArray, isNull, sql } from "./drizzle/core.js";
3
3
  import { identityOf } from "./identities.js";
4
4
  import { resolvePersonLinks } from "./person-resolution.js";
5
+ import { identitySeparated, separated } from "./person-separation.js";
5
6
  import { accountIdentities, accounts, chats, identities, identityLinkEvents, identityLinks, messages, persons, } from "./schema.js";
6
7
  import { hitsWhere } from "./search.js";
7
8
  const identityRow = ({ orm }, { provider, id }) => orm
@@ -38,17 +39,23 @@ const recordOf = ({ orm }, personPk) => {
38
39
  .orderBy(identities.provider, identities.externalId)
39
40
  .all();
40
41
  const seen = orm
41
- .select({ identityPk: accountIdentities.identityId, account: accounts.externalId })
42
+ .select({ identityPk: accountIdentities.identityId, account: accounts.externalId, scope: accounts.scope })
42
43
  .from(accountIdentities)
43
44
  .innerJoin(accounts, eq(accounts.id, accountIdentities.accountId))
44
45
  .where(inArray(accountIdentities.identityId, rows.map((row) => row.pk)))
45
46
  .all();
46
- const identitiesOf = rows.map(({ pk, isBot, linkedAt, ...row }) => ({
47
- ...row,
48
- isBot: isBot === null ? null : isBot === 1,
49
- accounts: seen.filter((one) => one.identityPk === pk).map((one) => one.account),
50
- linkedAt: new Date(linkedAt).toISOString(),
51
- }));
47
+ const identitiesOf = rows.map(({ pk, isBot, linkedAt, ...row }) => {
48
+ const seenIn = seen
49
+ .filter((one) => one.identityPk === pk)
50
+ .map(({ account, scope }) => ({ account, scope: scope }));
51
+ return {
52
+ ...row,
53
+ isBot: isBot === null ? null : isBot === 1,
54
+ accounts: seenIn.map((one) => one.account),
55
+ seenIn,
56
+ linkedAt: new Date(linkedAt).toISOString(),
57
+ };
58
+ });
52
59
  return { uid: String(person.id), name: person.name, identities: identitiesOf };
53
60
  };
54
61
  /** A person by the uid a `person:` reference holds, with every identity linked to them. */
@@ -75,13 +82,20 @@ const move = (context, identityPk, from, to, { method, by }) => {
75
82
  .values({ identityId: identityPk, fromPersonId: from, toPersonId: to, method, createdAt: at, author: by })
76
83
  .run();
77
84
  };
78
- /** A reviewed meeting participant association moves only its selected identity. */
85
+ /**
86
+ * A reviewed meeting participant association moves only its selected identity. Only the owner may move it back
87
+ * over a separation the owner made.
88
+ */
79
89
  export const linkIdentityToPerson = (context, identityPk, target, options) => {
80
90
  const found = context.orm
81
91
  .select({ personId: identityLinks.personId })
82
92
  .from(identityLinks)
83
93
  .where(eq(identityLinks.identityId, identityPk))
84
94
  .get();
95
+ if (options.by !== "owner" && found?.personId !== target && identitySeparated(context, identityPk, target))
96
+ throw new CliError("conflict", "the owner separated this identity from that person; only the owner links it again", {
97
+ reason: "identity.separated",
98
+ });
85
99
  if (found) {
86
100
  move(context, identityPk, found.personId, target, options);
87
101
  return;
@@ -136,18 +150,10 @@ export const mergePerson = (context, from, to, options) => {
136
150
  for (const { identityPk } of together)
137
151
  move(context, identityPk, from, to, options);
138
152
  };
139
- /** The owner once moved one of the two identities away from a person the other belonged to. */
140
- const separatedByOwner = ({ database }, one, other) => database
141
- .prepare(`SELECT 1 FROM identity_link_events moved
142
- JOIN identity_link_events held ON held.to_person_id = moved.from_person_id
143
- WHERE moved.author = 'owner' AND ((moved.identity_id = ? AND held.identity_id = ?)
144
- OR (moved.identity_id = ? AND held.identity_id = ?))
145
- LIMIT 1`)
146
- .get(one, other, other, one) !== undefined;
147
153
  /**
148
154
  * Joins the identity to the person of the mail contact with this exact address, making that contact when mail has
149
155
  * not seen it yet, so whichever import comes second lands on one person. The contact is seen by no account, so it is
150
- * no one's mail correspondent. An owner's unlink wins: two identities the owner separated stay apart.
156
+ * no one's mail correspondent. An owner's unlink wins: two people the owner separated stay apart.
151
157
  */
152
158
  export const joinByAddress = (context, ref, address, by) => {
153
159
  const key = address.trim().toLowerCase();
@@ -162,7 +168,7 @@ export const joinByAddress = (context, ref, address, by) => {
162
168
  if (!mail)
163
169
  identityOf(context, "email", key, null);
164
170
  const contact = required(context, { provider: "email", id: mail ? String(mail.external_id) : key });
165
- if (contact.personPk === found.personPk || separatedByOwner(context, found.pk, contact.pk))
171
+ if (contact.personPk === found.personPk || separated(context, found.personPk, contact.personPk))
166
172
  return;
167
173
  mergePerson(context, found.personPk, contact.personPk, { method: "same-email", by });
168
174
  resolvePersonLinks(context.database, recordOf(context, contact.personPk).identities.flatMap(({ name, username }) => [name, username]));
@@ -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.confirmed=1 AND l.to_id IN (${GLOBAL_PROJECT})`;
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
@@ -0,0 +1,5 @@
1
+ import type { StoreContext } from "./open.js";
2
+ /** Whether the owner separated anyone of `one` from anyone of `other`; nothing automatic may join them again. */
3
+ export declare const separated: (context: StoreContext, one: number, other: number) => boolean;
4
+ /** Whether the owner separated this one identity from `person` or from anyone of it. */
5
+ export declare const identitySeparated: (context: StoreContext, identity: number, person: number) => boolean;
@@ -0,0 +1,26 @@
1
+ const identitiesOf = ({ database }, person) => database
2
+ .prepare("SELECT identity_id AS pk FROM identity_links WHERE person_id = ?")
3
+ .all(person)
4
+ .map(({ pk }) => Number(pk));
5
+ const MOVED_AWAY = `moved.identity_id IN (SELECT value FROM json_each(?))
6
+ AND (moved.from_person_id IN (SELECT value FROM json_each(?))
7
+ OR EXISTS (SELECT 1 FROM identity_link_events held WHERE held.to_person_id = moved.from_person_id
8
+ AND held.identity_id IN (SELECT value FROM json_each(?))))`;
9
+ /**
10
+ * The owner once moved an identity of one side out of the other side's person, or out of a person that held an
11
+ * identity of the other side. Checked over whole people because a merge moves whole people: a pair check lets a
12
+ * third identity carry two separated people back together.
13
+ */
14
+ const apart = ({ database }, one, other) => {
15
+ const ids = (side) => JSON.stringify(side.identities);
16
+ const person = (side) => JSON.stringify(side.person === undefined ? [] : [side.person]);
17
+ return (database
18
+ .prepare(`SELECT 1 FROM identity_link_events moved WHERE moved.author = 'owner'
19
+ AND ((${MOVED_AWAY}) OR (${MOVED_AWAY})) LIMIT 1`)
20
+ .get(ids(one), person(other), ids(other), ids(other), person(one), ids(one)) !== undefined);
21
+ };
22
+ /** Whether the owner separated anyone of `one` from anyone of `other`; nothing automatic may join them again. */
23
+ export const separated = (context, one, other) => one !== other &&
24
+ apart(context, { identities: identitiesOf(context, one), person: one }, { identities: identitiesOf(context, other), person: other });
25
+ /** Whether the owner separated this one identity from `person` or from anyone of it. */
26
+ export const identitySeparated = (context, identity, person) => apart(context, { identities: [identity] }, { identities: identitiesOf(context, person).filter((pk) => pk !== identity), person });
@@ -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
- const row = database
47
- .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) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) RETURNING id")
48
- .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);
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) }));
@@ -0,0 +1,44 @@
1
+ import { type RecordEntityType } from "../../domain/record-types.js";
2
+ import type { EnvelopeSource } from "../../domain/records.js";
3
+ import type { financeOperationsOver, PaymentDetail } from "./finance.js";
4
+ export type Row = Record<string, unknown>;
5
+ export interface Share {
6
+ invoice: string;
7
+ /** As the source gave it; `null` settles as far as both allow. */
8
+ amount: string | null;
9
+ }
10
+ /** The entities a record's relations resolved to, by role, and what each invoice a payment settles gets. */
11
+ export interface Related {
12
+ related: Map<string, string[]>;
13
+ shares: Share[];
14
+ }
15
+ export interface ProjectionTools {
16
+ finance: ReturnType<typeof financeOperationsOver>;
17
+ settle: (made: PaymentDetail, shares: Share[]) => string;
18
+ }
19
+ /** Makes the proposal a record stands for and returns its ref. */
20
+ export type Projector = (fields: Row, related: Related, source: EnvelopeSource, tools: ProjectionTools) => string;
21
+ export declare const IMPORTER: {
22
+ readonly bot: "import";
23
+ };
24
+ /** `at` names the record's member at fault; a refused entity is the fields' fault. */
25
+ export declare const refusal: (message: string, code: string, at?: string | (string | number)[]) => never;
26
+ export declare const stringField: (fields: Row, name: string) => string | undefined;
27
+ /** `null` for a type whose entity only the owner's `map` gives. */
28
+ export declare const RECORD_PROJECTORS: {
29
+ readonly invoice: (fields: Row, { related }: Related, source: EnvelopeSource, { finance }: ProjectionTools) => string;
30
+ readonly payment: (fields: Row, { related, shares }: Related, source: EnvelopeSource, { finance, settle }: ProjectionTools) => string;
31
+ readonly person: null;
32
+ readonly organization: null;
33
+ readonly project: null;
34
+ };
35
+ export type ProjectedType = {
36
+ [K in RecordEntityType]: (typeof RECORD_PROJECTORS)[K] extends null ? never : K;
37
+ }[RecordEntityType];
38
+ export declare const PROJECTED_TYPES: ProjectedType[];
39
+ export declare const isProjected: (type: unknown) => type is ProjectedType;
40
+ /**
41
+ * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
42
+ * whose `fields.payer` is not text is refused, as before the registry.
43
+ */
44
+ export declare const FIELD_REFERENCE_ROLES: string[];
@@ -0,0 +1,72 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { RECORD_ENTITY_TYPES, roleNames } from "../../domain/record-types.js";
3
+ export const IMPORTER = { bot: "import" };
4
+ /** `at` names the record's member at fault; a refused entity is the fields' fault. */
5
+ export const refusal = (message, code, at) => {
6
+ throw new CliError("validation_error", message, { reason: code, ...(at === undefined ? {} : { at }) });
7
+ };
8
+ export const stringField = (fields, name) => {
9
+ const value = fields[name];
10
+ if (value === undefined || value === null)
11
+ return undefined;
12
+ if (typeof value !== "string")
13
+ return refusal(`fields.${name} is text`, "record.invalid");
14
+ return value;
15
+ };
16
+ const written = (source) => ({
17
+ by: IMPORTER,
18
+ source: `import:${source.provider}`,
19
+ reason: `imported from ${source.provider} account ${source.account}, batch ${source.batch_id}`,
20
+ });
21
+ const invoiceOf = (fields, related, source) => {
22
+ if (!Array.isArray(fields.lines) || fields.lines.some((line) => typeof line !== "object" || line === null))
23
+ return refusal("an invoice's fields.lines is a list of lines", "record.invalid");
24
+ const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
25
+ return {
26
+ ...written(source),
27
+ direction: fields.direction,
28
+ number: stringField(fields, "number"),
29
+ issuer: one("issuer"),
30
+ counterparty: one("counterparty"),
31
+ project: one("project"),
32
+ currency: fields.currency,
33
+ issueDate: stringField(fields, "issue_date"),
34
+ dueDate: stringField(fields, "due_date"),
35
+ total: fields.total,
36
+ lines: fields.lines.map((line) => ({
37
+ description: line.description,
38
+ quantity: line.quantity,
39
+ unitPrice: line.unit_price,
40
+ amount: line.amount,
41
+ })),
42
+ };
43
+ };
44
+ const paymentOf = (fields, related, source) => {
45
+ const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
46
+ return {
47
+ ...written(source),
48
+ direction: fields.direction,
49
+ payer: one("payer"),
50
+ payee: one("payee"),
51
+ project: one("project"),
52
+ amount: fields.amount,
53
+ currency: fields.currency,
54
+ date: fields.date,
55
+ reference: stringField(fields, "reference"),
56
+ };
57
+ };
58
+ /** `null` for a type whose entity only the owner's `map` gives. */
59
+ export const RECORD_PROJECTORS = {
60
+ invoice: (fields, { related }, source, { finance }) => finance.addInvoice(invoiceOf(fields, related, source)).ref,
61
+ payment: (fields, { related, shares }, source, { finance, settle }) => settle(finance.addPayment(paymentOf(fields, related, source)), shares),
62
+ person: null,
63
+ organization: null,
64
+ project: null,
65
+ };
66
+ export const PROJECTED_TYPES = RECORD_ENTITY_TYPES.filter((type) => RECORD_PROJECTORS[type] !== null);
67
+ export const isProjected = (type) => PROJECTED_TYPES.includes(type);
68
+ /**
69
+ * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
70
+ * whose `fields.payer` is not text is refused, as before the registry.
71
+ */
72
+ export const FIELD_REFERENCE_ROLES = roleNames(PROJECTED_TYPES, (role) => !role.many);
@@ -1,22 +1,14 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
3
+ import { rolesOf } from "../../domain/record-types.js";
3
4
  import { pointerOf, recordFingerprint, } from "../../domain/records.js";
4
5
  import { accountPk, findAccountPk } from "./accounts.js";
5
6
  import { financeOperationsOver } from "./finance.js";
6
7
  import { requiredThing } from "./notes.js";
8
+ import { FIELD_REFERENCE_ROLES, IMPORTER, isProjected, PROJECTED_TYPES, RECORD_PROJECTORS, refusal, stringField, } from "./record-projectors.js";
7
9
  import { referenceOfThing, storedThing } from "./things.js";
8
10
  import { read, write } from "./transaction.js";
9
- const PROJECTED = {
10
- invoice: { roles: ["issuer", "counterparty", "project"], many: [] },
11
- payment: { roles: ["payer", "payee", "project", "settles"], many: ["settles"] },
12
- };
13
- const isProjected = (type) => type === "invoice" || type === "payment";
14
- const IMPORTER = { bot: "import" };
15
- const REFERENCE_FIELDS = ["issuer", "counterparty", "project", "payer", "payee"];
16
- /** `at` names the record's member at fault; a refused entity is the fields' fault. */
17
- const refusal = (message, code, at) => {
18
- throw new CliError("validation_error", message, { reason: code, ...(at === undefined ? {} : { at }) });
19
- };
11
+ const PROJECTED_TYPES_SQL = PROJECTED_TYPES.map((type) => `'${type}'`).join(", ");
20
12
  const codeOf = (error) => {
21
13
  const reason = error.details?.reason;
22
14
  if (typeof reason === "string")
@@ -26,56 +18,6 @@ const codeOf = (error) => {
26
18
  /** A record's fingerprint without its settles relations: what an import may not change on a payment it proposed. */
27
19
  const unsettled = (fields, relations) => recordFingerprint(fields, relations.filter((relation) => relation.role !== "settles"));
28
20
  const iso = (value) => new Date(Number(value)).toISOString();
29
- const stringField = (fields, name) => {
30
- const value = fields[name];
31
- if (value === undefined || value === null)
32
- return undefined;
33
- if (typeof value !== "string")
34
- return refusal(`fields.${name} is text`, "record.invalid");
35
- return value;
36
- };
37
- const invoiceOf = (fields, related, source) => {
38
- if (!Array.isArray(fields.lines) || fields.lines.some((line) => typeof line !== "object" || line === null))
39
- return refusal("an invoice's fields.lines is a list of lines", "record.invalid");
40
- const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
41
- return {
42
- ...written(source),
43
- direction: fields.direction,
44
- number: stringField(fields, "number"),
45
- issuer: one("issuer"),
46
- counterparty: one("counterparty"),
47
- project: one("project"),
48
- currency: fields.currency,
49
- issueDate: stringField(fields, "issue_date"),
50
- dueDate: stringField(fields, "due_date"),
51
- total: fields.total,
52
- lines: fields.lines.map((line) => ({
53
- description: line.description,
54
- quantity: line.quantity,
55
- unitPrice: line.unit_price,
56
- amount: line.amount,
57
- })),
58
- };
59
- };
60
- const paymentOf = (fields, related, source) => {
61
- const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
62
- return {
63
- ...written(source),
64
- direction: fields.direction,
65
- payer: one("payer"),
66
- payee: one("payee"),
67
- project: one("project"),
68
- amount: fields.amount,
69
- currency: fields.currency,
70
- date: fields.date,
71
- reference: stringField(fields, "reference"),
72
- };
73
- };
74
- const written = (source) => ({
75
- by: IMPORTER,
76
- source: `import:${source.provider}`,
77
- reason: `imported from ${source.provider} account ${source.account}, batch ${source.batch_id}`,
78
- });
79
21
  export const recordStoreOver = (context) => {
80
22
  const { database, now } = context;
81
23
  const finance = financeOperationsOver(context);
@@ -91,7 +33,9 @@ export const recordStoreOver = (context) => {
91
33
  const entityRef = (type, id) => type == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? `${String(type)}:${String(id)}`);
92
34
  /** Roles a projection needs whose target has no entity yet, the entities of the rest, and what each invoice gets. */
93
35
  const relatedOf = (recordId, type) => {
94
- const { roles, many } = PROJECTED[type];
36
+ const roles = rolesOf(type);
37
+ const known = roles.map(([name]) => name);
38
+ const many = roles.flatMap(([name, role]) => (role.many ? [name] : []));
95
39
  const rows = sql("SELECT rr.role, rr.amount, t.entity_type, t.entity_id FROM record_relations rr " +
96
40
  "LEFT JOIN records t ON t.id = rr.target_id AND t.deleted_at IS NULL WHERE rr.record_id = ? ORDER BY rr.id").all(recordId);
97
41
  const related = new Map();
@@ -99,7 +43,7 @@ export const recordStoreOver = (context) => {
99
43
  const missing = new Set();
100
44
  for (const row of rows) {
101
45
  const role = String(row.role);
102
- if (!roles.includes(role))
46
+ if (!known.includes(role))
103
47
  continue;
104
48
  const ref = entityRef(row.entity_type, row.entity_id);
105
49
  if (ref === null)
@@ -114,18 +58,16 @@ export const recordStoreOver = (context) => {
114
58
  refusal(`a record has one ${role}`, "record.relation-ambiguous");
115
59
  return { related, shares, missing: [...missing] };
116
60
  };
117
- /** Makes the proposal a waiting invoice or payment record stands for, once every reference it names has an entity. */
61
+ /** Makes the proposal a waiting record stands for, once every reference it names has an entity. */
118
62
  const project = (row, source) => {
119
63
  const type = row.type;
120
64
  const { related, shares, missing } = relatedOf(Number(row.id), type);
121
65
  if (missing.length > 0)
122
66
  return { missing };
123
67
  const fields = JSON.parse(String(row.fields));
124
- for (const name of REFERENCE_FIELDS)
68
+ for (const name of FIELD_REFERENCE_ROLES)
125
69
  stringField(fields, name);
126
- const ref = type === "invoice"
127
- ? finance.addInvoice(invoiceOf(fields, related, source)).ref
128
- : settle(finance.addPayment(paymentOf(fields, related, source)), shares);
70
+ const ref = RECORD_PROJECTORS[type](fields, { related, shares }, source, { finance, settle });
129
71
  const entity = requiredThing(database, ref);
130
72
  sql("UPDATE records SET entity_type = ?, entity_id = ?, projected_fingerprint = fingerprint WHERE id = ?").run(entity.type, entity.id, Number(row.id));
131
73
  return { proposed: ref, missing: [] };
@@ -211,7 +153,7 @@ export const recordStoreOver = (context) => {
211
153
  const queue = [target];
212
154
  while (queue.length > 0) {
213
155
  const rows = sql("SELECT DISTINCT r.* FROM record_relations rr JOIN records r ON r.id = rr.record_id WHERE rr.target_id = ? " +
214
- "AND r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN ('invoice', 'payment')").all(queue.shift());
156
+ `AND r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN (${PROJECTED_TYPES_SQL})`).all(queue.shift());
215
157
  for (const row of rows) {
216
158
  try {
217
159
  const done = write(database, () => project(row, source));
@@ -434,7 +376,7 @@ export const recordStoreOver = (context) => {
434
376
  return [];
435
377
  const rows = database
436
378
  .prepare(`${SELECT}WHERE a.provider = ? AND a.external_id = ? AND (? IS NULL OR r.type = ?) ` +
437
- "AND (? IS NULL OR (r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN ('invoice', 'payment'))) " +
379
+ `AND (? IS NULL OR (r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN (${PROJECTED_TYPES_SQL}))) ` +
438
380
  "AND (? IS NULL OR (r.entity_id IS NOT NULL AND (r.deleted_at IS NOT NULL " +
439
381
  "OR r.projected_fingerprint IS NOT r.fingerprint))) ORDER BY r.updated_at DESC, r.id DESC LIMIT ?")
440
382
  .all(provider, account, type ?? null, type ?? null, waiting ? 1 : null, flagged ? 1 : null, limit);
@@ -0,0 +1,43 @@
1
+ import { type RelationKind, type Standing } from "../../domain/relations.js";
2
+ import type { AccountKey } from "../types.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type KnowledgeRelation } from "./relation-proposals.js";
5
+ export interface RelationFilter {
6
+ kind?: RelationKind;
7
+ role?: string;
8
+ /** `proposed` holds the pending `relationship` proposals and the unconfirmed suggestions. */
9
+ standing?: Standing;
10
+ from?: string;
11
+ to?: string;
12
+ /** Either end; each row then says its `direction` and, read backwards, the kind's inverse label. */
13
+ about?: string;
14
+ /** Held at this time (UTC ms): started by then, or with no start, and not ended by then. */
15
+ at?: number;
16
+ /** Ended relationships are left out unless asked for, or unless `standing` is `ended`. */
17
+ includeEnded?: boolean;
18
+ /** A source's relationships only from these accounts; the owner's and agents' always. */
19
+ accounts?: AccountKey[];
20
+ /** No row with an end of these types, such as `deal` and `lead` a profile denies. */
21
+ deniedKinds?: string[];
22
+ limit?: number;
23
+ /** 1-based. */
24
+ page?: number;
25
+ }
26
+ export interface RelationListItem extends KnowledgeRelation {
27
+ /** `proposal`: a pending `relationship` proposal, decided through the review list by its `id`. */
28
+ source: "link" | "proposal";
29
+ /** With `about`: whether that ref is the relationship's `from` (`outgoing`) or its `to` (`incoming`). */
30
+ direction?: "outgoing" | "incoming";
31
+ /** With `about` and `incoming`: how it reads backwards (`manages` for `reports-to`); `null` when it has none. */
32
+ inverse?: string | null;
33
+ /** A stored role off the list its ends take, such as one written before the lists. */
34
+ custom: boolean;
35
+ }
36
+ export interface RelationList {
37
+ /** Relationships and pending relationship proposals, filtered and paged in one query (WC-CMD-20). */
38
+ listRelations(filter?: RelationFilter): Promise<{
39
+ items: RelationListItem[];
40
+ hasMore: boolean;
41
+ }>;
42
+ }
43
+ export declare const relationListOver: (context: StoreContext) => RelationList;