@baack-software/baack-ts-crm 0.0.0-stage → 0.0.2

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 (219) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +74 -2
  3. package/dist/account.d.ts +36 -0
  4. package/dist/account.d.ts.map +1 -0
  5. package/dist/account.js +48 -0
  6. package/dist/account.js.map +1 -0
  7. package/dist/backend.d.ts +76 -0
  8. package/dist/backend.d.ts.map +1 -0
  9. package/dist/backend.js +233 -0
  10. package/dist/backend.js.map +1 -0
  11. package/dist/crm-client.d.ts +122 -0
  12. package/dist/crm-client.d.ts.map +1 -0
  13. package/dist/crm-client.js +168 -0
  14. package/dist/crm-client.js.map +1 -0
  15. package/dist/errors.d.ts +21 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +33 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/index.d.ts +13 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +13 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/invoices.d.ts +46 -0
  24. package/dist/invoices.d.ts.map +1 -0
  25. package/dist/invoices.js +137 -0
  26. package/dist/invoices.js.map +1 -0
  27. package/dist/leads.d.ts +29 -0
  28. package/dist/leads.d.ts.map +1 -0
  29. package/dist/leads.js +56 -0
  30. package/dist/leads.js.map +1 -0
  31. package/dist/mock/index.d.ts +43 -0
  32. package/dist/mock/index.d.ts.map +1 -0
  33. package/dist/mock/index.js +303 -0
  34. package/dist/mock/index.js.map +1 -0
  35. package/dist/money.d.ts +29 -0
  36. package/dist/money.d.ts.map +1 -0
  37. package/dist/money.js +82 -0
  38. package/dist/money.js.map +1 -0
  39. package/dist/period.d.ts +17 -0
  40. package/dist/period.d.ts.map +1 -0
  41. package/dist/period.js +23 -0
  42. package/dist/period.js.map +1 -0
  43. package/dist/pipeline.d.ts +30 -0
  44. package/dist/pipeline.d.ts.map +1 -0
  45. package/dist/pipeline.js +40 -0
  46. package/dist/pipeline.js.map +1 -0
  47. package/dist/react/Charts.d.ts +19 -0
  48. package/dist/react/Charts.d.ts.map +1 -0
  49. package/dist/react/Charts.js +38 -0
  50. package/dist/react/Charts.js.map +1 -0
  51. package/dist/react/CompanyAccountView.d.ts +21 -0
  52. package/dist/react/CompanyAccountView.d.ts.map +1 -0
  53. package/dist/react/CompanyAccountView.js +27 -0
  54. package/dist/react/CompanyAccountView.js.map +1 -0
  55. package/dist/react/DashboardCards.d.ts +32 -0
  56. package/dist/react/DashboardCards.d.ts.map +1 -0
  57. package/dist/react/DashboardCards.js +38 -0
  58. package/dist/react/DashboardCards.js.map +1 -0
  59. package/dist/react/DealsBoard.d.ts +30 -0
  60. package/dist/react/DealsBoard.d.ts.map +1 -0
  61. package/dist/react/DealsBoard.js +33 -0
  62. package/dist/react/DealsBoard.js.map +1 -0
  63. package/dist/react/Details.d.ts +52 -0
  64. package/dist/react/Details.d.ts.map +1 -0
  65. package/dist/react/Details.js +111 -0
  66. package/dist/react/Details.js.map +1 -0
  67. package/dist/react/Forms.d.ts +59 -0
  68. package/dist/react/Forms.d.ts.map +1 -0
  69. package/dist/react/Forms.js +204 -0
  70. package/dist/react/Forms.js.map +1 -0
  71. package/dist/react/LeadsTable.d.ts +22 -0
  72. package/dist/react/LeadsTable.d.ts.map +1 -0
  73. package/dist/react/LeadsTable.js +79 -0
  74. package/dist/react/LeadsTable.js.map +1 -0
  75. package/dist/react/Sales.d.ts +49 -0
  76. package/dist/react/Sales.d.ts.map +1 -0
  77. package/dist/react/Sales.js +186 -0
  78. package/dist/react/Sales.js.map +1 -0
  79. package/dist/react/SidePanel.d.ts +21 -0
  80. package/dist/react/SidePanel.d.ts.map +1 -0
  81. package/dist/react/SidePanel.js +37 -0
  82. package/dist/react/SidePanel.js.map +1 -0
  83. package/dist/react/format.d.ts +28 -0
  84. package/dist/react/format.d.ts.map +1 -0
  85. package/dist/react/format.js +30 -0
  86. package/dist/react/format.js.map +1 -0
  87. package/dist/react/index.d.ts +14 -0
  88. package/dist/react/index.d.ts.map +1 -0
  89. package/dist/react/index.js +14 -0
  90. package/dist/react/index.js.map +1 -0
  91. package/dist/react/parts.d.ts +45 -0
  92. package/dist/react/parts.d.ts.map +1 -0
  93. package/dist/react/parts.js +59 -0
  94. package/dist/react/parts.js.map +1 -0
  95. package/dist/react/text.d.ts +145 -0
  96. package/dist/react/text.d.ts.map +1 -0
  97. package/dist/react/text.js +142 -0
  98. package/dist/react/text.js.map +1 -0
  99. package/dist/react/ui/alert.d.ts +11 -0
  100. package/dist/react/ui/alert.d.ts.map +1 -0
  101. package/dist/react/ui/alert.js +29 -0
  102. package/dist/react/ui/alert.js.map +1 -0
  103. package/dist/react/ui/badge.d.ts +10 -0
  104. package/dist/react/ui/badge.d.ts.map +1 -0
  105. package/dist/react/ui/badge.js +26 -0
  106. package/dist/react/ui/badge.js.map +1 -0
  107. package/dist/react/ui/button.d.ts +11 -0
  108. package/dist/react/ui/button.d.ts.map +1 -0
  109. package/dist/react/ui/button.js +37 -0
  110. package/dist/react/ui/button.js.map +1 -0
  111. package/dist/react/ui/card.d.ts +12 -0
  112. package/dist/react/ui/card.d.ts.map +1 -0
  113. package/dist/react/ui/card.js +26 -0
  114. package/dist/react/ui/card.js.map +1 -0
  115. package/dist/react/ui/chart.d.ts +45 -0
  116. package/dist/react/ui/chart.d.ts.map +1 -0
  117. package/dist/react/ui/chart.js +116 -0
  118. package/dist/react/ui/chart.js.map +1 -0
  119. package/dist/react/ui/input.d.ts +4 -0
  120. package/dist/react/ui/input.d.ts.map +1 -0
  121. package/dist/react/ui/input.js +8 -0
  122. package/dist/react/ui/input.js.map +1 -0
  123. package/dist/react/ui/label.d.ts +5 -0
  124. package/dist/react/ui/label.d.ts.map +1 -0
  125. package/dist/react/ui/label.js +10 -0
  126. package/dist/react/ui/label.js.map +1 -0
  127. package/dist/react/ui/progress.d.ts +5 -0
  128. package/dist/react/ui/progress.d.ts.map +1 -0
  129. package/dist/react/ui/progress.js +10 -0
  130. package/dist/react/ui/progress.js.map +1 -0
  131. package/dist/react/ui/select.d.ts +16 -0
  132. package/dist/react/ui/select.d.ts.map +1 -0
  133. package/dist/react/ui/select.js +37 -0
  134. package/dist/react/ui/select.js.map +1 -0
  135. package/dist/react/ui/separator.d.ts +5 -0
  136. package/dist/react/ui/separator.d.ts.map +1 -0
  137. package/dist/react/ui/separator.js +10 -0
  138. package/dist/react/ui/separator.js.map +1 -0
  139. package/dist/react/ui/sheet.d.ts +15 -0
  140. package/dist/react/ui/sheet.d.ts.map +1 -0
  141. package/dist/react/ui/sheet.js +38 -0
  142. package/dist/react/ui/sheet.js.map +1 -0
  143. package/dist/react/ui/skeleton.d.ts +3 -0
  144. package/dist/react/ui/skeleton.d.ts.map +1 -0
  145. package/dist/react/ui/skeleton.js +7 -0
  146. package/dist/react/ui/skeleton.js.map +1 -0
  147. package/dist/react/ui/table.d.ts +11 -0
  148. package/dist/react/ui/table.d.ts.map +1 -0
  149. package/dist/react/ui/table.js +29 -0
  150. package/dist/react/ui/table.js.map +1 -0
  151. package/dist/react/ui/tabs.d.ts +12 -0
  152. package/dist/react/ui/tabs.d.ts.map +1 -0
  153. package/dist/react/ui/tabs.js +31 -0
  154. package/dist/react/ui/tabs.js.map +1 -0
  155. package/dist/react/views.d.ts +60 -0
  156. package/dist/react/views.d.ts.map +1 -0
  157. package/dist/react/views.js +172 -0
  158. package/dist/react/views.js.map +1 -0
  159. package/dist/sales.d.ts +57 -0
  160. package/dist/sales.d.ts.map +1 -0
  161. package/dist/sales.js +64 -0
  162. package/dist/sales.js.map +1 -0
  163. package/dist/store.d.ts +140 -0
  164. package/dist/store.d.ts.map +1 -0
  165. package/dist/store.js +244 -0
  166. package/dist/store.js.map +1 -0
  167. package/dist/target.d.ts +21 -0
  168. package/dist/target.d.ts.map +1 -0
  169. package/dist/target.js +36 -0
  170. package/dist/target.js.map +1 -0
  171. package/dist/types.d.ts +180 -0
  172. package/dist/types.d.ts.map +1 -0
  173. package/dist/types.js +2 -0
  174. package/dist/types.js.map +1 -0
  175. package/package.json +100 -4
  176. package/src/account.ts +79 -0
  177. package/src/backend.ts +371 -0
  178. package/src/crm-client.ts +250 -0
  179. package/src/errors.ts +34 -0
  180. package/src/index.ts +12 -0
  181. package/src/invoices.ts +157 -0
  182. package/src/leads.ts +78 -0
  183. package/src/mock/index.ts +398 -0
  184. package/src/money.ts +104 -0
  185. package/src/period.ts +32 -0
  186. package/src/pipeline.ts +61 -0
  187. package/src/react/Charts.tsx +143 -0
  188. package/src/react/CompanyAccountView.tsx +198 -0
  189. package/src/react/DashboardCards.tsx +171 -0
  190. package/src/react/DealsBoard.tsx +177 -0
  191. package/src/react/Details.tsx +293 -0
  192. package/src/react/Forms.tsx +619 -0
  193. package/src/react/LeadsTable.tsx +234 -0
  194. package/src/react/Sales.tsx +539 -0
  195. package/src/react/SidePanel.tsx +95 -0
  196. package/src/react/format.ts +53 -0
  197. package/src/react/index.ts +13 -0
  198. package/src/react/parts.tsx +131 -0
  199. package/src/react/text.ts +144 -0
  200. package/src/react/ui/README.md +6 -0
  201. package/src/react/ui/alert.tsx +75 -0
  202. package/src/react/ui/badge.tsx +48 -0
  203. package/src/react/ui/button.tsx +66 -0
  204. package/src/react/ui/card.tsx +102 -0
  205. package/src/react/ui/chart.tsx +304 -0
  206. package/src/react/ui/input.tsx +18 -0
  207. package/src/react/ui/label.tsx +23 -0
  208. package/src/react/ui/progress.tsx +30 -0
  209. package/src/react/ui/select.tsx +189 -0
  210. package/src/react/ui/separator.tsx +27 -0
  211. package/src/react/ui/sheet.tsx +145 -0
  212. package/src/react/ui/skeleton.tsx +13 -0
  213. package/src/react/ui/table.tsx +113 -0
  214. package/src/react/ui/tabs.tsx +89 -0
  215. package/src/react/views.tsx +443 -0
  216. package/src/sales.ts +120 -0
  217. package/src/store.ts +419 -0
  218. package/src/target.ts +51 -0
  219. package/src/types.ts +202 -0
