@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
@@ -2,17 +2,36 @@ import { toTimestamp } from '@baack-software/baack-ts-tasks';
2
2
  import { Download, Search } from 'lucide-react';
3
3
  import { useId, useMemo, useState, type FormEvent } from 'react';
4
4
  import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts';
5
- import type { RemittanceInput } from '../backend.ts';
6
- import { AGE_BUCKET_LABELS, isOverdueInvoice, outstanding } from '../invoices.ts';
5
+ import type { InvoiceInput, RemittanceInput } from '../backend.ts';
6
+ import type { InvoicePartyOptions } from '../crm-client.ts';
7
+ import {
8
+ AGE_BUCKET_LABELS,
9
+ INVOICE_STATUSES,
10
+ INVOICE_STATUS_LABELS,
11
+ isCostInvoice,
12
+ isOverdueInvoice,
13
+ outstanding,
14
+ } from '../invoices.ts';
7
15
  import { fractionDigits, fromMinor, formatMoney, minorOf, toDecimal, toMinor, type MoneyTotals } from '../money.ts';
8
16
  import type { SalesSummary } from '../sales.ts';
9
- import type { Invoice, InvoiceStatus, Remittance, RemittanceMethod } from '../types.ts';
17
+ import type { Invoice, InvoiceParty, InvoiceStatus, Remittance, RemittanceMethod } from '../types.ts';
18
+ import { ChoiceCombobox } from './ChoiceCombobox.tsx';
10
19
  import { DetailList } from './Details.tsx';
20
+ import { Field, NewCompanyStep, NewContactStep, type CrmChoice } from './Forms.tsx';
11
21
  import { MetricCard } from './DashboardCards.tsx';
12
- import { companyNameOf, enumLabel, formatDate, formatMaybeMoney, formatTotals, type CrmNames } from './format.ts';
22
+ import {
23
+ companyNameOf,
24
+ enumLabel,
25
+ formatDate,
26
+ formatMaybeMoney,
27
+ formatTotals,
28
+ personNameOf,
29
+ type CrmNames,
30
+ } from './format.ts';
13
31
  import { CrmCard, InvoiceStatusBadge } from './parts.tsx';
14
32
  import { recordItemId } from './SidePanel.tsx';
15
33
  import { withText, type CrmText } from './text.ts';
34
+ import { Badge } from './ui/badge.tsx';
16
35
  import { Button } from './ui/button.tsx';
17
36
  import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from './ui/chart.tsx';
18
37
  import { Input } from './ui/input.tsx';
@@ -22,12 +41,15 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '.
22
41
 
23
42
  type Words = { text?: Partial<CrmText> | undefined };
24
43
 
