@wirecat/cli-core 0.617.0 → 0.619.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 (306) hide show
  1. package/CHANGELOG.md +406 -1
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES +3 -0
  4. package/dist/background/backfill.d.ts +21 -0
  5. package/dist/background/backfill.js +41 -0
  6. package/dist/background/daily-archive-timer.d.ts +1 -1
  7. package/dist/background/deliver.d.ts +5 -2
  8. package/dist/background/deliver.js +30 -12
  9. package/dist/background/report/messages.js +4 -1
  10. package/dist/background/report/render.d.ts +3 -1
  11. package/dist/background/report/render.js +3 -1
  12. package/dist/background/report/view.js +4 -1
  13. package/dist/background/schedules.d.ts +17 -0
  14. package/dist/background/schedules.js +21 -8
  15. package/dist/calendar/cli/answers.d.ts +1 -0
  16. package/dist/calendar/cli/answers.js +6 -1
  17. package/dist/calendar/cli/index.js +2 -14
  18. package/dist/calendar/cli/people-link.d.ts +3 -0
  19. package/dist/calendar/cli/people-link.js +23 -0
  20. package/dist/calendar/index.d.ts +1 -1
  21. package/dist/calendar/index.js +1 -1
  22. package/dist/calendar/mcp/index.d.ts +12 -12
  23. package/dist/cli/base-stages-command.d.ts +22 -0
  24. package/dist/cli/base-stages-command.js +174 -0
  25. package/dist/cli/command-runs.d.ts +2 -0
  26. package/dist/cli/command-runs.js +3 -1
  27. package/dist/cli/config-command.js +6 -1
  28. package/dist/cli/context.d.ts +5 -0
  29. package/dist/cli/context.js +1 -0
  30. package/dist/cli/group-lock.d.ts +42 -0
  31. package/dist/cli/group-lock.js +130 -0
  32. package/dist/cli/index.d.ts +10 -4
  33. package/dist/cli/index.js +10 -4
  34. package/dist/cli/messenger/backfill-command.js +27 -15
  35. package/dist/cli/messenger/contacts-command.js +10 -3
  36. package/dist/cli/messenger/context.js +1 -0
  37. package/dist/cli/messenger/doctor-command.js +3 -1
  38. package/dist/cli/messenger/models-command.js +1 -1
  39. package/dist/cli/messenger/serve-command.js +24 -2
  40. package/dist/cli/messenger/serve-outdated.d.ts +22 -0
  41. package/dist/cli/messenger/serve-outdated.js +100 -0
  42. package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
  43. package/dist/cli/messenger/store-maintenance-command.js +9 -4
  44. package/dist/cli/model-catalogue-command.d.ts +3 -1
  45. package/dist/cli/model-catalogue-command.js +46 -2
  46. package/dist/cli/profile.d.ts +8 -0
  47. package/dist/cli/profile.js +25 -0
  48. package/dist/cli/program.js +2 -0
  49. package/dist/cli/runs/search-query.d.ts +1 -1
  50. package/dist/cli/runs/search-query.js +4 -0
  51. package/dist/cli/runs/search.d.ts +5 -1
  52. package/dist/cli/runs/search.js +12 -1
  53. package/dist/cli/schedule/schedule-command.d.ts +9 -0
  54. package/dist/cli/schedule/schedule-command.js +13 -0
  55. package/dist/cli/search-left-out.d.ts +6 -1
  56. package/dist/cli/search-left-out.js +9 -4
  57. package/dist/cli/settings.d.ts +8 -0
  58. package/dist/cli/settings.js +17 -2
  59. package/dist/cli/shared-command-exports.d.ts +16 -0
  60. package/dist/cli/store-recover.d.ts +3 -3
  61. package/dist/cli/store-recover.js +47 -23
  62. package/dist/cli/store-settings.d.ts +2 -0
  63. package/dist/cli/store-settings.js +37 -9
  64. package/dist/crm/cli/index.js +38 -6
  65. package/dist/crm/group-hint.d.ts +8 -0
  66. package/dist/crm/group-hint.js +13 -0
  67. package/dist/crm/source.d.ts +12 -1
  68. package/dist/crm/sync.d.ts +31 -2
  69. package/dist/crm/sync.js +110 -3
  70. package/dist/crm/testing/acme-scenario.d.ts +40 -0
  71. package/dist/crm/testing/acme-scenario.js +170 -0
  72. package/dist/crm/testing/index.d.ts +1 -0
  73. package/dist/crm/testing/index.js +1 -0
  74. package/dist/crm/testing/source-contract.js +12 -0
  75. package/dist/crm/testing/source.d.ts +2 -0
  76. package/dist/crm/testing/source.js +1 -0
  77. package/dist/domain/addresses.d.ts +13 -0
  78. package/dist/domain/addresses.js +63 -0
  79. package/dist/domain/categories.d.ts +3 -0
  80. package/dist/domain/categories.js +2 -0
  81. package/dist/domain/crm.d.ts +23 -0
  82. package/dist/domain/crm.js +7 -0
  83. package/dist/domain/links.d.ts +17 -4
  84. package/dist/domain/links.js +20 -7
  85. package/dist/domain/mentions.d.ts +2 -12
  86. package/dist/domain/mentions.js +2 -19
  87. package/dist/domain/orders.d.ts +8 -1
  88. package/dist/domain/orders.js +6 -2
  89. package/dist/domain/phones.d.ts +26 -0
  90. package/dist/domain/phones.js +48 -0
  91. package/dist/domain/record-types.d.ts +1 -1
  92. package/dist/domain/record-types.js +1 -0
  93. package/dist/domain/records.d.ts +5 -0
  94. package/dist/domain/ref-summaries.d.ts +39 -0
  95. package/dist/domain/ref-summaries.js +51 -3
  96. package/dist/domain/relations.d.ts +27 -2
  97. package/dist/domain/relations.js +37 -3
  98. package/dist/domain/vcard.d.ts +2 -2
  99. package/dist/domain/vcard.js +4 -10
  100. package/dist/embeddings/models.d.ts +11 -3
  101. package/dist/embeddings/models.js +28 -4
  102. package/dist/entities/business-context.d.ts +149 -0
  103. package/dist/entities/business-context.js +192 -0
  104. package/dist/entities/contact-activity.d.ts +2 -0
  105. package/dist/entities/contact-activity.js +7 -1
  106. package/dist/entities/contact-context.d.ts +157 -0
  107. package/dist/entities/contact-context.js +2 -0
  108. package/dist/entities/deal.d.ts +10 -0
  109. package/dist/entities/deal.js +2 -0
  110. package/dist/entities/index.d.ts +23 -3
  111. package/dist/entities/index.js +5 -0
  112. package/dist/entities/mention.d.ts +4 -3
  113. package/dist/entities/mention.js +2 -1
  114. package/dist/entities/message-transfer.d.ts +4 -2
  115. package/dist/entities/message-transfer.js +2 -2
  116. package/dist/entities/model.d.ts +2 -2
  117. package/dist/entities/model.js +1 -1
  118. package/dist/entities/relationship.d.ts +4 -0
  119. package/dist/entities/relationship.js +4 -0
  120. package/dist/errors/reasons.js +44 -4
  121. package/dist/fetch/page.js +2 -1
  122. package/dist/index.d.ts +4 -3
  123. package/dist/index.js +4 -3
  124. package/dist/meetings/context-store.d.ts +2 -0
  125. package/dist/meetings/findings-rules.d.ts +4 -0
  126. package/dist/meetings/findings-rules.js +5 -2
  127. package/dist/meetings/mcp/index.d.ts +15 -15
  128. package/dist/meetings/result-items.d.ts +1 -0
  129. package/dist/meetings/result-items.js +1 -0
  130. package/dist/models/index.js +22 -5
  131. package/dist/runs/events.d.ts +11 -1
  132. package/dist/runs/events.js +3 -1
  133. package/dist/runs/log-attributes.js +4 -0
  134. package/dist/runs/log-events.js +2 -0
  135. package/dist/runs/recording.d.ts +3 -0
  136. package/dist/runs/recording.js +36 -12
  137. package/dist/runs/run.d.ts +12 -3
  138. package/dist/runs/run.js +32 -13
  139. package/dist/search/account-list.d.ts +6 -0
  140. package/dist/search/account-list.js +9 -3
  141. package/dist/search/groups.d.ts +68 -0
  142. package/dist/search/groups.js +172 -0
  143. package/dist/services/account-groups.d.ts +28 -0
  144. package/dist/services/account-groups.js +89 -0
  145. package/dist/services/archive.d.ts +7 -1
  146. package/dist/services/archive.js +19 -3
  147. package/dist/services/business-context.d.ts +113 -0
  148. package/dist/services/business-context.js +156 -0
  149. package/dist/services/communications.d.ts +50 -0
  150. package/dist/services/communications.js +140 -0
  151. package/dist/services/deal-context.d.ts +90 -0
  152. package/dist/services/deal-context.js +131 -0
  153. package/dist/services/deps.d.ts +2 -0
  154. package/dist/services/enrichment.d.ts +7 -2
  155. package/dist/services/enrichment.js +46 -5
  156. package/dist/services/events-search.js +2 -1
  157. package/dist/services/group-guard.d.ts +28 -0
  158. package/dist/services/group-guard.js +131 -0
  159. package/dist/services/index.d.ts +15 -2
  160. package/dist/services/index.js +9 -2
  161. package/dist/services/ingest.d.ts +12 -0
  162. package/dist/services/ingest.js +4 -0
  163. package/dist/services/link-scorers/chat-senders.js +39 -29
  164. package/dist/services/link-scorers/member-chats.js +4 -3
  165. package/dist/services/link-scorers/member-dialog.js +5 -7
  166. package/dist/services/link-scorers/scan.js +17 -8
  167. package/dist/services/link-scorers/shared.d.ts +6 -2
  168. package/dist/services/link-scorers/shared.js +6 -2
  169. package/dist/services/link-scorers/types.d.ts +2 -0
  170. package/dist/services/meaning-model.d.ts +7 -0
  171. package/dist/services/meaning-model.js +20 -0
  172. package/dist/services/meeting-context.d.ts +6 -1
  173. package/dist/services/meeting-context.js +12 -5
  174. package/dist/services/message-resolution.js +2 -3
  175. package/dist/services/messages-meaning.js +4 -5
  176. package/dist/services/messages-search.d.ts +5 -1
  177. package/dist/services/messages-search.js +1 -1
  178. package/dist/services/model-downloads.d.ts +1 -1
  179. package/dist/services/model-downloads.js +6 -4
  180. package/dist/services/money-context.d.ts +73 -0
  181. package/dist/services/money-context.js +77 -0
  182. package/dist/services/notes-search.d.ts +4 -1
  183. package/dist/services/notes-search.js +19 -7
  184. package/dist/services/organization-context.d.ts +80 -0
  185. package/dist/services/organization-context.js +154 -0
  186. package/dist/services/people.d.ts +22 -6
  187. package/dist/services/people.js +38 -8
  188. package/dist/services/person-business.d.ts +43 -0
  189. package/dist/services/person-business.js +67 -0
  190. package/dist/services/person-context.d.ts +9 -1
  191. package/dist/services/person-context.js +5 -3
  192. package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
  193. package/dist/services/proposals/kinds/identity-link.js +48 -0
  194. package/dist/services/proposals/kinds/orders.js +1 -1
  195. package/dist/services/proposals/registry.js +2 -0
  196. package/dist/services/search-kind.d.ts +12 -5
  197. package/dist/services/search-kind.js +49 -10
  198. package/dist/services/text-model-choice.js +1 -1
  199. package/dist/store/accounts.d.ts +18 -0
  200. package/dist/store/accounts.js +18 -3
  201. package/dist/store/damage.d.ts +43 -10
  202. package/dist/store/damage.js +119 -36
  203. package/dist/store/decisions.js +3 -1
  204. package/dist/store/evidence-findings.d.ts +14 -0
  205. package/dist/store/evidence-findings.js +2 -0
  206. package/dist/store/exports.d.ts +2 -1
  207. package/dist/store/identity-links.d.ts +92 -0
  208. package/dist/store/identity-links.js +6 -0
  209. package/dist/store/index.d.ts +11 -5
  210. package/dist/store/index.js +5 -2
  211. package/dist/store/journal.d.ts +10 -0
  212. package/dist/store/journal.js +33 -0
  213. package/dist/store/marks.d.ts +19 -1
  214. package/dist/store/marks.js +23 -1
  215. package/dist/store/migrations.d.ts +1 -1
  216. package/dist/store/migrations.js +35 -12
  217. package/dist/store/people.d.ts +22 -0
  218. package/dist/store/people.js +15 -1
  219. package/dist/store/recover.d.ts +34 -0
  220. package/dist/store/recover.js +188 -6
  221. package/dist/store/refill.d.ts +28 -0
  222. package/dist/store/refill.js +120 -0
  223. package/dist/store/sqlite/accounts.js +2 -0
  224. package/dist/store/sqlite/base-stages.d.ts +122 -0
  225. package/dist/store/sqlite/base-stages.js +443 -0
  226. package/dist/store/sqlite/base-suggest.d.ts +13 -0
  227. package/dist/store/sqlite/base-suggest.js +62 -0
  228. package/dist/store/sqlite/business-contracts.js +10 -1
  229. package/dist/store/sqlite/clients.d.ts +7 -3
  230. package/dist/store/sqlite/clients.js +11 -7
  231. package/dist/store/sqlite/crm-settings.d.ts +12 -2
  232. package/dist/store/sqlite/crm-settings.js +56 -13
  233. package/dist/store/sqlite/crm.d.ts +13 -1
  234. package/dist/store/sqlite/crm.js +20 -4
  235. package/dist/store/sqlite/deals.d.ts +33 -0
  236. package/dist/store/sqlite/deals.js +42 -4
  237. package/dist/store/sqlite/decision-requests.js +7 -3
  238. package/dist/store/sqlite/email-index.js +17 -15
  239. package/dist/store/sqlite/evidence-findings.js +29 -5
  240. package/dist/store/sqlite/findings-core.js +4 -2
  241. package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
  242. package/dist/store/sqlite/identity-link-rows.js +146 -0
  243. package/dist/store/sqlite/identity-proposals.d.ts +53 -0
  244. package/dist/store/sqlite/identity-proposals.js +234 -0
  245. package/dist/store/sqlite/knowledge.js +5 -3
  246. package/dist/store/sqlite/link-kinds.d.ts +1 -0
  247. package/dist/store/sqlite/link-kinds.js +1 -0
  248. package/dist/store/sqlite/link-row.d.ts +6 -0
  249. package/dist/store/sqlite/link-row.js +35 -0
  250. package/dist/store/sqlite/link-source.d.ts +10 -0
  251. package/dist/store/sqlite/link-source.js +16 -0
  252. package/dist/store/sqlite/manifest.js +1 -0
  253. package/dist/store/sqlite/meeting-context-links.js +9 -6
  254. package/dist/store/sqlite/memories.js +9 -7
  255. package/dist/store/sqlite/mentions.d.ts +4 -1
  256. package/dist/store/sqlite/mentions.js +14 -9
  257. package/dist/store/sqlite/migrations.generated.js +8 -0
  258. package/dist/store/sqlite/note-index.js +9 -7
  259. package/dist/store/sqlite/notes.d.ts +2 -3
  260. package/dist/store/sqlite/notes.js +6 -29
  261. package/dist/store/sqlite/open-store.js +3 -0
  262. package/dist/store/sqlite/open.js +11 -2
  263. package/dist/store/sqlite/orders.d.ts +2 -0
  264. package/dist/store/sqlite/orders.js +9 -3
  265. package/dist/store/sqlite/organization-categories.d.ts +18 -0
  266. package/dist/store/sqlite/organization-categories.js +34 -0
  267. package/dist/store/sqlite/organizations.d.ts +5 -1
  268. package/dist/store/sqlite/organizations.js +14 -4
  269. package/dist/store/sqlite/person-links.d.ts +19 -4
  270. package/dist/store/sqlite/person-links.js +49 -11
  271. package/dist/store/sqlite/person-match-scan.d.ts +13 -0
  272. package/dist/store/sqlite/person-match-scan.js +251 -0
  273. package/dist/store/sqlite/person-matcher.d.ts +16 -0
  274. package/dist/store/sqlite/person-matcher.js +32 -0
  275. package/dist/store/sqlite/proposed-actions.js +6 -0
  276. package/dist/store/sqlite/record-matching.d.ts +2 -8
  277. package/dist/store/sqlite/record-matching.js +8 -40
  278. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  279. package/dist/store/sqlite/record-relationships.d.ts +52 -0
  280. package/dist/store/sqlite/record-relationships.js +243 -0
  281. package/dist/store/sqlite/record-run.d.ts +5 -0
  282. package/dist/store/sqlite/record-run.js +62 -2
  283. package/dist/store/sqlite/record-writes.d.ts +1 -1
  284. package/dist/store/sqlite/record-writes.js +4 -2
  285. package/dist/store/sqlite/records.js +27 -2
  286. package/dist/store/sqlite/ref-accounts.d.ts +13 -0
  287. package/dist/store/sqlite/ref-accounts.js +117 -0
  288. package/dist/store/sqlite/ref-summaries.js +5 -1
  289. package/dist/store/sqlite/relation-list.d.ts +4 -1
  290. package/dist/store/sqlite/relation-list.js +20 -2
  291. package/dist/store/sqlite/relation-proposals.d.ts +18 -1
  292. package/dist/store/sqlite/relation-proposals.js +53 -11
  293. package/dist/store/sqlite/relation-roles.js +12 -6
  294. package/dist/store/sqlite/reported-relations.d.ts +11 -1
  295. package/dist/store/sqlite/reported-relations.js +59 -18
  296. package/dist/store/sqlite/schema.d.ts +32 -0
  297. package/dist/store/sqlite/schema.js +3 -0
  298. package/dist/store/sqlite/transaction.d.ts +13 -0
  299. package/dist/store/sqlite/transaction.js +33 -15
  300. package/dist/store/store.d.ts +3 -0
  301. package/dist/store/store.js +5 -0
  302. package/dist/store/write-events.d.ts +18 -0
  303. package/dist/store/write-events.js +88 -0
  304. package/package.json +3 -3
  305. package/parity.json +11 -4
  306. package/schemas/records-envelope.v1.schema.json +3 -0
