Compare commits

..

4 commits

Author SHA1 Message Date
8076dd48ed Merge pull request 'Admin dashboard, Site design 2x2 grid, show password on login' (#25) from session/visual-tweaks into main
Reviewed-on: #25
2026-10-27 10:35:56 +01:00
05d8659685 Dashboard: coming up and needs attention first; year total on the chart
New order: Coming up (grouped by day) and Needs attention side by side
(stacked on a phone, with an all-clear message when empty), then the
income/hours tiles (two per row on a phone), then the income chart with
the year's total in its header and the month table folded under "Show as
table", then customers/regulars, what sells and popular lengths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gV9YDZk1XhjJ5LtyAt
2026-10-27 09:25:01 +00:00
2dc57fd27c 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
2026-10-27 09:14:27 +00:00
bdc040636a Admin: dashboard at / with income and hours; Site design 2x2 grid
The dashboard shows income (paid orders, by the month they were paid),
hours worked and still booked this month, the next 7 days' bookings and
a 12-month table. Booked time is counted with overlaps merged, so a
group session is one hour of work however many people booked it.
Login and the sidebar title now land on the dashboard.

Site design: four cards in a three-column grid left Style alone under
Header. Two columns on xl (Header|Footer, Colors|Style) and all four
side by side from 2xl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gV9YDZk1XhjJ5LtyAt
2026-10-27 08:54:57 +00:00
10 changed files with 621 additions and 38 deletions

View file

@ -25,6 +25,7 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts)
│ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
│ │ ├── +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
│ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events)
@ -143,12 +144,12 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### Styling
- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `font-sans` (body), `font-serif` (headings), chosen in Site design → Style (default DM Sans / Playfair Display).
- **Site design → Style** (`style` global: fonts, corners, text size, shadows, page width) becomes `--site-*` variables (`siteStyleVars` in `$shared/theme`) that the `@theme` tokens in both `app.css` files scale. So in public-site markup use the tokens — `rounded-xl`/`rounded-2xl`/`rounded-card`/`rounded-panel`, `shadow-sm`…`shadow-xl`, `max-w-3xl`/`6xl`/`7xl` — never `rounded-[2rem]` or an arbitrary `shadow-[…]`, which ignore the settings. Buttons, chips and icon buttons are `rounded-button` (a pill when Round, square when Sharp); only dots, avatars and badges stay `rounded-full`.
- Keep scrolling smooth: no `backdrop-blur` on public pages (it is redrawn on every scrolled frame; use a nearly solid background), and keep animations short. The `.reveal` / `.animate-fade-in` animations are switched off for people who ask for reduced motion and, by `scrollReveal.ts`, on devices that stutter (`plain-motion` on `<html>`, rules in both `app.css` files).
- Keep scrolling smooth: no `backdrop-blur` on public pages (it is redrawn on every scrolled frame; use a nearly solid background), and keep animations short. The `.reveal` / `.animate-fade-in` animations are switched off for people who ask for reduced motion and, by `scrollReveal.ts`, on devices that stutter (`plain-motion` on `<html>`, rules in both `app.css` files).
- Fonts are bundled `@fontsource-variable/*` packages, imported in each app's `src/lib/fonts.ts` and listed in `SITE_FONTS`; a new one goes in all three places.
- **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). Colours come from Site design via `$shared/theme`, rendered as a `<style>` in `<head>` (SSR, no flash): the admin gets only DaisyUI primary (= site Primary) and secondary (= site Accent) with auto-contrast text; `/preview` and the public site get all site colour variables. Never use `text-primary`/`text-secondary` for text — a light brand colour is unreadable as text; mark state with a tint/bar instead. Conventions:
- Section card: `rounded-box bg-base-100 p-5 shadow` with an `h2.text-2xl.font-bold` title (see Site design / globals).
- Form field: `<label class="fieldset"><span class="fieldset-legend">Label</span><input class="input w-full" /></label>`; hints in `<span class="label">`.
- Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker; in a narrow row (a phone) the label goes above (a `@container` query). More than about four choices don't fit a phone: use a slider (like the background Overlay).
- Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker; in a narrow row (a phone) the label goes above (a `@container` query). More than about four choices don't fit a phone: use a slider (like the background Overlay).
- Save results in editors: `$lib/admin/SaveStatus.svelte` (success fades out after a moment, an error stays).
- Images: always `$lib/admin/editors/ImagePicker.svelte` (choose, drag in or paste an image, or pick an uploaded one from the library: `MediaLibrary.svelte`, `/api/media`; address and alt text). It uploads to `media` through `/api/upload`; `withUrl={false}` + `altHint=""` + the `id` from `onChange` where a field stores a media relation (Services & products). Store only `url`/`alt` from `onChange` elsewhere.
- Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel).

