diff --git a/AGENTS.md b/AGENTS.md index c60b1ee..bb93e42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,6 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ ├── pages/ # Page CRUD + block editor │ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── items/ # Service/product CRUD (menu label: Services & products) -│ │ ├── passes/ # Vouchers & codes: search, void/extend, issue (menu label: Vouchers & codes) │ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings @@ -128,14 +127,13 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type ### PocketBase Integration - Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie - `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` -- 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) +- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled) - 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. - **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)*. -- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*. +- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email` and (during checkout) `baskets`. 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)*. - **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only). ### Styling diff --git a/README.md b/README.md index a36f911..06468aa 100644 --- a/README.md +++ b/README.md @@ -112,13 +112,12 @@ 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`, `stock` number (nullable), `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), `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) -- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text (empty for an order paid entirely with codes), `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty) -- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date and `minutes` number (nullable, the booked time), `pass` relation→passes (the code that paid for this booking; `price` is then 0) -- `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* +- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text +- `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) +- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty) +- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date and `minutes` number (nullable, the booked time) - `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. @@ -138,10 +137,9 @@ 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 - `/calendar` — events shown by Upcoming Calendar blocks -- `/items` — services, products and bundles shown in Shop blocks +- `/items` — services and products shown in Shop blocks - `/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). Windows may not overlap each other, nor sessions of the same service; 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 - `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons - `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) @@ -174,17 +172,6 @@ Setup: 4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). Two visitors can't take the same place: holds are checked and written in one PocketBase transaction (see *Slot availability*). 5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it. -## Bundles and codes - -A **bundle** (Services & products → type *Bundle / voucher*) has its own price and contains services at a set length (e.g. 3 × Massage, 1 hour) and/or products, plus how many months its code stays valid. A gift voucher for one service is a bundle with one part. - -- **Buying**: the bundle goes in the basket like a product (its products' stock is checked and taken with the order). The buyer can mark it as a gift (*for* and a message). After payment every bundle bought becomes a **pass** with its own code, sent in the confirmation email and shown on the result page. -- **Redeeming**: whoever has the code enters it in the basket (`apply_code`). It covers bookings of the same service **and** length while it has places left; covered lines cost 0 and carry `pass`. A basket that codes cover entirely is confirmed without Stripe (`/api/shop/checkout` returns `{ free, orderId }`; the result page is `/checkout/return?order=…`, shown only to that basket's cookie). -- **Counting**: a pass's used places are its order lines (not refunded) and its live basket holds — never a stored counter. Refunding a booking's order gives the place back. Holds keep two people with the same code from using its last place at once. -- **Value**: `parts[].value` splits the bundle price in proportion to what the parts cost on their own, for partial refunds (done in Stripe, as before). -- **Admin**: `/passes` (*Vouchers & codes*), via `GET /api/shop/passes`, `POST /api/shop/passes/update`, `POST /api/shop/passes/issue` (signed-in admins; passes are written only by the shop hooks). -- **Personal data**: a pass holds the buyer's email and possibly a recipient's name and message. Export, correction and erasure cover passes; erasure keeps the code working. Retention anonymises a pass together with orders, once it has expired or has nothing left to book. - ## Booking emails (Brevo) After the Stripe webhook creates an order (in PocketBase, which hands the order data back to the public app's webhook route) the public app sends two emails through an SMTP relay (Brevo) with `nodemailer`: @@ -210,11 +197,11 @@ With `SMTP_HOST` empty (local dev) emails are written to the app container logs What the software does; the studio (the controller) is responsible for the privacy policy text and for how it uses the data. -- **What is stored:** name, email, phone and booking notes, on `orders.customerDetails` (one copy per order) and on `baskets` while checkout is in progress. A paid basket's copy is cleared as soon as its order exists. Bundle/voucher codes (`passes`) keep the buyer's email and, for gifts, the recipient's name and message. +- **What is stored:** name, email, phone and booking notes, on `orders.customerDetails` (one copy per order) and on `baskets` while checkout is in progress. A paid basket's copy is cleared as soon as its order exists. - **Privacy policy:** *Site design → Footer → Privacy policy page* links a page from the footer and above the Pay button. *Create a privacy policy draft* makes an unpublished `privacy` page describing what this software does, with [gaps] to fill in. - **Checkout:** a short privacy notice with the link, and a hint under the notes field asking customers not to write health details (special-category data). There is deliberately no "I consent" box: booking data is processed to perform the contract, not on consent. Both texts are editable in the Checkout block. -- **Customers (admin):** look a customer up by name, email, phone or notes (orders and unpaid checkouts, matched by email case-insensitively); *Export data (JSON)* for access/portability requests; correct name/email/phone or remove notes on every record; *Erase* anonymises their orders (amounts, services and dates stay for the accounts) and their codes (the codes keep working), and deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards. -- **Retention:** daily at 03:15 UTC and on PocketBase start (`pocketbase/pb_hooks/privacy.pb.js`): unpaid checkouts are deleted after *N* days (default 30); orders are anonymised after *M* months (default 0 = never — set it once the accountant has said how long records must be kept). Orders with a booking still ahead are skipped; codes are anonymised with the same age once they have expired or are used up. Settings live in the `privacy` global. +- **Customers (admin):** look a customer up by name, email, phone or notes (orders and unpaid checkouts, matched by email case-insensitively); *Export data (JSON)* for access/portability requests; correct name/email/phone or remove notes on every record; *Erase* anonymises their orders (amounts, services and dates stay for the accounts) and deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards. +- **Retention:** daily at 03:15 UTC and on PocketBase start (`pocketbase/pb_hooks/privacy.pb.js`): unpaid checkouts are deleted after *N* days (default 30); orders are anonymised after *M* months (default 0 = never — set it once the accountant has said how long records must be kept). Orders with a booking still ahead are skipped. Settings live in the `privacy` global. - **No third parties on page load:** fonts are bundled (`@fontsource/*`), not loaded from Google, and Stripe.js loads only when the customer presses Pay (`@stripe/stripe-js/pure`). The only cookies are the basket cookie and the admin login, so no cookie banner is needed — keep it that way, or add one before adding analytics. - All customer-data reads and writes go through `/api/privacy/*` (signed-in admin only; `orders`/`baskets` are superuser-only collections). diff --git a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte index acbe1ba..c361298 100644 --- a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte +++ b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte @@ -28,8 +28,7 @@ const typeFilterLabels: Record = { all: 'All', item: 'Products', - item_with_time: 'Services', - bundle: 'Bundles' + item_with_time: 'Services' }; @@ -49,7 +48,7 @@ updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })} formatLabel={(v) => typeFilterLabels[String(v)] || String(v)} diff --git a/app-admin/src/lib/admin/privacyTemplate.ts b/app-admin/src/lib/admin/privacyTemplate.ts index 05125a9..ba881f2 100644 --- a/app-admin/src/lib/admin/privacyTemplate.ts +++ b/app-admin/src/lib/admin/privacyTemplate.ts @@ -30,7 +30,6 @@ export const privacyTemplateHtml = `