package/src/store.ts ADDED
@@ -0,0 +1,419 @@
1
+ import type { Company } from '@baack-software/baack-ts-client';
2
+ import { urnOf, type RefLike } from '@baack-software/baack-ts-tasks';
3
+ import { companyAccount, type CompanyAccount } from './account.ts';
4
+ import type { DealInput, InvoiceInput, LeadInput, RemittanceInput } from './backend.ts';
5
+ import type { ConvertOptions, CrmClient, NewLeadOptions } from './crm-client.ts';
6
+ import { CrmUnavailableError } from './errors.ts';
7
+ import { leadsBySource, type SourceCount } from './leads.ts';
8
+ import { addMoney, type MoneyTotals } from './money.ts';
9
+ import { inRange, periodChange, previousRange, type DateRange } from './period.ts';
10
+ import { dealCompany, dealOutcome, pipelineByStage, type StageSummary } from './pipeline.ts';
11
+ import { paymentsByDay, paymentsReceived } from './invoices.ts';
12
+ import { salesSummary, type SalesSummary } from './sales.ts';
13
+ import { salesTarget, type SalesTarget } from './target.ts';
14
+ import {
15
+ CRM_CONCEPTS,
16
+ type CrmConcept,
17
+ type Deal,
18
+ type DealOutcome,
19
+ type Invoice,
20
+ type Lead,
21
+ type LeadOutcome,
22
+ type Pipeline,
23
+ type PipelineStage,
24
+ type Remittance,
25
+ } from './types.ts';
26
+
27
+ export interface CrmStoreOptions {
28
+ /** The company whose CRM the store holds. */
29
+ owner: RefLike;
30
+ }
31
+
32
+ export type LoadStatus = 'idle' | 'loading' | 'ready' | 'error';
33
+
34
+ /** How one concept loaded. `unavailable`: the API doesn't have it yet and it isn't served from sample data. */
35
+ export interface ConceptState {
36
+ status: LoadStatus | 'unavailable';
37
+ error?: unknown;
38
+ }
39
+
40
+ /** A snapshot of the store. Each change replaces it, so it can be compared by reference. */
41
+ export interface CrmStoreState {
42
+ /** `ready` once every concept has loaded or been found unavailable; `error` if any failed otherwise. */
43
+ status: LoadStatus;
44
+ concepts: Readonly<Record<CrmConcept, ConceptState>>;
45
+ leads: readonly Lead[];
46
+ deals: readonly Deal[];
47
+ pipelines: readonly Pipeline[];
48
+ invoices: readonly Invoice[];
49
+ remittances: readonly Remittance[];
50
+ /** Client companies made while the store was open, such as a converted lead's prospect, with their names. */
51
+ companies: readonly Company[];
52
+ /** URNs of records with a write in flight. */
53
+ saving: ReadonlySet<string>;
54
+ /** The last write the server refused, until the next write. */
55
+ writeError?: unknown;
56
+ }
57
+
58
+ type Records = Pick<CrmStoreState, CrmConcept | 'companies'>;
59
+
60
+ const idle = Object.fromEntries(CRM_CONCEPTS.map((concept) => [concept, { status: 'idle' }])) as Record<
61
+ CrmConcept,
62
+ ConceptState
63
+ >;
64
+
65
+ const EMPTY: CrmStoreState = {
66
+ status: 'idle',
67
+ concepts: idle,
68
+ leads: [],
69
+ deals: [],
70
+ pipelines: [],
71
+ invoices: [],
72
+ remittances: [],
73
+ companies: [],
74
+ saving: new Set(),
75
+ };
76
+
77
+ let pendingCount = 0;
78
+
79
+ /**
80
+ * Holds a company's CRM records for a UI: loads every concept, applies changes straight away and rolls them back if
81
+ * the server refuses, and notifies subscribers. `subscribe` and `getState` fit React's `useSyncExternalStore`.
82
+ *
83
+ * ```ts
84
+ * const store = new CrmStore(crm, { owner });
85
+ * store.subscribe(() => render(selectDashboard(store.getState(), lastDays(28))));
86
+ * await store.load();
87
+ * await store.moveDeal(dealUrn, stage);
88
+ * ```
89
+ */
90
+ export class CrmStore {
91
+ #state: CrmStoreState = EMPTY;
92
+ readonly #listeners = new Set<() => void>();
93
+ #disposed = false;
94
+
95
+ constructor(
96
+ readonly client: CrmClient,
97
+ readonly options: CrmStoreOptions,
98
+ ) {}
99
+
100
+ getState = (): CrmStoreState => this.#state;
101
+
102
+ subscribe = (listener: () => void): (() => void) => {
103
+ this.#listeners.add(listener);
104
+ return () => this.#listeners.delete(listener);
105
+ };
106
+
107
+ /** Drops subscribers; answers still arriving are ignored. */
108
+ dispose(): void {
109
+ this.#disposed = true;
110
+ this.#listeners.clear();
111
+ }
112
+
113
+ #set(next: Partial<CrmStoreState>): void {
114
+ if (this.#disposed) return;
115
+ this.#state = { ...this.#state, ...next };
116
+ for (const listener of this.#listeners) listener();
117
+ }
118
+
119
+ // ==========================================
120
+ // LOADING
121
+ // ==========================================
122
+
123
+ /** Loads (or reloads) every concept at once. A concept that fails doesn't stop the others. */
124
+ async load(): Promise<void> {
125
+ const owner = urnOf(this.options.owner);
126
+ const loading = Object.fromEntries(CRM_CONCEPTS.map((concept) => [concept, { status: 'loading' }])) as Record<
127
+ CrmConcept,
128
+ ConceptState
129
+ >;
130
+ this.#set({ status: 'loading', concepts: loading });
131
+ await Promise.all(
132
+ CRM_CONCEPTS.map(async (concept) => {
133
+ try {
134
+ const records = await this.client[concept].list(owner);
135
+ this.#set({ [concept]: records, concepts: { ...this.#state.concepts, [concept]: { status: 'ready' } } });
136
+ } catch (error) {
137
+ const status = error instanceof CrmUnavailableError ? 'unavailable' : 'error';
138
+ this.#set({ concepts: { ...this.#state.concepts, [concept]: { status, error } } });
139
+ }
140
+ }),
141
+ );
142
+ const failed = Object.values(this.#state.concepts).some((state) => state.status === 'error');
143
+ this.#set({ status: failed ? 'error' : 'ready' });
144
+ }
145
+
146
+ // ==========================================
147
+ // WRITES
148
+ // ==========================================
149
+
150
+ /** Shows `optimistic` at once, runs `write`, then shows what the server stored, or rolls back if it refuses. */
151
+ async #write<T>(
152
+ urns: string[],
153
+ optimistic: (records: Records) => Partial<Records>,
154
+ write: () => Promise<T>,
155
+ stored: (records: Records, result: T) => Partial<Records>,
156
+ ): Promise<T> {
157
+ const before: Records = this.#records();
158
+ this.#set({ ...optimistic(before), saving: new Set([...this.#state.saving, ...urns]), writeError: undefined });
159
+ const saved = () => new Set([...this.#state.saving].filter((urn) => !urns.includes(urn)));
160
+ try {
161
+ const result = await write();
162
+ this.#set({ ...stored(this.#records(), result), saving: saved() });
163
+ return result;
164
+ } catch (error) {
165
+ this.#set({ ...before, saving: saved(), writeError: error });
166
+ throw error;
167
+ }
168
+ }
169
+
170
+ #records(): Records {
171
+ const { leads, deals, pipelines, invoices, remittances, companies } = this.#state;
172
+ return { leads, deals, pipelines, invoices, remittances, companies };
173
+ }
174
+
175
+ /**
176
+ * Creates a lead, shown at the top straight away. With `companyName`, the prospect's company is made first and linked
177
+ * (see `CrmClient.createLead`).
178
+ */
179
+ async createLead(input: LeadInput, options: NewLeadOptions = {}): Promise<Lead> {
180
+ const temporary = `pending-${++pendingCount}`;
181
+ const placeholder: Lead = { ...input, urn: temporary, createdTimestamp: '' };
182
+ const { lead } = await this.#write(
183
+ [temporary],
184
+ ({ leads }) => ({ leads: [placeholder, ...leads] }),
185
+ () => this.client.createLead(input, options),
186
+ ({ leads, companies }, result) => ({
187
+ leads: leads.map((candidate) => (candidate.urn === temporary ? result.lead : candidate)),
188
+ ...(result.company ? { companies: [...companies, result.company] } : {}),
189
+ }),
190
+ );
191
+ return lead;
192
+ }
193
+
194
+ /** Changes a lead. */
195
+ updateLead(lead: RefLike, changes: Partial<LeadInput>): Promise<Lead> {
196
+ const urn = urnOf(lead);
197
+ return this.#write(
198
+ [urn],
199
+ ({ leads }) => ({ leads: replace(leads, urn, (current) => ({ ...current, ...changes })) }),
200
+ () => this.client.leads.update(urn, changes),
201
+ ({ leads }, updated) => ({ leads: replace(leads, urn, () => updated) }),
202
+ );
203
+ }
204
+
205
+ /** Qualifies a lead into a deal (see `CrmClient.convertLead`). Shown once the server has made the deal. */
206
+ async convertLead(lead: RefLike, options: ConvertOptions): Promise<{ lead: Lead; deal: Deal; company?: Company }> {
207
+ const urn = urnOf(lead);
208
+ const current = this.#state.leads.find((candidate) => candidate.urn === urn);
209
+ if (!current) throw new Error(`No lead ${urn} in the store`);
210
+ return this.#write(
211
+ [urn],
212
+ () => ({}),
213
+ () => this.client.convertLead(current, options),
214
+ ({ leads, deals, companies }, result) => ({
215
+ leads: replace(leads, urn, () => result.lead),
216
+ deals: [result.deal, ...deals],
217
+ ...(result.company ? { companies: [...companies, result.company] } : {}),
218
+ }),
219
+ );
220
+ }
221
+
222
+ /** Moves a deal to a stage, shown at once (see `CrmClient.moveDeal`). */
223
+ moveDeal(deal: RefLike, stage: PipelineStage): Promise<Deal> {
224
+ const urn = urnOf(deal);
225
+ return this.#write(
226
+ [urn],
227
+ ({ deals }) => ({ deals: replace(deals, urn, (current) => ({ ...current, workflowStage: { urn: stage.urn } })) }),
228
+ () => this.client.moveDeal(urn, stage),
229
+ ({ deals }, moved) => ({ deals: replace(deals, urn, () => moved) }),
230
+ );
231
+ }
232
+
233
+ /** Wins, loses or reopens a deal, shown at once (see `CrmClient.setOutcome`). */
234
+ setOutcome(deal: RefLike, outcome: DealOutcome, options: { lostReason?: string } = {}): Promise<Deal> {
235
+ const urn = urnOf(deal);
236
+ return this.#write(
237
+ [urn],
238
+ ({ deals }) => ({ deals: replace(deals, urn, (current) => ({ ...current, outcome })) }),
239
+ () => this.client.setOutcome(urn, outcome, options),
240
+ ({ deals }, stored) => ({ deals: replace(deals, urn, () => stored) }),
241
+ );
242
+ }
243
+
244
+ /** Closes a lead as unqualified or reopens it, shown at once (see `CrmClient.setLeadOutcome`). */
245
+ setLeadOutcome(
246
+ lead: RefLike,
247
+ outcome: Exclude<LeadOutcome, 'CONVERTED'>,
248
+ options: { closedReason?: string } = {},
249
+ ): Promise<Lead> {
250
+ const urn = urnOf(lead);
251
+ return this.#write(
252
+ [urn],
253
+ ({ leads }) => ({ leads: replace(leads, urn, (current) => ({ ...current, outcome })) }),
254
+ () => this.client.setLeadOutcome(urn, outcome, options),
255
+ ({ leads }, stored) => ({ leads: replace(leads, urn, () => stored) }),
256
+ );
257
+ }
258
+
259
+ /** Creates a deal, shown on the board straight away. */
260
+ createDeal(input: DealInput): Promise<Deal> {
261
+ const temporary = `pending-${++pendingCount}`;
262
+ const placeholder: Deal = { ...input, urn: temporary, createdTimestamp: '' };
263
+ return this.#write(
264
+ [temporary],
265
+ ({ deals }) => ({ deals: [placeholder, ...deals] }),
266
+ () => this.client.createDeal(input),
267
+ ({ deals }, made) => ({ deals: deals.map((candidate) => (candidate.urn === temporary ? made : candidate)) }),
268
+ );
269
+ }
270
+
271
+ /**
272
+ * Creates an invoice with its lines, linked to `deal` when given (see `CrmClient.createInvoice`). Shown once the
273
+ * server has made it, as its lines are made one by one.
274
+ */
275
+ async createInvoice(
276
+ input: InvoiceInput,
277
+ lines: Parameters<CrmClient['createInvoice']>[1] = [],
278
+ options: { deal?: Deal } = {},
279
+ ): Promise<Invoice> {
280
+ const { invoice } = await this.#write(
281
+ options.deal ? [options.deal.urn] : [],
282
+ () => ({}),
283
+ () => this.client.createInvoice(input, lines, options),
284
+ ({ invoices, deals }, result) => ({
285
+ invoices: [result.invoice, ...invoices],
286
+ ...(result.deal ? { deals: replace(deals, result.deal.urn, () => result.deal!) } : {}),
287
+ }),
288
+ );
289
+ return invoice;
290
+ }
291
+
292
+ /** Records a payment or refund against an invoice. */
293
+ recordPayment(input: RemittanceInput): Promise<Remittance> {
294
+ const temporary = `pending-${++pendingCount}`;
295
+ return this.#write(
296
+ [temporary],
297
+ ({ remittances }) => ({ remittances: [{ ...input, urn: temporary }, ...remittances] }),
298
+ () => this.client.recordPayment(input),
299
+ ({ remittances }, made) => ({
300
+ remittances: remittances.map((candidate) => (candidate.urn === temporary ? made : candidate)),
301
+ }),
302
+ );
303
+ }
304
+ }
305
+
306
+ function replace<T extends { urn: string }>(records: readonly T[], urn: string, change: (record: T) => T): T[] {
307
+ return records.map((record) => (record.urn === urn ? change(record) : record));
308
+ }
309
+
310
+ // ==========================================
311
+ // SELECTORS
312
+ // ==========================================
313
+
314
+ /** A number now and in the period before, with the change between them (undefined with nothing before). */
315
+ export interface Compared<T> {
316
+ current: T;
317
+ previous: T;
318
+ change: number | undefined;
319
+ }
320
+
321
+ export interface Dashboard {
322
+ range: DateRange;
323
+ /** Companies with a won deal; compared: companies whose first won deal closed in each period. */
324
+ customers: { total: number; added: Compared<number> };
325
+ /** Open deals and their value; compared: deals created in each period. */
326
+ openDeals: { count: number; value: MoneyTotals; created: Compared<number> };
327
+ /** Payments received less refunds, in each period. */
328
+ revenue: Compared<MoneyTotals> & { currencyCode: string | undefined };
329
+ /** Payments received less refunds on each day of the period. */
330
+ revenueByDay: { day: string; totals: MoneyTotals }[];
331
+ /** Leads created in each period. */
332
+ newLeads: Compared<number>;
333
+ target: SalesTarget;
334
+ leadsBySource: SourceCount[];
335
+ /** The first pipeline's stages. */
336
+ pipeline: StageSummary[];
337
+ }
338
+
339
+ const compare = (current: number, previous: number): Compared<number> => ({
340
+ current,
341
+ previous,
342
+ change: periodChange(current, previous),
343
+ });
344
+
345
+ /** The largest currency in a set of totals. */
346
+ export const mainCurrency = (totals: MoneyTotals): string | undefined =>
347
+ Object.entries(totals).sort(([, a], [, b]) => b - a)[0]?.[0];
348
+
349
+ /** Everything a CRM dashboard shows for a period, compared with the period before. */
350
+ export function selectDashboard(state: CrmStoreState, range: DateRange): Dashboard {
351
+ const before = previousRange(range);
352
+ const { leads, deals, pipelines, remittances } = state;
353
+
354
+ const firstWins = new Map<string, string>();
355
+ let openValue: MoneyTotals = {};
356
+ let openCount = 0;
357
+ for (const deal of deals) {
358
+ const outcome = dealOutcome(deal);
359
+ if (outcome === 'OPEN') {
360
+ openCount += 1;
361
+ openValue = addMoney(openValue, deal.targetValue);
362
+ }
363
+ const company = dealCompany(deal)?.urn;
364
+ if (outcome === 'WON' && company) {
365
+ const closed = deal.closeTimestamp ?? deal.updatedTimestamp ?? deal.createdTimestamp;
366
+ const known = firstWins.get(company);
367
+ if (!known || closed < known) firstWins.set(company, closed);
368
+ }
369
+ }
370
+ const count = <T>(records: Iterable<T>, when: (record: T) => string | null | undefined, period: DateRange) =>
371
+ [...records].filter((record) => inRange(when(record), period)).length;
372
+ const wins = [...firstWins.values()];
373
+ const current = paymentsReceived(remittances, range);
374
+ const previous = paymentsReceived(remittances, before);
375
+ const revenueCurrency = mainCurrency(current) ?? mainCurrency(previous);
376
+
377
+ return {
378
+ range,
379
+ customers: {
380
+ total: firstWins.size,
381
+ added: compare(
382
+ count(wins, (when) => when, range),
383
+ count(wins, (when) => when, before),
384
+ ),
385
+ },
386
+ openDeals: {
387
+ count: openCount,
388
+ value: openValue,
389
+ created: compare(
390
+ count(deals, (deal) => deal.createdTimestamp, range),
391
+ count(deals, (deal) => deal.createdTimestamp, before),
392
+ ),
393
+ },
394
+ revenue: {
395
+ current,
396
+ previous,
397
+ currencyCode: revenueCurrency,
398
+ change: revenueCurrency ? periodChange(current[revenueCurrency] ?? 0, previous[revenueCurrency] ?? 0) : undefined,
399
+ },
400
+ revenueByDay: paymentsByDay(remittances, range),
401
+ newLeads: compare(
402
+ count(leads, (lead) => lead.createdTimestamp, range),
403
+ count(leads, (lead) => lead.createdTimestamp, before),
404
+ ),
405
+ target: salesTarget(leads, deals, remittances),
406
+ leadsBySource: leadsBySource(leads),
407
+ pipeline: pipelines[0] ? pipelineByStage(deals, pipelines[0]) : [],
408
+ };
409
+ }
410
+
411
+ /** One customer company's account from the store's records. */
412
+ export function selectAccount(state: CrmStoreState, company: RefLike, now = new Date()): CompanyAccount {
413
+ return companyAccount(urnOf(company), state, now);
414
+ }
415
+
416
+ /** Sales for a period from the store's invoices and payments (see `salesSummary`). */
417
+ export function selectSales(state: CrmStoreState, range: DateRange, now = new Date()): SalesSummary {
418
+ return salesSummary(state, range, now);
419
+ }
package/src/target.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { addMoney, type MoneyTotals } from './money.ts';
2
+ import { paymentsReceived } from './invoices.ts';
3
+ import { leadOutcome } from './leads.ts';
4
+ import { dealOutcome } from './pipeline.ts';
5
+ import type { Deal, Lead, Remittance } from './types.ts';
6
+
7
+ export interface SalesTarget {
8
+ /** The target per currency: leads' target values, each qualified lead's replaced by its deal's. */
9
+ target: MoneyTotals;
10
+ /** Won deals' target values per currency. */
11
+ won: MoneyTotals;
12
+ /** Payments received less refunds on the deals' invoices, per currency. */
13
+ received: MoneyTotals;
14
+ /** Received against target per currency, 0 to 1 (more than 1 past the target). */
15
+ progress: Readonly<Record<string, number>>;
16
+ }
17
+
18
+ /**
19
+ * The sales target and progress towards it. The target is the sum of the leads' target values, using the deal's target
20
+ * value instead once a lead is qualified into a deal. Deals created without a lead count too, as they're qualified
21
+ * already; unqualified leads don't. Lost deals stay in the target, so losing one doesn't make progress look better.
22
+ * Progress is the payments received against the target (decided 24 Oct 2026): money in on the invoices raised for the
23
+ * deals (`Deal.invoices`), refunds taken off. Payments on invoices without a deal, such as repeat orders, don't count.
24
+ */
25
+ export function salesTarget(
26
+ leads: readonly Lead[],
27
+ deals: readonly Deal[],
28
+ remittances: readonly Remittance[],
29
+ ): SalesTarget {
30
+ const fromLeads = new Set(deals.flatMap((deal) => (deal.leadSource ? [deal.leadSource.urn] : [])));
31
+ let target: MoneyTotals = {};
32
+ let won: MoneyTotals = {};
33
+ for (const deal of deals) {
34
+ target = addMoney(target, deal.targetValue);
35
+ if (dealOutcome(deal) === 'WON') won = addMoney(won, deal.targetValue);
36
+ }
37
+ for (const lead of leads) {
38
+ if (leadOutcome(lead) === 'CLOSED') continue;
39
+ // A lead that became one of these deals (its leadSource) is counted by its deal's value above.
40
+ if (fromLeads.has(lead.urn)) continue;
41
+ target = addMoney(target, lead.targetValue);
42
+ }
43
+ const invoiced = new Set(deals.flatMap((deal) => deal.invoices.map((invoice) => invoice.urn)));
44
+ const received = paymentsReceived(remittances.filter((remittance) => invoiced.has(remittance.paymentInvoice.urn)));
45
+ const progress = Object.fromEntries(
46
+ Object.entries(target)
47
+ .filter(([, minor]) => minor > 0)
48
+ .map(([currency, minor]) => [currency, (received[currency] ?? 0) / minor]),
49
+ );
50
+ return { target, won, received, progress };
51
+ }
package/src/types.ts ADDED
@@ -0,0 +1,202 @@
1
+ import type { Workflow, WorkflowStage } from '@baack-software/baack-ts-client';
2
+ import type { Ref } from '@baack-software/baack-ts-tasks';
3
+
4
+ /*
5
+ * CRM concepts, named as the Baack API names them (leads, deals and payment invoices are in the API from 26 Oct 2026;
6
+ * remittances are still a proposal, see docs/PLAN.md). Links are refs (`{ urn }`), as the API's shallow links are.
7
+ */
8
+
9
+ /**
10
+ * An amount of money in whole minor units (pence, cents), as content money items write it: `unitValue: 125000` with
11
+ * `currencyCode: "GBP"` is 1,250.00 GBP. `formattedValue` is the server's text for it, when it sends one. Decided
12
+ * 24 Oct 2026; invoices move to the same format.
13
+ */
14
+ export interface Money {
15
+ unitValue: number;
16
+ /** An ISO 4217 code such as `GBP`. */
17
+ currencyCode: string;
18
+ formattedValue?: string | null;
19
+ }
20
+
21
+ /** Where a lead came from. */
22
+ export type LeadSource = 'WEBSITE' | 'REFERRAL' | 'SOCIAL' | 'EMAIL' | 'CALL' | 'ADS' | 'EVENT' | 'UNKNOWN';
23
+
24
+ /** How far a lead has got: only progress. How it ended is its `outcome`. */
25
+ export type LeadStatus = 'NEW' | 'CONTACTED' | 'QUALIFIED';
26
+
27
+ /**
28
+ * How a lead ended, as a deal's outcome does: still being worked, converted into a deal (a lead's won), or closed as
29
+ * unqualified (a lead's lost).
30
+ */
31
+ export type LeadOutcome = 'IN_PROGRESS' | 'CONVERTED' | 'CLOSED';
32
+
33
+ /**
34
+ * A prospect who hasn't been qualified yet. People are always identities, so their names are held securely as person
35
+ * names: a lead links a contact identity rather than holding a name, and a business by its contact company, whose name
36
+ * is the company's. A lead converted into a deal is the deal's `leadSource`.
37
+ */
38
+ export interface Lead {
39
+ urn: string;
40
+ url?: string | null;
41
+ /** The company whose lead this is. */
42
+ owner: Ref;
43
+ /** What the lead is about, for example "Club robes for the spring season". */
44
+ title: string;
45
+ /** The person, as an identity. */
46
+ contactIdentity?: Ref | null;
47
+ /** The prospect's company, which holds its name. A consumer's lead has none. */
48
+ contactCompany?: Ref | null;
49
+ source: LeadSource;
50
+ status: LeadStatus;
51
+ /** In progress, converted or closed. In progress when absent. */
52
+ outcome?: LeadOutcome | null;
53
+ /** What the lead could be worth. Counts towards the sales target until the lead is converted into a deal. */
54
+ targetValue?: Money | null;
55
+ /** Who's working the lead. */
56
+ assignee?: Ref | null;
57
+ /** Why the lead was closed as unqualified. */
58
+ closedReason?: string | null;
59
+ /** A content entity for the business's own fields about the lead, as companies have. */
60
+ entity?: Ref | null;
61
+ createdTimestamp: string;
62
+ updatedTimestamp?: string | null;
63
+ }
64
+
65
+ /** How a deal stands: still open, won or lost. */
66
+ export type DealOutcome = 'OPEN' | 'WON' | 'LOST';
67
+
68
+ /**
69
+ * A deal pipeline: any workflow. Workflows are dynamic and not about deals, so a deal carries its own outcome and
70
+ * probability; its stage is only where it is in the workflow.
71
+ */
72
+ export type Pipeline = Workflow;
73
+
74
+ /** A pipeline's stage: a workflow stage. */
75
+ export type PipelineStage = WorkflowStage;
76
+
77
+ /**
78
+ * A qualified opportunity, moving through a pipeline (a workflow) stage by stage until it's won or lost.
79
+ */
80
+ export interface Deal {
81
+ urn: string;
82
+ url?: string | null;
83
+ owner: Ref;
84
+ title: string;
85
+ /** The customer's companies: usually one. */
86
+ contactCompanies: Ref[];
87
+ /** The people involved, as identities. */
88
+ contactIdentities: Ref[];
89
+ /** The deal's stage, in its pipeline (any workflow): named as a task's stage is. */
90
+ workflowStage?: Ref | null;
91
+ /** Open, won or lost, on the deal itself rather than its stage. Open when absent. */
92
+ outcome?: DealOutcome | null;
93
+ /** The chance it's won, 0 to 100, for weighted pipeline value. */
94
+ probability?: number | null;
95
+ /** What the deal is worth. Replaces its lead's target value in the sales target. */
96
+ targetValue?: Money | null;
97
+ /** When it's expected to close. */
98
+ targetCloseTimestamp?: string | null;
99
+ /** When it was won or lost, cleared when it reopens. */
100
+ closeTimestamp?: string | null;
101
+ /** Why it was lost, as leads have `closedReason`. */
102
+ lostReason?: string | null;
103
+ assignee?: Ref | null;
104
+ /** The lead it was converted from. */
105
+ leadSource?: Ref | null;
106
+ /** Invoices raised for it; there may be several. The link lives here, not on the invoice. */
107
+ invoices: Ref[];
108
+ /** A content entity for the business's own fields about the deal, as companies have. */
109
+ entity?: Ref | null;
110
+ createdTimestamp: string;
111
+ updatedTimestamp?: string | null;
112
+ }
113
+
114
+ /** The payment invoice statuses the API has. */
115
+ export type InvoiceStatus = 'DRAFT' | 'IN_REVIEW' | 'AUTHORISED' | 'PENDING' | 'VOIDED' | 'PAID' | 'REFUNDED';
116
+
117
+ /** Whether an invoice's line prices include tax. */
118
+ export type LineItemTax = 'EXCLUSIVE' | 'INCLUSIVE' | 'NO_TAX';
119
+
120
+ /** Who pays or receives an invoice: a company, an identity, or both (a person at a company). */
121
+ export interface InvoiceParty {
122
+ company?: Ref | null;
123
+ identity?: Ref | null;
124
+ }
125
+
126
+ /** An invoice line, as the API has it (`/n/v1/invoiceline/`). */
127
+ export interface InvoiceLine {
128
+ urn: string;
129
+ lineNumber?: number | null;
130
+ description?: string | null;
131
+ itemCode?: string | null;
132
+ quantity?: number | null;
133
+ /** In major units (pounds), unlike the line's money amounts. */
134
+ unitPrice?: number | null;
135
+ price?: Money | null;
136
+ tax?: Money | null;
137
+ discountPrice?: Money | null;
138
+ discountRate?: number | null;
139
+ taxName?: string | null;
140
+ }
141
+
142
+ /**
143
+ * A payment invoice (`/n/v1/paymentinvoice/`): its amounts as money in `currencyCode`, its lines, and the payments and
144
+ * refunds against it (`remittances`). Deals link to their invoices (`Deal.invoices`).
145
+ */
146
+ export interface Invoice {
147
+ urn: string;
148
+ url?: string | null;
149
+ owner: Ref;
150
+ /** Who pays. */
151
+ remitter?: InvoiceParty | null;
152
+ /** Who the invoice is addressed to. */
153
+ recipient?: InvoiceParty | null;
154
+ status: InvoiceStatus;
155
+ currencyCode: string;
156
+ lineItemTax?: LineItemTax | null;
157
+ subTotal?: Money | null;
158
+ discount?: Money | null;
159
+ tax?: Money | null;
160
+ /** Required on create. */
161
+ total: Money;
162
+ paid?: Money | null;
163
+ refunded?: Money | null;
164
+ issuedTimestamp?: string | null;
165
+ dueTimestamp?: string | null;
166
+ fullyPaidTimestamp?: string | null;
167
+ lines?: InvoiceLine[];
168
+ /** Payments and refunds against it, as the API lists them on the invoice. */
169
+ remittances?: Remittance[];
170
+ updatedTimestamp?: string | null;
171
+ }
172
+
173
+ /** Whether a remittance is money received for an invoice or a refund paid back. */
174
+ export type RemittanceDirection = 'PAYMENT' | 'REFUND';
175
+ export type RemittanceStatus = 'RECEIVED' | 'FAILED' | 'REVERSED';
176
+ export type RemittanceMethod = 'BANK_TRANSFER' | 'CARD_PAYMENT' | 'DIRECT_DEBIT' | 'CASH' | 'E_WALLET' | 'OTHER';
177
+
178
+ /**
179
+ * One payment received against an invoice, or a refund paid back (`/n/v1/invoiceremittance/`). It has no owner of its
180
+ * own: a company's remittances are its invoices'. An invoice's `paid`, `refunded`, `status` and `fullyPaidTimestamp`
181
+ * follow from them (see `invoiceFromRemittances`).
182
+ */
183
+ export interface Remittance {
184
+ urn: string;
185
+ url?: string | null;
186
+ paymentInvoice: Ref;
187
+ remittanceDirection: RemittanceDirection;
188
+ remittanceStatus: RemittanceStatus;
189
+ remittanceMethod: RemittanceMethod;
190
+ value: Money;
191
+ /** The bank or card reference. */
192
+ reference?: string | null;
193
+ /** Who paid: a company, an identity, or both. */
194
+ remittingCompany?: Ref | null;
195
+ remittingIdentity?: Ref | null;
196
+ receivedTimestamp: string;
197
+ }
198
+
199
+ /** The CRM concepts, each served by the API or by sample data (see CrmClient). */
200
+ export type CrmConcept = 'leads' | 'deals' | 'pipelines' | 'invoices' | 'remittances';
201
+
202
+ export const CRM_CONCEPTS: readonly CrmConcept[] = ['leads', 'deals', 'pipelines', 'invoices', 'remittances'];