View file

@ -30,7 +30,7 @@ export const handle: Handle = async ({ event, resolve }) => {
}
if (isLoginRoute && isAuthed && event.request.method === 'GET') {
throw redirect(303, '/pages');
throw redirect(303, '/');
}
const response = await resolve(event);

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

@ -0,0 +1,265 @@
// Figures for the admin dashboard (/). Months are calendar months in
// SITE_TIMEZONE.
//
// 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.
// Hours are the time covered by bookings, with overlaps counted once: 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 type { createPocketBase } from '$lib/pb';
import { listPasses } from '$lib/server/passes';
import { loadSlotDetails, seatsTaken } from '$lib/server/slots';
type Pb = ReturnType<typeof createPocketBase>;
/** How many months the month-by-month table and chart show, this one included. */
export const DASHBOARD_MONTHS = 12;
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;
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 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 Interval = { start: number; end: number };
/** `YYYY-MM` for `months` before (negative) or after `monthKey`. */
function shiftMonth(monthKey: string, months: number) {
const [year, month] = monthKey.split('-').map(Number);
const index = year * 12 + (month - 1) + months;
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`;
}
/** Epoch ms of a PocketBase date ('2026-10-27 09:00:00.000Z'), NaN if blank. */
const toMs = (value: unknown) => new Date(String(value || '').replace(' ', 'T')).getTime();
/** 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);
if (last && interval.start <= last.end) last.end = Math.max(last.end, interval.end);
else merged.push({ ...interval });
}
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()) {
const nowMs = now.getTime();
const thisMonth = zonedDateKey(now.toISOString(), timeZone).slice(0, 7);
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.
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, slotDetails, passes] = await Promise.all([
// Every paid order, so "new customer" means first order ever.
pb
.collection('orders')
.getFullList({ filter: "status = 'paid'", fields: 'id,email,total,created,customerDetails,emailError', requestKey: null })
.catch(() => []),
pb
.collection('order_lines')
.getFullList({
filter: pb.filter("order.status = 'paid' && (order.created >= {:from} || start >= {:from})", { from }),
sort: 'start',
expand: 'order',
fields: 'item,name,price,quantity,lineType,start,minutes,expand.order.created,expand.order.customerDetails',
requestKey: null
})
.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 }]));
// ── Income and customers ───────────────────────────────────────────
// 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.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++;
}
// ── 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) {
const created = line.expand?.order?.created;
if (!byMonth.has(monthOf(created))) continue;
const quantity = Number(line.quantity) || 1;
const income = (Number(line.price) || 0) * quantity;
const name = String(line.name || '');
const service = services.get(line.item) ?? { name, minutes: 0, count: 0, income: 0 };
service.count += quantity;
service.income += income;
services.set(line.item, service);
if (line.lineType === 'slot' && line.minutes) {
const key = `${line.item}:${line.minutes}`;
const length = lengths.get(key) ?? { name, minutes: Number(line.minutes), count: 0, income: 0 };
length.count += quantity;
length.income += income;
lengths.set(key, length);
}
}
// 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);
// ── 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
.filter((line) => {
if (line.lineType !== 'slot') return false;
const start = toMs(line.start);
return start + (Number(line.minutes) || 0) * 60_000 > nowMs && start < upcomingUntil;
})
.map((line) => ({
start: String(line.start),
minutes: Number(line.minutes) || 0,
name: String(line.name || ''),
customer: String(line.expand?.order?.customerDetails?.name || ''),
quantity: Number(line.quantity) || 1
}));
// Opened time this month (overlapping slots counted once) vs. booked time in it.
const slots = slotDetails?.slots ?? [];
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 monthRows = months.map((month) => byMonth.get(month)!);
return {
thisMonth: byMonth.get(thisMonth)!,
lastMonth: byMonth.get(shiftMonth(thisMonth, -1))!,
incomeThisYear: monthRows.filter((row) => row.month.startsWith(year)).reduce((total, row) => total + row.income, 0),
minutesDoneThisMonth: Math.round(minutesDoneThisMonth),
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,
upcoming,
upcomingMinutes: Math.round(minutesBetween(bookings, nowMs, upcomingUntil)),
newCustomers,
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

@ -22,6 +22,10 @@
// Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names.
const navGroups = [
{
title: 'Studio',
links: [{ href: '/', label: 'Dashboard' }]
},
{
title: 'Website',
links: [
@ -80,7 +84,7 @@
<label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu">
<svg xmlns="http://www.w3.org/2000/svg" class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16" /></svg>
</label>
<a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
<a class="ml-1 text-lg font-bold tracking-tight" href="/">Massage CMS</a>
</header>
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
{@render children()}
@ -90,7 +94,7 @@
<div class="drawer-side z-40">
<label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label>
<aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100">
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/">Massage CMS</a>
<nav class="flex-1" aria-label="Main">
<ul class="menu w-full gap-0.5 px-3">
{#each navGroups as group (group.title)}

View file

@ -0,0 +1,7 @@
import { env } from '$env/dynamic/private';
import { loadDashboard } from '$lib/server/dashboard';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => ({
dashboard: await loadDashboard(locals.pb, env.SITE_TIMEZONE || 'Europe/Oslo')
});

View file

@ -0,0 +1,215 @@
<script lang="ts">
import IncomeChart from '$lib/admin/IncomeChart.svelte';
import { DISPLAY_LOCALE, formatDateTime, formatInstant, formatPrice, zonedDateKey } from '$lib/calendar';
import { formatDuration } from '$shared/items';
let { data } = $props();
let dashboard = $derived(data.dashboard);
const hoursFormat = new Intl.NumberFormat(DISPLAY_LOCALE, { maximumFractionDigits: 1 });
const hours = (minutes: number) => `${hoursFormat.format(minutes / 60)} h`;
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.
const monthLabel = (month: string, options: Intl.DateTimeFormatOptions = { month: 'long', year: 'numeric' }) =>
formatInstant(`${month}-15T12:00:00Z`, data.timezone, options);
const dayLabel = (value: string) => formatInstant(value, data.timezone, { weekday: 'long', day: 'numeric', month: 'short' });
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 chartMonths = $derived(dashboard.months.map((m) => ({ ...m, label: monthLabel(m.month, { month: 'short' }), name: monthLabel(m.month) })));
let utilisationPercent = $derived(dashboard.utilisation ? Math.round((dashboard.utilisation.booked / dashboard.utilisation.open) * 100) : null);
let todayKey = $derived(zonedDateKey(new Date().toISOString(), data.timezone));
// Coming up, one group per day (bookings arrive sorted by start).
let upcomingDays = $derived.by(() => {
const days: { key: string; label: string; bookings: typeof dashboard.upcoming }[] = [];
for (const booking of dashboard.upcoming) {
const key = zonedDateKey(booking.start, data.timezone);
if (days.at(-1)?.key !== key) days.push({ key, label: dayLabel(booking.start), bookings: [] });
days.at(-1)!.bookings.push(booking);
}
return days;
});
</script>
<svelte:head><title>Dashboard | CMS</title></svelte:head>
{#snippet tile(label: string, value: string, note: string)}
<div class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<p class="text-sm text-base-content/60">{label}</p>
<p class="mt-1 text-2xl font-bold tabular-nums sm:text-3xl">{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">
<h1 class="text-3xl font-bold">Dashboard</h1>
<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>
<!-- What's next and what needs doing first; the figures follow. -->
<div class="grid gap-6 xl:grid-cols-2">
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-3 flex flex-wrap items-baseline justify-between gap-x-4">
<h2 class="text-2xl font-bold">Coming up</h2>
<p class="text-sm text-base-content/60">
Next {dashboard.upcomingDays} days: {dashboard.upcoming.length} {dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}, {hours(dashboard.upcomingMinutes)}
</p>
</div>
{#if upcomingDays.length}
<div class="space-y-4">
{#each upcomingDays as day (day.key)}
<div>
<h3 class="mb-1 text-sm font-semibold">{day.key === todayKey ? 'Today' : day.label}</h3>
<ul class="divide-y divide-base-300 rounded-box bg-base-200/60 px-3">
{#each day.bookings as booking, i (i)}
<li class="flex gap-3 py-2">
<span class="w-14 shrink-0 font-semibold tabular-nums">{timeLabel(booking.start)}</span>
<span class="min-w-0 flex-1">
<span class="block">{booking.name}{#if booking.quantity > 1}<span class="text-base-content/60">&nbsp;× {booking.quantity}</span>{/if}</span>
<span class="block text-sm text-base-content/60">{formatDuration(booking.minutes)}{#if booking.customer}&nbsp;· {booking.customer}{/if}</span>
</span>
</li>
{/each}
</ul>
</div>
{/each}
</div>
{:else}
<p class="text-base-content/60">Nothing booked in the next {dashboard.upcomingDays} days.</p>
{/if}
<a class="btn btn-sm mt-4" href="/orders">All orders</a>
</section>
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-3 flex flex-wrap items-baseline justify-between gap-x-4">
<h2 class="text-2xl font-bold">Needs attention</h2>
<p class="text-sm text-base-content/60">Sessions and codes: next {dashboard.attentionDays} days</p>
</div>
{#if dashboard.attention.length}
<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">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">{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">{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>
{:else}
<p class="text-base-content/60">✓ All clear: no failed emails, nearly full sessions or codes about to expire.</p>
{/if}
</section>
</div>
<div class="mt-6 grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
{@render tile(`Income in ${thisMonthName}`, money(dashboard.thisMonth.income), `${incomeChange >= 0 ? '+' : '−'}${money(Math.abs(incomeChange))} on ${monthLabel(dashboard.lastMonth.month, { month: 'long' })}`)}
{@render tile(`Hours worked in ${thisMonthName}`, hours(dashboard.minutesDoneThisMonth), `${hours(dashboard.minutesAheadThisMonth)} still booked`)}
{@render tile(
'Opened time booked',
utilisationPercent === null ? '—' : `${utilisationPercent} %`,
dashboard.utilisation ? `${hours(dashboard.utilisation.booked)} of ${hours(dashboard.utilisation.open)} in Slots this month` : 'No slots opened this month'
)}
{@render tile('Codes owed', money(dashboard.valueOutstanding), `${dashboard.codesOutstanding} ${dashboard.codesOutstanding === 1 ? 'code' : 'codes'} with sessions to book`)}
</div>
<section class="mt-6 rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-4 flex flex-wrap items-end justify-between gap-x-6 gap-y-2">
<div>
<h2 class="text-2xl font-bold">Income</h2>
<p class="text-sm text-base-content/60">Per month, last {dashboard.months.length} months</p>
</div>
<div class="sm:text-right">
<p class="text-sm text-base-content/60">Income in {dashboard.thisMonth.month.slice(0, 4)}</p>
<p class="text-2xl font-bold tabular-nums sm:text-3xl">{money(dashboard.incomeThisYear)}</p>
<p class="text-sm text-base-content/60">
{dashboard.thisMonth.orders} {dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month{#if dashboard.thisMonth.orders}, {money(dashboard.thisMonth.income / dashboard.thisMonth.orders)} on average{/if}
</p>
</div>
</div>
<IncomeChart months={chartMonths} format={money} tickFormat={roundMoney} current={dashboard.thisMonth.month} />
<details class="mt-2">
<summary class="cursor-pointer text-sm font-medium">Show as table</summary>
<div class="mt-2 overflow-x-auto">
<table class="table table-sm">
<thead>
<tr><th>Month</th><th class="text-right">Orders</th><th class="text-right">Income</th><th class="text-right">Hours</th></tr>
</thead>
<tbody>
{#each [...dashboard.months].reverse() as row (row.month)}
<tr class={row.month === dashboard.thisMonth.month ? 'bg-primary/10' : ''}>
<td>{monthLabel(row.month, { month: 'short', year: 'numeric' })}</td>
<td class="text-right tabular-nums">{row.orders}</td>
<td class="text-right tabular-nums">{money(row.income)}</td>
<td class="text-right tabular-nums">{hours(row.minutes)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
</details>
</section>
<div class="mt-6 grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<h2 class="mb-1 text-2xl font-bold">Customers</h2>
<p class="mb-3 text-sm text-base-content/60">
{dashboard.newCustomers + dashboard.returningCustomers} in {thisMonthName}: {dashboard.newCustomers} new, {dashboard.returningCustomers} returning
</p>
<h3 class="font-semibold">Regulars</h3>
{#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>
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<h2 class="mb-3 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-4 shadow sm:p-5">
<h2 class="mb-3 text-2xl font-bold">Popular lengths</h2>
{@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')}
</section>
</div>
<p class="mt-2 text-sm text-base-content/60">Regulars, what sells and popular lengths cover the last {dashboard.months.length} months.</p>

View file

@ -124,7 +124,7 @@
<p class="text-base-content/60">The header, footer, colors and style shared by every page of the site.</p>
</div>
<div class="grid gap-6 xl:grid-cols-3">
<div class="grid gap-6 xl:grid-cols-2 2xl:grid-cols-4">
<form class="flex flex-col rounded-box bg-base-100 p-5 shadow" method="POST" action="?/save" use:enhance={submit}>
<input type="hidden" name="id" value={data.header.id} />
<input type="hidden" name="section" value="header" />

View file

@ -1,28 +1,28 @@
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
login: async ({ request, locals }) => {
const data = await request.formData();
const email = String(data.get('email') || '');
const password = String(data.get('password') || '');
try {
try {
await locals.pb.collection('_superusers').authWithPassword(email, password);
} catch {
await locals.pb.collection('users').authWithPassword(email, password);
}
} catch {
// One line per failed attempt; the full SDK error object is noise here.
console.warn('Admin login failed for', email);
return fail(400, { email, message: 'Invalid email or password.' });
}
throw redirect(303, '/pages');
},
logout: async ({ locals }) => {
locals.pb.authStore.clear();
throw redirect(303, '/login');
}
};
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
login: async ({ request, locals }) => {
const data = await request.formData();
const email = String(data.get('email') || '');
const password = String(data.get('password') || '');
try {
try {
await locals.pb.collection('_superusers').authWithPassword(email, password);
} catch {
await locals.pb.collection('users').authWithPassword(email, password);
}
} catch {
// One line per failed attempt; the full SDK error object is noise here.
console.warn('Admin login failed for', email);
return fail(400, { email, message: 'Invalid email or password.' });
}
throw redirect(303, '/');
},
logout: async ({ locals }) => {
locals.pb.authStore.clear();
throw redirect(303, '/login');
}
};

View file

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