@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,24 +1,49 @@
1
1
  import { ref, type RefLike } from '@baack-software/baack-ts-tasks';
2
- import { Plus, X } from 'lucide-react';
2
+ import { ChevronRight, Plus, X } from 'lucide-react';
3
3
  import { useId, useState, type FormEvent, type ReactNode } from 'react';
4
4
  import type { DealInput, InvoiceInput, LeadInput } from '../backend.ts';
5
- import type { NewLeadOptions } from '../crm-client.ts';
5
+ import type { NewInvoiceOptions, NewLeadOptions } from '../crm-client.ts';
6
+ import { INVOICE_STATUSES, INVOICE_STATUS_LABELS } from '../invoices.ts';
6
7
  import { LEAD_SOURCES, SOURCE_LABELS } from '../leads.ts';
7
- import { fractionDigits, fromMinor, toMinor } from '../money.ts';
8
+ import { formatMoney, fractionDigits, fromMinor, toMinor } from '../money.ts';
8
9
  import { orderedStages } from '../pipeline.ts';
9
- import type { Deal, InvoiceStatus, LeadSource, Money, Pipeline } from '../types.ts';
10
+ import type {
11
+ Deal,
12
+ InvoiceStatus,
13
+ LeadSource,
14
+ Money,
15
+ NewContact,
16
+ Pipeline,
17
+ PipelineStage,
18
+ Taxability,
19
+ } from '../types.ts';
20
+ import { ChoiceCombobox } from './ChoiceCombobox.tsx';
21
+ import { PanelCloseButton } from './SidePanel.tsx';
10
22
  import { withText, type CrmText } from './text.ts';
11
23
  import { Button } from './ui/button.tsx';
24
+ import { Card, CardAction, CardContent, CardHeader, CardTitle } from './ui/card.tsx';
12
25
  import { Input } from './ui/input.tsx';
13
26
  import { Label } from './ui/label.tsx';
14
27
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select.tsx';
15
28
 
