Compare commits
10 commits
footer-pri
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 436e71a103 | |||
| 2633f5031e | |||
| 27d95e6f8e | |||
| 80cbe6ddb2 | |||
| e896fd3c99 | |||
| 97b1da2433 | |||
| 5e2db31b5e | |||
| dc8c58f4c2 | |||
| 5b92cae225 | |||
| d62799f263 |
22 changed files with 480 additions and 73 deletions
|
|
@ -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.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).
|
||||
|
||||
|
|
@ -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.
|
||||
|
|
@ -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)*.
|
||||
|
|
@ -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 `<scheme>://<sub>.<DOMAIN><port>`. 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 (`<scheme>://db.${DOMAIN}<port>`). 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: `<scheme>://admin.${DOMAIN}<port>` (admin), `<scheme>://www.${DOMAIN}<port>` (public).
|
||||
- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`<scheme>://www.${DOMAIN}<port>`).
|
||||
- `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.
|
||||
|
|
@ -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*. It's set by dragging the `/items` list (`?/reorder` renumbers n…1), not typed in the item form; `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".
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
46
README.md
46
README.md
|
|
@ -73,20 +73,41 @@ 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
|
||||
|
||||
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/<token>`. Open it with `http://0.0.0.0:8090` replaced by the address you reach PocketBase at, e.g. `http://db.localhost:8080/_/#/pbinstall/<token>`.
|
||||
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)
|
||||
|
||||
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 <project>_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.
|
||||
|
||||
### 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
|
||||
|
||||
|
|
@ -112,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; set by dragging the `/items` list, never typed), `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)
|
||||
|
|
@ -121,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
|
||||
|
||||
|
|
@ -138,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. Drag a row by its ⠿ handle (or focus the handle and press ↑/↓), then *Save order*: the `?/reorder` action stores it as `items.priority` (n…1, first = highest), writing only what changed. New items go to the end
|
||||
- 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
|
||||
|
|
|
|||
8
app-admin/package-lock.json
generated
8
app-admin/package-lock.json
generated
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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':
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
<script lang="ts">
|
||||
import type { ContentBlock, ShopBlockData } from '$lib/types';
|
||||
import type { ContentBlock, ShopBlockData, ShopSort } from '$lib/types';
|
||||
import { SHOP_SORTS } from '$shared/items';
|
||||
import SegmentedControl from './SegmentedControl.svelte';
|
||||
|
||||
let {
|
||||
|
|
@ -55,11 +56,28 @@
|
|||
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
|
||||
/>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Order</span>
|
||||
<select class="select w-full" value={block.data.sort || 'recommended'} onchange={(e) => updateData({ sort: e.currentTarget.value as ShopSort })}>
|
||||
{#each SHOP_SORTS as choice (choice.value)}
|
||||
<option value={choice.value}>{choice.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<span class="label whitespace-normal">
|
||||
Recommended follows each item’s priority (Services & products). Most popular counts what sold in the last 90 days; items without recent sales come after, in Recommended order.
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="label cursor-pointer gap-3 whitespace-normal text-base-content">
|
||||
<input class="toggle toggle-primary shrink-0" type="checkbox" checked={!!block.data.showSort} onchange={(e) => updateData({ showSort: e.currentTarget.checked })} />
|
||||
<span>Let visitors sort <span class="text-base-content/60">— a “Sort by” menu above the items, starting at the order chosen above</span></span>
|
||||
</label>
|
||||
|
||||
{#if items.length}
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<div class="mb-3">
|
||||
<h3 class="font-semibold">Items</h3>
|
||||
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
|
||||
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type. Chosen items are shown in the order above, not the order you pick them.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each items as item}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,9 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
|
|||
return durations.sort((a, b) => a.minutes - b.minutes);
|
||||
}
|
||||
|
||||
/** Priorities go from -this to this (the field's limits in pb_schema.json). Set by dragging the list (?/reorder), never typed. */
|
||||
const MAX_PRIORITY = 1000;
|
||||
|
||||
/** Most units of one thing a bundle can hold. */
|
||||
const MAX_PART_COUNT = 50;
|
||||
|
||||
|
|
@ -117,14 +120,14 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
|
|||
|
||||
/** 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(() => []);
|
||||
return pb.collection('items').getFullList({ fields: 'id,name,type,durations,priority' }).catch(() => []);
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const [records, waiting] = await Promise.all([
|
||||
locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ sort: 'name', expand: 'image' })
|
||||
.getFullList({ sort: '-priority,name', expand: 'image' })
|
||||
.catch(() => []),
|
||||
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>)
|
||||
]);
|
||||
|
|
@ -133,9 +136,13 @@ 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 items = await allItems(locals.pb);
|
||||
const result = itemPayload(await request.formData(), items);
|
||||
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));
|
||||
// New items go to the end of the shop order; drag them up from there.
|
||||
const lowest = items.length ? Math.min(...items.map((item) => Number(item.priority) || 0)) : 1;
|
||||
const priority = Math.max(-MAX_PRIORITY, lowest - 1);
|
||||
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create({ ...result.payload, priority }));
|
||||
if (!created.ok) return created.failure;
|
||||
return { ok: true };
|
||||
},
|
||||
|
|
@ -149,6 +156,33 @@ export const actions: Actions = {
|
|||
if (!updated.ok) return updated.failure;
|
||||
return { ok: true };
|
||||
},
|
||||
/**
|
||||
* The list's new order (`order`: JSON item ids, first = shown first) →
|
||||
* priorities n…1. Only items whose priority changes are written; items
|
||||
* missing from the list (added meanwhile) go after it.
|
||||
*/
|
||||
reorder: async ({ request, locals }) => {
|
||||
let ids: unknown;
|
||||
try {
|
||||
ids = JSON.parse(String((await request.formData()).get('order') || '[]'));
|
||||
} catch {
|
||||
ids = null;
|
||||
}
|
||||
if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string')) return fail(400, { message: 'Could not read the new order — reload the page and try again.' });
|
||||
const records = await locals.pb.collection('items').getFullList({ fields: 'id,priority', sort: '-priority,name' });
|
||||
const known = new Set(records.map((record) => record.id));
|
||||
const listed = [...new Set(ids as string[])].filter((id) => known.has(id));
|
||||
const ordered = [...listed, ...records.map((record) => record.id).filter((id) => !listed.includes(id))];
|
||||
if (ordered.length > MAX_PRIORITY) return fail(400, { message: `The order can only be set for up to ${MAX_PRIORITY} items.` });
|
||||
const current = new Map(records.map((record) => [record.id, Number(record.priority) || 0]));
|
||||
for (const [index, id] of ordered.entries()) {
|
||||
const priority = ordered.length - index;
|
||||
if (current.get(id) === priority) continue;
|
||||
const saved = await attempt('Could not save the order.', () => locals.pb.collection('items').update(id, { priority }));
|
||||
if (!saved.ok) return saved.failure;
|
||||
}
|
||||
return { ok: true, message: 'Order saved.' };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
<script lang="ts">
|
||||
import { enhance } from '$app/forms';
|
||||
import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import SaveStatus from '$lib/admin/SaveStatus.svelte';
|
||||
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
|
||||
import type { ItemRecord, ItemType } from '$lib/types';
|
||||
import { formatDuration } from '$shared/items';
|
||||
|
||||
|
|
@ -10,6 +13,85 @@
|
|||
let showEditor = $state(false);
|
||||
let uploading = $state(false);
|
||||
|
||||
// ── Shop order ─────────────────────────────────────────────────────
|
||||
// The list is in shop order (highest priority first). Dragging a row (or
|
||||
// the arrow keys on its handle) changes `order` here; "Save order" turns
|
||||
// it into priorities on the server (?/reorder). null = as saved.
|
||||
let order = $state<string[] | null>(null);
|
||||
let shown = $derived.by(() => {
|
||||
if (!order) return items;
|
||||
const byId = new Map(items.map((item: ItemRecord) => [item.id, item]));
|
||||
const listed = order.map((id) => byId.get(id)).filter((item): item is ItemRecord => !!item);
|
||||
// Anything added meanwhile (another tab) goes at the end.
|
||||
return [...listed, ...items.filter((item: ItemRecord) => !order!.includes(item.id))];
|
||||
});
|
||||
let orderChanged = $derived(!!order && shown.map((item) => item.id).join() !== items.map((item: ItemRecord) => item.id).join());
|
||||
let savingOrder = $state(false);
|
||||
warnOnUnsavedChanges(() => orderChanged);
|
||||
|
||||
function move(from: number, to: number) {
|
||||
if (to < 0 || to >= shown.length || from === to) return;
|
||||
const ids = shown.map((item) => item.id);
|
||||
const [id] = ids.splice(from, 1);
|
||||
ids.splice(to, 0, id);
|
||||
order = ids;
|
||||
}
|
||||
|
||||
// Mouse: native drag and drop on the whole row. Touch: phones don't fire
|
||||
// drag events, so the handle follows the finger with pointer events (as
|
||||
// in the page editor's block list).
|
||||
let dragIndex = $state<number | null>(null);
|
||||
let dropIndex = $state<number | null>(null);
|
||||
|
||||
function endDrag() {
|
||||
if (dragIndex !== null && dropIndex !== null) move(dragIndex, dropIndex);
|
||||
dragIndex = null;
|
||||
dropIndex = null;
|
||||
}
|
||||
|
||||
function rowDrag(index: number) {
|
||||
return {
|
||||
draggable: true,
|
||||
ondragstart: (e: DragEvent) => {
|
||||
dragIndex = index;
|
||||
// Firefox won't start a drag without data.
|
||||
e.dataTransfer?.setData('text/plain', String(index));
|
||||
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
|
||||
},
|
||||
ondragover: (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
dropIndex = index;
|
||||
},
|
||||
ondrop: (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
endDrag();
|
||||
},
|
||||
ondragend: () => {
|
||||
dragIndex = null;
|
||||
dropIndex = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function touchDragStart(e: PointerEvent, index: number) {
|
||||
if (e.pointerType === 'mouse') return;
|
||||
e.preventDefault();
|
||||
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
|
||||
dragIndex = index;
|
||||
dropIndex = index;
|
||||
}
|
||||
|
||||
function touchDragMove(e: PointerEvent) {
|
||||
if (dragIndex === null) return;
|
||||
// The rows are the children of the list (phones) or the table body.
|
||||
const rows = [...((e.currentTarget as HTMLElement).closest('ul, tbody')?.children ?? [])] as HTMLElement[];
|
||||
const over = rows.findIndex((row) => e.clientY < row.getBoundingClientRect().bottom);
|
||||
dropIndex = over === -1 ? rows.length - 1 : over;
|
||||
// The handle blocks scrolling, so scroll for the finger near the screen's edges.
|
||||
if (e.clientY < 64) window.scrollBy(0, -12);
|
||||
else if (e.clientY > window.innerHeight - 64) window.scrollBy(0, 12);
|
||||
}
|
||||
|
||||
type ItemDraft = {
|
||||
id: string;
|
||||
name: string;
|
||||
|
|
@ -130,12 +212,38 @@
|
|||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Services & products</h1>
|
||||
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.</p>
|
||||
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later). Shop blocks show them in this order (their <em>Recommended</em> order): drag <span aria-hidden="true">⠿</span> to change it.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
|
||||
<SaveStatus result={form} />
|
||||
|
||||
{#if orderChanged}
|
||||
<!-- Sticky, so Save stays in reach while dragging down a long list. -->
|
||||
<form
|
||||
method="POST"
|
||||
action="?/reorder"
|
||||
class="sticky top-2 z-10 flex flex-wrap items-center gap-3 rounded-box bg-base-100 p-3 shadow-lg"
|
||||
use:enhance={() => {
|
||||
savingOrder = true;
|
||||
return async ({ result, update }) => {
|
||||
await update();
|
||||
savingOrder = false;
|
||||
// Saved: the reloaded list is in the new order.
|
||||
if (result.type === 'success') order = null;
|
||||
};
|
||||
}}
|
||||
>
|
||||
<input type="hidden" name="order" value={JSON.stringify(shown.map((item) => item.id))} />
|
||||
<span class="badge badge-warning">Unsaved order</span>
|
||||
<span class="min-w-40 flex-1 text-sm text-base-content/70">Shop blocks change once it’s saved.</span>
|
||||
<span class="ml-auto flex gap-2">
|
||||
<button class="btn btn-sm" type="button" disabled={savingOrder} onclick={() => (order = null)}>Undo</button>
|
||||
<button class="btn btn-primary btn-sm" type="submit" disabled={savingOrder}>Save order</button>
|
||||
</span>
|
||||
</form>
|
||||
{/if}
|
||||
|
||||
{#snippet thumbnail(item: ItemRecord)}
|
||||
{#if item.imageUrl}
|
||||
|
|
@ -145,6 +253,33 @@
|
|||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet handle(item: ItemRecord, index: number)}
|
||||
<!-- A button so the keyboard can move it too (↑/↓); the pointer drags the whole row. -->
|
||||
<button
|
||||
class="btn btn-ghost btn-sm btn-square shrink-0 cursor-grab touch-none text-xl text-base-content/50"
|
||||
type="button"
|
||||
title="Drag to change the order (or focus and press ↑/↓)"
|
||||
aria-label="Move {item.name} — use the arrow keys"
|
||||
disabled={shown.length < 2}
|
||||
onpointerdown={(e) => touchDragStart(e, index)}
|
||||
onpointermove={touchDragMove}
|
||||
onpointerup={endDrag}
|
||||
onpointercancel={() => {
|
||||
dragIndex = null;
|
||||
dropIndex = null;
|
||||
}}
|
||||
onkeydown={(e) => {
|
||||
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
|
||||
e.preventDefault();
|
||||
const to = index + (e.key === 'ArrowUp' ? -1 : 1);
|
||||
move(index, to);
|
||||
// Keep the focus on this item's handle in its new place.
|
||||
const button = e.currentTarget;
|
||||
requestAnimationFrame(() => (button.closest('ul, tbody')?.children[Math.max(0, Math.min(to, shown.length - 1))]?.querySelector('button') as HTMLElement | null)?.focus());
|
||||
}}>⠿</button
|
||||
>
|
||||
{/snippet}
|
||||
|
||||
{#snippet typeBadge(item: ItemRecord)}
|
||||
<span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span>
|
||||
{/snippet}
|
||||
|
|
@ -178,11 +313,12 @@
|
|||
|
||||
<!-- Phones and tablets: one card per item (seven columns didn't fit; long bundle lists made rows very tall). -->
|
||||
<ul class="divide-y divide-base-200 rounded-box bg-base-100 shadow lg:hidden">
|
||||
{#each items as item (item.id)}
|
||||
{#each shown as item, i (item.id)}
|
||||
{@const problem = item.type === 'bundle' && item.active ? bundleProblem(item) : ''}
|
||||
{@const waiting = !item.active && item.type === 'item_with_time' ? (data.waiting[item.id] ?? 0) : 0}
|
||||
<li class="p-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<li class="p-4 pl-2 transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
|
||||
<div class="flex items-start gap-2">
|
||||
{@render handle(item, i)}
|
||||
{@render thumbnail(item)}
|
||||
<div class="min-w-0 flex-1">
|
||||
<span class="block font-semibold break-words">{item.name}</span>
|
||||
|
|
@ -207,12 +343,13 @@
|
|||
<div class="hidden rounded-box bg-base-100 p-5 shadow lg:block">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<thead><tr><th class="w-0"><span class="sr-only">Order</span></th><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each items as item (item.id)}
|
||||
{#each shown as item, i (item.id)}
|
||||
{@const problem = item.type === 'bundle' && item.active ? bundleProblem(item) : ''}
|
||||
{@const waiting = !item.active && item.type === 'item_with_time' ? (data.waiting[item.id] ?? 0) : 0}
|
||||
<tr>
|
||||
<tr class="transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
|
||||
<td class="pr-0">{@render handle(item, i)}</td>
|
||||
<td>
|
||||
<div class="flex items-center gap-3">
|
||||
{@render thumbnail(item)}
|
||||
|
|
@ -230,7 +367,7 @@
|
|||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||
</tr>
|
||||
{:else}
|
||||
<tr><td colspan="7" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
|
||||
<tr><td colspan="8" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
|
|
|
|||
8
app-public/package-lock.json
generated
8
app-public/package-lock.json
generated
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.40.6@sha256:936756ccefb13cedaf2e7c49745412455bc81f2d1a511132f4012e411b970437
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ItemRecord } from '$shared/types';
|
||||
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ShopSort, type ItemRecord } from '$shared/types';
|
||||
import { getBasketContext } from '$shared/basket.svelte';
|
||||
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
|
||||
import { bundleListPrice, formatDuration, lowestPrice } from '$shared/items';
|
||||
import { SHOP_SORTS, bundleListPrice, formatDuration, lowestPrice, sortItems } from '$shared/items';
|
||||
import { addDaysToKey, formatDateKey } from '$shared/slots';
|
||||
|
||||
let { data = {}, items = [] } = $props<{
|
||||
|
|
@ -55,13 +55,22 @@
|
|||
}
|
||||
if (data.itemIds?.length) {
|
||||
const wanted = new Set(data.itemIds);
|
||||
result = result
|
||||
.filter((i) => wanted.has(i.id))
|
||||
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
|
||||
result = result.filter((i) => wanted.has(i.id));
|
||||
}
|
||||
return result;
|
||||
return sortItems(result, sort);
|
||||
});
|
||||
|
||||
/** What the visitor picked in "Sort by" (only while the menu is shown); else the block's own order. */
|
||||
let pickedSort = $state<ShopSort | null>(null);
|
||||
// "Most popular" needs recent sales to go by; without any it would only repeat Recommended, so it's left out.
|
||||
let hasSales = $derived(items.some((item: ItemRecord) => item.popularRank !== null));
|
||||
let sort = $derived.by<ShopSort>(() => {
|
||||
const wanted = (data.showSort && pickedSort) || data.sort || 'recommended';
|
||||
return wanted === 'popular' && !hasSales ? 'recommended' : wanted;
|
||||
});
|
||||
let sortChoices = $derived(SHOP_SORTS.filter((choice) => choice.value !== 'popular' || hasSales));
|
||||
let showSortMenu = $derived(!!data.showSort && visibleItems.length > 1);
|
||||
|
||||
let isList = $derived(data.layout === 'list');
|
||||
|
||||
/** Item id → name, for what bundles contain. */
|
||||
|
|
@ -277,7 +286,24 @@
|
|||
|
||||
<section class="mx-auto max-w-6xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
|
||||
<h2 class={showSortMenu ? 'mb-8 text-center font-serif text-3xl text-charcoal md:text-4xl' : 'mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl'}>{data.title}</h2>
|
||||
{/if}
|
||||
|
||||
{#if showSortMenu}
|
||||
<div class="mb-6 flex justify-end">
|
||||
<label class="inline-flex items-center gap-2 text-sm text-charcoal/70">
|
||||
Sort by
|
||||
<select
|
||||
class="rounded-button border border-charcoal/15 bg-white py-1.5 pr-8 pl-3.5 text-sm text-charcoal"
|
||||
value={sort}
|
||||
onchange={(e) => (pickedSort = e.currentTarget.value as ShopSort)}
|
||||
>
|
||||
{#each sortChoices as choice (choice.value)}
|
||||
<option value={choice.value}>{choice.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !visibleItems.length}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// the Shop block and the checkout. Which duration costs what is decided
|
||||
// (and charged) by the shop hooks in PocketBase; this only reads and shows it.
|
||||
|
||||
import type { BundlePart, ItemDuration, ItemRecord } from './types';
|
||||
import type { BundlePart, ItemDuration, ItemRecord, ShopSort } from './types';
|
||||
|
||||
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
|
||||
export function parseDurations(raw: unknown): ItemDuration[] {
|
||||
|
|
@ -49,3 +49,37 @@ export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) {
|
|||
}
|
||||
return Math.round(total * 100) / 100;
|
||||
}
|
||||
|
||||
/** The Shop block's sort choices, in menu order, with what visitors see. */
|
||||
export const SHOP_SORTS: { value: ShopSort; label: string }[] = [
|
||||
{ value: 'recommended', label: 'Recommended' },
|
||||
{ value: 'popular', label: 'Most popular' },
|
||||
{ value: 'price_asc', label: 'Price: low to high' },
|
||||
{ value: 'price_desc', label: 'Price: high to low' },
|
||||
{ value: 'name', label: 'Name (A–Z)' }
|
||||
];
|
||||
|
||||
const byName = (a: ItemRecord, b: ItemRecord) => a.name.localeCompare(b.name, 'en-GB', { sensitivity: 'base' });
|
||||
const byPriority = (a: ItemRecord, b: ItemRecord) => b.priority - a.priority || byName(a, b);
|
||||
|
||||
/**
|
||||
* `items` in the Shop block's `sort` order (a new array). Ties — and, for
|
||||
* "Most popular", items that haven't sold lately — fall back to Recommended,
|
||||
* so the admin's priorities still decide whatever the numbers don't.
|
||||
* Services sort by their lowest price (what "from …" shows).
|
||||
*/
|
||||
export function sortItems(items: ItemRecord[], sort: ShopSort = 'recommended') {
|
||||
const list = [...items];
|
||||
switch (sort) {
|
||||
case 'popular':
|
||||
return list.sort((a, b) => (a.popularRank ?? Infinity) - (b.popularRank ?? Infinity) || byPriority(a, b));
|
||||
case 'price_asc':
|
||||
return list.sort((a, b) => a.price - b.price || byPriority(a, b));
|
||||
case 'price_desc':
|
||||
return list.sort((a, b) => b.price - a.price || byPriority(a, b));
|
||||
case 'name':
|
||||
return list.sort(byName);
|
||||
default:
|
||||
return list.sort(byPriority);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,9 +27,13 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
|||
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
|
||||
bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [],
|
||||
validMonths: type === 'bundle' ? Number(record.validMonths) || null : null,
|
||||
bufferMinutes: record.bufferMinutes ?? null,
|
||||
capacity: record.capacity ?? null,
|
||||
active: record.active !== false
|
||||
// PocketBase reads an empty number back as 0, never null: 0 means "not set" for both
|
||||
// (and a 0 in the admin form would fail capacity's min of 1, blocking every save).
|
||||
bufferMinutes: Number(record.bufferMinutes) || null,
|
||||
capacity: Number(record.capacity) || null,
|
||||
active: record.active !== false,
|
||||
priority: Number(record.priority) || 0,
|
||||
popularRank: null
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -41,8 +45,16 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
|||
* (see `loadBookableTimes`). Errors propagate.
|
||||
*/
|
||||
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
|
||||
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
|
||||
const items = records.map(mapItemRecord);
|
||||
const [records, popular] = await Promise.all([
|
||||
pb.collection('items').getFullList({ filter: 'active = true', sort: '-priority,name', expand: 'image' }),
|
||||
// Only orders the "Most popular" sort; without it the shop still works.
|
||||
pb.send<{ items: string[] }>('/api/shop/popular', { requestKey: null }).catch((e) => {
|
||||
console.warn('Best sellers unavailable ("Most popular" falls back to Recommended):', e instanceof Error ? e.message : e);
|
||||
return { items: [] as string[] };
|
||||
})
|
||||
]);
|
||||
const rank = new Map(popular.items.map((id, i) => [id, i]));
|
||||
const items = records.map((record) => ({ ...mapItemRecord(record), popularRank: rank.get(record.id) ?? null }));
|
||||
// A bundle with a part that isn't on sale (inactive, deleted, or a length
|
||||
// the service dropped) can't be bought — the shop hook refuses it too.
|
||||
return { items: items.filter((item) => item.type !== 'bundle' || bundleListPrice(item.bundleParts, items) !== null) };
|
||||
|
|
|
|||
|
|
@ -156,6 +156,10 @@ export type ItemRecord = {
|
|||
bufferMinutes: number | null; // get-ready time after each appointment
|
||||
capacity: number | null; // places in a new group session (>1 = group)
|
||||
active: boolean;
|
||||
/** Shop order under "Recommended": higher first, then by name (0 = not set). */
|
||||
priority: number;
|
||||
/** Place among the best sellers (0 = best), null if it hasn't sold lately. Set only by `loadShopData`. */
|
||||
popularRank: number | null;
|
||||
};
|
||||
|
||||
/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */
|
||||
|
|
@ -291,11 +295,18 @@ export type OrderLine = {
|
|||
|
||||
// ── Block data types ──────────────────────────────────────────────────
|
||||
|
||||
/** How a Shop block orders its items (`recommended` = by each item's priority). */
|
||||
export type ShopSort = 'recommended' | 'popular' | 'price_asc' | 'price_desc' | 'name';
|
||||
|
||||
export type ShopBlockData = {
|
||||
title?: string;
|
||||
itemTypeFilter?: 'all' | ItemType;
|
||||
itemIds?: string[];
|
||||
layout?: 'grid' | 'list';
|
||||
/** Order shown first (default `recommended`). */
|
||||
sort?: ShopSort;
|
||||
/** Show a "Sort by" menu so visitors can reorder the items. */
|
||||
showSort?: boolean;
|
||||
};
|
||||
|
||||
export type CheckoutBlockData = {
|
||||
|
|
|
|||
|
|
@ -47,9 +47,7 @@
|
|||
"required": false,
|
||||
"presentable": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"maxSize": 2000000
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "bool_published",
|
||||
|
|
@ -103,9 +101,7 @@
|
|||
"required": false,
|
||||
"presentable": false,
|
||||
"unique": false,
|
||||
"options": {
|
||||
"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
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "bool_eventpub",
|
||||
|
|
@ -336,6 +330,7 @@
|
|||
{ "id": "num_itemvalidmo1", "name": "validMonths", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 1, "max": 120, "onlyInt": true },
|
||||
{ "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true },
|
||||
{ "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
|
||||
{ "id": "num_itempriority", "name": "priority", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": -1000, "max": 1000, "onlyInt": true },
|
||||
{ "id": "bool_itemactive", "name": "active", "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},
|
||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
|
|
@ -388,7 +383,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 +444,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 +510,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},
|
||||
|
|
|
|||
|
|
@ -16,6 +16,12 @@ routerAdd('GET', '/api/shop/slots', (e) => {
|
|||
return e.json(200, shop.bookableTimes($app, { item: query.get('item'), minutes: query.get('minutes'), from: query.get('from'), to: query.get('to') }));
|
||||
});
|
||||
|
||||
// Best sellers first (ids only), for the Shop block's "Most popular" sort.
|
||||
routerAdd('GET', '/api/shop/popular', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
return e.json(200, { items: shop.popularItems($app) });
|
||||
});
|
||||
|
||||
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
shop.sweepExpiredHolds($app);
|
||||
|
|
|
|||
|
|
@ -1305,6 +1305,33 @@ function createOrder(app, basketId, payment) {
|
|||
return orderId;
|
||||
}
|
||||
|
||||
// ── Popularity ──────────────────────────────────────────────────────────
|
||||
|
||||
/** "Most popular" in the Shop block counts what sold in this many days. */
|
||||
const POPULAR_DAYS = 90;
|
||||
|
||||
/**
|
||||
* Item ids, best-selling first, by units in paid orders over the last
|
||||
* POPULAR_DAYS (refunded orders don't count). A booking paid with a code
|
||||
* counts for its service; products handed over inside a bundle (price 0, no
|
||||
* code) don't — the bundle's own line counts for it. Only the order is
|
||||
* returned, never the numbers: this is public, and sales figures aren't.
|
||||
*/
|
||||
function popularItems(app) {
|
||||
const rows = arrayOf(new DynamicModel({ item: '', sold: 0 }));
|
||||
app
|
||||
.db()
|
||||
.newQuery(
|
||||
`SELECT ol.item AS item, SUM(ol.quantity) AS sold
|
||||
FROM order_lines ol JOIN orders o ON o.id = ol.[[order]]
|
||||
WHERE o.status = 'paid' AND o.created >= {:since} AND (ol.price > 0 OR ol.pass != '')
|
||||
GROUP BY ol.item HAVING sold > 0 ORDER BY sold DESC, ol.item`
|
||||
)
|
||||
.bind({ since: pbDate(Date.now() - POPULAR_DAYS * DAY_MS) })
|
||||
.all(rows);
|
||||
return rows.map((row) => row.item);
|
||||
}
|
||||
|
||||
// ── Orders ──────────────────────────────────────────────────────────────
|
||||
|
||||
function globalData(app, key) {
|
||||
|
|
@ -1409,6 +1436,7 @@ module.exports = {
|
|||
issuePass,
|
||||
bookableTimes,
|
||||
slotDetails,
|
||||
popularItems,
|
||||
sweepExpiredHolds,
|
||||
loadActiveBasket,
|
||||
basketPayload,
|
||||
|
|
|
|||
47
pocketbase/pb_migrations/1793400000_json_field_limits.js
Normal file
47
pocketbase/pb_migrations/1793400000_json_field_limits.js
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// 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)
|
||||
);
|
||||
29
pocketbase/pb_migrations/1793500000_item_priority.js
Normal file
29
pocketbase/pb_migrations/1793500000_item_priority.js
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// items.priority: where an item comes in Shop blocks under "Recommended"
|
||||
// (the default order). Higher comes first; equal priorities go by name.
|
||||
// Empty reads back as 0, so every existing item starts at 0 and the shop
|
||||
// keeps its old alphabetical order until priorities are set.
|
||||
|
||||
function find(app, name) {
|
||||
try {
|
||||
return app.findCollectionByNameOrId(name);
|
||||
} catch (e) {
|
||||
return null; // fresh install: pb_schema.json (already with the field) is imported later
|
||||
}
|
||||
}
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const items = find(app, 'items');
|
||||
if (!items || items.fields.getByName('priority')) return;
|
||||
items.fields.add(new NumberField({ id: 'num_itempriority', name: 'priority', min: -1000, max: 1000, onlyInt: true }));
|
||||
app.save(items);
|
||||
},
|
||||
(app) => {
|
||||
const items = find(app, 'items');
|
||||
if (!items || !items.fields.getByName('priority')) return;
|
||||
items.fields.removeByName('priority');
|
||||
app.save(items);
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue