@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,9 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { eventOf } from "./events.js";
3
+ import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
3
4
  const DAY = 86_400_000;
5
+ const COUNTERPART_LINK = "EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'event' AND l.from_id = e.id AND l.to_type = 'person' " +
6
+ `AND l.to_id = ? AND l.kind = ${linkKind("related-to")} AND l.role = '${COUNTERPART_ROLE}')`;
4
7
  const accountsOf = (filter) => {
5
8
  if (filter.accountIds !== undefined && filter.accountId !== undefined)
6
9
  throw new CliError("validation_error", "an event filter takes accountId or accountIds, not both");
@@ -73,9 +76,10 @@ export const listEvents = (database, filter) => {
73
76
  if (filter.notEventTypes?.length)
74
77
  clauses.push(`NOT ${ofKind(filter.notEventTypes)}`);
75
78
  if (filter.personId !== undefined) {
76
- clauses.push(entries("EXISTS (SELECT 1 FROM calendar_entry_participants p JOIN identity_links il ON il.identity_id = p.identity_id " +
77
- "WHERE p.entry_id = ce.id AND il.person_id = ?)"));
78
- params.push(filter.personId);
79
+ // A phone call's other side is a number, which a participant (an address) cannot hold: the import links the person.
80
+ clauses.push(`(${entries("EXISTS (SELECT 1 FROM calendar_entry_participants p JOIN identity_links il ON il.identity_id = p.identity_id " +
81
+ "WHERE p.entry_id = ce.id AND il.person_id = ?)")} OR ${COUNTERPART_LINK})`);
82
+ params.push(filter.personId, filter.personId);
79
83
  }
80
84
  const account = (alias) => (accounts === undefined ? "" : ` AND ${inAccounts(`${alias}.account_id`)}`);
81
85
  if (filter.changedSince !== undefined) {
@@ -1,4 +1,5 @@
1
1
  import { dropOrphanPeople, unreferenced } from "./accounts.js";
2
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
2
3
  import { dropUnusedVectors } from "./vector-index.js";
3
4
  const distinctIds = (rows) => [...new Set(rows.map((row) => Number(row.id)))];
4
5
  /**
@@ -46,6 +47,7 @@ export const forgetCalendarRows = (database, { calendarId, accountId, cursorKey,
46
47
  database
47
48
  .prepare("UPDATE meetings SET event_id = NULL, updated_at = ? WHERE event_id IN (SELECT value FROM json_each(?))")
48
49
  .run(now, gone(goneEvents));
50
+ forgetEvidenceTo(database, "event", { sql: "SELECT value FROM json_each(?)", params: [gone(goneEvents)] }, now);
49
51
  dropAround("event", goneEvents);
50
52
  database.prepare("DELETE FROM events WHERE id IN (SELECT value FROM json_each(?))").run(gone(goneEvents));
51
53
  for (const table of ["meeting_series", "events"])
@@ -63,6 +65,7 @@ export const forgetCalendarRows = (database, { calendarId, accountId, cursorKey,
63
65
  database.prepare("DELETE FROM sync_cursors WHERE account_id = ? AND key = ?").run(accountId, cursorKey);
64
66
  database.prepare("DELETE FROM calendars WHERE id = ?").run(calendarId);
65
67
  dropOrphanPeople(database, unseenBefore);
68
+ forgetDanglingEvidence(database, now);
66
69
  dropUnusedVectors(database, hashes);
67
70
  return { entries: entryIds.length, events: goneEvents.length };
68
71
  };
@@ -1,3 +1,23 @@
1
- import { type EventStore } from "../../meetings/index.js";
1
+ import { type CalendarInput, type EntryInput, type EventStore, type StoredCalendar, type StoredEntry } from "../../meetings/index.js";
2
2
  import type { StoreContext } from "./open.js";
3
+ type Row = Record<string, unknown>;
4
+ /** The entry writes behind the calendar store, run inside the caller's transaction: the records import shares them. */
5
+ export declare const calendarWritesOver: (context: StoreContext) => {
6
+ entryRow: (id: number) => Row;
7
+ saveCalendar: (accountId: number, one: CalendarInput, now: number) => StoredCalendar;
8
+ calendarRow: (id: number) => Record<string, unknown>;
9
+ setEntity: (entry: StoredEntry, to: number, method: string, author: string, now: number) => void;
10
+ newEntity: (entry: StoredEntry, now: number) => number;
11
+ refreshEvent: (eventId: number, now: number) => void;
12
+ refreshSeries: (seriesId: number, now: number) => void;
13
+ refreshAround: (entryIds: number[], now: number) => void;
14
+ saveAll: (calendarId: number, entries: EntryInput[], now: number) => StoredEntry[];
15
+ removeAll: (calendarId: number, externalIds: string[], now: number) => number;
16
+ putCursor: (calendarId: number, value: string | null, now: number) => void;
17
+ slotRows: (calendarId: number, series: string, window: {
18
+ from: number;
19
+ to: number;
20
+ }) => Record<string, unknown>[];
21
+ };
3
22
  export declare const eventStoreOver: (context: StoreContext) => EventStore;
23
+ export {};
@@ -136,7 +136,8 @@ const spanOf = (entry) => {
136
136
  const start = entry.startsAt ?? 0;
137
137
  return { start, end: Math.max(entry.endsAt ?? start, start + 1) };
138
138
  };
139
- export const eventStoreOver = (context) => {
139
+ /** The entry writes behind the calendar store, run inside the caller's transaction: the records import shares them. */
140
+ export const calendarWritesOver = (context) => {
140
141
  const { database } = context;
141
142
  const entryRow = (id) => database.prepare("SELECT * FROM calendar_entries WHERE id = ?").get(id);
142
143
  const calendarRow = (id) => {
@@ -505,16 +506,35 @@ export const eventStoreOver = (context) => {
505
506
  .prepare(`SELECT * FROM calendar_entries WHERE calendar_id = ? AND kind = 'occurrence' AND series_external_id = ?
506
507
  AND original_starts_at >= ? AND original_starts_at < ? AND deleted_at IS NULL ORDER BY original_starts_at`)
507
508
  .all(calendarId, series, window.from, window.to);
508
- return {
509
- saveCalendars: async (accountId, calendars, now) => write(database, () => {
510
- const upsert = database.prepare(`INSERT INTO calendars (account_id, external_id, title, timezone, access_role, primary_calendar, synced, seen_at,
509
+ /** One calendar as a provider lists it; one the owner forgot comes back, as a list naming it again does. */
510
+ const saveCalendar = (accountId, one, now) => calendarOf(database
511
+ .prepare(`INSERT INTO calendars (account_id, external_id, title, timezone, access_role, primary_calendar, synced, seen_at,
511
512
  created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
512
513
  ON CONFLICT (account_id, external_id) DO UPDATE SET title = excluded.title, timezone = excluded.timezone,
513
514
  access_role = excluded.access_role, primary_calendar = excluded.primary_calendar, seen_at = excluded.seen_at,
514
515
  deleted_at = NULL, updated_at = excluded.updated_at
515
- RETURNING *`);
516
- return calendars.map((one) => calendarOf(upsert.get(accountId, one.externalId, one.title, one.timezone, one.accessRole, flag(one.primary), flag(one.syncByDefault), now, now, now)));
517
- }),
516
+ RETURNING *`)
517
+ .get(accountId, one.externalId, one.title, one.timezone, one.accessRole, flag(one.primary), flag(one.syncByDefault), now, now, now));
518
+ return {
519
+ entryRow,
520
+ saveCalendar,
521
+ calendarRow,
522
+ setEntity,
523
+ newEntity,
524
+ refreshEvent,
525
+ refreshSeries,
526
+ refreshAround,
527
+ saveAll,
528
+ removeAll,
529
+ putCursor,
530
+ slotRows,
531
+ };
532
+ };
533
+ export const eventStoreOver = (context) => {
534
+ const { database } = context;
535
+ const { entryRow, calendarRow, setEntity, newEntity, refreshEvent, refreshSeries, refreshAround, saveAll, removeAll, putCursor, slotRows, saveCalendar, } = calendarWritesOver(context);
536
+ return {
537
+ saveCalendars: async (accountId, calendars, now) => write(database, () => calendars.map((one) => saveCalendar(accountId, one, now))),
518
538
  calendars: async (accountId) => database
519
539
  .prepare("SELECT * FROM calendars WHERE account_id = ? ORDER BY primary_calendar DESC, title, id")
520
540
  .all(accountId)
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { formatLocator } from "../../domain/locator.js";
3
3
  import { purgeChats, revisedBy, stricterPrivacy } from "./chats.js";
4
4
  import { pointerPairs } from "./entity-types.js";
5
+ import { evidenceSignature, resignEvidence, storedEvidenceMetadata } from "./evidence-signature.js";
5
6
  import { tombstone, writeDerivedReactions } from "./messages.js";
6
7
  import { targetKey } from "./notes.js";
7
8
  import { write } from "./transaction.js";
@@ -20,11 +21,17 @@ const pointerMover = (context, type) => {
20
21
  context.database.prepare(`DELETE FROM ${table} ${where}`),
21
22
  ];
22
23
  });
24
+ const cited = context.database.prepare("SELECT id, metadata FROM links WHERE kind = 'evidence' AND to_type = ? AND to_id = ?");
23
25
  return (from, to) => {
26
+ const evidence = cited.all(type, from);
24
27
  for (const [move, drop] of statements) {
25
28
  move.run(to, from);
26
29
  drop.run(from);
27
30
  }
31
+ // The kept row is the same source under another id; signed as it is, the next check sees no change.
32
+ const signature = evidenceSignature(context.database, { type, id: to });
33
+ for (const link of evidence)
34
+ resignEvidence(context.database, Number(link.id), signature, context.now(), storedEvidenceMetadata(link.metadata));
28
35
  };
29
36
  };
30
37
  const renameText = (context, key, accountKey, from, to) => {
@@ -37,6 +37,8 @@ export declare const stricterPrivacy: ({ database }: StoreContext, accountKey: n
37
37
  */
38
38
  export declare const answeredChatPk: (context: StoreContext, accountKey: number, chatId: Id, typed: Id) => number;
39
39
  export declare const upsertChat: (context: StoreContext, accountKey: number, chat: ChatUpdate) => void;
40
+ /** Moves a chat's newest-message time forward only: messages imported out of order never move it back. */
41
+ export declare const raiseLastMessageAt: ({ orm }: StoreContext, chatKey: number, at: number) => void;
40
42
  /** Replaces who is in the chat, whole. */
41
43
  export declare const writeMembers: (context: StoreContext, key: AccountKey, accountKey: number, chatId: Id, memberIds: Id[]) => void;
42
44
  export declare const members: ({ orm }: StoreContext, chatKey: number) => Member[];
@@ -60,7 +62,7 @@ export declare const leftChats: ({ orm }: StoreContext, accountKey: number) => {
60
62
  messages: number;
61
63
  };
62
64
  /** These chats and everything under them, children before parents: the foreign keys are enforced. */
63
- export declare const purgeChats: ({ orm, database }: StoreContext, pks: number[]) => void;
65
+ export declare const purgeChats: ({ orm, database, now }: StoreContext, pks: number[]) => void;
64
66
  export declare const chatsWith: ({ orm, now }: StoreContext, accountKey: number, key: AccountKey, memberId: Id) => Chat[];
65
67
  /**
66
68
  * How the store answers a chat list's query. `title:` goes through the trigram index, so it matches part of a
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { and, eq, inArray, or, sql } from "./drizzle/core.js";
3
+ import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
3
4
  import { folded } from "./folded.js";
4
5
  import { withoutHistory } from "./history-skips.js";
5
6
  import { identityPk } from "./identities.js";
@@ -174,6 +175,14 @@ export const upsertChat = (context, accountKey, chat) => {
174
175
  })
175
176
  .run();
176
177
  };
178
+ /** Moves a chat's newest-message time forward only: messages imported out of order never move it back. */
179
+ export const raiseLastMessageAt = ({ orm }, chatKey, at) => {
180
+ orm
181
+ .update(chats)
182
+ .set({ lastMessageAt: sql `max(coalesce(${chats.lastMessageAt}, 0), ${at})` })
183
+ .where(eq(chats.id, chatKey))
184
+ .run();
185
+ };
177
186
  const bit = (value) => (value === undefined ? null : value ? 1 : 0);
178
187
  /**
179
188
  * The count is taken as of the chat's newest message where the update names it, else as of now: a message the store
@@ -277,9 +286,13 @@ export const leftChats = ({ orm }, accountKey) => {
277
286
  return { pks, chats: left, messages: left.reduce((sum, chat) => sum + chat.messages, 0) };
278
287
  };
279
288
  /** These chats and everything under them, children before parents: the foreign keys are enforced. */
280
- export const purgeChats = ({ orm, database }, pks) => {
289
+ export const purgeChats = ({ orm, database, now }, pks) => {
281
290
  if (pks.length === 0)
282
291
  return;
292
+ const at = now();
293
+ const chatIds = { sql: "SELECT value FROM json_each(?)", params: [JSON.stringify(pks)] };
294
+ forgetEvidenceTo(database, "message", { ...chatIds, sql: `SELECT id FROM messages WHERE chat_id IN (${chatIds.sql})` }, at);
295
+ forgetEvidenceTo(database, "chat", chatIds, at);
283
296
  const messagesOf = orm.select({ pk: messages.id }).from(messages).where(inArray(messages.chatId, pks));
284
297
  const chatPks = sql `(SELECT value FROM json_each(${JSON.stringify(pks)}))`;
285
298
  const released = orm
@@ -319,6 +332,7 @@ export const purgeChats = ({ orm, database }, pks) => {
319
332
  orm.delete(messageRevisions).where(inArray(messageRevisions.messageId, messagesOf)).run();
320
333
  orm.delete(messages).where(inArray(messages.chatId, pks)).run();
321
334
  orm.delete(chats).where(inArray(chats.id, pks)).run();
335
+ forgetDanglingEvidence(database, at);
322
336
  dropUnusedVectors(database, released.map(({ hash }) => hash));
323
337
  };
324
338
  export const chatsWith = ({ orm, now }, accountKey, key, memberId) => {
@@ -0,0 +1,44 @@
1
+ import type { CrmItem, CrmPipeline } from "../../domain/crm.js";
2
+ import { type DealKind } from "../../domain/deals.js";
3
+ import type { AccountKey } from "../types.js";
4
+ import type { StoreContext } from "./open.js";
5
+ /** What the store could not keep, and why: an item whose stage is not stored or whose field it refuses, or a pipeline. */
6
+ export interface CrmSkipped {
7
+ externalId: string;
8
+ reason: "crm.stage-unknown" | "crm.item-invalid";
9
+ message: string;
10
+ }
11
+ export declare const TABLES: {
12
+ readonly deal: "deals";
13
+ readonly lead: "leads";
14
+ };
15
+ /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
16
+ export declare const SOURCE = "crm";
17
+ /**
18
+ * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
19
+ * `contact:` references percent-encode it, so the `/` stays one part.
20
+ */
21
+ export declare const crmIdentityId: (key: AccountKey, externalId: string, type?: "contact" | "user") => string;
22
+ /** What every contact identity of the account starts with. */
23
+ export declare const crmAccountPrefix: (key: AccountKey) => string;
24
+ export declare const day: (value: unknown, what: string) => string | null;
25
+ export declare const epoch: (value: unknown, fallback: number) => number;
26
+ export declare const textOf: (value: unknown, most: number) => string | null;
27
+ /** What another writer than CRM sync resolved for an item: given ids win over the CRM's own lookups by external id. */
28
+ export interface ItemWriter {
29
+ organization?: number | null;
30
+ deal?: number | null;
31
+ project?: number | null;
32
+ author?: {
33
+ type: string;
34
+ id: number;
35
+ };
36
+ source?: string;
37
+ }
38
+ /** The single-row writes CRM sync and the records envelope share, so both land on one `(account, external id)` row. */
39
+ export declare const crmRowsOver: (context: StoreContext) => {
40
+ savePipeline: (accountId: number, kind: DealKind, pipeline: CrmPipeline, at: number) => number;
41
+ saveItemRow: (key: AccountKey, accountId: number, kind: DealKind, item: CrmItem, at: number, writer?: ItemWriter) => CrmSkipped | {
42
+ id: number;
43
+ };
44
+ };
@@ -0,0 +1,195 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { STAGE_OUTCOMES } from "../../domain/deals.js";
3
+ import { currencyOf, minorUnits } from "../../domain/money.js";
4
+ import { fold } from "../normalize.js";
5
+ import { authorActor } from "./memories.js";
6
+ export const TABLES = { deal: "deals", lead: "leads" };
7
+ /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
8
+ export const SOURCE = "crm";
9
+ /**
10
+ * A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
11
+ * `contact:` references percent-encode it, so the `/` stays one part.
12
+ */
13
+ export const crmIdentityId = (key, externalId, type = "contact") => `${idPart(key.account)}/${type}/${idPart(externalId)}`;
14
+ /**
15
+ * A `/` inside an account or an id would let `a` + `b/contact/c` and `a/contact/b` + `c` name one contact, so it is
16
+ * escaped, with the `%` that escapes it; an id with neither, every CRM's so far, is written as before.
17
+ */
18
+ const idPart = (value) => value.replaceAll("%", "%25").replaceAll("/", "%2F");
19
+ /** What every contact identity of the account starts with. */
20
+ export const crmAccountPrefix = (key) => `${idPart(key.account)}/`;
21
+ export const day = (value, what) => {
22
+ if (value === undefined || value === null || value === "")
23
+ return null;
24
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(value)))
25
+ throw new CliError("validation_error", `${what} is YYYY-MM-DD, not ${JSON.stringify(value)}`);
26
+ return value;
27
+ };
28
+ export const epoch = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
29
+ export const textOf = (value, most) => {
30
+ if (typeof value !== "string")
31
+ return null;
32
+ const kept = value.trim().slice(0, most);
33
+ return kept || null;
34
+ };
35
+ /** The single-row writes CRM sync and the records envelope share, so both land on one `(account, external id)` row. */
36
+ export const crmRowsOver = (context) => {
37
+ const { database } = context;
38
+ const author = (key) => authorActor(context, { bot: key.provider, kind: "rule" }).actor;
39
+ const pipelineOf = (accountId, kind, externalId) => database
40
+ .prepare("SELECT * FROM pipelines WHERE account_id = ? AND kind = ? AND external_id = ?")
41
+ .get(accountId, kind, externalId);
42
+ /** One pipeline and its stages, by the source's ids; the rest of the account's pipelines stay as they are. */
43
+ const savePipeline = (accountId, kind, pipeline, at) => {
44
+ const name = textOf(pipeline.name, 80) ?? pipeline.externalId;
45
+ const held = pipelineOf(accountId, kind, pipeline.externalId);
46
+ const id = held
47
+ ? Number(held.id)
48
+ : Number(database
49
+ .prepare("INSERT INTO pipelines (account_id, external_id, kind, name, name_folded, created_at, updated_at) " +
50
+ "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id")
51
+ .get(accountId, pipeline.externalId, kind, name, fold(name), at, at)?.id);
52
+ if (held && (held.name !== name || held.deleted_at != null))
53
+ database
54
+ .prepare("UPDATE pipelines SET name = ?, name_folded = ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
55
+ .run(name, fold(name), at, id);
56
+ saveStages(id, pipeline, at);
57
+ saveStages(id, pipeline, at);
58
+ return id;
59
+ };
60
+ /**
61
+ * Stage names are unique in a pipeline, but a CRM may swap two, or give two stages one name: listed stages first
62
+ * take a name no stage has, then their own, and a name used twice keeps the stage's id beside it.
63
+ */
64
+ const saveStages = (pipelineId, pipeline, at) => {
65
+ const ordered = [...pipeline.stages].sort((a, b) => a.position - b.position);
66
+ const counts = new Map();
67
+ for (const stage of ordered)
68
+ counts.set(fold(stage.name), (counts.get(fold(stage.name)) ?? 0) + 1);
69
+ const wanted = ordered.map((stage, index) => {
70
+ const name = textOf(stage.name, 80) ?? stage.externalId;
71
+ const folded = (counts.get(fold(stage.name)) ?? 0) > 1 ? `${fold(name)} (${stage.externalId})` : fold(name);
72
+ if (!STAGE_OUTCOMES.includes(stage.outcome))
73
+ throw new CliError("invalid_response", `stage ${stage.externalId} has no known outcome: ${stage.outcome}`);
74
+ return { ...stage, name, folded, position: index + 1 };
75
+ });
76
+ const held = database.prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ?").all(pipelineId);
77
+ const listed = new Set(wanted.map(({ externalId }) => externalId));
78
+ const taken = new Set(wanted.map(({ folded }) => folded));
79
+ const rename = database.prepare("UPDATE pipeline_stages SET name_folded = ? WHERE id = ?");
80
+ const gone = database.prepare("UPDATE pipeline_stages SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL");
81
+ for (const row of held) {
82
+ const kept = row.external_id != null && listed.has(String(row.external_id));
83
+ if (kept)
84
+ rename.run(`\u0000${row.id}`, Number(row.id));
85
+ else if (taken.has(String(row.name_folded)))
86
+ rename.run(`${row.name_folded} (${row.external_id ?? row.id})`, Number(row.id));
87
+ if (!kept)
88
+ gone.run(at, Number(row.id));
89
+ }
90
+ const byId = new Map(held.map((row) => [String(row.external_id), row]));
91
+ for (const stage of wanted) {
92
+ const row = byId.get(stage.externalId);
93
+ if (row)
94
+ database
95
+ .prepare("UPDATE pipeline_stages SET name = ?, name_folded = ?, position = ?, outcome = ?, updated_at = ?, " +
96
+ "deleted_at = NULL WHERE id = ?")
97
+ .run(stage.name, stage.folded, stage.position, stage.outcome, at, Number(row.id));
98
+ else
99
+ database
100
+ .prepare("INSERT INTO pipeline_stages (pipeline_id, name, name_folded, position, outcome, external_id, created_at, " +
101
+ "updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
102
+ .run(pipelineId, stage.name, stage.folded, stage.position, stage.outcome, stage.externalId, at, at);
103
+ }
104
+ };
105
+ const organizationIdOf = (accountId, externalId) => {
106
+ const row = database
107
+ .prepare("SELECT entity_id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
108
+ "AND entity_type = 'organization'")
109
+ .get(accountId, externalId);
110
+ return row?.entity_id == null ? null : Number(row.entity_id);
111
+ };
112
+ /** The deal or lead row of `(account, external id)`; `writer` gives what another writer than CRM sync resolved. */
113
+ const saveItemRow = (key, accountId, kind, item, at, writer = {}) => {
114
+ const pipeline = pipelineOf(accountId, kind, item.pipeline);
115
+ const stage = pipeline &&
116
+ database
117
+ .prepare("SELECT id, outcome FROM pipeline_stages WHERE pipeline_id = ? AND external_id = ?")
118
+ .get(Number(pipeline.id), item.stage);
119
+ if (!pipeline || !stage)
120
+ return {
121
+ externalId: item.externalId,
122
+ reason: "crm.stage-unknown",
123
+ message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
124
+ };
125
+ const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
126
+ const given = item.amount != null && item.currency != null;
127
+ const currency = given ? currencyOf(item.currency) : null;
128
+ const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
129
+ if (amount !== null && amount < 0)
130
+ throw new CliError("validation_error", "an amount is 0 or more");
131
+ if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
132
+ throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
133
+ const status = item.status ?? String(stage.outcome);
134
+ const closed = status === "open"
135
+ ? null
136
+ : (day(item.closedDate, "a closed day") ?? new Date(epoch(item.updatedAt, at)).toISOString().slice(0, 10));
137
+ const deal = writer.deal !== undefined
138
+ ? writer.deal === null
139
+ ? undefined
140
+ : { id: writer.deal }
141
+ : kind === "lead" && item.deal
142
+ ? database.prepare("SELECT id FROM deals WHERE account_id = ? AND external_id = ?").get(accountId, item.deal)
143
+ : undefined;
144
+ const metadata = {
145
+ ...(item.metadata ?? {}),
146
+ ...(item.url ? { url: item.url } : {}),
147
+ ...(item.assignee ? { assignee: crmIdentityId(key, item.assignee, "user") } : {}),
148
+ ...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
149
+ };
150
+ const values = {
151
+ title,
152
+ organization: writer.organization !== undefined
153
+ ? writer.organization
154
+ : item.organization
155
+ ? organizationIdOf(accountId, item.organization)
156
+ : null,
157
+ stage: Number(stage.id),
158
+ status,
159
+ currency,
160
+ amount,
161
+ close: day(item.closeDate, "an expected close day"),
162
+ closed,
163
+ metadata: Object.keys(metadata).length ? JSON.stringify(metadata) : null,
164
+ created: epoch(item.createdAt, at),
165
+ updated: epoch(item.updatedAt, at),
166
+ };
167
+ const table = TABLES[kind];
168
+ const held = database
169
+ .prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
170
+ .get(accountId, item.externalId);
171
+ let id;
172
+ if (held) {
173
+ id = Number(held.id);
174
+ database
175
+ .prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
176
+ "close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
177
+ (kind === "lead" ? ", deal_id = coalesce(?, deal_id)" : "") +
178
+ " WHERE id = ?")
179
+ .run(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, values.metadata, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []), id);
180
+ }
181
+ else {
182
+ const actor = writer.author ?? author(key);
183
+ id = Number(database
184
+ .prepare(`INSERT INTO ${table} (title, organization_id, stage_id, status, currency, amount, close_date, closed_date, ` +
185
+ `account_id, external_id, author_type, author_id, source, metadata, created_at, updated_at` +
186
+ (kind === "lead" ? ", deal_id" : "") +
187
+ `) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${kind === "lead" ? ", ?" : ""}) RETURNING id`)
188
+ .get(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, accountId, item.externalId, actor.type, actor.id, writer.source ?? SOURCE, values.metadata, values.created, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []))?.id);
189
+ }
190
+ if (writer.project !== undefined)
191
+ database.prepare(`UPDATE ${table} SET project_id = ? WHERE id = ?`).run(writer.project, id);
192
+ return { id };
193
+ };
194
+ return { savePipeline, saveItemRow };
195
+ };
@@ -0,0 +1,28 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ import type { AccountKey } from "../types.js";
3
+ /** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
4
+ export declare const CRM_LINK_MODES: readonly ["reported", "review"];
5
+ export type CrmLinkMode = (typeof CRM_LINK_MODES)[number];
6
+ /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
7
+ export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier", "partner-of"];
8
+ export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
9
+ declare const NAMES: readonly ["links", "company-types"];
10
+ type CrmSettingName = (typeof NAMES)[number];
11
+ export declare const crmSettingKey: (key: AccountKey, name: CrmSettingName) => string;
12
+ /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
13
+ export declare const parseCrmSetting: (setting: string) => {
14
+ key: AccountKey;
15
+ name: CrmSettingName;
16
+ } | undefined;
17
+ /** A value this build cannot read is the default: the CRM's relationships stay reported. */
18
+ export declare const crmLinkMode: (database: CacheDatabase, key: AccountKey) => CrmLinkMode;
19
+ /** Only the owner's mapping gives a company type a meaning; none by default. */
20
+ export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
21
+ /** `links`: reported or review; `company-types`: `TYPE=meaning` pairs, comma-separated. */
22
+ export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
23
+ export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
24
+ export declare const crmSettingsOf: (database: CacheDatabase) => {
25
+ setting: string;
26
+ value: unknown;
27
+ }[];
28
+ export {};
@@ -0,0 +1,80 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
3
+ export const CRM_LINK_MODES = ["reported", "review"];
4
+ /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
5
+ export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
6
+ const NAMES = ["links", "company-types"];
7
+ export const crmSettingKey = (key, name) => `crm.${key.provider}:${key.account}.${name}`;
8
+ /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
9
+ export const parseCrmSetting = (setting) => {
10
+ const match = /^crm\.([a-z0-9-]+):(.+)\.(links|company-types)$/.exec(setting);
11
+ return match
12
+ ? { key: { provider: match[1], account: match[2] }, name: match[3] }
13
+ : undefined;
14
+ };
15
+ const stored = (database, setting) => {
16
+ const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(setting);
17
+ if (!row)
18
+ return undefined;
19
+ try {
20
+ return JSON.parse(String(row.value));
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ /** A value this build cannot read is the default: the CRM's relationships stay reported. */
27
+ export const crmLinkMode = (database, key) => {
28
+ const value = stored(database, crmSettingKey(key, "links"));
29
+ return value === "review" ? "review" : "reported";
30
+ };
31
+ /** Only the owner's mapping gives a company type a meaning; none by default. */
32
+ export const crmCompanyTypes = (database, key) => {
33
+ const value = stored(database, crmSettingKey(key, "company-types"));
34
+ if (typeof value !== "object" || value === null || Array.isArray(value))
35
+ return {};
36
+ return Object.fromEntries(Object.entries(value).filter((entry) => COMPANY_TYPE_MEANINGS.includes(entry[1])));
37
+ };
38
+ /** `links`: reported or review; `company-types`: `TYPE=meaning` pairs, comma-separated. */
39
+ export const parseCrmSettingValue = (name, value) => {
40
+ const text = value.trim();
41
+ if (name === "links") {
42
+ if (!CRM_LINK_MODES.includes(text))
43
+ throw new CliError("validation_error", `a CRM account's links setting is ${CRM_LINK_MODES.join(" or ")}`);
44
+ return text;
45
+ }
46
+ const pairs = text
47
+ .split(",")
48
+ .map((pair) => pair.trim())
49
+ .filter(Boolean);
50
+ const map = {};
51
+ for (const pair of pairs) {
52
+ const [type, meaning] = pair.split("=").map((part) => part.trim());
53
+ if (!type || !COMPANY_TYPE_MEANINGS.includes(meaning ?? ""))
54
+ throw new CliError("validation_error", `company-types takes TYPE=meaning pairs, the meaning ${COMPANY_TYPE_MEANINGS.join(", ")}: not "${pair}"`);
55
+ map[type] = meaning;
56
+ }
57
+ return map;
58
+ };
59
+ export const saveCrmSetting = (database, setting, value, now) => {
60
+ if (value === undefined)
61
+ database.prepare("DELETE FROM store_settings WHERE key = ?").run(setting);
62
+ else
63
+ database
64
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
65
+ .run(setting, JSON.stringify(value), now);
66
+ };
67
+ export const crmSettingsOf = (database) => database
68
+ .prepare("SELECT key, value FROM store_settings WHERE key LIKE 'crm.%' ORDER BY key")
69
+ .all()
70
+ .flatMap((row) => {
71
+ const parsed = parseCrmSetting(String(row.key));
72
+ if (!parsed)
73
+ return [];
74
+ return [
75
+ {
76
+ setting: String(row.key),
77
+ value: parsed.name === "links" ? crmLinkMode(database, parsed.key) : crmCompanyTypes(database, parsed.key),
78
+ },
79
+ ];
80
+ });