16
- /** A company the forms can link a record to: the host's customers, named. */
17
- export interface CrmCompanyChoice {
29
+ /**
30
+ * A record the forms can link to, named: one of the host's customers, or one of its people. `detail`, such as a
31
+ * person's email address, tells apart records with the same name.
32
+ */
33
+ export interface CrmChoice {
18
34
  urn: string;
19
35
  name: string;
36
+ detail?: string | undefined;
37
+ /** More to find it by when searching, such as a person's other emails and telephone numbers. */
38
+ keywords?: readonly string[] | undefined;
20
39
  }
21
40
 
41
+ /** A company the forms can link a record to: the host's customers. */
42
+ export type CrmCompanyChoice = CrmChoice;
43
+
44
+ /** A person the forms can link a record to, as its contact or assignee: the host's people. */
45
+ export type CrmPersonChoice = CrmChoice;
46
+
22
47
  interface FormProps {
23
48
  /** The company whose CRM this is. */
24
49
  owner: RefLike;
@@ -32,16 +57,25 @@ export interface InvoiceLineDraft {
32
57
  unitPrice: number;
33
58
  price: Money;
34
59
  tax: Money;
60
+ itemCode?: string;
61
+ discountRate?: number;
62
+ discountPrice?: Money;
63
+ taxability?: Taxability;
64
+ taxName?: string;
35
65
  }
36
66
 
37
67
  /** Radix's select keeps "" for "no value", so "none" is chosen with this instead. */
38
68
  const NONE = '__none__';
69
+ /** "Add a new ..." in a choice select. */
70
+ const ADD = '__add__';
71
+ /** A new record, made when the form is saved, shown as chosen. */
72
+ const PENDING = '__pending__';
39
73
 
40
74
  /**
41
75
  * An amount typed in major units (120.00, or 1,500.00 with separators) as minor units, or undefined when it isn't a
42
76
  * number of at least zero.
43
77
  */
44
- function minorOrUndefined(amount: string, currencyCode: string): number | undefined {
78
+ export function minorOrUndefined(amount: string, currencyCode: string): number | undefined {
45
79
  try {
46
80
  const minor = toMinor(amount.replaceAll(',', '').trim(), currencyCode);
47
81
  return minor >= 0 ? minor : undefined;
@@ -55,7 +89,10 @@ const dayTimestamp = (day: string) => (day ? `${day}T00:00:00` : null);
55
89
  const today = (now: Date) => now.toISOString().slice(0, 10);
56
90
  const inDays = (now: Date, days: number) => today(new Date(now.getTime() + days * 86_400_000));
57
91
 
58
- /** A form's frame: its heading, fields, problem and submit button, as the record payment form is laid out. */
92
+ /**
93
+ * A form's frame: a card, as an open record's is, with its heading (and the side panel's close button), fields,
94
+ * problem and submit button. `back` adds a way back beside the submit button, for a step of a larger form.
95
+ */
59
96
  function FormFrame({
60
97
  title,
61
98
  submit,
@@ -63,6 +100,8 @@ function FormFrame({
63
100
  saving,
64
101
  error,
65
102
  onSubmit,
103
+ back,
104
+ framed = true,
66
105
  children,
67
106
  }: {
68
107
  title: string;
@@ -71,11 +110,19 @@ function FormFrame({
71
110
  saving: boolean;
72
111
  error: string | undefined;
73
112
  onSubmit: () => Promise<void>;
113
+ back?: { label: string; onBack: () => void } | undefined;
114
+ /** False for a form inside another card, such as a step of an open lead: no card of its own. */
115
+ framed?: boolean | undefined;
74
116
  children: (ids: { error: string | undefined }) => ReactNode;
75
117
  }) {
76
118
  const id = useId();
77
119
  const errorId = error ? `${id}-error` : undefined;
78
- return (
120
+ const heading = (
121
+ <h2 id={`${id}-title`} className="text-base font-semibold">
122
+ {title}
123
+ </h2>
124
+ );
125
+ const form = (
79
126
  <form
80
127
  className="grid gap-3"
81
128
  aria-labelledby={`${id}-title`}
@@ -85,25 +132,55 @@ function FormFrame({
85
132
  void onSubmit();
86
133
  }}
87
134
  >
88
- <h2 id={`${id}-title`} className="text-base font-semibold">
89
- {title}
90
- </h2>
135
+ {!framed && (
136
+ <div className="flex items-center justify-between gap-2">
137
+ {heading}
138
+ <PanelCloseButton />
139
+ </div>
140
+ )}
91
141
  {children({ error: errorId })}
92
142
  {error && (
93
143
  <p id={errorId} role="alert" className="text-destructive text-sm">
94
144
  {error}
95
145
  </p>
96
146
  )}
97
- <div>
147
+ <div className="flex gap-2">
98
148
  <Button type="submit" disabled={saving}>
99
149
  {saving ? submitting : submit}
100
150
  </Button>
151
+ {back && (
152
+ <Button type="button" variant="ghost" onClick={back.onBack}>
153
+ {back.label}
154
+ </Button>
155
+ )}
101
156
  </div>
102
157
  </form>
103
158
  );
159
+ if (!framed) return form;
160
+ return (
161
+ <Card>
162
+ <CardHeader>
163
+ <CardTitle>{heading}</CardTitle>
164
+ <CardAction>
165
+ <PanelCloseButton />
166
+ </CardAction>
167
+ </CardHeader>
168
+ <CardContent>{form}</CardContent>
169
+ </Card>
170
+ );
104
171
  }
105
172
 
106
- function Field({ id, label, hint, children }: { id: string; label: string; hint?: string; children: ReactNode }) {
173
+ export function Field({
174
+ id,
175
+ label,
176
+ hint,
177
+ children,
178
+ }: {
179
+ id: string;
180
+ label: string;
181
+ hint?: string | undefined;
182
+ children: ReactNode;
183
+ }) {
107
184
  return (
108
185
  <div className="grid gap-1.5">
109
186
  <Label htmlFor={id}>{label}</Label>
@@ -117,36 +194,345 @@ function Field({ id, label, hint, children }: { id: string; label: string; hint?
117
194
  );
118
195
  }
119
196
 
120
- function CompanySelect({
197
+ /**
198
+ * A record to link: none, one of `choices`, or, with `add`, a new one made by the step `add` opens. A new one waiting
199
+ * to be made shows as chosen (`pending`, its name). A linked record missing from `choices` is still shown, named by
200
+ * `named` or by the end of its URN.
201
+ */
202
+ export function ChoiceSelect({
121
203
  id,
122
204
  value,
123
205
  onChange,
124
- companies,
206
+ choices,
125
207
  none,
208
+ add,
209
+ pending,
210
+ named,
211
+ disabled,
212
+ describedBy,
213
+ text,
126
214
  }: {
127
215
  id: string;
128
216
  value: string;
129
217
  onChange: (urn: string) => void;
130
- companies: readonly CrmCompanyChoice[];
218
+ choices: readonly CrmChoice[];
131
219
  none: string;
220
+ add?: { label: string; onAdd: () => void } | undefined;
221
+ pending?: string | undefined;
222
+ named?: ((urn: string) => string | undefined) | undefined;
223
+ disabled?: boolean | undefined;
224
+ describedBy?: string | undefined;
225
+ text?: Partial<CrmText> | undefined;
132
226
  }) {
227
+ const words = withText(text);
228
+ const missing = value && !choices.some((choice) => choice.urn === value) ? value : undefined;
133
229
  return (
134
- <Select value={value || NONE} onValueChange={(next) => onChange(next === NONE ? '' : next)}>
135
- <SelectTrigger id={id} className="w-full">
230
+ <Select
231
+ value={pending ? PENDING : value || NONE}
232
+ disabled={disabled ?? false}
233
+ onValueChange={(next) => {
234
+ if (next === ADD) add?.onAdd();
235
+ else if (next !== PENDING) onChange(next === NONE ? '' : next);
236
+ }}
237
+ >
238
+ <SelectTrigger id={id} className="w-full" aria-describedby={describedBy}>
136
239
  <SelectValue />
137
240
  </SelectTrigger>
138
241
  <SelectContent>
139
242
  <SelectItem value={NONE}>{none}</SelectItem>
140
- {companies.map((company) => (
141
- <SelectItem key={company.urn} value={company.urn}>
142
- {company.name}
243
+ {pending && <SelectItem value={PENDING}>{`${pending} (${words.toBeCreated})`}</SelectItem>}
244
+ {missing && <SelectItem value={missing}>{named?.(missing) ?? `...${missing.slice(-6)}`}</SelectItem>}
245
+ {choices.map((choice) => (
246
+ <SelectItem key={choice.urn} value={choice.urn}>
247
+ {choice.name}
248
+ {choice.detail && (
249
+ <>
250
+ {' '}
251
+ <span className="text-muted-foreground">{choice.detail}</span>
252
+ </>
253
+ )}
143
254
  </SelectItem>
144
255
  ))}
256
+ {add && <SelectItem value={ADD}>{add.label}</SelectItem>}
145
257
  </SelectContent>
146
258
  </Select>
147
259
  );
148
260
  }
149
261
 
262
+ /** The currencies offered for an amount, with the one it's already in when that's another. */
263
+ export const CURRENCIES: readonly string[] = ['GBP', 'EUR', 'USD'];
264
+
265
+ /**
266
+ * An amount of money: a currency select joined to the amount, typed in major units (1,500.00). The amount's input
267
+ * has `id`, so a field's label names it; the currency select is named by `currencyLabel`.
268
+ */
269
+ export function MoneyInput({
270
+ id,
271
+ amount,
272
+ currencyCode,
273
+ onAmount,
274
+ onCurrency,
275
+ onCommit,
276
+ describedBy,
277
+ text,
278
+ }: {
279
+ id: string;
280
+ amount: string;
281
+ currencyCode: string;
282
+ onAmount: (amount: string) => void;
283
+ onCurrency: (currencyCode: string) => void;
284
+ /** Called when the amount loses focus or Enter is pressed, for fields that save as they change. */
285
+ onCommit?: (() => void) | undefined;
286
+ describedBy?: string | undefined;
287
+ text?: Partial<CrmText> | undefined;
288
+ }) {
289
+ const words = withText(text);
290
+ const currencies = CURRENCIES.includes(currencyCode) ? CURRENCIES : [currencyCode, ...CURRENCIES];
291
+ return (
292
+ <div className="flex">
293
+ <Select value={currencyCode} onValueChange={onCurrency}>
294
+ <SelectTrigger aria-label={words.currency} className="w-24 shrink-0 rounded-e-none border-e-0">
295
+ <SelectValue />
296
+ </SelectTrigger>
297
+ <SelectContent>
298
+ {currencies.map((code) => (
299
+ <SelectItem key={code} value={code}>
300
+ {code}
301
+ </SelectItem>
302
+ ))}
303
+ </SelectContent>
304
+ </Select>
305
+ <Input
306
+ id={id}
307
+ inputMode="decimal"
308
+ className="rounded-s-none"
309
+ value={amount}
310
+ onChange={(event) => onAmount(event.target.value)}
311
+ onBlur={onCommit}
312
+ onKeyDown={(event) => {
313
+ if (event.key === 'Enter') onCommit?.();
314
+ }}
315
+ aria-describedby={describedBy}
316
+ />
317
+ </div>
318
+ );
319
+ }
320
+
321
+ /**
322
+ * Money typed into a `MoneyInput`, for saving: the money, null for no amount, or undefined when the amount isn't a
323
+ * number of at least zero.
324
+ */
325
+ export function moneyOf(amount: string, currencyCode: string): Money | null | undefined {
326
+ if (!amount.trim()) return null;
327
+ const minor = minorOrUndefined(amount, currencyCode);
328
+ if (minor === undefined) return undefined;
329
+ return minor ? fromMinor(minor, currencyCode) : null;
330
+ }
331
+
332
+ /**
333
+ * A new client company, as a step of a lead's form: its name, made when the lead is saved. `Use this` goes back to
334
+ * the lead with it chosen.
335
+ */
336
+ export function NewCompanyStep({
337
+ initial = '',
338
+ onUse,
339
+ onBack,
340
+ framed,
341
+ text,
342
+ }: {
343
+ initial?: string | undefined;
344
+ /** False inside another card, such as an open lead's. */
345
+ framed?: boolean | undefined;
346
+ onUse: (name: string) => Promise<unknown> | void;
347
+ onBack: () => void;
348
+ text?: Partial<CrmText> | undefined;
349
+ }) {
350
+ const words = withText(text);
351
+ const id = useId();
352
+ const [name, setName] = useState(initial);
353
+ const { saving, error, setError, run } = useSave();
354
+ return (
355
+ <FormFrame
356
+ title={words.newCompany}
357
+ submit={words.useThis}
358
+ submitting={words.saving}
359
+ saving={saving}
360
+ error={error}
361
+ back={{ label: words.back, onBack }}
362
+ framed={framed}
363
+ onSubmit={async () => {
364
+ if (!name.trim()) return setError(words.companyNameRequired);
365
+ await run(async () => onUse(name.trim()));
366
+ }}
367
+ >
368
+ {({ error: errorId }) => (
369
+ <Field id={`${id}-name`} label={words.companyName} hint={words.newCompanyHint}>
370
+ <Input
371
+ id={`${id}-name`}
372
+ value={name}
373
+ onChange={(event) => setName(event.target.value)}
374
+ aria-describedby={[`${id}-name-hint`, errorId].filter(Boolean).join(' ')}
375
+ />
376
+ </Field>
377
+ )}
378
+ </FormFrame>
379
+ );
380
+ }
381
+
382
+ /**
383
+ * A new person to be a lead's contact, as a step of the lead's form: their given and family name and email, made
384
+ * when the lead is saved. `Use this` goes back to the lead with them chosen.
385
+ */
386
+ export function NewContactStep({
387
+ initial,
388
+ onUse,
389
+ onBack,
390
+ framed,
391
+ text,
392
+ }: {
393
+ initial?: NewContact | undefined;
394
+ /** False inside another card, such as an open lead's. */
395
+ framed?: boolean | undefined;
396
+ onUse: (contact: NewContact) => Promise<unknown> | void;
397
+ onBack: () => void;
398
+ text?: Partial<CrmText> | undefined;
399
+ }) {
400
+ const words = withText(text);
401
+ return (
402
+ <ContactForm
403
+ initial={initial}
404
+ title={words.newContact}
405
+ hint={words.newContactHint}
406
+ submit={words.useThis}
407
+ submitting={words.saving}
408
+ back={{ label: words.back, onBack }}
409
+ framed={framed}
410
+ onSave={onUse}
411
+ text={text}
412
+ />
413
+ );
414
+ }
415
+
416
+ /**
417
+ * A new person, such as one of a customer company's people: their given and family name and email. `onCreate` makes
418
+ * them (`CrmStore.createContact`); the form stays as it was if that fails, so it can be sent again.
419
+ */
420
+ export function NewContactForm({
421
+ onCreate,
422
+ text,
423
+ }: {
424
+ onCreate: (contact: NewContact) => Promise<unknown>;
425
+ text?: Partial<CrmText> | undefined;
426
+ }) {
427
+ const words = withText(text);
428
+ return (
429
+ <ContactForm
430
+ title={words.addPerson}
431
+ submit={words.addPerson}
432
+ submitting={words.creating}
433
+ // Shown in the host's card, such as a customer's people.
434
+ framed={false}
435
+ onSave={onCreate}
436
+ text={text}
437
+ />
438
+ );
439
+ }
440
+
441
+ function ContactForm({
442
+ initial,
443
+ title,
444
+ hint,
445
+ submit,
446
+ submitting,
447
+ back,
448
+ framed,
449
+ onSave,
450
+ text,
451
+ }: {
452
+ initial?: NewContact | undefined;
453
+ title: string;
454
+ hint?: string;
455
+ submit: string;
456
+ submitting: string;
457
+ back?: { label: string; onBack: () => void };
458
+ framed?: boolean | undefined;
459
+ onSave: (contact: NewContact) => Promise<unknown> | void;
460
+ text?: Partial<CrmText> | undefined;
461
+ }) {
462
+ const words = withText(text);
463
+ const id = useId();
464
+ const [givenName, setGivenName] = useState(initial?.givenName ?? '');
465
+ const [familyName, setFamilyName] = useState(initial?.familyName ?? '');
466
+ const [email, setEmail] = useState(initial?.email ?? '');
467
+ const [telephone, setTelephone] = useState(initial?.telephone ?? '');
468
+ const { saving, error, setError, run } = useSave();
469
+ return (
470
+ <FormFrame
471
+ title={title}
472
+ submit={submit}
473
+ submitting={submitting}
474
+ saving={saving}
475
+ error={error}
476
+ back={back}
477
+ framed={framed}
478
+ onSubmit={async () => {
479
+ if (!givenName.trim()) return setError(words.givenNameRequired);
480
+ const contact: NewContact = {
481
+ givenName: givenName.trim(),
482
+ ...(familyName.trim() ? { familyName: familyName.trim() } : {}),
483
+ ...(email.trim() ? { email: email.trim() } : {}),
484
+ ...(telephone.trim() ? { telephone: telephone.trim() } : {}),
485
+ };
486
+ await run(async () => onSave(contact));
487
+ }}
488
+ >
489
+ {({ error: errorId }) => (
490
+ <>
491
+ {hint && <p className="text-muted-foreground text-sm">{hint}</p>}
492
+ <Field id={`${id}-given`} label={words.givenName}>
493
+ <Input
494
+ id={`${id}-given`}
495
+ autoComplete="off"
496
+ value={givenName}
497
+ onChange={(event) => setGivenName(event.target.value)}
498
+ aria-describedby={errorId}
499
+ />
500
+ </Field>
501
+ <Field id={`${id}-family`} label={words.familyName}>
502
+ <Input
503
+ id={`${id}-family`}
504
+ autoComplete="off"
505
+ value={familyName}
506
+ onChange={(event) => setFamilyName(event.target.value)}
507
+ />
508
+ </Field>
509
+ <Field id={`${id}-email`} label={words.email}>
510
+ <Input
511
+ id={`${id}-email`}
512
+ type="email"
513
+ autoComplete="off"
514
+ value={email}
515
+ onChange={(event) => setEmail(event.target.value)}
516
+ />
517
+ </Field>
518
+ <Field id={`${id}-telephone`} label={words.telephone}>
519
+ <Input
520
+ id={`${id}-telephone`}
521
+ type="tel"
522
+ autoComplete="off"
523
+ value={telephone}
524
+ onChange={(event) => setTelephone(event.target.value)}
525
+ />
526
+ </Field>
527
+ </>
528
+ )}
529
+ </FormFrame>
530
+ );
531
+ }
532
+
533
+ /** A contact's name for showing while they're waiting to be made. */
534
+ export const draftName = (contact: NewContact) => [contact.givenName, contact.familyName].filter(Boolean).join(' ');
535
+
150
536
  /** Runs a form's save: the problem in words when it fails, the form left as it was so it can be sent again. */
151
537
  function useSave() {
152
538
  const [saving, setSaving] = useState(false);
@@ -166,33 +552,44 @@ function useSave() {
166
552
  }
167
553
 
168
554
  /**
169
- * A new lead: its title, source, value, and its company, chosen from the host's companies or made from a new name (a
170
- * lead holds its business by its company).
555
+ * A new lead: its title, source, value, assignee, and its company and contact person (a lead holds its business by
556
+ * its company). Each is chosen from the host's, or added: "Add a new ..." opens a step for its details in the same
557
+ * form, and it's made when the lead is saved.
171
558
  */
172
559
  export function NewLeadForm({
173
560
  owner,
174
561
  companies = [],
562
+ people = [],
563
+ team = [],
175
564
  currencyCode = 'GBP',
176
565
  onCreate,
177
566
  text,
178
567
  }: FormProps & {
179
568
  companies?: readonly CrmCompanyChoice[] | undefined;
569
+ /** People to choose as the contact: the host's customers' people. */
570
+ people?: readonly CrmPersonChoice[] | undefined;
571
+ /** People to assign the lead to: the host's team. */
572
+ team?: readonly CrmPersonChoice[] | undefined;
180
573
  currencyCode?: string;
181
574
  onCreate: (input: LeadInput, options: NewLeadOptions) => Promise<unknown>;
182
575
  }) {
183
576
  const words = withText(text);
184
577
  const id = useId();
578
+ const [step, setStep] = useState<'lead' | 'company' | 'contact'>('lead');
185
579
  const [title, setTitle] = useState('');
186
580
  const [source, setSource] = useState<LeadSource>('WEBSITE');
187
581
  const [value, setValue] = useState('');
582
+ const [currency, setCurrency] = useState(currencyCode);
188
583
  const [company, setCompany] = useState('');
189
- const [newCompany, setNewCompany] = useState('');
584
+ const [newCompany, setNewCompany] = useState<string>();
585
+ const [contact, setContact] = useState('');
586
+ const [newContact, setNewContact] = useState<NewContact>();
587
+ const [assignee, setAssignee] = useState('');
190
588
  const { saving, error, setError, run } = useSave();
191
589
  const submit = async () => {
192
- const minor = value.trim() ? minorOrUndefined(value, currencyCode) : 0;
590
+ const targetValue = moneyOf(value, currency);
193
591
  if (!title.trim()) return setError(words.titleRequired);
194
- if (minor === undefined) return setError(words.invalidAmount);
195
- const named = company ? '' : newCompany.trim();
592
+ if (targetValue === undefined) return setError(words.invalidAmount);
196
593
  await run(() =>
197
594
  onCreate(
198
595
  {
@@ -202,12 +599,40 @@ export function NewLeadForm({
202
599
  status: 'NEW',
203
600
  outcome: 'IN_PROGRESS',
204
601
  contactCompany: company ? { urn: company } : null,
205
- targetValue: minor ? fromMinor(minor, currencyCode) : null,
602
+ contactIdentity: contact ? { urn: contact } : null,
603
+ assignee: assignee ? { urn: assignee } : null,
604
+ targetValue,
206
605
  },
207
- named ? { companyName: named } : {},
606
+ { ...(newCompany ? { companyName: newCompany } : {}), ...(newContact ? { contact: newContact } : {}) },
208
607
  ),
209
608
  );
210
609
  };
610
+ if (step === 'company')
611
+ return (
612
+ <NewCompanyStep
613
+ initial={newCompany}
614
+ text={text}
615
+ onBack={() => setStep('lead')}
616
+ onUse={(name) => {
617
+ setCompany('');
618
+ setNewCompany(name);
619
+ setStep('lead');
620
+ }}
621
+ />
622
+ );
623
+ if (step === 'contact')
624
+ return (
625
+ <NewContactStep
626
+ initial={newContact}
627
+ text={text}
628
+ onBack={() => setStep('lead')}
629
+ onUse={(made) => {
630
+ setContact('');
631
+ setNewContact(made);
632
+ setStep('lead');
633
+ }}
634
+ />
635
+ );
211
636
  return (
212
637
  <FormFrame
213
638
  title={words.newLead}
@@ -241,33 +666,56 @@ export function NewLeadForm({
241
666
  </SelectContent>
242
667
  </Select>
243
668
  </Field>
244
- <Field id={`${id}-value`} label={`${words.value} (${currencyCode})`}>
245
- <Input
669
+ <Field id={`${id}-value`} label={words.value}>
670
+ <MoneyInput
246
671
  id={`${id}-value`}
247
- inputMode="decimal"
248
- value={value}
249
- onChange={(event) => setValue(event.target.value)}
672
+ amount={value}
673
+ currencyCode={currency}
674
+ onAmount={setValue}
675
+ onCurrency={setCurrency}
676
+ text={text}
250
677
  />
251
678
  </Field>
252
679
  <Field id={`${id}-company`} label={words.company}>
253
- <CompanySelect
680
+ <ChoiceSelect
254
681
  id={`${id}-company`}
255
682
  value={company}
256
- onChange={setCompany}
257
- companies={companies}
683
+ onChange={(urn) => {
684
+ setCompany(urn);
685
+ setNewCompany(undefined);
686
+ }}
687
+ choices={companies}
258
688
  none={words.noCompany}
689
+ add={{ label: words.addCompany, onAdd: () => setStep('company') }}
690
+ pending={newCompany}
691
+ text={text}
692
+ />
693
+ </Field>
694
+ <Field id={`${id}-contact`} label={words.contact}>
695
+ <ChoiceSelect
696
+ id={`${id}-contact`}
697
+ value={contact}
698
+ onChange={(urn) => {
699
+ setContact(urn);
700
+ setNewContact(undefined);
701
+ }}
702
+ choices={people}
703
+ none={words.noContact}
704
+ add={{ label: words.addContact, onAdd: () => setStep('contact') }}
705
+ pending={newContact && draftName(newContact)}
706
+ text={text}
707
+ />
708
+ </Field>
709
+ <Field id={`${id}-assignee`} label={words.assignee}>
710
+ <ChoiceSelect
711
+ id={`${id}-assignee`}
712
+ value={assignee}
713
+ onChange={setAssignee}
714
+ choices={team}
715
+ none={words.unassigned}
716
+ text={text}
259
717
  />
260
718
  </Field>
261
- {!company && (
262
- <Field id={`${id}-new-company`} label={words.newCompany} hint={words.newCompanyHint}>
263
- <Input
264
- id={`${id}-new-company`}
265
- value={newCompany}
266
- onChange={(event) => setNewCompany(event.target.value)}
267
- aria-describedby={`${id}-new-company-hint`}
268
- />
269
- </Field>
270
- )}
271
719
  </>
272
720
  )}
273
721
  </FormFrame>
@@ -275,51 +723,132 @@ export function NewLeadForm({
275
723
  }
276
724
 
277
725
  /**
278
- * A new deal that didn't start as a lead: its title, company, value, stage in the pipeline (the first, to start with),
279
- * expected close and probability.
726
+ * Where a deal is: its workflow (any workflow can be a pipeline) and its stage in it. Choosing a workflow moves the
727
+ * deal to that workflow's first stage.
728
+ */
729
+ export function PipelineStageFields({
730
+ id,
731
+ pipelines,
732
+ stage,
733
+ onStage,
734
+ disabled,
735
+ text,
736
+ }: {
737
+ id: string;
738
+ pipelines: readonly Pipeline[];
739
+ /** The deal's stage URN, or "" for none. */
740
+ stage: string;
741
+ onStage: (stage: PipelineStage) => void;
742
+ disabled?: boolean | undefined;
743
+ text?: Partial<CrmText> | undefined;
744
+ }) {
745
+ const words = withText(text);
746
+ const pipeline =
747
+ pipelines.find((candidate) => candidate.stages?.some((option) => option.urn === stage)) ?? pipelines[0];
748
+ const stages = pipeline ? orderedStages(pipeline) : [];
749
+ return (
750
+ <>
751
+ {pipelines.length > 1 && (
752
+ <Field id={`${id}-workflow`} label={words.workflow}>
753
+ <Select
754
+ value={pipeline?.urn ?? ''}
755
+ disabled={disabled ?? false}
756
+ onValueChange={(urn) => {
757
+ const first = orderedStages(pipelines.find((candidate) => candidate.urn === urn)!)[0];
758
+ if (first) onStage(first);
759
+ }}
760
+ >
761
+ <SelectTrigger id={`${id}-workflow`} className="w-full">
762
+ <SelectValue />
763
+ </SelectTrigger>
764
+ <SelectContent>
765
+ {pipelines.map((option) => (
766
+ <SelectItem key={option.urn} value={option.urn}>
767
+ {option.name}
768
+ </SelectItem>
769
+ ))}
770
+ </SelectContent>
771
+ </Select>
772
+ </Field>
773
+ )}
774
+ <Field id={`${id}-stage`} label={words.stage}>
775
+ <Select
776
+ value={stages.some((option) => option.urn === stage) ? stage : ''}
777
+ disabled={disabled ?? false}
778
+ onValueChange={(urn) => onStage(stages.find((option) => option.urn === urn)!)}
779
+ >
780
+ <SelectTrigger id={`${id}-stage`} className="w-full">
781
+ <SelectValue />
782
+ </SelectTrigger>
783
+ <SelectContent>
784
+ {stages.map((option) => (
785
+ <SelectItem key={option.urn} value={option.urn}>
786
+ {option.name}
787
+ </SelectItem>
788
+ ))}
789
+ </SelectContent>
790
+ </Select>
791
+ </Field>
792
+ </>
793
+ );
794
+ }
795
+
796
+ /**
797
+ * A new deal that didn't start as a lead: its title, companies and contacts (found by searching), value, workflow and stage (the first
798
+ * workflow's first stage, to start with), expected close, probability and assignee.
280
799
  */
281
800
  export function NewDealForm({
282
801
  owner,
283
- pipeline,
802
+ pipelines,
284
803
  companies = [],
804
+ people = [],
805
+ team = [],
285
806
  currencyCode = 'GBP',
286
807
  now = new Date(),
287
808
  onCreate,
288
809
  text,
289
810
  }: FormProps & {
290
- pipeline: Pipeline;
811
+ /** The workflows a deal can be in, the first chosen to start with. */
812
+ pipelines: readonly Pipeline[];
291
813
  companies?: readonly CrmCompanyChoice[] | undefined;
814
+ /** People to choose as the contact: the host's customers' people. */
815
+ people?: readonly CrmPersonChoice[] | undefined;
816
+ /** People to assign the deal to: the host's team. */
817
+ team?: readonly CrmPersonChoice[] | undefined;
292
818
  currencyCode?: string;
293
819
  now?: Date;
294
820
  onCreate: (input: DealInput) => Promise<unknown>;
295
821
  }) {
296
822
  const words = withText(text);
297
823
  const id = useId();
298
- const stages = orderedStages(pipeline);
299
824
  const [title, setTitle] = useState('');
300
- const [company, setCompany] = useState('');
825
+ const [chosenCompanies, setCompanies] = useState<string[]>([]);
826
+ const [contacts, setContacts] = useState<string[]>([]);
827
+ const [assignee, setAssignee] = useState('');
301
828
  const [value, setValue] = useState('');
302
- const [stage, setStage] = useState(stages[0]?.urn ?? '');
829
+ const [currency, setCurrency] = useState(currencyCode);
830
+ const [stage, setStage] = useState(pipelines[0] ? (orderedStages(pipelines[0])[0]?.urn ?? '') : '');
303
831
  const [close, setClose] = useState(inDays(now, 30));
304
832
  const [probability, setProbability] = useState('');
305
833
  const { saving, error, setError, run } = useSave();
306
834
  const submit = async () => {
307
- const minor = value.trim() ? minorOrUndefined(value, currencyCode) : 0;
835
+ const targetValue = moneyOf(value, currency);
308
836
  const chance = probability.trim() ? Number(probability) : undefined;
309
837
  if (!title.trim()) return setError(words.titleRequired);
310
- if (minor === undefined) return setError(words.invalidAmount);
838
+ if (targetValue === undefined) return setError(words.invalidAmount);
311
839
  if (chance !== undefined && !(chance >= 0 && chance <= 100)) return setError(words.invalidProbability);
312
840
  await run(() =>
313
841
  onCreate({
314
842
  owner: ref(owner),
315
843
  title: title.trim(),
316
- contactCompanies: company ? [{ urn: company }] : [],
317
- contactIdentities: [],
844
+ contactCompanies: chosenCompanies.map((urn) => ({ urn })),
845
+ contactIdentities: contacts.map((urn) => ({ urn })),
318
846
  workflowStage: stage ? { urn: stage } : null,
319
847
  outcome: 'OPEN',
320
848
  probability: chance ?? null,
321
- targetValue: minor ? fromMinor(minor, currencyCode) : null,
849
+ targetValue,
322
850
  targetCloseTimestamp: dayTimestamp(close),
851
+ assignee: assignee ? { urn: assignee } : null,
323
852
  invoices: [],
324
853
  }),
325
854
  );
@@ -343,36 +872,52 @@ export function NewDealForm({
343
872
  aria-describedby={errorId}
344
873
  />
345
874
  </Field>
346
- <Field id={`${id}-company`} label={words.company}>
347
- <CompanySelect
348
- id={`${id}-company`}
349
- value={company}
350
- onChange={setCompany}
351
- companies={companies}
352
- none={words.noCompany}
875
+ <Field id={`${id}-companies`} label={words.companies}>
876
+ <ChoiceCombobox
877
+ id={`${id}-companies`}
878
+ value={chosenCompanies}
879
+ onChange={setCompanies}
880
+ choices={companies}
881
+ placeholder={words.searchCompanies}
882
+ text={text}
353
883
  />
354
884
  </Field>
355
- <Field id={`${id}-value`} label={`${words.value} (${currencyCode})`}>
356
- <Input
885
+ <Field id={`${id}-contacts`} label={words.contacts}>
886
+ <ChoiceCombobox
887
+ id={`${id}-contacts`}
888
+ value={contacts}
889
+ onChange={setContacts}
890
+ choices={people}
891
+ placeholder={words.searchContacts}
892
+ text={text}
893
+ />
894
+ </Field>
895
+ <Field id={`${id}-value`} label={words.value}>
896
+ <MoneyInput
357
897
  id={`${id}-value`}
358
- inputMode="decimal"
359
- value={value}
360
- onChange={(event) => setValue(event.target.value)}
898
+ amount={value}
899
+ currencyCode={currency}
900
+ onAmount={setValue}
901
+ onCurrency={setCurrency}
902
+ text={text}
361
903
  />
362
904
  </Field>
363
- <Field id={`${id}-stage`} label={words.stage}>
364
- <Select value={stage} onValueChange={setStage}>
365
- <SelectTrigger id={`${id}-stage`} className="w-full">
366
- <SelectValue />
367
- </SelectTrigger>
368
- <SelectContent>
369
- {stages.map((option) => (
370
- <SelectItem key={option.urn} value={option.urn}>
371
- {option.name}
372
- </SelectItem>
373
- ))}
374
- </SelectContent>
375
- </Select>
905
+ <PipelineStageFields
906
+ id={id}
907
+ pipelines={pipelines}
908
+ stage={stage}
909
+ onStage={(next) => setStage(next.urn)}
910
+ text={text}
911
+ />
912
+ <Field id={`${id}-assignee`} label={words.assignee}>
913
+ <ChoiceSelect
914
+ id={`${id}-assignee`}
915
+ value={assignee}
916
+ onChange={setAssignee}
917
+ choices={team}
918
+ none={words.unassigned}
919
+ text={text}
920
+ />
376
921
  </Field>
377
922
  <Field id={`${id}-close`} label={words.expectedClose}>
378
923
  <Input id={`${id}-close`} type="date" value={close} onChange={(event) => setClose(event.target.value)} />
@@ -391,98 +936,390 @@ export function NewDealForm({
391
936
  );
392
937
  }
393
938
 
394
- const INVOICE_STATUSES: readonly InvoiceStatus[] = ['DRAFT', 'AUTHORISED'];
939
+ const TAXABILITY_LABELS: Record<Taxability, string> = {
940
+ TAXABLE: 'Taxable',
941
+ PARTIALLY_TAXABLE: 'Partly taxable',
942
+ NON_TAXABLE: 'Not taxable',
943
+ TAX_EXEMPT: 'Exempt',
944
+ NOT_APPLICABLE: 'Not applicable',
945
+ };
946
+ const TAXABILITIES = Object.keys(TAXABILITY_LABELS) as Taxability[];
947
+ /** Taxed at the invoice's rate; the others have no tax. */
948
+ const TAXED: readonly Taxability[] = ['TAXABLE', 'PARTIALLY_TAXABLE'];
395
949
 
396
950
  interface LineRow {
397
951
  description: string;
398
952
  quantity: string;
399
953
  unitPrice: string;
954
+ itemCode: string;
955
+ discountRate: string;
956
+ taxability: Taxability;
957
+ taxName: string;
400
958
  }
401
959
 
402
- const EMPTY_LINE: LineRow = { description: '', quantity: '1', unitPrice: '' };
960
+ const EMPTY_LINE: LineRow = {
961
+ description: '',
962
+ quantity: '1',
963
+ unitPrice: '',
964
+ itemCode: '',
965
+ discountRate: '',
966
+ taxability: 'TAXABLE',
967
+ taxName: '',
968
+ };
403
969
 
404
- /** What a line, typed in, comes to: its net price and tax in minor units, or undefined when it isn't complete. */
970
+ /**
971
+ * What a line, typed in, comes to, in minor units: before discount, the discount, its net price and tax. Undefined
972
+ * when it isn't complete or its discount isn't 0 to 100.
973
+ */
405
974
  function priceLine(line: LineRow, currencyCode: string, rate: number) {
406
975
  const quantity = Number(line.quantity);
407
976
  const unit = minorOrUndefined(line.unitPrice, currencyCode);
408
- if (!line.description.trim() || !(quantity > 0) || !unit) return undefined;
409
- const price = Math.round(unit * quantity);
410
- return { description: line.description.trim(), quantity, unit, price, tax: Math.round((price * rate) / 100) };
977
+ const discountRate = line.discountRate.trim() ? Number(line.discountRate) : 0;
978
+ if (!line.description.trim() || !(quantity > 0) || !unit || !(discountRate >= 0 && discountRate <= 100))
979
+ return undefined;
980
+ const gross = Math.round(unit * quantity);
981
+ const discount = Math.round((gross * discountRate) / 100);
982
+ const price = gross - discount;
983
+ const tax = TAXED.includes(line.taxability) ? Math.round((price * rate) / 100) : 0;
984
+ return { line, quantity, unit, discountRate, discount, price, tax };
985
+ }
986
+
987
+ /** The line as the API takes it: its unit price in major units, its amounts as money. */
988
+ function lineDraft(priced: NonNullable<ReturnType<typeof priceLine>>, code: string): InvoiceLineDraft {
989
+ const { line } = priced;
990
+ return {
991
+ description: line.description.trim(),
992
+ quantity: priced.quantity,
993
+ unitPrice: priced.unit / 10 ** fractionDigits(code),
994
+ price: fromMinor(priced.price, code),
995
+ tax: fromMinor(priced.tax, code),
996
+ taxability: line.taxability,
997
+ ...(line.itemCode.trim() ? { itemCode: line.itemCode.trim() } : {}),
998
+ ...(priced.discountRate
999
+ ? { discountRate: priced.discountRate, discountPrice: fromMinor(priced.discount, code) }
1000
+ : {}),
1001
+ ...(line.taxName.trim() ? { taxName: line.taxName.trim() } : {}),
1002
+ };
1003
+ }
1004
+
1005
+ /**
1006
+ * One invoice line with all its fields, as a step of the invoice form: description, item code, quantity, unit price,
1007
+ * discount, tax treatment and tax name, with what it comes to. `Done` goes back to the invoice with it kept.
1008
+ */
1009
+ function InvoiceLineStep({
1010
+ number,
1011
+ initial,
1012
+ currencyCode,
1013
+ rate,
1014
+ onDone,
1015
+ onBack,
1016
+ text,
1017
+ }: {
1018
+ number: number;
1019
+ initial: LineRow;
1020
+ currencyCode: string;
1021
+ rate: number;
1022
+ onDone: (line: LineRow) => void;
1023
+ onBack: () => void;
1024
+ text?: Partial<CrmText> | undefined;
1025
+ }) {
1026
+ const words = withText(text);
1027
+ const id = useId();
1028
+ const [line, setLine] = useState(initial);
1029
+ const { saving, error, setError, run } = useSave();
1030
+ const set = (field: keyof LineRow, value: string) => setLine((current) => ({ ...current, [field]: value }));
1031
+ const priced = priceLine(line, currencyCode, Number.isFinite(rate) ? rate : 0);
1032
+ const money = (minor: number) => formatMoney(fromMinor(minor, currencyCode));
1033
+ const input = (field: Exclude<keyof LineRow, 'taxability'>, label: string, inputMode?: 'decimal') => (
1034
+ <Field id={`${id}-${field}`} label={label}>
1035
+ <Input
1036
+ id={`${id}-${field}`}
1037
+ inputMode={inputMode}
1038
+ value={line[field]}
1039
+ onChange={(event) => set(field, event.target.value)}
1040
+ />
1041
+ </Field>
1042
+ );
1043
+ return (
1044
+ <FormFrame
1045
+ title={`${words.line} ${number}`}
1046
+ submit={words.done}
1047
+ submitting={words.saving}
1048
+ saving={saving}
1049
+ error={error}
1050
+ back={{ label: words.back, onBack }}
1051
+ onSubmit={async () => {
1052
+ const discount = line.discountRate.trim() ? Number(line.discountRate) : 0;
1053
+ if (!(discount >= 0 && discount <= 100)) return setError(words.invalidDiscount);
1054
+ await run(async () => onDone(line));
1055
+ }}
1056
+ >
1057
+ {() => (
1058
+ <>
1059
+ {input('description', words.description)}
1060
+ {input('itemCode', words.itemCode)}
1061
+ <div className="grid grid-cols-2 gap-3">
1062
+ {input('quantity', words.quantity, 'decimal')}
1063
+ {input('unitPrice', `${words.unitPrice} (${currencyCode})`, 'decimal')}
1064
+ {input('discountRate', words.discountRate, 'decimal')}
1065
+ <Field id={`${id}-taxability`} label={words.taxability}>
1066
+ <Select value={line.taxability} onValueChange={(next) => set('taxability', next)}>
1067
+ <SelectTrigger id={`${id}-taxability`} className="w-full">
1068
+ <SelectValue />
1069
+ </SelectTrigger>
1070
+ <SelectContent>
1071
+ {TAXABILITIES.map((option) => (
1072
+ <SelectItem key={option} value={option}>
1073
+ {TAXABILITY_LABELS[option]}
1074
+ </SelectItem>
1075
+ ))}
1076
+ </SelectContent>
1077
+ </Select>
1078
+ </Field>
1079
+ </div>
1080
+ {input('taxName', words.taxName)}
1081
+ <dl aria-live="polite" className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
1082
+ <dt className="text-muted-foreground">{words.price}</dt>
1083
+ <dd className="tabular-nums">{priced ? money(priced.price) : '-'}</dd>
1084
+ <dt className="text-muted-foreground">{words.tax}</dt>
1085
+ <dd className="tabular-nums">{priced ? money(priced.tax) : '-'}</dd>
1086
+ </dl>
1087
+ </>
1088
+ )}
1089
+ </FormFrame>
1090
+ );
1091
+ }
1092
+
1093
+ /**
1094
+ * A party's company and person, as the invoice form picks them: an existing company or a new one by name, and an
1095
+ * existing person or a new one.
1096
+ */
1097
+ interface PartyDraft {
1098
+ company: string;
1099
+ identity: string;
1100
+ newCompany?: string | undefined;
1101
+ newContact?: NewContact | undefined;
1102
+ }
1103
+
1104
+ const recipientKey = (owner: string) => `baack-crm:invoice-recipient:${owner}`;
1105
+
1106
+ /** The recipient last used for this owner's invoices, kept in the browser; else the owner itself. */
1107
+ function lastRecipient(owner: string): PartyDraft {
1108
+ try {
1109
+ const saved = JSON.parse(localStorage.getItem(recipientKey(owner)) ?? 'null') as Partial<PartyDraft> | null;
1110
+ if (saved && typeof saved.company === 'string')
1111
+ return { company: saved.company, identity: typeof saved.identity === 'string' ? saved.identity : '' };
1112
+ } catch {
1113
+ // No storage: the owner, as on first use.
1114
+ }
1115
+ return { company: owner, identity: '' };
411
1116
  }
412
1117
 
1118
+ function keepRecipient(owner: string, party: PartyDraft) {
1119
+ try {
1120
+ localStorage.setItem(recipientKey(owner), JSON.stringify({ company: party.company, identity: party.identity }));
1121
+ } catch {
1122
+ // Not kept; next time starts from the owner.
1123
+ }
1124
+ }
1125
+
1126
+ const partyRefs = (party: PartyDraft) => ({
1127
+ company: party.company ? { urn: party.company } : null,
1128
+ identity: party.identity ? { urn: party.identity } : null,
1129
+ });
1130
+
413
1131
  /**
414
- * A new invoice to a customer: its lines (description, quantity, unit price) and a tax rate, which give its subtotal,
415
- * tax and total (the API keeps an invoice's amounts as given), its dates and status, and the deal it's for, if any.
1132
+ * A new invoice: who pays it (the remitter) and who's paid (the recipient), each a company, a person or both, found by
1133
+ * searching; a company not in Baack yet can be added by name. The recipient starts as the one used last, else the
1134
+ * owner. An invoice can be a sale (a customer pays the owner) or a cost (the owner pays a supplier). Its amount is
1135
+ * lines, each opening into all its fields, or a total including tax, with a tax rate; then its dates, status, and
1136
+ * the deal it's for, if any.
416
1137
  */
417
1138
  export function NewInvoiceForm({
418
1139
  owner,
419
1140
  companies = [],
1141
+ people = [],
420
1142
  deals = [],
421
1143
  currencyCode: defaultCurrency = 'GBP',
422
1144
  now = new Date(),
423
1145
  onCreate,
424
1146
  text,
425
1147
  }: FormProps & {
1148
+ /** Companies either party can be: the host's own companies (the owner and its child companies) and customers. */
426
1149
  companies?: readonly CrmCompanyChoice[] | undefined;
1150
+ /** People either party can be. */
1151
+ people?: readonly CrmPersonChoice[] | undefined;
427
1152
  /** Deals the invoice can be raised for. */
428
1153
  deals?: readonly Deal[];
429
1154
  currencyCode?: string;
430
1155
  now?: Date;
431
- onCreate: (input: InvoiceInput, lines: InvoiceLineDraft[], options: { deal?: Deal }) => Promise<unknown>;
1156
+ onCreate: (input: InvoiceInput, lines: InvoiceLineDraft[], options: NewInvoiceOptions) => Promise<unknown>;
432
1157
  }) {
433
1158
  const words = withText(text);
434
1159
  const id = useId();
435
- const [customer, setCustomer] = useState('');
1160
+ const ownerUrn = ref(owner).urn;
1161
+ const [remitter, setRemitter] = useState<PartyDraft>({ company: '', identity: '' });
1162
+ const [recipient, setRecipient] = useState<PartyDraft>(() => lastRecipient(ownerUrn));
1163
+ // A party whose new company or person is being made, in a step of the form.
1164
+ const [adding, setAdding] = useState<{ which: 'remitter' | 'recipient'; record: 'company' | 'contact' }>();
1165
+ const [editing, setEditing] = useState<number>();
436
1166
  const [deal, setDeal] = useState('');
437
1167
  const [currencyCode, setCurrencyCode] = useState(defaultCurrency);
438
1168
  const [status, setStatus] = useState<InvoiceStatus>('DRAFT');
439
- const [issued, setIssued] = useState(today(now));
1169
+ // Not issued yet, as drafts usually aren't: set when it's sent.
1170
+ const [issued, setIssued] = useState('');
440
1171
  const [due, setDue] = useState(inDays(now, 30));
441
1172
  const [rate, setRate] = useState('20');
1173
+ const [amountAs, setAmountAs] = useState<'lines' | 'total'>('lines');
442
1174
  const [lines, setLines] = useState<LineRow[]>([EMPTY_LINE]);
1175
+ const [total, setTotal] = useState('');
443
1176
  const { saving, error, setError, run } = useSave();
444
1177
  const change = (index: number, field: keyof LineRow, value: string) =>
445
1178
  setLines((current) => current.map((line, at) => (at === index ? { ...line, [field]: value } : line)));
1179
+ const hasParty = (party: PartyDraft) =>
1180
+ Boolean(party.company || party.identity || party.newCompany || party.newContact);
446
1181
  const submit = async () => {
447
1182
  const taxRate = Number(rate);
448
- const code = currencyCode.trim().toUpperCase();
449
- if (!customer) return setError(words.customerRequired);
1183
+ const code = currencyCode;
1184
+ if (!hasParty(remitter)) return setError(words.remitterRequired);
1185
+ if (!hasParty(recipient)) return setError(words.recipientRequired);
450
1186
  if (!(taxRate >= 0 && taxRate <= 100)) return setError(words.invalidRate);
451
- const priced = lines.map((line) => priceLine(line, code, taxRate));
452
- if (priced.some((line) => line === undefined)) return setError(words.linesRequired);
453
- const done = priced as NonNullable<(typeof priced)[number]>[];
454
- const subTotal = done.reduce((sum, line) => sum + line.price, 0);
455
- const tax = done.reduce((sum, line) => sum + line.tax, 0);
456
- const party = { company: { urn: customer }, identity: null };
1187
+ let done: InvoiceLineDraft[] = [];
1188
+ let subTotal: number;
1189
+ let tax: number;
1190
+ if (amountAs === 'total') {
1191
+ // A total includes tax: the subtotal and tax are worked out from it at the rate.
1192
+ const gross = minorOrUndefined(total, code);
1193
+ if (!gross) return setError(words.totalRequired);
1194
+ subTotal = Math.round(gross / (1 + taxRate / 100));
1195
+ tax = gross - subTotal;
1196
+ } else {
1197
+ const priced = lines.map((line) => priceLine(line, code, taxRate));
1198
+ if (priced.some((line) => line === undefined)) return setError(words.linesRequired);
1199
+ const complete = priced as NonNullable<(typeof priced)[number]>[];
1200
+ done = complete.map((line) => lineDraft(line, code));
1201
+ subTotal = complete.reduce((sum, line) => sum + line.price, 0);
1202
+ tax = complete.reduce((sum, line) => sum + line.tax, 0);
1203
+ }
457
1204
  const linked = deals.find((candidate) => candidate.urn === deal);
458
- await run(() =>
459
- onCreate(
1205
+ await run(async () => {
1206
+ await onCreate(
460
1207
  {
461
1208
  owner: ref(owner),
462
- recipient: party,
463
- remitter: party,
1209
+ remitter: partyRefs(remitter),
1210
+ recipient: partyRefs(recipient),
464
1211
  status,
465
1212
  currencyCode: code,
466
- lineItemTax: taxRate ? 'EXCLUSIVE' : 'NO_TAX',
1213
+ // A total is given with its tax in it; lines are priced before tax.
1214
+ lineItemTax: !taxRate ? 'NO_TAX' : amountAs === 'total' ? 'INCLUSIVE' : 'EXCLUSIVE',
467
1215
  subTotal: fromMinor(subTotal, code),
468
1216
  tax: fromMinor(tax, code),
469
1217
  total: fromMinor(subTotal + tax, code),
470
1218
  paid: fromMinor(0, code),
471
- issuedTimestamp: status === 'DRAFT' ? null : dayTimestamp(issued),
1219
+ issuedTimestamp: dayTimestamp(issued),
472
1220
  dueTimestamp: dayTimestamp(due),
473
1221
  },
474
- done.map((line) => ({
475
- description: line.description,
476
- quantity: line.quantity,
477
- // A line's unit price is in major units; its price and tax are money.
478
- unitPrice: line.unit / 10 ** fractionDigits(code),
479
- price: fromMinor(line.price, code),
480
- tax: fromMinor(line.tax, code),
481
- })),
482
- linked ? { deal: linked } : {},
483
- ),
484
- );
1222
+ done,
1223
+ {
1224
+ ...(linked ? { deal: linked } : {}),
1225
+ ...(remitter.newCompany ? { remitterCompanyName: remitter.newCompany } : {}),
1226
+ ...(recipient.newCompany ? { recipientCompanyName: recipient.newCompany } : {}),
1227
+ ...(remitter.newContact ? { remitterContact: remitter.newContact } : {}),
1228
+ ...(recipient.newContact ? { recipientContact: recipient.newContact } : {}),
1229
+ },
1230
+ );
1231
+ // A new record's URN isn't known here, so only an existing recipient is kept for next time.
1232
+ if (!recipient.newCompany && !recipient.newContact) keepRecipient(ownerUrn, recipient);
1233
+ });
485
1234
  };
1235
+
1236
+ if (adding) {
1237
+ const party = adding.which === 'remitter' ? remitter : recipient;
1238
+ const setParty = adding.which === 'remitter' ? setRemitter : setRecipient;
1239
+ return adding.record === 'company' ? (
1240
+ <NewCompanyStep
1241
+ initial={party.newCompany ?? ''}
1242
+ text={text}
1243
+ onBack={() => setAdding(undefined)}
1244
+ onUse={(name) => {
1245
+ setParty({ ...party, company: '', newCompany: name });
1246
+ setAdding(undefined);
1247
+ }}
1248
+ />
1249
+ ) : (
1250
+ <NewContactStep
1251
+ initial={party.newContact}
1252
+ text={text}
1253
+ onBack={() => setAdding(undefined)}
1254
+ onUse={(contact) => {
1255
+ setParty({ ...party, identity: '', newContact: contact });
1256
+ setAdding(undefined);
1257
+ }}
1258
+ />
1259
+ );
1260
+ }
1261
+ if (editing !== undefined && lines[editing]) {
1262
+ return (
1263
+ <InvoiceLineStep
1264
+ number={editing + 1}
1265
+ initial={lines[editing]}
1266
+ currencyCode={currencyCode}
1267
+ rate={Number(rate)}
1268
+ text={text}
1269
+ onBack={() => setEditing(undefined)}
1270
+ onDone={(line) => {
1271
+ setLines((current) => current.map((other, at) => (at === editing ? line : other)));
1272
+ setEditing(undefined);
1273
+ }}
1274
+ />
1275
+ );
1276
+ }
1277
+
1278
+ const partyFields = (which: 'remitter' | 'recipient', party: PartyDraft, setParty: (next: PartyDraft) => void) => (
1279
+ <fieldset className="grid gap-3">
1280
+ <legend className="mb-1 text-sm font-medium">{which === 'remitter' ? words.remitter : words.recipient}</legend>
1281
+ <Field
1282
+ id={`${id}-${which}-company`}
1283
+ label={which === 'remitter' ? words.remitterCompany : words.recipientCompany}
1284
+ hint={which === 'recipient' ? words.recipientHint : undefined}
1285
+ >
1286
+ <ChoiceCombobox
1287
+ id={`${id}-${which}-company`}
1288
+ single
1289
+ value={party.company ? [party.company] : []}
1290
+ onChange={([company = '']) => setParty({ ...party, company, newCompany: undefined })}
1291
+ choices={companies}
1292
+ placeholder={words.searchCompanies}
1293
+ add={{ label: words.addCompany, onAdd: () => setAdding({ which, record: 'company' }) }}
1294
+ pending={
1295
+ party.newCompany
1296
+ ? { name: party.newCompany, onClear: () => setParty({ ...party, newCompany: undefined }) }
1297
+ : undefined
1298
+ }
1299
+ describedBy={which === 'recipient' ? `${id}-${which}-company-hint` : undefined}
1300
+ text={text}
1301
+ />
1302
+ </Field>
1303
+ <Field id={`${id}-${which}-person`} label={which === 'remitter' ? words.remitterPerson : words.recipientPerson}>
1304
+ <ChoiceCombobox
1305
+ id={`${id}-${which}-person`}
1306
+ single
1307
+ value={party.identity ? [party.identity] : []}
1308
+ onChange={([identity = '']) => setParty({ ...party, identity, newContact: undefined })}
1309
+ choices={people}
1310
+ placeholder={words.searchPeople}
1311
+ add={{ label: words.addContact, onAdd: () => setAdding({ which, record: 'contact' }) }}
1312
+ pending={
1313
+ party.newContact
1314
+ ? { name: draftName(party.newContact), onClear: () => setParty({ ...party, newContact: undefined }) }
1315
+ : undefined
1316
+ }
1317
+ text={text}
1318
+ />
1319
+ </Field>
1320
+ </fieldset>
1321
+ );
1322
+
486
1323
  return (
487
1324
  <FormFrame
488
1325
  title={words.newInvoice}
@@ -494,15 +1331,8 @@ export function NewInvoiceForm({
494
1331
  >
495
1332
  {({ error: errorId }) => (
496
1333
  <>
497
- <Field id={`${id}-customer`} label={words.customer}>
498
- <CompanySelect
499
- id={`${id}-customer`}
500
- value={customer}
501
- onChange={setCustomer}
502
- companies={companies}
503
- none={words.noCompany}
504
- />
505
- </Field>
1334
+ {partyFields('remitter', remitter, setRemitter)}
1335
+ {partyFields('recipient', recipient, setRecipient)}
506
1336
  <Field id={`${id}-deal`} label={words.forDeal}>
507
1337
  <Select value={deal || NONE} onValueChange={(next) => setDeal(next === NONE ? '' : next)}>
508
1338
  <SelectTrigger id={`${id}-deal`} className="w-full">
@@ -520,12 +1350,18 @@ export function NewInvoiceForm({
520
1350
  </Field>
521
1351
  <div className="grid grid-cols-2 gap-3">
522
1352
  <Field id={`${id}-currency`} label={words.currency}>
523
- <Input
524
- id={`${id}-currency`}
525
- value={currencyCode}
526
- maxLength={3}
527
- onChange={(event) => setCurrencyCode(event.target.value)}
528
- />
1353
+ <Select value={currencyCode} onValueChange={setCurrencyCode}>
1354
+ <SelectTrigger id={`${id}-currency`} className="w-full">
1355
+ <SelectValue />
1356
+ </SelectTrigger>
1357
+ <SelectContent>
1358
+ {(CURRENCIES.includes(currencyCode) ? CURRENCIES : [currencyCode, ...CURRENCIES]).map((code) => (
1359
+ <SelectItem key={code} value={code}>
1360
+ {code}
1361
+ </SelectItem>
1362
+ ))}
1363
+ </SelectContent>
1364
+ </Select>
529
1365
  </Field>
530
1366
  <Field id={`${id}-status`} label={words.status}>
531
1367
  <Select value={status} onValueChange={(next) => setStatus(next as InvoiceStatus)}>
@@ -535,7 +1371,7 @@ export function NewInvoiceForm({
535
1371
  <SelectContent>
536
1372
  {INVOICE_STATUSES.map((option) => (
537
1373
  <SelectItem key={option} value={option}>
538
- {option === 'DRAFT' ? 'Draft' : words.awaitingPayment}
1374
+ {INVOICE_STATUS_LABELS[option]}
539
1375
  </SelectItem>
540
1376
  ))}
541
1377
  </SelectContent>
@@ -553,10 +1389,32 @@ export function NewInvoiceForm({
553
1389
  <Input id={`${id}-due`} type="date" value={due} onChange={(event) => setDue(event.target.value)} />
554
1390
  </Field>
555
1391
  </div>
556
- <fieldset className="grid gap-2" aria-describedby={errorId}>
1392
+ <Field id={`${id}-amount-as`} label={words.amountAs}>
1393
+ <Select value={amountAs} onValueChange={(next) => setAmountAs(next as 'lines' | 'total')}>
1394
+ <SelectTrigger id={`${id}-amount-as`} className="w-full">
1395
+ <SelectValue />
1396
+ </SelectTrigger>
1397
+ <SelectContent>
1398
+ <SelectItem value="lines">{words.amountAsLines}</SelectItem>
1399
+ <SelectItem value="total">{words.amountAsTotal}</SelectItem>
1400
+ </SelectContent>
1401
+ </Select>
1402
+ </Field>
1403
+ {amountAs === 'total' && (
1404
+ <Field id={`${id}-total`} label={`${words.totalWithTax} (${currencyCode})`} hint={words.totalHint}>
1405
+ <Input
1406
+ id={`${id}-total`}
1407
+ inputMode="decimal"
1408
+ value={total}
1409
+ onChange={(event) => setTotal(event.target.value)}
1410
+ aria-describedby={[`${id}-total-hint`, errorId].filter(Boolean).join(' ')}
1411
+ />
1412
+ </Field>
1413
+ )}
1414
+ <fieldset className="grid gap-2" aria-describedby={errorId} hidden={amountAs === 'total'}>
557
1415
  <legend className="mb-1 text-sm font-medium">{words.lines}</legend>
558
1416
  {lines.map((line, index) => (
559
- <div key={index} className="grid grid-cols-[1fr_4rem_6rem_auto] items-end gap-2">
1417
+ <div key={index} className="grid grid-cols-[1fr_4rem_6rem_auto_auto] items-end gap-2">
560
1418
  <Field id={`${id}-line-${index}-description`} label={`${words.description} ${index + 1}`}>
561
1419
  <Input
562
1420
  id={`${id}-line-${index}-description`}
@@ -580,6 +1438,15 @@ export function NewInvoiceForm({
580
1438
  onChange={(event) => change(index, 'unitPrice', event.target.value)}
581
1439
  />
582
1440
  </Field>
1441
+ <Button
1442
+ type="button"
1443
+ variant="ghost"
1444
+ size="icon"
1445
+ aria-label={`${words.lineDetails}: ${words.line} ${index + 1}`}
1446
+ onClick={() => setEditing(index)}
1447
+ >
1448
+ <ChevronRight aria-hidden="true" />
1449
+ </Button>
583
1450
  <Button
584
1451
  type="button"
585
1452
  variant="ghost"