@baack-software/baack-ts-crm 0.0.0-stage → 0.0.2

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 (219) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +74 -2
  3. package/dist/account.d.ts +36 -0
  4. package/dist/account.d.ts.map +1 -0
  5. package/dist/account.js +48 -0
  6. package/dist/account.js.map +1 -0
  7. package/dist/backend.d.ts +76 -0
  8. package/dist/backend.d.ts.map +1 -0
  9. package/dist/backend.js +233 -0
  10. package/dist/backend.js.map +1 -0
  11. package/dist/crm-client.d.ts +122 -0
  12. package/dist/crm-client.d.ts.map +1 -0
  13. package/dist/crm-client.js +168 -0
  14. package/dist/crm-client.js.map +1 -0
  15. package/dist/errors.d.ts +21 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +33 -0
  18. package/dist/errors.js.map +1 -0
  19. package/dist/index.d.ts +13 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +13 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/invoices.d.ts +46 -0
  24. package/dist/invoices.d.ts.map +1 -0
  25. package/dist/invoices.js +137 -0
  26. package/dist/invoices.js.map +1 -0
  27. package/dist/leads.d.ts +29 -0
  28. package/dist/leads.d.ts.map +1 -0
  29. package/dist/leads.js +56 -0
  30. package/dist/leads.js.map +1 -0
  31. package/dist/mock/index.d.ts +43 -0
  32. package/dist/mock/index.d.ts.map +1 -0
  33. package/dist/mock/index.js +303 -0
  34. package/dist/mock/index.js.map +1 -0
  35. package/dist/money.d.ts +29 -0
  36. package/dist/money.d.ts.map +1 -0
  37. package/dist/money.js +82 -0
  38. package/dist/money.js.map +1 -0
  39. package/dist/period.d.ts +17 -0
  40. package/dist/period.d.ts.map +1 -0
  41. package/dist/period.js +23 -0
  42. package/dist/period.js.map +1 -0
  43. package/dist/pipeline.d.ts +30 -0
  44. package/dist/pipeline.d.ts.map +1 -0
  45. package/dist/pipeline.js +40 -0
  46. package/dist/pipeline.js.map +1 -0
  47. package/dist/react/Charts.d.ts +19 -0
  48. package/dist/react/Charts.d.ts.map +1 -0
  49. package/dist/react/Charts.js +38 -0
  50. package/dist/react/Charts.js.map +1 -0
  51. package/dist/react/CompanyAccountView.d.ts +21 -0
  52. package/dist/react/CompanyAccountView.d.ts.map +1 -0
  53. package/dist/react/CompanyAccountView.js +27 -0
  54. package/dist/react/CompanyAccountView.js.map +1 -0
  55. package/dist/react/DashboardCards.d.ts +32 -0
  56. package/dist/react/DashboardCards.d.ts.map +1 -0
  57. package/dist/react/DashboardCards.js +38 -0
  58. package/dist/react/DashboardCards.js.map +1 -0
  59. package/dist/react/DealsBoard.d.ts +30 -0
  60. package/dist/react/DealsBoard.d.ts.map +1 -0
  61. package/dist/react/DealsBoard.js +33 -0
  62. package/dist/react/DealsBoard.js.map +1 -0
  63. package/dist/react/Details.d.ts +52 -0
  64. package/dist/react/Details.d.ts.map +1 -0
  65. package/dist/react/Details.js +111 -0
  66. package/dist/react/Details.js.map +1 -0
  67. package/dist/react/Forms.d.ts +59 -0
  68. package/dist/react/Forms.d.ts.map +1 -0
  69. package/dist/react/Forms.js +204 -0
  70. package/dist/react/Forms.js.map +1 -0
  71. package/dist/react/LeadsTable.d.ts +22 -0
  72. package/dist/react/LeadsTable.d.ts.map +1 -0
  73. package/dist/react/LeadsTable.js +79 -0
  74. package/dist/react/LeadsTable.js.map +1 -0
  75. package/dist/react/Sales.d.ts +49 -0
  76. package/dist/react/Sales.d.ts.map +1 -0
  77. package/dist/react/Sales.js +186 -0
  78. package/dist/react/Sales.js.map +1 -0
  79. package/dist/react/SidePanel.d.ts +21 -0
  80. package/dist/react/SidePanel.d.ts.map +1 -0
  81. package/dist/react/SidePanel.js +37 -0
  82. package/dist/react/SidePanel.js.map +1 -0
  83. package/dist/react/format.d.ts +28 -0
  84. package/dist/react/format.d.ts.map +1 -0
  85. package/dist/react/format.js +30 -0
  86. package/dist/react/format.js.map +1 -0
  87. package/dist/react/index.d.ts +14 -0
  88. package/dist/react/index.d.ts.map +1 -0
  89. package/dist/react/index.js +14 -0
  90. package/dist/react/index.js.map +1 -0
  91. package/dist/react/parts.d.ts +45 -0
  92. package/dist/react/parts.d.ts.map +1 -0
  93. package/dist/react/parts.js +59 -0
  94. package/dist/react/parts.js.map +1 -0
  95. package/dist/react/text.d.ts +145 -0
  96. package/dist/react/text.d.ts.map +1 -0
  97. package/dist/react/text.js +142 -0
  98. package/dist/react/text.js.map +1 -0
  99. package/dist/react/ui/alert.d.ts +11 -0
  100. package/dist/react/ui/alert.d.ts.map +1 -0
  101. package/dist/react/ui/alert.js +29 -0
  102. package/dist/react/ui/alert.js.map +1 -0
  103. package/dist/react/ui/badge.d.ts +10 -0
  104. package/dist/react/ui/badge.d.ts.map +1 -0
  105. package/dist/react/ui/badge.js +26 -0
  106. package/dist/react/ui/badge.js.map +1 -0
  107. package/dist/react/ui/button.d.ts +11 -0
  108. package/dist/react/ui/button.d.ts.map +1 -0
  109. package/dist/react/ui/button.js +37 -0
  110. package/dist/react/ui/button.js.map +1 -0
  111. package/dist/react/ui/card.d.ts +12 -0
  112. package/dist/react/ui/card.d.ts.map +1 -0
  113. package/dist/react/ui/card.js +26 -0
  114. package/dist/react/ui/card.js.map +1 -0
  115. package/dist/react/ui/chart.d.ts +45 -0
  116. package/dist/react/ui/chart.d.ts.map +1 -0
  117. package/dist/react/ui/chart.js +116 -0
  118. package/dist/react/ui/chart.js.map +1 -0
  119. package/dist/react/ui/input.d.ts +4 -0
  120. package/dist/react/ui/input.d.ts.map +1 -0
  121. package/dist/react/ui/input.js +8 -0
  122. package/dist/react/ui/input.js.map +1 -0
  123. package/dist/react/ui/label.d.ts +5 -0
  124. package/dist/react/ui/label.d.ts.map +1 -0
  125. package/dist/react/ui/label.js +10 -0
  126. package/dist/react/ui/label.js.map +1 -0
  127. package/dist/react/ui/progress.d.ts +5 -0
  128. package/dist/react/ui/progress.d.ts.map +1 -0
  129. package/dist/react/ui/progress.js +10 -0
  130. package/dist/react/ui/progress.js.map +1 -0
  131. package/dist/react/ui/select.d.ts +16 -0
  132. package/dist/react/ui/select.d.ts.map +1 -0
  133. package/dist/react/ui/select.js +37 -0
  134. package/dist/react/ui/select.js.map +1 -0
  135. package/dist/react/ui/separator.d.ts +5 -0
  136. package/dist/react/ui/separator.d.ts.map +1 -0
  137. package/dist/react/ui/separator.js +10 -0
  138. package/dist/react/ui/separator.js.map +1 -0
  139. package/dist/react/ui/sheet.d.ts +15 -0
  140. package/dist/react/ui/sheet.d.ts.map +1 -0
  141. package/dist/react/ui/sheet.js +38 -0
  142. package/dist/react/ui/sheet.js.map +1 -0
  143. package/dist/react/ui/skeleton.d.ts +3 -0
  144. package/dist/react/ui/skeleton.d.ts.map +1 -0
  145. package/dist/react/ui/skeleton.js +7 -0
  146. package/dist/react/ui/skeleton.js.map +1 -0
  147. package/dist/react/ui/table.d.ts +11 -0
  148. package/dist/react/ui/table.d.ts.map +1 -0
  149. package/dist/react/ui/table.js +29 -0
  150. package/dist/react/ui/table.js.map +1 -0
  151. package/dist/react/ui/tabs.d.ts +12 -0
  152. package/dist/react/ui/tabs.d.ts.map +1 -0
  153. package/dist/react/ui/tabs.js +31 -0
  154. package/dist/react/ui/tabs.js.map +1 -0
  155. package/dist/react/views.d.ts +60 -0
  156. package/dist/react/views.d.ts.map +1 -0
  157. package/dist/react/views.js +172 -0
  158. package/dist/react/views.js.map +1 -0
  159. package/dist/sales.d.ts +57 -0
  160. package/dist/sales.d.ts.map +1 -0
  161. package/dist/sales.js +64 -0
  162. package/dist/sales.js.map +1 -0
  163. package/dist/store.d.ts +140 -0
  164. package/dist/store.d.ts.map +1 -0
  165. package/dist/store.js +244 -0
  166. package/dist/store.js.map +1 -0
  167. package/dist/target.d.ts +21 -0
  168. package/dist/target.d.ts.map +1 -0
  169. package/dist/target.js +36 -0
  170. package/dist/target.js.map +1 -0
  171. package/dist/types.d.ts +180 -0
  172. package/dist/types.d.ts.map +1 -0
  173. package/dist/types.js +2 -0
  174. package/dist/types.js.map +1 -0
  175. package/package.json +100 -4
  176. package/src/account.ts +79 -0
  177. package/src/backend.ts +371 -0
  178. package/src/crm-client.ts +250 -0
  179. package/src/errors.ts +34 -0
  180. package/src/index.ts +12 -0
  181. package/src/invoices.ts +157 -0
  182. package/src/leads.ts +78 -0
  183. package/src/mock/index.ts +398 -0
  184. package/src/money.ts +104 -0
  185. package/src/period.ts +32 -0
  186. package/src/pipeline.ts +61 -0
  187. package/src/react/Charts.tsx +143 -0
  188. package/src/react/CompanyAccountView.tsx +198 -0
  189. package/src/react/DashboardCards.tsx +171 -0
  190. package/src/react/DealsBoard.tsx +177 -0
  191. package/src/react/Details.tsx +293 -0
  192. package/src/react/Forms.tsx +619 -0
  193. package/src/react/LeadsTable.tsx +234 -0
  194. package/src/react/Sales.tsx +539 -0
  195. package/src/react/SidePanel.tsx +95 -0
  196. package/src/react/format.ts +53 -0
  197. package/src/react/index.ts +13 -0
  198. package/src/react/parts.tsx +131 -0
  199. package/src/react/text.ts +144 -0
  200. package/src/react/ui/README.md +6 -0
  201. package/src/react/ui/alert.tsx +75 -0
  202. package/src/react/ui/badge.tsx +48 -0
  203. package/src/react/ui/button.tsx +66 -0
  204. package/src/react/ui/card.tsx +102 -0
  205. package/src/react/ui/chart.tsx +304 -0
  206. package/src/react/ui/input.tsx +18 -0
  207. package/src/react/ui/label.tsx +23 -0
  208. package/src/react/ui/progress.tsx +30 -0
  209. package/src/react/ui/select.tsx +189 -0
  210. package/src/react/ui/separator.tsx +27 -0
  211. package/src/react/ui/sheet.tsx +145 -0
  212. package/src/react/ui/skeleton.tsx +13 -0
  213. package/src/react/ui/table.tsx +113 -0
  214. package/src/react/ui/tabs.tsx +89 -0
  215. package/src/react/views.tsx +443 -0
  216. package/src/sales.ts +120 -0
  217. package/src/store.ts +419 -0
  218. package/src/target.ts +51 -0
  219. package/src/types.ts +202 -0