25
- /** The invoiced, received, outstanding and sales tax figures, each against the period before where it applies. */
44
+ /**
45
+ * The invoiced, received, outstanding and sales tax figures, each against the period before where it applies, then
46
+ * costs (invoices the business pays) and drafts, apart from them.
47
+ */
26
48
  export function SalesMetricCards({ summary, text }: { summary: SalesSummary } & Words) {
27
49
  const words = withText(text);
28
50
  const currency = summary.currencyCode;
29
51
  return (
30
- <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
52
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
31
53
  <MetricCard
32
54
  label={words.invoiced}
33
55
  value={formatTotals(summary.invoiced.current, currency)}
@@ -56,6 +78,20 @@ export function SalesMetricCards({ summary, text }: { summary: SalesSummary } &
56
78
  hint={words.salesTaxHint}
57
79
  text={text}
58
80
  />
81
+ <MetricCard
82
+ label={words.costs}
83
+ value={formatTotals(summary.costs.invoiced.current, currency)}
84
+ change={summary.costs.invoiced.change}
85
+ hint={`${words.toPay}: ${formatTotals(summary.costs.outstanding, currency)}`}
86
+ text={text}
87
+ />
88
+ <MetricCard
89
+ label={words.drafts}
90
+ value={formatTotals(summary.drafts.totals, currency)}
91
+ change={undefined}
92
+ hint={`${summary.drafts.count} ${summary.drafts.count === 1 ? words.draftInvoice : words.draftInvoices}`}
93
+ text={{ ...text, noChange: words.draftsHint }}
94
+ />
59
95
  </div>
60
96
  );
61
97
  }
@@ -171,16 +207,34 @@ type InvoiceFilter = typeof ALL | typeof AWAITING | typeof OVERDUE | InvoiceStat
171
207
  /** An invoice's name for people: its first line, else the end of its URN. */
172
208
  export const invoiceTitle = (invoice: Invoice) => invoice.lines?.[0]?.description ?? `Invoice ${invoice.urn.slice(-6)}`;
173
209
 
174
- /** The company an invoice is for. */
175
- const customerOf = (invoice: Invoice, names?: CrmNames) =>
176
- companyNameOf(names, (invoice.recipient ?? invoice.remitter)?.company?.urn) ?? '-';
210
+ /** A party to an invoice by name: its company, else its person. */
211
+ const partyName = (party: InvoiceParty | null | undefined, names?: CrmNames) =>
212
+ companyNameOf(names, party?.company?.urn) ?? personNameOf(names, party?.identity?.urn);
213
+
214
+ /** The other side of an invoice: the customer who pays a sale, or the supplier paid for a cost. */
215
+ const customerOf = (invoice: Invoice, names?: CrmNames, own?: ReadonlySet<string>) =>
216
+ (isCostInvoice(invoice, own)
217
+ ? partyName(invoice.recipient, names)
218
+ : (partyName(invoice.remitter, names) ?? partyName(invoice.recipient, names))) ?? '-';
177
219
 
178
- function invoicesCsv(invoices: readonly Invoice[], names?: CrmNames): string {
220
+ function invoicesCsv(invoices: readonly Invoice[], names?: CrmNames, own?: ReadonlySet<string>): string {
179
221
  const cell = (value: string) => (/[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value);
180
- const header = ['Invoice', 'Customer', 'Status', 'Issued', 'Due', 'Currency', 'Total', 'Paid', 'Outstanding'];
222
+ const header = [
223
+ 'Invoice',
224
+ 'Kind',
225
+ 'Customer or supplier',
226
+ 'Status',
227
+ 'Issued',
228
+ 'Due',
229
+ 'Currency',
230
+ 'Total',
231
+ 'Paid',
232
+ 'Outstanding',
233
+ ];
181
234
  const rows = invoices.map((invoice) => [
182
235
  invoiceTitle(invoice),
183
- customerOf(invoice, names),
236
+ isCostInvoice(invoice, own) ? 'Cost' : 'Sale',
237
+ customerOf(invoice, names, own),
184
238
  invoice.status,
185
239
  invoice.issuedTimestamp ?? '',
186
240
  invoice.dueTimestamp ?? '',
@@ -192,10 +246,14 @@ function invoicesCsv(invoices: readonly Invoice[], names?: CrmNames): string {
192
246
  return [header, ...rows].map((row) => row.map(cell).join(',')).join('\n');
193
247
  }
194
248
 
195
- /** Invoices filtered by words and status (awaiting payment, overdue, paid and so on), a page at a time. */
249
+ /**
250
+ * Invoices filtered by words, sales or costs, and status (awaiting payment, overdue, paid and so on), a page at a time.
251
+ * `own` is the companies the business counts as itself, which tell its costs from its sales (see `isCostInvoice`).
252
+ */
196
253
  export function InvoicesTable({
197
254
  invoices,
198
255
  names,
256
+ own,
199
257
  onOpen,
200
258
  selected,
201
259
  now = new Date(),
@@ -204,6 +262,7 @@ export function InvoicesTable({
204
262
  }: {
205
263
  invoices: readonly Invoice[];
206
264
  names?: CrmNames | undefined;
265
+ own?: ReadonlySet<string> | undefined;
207
266
  onOpen?: ((invoice: Invoice) => void) | undefined;
208
267
  /** The open invoice, highlighted. */
209
268
  selected?: string | undefined;
@@ -213,16 +272,18 @@ export function InvoicesTable({
213
272
  const words = withText(text);
214
273
  const [query, setQuery] = useState('');
215
274
  const [filter, setFilter] = useState<InvoiceFilter>(ALL);
275
+ const [kind, setKind] = useState<'all' | 'sales' | 'costs'>('all');
216
276
  const [page, setPage] = useState(0);
217
277
  const filtered = useMemo(() => {
218
278
  const needle = query.trim().toLowerCase();
219
279
  return invoices.filter((invoice) => {
280
+ if (kind !== 'all' && isCostInvoice(invoice, own) !== (kind === 'costs')) return false;
220
281
  if (filter === AWAITING && !outstanding(invoice)) return false;
221
282
  if (filter === OVERDUE && !isOverdueInvoice(invoice, now)) return false;
222
283
  if (filter !== ALL && filter !== AWAITING && filter !== OVERDUE && invoice.status !== filter) return false;
223
- return !needle || `${invoiceTitle(invoice)} ${customerOf(invoice, names)}`.toLowerCase().includes(needle);
284
+ return !needle || `${invoiceTitle(invoice)} ${customerOf(invoice, names, own)}`.toLowerCase().includes(needle);
224
285
  });
225
- }, [invoices, names, query, filter, now]);
286
+ }, [invoices, names, own, query, kind, filter, now]);
226
287
  const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
227
288
  const current = Math.min(page, pages - 1);
228
289
  const shown = filtered.slice(current * pageSize, (current + 1) * pageSize);
@@ -237,7 +298,7 @@ export function InvoicesTable({
237
298
  variant="outline"
238
299
  size="sm"
239
300
  onClick={() => {
240
- const url = URL.createObjectURL(new Blob([invoicesCsv(filtered, names)], { type: 'text/csv' }));
301
+ const url = URL.createObjectURL(new Blob([invoicesCsv(filtered, names, own)], { type: 'text/csv' }));
241
302
  const link = document.createElement('a');
242
303
  link.href = url;
243
304
  link.download = 'invoices.csv';
@@ -268,6 +329,22 @@ export function InvoicesTable({
268
329
  className="pl-8"
269
330
  />
270
331
  </div>
332
+ <Select
333
+ value={kind}
334
+ onValueChange={(value) => {
335
+ setKind(value as typeof kind);
336
+ setPage(0);
337
+ }}
338
+ >
339
+ <SelectTrigger aria-label={words.allKinds} className="w-40">
340
+ <SelectValue />
341
+ </SelectTrigger>
342
+ <SelectContent>
343
+ <SelectItem value="all">{words.allKinds}</SelectItem>
344
+ <SelectItem value="sales">{words.salesOnly}</SelectItem>
345
+ <SelectItem value="costs">{words.costsOnly}</SelectItem>
346
+ </SelectContent>
347
+ </Select>
271
348
  <Select
272
349
  value={filter}
273
350
  onValueChange={(value) => {
@@ -282,9 +359,11 @@ export function InvoicesTable({
282
359
  <SelectItem value={ALL}>{words.allInvoices}</SelectItem>
283
360
  <SelectItem value={AWAITING}>{words.awaitingPayment}</SelectItem>
284
361
  <SelectItem value={OVERDUE}>{words.overdue}</SelectItem>
285
- <SelectItem value="PAID">{words.paid}</SelectItem>
286
- <SelectItem value="DRAFT">Draft</SelectItem>
287
- <SelectItem value="REFUNDED">Refunded</SelectItem>
362
+ {INVOICE_STATUSES.map((status) => (
363
+ <SelectItem key={status} value={status}>
364
+ {INVOICE_STATUS_LABELS[status]}
365
+ </SelectItem>
366
+ ))}
288
367
  </SelectContent>
289
368
  </Select>
290
369
  </div>
@@ -293,7 +372,7 @@ export function InvoicesTable({
293
372
  <TableHeader>
294
373
  <TableRow>
295
374
  <TableHead>{words.invoice}</TableHead>
296
- <TableHead>{words.customer}</TableHead>
375
+ <TableHead>{words.party}</TableHead>
297
376
  <TableHead>{words.status}</TableHead>
298
377
  <TableHead>{words.issued}</TableHead>
299
378
  <TableHead>{words.due}</TableHead>
@@ -326,9 +405,12 @@ export function InvoicesTable({
326
405
  <span className="font-medium">{invoiceTitle(invoice)}</span>
327
406
  )}
328
407
  </TableCell>
329
- <TableCell>{customerOf(invoice, names)}</TableCell>
408
+ <TableCell>{customerOf(invoice, names, own)}</TableCell>
330
409
  <TableCell>
331
- <InvoiceStatusBadge status={invoice.status} overdue={isOverdueInvoice(invoice, now)} />
410
+ <span className="flex flex-wrap gap-1">
411
+ {isCostInvoice(invoice, own) && <Badge variant="outline">{words.cost}</Badge>}
412
+ <InvoiceStatusBadge status={invoice.status} overdue={isOverdueInvoice(invoice, now)} />
413
+ </span>
332
414
  </TableCell>
333
415
  <TableCell>{formatDate(invoice.issuedTimestamp)}</TableCell>
334
416
  <TableCell>{formatDate(invoice.dueTimestamp)}</TableCell>
@@ -470,11 +552,190 @@ export function RecordPaymentForm({
470
552
  );
471
553
  }
472
554
 
473
- /** An invoice's details, its payments, and recording another while something is still to pay. */
555
+ /** A date input's day (YYYY-MM-DD) as the API's timestamp, the start of that day UTC, or null when it's empty. */
556
+ const dayOrNull = (day: string) => (day ? `${day}T00:00:00` : null);
557
+
558
+ /**
559
+ * An invoice's own fields, each saved as it changes: status, who pays and who's paid (company and person, found by
560
+ * searching), and the issue and due dates. A party's new company or person opens a step for its details, and using it
561
+ * saves the invoice. Its amounts and lines are as it was made.
562
+ */
563
+ function InvoiceFields({
564
+ invoice,
565
+ companies,
566
+ people,
567
+ names,
568
+ onChange,
569
+ saving,
570
+ text,
571
+ }: {
572
+ invoice: Invoice;
573
+ companies: readonly CrmChoice[];
574
+ people: readonly CrmChoice[];
575
+ names?: CrmNames | undefined;
576
+ onChange: (changes: Partial<InvoiceInput>, options?: InvoicePartyOptions) => Promise<unknown>;
577
+ saving?: boolean | undefined;
578
+ } & Words) {
579
+ const words = withText(text);
580
+ const id = useId();
581
+ const [adding, setAdding] = useState<{ which: 'remitter' | 'recipient'; record: 'company' | 'contact' }>();
582
+ const [error, setError] = useState<string>();
583
+ const save = async (changes: Partial<InvoiceInput>) => {
584
+ setError(undefined);
585
+ try {
586
+ await onChange(changes);
587
+ } catch (failure) {
588
+ setError(`${words.saveFailed} ${failure instanceof Error ? failure.message : ''}`.trim());
589
+ }
590
+ };
591
+ if (adding) {
592
+ const back = () => setAdding(undefined);
593
+ // Made, linked and saved before going back; a failure stays on the step, to be sent again.
594
+ return adding.record === 'company' ? (
595
+ <NewCompanyStep
596
+ framed={false}
597
+ text={text}
598
+ onBack={back}
599
+ onUse={async (name) => {
600
+ await onChange({}, { [`${adding.which}CompanyName`]: name });
601
+ back();
602
+ }}
603
+ />
604
+ ) : (
605
+ <NewContactStep
606
+ framed={false}
607
+ text={text}
608
+ onBack={back}
609
+ onUse={async (contact) => {
610
+ await onChange({}, { [`${adding.which}Contact`]: contact });
611
+ back();
612
+ }}
613
+ />
614
+ );
615
+ }
616
+ const party = (which: 'remitter' | 'recipient') => {
617
+ const current = invoice[which];
618
+ const set = (changes: InvoiceParty) =>
619
+ void save({ [which]: { company: current?.company ?? null, identity: current?.identity ?? null, ...changes } });
620
+ return (
621
+ <fieldset className="grid gap-3">
622
+ <legend className="mb-1 text-sm font-medium">{which === 'remitter' ? words.paidBy : words.paidTo}</legend>
623
+ <Field
624
+ id={`${id}-${which}-company`}
625
+ label={which === 'remitter' ? words.remitterCompany : words.recipientCompany}
626
+ >
627
+ <ChoiceCombobox
628
+ id={`${id}-${which}-company`}
629
+ single
630
+ value={current?.company ? [current.company.urn] : []}
631
+ onChange={([urn]) => set({ company: urn ? { urn } : null })}
632
+ choices={companies}
633
+ named={(urn) => companyNameOf(names, urn)}
634
+ placeholder={words.searchCompanies}
635
+ add={{ label: words.addCompany, onAdd: () => setAdding({ which, record: 'company' }) }}
636
+ text={text}
637
+ />
638
+ </Field>
639
+ <Field id={`${id}-${which}-person`} label={which === 'remitter' ? words.remitterPerson : words.recipientPerson}>
640
+ <ChoiceCombobox
641
+ id={`${id}-${which}-person`}
642
+ single
643
+ value={current?.identity ? [current.identity.urn] : []}
644
+ onChange={([urn]) => set({ identity: urn ? { urn } : null })}
645
+ choices={people}
646
+ named={(urn) => personNameOf(names, urn)}
647
+ placeholder={words.searchPeople}
648
+ add={{ label: words.addContact, onAdd: () => setAdding({ which, record: 'contact' }) }}
649
+ text={text}
650
+ />
651
+ </Field>
652
+ </fieldset>
653
+ );
654
+ };
655
+ return (
656
+ <div className="grid gap-3">
657
+ <Field id={`${id}-status`} label={words.status}>
658
+ <Select value={invoice.status} onValueChange={(next) => void save({ status: next as InvoiceStatus })}>
659
+ <SelectTrigger id={`${id}-status`} className="w-full">
660
+ <SelectValue />
661
+ </SelectTrigger>
662
+ <SelectContent>
663
+ {INVOICE_STATUSES.map((status) => (
664
+ <SelectItem key={status} value={status}>
665
+ {INVOICE_STATUS_LABELS[status]}
666
+ </SelectItem>
667
+ ))}
668
+ </SelectContent>
669
+ </Select>
670
+ </Field>
671
+ {party('remitter')}
672
+ {party('recipient')}
673
+ <div className="grid grid-cols-2 gap-3">
674
+ <Field id={`${id}-issued`} label={words.issuedOn}>
675
+ <Input
676
+ id={`${id}-issued`}
677
+ type="date"
678
+ value={invoice.issuedTimestamp?.slice(0, 10) ?? ''}
679
+ onChange={(event) => void save({ issuedTimestamp: dayOrNull(event.target.value) })}
680
+ />
681
+ </Field>
682
+ <Field id={`${id}-due`} label={words.dueOn}>
683
+ <Input
684
+ id={`${id}-due`}
685
+ type="date"
686
+ value={invoice.dueTimestamp?.slice(0, 10) ?? ''}
687
+ onChange={(event) => void save({ dueTimestamp: dayOrNull(event.target.value) })}
688
+ />
689
+ </Field>
690
+ </div>
691
+ <p aria-live="polite" className="text-muted-foreground text-xs">
692
+ {saving ? words.saving : ''}
693
+ </p>
694
+ {error && (
695
+ <p role="alert" className="text-destructive text-sm">
696
+ {error}
697
+ </p>
698
+ )}
699
+ </div>
700
+ );
701
+ }
702
+
703
+ /** An invoice's lines, read only: description, quantity, unit price and price. */
704
+ function InvoiceLines({ invoice, text }: { invoice: Invoice } & Words) {
705
+ const words = withText(text);
706
+ const lines = (invoice.lines ?? []).toSorted((a, b) => (a.lineNumber ?? 0) - (b.lineNumber ?? 0));
707
+ if (lines.length === 0) return null;
708
+ return (
709
+ <div className="grid gap-2">
710
+ <h3 className="text-sm font-semibold">{words.lines}</h3>
711
+ <ul className="grid gap-1.5 text-sm">
712
+ {lines.map((line) => (
713
+ <li key={line.urn} className="flex justify-between gap-2">
714
+ <span>
715
+ {line.description ?? '-'}
716
+ {line.quantity && line.quantity !== 1 ? ` x ${line.quantity}` : ''}
717
+ {line.itemCode ? <span className="text-muted-foreground"> ({line.itemCode})</span> : null}
718
+ </span>
719
+ <span className="tabular-nums">{formatMaybeMoney(line.price)}</span>
720
+ </li>
721
+ ))}
722
+ </ul>
723
+ </div>
724
+ );
725
+ }
726
+
727
+ /**
728
+ * An invoice's details, its lines, its payments, and recording another while something is still to pay. With
729
+ * `onChange`, its status, parties and dates can be edited, saved as they change.
730
+ */
474
731
  export function InvoiceDetail({
475
732
  invoice,
476
733
  payments,
477
734
  names,
735
+ companies = [],
736
+ people = [],
737
+ onChange,
738
+ saving,
478
739
  onRecord,
479
740
  now = new Date(),
480
741
  text,
@@ -483,34 +744,59 @@ export function InvoiceDetail({
483
744
  /** Remittances against this invoice. */
484
745
  payments: readonly Remittance[];
485
746
  names?: CrmNames | undefined;
747
+ /** Companies either party can be. */
748
+ companies?: readonly CrmChoice[] | undefined;
749
+ /** People either party can be. */
750
+ people?: readonly CrmChoice[] | undefined;
751
+ /** Saves a change to the invoice's own fields, making a party's new company or person first when `options` asks. */
752
+ onChange?: ((changes: Partial<InvoiceInput>, options?: InvoicePartyOptions) => Promise<unknown>) | undefined;
753
+ saving?: boolean | undefined;
486
754
  onRecord?: ((input: RemittanceInput) => Promise<unknown>) | undefined;
487
755
  now?: Date;
488
756
  } & Words) {
489
757
  const words = withText(text);
490
758
  const due = outstanding(invoice);
759
+ const amounts = [
760
+ { label: words.total, value: formatMaybeMoney(invoice.total) },
761
+ {
762
+ label: words.paid,
763
+ value: formatMaybeMoney({ unitValue: minorOf(invoice.paid), currencyCode: invoice.currencyCode }),
764
+ },
765
+ { label: words.outstanding, value: formatMaybeMoney(due) },
766
+ ];
491
767
  return (
492
768
  <CrmCard title={invoiceTitle(invoice)} text={text}>
493
769
  <div className="grid gap-5">
494
- <DetailList
495
- items={[
496
- {
497
- label: words.status,
498
- value: <InvoiceStatusBadge status={invoice.status} overdue={isOverdueInvoice(invoice, now)} />,
499
- },
500
- { label: words.customer, value: customerOf(invoice, names) },
501
- { label: words.issued, value: formatDate(invoice.issuedTimestamp) },
502
- { label: words.due, value: formatDate(invoice.dueTimestamp) },
503
- {
504
- label: words.total,
505
- value: formatMaybeMoney(invoice.total),
506
- },
507
- {
508
- label: words.paid,
509
- value: formatMaybeMoney({ unitValue: minorOf(invoice.paid), currencyCode: invoice.currencyCode }),
510
- },
511
- { label: words.outstanding, value: formatMaybeMoney(due) },
512
- ]}
513
- />
770
+ {onChange ? (
771
+ <>
772
+ <InvoiceFields
773
+ key={invoice.urn}
774
+ invoice={invoice}
775
+ companies={companies}
776
+ people={people}
777
+ names={names}
778
+ onChange={onChange}
779
+ saving={saving}
780
+ text={text}
781
+ />
782
+ <DetailList items={amounts} />
783
+ </>
784
+ ) : (
785
+ <DetailList
786
+ items={[
787
+ {
788
+ label: words.status,
789
+ value: <InvoiceStatusBadge status={invoice.status} overdue={isOverdueInvoice(invoice, now)} />,
790
+ },
791
+ { label: words.paidBy, value: partyName(invoice.remitter, names) ?? '-' },
792
+ { label: words.paidTo, value: partyName(invoice.recipient, names) ?? '-' },
793
+ { label: words.issued, value: formatDate(invoice.issuedTimestamp) },
794
+ { label: words.due, value: formatDate(invoice.dueTimestamp) },
795
+ ...amounts,
796
+ ]}
797
+ />
798
+ )}
799
+ <InvoiceLines invoice={invoice} text={text} />
514
800
  <div className="grid gap-2">
515
801
  <h3 className="text-sm font-semibold">{words.payments}</h3>
516
802
  {payments.length === 0 ? (
@@ -521,7 +807,9 @@ export function InvoiceDetail({
521
807
  <li key={payment.urn} className="flex justify-between gap-2">
522
808
  <span>
523
809
  {formatDate(payment.receivedTimestamp)}, {enumLabel(payment.remittanceMethod).toLowerCase()}
524
- {payment.remittanceStatus === 'RECEIVED' ? '' : ` (${enumLabel(payment.remittanceStatus).toLowerCase()})`}
810
+ {payment.remittanceStatus === 'RECEIVED'
811
+ ? ''
812
+ : ` (${enumLabel(payment.remittanceStatus).toLowerCase()})`}
525
813
  </span>
526
814
  <span className="tabular-nums">
527
815
  {payment.remittanceDirection === 'REFUND' ? '-' : ''}
@@ -1,6 +1,6 @@
1
1
  import { cn } from 'cn';
2
2
  import { X } from 'lucide-react';
3
- import { useCallback, useSyncExternalStore, type ReactNode } from 'react';
3
+ import { createContext, useCallback, useContext, useSyncExternalStore, type ReactNode } from 'react';
4
4
  import { withText, type CrmText } from './text.ts';
5
5
  import { Button } from './ui/button.tsx';
6
6
  import { Sheet, SheetContent, SheetTitle } from './ui/sheet.tsx';
@@ -23,6 +23,23 @@ export function useMediaQuery(query: string): boolean {
23
23
  /** The id of a record's card or row, so closing its panel can put focus back on it. */
24
24
  export const recordItemId = (urn: string) => `crm-item-${urn}`;
25
25
 
26
+ /** The open panel's close action, for the card or form heading it holds to show beside its title. */
27
+ export const PanelClose = createContext<{ close: () => void; label: string } | undefined>(undefined);
28
+
29
+ /**
30
+ * Closes the side panel this is in, beside a card's or form's title so it lines up with it. Nothing outside a panel.
31
+ * A card shows it once: it clears the context for what it holds (see `CrmCard`).
32
+ */
33
+ export function PanelCloseButton() {
34
+ const panel = useContext(PanelClose);
35
+ if (!panel) return null;
36
+ return (
37
+ <Button variant="ghost" size="icon-sm" onClick={panel.close} aria-label={panel.label}>
38
+ <X aria-hidden="true" />
39
+ </Button>
40
+ );
41
+ }
42
+
26
43
  /**
27
44
  * A list or board with the open record beside it, as baack-ts-tasks' task view does: a sticky panel to the right on
28
45
  * wide screens, a sheet from the right on narrow ones. Closing puts focus back on the record's card or row.
@@ -51,15 +68,7 @@ export function SidePanelLayout({
51
68
  if (open) requestAnimationFrame(() => document.getElementById(recordItemId(open))?.focus());
52
69
  };
53
70
  const content = (
54
- <div className="grid gap-2">
55
- <div className="flex justify-end">
56
- <Button variant="ghost" size="sm" onClick={close} aria-label={`${words.close}: ${title}`}>
57
- <X aria-hidden="true" />
58
- {words.close}
59
- </Button>
60
- </div>
61
- {panel}
62
- </div>
71
+ <PanelClose.Provider value={{ close, label: `${words.close}: ${title}` }}>{panel}</PanelClose.Provider>
63
72
  );
64
73
  return (
65
74
  <>
@@ -82,7 +91,9 @@ export function SidePanelLayout({
82
91
  side="right"
83
92
  showCloseButton={false}
84
93
  aria-describedby={undefined}
85
- className="w-full overflow-y-auto p-4 sm:max-w-md"
94
+ // The sheet is a flex column of fixed height: without shrink-0 a card, which hides its overflow, shrinks to
95
+ // fit and clips its end, leaving the sheet nothing to scroll.
96
+ className="w-full overflow-y-auto p-4 *:shrink-0 sm:max-w-md"
86
97
  onCloseAutoFocus={(event) => event.preventDefault()}
87
98
  >
88
99
  <SheetTitle className="sr-only">{title}</SheetTitle>
@@ -9,5 +9,6 @@ export * from './Details.tsx';
9
9
  export * from './CompanyAccountView.tsx';
10
10
  export * from './Sales.tsx';
11
11
  export * from './Forms.tsx';
12
+ export * from './ChoiceCombobox.tsx';
12
13
  export * from './SidePanel.tsx';
13
14
  export * from './views.tsx';