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
This commit is contained in:
agent 2026-10-27 08:54:57 +00:00
parent 312dc5ed3c
commit bdc040636a
8 changed files with 270 additions and 34 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) │ │ └── 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
│ │ ├── 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

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

View file

@ -0,0 +1,130 @@
// Figures for the admin dashboard (/): income from paid orders and the hours
// booked from their slot lines. 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.
import { zonedDateKey, zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb';
type Pb = ReturnType<typeof createPocketBase>;
/** How many months the month-by-month table shows, this one included. */
export const DASHBOARD_MONTHS = 12;
const UPCOMING_DAYS = 7;
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 };
type Booking = { 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')}`;
}
/** Bookings merged where they overlap or touch, sorted by start. */
function mergeBookings(bookings: Booking[]) {
const merged: Booking[] = [];
for (const booking of [...bookings].sort((a, b) => a.start - b.start)) {
const last = merged.at(-1);
if (last && booking.start <= last.end) last.end = Math.max(last.end, booking.end);
else merged.push({ ...booking });
}
return merged;
}
export async function loadDashboard(pb: Pb, timeZone: string, now = new Date()) {
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 [orders, lines] = await Promise.all([
pb
.collection('orders')
.getFullList({ filter: pb.filter("status = 'paid' && created >= {:from}", { from }), fields: 'total,created', requestKey: null })
.catch(() => []),
pb
.collection('order_lines')
.getFullList({
filter: pb.filter("lineType = 'slot' && order.status = 'paid' && start >= {:from}", { from }),
sort: 'start',
expand: 'order',
fields: 'name,start,minutes,quantity,expand.order.customerDetails',
requestKey: null
})
.catch(() => [])
]);
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));
if (!row) continue;
row.income += Number(order.total) || 0;
row.orders += 1;
}
const bookings: Booking[] = [];
for (const line of lines) {
const start = new Date(String(line.start).replace(' ', 'T')).getTime();
const minutes = Number(line.minutes) || 0;
if (!Number.isNaN(start) && minutes > 0) bookings.push({ start, end: start + minutes * 60_000 });
}
// Split at "now" so this month can show done vs. still to come.
let doneThisMonth = 0;
let aheadThisMonth = 0;
for (const { start, end } of mergeBookings(bookings)) {
const month = zonedDateKey(new Date(start).toISOString(), timeZone).slice(0, 7);
const row = byMonth.get(month);
if (!row) continue;
const minutes = (end - start) / 60_000;
row.minutes += minutes;
if (month === thisMonth) {
const done = Math.min(Math.max(now.getTime() - start, 0) / 60_000, minutes);
doneThisMonth += done;
aheadThisMonth += minutes - done;
}
}
const upcomingUntil = now.getTime() + UPCOMING_DAYS * DAY_MS;
const upcoming: UpcomingBooking[] = lines
.filter((line) => {
const start = new Date(String(line.start).replace(' ', 'T')).getTime();
const end = start + (Number(line.minutes) || 0) * 60_000;
return end > now.getTime() && 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
}));
const upcomingMinutes = mergeBookings(bookings).reduce(
(total, { start, end }) => total + Math.max(Math.min(end, upcomingUntil) - Math.max(start, now.getTime()), 0) / 60_000,
0
);
const year = thisMonth.slice(0, 4);
const monthRows = months.map((month) => byMonth.get(month)!);
const sum = (rows: DashboardMonth[], key: 'income' | 'minutes') => rows.reduce((total, row) => total + row[key], 0);
return {
thisMonth: byMonth.get(thisMonth)!,
lastMonth: byMonth.get(shiftMonth(thisMonth, -1))!,
incomeThisYear: sum(monthRows.filter((row) => row.month.startsWith(year)), 'income'),
minutesDoneThisMonth: Math.round(doneThisMonth),
minutesAheadThisMonth: Math.round(aheadThisMonth),
upcomingDays: UPCOMING_DAYS,
upcoming,
upcomingMinutes: Math.round(upcomingMinutes),
// Newest first, like the Orders list.
months: monthRows.reverse()
};
}

View file

