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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +74 -2
  3. package/dist/account.d.ts +36 -0
  4. package/dist/account.d.ts.map +1 -0
  5. package/dist/account.js +48 -0
  6. package/dist/account.js.map +1 -0
  7. package/dist/backend.d.ts +104 -0
  8. package/dist/backend.d.ts.map +1 -0
  9. package/dist/backend.js +328 -0
  10. package/dist/backend.js.map +1 -0
  11. package/dist/crm-client.d.ts +164 -0
  12. package/dist/crm-client.d.ts.map +1 -0
  13. package/dist/crm-client.js +252 -0
  14. package/dist/crm-client.js.map +1 -0
  15. package/dist/deal-order.d.ts +42 -0
  16. package/dist/deal-order.d.ts.map +1 -0
  17. package/dist/deal-order.js +80 -0
  18. package/dist/deal-order.js.map +1 -0
  19. package/dist/errors.d.ts +21 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +33 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/index.d.ts +14 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +14 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/invoices.d.ts +53 -0
  28. package/dist/invoices.d.ts.map +1 -0
  29. package/dist/invoices.js +155 -0
  30. package/dist/invoices.js.map +1 -0
  31. package/dist/leads.d.ts +29 -0
  32. package/dist/leads.d.ts.map +1 -0
  33. package/dist/leads.js +56 -0
  34. package/dist/leads.js.map +1 -0
  35. package/dist/mock/index.d.ts +43 -0
  36. package/dist/mock/index.d.ts.map +1 -0
  37. package/dist/mock/index.js +303 -0
  38. package/dist/mock/index.js.map +1 -0
  39. package/dist/money.d.ts +29 -0
  40. package/dist/money.d.ts.map +1 -0
  41. package/dist/money.js +82 -0
  42. package/dist/money.js.map +1 -0
  43. package/dist/period.d.ts +30 -0
  44. package/dist/period.d.ts.map +1 -0
  45. package/dist/period.js +49 -0
  46. package/dist/period.js.map +1 -0
  47. package/dist/pipeline.d.ts +36 -0
  48. package/dist/pipeline.d.ts.map +1 -0
  49. package/dist/pipeline.js +58 -0
  50. package/dist/pipeline.js.map +1 -0
  51. package/dist/react/Charts.d.ts +19 -0
  52. package/dist/react/Charts.d.ts.map +1 -0
  53. package/dist/react/Charts.js +38 -0
  54. package/dist/react/Charts.js.map +1 -0
  55. package/dist/react/ChoiceCombobox.d.ts +36 -0
  56. package/dist/react/ChoiceCombobox.d.ts.map +1 -0
  57. package/dist/react/ChoiceCombobox.js +105 -0
  58. package/dist/react/ChoiceCombobox.js.map +1 -0
  59. package/dist/react/CompanyAccountView.d.ts +21 -0
  60. package/dist/react/CompanyAccountView.d.ts.map +1 -0
  61. package/dist/react/CompanyAccountView.js +27 -0
  62. package/dist/react/CompanyAccountView.js.map +1 -0
  63. package/dist/react/DashboardCards.d.ts +32 -0
  64. package/dist/react/DashboardCards.d.ts.map +1 -0
  65. package/dist/react/DashboardCards.js +38 -0
  66. package/dist/react/DashboardCards.js.map +1 -0
  67. package/dist/react/DealsBoard.d.ts +49 -0
  68. package/dist/react/DealsBoard.d.ts.map +1 -0
  69. package/dist/react/DealsBoard.js +82 -0
  70. package/dist/react/DealsBoard.js.map +1 -0
  71. package/dist/react/Details.d.ts +85 -0
  72. package/dist/react/Details.d.ts.map +1 -0
  73. package/dist/react/Details.js +268 -0
  74. package/dist/react/Details.js.map +1 -0
  75. package/dist/react/Forms.d.ts +190 -0
  76. package/dist/react/Forms.d.ts.map +1 -0
  77. package/dist/react/Forms.js +494 -0
  78. package/dist/react/Forms.js.map +1 -0
  79. package/dist/react/LeadsTable.d.ts +22 -0
  80. package/dist/react/LeadsTable.d.ts.map +1 -0
  81. package/dist/react/LeadsTable.js +79 -0
  82. package/dist/react/LeadsTable.js.map +1 -0
  83. package/dist/react/Sales.d.ts +68 -0
  84. package/dist/react/Sales.d.ts.map +1 -0
  85. package/dist/react/Sales.js +270 -0
  86. package/dist/react/Sales.js.map +1 -0
  87. package/dist/react/SidePanel.d.ts +31 -0
  88. package/dist/react/SidePanel.d.ts.map +1 -0
  89. package/dist/react/SidePanel.js +49 -0
  90. package/dist/react/SidePanel.js.map +1 -0
  91. package/dist/react/format.d.ts +28 -0
  92. package/dist/react/format.d.ts.map +1 -0
  93. package/dist/react/format.js +30 -0
  94. package/dist/react/format.js.map +1 -0
  95. package/dist/react/index.d.ts +15 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +15 -0
  98. package/dist/react/index.js.map +1 -0
  99. package/dist/react/parts.d.ts +55 -0
  100. package/dist/react/parts.d.ts.map +1 -0
  101. package/dist/react/parts.js +82 -0
  102. package/dist/react/parts.js.map +1 -0
  103. package/dist/react/pipeline-choice.d.ts +19 -0
  104. package/dist/react/pipeline-choice.d.ts.map +1 -0
  105. package/dist/react/pipeline-choice.js +39 -0
  106. package/dist/react/pipeline-choice.js.map +1 -0
  107. package/dist/react/text.d.ts +232 -0
  108. package/dist/react/text.d.ts.map +1 -0
  109. package/dist/react/text.js +229 -0
  110. package/dist/react/text.js.map +1 -0
  111. package/dist/react/ui/alert.d.ts +11 -0
  112. package/dist/react/ui/alert.d.ts.map +1 -0
  113. package/dist/react/ui/alert.js +29 -0
  114. package/dist/react/ui/alert.js.map +1 -0
  115. package/dist/react/ui/badge.d.ts +10 -0
  116. package/dist/react/ui/badge.d.ts.map +1 -0
  117. package/dist/react/ui/badge.js +26 -0
  118. package/dist/react/ui/badge.js.map +1 -0
  119. package/dist/react/ui/button.d.ts +11 -0
  120. package/dist/react/ui/button.d.ts.map +1 -0
  121. package/dist/react/ui/button.js +37 -0
  122. package/dist/react/ui/button.js.map +1 -0
  123. package/dist/react/ui/card.d.ts +12 -0
  124. package/dist/react/ui/card.d.ts.map +1 -0
  125. package/dist/react/ui/card.js +26 -0
  126. package/dist/react/ui/card.js.map +1 -0
  127. package/dist/react/ui/chart.d.ts +45 -0
  128. package/dist/react/ui/chart.d.ts.map +1 -0
  129. package/dist/react/ui/chart.js +116 -0
  130. package/dist/react/ui/chart.js.map +1 -0
  131. package/dist/react/ui/input.d.ts +4 -0
  132. package/dist/react/ui/input.d.ts.map +1 -0
  133. package/dist/react/ui/input.js +8 -0
  134. package/dist/react/ui/input.js.map +1 -0
  135. package/dist/react/ui/label.d.ts +5 -0
  136. package/dist/react/ui/label.d.ts.map +1 -0
  137. package/dist/react/ui/label.js +10 -0
  138. package/dist/react/ui/label.js.map +1 -0
  139. package/dist/react/ui/progress.d.ts +5 -0
  140. package/dist/react/ui/progress.d.ts.map +1 -0
  141. package/dist/react/ui/progress.js +10 -0
  142. package/dist/react/ui/progress.js.map +1 -0
  143. package/dist/react/ui/select.d.ts +16 -0
  144. package/dist/react/ui/select.d.ts.map +1 -0
  145. package/dist/react/ui/select.js +37 -0
  146. package/dist/react/ui/select.js.map +1 -0
  147. package/dist/react/ui/separator.d.ts +5 -0
  148. package/dist/react/ui/separator.d.ts.map +1 -0
  149. package/dist/react/ui/separator.js +10 -0
  150. package/dist/react/ui/separator.js.map +1 -0
  151. package/dist/react/ui/sheet.d.ts +15 -0
  152. package/dist/react/ui/sheet.d.ts.map +1 -0
  153. package/dist/react/ui/sheet.js +38 -0
  154. package/dist/react/ui/sheet.js.map +1 -0
  155. package/dist/react/ui/skeleton.d.ts +3 -0
  156. package/dist/react/ui/skeleton.d.ts.map +1 -0
  157. package/dist/react/ui/skeleton.js +7 -0
  158. package/dist/react/ui/skeleton.js.map +1 -0
  159. package/dist/react/ui/table.d.ts +11 -0
  160. package/dist/react/ui/table.d.ts.map +1 -0
  161. package/dist/react/ui/table.js +29 -0
  162. package/dist/react/ui/table.js.map +1 -0
  163. package/dist/react/ui/tabs.d.ts +12 -0
  164. package/dist/react/ui/tabs.d.ts.map +1 -0
  165. package/dist/react/ui/tabs.js +31 -0
  166. package/dist/react/ui/tabs.js.map +1 -0
  167. package/dist/react/views.d.ts +82 -0
  168. package/dist/react/views.d.ts.map +1 -0
  169. package/dist/react/views.js +241 -0
  170. package/dist/react/views.js.map +1 -0
  171. package/dist/sales.d.ts +82 -0
  172. package/dist/sales.d.ts.map +1 -0
  173. package/dist/sales.js +87 -0
  174. package/dist/sales.js.map +1 -0
  175. package/dist/store.d.ts +159 -0
  176. package/dist/store.d.ts.map +1 -0
  177. package/dist/store.js +305 -0
  178. package/dist/store.js.map +1 -0
  179. package/dist/target.d.ts +22 -0
  180. package/dist/target.d.ts.map +1 -0
  181. package/dist/target.js +40 -0
  182. package/dist/target.js.map +1 -0
  183. package/dist/types.d.ts +204 -0
  184. package/dist/types.d.ts.map +1 -0
  185. package/dist/types.js +2 -0
  186. package/dist/types.js.map +1 -0
  187. package/package.json +100 -4
  188. package/src/account.ts +79 -0
  189. package/src/backend.ts +501 -0
  190. package/src/crm-client.ts +393 -0
  191. package/src/deal-order.ts +116 -0
  192. package/src/errors.ts +34 -0
  193. package/src/index.ts +13 -0
  194. package/src/invoices.ts +177 -0
  195. package/src/leads.ts +78 -0
  196. package/src/mock/index.ts +398 -0
  197. package/src/money.ts +104 -0
  198. package/src/period.ts +71 -0
  199. package/src/pipeline.ts +82 -0
  200. package/src/react/Charts.tsx +143 -0
  201. package/src/react/ChoiceCombobox.tsx +227 -0
  202. package/src/react/CompanyAccountView.tsx +198 -0
  203. package/src/react/DashboardCards.tsx +171 -0
  204. package/src/react/DealsBoard.tsx +344 -0
  205. package/src/react/Details.tsx +870 -0
  206. package/src/react/Forms.tsx +1486 -0
  207. package/src/react/LeadsTable.tsx +234 -0
  208. package/src/react/Sales.tsx +827 -0
  209. package/src/react/SidePanel.tsx +104 -0
  210. package/src/react/format.ts +53 -0
  211. package/src/react/index.ts +14 -0
  212. package/src/react/parts.tsx +183 -0
  213. package/src/react/pipeline-choice.ts +54 -0
  214. package/src/react/text.ts +232 -0
  215. package/src/react/ui/README.md +6 -0
  216. package/src/react/ui/alert.tsx +75 -0
  217. package/src/react/ui/badge.tsx +48 -0
  218. package/src/react/ui/button.tsx +66 -0
  219. package/src/react/ui/card.tsx +102 -0
  220. package/src/react/ui/chart.tsx +304 -0
  221. package/src/react/ui/input.tsx +18 -0
  222. package/src/react/ui/label.tsx +23 -0
  223. package/src/react/ui/progress.tsx +30 -0
  224. package/src/react/ui/select.tsx +189 -0
  225. package/src/react/ui/separator.tsx +27 -0
  226. package/src/react/ui/sheet.tsx +145 -0
  227. package/src/react/ui/skeleton.tsx +13 -0
  228. package/src/react/ui/table.tsx +113 -0
  229. package/src/react/ui/tabs.tsx +89 -0
  230. package/src/react/views.tsx +633 -0
  231. package/src/sales.ts +167 -0
  232. package/src/store.ts +528 -0
  233. package/src/target.ts +54 -0
  234. package/src/types.ts +230 -0
