@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.
Files changed (260) hide show
  1. package/CHANGELOG.md +284 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +4 -1
  12. package/dist/cli/index.js +4 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/cli/store-settings.js +38 -4
  17. package/dist/crm/cli/csv.d.ts +23 -0
  18. package/dist/crm/cli/csv.js +135 -0
  19. package/dist/crm/cli/index.d.ts +1 -1
  20. package/dist/crm/cli/index.js +36 -22
  21. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  22. package/dist/crm/cli/pipeline-view.js +36 -0
  23. package/dist/crm/index.d.ts +2 -2
  24. package/dist/crm/index.js +1 -1
  25. package/dist/crm/source.d.ts +35 -5
  26. package/dist/crm/sync.d.ts +15 -7
  27. package/dist/crm/sync.js +169 -11
  28. package/dist/crm/writes.d.ts +6 -4
  29. package/dist/crm/writes.js +17 -13
  30. package/dist/documents.d.ts +2 -0
  31. package/dist/documents.js +2 -0
  32. package/dist/domain/business.d.ts +79 -0
  33. package/dist/domain/business.js +42 -0
  34. package/dist/domain/crm.d.ts +41 -2
  35. package/dist/domain/deals.d.ts +5 -2
  36. package/dist/domain/deals.js +5 -2
  37. package/dist/domain/finance.d.ts +2 -0
  38. package/dist/domain/finance.js +2 -2
  39. package/dist/domain/google-documents.d.ts +2 -0
  40. package/dist/domain/google-documents.js +3 -1
  41. package/dist/domain/money.d.ts +2 -0
  42. package/dist/domain/money.js +11 -3
  43. package/dist/domain/providers.d.ts +36 -1
  44. package/dist/domain/providers.js +69 -7
  45. package/dist/domain/record-fields.d.ts +42 -0
  46. package/dist/domain/record-fields.js +122 -0
  47. package/dist/domain/record-types.d.ts +489 -16
  48. package/dist/domain/record-types.js +374 -7
  49. package/dist/domain/records.d.ts +96 -5
  50. package/dist/domain/records.js +178 -32
  51. package/dist/domain/ref-summaries.js +5 -0
  52. package/dist/domain/references.d.ts +1 -1
  53. package/dist/domain/references.js +5 -0
  54. package/dist/domain/relations.d.ts +125 -0
  55. package/dist/domain/relations.js +107 -0
  56. package/dist/domain/vcard.d.ts +25 -0
  57. package/dist/domain/vcard.js +267 -0
  58. package/dist/entities/deal.d.ts +16 -2
  59. package/dist/entities/deal.js +5 -1
  60. package/dist/entities/index.d.ts +29 -13
  61. package/dist/entities/relationship.d.ts +8 -2
  62. package/dist/entities/relationship.js +8 -2
  63. package/dist/entities/task-results.d.ts +10 -10
  64. package/dist/errors/reasons.js +73 -2
  65. package/dist/fetch/addresses.d.ts +5 -0
  66. package/dist/fetch/addresses.js +76 -0
  67. package/dist/fetch/page.d.ts +64 -0
  68. package/dist/fetch/page.js +256 -0
  69. package/dist/index.d.ts +7 -4
  70. package/dist/index.js +6 -3
  71. package/dist/mail/cli/review.js +20 -6
  72. package/dist/mail/index.d.ts +1 -1
  73. package/dist/mail/marks.d.ts +10 -5
  74. package/dist/mail/marks.js +16 -8
  75. package/dist/mail/review.d.ts +5 -0
  76. package/dist/meetings/calendar-text.d.ts +1 -1
  77. package/dist/meetings/calendar-text.js +4 -0
  78. package/dist/meetings/event-store.d.ts +2 -2
  79. package/dist/search/account-list.d.ts +4 -0
  80. package/dist/search/account-list.js +19 -8
  81. package/dist/search/query.js +2 -2
  82. package/dist/services/events-search.js +2 -2
  83. package/dist/services/index.d.ts +1 -1
  84. package/dist/services/index.js +1 -1
  85. package/dist/services/ingest.d.ts +56 -8
  86. package/dist/services/ingest.js +95 -61
  87. package/dist/services/link-scorers/scan.js +2 -1
  88. package/dist/services/link-scorers/shared.js +2 -1
  89. package/dist/services/messages-search.js +3 -2
  90. package/dist/services/metadata.d.ts +1 -1
  91. package/dist/services/notes-search.js +1 -0
  92. package/dist/services/project-status/index.js +2 -1
  93. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  94. package/dist/services/proposals/kinds/contracts.js +9 -0
  95. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  96. package/dist/services/proposals/kinds/finance.js +14 -35
  97. package/dist/services/proposals/kinds/orders.js +7 -30
  98. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  99. package/dist/services/proposals/kinds/shared.js +34 -0
  100. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  101. package/dist/services/proposals/kinds/source-review.js +45 -0
  102. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  103. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  104. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  105. package/dist/services/proposals/kinds/transactions.js +10 -0
  106. package/dist/services/proposals/registry.js +9 -0
  107. package/dist/services/search-all-meetings.js +2 -2
  108. package/dist/services/search-all.js +4 -3
  109. package/dist/services/search-kind.js +3 -3
  110. package/dist/services/stored-project-gathering.js +4 -3
  111. package/dist/store/decisions.js +5 -1
  112. package/dist/store/exports.d.ts +1 -0
  113. package/dist/store/exports.js +1 -0
  114. package/dist/store/index.d.ts +20 -4
  115. package/dist/store/index.js +4 -0
  116. package/dist/store/people.js +1 -1
  117. package/dist/store/project-transfer/request.d.ts +4 -1
  118. package/dist/store/project-transfer/schema.d.ts +9 -2
  119. package/dist/store/project-transfer/schema.js +4 -0
  120. package/dist/store/project-transfer/snapshot-model.d.ts +8 -2
  121. package/dist/store/source-review.d.ts +64 -0
  122. package/dist/store/source-review.js +7 -0
  123. package/dist/store/sqlite/accounts.d.ts +1 -1
  124. package/dist/store/sqlite/accounts.js +24 -1
  125. package/dist/store/sqlite/added-sources.d.ts +82 -0
  126. package/dist/store/sqlite/added-sources.js +237 -0
  127. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  128. package/dist/store/sqlite/business-contracts.js +182 -0
  129. package/dist/store/sqlite/calendar-events.js +7 -3
  130. package/dist/store/sqlite/calendar-forget.js +3 -0
  131. package/dist/store/sqlite/calendar.d.ts +21 -1
  132. package/dist/store/sqlite/calendar.js +27 -7
  133. package/dist/store/sqlite/chat-rekey.js +7 -0
  134. package/dist/store/sqlite/chats.d.ts +3 -1
  135. package/dist/store/sqlite/chats.js +15 -1
  136. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  137. package/dist/store/sqlite/crm-rows.js +195 -0
  138. package/dist/store/sqlite/crm-settings.d.ts +28 -0
  139. package/dist/store/sqlite/crm-settings.js +80 -0
  140. package/dist/store/sqlite/crm.d.ts +42 -11
  141. package/dist/store/sqlite/crm.js +402 -196
  142. package/dist/store/sqlite/deals.d.ts +4 -8
  143. package/dist/store/sqlite/deals.js +8 -5
  144. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  145. package/dist/store/sqlite/emails.js +2 -0
  146. package/dist/store/sqlite/entity-types.d.ts +14 -9
  147. package/dist/store/sqlite/entity-types.js +4 -10
  148. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  149. package/dist/store/sqlite/evidence-signature.js +349 -0
  150. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  151. package/dist/store/sqlite/evidence-sources.js +7 -3
  152. package/dist/store/sqlite/facts.d.ts +7 -2
  153. package/dist/store/sqlite/facts.js +21 -5
  154. package/dist/store/sqlite/finance.d.ts +18 -105
  155. package/dist/store/sqlite/finance.js +100 -219
  156. package/dist/store/sqlite/involvement-queue.js +4 -3
  157. package/dist/store/sqlite/knowledge.d.ts +14 -4
  158. package/dist/store/sqlite/knowledge.js +108 -102
  159. package/dist/store/sqlite/labelled.d.ts +3 -0
  160. package/dist/store/sqlite/labelled.js +11 -0
  161. package/dist/store/sqlite/link-kinds.d.ts +4 -3
  162. package/dist/store/sqlite/link-kinds.js +6 -2
  163. package/dist/store/sqlite/manifest.js +7 -0
  164. package/dist/store/sqlite/memories.d.ts +24 -10
  165. package/dist/store/sqlite/memories.js +73 -19
  166. package/dist/store/sqlite/messages.js +2 -0
  167. package/dist/store/sqlite/migrations.generated.js +134 -0
  168. package/dist/store/sqlite/money-lines.d.ts +48 -0
  169. package/dist/store/sqlite/money-lines.js +76 -0
  170. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  171. package/dist/store/sqlite/money-transactions.js +295 -0
  172. package/dist/store/sqlite/notes.d.ts +14 -4
  173. package/dist/store/sqlite/notes.js +43 -31
  174. package/dist/store/sqlite/orders.d.ts +36 -6
  175. package/dist/store/sqlite/orders.js +126 -46
  176. package/dist/store/sqlite/organizations.d.ts +8 -0
  177. package/dist/store/sqlite/organizations.js +14 -0
  178. package/dist/store/sqlite/payment-facts.js +1 -1
  179. package/dist/store/sqlite/person-preparation.d.ts +1 -1
  180. package/dist/store/sqlite/person-preparation.js +3 -2
  181. package/dist/store/sqlite/private-people.js +2 -0
  182. package/dist/store/sqlite/products.d.ts +78 -0
  183. package/dist/store/sqlite/products.js +131 -0
  184. package/dist/store/sqlite/project-transfer/records.js +39 -3
  185. package/dist/store/sqlite/project-transfer/snapshot.d.ts +4 -1
  186. package/dist/store/sqlite/project-transfer/snapshot.js +11 -3
  187. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  188. package/dist/store/sqlite/proposed-actions.js +24 -7
  189. package/dist/store/sqlite/providers.d.ts +0 -4
  190. package/dist/store/sqlite/providers.js +20 -2
  191. package/dist/store/sqlite/record-matching.d.ts +80 -0
  192. package/dist/store/sqlite/record-matching.js +264 -0
  193. package/dist/store/sqlite/record-projection.d.ts +89 -0
  194. package/dist/store/sqlite/record-projection.js +50 -0
  195. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  196. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  197. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  198. package/dist/store/sqlite/record-projectors-money.js +214 -0
  199. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  200. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  201. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  202. package/dist/store/sqlite/record-projectors.js +7 -67
  203. package/dist/store/sqlite/record-relations.d.ts +24 -0
  204. package/dist/store/sqlite/record-relations.js +92 -0
  205. package/dist/store/sqlite/record-remap.d.ts +12 -0
  206. package/dist/store/sqlite/record-remap.js +92 -0
  207. package/dist/store/sqlite/record-run.d.ts +71 -0
  208. package/dist/store/sqlite/record-run.js +179 -0
  209. package/dist/store/sqlite/record-settling.d.ts +9 -0
  210. package/dist/store/sqlite/record-settling.js +74 -0
  211. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  212. package/dist/store/sqlite/record-stamps.js +30 -0
  213. package/dist/store/sqlite/record-writes.d.ts +43 -0
  214. package/dist/store/sqlite/record-writes.js +307 -0
  215. package/dist/store/sqlite/records.d.ts +52 -42
  216. package/dist/store/sqlite/records.js +123 -353
  217. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  218. package/dist/store/sqlite/ref-summaries.js +60 -8
  219. package/dist/store/sqlite/refunds.d.ts +31 -0
  220. package/dist/store/sqlite/refunds.js +112 -0
  221. package/dist/store/sqlite/relation-list.d.ts +43 -0
  222. package/dist/store/sqlite/relation-list.js +133 -0
  223. package/dist/store/sqlite/relation-proposals.d.ts +28 -6
  224. package/dist/store/sqlite/relation-proposals.js +134 -10
  225. package/dist/store/sqlite/relation-reads.d.ts +8 -0
  226. package/dist/store/sqlite/relation-reads.js +7 -0
  227. package/dist/store/sqlite/relation-roles.d.ts +26 -0
  228. package/dist/store/sqlite/relation-roles.js +91 -0
  229. package/dist/store/sqlite/reported-relations.d.ts +63 -0
  230. package/dist/store/sqlite/reported-relations.js +132 -0
  231. package/dist/store/sqlite/reviewed.d.ts +109 -0
  232. package/dist/store/sqlite/reviewed.js +173 -0
  233. package/dist/store/sqlite/schema/link-revisions.d.ts +136 -0
  234. package/dist/store/sqlite/schema/link-revisions.js +11 -0
  235. package/dist/store/sqlite/schema/links.d.ts +360 -0
  236. package/dist/store/sqlite/schema/links.js +32 -0
  237. package/dist/store/sqlite/schema.d.ts +2769 -306
  238. package/dist/store/sqlite/schema.js +258 -25
  239. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  240. package/dist/store/sqlite/source-review-marks.js +143 -0
  241. package/dist/store/sqlite/source-review.d.ts +54 -0
  242. package/dist/store/sqlite/source-review.js +221 -0
  243. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  244. package/dist/store/sqlite/stage-amounts.js +23 -0
  245. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  246. package/dist/store/sqlite/subscriptions.js +294 -0
  247. package/dist/store/sqlite/text-input.d.ts +3 -0
  248. package/dist/store/sqlite/text-input.js +13 -0
  249. package/dist/store/sqlite/things.js +2 -9
  250. package/dist/store/sqlite/transaction.d.ts +15 -0
  251. package/dist/store/sqlite/transaction.js +57 -0
  252. package/dist/store/sqlite/wallets.d.ts +88 -0
  253. package/dist/store/sqlite/wallets.js +143 -0
  254. package/dist/store/store-errors.d.ts +1 -0
  255. package/dist/store/store-errors.js +45 -0
  256. package/dist/store/store.d.ts +19 -1
  257. package/dist/store/store.js +35 -6
  258. package/package.json +6 -3
  259. package/schemas/examples/records-business.jsonl +11 -0
  260. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { and, asc, eq, inArray, sql } from "./drizzle/core.js";