Privacy policy

How long we keep it

  • Details entered at checkout without completing payment: deleted after [30] days.
  • -
  • Gift vouchers and bundles: the code is kept until it expires; your email and any recipient name and message you added are removed together with your order details.
  • Orders: your contact details are removed [after N months / when you ask]; the order record without them is kept for [N] years as required for our accounts.
  • Server logs (including IP addresses): [a few] days.
diff --git a/app-admin/src/lib/customers.ts b/app-admin/src/lib/customers.ts index a5e08c0..f853d5a 100644 --- a/app-admin/src/lib/customers.ts +++ b/app-admin/src/lib/customers.ts @@ -28,6 +28,4 @@ export type CustomerData = { lines: { name: string; quantity: number; price: number; start: string }[]; }[]; unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[]; - /** Bundle/voucher codes bought with this email, and who they're for. */ - codes: { code: string; name: string; created: string; expiresAt: string; status: string; recipientName: string; message: string }[]; }; diff --git a/app-admin/src/lib/server/customers.ts b/app-admin/src/lib/server/customers.ts index 8fd186a..6e18d8e 100644 --- a/app-admin/src/lib/server/customers.ts +++ b/app-admin/src/lib/server/customers.ts @@ -20,5 +20,5 @@ export function updateCustomer(pb: Pb, body: { email: string; name?: string; new } export function eraseCustomer(pb: Pb, email: string) { - return pb.send<{ ordersAnonymised: number; basketsDeleted: number; passesAnonymised: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); + return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); } diff --git a/app-admin/src/lib/server/passes.ts b/app-admin/src/lib/server/passes.ts deleted file mode 100644 index 1ae8380..0000000 --- a/app-admin/src/lib/server/passes.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Bundle/voucher codes for the admin. Codes are commerce data: they are -// only written by the shop hooks in PocketBase (/api/shop/passes*, signed-in -// admins only), which also count what each code has left. - -import { ClientResponseError } from 'pocketbase'; -import type { createPocketBase } from '$lib/pb'; -import type { PassSummary } from '$lib/types'; - -type Pb = ReturnType; - -/** A code as the admin list shows it: the summary plus who bought it and when. */ -export type AdminPass = PassSummary & { email: string; order: string; created: string; anonymisedAt: string }; - -export async function listPasses(pb: Pb, q: string) { - const { passes } = await pb.send<{ passes: AdminPass[] }>('/api/shop/passes', { query: { q }, requestKey: null }); - return passes; -} - -export function updatePass(pb: Pb, body: { id: string; status?: 'active' | 'void'; expiresAt?: string }) { - return pb.send<{ pass: PassSummary }>('/api/shop/passes/update', { method: 'POST', body, requestKey: null }); -} - -export function issuePass(pb: Pb, body: { itemId: string; email: string; recipientName: string; message: string; months: string }) { - return pb.send<{ pass: PassSummary }>('/api/shop/passes/issue', { method: 'POST', body, requestKey: null }); -} - -/** The hook's own message (e.g. "Choose a bundle"), or `fallback`. */ -export function hookError(e: unknown, fallback: string) { - if (e instanceof ClientResponseError && e.status >= 400 && e.status < 500 && e.response?.message) return String(e.response.message); - console.error(`[passes] ${fallback}`, e); - return fallback; -} diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index 8e68676..30954ef 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -41,7 +41,6 @@ { href: '/customers', label: 'Customers' }, { href: '/slots', label: 'Slots' }, { href: '/items', label: 'Services & products' }, - { href: '/passes', label: 'Vouchers & codes' }, { href: '/calendar', label: 'Events' } ] }, diff --git a/app-admin/src/routes/customers/+page.server.ts b/app-admin/src/routes/customers/+page.server.ts index ed3384d..39fa972 100644 --- a/app-admin/src/routes/customers/+page.server.ts +++ b/app-admin/src/routes/customers/+page.server.ts @@ -63,11 +63,10 @@ export const actions: Actions = { const email = String((await request.formData()).get('email') || ''); const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email)); if (!result.ok) return result.failure; - const { ordersAnonymised, basketsDeleted, passesAnonymised } = result.value; - const codes = passesAnonymised ? `, ${passesAnonymised} code${passesAnonymised === 1 ? '' : 's'} anonymised (still usable)` : ''; + const { ordersAnonymised, basketsDeleted } = result.value; return { ok: true, - message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted${codes}.` + message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.` }; }, diff --git a/app-admin/src/routes/customers/+page.svelte b/app-admin/src/routes/customers/+page.svelte index 3427d15..9c0f8c3 100644 --- a/app-admin/src/routes/customers/+page.svelte +++ b/app-admin/src/routes/customers/+page.svelte @@ -3,7 +3,6 @@ import { page } from '$app/state'; import { confirmSubmit } from '$lib/admin/confirm'; import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar'; - import { formatCode } from '$shared/items'; let { data, form } = $props(); let customer = $derived(data.customer); @@ -155,16 +154,6 @@ {/each} - {#if customer.codes?.length} -