@@ -0,0 +1,443 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { DEAL_KINDS, STAGE_OUTCOMES } from "../../domain/deals.js";
3
+ import { fold } from "../normalize.js";
4
+ import { basePipelineOf, baseSettingKey, baseStagesOf, suggestBaseStages } from "./base-suggest.js";
5
+ import { dealOperationsOver } from "./deals.js";
6
+ import { ownerLanguages } from "./owner-languages.js";
7
+ import { oneOf, refuse, text } from "./reviewed.js";
8
+ import { write } from "./transaction.js";
9
+ const OUTCOMES = {
10
+ lead: ["open", "open", "open", "won", "lost"],
11
+ deal: ["open", "open", "open", "open", "won", "lost"],
12
+ };
13
+ /** The default sets' names in the languages they are written in; any other owner language gets English. */
14
+ const NAMES = {
15
+ en: {
16
+ set: "Base stages",
17
+ lead: ["New", "Contacted", "Qualified", "Converted", "Rejected"],
18
+ deal: ["New", "Qualification", "Proposal", "Negotiation", "Won", "Lost"],
19
+ },
20
+ ru: {
21
+ set: "Базовые стадии",
22
+ lead: ["Новый", "Связались", "Квалифицирован", "Конвертирован", "Отклонён"],
23
+ deal: ["Новая", "Квалификация", "Предложение", "Переговоры", "Выиграна", "Проиграна"],
24
+ },
25
+ es: {
26
+ set: "Etapas base",
27
+ lead: ["Nuevo", "Contactado", "Calificado", "Convertido", "Rechazado"],
28
+ deal: ["Nuevo", "Calificación", "Propuesta", "Negociación", "Ganado", "Perdido"],
29
+ },
30
+ };
31
+ const namesFor = (database) => NAMES[ownerLanguages(database)[0] ?? "en"] ?? NAMES.en;
32
+ const MAX_BASE_STAGES = 30;
33
+ const ITEM_TABLES = { deal: "deals", lead: "leads" };
34
+ const stageRef = (id) => `stage:${id}`;
35
+ /** `(p.account_id IS NULL OR …)`: the owner's own pipelines pass, as a group lock lets them. */
36
+ const scopeSql = (scope, alias = "p") => {
37
+ const accounts = scope?.accounts;
38
+ if (accounts === undefined)
39
+ return { sql: "1", params: [] };
40
+ if (accounts.length === 0)
41
+ return { sql: `${alias}.account_id IS NULL`, params: [] };
42
+ return {
43
+ sql: `(${alias}.account_id IS NULL OR ${alias}.account_id IN (SELECT id FROM accounts WHERE ` +
44
+ `${accounts.map(() => "(provider = ? AND external_id = ?)").join(" OR ")}))`,
45
+ params: accounts.flatMap(({ provider, account }) => [provider, account]),
46
+ };
47
+ };
48
+ export const baseStagesOver = (context) => {
49
+ const { database, now } = context;
50
+ const deals = dealOperationsOver(context);
51
+ const kindOf = (kind) => oneOf(kind, DEAL_KINDS, "a kind");
52
+ const freeName = (kind) => {
53
+ const taken = new Set(database
54
+ .prepare("SELECT name_folded FROM pipelines WHERE kind = ? AND account_id IS NULL")
55
+ .all(kind)
56
+ .map((row) => String(row.name_folded)));
57
+ const base = namesFor(database).set;
58
+ let name = base;
59
+ for (let suffix = 2; taken.has(fold(name)); suffix += 1)
60
+ name = `${base} ${suffix}`;
61
+ return name;
62
+ };
63
+ /**
64
+ * The owner's only own pipeline of the kind, when it has every outcome: the store's own `Leads` is the lead set, so
65
+ * a second own pipeline does not make a lead's first stage or a stage's name ambiguous.
66
+ */
67
+ const adoptable = (kind) => {
68
+ const own = database
69
+ .prepare("SELECT id FROM pipelines WHERE kind = ? AND account_id IS NULL AND deleted_at IS NULL")
70
+ .all(kind);
71
+ if (own.length !== 1)
72
+ return undefined;
73
+ const id = Number(own[0]?.id);
74
+ const outcomes = new Set(baseStagesOf(database, id).map((stage) => stage.outcome));
75
+ return STAGE_OUTCOMES.every((outcome) => outcomes.has(outcome)) ? id : undefined;
76
+ };
77
+ /** Every pipeline but the base sets, and the one a first use would take: what maps onto them. */
78
+ const notBaseSql = () => ({
79
+ sql: "p.id NOT IN (?, ?)",
80
+ params: DEAL_KINDS.map((kind) => basePipelineOf(database, kind) ?? adoptable(kind) ?? -1),
81
+ });
82
+ /** The set's pipeline, adopted or made with the defaults on first use; each base stage maps to itself, confirmed. */
83
+ const ensure = (kind) => {
84
+ const held = basePipelineOf(database, kind);
85
+ if (held !== undefined)
86
+ return held;
87
+ return write(database, () => {
88
+ const at = now();
89
+ let id = adoptable(kind);
90
+ if (id === undefined) {
91
+ const name = freeName(kind);
92
+ id = Number(database
93
+ .prepare("INSERT INTO pipelines (kind, name, name_folded, created_at, updated_at) VALUES (?, ?, ?, ?, ?) RETURNING id")
94
+ .get(kind, name, fold(name), at, at)?.id);
95
+ const names = namesFor(database)[kind];
96
+ for (const [index, name] of names.entries())
97
+ insertStage(id, name, OUTCOMES[kind][index], index + 1, at);
98
+ }
99
+ else {
100
+ database
101
+ .prepare("UPDATE pipeline_stages SET base_stage_id = id, base_confirmed = 1 WHERE pipeline_id = ?")
102
+ .run(id);
103
+ const rename = database.prepare("UPDATE pipeline_stages SET name = ?, updated_at = ? WHERE id = ?");
104
+ for (const stage of baseStagesOf(database, id))
105
+ if (String(stage.name) !== capitalised(String(stage.name)))
106
+ rename.run(capitalised(String(stage.name)), at, Number(stage.id));
107
+ }
108
+ database
109
+ .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
110
+ .run(baseSettingKey(kind), JSON.stringify(`pipeline:${id}`), at);
111
+ suggestBaseStages(database, kind);
112
+ return id;
113
+ });
114
+ };
115
+ /** The seeded `Leads` has `new` … `lost`: a column title starts with a capital; the folded name stays. */
116
+ const capitalised = (name) => name === name.toLocaleLowerCase() ? name.charAt(0).toLocaleUpperCase() + name.slice(1) : name;
117
+ const readOnly = () => Number(database.prepare("PRAGMA query_only").get()?.query_only) === 1;
118
+ const insertStage = (pipeline, name, outcome, position, at) => {
119
+ const id = Number(database
120
+ .prepare("INSERT INTO pipeline_stages (pipeline_id, name, name_folded, position, outcome, base_confirmed, created_at, " +
121
+ "updated_at) VALUES (?, ?, ?, ?, ?, 1, ?, ?) RETURNING id")
122
+ .get(pipeline, name, fold(name), position, outcome, at, at)?.id);
123
+ database.prepare("UPDATE pipeline_stages SET base_stage_id = id WHERE id = ?").run(id);
124
+ return id;
125
+ };
126
+ /** A base stage by `stage:<id>` or by its name, in any letter case. */
127
+ const baseStageRow = (pipeline, given) => {
128
+ const named = given.trim();
129
+ const byRef = /^stage:(\d+)$/.exec(named);
130
+ const row = byRef
131
+ ? database
132
+ .prepare("SELECT * FROM pipeline_stages WHERE id = ? AND pipeline_id = ?")
133
+ .get(Number(byRef[1]), pipeline)
134
+ : database
135
+ .prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ? AND name_folded = ?")
136
+ .get(pipeline, fold(named));
137
+ if (!row)
138
+ throw new CliError("not_found", `no base stage ${named}: ${stageNames(pipeline)}`, { reason: "stage.not-found" });
139
+ return row;
140
+ };
141
+ const stageNames = (pipeline) => baseStagesOf(database, pipeline)
142
+ .map((stage) => `${stage.name} (${stageRef(stage.id)})`)
143
+ .join(", ");
144
+ const nameOf = (value) => text(value, "a stage's name", 80, "stage.base-field") ?? refuse("a stage needs a name", "stage.base-field");
145
+ const unique = (pipeline, name, except) => {
146
+ const held = database
147
+ .prepare("SELECT id FROM pipeline_stages WHERE pipeline_id = ? AND name_folded = ?")
148
+ .get(pipeline, fold(name));
149
+ if (held && Number(held.id) !== except)
150
+ refuse(`the base set already has a stage named ${name}`, "stage.base-field");
151
+ };
152
+ /** Writes positions 1… in the given order, then suggests again: a moved column moves what lands on it. */
153
+ const reorder = (kind, ids) => {
154
+ const at = now();
155
+ const set = database.prepare("UPDATE pipeline_stages SET position = ?, updated_at = ? WHERE id = ?");
156
+ for (const [index, id] of ids.entries())
157
+ set.run(index + 1, at, id);
158
+ suggestBaseStages(database, kind);
159
+ };
160
+ const positionOf = (value, most) => {
161
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > most)
162
+ return refuse(`a position is 1–${most}`, "stage.base-field");
163
+ return value;
164
+ };
165
+ /**
166
+ * The set a first use would make, read without a write: on a read-only store the columns of the pipeline it would
167
+ * take, or the defaults with no reference yet. Nothing is mapped, so every CRM stage and row is unsorted.
168
+ */
169
+ const unmade = (kind, scope) => {
170
+ const { sql, params } = scopeSql(scope);
171
+ const adopted = adoptable(kind);
172
+ const standing = (stage) => Number(database
173
+ .prepare(`SELECT count(*) AS n FROM ${ITEM_TABLES[kind]} WHERE stage_id = ? AND status = 'open' AND deleted_at IS NULL`)
174
+ .get(stage)?.n);
175
+ const stages = adopted === undefined
176
+ ? namesFor(database)[kind].map((name, index) => ({
177
+ ref: null,
178
+ name,
179
+ position: index + 1,
180
+ outcome: OUTCOMES[kind][index],
181
+ open: 0,
182
+ mapped: 0,
183
+ }))
184
+ : baseStagesOf(database, adopted).map((stage) => ({
185
+ ref: stageRef(stage.id),
186
+ name: capitalised(String(stage.name)),
187
+ position: Number(stage.position),
188
+ outcome: stage.outcome,
189
+ open: standing(Number(stage.id)),
190
+ mapped: 0,
191
+ }));
192
+ const total = database
193
+ .prepare(`SELECT count(*) AS n FROM ${ITEM_TABLES[kind]} d JOIN pipeline_stages s ON s.id = d.stage_id ` +
194
+ `JOIN pipelines p ON p.id = s.pipeline_id WHERE d.status = 'open' AND d.deleted_at IS NULL AND ${sql}`)
195
+ .get(...params);
196
+ const crm = database
197
+ .prepare("SELECT count(*) AS n FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id WHERE p.kind = ? " +
198
+ `AND p.id <> ? AND s.deleted_at IS NULL AND p.deleted_at IS NULL AND ${sql}`)
199
+ .get(kind, adopted ?? -1, ...params);
200
+ const own = stages.reduce((sum, stage) => sum + stage.open, 0);
201
+ return {
202
+ kind,
203
+ pipeline: adopted === undefined ? null : `pipeline:${adopted}`,
204
+ stages,
205
+ unsorted: { open: Number(total?.n) - own, stages: Number(crm?.n) },
206
+ };
207
+ };
208
+ const show = (kind, scope) => {
209
+ if (basePipelineOf(database, kindOf(kind)) === undefined && readOnly())
210
+ return unmade(kind, scope);
211
+ const pipeline = ensure(kindOf(kind));
212
+ const { sql, params } = scopeSql(scope);
213
+ const table = ITEM_TABLES[kind];
214
+ const counted = database
215
+ .prepare("SELECT CASE WHEN s.base_confirmed = 1 THEN s.base_stage_id END AS base, " +
216
+ `count(DISTINCT d.id) AS open FROM ${table} d JOIN pipeline_stages s ON s.id = d.stage_id ` +
217
+ `JOIN pipelines p ON p.id = s.pipeline_id WHERE d.status = 'open' AND d.deleted_at IS NULL AND ${sql} ` +
218
+ "GROUP BY base")
219
+ .all(...params);
220
+ const mapped = database
221
+ .prepare("SELECT CASE WHEN s.base_confirmed = 1 THEN s.base_stage_id END AS base, count(*) AS stages " +
222
+ "FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id WHERE p.kind = ? AND p.id <> ? " +
223
+ `AND s.deleted_at IS NULL AND p.deleted_at IS NULL AND ${sql} GROUP BY base`)
224
+ .all(kind, pipeline, ...params);
225
+ const countOf = (rows, base, field) => Number(rows.find((row) => (row.base ?? null) === (base ?? null))?.[field] ?? 0);
226
+ return {
227
+ kind,
228
+ pipeline: `pipeline:${pipeline}`,
229
+ stages: baseStagesOf(database, pipeline).map((stage) => ({
230
+ ref: stageRef(stage.id),
231
+ name: String(stage.name),
232
+ position: Number(stage.position),
233
+ outcome: stage.outcome,
234
+ open: countOf(counted, stage.id, "open"),
235
+ mapped: countOf(mapped, stage.id, "stages"),
236
+ })),
237
+ unsorted: { open: countOf(counted, null, "open"), stages: countOf(mapped, null, "stages") },
238
+ };
239
+ };
240
+ const mappingSql = "SELECT s.*, p.name AS pipeline_name, p.kind, a.provider AS account_provider, a.external_id AS account_external_id, " +
241
+ "b.id AS base_id, b.name AS base_name, (SELECT count(*) FROM deals d WHERE d.stage_id = s.id AND " +
242
+ "d.status = 'open' AND d.deleted_at IS NULL) + (SELECT count(*) FROM leads l WHERE l.stage_id = s.id AND " +
243
+ "l.status = 'open' AND l.deleted_at IS NULL) AS open FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id " +
244
+ "LEFT JOIN accounts a ON a.id = p.account_id LEFT JOIN pipeline_stages b ON b.id = s.base_stage_id";
245
+ const mappingOf = (row) => ({
246
+ ref: stageRef(row.id),
247
+ name: String(row.name),
248
+ position: Number(row.position),
249
+ outcome: row.outcome,
250
+ externalId: row.external_id == null ? null : String(row.external_id),
251
+ kind: row.kind,
252
+ pipeline: `pipeline:${row.pipeline_id}`,
253
+ pipelineName: String(row.pipeline_name),
254
+ account: row.account_provider == null
255
+ ? null
256
+ : { provider: String(row.account_provider), account: String(row.account_external_id) },
257
+ baseStage: row.base_id == null ? null : { ref: stageRef(row.base_id), name: String(row.base_name) },
258
+ confirmed: Number(row.base_confirmed) === 1,
259
+ open: Number(row.open),
260
+ });
261
+ /** Live stages of every pipeline in scope but the base sets: what the owner maps. */
262
+ const mappableRows = (filter, extra = "1", extraParams = []) => {
263
+ const kinds = filter.kind === undefined ? DEAL_KINDS : [kindOf(filter.kind)];
264
+ const pipeline = filter.pipeline === undefined
265
+ ? null
266
+ : Number(deals.pipeline(filter.pipeline, filter.kind === undefined ? {} : { kind: filter.kind }).id);
267
+ const { sql, params } = scopeSql(filter);
268
+ const bases = notBaseSql();
269
+ return database
270
+ .prepare(`${mappingSql} WHERE p.kind IN (${kinds.map(() => "?").join(", ")}) ` +
271
+ `AND ${bases.sql} AND s.deleted_at IS NULL AND p.deleted_at IS NULL ` +
272
+ `AND (? IS NULL OR p.id = ?) AND (? = 0 OR s.base_confirmed = 0) AND ${sql} AND ${extra} ` +
273
+ "ORDER BY p.kind, p.name_folded, p.id, s.position, s.id")
274
+ .all(...kinds, ...bases.params, pipeline, pipeline, filter.unconfirmed ? 1 : 0, ...params, ...extraParams);
275
+ };
276
+ return {
277
+ show,
278
+ add: (kind, input) => {
279
+ const chosen = kindOf(kind);
280
+ const name = nameOf(input.name);
281
+ const outcome = input.outcome === undefined ? "open" : oneOf(input.outcome, STAGE_OUTCOMES, "a stage's outcome");
282
+ write(database, () => {
283
+ const pipeline = ensure(chosen);
284
+ unique(pipeline, name);
285
+ const ids = baseStagesOf(database, pipeline).map((stage) => ({ id: Number(stage.id), outcome: stage.outcome }));
286
+ if (ids.length >= MAX_BASE_STAGES)
287
+ refuse(`a base set has at most ${MAX_BASE_STAGES} stages`, "stage.base-field");
288
+ const firstEnd = ids.findIndex((stage) => stage.outcome !== "open");
289
+ const index = input.position === undefined
290
+ ? outcome === "open" && firstEnd !== -1
291
+ ? firstEnd
292
+ : ids.length
293
+ : positionOf(input.position, ids.length + 1) - 1;
294
+ const id = insertStage(pipeline, name, outcome, ids.length + 1, now());
295
+ const order = ids.map((stage) => stage.id);
296
+ order.splice(index, 0, id);
297
+ reorder(chosen, order);
298
+ });
299
+ return show(chosen);
300
+ },
301
+ rename: (kind, stage, name) => {
302
+ const chosen = kindOf(kind);
303
+ const named = nameOf(name);
304
+ write(database, () => {
305
+ const pipeline = ensure(chosen);
306
+ const row = baseStageRow(pipeline, stage);
307
+ unique(pipeline, named, Number(row.id));
308
+ database
309
+ .prepare("UPDATE pipeline_stages SET name = ?, name_folded = ?, updated_at = ? WHERE id = ?")
310
+ .run(named, fold(named), now(), Number(row.id));
311
+ });
312
+ return show(chosen);
313
+ },
314
+ move: (kind, stage, position) => {
315
+ const chosen = kindOf(kind);
316
+ write(database, () => {
317
+ const pipeline = ensure(chosen);
318
+ const id = Number(baseStageRow(pipeline, stage).id);
319
+ const order = baseStagesOf(database, pipeline)
320
+ .map((one) => Number(one.id))
321
+ .filter((one) => one !== id);
322
+ order.splice(positionOf(position, order.length + 1) - 1, 0, id);
323
+ reorder(chosen, order);
324
+ });
325
+ return show(chosen);
326
+ },
327
+ remove: (kind, stage) => {
328
+ const chosen = kindOf(kind);
329
+ write(database, () => {
330
+ const pipeline = ensure(chosen);
331
+ const row = baseStageRow(pipeline, stage);
332
+ const id = Number(row.id);
333
+ const same = baseStagesOf(database, pipeline).filter((one) => one.outcome === row.outcome);
334
+ if (same.length === 1)
335
+ refuse(`${row.name} is the base set's only ${row.outcome} stage; add another first`, "stage.base-outcome");
336
+ const used = database
337
+ .prepare(`SELECT (SELECT count(*) FROM ${ITEM_TABLES[chosen]} WHERE stage_id = ?) + ` +
338
+ "(SELECT count(*) FROM pipeline_stage_changes WHERE from_stage_id = ? OR to_stage_id = ?) AS n")
339
+ .get(id, id, id);
340
+ if (Number(used?.n) > 0)
341
+ refuse(`the owner's own ${chosen}s stand or stood in ${row.name}; it stays`, "stage.base-in-use");
342
+ database
343
+ .prepare("UPDATE pipeline_stages SET base_stage_id = NULL, base_confirmed = 0 WHERE base_stage_id = ?")
344
+ .run(id);
345
+ database.prepare("DELETE FROM pipeline_stages WHERE id = ?").run(id);
346
+ reorder(chosen, baseStagesOf(database, pipeline).map((one) => Number(one.id)));
347
+ });
348
+ return show(chosen);
349
+ },
350
+ mappings: (filter = {}) => mappableRows(filter).map(mappingOf),
351
+ map: (stage, base, scope, { confirmed = true } = {}) => {
352
+ const id = /^stage:(\d+)$/.exec(stage.trim())?.[1];
353
+ if (id === undefined)
354
+ refuse(`a stage is named by its stage:<id> reference, as memo's \`stages list\` shows it; not ${stage}`, "stage.ref");
355
+ const kindRow = database
356
+ .prepare("SELECT p.kind FROM pipeline_stages s JOIN pipelines p ON p.id = s.pipeline_id WHERE s.id = ?")
357
+ .get(Number(id));
358
+ if (!kindRow)
359
+ throw new CliError("not_found", `no stage ${stage}`, { reason: "stage.not-found" });
360
+ const kind = kindRow.kind;
361
+ return write(database, () => {
362
+ const pipeline = ensure(kind);
363
+ const row = mappableRows({ ...scope, kind }, "s.id = ?", [Number(id)])[0];
364
+ if (!row)
365
+ throw new CliError("not_found", `${stage} is not a stage to map: a base stage, a deleted one or out of scope`, {
366
+ reason: "stage.not-found",
367
+ });
368
+ const target = baseStageRow(pipeline, base);
369
+ database
370
+ .prepare("UPDATE pipeline_stages SET base_stage_id = ?, base_confirmed = ?, updated_at = ? WHERE id = ?")
371
+ .run(Number(target.id), confirmed ? 1 : 0, now(), Number(id));
372
+ return mappingOf(mappableRows({ kind }, "s.id = ?", [Number(id)])[0]);
373
+ });
374
+ },
375
+ confirm: (target, scope) => write(database, () => {
376
+ const filter = "pipeline" in target
377
+ ? { ...scope, pipeline: target.pipeline, unconfirmed: true }
378
+ : { ...scope, ...(target.kind === undefined ? {} : { kind: target.kind }), unconfirmed: true };
379
+ for (const kind of filter.kind === undefined ? DEAL_KINDS : [filter.kind])
380
+ ensure(kind);
381
+ const rows = mappableRows(filter).filter((row) => row.base_id != null);
382
+ const set = database.prepare("UPDATE pipeline_stages SET base_confirmed = 1, updated_at = ? WHERE id = ?");
383
+ const at = now();
384
+ for (const row of rows)
385
+ set.run(at, Number(row.id));
386
+ return rows.length;
387
+ }),
388
+ resolve: (item, base) => {
389
+ const found = deals.get(item);
390
+ const pipeline = Number(found.pipeline.slice("pipeline:".length));
391
+ const candidateOf = (row) => ({
392
+ ref: stageRef(row.id),
393
+ name: String(row.name),
394
+ externalId: row.external_id == null ? null : String(row.external_id),
395
+ outcome: row.outcome,
396
+ });
397
+ // A candidate named back by its reference, after a choice-required answer, is the move itself.
398
+ const own = /^stage:(\d+)$/.exec(base.trim())?.[1];
399
+ const direct = own === undefined
400
+ ? undefined
401
+ : database
402
+ .prepare("SELECT * FROM pipeline_stages WHERE id = ? AND pipeline_id = ? AND deleted_at IS NULL")
403
+ .get(Number(own), pipeline);
404
+ if (direct)
405
+ return { stage: candidateOf(direct) };
406
+ const target = baseStageRow(ensure(found.kind), base);
407
+ const candidates = database
408
+ .prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ? AND base_confirmed = 1 AND base_stage_id = ? " +
409
+ "AND deleted_at IS NULL ORDER BY position, id")
410
+ .all(pipeline, Number(target.id))
411
+ .map(candidateOf);
412
+ if (candidates.length === 1)
413
+ return { stage: candidates[0] };
414
+ if (candidates.length > 1)
415
+ throw new CliError("validation_error", `more than one stage of ${found.pipelineName} maps to ${target.name}: ` +
416
+ `${candidates.map(({ name, ref }) => `${name} (${ref})`).join(", ")}; move to one of them by its reference`, {
417
+ reason: "stage.choice-required",
418
+ candidates: candidates.map(({ ref, name, externalId, outcome }) => ({
419
+ ref,
420
+ name,
421
+ external_id: externalId,
422
+ outcome,
423
+ })),
424
+ });
425
+ throw new CliError("validation_error", `no stage of ${found.pipelineName} (${found.pipeline}) is mapped to ${target.name}; map one with ` +
426
+ `memo's \`stages set <stage:id> ${stageRef(target.id)}\` (the stages: \`stages list pipeline:${found.pipeline}\`)`, { reason: "stage.unmapped" });
427
+ },
428
+ };
429
+ };
430
+ export const baseStagesStoreOver = (context) => {
431
+ const operations = baseStagesOver(context);
432
+ return {
433
+ show: async (kind, scope) => operations.show(kind, scope),
434
+ add: async (kind, input) => operations.add(kind, input),
435
+ rename: async (kind, stage, name) => operations.rename(kind, stage, name),
436
+ move: async (kind, stage, position) => operations.move(kind, stage, position),
437
+ remove: async (kind, stage) => operations.remove(kind, stage),
438
+ mappings: async (filter) => operations.mappings(filter),
439
+ map: async (stage, base, scope, options) => operations.map(stage, base, scope, options),
440
+ confirm: async (target, scope) => operations.confirm(target, scope),
441
+ resolve: async (item, base) => operations.resolve(item, base),
442
+ };
443
+ };
@@ -0,0 +1,13 @@
1
+ import type { DealKind } from "../../domain/deals.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ type Row = Record<string, unknown>;
4
+ export declare const baseSettingKey: (kind: DealKind) => string;
5
+ /** The set's pipeline, while the setting names an own, live pipeline of the kind. */
6
+ export declare const basePipelineOf: (database: CacheDatabase, kind: DealKind) => number | undefined;
7
+ export declare const baseStagesOf: (database: CacheDatabase, pipeline: number) => Row[];
8
+ /**
9
+ * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
10
+ * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
11
+ */
12
+ export declare const suggestBaseStages: (database: CacheDatabase, kind: DealKind, pipelines?: readonly number[]) => void;
13
+ export {};
@@ -0,0 +1,62 @@
1
+ export const baseSettingKey = (kind) => `stages.base.${kind}`;
2
+ const storedPipeline = (value) => {
3
+ if (typeof value !== "string")
4
+ return undefined;
5
+ const match = /^"pipeline:(\d+)"$/.exec(value);
6
+ return match ? Number(match[1]) : undefined;
7
+ };
8
+ /** The set's pipeline, while the setting names an own, live pipeline of the kind. */
9
+ export const basePipelineOf = (database, kind) => {
10
+ const id = storedPipeline(database.prepare("SELECT value FROM store_settings WHERE key = ?").get(baseSettingKey(kind))?.value);
11
+ if (id === undefined)
12
+ return undefined;
13
+ const row = database
14
+ .prepare("SELECT 1 FROM pipelines WHERE id = ? AND kind = ? AND account_id IS NULL AND deleted_at IS NULL")
15
+ .get(id, kind);
16
+ return row ? id : undefined;
17
+ };
18
+ export const baseStagesOf = (database, pipeline) => database.prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ? ORDER BY position, id").all(pipeline);
19
+ /**
20
+ * Suggests a base stage for every unconfirmed live stage of `pipelines` (every pipeline of the kind but the set's when absent): won and lost by outcome; an open one by its relative place among its pipeline's open stages, and when that
21
+ * falls between two base stages, the one of the same name, else the nearer. Does nothing before the set exists.
22
+ */
23
+ export const suggestBaseStages = (database, kind, pipelines) => {
24
+ const base = basePipelineOf(database, kind);
25
+ if (base === undefined)
26
+ return;
27
+ const stages = baseStagesOf(database, base);
28
+ const byOutcome = (outcome) => stages.filter((stage) => stage.outcome === outcome);
29
+ const open = byOutcome("open");
30
+ const ends = { won: byOutcome("won")[0], lost: byOutcome("lost")[0] };
31
+ const ids = pipelines ??
32
+ database
33
+ .prepare("SELECT id FROM pipelines WHERE kind = ? AND id <> ? AND deleted_at IS NULL")
34
+ .all(kind, base)
35
+ .map((row) => Number(row.id));
36
+ const update = database.prepare("UPDATE pipeline_stages SET base_stage_id = ? WHERE id = ? AND base_confirmed = 0 AND base_stage_id IS NOT ?");
37
+ for (const pipeline of ids) {
38
+ if (pipeline === base)
39
+ continue;
40
+ const own = database
41
+ .prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ? AND deleted_at IS NULL ORDER BY position, id")
42
+ .all(pipeline);
43
+ const ownOpen = own.filter((stage) => stage.outcome === "open");
44
+ for (const stage of own) {
45
+ let chosen;
46
+ if (stage.outcome === "open" && open.length > 0) {
47
+ const at = ownOpen.indexOf(stage);
48
+ const place = ownOpen.length === 1 ? 0 : (at / (ownOpen.length - 1)) * (open.length - 1);
49
+ const [below, above] = [open[Math.floor(place)], open[Math.ceil(place)]];
50
+ chosen =
51
+ below === above
52
+ ? below
53
+ : ([below, above].find((one) => one.name_folded === stage.name_folded) ??
54
+ (place - Math.floor(place) < 0.5 ? below : above));
55
+ }
56
+ else if (stage.outcome !== "open")
57
+ chosen = ends[stage.outcome];
58
+ const target = chosen === undefined ? null : Number(chosen.id);
59
+ update.run(target, Number(stage.id), target);
60
+ }
61
+ }
62
+ };
@@ -4,7 +4,9 @@ import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/mon
4
4
  import { proposedBySql } from "./actors.js";
