Dashboard: chart, utilisation, sales, customers, codes owed, attention; show password

Adds to the dashboard: an income-per-month bar chart (hover for the
figures; the month table is its table view), opened-time utilisation
(booked hours against hours opened in Slots), what sells and popular
lengths, new vs. returning customers and regulars, what usable codes are
still worth, and a "Needs attention" list (failed booking emails, group
sessions nearly full and codes expiring in the next 30 days). Slot places
and code credits come from the shop hooks, as everywhere else.

Login: a Show/Hide button on the password field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gV9YDZk1XhjJ5LtyAt
This commit is contained in:
agent 2026-10-27 09:14:27 +00:00
parent bdc040636a
commit 2dc57fd27c
5 changed files with 413 additions and 99 deletions

View file

@ -25,7 +25,7 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts) │ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts)
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
│ │ ├── +page.svelte # Dashboard (income, hours worked/booked, coming up); figures from $lib/server/dashboard.ts. Login lands here │ │ ├── +page.svelte # Dashboard (income + chart, hours, utilisation, customers, codes owed, what sells, needs attention); figures from $lib/server/dashboard.ts. Login lands here
│ │ ├── login/ # Admin login │ │ ├── login/ # Admin login
│ │ ├── pages/ # Page CRUD + block editor │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── calendar/ # Event CRUD (menu label: Events)

View file

