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

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 (234) 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 +104 -0
  8. package/dist/backend.d.ts.map +1 -0
  9. package/dist/backend.js +328 -0
  10. package/dist/backend.js.map +1 -0
  11. package/dist/crm-client.d.ts +164 -0
  12. package/dist/crm-client.d.ts.map +1 -0
  13. package/dist/crm-client.js +252 -0
  14. package/dist/crm-client.js.map +1 -0
  15. package/dist/deal-order.d.ts +42 -0
  16. package/dist/deal-order.d.ts.map +1 -0
  17. package/dist/deal-order.js +80 -0
  18. package/dist/deal-order.js.map +1 -0
  19. package/dist/errors.d.ts +21 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +33 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/index.d.ts +14 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +14 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/invoices.d.ts +53 -0
  28. package/dist/invoices.d.ts.map +1 -0
  29. package/dist/invoices.js +155 -0
  30. package/dist/invoices.js.map +1 -0
  31. package/dist/leads.d.ts +29 -0
  32. package/dist/leads.d.ts.map +1 -0
  33. package/dist/leads.js +56 -0
  34. package/dist/leads.js.map +1 -0
  35. package/dist/mock/index.d.ts +43 -0
  36. package/dist/mock/index.d.ts.map +1 -0
  37. package/dist/mock/index.js +303 -0
  38. package/dist/mock/index.js.map +1 -0
  39. package/dist/money.d.ts +29 -0
  40. package/dist/money.d.ts.map +1 -0
  41. package/dist/money.js +82 -0
  42. package/dist/money.js.map +1 -0
  43. package/dist/period.d.ts +30 -0
  44. package/dist/period.d.ts.map +1 -0
  45. package/dist/period.js +49 -0
  46. package/dist/period.js.map +1 -0
  47. package/dist/pipeline.d.ts +36 -0
  48. package/dist/pipeline.d.ts.map +1 -0
  49. package/dist/pipeline.js +58 -0
  50. package/dist/pipeline.js.map +1 -0
  51. package/dist/react/Charts.d.ts +19 -0
  52. package/dist/react/Charts.d.ts.map +1 -0
  53. package/dist/react/Charts.js +38 -0
  54. package/dist/react/Charts.js.map +1 -0
  55. package/dist/react/ChoiceCombobox.d.ts +36 -0
  56. package/dist/react/ChoiceCombobox.d.ts.map +1 -0
  57. package/dist/react/ChoiceCombobox.js +105 -0
  58. package/dist/react/ChoiceCombobox.js.map +1 -0
  59. package/dist/react/CompanyAccountView.d.ts +21 -0
  60. package/dist/react/CompanyAccountView.d.ts.map +1 -0
  61. package/dist/react/CompanyAccountView.js +27 -0
  62. package/dist/react/CompanyAccountView.js.map +1 -0
  63. package/dist/react/DashboardCards.d.ts +32 -0
  64. package/dist/react/DashboardCards.d.ts.map +1 -0
  65. package/dist/react/DashboardCards.js +38 -0
  66. package/dist/react/DashboardCards.js.map +1 -0
  67. package/dist/react/DealsBoard.d.ts +49 -0
  68. package/dist/react/DealsBoard.d.ts.map +1 -0
  69. package/dist/react/DealsBoard.js +82 -0
  70. package/dist/react/DealsBoard.js.map +1 -0
  71. package/dist/react/Details.d.ts +85 -0
  72. package/dist/react/Details.d.ts.map +1 -0
  73. package/dist/react/Details.js +268 -0
  74. package/dist/react/Details.js.map +1 -0
  75. package/dist/react/Forms.d.ts +190 -0
  76. package/dist/react/Forms.d.ts.map +1 -0
  77. package/dist/react/Forms.js +494 -0
  78. package/dist/react/Forms.js.map +1 -0
  79. package/dist/react/LeadsTable.d.ts +22 -0
  80. package/dist/react/LeadsTable.d.ts.map +1 -0
  81. package/dist/react/LeadsTable.js +79 -0
  82. package/dist/react/LeadsTable.js.map +1 -0
  83. package/dist/react/Sales.d.ts +68 -0
  84. package/dist/react/Sales.d.ts.map +1 -0
  85. package/dist/react/Sales.js +270 -0
  86. package/dist/react/Sales.js.map +1 -0
  87. package/dist/react/SidePanel.d.ts +31 -0
  88. package/dist/react/SidePanel.d.ts.map +1 -0
  89. package/dist/react/SidePanel.js +49 -0
  90. package/dist/react/SidePanel.js.map +1 -0
  91. package/dist/react/format.d.ts +28 -0
  92. package/dist/react/format.d.ts.map +1 -0
  93. package/dist/react/format.js +30 -0
  94. package/dist/react/format.js.map +1 -0
  95. package/dist/react/index.d.ts +15 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +15 -0
  98. package/dist/react/index.js.map +1 -0
  99. package/dist/react/parts.d.ts +55 -0
  100. package/dist/react/parts.d.ts.map +1 -0
  101. package/dist/react/parts.js +82 -0
  102. package/dist/react/parts.js.map +1 -0
  103. package/dist/react/pipeline-choice.d.ts +19 -0
  104. package/dist/react/pipeline-choice.d.ts.map +1 -0
  105. package/dist/react/pipeline-choice.js +39 -0
  106. package/dist/react/pipeline-choice.js.map +1 -0
  107. package/dist/react/text.d.ts +232 -0
  108. package/dist/react/text.d.ts.map +1 -0
  109. package/dist/react/text.js +229 -0
  110. package/dist/react/text.js.map +1 -0
  111. package/dist/react/ui/alert.d.ts +11 -0
  112. package/dist/react/ui/alert.d.ts.map +1 -0
  113. package/dist/react/ui/alert.js +29 -0
  114. package/dist/react/ui/alert.js.map +1 -0
  115. package/dist/react/ui/badge.d.ts +10 -0
  116. package/dist/react/ui/badge.d.ts.map +1 -0
  117. package/dist/react/ui/badge.js +26 -0
  118. package/dist/react/ui/badge.js.map +1 -0
  119. package/dist/react/ui/button.d.ts +11 -0
  120. package/dist/react/ui/button.d.ts.map +1 -0
  121. package/dist/react/ui/button.js +37 -0
  122. package/dist/react/ui/button.js.map +1 -0
  123. package/dist/react/ui/card.d.ts +12 -0
  124. package/dist/react/ui/card.d.ts.map +1 -0
  125. package/dist/react/ui/card.js +26 -0
  126. package/dist/react/ui/card.js.map +1 -0
  127. package/dist/react/ui/chart.d.ts +45 -0
  128. package/dist/react/ui/chart.d.ts.map +1 -0
  129. package/dist/react/ui/chart.js +116 -0
  130. package/dist/react/ui/chart.js.map +1 -0
  131. package/dist/react/ui/input.d.ts +4 -0
  132. package/dist/react/ui/input.d.ts.map +1 -0
  133. package/dist/react/ui/input.js +8 -0
  134. package/dist/react/ui/input.js.map +1 -0
  135. package/dist/react/ui/label.d.ts +5 -0
  136. package/dist/react/ui/label.d.ts.map +1 -0
  137. package/dist/react/ui/label.js +10 -0
  138. package/dist/react/ui/label.js.map +1 -0
  139. package/dist/react/ui/progress.d.ts +5 -0
  140. package/dist/react/ui/progress.d.ts.map +1 -0
  141. package/dist/react/ui/progress.js +10 -0
  142. package/dist/react/ui/progress.js.map +1 -0
  143. package/dist/react/ui/select.d.ts +16 -0
  144. package/dist/react/ui/select.d.ts.map +1 -0
  145. package/dist/react/ui/select.js +37 -0
  146. package/dist/react/ui/select.js.map +1 -0
  147. package/dist/react/ui/separator.d.ts +5 -0
  148. package/dist/react/ui/separator.d.ts.map +1 -0
  149. package/dist/react/ui/separator.js +10 -0
  150. package/dist/react/ui/separator.js.map +1 -0
  151. package/dist/react/ui/sheet.d.ts +15 -0
  152. package/dist/react/ui/sheet.d.ts.map +1 -0
  153. package/dist/react/ui/sheet.js +38 -0
  154. package/dist/react/ui/sheet.js.map +1 -0
  155. package/dist/react/ui/skeleton.d.ts +3 -0
  156. package/dist/react/ui/skeleton.d.ts.map +1 -0
  157. package/dist/react/ui/skeleton.js +7 -0
  158. package/dist/react/ui/skeleton.js.map +1 -0
  159. package/dist/react/ui/table.d.ts +11 -0
  160. package/dist/react/ui/table.d.ts.map +1 -0
  161. package/dist/react/ui/table.js +29 -0
  162. package/dist/react/ui/table.js.map +1 -0
  163. package/dist/react/ui/tabs.d.ts +12 -0
  164. package/dist/react/ui/tabs.d.ts.map +1 -0
  165. package/dist/react/ui/tabs.js +31 -0
  166. package/dist/react/ui/tabs.js.map +1 -0
  167. package/dist/react/views.d.ts +82 -0
  168. package/dist/react/views.d.ts.map +1 -0
  169. package/dist/react/views.js +241 -0
  170. package/dist/react/views.js.map +1 -0
  171. package/dist/sales.d.ts +82 -0
  172. package/dist/sales.d.ts.map +1 -0
  173. package/dist/sales.js +87 -0
  174. package/dist/sales.js.map +1 -0
  175. package/dist/store.d.ts +159 -0
  176. package/dist/store.d.ts.map +1 -0
  177. package/dist/store.js +305 -0
  178. package/dist/store.js.map +1 -0
  179. package/dist/target.d.ts +22 -0
  180. package/dist/target.d.ts.map +1 -0
  181. package/dist/target.js +40 -0
  182. package/dist/target.js.map +1 -0
  183. package/dist/types.d.ts +204 -0
  184. package/dist/types.d.ts.map +1 -0
  185. package/dist/types.js +2 -0
  186. package/dist/types.js.map +1 -0
  187. package/package.json +100 -4
  188. package/src/account.ts +79 -0
  189. package/src/backend.ts +501 -0
  190. package/src/crm-client.ts +393 -0
  191. package/src/deal-order.ts +116 -0
  192. package/src/errors.ts +34 -0
  193. package/src/index.ts +13 -0
  194. package/src/invoices.ts +177 -0
  195. package/src/leads.ts +78 -0
  196. package/src/mock/index.ts +398 -0
  197. package/src/money.ts +104 -0
  198. package/src/period.ts +71 -0
  199. package/src/pipeline.ts +82 -0
  200. package/src/react/Charts.tsx +143 -0
  201. package/src/react/ChoiceCombobox.tsx +227 -0
  202. package/src/react/CompanyAccountView.tsx +198 -0
  203. package/src/react/DashboardCards.tsx +171 -0
  204. package/src/react/DealsBoard.tsx +344 -0
  205. package/src/react/Details.tsx +870 -0
  206. package/src/react/Forms.tsx +1486 -0
  207. package/src/react/LeadsTable.tsx +234 -0
  208. package/src/react/Sales.tsx +827 -0
  209. package/src/react/SidePanel.tsx +104 -0
  210. package/src/react/format.ts +53 -0
  211. package/src/react/index.ts +14 -0
  212. package/src/react/parts.tsx +183 -0
  213. package/src/react/pipeline-choice.ts +54 -0
  214. package/src/react/text.ts +232 -0
  215. package/src/react/ui/README.md +6 -0
  216. package/src/react/ui/alert.tsx +75 -0
  217. package/src/react/ui/badge.tsx +48 -0
  218. package/src/react/ui/button.tsx +66 -0
  219. package/src/react/ui/card.tsx +102 -0
  220. package/src/react/ui/chart.tsx +304 -0
  221. package/src/react/ui/input.tsx +18 -0
  222. package/src/react/ui/label.tsx +23 -0
  223. package/src/react/ui/progress.tsx +30 -0
  224. package/src/react/ui/select.tsx +189 -0
  225. package/src/react/ui/separator.tsx +27 -0
  226. package/src/react/ui/sheet.tsx +145 -0
  227. package/src/react/ui/skeleton.tsx +13 -0
  228. package/src/react/ui/table.tsx +113 -0
  229. package/src/react/ui/tabs.tsx +89 -0
  230. package/src/react/views.tsx +633 -0
  231. package/src/sales.ts +167 -0
  232. package/src/store.ts +528 -0
  233. package/src/target.ts +54 -0
  234. package/src/types.ts +230 -0
@@ -0,0 +1,393 @@
1
+ import type { BaackClient, Company } from '@baack-software/baack-ts-client';
2
+ import { ref, toTimestamp, urnOf, type RefLike } from '@baack-software/baack-ts-tasks';
3
+ import { companyAccount, type CompanyAccount } from './account.ts';
4
+ import {
5
+ apiBackend,
6
+ type CrmBackend,
7
+ type DealInput,
8
+ type InvoiceInput,
9
+ type InvoiceLineInput,
10
+ type LeadInput,
11
+ type RemittanceInput,
12
+ } from './backend.ts';
13
+ import { orderedStages, pipelineOf } from './pipeline.ts';
14
+ import {
15
+ CRM_CONCEPTS,
16
+ type ContactDetails,
17
+ type CrmConcept,
18
+ type CrmPerson,
19
+ type Deal,
20
+ type DealOutcome,
21
+ type Invoice,
22
+ type Lead,
23
+ type LeadOutcome,
24
+ type NewContact,
25
+ type Pipeline,
26
+ type PipelineStage,
27
+ } from './types.ts';
28
+
29
+ /** Where a concept's records come from: the Baack API, or sample data while the API doesn't have it. */
30
+ export type CrmSource = 'api' | 'sample';
31
+
32
+ export interface CrmClientOptions {
33
+ client: BaackClient;
34
+ /**
35
+ * Concepts served from sample data, with the backend holding it (usually `memoryBackend(sampleCrm(...))` from
36
+ * `@baack-software/baack-ts-crm/mock`). The rest come from the API.
37
+ */
38
+ sample?: { backend: CrmBackend; concepts: readonly CrmConcept[] | 'all' };
39
+ }
40
+
41
+ export interface ConvertOptions {
42
+ /** The new deal's pipeline. It starts at the first open stage. */
43
+ pipeline: Pipeline;
44
+ /** Defaults to the lead's title. */
45
+ title?: string;
46
+ /** Defaults to the lead's target value. */
47
+ targetValue?: Deal['targetValue'];
48
+ /**
49
+ * The client company's name when the lead has no contact company yet, as confirmed on qualifying: the company is
50
+ * made and linked to the lead and the deal. Empty or absent converts without a company, as for a consumer.
51
+ */
52
+ companyName?: string;
53
+ }
54
+
55
+ /**
56
+ * What an invoice's parties also need made: a company that isn't in Baack yet, by name, and a new person, made after
57
+ * that party's company (so they're its customer's person).
58
+ */
59
+ export interface InvoicePartyOptions {
60
+ remitterCompanyName?: string | undefined;
61
+ recipientCompanyName?: string | undefined;
62
+ remitterContact?: NewContact | undefined;
63
+ recipientContact?: NewContact | undefined;
64
+ }
65
+
66
+ /** What a new invoice also needs: the deal it's for, and its parties' new companies and people. */
67
+ export interface NewInvoiceOptions extends InvoicePartyOptions {
68
+ deal?: Deal;
69
+ }
70
+
71
+ /** What saving an invoice made along the way: its parties' new companies and people. */
72
+ export interface InvoiceSaved {
73
+ invoice: Invoice;
74
+ companies: Company[];
75
+ people: CrmPerson[];
76
+ }
77
+
78
+ export interface NewLeadOptions {
79
+ /**
80
+ * The prospect's business name when it isn't a company in Baack yet: the company is made first, owned by the lead's
81
+ * owner, and linked as the lead's contact company, since a lead holds a business by its company.
82
+ */
83
+ companyName?: string;
84
+ /**
85
+ * A new person to be the lead's contact: made after the company (so they're linked to it, as its customer's person),
86
+ * and linked as the lead's contact identity.
87
+ */
88
+ contact?: NewContact;
89
+ }
90
+
91
+ /** What saving a lead made along the way: the prospect's company and the contact, when they were new. */
92
+ export interface LeadSaved {
93
+ lead: Lead;
94
+ company?: Company;
95
+ person?: CrmPerson;
96
+ }
97
+
98
+ /**
99
+ * CRM records for a company, each concept from the API or from sample data (see `CrmClientOptions.sample`), so views
100
+ * can be built and reviewed before the API has every concept. Moving a concept to the API changes the options, not
101
+ * the code using this client.
102
+ *
103
+ * ```ts
104
+ * const crm = createCrmClient({ client, sample: { backend: memoryBackend(sampleCrm({ owner })), concepts: 'all' } });
105
+ * const leads = await crm.leads.list(owner);
106
+ * ```
107
+ */
108
+ export class CrmClient {
109
+ readonly companies: CrmBackend['companies'];
110
+ readonly people: CrmBackend['people'];
111
+ readonly leads: CrmBackend['leads'];
112
+ readonly deals: CrmBackend['deals'];
113
+ readonly pipelines: CrmBackend['pipelines'];
114
+ readonly invoices: CrmBackend['invoices'];
115
+ readonly invoiceLines: CrmBackend['invoiceLines'];
116
+ readonly remittances: CrmBackend['remittances'];
117
+
118
+ constructor(
119
+ backend: CrmBackend,
120
+ /** Where each concept comes from, so views can mark sample data. */
121
+ readonly sources: Readonly<Record<CrmConcept, CrmSource>>,
122
+ ) {
123
+ this.companies = backend.companies;
124
+ this.people = backend.people;
125
+ this.leads = backend.leads;
126
+ this.deals = backend.deals;
127
+ this.pipelines = backend.pipelines;
128
+ this.invoices = backend.invoices;
129
+ this.invoiceLines = backend.invoiceLines;
130
+ this.remittances = backend.remittances;
131
+ }
132
+
133
+ /** Whether any of these concepts come from sample data. */
134
+ isSample(...concepts: CrmConcept[]): boolean {
135
+ return concepts.some((concept) => this.sources[concept] === 'sample');
136
+ }
137
+
138
+ /**
139
+ * Qualifies a lead into a deal: creates the deal (open, with the lead's company, contact and target value, at the
140
+ * pipeline's first stage, with the lead as its `leadSource`), then marks the lead converted. A lead without a contact
141
+ * company gets one first when `companyName` is given, owned by the lead's owner and linked to the lead too, so the
142
+ * deal shows on the customer's page. A consumer's lead (a person, no business) converts without a company.
143
+ */
144
+ async convertLead(lead: Lead, options: ConvertOptions): Promise<{ lead: Lead; deal: Deal; company?: Company }> {
145
+ const first = orderedStages(options.pipeline)[0];
146
+ const name = options.companyName?.trim();
147
+ // TODO: search the owner's companies first so people can pick one rather than make a duplicate (TODO.md).
148
+ const company = !lead.contactCompany && name ? await this.companies.create({ owner: lead.owner, name }) : undefined;
149
+ const companyRef = lead.contactCompany ? ref(lead.contactCompany) : company ? ref(company) : null;
150
+ const input: DealInput = {
151
+ owner: ref(lead.owner),
152
+ title: options.title ?? lead.title,
153
+ contactCompanies: companyRef ? [companyRef] : [],
154
+ contactIdentities: lead.contactIdentity ? [ref(lead.contactIdentity)] : [],
155
+ workflowStage: first ? ref(first) : null,
156
+ outcome: 'OPEN',
157
+ targetValue: options.targetValue ?? lead.targetValue ?? null,
158
+ assignee: lead.assignee ? ref(lead.assignee) : null,
159
+ leadSource: ref(lead),
160
+ invoices: [],
161
+ };
162
+ const deal = await this.deals.create(input);
163
+ const converted = await this.leads.update(lead, {
164
+ status: 'QUALIFIED',
165
+ outcome: 'CONVERTED',
166
+ ...(company ? { contactCompany: ref(company) } : {}),
167
+ });
168
+ return { lead: converted, deal, ...(company ? { company } : {}) };
169
+ }
170
+
171
+ /** Moves a deal to a stage of its pipeline. Stages are only progress: winning or losing is `setOutcome`. */
172
+ moveDeal(deal: RefLike, stage: PipelineStage): Promise<Deal> {
173
+ return this.deals.update(deal, { workflowStage: ref(stage) });
174
+ }
175
+
176
+ /**
177
+ * Wins, loses or reopens a deal. Won or lost closes it now (`closeTimestamp`); reopening clears the close time and
178
+ * reason. `lostReason` is kept only when the deal is lost.
179
+ */
180
+ setOutcome(deal: RefLike, outcome: DealOutcome, options: { lostReason?: string; now?: Date } = {}): Promise<Deal> {
181
+ const closed = outcome !== 'OPEN';
182
+ return this.deals.update(deal, {
183
+ outcome,
184
+ closeTimestamp: closed ? toTimestamp(options.now ?? new Date()) : null,
185
+ lostReason: outcome === 'LOST' ? options.lostReason?.trim() || null : null,
186
+ });
187
+ }
188
+
189
+ /**
190
+ * Closes a lead as unqualified (with why), or reopens it, as `setOutcome` does for deals. Converting is
191
+ * `convertLead`, which also makes the deal. A lead has no close time of its own: its `updatedTimestamp` says when.
192
+ */
193
+ setLeadOutcome(
194
+ lead: RefLike,
195
+ outcome: Exclude<LeadOutcome, 'CONVERTED'>,
196
+ options: { closedReason?: string } = {},
197
+ ): Promise<Lead> {
198
+ const closed = outcome === 'CLOSED';
199
+ return this.leads.update(lead, { outcome, closedReason: closed ? options.closedReason?.trim() || null : null });
200
+ }
201
+
202
+ /** Creates a deal, for example one that didn't start as a lead. */
203
+ createDeal(input: DealInput): Promise<Deal> {
204
+ return this.deals.create(input);
205
+ }
206
+
207
+ /**
208
+ * Creates an invoice, then its lines (numbered in order), then links it to `deal` when given, as deals hold their
209
+ * invoices. A party's new company (`remitterCompanyName`, `recipientCompanyName`) is made first, owned by the
210
+ * invoice's owner, then its new person (`remitterContact`, `recipientContact`). The invoice's amounts are as given:
211
+ * the API doesn't add them up from the lines. Returns it read back, with its lines, the deal as updated and the
212
+ * companies and people made.
213
+ */
214
+ async createInvoice(
215
+ input: InvoiceInput,
216
+ lines: readonly Omit<InvoiceLineInput, 'paymentInvoice' | 'lineNumber'>[] = [],
217
+ options: NewInvoiceOptions = {},
218
+ ): Promise<InvoiceSaved & { deal?: Deal }> {
219
+ const { links, companies, people } = await this.#parties(input.owner, input, options);
220
+ const created = await this.invoices.create({ ...input, ...links });
221
+ for (const [index, line] of lines.entries()) {
222
+ await this.invoiceLines.create({ ...line, lineNumber: index + 1, paymentInvoice: ref(created) });
223
+ }
224
+ const deal = options.deal
225
+ ? await this.deals.update(options.deal, { invoices: [...options.deal.invoices, ref(created)] })
226
+ : undefined;
227
+ const invoice = await this.invoices.get(created);
228
+ return { invoice, ...(deal ? { deal } : {}), companies, people };
229
+ }
230
+
231
+ /**
232
+ * Changes an invoice's own fields (status, parties, dates), making a party's new company and person first, as for a
233
+ * new invoice. Its lines aren't changed.
234
+ */
235
+ async updateInvoice(
236
+ invoice: Invoice,
237
+ changes: Partial<InvoiceInput>,
238
+ options: InvoicePartyOptions = {},
239
+ ): Promise<InvoiceSaved> {
240
+ const parties = {
241
+ remitter: changes.remitter === undefined ? (invoice.remitter ?? null) : changes.remitter,
242
+ recipient: changes.recipient === undefined ? (invoice.recipient ?? null) : changes.recipient,
243
+ };
244
+ const { links, companies, people } = await this.#parties(invoice.owner, parties, options);
245
+ const updated = await this.invoices.update(invoice, { ...changes, ...links });
246
+ return { invoice: updated, companies, people };
247
+ }
248
+
249
+ /**
250
+ * An invoice's parties with their new companies and people made and linked: each party's company from its
251
+ * `...CompanyName`, then its person from its `...Contact`, linked to that party's company. Only parties that changed
252
+ * are returned in `links`.
253
+ */
254
+ async #parties(
255
+ owner: RefLike,
256
+ parties: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'>,
257
+ options: InvoicePartyOptions,
258
+ ): Promise<{
259
+ links: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'>;
260
+ companies: Company[];
261
+ people: CrmPerson[];
262
+ }> {
263
+ const companies: Company[] = [];
264
+ const people: CrmPerson[] = [];
265
+ const links: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'> = {};
266
+ for (const which of ['remitter', 'recipient'] as const) {
267
+ const name = options[`${which}CompanyName`]?.trim();
268
+ const contact = options[`${which}Contact`];
269
+ if (!name && !contact) continue;
270
+ const given = parties[which];
271
+ let company = given?.company ?? null;
272
+ if (name) {
273
+ const made = await this.companies.create({ owner, name });
274
+ companies.push(made);
275
+ company = ref(made);
276
+ }
277
+ let identity = given?.identity ?? null;
278
+ if (contact) {
279
+ const person = await this.createContact(owner, contact, company);
280
+ people.push(person);
281
+ identity = { urn: person.urn };
282
+ }
283
+ links[which] = { ...given, company, identity };
284
+ }
285
+ return { links, companies, people };
286
+ }
287
+
288
+ /** Records a payment (or refund) received against an invoice. */
289
+ recordPayment(input: RemittanceInput) {
290
+ return this.remittances.create(input);
291
+ }
292
+
293
+ /** A person's email and telephone (see `PeopleApi.contactDetails`). */
294
+ contactDetails(identity: RefLike): Promise<ContactDetails> {
295
+ return this.people.contactDetails(identity);
296
+ }
297
+
298
+ /** Sets a person's email and telephone; fields left out are kept (see `PeopleApi.setContactDetails`). */
299
+ setContactDetails(identity: RefLike, details: Partial<ContactDetails>): Promise<ContactDetails> {
300
+ return this.people.setContactDetails(identity, details);
301
+ }
302
+
303
+ /** Makes a person owned by `owner`: a customer's person when `company` is given (see `PeopleApi`). */
304
+ createContact(owner: RefLike, contact: NewContact, company?: RefLike | null): Promise<CrmPerson> {
305
+ return this.people.createContact({ owner, contact, company: company ?? null });
306
+ }
307
+
308
+ /**
309
+ * A lead's company and contact links, making them first when `options` asks: the company from `companyName` when
310
+ * the lead has none, then the contact from `contact`, linked to that company.
311
+ */
312
+ async #prospect(
313
+ owner: RefLike,
314
+ company: Lead['contactCompany'],
315
+ options: NewLeadOptions,
316
+ ): Promise<{ links: Partial<LeadInput>; company?: Company; person?: CrmPerson }> {
317
+ const name = options.companyName?.trim();
318
+ const made = !company && name ? await this.companies.create({ owner, name }) : undefined;
319
+ const companyRef = made ? ref(made) : (company ?? null);
320
+ const person = options.contact ? await this.createContact(owner, options.contact, companyRef) : undefined;
321
+ return {
322
+ links: {
323
+ ...(made ? { contactCompany: companyRef } : {}),
324
+ ...(person ? { contactIdentity: { urn: person.urn } } : {}),
325
+ },
326
+ ...(made ? { company: made } : {}),
327
+ ...(person ? { person } : {}),
328
+ };
329
+ }
330
+
331
+ /**
332
+ * Creates a lead. With `companyName` and no contact company, the prospect's company is made first and linked; with
333
+ * `contact`, so is the contact. Both are returned with the lead.
334
+ */
335
+ async createLead(input: LeadInput, options: NewLeadOptions = {}): Promise<LeadSaved> {
336
+ const { links, ...made } = await this.#prospect(input.owner, input.contactCompany, options);
337
+ const lead = await this.leads.create({ ...input, ...links });
338
+ return { lead, ...made };
339
+ }
340
+
341
+ /** Changes a lead, making its new company or contact first as `createLead` does. */
342
+ async updateLead(lead: Lead, changes: Partial<LeadInput>, options: NewLeadOptions = {}): Promise<LeadSaved> {
343
+ const company = changes.contactCompany === undefined ? lead.contactCompany : changes.contactCompany;
344
+ const { links, ...made } = await this.#prospect(lead.owner, company, options);
345
+ const updated = await this.leads.update(lead, { ...changes, ...links });
346
+ return { lead: updated, ...made };
347
+ }
348
+
349
+ /** Everything the CRM holds about one customer company of `owner`. */
350
+ async companyAccount(owner: RefLike, company: RefLike, now = new Date()): Promise<CompanyAccount> {
351
+ const [leads, deals, pipelines, invoices, remittances] = await Promise.all([
352
+ this.leads.list(owner),
353
+ this.deals.list(owner),
354
+ this.pipelines.list(owner),
355
+ this.invoices.list(owner),
356
+ this.remittances.list(owner),
357
+ ]);
358
+ return companyAccount(urnOf(company), { leads, deals, pipelines, invoices, remittances }, now);
359
+ }
360
+
361
+ /** The pipeline a deal is in, among the owner's. */
362
+ async pipelineFor(deal: Deal): Promise<Pipeline | undefined> {
363
+ return pipelineOf(deal, await this.pipelines.list(deal.owner));
364
+ }
365
+ }
366
+
367
+ /** A CrmClient over the Baack API, with the concepts named in `sample` served from sample data instead. */
368
+ export function createCrmClient({ client, sample }: CrmClientOptions): CrmClient {
369
+ const api = apiBackend(client);
370
+ const fromSample = (concept: CrmConcept) =>
371
+ sample !== undefined && (sample.concepts === 'all' || sample.concepts.includes(concept));
372
+ const pick = <K extends CrmConcept>(concept: K): CrmBackend[K] =>
373
+ fromSample(concept) ? sample!.backend[concept] : api[concept];
374
+ // Companies and people are made for leads, so they come from wherever the leads do: sample leads never make real
375
+ // companies or people.
376
+ const sources = Object.fromEntries(
377
+ CRM_CONCEPTS.map((concept) => [concept, fromSample(concept) ? 'sample' : 'api']),
378
+ ) as Record<CrmConcept, CrmSource>;
379
+ return new CrmClient(
380
+ {
381
+ companies: fromSample('leads') ? sample!.backend.companies : api.companies,
382
+ people: fromSample('leads') ? sample!.backend.people : api.people,
383
+ leads: pick('leads'),
384
+ deals: pick('deals'),
385
+ pipelines: pick('pipelines'),
386
+ invoices: pick('invoices'),
387
+ // Lines are made with their invoices, so they come from wherever the invoices do.
388
+ invoiceLines: fromSample('invoices') ? sample!.backend.invoiceLines : api.invoiceLines,
389
+ remittances: pick('remittances'),
390
+ },
391
+ sources,
392
+ );
393
+ }
@@ -0,0 +1,116 @@
1
+ import { minorOf } from './money.ts';
2
+ import { dealOutcome } from './pipeline.ts';
3
+ import type { Deal, DealOutcome } from './types.ts';
4
+
5
+ /**
6
+ * How a board's columns order their deals:
7
+ * - `weighted`: value times chance of winning, sooner closes first (see `weightedScore`), highest first;
8
+ * - `size`: the target value, largest first;
9
+ * - `urgency`: the expected close, soonest (or most overdue) first, deals without one last.
10
+ */
11
+ export type DealOrder = 'weighted' | 'size' | 'urgency';
12
+
13
+ export const DEAL_ORDERS: readonly DealOrder[] = ['weighted', 'size', 'urgency'];
14
+
15
+ const DAY_MS = 86_400_000;
16
+ /** Days to close assumed for a deal without an expected close. */
17
+ export const DEFAULT_DAYS_TO_CLOSE = 30;
18
+ /** The chance of winning assumed when no deal has a probability. */
19
+ export const DEFAULT_PROBABILITY = 10;
20
+
21
+ const average = (values: readonly number[]): number | undefined =>
22
+ values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : undefined;
23
+
24
+ /** Whole days from `now` until a deal's expected close, negative once past; undefined without one. */
25
+ export function daysToClose(deal: Deal, now: Date): number | undefined {
26
+ if (!deal.targetCloseTimestamp) return undefined;
27
+ const close = Date.parse(
28
+ deal.targetCloseTimestamp.endsWith('Z') ? deal.targetCloseTimestamp : `${deal.targetCloseTimestamp}Z`,
29
+ );
30
+ return Number.isNaN(close) ? undefined : Math.ceil((close - now.getTime()) / DAY_MS);
31
+ }
32
+
33
+ /** What the weighted order assumes for deals missing a value or probability: the averages of those that have one. */
34
+ export interface WeightDefaults {
35
+ /** In minor units; at least 1. */
36
+ value: number;
37
+ /** 0 to 100. */
38
+ probability: number;
39
+ }
40
+
41
+ export function weightDefaults(deals: readonly Deal[]): WeightDefaults {
42
+ const values = deals.flatMap((deal) => (deal.targetValue ? [minorOf(deal.targetValue)] : []));
43
+ const chances = deals.flatMap((deal) => (typeof deal.probability === 'number' ? [deal.probability] : []));
44
+ return { value: Math.max(1, average(values) ?? 1), probability: average(chances) ?? DEFAULT_PROBABILITY };
45
+ }
46
+
47
+ /**
48
+ * A deal's weighted score: its value (the average when it has none, and at least 1) times its chance of winning (the
49
+ * average probability when it has none, or 10%), divided by the days until its expected close (30 when it has none,
50
+ * and at least 1, so overdue deals count as due now). Values are compared in minor units, whatever the currency.
51
+ */
52
+ export function weightedScore(deal: Deal, defaults: WeightDefaults, now: Date): number {
53
+ const value = Math.max(1, deal.targetValue ? minorOf(deal.targetValue) : defaults.value);
54
+ const probability = typeof deal.probability === 'number' ? deal.probability : defaults.probability;
55
+ const days = Math.max(1, daysToClose(deal, now) ?? DEFAULT_DAYS_TO_CLOSE);
56
+ return (value * probability) / 100 / days;
57
+ }
58
+
59
+ /** Deals in `order`, ties by title. Averages for the weighted order come from all of `deals`. */
60
+ export function sortDeals(deals: readonly Deal[], order: DealOrder, now = new Date()): Deal[] {
61
+ const byTitle = (a: Deal, b: Deal) => a.title.localeCompare(b.title, 'en-GB');
62
+ switch (order) {
63
+ case 'weighted': {
64
+ const defaults = weightDefaults(deals);
65
+ const scores = new Map(deals.map((deal) => [deal.urn, weightedScore(deal, defaults, now)]));
66
+ return deals.toSorted((a, b) => scores.get(b.urn)! - scores.get(a.urn)! || byTitle(a, b));
67
+ }
68
+ case 'size':
69
+ return deals.toSorted((a, b) => minorOf(b.targetValue) - minorOf(a.targetValue) || byTitle(a, b));
70
+ case 'urgency':
71
+ return deals.toSorted((a, b) => {
72
+ const da = daysToClose(a, now) ?? Number.POSITIVE_INFINITY;
73
+ const db = daysToClose(b, now) ?? Number.POSITIVE_INFINITY;
74
+ return da === db ? byTitle(a, b) : da - db;
75
+ });
76
+ }
77
+ }
78
+
79
+ /** What a deals board shows. Absent fields don't filter; `null` assignee or company means "none". */
80
+ export interface DealFilter {
81
+ /** Words to find in the title, or the names of its companies, contacts and assignee. */
82
+ text?: string | undefined;
83
+ outcome?: DealOutcome | undefined;
84
+ assignee?: string | null | undefined;
85
+ company?: string | null | undefined;
86
+ }
87
+
88
+ /** Deals matching `filter`. `name` names a company or person, for the text search. */
89
+ export function filterDeals(
90
+ deals: readonly Deal[],
91
+ filter: DealFilter,
92
+ name: (urn: string) => string | undefined = () => undefined,
93
+ ): Deal[] {
94
+ const words = (filter.text ?? '').toLocaleLowerCase('en-GB').split(/\s+/).filter(Boolean);
95
+ return deals.filter((deal) => {
96
+ if (filter.outcome && dealOutcome(deal) !== filter.outcome) return false;
97
+ if (filter.assignee !== undefined && (deal.assignee?.urn ?? null) !== filter.assignee) return false;
98
+ if (filter.company !== undefined) {
99
+ const companies = deal.contactCompanies ?? [];
100
+ if (filter.company === null ? companies.length > 0 : !companies.some((c) => c.urn === filter.company))
101
+ return false;
102
+ }
103
+ if (words.length === 0) return true;
104
+ const haystack = [
105
+ deal.title,
106
+ ...[
107
+ ...(deal.contactCompanies ?? []),
108
+ ...(deal.contactIdentities ?? []),
109
+ ...(deal.assignee ? [deal.assignee] : []),
110
+ ].map((ref) => name(ref.urn) ?? ''),
111
+ ]
112
+ .join(' ')
113
+ .toLocaleLowerCase('en-GB');
114
+ return words.every((word) => haystack.includes(word));
115
+ });
116
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { CrmConcept } from './types.ts';
2
+
3
+ /**
4
+ * The Baack API doesn't offer this yet (leads, deals, remittances, listing invoices). Serve the concept from sample
5
+ * data (see `createCrmClient`) until it does.
6
+ */
7
+ export class CrmUnavailableError extends Error {
8
+ constructor(
9
+ readonly concept: CrmConcept,
10
+ readonly operation: string,
11
+ ) {
12
+ super(`The Baack API can't ${operation} ${concept} yet: serve them from sample data`);
13
+ this.name = 'CrmUnavailableError';
14
+ }
15
+ }
16
+
17
+ /** A record asked for by URN isn't there. */
18
+ export class CrmNotFoundError extends Error {
19
+ constructor(
20
+ readonly concept: CrmConcept,
21
+ readonly urn: string,
22
+ ) {
23
+ super(`No ${concept} record ${urn}`);
24
+ this.name = 'CrmNotFoundError';
25
+ }
26
+ }
27
+
28
+ /** A search didn't finish in time. */
29
+ export class CrmSearchTimeoutError extends Error {
30
+ constructor() {
31
+ super("The search didn't finish in time");
32
+ this.name = 'CrmSearchTimeoutError';
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ export * from './types.ts';
2
+ export * from './money.ts';
3
+ export * from './period.ts';
4
+ export * from './leads.ts';
5
+ export * from './pipeline.ts';
6
+ export * from './deal-order.ts';
7
+ export * from './target.ts';
8
+ export * from './invoices.ts';
9
+ export * from './account.ts';
10
+ export * from './sales.ts';
11
+ export * from './errors.ts';
12
+ export * from './backend.ts';
13
+ export * from './crm-client.ts';