5
5
  import { projectId } from "./memories.js";
6
6
  import { requiredThing } from "./notes.js";
7
+ import { recordRelationshipsOver } from "./record-relationships.js";
7
8
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
9
+ import { storedThing } from "./things.js";
8
10
  import { write } from "./transaction.js";
9
11
  const CONTRACTS = "SELECT k.*, b.name AS author_name, b.kind AS author_kind FROM contracts k " +
10
12
  "LEFT JOIN bots b ON k.author_type = 'bot' AND b.id = k.author_id";
@@ -66,6 +68,7 @@ const columnsOf = (fields, base) => {
66
68
  export const contractOperationsOver = (context) => {
67
69
  const { database, now } = context;
68
70
  const { reviewedOf, written, keepEvidence, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
71
+ const relationships = recordRelationshipsOver(context);
69
72
  const contractOf = (row) => {
70
73
  const currency = row.currency == null ? null : String(row.currency);
71
74
  const value = row.value == null || currency === null ? null : Number(row.value);
@@ -110,7 +113,13 @@ export const contractOperationsOver = (context) => {
110
113
  };
111
114
  const decide = (reference, by, reason, confirm) => {
112
115
  const row = rowOf(reference);
113
- decideRow("contract", row, { by, reason, confirm });
116
+ decideRow("contract", row, { by, reason, confirm }, {
117
+ // The owner's no outweighs the source: the parties an import reported go with it now, not on the next run.
118
+ after: (confirmer) => {
119
+ if (confirmer === null)
120
+ relationships.withdrawFrom(storedThing("contract", row.id));
121
+ },
122
+ });
114
123
  return contractOf(rowOf(`contract:${row.id}`));
115
124
  };
116
125
  return {
@@ -10,12 +10,15 @@ export interface StoreClient {
10
10
  }
11
11
  /** Readable from any schema: `store_settings` is in the initial migration. */
12
12
  export declare const storeClients: (database: CacheDatabase) => StoreClient[];
13
- /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
14
- export declare const recordClient: (database: CacheDatabase, { command, version, speaks }: {
13
+ type Client = {
15
14
  command: string;
16
15
  version: string;
17
16
  speaks: number;
18
- }, now: number) => void;
17
+ };
18
+ /** Whether `recordClient` would write nothing: the CLI's version, cli-core and schema are unchanged within a day. */
19
+ export declare const clientRecorded: (database: CacheDatabase, { command, version, speaks }: Client, now: number) => boolean;
20
+ /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
21
+ export declare const recordClient: (database: CacheDatabase, { command, version, speaks }: Client, now: number) => void;
19
22
  /** The sentence an upgrade that raised the store's minimum prints: who can no longer open it, and what to run. */
20
23
  export declare const lockedOutNotice: (clients: readonly StoreClient[], { command, schema, minCompatible }: {
21
24
  command?: string;
@@ -24,3 +27,4 @@ export declare const lockedOutNotice: (clients: readonly StoreClient[], { comman
24
27
  }) => string | undefined;
25
28
  /** Added to a refusal: this tool's own command, and the CLI that moved the store, so the owner knows what to run. */
26
29
  export declare const refusalAdvice: (clients: readonly StoreClient[], command: string | undefined, schema: number) => string;
30
+ export {};
@@ -38,18 +38,22 @@ export const storeClients = (database) => {
38
38
  return [];
39
39
  }
40
40
  };
41
- /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
42
- export const recordClient = (database, { command, version, speaks }, now) => {
41
+ /** Whether `recordClient` would write nothing: the CLI's version, cli-core and schema are unchanged within a day. */
42
+ export const clientRecorded = (database, { command, version, speaks }, now) => {
43
43
  if (!hasSettings(database))
44
- return;
45
- const stored = storeClients(database);
46
- const same = stored.find((one) => one.command === command);
47
- if (same &&
44
+ return true;
45
+ const same = storeClients(database).find((one) => one.command === command);
46
+ return (same !== undefined &&
48
47
  same.version === version &&
49
48
  same.core === coreVersion &&
50
49
  same.speaks === speaks &&
51
- now - same.seenAt < 86_400_000)
50
+ now - same.seenAt < 86_400_000);
51
+ };
52
+ /** Writes only when the CLI's version, cli-core or schema changed, or a day passed: every run calls it. */
53
+ export const recordClient = (database, { command, version, speaks }, now) => {
54
+ if (clientRecorded(database, { command, version, speaks }, now))
52
55
  return;
56
+ const stored = storeClients(database);
53
57
  const entry = { command, version, core: coreVersion, speaks, seenAt: now };
54
58
  database
55
59
  .prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
@@ -1,3 +1,4 @@
1
+ import { type CrmScopeSetting } from "../../domain/crm.js";
1
2
  import type { CacheDatabase } from "../driver.js";
2
3
  import type { AccountKey } from "../types.js";
3
4
  /** `reported`: what a CRM account says is a relationship nobody confirmed; `review`: it waits as a proposal. */
@@ -6,7 +7,9 @@ export type CrmLinkMode = (typeof CRM_LINK_MODES)[number];
6
7
  /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
7
8
  export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier", "partner-of"];
8
9
  export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
9
- declare const NAMES: readonly ["links", "company-types"];
10
+ /** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
11
+ export declare const CRM_SCOPES: readonly ["mine", "all"];
12
+ declare const NAMES: readonly ["links", "company-types", "scope", "unassigned", "self"];
10
13
  type CrmSettingName = (typeof NAMES)[number];
11
14
  export declare const crmSettingKey: (key: AccountKey, name: CrmSettingName) => string;
12
15
  /** The account and the setting a key names; a portal's account may hold dots, so it is read from both ends. */
@@ -18,7 +21,14 @@ export declare const parseCrmSetting: (setting: string) => {
18
21
  export declare const crmLinkMode: (database: CacheDatabase, key: AccountKey) => CrmLinkMode;
19
22
  /** Only the owner's mapping gives a company type a meaning; none by default. */
20
23
  export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
21
- /** `links`: reported or review; `company-types`: `TYPE=meaning` pairs, comma-separated. */
24
+ /** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
25
+ export declare const crmScope: (database: CacheDatabase, key: AccountKey) => CrmScopeSetting;
26
+ /**
27
+ * `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
28
+ * `company-types`: `TYPE=meaning` pairs, comma-separated.
29
+ */
30
+ /** The CRM user whose deals the account's copy holds: the first sync's sign-in, until the owner unsets it. */
31
+ export declare const crmOwnUser: (database: CacheDatabase, key: AccountKey) => string | undefined;
22
32
  export declare const parseCrmSettingValue: (name: CrmSettingName, value: string) => unknown;
23
33
  export declare const saveCrmSetting: (database: CacheDatabase, setting: string, value: unknown, now: number) => void;
24
34
  export declare const crmSettingsOf: (database: CacheDatabase) => {