@baack-software/baack-ts-crm 0.0.5 → 0.0.7

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 (46) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/invoices.d.ts +10 -0
  6. package/dist/invoices.d.ts.map +1 -1
  7. package/dist/invoices.js +57 -9
  8. package/dist/invoices.js.map +1 -1
  9. package/dist/react/Charts.d.ts +29 -3
  10. package/dist/react/Charts.d.ts.map +1 -1
  11. package/dist/react/Charts.js +71 -16
  12. package/dist/react/Charts.js.map +1 -1
  13. package/dist/react/text.d.ts +11 -1
  14. package/dist/react/text.d.ts.map +1 -1
  15. package/dist/react/text.js +11 -1
  16. package/dist/react/text.js.map +1 -1
  17. package/dist/react/views.d.ts +3 -1
  18. package/dist/react/views.d.ts.map +1 -1
  19. package/dist/react/views.js +11 -6
  20. package/dist/react/views.js.map +1 -1
  21. package/dist/sales.d.ts +5 -0
  22. package/dist/sales.d.ts.map +1 -1
  23. package/dist/sales.js +2 -1
  24. package/dist/sales.js.map +1 -1
  25. package/dist/store.d.ts +11 -1
  26. package/dist/store.d.ts.map +1 -1
  27. package/dist/store.js +9 -4
  28. package/dist/store.js.map +1 -1
  29. package/dist/target.d.ts +9 -7
  30. package/dist/target.d.ts.map +1 -1
  31. package/dist/target.js +9 -20
  32. package/dist/target.js.map +1 -1
  33. package/dist/timeline.d.ts +29 -0
  34. package/dist/timeline.d.ts.map +1 -0
  35. package/dist/timeline.js +44 -0
  36. package/dist/timeline.js.map +1 -0
  37. package/package.json +1 -1
  38. package/src/index.ts +1 -0
  39. package/src/invoices.ts +59 -9
  40. package/src/react/Charts.tsx +227 -20
  41. package/src/react/text.ts +12 -1
  42. package/src/react/views.tsx +53 -9
  43. package/src/sales.ts +4 -0
  44. package/src/store.ts +20 -3
  45. package/src/target.ts +12 -23
  46. package/src/timeline.ts +72 -0
package/src/invoices.ts CHANGED
@@ -112,21 +112,71 @@ export function paymentsReceived(remittances: readonly Remittance[], range?: Dat
112
112
  return totals;
113
113
  }
114
114
 
115
+ /** Every UTC day a range touches, as its date (`2026-11-13`) and the instants it starts and ends. */
116
+ function utcDays(range: DateRange): { day: string; start: Date; end: Date }[] {
117
+ const days: { day: string; start: Date; end: Date }[] = [];
118
+ const first = new Date(Date.UTC(range.start.getUTCFullYear(), range.start.getUTCMonth(), range.start.getUTCDate()));
119
+ for (let start = first; start < range.end; start = new Date(start.getTime() + 86_400_000)) {
120
+ days.push({ day: start.toISOString().slice(0, 10), start, end: new Date(start.getTime() + 86_400_000) });
121
+ }
122
+ return days;
123
+ }
124
+
115
125
  /** Payments received per UTC day in a range, every day included, for a chart. */