Codes bought

-

Bundles and vouchers. Erasing keeps the codes usable but removes the email, recipient and message.

-
    - {#each customer.codes as code (code.code)} -
  • {formatCode(code.code)} — {code.name}{code.recipientName ? ` · for ${code.recipientName}` : ''}{code.message ? ` · “${code.message}”` : ''}
  • - {/each} -
- {/if} - {#if customer.unpaidBaskets.length}

Unpaid checkouts

Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.

@@ -178,7 +167,7 @@

Erase this customer

- For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts), removes their email and any recipient name and message from codes they bought (the codes keep working), and deletes unpaid checkouts. + For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts) and deletes unpaid checkouts. Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.

{#if upcoming.length} diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index a16c016..f6b2006 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -1,8 +1,7 @@ import { fail } from '@sveltejs/kit'; import { attempt } from '$lib/server/actions'; -import { parseDurations } from '$shared/items'; import { mapItemRecord } from '$shared/server/shop'; -import type { BundlePart, ItemDuration, ItemType } from '$lib/types'; +import type { ItemDuration, ItemType } from '$lib/types'; import type { Actions, PageServerLoad } from './$types'; /** Longest bookable length, in minutes (a booking must fit in one day's window). */ @@ -26,39 +25,8 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } { return durations.sort((a, b) => a.minutes - b.minutes); } -/** Most units of one thing a bundle can hold. */ -const MAX_PART_COUNT = 50; - -/** - * A bundle's parts from the form's `partItem`/`partMinutes`/`partCount` rows: - * services (at one of their lengths) and products, not other bundles. - */ -function parseBundleRows(data: FormData, items: Record[]): BundlePart[] | { error: string } { - const ids = data.getAll('partItem').map(String); - const minutes = data.getAll('partMinutes').map(String); - const counts = data.getAll('partCount').map(String); - const parts: BundlePart[] = []; - for (let i = 0; i < ids.length; i++) { - if (!ids[i]) continue; - const item = items.find((candidate) => candidate.id === ids[i]); - if (!item || item.type === 'bundle') return { error: 'A bundle can only contain services and products.' }; - const count = Number(counts[i]); - if (!Number.isInteger(count) || count < 1 || count > MAX_PART_COUNT) return { error: `How many of “${item.name}”: a whole number from 1 to ${MAX_PART_COUNT}.` }; - let length: number | null = null; - if (item.type === 'item_with_time') { - length = Number(minutes[i]); - if (!parseDurations(item.durations).some((d) => d.minutes === length)) return { error: `Choose one of the lengths “${item.name}” is offered for.` }; - } - if (parts.some((p) => p.item === item.id && p.minutes === length)) return { error: `“${item.name}” is listed twice — raise its count instead.` }; - parts.push({ item: item.id, minutes: length, count }); - } - if (!parts.some((p) => p.minutes)) return { error: 'A bundle needs at least one service — its code is what books it.' }; - return parts; -} - -function itemPayload(data: FormData, items: Record[]) { - const rawType = String(data.get('type')); - const type: ItemType = rawType === 'item_with_time' || rawType === 'bundle' ? rawType : 'item'; +function itemPayload(data: FormData) { + const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; const name = String(data.get('name') || '').trim(); if (!name) return { error: 'Name is required.' }; const rawStock = String(data.get('stock') ?? '').trim(); @@ -67,18 +35,7 @@ function itemPayload(data: FormData, items: Record[]) { let price: number; let durations: ItemDuration[] = []; - let bundleParts: BundlePart[] = []; - let validMonths: number | null = null; - if (type === 'bundle') { - const parsed = parseBundleRows(data, items.filter((item) => item.id !== String(data.get('id') || ''))); - if ('error' in parsed) return parsed; - bundleParts = parsed; - price = parseFloat(String(data.get('price') || '')); - if (Number.isNaN(price) || price <= 0) return { error: 'A bundle needs a price above 0.' }; - const rawMonths = String(data.get('validMonths') ?? '').trim(); - validMonths = rawMonths === '' ? null : Number(rawMonths); - if (validMonths !== null && !(Number.isInteger(validMonths) && validMonths >= 1 && validMonths <= 120)) return { error: 'Valid for: 1 to 120 months, or empty for no expiry.' }; - } else if (type === 'item_with_time') { + if (type === 'item_with_time') { const parsed = parseDurationRows(data); if ('error' in parsed) return parsed; durations = parsed; @@ -100,12 +57,8 @@ function itemPayload(data: FormData, items: Record[]) { price, image: String(data.get('image') || '').trim(), type, - // Empty = unlimited (PocketBase can't store an empty number, hence the flag). - stock: Number.isNaN(stock) ? 0 : (stock ?? 0), - trackStock: stock !== null && !Number.isNaN(stock), + stock: Number.isNaN(stock) ? null : stock, durations, - bundleParts, - validMonths, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, capacity: Number.isNaN(capacity) ? null : capacity, active: String(data.get('active')) === 'true' @@ -113,11 +66,6 @@ function itemPayload(data: FormData, items: Record[]) { }; } -/** Every item, for checking what a bundle may contain. */ -function allItems(pb: App.Locals['pb']) { - return pb.collection('items').getFullList({ fields: 'id,name,type,durations' }).catch(() => []); -} - export const load: PageServerLoad = async ({ locals }) => { const records = await locals.pb .collection('items') @@ -128,7 +76,7 @@ export const load: PageServerLoad = async ({ locals }) => { export const actions: Actions = { create: async ({ request, locals }) => { - const result = itemPayload(await request.formData(), await allItems(locals.pb)); + const result = itemPayload(await request.formData()); if ('error' in result) return fail(400, { message: result.error }); const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload)); if (!created.ok) return created.failure; @@ -138,7 +86,7 @@ export const actions: Actions = { const data = await request.formData(); const id = String(data.get('id') || ''); if (!id) return fail(400, { message: 'Item id is required.' }); - const result = itemPayload(data, await allItems(locals.pb)); + const result = itemPayload(data); if ('error' in result) return fail(400, { message: result.error }); const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload)); if (!updated.ok) return updated.failure; diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index c917bbf..4e2b6cb 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -23,9 +23,6 @@ stock: string; /** Service lengths and prices, as typed (one form row each). */ durations: { minutes: string; price: string }[]; - /** Bundle contents, as typed (one form row each); minutes '' for a product. */ - parts: { item: string; minutes: string; count: string }[]; - validMonths: string; bufferMinutes: string; capacity: string; active: boolean; @@ -37,48 +34,9 @@ let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); function emptyDraft(): ItemDraft { - return { - id: '', - name: '', - description: '', - price: 0, - image: '', - imageUrl: '', - type: 'item', - stock: '', - durations: [{ minutes: '60', price: '' }], - parts: [{ item: '', minutes: '', count: '1' }], - validMonths: '12', - bufferMinutes: '', - capacity: '', - active: true - }; + return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true }; } - /** What a bundle can contain: services and products (never itself or another bundle). */ - let partChoices = $derived(items.filter((item) => item.type !== 'bundle' && item.id !== draft.id)); - - function choosePartItem(row: ItemDraft['parts'][number], id: string) { - row.item = id; - const item = items.find((candidate) => candidate.id === id); - row.minutes = item?.durations[0] ? String(item.durations[0].minutes) : ''; - } - - /** "3× Massage (1 hour), 1× Oil" for the table. */ - function bundleList(item: ItemRecord) { - const names = new Map(items.map((i) => [i.id, i.name])); - return item.bundleParts.map((p) => `${p.count}× ${names.get(p.item) ?? '?'}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', '); - } - - /** What the parts cost on their own, to compare with the bundle price. */ - let partsListPrice = $derived( - draft.parts.reduce((sum, row) => { - const item = items.find((candidate) => candidate.id === row.item); - const unit = item?.type === 'item_with_time' ? (item.durations.find((d) => String(d.minutes) === row.minutes)?.price ?? 0) : (item?.price ?? 0); - return sum + unit * (Number(row.count) || 0); - }, 0) - ); - function addDuration() { const last = Number(draft.durations.at(-1)?.minutes) || 0; draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' }); @@ -106,8 +64,6 @@ type: item.type, stock: item.stock == null ? '' : String(item.stock), durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }], - parts: item.bundleParts.length ? item.bundleParts.map((p) => ({ item: p.item, minutes: p.minutes ? String(p.minutes) : '', count: String(p.count) })) : [{ item: '', minutes: '', count: '1' }], - validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12', bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), capacity: item.capacity == null ? '' : String(item.capacity), active: item.active @@ -140,7 +96,7 @@

Services & products

-

Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.

+

Bookable services and products, shown in Shop blocks.

@@ -164,16 +120,10 @@ {item.name}
- {item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'} + {item.type === 'item_with_time' ? 'Service' : 'Product'} {item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)} {item.type === 'item' ? (item.stock ?? '∞') : '—'} - - {#if item.type === 'item_with_time'} - {durationList(item)}{item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}{(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''} - {:else if item.type === 'bundle'} - {bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'} - {:else}—{/if} - + {item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'} {item.active ? 'Active' : 'Inactive'} @@ -207,52 +157,10 @@ - {#if draft.type === 'bundle'} -
- What’s in it -
- {#each draft.parts as row, i} - {@const partItem = items.find((item) => item.id === row.item)} -
- - × - - {#if partItem?.type === 'item_with_time'} - - {:else} - - {/if} - {#if draft.parts.length > 1} - - {/if} -
- {/each} -
- - The buyer gets a code; whoever has it books the services, each at the length set here, without paying again. Products are handed over with the purchase. A one-service voucher is a bundle with one part. -
-
- - -
- {:else if draft.type === 'item'} + {#if draft.type === 'item'}