@baack-software/baack-ts-crm 0.0.6 → 0.0.8

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.
@@ -1,11 +1,19 @@
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';
5
6
  import type { Timeline } from '../timeline.ts';
6
7
  import { CrmCard } from './parts.tsx';
7
8
  import { withText, type CrmText } from './text.ts';
8
- 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';
9
17
  import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs.tsx';
10
18
 
11
19
  /*
@@ -27,13 +35,19 @@ function currencyScale(currency: string) {
27
35
  };
28
36
  }
29
37
 
30
- /** Payments received each day, as an area like the console's usage chart. */
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
+ */
31
42
  export function RevenueChart({
32
43
  days,
44
+ overdue,
33
45
  currencyCode,
34
46
  text,
35
47
  }: {
36
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;
37
51
  /** The currency charted; others aren't added in. */
38
52
  currencyCode: string | undefined;
39
53
  text?: Partial<CrmText> | undefined;
@@ -42,13 +56,27 @@ export function RevenueChart({
42
56
  const id = useId().replace(/:/g, '');
43
57
  const currency = currencyCode ?? 'GBP';
44
58
  const { scale, money, short } = currencyScale(currency);
45
- const points = days.map(({ day, totals }) => ({ day, revenue: (totals[currency] ?? 0) / scale }));
46
- const config = { revenue: { label: words.revenue, color: 'var(--chart-1)' } } satisfies ChartConfig;
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;
47
71
 
48
72
  return (
49
- <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
+ >
50
78
  <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
51
- <AreaChart data={points} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
79
+ <ComposedChart data={points} accessibilityLayer={false} margin={{ left: 0, right: 8 }}>
52
80
  <defs>
53
81
  <linearGradient id={`${id}-revenue`} x1="0" y1="0" x2="0" y2="1">
54
82
  <stop offset="5%" stopColor="var(--color-revenue)" stopOpacity={0.8} />
@@ -70,19 +98,42 @@ export function RevenueChart({
70
98
  content={
71
99
  <ChartTooltipContent
72
100
  labelFormatter={(value) => formatDay(String(value))}
73
- formatter={(value) => money(Number(value))}
74
- 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
+ )}
75
114
  />
76
115
  }
77
116
  />
117
+ {overdue && <ChartLegend content={<ChartLegendContent />} />}
78
118
  <Area
79
119
  dataKey="revenue"
80
120
  type="monotone"
81
121
  fill={`url(#${id}-revenue)`}
82
122
  stroke="var(--color-revenue)"
123
+ strokeWidth={2}
83
124
  isAnimationActive={false}
84
125
  />
85
- </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>
86
137
  </ChartContainer>
87
138
  {/* Tables ignore sr-only's 1px height, so the wrapper hides it. */}
88
139
  <div className="sr-only">
@@ -91,16 +142,20 @@ export function RevenueChart({
91
142
  <thead>
92
143
  <tr>
93
144
  <th scope="col">{words.date}</th>
94
- <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>}
95
148
  </tr>
96
149
  </thead>
97
150
  <tbody>
98
151
  {points
99
- .filter((point) => point.revenue !== 0)
152
+ .filter((point) => point.received !== 0 || point.overdue !== 0)
100
153
  .map((point) => (
101
154
  <tr key={point.day}>
102
155
  <th scope="row">{formatDay(point.day)}</th>
156
+ <td>{money(point.received)}</td>
103
157
  <td>{money(point.revenue)}</td>
158
+ {overdue && <td>{money(point.overdue)}</td>}
104
159
  </tr>
105
160
  ))}
106
161
  </tbody>
@@ -110,14 +165,30 @@ export function RevenueChart({
110
165
  );
111
166
  }
112
167
 
113
- /** 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. */
114
185
  export function LeadsBySourceCard({ counts, text }: { counts: SourceCount[]; text?: Partial<CrmText> | undefined }) {
115
186
  const words = withText(text);
116
187
  const total = counts.reduce((sum, row) => sum + row.count, 0);
117
188
  const points = counts
118
189
  .filter((row) => row.count > 0)
119
- .map((row) => ({ source: SOURCE_LABELS[row.source], leads: row.count }));
120
- 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;
121
192
  return (
122
193
  <CrmCard title={words.leadsBySource} description={`${total} ${words.leads.toLowerCase()}`} text={text}>
123
194
  <ChartContainer config={config} className="aspect-auto h-60 w-full" aria-hidden="true">
@@ -126,7 +197,7 @@ export function LeadsBySourceCard({ counts, text }: { counts: SourceCount[]; tex
126
197
  <YAxis dataKey="source" type="category" tickLine={false} axisLine={false} width={72} />
127
198
  <XAxis type="number" dataKey="leads" allowDecimals={false} tickLine={false} axisLine={false} />
128
199
  <ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dot" />} />
129
- <Bar dataKey="leads" fill="var(--color-leads)" radius={4} isAnimationActive={false} />
200
+ <Bar dataKey="leads" radius={4} isAnimationActive={false} />
130
201
  </BarChart>
131
202
  </ChartContainer>
132
203
  <div className="sr-only">
@@ -194,6 +265,7 @@ export function TimelineCard({
194
265
  <CrmCard
195
266
  title={title}
196
267
  text={text}
268
+ className="flex-1"
197
269
  {...(description ? { description } : {})}
198
270
  action={
199
271
  <TabsList aria-label={title}>
@@ -1,4 +1,5 @@
1
1
  import { useEffect, useId, useState, type FormEvent, type ReactNode } from 'react';
2
+ import { ArrowUpRight } from 'lucide-react';
2
3
  import type { DealInput, LeadInput } from '../backend.ts';
3
4
  import type { NewLeadOptions } from '../crm-client.ts';
4
5
  import { LEAD_SOURCES, LEAD_STATUS_LABELS, SOURCE_LABELS, leadOutcome } from '../leads.ts';
@@ -233,6 +234,7 @@ function LeadFields({
233
234
  onChange,
234
235
  saving,
235
236
  contactDetails,
237
+ onOpenCompany,
236
238
  text,
237
239
  }: {
238
240
  lead: Lead;
@@ -243,6 +245,7 @@ function LeadFields({
243
245
  onChange: (changes: Partial<LeadInput>, options?: NewLeadOptions) => Promise<unknown>;
244
246
  saving?: boolean | undefined;
245
247
  contactDetails?: ContactDetailsAccess | undefined;
248
+ onOpenCompany?: ((company: string) => void) | undefined;
246
249
  text?: Partial<CrmText> | undefined;
247
250
  }) {
248
251
  const words = withText(text);
@@ -313,6 +316,16 @@ function LeadFields({
313
316
  named={(urn) => companyNameOf(names, urn)}
314
317
  text={text}
315
318
  />
319
+ {lead.contactCompany && onOpenCompany && (
320
+ <CompanyOpener
321
+ company={lead.contactCompany.urn}
322
+ onOpen={onOpenCompany}
323
+ className="justify-self-start text-sm"
324
+ >
325
+ {words.openCompany}
326
+ <ArrowUpRight aria-hidden="true" className="size-3.5" />
327
+ </CompanyOpener>
328
+ )}
316
329
  </Field>
317
330
  <Field id={`${id}-contact`} label={words.contact}>
318
331
  <ChoiceSelect
@@ -380,6 +393,29 @@ function LeadFields({
380
393
  );
381
394
  }
382
395
 
396
+ /** A button that opens a company's own page in the host, looking like a link. */
397
+ function CompanyOpener({
398
+ company,
399
+ onOpen,
400
+ className = '',
401
+ children,
402
+ }: {
403
+ company: string;
404
+ onOpen: (company: string) => void;
405
+ className?: string;
406
+ children: ReactNode;
407
+ }) {
408
+ return (
409
+ <button
410
+ type="button"
411
+ className={`text-primary inline-flex items-center gap-1 font-medium underline-offset-4 hover:underline ${className}`}
412
+ onClick={() => onOpen(company)}
413
+ >
414
+ {children}
415
+ </button>
416
+ );
417
+ }
418
+
383
419
  /**
384
420
  * A lead's details. While it's open, its fields can be changed (with `onChange`), it can be converted ("Convert to
385
421
  * deal", where the new client company's name can be corrected) and marked unqualified with why. Once unqualified it
@@ -396,6 +432,7 @@ export function LeadDetail({
396
432
  onSetOutcome,
397
433
  converting,
398
434
  contactDetails,
435
+ onOpenCompany,
399
436
  sample,
400
437
  text,
401
438
  }: {
@@ -416,6 +453,8 @@ export function LeadDetail({
416
453
  converting?: boolean | undefined;
417
454
  /** Reads and sets the contact's email and telephone, shown under the contact when given. */
418
455
  contactDetails?: ContactDetailsAccess | undefined;
456
+ /** Opens the lead's company's own page in the host: its company is then a link. */
457
+ onOpenCompany?: ((company: string) => void) | undefined;
419
458
  sample?: boolean | undefined;
420
459
  text?: Partial<CrmText> | undefined;
421
460
  }) {
@@ -444,6 +483,7 @@ export function LeadDetail({
444
483
  onChange={onChange}
445
484
  saving={converting}
446
485
  contactDetails={contactDetails}
486
+ onOpenCompany={onOpenCompany}
447
487
  text={text}
448
488
  />
449
489
  )}
@@ -457,7 +497,17 @@ export function LeadDetail({
457
497
  ? []
458
498
  : [
459
499
  { label: words.contact, value: personNameOf(names, lead.contactIdentity?.urn) ?? '-' },
460
- { label: words.company, value: leadCompany(lead, names) || '-' },
500
+ {
501
+ label: words.company,
502
+ value:
503
+ lead.contactCompany && onOpenCompany ? (
504
+ <CompanyOpener company={lead.contactCompany.urn} onOpen={onOpenCompany}>
505
+ {leadCompany(lead, names) || words.unnamed}
506
+ </CompanyOpener>
507
+ ) : (
508
+ leadCompany(lead, names) || '-'
509
+ ),
510
+ },
461
511
  { label: words.source, value: SOURCE_LABELS[lead.source] },
462
512
  { label: words.value, value: formatMaybeMoney(lead.targetValue) },
463
513
  { label: words.assignee, value: personNameOf(names, lead.assignee?.urn) ?? '-' },
package/src/react/text.ts CHANGED
@@ -18,6 +18,10 @@ 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
27
  targetSummary: 'Payments received on deals against the value of deals open or won',
@@ -126,6 +130,7 @@ export const CRM_TEXT = {
126
130
  newCompany: 'New company',
127
131
  newCompanyHint: 'Makes the client company, owned by yours, when the lead is saved.',
128
132
  addCompany: 'Add a new company',
133
+ openCompany: 'Open company',
129
134
  companyNameRequired: 'Enter the company name.',
130
135
  noContact: 'No contact',
131
136
  newContact: 'New contact',
@@ -158,8 +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, revenue over time, leads by source and over time, the host's tasks panel, the target with the new
162
- * deals that make it up, the pipeline 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.
163
164
  */
164
165
  export function CrmDashboard({
165
166
  store,
@@ -189,29 +190,35 @@ export function CrmDashboard({
189
190
  [state, period, ownKey, pipeline?.urn],
190
191
  );
191
192
  if (state.status === 'idle' || state.status === 'loading') return <Loading label={words.loading} />;
192
- 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
+ );
193
209
  return (
194
210
  <div className="grid gap-6">
195
211
  <Sample store={store} concepts={concepts} text={text} />
196
212
  <Problems state={state} concepts={concepts} text={words} />
197
213
  {!range && <PeriodSelect value={picked} onChange={setPicked} text={text} />}
198
214
  <MetricCards dashboard={dashboard} text={range ? text : periodText(picked, text)} />
199
- <RevenueChart days={dashboard.revenueByDay} currencyCode={dashboard.revenue.currencyCode} text={text} />
200
- <div className={tasks ? 'grid items-start gap-6 lg:grid-cols-3' : 'grid items-start gap-6 lg:grid-cols-2'}>
201
- {/* Where leads come from, and when they came. */}
202
- <LeadsBySourceCard counts={dashboard.leadsBySource} text={text} />
203
- <TimelineCard
204
- title={words.leadsOverTime}
205
- description={words.leadsOverTimeHint}
206
- timeline={dashboard.leadsOverTime}
207
- countLabel={words.leads}
208
- color="var(--chart-2)"
209
- fallbackCurrency={dashboard.revenue.currencyCode}
210
- text={text}
211
- />
212
- {tasks ?? null}
213
- </div>
214
- <div className="grid items-start gap-6 lg:grid-cols-3">
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">
215
222
  {/* What deals have brought in against the target, then the new deals that make it up. */}
216
223
  <TargetCard target={dashboard.target} text={text} />
217
224
  <TimelineCard
@@ -226,6 +233,15 @@ export function CrmDashboard({
226
233
  />
227
234
  </div>
228
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
+ )}
229
245
  <LeadsTable leads={state.leads} names={names} onOpen={onOpenLead} text={text} />
230
246
  </div>
231
247
  );
@@ -242,6 +258,7 @@ export function CrmLeadsView({
242
258
  selected,
243
259
  onSelect,
244
260
  onConverted,
261
+ onOpenCompany,
245
262
  }: ViewProps & {
246
263
  /** People a lead's contact can be chosen from: the host's customers' people. */
247
264
  people?: readonly CrmPersonChoice[] | undefined;
@@ -251,6 +268,8 @@ export function CrmLeadsView({
251
268
  onSelect?: ((lead: Lead | undefined) => void) | undefined;
252
269
  /** After a lead becomes a deal, for example to open the deal. */
253
270
  onConverted?: ((deal: Deal) => void) | undefined;
271
+ /** Opens a lead's company's own page in the host: the open lead's company is then a link. */
272
+ onOpenCompany?: ((company: string) => void) | undefined;
254
273
  }) {
255
274
  const state = useCrmStore(store);
256
275
  names = useCrmNames(names, state);
@@ -306,6 +325,7 @@ export function CrmLeadsView({
306
325
  text={text}
307
326
  converting={state.saving.has(lead.urn)}
308
327
  contactDetails={contactDetails}
328
+ onOpenCompany={onOpenCompany}
309
329
  onSetOutcome={(closing, outcome, closedReason) =>
310
330
  void store
311
331
  .setLeadOutcome(closing, outcome, closedReason === undefined ? {} : { closedReason })
@@ -567,7 +587,12 @@ export function CrmSalesView({
567
587
  <Problems state={state} concepts={concepts} text={words} />
568
588
  {!range && <PeriodSelect value={picked} onChange={setPicked} text={text} />}
569
589
  <SalesMetricCards summary={summary} text={range ? text : periodText(picked, text)} />
570
- <RevenueChart days={summary.byDay} currencyCode={summary.currencyCode} text={text} />
590
+ <RevenueChart
591
+ days={summary.byDay}
592
+ overdue={summary.overdueByDay}
593
+ currencyCode={summary.currencyCode}
594
+ text={text}
595
+ />
571
596
  <div className="grid items-start gap-6 lg:grid-cols-2">
572
597
  <OutstandingByAgeCard summary={summary} text={text} />
573
598
  <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,7 +15,7 @@ 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
20
  import { countsTowardsTarget, salesTarget, type SalesTarget } from './target.ts';
21
21
  import { timeline, type Timeline } from './timeline.ts';
@@ -424,6 +424,8 @@ export interface Dashboard {
424
424
  revenue: Compared<MoneyTotals> & { currencyCode: string | undefined };
425
425
  /** Payments received less refunds on each day of the period. */
426
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 }[];
427
429
  /** Leads created in each period. */
428
430
  newLeads: Compared<number>;
429
431
  /** Leads created in the period, counted and valued per day or week. */
@@ -453,12 +455,14 @@ export function selectDashboard(
453
455
  own?: ReadonlySet<string>,
454
456
  /** The user's chosen pipeline, for the pipeline card (see `defaultPipeline`). */
455
457
  chosenPipeline?: string,
458
+ now = new Date(),
456
459
  ): Dashboard {
457
460
  const before = previousRange(range);
458
461
  const { leads, deals, pipelines } = state;
459
462
  const shownPipeline = defaultPipeline(pipelines, deals, chosenPipeline);
460
463
  // Revenue is what customers paid: payments the business made on its costs aren't counted.
461
464
  const remittances = salesRemittances(state, own);
465
+ const salesInvoices = state.invoices.filter((invoice) => !isCostInvoice(invoice, own));
462
466
 
463
467
  const firstWins = new Map<string, string>();
464
468
  let openValue: MoneyTotals = {};
@@ -507,6 +511,7 @@ export function selectDashboard(
507
511
  change: revenueCurrency ? periodChange(current[revenueCurrency] ?? 0, previous[revenueCurrency] ?? 0) : undefined,
508
512
  },
509
513
  revenueByDay: paymentsByDay(remittances, range),
514
+ overdueByDay: overdueByDay(salesInvoices, remittances, range, now),
510
515
  newLeads: compare(
511
516
  count(leads, (lead) => lead.createdTimestamp, range),
512
517
  count(leads, (lead) => lead.createdTimestamp, before),