@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,870 @@
1
+ import { useEffect, useId, useState, type FormEvent, type ReactNode } from 'react';
2
+ import type { DealInput, LeadInput } from '../backend.ts';
3
+ import type { NewLeadOptions } from '../crm-client.ts';
4
+ import { LEAD_SOURCES, LEAD_STATUS_LABELS, SOURCE_LABELS, leadOutcome } from '../leads.ts';
5
+ import { minorOf, toDecimal } from '../money.ts';
6
+ import { dealOutcome, dealProbability, orderedStages, pipelineOf, stageOf } from '../pipeline.ts';
7
+ import type {
8
+ ContactDetails,
9
+ Deal,
10
+ DealOutcome,
11
+ Lead,
12
+ LeadSource,
13
+ LeadStatus,
14
+ Money,
15
+ Pipeline,
16
+ PipelineStage,
17
+ } from '../types.ts';
18
+ import {
19
+ ChoiceSelect,
20
+ Field,
21
+ moneyOf,
22
+ MoneyInput,
23
+ NewCompanyStep,
24
+ NewContactStep,
25
+ PipelineStageFields,
26
+ type CrmChoice,
27
+ } from './Forms.tsx';
28
+ import { ChoiceCombobox } from './ChoiceCombobox.tsx';
29
+ import { StageSelect } from './DealsBoard.tsx';
30
+ import { companyNameOf, formatDate, formatMaybeMoney, personNameOf, type CrmNames } from './format.ts';
31
+ import { leadCompany } from './LeadsTable.tsx';
32
+ import { CrmCard, LeadStatusBadge, OutcomeBadge } from './parts.tsx';
33
+ import { withText, type CrmText } from './text.ts';
34
+ import { Button } from './ui/button.tsx';
35
+ import { Input } from './ui/input.tsx';
36
+ import { Label } from './ui/label.tsx';
37
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select.tsx';
38
+
39
+ /** Label and value pairs as a description list. */
40
+ export function DetailList({ items }: { items: { label: string; value: ReactNode }[] }) {
41
+ return (
42
+ <dl className="grid grid-cols-[minmax(7rem,auto)_minmax(0,1fr)] gap-x-4 gap-y-2 text-sm">
43
+ {items.map(({ label, value }) => (
44
+ <div key={label} className="contents">
45
+ <dt className="text-muted-foreground">{label}</dt>
46
+ <dd>{value}</dd>
47
+ </div>
48
+ ))}
49
+ </dl>
50
+ );
51
+ }
52
+
53
+ /** What converting a lead was asked to do: the company name confirmed or corrected, when the lead had no company. */
54
+ export interface ConvertChoice {
55
+ companyName?: string;
56
+ }
57
+
58
+ /** A text field that saves when it loses focus or Enter is pressed, and only when it changed. */
59
+ function CommitInput({
60
+ id,
61
+ value,
62
+ onCommit,
63
+ ...props
64
+ }: {
65
+ id: string;
66
+ value: string;
67
+ onCommit: (value: string) => void;
68
+ inputMode?: 'decimal';
69
+ type?: 'email' | 'tel';
70
+ autoComplete?: string;
71
+ disabled?: boolean;
72
+ }) {
73
+ const [draft, setDraft] = useState(value);
74
+ useEffect(() => setDraft(value), [value]);
75
+ const commit = () => {
76
+ if (draft.trim() !== value) onCommit(draft.trim());
77
+ };
78
+ return (
79
+ <Input
80
+ id={id}
81
+ value={draft}
82
+ onChange={(event) => setDraft(event.target.value)}
83
+ onBlur={commit}
84
+ onKeyDown={(event) => {
85
+ if (event.key === 'Enter') commit();
86
+ }}
87
+ {...props}
88
+ />
89
+ );
90
+ }
91
+
92
+ /**
93
+ * A record's money, saved as it changes: when the amount loses focus or Enter is pressed, or the currency is chosen.
94
+ * `onInvalid` is told when the amount isn't a number of at least zero.
95
+ */
96
+ function CommitMoney({
97
+ id,
98
+ value,
99
+ onCommit,
100
+ onInvalid,
101
+ text,
102
+ }: {
103
+ id: string;
104
+ value: Money | null | undefined;
105
+ onCommit: (money: Money | null) => void;
106
+ onInvalid: () => void;
107
+ text?: Partial<CrmText> | undefined;
108
+ }) {
109
+ const savedCurrency = value?.currencyCode ?? 'GBP';
110
+ const savedAmount = value ? toDecimal(minorOf(value), savedCurrency) : '';
111
+ const [amount, setAmount] = useState(savedAmount);
112
+ const [currency, setCurrency] = useState(savedCurrency);
113
+ useEffect(() => {
114
+ setAmount(savedAmount);
115
+ setCurrency(savedCurrency);
116
+ }, [savedAmount, savedCurrency]);
117
+ const commit = (nextAmount: string, nextCurrency: string) => {
118
+ if (nextAmount.trim() === savedAmount && nextCurrency === savedCurrency) return;
119
+ const money = moneyOf(nextAmount, nextCurrency);
120
+ if (money === undefined) return onInvalid();
121
+ // No amount yet: the currency is kept here until there's an amount to save in it.
122
+ if (money === null && !value) return;
123
+ onCommit(money);
124
+ };
125
+ return (
126
+ <MoneyInput
127
+ id={id}
128
+ amount={amount}
129
+ currencyCode={currency}
130
+ onAmount={setAmount}
131
+ onCurrency={(next) => {
132
+ setCurrency(next);
133
+ commit(amount, next);
134
+ }}
135
+ onCommit={() => commit(amount, currency)}
136
+ text={text}
137
+ />
138
+ );
139
+ }
140
+
141
+ /** Reads and sets people's email and telephone, such as `CrmStore.contactDetails` and `setContactDetails`. */
142
+ export interface ContactDetailsAccess {
143
+ load: (identity: string) => Promise<ContactDetails>;
144
+ save: (identity: string, details: Partial<ContactDetails>) => Promise<ContactDetails>;
145
+ }
146
+
147
+ /**
148
+ * The chosen contact's email and telephone, read from their record and saved there as they change: on the person, not
149
+ * the lead or deal, so every record with them as contact sees the change.
150
+ */
151
+ function ContactDetailsFields({
152
+ id,
153
+ contact,
154
+ name,
155
+ access,
156
+ text,
157
+ }: {
158
+ id: string;
159
+ contact: string;
160
+ /** The contact's name, shown above their fields and in their labels, when the record has several contacts. */
161
+ name?: string | undefined;
162
+ access: ContactDetailsAccess;
163
+ text?: Partial<CrmText> | undefined;
164
+ }) {
165
+ const words = withText(text);
166
+ const [details, setDetails] = useState<ContactDetails>();
167
+ const [error, setError] = useState<string>();
168
+ useEffect(() => {
169
+ let current = true;
170
+ setDetails(undefined);
171
+ setError(undefined);
172
+ access
173
+ .load(contact)
174
+ .then((loaded) => current && setDetails(loaded))
175
+ .catch(() => current && setError(words.contactDetailsUnavailable));
176
+ return () => {
177
+ current = false;
178
+ };
179
+ }, [access, contact, words.contactDetailsUnavailable]);
180
+ const save = async (changes: Partial<ContactDetails>) => {
181
+ setError(undefined);
182
+ try {
183
+ setDetails(await access.save(contact, changes));
184
+ } catch (failure) {
185
+ setError(`${words.saveFailed} ${failure instanceof Error ? failure.message : ''}`.trim());
186
+ }
187
+ };
188
+ return (
189
+ <fieldset className="grid gap-3 border-s-2 ps-3" aria-describedby={error ? `${id}-error` : undefined}>
190
+ <legend className={name ? 'text-sm font-medium' : 'sr-only'}>{name ?? words.contactDetails}</legend>
191
+ <Field id={`${id}-email`} label={name ? `${name}: ${words.email}` : words.contactEmail}>
192
+ <CommitInput
193
+ id={`${id}-email`}
194
+ type="email"
195
+ autoComplete="off"
196
+ value={details?.email ?? ''}
197
+ disabled={!details}
198
+ onCommit={(email) => void save({ email })}
199
+ />
200
+ </Field>
201
+ <Field id={`${id}-telephone`} label={name ? `${name}: ${words.telephone}` : words.contactTelephone}>
202
+ <CommitInput
203
+ id={`${id}-telephone`}
204
+ type="tel"
205
+ autoComplete="off"
206
+ value={details?.telephone ?? ''}
207
+ disabled={!details}
208
+ onCommit={(telephone) => void save({ telephone })}
209
+ />
210
+ </Field>
211
+ {error && (
212
+ <p id={`${id}-error`} role="alert" className="text-destructive text-sm">
213
+ {error}
214
+ </p>
215
+ )}
216
+ </fieldset>
217
+ );
218
+ }
219
+
220
+ /** Statuses a lead can be set to: qualified comes from converting it. */
221
+ const SETTABLE_STATUSES: readonly LeadStatus[] = ['NEW', 'CONTACTED'];
222
+
223
+ /**
224
+ * An open lead's fields, each saved as it changes: title, status, company, contact, source, value and assignee. The
225
+ * company and contact can be added: "Add a new ..." opens a step for its details, and saving it saves the lead.
226
+ */
227
+ function LeadFields({
228
+ lead,
229
+ names,
230
+ companies,
231
+ people,
232
+ team,
233
+ onChange,
234
+ saving,
235
+ contactDetails,
236
+ text,
237
+ }: {
238
+ lead: Lead;
239
+ names?: CrmNames | undefined;
240
+ companies: readonly CrmChoice[];
241
+ people: readonly CrmChoice[];
242
+ team: readonly CrmChoice[];
243
+ onChange: (changes: Partial<LeadInput>, options?: NewLeadOptions) => Promise<unknown>;
244
+ saving?: boolean | undefined;
245
+ contactDetails?: ContactDetailsAccess | undefined;
246
+ text?: Partial<CrmText> | undefined;
247
+ }) {
248
+ const words = withText(text);
249
+ const id = useId();
250
+ const [step, setStep] = useState<'fields' | 'company' | 'contact'>('fields');
251
+ const [error, setError] = useState<string>();
252
+ const save = async (changes: Partial<LeadInput>) => {
253
+ setError(undefined);
254
+ try {
255
+ await onChange(changes);
256
+ } catch (failure) {
257
+ setError(`${words.saveFailed} ${failure instanceof Error ? failure.message : ''}`.trim());
258
+ }
259
+ };
260
+ if (step === 'company')
261
+ return (
262
+ <NewCompanyStep
263
+ framed={false}
264
+ text={text}
265
+ onBack={() => setStep('fields')}
266
+ onUse={async (name) => {
267
+ // A new company replaces the lead's, so the link is cleared for it to be made.
268
+ await onChange({ contactCompany: null }, { companyName: name });
269
+ setStep('fields');
270
+ }}
271
+ />
272
+ );
273
+ if (step === 'contact')
274
+ return (
275
+ <NewContactStep
276
+ framed={false}
277
+ text={text}
278
+ onBack={() => setStep('fields')}
279
+ onUse={async (contact) => {
280
+ await onChange({}, { contact });
281
+ setStep('fields');
282
+ }}
283
+ />
284
+ );
285
+ const link = (urn: string) => (urn ? { urn } : null);
286
+ return (
287
+ <div className="grid gap-3">
288
+ <Field id={`${id}-title`} label={words.title}>
289
+ <CommitInput id={`${id}-title`} value={lead.title} onCommit={(title) => title && void save({ title })} />
290
+ </Field>
291
+ <Field id={`${id}-status`} label={words.status}>
292
+ <Select value={lead.status} onValueChange={(status) => void save({ status: status as LeadStatus })}>
293
+ <SelectTrigger id={`${id}-status`} className="w-full">
294
+ <SelectValue />
295
+ </SelectTrigger>
296
+ <SelectContent>
297
+ {[...new Set([...SETTABLE_STATUSES, lead.status])].map((status) => (
298
+ <SelectItem key={status} value={status} disabled={!SETTABLE_STATUSES.includes(status)}>
299
+ {LEAD_STATUS_LABELS[status]}
300
+ </SelectItem>
301
+ ))}
302
+ </SelectContent>
303
+ </Select>
304
+ </Field>
305
+ <Field id={`${id}-company`} label={words.company}>
306
+ <ChoiceSelect
307
+ id={`${id}-company`}
308
+ value={lead.contactCompany?.urn ?? ''}
309
+ onChange={(urn) => void save({ contactCompany: link(urn) })}
310
+ choices={companies}
311
+ none={words.noCompany}
312
+ add={{ label: words.addCompany, onAdd: () => setStep('company') }}
313
+ named={(urn) => companyNameOf(names, urn)}
314
+ text={text}
315
+ />
316
+ </Field>
317
+ <Field id={`${id}-contact`} label={words.contact}>
318
+ <ChoiceSelect
319
+ id={`${id}-contact`}
320
+ value={lead.contactIdentity?.urn ?? ''}
321
+ onChange={(urn) => void save({ contactIdentity: link(urn) })}
322
+ choices={people}
323
+ none={words.noContact}
324
+ add={{ label: words.addContact, onAdd: () => setStep('contact') }}
325
+ named={(urn) => personNameOf(names, urn)}
326
+ text={text}
327
+ />
328
+ </Field>
329
+ {lead.contactIdentity && contactDetails && (
330
+ <ContactDetailsFields
331
+ id={`${id}-contact-details`}
332
+ contact={lead.contactIdentity.urn}
333
+ access={contactDetails}
334
+ text={text}
335
+ />
336
+ )}
337
+ <Field id={`${id}-source`} label={words.source}>
338
+ <Select value={lead.source} onValueChange={(source) => void save({ source: source as LeadSource })}>
339
+ <SelectTrigger id={`${id}-source`} className="w-full">
340
+ <SelectValue />
341
+ </SelectTrigger>
342
+ <SelectContent>
343
+ {LEAD_SOURCES.map((source) => (
344
+ <SelectItem key={source} value={source}>
345
+ {SOURCE_LABELS[source]}
346
+ </SelectItem>
347
+ ))}
348
+ </SelectContent>
349
+ </Select>
350
+ </Field>
351
+ <Field id={`${id}-value`} label={words.value}>
352
+ <CommitMoney
353
+ id={`${id}-value`}
354
+ value={lead.targetValue}
355
+ onCommit={(targetValue) => void save({ targetValue })}
356
+ onInvalid={() => setError(words.invalidAmount)}
357
+ text={text}
358
+ />
359
+ </Field>
360
+ <Field id={`${id}-assignee`} label={words.assignee}>
361
+ <ChoiceSelect
362
+ id={`${id}-assignee`}
363
+ value={lead.assignee?.urn ?? ''}
364
+ onChange={(urn) => void save({ assignee: link(urn) })}
365
+ choices={team}
366
+ none={words.unassigned}
367
+ named={(urn) => personNameOf(names, urn)}
368
+ text={text}
369
+ />
370
+ </Field>
371
+ <p aria-live="polite" className="text-muted-foreground text-xs">
372
+ {saving ? words.saving : ''}
373
+ </p>
374
+ {error && (
375
+ <p role="alert" className="text-destructive text-sm">
376
+ {error}
377
+ </p>
378
+ )}
379
+ </div>
380
+ );
381
+ }
382
+
383
+ /**
384
+ * A lead's details. While it's open, its fields can be changed (with `onChange`), it can be converted ("Convert to
385
+ * deal", where the new client company's name can be corrected) and marked unqualified with why. Once unqualified it
386
+ * can be reopened.
387
+ */
388
+ export function LeadDetail({
389
+ lead,
390
+ names,
391
+ companies = [],
392
+ people = [],
393
+ team = [],
394
+ onChange,
395
+ onConvert,
396
+ onSetOutcome,
397
+ converting,
398
+ contactDetails,
399
+ sample,
400
+ text,
401
+ }: {
402
+ lead: Lead;
403
+ names?: CrmNames | undefined;
404
+ /** Companies the lead can be linked to: the host's customers. */
405
+ companies?: readonly CrmChoice[] | undefined;
406
+ /** People to choose as the contact: the host's customers' people. */
407
+ people?: readonly CrmChoice[] | undefined;
408
+ /** People to assign the lead to: the host's team. */
409
+ team?: readonly CrmChoice[] | undefined;
410
+ /** Saves a change to the open lead, making a new company or contact first when `options` asks. */
411
+ onChange?: ((changes: Partial<LeadInput>, options?: NewLeadOptions) => Promise<unknown>) | undefined;
412
+ /** Shown while the lead is open. */
413
+ onConvert?: ((lead: Lead, choice: ConvertChoice) => void) | undefined;
414
+ /** Unqualifies (with why) or reopens the lead. */
415
+ onSetOutcome?: ((lead: Lead, outcome: 'IN_PROGRESS' | 'CLOSED', closedReason?: string) => void) | undefined;
416
+ converting?: boolean | undefined;
417
+ /** Reads and sets the contact's email and telephone, shown under the contact when given. */
418
+ contactDetails?: ContactDetailsAccess | undefined;
419
+ sample?: boolean | undefined;
420
+ text?: Partial<CrmText> | undefined;
421
+ }) {
422
+ const words = withText(text);
423
+ const id = useId();
424
+ const [companyName, setCompanyName] = useState('');
425
+ const [unqualifying, setUnqualifying] = useState(false);
426
+ const [reason, setReason] = useState('');
427
+ const outcome = leadOutcome(lead);
428
+ const open = outcome === 'IN_PROGRESS';
429
+ const editable = open && onChange !== undefined;
430
+ const submit = (event: FormEvent) => {
431
+ event.preventDefault();
432
+ onConvert?.(lead, lead.contactCompany ? {} : { companyName: companyName.trim() });
433
+ };
434
+ return (
435
+ <CrmCard title={lead.title} sample={sample} text={text}>
436
+ <div className="grid gap-5">
437
+ {editable && (
438
+ <LeadFields
439
+ lead={lead}
440
+ names={names}
441
+ companies={companies}
442
+ people={people}
443
+ team={team}
444
+ onChange={onChange}
445
+ saving={converting}
446
+ contactDetails={contactDetails}
447
+ text={text}
448
+ />
449
+ )}
450
+ <DetailList
451
+ items={[
452
+ ...(editable ? [] : [{ label: words.status, value: <LeadStatusBadge lead={lead} /> }]),
453
+ // A lead has no close time of its own: it was last changed when it closed.
454
+ ...(!open ? [{ label: words.closed, value: formatDate(lead.updatedTimestamp) }] : []),
455
+ ...(lead.closedReason ? [{ label: words.unqualifiedReason, value: lead.closedReason }] : []),
456
+ ...(editable
457
+ ? []
458
+ : [
459
+ { label: words.contact, value: personNameOf(names, lead.contactIdentity?.urn) ?? '-' },
460
+ { label: words.company, value: leadCompany(lead, names) || '-' },
461
+ { label: words.source, value: SOURCE_LABELS[lead.source] },
462
+ { label: words.value, value: formatMaybeMoney(lead.targetValue) },
463
+ { label: words.assignee, value: personNameOf(names, lead.assignee?.urn) ?? '-' },
464
+ ]),
465
+ { label: words.created, value: formatDate(lead.createdTimestamp) },
466
+ ]}
467
+ />
468
+ {open && onConvert && (
469
+ <form onSubmit={submit} className="grid gap-3" aria-labelledby={`${id}-title`}>
470
+ <div className="grid gap-1">
471
+ <h3 id={`${id}-title`} className="text-sm font-semibold">
472
+ {words.convert}
473
+ </h3>
474
+ <p className="text-muted-foreground text-sm">{words.convertSummary}</p>
475
+ </div>
476
+ {!lead.contactCompany && (
477
+ <div className="grid gap-1.5">
478
+ <Label htmlFor={`${id}-company`}>{words.companyName}</Label>
479
+ <Input
480
+ id={`${id}-company`}
481
+ value={companyName}
482
+ onChange={(event) => setCompanyName(event.target.value)}
483
+ aria-describedby={`${id}-company-hint`}
484
+ />
485
+ <p id={`${id}-company-hint`} className="text-muted-foreground text-xs">
486
+ {words.companyNameHint}
487
+ </p>
488
+ </div>
489
+ )}
490
+ <div>
491
+ <Button type="submit" size="sm" disabled={converting ?? false}>
492
+ {converting ? words.converting : words.convert}
493
+ </Button>
494
+ </div>
495
+ </form>
496
+ )}
497
+ {open && onSetOutcome && !unqualifying && (
498
+ <div>
499
+ <Button type="button" size="sm" variant="outline" onClick={() => setUnqualifying(true)}>
500
+ {words.markUnqualified}
501
+ </Button>
502
+ </div>
503
+ )}
504
+ {open && onSetOutcome && unqualifying && (
505
+ <form
506
+ className="grid gap-2"
507
+ onSubmit={(event) => {
508
+ event.preventDefault();
509
+ setUnqualifying(false);
510
+ onSetOutcome(lead, 'CLOSED', reason);
511
+ }}
512
+ >
513
+ <Label htmlFor={`${id}-reason`}>{words.unqualifiedReason}</Label>
514
+ <Input id={`${id}-reason`} value={reason} onChange={(event) => setReason(event.target.value)} />
515
+ <div className="flex gap-2">
516
+ <Button type="submit" size="sm">
517
+ {words.markUnqualified}
518
+ </Button>
519
+ <Button type="button" size="sm" variant="ghost" onClick={() => setUnqualifying(false)}>
520
+ {words.cancel}
521
+ </Button>
522
+ </div>
523
+ </form>
524
+ )}
525
+ {outcome === 'CLOSED' && onSetOutcome && (
526
+ <div>
527
+ <Button type="button" size="sm" variant="outline" onClick={() => onSetOutcome(lead, 'IN_PROGRESS')}>
528
+ {words.reopen}
529
+ </Button>
530
+ </div>
531
+ )}
532
+ </div>
533
+ </CrmCard>
534
+ );
535
+ }
536
+
537
+ const OUTCOME_LABELS: Record<DealOutcome, keyof CrmText> = {
538
+ OPEN: 'outcomeOpen',
539
+ WON: 'outcomeWon',
540
+ LOST: 'outcomeLost',
541
+ };
542
+
543
+ /**
544
+ * Wins, loses or reopens a deal. Its outcome is on the deal, not its stage, as workflows are only progress. Open and
545
+ * won apply at once; lost asks why first.
546
+ */
547
+ export function OutcomeControl({
548
+ deal,
549
+ onSetOutcome,
550
+ disabled,
551
+ text,
552
+ }: {
553
+ deal: Deal;
554
+ onSetOutcome: (deal: Deal, outcome: DealOutcome, closedReason?: string) => void;
555
+ disabled?: boolean | undefined;
556
+ text?: Partial<CrmText> | undefined;
557
+ }) {
558
+ const words = withText(text);
559
+ const id = useId();
560
+ const [losing, setLosing] = useState(false);
561
+ const [reason, setReason] = useState(deal.lostReason ?? '');
562
+ const outcome = dealOutcome(deal);
563
+ return (
564
+ <div className="grid gap-2">
565
+ <Select
566
+ value={losing ? 'LOST' : outcome}
567
+ disabled={disabled ?? false}
568
+ onValueChange={(value) => {
569
+ if (value === 'LOST') return setLosing(true);
570
+ setLosing(false);
571
+ onSetOutcome(deal, value as DealOutcome);
572
+ }}
573
+ >
574
+ <SelectTrigger size="sm" aria-label={`${words.outcome}: ${deal.title}`}>
575
+ <SelectValue />
576
+ </SelectTrigger>
577
+ <SelectContent>
578
+ {(['OPEN', 'WON', 'LOST'] as const).map((value) => (
579
+ <SelectItem key={value} value={value}>
580
+ {words[OUTCOME_LABELS[value]]}
581
+ </SelectItem>
582
+ ))}
583
+ </SelectContent>
584
+ </Select>
585
+ {losing && (
586
+ <form
587
+ className="grid gap-2"
588
+ onSubmit={(event) => {
589
+ event.preventDefault();
590
+ setLosing(false);
591
+ onSetOutcome(deal, 'LOST', reason);
592
+ }}
593
+ >
594
+ <Label htmlFor={`${id}-reason`}>{words.lostReason}</Label>
595
+ <Input id={`${id}-reason`} value={reason} onChange={(event) => setReason(event.target.value)} />
596
+ <div className="flex gap-2">
597
+ <Button type="submit" size="sm">
598
+ {words.markLost}
599
+ </Button>
600
+ <Button type="button" size="sm" variant="ghost" onClick={() => setLosing(false)}>
601
+ {words.cancel}
602
+ </Button>
603
+ </div>
604
+ </form>
605
+ )}
606
+ </div>
607
+ );
608
+ }
609
+
610
+ /**
611
+ * A deal's fields, each saved as it changes: title, workflow and stage, companies and contacts (found by searching, each
612
+ * contact with their email and telephone), value, probability, expected close and assignee.
613
+ */
614
+ function DealFields({
615
+ deal,
616
+ pipelines,
617
+ names,
618
+ companies,
619
+ people,
620
+ team,
621
+ onChange,
622
+ onMove,
623
+ saving,
624
+ contactDetails,
625
+ text,
626
+ }: {
627
+ deal: Deal;
628
+ pipelines: readonly Pipeline[];
629
+ names?: CrmNames | undefined;
630
+ companies: readonly CrmChoice[];
631
+ people: readonly CrmChoice[];
632
+ team: readonly CrmChoice[];
633
+ onChange: (changes: Partial<DealInput>) => Promise<unknown>;
634
+ onMove?: ((deal: Deal, stage: PipelineStage) => void) | undefined;
635
+ saving?: boolean | undefined;
636
+ contactDetails?: ContactDetailsAccess | undefined;
637
+ text?: Partial<CrmText> | undefined;
638
+ }) {
639
+ const words = withText(text);
640
+ const id = useId();
641
+ const [error, setError] = useState<string>();
642
+ const save = async (changes: Partial<DealInput>) => {
643
+ setError(undefined);
644
+ try {
645
+ await onChange(changes);
646
+ } catch (failure) {
647
+ setError(`${words.saveFailed} ${failure instanceof Error ? failure.message : ''}`.trim());
648
+ }
649
+ };
650
+ return (
651
+ <div className="grid gap-3">
652
+ <Field id={`${id}-title`} label={words.title}>
653
+ <CommitInput id={`${id}-title`} value={deal.title} onCommit={(title) => title && void save({ title })} />
654
+ </Field>
655
+ <PipelineStageFields
656
+ id={id}
657
+ pipelines={pipelines}
658
+ stage={deal.workflowStage?.urn ?? ''}
659
+ onStage={(stage) => (onMove ? onMove(deal, stage) : void save({ workflowStage: { urn: stage.urn } }))}
660
+ disabled={saving}
661
+ text={text}
662
+ />
663
+ <Field id={`${id}-companies`} label={words.companies}>
664
+ <ChoiceCombobox
665
+ id={`${id}-companies`}
666
+ value={deal.contactCompanies.map((company) => company.urn)}
667
+ onChange={(urns) => void save({ contactCompanies: urns.map((urn) => ({ urn })) })}
668
+ choices={companies}
669
+ named={(urn) => companyNameOf(names, urn)}
670
+ placeholder={words.searchCompanies}
671
+ text={text}
672
+ />
673
+ </Field>
674
+ <Field id={`${id}-contacts`} label={words.contacts}>
675
+ <ChoiceCombobox
676
+ id={`${id}-contacts`}
677
+ value={deal.contactIdentities.map((contact) => contact.urn)}
678
+ onChange={(urns) => void save({ contactIdentities: urns.map((urn) => ({ urn })) })}
679
+ choices={people}
680
+ named={(urn) => personNameOf(names, urn)}
681
+ placeholder={words.searchContacts}
682
+ text={text}
683
+ />
684
+ </Field>
685
+ {contactDetails &&
686
+ deal.contactIdentities.map((contact, index) => (
687
+ <ContactDetailsFields
688
+ key={contact.urn}
689
+ id={`${id}-contact-${index}`}
690
+ contact={contact.urn}
691
+ // Each contact's fields are named for them when there are several.
692
+ name={deal.contactIdentities.length > 1 ? (personNameOf(names, contact.urn) ?? words.unnamed) : undefined}
693
+ access={contactDetails}
694
+ text={text}
695
+ />
696
+ ))}
697
+ <Field id={`${id}-value`} label={words.value}>
698
+ <CommitMoney
699
+ id={`${id}-value`}
700
+ value={deal.targetValue}
701
+ onCommit={(targetValue) => void save({ targetValue })}
702
+ onInvalid={() => setError(words.invalidAmount)}
703
+ text={text}
704
+ />
705
+ </Field>
706
+ <Field id={`${id}-probability`} label={`${words.probability} (%)`}>
707
+ <CommitInput
708
+ id={`${id}-probability`}
709
+ inputMode="decimal"
710
+ value={deal.probability === null || deal.probability === undefined ? '' : String(deal.probability)}
711
+ onCommit={(typed) => {
712
+ const chance = typed ? Number(typed) : null;
713
+ if (chance !== null && !(chance >= 0 && chance <= 100)) return setError(words.invalidProbability);
714
+ void save({ probability: chance });
715
+ }}
716
+ />
717
+ </Field>
718
+ <Field id={`${id}-close`} label={words.expectedClose}>
719
+ <Input
720
+ id={`${id}-close`}
721
+ type="date"
722
+ value={deal.targetCloseTimestamp?.slice(0, 10) ?? ''}
723
+ onChange={(event) =>
724
+ void save({ targetCloseTimestamp: event.target.value ? `${event.target.value}T00:00:00` : null })
725
+ }
726
+ />
727
+ </Field>
728
+ <Field id={`${id}-assignee`} label={words.assignee}>
729
+ <ChoiceSelect
730
+ id={`${id}-assignee`}
731
+ value={deal.assignee?.urn ?? ''}
732
+ onChange={(urn) => void save({ assignee: urn ? { urn } : null })}
733
+ choices={team}
734
+ none={words.unassigned}
735
+ named={(urn) => personNameOf(names, urn)}
736
+ text={text}
737
+ />
738
+ </Field>
739
+ <p aria-live="polite" className="text-muted-foreground text-xs">
740
+ {saving ? words.saving : ''}
741
+ </p>
742
+ {error && (
743
+ <p role="alert" className="text-destructive text-sm">
744
+ {error}
745
+ </p>
746
+ )}
747
+ </div>
748
+ );
749
+ }
750
+
751
+ /**
752
+ * A deal's details: with `onChange`, its fields can be edited, saved as they change; its outcome is set with
753
+ * `onSetOutcome`. Without them, read only.
754
+ */
755
+ export function DealDetail({
756
+ deal,
757
+ pipelines,
758
+ names,
759
+ companies = [],
760
+ people = [],
761
+ team = [],
762
+ onChange,
763
+ onMove,
764
+ onSetOutcome,
765
+ saving,
766
+ contactDetails,
767
+ sample,
768
+ text,
769
+ }: {
770
+ deal: Deal;
771
+ /** The workflows a deal can be in: its own is found from its stage. */
772
+ pipelines: readonly Pipeline[];
773
+ names?: CrmNames | undefined;
774
+ /** Companies the deal can be with: the host's customers. */
775
+ companies?: readonly CrmChoice[] | undefined;
776
+ /** People to choose as the contact: the host's customers' people. */
777
+ people?: readonly CrmChoice[] | undefined;
778
+ /** People to assign the deal to: the host's team. */
779
+ team?: readonly CrmChoice[] | undefined;
780
+ /** Saves a change to the deal's fields. */
781
+ onChange?: ((changes: Partial<DealInput>) => Promise<unknown>) | undefined;
782
+ onMove?: ((deal: Deal, stage: PipelineStage) => void) | undefined;
783
+ onSetOutcome?: ((deal: Deal, outcome: DealOutcome, closedReason?: string) => void) | undefined;
784
+ saving?: boolean | undefined;
785
+ /** Reads and sets the contact's email and telephone, shown under the contact when given. */
786
+ contactDetails?: ContactDetailsAccess | undefined;
787
+ sample?: boolean | undefined;
788
+ text?: Partial<CrmText> | undefined;
789
+ }) {
790
+ const words = withText(text);
791
+ const pipeline = pipelineOf(deal, pipelines) ?? pipelines[0];
792
+ const stage = pipeline && (stageOf(deal, pipeline) ?? orderedStages(pipeline)[0]);
793
+ const outcome = dealOutcome(deal);
794
+ const probability = dealProbability(deal);
795
+ const outcomeItem = {
796
+ label: words.outcome,
797
+ value: onSetOutcome ? (
798
+ <OutcomeControl key={deal.urn} deal={deal} onSetOutcome={onSetOutcome} disabled={saving} text={text} />
799
+ ) : (
800
+ <OutcomeBadge outcome={outcome} label={words[OUTCOME_LABELS[outcome]]} />
801
+ ),
802
+ };
803
+ if (onChange)
804
+ return (
805
+ <CrmCard title={deal.title} sample={sample} text={text}>
806
+ <div className="grid gap-5">
807
+ <DealFields
808
+ deal={deal}
809
+ pipelines={pipelines}
810
+ names={names}
811
+ companies={companies}
812
+ people={people}
813
+ team={team}
814
+ onChange={onChange}
815
+ onMove={onMove}
816
+ saving={saving}
817
+ contactDetails={contactDetails}
818
+ text={text}
819
+ />
820
+ <DetailList
821
+ items={[
822
+ outcomeItem,
823
+ ...(deal.closeTimestamp ? [{ label: words.closed, value: formatDate(deal.closeTimestamp) }] : []),
824
+ ...(deal.lostReason ? [{ label: words.lostReason, value: deal.lostReason }] : []),
825
+ { label: words.created, value: formatDate(deal.createdTimestamp) },
826
+ ]}
827
+ />
828
+ </div>
829
+ </CrmCard>
830
+ );
831
+ return (
832
+ <CrmCard title={deal.title} sample={sample} text={text}>
833
+ <DetailList
834
+ items={[
835
+ {
836
+ label: words.stage,
837
+ value:
838
+ onMove && pipeline ? (
839
+ <StageSelect deal={deal} pipeline={pipeline} onMove={onMove} disabled={saving} text={text} />
840
+ ) : (
841
+ (stage?.name ?? '-')
842
+ ),
843
+ },
844
+ outcomeItem,
845
+ {
846
+ label: words.company,
847
+ value:
848
+ deal.contactCompanies.map((company) => companyNameOf(names, company.urn) ?? words.unnamed).join(', ') ||
849
+ '-',
850
+ },
851
+ {
852
+ label: words.contact,
853
+ value:
854
+ deal.contactIdentities.map((contact) => personNameOf(names, contact.urn) ?? words.unnamed).join(', ') ||
855
+ '-',
856
+ },
857
+ { label: words.value, value: formatMaybeMoney(deal.targetValue) },
858
+ { label: words.probability, value: probability === undefined ? '-' : `${probability}%` },
859
+ {
860
+ label: deal.closeTimestamp ? words.closed : words.expectedClose,
861
+ value: formatDate(deal.closeTimestamp ?? deal.targetCloseTimestamp),
862
+ },
863
+ ...(deal.lostReason ? [{ label: words.lostReason, value: deal.lostReason }] : []),
864
+ { label: words.assignee, value: personNameOf(names, deal.assignee?.urn) ?? '-' },
865
+ { label: words.created, value: formatDate(deal.createdTimestamp) },
866
+ ]}
867
+ />
868
+ </CrmCard>
869
+ );
870
+ }