Compare commits
No commits in common. "8076dd48edb89ff43272f7cd17721539ab05493a" and "312dc5ed3c29e7a16f2b2f9181619026dac7a2f0" have entirely different histories.
8076dd48ed
...
312dc5ed3c
10 changed files with 38 additions and 621 deletions
|
|
@ -25,7 +25,6 @@ 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)
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export const handle: Handle = async ({ event, resolve }) => {
|
|||
}
|
||||
|
||||
if (isLoginRoute && isAuthed && event.request.method === 'GET') {
|
||||
throw redirect(303, '/');
|
||||
throw redirect(303, '/pages');
|
||||
}
|
||||
|
||||
const response = await resolve(event);
|
||||
|
|
|
|||
|
|
@ -1,84 +0,0 @@
|
|||
<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>
|
||||
|
|
@ -1,265 +0,0 @@
|
|||
// 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
|
||||
};
|
||||
}
|
||||
|
|
@ -22,10 +22,6 @@
|
|||
// 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: [
|
||||
|
|
@ -84,7 +80,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="/">Massage CMS</a>
|
||||
<a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
|
||||
</header>
|
||||
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
|
||||
{@render children()}
|
||||
|
|
@ -94,7 +90,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="/">Massage CMS</a>
|
||||
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">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)}
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
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')
|
||||
});
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
<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"> × {booking.quantity}</span>{/if}</span>
|
||||
<span class="block text-sm text-base-content/60">{formatDuration(booking.minutes)}{#if booking.customer} · {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"> · 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"> · {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"> · 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>
|
||||
|
|
@ -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-2 2xl:grid-cols-4">
|
||||
<div class="grid gap-6 xl:grid-cols-3">
|
||||
<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" />
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ export const actions: Actions = {
|
|||
return fail(400, { email, message: 'Invalid email or password.' });
|
||||
}
|
||||
|
||||
throw redirect(303, '/');
|
||||
throw redirect(303, '/pages');
|
||||
},
|
||||
logout: async ({ locals }) => {
|
||||
locals.pb.authStore.clear();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
<script lang="ts">
|
||||
let { form } = $props();
|
||||
let submitting = $state(false);
|
||||
let showPassword = $state(false);
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Sign in | CMS</title></svelte:head>
|
||||
|
|
@ -24,16 +23,10 @@
|
|||
<!-- svelte-ignore a11y_autofocus -->
|
||||
<input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus />
|
||||
</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>
|
||||
<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>
|
||||
</fieldset>
|
||||
<button class="btn btn-primary w-full" type="submit" disabled={submitting}>
|
||||
{#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue