diff --git a/AGENTS.md b/AGENTS.md index e7d9c5c..bb93e42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,14 +29,14 @@ 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) -│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear +│ │ ├── 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 │ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── backup/ # Export/import UI (calls api/export, api/import) │ │ ├── preview/ # Draft preview via sessionStorage (same-origin) -│ │ └── api/ # upload, export, import endpoints +│ │ └── api/ # upload, export, import, slots (Shop block times in /preview) endpoints │ ├── hooks.server.ts # Auth guard — all routes except /login │ └── app.css # Tailwind + DaisyUI + custom theme ├── static/ # Static assets @@ -60,7 +60,7 @@ app-public/ # SvelteKit public app (serves *.) │ │ ├── +layout.svelte # Root layout (always renders Header/Footer) │ │ ├── +page.svelte # Home page (slug=home) │ │ ├── [slug]/ # Dynamic CMS pages -│ │ ├── api/ # basket, checkout, webhooks endpoints +│ │ ├── api/ # basket, checkout, webhooks, slots (Shop block times) endpoints │ │ └── checkout/return/ # Stripe return URL │ ├── hooks.server.ts # Creates PB client in locals (no auth guard) │ └── app.css # Tailwind + DaisyUI + custom theme @@ -119,6 +119,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type ### Shared Code - `packages/shared/src/types.ts` — all type definitions - `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) +- `packages/shared/src/items.ts` — service durations (`parseDurations`, `formatDuration`, `lowestPrice`); which length costs what is charged by the shop hooks - `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts` - Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` - Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work @@ -131,7 +132,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - **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** (places + blocking by overlapping bookings, incl. get-ready time) is computed only by `slotStates()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots`, `?detail=1` for the admin). Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*. +- **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` 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). @@ -188,4 +189,4 @@ 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 listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`; slots via `GET /api/shop/slots`); if a Shop block has nothing to show it says "Nothing is available". +- 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 6784ea9..06468aa 100644 --- a/README.md +++ b/README.md @@ -112,12 +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`, `stock` number (nullable), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new slots), `active` bool -- `slots` — `item` relation→items, `start` date, `end` date, `capacity` number (places; >1 = group session), `notes` text. Nothing about bookings is stored here — see *Slot availability* below +- `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 -- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `heldUntil` date (a slot line's hold) +- `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 (nullable, snapshot) +- `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,7 +138,8 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - `/pages/[slug]` — block editor with draft preview - `/calendar` — events shown by Upcoming Calendar blocks - `/items` — services and products shown in Shop blocks -- `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions. +- `/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. - `/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) @@ -150,12 +151,14 @@ The shop/checkout blocks implement a basket-based booking flow: visitors add ser **Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that tidies expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`. -**Slot availability** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live): +**Slot availability** (`availability()` / `windowStartTimes()` / `checkBooking()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live): -- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does. -- One practitioner works every service, so a slot with **any** place taken blocks every other slot that overlaps it — whatever the service — counting each service's get-ready time (`items.bufferMinutes`) after it. The client can offer three massages at 10:00; once one is in a basket or booked, the other two disappear. A group session with one place booked blocks massages at that time too, while staying bookable itself until full. -- `GET /api/shop/slots` lists the bookable future slots (public; feeds the Shop block). With `?detail=1` a signed-in admin gets every slot in a range with booked/held places and what blocks it (the `/slots` page). -- Adding to a basket (`add_slot`, with `seats`) and changing a group line's places re-check capacity and blocking inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. +- A **booking** is a paid order line or a basket line whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts), each with its own `start` and `minutes`. It keeps the practitioner busy until its service's get-ready time (`items.bufferMinutes`) is over. A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does. +- One practitioner works every service, so no booking may overlap another — whatever the service, whatever the slot — including get-ready time. +- A **window** offers its services at any of their lengths. A booking must start and end inside it (its get-ready time may run past the end) and fit before the next booking. `startTimes = grid`: every `gridMinutes` (chosen per window: 10, 15, 20, 30, 45 or 60; default 30) from the window's start. `edges`: only right at the start or the end of each free stretch — a 09:00–12:00 window offers a 1-hour massage at 09:00 or 11:00; once 09:00 is booked (+15 min get-ready) it offers 10:15 or 11:00 — so time is taken from the ends and no gaps are left. +- A **group session** has `capacity` places for one service at one length; places are counted from its bookings. With any place taken its whole time is busy (windows lose that time); it stays bookable until full, and can't be booked while another booking overlaps it. +- `GET /api/shop/slots?item=&minutes=&from=&to=` lists the times a customer can book for one service and length (public; the Shop block fetches it through each app's `GET /api/slots` for the months on screen), plus `next` — the first bookable time after the range — when there are none in it. With `?detail=1` a signed-in admin gets every slot in a range with its bookings, free stretches and what blocks it (the `/slots` page). +- Adding to a basket (`add_slot`: `slotId` plus `itemId`, `minutes`, `start` for a window, or `seats` for a session) and changing a group line's places re-check everything inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. The price is the service's price for the booked length, read again at checkout. Setup: diff --git a/app-admin/src/lib/admin/slots/BulkActions.svelte b/app-admin/src/lib/admin/slots/BulkActions.svelte index bc7aedb..1345df1 100644 --- a/app-admin/src/lib/admin/slots/BulkActions.svelte +++ b/app-admin/src/lib/admin/slots/BulkActions.svelte @@ -26,9 +26,9 @@

Nothing to {deleting ? 'delete' : 'create'}.

{/if} {/if} diff --git a/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte index 5ff93c6..2840345 100644 --- a/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte +++ b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte @@ -33,7 +33,7 @@
-

Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.

+

Delete the windows and group sessions in a date range that have nothing booked. Slots with a booking, or with a time in a customer’s basket right now, are always kept.