@@ -0,0 +1,827 @@
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 { 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';
15
+ import { fractionDigits, fromMinor, formatMoney, minorOf, toDecimal, toMinor, type MoneyTotals } from '../money.ts';
16
+ import type { SalesSummary } from '../sales.ts';
17
+ import type { Invoice, InvoiceParty, InvoiceStatus, Remittance, RemittanceMethod } from '../types.ts';
18
+ import { ChoiceCombobox } from './ChoiceCombobox.tsx';
19
+ import { DetailList } from './Details.tsx';
20
+ import { Field, NewCompanyStep, NewContactStep, type CrmChoice } from './Forms.tsx';
21
+ import { MetricCard } from './DashboardCards.tsx';
22
+ import {
23
+ companyNameOf,
24
+ enumLabel,
25
+ formatDate,
26
+ formatMaybeMoney,
27
+ formatTotals,
28
+ personNameOf,
29
+ type CrmNames,
30
+ } from './format.ts';
31
+ import { CrmCard, InvoiceStatusBadge } from './parts.tsx';
32
+ import { recordItemId } from './SidePanel.tsx';
33
+ import { withText, type CrmText } from './text.ts';
34
+ import { Badge } from './ui/badge.tsx';
35
+ import { Button } from './ui/button.tsx';
36
+ import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from './ui/chart.tsx';
37
+ import { Input } from './ui/input.tsx';
38
+ import { Label } from './ui/label.tsx';
39
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select.tsx';
40
+ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table.tsx';
41
+
42
+ type Words = { text?: Partial<CrmText> | undefined };
43
+
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
+ */
48
+ export function SalesMetricCards({ summary, text }: { summary: SalesSummary } & Words) {
49
+ const words = withText(text);
50
+ const currency = summary.currencyCode;
51
+ return (
52
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
53
+ <MetricCard
54
+ label={words.invoiced}
55
+ value={formatTotals(summary.invoiced.current, currency)}
56
+ change={summary.invoiced.change}
57
+ hint={words.invoicedHint}
58
+ text={text}
59
+ />
60
+ <MetricCard
61
+ label={words.received}
62
+ value={formatTotals(summary.received.current, currency)}
63
+ change={summary.received.change}
64
+ hint={words.revenueHint}
65
+ text={text}
66
+ />
67
+ <MetricCard
68
+ label={words.outstanding}
69
+ value={formatTotals(summary.outstanding, currency)}
70
+ change={undefined}
71
+ hint={`${words.overdue}: ${formatTotals(summary.overdue, currency)}`}
72
+ text={{ ...text, noChange: words.outstandingHint }}
73
+ />
74
+ <MetricCard
75
+ label={words.salesTax}
76
+ value={formatTotals(summary.tax.current, currency)}
77
+ change={summary.tax.change}
78
+ hint={words.salesTaxHint}
79
+ text={text}
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
+ />
95
+ </div>
96
+ );
97
+ }
98
+
99
+ /** Totals in one currency as a number of whole units, for a chart axis. */
100
+ const units = (totals: MoneyTotals, currency: string) => (totals[currency] ?? 0) / 10 ** fractionDigits(currency);
101
+
102
+ function MoneyBars({
103
+ title,
104
+ description,
105
+ rows,
106
+ currencyCode,
107
+ color,
108
+ layout,
109
+ text,
110
+ }: {
111
+ title: string;
112
+ description?: string;
113
+ rows: { label: string; totals: MoneyTotals }[];
114
+ currencyCode: string | undefined;
115
+ color: string;
116
+ layout: 'horizontal' | 'vertical';
117
+ } & Words) {
118
+ const words = withText(text);
119
+ const currency = currencyCode ?? 'GBP';
120
+ const points = rows.map((row) => ({ label: row.label, amount: units(row.totals, currency) }));
121
+ const config = { amount: { label: words.amount, color } } satisfies ChartConfig;
122
+ const money = (value: number) => formatMoney(fromMinor(Math.round(value * 10 ** fractionDigits(currency)), currency));
123
+ const short = (value: number) =>
124
+ new Intl.NumberFormat('en-GB', { style: 'currency', currency, notation: 'compact' }).format(value);
125
+ const vertical = layout === 'vertical';
126
+ return (
127
+ <CrmCard title={title} {...(description ? { description } : {})} text={text}>
128
+ <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
129
+ <BarChart data={points} layout={layout} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
130
+ <CartesianGrid vertical={vertical} horizontal={!vertical} />
131
+ {vertical ? (
132
+ <>
133
+ <YAxis dataKey="label" type="category" tickLine={false} axisLine={false} width={104} />
134
+ <XAxis type="number" tickLine={false} axisLine={false} tickFormatter={short} />
135
+ </>
136
+ ) : (
137
+ <>
138
+ <XAxis dataKey="label" tickLine={false} axisLine={false} interval={0} tick={{ fontSize: 11 }} />
139
+ <YAxis tickLine={false} axisLine={false} width={56} tickFormatter={short} />
140
+ </>
141
+ )}
142
+ <ChartTooltip
143
+ cursor={false}
144
+ content={<ChartTooltipContent formatter={(value) => money(Number(value))} indicator="dot" />}
145
+ />
146
+ <Bar dataKey="amount" fill="var(--color-amount)" radius={4} isAnimationActive={false} />
147
+ </BarChart>
148
+ </ChartContainer>
149
+ <div className="sr-only">
150
+ <table>
151
+ <caption>{title}</caption>
152
+ <tbody>
153
+ {points.map((point) => (
154
+ <tr key={point.label}>
155
+ <th scope="row">{point.label}</th>
156
+ <td>{money(point.amount)}</td>
157
+ </tr>
158
+ ))}
159
+ </tbody>
160
+ </table>
161
+ </div>
162
+ </CrmCard>
163
+ );
164
+ }
165
+
166
+ /** What's still to pay, by how long it's been overdue. */
167
+ export function OutstandingByAgeCard({ summary, text }: { summary: SalesSummary } & Words) {
168
+ const words = withText(text);
169
+ return (
170
+ <MoneyBars
171
+ title={words.outstandingByAge}
172
+ description={formatTotals(summary.outstanding, summary.currencyCode)}
173
+ rows={summary.byAge.map((row) => ({
174
+ label: AGE_BUCKET_LABELS[row.bucket].replace(' overdue', ''),
175
+ totals: row.totals,
176
+ }))}
177
+ currencyCode={summary.currencyCode}
178
+ color="var(--chart-3)"
179
+ layout="horizontal"
180
+ text={text}
181
+ />
182
+ );
183
+ }
184
+
185
+ /** Money received in the period by payment method. */
186
+ export function PaymentMethodsCard({ summary, text }: { summary: SalesSummary } & Words) {
187
+ const words = withText(text);
188
+ return (
189
+ <MoneyBars
190
+ title={words.paymentMethods}
191
+ rows={summary.byMethod
192
+ .filter((row) => Object.values(row.totals).some((minor) => minor !== 0))
193
+ .map((row) => ({ label: enumLabel(row.method), totals: row.totals }))}
194
+ currencyCode={summary.currencyCode}
195
+ color="var(--chart-4)"
196
+ layout="vertical"
197
+ text={text}
198
+ />
199
+ );
200
+ }
201
+
202
+ const AWAITING = 'awaiting';
203
+ const OVERDUE = 'overdue';
204
+ const ALL = 'all';
205
+ type InvoiceFilter = typeof ALL | typeof AWAITING | typeof OVERDUE | InvoiceStatus;
206
+
207
+ /** An invoice's name for people: its first line, else the end of its URN. */
208
+ export const invoiceTitle = (invoice: Invoice) => invoice.lines?.[0]?.description ?? `Invoice ${invoice.urn.slice(-6)}`;
209
+
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))) ?? '-';
219
+
220
+ function invoicesCsv(invoices: readonly Invoice[], names?: CrmNames, own?: ReadonlySet<string>): string {
221
+ const cell = (value: string) => (/[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value);
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
+ ];
234
+ const rows = invoices.map((invoice) => [
235
+ invoiceTitle(invoice),
236
+ isCostInvoice(invoice, own) ? 'Cost' : 'Sale',
237
+ customerOf(invoice, names, own),
238
+ invoice.status,
239
+ invoice.issuedTimestamp ?? '',
240
+ invoice.dueTimestamp ?? '',
241
+ invoice.currencyCode,
242
+ toDecimal(minorOf(invoice.total), invoice.currencyCode),
243
+ toDecimal(minorOf(invoice.paid), invoice.currencyCode),
244
+ toDecimal(outstanding(invoice)?.unitValue ?? 0, invoice.currencyCode),
245
+ ]);
246
+ return [header, ...rows].map((row) => row.map(cell).join(',')).join('\n');
247
+ }
248
+
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
+ */
253
+ export function InvoicesTable({
254
+ invoices,
255
+ names,
256
+ own,
257
+ onOpen,
258
+ selected,
259
+ now = new Date(),
260
+ pageSize = 10,
261
+ text,
262
+ }: {
263
+ invoices: readonly Invoice[];
264
+ names?: CrmNames | undefined;
265
+ own?: ReadonlySet<string> | undefined;
266
+ onOpen?: ((invoice: Invoice) => void) | undefined;
267
+ /** The open invoice, highlighted. */
268
+ selected?: string | undefined;
269
+ now?: Date;
270
+ pageSize?: number;
271
+ } & Words) {
272
+ const words = withText(text);
273
+ const [query, setQuery] = useState('');
274
+ const [filter, setFilter] = useState<InvoiceFilter>(ALL);
275
+ const [kind, setKind] = useState<'all' | 'sales' | 'costs'>('all');
276
+ const [page, setPage] = useState(0);
277
+ const filtered = useMemo(() => {
278
+ const needle = query.trim().toLowerCase();
279
+ return invoices.filter((invoice) => {
280
+ if (kind !== 'all' && isCostInvoice(invoice, own) !== (kind === 'costs')) return false;
281
+ if (filter === AWAITING && !outstanding(invoice)) return false;
282
+ if (filter === OVERDUE && !isOverdueInvoice(invoice, now)) return false;
283
+ if (filter !== ALL && filter !== AWAITING && filter !== OVERDUE && invoice.status !== filter) return false;
284
+ return !needle || `${invoiceTitle(invoice)} ${customerOf(invoice, names, own)}`.toLowerCase().includes(needle);
285
+ });
286
+ }, [invoices, names, own, query, kind, filter, now]);
287
+ const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
288
+ const current = Math.min(page, pages - 1);
289
+ const shown = filtered.slice(current * pageSize, (current + 1) * pageSize);
290
+ const first = current * pageSize + 1;
291
+
292
+ return (
293
+ <CrmCard
294
+ title={words.invoices}
295
+ text={text}
296
+ action={
297
+ <Button
298
+ variant="outline"
299
+ size="sm"
300
+ onClick={() => {
301
+ const url = URL.createObjectURL(new Blob([invoicesCsv(filtered, names, own)], { type: 'text/csv' }));
302
+ const link = document.createElement('a');
303
+ link.href = url;
304
+ link.download = 'invoices.csv';
305
+ link.click();
306
+ URL.revokeObjectURL(url);
307
+ }}
308
+ >
309
+ <Download aria-hidden="true" />
310
+ {words.export}
311
+ </Button>
312
+ }
313
+ >
314
+ <div className="mb-3 flex flex-wrap items-center gap-2">
315
+ <div className="relative min-w-48 flex-1">
316
+ <Search
317
+ aria-hidden="true"
318
+ className="text-muted-foreground absolute top-1/2 left-2.5 size-4 -translate-y-1/2"
319
+ />
320
+ <Input
321
+ type="search"
322
+ aria-label={words.filterInvoices}
323
+ placeholder={words.filterInvoices}
324
+ value={query}
325
+ onChange={(event) => {
326
+ setQuery(event.target.value);
327
+ setPage(0);
328
+ }}
329
+ className="pl-8"
330
+ />
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>
348
+ <Select
349
+ value={filter}
350
+ onValueChange={(value) => {
351
+ setFilter(value as InvoiceFilter);
352
+ setPage(0);
353
+ }}
354
+ >
355
+ <SelectTrigger aria-label={words.status} className="w-44">
356
+ <SelectValue />
357
+ </SelectTrigger>
358
+ <SelectContent>
359
+ <SelectItem value={ALL}>{words.allInvoices}</SelectItem>
360
+ <SelectItem value={AWAITING}>{words.awaitingPayment}</SelectItem>
361
+ <SelectItem value={OVERDUE}>{words.overdue}</SelectItem>
362
+ {INVOICE_STATUSES.map((status) => (
363
+ <SelectItem key={status} value={status}>
364
+ {INVOICE_STATUS_LABELS[status]}
365
+ </SelectItem>
366
+ ))}
367
+ </SelectContent>
368
+ </Select>
369
+ </div>
370
+ <Table>
371
+ <caption className="sr-only">{words.invoices}</caption>
372
+ <TableHeader>
373
+ <TableRow>
374
+ <TableHead>{words.invoice}</TableHead>
375
+ <TableHead>{words.party}</TableHead>
376
+ <TableHead>{words.status}</TableHead>
377
+ <TableHead>{words.issued}</TableHead>
378
+ <TableHead>{words.due}</TableHead>
379
+ <TableHead className="text-right">{words.total}</TableHead>
380
+ <TableHead className="text-right">{words.outstanding}</TableHead>
381
+ </TableRow>
382
+ </TableHeader>
383
+ <TableBody>
384
+ {shown.length === 0 ? (
385
+ <TableRow>
386
+ <TableCell colSpan={7} className="text-muted-foreground py-6 text-center">
387
+ {words.noMatchingInvoices}
388
+ </TableCell>
389
+ </TableRow>
390
+ ) : (
391
+ shown.map((invoice) => (
392
+ <TableRow key={invoice.urn} data-state={selected === invoice.urn ? 'selected' : undefined}>
393
+ <TableCell className="max-w-64 whitespace-normal">
394
+ {onOpen ? (
395
+ <button
396
+ type="button"
397
+ id={recordItemId(invoice.urn)}
398
+ aria-current={selected === invoice.urn ? 'true' : undefined}
399
+ className="text-left font-medium hover:underline"
400
+ onClick={() => onOpen(invoice)}
401
+ >
402
+ {invoiceTitle(invoice)}
403
+ </button>
404
+ ) : (
405
+ <span className="font-medium">{invoiceTitle(invoice)}</span>
406
+ )}
407
+ </TableCell>
408
+ <TableCell>{customerOf(invoice, names, own)}</TableCell>
409
+ <TableCell>
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>
414
+ </TableCell>
415
+ <TableCell>{formatDate(invoice.issuedTimestamp)}</TableCell>
416
+ <TableCell>{formatDate(invoice.dueTimestamp)}</TableCell>
417
+ <TableCell className="text-right tabular-nums">
418
+ {formatMaybeMoney(invoice.total)}
419
+ </TableCell>
420
+ <TableCell className="text-right tabular-nums">{formatMaybeMoney(outstanding(invoice))}</TableCell>
421
+ </TableRow>
422
+ ))
423
+ )}
424
+ </TableBody>
425
+ </Table>
426
+ <div className="mt-3 flex items-center justify-between gap-2 text-sm">
427
+ <p className="text-muted-foreground" aria-live="polite">
428
+ {filtered.length === 0
429
+ ? `0 ${words.invoices.toLowerCase()}`
430
+ : `${first} - ${first + shown.length - 1} ${words.of} ${filtered.length} ${words.invoices.toLowerCase()}`}
431
+ </p>
432
+ <div className="flex gap-2">
433
+ <Button variant="outline" size="sm" disabled={current === 0} onClick={() => setPage(current - 1)}>
434
+ {words.previous}
435
+ </Button>
436
+ <Button variant="outline" size="sm" disabled={current >= pages - 1} onClick={() => setPage(current + 1)}>
437
+ {words.next}
438
+ </Button>
439
+ </div>
440
+ </div>
441
+ </CrmCard>
442
+ );
443
+ }
444
+
445
+ const METHODS: RemittanceMethod[] = ['BANK_TRANSFER', 'CARD_PAYMENT', 'DIRECT_DEBIT', 'CASH', 'E_WALLET', 'OTHER'];
446
+
447
+ /** Records a payment against an invoice: the amount (what's outstanding to start with), method and reference. */
448
+ export function RecordPaymentForm({
449
+ invoice,
450
+ onRecord,
451
+ now = () => new Date(),
452
+ text,
453
+ }: {
454
+ invoice: Invoice;
455
+ onRecord: (input: RemittanceInput) => Promise<unknown>;
456
+ now?: () => Date;
457
+ } & Words) {
458
+ const words = withText(text);
459
+ const id = useId();
460
+ const due = outstanding(invoice);
461
+ const [amount, setAmount] = useState(due ? toDecimal(due.unitValue, due.currencyCode) : '');
462
+ const [method, setMethod] = useState<RemittanceMethod>('BANK_TRANSFER');
463
+ const [reference, setReference] = useState('');
464
+ const [error, setError] = useState<string>();
465
+ const [status, setStatus] = useState<'idle' | 'saving' | 'saved'>('idle');
466
+
467
+ const submit = async (event: FormEvent) => {
468
+ event.preventDefault();
469
+ let minor = 0;
470
+ try {
471
+ minor = toMinor(amount, invoice.currencyCode);
472
+ } catch {
473
+ minor = 0;
474
+ }
475
+ if (minor <= 0) {
476
+ setError(words.invalidAmount);
477
+ return;
478
+ }
479
+ setError(undefined);
480
+ setStatus('saving');
481
+ try {
482
+ await onRecord({
483
+ paymentInvoice: { urn: invoice.urn },
484
+ remittanceDirection: 'PAYMENT',
485
+ remittanceStatus: 'RECEIVED',
486
+ remittanceMethod: method,
487
+ value: { unitValue: minor, currencyCode: invoice.currencyCode },
488
+ reference: reference.trim() || null,
489
+ remittingCompany: invoice.remitter?.company ?? null,
490
+ remittingIdentity: invoice.remitter?.identity ?? null,
491
+ receivedTimestamp: toTimestamp(now()),
492
+ });
493
+ setStatus('saved');
494
+ setReference('');
495
+ } catch (failure) {
496
+ setStatus('idle');
497
+ setError(failure instanceof Error ? failure.message : String(failure));
498
+ }
499
+ };
500
+
501
+ return (
502
+ <form onSubmit={(event) => void submit(event)} className="grid gap-3" aria-labelledby={`${id}-title`}>
503
+ <h3 id={`${id}-title`} className="text-sm font-semibold">
504
+ {words.recordPayment}
505
+ </h3>
506
+ <div className="grid gap-1.5">
507
+ <Label htmlFor={`${id}-amount`}>
508
+ {words.amount} ({invoice.currencyCode})
509
+ </Label>
510
+ <Input
511
+ id={`${id}-amount`}
512
+ inputMode="decimal"
513
+ value={amount}
514
+ onChange={(event) => setAmount(event.target.value)}
515
+ aria-invalid={error ? true : undefined}
516
+ aria-describedby={error ? `${id}-error` : undefined}
517
+ />
518
+ </div>
519
+ <div className="grid gap-1.5">
520
+ <Label htmlFor={`${id}-method`}>{words.method}</Label>
521
+ <Select value={method} onValueChange={(value) => setMethod(value as RemittanceMethod)}>
522
+ <SelectTrigger id={`${id}-method`} className="w-full">
523
+ <SelectValue />
524
+ </SelectTrigger>
525
+ <SelectContent>
526
+ {METHODS.map((value) => (
527
+ <SelectItem key={value} value={value}>
528
+ {enumLabel(value)}
529
+ </SelectItem>
530
+ ))}
531
+ </SelectContent>
532
+ </Select>
533
+ </div>
534
+ <div className="grid gap-1.5">
535
+ <Label htmlFor={`${id}-reference`}>{words.reference}</Label>
536
+ <Input id={`${id}-reference`} value={reference} onChange={(event) => setReference(event.target.value)} />
537
+ </div>
538
+ {error && (
539
+ <p id={`${id}-error`} role="alert" className="text-destructive text-sm">
540
+ {error}
541
+ </p>
542
+ )}
543
+ <div className="flex items-center gap-3">
544
+ <Button type="submit" disabled={status === 'saving'}>
545
+ {status === 'saving' ? words.recording : words.recordPayment}
546
+ </Button>
547
+ <p aria-live="polite" className="text-muted-foreground text-sm">
548
+ {status === 'saved' ? words.paymentRecorded : ''}
549
+ </p>
550
+ </div>
551
+ </form>
552
+ );
553
+ }
554
+
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
+ */
731
+ export function InvoiceDetail({
732
+ invoice,
733
+ payments,
734
+ names,
735
+ companies = [],
736
+ people = [],
737
+ onChange,
738
+ saving,
739
+ onRecord,
740
+ now = new Date(),
741
+ text,
742
+ }: {
743
+ invoice: Invoice;
744
+ /** Remittances against this invoice. */
745
+ payments: readonly Remittance[];
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;
754
+ onRecord?: ((input: RemittanceInput) => Promise<unknown>) | undefined;
755
+ now?: Date;
756
+ } & Words) {
757
+ const words = withText(text);
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
+ ];
767
+ return (
768
+ <CrmCard title={invoiceTitle(invoice)} text={text}>
769
+ <div className="grid gap-5">
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} />
800
+ <div className="grid gap-2">
801
+ <h3 className="text-sm font-semibold">{words.payments}</h3>
802
+ {payments.length === 0 ? (
803
+ <p className="text-muted-foreground text-sm">{words.noPayments}</p>
804
+ ) : (
805
+ <ul className="grid gap-1.5 text-sm">
806
+ {payments.map((payment) => (
807
+ <li key={payment.urn} className="flex justify-between gap-2">
808
+ <span>
809
+ {formatDate(payment.receivedTimestamp)}, {enumLabel(payment.remittanceMethod).toLowerCase()}
810
+ {payment.remittanceStatus === 'RECEIVED'
811
+ ? ''
812
+ : ` (${enumLabel(payment.remittanceStatus).toLowerCase()})`}
813
+ </span>
814
+ <span className="tabular-nums">
815
+ {payment.remittanceDirection === 'REFUND' ? '-' : ''}
816
+ {formatMaybeMoney(payment.value)}
817
+ </span>
818
+ </li>
819
+ ))}
820
+ </ul>
821
+ )}
822
+ </div>
823
+ {due && onRecord && <RecordPaymentForm key={invoice.urn} invoice={invoice} onRecord={onRecord} text={text} />}
824
+ </div>
825
+ </CrmCard>
826
+ );
827
+ }