116
126
  export function paymentsByDay(
117
127
  remittances: readonly Remittance[],
118
128
  range: DateRange,
119
129
  ): { day: string; totals: MoneyTotals }[] {
120
- const days: { day: string; totals: MoneyTotals }[] = [];
121
- const start = new Date(Date.UTC(range.start.getUTCFullYear(), range.start.getUTCMonth(), range.start.getUTCDate()));
122
- for (let day = start; day < range.end; day = new Date(day.getTime() + 86_400_000)) {
123
- const next = new Date(day.getTime() + 86_400_000);
124
- days.push({
125
- day: day.toISOString().slice(0, 10),
126
- totals: paymentsReceived(remittances, { start: day, end: next }),
127
- });
130
+ return utcDays(range).map(({ day, start, end }) => ({ day, totals: paymentsReceived(remittances, { start, end }) }));
131
+ }
132
+
133
+ /** Statuses of an invoice that was sent, whether or not it has been paid since. */
134
+ const SENT: readonly InvoiceStatus[] = [...AWAITING_PAYMENT, 'PAID', 'REFUNDED'];
135
+
136
+ /**
137
+ * What was overdue at the end of each UTC day in a range, per currency: sent invoices past their due date by then,
138
+ * less what had been paid on them by then. Today's runs to `now`, so it matches `overdueTotals`. Refunds aren't taken
139
+ * off what was paid: money paid back doesn't make an invoice owed again. An invoice without remittances is taken as
140
+ * the API gives it: paid in full when its `fullyPaidTimestamp` had passed, else its `paid` so far.
141
+ */
142
+ export function overdueByDay(
143
+ invoices: readonly Invoice[],
144
+ remittances: readonly Remittance[],
145
+ range: DateRange,
146
+ now = new Date(),
147
+ ): { day: string; totals: MoneyTotals }[] {
148
+ const payments = new Map<string, { at: number; minor: number }[]>();
149
+ for (const remittance of remittances) {
150
+ if (!counts(remittance) || remittance.remittanceDirection === 'REFUND') continue;
151
+ const at = parseTimestamp(remittance.receivedTimestamp)?.getTime();
152
+ if (at === undefined) continue;
153
+ const urn = remittance.paymentInvoice.urn;
154
+ payments.set(urn, [...(payments.get(urn) ?? []), { at, minor: remittance.value.unitValue }]);
128
155
  }
129
- return days;
156
+ const sent = invoices
157
+ .filter((invoice) => SENT.includes(invoice.status))
158
+ .map((invoice) => ({
159
+ invoice,
160
+ due: parseTimestamp(invoice.dueTimestamp)?.getTime(),
161
+ total: minorOf(invoice.total),
162
+ fullyPaid: parseTimestamp(invoice.fullyPaidTimestamp)?.getTime(),
163
+ paid: payments.get(invoice.urn),
164
+ }));
165
+ const paidBy = (owed: (typeof sent)[number], cut: number): number => {
166
+ if (owed.paid) return owed.paid.filter((payment) => payment.at < cut).reduce((sum, { minor }) => sum + minor, 0);
167
+ if (owed.fullyPaid !== undefined) return owed.fullyPaid < cut ? owed.total : 0;
168
+ return AWAITING_PAYMENT.includes(owed.invoice.status) ? minorOf(owed.invoice.paid) : owed.total;
169
+ };
170
+ return utcDays(range).map(({ day, end }) => {
171
+ const cut = Math.min(end.getTime(), now.getTime());
172
+ let totals: MoneyTotals = {};
173
+ for (const owed of sent) {
174
+ if (owed.due === undefined || owed.due >= cut) continue;
175
+ const left = owed.total - paidBy(owed, cut);
176
+ if (left > 0) totals = addMoney(totals, fromMinor(left, owed.invoice.currencyCode));
177
+ }
178
+ return { day, totals };
179
+ });
130
180
  }
131
181
 
132
182
  /** An invoice's payment fields as they follow from its remittances. */
@@ -1,10 +1,20 @@
1
1
  import { useId } from 'react';
2
- import { Area, AreaChart, Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts';
2
+ import { Area, Bar, BarChart, CartesianGrid, ComposedChart, Line, XAxis, YAxis } from 'recharts';
3
3
  import { SOURCE_LABELS, type SourceCount } from '../leads.ts';
4
+ import type { LeadSource } from '../types.ts';
4
5
  import { formatMoney, fractionDigits, fromMinor, type MoneyTotals } from '../money.ts';
6
+ import type { Timeline } from '../timeline.ts';
5
7
  import { CrmCard } from './parts.tsx';
6
8
  import { withText, type CrmText } from './text.ts';
7
- import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from './ui/chart.tsx';
9
+ import {
10
+ ChartContainer,
11
+ ChartLegend,
12
+ ChartLegendContent,
13
+ ChartTooltip,
14
+ ChartTooltipContent,
15
+ type ChartConfig,
16
+ } from './ui/chart.tsx';
17
+ import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs.tsx';
8
18
 
9
19
  /*
10
20
  * Charts as the Baack console draws them: shadcn's chart wrapper on Recharts, coloured by the theme's chart tokens.
@@ -14,13 +24,30 @@ import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } f
14
24
  const formatDay = (day: string) =>
15
25
  new Date(`${day}T00:00:00Z`).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });
16
26
 
17
- /** Payments received each day, as an area like the console's usage chart. */
27
+ /** A currency's amounts in major units (pounds, not pence) for charts: exact, and short for an axis. */
28
+ function currencyScale(currency: string) {
29
+ const scale = 10 ** fractionDigits(currency);
30
+ return {
31
+ scale,
32
+ money: (value: number) => formatMoney(fromMinor(Math.round(value * scale), currency), 'en-GB'),
33
+ short: (value: number) =>
34
+ new Intl.NumberFormat('en-GB', { style: 'currency', currency, notation: 'compact' }).format(value),
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Revenue over the period as it adds up (payments received less refunds), with what customers owed past its due date
40
+ * at the end of each day when `overdue` is given. Both are amounts at the end of a day, so they share one axis.
41
+ */
18
42
  export function RevenueChart({
19
43
  days,
44
+ overdue,
20
45
  currencyCode,
21
46
  text,
22
47
  }: {
23
48
  days: { day: string; totals: MoneyTotals }[];
49
+ /** What was overdue at the end of each day (see `overdueByDay`). */
50
+ overdue?: { day: string; totals: MoneyTotals }[] | undefined;
24
51
  /** The currency charted; others aren't added in. */
25
52
  currencyCode: string | undefined;
26
53
  text?: Partial<CrmText> | undefined;
@@ -28,17 +55,28 @@ export function RevenueChart({
28
55
  const words = withText(text);
29
56
  const id = useId().replace(/:/g, '');
30
57
  const currency = currencyCode ?? 'GBP';
31
- const scale = 10 ** fractionDigits(currency);
32
- const points = days.map(({ day, totals }) => ({ day, revenue: (totals[currency] ?? 0) / scale }));
33
- const config = { revenue: { label: words.revenue, color: 'var(--chart-1)' } } satisfies ChartConfig;
34
- const money = (value: number) => formatMoney(fromMinor(Math.round(value * scale), currency), 'en-GB');
35
- const short = (value: number) =>
36
- new Intl.NumberFormat('en-GB', { style: 'currency', currency, notation: 'compact' }).format(value);
58
+ const { scale, money, short } = currencyScale(currency);
59
+ const overdueOn = new Map(overdue?.map(({ day, totals }) => [day, (totals[currency] ?? 0) / scale]));
60
+ let soFar = 0;
61
+ const points = days.map(({ day, totals }) => {
62
+ const received = (totals[currency] ?? 0) / scale;
63
+ soFar += received;
64
+ return { day, received, revenue: soFar, overdue: overdueOn.get(day) ?? 0 };
65
+ });
66
+ const config = {
67
+ revenue: { label: words.revenueSoFar, color: 'var(--chart-1)' },
68
+ ...(overdue ? { overdue: { label: words.overdue, color: 'var(--chart-4)' } } : {}),
69
+ } satisfies ChartConfig;
70
+ const label = (key: string) => config[key as keyof typeof config]?.label ?? key;
37
71
 
38
72
  return (
39
- <CrmCard title={words.revenueOverTime} description={words.revenueHint} text={text}>
73
+ <CrmCard
74
+ title={words.revenueOverTime}
75
+ description={overdue ? words.revenueOverTimeHint : words.revenueSoFarHint}
76
+ text={text}
77
+ >
40
78
  <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
41
- <AreaChart data={points} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
79
+ <ComposedChart data={points} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
42
80
  <defs>
43
81
  <linearGradient id={`${id}-revenue`} x1="0" y1="0" x2="0" y2="1">
44
82
  <stop offset="5%" stopColor="var(--color-revenue)" stopOpacity={0.8} />
@@ -60,19 +98,42 @@ export function RevenueChart({
60
98
  content={
61
99
  <ChartTooltipContent
62
100
  labelFormatter={(value) => formatDay(String(value))}
63
- formatter={(value) => money(Number(value))}
64
- indicator="dot"
101
+ formatter={(value, name) => (
102
+ <span className="flex w-full items-center justify-between gap-4">
103
+ <span className="flex items-center gap-1.5 text-muted-foreground">
104
+ <span
105
+ aria-hidden="true"
106
+ className="size-2.5 shrink-0 rounded-[2px]"
107
+ style={{ background: `var(--color-${String(name)})` }}
108
+ />
109
+ {label(String(name))}
110
+ </span>
111
+ <span className="font-mono font-medium text-foreground tabular-nums">{money(Number(value))}</span>
112
+ </span>
113
+ )}
65
114
  />
66
115
  }
67
116
  />
117
+ {overdue && <ChartLegend content={<ChartLegendContent />} />}
68
118
  <Area
69
119
  dataKey="revenue"
70
120
  type="monotone"
71
121
  fill={`url(#${id}-revenue)`}
72
122
  stroke="var(--color-revenue)"
123
+ strokeWidth={2}
73
124
  isAnimationActive={false}
74
125
  />
75
- </AreaChart>
126
+ {overdue && (
127
+ <Line
128
+ dataKey="overdue"
129
+ type="monotone"
130
+ stroke="var(--color-overdue)"
131
+ strokeWidth={2}
132
+ dot={false}
133
+ isAnimationActive={false}
134
+ />
135
+ )}
136
+ </ComposedChart>
76
137
  </ChartContainer>
77
138
  {/* Tables ignore sr-only's 1px height, so the wrapper hides it. */}
78
139
  <div className="sr-only">
@@ -81,16 +142,20 @@ export function RevenueChart({
81
142
  <thead>
82
143
  <tr>
83
144
  <th scope="col">{words.date}</th>
84
- <th scope="col">{words.revenue}</th>
145
+ <th scope="col">{words.revenueHint}</th>
146
+ <th scope="col">{words.revenueSoFar}</th>
147
+ {overdue && <th scope="col">{words.overdue}</th>}
85
148
  </tr>
86
149
  </thead>
87
150
  <tbody>
88
151
  {points
89
- .filter((point) => point.revenue !== 0)
152
+ .filter((point) => point.received !== 0 || point.overdue !== 0)
90
153
  .map((point) => (
91
154
  <tr key={point.day}>
92
155
  <th scope="row">{formatDay(point.day)}</th>
156
+ <td>{money(point.received)}</td>
93
157
  <td>{money(point.revenue)}</td>
158
+ {overdue && <td>{money(point.overdue)}</td>}
94
159
  </tr>
95
160
  ))}
96
161
  </tbody>
@@ -100,14 +165,30 @@ export function RevenueChart({
100
165
  );
101
166
  }
102
167
 
103
- /** How many leads came from each source, as a shadcn bar chart. */
168
+ /**
169
+ * Each source's bar color, fixed so a source keeps its color whatever else is shown. The first four take the theme's
170
+ * chart colors in an order checked (light and dark) to keep neighbors apart for color-blind readers; the rest share a
171
+ * neutral gray, as five colors can't separate eight sources. The bars are labeled, so color is never the only cue.
172
+ */
173
+ const SOURCE_COLORS: Readonly<Record<LeadSource, string>> = {
174
+ WEBSITE: 'var(--chart-1)',
175
+ REFERRAL: 'var(--chart-4)',
176
+ SOCIAL: 'var(--chart-2)',
177
+ EMAIL: 'var(--chart-5)',
178
+ CALL: 'var(--muted-foreground)',
179
+ ADS: 'var(--muted-foreground)',
180
+ EVENT: 'var(--muted-foreground)',
181
+ UNKNOWN: 'var(--muted-foreground)',
182
+ };
183
+
184
+ /** How many leads came from each source, as a shadcn bar chart, a color per source. */
104
185
  export function LeadsBySourceCard({ counts, text }: { counts: SourceCount[]; text?: Partial<CrmText> | undefined }) {
105
186
  const words = withText(text);
106
187
  const total = counts.reduce((sum, row) => sum + row.count, 0);
107
188
  const points = counts
108
189
  .filter((row) => row.count > 0)
109
- .map((row) => ({ source: SOURCE_LABELS[row.source], leads: row.count }));
110
- const config = { leads: { label: words.leads, color: 'var(--chart-2)' } } satisfies ChartConfig;
190
+ .map((row) => ({ source: SOURCE_LABELS[row.source], leads: row.count, fill: SOURCE_COLORS[row.source] }));
191
+ const config = { leads: { label: words.leads, color: 'var(--chart-1)' } } satisfies ChartConfig;
111
192
  return (
112
193
  <CrmCard title={words.leadsBySource} description={`${total} ${words.leads.toLowerCase()}`} text={text}>
113
194
  <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
@@ -116,7 +197,7 @@ export function LeadsBySourceCard({ counts, text }: { counts: SourceCount[]; tex
116
197
  <YAxis dataKey="source" type="category" tickLine={false} axisLine={false} width={72} />
117
198
  <XAxis type="number" dataKey="leads" allowDecimals={false} tickLine={false} axisLine={false} />
118
199
  <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dot" />} />
119
- <Bar dataKey="leads" fill="var(--color-leads)" radius={4} isAnimationActive={false} />
200
+ <Bar dataKey="leads" radius={4} isAnimationActive={false} />
120
201
  </BarChart>
121
202
  </ChartContainer>
122
203
  <div className="sr-only">
@@ -141,3 +222,129 @@ export function LeadsBySourceCard({ counts, text }: { counts: SourceCount[]; tex
141
222
  </CrmCard>
142
223
  );
143
224
  }
225
+
226
+ /**
227
+ * Records over a period as bars per day or week, by how many (volume) or what they're worth (value), one at a time
228
+ * on tabs so each has its own axis. Screen readers get both in a table.
229
+ */
230
+ export function TimelineCard({
231
+ title,
232
+ description,
233
+ timeline,
234
+ countLabel,
235
+ color,
236
+ fallbackCurrency,
237
+ text,
238
+ className,
239
+ }: {
240
+ title: string;
241
+ description?: string | undefined;
242
+ timeline: Timeline;
243
+ /** What's counted, such as "Leads". */
244
+ countLabel: string;
245
+ /** A theme chart token, such as `var(--chart-2)`. */
246
+ color: string;
247
+ /** The currency to show when the records have no value in any. */
248
+ fallbackCurrency?: string | undefined;
249
+ text?: Partial<CrmText> | undefined;
250
+ className?: string | undefined;
251
+ }) {
252
+ const words = withText(text);
253
+ const currency = timeline.currencyCode ?? fallbackCurrency ?? 'GBP';
254
+ const { scale, money, short } = currencyScale(currency);
255
+ const points = timeline.points.map(({ day, count, value }) => ({ day, count, value: (value[currency] ?? 0) / scale }));
256
+ const label = (day: string) => (timeline.step === 'week' ? `${words.weekOf} ${formatDay(day)}` : formatDay(day));
257
+ const measures = [
258
+ { key: 'count', name: words.volume, label: countLabel, format: String, axis: String },
259
+ { key: 'value', name: words.value, label: words.value, format: money, axis: short },
260
+ ] as const;
261
+
262
+ // The tabs sit in the card's header, beside its title, so the root wraps the card.
263
+ return (
264
+ <Tabs defaultValue="count" className={className}>
265
+ <CrmCard
266
+ title={title}
267
+ text={text}
268
+ className="flex-1"
269
+ {...(description ? { description } : {})}
270
+ action={
271
+ <TabsList aria-label={title}>
272
+ {measures.map((measure) => (
273
+ <TabsTrigger key={measure.key} value={measure.key}>
274
+ {measure.name}
275
+ </TabsTrigger>
276
+ ))}
277
+ </TabsList>
278
+ }
279
+ >
280
+ {measures.map((measure) => (
281
+ <TabsContent key={measure.key} value={measure.key}>
282
+ <ChartContainer
283
+ config={{ [measure.key]: { label: measure.label, color } } satisfies ChartConfig}
284
+ className="aspect-auto h-52 w-full"
285
+ aria-hidden="true"
286
+ >
287
+ <BarChart data={points} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
288
+ <CartesianGrid vertical={false} />
289
+ <XAxis
290
+ dataKey="day"
291
+ tickLine={false}
292
+ axisLine={false}
293
+ tickMargin={8}
294
+ minTickGap={24}
295
+ tickFormatter={formatDay}
296
+ />
297
+ <YAxis
298
+ tickLine={false}
299
+ axisLine={false}
300
+ width={measure.key === 'value' ? 56 : 32}
301
+ allowDecimals={false}
302
+ tickFormatter={(value: number) => measure.axis(value)}
303
+ />
304
+ <ChartTooltip
305
+ cursor={false}
306
+ content={
307
+ <ChartTooltipContent
308
+ labelFormatter={(value) => label(String(value))}
309
+ formatter={(value) => `${measure.label}: ${measure.format(Number(value))}`}
310
+ indicator="dot"
311
+ />
312
+ }
313
+ />
314
+ <Bar
315
+ dataKey={measure.key}
316
+ fill={`var(--color-${measure.key})`}
317
+ radius={[4, 4, 0, 0]}
318
+ isAnimationActive={false}
319
+ />
320
+ </BarChart>
321
+ </ChartContainer>
322
+ </TabsContent>
323
+ ))}
324
+ <div className="sr-only">
325
+ <table>
326
+ <caption>{title}</caption>
327
+ <thead>
328
+ <tr>
329
+ <th scope="col">{timeline.step === 'week' ? words.week : words.date}</th>
330
+ <th scope="col">{countLabel}</th>
331
+ <th scope="col">{words.value}</th>
332
+ </tr>
333
+ </thead>
334
+ <tbody>
335
+ {points
336
+ .filter((point) => point.count !== 0)
337
+ .map((point) => (
338
+ <tr key={point.day}>
339
+ <th scope="row">{label(point.day)}</th>
340
+ <td>{point.count}</td>
341
+ <td>{money(point.value)}</td>
342
+ </tr>
343
+ ))}
344
+ </tbody>
345
+ </table>
346
+ </div>
347
+ </CrmCard>
348
+ </Tabs>
349
+ );
350
+ }
package/src/react/text.ts CHANGED
@@ -18,11 +18,22 @@ export const CRM_TEXT = {
18
18
  revenue: 'Revenue',
19
19
  revenueHint: 'Payments received less refunds',
20
20
  revenueOverTime: 'Revenue over time',
21
+ revenueSoFar: 'Received less refunds, to date',
22
+ revenueSoFarHint: 'Payments received less refunds, adding up over the period',
23
+ revenueOverTimeHint:
24
+ 'Payments received less refunds, adding up over the period, and what customers owed past its due date each day',
21
25
  newLeads: 'New leads',
22
26
  target: 'Sales target',
23
- targetSummary: 'Payments received on deals against the value of leads and deals',
27
+ targetSummary: 'Payments received on deals against the value of deals open or won',
24
28
  targetReceived: 'received of',
25
29
  leadsBySource: 'Leads by source',
30
+ leadsOverTime: 'Leads over time',
31
+ leadsOverTimeHint: 'Leads created, and their target value',
32
+ dealsOverTime: 'New deals',
33
+ dealsOverTimeHint: 'Deals qualified in the period, open or won, which make up the target',
34
+ volume: 'Volume',
35
+ week: 'Week',
36
+ weekOf: 'Week of',
26
37
  pipeline: 'Sales pipeline',
27
38
  stage: 'Stage',
28
39
  workflow: 'Workflow',
@@ -6,7 +6,7 @@ import { periodRange, type DateRange, type ReportingPeriod } from '../period.ts'
6
6
  import { pipelineOf } from '../pipeline.ts';
7
7
  import { selectAccount, selectDashboard, selectSales, type CrmStore, type CrmStoreState } from '../store.ts';
8
8
  import type { CrmConcept, Deal, DealOutcome, Invoice, Lead, PipelineStage } from '../types.ts';
9
- import { LeadsBySourceCard, RevenueChart } from './Charts.tsx';
9
+ import { LeadsBySourceCard, RevenueChart, TimelineCard } from './Charts.tsx';
10
10
  import { MetricCards, PipelineCard, TargetCard } from './DashboardCards.tsx';
11
11
  import { DealFilters, DealsBoard } from './DealsBoard.tsx';
12
12
  import { DealDetail, LeadDetail, type ContactDetailsAccess } from './Details.tsx';
@@ -158,7 +158,9 @@ function NewButton({ panel, label, onClick }: { panel: string; label: string; on
158
158
 
159
159
  /**
160
160
  * The CRM dashboard for a period: `range`, else the one picked (the last 30 days to start with), with figures against
161
- * the period before, the target, leads by source, the pipeline, the host's tasks panel and the leads table.
161
+ * the period before, then from realised revenue back up the funnel: revenue over time with what's overdue, the target
162
+ * with the new deals that make it up, the pipeline, leads by source and over time beside the host's tasks panel, and
163
+ * the leads table. Cards in a row share its height.
162
164
  */
163
165
  export function CrmDashboard({
164
166
  store,
@@ -188,21 +190,58 @@ export function CrmDashboard({
188
190
  [state, period, ownKey, pipeline?.urn],
189
191
  );
190
192
  if (state.status === 'idle' || state.status === 'loading') return <Loading label={words.loading} />;
191
- const concepts: CrmConcept[] = ['leads', 'deals', 'pipelines', 'remittances'];
193
+ const concepts: CrmConcept[] = ['leads', 'deals', 'pipelines', 'invoices', 'remittances'];
194
+ const leadCharts = (
195
+ <>
196
+ {/* Where leads come from, and when they came. */}
197
+ <LeadsBySourceCard counts={dashboard.leadsBySource} text={text} />
198
+ <TimelineCard
199
+ title={words.leadsOverTime}
200
+ description={words.leadsOverTimeHint}
201
+ timeline={dashboard.leadsOverTime}
202
+ countLabel={words.leads}
203
+ color="var(--chart-2)"
204
+ fallbackCurrency={dashboard.revenue.currencyCode}
205
+ text={text}
206
+ />
207
+ </>
208
+ );
192
209
  return (
193
210
  <div className="grid gap-6">
194
211
  <Sample store={store} concepts={concepts} text={text} />
195
212
  <Problems state={state} concepts={concepts} text={words} />
196
213
  {!range && <PeriodSelect value={picked} onChange={setPicked} text={text} />}
197
214
  <MetricCards dashboard={dashboard} text={range ? text : periodText(picked, text)} />
198
- <RevenueChart days={dashboard.revenueByDay} currencyCode={dashboard.revenue.currencyCode} text={text} />
199
- <div className={tasks ? 'grid items-start gap-6 lg:grid-cols-3' : 'grid items-start gap-6 lg:grid-cols-2'}>
200
- {/* Where leads come from, then what deals have brought in against the target. */}
201
- <LeadsBySourceCard counts={dashboard.leadsBySource} text={text} />
215
+ <RevenueChart
216
+ days={dashboard.revenueByDay}
217
+ overdue={dashboard.overdueByDay}
218
+ currencyCode={dashboard.revenue.currencyCode}
219
+ text={text}
220
+ />
221
+ <div className="grid gap-6 lg:grid-cols-3">
222
+ {/* What deals have brought in against the target, then the new deals that make it up. */}
202
223
  <TargetCard target={dashboard.target} text={text} />
203
- {tasks ?? null}
224
+ <TimelineCard
225
+ title={words.dealsOverTime}
226
+ description={words.dealsOverTimeHint}
227
+ timeline={dashboard.dealsOverTime}
228
+ countLabel={words.deals}
229
+ color="var(--chart-3)"
230
+ fallbackCurrency={dashboard.revenue.currencyCode}
231
+ text={text}
232
+ className="lg:col-span-2"
233
+ />
204
234
  </div>
205
235
  <PipelineCard stages={dashboard.pipeline} text={text} />
236
+ {tasks ? (
237
+ // The tasks panel keeps its own height, so a long list doesn't stretch the charts beside it.
238
+ <div className="grid items-start gap-6 lg:grid-cols-3">
239
+ <div className="grid gap-6 lg:col-span-2 lg:grid-cols-2">{leadCharts}</div>
240
+ {tasks}
241
+ </div>
242
+ ) : (
243
+ <div className="grid gap-6 lg:grid-cols-2">{leadCharts}</div>
244
+ )}
206
245
  <LeadsTable leads={state.leads} names={names} onOpen={onOpenLead} text={text} />
207
246
  </div>
208
247
  );
@@ -544,7 +583,12 @@ export function CrmSalesView({
544
583
  <Problems state={state} concepts={concepts} text={words} />
545
584
  {!range && <PeriodSelect value={picked} onChange={setPicked} text={text} />}
546
585
  <SalesMetricCards summary={summary} text={range ? text : periodText(picked, text)} />
547
- <RevenueChart days={summary.byDay} currencyCode={summary.currencyCode} text={text} />
586
+ <RevenueChart
587
+ days={summary.byDay}
588
+ overdue={summary.overdueByDay}
589
+ currencyCode={summary.currencyCode}
590
+ text={text}
591
+ />
548
592
  <div className="grid items-start gap-6 lg:grid-cols-2">
549
593
  <OutstandingByAgeCard summary={summary} text={text} />
550
594
  <PaymentMethodsCard summary={summary} text={text} />
package/src/sales.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  isCostInvoice,
6
6
  outstandingByAge,
7
7
  outstandingTotals,
8
+ overdueByDay,
8
9
  overdueTotals,
9
10
  paymentsByDay,
10
11
  paymentsReceived,
@@ -46,6 +47,8 @@ export interface SalesSummary {
46
47
  /** Draft invoices now, whenever drafted: not yet sent, so not in the other figures. */
47
48
  drafts: { count: number; totals: MoneyTotals };
48
49
  byDay: { day: string; totals: MoneyTotals }[];
50
+ /** What was overdue at the end of each day of the period (see `overdueByDay`). */
51
+ overdueByDay: { day: string; totals: MoneyTotals }[];
49
52
  byAge: { bucket: AgeBucket; totals: MoneyTotals }[];
50
53
  byMethod: { method: RemittanceMethod; totals: MoneyTotals }[];
51
54
  /** Invoices the business pays, apart from the sales figures above. */
@@ -150,6 +153,7 @@ export function salesSummary(
150
153
  return { count: drafts.length, totals: sum(drafts, (invoice) => invoice.total) };
151
154
  })(),
152
155
  byDay: paymentsByDay(remittances, range),
156
+ overdueByDay: overdueByDay(invoices, remittances, range, now),
153
157
  byAge: outstandingByAge(invoices, now),
154
158
  byMethod: paymentsByMethod(remittances, range),
155
159
  costs: {
package/src/store.ts CHANGED
@@ -15,9 +15,10 @@ import { leadsBySource, type SourceCount } from './leads.ts';
15
15
  import { addMoney, type MoneyTotals } from './money.ts';
16
16
  import { inRange, periodChange, previousRange, type DateRange } from './period.ts';
17
17
  import { dealCompany, dealOutcome, defaultPipeline, pipelineByStage, type StageSummary } from './pipeline.ts';
18
- import { paymentsByDay, paymentsReceived } from './invoices.ts';
18
+ import { isCostInvoice, overdueByDay, paymentsByDay, paymentsReceived } from './invoices.ts';
19
19
  import { salesRemittances, salesSummary, type SalesSummary } from './sales.ts';
20
- import { salesTarget, type SalesTarget } from './target.ts';
20
+ import { countsTowardsTarget, salesTarget, type SalesTarget } from './target.ts';
21
+ import { timeline, type Timeline } from './timeline.ts';
21
22
  import {
22
23
  CRM_CONCEPTS,
23
24
  type ContactDetails,
@@ -423,9 +424,15 @@ export interface Dashboard {
423
424
  revenue: Compared<MoneyTotals> & { currencyCode: string | undefined };
424
425
  /** Payments received less refunds on each day of the period. */
425
426
  revenueByDay: { day: string; totals: MoneyTotals }[];
427
+ /** What customers owed past its due date at the end of each day of the period (see `overdueByDay`). */
428
+ overdueByDay: { day: string; totals: MoneyTotals }[];
426
429
  /** Leads created in each period. */
427
430
  newLeads: Compared<number>;
431
+ /** Leads created in the period, counted and valued per day or week. */
432
+ leadsOverTime: Timeline;
428
433
  target: SalesTarget;
434
+ /** Deals qualified in the period that count towards the target (not lost), counted and valued per day or week. */
435
+ dealsOverTime: Timeline;
429
436
  leadsBySource: SourceCount[];
430
437
  /** The first pipeline's stages. */
431
438
  pipeline: StageSummary[];
@@ -448,12 +455,14 @@ export function selectDashboard(
448
455
  own?: ReadonlySet<string>,
449
456
  /** The user's chosen pipeline, for the pipeline card (see `defaultPipeline`). */
450
457
  chosenPipeline?: string,
458
+ now = new Date(),
451
459
  ): Dashboard {
452
460
  const before = previousRange(range);
453
461
  const { leads, deals, pipelines } = state;
454
462
  const shownPipeline = defaultPipeline(pipelines, deals, chosenPipeline);
455
463
  // Revenue is what customers paid: payments the business made on its costs aren't counted.
456
464
  const remittances = salesRemittances(state, own);
465
+ const salesInvoices = state.invoices.filter((invoice) => !isCostInvoice(invoice, own));
457
466
 
458
467
  const firstWins = new Map<string, string>();
459
468
  let openValue: MoneyTotals = {};
@@ -502,11 +511,19 @@ export function selectDashboard(
502
511
  change: revenueCurrency ? periodChange(current[revenueCurrency] ?? 0, previous[revenueCurrency] ?? 0) : undefined,
503
512
  },
504
513
  revenueByDay: paymentsByDay(remittances, range),
514
+ overdueByDay: overdueByDay(salesInvoices, remittances, range, now),
505
515
  newLeads: compare(
506
516
  count(leads, (lead) => lead.createdTimestamp, range),
507
517
  count(leads, (lead) => lead.createdTimestamp, before),
508
518
  ),
509
- target: salesTarget(leads, deals, remittances),
519
+ leadsOverTime: timeline(leads, range, (lead) => lead.createdTimestamp, (lead) => lead.targetValue),
520
+ target: salesTarget(deals, remittances),
521
+ dealsOverTime: timeline(
522
+ deals.filter(countsTowardsTarget),
523
+ range,
524
+ (deal) => deal.createdTimestamp,
525
+ (deal) => deal.targetValue,
526
+ ),
510
527
  leadsBySource: leadsBySource(leads),
511
528
  pipeline: shownPipeline ? pipelineByStage(deals, shownPipeline) : [],
512
529
  };