@baack-software/baack-ts-crm 0.0.2 → 0.0.4

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 (112) hide show
  1. package/dist/backend.d.ts +29 -1
  2. package/dist/backend.d.ts.map +1 -1
  3. package/dist/backend.js +95 -0
  4. package/dist/backend.js.map +1 -1
  5. package/dist/crm-client.d.ts +55 -13
  6. package/dist/crm-client.d.ts.map +1 -1
  7. package/dist/crm-client.js +99 -15
  8. package/dist/crm-client.js.map +1 -1
  9. package/dist/deal-order.d.ts +42 -0
  10. package/dist/deal-order.d.ts.map +1 -0
  11. package/dist/deal-order.js +80 -0
  12. package/dist/deal-order.js.map +1 -0
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/invoices.d.ts +7 -0
  18. package/dist/invoices.d.ts.map +1 -1
  19. package/dist/invoices.js +20 -2
  20. package/dist/invoices.js.map +1 -1
  21. package/dist/period.d.ts +15 -2
  22. package/dist/period.d.ts.map +1 -1
  23. package/dist/period.js +27 -1
  24. package/dist/period.js.map +1 -1
  25. package/dist/pipeline.d.ts +6 -0
  26. package/dist/pipeline.d.ts.map +1 -1
  27. package/dist/pipeline.js +18 -0
  28. package/dist/pipeline.js.map +1 -1
  29. package/dist/react/ChoiceCombobox.d.ts +36 -0
  30. package/dist/react/ChoiceCombobox.d.ts.map +1 -0
  31. package/dist/react/ChoiceCombobox.js +105 -0
  32. package/dist/react/ChoiceCombobox.js.map +1 -0
  33. package/dist/react/DealsBoard.d.ts +22 -3
  34. package/dist/react/DealsBoard.d.ts.map +1 -1
  35. package/dist/react/DealsBoard.js +53 -4
  36. package/dist/react/DealsBoard.js.map +1 -1
  37. package/dist/react/Details.d.ts +40 -7
  38. package/dist/react/Details.d.ts.map +1 -1
  39. package/dist/react/Details.js +180 -23
  40. package/dist/react/Details.js.map +1 -1
  41. package/dist/react/Forms.d.ts +148 -17
  42. package/dist/react/Forms.d.ts.map +1 -1
  43. package/dist/react/Forms.js +365 -75
  44. package/dist/react/Forms.js.map +1 -1
  45. package/dist/react/Sales.d.ts +25 -6
  46. package/dist/react/Sales.d.ts.map +1 -1
  47. package/dist/react/Sales.js +114 -30
  48. package/dist/react/Sales.js.map +1 -1
  49. package/dist/react/SidePanel.d.ts +10 -0
  50. package/dist/react/SidePanel.d.ts.map +1 -1
  51. package/dist/react/SidePanel.js +18 -3
  52. package/dist/react/SidePanel.js.map +1 -1
  53. package/dist/react/index.d.ts +1 -0
  54. package/dist/react/index.d.ts.map +1 -1
  55. package/dist/react/index.js +1 -0
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/react/parts.d.ts +12 -2
  58. package/dist/react/parts.d.ts.map +1 -1
  59. package/dist/react/parts.js +25 -2
  60. package/dist/react/parts.js.map +1 -1
  61. package/dist/react/pipeline-choice.d.ts +19 -0
  62. package/dist/react/pipeline-choice.d.ts.map +1 -0
  63. package/dist/react/pipeline-choice.js +39 -0
  64. package/dist/react/pipeline-choice.js.map +1 -0
  65. package/dist/react/text.d.ts +89 -2
  66. package/dist/react/text.d.ts.map +1 -1
  67. package/dist/react/text.js +89 -2
  68. package/dist/react/text.js.map +1 -1
  69. package/dist/react/ui/badge.d.ts +1 -1
  70. package/dist/react/ui/button.d.ts +2 -2
  71. package/dist/react/views.d.ts +33 -11
  72. package/dist/react/views.d.ts.map +1 -1
  73. package/dist/react/views.js +96 -27
  74. package/dist/react/views.js.map +1 -1
  75. package/dist/sales.d.ts +28 -3
  76. package/dist/sales.d.ts.map +1 -1
  77. package/dist/sales.js +33 -10
  78. package/dist/sales.js.map +1 -1
  79. package/dist/store.d.ts +31 -12
  80. package/dist/store.d.ts.map +1 -1
  81. package/dist/store.js +82 -21
  82. package/dist/store.js.map +1 -1
  83. package/dist/target.d.ts +2 -1
  84. package/dist/target.d.ts.map +1 -1
  85. package/dist/target.js +6 -2
  86. package/dist/target.js.map +1 -1
  87. package/dist/types.d.ts +24 -0
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/backend.ts +131 -1
  92. package/src/crm-client.ts +162 -19
  93. package/src/deal-order.ts +116 -0
  94. package/src/index.ts +1 -0
  95. package/src/invoices.ts +22 -2
  96. package/src/period.ts +41 -2
  97. package/src/pipeline.ts +21 -0
  98. package/src/react/ChoiceCombobox.tsx +227 -0
  99. package/src/react/DealsBoard.tsx +171 -4
  100. package/src/react/Details.tsx +608 -31
  101. package/src/react/Forms.tsx +1006 -139
  102. package/src/react/Sales.tsx +332 -44
  103. package/src/react/SidePanel.tsx +22 -11
  104. package/src/react/index.ts +1 -0
  105. package/src/react/parts.tsx +56 -4
  106. package/src/react/pipeline-choice.ts +54 -0
  107. package/src/react/text.ts +90 -2
  108. package/src/react/views.tsx +222 -32
  109. package/src/sales.ts +57 -10
  110. package/src/store.ts +136 -27
  111. package/src/target.ts +5 -2
  112. package/src/types.ts +28 -0