@ -0,0 +1,84 @@
<script lang="ts">
// Income per month as bars, one series (so no legend: the section title names
// it). The month-by-month table below it on the dashboard is its table view.
// Drawn at the box's real pixel width so labels stay readable on a phone.
/** `label` goes under the bar; `name` (e.g. "October 2026") heads the tooltip. */
type Month = { month: string; label: string; name: string; income: number; orders: number };
let {
months,
format,
tickFormat = format,
current = ''
}: { months: Month[]; format: (amount: number) => string; tickFormat?: (amount: number) => string; current?: string } = $props();
let width = $state(600);
const height = 220;
const pad = { top: 12, right: 8, bottom: 28, left: 64 };
let plotWidth = $derived(Math.max(width - pad.left - pad.right, 100));
const plotHeight = height - pad.top - pad.bottom;
// A 1-2-5 step giving about four gridlines.
let ticks = $derived.by(() => {
const max = Math.max(...months.map((m) => m.income), 0);
if (max <= 0) return [0];
const rough = max / 4;
const magnitude = 10 ** Math.floor(Math.log10(rough));
const step = [1, 2, 5, 10].map((n) => n * magnitude).find((n) => n >= rough)!;
return Array.from({ length: Math.ceil(max / step) + 1 }, (_, i) => i * step);
});
let top = $derived(ticks.at(-1) || 1);
let slot = $derived(plotWidth / Math.max(months.length, 1));
// Thin bars: at most 28px, with the gap between them clearly wider than 2px.
let barWidth = $derived(Math.min(28, slot * 0.6));
const y = (value: number) => pad.top + plotHeight - (value / top) * plotHeight;
/** A bar with 4px rounded top corners, square on the baseline. */
function barPath(x: number, value: number) {
const h = (value / top) * plotHeight;
if (h <= 0) return '';
const r = Math.min(4, h, barWidth / 2);
const yTop = pad.top + plotHeight - h;
const base = pad.top + plotHeight;
return `M${x},${base}V${yTop + r}Q${x},${yTop} ${x + r},${yTop}H${x + barWidth - r}Q${x + barWidth},${yTop} ${x + barWidth},${yTop + r}V${base}Z`;
}
let hovered = $state<number | null>(null);
// Every month labelled when there's room, else every other one (current month always).
let labelEvery = $derived(slot < 40 ? 2 : 1);
</script>
<div class="relative" bind:clientWidth={width}>
<svg {width} {height} role="img" aria-label="Income per month, last {months.length} months. The table below lists the figures.">
{#each ticks as tick (tick)}
<line x1={pad.left} x2={pad.left + plotWidth} y1={y(tick)} y2={y(tick)} class="stroke-base-content/10" stroke-width="1" />
<text x={pad.left - 8} y={y(tick)} dy="0.32em" text-anchor="end" class="fill-base-content/60 text-[11px] tabular-nums">{tickFormat(tick)}</text>
{/each}
{#each months as m, i (m.month)}
{@const x = pad.left + i * slot + (slot - barWidth) / 2}
<path d={barPath(x, m.income)} class={hovered === null || hovered === i ? 'fill-primary' : 'fill-primary/40'} />
{#if i % labelEvery === (months.length - 1) % labelEvery || m.month === current}
<text x={x + barWidth / 2} y={height - 8} text-anchor="middle" class="text-[11px] {m.month === current ? 'fill-base-content font-semibold' : 'fill-base-content/60'}">{m.label}</text>
{/if}
<!-- Hit target: the whole column, much bigger than the bar. -->
<rect
x={pad.left + i * slot}
y={pad.top}
width={slot}
height={plotHeight}
fill="transparent"
role="presentation"
onpointerenter={() => (hovered = i)}
onpointerleave={() => (hovered = null)}
/>
{/each}
</svg>
{#if hovered !== null}
{@const m = months[hovered]}
{@const left = Math.min(Math.max(pad.left + hovered * slot + slot / 2, 70), width - 70)}
<div class="pointer-events-none absolute -translate-x-1/2 whitespace-nowrap rounded-box bg-base-100 px-3 py-2 text-sm shadow-lg ring-1 ring-base-300" style="left: {left}px; top: {Math.max(y(m.income) - 64, 0)}px">
<p class="font-semibold">{m.name}</p>
<p class="tabular-nums">{format(m.income)} · {m.orders} {m.orders === 1 ? 'order' : 'orders'}</p>
</div>
{/if}
</div>

View file

@ -1,25 +1,42 @@
// Figures for the admin dashboard (/): income from paid orders and the hours // Figures for the admin dashboard (/). Months are calendar months in
// booked from their slot lines. Months are calendar months in SITE_TIMEZONE. // SITE_TIMEZONE.
// //
// Income counts an order in the month it was paid, so a voucher sold in March // Income counts an order in the month it was paid, so a voucher sold in March
// is March income and the session it later pays for adds hours but no income. // is March income and the session it later pays for adds hours but no income.
// Hours are the time covered by bookings, with overlaps counted once: six // Hours are the time covered by bookings, with overlaps counted once: six
// people in one group session are one hour of work, not six. // people in one group session are one hour of work, not six. Utilisation is
// that booked time against the time opened in Slots.
//
// Slot places and what codes have left come from the shop hooks (the only
// place that counts them); everything else is read from paid orders.
import { zonedDateKey, zonedInputToIso } from '$lib/calendar'; import { zonedDateKey, zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb'; import type { createPocketBase } from '$lib/pb';
import { listPasses } from '$lib/server/passes';
import { loadSlotDetails, seatsTaken } from '$lib/server/slots';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
/** How many months the month-by-month table shows, this one included. */ /** How many months the month-by-month table and chart show, this one included. */
export const DASHBOARD_MONTHS = 12; export const DASHBOARD_MONTHS = 12;
const UPCOMING_DAYS = 7; const UPCOMING_DAYS = 7;
/** How far ahead "Needs attention" looks for nearly full sessions and expiring codes. */
const ATTENTION_DAYS = 30;
/** A group session is "nearly full" with this share of its places taken (or one place left). */
const NEARLY_FULL_SHARE = 0.75;
const TOP_LIST = 5;
const DAY_MS = 24 * 60 * 60 * 1000; const DAY_MS = 24 * 60 * 60 * 1000;
export type DashboardMonth = { month: string; income: number; orders: number; minutes: number }; export type DashboardMonth = { month: string; income: number; orders: number; minutes: number };
export type UpcomingBooking = { start: string; minutes: number; name: string; customer: string; quantity: number }; export type UpcomingBooking = { start: string; minutes: number; name: string; customer: string; quantity: number };
export type SalesRow = { name: string; minutes: number; count: number; income: number };
export type Regular = { name: string; orders: number; spent: number };
export type Attention =
| { kind: 'email'; orderId: string; customer: string; created: string }
| { kind: 'session'; start: string; name: string; taken: number; capacity: number }
| { kind: 'code'; code: string; name: string; expiresAt: string; left: number };
type Booking = { start: number; end: number }; type Interval = { start: number; end: number };
/** `YYYY-MM` for `months` before (negative) or after `monthKey`. */ /** `YYYY-MM` for `months` before (negative) or after `monthKey`. */
function shiftMonth(monthKey: string, months: number) { function shiftMonth(monthKey: string, months: number) {
@ -28,76 +45,149 @@ function shiftMonth(monthKey: string, months: number) {
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`; return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`;
} }
/** Bookings merged where they overlap or touch, sorted by start. */ /** Epoch ms of a PocketBase date ('2026-10-27 09:00:00.000Z'), NaN if blank. */
function mergeBookings(bookings: Booking[]) { const toMs = (value: unknown) => new Date(String(value || '').replace(' ', 'T')).getTime();
const merged: Booking[] = [];
for (const booking of [...bookings].sort((a, b) => a.start - b.start)) { /** Intervals merged where they overlap or touch, sorted by start. */
function mergeIntervals(intervals: Interval[]) {
const merged: Interval[] = [];
for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {
const last = merged.at(-1); const last = merged.at(-1);
if (last && booking.start <= last.end) last.end = Math.max(last.end, booking.end); if (last && interval.start <= last.end) last.end = Math.max(last.end, interval.end);
else merged.push({ ...booking }); else merged.push({ ...interval });
} }
return merged; return merged;
} }
/** Minutes of merged `intervals` that fall inside [from, to). */
function minutesBetween(intervals: Interval[], from: number, to: number) {
return intervals.reduce((total, { start, end }) => total + Math.max(Math.min(end, to) - Math.max(start, from), 0) / 60_000, 0);
}
/** Top rows by income, the rest folded into one "Other" row. */
function topWithOther(rows: SalesRow[], other: string) {
const sorted = [...rows].sort((a, b) => b.income - a.income || b.count - a.count);
if (sorted.length <= TOP_LIST) return sorted;
const rest = sorted.slice(TOP_LIST - 1);
return [
...sorted.slice(0, TOP_LIST - 1),
{ name: other, minutes: 0, count: rest.reduce((n, row) => n + row.count, 0), income: rest.reduce((n, row) => n + row.income, 0) }
];
}
export async function loadDashboard(pb: Pb, timeZone: string, now = new Date()) { export async function loadDashboard(pb: Pb, timeZone: string, now = new Date()) {
const nowMs = now.getTime();
const thisMonth = zonedDateKey(now.toISOString(), timeZone).slice(0, 7); const thisMonth = zonedDateKey(now.toISOString(), timeZone).slice(0, 7);
const months = Array.from({ length: DASHBOARD_MONTHS }, (_, i) => shiftMonth(thisMonth, i - (DASHBOARD_MONTHS - 1))); const months = Array.from({ length: DASHBOARD_MONTHS }, (_, i) => shiftMonth(thisMonth, i - (DASHBOARD_MONTHS - 1)));
// The table reaches back at least to January, so it covers "this year" too. // The table reaches back at least to January, so it covers "this year" too.
const from = zonedInputToIso(`${months[0]}-01T00:00`, timeZone); const from = zonedInputToIso(`${months[0]}-01T00:00`, timeZone);
const monthStart = zonedInputToIso(`${thisMonth}-01T00:00`, timeZone);
const monthEnd = zonedInputToIso(`${shiftMonth(thisMonth, 1)}-01T00:00`, timeZone);
const attentionUntil = nowMs + ATTENTION_DAYS * DAY_MS;
const [orders, lines] = await Promise.all([ const [orders, lines, slotDetails, passes] = await Promise.all([
// Every paid order, so "new customer" means first order ever.
pb pb
.collection('orders') .collection('orders')
.getFullList({ filter: pb.filter("status = 'paid' && created >= {:from}", { from }), fields: 'total,created', requestKey: null }) .getFullList({ filter: "status = 'paid'", fields: 'id,email,total,created,customerDetails,emailError', requestKey: null })
.catch(() => []), .catch(() => []),
pb pb
.collection('order_lines') .collection('order_lines')
.getFullList({ .getFullList({
filter: pb.filter("lineType = 'slot' && order.status = 'paid' && start >= {:from}", { from }), filter: pb.filter("order.status = 'paid' && (order.created >= {:from} || start >= {:from})", { from }),
sort: 'start', sort: 'start',
expand: 'order', expand: 'order',
fields: 'name,start,minutes,quantity,expand.order.customerDetails', fields: 'item,name,price,quantity,lineType,start,minutes,expand.order.created,expand.order.customerDetails',
requestKey: null requestKey: null
}) })
.catch(() => []) .catch(() => []),
loadSlotDetails(pb, { from: monthStart, to: new Date(Math.max(toMs(monthEnd), attentionUntil)).toISOString() }).catch(() => null),
listPasses(pb, '').catch(() => [])
]); ]);
const monthOf = (value: unknown) => zonedDateKey(String(value || ''), timeZone).slice(0, 7);
const byMonth = new Map<string, DashboardMonth>(months.map((month) => [month, { month, income: 0, orders: 0, minutes: 0 }])); const byMonth = new Map<string, DashboardMonth>(months.map((month) => [month, { month, income: 0, orders: 0, minutes: 0 }]));
for (const order of orders) {
const row = byMonth.get(zonedDateKey(String(order.created), timeZone).slice(0, 7)); // ── Income and customers ───────────────────────────────────────────
if (!row) continue; // Orders from before `created` existed have no date: they count as
// "earlier" (so their customers are returning), never as this month.
const firstOrder = new Map<string, number>();
const regulars = new Map<string, Regular>();
for (const order of [...orders].sort((a, b) => (toMs(a.created) || 0) - (toMs(b.created) || 0))) {
const created = toMs(order.created);
const month = Number.isNaN(created) ? '' : monthOf(order.created);
const row = byMonth.get(month);
if (row) {
row.income += Number(order.total) || 0; row.income += Number(order.total) || 0;
row.orders += 1; row.orders += 1;
} }
// Anonymised orders have no email: they're nobody's history any more.
const email = String(order.email || '').trim().toLowerCase();
if (!email) continue;
if (!firstOrder.has(email)) firstOrder.set(email, Number.isNaN(created) ? 0 : created);
if (row) {
const regular = regulars.get(email) ?? { name: '', orders: 0, spent: 0 };
regular.name = String(order.customerDetails?.name || '') || regular.name || email;
regular.orders += 1;
regular.spent += Number(order.total) || 0;
regulars.set(email, regular);
}
}
let newCustomers = 0;
let returningCustomers = 0;
const seenThisMonth = new Set<string>();
for (const order of orders) {
const email = String(order.email || '').trim().toLowerCase();
if (!email || seenThisMonth.has(email) || Number.isNaN(toMs(order.created)) || monthOf(order.created) !== thisMonth) continue;
seenThisMonth.add(email);
if ((firstOrder.get(email) ?? 0) >= toMs(monthStart)) newCustomers++;
else returningCustomers++;
}
const bookings: Booking[] = []; // ── What sells (orders paid in the 12 months) ─────────────────────────
const services = new Map<string, SalesRow>();
const lengths = new Map<string, SalesRow>();
for (const line of lines) { for (const line of lines) {
const start = new Date(String(line.start).replace(' ', 'T')).getTime(); const created = line.expand?.order?.created;
const minutes = Number(line.minutes) || 0; if (!byMonth.has(monthOf(created))) continue;
if (!Number.isNaN(start) && minutes > 0) bookings.push({ start, end: start + minutes * 60_000 }); const quantity = Number(line.quantity) || 1;
} const income = (Number(line.price) || 0) * quantity;
// Split at "now" so this month can show done vs. still to come. const name = String(line.name || '');
let doneThisMonth = 0; const service = services.get(line.item) ?? { name, minutes: 0, count: 0, income: 0 };
let aheadThisMonth = 0; service.count += quantity;
for (const { start, end } of mergeBookings(bookings)) { service.income += income;
const month = zonedDateKey(new Date(start).toISOString(), timeZone).slice(0, 7); services.set(line.item, service);
const row = byMonth.get(month); if (line.lineType === 'slot' && line.minutes) {
if (!row) continue; const key = `${line.item}:${line.minutes}`;
const minutes = (end - start) / 60_000; const length = lengths.get(key) ?? { name, minutes: Number(line.minutes), count: 0, income: 0 };
row.minutes += minutes; length.count += quantity;
if (month === thisMonth) { length.income += income;
const done = Math.min(Math.max(now.getTime() - start, 0) / 60_000, minutes); lengths.set(key, length);
doneThisMonth += done;
aheadThisMonth += minutes - done;
} }
} }
// Products inside a bundle are lines at price 0: the bundle line has the money.
const sales = topWithOther([...services.values()].filter((row) => row.income > 0), 'Everything else');
const topLengths = [...lengths.values()].sort((a, b) => b.count - a.count || b.income - a.income).slice(0, TOP_LIST);
const upcomingUntil = now.getTime() + UPCOMING_DAYS * DAY_MS; // ── Hours ────────────────────────────────────────────────────────────
const bookings = mergeIntervals(
lines
.filter((line) => line.lineType === 'slot' && Number(line.minutes) > 0 && !Number.isNaN(toMs(line.start)))
.map((line) => ({ start: toMs(line.start), end: toMs(line.start) + Number(line.minutes) * 60_000 }))
);
for (const { start, end } of bookings) {
const row = byMonth.get(monthOf(new Date(start).toISOString()));
if (row) row.minutes += (end - start) / 60_000;
}
const minutesDoneThisMonth = minutesBetween(bookings, toMs(monthStart), Math.min(nowMs, toMs(monthEnd)));
const minutesAheadThisMonth = minutesBetween(bookings, nowMs, toMs(monthEnd));
const upcomingUntil = nowMs + UPCOMING_DAYS * DAY_MS;
const upcoming: UpcomingBooking[] = lines const upcoming: UpcomingBooking[] = lines
.filter((line) => { .filter((line) => {
const start = new Date(String(line.start).replace(' ', 'T')).getTime(); if (line.lineType !== 'slot') return false;
const end = start + (Number(line.minutes) || 0) * 60_000; const start = toMs(line.start);
return end > now.getTime() && start < upcomingUntil; return start + (Number(line.minutes) || 0) * 60_000 > nowMs && start < upcomingUntil;
}) })
.map((line) => ({ .map((line) => ({
start: String(line.start), start: String(line.start),
@ -107,24 +197,69 @@ export async function loadDashboard(pb: Pb, timeZone: string, now = new Date())
quantity: Number(line.quantity) || 1 quantity: Number(line.quantity) || 1
})); }));
const upcomingMinutes = mergeBookings(bookings).reduce( // Opened time this month (overlapping slots counted once) vs. booked time in it.
(total, { start, end }) => total + Math.max(Math.min(end, upcomingUntil) - Math.max(start, now.getTime()), 0) / 60_000, const slots = slotDetails?.slots ?? [];
0 const opened = mergeIntervals(slots.map((slot) => ({ start: toMs(slot.start), end: toMs(slot.end) })).filter((i) => !Number.isNaN(i.start)));
); const openMinutes = minutesBetween(opened, toMs(monthStart), toMs(monthEnd));
const bookedInMonth = minutesBetween(bookings, toMs(monthStart), toMs(monthEnd));
// ── Vouchers and codes ───────────────────────────────────────────────
// What's owed: the unbooked share of each usable code's value.
let codesOutstanding = 0;
let valueOutstanding = 0;
const attention: Attention[] = [];
for (const pass of passes) {
const expires = pass.expiresAt ? toMs(pass.expiresAt) : Infinity;
if (pass.status !== 'active' || expires <= nowMs) continue;
const open = pass.parts.filter((part) => part.redeemable && part.left > 0);
if (!open.length) continue;
codesOutstanding++;
valueOutstanding += open.reduce((total, part) => total + (part.count ? (part.value * part.left) / part.count : 0), 0);
if (expires <= attentionUntil) {
attention.push({ kind: 'code', code: pass.code, name: pass.name, expiresAt: pass.expiresAt, left: open.reduce((n, part) => n + part.left, 0) });
}
}
// ── Needs attention ──────────────────────────────────────────────────
for (const order of orders) {
if (order.emailError) {
attention.push({ kind: 'email', orderId: order.id, customer: String(order.customerDetails?.name || order.email || 'A customer'), created: String(order.created || '') });
}
}
for (const slot of slots) {
if (slot.kind !== 'session' || !slot.capacity || toMs(slot.start) <= nowMs || toMs(slot.start) > attentionUntil) continue;
const taken = seatsTaken(slot);
if (taken < slot.capacity && (taken >= slot.capacity * NEARLY_FULL_SHARE || slot.capacity - taken === 1)) {
attention.push({ kind: 'session', start: slot.start, name: slot.itemNames.join(', '), taken, capacity: slot.capacity });
}
}
const year = thisMonth.slice(0, 4); const year = thisMonth.slice(0, 4);
const monthRows = months.map((month) => byMonth.get(month)!); const monthRows = months.map((month) => byMonth.get(month)!);
const sum = (rows: DashboardMonth[], key: 'income' | 'minutes') => rows.reduce((total, row) => total + row[key], 0);
return { return {
thisMonth: byMonth.get(thisMonth)!, thisMonth: byMonth.get(thisMonth)!,
lastMonth: byMonth.get(shiftMonth(thisMonth, -1))!, lastMonth: byMonth.get(shiftMonth(thisMonth, -1))!,
incomeThisYear: sum(monthRows.filter((row) => row.month.startsWith(year)), 'income'), incomeThisYear: monthRows.filter((row) => row.month.startsWith(year)).reduce((total, row) => total + row.income, 0),
minutesDoneThisMonth: Math.round(doneThisMonth), minutesDoneThisMonth: Math.round(minutesDoneThisMonth),
minutesAheadThisMonth: Math.round(aheadThisMonth), minutesAheadThisMonth: Math.round(minutesAheadThisMonth),
// null when nothing is opened (or slots couldn't be read): no percentage to show.
utilisation: openMinutes > 0 && slotDetails ? { booked: Math.round(bookedInMonth), open: Math.round(openMinutes) } : null,
upcomingDays: UPCOMING_DAYS, upcomingDays: UPCOMING_DAYS,
upcoming, upcoming,
upcomingMinutes: Math.round(upcomingMinutes), upcomingMinutes: Math.round(minutesBetween(bookings, nowMs, upcomingUntil)),
// Newest first, like the Orders list. newCustomers,
months: monthRows.reverse() returningCustomers,
regulars: [...regulars.values()]
.filter((regular) => regular.orders > 1)
.sort((a, b) => b.orders - a.orders || b.spent - a.spent)
.slice(0, TOP_LIST),
sales,
lengths: topLengths,
codesOutstanding,
valueOutstanding,
attentionDays: ATTENTION_DAYS,
attention,
// Oldest first: the chart reads left to right.
months: monthRows
}; };
} }

View file

@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { DISPLAY_LOCALE, formatInstant, formatPrice } from '$lib/calendar'; import IncomeChart from '$lib/admin/IncomeChart.svelte';
import { DISPLAY_LOCALE, formatDateTime, formatInstant, formatPrice } from '$lib/calendar';
import { formatDuration } from '$shared/items'; import { formatDuration } from '$shared/items';
let { data } = $props(); let { data } = $props();
@ -8,48 +9,108 @@
const hoursFormat = new Intl.NumberFormat(DISPLAY_LOCALE, { maximumFractionDigits: 1 }); const hoursFormat = new Intl.NumberFormat(DISPLAY_LOCALE, { maximumFractionDigits: 1 });
const hours = (minutes: number) => `${hoursFormat.format(minutes / 60)} h`; const hours = (minutes: number) => `${hoursFormat.format(minutes / 60)} h`;
const money = (amount: number) => formatPrice(amount, data.currency); const money = (amount: number) => formatPrice(amount, data.currency);
// Whole units for the chart axis; falls back to the full price if the currency code is unknown.
const roundMoney = (amount: number) => {
try {
return new Intl.NumberFormat(DISPLAY_LOCALE, { style: 'currency', currency: data.currency, maximumFractionDigits: 0 }).format(amount);
} catch {
return money(amount);
}
};
// Mid-month noon UTC is inside the same month in every timezone. // Mid-month noon UTC is inside the same month in every timezone.
const monthLabel = (month: string, options: Intl.DateTimeFormatOptions = { month: 'long', year: 'numeric' }) => const monthLabel = (month: string, options: Intl.DateTimeFormatOptions = { month: 'long', year: 'numeric' }) =>
formatInstant(`${month}-15T12:00:00Z`, data.timezone, options); formatInstant(`${month}-15T12:00:00Z`, data.timezone, options);
const dayLabel = (value: string) => formatInstant(value, data.timezone, { weekday: 'short', day: 'numeric', month: 'short' }); const dayLabel = (value: string) => formatInstant(value, data.timezone, { weekday: 'short', day: 'numeric', month: 'short' });
const timeLabel = (value: string) => formatInstant(value, data.timezone, { hour: '2-digit', minute: '2-digit' }); const timeLabel = (value: string) => formatInstant(value, data.timezone, { hour: '2-digit', minute: '2-digit' });
let thisMonthName = $derived(monthLabel(dashboard.thisMonth.month, { month: 'long' }));
let incomeChange = $derived(dashboard.thisMonth.income - dashboard.lastMonth.income); let incomeChange = $derived(dashboard.thisMonth.income - dashboard.lastMonth.income);
let chartMonths = $derived(dashboard.months.map((m) => ({ ...m, label: monthLabel(m.month, { month: 'short' }), name: monthLabel(m.month) })));
let customersThisMonth = $derived(dashboard.newCustomers + dashboard.returningCustomers);
let utilisationPercent = $derived(dashboard.utilisation ? Math.round((dashboard.utilisation.booked / dashboard.utilisation.open) * 100) : null);
</script> </script>
<svelte:head><title>Dashboard | CMS</title></svelte:head> <svelte:head><title>Dashboard | CMS</title></svelte:head>
{#snippet tile(label: string, value: string, note: string)}
<div class="rounded-box bg-base-100 p-5 shadow">
<p class="text-sm text-base-content/60">{label}</p>
<p class="mt-1 text-3xl font-bold tabular-nums">{value}</p>
<p class="mt-1 text-sm text-base-content/60">{note}</p>
</div>
{/snippet}
{#snippet salesTable(rows: typeof dashboard.sales, nameOf: (row: (typeof dashboard.sales)[number]) => string, empty: string)}
{#if rows.length}
<table class="table table-sm">
<thead><tr><th></th><th class="text-right">Sold</th><th class="text-right">Income</th></tr></thead>
<tbody>
{#each rows as row, i (i)}
<tr><td>{nameOf(row)}</td><td class="text-right tabular-nums">{row.count}</td><td class="text-right tabular-nums">{money(row.income)}</td></tr>
{/each}
</tbody>
</table>
{:else}
<p class="text-base-content/60">{empty}</p>
{/if}
{/snippet}
<div class="mb-6"> <div class="mb-6">
<h1 class="text-3xl font-bold">Dashboard</h1> <h1 class="text-3xl font-bold">Dashboard</h1>
<p class="text-base-content/60">How the studio is doing. Income is paid orders; hours are booked appointment time, with group sessions counted once.</p> <p class="text-base-content/60">How the studio is doing. Income is paid orders, in the month they were paid; hours are booked appointment time, with group sessions counted once.</p>
</div> </div>
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4"> <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-box bg-base-100 p-5 shadow"> {@render tile(`Income in ${thisMonthName}`, money(dashboard.thisMonth.income), `${incomeChange >= 0 ? '+' : '−'}${money(Math.abs(incomeChange))} on ${monthLabel(dashboard.lastMonth.month, { month: 'long' })}`)}
<p class="text-sm text-base-content/60">Income in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}</p> {@render tile(
<p class="mt-1 text-3xl font-bold">{money(dashboard.thisMonth.income)}</p> `Income in ${dashboard.thisMonth.month.slice(0, 4)}`,
<p class="mt-1 text-sm text-base-content/60"> money(dashboard.incomeThisYear),
{incomeChange >= 0 ? '+' : '−'}{money(Math.abs(incomeChange))} on {monthLabel(dashboard.lastMonth.month, { month: 'long' })} `${dashboard.thisMonth.orders} ${dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month${dashboard.thisMonth.orders ? `, ${money(dashboard.thisMonth.income / dashboard.thisMonth.orders)} on average` : ''}`
</p> )}
</div> {@render tile(`Hours worked in ${thisMonthName}`, hours(dashboard.minutesDoneThisMonth), `${hours(dashboard.minutesAheadThisMonth)} still booked this month`)}
<div class="rounded-box bg-base-100 p-5 shadow"> {@render tile(
<p class="text-sm text-base-content/60">Income in {dashboard.thisMonth.month.slice(0, 4)}</p> 'Opened time booked',
<p class="mt-1 text-3xl font-bold">{money(dashboard.incomeThisYear)}</p> utilisationPercent === null ? '—' : `${utilisationPercent} %`,
<p class="mt-1 text-sm text-base-content/60">{dashboard.thisMonth.orders} {dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month</p> dashboard.utilisation ? `${hours(dashboard.utilisation.booked)} of ${hours(dashboard.utilisation.open)} opened in Slots this month` : 'No slots opened this month'
</div> )}
<div class="rounded-box bg-base-100 p-5 shadow"> {@render tile(`Next ${dashboard.upcomingDays} days`, `${dashboard.upcoming.length} ${dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}`, `${hours(dashboard.upcomingMinutes)} of appointments`)}
<p class="text-sm text-base-content/60">Hours worked in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}</p> {@render tile(`Customers in ${thisMonthName}`, String(customersThisMonth), `${dashboard.newCustomers} new, ${dashboard.returningCustomers} returning`)}
<p class="mt-1 text-3xl font-bold">{hours(dashboard.minutesDoneThisMonth)}</p> {@render tile('Vouchers & codes owed', money(dashboard.valueOutstanding), `${dashboard.codesOutstanding} ${dashboard.codesOutstanding === 1 ? 'code' : 'codes'} with sessions still to book`)}
<p class="mt-1 text-sm text-base-content/60">{hours(dashboard.minutesAheadThisMonth)} still booked this month</p> {@render tile('Needs attention', String(dashboard.attention.length), dashboard.attention.length ? 'See the list below' : 'Nothing right now')}
</div>
<div class="rounded-box bg-base-100 p-5 shadow">
<p class="text-sm text-base-content/60">Next {dashboard.upcomingDays} days</p>
<p class="mt-1 text-3xl font-bold">{dashboard.upcoming.length} {dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}</p>
<p class="mt-1 text-sm text-base-content/60">{hours(dashboard.upcomingMinutes)} of appointments</p>
</div>
</div> </div>
{#if dashboard.attention.length}
<section class="mt-6 rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Needs attention</h2>
<ul class="divide-y divide-base-300">
{#each dashboard.attention as item, i (i)}
<li class="flex flex-wrap items-center gap-x-3 gap-y-1 py-2">
{#if item.kind === 'email'}
<span class="badge badge-warning badge-sm">⚠ Email failed</span>
<span class="order-last basis-full sm:order-none sm:basis-0 sm:flex-1">Booking email for {item.customer}{#if item.created}<span class="text-base-content/60">&nbsp;· ordered {formatDateTime(item.created, data.timezone)}</span>{/if}</span>
<a class="btn btn-ghost btn-xs ml-auto" href="/orders">Resend in Orders</a>
{:else if item.kind === 'session'}
<span class="badge badge-info badge-sm">◔ Nearly full</span>
<span class="order-last basis-full sm:order-none sm:basis-0 sm:flex-1">{item.name || 'Group session'} · {formatDateTime(item.start, data.timezone)}<span class="text-base-content/60">&nbsp;· {item.taken} of {item.capacity} places taken</span></span>
<a class="btn btn-ghost btn-xs ml-auto" href="/slots">Slots</a>
{:else}
<span class="badge badge-sm">⏱ Expires soon</span>
<span class="order-last basis-full sm:order-none sm:basis-0 sm:flex-1">{item.code} ({item.name}) · {item.left} {item.left === 1 ? 'session' : 'sessions'} left<span class="text-base-content/60">&nbsp;· expires {formatDateTime(item.expiresAt, data.timezone)}</span></span>
<a class="btn btn-ghost btn-xs ml-auto" href="/passes?q={encodeURIComponent(item.code)}">Vouchers & codes</a>
{/if}
</li>
{/each}
</ul>
<p class="mt-2 text-sm text-base-content/60">Sessions and codes in the next {dashboard.attentionDays} days.</p>
</section>
{/if}
<div class="mt-6 grid gap-6 xl:grid-cols-2"> <div class="mt-6 grid gap-6 xl:grid-cols-2">
<section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Income per month</h2>
<IncomeChart months={chartMonths} format={money} tickFormat={roundMoney} current={dashboard.thisMonth.month} />
</section>
<section class="rounded-box bg-base-100 p-5 shadow"> <section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Coming up</h2> <h2 class="mb-4 text-2xl font-bold">Coming up</h2>
{#if dashboard.upcoming.length} {#if dashboard.upcoming.length}
@ -57,9 +118,9 @@
{#each dashboard.upcoming as booking, i (i)} {#each dashboard.upcoming as booking, i (i)}
<li class="flex flex-wrap items-baseline gap-x-3 py-2"> <li class="flex flex-wrap items-baseline gap-x-3 py-2">
<span class="w-28 shrink-0 font-semibold">{dayLabel(booking.start)}</span> <span class="w-28 shrink-0 font-semibold">{dayLabel(booking.start)}</span>
<span class="w-24 shrink-0 tabular-nums">{timeLabel(booking.start)} · {formatDuration(booking.minutes)}</span> <span class="w-28 shrink-0 tabular-nums">{timeLabel(booking.start)} · {formatDuration(booking.minutes)}</span>
<span class="min-w-0 flex-1"> <span class="min-w-0 flex-1">
{booking.name}{#if booking.quantity > 1}<span class="text-base-content/60"> × {booking.quantity}</span>{/if} {booking.name}{#if booking.quantity > 1}<span class="text-base-content/60">&nbsp;× {booking.quantity}</span>{/if}
{#if booking.customer}<span class="block text-sm text-base-content/60">{booking.customer}</span>{/if} {#if booking.customer}<span class="block text-sm text-base-content/60">{booking.customer}</span>{/if}
</span> </span>
</li> </li>
@ -70,16 +131,44 @@
{/if} {/if}
<a class="btn btn-sm mt-4" href="/orders">All orders</a> <a class="btn btn-sm mt-4" href="/orders">All orders</a>
</section> </section>
</div>
<div class="mt-6 grid gap-6 xl:grid-cols-3">
<section class="rounded-box bg-base-100 p-5 shadow"> <section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">What sells</h2>
{@render salesTable(dashboard.sales, (row) => row.name, 'Nothing sold yet.')}
</section>
<section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Popular lengths</h2>
{@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')}
</section>
<section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Regulars</h2>
{#if dashboard.regulars.length}
<table class="table table-sm">
<thead><tr><th></th><th class="text-right">Orders</th><th class="text-right">Spent</th></tr></thead>
<tbody>
{#each dashboard.regulars as regular, i (i)}
<tr><td>{regular.name}</td><td class="text-right tabular-nums">{regular.orders}</td><td class="text-right tabular-nums">{money(regular.spent)}</td></tr>
{/each}
</tbody>
</table>
{:else}
<p class="text-base-content/60">Nobody has ordered more than once yet.</p>
{/if}
</section>
</div>
<p class="mt-2 text-sm text-base-content/60">What sells, popular lengths and regulars cover the last {dashboard.months.length} months.</p>
<section class="mt-6 rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Month by month</h2> <h2 class="mb-4 text-2xl font-bold">Month by month</h2>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table table-sm"> <table class="table table-sm">
<thead> <thead>
<tr><th>Month</th><th class="text-right">Orders</th><th class="text-right">Income</th><th class="text-right">Hours booked</th></tr> <tr><th>Month</th><th class="text-right">Orders</th><th class="text-right">Income</th><th class="text-right">Hours</th></tr>
</thead> </thead>
<tbody> <tbody>
{#each dashboard.months as row (row.month)} {#each [...dashboard.months].reverse() as row (row.month)}
<tr class={row.month === dashboard.thisMonth.month ? 'bg-primary/10' : ''}> <tr class={row.month === dashboard.thisMonth.month ? 'bg-primary/10' : ''}>
<td>{monthLabel(row.month)}</td> <td>{monthLabel(row.month)}</td>
<td class="text-right tabular-nums">{row.orders}</td> <td class="text-right tabular-nums">{row.orders}</td>
@ -91,4 +180,3 @@
</table> </table>
</div> </div>
</section> </section>
</div>

View file

@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
let { form } = $props(); let { form } = $props();
let submitting = $state(false); let submitting = $state(false);
let showPassword = $state(false);
</script> </script>
<svelte:head><title>Sign in | CMS</title></svelte:head> <svelte:head><title>Sign in | CMS</title></svelte:head>
@ -23,10 +24,16 @@
<!-- svelte-ignore a11y_autofocus --> <!-- svelte-ignore a11y_autofocus -->
<input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus /> <input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus />
</label> </label>
<label class="flex flex-col gap-1"> <div class="flex flex-col gap-1">
<span class="fieldset-legend p-0">Password</span> <label class="fieldset-legend p-0" for="password">Password</label>
<input class="input w-full" name="password" type="password" autocomplete="current-password" required /> <!-- DaisyUI's input wrapper: the field and the Show button share one box. -->
</label> <div class="input w-full pr-1">
<input class="grow" id="password" name="password" type={showPassword ? 'text' : 'password'} autocomplete="current-password" required />
<button class="btn btn-ghost btn-xs" type="button" aria-controls="password" aria-pressed={showPassword} onclick={() => (showPassword = !showPassword)}>
{showPassword ? 'Hide' : 'Show'}
</button>
</div>
</div>
</fieldset> </fieldset>
<button class="btn btn-primary w-full" type="submit" disabled={submitting}> <button class="btn btn-primary w-full" type="submit" disabled={submitting}>
{#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if} {#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if}