From 00365165fe714e98eff5a98f866dbe6ccacf752b Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 26 Oct 2026 17:50:37 +0000 Subject: [PATCH 01/18] Public site on phones: basket lines, timeline, events calendar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Checkout: a basket line's quantity, price and remove button go on their own row under the description on a phone (a bundle's description was squeezed into a one-word column and the price ran into the ✕). - Timeline: cards stack in one column without the desktop overlap. - Events calendar: on a phone the grid shows thin coloured bars and a list of the month's events under it (name, dates, description, link); the hover box is desktop-only and opens leftwards on Thu–Sat so it stays on screen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- .../shared/src/blocks/CheckoutBlock.svelte | 79 ++++++++++--------- .../shared/src/blocks/TimelineBlock.svelte | 7 +- .../src/blocks/UpcomingCalendarBlock.svelte | 49 +++++++++--- 3 files changed, 83 insertions(+), 52 deletions(-) diff --git a/packages/shared/src/blocks/CheckoutBlock.svelte b/packages/shared/src/blocks/CheckoutBlock.svelte index 4e9bbe7..ec271bc 100644 --- a/packages/shared/src/blocks/CheckoutBlock.svelte +++ b/packages/shared/src/blocks/CheckoutBlock.svelte @@ -394,7 +394,8 @@ diff --git a/packages/shared/src/blocks/TimelineBlock.svelte b/packages/shared/src/blocks/TimelineBlock.svelte index 9673c9e..4d3a3a9 100644 --- a/packages/shared/src/blocks/TimelineBlock.svelte +++ b/packages/shared/src/blocks/TimelineBlock.svelte @@ -6,8 +6,9 @@ let items = $derived(data.items?.length ? data.items : [ { title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' } ]); + // Desktop only: cards alternate sides and overlap a little; on a phone they stack in one column. let widths = $derived(items.map((_: TimelineItem, i: number) => { - const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]']; + const opts = ['md:w-[78%]', 'md:w-[85%]', 'md:w-[90%]', 'md:w-[95%]', 'md:w-[98%]']; return opts[(i * 7 + 3) % opts.length]; })); @@ -19,9 +20,9 @@
{#each items as item, index} -
+
-
+

{item.title}

{item.description}

diff --git a/packages/shared/src/blocks/UpcomingCalendarBlock.svelte b/packages/shared/src/blocks/UpcomingCalendarBlock.svelte index 2749794..d59c7ec 100644 --- a/packages/shared/src/blocks/UpcomingCalendarBlock.svelte +++ b/packages/shared/src/blocks/UpcomingCalendarBlock.svelte @@ -4,6 +4,7 @@ dateKey, eventMatchesCategories, eventOverlapsDay, + eventOverlapsRange, eventRange, formatEventDateRange, getCurrentAndNextMonths, @@ -26,6 +27,12 @@ return visibleEvents.filter((event) => eventOverlapsDay(event, date)); } + // On a phone the grid only shows coloured bars; this list under it says what they are. + function eventsInMonth(days: { date: Date; inMonth: boolean }[]) { + const inMonth = days.filter((day) => day.inMonth); + return visibleEvents.filter((event) => eventOverlapsRange(event, inMonth[0].date, inMonth[inMonth.length - 1].date)); + } + function eventStyle(event: CalendarEventRecord) { return `--event-color: ${event.color || '#8a9a7b'};`; } @@ -42,10 +49,11 @@ return { showLabel: visualStart, classes: [ - visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3', - visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3', + // Continuing bars reach across the cell padding and the gap (p-1/p-2 + gap-1). + visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-2 sm:-ml-3', + visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-2 sm:-mr-3', visualStart && visualEnd ? 'mx-0' : '', - !visualStart && !visualEnd ? '-mx-3' : '' + !visualStart && !visualEnd ? '-mx-2 sm:-mx-3' : '' ].filter(Boolean).join(' ') }; } @@ -63,14 +71,14 @@ {:else}
{#each months as month} -
+

{month.label}

{#each weekdays as weekday}
{weekday}
{/each}
{#each month.days as day} -
+
{day.dayNumber}
@@ -81,7 +89,7 @@ {@const segment = segmentMeta(event, day.date)} {#if href} - {segment.showLabel ? event.name : '\u00a0'} - {:else} - {segment.showLabel ? event.name : '\u00a0'} -
{/each}
+ {#if eventsInMonth(month.days).length} +
    + {#each eventsInMonth(month.days) as event} + {@const href = normalizeLink(event.link)} +
  • + +
    + {#if href} + {event.name} + {:else} + {event.name} + {/if} + · {formatEventDateRange(event)} + {#if event.description}

    {event.description}

    {/if} +
    +
  • + {/each} +
+ {/if}
{/each}
From 382af282626882a891be4e322f42a3e9fefb1f42 Mon Sep 17 00:00:00 2001 From: agent Date: Mon, 26 Oct 2026 18:31:04 +0000 Subject: [PATCH 02/18] Admin on phones: Events page layout; Site design no wider than the screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Events: on a phone the month grid shows coloured bars (tap to edit) instead of names squeezed to one letter; arrows only for previous/next, so they share a row with the month; the event list shows the date under the name and drops the Date and Categories columns. - Site design: the ⓘ tooltips open downwards on a phone. Opening to the right, their hidden text stuck out past the screen and made the whole page scroll sideways. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- app-admin/src/routes/calendar/+page.svelte | 32 ++++++++++++---------- app-admin/src/routes/globals/+page.svelte | 2 +- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/app-admin/src/routes/calendar/+page.svelte b/app-admin/src/routes/calendar/+page.svelte index 2478d2d..a0b107e 100644 --- a/app-admin/src/routes/calendar/+page.svelte +++ b/app-admin/src/routes/calendar/+page.svelte @@ -100,24 +100,25 @@ {#if form?.message}{/if}
-
- -

{month.label}

- +
+ +

{month.label}

+
-
+
{#each weekdays as weekday}
{weekday}
{/each}
-
+ +
{#each month.days as day} -
+
{#each eventsForDay(day.date) as event} - {/each}
@@ -130,13 +131,16 @@

All events

- + {#each events as event (event.id)} - - - + + + diff --git a/app-admin/src/routes/globals/+page.svelte b/app-admin/src/routes/globals/+page.svelte index a34f31c..6e8e5ad 100644 --- a/app-admin/src/routes/globals/+page.svelte +++ b/app-admin/src/routes/globals/+page.svelte @@ -96,7 +96,7 @@ {/snippet} {#snippet info(text: string)} - +
NameDateCategoriesStatus
NameStatus
{event.name}{formatEventDateRange(event)}{event.categories.join(', ')} + {event.name} + {formatEventDateRange(event)} + {event.published ? 'Published' : 'Draft'}
+ + + + + {#each dashboard.months as row (row.month)} + + + + + + + {/each} + +
MonthOrdersIncomeHours booked
{monthLabel(row.month)}{row.orders}{money(row.income)}{hours(row.minutes)}
+
+ +
diff --git a/app-admin/src/routes/globals/+page.svelte b/app-admin/src/routes/globals/+page.svelte index ae1ce93..e0e515c 100644 --- a/app-admin/src/routes/globals/+page.svelte +++ b/app-admin/src/routes/globals/+page.svelte @@ -124,7 +124,7 @@

The header, footer, colors and style shared by every page of the site.

-
+
diff --git a/app-admin/src/routes/login/+page.server.ts b/app-admin/src/routes/login/+page.server.ts index 3062b49..bdd0aaf 100644 --- a/app-admin/src/routes/login/+page.server.ts +++ b/app-admin/src/routes/login/+page.server.ts @@ -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'); + } +}; From 2dc57fd27c481a61f0e2be159f84f8e2efd21cb3 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 27 Oct 2026 09:14:27 +0000 Subject: [PATCH 11/18] 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 Claude-Session: https://claude.ai/code/session_01HA82gV9YDZk1XhjJ5LtyAt --- AGENTS.md | 2 +- app-admin/src/lib/admin/IncomeChart.svelte | 84 +++++++ app-admin/src/lib/server/dashboard.ts | 245 ++++++++++++++++----- app-admin/src/routes/+page.svelte | 166 ++++++++++---- app-admin/src/routes/login/+page.svelte | 15 +- 5 files changed, 413 insertions(+), 99 deletions(-) create mode 100644 app-admin/src/lib/admin/IncomeChart.svelte diff --git a/AGENTS.md b/AGENTS.md index 1327b08..1a91d05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ └── 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, 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 │ │ ├── pages/ # Page CRUD + block editor │ │ ├── calendar/ # Event CRUD (menu label: Events) diff --git a/app-admin/src/lib/admin/IncomeChart.svelte b/app-admin/src/lib/admin/IncomeChart.svelte new file mode 100644 index 0000000..8fc4ab9 --- /dev/null +++ b/app-admin/src/lib/admin/IncomeChart.svelte @@ -0,0 +1,84 @@ + + +
+ + {#each ticks as tick (tick)} + + {tickFormat(tick)} + {/each} + {#each months as m, i (m.month)} + {@const x = pad.left + i * slot + (slot - barWidth) / 2} + + {#if i % labelEvery === (months.length - 1) % labelEvery || m.month === current} + {m.label} + {/if} + + (hovered = i)} + onpointerleave={() => (hovered = null)} + /> + {/each} + + {#if hovered !== null} + {@const m = months[hovered]} + {@const left = Math.min(Math.max(pad.left + hovered * slot + slot / 2, 70), width - 70)} +
+

{m.name}

+

{format(m.income)} · {m.orders} {m.orders === 1 ? 'order' : 'orders'}

+
+ {/if} +
diff --git a/app-admin/src/lib/server/dashboard.ts b/app-admin/src/lib/server/dashboard.ts index 6beeb3b..c63c9de 100644 --- a/app-admin/src/lib/server/dashboard.ts +++ b/app-admin/src/lib/server/dashboard.ts @@ -1,25 +1,42 @@ -// Figures for the admin dashboard (/): income from paid orders and the hours -// booked from their slot lines. Months are calendar months in SITE_TIMEZONE. +// 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. +// 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; -/** 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; 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 Booking = { start: number; end: number }; +type Interval = { start: number; end: number }; /** `YYYY-MM` for `months` before (negative) or after `monthKey`. */ 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')}`; } -/** 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)) { +/** 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 && booking.start <= last.end) last.end = Math.max(last.end, booking.end); - else merged.push({ ...booking }); + 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] = await Promise.all([ + const [orders, lines, slotDetails, passes] = await Promise.all([ + // Every paid order, so "new customer" means first order ever. pb .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(() => []), pb .collection('order_lines') .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', 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 }) - .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(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); + // ── 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(); + const regulars = new Map(); + 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) 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; + 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(); + 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 upcomingUntil = now.getTime() + UPCOMING_DAYS * DAY_MS; + // ── What sells (orders paid in the 12 months) ───────────────────────── + const services = new Map(); + const lengths = new Map(); + 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) => { - 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; + 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), @@ -107,24 +197,69 @@ export async function loadDashboard(pb: Pb, timeZone: string, now = new Date()) 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 - ); + // 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)!); - 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), + 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(upcomingMinutes), - // Newest first, like the Orders list. - months: monthRows.reverse() + 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 }; } diff --git a/app-admin/src/routes/+page.svelte b/app-admin/src/routes/+page.svelte index 026b7b4..e88543c 100644 --- a/app-admin/src/routes/+page.svelte +++ b/app-admin/src/routes/+page.svelte @@ -1,5 +1,6 @@ Dashboard | CMS +{#snippet tile(label: string, value: string, note: string)} +
+

{label}

+

{value}

+

{note}

+
+{/snippet} + +{#snippet salesTable(rows: typeof dashboard.sales, nameOf: (row: (typeof dashboard.sales)[number]) => string, empty: string)} + {#if rows.length} + + + + {#each rows as row, i (i)} + + {/each} + +
SoldIncome
{nameOf(row)}{row.count}{money(row.income)}
+ {:else} +

{empty}

+ {/if} +{/snippet} +

Dashboard

-

How the studio is doing. Income is paid orders; hours are booked appointment time, with group sessions counted once.

+

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.

-
-

Income in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}

-

{money(dashboard.thisMonth.income)}

-

- {incomeChange >= 0 ? '+' : '−'}{money(Math.abs(incomeChange))} on {monthLabel(dashboard.lastMonth.month, { month: 'long' })} -

-
-
-

Income in {dashboard.thisMonth.month.slice(0, 4)}

-

{money(dashboard.incomeThisYear)}

-

{dashboard.thisMonth.orders} {dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month

-
-
-

Hours worked in {monthLabel(dashboard.thisMonth.month, { month: 'long' })}

-

{hours(dashboard.minutesDoneThisMonth)}

-

{hours(dashboard.minutesAheadThisMonth)} still booked this month

-
-
-

Next {dashboard.upcomingDays} days

-

{dashboard.upcoming.length} {dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}

-

{hours(dashboard.upcomingMinutes)} of appointments

-
+ {@render tile(`Income in ${thisMonthName}`, money(dashboard.thisMonth.income), `${incomeChange >= 0 ? '+' : '−'}${money(Math.abs(incomeChange))} on ${monthLabel(dashboard.lastMonth.month, { month: 'long' })}`)} + {@render tile( + `Income in ${dashboard.thisMonth.month.slice(0, 4)}`, + money(dashboard.incomeThisYear), + `${dashboard.thisMonth.orders} ${dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month${dashboard.thisMonth.orders ? `, ${money(dashboard.thisMonth.income / dashboard.thisMonth.orders)} on average` : ''}` + )} + {@render tile(`Hours worked in ${thisMonthName}`, hours(dashboard.minutesDoneThisMonth), `${hours(dashboard.minutesAheadThisMonth)} still booked this month`)} + {@render tile( + 'Opened time booked', + utilisationPercent === null ? '—' : `${utilisationPercent} %`, + dashboard.utilisation ? `${hours(dashboard.utilisation.booked)} of ${hours(dashboard.utilisation.open)} opened in Slots this month` : 'No slots opened this month' + )} + {@render tile(`Next ${dashboard.upcomingDays} days`, `${dashboard.upcoming.length} ${dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}`, `${hours(dashboard.upcomingMinutes)} of appointments`)} + {@render tile(`Customers in ${thisMonthName}`, String(customersThisMonth), `${dashboard.newCustomers} new, ${dashboard.returningCustomers} returning`)} + {@render tile('Vouchers & codes owed', money(dashboard.valueOutstanding), `${dashboard.codesOutstanding} ${dashboard.codesOutstanding === 1 ? 'code' : 'codes'} with sessions still to book`)} + {@render tile('Needs attention', String(dashboard.attention.length), dashboard.attention.length ? 'See the list below' : 'Nothing right now')}
+{#if dashboard.attention.length} +
+

Needs attention

+
    + {#each dashboard.attention as item, i (i)} +
  • + {#if item.kind === 'email'} + ⚠ Email failed + Booking email for {item.customer}{#if item.created} · ordered {formatDateTime(item.created, data.timezone)}{/if} + Resend in Orders + {:else if item.kind === 'session'} + ◔ Nearly full + {item.name || 'Group session'} · {formatDateTime(item.start, data.timezone)} · {item.taken} of {item.capacity} places taken + Slots + {:else} + ⏱ Expires soon + {item.code} ({item.name}) · {item.left} {item.left === 1 ? 'session' : 'sessions'} left · expires {formatDateTime(item.expiresAt, data.timezone)} + Vouchers & codes + {/if} +
  • + {/each} +
+

Sessions and codes in the next {dashboard.attentionDays} days.

+
+{/if} +
+
+

Income per month

+ +
+

Coming up

{#if dashboard.upcoming.length} @@ -57,9 +118,9 @@ {#each dashboard.upcoming as booking, i (i)}
  • {dayLabel(booking.start)} - {timeLabel(booking.start)} · {formatDuration(booking.minutes)} + {timeLabel(booking.start)} · {formatDuration(booking.minutes)} - {booking.name}{#if booking.quantity > 1} × {booking.quantity}{/if} + {booking.name}{#if booking.quantity > 1} × {booking.quantity}{/if} {#if booking.customer}{booking.customer}{/if}
  • @@ -70,25 +131,52 @@ {/if} All orders
    +
    +
    -

    Month by month

    -
    +

    What sells

    + {@render salesTable(dashboard.sales, (row) => row.name, 'Nothing sold yet.')} +
    +
    +

    Popular lengths

    + {@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')} +
    +
    +

    Regulars

    + {#if dashboard.regulars.length} - - - + - {#each dashboard.months as row (row.month)} - - - - - - + {#each dashboard.regulars as regular, i (i)} + {/each}
    MonthOrdersIncomeHours booked
    OrdersSpent
    {monthLabel(row.month)}{row.orders}{money(row.income)}{hours(row.minutes)}
    {regular.name}{regular.orders}{money(regular.spent)}
    -
    + {:else} +

    Nobody has ordered more than once yet.

    + {/if}
    +

    What sells, popular lengths and regulars cover the last {dashboard.months.length} months.

    + +
    +

    Month by month

    +
    + + + + + + {#each [...dashboard.months].reverse() as row (row.month)} + + + + + + + {/each} + +
    MonthOrdersIncomeHours
    {monthLabel(row.month)}{row.orders}{money(row.income)}{hours(row.minutes)}
    +
    +
    diff --git a/app-admin/src/routes/login/+page.svelte b/app-admin/src/routes/login/+page.svelte index e8d1682..c8be39a 100644 --- a/app-admin/src/routes/login/+page.svelte +++ b/app-admin/src/routes/login/+page.svelte @@ -1,6 +1,7 @@ Sign in | CMS @@ -23,10 +24,16 @@ - +
    + + +
    + + +
    +
    -
    -
    -

    What sells

    - {@render salesTable(dashboard.sales, (row) => row.name, 'Nothing sold yet.')} -
    -
    -

    Popular lengths

    - {@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')} -
    -
    -

    Regulars

    +
    + {@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`)} +
    + +
    +
    +
    +

    Income

    +

    Per month, last {dashboard.months.length} months

    +
    +
    +

    Income in {dashboard.thisMonth.month.slice(0, 4)}

    +

    {money(dashboard.incomeThisYear)}

    +

    + {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} +

    +
    +
    + +
    + Show as table +
    + + + + + + {#each [...dashboard.months].reverse() as row (row.month)} + + + + + + + {/each} + +
    MonthOrdersIncomeHours
    {monthLabel(row.month, { month: 'short', year: 'numeric' })}{row.orders}{money(row.income)}{hours(row.minutes)}
    +
    +
    +
    + +
    +
    +

    Customers

    +

    + {dashboard.newCustomers + dashboard.returningCustomers} in {thisMonthName}: {dashboard.newCustomers} new, {dashboard.returningCustomers} returning +

    +

    Regulars

    {#if dashboard.regulars.length} @@ -157,26 +203,13 @@

    Nobody has ordered more than once yet.

    {/if} +
    +

    What sells

    + {@render salesTable(dashboard.sales, (row) => row.name, 'Nothing sold yet.')} +
    +
    +

    Popular lengths

    + {@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')} +
    -

    What sells, popular lengths and regulars cover the last {dashboard.months.length} months.

    - -
    -

    Month by month

    -
    -
    OrdersSpent
    - - - - - {#each [...dashboard.months].reverse() as row (row.month)} - - - - - - - {/each} - -
    MonthOrdersIncomeHours
    {monthLabel(row.month)}{row.orders}{money(row.income)}{hours(row.minutes)}
    -
    -
    +

    Regulars, what sells and popular lengths cover the last {dashboard.months.length} months.

    From d62799f263646268829f0799a3d0c5dd457629cc Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 3 Nov 2026 09:10:16 +0000 Subject: [PATCH 13/18] PocketBase: switch image to elestio/pocketbase v0.23.12 spectado/pocketbase has been removed from Docker Hub. elestio publishes the same PocketBase version (0.23.12), so schema, migrations and hooks are unchanged. The image differs in packaging: - listens on 8090 instead of 80 (Caddyfile, POCKETBASE_INTERNAL_URL) - runs as non-root user `pocketbase` (uid 100), so pb_data written by the old root-run image needs a one-off chown; README documents it - pinned by digest as well as tag Tested: copy of an existing pb_data volume, README chown command via podman-compose, then the full stack (public page renders, admin and db routes via Caddy, shop hooks respond). A fresh volume also works. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gX7xH4zwYTr5vE7mf8 --- AGENTS.md | 6 +++--- Caddyfile | 2 +- README.md | 15 ++++++++++++++- docker-compose.yml | 13 +++++++++---- 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1a91d05..fa3796a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Stack - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). +- **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`, image `elestio/pocketbase`, digest-pinned; runs as non-root uid 100 on port 8090), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). @@ -82,7 +82,7 @@ Caddyfile # Subdomain-based routing Caddy routes by `Host` header — no path stripping: - `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app) -- `db.{$DOMAIN}:8080` → `pocketbase:80` (redirects `/` to `/_/`) +- `db.{$DOMAIN}:8080` → `pocketbase:8090` (redirects `/` to `/_/`) - `www.{$DOMAIN}:8080`, `*.{$DOMAIN}:8080` → `app-public:3000` (public app) For local dev, `DOMAIN` defaults to `localhost`, so Caddy serves `admin.localhost:8080`, `db.localhost:8080`, `www.localhost:8080`. Caddy's `.localhost` handling works without DNS or hosts-file changes. @@ -193,7 +193,7 @@ cd app-public && npm run build - `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`. - `URL_SCHEME` (default `http`), `URL_PORT` (default `:8080`; set it empty for no port) — build every browser-facing URL below as `://.`. They must match the address bar exactly: a mismatched `ORIGIN` makes SvelteKit reject form POSTs (admin login) with "Cross-site POST form submissions are forbidden". Behind a TLS reverse proxy: `URL_SCHEME=https`, `URL_PORT=`. (podman-compose 1.5 can't do nested `${A:-${B}}` defaults, hence two flat variables.) - `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`://db.${DOMAIN}`). Set in `docker-compose.yml`. -- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`. +- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:8090`). Set in `docker-compose.yml`. - `ORIGIN` — SvelteKit origin for SSR. Differs per app: `://admin.${DOMAIN}` (admin), `://www.${DOMAIN}` (public). - `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`://www.${DOMAIN}`). - `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `EMAIL_FROM`, `EMAIL_FROM_NAME` — Brevo SMTP relay for booking emails (both apps). Empty `SMTP_HOST` = log emails instead of sending. diff --git a/Caddyfile b/Caddyfile index 5a4f529..9959c35 100644 --- a/Caddyfile +++ b/Caddyfile @@ -18,7 +18,7 @@ {$CADDY_SCHEME}://db.{$DOMAIN}:8080 { # PocketBase admin UI lives at /_/ — redirect bare root there. redir / /_/{path} - reverse_proxy pocketbase:80 + reverse_proxy pocketbase:8090 } {$CADDY_SCHEME}://www.{$DOMAIN}:8080, {$CADDY_SCHEME}://*.{$DOMAIN}:8080 { diff --git a/README.md b/README.md index 48606f9..e980d96 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Subsequent builds reuse the npm cache declared in each app's `Dockerfile`. The app containers use two PocketBase URLs: -- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app containers when using the included `spectado/pocketbase` image. +- `POCKETBASE_INTERNAL_URL=http://pocketbase:8090` for server-side SvelteKit calls from the app containers (the `elestio/pocketbase` image listens on 8090). - `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain. ## PocketBase setup @@ -88,6 +88,19 @@ The app containers use two PocketBase URLs: If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. +### Switching PocketBase image (existing installs) + +The PocketBase image changed from `spectado/pocketbase:0.23.12` (removed from Docker Hub) to `elestio/pocketbase:v0.23.12`. It is the same PocketBase version, so the schema, migrations and hooks are unchanged, but the new image runs as a non-root `pocketbase` user (uid 100) and listens on port 8090. Files the old image wrote are owned by root, and PocketBase refuses to start on them (`attempt to write a readonly database`). Fix the ownership once, before the first start on the new image: + +```sh +docker compose stop pocketbase +# back up first: the volume is _pocketbase (see `docker volume ls`) +docker compose run --rm --no-deps --user root --entrypoint chown pocketbase -R pocketbase:pocketbase /pb_data +docker compose up -d +``` + +Fresh installs need nothing: a new volume is created with the right owner. + ### Migrations `pocketbase/pb_migrations/` is mounted into the PocketBase container, which applies any new migration once when it starts (`docker compose up` / restart). The first one (`1791244800_lock_rules_dates_unique.js`) closes public sign-up on the `users` collection, makes order/basket writes superuser-only, adds `created`/`updated` dates and unique slug/key indexes. On an existing install, check the PocketBase log after restarting — if duplicate page slugs or global keys exist, the unique index is skipped with a log line. `1791331200_lock_order_lines.js` makes `order_lines` writes superuser-only (they were public). diff --git a/docker-compose.yml b/docker-compose.yml index 881482d..6c336ae 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,12 +3,17 @@ services: # Pinned: schema (pb_schema.json) and migrations target this version's # format/JS API. Upgrade deliberately — read the PocketBase changelog, # back up pb_data, then bump the tag and test migrations locally. - image: docker.io/spectado/pocketbase:0.23.12 + # Digest-pinned too, so a re-pushed tag can't change what runs. + # This image runs as a non-root `pocketbase` user (uid 100) on port 8090 + # and finds /pb_migrations and /pb_hooks next to /pb_data by default. + # Data written by the old root-run image (spectado/pocketbase, now gone) + # must be chown'ed once — see the README's "Switching PocketBase image". + image: docker.io/elestio/pocketbase:v0.23.12@sha256:e8c375d4fd50c4ee2f2922361392ba7c6b16c4d5df39bfc7cf2372af2bc3305e container_name: massage-pocketbase restart: unless-stopped # Internal only — accessed via the caddy reverse proxy expose: - - "80" + - "8090" volumes: - pocketbase:/pb_data # Versioned schema changes; PocketBase applies pending ones on start. @@ -33,7 +38,7 @@ services: - pocketbase environment: PORT: 3001 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 + POCKETBASE_INTERNAL_URL: http://pocketbase:8090 # Browser-facing URLs. They must match the address bar exactly, or # SvelteKit rejects logins/forms ("Cross-site POST form submissions are # forbidden"). Behind a TLS proxy: URL_SCHEME=https and URL_PORT= (empty). @@ -64,7 +69,7 @@ services: - pocketbase environment: PORT: 3000 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 + POCKETBASE_INTERNAL_URL: http://pocketbase:8090 PUBLIC_POCKETBASE_URL: ${URL_SCHEME:-http}://db.${DOMAIN:-localhost}${URL_PORT-:8080} ORIGIN: ${URL_SCHEME:-http}://www.${DOMAIN:-localhost}${URL_PORT-:8080} # No PocketBase or Stripe secrets here: shop writes happen in PocketBase From dc8c58f4c237ca46cd0a6b9d0e278947da5ee7c2 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 3 Nov 2026 09:43:49 +0000 Subject: [PATCH 14/18] Schema: explicit size limits on JSON fields pb_schema.json had six JSON field limits under `options.maxSize`, which PocketBase ignores since 0.23, so those fields used PocketBase's default. That default dropped to 1MB in 0.29: on 0.40 a 1.5MB page that 0.23 saved is refused. Move the limits to the field's top level and add a migration that sets them on existing installs (pages/email blocks 2MB, globals 1MB, event categories 200KB, customer details 100KB). Tested on 0.40.6: existing install (migration applied, 1.5MB page saves, 2.5MB refused at 2MB) and fresh install + pb_schema.json import; both end with identical schemas. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gX7xH4zwYTr5vE7mf8 --- pb_schema.json | 18 +++---- .../1793400000_json_field_limits.js | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 pocketbase/pb_migrations/1793400000_json_field_limits.js diff --git a/pb_schema.json b/pb_schema.json index 9cfcc85..4ae6c9e 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -47,9 +47,7 @@ "required": false, "presentable": false, "unique": false, - "options": { - "maxSize": 2000000 - } + "maxSize": 2000000 }, { "id": "bool_published", @@ -103,9 +101,7 @@ "required": false, "presentable": false, "unique": false, - "options": { - "maxSize": 1000000 - } + "maxSize": 1000000 }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} @@ -279,9 +275,7 @@ "required": false, "presentable": false, "unique": false, - "options": { - "maxSize": 200000 - } + "maxSize": 200000 }, { "id": "bool_eventpub", @@ -388,7 +382,7 @@ { "id": "sel_basketstat0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["active", "completed", "abandoned"] }, { "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, - { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, + { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "maxSize": 100000 }, { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, { "id": "rel_basketpass01", "name": "pass", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_passes00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, @@ -449,7 +443,7 @@ { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, - { "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, + { "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "maxSize": 100000 }, { "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] }, { "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, @@ -515,7 +509,7 @@ { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "text_etplkey0001", "name": "key", "type": "text", "system": false, "required": true, "presentable": true, "unique": true, "options": { "min": null, "max": 80, "pattern": "" } }, { "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } }, - { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } }, + { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "maxSize": 2000000 }, { "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, { "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, diff --git a/pocketbase/pb_migrations/1793400000_json_field_limits.js b/pocketbase/pb_migrations/1793400000_json_field_limits.js new file mode 100644 index 0000000..6b47e7a --- /dev/null +++ b/pocketbase/pb_migrations/1793400000_json_field_limits.js @@ -0,0 +1,47 @@ +/// + +// Give every JSON field an explicit size limit. +// +// pb_schema.json used to put these limits under `options.maxSize`, which +// PocketBase has ignored since 0.23, so the fields below had no limit of +// their own and fell back to PocketBase's default. That default dropped from +// several MB to 1MB in PocketBase 0.29: a page's blocks over 1MB that saved +// on 0.23 are refused on 0.40 ("The maximum allowed JSON size is 1048576 +// bytes"). Real pages are far smaller (the largest in the backups is ~17KB), +// but the limit should be the one we chose, not whatever the default is. +// +// Only the limit changes; nothing is rewritten. A limit is checked when a +// record is saved, so existing data is not affected. + +const LIMITS = [ + ['pages', 'blocks', 2000000], + ['email_templates', 'blocks', 2000000], + ['globals', 'data', 1000000], + ['events', 'categories', 200000], + ['baskets', 'customerDetails', 100000], + ['orders', 'customerDetails', 100000] +]; + +function setLimits(app, size) { + for (const [name, fieldName, limit] of LIMITS) { + let collection; + try { + collection = app.findCollectionByNameOrId(name); + } catch (e) { + continue; // fresh install: pb_schema.json (already with these limits) is imported later + } + const field = collection.fields.getByName(fieldName); + if (!field || field.type() !== 'json') continue; + field.maxSize = size === undefined ? limit : size; + try { + app.save(collection); + } catch (e) { + console.log(`[migration] could not set the size limit on ${name}.${fieldName}: ${e}`); + } + } +} + +migrate( + (app) => setLimits(app), + (app) => setLimits(app, 0) +); From 5e2db31b5e6a10f1191d86c31e18f37c59ec5fe5 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 3 Nov 2026 09:43:49 +0000 Subject: [PATCH 15/18] PocketBase 0.40.6, JS SDK 0.28.2; fresh-install steps for the new dashboard - docker-compose: elestio/pocketbase v0.40.6, digest-pinned (same port, user and layout as v0.23.12) - pocketbase SDK ^0.28.2 in both apps and packages/shared (0.27/0.28 are additions and pb.filter() fixes, nothing breaking) - README: setup steps rewritten for the 0.40 dashboard: install link from the log, and tick "Merge with the existing collections" on schema import (the default deletes `users`); an upgrade section (back up first, data upgrade is one-way, what changed) - AGENTS.md: versions; field settings go at the top level, not `options` Compared with main (0.23.12 + SDK 0.26) on copies of real data: admin and public page text, image upload, import of all three backups, the shop flow via hooks, Stripe webhook signatures, and a fresh install with pb_schema.json import all behave the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gX7xH4zwYTr5vE7mf8 --- AGENTS.md | 4 ++-- README.md | 26 +++++++++++++++++--------- app-admin/package-lock.json | 8 ++++---- app-admin/package.json | 2 +- app-public/package-lock.json | 8 ++++---- app-public/package.json | 2 +- docker-compose.yml | 2 +- packages/shared/package.json | 2 +- 8 files changed, 31 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fa3796a..7cc611e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Stack - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`, image `elestio/pocketbase`, digest-pinned; runs as non-root uid 100 on port 8090), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). +- **PocketBase** — server pinned to **0.40.6** (`docker-compose.yml`, image `elestio/pocketbase`, digest-pinned; runs as non-root uid 100 on port 8090), REST API via the `pocketbase` SDK (v0.28). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). @@ -134,7 +134,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled); commerce: `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`, `passes` (bundle/voucher codes) - Server load functions use `locals.pb.collection('pages').getFirstListItem()` - **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them). -- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. +- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Field settings go at the field's top level (`"maxSize": 2000000`), never under `options`: PocketBase has ignored `options` since 0.23. Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. - **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. - **Slot availability** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*. - **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email`, `passes.email`/`recipientName`/`message` and (during checkout) `baskets` / `basket_lines.giftTo`/`giftMessage`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*. diff --git a/README.md b/README.md index e980d96..4210614 100644 --- a/README.md +++ b/README.md @@ -78,15 +78,13 @@ The app containers use two PocketBase URLs: ## PocketBase setup -1. Open `http://db.localhost:8080/_/`. -2. Create the first PocketBase admin user when prompted. -3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below. -4. Create starter records: - - `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. - - `globals`: key `header`, data matching the header JSON in the project prompt. - - `globals`: key `footer`, data matching the footer JSON in the project prompt. +A fresh install, once the stack is up (written for the PocketBase 0.40 dashboard): -If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. +1. **Create the first superuser.** PocketBase prints a one-time install link in its log (`docker compose logs pocketbase`): `http://0.0.0.0:8090/_/#/pbinstall/`. Open it with `http://0.0.0.0:8090` replaced by the address you reach PocketBase at, e.g. `http://db.localhost:8080/_/#/pbinstall/`. +2. **Import the schema.** In the dashboard: **Settings → Import collections → Load from JSON file**, choose `pb_schema.json`, and **tick "Merge with the existing collections"**. It is off by default, and without it the import deletes every collection that isn't in the file, including `users` (so nobody but superusers could sign in to the admin). Review, then **Confirm and import**. `PUT /api/collections/import` with `"deleteMissing": false` does the same. +3. **Add content.** Sign in to the admin app and import a site from `backups/` under **Backup → Import** (see `backups/README.md`), or start from empty: pages are created under **Pages**, and **Site design** creates its own records the first time it is opened. + +The migrations in `pocketbase/pb_migrations/` already ran when PocketBase first started (before the collections existed, so they skipped); the imported `pb_schema.json` is the end state they lead to. On that first start the privacy cron also logs `[privacy] retention at startup failed: … no rows in result set`, because the collections don't exist yet; it is harmless and gone from the next start. ### Switching PocketBase image (existing installs) @@ -101,6 +99,16 @@ docker compose up -d Fresh installs need nothing: a new volume is created with the right owner. +### Upgrading to PocketBase 0.40 (existing installs) + +PocketBase went from 0.23.12 to 0.40.6 (same image, same port and user, so nothing above changes). On its first start 0.40 upgrades `pb_data` in place, and that can't be undone by going back to the old image: **back up `pb_data` first**, and to roll back, restore that backup. Coming from the spectado image, do the `chown` above too. + +What changed for this project: + +- **JSON field limits.** PocketBase's default limit for JSON fields fell to 1MB in 0.29, and six of ours had relied on it (their limits were under `options` in `pb_schema.json`, which PocketBase ignores). Migration `1793400000_json_field_limits.js` sets them explicitly (page and email blocks 2MB, site design 1MB, …). Real pages are far below that. +- **New dashboard** at `db.…/_/` (rewritten in 0.37); the setup steps above describe it. +- Downloads now send a quoted filename (`filename="photo.jpg"`); nothing here depends on it. + ### Migrations `pocketbase/pb_migrations/` is mounted into the PocketBase container, which applies any new migration once when it starts (`docker compose up` / restart). The first one (`1791244800_lock_rules_dates_unique.js`) closes public sign-up on the `users` collection, makes order/basket writes superuser-only, adds `created`/`updated` dates and unique slug/key indexes. On an existing install, check the PocketBase log after restarting — if duplicate page slugs or global keys exist, the unique index is skipped with a log line. `1791331200_lock_order_lines.js` makes `order_lines` writes superuser-only (they were public). @@ -134,7 +142,7 @@ Commerce collections (see the Stripe section above for context): - `passes` — bundle/voucher codes: `code` text (unique, 8 characters, shown as `ABCD-2345`), `item` relation→items (the bundle), `order` relation→orders (empty when issued in the admin), `name` text, `parts` json (snapshot: `[{ item, name, minutes, count, value }]`, `value` = the part's share of the price), `email` text (buyer), `recipientName` / `message` text, `expiresAt` date, `status` select `active|void`, `anonymisedAt` date. What's used is never stored — see *Bundles and codes* - `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool -> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Field config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`, number `min`/`max`/`onlyInt`) belongs at the field top level — 0.23 silently ignores anything nested under `options`, so the older number/text fields that still use `options` get no min/max on a fresh install. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass. +> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Field config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`, number `min`/`max`/`onlyInt`) belongs at the field top level — 0.23 silently ignores anything nested under `options`, so the older number/text fields that still use `options` get no min/max on a fresh install (the JSON fields' `maxSize` has been moved up; see *Upgrading to PocketBase 0.40*). Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass; keep *Merge with the existing collections* ticked (`deleteMissing: false`), or `users` is deleted. ## Authentication diff --git a/app-admin/package-lock.json b/app-admin/package-lock.json index 1d5dcc8..74f454d 100644 --- a/app-admin/package-lock.json +++ b/app-admin/package-lock.json @@ -20,7 +20,7 @@ "@tiptap/starter-kit": "^3.23.4", "daisyui": "^5.5.19", "nodemailer": "^10.0.12", - "pocketbase": "^0.26.9", + "pocketbase": "^0.28.2", "svelte-tiptap": "^3.0.1", "tailwindcss": "^4.3.0", "uuid": "^14.0.0" @@ -2499,9 +2499,9 @@ } }, "node_modules/pocketbase": { - "version": "0.26.9", - "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.26.9.tgz", - "integrity": "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.28.2.tgz", + "integrity": "sha512-5lS4g7iDZi90LxLai8kyUK4r5u1GkEAoZ3yuzTEFX97FyDQAoEmXWbTqf+pYA1hz5e/icBQu1MCUjM/9V8mitg==", "license": "MIT" }, "node_modules/postcss": { diff --git a/app-admin/package.json b/app-admin/package.json index 3b8027e..8131a9d 100644 --- a/app-admin/package.json +++ b/app-admin/package.json @@ -48,7 +48,7 @@ "@tiptap/starter-kit": "^3.23.4", "daisyui": "^5.5.19", "nodemailer": "^10.0.12", - "pocketbase": "^0.26.9", + "pocketbase": "^0.28.2", "svelte-tiptap": "^3.0.1", "tailwindcss": "^4.3.0", "uuid": "^14.0.0" diff --git a/app-public/package-lock.json b/app-public/package-lock.json index f246f5d..556d953 100644 --- a/app-public/package-lock.json +++ b/app-public/package-lock.json @@ -13,7 +13,7 @@ "@tailwindcss/vite": "^4.3.0", "daisyui": "^5.5.19", "nodemailer": "^10.0.12", - "pocketbase": "^0.26.9", + "pocketbase": "^0.28.2", "tailwindcss": "^4.3.0" }, "devDependencies": { @@ -1964,9 +1964,9 @@ } }, "node_modules/pocketbase": { - "version": "0.26.9", - "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.26.9.tgz", - "integrity": "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.28.2.tgz", + "integrity": "sha512-5lS4g7iDZi90LxLai8kyUK4r5u1GkEAoZ3yuzTEFX97FyDQAoEmXWbTqf+pYA1hz5e/icBQu1MCUjM/9V8mitg==", "license": "MIT" }, "node_modules/postcss": { diff --git a/app-public/package.json b/app-public/package.json index 2888865..0f8b1d3 100644 --- a/app-public/package.json +++ b/app-public/package.json @@ -40,7 +40,7 @@ "@tailwindcss/vite": "^4.3.0", "daisyui": "^5.5.19", "nodemailer": "^10.0.12", - "pocketbase": "^0.26.9", + "pocketbase": "^0.28.2", "tailwindcss": "^4.3.0" } } diff --git a/docker-compose.yml b/docker-compose.yml index 6c336ae..8d991c8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ services: # and finds /pb_migrations and /pb_hooks next to /pb_data by default. # Data written by the old root-run image (spectado/pocketbase, now gone) # must be chown'ed once — see the README's "Switching PocketBase image". - image: docker.io/elestio/pocketbase:v0.23.12@sha256:e8c375d4fd50c4ee2f2922361392ba7c6b16c4d5df39bfc7cf2372af2bc3305e + image: docker.io/elestio/pocketbase:v0.40.6@sha256:936756ccefb13cedaf2e7c49745412455bc81f2d1a511132f4012e411b970437 container_name: massage-pocketbase restart: unless-stopped # Internal only — accessed via the caddy reverse proxy diff --git a/packages/shared/package.json b/packages/shared/package.json index 700f658..0e1c732 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -19,7 +19,7 @@ "dependencies": { "@stripe/stripe-js": "^9.12.1", "nodemailer": "^10.0.12", - "pocketbase": "^0.26.9" + "pocketbase": "^0.28.2" }, "devDependencies": { "@types/nodemailer": "^8.0.2" From e896fd3c99b34db3e1c554cb44c7feca36461af5 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 4 Nov 2026 22:36:50 +0000 Subject: [PATCH 16/18] Shop: item priority, block sort order and an optional "Sort by" menu - items.priority (migration + pb_schema.json): Recommended order in Shop blocks, higher first, then by name. Set under Services & products, which now lists items in that order. - Shop block: choose its order (Recommended, Most popular, price up/down, name) and optionally let visitors re-sort with a "Sort by" menu. sortItems() in shared/items.ts is the one place items are ordered. - Most popular: GET /api/shop/popular returns item ids by units sold in paid orders over the last 90 days (ids only, no sales figures). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gWt7pNdAsocjxujY3m --- AGENTS.md | 1 + README.md | 5 ++- app-admin/src/lib/admin/blockDefaults.ts | 4 +- .../lib/admin/editors/ShopBlockEditor.svelte | 22 +++++++++- app-admin/src/routes/items/+page.server.ts | 9 ++++- app-admin/src/routes/items/+page.svelte | 22 +++++++++- packages/shared/src/blocks/ShopBlock.svelte | 40 +++++++++++++++---- packages/shared/src/items.ts | 36 ++++++++++++++++- packages/shared/src/server/shop.ts | 16 ++++++-- packages/shared/src/types.ts | 11 +++++ pb_schema.json | 1 + pocketbase/pb_hooks/shop.pb.js | 6 +++ pocketbase/pb_hooks/shop/lib.js | 28 +++++++++++++ .../pb_migrations/1793500000_item_priority.js | 29 ++++++++++++++ 14 files changed, 211 insertions(+), 19 deletions(-) create mode 100644 pocketbase/pb_migrations/1793500000_item_priority.js diff --git a/AGENTS.md b/AGENTS.md index 7cc611e..779bfcb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,4 +201,5 @@ cd app-public && npm run build - `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency. - Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. - `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials. +- Shop order: `items.priority` (higher first) is *Recommended*; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`. - Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`). The Shop block fetches bookable times itself, per service and length, from `GET /api/slots` in each app (a proxy to `GET /api/shop/slots`); if it has nothing to show it says "Nothing is available". diff --git a/README.md b/README.md index 4210614..c11774f 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ If schema import fails because of a PocketBase version mismatch, create these co Commerce collections (see the Stripe section above for context): -- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `active` bool +- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name), `active` bool - `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text, `pass` relation→passes (the code applied at checkout) - `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold), `pass` relation→passes (the code paying for this booking), `giftTo` / `giftMessage` text (who a bundle is for) @@ -159,7 +159,8 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - `/pages` — list/create pages - `/pages/[slug]` — block editor with draft preview. Text is edited visually (headings, bold, italic, strikethrough, links, lists, pull quotes, lines; alignment and a small *footnote* size per block). Layouts have their own blocks: **Cards** (pictures or numbered steps, optionally linked — e.g. *Who I work with*, *Read next*, *How it works*) and **FAQ** (questions that open to show the answer). An **HTML** block takes raw HTML for embeds and one-offs (inline styles only; anything it loads from another site shares visitors' IPs). Every block has an *Anchor*, so a button or link to `#prices` jumps to it. - `/calendar` — events shown by Upcoming Calendar blocks -- `/items` — services, products and bundles shown in Shop blocks +- `/items` — services, products and bundles shown in Shop blocks, listed in shop order (highest *Priority in the shop* first, then by name) +- Shop block order: *Recommended* (by priority), *Most popular*, *Price: low to high / high to low*, *Name (A–Z)*, chosen per block (`sort`); *Let visitors sort* (`showSort`) adds a "Sort by" menu that starts at that order. *Most popular* = units in paid orders over the last 90 days, from `GET /api/shop/popular` (public; item ids best-selling first, never the numbers; refunded orders and products handed over inside a bundle don't count, bookings paid with a code do). Items without recent sales follow in Recommended order, and the menu leaves the choice out until something has sold. Chosen items (`itemIds`) follow the block's order too, not the order they were picked in. - `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). No two slots may overlap (windows and group sessions alike); bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it. - `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them. - `/passes` — *Vouchers & codes*: search codes (code, email, recipient, bundle), see what each has used/held/left and each part's share of the price, change the expiry, void/reactivate, and issue a code without a purchase diff --git a/app-admin/src/lib/admin/blockDefaults.ts b/app-admin/src/lib/admin/blockDefaults.ts index 97b93c9..e269c80 100644 --- a/app-admin/src/lib/admin/blockDefaults.ts +++ b/app-admin/src/lib/admin/blockDefaults.ts @@ -73,7 +73,9 @@ export function createBlock(type: BlockType): ContentBlock { title: 'Our Services', itemTypeFilter: 'all', itemIds: [], - layout: 'grid' + layout: 'grid', + sort: 'recommended', + showSort: false }; break; case 'checkout': diff --git a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte index acbe1ba..d342a26 100644 --- a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte +++ b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte @@ -1,5 +1,6 @@