@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
package/src/backend.ts ADDED
@@ -0,0 +1,501 @@
1
+ import {
2
+ Endpoint,
3
+ type BaackClient,
4
+ type Company,
5
+ type IncludeScope,
6
+ type Search,
7
+ type Workflow,
8
+ } from '@baack-software/baack-ts-client';
9
+ import { toTimestamp, urnOf, type Ref, type RefLike } from '@baack-software/baack-ts-tasks';
10
+ import { CrmNotFoundError, CrmSearchTimeoutError } from './errors.ts';
11
+ import type {
12
+ ContactDetails,
13
+ CrmConcept,
14
+ CrmPerson,
15
+ Deal,
16
+ Invoice,
17
+ InvoiceLine,
18
+ InvoiceParty,
19
+ Lead,
20
+ NewContact,
21
+ Pipeline,
22
+ Remittance,
23
+ } from './types.ts';
24
+
25
+ /** Fields of a new record: everything but what the server sets. */
26
+ export type RecordInput<T> = Omit<T, 'urn' | 'url' | 'createdTimestamp' | 'updatedTimestamp'>;
27
+
28
+ export type LeadInput = RecordInput<Lead>;
29
+ export type DealInput = RecordInput<Deal>;
30
+ /** A new invoice: its lines and remittances are made on their own endpoints, once it exists. */
31
+ export type InvoiceInput = Omit<RecordInput<Invoice>, 'lines' | 'remittances'>;
32
+ export type RemittanceInput = RecordInput<Remittance>;
33
+ /** A new line on an existing invoice. */
34
+ export type InvoiceLineInput = Omit<InvoiceLine, 'urn'> & { paymentInvoice: Ref };
35
+
36
+ /** A concept that can only be read. */
37
+ export interface ReadApi<T> {
38
+ /** Every record a company owns. */
39
+ list(owner: RefLike): Promise<T[]>;
40
+ get(record: RefLike): Promise<T>;
41
+ }
42
+
43
+ /** A concept with full create, read, update and delete. */
44
+ export interface RecordApi<T, TInput> extends ReadApi<T> {
45
+ create(input: TInput): Promise<T>;
46
+ /** Applies `changes` and returns the record as stored. */
47
+ update(record: RefLike, changes: Partial<TInput>): Promise<T>;
48
+ delete(record: RefLike): Promise<void>;
49
+ }
50
+
51
+ /** Making client companies (baack-ts-client's `Company`): a company owned by the CRM's company, named. */
52
+ export interface CompanyApi {
53
+ create(input: { owner: RefLike; name: string }): Promise<Company>;
54
+ }
55
+
56
+ /**
57
+ * Making people: an identity owned by the CRM's company, linked to `company` (a customer) when given, with a person,
58
+ * the person's name, an email address and a telephone number. A person's email and telephone can be read and changed
59
+ * later, each kept as one record on their identity.
60
+ */
61
+ export interface PeopleApi {
62
+ createContact(input: { owner: RefLike; contact: NewContact; company?: RefLike | null }): Promise<CrmPerson>;
63
+ /** A person's email and telephone: the first of each on their identity. */
64
+ contactDetails(identity: RefLike): Promise<ContactDetails>;
65
+ /**
66
+ * Sets a person's email and telephone: the first of each on their identity is changed, made when there's none, and
67
+ * deleted when emptied. Fields left out are kept.
68
+ */
69
+ setContactDetails(identity: RefLike, details: Partial<ContactDetails>): Promise<ContactDetails>;
70
+ }
71
+
72
+ /** A contact's name, as shown: given and family name. */
73
+ export const contactName = ({ givenName, familyName }: NewContact): string =>
74
+ [givenName.trim(), familyName?.trim()].filter(Boolean).join(' ');
75
+
76
+ /**
77
+ * A contact's identity label: their initials, such as "J.S.". A label isn't held securely, so it never carries a
78
+ * person's name, which goes in the person name instead.
79
+ */
80
+ export const contactLabel = ({ givenName, familyName }: NewContact): string =>
81
+ [givenName, familyName ?? '']
82
+ .map((name) => name.trim().charAt(0).toUpperCase())
83
+ .filter(Boolean)
84
+ .map((initial) => `${initial}.`)
85
+ .join('');
86
+
87
+ /** Where each CRM concept is read and written. */
88
+ export interface CrmBackend {
89
+ /** Client companies, made when a lead is created or converted with a business name. */
90
+ companies: CompanyApi;
91
+ /** People, made as a lead's contact or a customer's person. */
92
+ people: PeopleApi;
93
+ leads: RecordApi<Lead, LeadInput>;
94
+ deals: RecordApi<Deal, DealInput>;
95
+ pipelines: ReadApi<Pipeline>;
96
+ invoices: RecordApi<Invoice, InvoiceInput>;
97
+ /** An invoice's lines are made on their own, once the invoice exists; they're read with it. */
98
+ invoiceLines: { create(input: InvoiceLineInput): Promise<InvoiceLine> };
99
+ remittances: RecordApi<Remittance, RemittanceInput>;
100
+ }
101
+
102
+ // ==========================================
103
+ // THE BAACK API
104
+ // ==========================================
105
+
106
+ const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
107
+
108
+ /** The URNs of everything a company owns in one search scope: created, read again until full, pages followed. */
109
+ async function searchUrns(
110
+ client: BaackClient,
111
+ owner: string,
112
+ scope: IncludeScope,
113
+ timeoutMs = 15_000,
114
+ ): Promise<string[]> {
115
+ let search: Search = await client.search({ owner: { urn: owner, url: '' }, includeScopes: [scope], order: 'NAME' });
116
+ const urn = search.urn;
117
+ if (!urn) throw new Error('The API created a search without a URN');
118
+ const started = Date.now();
119
+ for (let delay = 250; search.status !== 'FULL_RESULT'; delay = Math.min(delay * 1.5, 2000)) {
120
+ if (Date.now() - started > timeoutMs) throw new CrmSearchTimeoutError();
121
+ await wait(delay);
122
+ search = await client.searchResult(urn);
123
+ }
124
+ const urns = (search.items ?? []).map((item) => item.urn);
125
+ for (let page = search; page.pagination?.isMorePages && page.pagination.after;) {
126
+ page = await client.searchResult(urn, page.pagination.after);
127
+ urns.push(...(page.items ?? []).map((item) => item.urn));
128
+ }
129
+ return urns;
130
+ }
131
+
132
+ /** The API is rate limited (10 requests a second): records found by search are read a few at a time. */
133
+ const READS_AT_ONCE = 4;
134
+
135
+ async function readEach<T>(urns: readonly string[], read: (urn: string) => Promise<T>): Promise<T[]> {
136
+ const records: T[] = new Array(urns.length);
137
+ let next = 0;
138
+ const worker = async () => {
139
+ for (let index = next++; index < urns.length; index = next++) records[index] = await read(urns[index]!);
140
+ };
141
+ await Promise.all(Array.from({ length: Math.min(READS_AT_ONCE, urns.length) }, worker));
142
+ return records;
143
+ }
144
+
145
+ /** Any of the API's links, which are the same type with only a URN (and URL) set. */
146
+ type Linked = { urn?: string | null } | null | undefined;
147
+
148
+ /** A link as a ref, or null when it's absent or empty (the API has answered a missing link as `{ urn: "" }`). */
149
+ const link = (value: Linked): Ref | null => (value?.urn ? { urn: value.urn } : null);
150
+ const links = (values: readonly Linked[] | null | undefined): Ref[] =>
151
+ (values ?? []).flatMap((value) => (value?.urn ? [{ urn: value.urn }] : []));
152
+ const party = (value: { company?: Linked; identity?: Linked } | null | undefined): InvoiceParty | null => {
153
+ const company = link(value?.company);
154
+ const identity = link(value?.identity);
155
+ return company || identity ? { company, identity } : null;
156
+ };
157
+ /** An empty text as absent: the API answers an unset reason as "". */
158
+ const text = (value: string | null | undefined) => value || null;
159
+
160
+ /** The fields of the API's representations that are turned into the package's: links as refs, lists present. */
161
+ interface Raw {
162
+ urn: string;
163
+ owner?: Linked;
164
+ assignee?: Linked;
165
+ entity?: Linked;
166
+ contactIdentity?: Linked;
167
+ contactCompany?: Linked;
168
+ contactCompanies?: Linked[] | null;
169
+ contactIdentities?: Linked[] | null;
170
+ workflowStage?: Linked;
171
+ leadSource?: Linked;
172
+ invoices?: Linked[] | null;
173
+ closedReason?: string | null;
174
+ lostReason?: string | null;
175
+ remitter?: { company?: Linked; identity?: Linked } | null;
176
+ recipient?: { company?: Linked; identity?: Linked } | null;
177
+ lines?: unknown[] | null;
178
+ remittances?: Raw[] | null;
179
+ paymentInvoice?: Linked;
180
+ remittingCompany?: Linked;
181
+ remittingIdentity?: Linked;
182
+ }
183
+
184
+ // The API's representations as the package's: links as refs, lists always present.
185
+
186
+ const asLead = (raw: Raw): Lead =>
187
+ ({
188
+ ...raw,
189
+ owner: link(raw.owner)!,
190
+ contactIdentity: link(raw.contactIdentity),
191
+ contactCompany: link(raw.contactCompany),
192
+ assignee: link(raw.assignee),
193
+ entity: link(raw.entity),
194
+ closedReason: text(raw.closedReason),
195
+ }) as unknown as Lead;
196
+
197
+ const asDeal = (raw: Raw): Deal =>
198
+ ({
199
+ ...raw,
200
+ owner: link(raw.owner)!,
201
+ contactCompanies: links(raw.contactCompanies),
202
+ contactIdentities: links(raw.contactIdentities),
203
+ workflowStage: link(raw.workflowStage),
204
+ leadSource: link(raw.leadSource),
205
+ assignee: link(raw.assignee),
206
+ invoices: links(raw.invoices),
207
+ entity: link(raw.entity),
208
+ lostReason: text(raw.lostReason),
209
+ }) as unknown as Deal;
210
+
211
+ const asRemittance = (raw: Raw, invoice?: string): Remittance =>
212
+ ({
213
+ ...raw,
214
+ // On its invoice, a remittance's own link to the invoice can be absent: it's the invoice it's listed on.
215
+ paymentInvoice: link(raw.paymentInvoice) ?? { urn: invoice ?? '' },
216
+ remittingCompany: link(raw.remittingCompany),
217
+ remittingIdentity: link(raw.remittingIdentity),
218
+ }) as unknown as Remittance;
219
+
220
+ const asInvoice = (raw: Raw): Invoice =>
221
+ ({
222
+ ...raw,
223
+ owner: link(raw.owner)!,
224
+ remitter: party(raw.remitter),
225
+ recipient: party(raw.recipient),
226
+ lines: raw.lines ?? [],
227
+ remittances: (raw.remittances ?? []).map((remittance) => asRemittance(remittance, raw.urn)),
228
+ }) as unknown as Invoice;
229
+
230
+ /**
231
+ * One concept on the API: listed by search in `scope` then read a few at a time, read by URN, created, updated (the
232
+ * record is read, the changes merged in, and the whole of it sent, as the API replaces on update; then read back) and
233
+ * deleted. `as` turns the API's representation into the package's.
234
+ */
235
+ function onApi<T, TInput>(
236
+ client: BaackClient,
237
+ endpoint: string,
238
+ scope: IncludeScope,
239
+ as: (raw: Raw) => T,
240
+ omit: readonly string[] = [],
241
+ ): RecordApi<T, TInput> {
242
+ const read = async (urn: string) => as(await client.read<Raw>(endpoint, urn));
243
+ const body = (record: object) =>
244
+ Object.fromEntries(Object.entries(record).filter(([field]) => !omit.includes(field)));
245
+ return {
246
+ list: async (owner) => readEach(await searchUrns(client, urnOf(owner), scope), read),
247
+ get: (record) => read(urnOf(record)),
248
+ create: async (input) => as(await client.create<Raw>(endpoint, body(input as object))),
249
+ async update(record, changes) {
250
+ const urn = urnOf(record);
251
+ const current = await client.read<Raw>(endpoint, urn);
252
+ await client.update(endpoint, urn, body({ ...current, ...changes }));
253
+ return read(urn);
254
+ },
255
+ delete: async (record) => {
256
+ await client.delete(endpoint, urnOf(record));
257
+ },
258
+ };
259
+ }
260
+
261
+ /**
262
+ * Every CRM concept on the Baack API: leads, deals and payment invoices found by search; remittances, which have no
263
+ * owner, through their invoices; pipelines are the company's workflows.
264
+ */
265
+ export function apiBackend(client: BaackClient): CrmBackend {
266
+ const invoices = onApi<Invoice, InvoiceInput>(client, Endpoint.PAYMENT_INVOICE, 'PAYMENT_INVOICE', asInvoice, [
267
+ // Ignored on update, and made on their own endpoints.
268
+ 'lines',
269
+ 'remittances',
270
+ ]);
271
+ const remittance = async (urn: string) => asRemittance(await client.read<Raw>(Endpoint.INVOICE_REMITTANCE, urn));
272
+ // An identity's emails and telephones, which the API returns with the identity.
273
+ const reachable = (urn: string) =>
274
+ client.read<{ emails?: { urn: string; email: string }[]; telephones?: { urn: string; number: string }[] }>(
275
+ Endpoint.IDENTITY,
276
+ urn,
277
+ );
278
+ const detailsOf = (identity: Awaited<ReturnType<typeof reachable>>): ContactDetails => ({
279
+ email: identity.emails?.[0]?.email ?? '',
280
+ telephone: identity.telephones?.[0]?.number ?? '',
281
+ });
282
+ // An identity's first email or telephone set to `value`: changed (read, merged and sent whole, as other updates
283
+ // are), made when there's none, deleted when emptied, and left alone when `value` is undefined or unchanged.
284
+ const setFirst = async (
285
+ endpoint: string,
286
+ existing: { urn: string; email?: string; number?: string } | undefined,
287
+ field: 'email' | 'number',
288
+ value: string | undefined,
289
+ identity: string,
290
+ ) => {
291
+ if (value === undefined) return;
292
+ const next = value.trim();
293
+ if (existing?.[field] === next) return;
294
+ if (existing && !next) return void (await client.delete(endpoint, existing.urn));
295
+ if (existing) {
296
+ const stored = await client.read<Raw>(endpoint, existing.urn);
297
+ return void (await client.update(endpoint, existing.urn, { ...stored, [field]: next }));
298
+ }
299
+ if (next) await client.create(endpoint, { identity: { urn: identity }, [field]: next });
300
+ };
301
+ return {
302
+ companies: {
303
+ create: ({ owner, name }) => client.create<Company>(Endpoint.COMPANY, { owner: { urn: urnOf(owner) }, name }),
304
+ },
305
+ people: {
306
+ // An identity, then its person, the person's name and the email, each on its own endpoint. If any of those is
307
+ // refused (an email the API doesn't accept, say), the identity is deleted, which takes what was made with it,
308
+ // so trying again doesn't leave a half-made contact behind.
309
+ async createContact({ owner, contact, company }) {
310
+ const identity = await client.create<{ urn: string }>(Endpoint.IDENTITY, {
311
+ owner: { urn: urnOf(owner) },
312
+ label: contactLabel(contact),
313
+ companies: company ? [{ urn: urnOf(company) }] : [],
314
+ });
315
+ try {
316
+ const person = await client.create<{ urn: string }>(Endpoint.PERSON, { identity: { urn: identity.urn } });
317
+ await client.create(Endpoint.PERSON_NAME, {
318
+ person: { urn: person.urn },
319
+ givenName: contact.givenName.trim(),
320
+ familyName: contact.familyName?.trim() || null,
321
+ });
322
+ const email = contact.email?.trim();
323
+ if (email) await client.create(Endpoint.EMAIL, { identity: { urn: identity.urn }, email });
324
+ const number = contact.telephone?.trim();
325
+ if (number) await client.create(Endpoint.TELEPHONE, { identity: { urn: identity.urn }, number });
326
+ } catch (error) {
327
+ await client.delete(Endpoint.IDENTITY, identity.urn).catch(() => undefined);
328
+ throw error;
329
+ }
330
+ return { urn: identity.urn, name: contactName(contact), company: company ? { urn: urnOf(company) } : null };
331
+ },
332
+ contactDetails: async (identity) => detailsOf(await reachable(urnOf(identity))),
333
+ async setContactDetails(identity, details) {
334
+ const urn = urnOf(identity);
335
+ const current = await reachable(urn);
336
+ await setFirst(Endpoint.EMAIL, current.emails?.[0], 'email', details.email, urn);
337
+ await setFirst(Endpoint.TELEPHONE, current.telephones?.[0], 'number', details.telephone, urn);
338
+ return detailsOf(await reachable(urn));
339
+ },
340
+ },
341
+ leads: onApi(client, Endpoint.LEAD, 'LEAD', asLead),
342
+ deals: onApi(client, Endpoint.DEAL, 'DEAL', asDeal),
343
+ invoices,
344
+ invoiceLines: { create: (input) => client.create<InvoiceLine>(Endpoint.INVOICE_LINE, input) },
345
+ remittances: {
346
+ list: async (owner) => (await invoices.list(owner)).flatMap((invoice) => invoice.remittances ?? []),
347
+ get: (record) => remittance(urnOf(record)),
348
+ create: async (input) => asRemittance(await client.create<Raw>(Endpoint.INVOICE_REMITTANCE, input)),
349
+ async update(record, changes) {
350
+ const urn = urnOf(record);
351
+ const current = await client.read<Raw>(Endpoint.INVOICE_REMITTANCE, urn);
352
+ await client.update(Endpoint.INVOICE_REMITTANCE, urn, { ...current, ...changes });
353
+ return remittance(urn);
354
+ },
355
+ delete: async (record) => {
356
+ await client.delete(Endpoint.INVOICE_REMITTANCE, urnOf(record));
357
+ },
358
+ },
359
+ pipelines: {
360
+ list: async (owner) =>
361
+ readEach(await searchUrns(client, urnOf(owner), 'WORKFLOW'), (urn) =>
362
+ client.read<Workflow>(Endpoint.WORKFLOW, urn),
363
+ ),
364
+ get: (record) => client.read<Workflow>(Endpoint.WORKFLOW, urnOf(record)),
365
+ },
366
+ };
367
+ }
368
+
369
+ // ==========================================
370
+ // IN MEMORY (sample data, tests, demos)
371
+ // ==========================================
372
+
373
+ /** The records an in-memory backend starts with. */
374
+ export interface CrmData {
375
+ leads: Lead[];
376
+ deals: Deal[];
377
+ pipelines: Pipeline[];
378
+ invoices: Invoice[];
379
+ /** Kept apart from their invoices here; the API lists them on the invoice. */
380
+ remittances: Remittance[];
381
+ }
382
+
383
+ export interface MemoryOptions {
384
+ /** Delay before each answer, to show loading states in demos. Default 0. */
385
+ latencyMs?: number;
386
+ /** New records' URNs. Default `crypto.randomUUID()`. */
387
+ newUrn?: () => string;
388
+ /** The time new and changed records are stamped with. Default now. */
389
+ now?: () => Date;
390
+ }
391
+
392
+ /**
393
+ * Every CRM concept held in memory, starting from `data` (copied, so the caller's arrays aren't changed). Writes
394
+ * behave as the API's would: create stamps a URN and times, update merges the changes, delete removes.
395
+ */
396
+ export function memoryBackend(data: CrmData, options: MemoryOptions = {}): CrmBackend {
397
+ const { latencyMs = 0, newUrn = () => crypto.randomUUID(), now = () => new Date() } = options;
398
+ const answer = async <T>(value: T): Promise<T> => {
399
+ if (latencyMs > 0) await wait(latencyMs);
400
+ return structuredClone(value);
401
+ };
402
+
403
+ function collection<T extends { urn: string }, TInput>(
404
+ concept: CrmConcept,
405
+ records: T[],
406
+ url: string,
407
+ stamped: boolean,
408
+ ownerOf: (record: T) => string | undefined,
409
+ ): RecordApi<T, TInput> {
410
+ const find = (record: RefLike) => {
411
+ const index = records.findIndex((candidate) => candidate.urn === urnOf(record));
412
+ if (index < 0) throw new CrmNotFoundError(concept, urnOf(record));
413
+ return index;
414
+ };
415
+ return {
416
+ list: async (owner) => answer(records.filter((record) => ownerOf(record) === urnOf(owner))),
417
+ get: async (record) => answer(records[find(record)]!),
418
+ async create(input) {
419
+ const urn = newUrn();
420
+ const time = toTimestamp(now());
421
+ const created = {
422
+ ...structuredClone(input),
423
+ urn,
424
+ url: `${url}${urn}`,
425
+ ...(stamped ? { createdTimestamp: time, updatedTimestamp: time } : {}),
426
+ } as unknown as T;
427
+ records.push(created);
428
+ return answer(created);
429
+ },
430
+ async update(record, changes) {
431
+ const index = find(record);
432
+ const updated = {
433
+ ...records[index]!,
434
+ ...structuredClone(changes),
435
+ ...(stamped ? { updatedTimestamp: toTimestamp(now()) } : {}),
436
+ };
437
+ records[index] = updated;
438
+ return answer(updated);
439
+ },
440
+ async delete(record) {
441
+ records.splice(find(record), 1);
442
+ await answer(undefined);
443
+ },
444
+ };
445
+ }
446
+
447
+ const copy = structuredClone(data);
448
+ const owned = (record: { owner?: { urn: string } | null }) => record.owner?.urn;
449
+ // A remittance has no owner: it's its invoice's owner's.
450
+ const invoiceOwner = (remittance: Remittance) =>
451
+ copy.invoices.find((invoice) => invoice.urn === remittance.paymentInvoice.urn)?.owner.urn;
452
+ // Sample people's email and telephone, by identity URN; anyone else has none until they're set.
453
+ const details = new Map<string, ContactDetails>();
454
+ const detailsFor = (urn: string): ContactDetails => details.get(urn) ?? { email: '', telephone: '' };
455
+ return {
456
+ // Sample companies live only in memory: converting a sample lead never makes a real company.
457
+ companies: {
458
+ async create({ owner, name }) {
459
+ const urn = newUrn();
460
+ const company: Company = {
461
+ urn,
462
+ url: `/n/v1/company/${urn}`,
463
+ name,
464
+ owner: { urn: urnOf(owner), url: `/n/v1/company/${urnOf(owner)}` },
465
+ };
466
+ return answer(company);
467
+ },
468
+ },
469
+ // Sample people too: a sample lead's contact is never a real identity.
470
+ people: {
471
+ async createContact({ contact, company }) {
472
+ const urn = newUrn();
473
+ details.set(urn, { email: contact.email?.trim() ?? '', telephone: contact.telephone?.trim() ?? '' });
474
+ return answer({ urn, name: contactName(contact), company: company ? { urn: urnOf(company) } : null });
475
+ },
476
+ contactDetails: async (identity) => answer({ ...detailsFor(urnOf(identity)) }),
477
+ async setContactDetails(identity, changes) {
478
+ const urn = urnOf(identity);
479
+ const next = { ...detailsFor(urn) };
480
+ if (changes.email !== undefined) next.email = changes.email.trim();
481
+ if (changes.telephone !== undefined) next.telephone = changes.telephone.trim();
482
+ details.set(urn, next);
483
+ return answer({ ...next });
484
+ },
485
+ },
486
+ leads: collection('leads', copy.leads, '/n/v1/lead/', true, owned),
487
+ deals: collection('deals', copy.deals, '/n/v1/deal/', true, owned),
488
+ invoiceLines: {
489
+ async create({ paymentInvoice, ...fields }) {
490
+ const invoice = copy.invoices.find((candidate) => candidate.urn === paymentInvoice.urn);
491
+ if (!invoice) throw new CrmNotFoundError('invoices', paymentInvoice.urn);
492
+ const line: InvoiceLine = { ...structuredClone(fields), urn: newUrn() };
493
+ invoice.lines = [...(invoice.lines ?? []), line];
494
+ return answer(line);
495
+ },
496
+ },
497
+ remittances: collection('remittances', copy.remittances, '/n/v1/invoiceremittance/', false, invoiceOwner),
498
+ pipelines: collection('pipelines', copy.pipelines, '', false, owned),
499
+ invoices: collection('invoices', copy.invoices, '/n/v1/paymentinvoice/', false, owned),
500
+ };
501
+ }