@@ -0,0 +1,539 @@
1
+ import { toTimestamp } from '@baack-software/baack-ts-tasks';
2
+ import { Download, Search } from 'lucide-react';
3
+ import { useId, useMemo, useState, type FormEvent } from 'react';
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';
7
+ import { fractionDigits, fromMinor, formatMoney, minorOf, toDecimal, toMinor, type MoneyTotals } from '../money.ts';
8
+ import type { SalesSummary } from '../sales.ts';
9
+ import type { Invoice, InvoiceStatus, Remittance, RemittanceMethod } from '../types.ts';
10
+ import { DetailList } from './Details.tsx';
11
+ import { MetricCard } from './DashboardCards.tsx';
12
+ import { companyNameOf, enumLabel, formatDate, formatMaybeMoney, formatTotals, type CrmNames } from './format.ts';
13
+ import { CrmCard, InvoiceStatusBadge } from './parts.tsx';
14
+ import { recordItemId } from './SidePanel.tsx';
15
+ import { withText, type CrmText } from './text.ts';
16
+ import { Button } from './ui/button.tsx';
17
+ import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from './ui/chart.tsx';
18
+ import { Input } from './ui/input.tsx';
19
+ import { Label } from './ui/label.tsx';
20
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select.tsx';
21
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table.tsx';
22
+
23
+ type Words = { text?: Partial<CrmText> | undefined };
24
+
25
+ /** The invoiced, received, outstanding and sales tax figures, each against the period before where it applies. */
26
+ export function SalesMetricCards({ summary, text }: { summary: SalesSummary } & Words) {
27
+ const words = withText(text);
28
+ const currency = summary.currencyCode;
29
+ return (
30
+ <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
31
+ <MetricCard
32
+ label={words.invoiced}
33
+ value={formatTotals(summary.invoiced.current, currency)}
34
+ change={summary.invoiced.change}
35
+ hint={words.invoicedHint}
36
+ text={text}
37
+ />
38
+ <MetricCard
39
+ label={words.received}
40
+ value={formatTotals(summary.received.current, currency)}
41
+ change={summary.received.change}
42
+ hint={words.revenueHint}
43
+ text={text}
44
+ />
45
+ <MetricCard
46
+ label={words.outstanding}
47
+ value={formatTotals(summary.outstanding, currency)}
48
+ change={undefined}
49
+ hint={`${words.overdue}: ${formatTotals(summary.overdue, currency)}`}
50
+ text={{ ...text, noChange: words.outstandingHint }}
51
+ />
52
+ <MetricCard
53
+ label={words.salesTax}
54
+ value={formatTotals(summary.tax.current, currency)}
55
+ change={summary.tax.change}
56
+ hint={words.salesTaxHint}
57
+ text={text}
58
+ />
59
+ </div>
60
+ );
61
+ }
62
+
63
+ /** Totals in one currency as a number of whole units, for a chart axis. */
64
+ const units = (totals: MoneyTotals, currency: string) => (totals[currency] ?? 0) / 10 ** fractionDigits(currency);
65
+
66
+ function MoneyBars({
67
+ title,
68
+ description,
69
+ rows,
70
+ currencyCode,
71
+ color,
72
+ layout,
73
+ text,
74
+ }: {
75
+ title: string;
76
+ description?: string;
77
+ rows: { label: string; totals: MoneyTotals }[];
78
+ currencyCode: string | undefined;
79
+ color: string;
80
+ layout: 'horizontal' | 'vertical';
81
+ } & Words) {
82
+ const words = withText(text);
83
+ const currency = currencyCode ?? 'GBP';
84
+ const points = rows.map((row) => ({ label: row.label, amount: units(row.totals, currency) }));
85
+ const config = { amount: { label: words.amount, color } } satisfies ChartConfig;
86
+ const money = (value: number) => formatMoney(fromMinor(Math.round(value * 10 ** fractionDigits(currency)), currency));
87
+ const short = (value: number) =>
88
+ new Intl.NumberFormat('en-GB', { style: 'currency', currency, notation: 'compact' }).format(value);
89
+ const vertical = layout === 'vertical';
90
+ return (
91
+ <CrmCard title={title} {...(description ? { description } : {})} text={text}>
92
+ <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
93
+ <BarChart data={points} layout={layout} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
94
+ <CartesianGrid vertical={vertical} horizontal={!vertical} />
95
+ {vertical ? (
96
+ <>
97
+ <YAxis dataKey="label" type="category" tickLine={false} axisLine={false} width={104} />
98
+ <XAxis type="number" tickLine={false} axisLine={false} tickFormatter={short} />
99
+ </>
100
+ ) : (
101
+ <>
102
+ <XAxis dataKey="label" tickLine={false} axisLine={false} interval={0} tick={{ fontSize: 11 }} />
103
+ <YAxis tickLine={false} axisLine={false} width={56} tickFormatter={short} />
104
+ </>
105
+ )}
106
+ <ChartTooltip
107
+ cursor={false}
108
+ content={<ChartTooltipContent formatter={(value) => money(Number(value))} indicator="dot" />}
109
+ />
110
+ <Bar dataKey="amount" fill="var(--color-amount)" radius={4} isAnimationActive={false} />
111
+ </BarChart>
112
+ </ChartContainer>
113
+ <div className="sr-only">
114
+ <table>
115
+ <caption>{title}</caption>
116
+ <tbody>
117
+ {points.map((point) => (
118
+ <tr key={point.label}>
119
+ <th scope="row">{point.label}</th>
120
+ <td>{money(point.amount)}</td>
121
+ </tr>
122
+ ))}
123
+ </tbody>
124
+ </table>
125
+ </div>
126
+ </CrmCard>
127
+ );
128
+ }
129
+
130
+ /** What's still to pay, by how long it's been overdue. */
131
+ export function OutstandingByAgeCard({ summary, text }: { summary: SalesSummary } & Words) {
132
+ const words = withText(text);
133
+ return (
134
+ <MoneyBars
135
+ title={words.outstandingByAge}
136
+ description={formatTotals(summary.outstanding, summary.currencyCode)}
137
+ rows={summary.byAge.map((row) => ({
138
+ label: AGE_BUCKET_LABELS[row.bucket].replace(' overdue', ''),
139
+ totals: row.totals,
140
+ }))}
141
+ currencyCode={summary.currencyCode}
142
+ color="var(--chart-3)"
143
+ layout="horizontal"
144
+ text={text}
145
+ />
146
+ );
147
+ }
148
+
149
+ /** Money received in the period by payment method. */
150
+ export function PaymentMethodsCard({ summary, text }: { summary: SalesSummary } & Words) {
151
+ const words = withText(text);
152
+ return (
153
+ <MoneyBars
154
+ title={words.paymentMethods}
155
+ rows={summary.byMethod
156
+ .filter((row) => Object.values(row.totals).some((minor) => minor !== 0))
157
+ .map((row) => ({ label: enumLabel(row.method), totals: row.totals }))}
158
+ currencyCode={summary.currencyCode}
159
+ color="var(--chart-4)"
160
+ layout="vertical"
161
+ text={text}
162
+ />
163
+ );
164
+ }
165
+
166
+ const AWAITING = 'awaiting';
167
+ const OVERDUE = 'overdue';
168
+ const ALL = 'all';
169
+ type InvoiceFilter = typeof ALL | typeof AWAITING | typeof OVERDUE | InvoiceStatus;
170
+
171
+ /** An invoice's name for people: its first line, else the end of its URN. */
172
+ export const invoiceTitle = (invoice: Invoice) => invoice.lines?.[0]?.description ?? `Invoice ${invoice.urn.slice(-6)}`;
173
+
174
+ /** The company an invoice is for. */
175
+ const customerOf = (invoice: Invoice, names?: CrmNames) =>
176
+ companyNameOf(names, (invoice.recipient ?? invoice.remitter)?.company?.urn) ?? '-';
177
+
178
+ function invoicesCsv(invoices: readonly Invoice[], names?: CrmNames): string {
179
+ const cell = (value: string) => (/[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value);
180
+ const header = ['Invoice', 'Customer', 'Status', 'Issued', 'Due', 'Currency', 'Total', 'Paid', 'Outstanding'];
181
+ const rows = invoices.map((invoice) => [
182
+ invoiceTitle(invoice),
183
+ customerOf(invoice, names),
184
+ invoice.status,
185
+ invoice.issuedTimestamp ?? '',
186
+ invoice.dueTimestamp ?? '',
187
+ invoice.currencyCode,
188
+ toDecimal(minorOf(invoice.total), invoice.currencyCode),
189
+ toDecimal(minorOf(invoice.paid), invoice.currencyCode),
190
+ toDecimal(outstanding(invoice)?.unitValue ?? 0, invoice.currencyCode),
191
+ ]);
192
+ return [header, ...rows].map((row) => row.map(cell).join(',')).join('\n');
193
+ }
194
+
195
+ /** Invoices filtered by words and status (awaiting payment, overdue, paid and so on), a page at a time. */
196
+ export function InvoicesTable({
197
+ invoices,
198
+ names,
199
+ onOpen,
200
+ selected,
201
+ now = new Date(),
202
+ pageSize = 10,
203
+ text,
204
+ }: {
205
+ invoices: readonly Invoice[];
206
+ names?: CrmNames | undefined;
207
+ onOpen?: ((invoice: Invoice) => void) | undefined;
208
+ /** The open invoice, highlighted. */
209
+ selected?: string | undefined;
210
+ now?: Date;
211
+ pageSize?: number;
212
+ } & Words) {
213
+ const words = withText(text);
214
+ const [query, setQuery] = useState('');
215
+ const [filter, setFilter] = useState<InvoiceFilter>(ALL);
216
+ const [page, setPage] = useState(0);
217
+ const filtered = useMemo(() => {
218
+ const needle = query.trim().toLowerCase();
219
+ return invoices.filter((invoice) => {
220
+ if (filter === AWAITING && !outstanding(invoice)) return false;
221
+ if (filter === OVERDUE && !isOverdueInvoice(invoice, now)) return false;
222
+ if (filter !== ALL && filter !== AWAITING && filter !== OVERDUE && invoice.status !== filter) return false;
223
+ return !needle || `${invoiceTitle(invoice)} ${customerOf(invoice, names)}`.toLowerCase().includes(needle);
224
+ });
225
+ }, [invoices, names, query, filter, now]);
226
+ const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
227
+ const current = Math.min(page, pages - 1);
228
+ const shown = filtered.slice(current * pageSize, (current + 1) * pageSize);
229
+ const first = current * pageSize + 1;
230
+
231
+ return (
232
+ <CrmCard
233
+ title={words.invoices}
234
+ text={text}
235
+ action={
236
+ <Button
237
+ variant="outline"
238
+ size="sm"
239
+ onClick={() => {
240
+ const url = URL.createObjectURL(new Blob([invoicesCsv(filtered, names)], { type: 'text/csv' }));
241
+ const link = document.createElement('a');
242
+ link.href = url;
243
+ link.download = 'invoices.csv';
244
+ link.click();
245
+ URL.revokeObjectURL(url);
246
+ }}
247
+ >
248
+ <Download aria-hidden="true" />
249
+ {words.export}
250
+ </Button>
251
+ }
252
+ >
253
+ <div className="mb-3 flex flex-wrap items-center gap-2">
254
+ <div className="relative min-w-48 flex-1">
255
+ <Search
256
+ aria-hidden="true"
257
+ className="text-muted-foreground absolute top-1/2 left-2.5 size-4 -translate-y-1/2"
258
+ />
259
+ <Input
260
+ type="search"
261
+ aria-label={words.filterInvoices}
262
+ placeholder={words.filterInvoices}
263
+ value={query}
264
+ onChange={(event) => {
265
+ setQuery(event.target.value);
266
+ setPage(0);
267
+ }}
268
+ className="pl-8"
269
+ />
270
+ </div>
271
+ <Select
272
+ value={filter}
273
+ onValueChange={(value) => {
274
+ setFilter(value as InvoiceFilter);
275
+ setPage(0);
276
+ }}
277
+ >
278
+ <SelectTrigger aria-label={words.status} className="w-44">
279
+ <SelectValue />
280
+ </SelectTrigger>
281
+ <SelectContent>
282
+ <SelectItem value={ALL}>{words.allInvoices}</SelectItem>
283
+ <SelectItem value={AWAITING}>{words.awaitingPayment}</SelectItem>
284
+ <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>
288
+ </SelectContent>
289
+ </Select>
290
+ </div>
291
+ <Table>
292
+ <caption className="sr-only">{words.invoices}</caption>
293
+ <TableHeader>
294
+ <TableRow>
295
+ <TableHead>{words.invoice}</TableHead>
296
+ <TableHead>{words.customer}</TableHead>
297
+ <TableHead>{words.status}</TableHead>
298
+ <TableHead>{words.issued}</TableHead>
299
+ <TableHead>{words.due}</TableHead>
300
+ <TableHead className="text-right">{words.total}</TableHead>
301
+ <TableHead className="text-right">{words.outstanding}</TableHead>
302
+ </TableRow>
303
+ </TableHeader>
304
+ <TableBody>
305
+ {shown.length === 0 ? (
306
+ <TableRow>
307
+ <TableCell colSpan={7} className="text-muted-foreground py-6 text-center">
308
+ {words.noMatchingInvoices}
309
+ </TableCell>
310
+ </TableRow>
311
+ ) : (
312
+ shown.map((invoice) => (
313
+ <TableRow key={invoice.urn} data-state={selected === invoice.urn ? 'selected' : undefined}>
314
+ <TableCell className="max-w-64 whitespace-normal">
315
+ {onOpen ? (
316
+ <button
317
+ type="button"
318
+ id={recordItemId(invoice.urn)}
319
+ aria-current={selected === invoice.urn ? 'true' : undefined}
320
+ className="text-left font-medium hover:underline"
321
+ onClick={() => onOpen(invoice)}
322
+ >
323
+ {invoiceTitle(invoice)}
324
+ </button>
325
+ ) : (
326
+ <span className="font-medium">{invoiceTitle(invoice)}</span>
327
+ )}
328
+ </TableCell>
329
+ <TableCell>{customerOf(invoice, names)}</TableCell>
330
+ <TableCell>
331
+ <InvoiceStatusBadge status={invoice.status} overdue={isOverdueInvoice(invoice, now)} />
332
+ </TableCell>
333
+ <TableCell>{formatDate(invoice.issuedTimestamp)}</TableCell>
334
+ <TableCell>{formatDate(invoice.dueTimestamp)}</TableCell>
335
+ <TableCell className="text-right tabular-nums">
336
+ {formatMaybeMoney(invoice.total)}
337
+ </TableCell>
338
+ <TableCell className="text-right tabular-nums">{formatMaybeMoney(outstanding(invoice))}</TableCell>
339
+ </TableRow>
340
+ ))
341
+ )}
342
+ </TableBody>
343
+ </Table>
344
+ <div className="mt-3 flex items-center justify-between gap-2 text-sm">
345
+ <p className="text-muted-foreground" aria-live="polite">
346
+ {filtered.length === 0
347
+ ? `0 ${words.invoices.toLowerCase()}`
348
+ : `${first} - ${first + shown.length - 1} ${words.of} ${filtered.length} ${words.invoices.toLowerCase()}`}
349
+ </p>
350
+ <div className="flex gap-2">
351
+ <Button variant="outline" size="sm" disabled={current === 0} onClick={() => setPage(current - 1)}>
352
+ {words.previous}
353
+ </Button>
354
+ <Button variant="outline" size="sm" disabled={current >= pages - 1} onClick={() => setPage(current + 1)}>
355
+ {words.next}
356
+ </Button>
357
+ </div>
358
+ </div>
359
+ </CrmCard>
360
+ );
361
+ }
362
+
363
+ const METHODS: RemittanceMethod[] = ['BANK_TRANSFER', 'CARD_PAYMENT', 'DIRECT_DEBIT', 'CASH', 'E_WALLET', 'OTHER'];
364
+
365
+ /** Records a payment against an invoice: the amount (what's outstanding to start with), method and reference. */
366
+ export function RecordPaymentForm({
367
+ invoice,
368
+ onRecord,
369
+ now = () => new Date(),
370
+ text,
371
+ }: {
372
+ invoice: Invoice;
373
+ onRecord: (input: RemittanceInput) => Promise<unknown>;
374
+ now?: () => Date;
375
+ } & Words) {
376
+ const words = withText(text);
377
+ const id = useId();
378
+ const due = outstanding(invoice);
379
+ const [amount, setAmount] = useState(due ? toDecimal(due.unitValue, due.currencyCode) : '');
380
+ const [method, setMethod] = useState<RemittanceMethod>('BANK_TRANSFER');
381
+ const [reference, setReference] = useState('');
382
+ const [error, setError] = useState<string>();
383
+ const [status, setStatus] = useState<'idle' | 'saving' | 'saved'>('idle');
384
+
385
+ const submit = async (event: FormEvent) => {
386
+ event.preventDefault();
387
+ let minor = 0;
388
+ try {
389
+ minor = toMinor(amount, invoice.currencyCode);
390
+ } catch {
391
+ minor = 0;
392
+ }
393
+ if (minor <= 0) {
394
+ setError(words.invalidAmount);
395
+ return;
396
+ }
397
+ setError(undefined);
398
+ setStatus('saving');
399
+ try {
400
+ await onRecord({
401
+ paymentInvoice: { urn: invoice.urn },
402
+ remittanceDirection: 'PAYMENT',
403
+ remittanceStatus: 'RECEIVED',
404
+ remittanceMethod: method,
405
+ value: { unitValue: minor, currencyCode: invoice.currencyCode },
406
+ reference: reference.trim() || null,
407
+ remittingCompany: invoice.remitter?.company ?? null,
408
+ remittingIdentity: invoice.remitter?.identity ?? null,
409
+ receivedTimestamp: toTimestamp(now()),
410
+ });
411
+ setStatus('saved');
412
+ setReference('');
413
+ } catch (failure) {
414
+ setStatus('idle');
415
+ setError(failure instanceof Error ? failure.message : String(failure));
416
+ }
417
+ };
418
+
419
+ return (
420
+ <form onSubmit={(event) => void submit(event)} className="grid gap-3" aria-labelledby={`${id}-title`}>
421
+ <h3 id={`${id}-title`} className="text-sm font-semibold">
422
+ {words.recordPayment}
423
+ </h3>
424
+ <div className="grid gap-1.5">
425
+ <Label htmlFor={`${id}-amount`}>
426
+ {words.amount} ({invoice.currencyCode})
427
+ </Label>
428
+ <Input
429
+ id={`${id}-amount`}
430
+ inputMode="decimal"
431
+ value={amount}
432
+ onChange={(event) => setAmount(event.target.value)}
433
+ aria-invalid={error ? true : undefined}
434
+ aria-describedby={error ? `${id}-error` : undefined}
435
+ />
436
+ </div>
437
+ <div className="grid gap-1.5">
438
+ <Label htmlFor={`${id}-method`}>{words.method}</Label>
439
+ <Select value={method} onValueChange={(value) => setMethod(value as RemittanceMethod)}>
440
+ <SelectTrigger id={`${id}-method`} className="w-full">
441
+ <SelectValue />
442
+ </SelectTrigger>
443
+ <SelectContent>
444
+ {METHODS.map((value) => (
445
+ <SelectItem key={value} value={value}>
446
+ {enumLabel(value)}
447
+ </SelectItem>
448
+ ))}
449
+ </SelectContent>
450
+ </Select>
451
+ </div>
452
+ <div className="grid gap-1.5">
453
+ <Label htmlFor={`${id}-reference`}>{words.reference}</Label>
454
+ <Input id={`${id}-reference`} value={reference} onChange={(event) => setReference(event.target.value)} />
455
+ </div>
456
+ {error && (
457
+ <p id={`${id}-error`} role="alert" className="text-destructive text-sm">
458
+ {error}
459
+ </p>
460
+ )}
461
+ <div className="flex items-center gap-3">
462
+ <Button type="submit" disabled={status === 'saving'}>
463
+ {status === 'saving' ? words.recording : words.recordPayment}
464
+ </Button>
465
+ <p aria-live="polite" className="text-muted-foreground text-sm">
466
+ {status === 'saved' ? words.paymentRecorded : ''}
467
+ </p>
468
+ </div>
469
+ </form>
470
+ );
471
+ }
472
+
473
+ /** An invoice's details, its payments, and recording another while something is still to pay. */
474
+ export function InvoiceDetail({
475
+ invoice,
476
+ payments,
477
+ names,
478
+ onRecord,
479
+ now = new Date(),
480
+ text,
481
+ }: {
482
+ invoice: Invoice;
483
+ /** Remittances against this invoice. */
484
+ payments: readonly Remittance[];
485
+ names?: CrmNames | undefined;
486
+ onRecord?: ((input: RemittanceInput) => Promise<unknown>) | undefined;
487
+ now?: Date;
488
+ } & Words) {
489
+ const words = withText(text);
490
+ const due = outstanding(invoice);
491
+ return (
492
+ <CrmCard title={invoiceTitle(invoice)} text={text}>
493
+ <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
+ />
514
+ <div className="grid gap-2">
515
+ <h3 className="text-sm font-semibold">{words.payments}</h3>
516
+ {payments.length === 0 ? (
517
+ <p className="text-muted-foreground text-sm">{words.noPayments}</p>
518
+ ) : (
519
+ <ul className="grid gap-1.5 text-sm">
520
+ {payments.map((payment) => (
521
+ <li key={payment.urn} className="flex justify-between gap-2">
522
+ <span>
523
+ {formatDate(payment.receivedTimestamp)}, {enumLabel(payment.remittanceMethod).toLowerCase()}
524
+ {payment.remittanceStatus === 'RECEIVED' ? '' : ` (${enumLabel(payment.remittanceStatus).toLowerCase()})`}
525
+ </span>
526
+ <span className="tabular-nums">
527
+ {payment.remittanceDirection === 'REFUND' ? '-' : ''}
528
+ {formatMaybeMoney(payment.value)}
529
+ </span>
530
+ </li>
531
+ ))}
532
+ </ul>
533
+ )}
534
+ </div>
535
+ {due && onRecord && <RecordPaymentForm key={invoice.urn} invoice={invoice} onRecord={onRecord} text={text} />}
536
+ </div>
537
+ </CrmCard>
538
+ );
539
+ }
@@ -0,0 +1,95 @@
1
+ import { cn } from 'cn';
2
+ import { X } from 'lucide-react';
3
+ import { useCallback, useSyncExternalStore, type ReactNode } from 'react';
4
+ import { withText, type CrmText } from './text.ts';
5
+ import { Button } from './ui/button.tsx';
6
+ import { Sheet, SheetContent, SheetTitle } from './ui/sheet.tsx';
7
+
8
+ /** Whether a media query matches, following changes. True where there is no `matchMedia`, such as on the server. */
9
+ export function useMediaQuery(query: string): boolean {
10
+ const subscribe = useCallback(
11
+ (onChange: () => void) => {
12
+ if (typeof matchMedia !== 'function') return () => undefined;
13
+ const list = matchMedia(query);
14
+ list.addEventListener('change', onChange);
15
+ return () => list.removeEventListener('change', onChange);
16
+ },
17
+ [query],
18
+ );
19
+ const matches = () => typeof matchMedia !== 'function' || matchMedia(query).matches;
20
+ return useSyncExternalStore(subscribe, matches, () => true);
21
+ }
22
+
23
+ /** The id of a record's card or row, so closing its panel can put focus back on it. */
24
+ export const recordItemId = (urn: string) => `crm-item-${urn}`;
25
+
26
+ /**
27
+ * 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
+ * wide screens, a sheet from the right on narrow ones. Closing puts focus back on the record's card or row.
29
+ */
30
+ export function SidePanelLayout({
31
+ open,
32
+ title,
33
+ onClose,
34
+ children,
35
+ panel,
36
+ text,
37
+ }: {
38
+ /** The URN of the open record, if any. */
39
+ open: string | undefined;
40
+ /** What the panel holds, for its close button and the sheet's name. */
41
+ title: string;
42
+ onClose: () => void;
43
+ children: ReactNode;
44
+ panel: ReactNode;
45
+ text?: Partial<CrmText> | undefined;
46
+ }) {
47
+ const words = withText(text);
48
+ const wide = useMediaQuery('(min-width: 64rem)');
49
+ const close = () => {
50
+ onClose();
51
+ if (open) requestAnimationFrame(() => document.getElementById(recordItemId(open))?.focus());
52
+ };
53
+ 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>
63
+ );
64
+ return (
65
+ <>
66
+ <div
67
+ className={cn(
68
+ 'grid grid-cols-1 items-start gap-4',
69
+ open && wide && 'grid-cols-[minmax(0,1fr)_minmax(22rem,28rem)]',
70
+ )}
71
+ >
72
+ <div className="min-w-0">{children}</div>
73
+ {open && wide && (
74
+ <aside aria-label={title} className="sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto p-px">
75
+ {content}
76
+ </aside>
77
+ )}
78
+ </div>
79
+ {!wide && (
80
+ <Sheet open={open !== undefined} onOpenChange={(isOpen) => !isOpen && close()}>
81
+ <SheetContent
82
+ side="right"
83
+ showCloseButton={false}
84
+ aria-describedby={undefined}
85
+ className="w-full overflow-y-auto p-4 sm:max-w-md"
86
+ onCloseAutoFocus={(event) => event.preventDefault()}
87
+ >
88
+ <SheetTitle className="sr-only">{title}</SheetTitle>
89
+ {content}
90
+ </SheetContent>
91
+ </Sheet>
92
+ )}
93
+ </>
94
+ );
95
+ }
@@ -0,0 +1,53 @@
1
+ import { parseTimestamp } from '@baack-software/baack-ts-tasks';
2
+ import { formatMoney, totalsToMoney, type MoneyTotals } from '../money.ts';
3
+ import type { Money } from '../types.ts';
4
+
5
+ /**
6
+ * Names for the companies and people records point at. The CRM records hold references only; the host knows the
7
+ * names (from the identity and company reads it already makes).
8
+ */
9
+ export interface CrmNames {
10
+ company?: (urn: string) => string | undefined;
11
+ person?: (urn: string) => string | undefined;
12
+ }
13
+
14
+ export const companyNameOf = (names: CrmNames | undefined, urn: string | undefined) =>
15
+ urn ? names?.company?.(urn) : undefined;
16
+
17
+ export const personNameOf = (names: CrmNames | undefined, urn: string | undefined) =>
18
+ urn ? names?.person?.(urn) : undefined;
19
+
20
+ /**
21
+ * Totals in each currency, joined with "and", such as "GBP 1,250.00 and EUR 300.00" written with symbols. An empty
22
+ * total reads as zero in `fallbackCurrency`.
23
+ */
24
+ export function formatTotals(totals: MoneyTotals, fallbackCurrency = 'GBP', locale = 'en-GB'): string {
25
+ const money = totalsToMoney(totals);
26
+ if (money.length === 0) return formatMoney({ unitValue: 0, currencyCode: fallbackCurrency }, locale);
27
+ return money.map((value) => formatMoney(value, locale)).join(' and ');
28
+ }
29
+
30
+ /** Money, or a dash when there's none. */
31
+ export const formatMaybeMoney = (money: Money | null | undefined, locale = 'en-GB') =>
32
+ money ? formatMoney(money, locale) : '-';
33
+
34
+ /** A short date such as "24 Oct 2026", or a dash. */
35
+ export function formatDate(timestamp: string | null | undefined, locale = 'en-GB'): string {
36
+ const date = parseTimestamp(timestamp);
37
+ return date
38
+ ? date.toLocaleDateString(locale, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })
39
+ : '-';
40
+ }
41
+
42
+ /** A fraction as a percentage: 0.104 is "10.4%". */
43
+ export const formatPercent = (fraction: number, locale = 'en-GB') =>
44
+ new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1 }).format(fraction);
45
+
46
+ /** A change with its sign: "+10.4%" or "-0.8%". */
47
+ export const formatChange = (fraction: number, locale = 'en-GB') =>
48
+ new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 1, signDisplay: 'exceptZero' }).format(
49
+ fraction,
50
+ );
51
+
52
+ /** An enum value as words: `BANK_TRANSFER` is "Bank transfer". */
53
+ export const enumLabel = (value: string) => value.charAt(0) + value.slice(1).toLowerCase().replaceAll('_', ' ');