@@ -1,7 +1,31 @@
1
- import { useId, useState, type FormEvent, type ReactNode } from 'react';
2
- import { SOURCE_LABELS, leadOutcome } from '../leads.ts';
3
- import { dealOutcome, dealProbability, orderedStages, stageOf } from '../pipeline.ts';
4
- import type { Deal, DealOutcome, Lead, Pipeline, PipelineStage } from '../types.ts';
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';
5
29
  import { StageSelect } from './DealsBoard.tsx';
6
30
  import { companyNameOf, formatDate, formatMaybeMoney, personNameOf, type CrmNames } from './format.ts';
7
31
  import { leadCompany } from './LeadsTable.tsx';
@@ -31,26 +55,367 @@ export interface ConvertChoice {
31
55
  companyName?: string;
32
56
  }
33
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
+
34
223
  /**
35
- * A lead's details. While it's open: "Convert to deal", where the new client company's name can be corrected, and
36
- * "Mark unqualified" with why. Once unqualified it can be reopened.
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.
37
387
  */
38
388
  export function LeadDetail({
39
389
  lead,
40
390
  names,
391
+ companies = [],
392
+ people = [],
393
+ team = [],
394
+ onChange,
41
395
  onConvert,
42
396
  onSetOutcome,
43
397
  converting,
398
+ contactDetails,
44
399
  sample,
45
400
  text,
46
401
  }: {
47
402
  lead: Lead;
48
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;
49
412
  /** Shown while the lead is open. */
50
413
  onConvert?: ((lead: Lead, choice: ConvertChoice) => void) | undefined;
51
414
  /** Unqualifies (with why) or reopens the lead. */
52
415
  onSetOutcome?: ((lead: Lead, outcome: 'IN_PROGRESS' | 'CLOSED', closedReason?: string) => void) | undefined;
53
416
  converting?: boolean | undefined;
417
+ /** Reads and sets the contact's email and telephone, shown under the contact when given. */
418
+ contactDetails?: ContactDetailsAccess | undefined;
54
419
  sample?: boolean | undefined;
55
420
  text?: Partial<CrmText> | undefined;
56
421
  }) {
@@ -61,6 +426,7 @@ export function LeadDetail({
61
426
  const [reason, setReason] = useState('');
62
427
  const outcome = leadOutcome(lead);
63
428
  const open = outcome === 'IN_PROGRESS';
429
+ const editable = open && onChange !== undefined;
64
430
  const submit = (event: FormEvent) => {
65
431
  event.preventDefault();
66
432
  onConvert?.(lead, lead.contactCompany ? {} : { companyName: companyName.trim() });
@@ -68,17 +434,34 @@ export function LeadDetail({
68
434
  return (
69
435
  <CrmCard title={lead.title} sample={sample} text={text}>
70
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
+ )}
71
450
  <DetailList
72
451
  items={[
73
- { label: words.status, value: <LeadStatusBadge lead={lead} /> },
452
+ ...(editable ? [] : [{ label: words.status, value: <LeadStatusBadge lead={lead} /> }]),
74
453
  // A lead has no close time of its own: it was last changed when it closed.
75
454
  ...(!open ? [{ label: words.closed, value: formatDate(lead.updatedTimestamp) }] : []),
76
455
  ...(lead.closedReason ? [{ label: words.unqualifiedReason, value: lead.closedReason }] : []),
77
- { label: words.contact, value: personNameOf(names, lead.contactIdentity?.urn) ?? '-' },
78
- { label: words.company, value: leadCompany(lead, names) || '-' },
79
- { label: words.source, value: SOURCE_LABELS[lead.source] },
80
- { label: words.value, value: formatMaybeMoney(lead.targetValue) },
81
- { label: words.assignee, value: personNameOf(names, lead.assignee?.urn) ?? '-' },
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
+ ]),
82
465
  { label: words.created, value: formatDate(lead.createdTimestamp) },
83
466
  ]}
84
467
  />
@@ -224,58 +607,252 @@ export function OutcomeControl({
224
607
  );
225
608
  }
226
609
 
227
- /** A deal's details, with its stage picker and its outcome (open, won or lost). */
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
+ */
228
755
  export function DealDetail({
229
756
  deal,
230
- pipeline,
757
+ pipelines,
231
758
  names,
759
+ companies = [],
760
+ people = [],
761
+ team = [],
762
+ onChange,
232
763
  onMove,
233
764
  onSetOutcome,
234
765
  saving,
766
+ contactDetails,
235
767
  sample,
236
768
  text,
237
769
  }: {
238
770
  deal: Deal;
239
- pipeline: Pipeline;
771
+ /** The workflows a deal can be in: its own is found from its stage. */
772
+ pipelines: readonly Pipeline[];
240
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;
241
782
  onMove?: ((deal: Deal, stage: PipelineStage) => void) | undefined;
242
783
  onSetOutcome?: ((deal: Deal, outcome: DealOutcome, closedReason?: string) => void) | undefined;
243
784
  saving?: boolean | undefined;
785
+ /** Reads and sets the contact's email and telephone, shown under the contact when given. */
786
+ contactDetails?: ContactDetailsAccess | undefined;
244
787
  sample?: boolean | undefined;
245
788
  text?: Partial<CrmText> | undefined;
246
789
  }) {
247
790
  const words = withText(text);
248
- const stage = stageOf(deal, pipeline) ?? orderedStages(pipeline)[0];
791
+ const pipeline = pipelineOf(deal, pipelines) ?? pipelines[0];
792
+ const stage = pipeline && (stageOf(deal, pipeline) ?? orderedStages(pipeline)[0]);
249
793
  const outcome = dealOutcome(deal);
250
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
+ );
251
831
  return (
252
832
  <CrmCard title={deal.title} sample={sample} text={text}>
253
833
  <DetailList
254
834
  items={[
255
835
  {
256
836
  label: words.stage,
257
- value: onMove ? (
258
- <StageSelect deal={deal} pipeline={pipeline} onMove={onMove} disabled={saving} text={text} />
259
- ) : (
260
- (stage?.name ?? '-')
261
- ),
262
- },
263
- {
264
- label: words.outcome,
265
- value: onSetOutcome ? (
266
- <OutcomeControl key={deal.urn} deal={deal} onSetOutcome={onSetOutcome} disabled={saving} text={text} />
267
- ) : (
268
- <OutcomeBadge outcome={outcome} label={words[OUTCOME_LABELS[outcome]]} />
269
- ),
837
+ value:
838
+ onMove && pipeline ? (
839
+ <StageSelect deal={deal} pipeline={pipeline} onMove={onMove} disabled={saving} text={text} />
840
+ ) : (
841
+ (stage?.name ?? '-')
842
+ ),
270
843
  },
844
+ outcomeItem,
271
845
  {
272
846
  label: words.company,
273
- value: deal.contactCompanies.map((company) => companyNameOf(names, company.urn) ?? words.unnamed).join(', ') || '-',
847
+ value:
848
+ deal.contactCompanies.map((company) => companyNameOf(names, company.urn) ?? words.unnamed).join(', ') ||
849
+ '-',
274
850
  },
275
851
  {
276
852
  label: words.contact,
277
853
  value:
278
- deal.contactIdentities.map((contact) => personNameOf(names, contact.urn) ?? words.unnamed).join(', ') || '-',
854
+ deal.contactIdentities.map((contact) => personNameOf(names, contact.urn) ?? words.unnamed).join(', ') ||
855
+ '-',
279
856
  },
280
857
  { label: words.value, value: formatMaybeMoney(deal.targetValue) },
281
858
  { label: words.probability, value: probability === undefined ? '-' : `${probability}%` },