@ -22,6 +22,10 @@
// Sidebar navigation, grouped by what the studio is doing. Labels are // Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names. // user-facing names; hrefs keep the original route names.
const navGroups = [ const navGroups = [
{
title: 'Studio',
links: [{ href: '/', label: 'Dashboard' }]
},
{ {
title: 'Website', title: 'Website',
links: [ links: [
@ -80,7 +84,7 @@
<label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu"> <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> <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> </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> </header>
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8"> <main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
{@render children()} {@render children()}
@ -90,7 +94,7 @@
<div class="drawer-side z-40"> <div class="drawer-side z-40">
<label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label> <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"> <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"> <nav class="flex-1" aria-label="Main">
<ul class="menu w-full gap-0.5 px-3"> <ul class="menu w-full gap-0.5 px-3">
{#each navGroups as group (group.title)} {#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,94 @@
<script lang="ts">
import { DISPLAY_LOCALE, formatInstant, formatPrice } 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);
// 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: 'short', day: 'numeric', month: 'short' });
const timeLabel = (value: string) => formatInstant(value, data.timezone, { hour: '2-digit', minute: '2-digit' });
let incomeChange = $derived(dashboard.thisMonth.income - dashboard.lastMonth.income);
</script>
<svelte:head><title>Dashboard | CMS</title></svelte:head>
<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; hours are booked appointment time, with group sessions counted once.</p>
</div>
<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
<div class="rounded-box bg-base-100 p-5 shadow">
<p class="text-sm text-base-content/60">Income in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}</p>
<p class="mt-1 text-3xl font-bold">{money(dashboard.thisMonth.income)}</p>
<p class="mt-1 text-sm text-base-content/60">
{incomeChange >= 0 ? '+' : '−'}{money(Math.abs(incomeChange))} on {monthLabel(dashboard.lastMonth.month, { month: 'long' })}
</p>
</div>
<div class="rounded-box bg-base-100 p-5 shadow">
<p class="text-sm text-base-content/60">Income in {dashboard.thisMonth.month.slice(0, 4)}</p>
<p class="mt-1 text-3xl font-bold">{money(dashboard.incomeThisYear)}</p>
<p class="mt-1 text-sm text-base-content/60">{dashboard.thisMonth.orders} {dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month</p>
</div>
<div class="rounded-box bg-base-100 p-5 shadow">
<p class="text-sm text-base-content/60">Hours worked in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}</p>
<p class="mt-1 text-3xl font-bold">{hours(dashboard.minutesDoneThisMonth)}</p>
<p class="mt-1 text-sm text-base-content/60">{hours(dashboard.minutesAheadThisMonth)} still booked this month</p>
</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 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">Coming up</h2>
{#if dashboard.upcoming.length}
<ul class="divide-y divide-base-300">
{#each dashboard.upcoming as booking, i (i)}
<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-24 shrink-0 tabular-nums">{timeLabel(booking.start)} · {formatDuration(booking.minutes)}</span>
<span class="min-w-0 flex-1">
{booking.name}{#if booking.quantity > 1}<span class="text-base-content/60"> × {booking.quantity}</span>{/if}
{#if booking.customer}<span class="block text-sm text-base-content/60">{booking.customer}</span>{/if}
</span>
</li>
{/each}
</ul>
{: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-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Month by month</h2>
<div class="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 booked</th></tr>
</thead>
<tbody>
{#each dashboard.months as row (row.month)}
<tr class={row.month === dashboard.thisMonth.month ? 'bg-primary/10' : ''}>
<td>{monthLabel(row.month)}</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>
</section>
</div>

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> <p class="text-base-content/60">The header, footer, colors and style shared by every page of the site.</p>
</div> </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}> <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="id" value={data.header.id} />
<input type="hidden" name="section" value="header" /> <input type="hidden" name="section" value="header" />

View file

@ -19,7 +19,7 @@ export const actions: Actions = {
return fail(400, { email, message: 'Invalid email or password.' }); return fail(400, { email, message: 'Invalid email or password.' });
} }
throw redirect(303, '/pages'); throw redirect(303, '/');
}, },
logout: async ({ locals }) => { logout: async ({ locals }) => {
locals.pb.authStore.clear(); locals.pb.authStore.clear();