3
3
  import { pointerPairs } from "./entity-types.js";
4
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
4
5
  import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
5
6
  import { dropUnusedVectors } from "./vector-index.js";
6
7
  /** An account's row, made on first sight; a name only replaces what was known when there is one. */
@@ -53,8 +54,24 @@ export const storedAccount = ({ orm }, { provider, account }) => {
53
54
  return found;
54
55
  };
55
56
  /** Everything the account holds, children before parents: the foreign keys are enforced. */
56
- export const purgeAccount = ({ orm, database }, accountKey) => {
57
+ export const purgeAccount = ({ orm, database, now }, accountKey) => {
57
58
  const unseenBefore = unreferenced(database, "identities");
59
+ const at = now();
60
+ const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
61
+ const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
62
+ for (const [type, sql] of [
63
+ ["message", "SELECT id FROM messages WHERE account_id = ?"],
64
+ ["chat", "SELECT id FROM chats WHERE account_id = ?"],
65
+ ["email", "SELECT id FROM emails WHERE account_id = ?"],
66
+ ["email_thread", "SELECT id FROM email_threads WHERE account_id = ?"],
67
+ ["meeting", meetingIds],
68
+ ["meeting_transcript", transcriptIds],
69
+ [
70
+ "meeting_transcript_row",
71
+ `SELECT id FROM meeting_transcript_rows WHERE meeting_transcript_id IN (${transcriptIds})`,
72
+ ],
73
+ ])
74
+ forgetEvidenceTo(database, type, { sql, params: [accountKey] }, at);
58
75
  const chatsOf = orm.select({ pk: chats.id }).from(chats).where(eq(chats.accountId, accountKey));
59
76
  const messagesOf = orm.select({ pk: messages.id }).from(messages).where(eq(messages.accountId, accountKey));
60
77
  orm.delete(botUpdates).where(eq(botUpdates.accountId, accountKey)).run();
@@ -114,6 +131,11 @@ export const purgeAccount = ({ orm, database }, accountKey) => {
114
131
  // The inbox project and its tasks are the owner's; only the tie to the account goes.
115
132
  orm.update(projects).set({ accountId: null }).where(eq(projects.accountId, accountKey)).run();
116
133
  orm.run(sql `DELETE FROM files WHERE account_id = ${accountKey}`);
134
+ // Deleting a document clears its pieces, words, revisions, tags and own links (trigger document_bd).
135
+ const documentsOf = sql `(SELECT id FROM documents WHERE account_id = ${accountKey})`;
136
+ orm.run(sql `DELETE FROM links WHERE to_type = 'document' AND to_id IN ${documentsOf}`);
137
+ orm.run(sql `UPDATE files SET document_id = NULL WHERE document_id IN ${documentsOf}`);
138
+ orm.run(sql `DELETE FROM documents WHERE account_id = ${accountKey}`);
117
139
  orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
118
140
  // An entity made from a record is the owner's and stays; only what the source said goes.
119
141
  const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
@@ -121,6 +143,7 @@ export const purgeAccount = ({ orm, database }, accountKey) => {
121
143
  orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
122
144
  orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
123
145
  dropOrphanPeople(database, unseenBefore);
146
+ forgetDanglingEvidence(database, at);
124
147
  dropUnusedVectors(database, hashes);
125
148
  };
126
149
  /** Identity and person rows a person's own record keeps, not evidence that anyone saw them. */
@@ -0,0 +1,82 @@
1
+ import type { Section } from "../../readers/types.js";
2
+ import type { Decider } from "../decisions.js";
3
+ import { type DocumentMetadata } from "./document-metadata.js";
4
+ import { type Note, type NoteFolder } from "./notes.js";
5
+ import type { StoreContext } from "./open.js";
6
+ export declare const ADDED_KINDS: readonly ["text", "file", "page"];
7
+ /** A source the owner adds by hand: pasted text, a file, or a page read from a link. */
8
+ export interface AddedSourceInput {
9
+ kind: (typeof ADDED_KINDS)[number];
10
+ /** What a reader found; empty when it found none (`read: "no-text"`). */
11
+ text: string;
12
+ read: "extracted" | "no-text";
13
+ title?: string | null;
14
+ /** The page's address, or where a file came from. */
15
+ url?: string | null;
16
+ fileName?: string | null;
17
+ mime?: string | null;
18
+ size?: number | null;
19
+ /** A file's own bytes, which name it. Pasted text and a page are named by their normalized text. */
20
+ bytes?: Uint8Array;
21
+ /** People, organizations, projects, tasks or meetings it is about (`person:3`), linked `about`. */
22
+ subjects?: readonly string[];
23
+ /** The owner's subjects are his statement; an agent's wait unconfirmed, as its links always do. */
24
+ by: Decider;
25
+ /** Where the caller keeps a copy of the file. Without it only the text is kept, and nothing claims a copy. */
26
+ keepCopy?: {
27
+ path: string;
28
+ };
29
+ metadata?: DocumentMetadata;
30
+ sections?: Section[];
31
+ }
32
+ /** What names an added source: enough to find it before anything is written. */
33
+ export type AddedSourceContent = Pick<AddedSourceInput, "kind" | "text" | "url" | "bytes">;
34
+ /** The part of `store.notes` that keeps the sources added by hand. */
35
+ export interface AddedSources {
36
+ /**
37
+ * Saves a source the owner added by hand into the `added` account, named `sha256:<hash>`: a repeat is the same
38
+ * document, and a live folder or Drive document with the same content is answered as `duplicateOf`, given only the
39
+ * new subjects.
40
+ */
41
+ saveAddedSource(input: AddedSourceInput): Promise<AddedSource>;
42
+ /** The account of the sources added by hand, once one was saved. */
43
+ addedAccount(): Promise<NoteFolder | undefined>;
44
+ /**
45
+ * What saving this content would find, read only: the live added source it repeats, or the folder or Drive document
46
+ * it duplicates. A caller that keeps a copy of the file asks this first, and writes the copy only when both are null.
47
+ */
48
+ findAddedSource(content: AddedSourceContent): Promise<{
49
+ existing: string | null;
50
+ duplicateOf: string | null;
51
+ }>;
52
+ /**
53
+ * Removes an added source the way a folder file's removal does: its text goes, its row stays as deleted. The owner's
54
+ * alone. Answers the copy's path, for the caller to delete, when one was kept.
55
+ */
56
+ removeAddedSource(reference: string, by: Decider): Promise<{
57
+ ref: string;
58
+ removed: true;
59
+ copy: string | null;
60
+ }>;
61
+ }
62
+ export interface AddedSource {
63
+ /** The document holding it: the added one, or the live document of the same content it duplicates. */
64
+ note: Note;
65
+ created: boolean;
66
+ /** The folder or Drive document with the same content, when nothing new was stored. */
67
+ duplicateOf: string | null;
68
+ /** What is kept of the source: its text, or its text and a copy; `null` for a duplicate. */
69
+ kept: "text" | "copy" | null;
70
+ /** Every subject the document is about now, the ones linked before included. */
71
+ subjects: string[];
72
+ }
73
+ /**
74
+ * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
75
+ * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
76
+ */
77
+ export declare const addedSourceKeyOf: (content: AddedSourceContent) => {
78
+ externalId: string;
79
+ hash: string;
80
+ hashes: string[];
81
+ };
82
+ export declare const addedSourcesOver: (context: StoreContext) => AddedSources;
@@ -0,0 +1,237 @@
1
+ import { createHash } from "node:crypto";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { MAX_TEXT_CHARS } from "../../attachments/limits.js";
4
+ import { ADDED_ACCOUNT, ADDED_PROVIDER, notAdded } from "../../domain/providers.js";
5
+ import { fold } from "../normalize.js";
6
+ import { encodeDocumentMetadata, languageOf } from "./document-metadata.js";
7
+ import { syncFile } from "./files.js";
8
+ import { linkKind } from "./link-kinds.js";
9
+ import { documentOf, folderOf, insertLink, pathParts, requiredThing, thingRef, } from "./notes.js";
10
+ import { oneOf, textOf } from "./text-input.js";
11
+ import { write } from "./transaction.js";
12
+ export const ADDED_KINDS = ["text", "file", "page"];
13
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
14
+ /**
15
+ * The key an added source is stored under, `sha256:<hash>` (a file's bytes; pasted text or a page by its normalized
16
+ * text, or its address when it has none), and every hash a folder or Drive document of the same content may carry.
17
+ */
18
+ export const addedSourceKeyOf = (content) => {
19
+ const kind = oneOf(content.kind, ADDED_KINDS, "an added source's kind");
20
+ if (kind === "file" && !content.bytes)
21
+ throw new CliError("validation_error", "an added file needs its bytes");
22
+ const text = content.text.trim();
23
+ const url = content.url?.trim() || null;
24
+ const normalized = text.normalize("NFC").replace(/\s+/gu, " ").trim();
25
+ if (kind !== "file" && !normalized && !url)
26
+ throw new CliError("validation_error", "an added source without text needs its address");
27
+ const hash = kind === "file" ? sha256(content.bytes) : sha256(normalized || url);
28
+ // Drive keeps the sha256 of the text it exported, as is: pasted text or a page with that text is that file.
29
+ const hashes = [...new Set(kind === "file" || !text ? [hash] : [hash, sha256(content.text)])];
30
+ return { externalId: `sha256:${hash}`, hash, hashes };
31
+ };
32
+ /** The input checked. */
33
+ const checked = (input) => {
34
+ const read = oneOf(input.read, ["extracted", "no-text"], "what was read");
35
+ const text = textOf(input.text, "an added source's text", MAX_TEXT_CHARS, read === "no-text");
36
+ if (read === "no-text" && text)
37
+ throw new CliError("validation_error", "a source read as no-text has no text");
38
+ if (input.kind === "text" && read === "no-text")
39
+ throw new CliError("validation_error", "pasted text cannot be empty");
40
+ const url = input.url == null ? null : textOf(input.url, "an added source's address", 4096);
41
+ if (input.kind === "page" && !url)
42
+ throw new CliError("validation_error", "an added page needs its address");
43
+ const copy = input.keepCopy === undefined ? null : textOf(input.keepCopy.path, "the copy's path", 4096);
44
+ if (copy !== null && input.kind !== "file")
45
+ throw new CliError("validation_error", "only a file is kept as a copy");
46
+ const fileName = input.fileName == null ? null : textOf(input.fileName, "a file's name", 500);
47
+ const title = input.title == null || !input.title.trim() ? null : textOf(input.title, "a title", 500);
48
+ return {
49
+ ...addedSourceKeyOf(input),
50
+ kind: input.kind,
51
+ read,
52
+ text,
53
+ url,
54
+ copy,
55
+ title,
56
+ fileName,
57
+ extension: fileName === null ? null : pathParts(fileName).extension,
58
+ };
59
+ };
60
+ export const addedSourcesOver = (context) => {
61
+ const { database, now } = context;
62
+ const accountRow = () => database.prepare("SELECT * FROM accounts WHERE provider = ? AND external_id = ?").get(ADDED_PROVIDER, ADDED_ACCOUNT);
63
+ const documentAt = (id) => documentOf(database.prepare("SELECT * FROM documents WHERE id = ?").get(id));
64
+ const ownRow = (externalId) => {
65
+ const account = accountRow();
66
+ return account
67
+ ? database
68
+ .prepare("SELECT * FROM documents WHERE account_id = ? AND external_id = ?")
69
+ .get(Number(account.id), externalId)
70
+ : undefined;
71
+ };
72
+ const about = (id, subjects, by) => {
73
+ const at = now();
74
+ for (const subject of subjects) {
75
+ if (by === "owner") {
76
+ const link = insertLink(context, { from: `document:${id}`, to: subject, kind: "about", origin: "owner" });
77
+ // An agent's proposal of the same subject is what the owner now states.
78
+ if (!link.confirmed)
79
+ database
80
+ .prepare("UPDATE links SET confirmed = 1, source = 'owner', author = 'owner', updated_at = ? WHERE id = ?")
81
+ .run(at, Number(link.id));
82
+ continue;
83
+ }
84
+ const thing = requiredThing(database, subject, "a subject");
85
+ const known = database
86
+ .prepare(`SELECT 1 FROM links WHERE from_type = 'document' AND from_id = ? AND to_type = ? AND to_id = ? AND kind = ${linkKind("about")} AND anchor IS NULL`)
87
+ .get(id, thing.type, thing.id);
88
+ const link = insertLink(context, {
89
+ from: `document:${id}`,
90
+ to: subject,
91
+ kind: "about",
92
+ origin: "suggested",
93
+ confirmed: false,
94
+ provenance: by.reason,
95
+ });
96
+ if (!known)
97
+ database
98
+ .prepare("UPDATE links SET author = ?, metadata = ? WHERE id = ?")
99
+ .run(by.bot, JSON.stringify({ provenance: by.reason, ...(by.model ? { model: by.model } : {}) }), Number(link.id));
100
+ }
101
+ return database
102
+ .prepare(`SELECT to_type, to_id FROM links WHERE from_type = 'document' AND from_id = ? AND kind = ${linkKind("about")} ` +
103
+ "AND to_id IS NOT NULL ORDER BY id")
104
+ .all(id)
105
+ .flatMap((row) => thingRef(database, row.to_type, row.to_id) ?? []);
106
+ };
107
+ /** A live folder or Drive document with this content; a document no reader could read matches nothing. */
108
+ const duplicateOf = (hashes) => {
109
+ const row = database
110
+ .prepare("SELECT d.id FROM documents d WHERE d.content_hash IN (SELECT value FROM json_each(?)) AND d.deleted_at IS NULL " +
111
+ `AND d.body <> '' AND ${notAdded} AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1) = 1 ` +
112
+ "ORDER BY d.id LIMIT 1")
113
+ .get(JSON.stringify(hashes));
114
+ return row ? Number(row.id) : undefined;
115
+ };
116
+ /** Its `files` row is named as the owner named the source, not by its hash. */
117
+ const placeFile = (id, at, name) => {
118
+ syncFile(database, at, id);
119
+ database
120
+ .prepare("UPDATE files SET name = ?, path = ?, path_folded = ? WHERE document_id = ? AND kind <> 'folder'")
121
+ .run(name, name, fold(name), id);
122
+ };
123
+ return {
124
+ addedAccount: async () => {
125
+ const row = accountRow();
126
+ return row ? folderOf(row) : undefined;
127
+ },
128
+ findAddedSource: async (content) => {
129
+ const key = addedSourceKeyOf(content);
130
+ const own = ownRow(key.externalId);
131
+ if (own && own.deleted_at == null)
132
+ return { existing: `document:${own.id}`, duplicateOf: null };
133
+ const duplicate = duplicateOf(key.hashes);
134
+ return { existing: null, duplicateOf: duplicate === undefined ? null : `document:${duplicate}` };
135
+ },
136
+ removeAddedSource: async (reference, by) => {
137
+ if (by !== "owner")
138
+ throw new CliError("permission_error", "only the owner removes a source he added", {
139
+ reason: "proposal.owner-only",
140
+ });
141
+ return write(database, () => {
142
+ const id = /^document:\d+$/.test(reference) ? Number(reference.slice("document:".length)) : Number.NaN;
143
+ const row = database
144
+ .prepare("SELECT d.* FROM documents d JOIN accounts a ON a.id = d.account_id WHERE d.id = ? AND a.provider = ? " +
145
+ "AND d.deleted_at IS NULL")
146
+ .get(id, ADDED_PROVIDER);
147
+ if (!row)
148
+ throw new CliError("not_found", `no live added source ${reference} in the local store`);
149
+ const at = now();
150
+ database
151
+ .prepare("UPDATE files SET deleted_at = ?, updated_at = ? WHERE document_id = ? AND deleted_at IS NULL")
152
+ .run(at, at, id);
153
+ database.prepare("UPDATE documents SET deleted_at = ?, body = '' WHERE id = ?").run(at, id);
154
+ return {
155
+ ref: `document:${id}`,
156
+ removed: true,
157
+ copy: row.storage === "copy" ? String(row.local_path) : null,
158
+ };
159
+ });
160
+ },
161
+ saveAddedSource: async (input) => {
162
+ const source = checked(input);
163
+ const metadata = encodeDocumentMetadata(input.metadata, input.sections);
164
+ const subjects = input.subjects ?? [];
165
+ return write(database, () => {
166
+ const at = now();
167
+ const own = ownRow(source.externalId);
168
+ if (own !== undefined && own.deleted_at == null) {
169
+ const id = Number(own.id);
170
+ if (source.copy !== null && own.storage !== "copy")
171
+ database
172
+ .prepare("UPDATE documents SET storage = 'copy', local_path = ?, updated_at = ? WHERE id = ?")
173
+ .run(source.copy, at, id);
174
+ const kept = source.copy !== null || own.storage === "copy" ? "copy" : "text";
175
+ return {
176
+ note: documentAt(id),
177
+ created: false,
178
+ duplicateOf: null,
179
+ kept,
180
+ subjects: about(id, subjects, input.by),
181
+ };
182
+ }
183
+ const duplicate = duplicateOf(source.hashes);
184
+ if (duplicate !== undefined) {
185
+ const linked = about(duplicate, subjects, input.by);
186
+ const note = documentAt(duplicate);
187
+ return { note, created: false, duplicateOf: note.ref, kept: null, subjects: linked };
188
+ }
189
+ const values = [
190
+ source.kind,
191
+ source.title,
192
+ source.fileName,
193
+ source.extension,
194
+ source.url,
195
+ source.copy === null ? "text" : "copy",
196
+ source.copy,
197
+ input.mime ?? null,
198
+ input.size ?? input.bytes?.byteLength ?? null,
199
+ source.hash,
200
+ source.text,
201
+ source.read === "extracted" ? "text" : "none",
202
+ metadata,
203
+ languageOf(input.metadata),
204
+ ];
205
+ let id;
206
+ if (own) {
207
+ id = Number(own.id);
208
+ database
209
+ .prepare("UPDATE documents SET kind = ?, title = ?, file_name = ?, extension = ?, url = ?, storage = ?, local_path = ?, " +
210
+ "mime = ?, size = ?, content_hash = ?, body = ?, extraction = ?, metadata = ?, language = ?, " +
211
+ "updated_at = ?, deleted_at = NULL WHERE id = ?")
212
+ .run(...values, at, id);
213
+ }
214
+ else {
215
+ const holder = accountRow()?.id ??
216
+ database
217
+ .prepare("INSERT INTO accounts (provider, external_id, name, settings, created_at, updated_at) " +
218
+ "VALUES (?, ?, NULL, ?, ?, ?) RETURNING id")
219
+ .get(ADDED_PROVIDER, ADDED_ACCOUNT, JSON.stringify({ format: "markdown" }), at, at)?.id;
220
+ id = Number(database
221
+ .prepare("INSERT INTO documents (account_id, external_id, kind, title, file_name, extension, url, storage, local_path, " +
222
+ "mime, size, content_hash, body, extraction, metadata, language, revision, created_at, updated_at) " +
223
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
224
+ .get(Number(holder), source.externalId, ...values, at, at)?.id);
225
+ }
226
+ placeFile(id, at, source.fileName ?? source.title ?? source.externalId);
227
+ return {
228
+ note: documentAt(id),
229
+ created: !own,
230
+ duplicateOf: null,
231
+ kept: source.copy === null ? "text" : "copy",
232
+ subjects: about(id, subjects, input.by),
233
+ };
234
+ });
235
+ },
236
+ };
237
+ };
@@ -0,0 +1,90 @@
1
+ import { type ContractKind, type ContractStatus, type Interval } from "../../domain/business.js";
2
+ import { type FinanceReview } from "../../domain/finance.js";
3
+ import type { Decider } from "../decisions.js";
4
+ import { type ProposedByFilter } from "./actors.js";
5
+ import { type Author } from "./memories.js";
6
+ import type { StoreContext } from "./open.js";
7
+ import { type Reviewed, type Written } from "./reviewed.js";
8
+ export interface Contract extends Reviewed {
9
+ id: string;
10
+ ref: string;
11
+ /** One line, as a list or the review inbox prints it. */
12
+ title: string;
13
+ name: string;
14
+ number: string | null;
15
+ kind: ContractKind;
16
+ status: ContractStatus;
17
+ /** `YYYY-MM-DD`. */
18
+ signedDate: string | null;
19
+ effectiveDate: string | null;
20
+ /** `null` when it runs until ended. */
21
+ expirationDate: string | null;
22
+ autoRenew: boolean;
23
+ /** What one renewal adds, such as 1-year. */
24
+ renewal: Interval | null;
25
+ noticeDays: number | null;
26
+ /** The last day to give notice: the expiration date less the notice days; computed, never stored. */
27
+ noticeDeadline: string | null;
28
+ terms: string | null;
29
+ /** Both `null` when it carries no value. */
30
+ value: string | null;
31
+ currency: string | null;
32
+ deal: string | null;
33
+ }
34
+ export interface ContractFields {
35
+ name?: string;
36
+ number?: string;
37
+ kind?: ContractKind;
38
+ /** `active` when left out. */
39
+ status?: ContractStatus;
40
+ signedDate?: string;
41
+ effectiveDate?: string;
42
+ expirationDate?: string;
43
+ autoRenew?: boolean;
44
+ /** A count and a unit, such as 1-year. */
45
+ renewal?: string;
46
+ noticeDays?: number;
47
+ terms?: string;
48
+ /** A decimal string in `currency`; give both or neither. */
49
+ value?: string;
50
+ currency?: string;
51
+ deal?: string;
52
+ }
53
+ export interface ContractInput extends Written, ContractFields {
54
+ name: string;
55
+ kind: ContractKind;
56
+ }
57
+ export interface ContractUpdate extends ContractFields {
58
+ by: Author;
59
+ }
60
+ export interface ContractFilter {
61
+ status?: ContractStatus;
62
+ kind?: ContractKind;
63
+ project?: string;
64
+ review?: FinanceReview;
65
+ proposedBy?: ProposedByFilter;
66
+ /** `YYYY-MM-DD`: only those that expire on or before it. */
67
+ expiresBy?: string;
68
+ /** 1–500, 100 by default; newest written first. */
69
+ limit?: number;
70
+ }
71
+ /**
72
+ * The contracts the owner works under. One without a value is written confirmed by anyone, as it feeds no total: its
73
+ * `confirmedBy` stays `null` and `author` says who wrote it. With a value an agent's waits as proposed. A confirmed
74
+ * contract is the owner's to change.
75
+ */
76
+ export interface ContractsStore {
77
+ add(input: ContractInput): Promise<Contract>;
78
+ get(reference: string): Promise<Contract>;
79
+ list(filter?: ContractFilter): Promise<Contract[]>;
80
+ /** The owner changes any; a bot only one it proposed that is still proposed. */
81
+ update(reference: string, input: ContractUpdate): Promise<Contract>;
82
+ confirm(reference: string, by: Decider, reason?: string): Promise<Contract>;
83
+ reject(reference: string, by: Decider, reason?: string): Promise<Contract>;
84
+ }
85
+ type ContractOperations = {
86
+ [K in keyof ContractsStore]: ContractsStore[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => R : never;
87
+ };
88
+ export declare const contractOperationsOver: (context: StoreContext) => ContractOperations;
89
+ export declare const contractsStoreOver: (context: StoreContext) => ContractsStore;
90
+ export {};
@@ -0,0 +1,182 @@
1
+ import { CONTRACT_KINDS, CONTRACT_STATUSES, contractLine, intervalOf, } from "../../domain/business.js";
2
+ import { FINANCE_REVIEWS } from "../../domain/finance.js";
3
+ import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
4
+ import { proposedBySql } from "./actors.js";
5
+ import { projectId } from "./memories.js";
6
+ import { requiredThing } from "./notes.js";
7
+ import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
8
+ import { write } from "./transaction.js";
9
+ const CONTRACTS = "SELECT k.*, b.name AS author_name, b.kind AS author_kind FROM contracts k " +
10
+ "LEFT JOIN bots b ON k.author_type = 'bot' AND b.id = k.author_id";
11
+ const DAY_MS = 86_400_000;
12
+ const deadlineOf = (expiration, days) => expiration === null || days === null
13
+ ? null
14
+ : new Date(Date.parse(`${expiration}T00:00:00Z`) - days * DAY_MS).toISOString().slice(0, 10);
15
+ /** The columns a contract's fields set, checked; a field left out keeps `base`'s value. */
16
+ const columnsOf = (fields, base) => {
17
+ const kept = (given, column, read) => given === undefined ? (base[column] ?? null) : read(given);
18
+ const name = kept(fields.name, "name", (value) => text(value, "a contract's name", 200));
19
+ if (name == null)
20
+ refuse("a contract needs a name", "contract.field");
21
+ const renewal = fields.renewal !== undefined
22
+ ? intervalOf(fields.renewal, "contract.field")
23
+ : base.renewal_count == null
24
+ ? null
25
+ : { count: Number(base.renewal_count), unit: base.renewal_unit };
26
+ const noticeDays = kept(fields.noticeDays, "notice_days", (value) => {
27
+ if (!Number.isSafeInteger(value) || value < 0 || value > 3650)
28
+ refuse("a contract's notice is 0–3650 days", "contract.field");
29
+ return value;
30
+ });
31
+ const dates = {
32
+ signed_date: kept(fields.signedDate, "signed_date", (value) => isoDate(value, "a contract's signing date")),
33
+ effective_date: kept(fields.effectiveDate, "effective_date", (value) => isoDate(value, "a contract's start date")),
34
+ expiration_date: kept(fields.expirationDate, "expiration_date", (value) => isoDate(value, "a contract's end date")),
35
+ };
36
+ if (dates.effective_date != null &&
37
+ dates.expiration_date != null &&
38
+ String(dates.effective_date) > String(dates.expiration_date))
39
+ refuse("a contract ends on or after the day it starts", "contract.field");
40
+ const valued = fields.value !== undefined || fields.currency !== undefined;
41
+ if (valued && (fields.value === undefined) !== (fields.currency === undefined))
42
+ refuse("a contract's value and currency come together", "contract.field");
43
+ const currency = valued ? currencyOf(fields.currency) : (base.currency ?? null);
44
+ const value = valued
45
+ ? minorUnits(fields.value, currency, "a contract's value")
46
+ : (base.value ?? null);
47
+ return {
48
+ name: name,
49
+ number: kept(fields.number, "number", (value) => text(value, "a contract's number", 80)),
50
+ kind: kept(fields.kind, "kind", (value) => oneOf(value, CONTRACT_KINDS, "a contract's kind")),
51
+ status: kept(fields.status, "status", (value) => oneOf(value, CONTRACT_STATUSES, "a contract's status")),
52
+ ...dates,
53
+ auto_renew: kept(fields.autoRenew, "auto_renew", (value) => {
54
+ if (typeof value !== "boolean")
55
+ refuse("a contract's renewal is on or off", "contract.field");
56
+ return value ? 1 : 0;
57
+ }),
58
+ renewal_count: renewal?.count ?? null,
59
+ renewal_unit: renewal?.unit ?? null,
60
+ notice_days: noticeDays,
61
+ terms: kept(fields.terms, "terms", (value) => text(value, "a contract's terms", 20_000)),
62
+ value,
63
+ currency,
64
+ };
65
+ };
66
+ export const contractOperationsOver = (context) => {
67
+ const { database, now } = context;
68
+ const { reviewedOf, written, keepEvidence, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
69
+ const contractOf = (row) => {
70
+ const currency = row.currency == null ? null : String(row.currency);
71
+ const value = row.value == null || currency === null ? null : Number(row.value);
72
+ const expirationDate = row.expiration_date == null ? null : String(row.expiration_date);
73
+ const noticeDays = row.notice_days == null ? null : Number(row.notice_days);
74
+ const fields = {
75
+ id: Number(row.id),
76
+ name: String(row.name),
77
+ number: row.number == null ? null : String(row.number),
78
+ value,
79
+ currency,
80
+ status: row.status,
81
+ review: row.review,
82
+ };
83
+ return {
84
+ id: String(row.id),
85
+ ref: `contract:${row.id}`,
86
+ title: `Contract ${contractLine(fields)}`,
87
+ name: fields.name,
88
+ number: fields.number,
89
+ kind: row.kind,
90
+ status: fields.status,
91
+ signedDate: row.signed_date == null ? null : String(row.signed_date),
92
+ effectiveDate: row.effective_date == null ? null : String(row.effective_date),
93
+ expirationDate,
94
+ autoRenew: row.auto_renew === 1,
95
+ renewal: row.renewal_count == null ? null : { count: Number(row.renewal_count), unit: row.renewal_unit },
96
+ noticeDays,
97
+ noticeDeadline: deadlineOf(expirationDate, noticeDays),
98
+ terms: row.terms == null ? null : String(row.terms),
99
+ value: value === null || currency === null ? null : formatDecimal(value, scaleOf(currency)),
100
+ currency,
101
+ deal: row.deal_id == null ? null : `deal:${row.deal_id}`,
102
+ ...reviewedOf(row, "contract"),
103
+ };
104
+ };
105
+ const rowOf = (reference) => {
106
+ const thing = requiredThing(database, reference.includes(":") ? reference : `contract:${reference}`, "the contract");
107
+ if (thing.type !== "contract")
108
+ return refuse(`${reference} is not a contract`, "contract.ref");
109
+ return database.prepare(`${CONTRACTS} WHERE k.id = ?`).get(thing.id);
110
+ };
111
+ const decide = (reference, by, reason, confirm) => {
112
+ const row = rowOf(reference);
113
+ decideRow("contract", row, { by, reason, confirm });
114
+ return contractOf(rowOf(`contract:${row.id}`));
115
+ };
116
+ return {
117
+ add: (input) => {
118
+ const columns = columnsOf({ ...input, status: input.status ?? "active", autoRenew: input.autoRenew ?? false }, {});
119
+ const id = write(database, () => {
120
+ const deal = linkedId(input.deal, "deal", "contract.ref");
121
+ const by = written(input);
122
+ // Without a value a contract feeds no total, so an agent's needs no decision.
123
+ const direct = !by.owner && columns.value === null;
124
+ const at = now();
125
+ const made = Number(database
126
+ .prepare("INSERT INTO contracts (name, number, kind, status, signed_date, effective_date, expiration_date, auto_renew, " +
127
+ "renewal_count, renewal_unit, notice_days, terms, value, currency, project_id, deal_id, review, author_type, " +
128
+ "author_id, model, confirmed_by_type, confirmed_by_id, source, metadata, created_at, updated_at) " +
129
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id")
130
+ .get(columns.name, columns.number, columns.kind, columns.status, columns.signed_date, columns.effective_date, columns.expiration_date, columns.auto_renew, columns.renewal_count, columns.renewal_unit, columns.notice_days, columns.terms, columns.value, columns.currency, by.project, deal, direct ? "confirmed" : by.review, by.actor.type, by.actor.id, by.model, by.confirmedType, by.confirmedId, by.source, by.metadata, at, at)?.id);
131
+ keepEvidence("contract", made, by);
132
+ return made;
133
+ });
134
+ return contractOf(rowOf(`contract:${id}`));
135
+ },
136
+ get: (reference) => contractOf(rowOf(reference)),
137
+ list: (filter = {}) => {
138
+ const project = filter.project === undefined ? null : projectId(database, filter.project);
139
+ const status = filter.status === undefined ? null : oneOf(filter.status, CONTRACT_STATUSES, "a status");
140
+ const kind = filter.kind === undefined ? null : oneOf(filter.kind, CONTRACT_KINDS, "a kind");
141
+ const review = filter.review === undefined ? null : oneOf(filter.review, FINANCE_REVIEWS, "a review");
142
+ const expires = isoDate(filter.expiresBy, "the last expiration day");
143
+ const by = proposedBySql("k.author_type", "k.author_id", filter.proposedBy);
144
+ return database
145
+ .prepare(`${CONTRACTS} WHERE k.deleted_at IS NULL AND (? IS NULL OR k.status = ?) AND (? IS NULL OR k.kind = ?) ` +
146
+ "AND (? IS NULL OR k.review = ?) AND (? IS NULL OR k.project_id = ?) " +
147
+ `AND (? IS NULL OR k.expiration_date <= ?) AND ${by.sql} ORDER BY k.created_at DESC, k.id DESC LIMIT ?`)
148
+ .all(status, status, kind, kind, review, review, project, project, expires, expires, ...by.params, limitOf(filter.limit))
149
+ .map((row) => contractOf(row));
150
+ },
151
+ update: (reference, { by, ...fields }) => {
152
+ const row = rowOf(reference);
153
+ const ref = `contract:${row.id}`;
154
+ if (row.review === "rejected" || row.deleted_at != null)
155
+ refuse(`${ref} is ${row.deleted_at != null ? "deleted" : "rejected"}`, "contract.ref");
156
+ mayChangeParts(row, by, `only the owner changes ${ref}; a bot changes only a contract it proposed that is still proposed`);
157
+ const columns = columnsOf(fields, row);
158
+ write(database, () => {
159
+ const deal = fields.deal === undefined ? row.deal_id : linkedId(fields.deal, "deal", "contract.ref");
160
+ database
161
+ .prepare("UPDATE contracts SET name = ?, number = ?, kind = ?, status = ?, signed_date = ?, effective_date = ?, " +
162
+ "expiration_date = ?, auto_renew = ?, renewal_count = ?, renewal_unit = ?, notice_days = ?, terms = ?, " +
163
+ "value = ?, currency = ?, deal_id = ?, updated_at = ? WHERE id = ?")
164
+ .run(columns.name, columns.number, columns.kind, columns.status, columns.signed_date, columns.effective_date, columns.expiration_date, columns.auto_renew, columns.renewal_count, columns.renewal_unit, columns.notice_days, columns.terms, columns.value, columns.currency, deal, now(), Number(row.id));
165
+ });
166
+ return contractOf(rowOf(ref));
167
+ },
168
+ confirm: (reference, by, reason) => decide(reference, by, reason, true),
169
+ reject: (reference, by, reason) => decide(reference, by, reason, false),
170
+ };
171
+ };
172
+ export const contractsStoreOver = (context) => {
173
+ const operations = contractOperationsOver(context);
174
+ return {
175
+ add: async (input) => operations.add(input),
176
+ get: async (reference) => operations.get(reference),
177
+ list: async (filter) => operations.list(filter),
178
+ update: async (reference, input) => operations.update(reference, input),
179
+ confirm: async (reference, by, reason) => operations.confirm(reference, by, reason),
180
+ reject: async (reference, by, reason) => operations.reject(reference, by, reason),
181
+ };
182
+ };