Compare commits
5 commits
650de78bac
...
c7e019131a
| Author | SHA1 | Date | |
|---|---|---|---|
| c7e019131a | |||
| df840b7fd7 | |||
| e824f16e31 | |||
| 32984ac01d | |||
| e30e1d3beb |
34 changed files with 1734 additions and 145 deletions
|
|
@ -29,6 +29,7 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
||||||
│ │ ├── pages/ # Page CRUD + block editor
|
│ │ ├── pages/ # Page CRUD + block editor
|
||||||
│ │ ├── calendar/ # Event CRUD (menu label: Events)
|
│ │ ├── calendar/ # Event CRUD (menu label: Events)
|
||||||
│ │ ├── items/ # Service/product CRUD (menu label: Services & products)
|
│ │ ├── 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
|
│ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
|
||||||
│ │ ├── orders/ # Order list + booking-email status/resend
|
│ │ ├── orders/ # Order list + booking-email status/resend
|
||||||
│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings
|
│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings
|
||||||
|
|
@ -127,13 +128,14 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
|
||||||
### PocketBase Integration
|
### PocketBase Integration
|
||||||
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
|
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
|
||||||
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
|
- `$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)
|
- 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()`
|
- 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).
|
- **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). 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.
|
- **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*.
|
- **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)*.
|
- **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*.
|
||||||
- **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).
|
- **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
|
### Styling
|
||||||
|
|
|
||||||
31
README.md
31
README.md
|
|
@ -112,12 +112,13 @@ If schema import fails because of a PocketBase version mismatch, create these co
|
||||||
|
|
||||||
Commerce collections (see the Stripe section above for context):
|
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), `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
|
- `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
|
||||||
- `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
|
- `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
|
- `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)
|
- `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, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty)
|
- `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)
|
- `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*
|
||||||
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool
|
- `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. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass.
|
||||||
|
|
@ -137,9 +138,10 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
|
||||||
- `/pages` — list/create pages
|
- `/pages` — list/create pages
|
||||||
- `/pages/[slug]` — block editor with draft preview
|
- `/pages/[slug]` — block editor with draft preview
|
||||||
- `/calendar` — events shown by Upcoming Calendar blocks
|
- `/calendar` — events shown by Upcoming Calendar blocks
|
||||||
- `/items` — services and products shown in Shop blocks
|
- `/items` — services, products and bundles 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.
|
- `/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.
|
- `/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
|
- `/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)*)
|
- `/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)
|
- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
|
||||||
|
|
@ -172,6 +174,17 @@ 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*).
|
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.
|
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)
|
## 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`:
|
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`:
|
||||||
|
|
@ -197,11 +210,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 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.
|
- **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.
|
||||||
- **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.
|
- **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.
|
- **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 deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards.
|
- **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. Settings live in the `privacy` global.
|
- **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.
|
||||||
- **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.
|
- **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).
|
- All customer-data reads and writes go through `/api/privacy/*` (signed-in admin only; `orders`/`baskets` are superuser-only collections).
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,8 @@
|
||||||
const typeFilterLabels: Record<string, string> = {
|
const typeFilterLabels: Record<string, string> = {
|
||||||
all: 'All',
|
all: 'All',
|
||||||
item: 'Products',
|
item: 'Products',
|
||||||
item_with_time: 'Services'
|
item_with_time: 'Services',
|
||||||
|
bundle: 'Bundles'
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
@ -48,7 +49,7 @@
|
||||||
|
|
||||||
<SegmentedControl
|
<SegmentedControl
|
||||||
label="Item type"
|
label="Item type"
|
||||||
options={['all', 'item', 'item_with_time']}
|
options={['all', 'item', 'item_with_time', 'bundle']}
|
||||||
value={block.data.itemTypeFilter || 'all'}
|
value={block.data.itemTypeFilter || 'all'}
|
||||||
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
|
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
|
||||||
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
|
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,7 @@ export const privacyTemplateHtml = `<h2>Privacy policy</h2>
|
||||||
<h3>How long we keep it</h3>
|
<h3>How long we keep it</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>Details entered at checkout without completing payment: deleted after [30] days.</li>
|
<li>Details entered at checkout without completing payment: deleted after [30] days.</li>
|
||||||
|
<li>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.</li>
|
||||||
<li>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.</li>
|
<li>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.</li>
|
||||||
<li>Server logs (including IP addresses): [a few] days.</li>
|
<li>Server logs (including IP addresses): [a few] days.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
|
||||||
|
|
@ -28,4 +28,6 @@ export type CustomerData = {
|
||||||
lines: { name: string; quantity: number; price: number; start: string }[];
|
lines: { name: string; quantity: number; price: number; start: string }[];
|
||||||
}[];
|
}[];
|
||||||
unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[];
|
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 }[];
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -20,5 +20,5 @@ export function updateCustomer(pb: Pb, body: { email: string; name?: string; new
|
||||||
}
|
}
|
||||||
|
|
||||||
export function eraseCustomer(pb: Pb, email: string) {
|
export function eraseCustomer(pb: Pb, email: string) {
|
||||||
return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null });
|
return pb.send<{ ordersAnonymised: number; basketsDeleted: number; passesAnonymised: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
32
app-admin/src/lib/server/passes.ts
Normal file
32
app-admin/src/lib/server/passes.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
// 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<typeof createPocketBase>;
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
}
|
||||||
|
|
@ -41,6 +41,7 @@
|
||||||
{ href: '/customers', label: 'Customers' },
|
{ href: '/customers', label: 'Customers' },
|
||||||
{ href: '/slots', label: 'Slots' },
|
{ href: '/slots', label: 'Slots' },
|
||||||
{ href: '/items', label: 'Services & products' },
|
{ href: '/items', label: 'Services & products' },
|
||||||
|
{ href: '/passes', label: 'Vouchers & codes' },
|
||||||
{ href: '/calendar', label: 'Events' }
|
{ href: '/calendar', label: 'Events' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -63,10 +63,11 @@ export const actions: Actions = {
|
||||||
const email = String((await request.formData()).get('email') || '');
|
const email = String((await request.formData()).get('email') || '');
|
||||||
const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email));
|
const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email));
|
||||||
if (!result.ok) return result.failure;
|
if (!result.ok) return result.failure;
|
||||||
const { ordersAnonymised, basketsDeleted } = result.value;
|
const { ordersAnonymised, basketsDeleted, passesAnonymised } = result.value;
|
||||||
|
const codes = passesAnonymised ? `, ${passesAnonymised} code${passesAnonymised === 1 ? '' : 's'} anonymised (still usable)` : '';
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.`
|
message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted${codes}.`
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { confirmSubmit } from '$lib/admin/confirm';
|
import { confirmSubmit } from '$lib/admin/confirm';
|
||||||
import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar';
|
import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar';
|
||||||
|
import { formatCode } from '$shared/items';
|
||||||
|
|
||||||
let { data, form } = $props();
|
let { data, form } = $props();
|
||||||
let customer = $derived(data.customer);
|
let customer = $derived(data.customer);
|
||||||
|
|
@ -154,6 +155,16 @@
|
||||||
{/each}
|
{/each}
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
|
{#if customer.codes?.length}
|
||||||
|
<h3 class="mt-6 font-bold">Codes bought</h3>
|
||||||
|
<p class="text-sm text-base-content/60">Bundles and vouchers. Erasing keeps the codes usable but removes the email, recipient and message.</p>
|
||||||
|
<ul class="mt-2 space-y-1 text-sm">
|
||||||
|
{#each customer.codes as code (code.code)}
|
||||||
|
<li><span class="font-mono">{formatCode(code.code)}</span> — {code.name}{code.recipientName ? ` · for ${code.recipientName}` : ''}{code.message ? ` · “${code.message}”` : ''}</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if customer.unpaidBaskets.length}
|
{#if customer.unpaidBaskets.length}
|
||||||
<h3 class="mt-6 font-bold">Unpaid checkouts</h3>
|
<h3 class="mt-6 font-bold">Unpaid checkouts</h3>
|
||||||
<p class="text-sm text-base-content/60">Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.</p>
|
<p class="text-sm text-base-content/60">Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.</p>
|
||||||
|
|
@ -167,7 +178,7 @@
|
||||||
<div class="mt-6 rounded-box border border-error/40 p-4">
|
<div class="mt-6 rounded-box border border-error/40 p-4">
|
||||||
<h3 class="font-bold">Erase this customer</h3>
|
<h3 class="font-bold">Erase this customer</h3>
|
||||||
<p class="mt-1 text-sm text-base-content/70">
|
<p class="mt-1 text-sm text-base-content/70">
|
||||||
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.
|
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.
|
||||||
Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.
|
Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.
|
||||||
</p>
|
</p>
|
||||||
{#if upcoming.length}
|
{#if upcoming.length}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import { fail } from '@sveltejs/kit';
|
import { fail } from '@sveltejs/kit';
|
||||||
import { attempt } from '$lib/server/actions';
|
import { attempt } from '$lib/server/actions';
|
||||||
|
import { parseDurations } from '$shared/items';
|
||||||
import { mapItemRecord } from '$shared/server/shop';
|
import { mapItemRecord } from '$shared/server/shop';
|
||||||
import type { ItemDuration, ItemType } from '$lib/types';
|
import type { BundlePart, ItemDuration, ItemType } from '$lib/types';
|
||||||
import type { Actions, PageServerLoad } from './$types';
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
|
||||||
/** Longest bookable length, in minutes (a booking must fit in one day's window). */
|
/** Longest bookable length, in minutes (a booking must fit in one day's window). */
|
||||||
|
|
@ -25,8 +26,39 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
|
||||||
return durations.sort((a, b) => a.minutes - b.minutes);
|
return durations.sort((a, b) => a.minutes - b.minutes);
|
||||||
}
|
}
|
||||||
|
|
||||||
function itemPayload(data: FormData) {
|
/** Most units of one thing a bundle can hold. */
|
||||||
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
|
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<string, any>[]): 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<string, any>[]) {
|
||||||
|
const rawType = String(data.get('type'));
|
||||||
|
const type: ItemType = rawType === 'item_with_time' || rawType === 'bundle' ? rawType : 'item';
|
||||||
const name = String(data.get('name') || '').trim();
|
const name = String(data.get('name') || '').trim();
|
||||||
if (!name) return { error: 'Name is required.' };
|
if (!name) return { error: 'Name is required.' };
|
||||||
const rawStock = String(data.get('stock') ?? '').trim();
|
const rawStock = String(data.get('stock') ?? '').trim();
|
||||||
|
|
@ -35,7 +67,18 @@ function itemPayload(data: FormData) {
|
||||||
|
|
||||||
let price: number;
|
let price: number;
|
||||||
let durations: ItemDuration[] = [];
|
let durations: ItemDuration[] = [];
|
||||||
if (type === 'item_with_time') {
|
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') {
|
||||||
const parsed = parseDurationRows(data);
|
const parsed = parseDurationRows(data);
|
||||||
if ('error' in parsed) return parsed;
|
if ('error' in parsed) return parsed;
|
||||||
durations = parsed;
|
durations = parsed;
|
||||||
|
|
@ -57,8 +100,12 @@ function itemPayload(data: FormData) {
|
||||||
price,
|
price,
|
||||||
image: String(data.get('image') || '').trim(),
|
image: String(data.get('image') || '').trim(),
|
||||||
type,
|
type,
|
||||||
stock: Number.isNaN(stock) ? null : stock,
|
// 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),
|
||||||
durations,
|
durations,
|
||||||
|
bundleParts,
|
||||||
|
validMonths,
|
||||||
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
|
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
|
||||||
capacity: Number.isNaN(capacity) ? null : capacity,
|
capacity: Number.isNaN(capacity) ? null : capacity,
|
||||||
active: String(data.get('active')) === 'true'
|
active: String(data.get('active')) === 'true'
|
||||||
|
|
@ -66,6 +113,11 @@ function itemPayload(data: FormData) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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 }) => {
|
export const load: PageServerLoad = async ({ locals }) => {
|
||||||
const records = await locals.pb
|
const records = await locals.pb
|
||||||
.collection('items')
|
.collection('items')
|
||||||
|
|
@ -76,7 +128,7 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
|
|
||||||
export const actions: Actions = {
|
export const actions: Actions = {
|
||||||
create: async ({ request, locals }) => {
|
create: async ({ request, locals }) => {
|
||||||
const result = itemPayload(await request.formData());
|
const result = itemPayload(await request.formData(), await allItems(locals.pb));
|
||||||
if ('error' in result) return fail(400, { message: result.error });
|
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));
|
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload));
|
||||||
if (!created.ok) return created.failure;
|
if (!created.ok) return created.failure;
|
||||||
|
|
@ -86,7 +138,7 @@ export const actions: Actions = {
|
||||||
const data = await request.formData();
|
const data = await request.formData();
|
||||||
const id = String(data.get('id') || '');
|
const id = String(data.get('id') || '');
|
||||||
if (!id) return fail(400, { message: 'Item id is required.' });
|
if (!id) return fail(400, { message: 'Item id is required.' });
|
||||||
const result = itemPayload(data);
|
const result = itemPayload(data, await allItems(locals.pb));
|
||||||
if ('error' in result) return fail(400, { message: result.error });
|
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));
|
const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload));
|
||||||
if (!updated.ok) return updated.failure;
|
if (!updated.ok) return updated.failure;
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,9 @@
|
||||||
stock: string;
|
stock: string;
|
||||||
/** Service lengths and prices, as typed (one form row each). */
|
/** Service lengths and prices, as typed (one form row each). */
|
||||||
durations: { minutes: string; price: string }[];
|
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;
|
bufferMinutes: string;
|
||||||
capacity: string;
|
capacity: string;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
|
|
@ -34,9 +37,48 @@
|
||||||
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
|
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
|
||||||
|
|
||||||
function emptyDraft(): ItemDraft {
|
function emptyDraft(): ItemDraft {
|
||||||
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true };
|
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
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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() {
|
function addDuration() {
|
||||||
const last = Number(draft.durations.at(-1)?.minutes) || 0;
|
const last = Number(draft.durations.at(-1)?.minutes) || 0;
|
||||||
draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' });
|
draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' });
|
||||||
|
|
@ -64,6 +106,8 @@
|
||||||
type: item.type,
|
type: item.type,
|
||||||
stock: item.stock == null ? '' : String(item.stock),
|
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: '' }],
|
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),
|
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
|
||||||
capacity: item.capacity == null ? '' : String(item.capacity),
|
capacity: item.capacity == null ? '' : String(item.capacity),
|
||||||
active: item.active
|
active: item.active
|
||||||
|
|
@ -96,7 +140,7 @@
|
||||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||||
<div>
|
<div>
|
||||||
<h1 class="text-3xl font-bold">Services & products</h1>
|
<h1 class="text-3xl font-bold">Services & products</h1>
|
||||||
<p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p>
|
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.</p>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
|
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -120,10 +164,16 @@
|
||||||
<span class="font-semibold">{item.name}</span>
|
<span class="font-semibold">{item.name}</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
|
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span></td>
|
||||||
<td>{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}</td>
|
<td>{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}</td>
|
||||||
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
|
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
|
||||||
<td>{item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td>
|
<td>
|
||||||
|
{#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}
|
||||||
|
</td>
|
||||||
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
|
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
|
||||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
@ -157,10 +207,52 @@
|
||||||
<select class="select w-full" name="type" bind:value={draft.type}>
|
<select class="select w-full" name="type" bind:value={draft.type}>
|
||||||
<option value="item">Product</option>
|
<option value="item">Product</option>
|
||||||
<option value="item_with_time">Service (bookable)</option>
|
<option value="item_with_time">Service (bookable)</option>
|
||||||
|
<option value="bundle">Bundle / voucher (paid now, booked later with a code)</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
{#if draft.type === 'item'}
|
{#if draft.type === 'bundle'}
|
||||||
|
<div class="fieldset">
|
||||||
|
<span class="fieldset-legend">What’s in it</span>
|
||||||
|
<div class="space-y-2">
|
||||||
|
{#each draft.parts as row, i}
|
||||||
|
{@const partItem = items.find((item) => item.id === row.item)}
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<input class="input w-20" type="number" min="1" max="50" step="1" name="partCount" required aria-label="How many" bind:value={row.count} />
|
||||||
|
<span>×</span>
|
||||||
|
<select class="select w-56" name="partItem" required aria-label="Service or product" value={row.item} onchange={(e) => choosePartItem(row, e.currentTarget.value)}>
|
||||||
|
<option value="" disabled>Choose…</option>
|
||||||
|
{#each partChoices as choice (choice.id)}<option value={choice.id}>{choice.name}{choice.type === 'item' ? ' (product)' : ''}</option>{/each}
|
||||||
|
</select>
|
||||||
|
{#if partItem?.type === 'item_with_time'}
|
||||||
|
<select class="select w-36" name="partMinutes" aria-label="Length" bind:value={row.minutes}>
|
||||||
|
{#each partItem.durations as duration (duration.minutes)}<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>{/each}
|
||||||
|
</select>
|
||||||
|
{:else}
|
||||||
|
<input type="hidden" name="partMinutes" value="" />
|
||||||
|
{/if}
|
||||||
|
{#if draft.parts.length > 1}
|
||||||
|
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove this part" onclick={() => draft.parts.splice(i, 1)}>✕</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={() => draft.parts.push({ item: '', minutes: '', count: '1' })}>+ Add a service or product</button>
|
||||||
|
<span class="label whitespace-normal">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.</span>
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-x-4 md:grid-cols-2">
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Bundle price ({data.currency})</span>
|
||||||
|
<input class="input w-full" type="number" step="0.01" min="0.01" name="price" required bind:value={draft.price} />
|
||||||
|
{#if partsListPrice}<span class="label">Bought separately: {money.format(partsListPrice)}</span>{/if}
|
||||||
|
</label>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Valid for (months)</span>
|
||||||
|
<input class="input w-full" type="number" min="1" max="120" step="1" name="validMonths" placeholder="No expiry" bind:value={draft.validMonths} />
|
||||||
|
<span class="label">From the day it’s bought. Check local rules on minimum validity for gift cards.</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{:else if draft.type === 'item'}
|
||||||
<div class="grid gap-x-4 md:grid-cols-2">
|
<div class="grid gap-x-4 md:grid-cols-2">
|
||||||
<label class="fieldset">
|
<label class="fieldset">
|
||||||
<span class="fieldset-legend">Price ({data.currency})</span>
|
<span class="fieldset-legend">Price ({data.currency})</span>
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { fail } from '@sveltejs/kit';
|
import { fail } from '@sveltejs/kit';
|
||||||
import { sendOrderEmails, type EmailKind } from '$lib/server/email';
|
import { sendOrderEmails, type EmailKind } from '$lib/server/email';
|
||||||
|
import { formatCode } from '$shared/items';
|
||||||
import type { Actions, PageServerLoad } from './$types';
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ locals }) => {
|
export const load: PageServerLoad = async ({ locals }) => {
|
||||||
|
|
@ -8,13 +9,20 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
// can't be ordered chronologically).
|
// can't be ordered chronologically).
|
||||||
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
|
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
|
||||||
|
|
||||||
// All lines in one request (previously one request per order).
|
// All lines in one request (previously one request per order), with the
|
||||||
const lineRecords = records.length
|
// code that paid each; and the codes each order bought.
|
||||||
? await locals.pb
|
const [lineRecords, passRecords] = records.length
|
||||||
|
? await Promise.all([
|
||||||
|
locals.pb
|
||||||
.collection('order_lines')
|
.collection('order_lines')
|
||||||
.getFullList({ sort: 'start' })
|
.getFullList({ sort: 'start', expand: 'pass' })
|
||||||
|
.catch(() => []),
|
||||||
|
locals.pb
|
||||||
|
.collection('passes')
|
||||||
|
.getFullList({ filter: "order != ''", sort: 'created', fields: 'order,code,name,recipientName' })
|
||||||
.catch(() => [])
|
.catch(() => [])
|
||||||
: [];
|
])
|
||||||
|
: [[], []];
|
||||||
const linesByOrder = new Map<string, typeof lineRecords>();
|
const linesByOrder = new Map<string, typeof lineRecords>();
|
||||||
for (const line of lineRecords) {
|
for (const line of lineRecords) {
|
||||||
const list = linesByOrder.get(line.order) ?? [];
|
const list = linesByOrder.get(line.order) ?? [];
|
||||||
|
|
@ -40,8 +48,12 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
quantity: Number(line.quantity) || 1,
|
quantity: Number(line.quantity) || 1,
|
||||||
lineType: String(line.lineType || 'item'),
|
lineType: String(line.lineType || 'item'),
|
||||||
start: line.start ? String(line.start) : '',
|
start: line.start ? String(line.start) : '',
|
||||||
minutes: Number(line.minutes) || 0
|
minutes: Number(line.minutes) || 0,
|
||||||
}))
|
passCode: line.expand?.pass?.code ? formatCode(String(line.expand.pass.code)) : ''
|
||||||
|
})),
|
||||||
|
passes: passRecords
|
||||||
|
.filter((pass) => pass.order === record.id)
|
||||||
|
.map((pass) => ({ code: formatCode(String(pass.code)), name: String(pass.name || ''), recipientName: String(pass.recipientName || '') }))
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return { orders };
|
return { orders };
|
||||||
|
|
|
||||||
|
|
@ -75,9 +75,18 @@
|
||||||
{#if line.lineType === 'slot' && line.start}
|
{#if line.lineType === 'slot' && line.start}
|
||||||
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</span>
|
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</span>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if line.passCode}
|
||||||
|
<span class="block text-sm text-base-content/60">Paid with code <a class="link font-mono" href="/passes?q={encodeURIComponent(line.passCode)}">{line.passCode}</a></span>
|
||||||
|
{/if}
|
||||||
</li>
|
</li>
|
||||||
{/each}
|
{/each}
|
||||||
</ul>
|
</ul>
|
||||||
|
{#if order.passes.length}
|
||||||
|
<p class="mt-2 text-sm">
|
||||||
|
{order.passes.length === 1 ? 'Code' : 'Codes'} bought:
|
||||||
|
{#each order.passes as pass, i (pass.code)}{i ? ', ' : ''}<a class="link font-mono" href="/passes?q={encodeURIComponent(pass.code)}">{pass.code}</a>{pass.recipientName ? ` (for ${pass.recipientName})` : ''}{/each}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if order.customerDetails?.notes}
|
{#if order.customerDetails?.notes}
|
||||||
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
||||||
|
|
|
||||||
71
app-admin/src/routes/passes/+page.server.ts
Normal file
71
app-admin/src/routes/passes/+page.server.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import { zonedInputToIso } from '$lib/calendar';
|
||||||
|
import { hookError, issuePass, listPasses, updatePass } from '$lib/server/passes';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ locals, url }) => {
|
||||||
|
const q = url.searchParams.get('q')?.trim() ?? '';
|
||||||
|
const [passes, bundles] = await Promise.all([
|
||||||
|
listPasses(locals.pb, q).catch((e) => {
|
||||||
|
console.error('[passes] could not list codes', e);
|
||||||
|
return null;
|
||||||
|
}),
|
||||||
|
locals.pb
|
||||||
|
.collection('items')
|
||||||
|
.getFullList({ filter: "type = 'bundle'", sort: 'name', fields: 'id,name,validMonths,active' })
|
||||||
|
.catch(() => [])
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
q,
|
||||||
|
passes: passes ?? [],
|
||||||
|
passesError: passes === null,
|
||||||
|
bundles: bundles.map((b) => ({ id: b.id, name: String(b.name), validMonths: Number(b.validMonths) || null, active: b.active !== false }))
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions: Actions = {
|
||||||
|
/** Void or reactivate a code. */
|
||||||
|
status: async ({ request, locals }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const status = String(data.get('status')) === 'void' ? 'void' : 'active';
|
||||||
|
try {
|
||||||
|
await updatePass(locals.pb, { id: String(data.get('id') || ''), status });
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { message: hookError(e, 'Could not change the code.') });
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
/** Change when a code expires (empty date: never). */
|
||||||
|
expiry: async ({ request, locals }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const date = data.get('never') ? '' : String(data.get('expiresAt') || '');
|
||||||
|
// The end of that day in the site's timezone.
|
||||||
|
const expiresAt = date ? zonedInputToIso(`${date}T23:59`, siteTimezone()) : '';
|
||||||
|
if (date && !expiresAt) return fail(400, { message: 'Invalid date.' });
|
||||||
|
try {
|
||||||
|
await updatePass(locals.pb, { id: String(data.get('id') || ''), expiresAt });
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { message: hookError(e, 'Could not change the expiry date.') });
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
/** Issue a code without a purchase (a gift from the studio, a replacement). */
|
||||||
|
issue: async ({ request, locals }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
const { pass } = await issuePass(locals.pb, {
|
||||||
|
itemId: String(data.get('itemId') || ''),
|
||||||
|
email: String(data.get('email') || ''),
|
||||||
|
recipientName: String(data.get('recipientName') || ''),
|
||||||
|
message: String(data.get('message') || ''),
|
||||||
|
months: String(data.get('months') ?? '')
|
||||||
|
});
|
||||||
|
return { issued: pass.code };
|
||||||
|
} catch (e) {
|
||||||
|
return fail(400, { message: hookError(e, 'Could not issue the code.') });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
231
app-admin/src/routes/passes/+page.svelte
Normal file
231
app-admin/src/routes/passes/+page.svelte
Normal file
|
|
@ -0,0 +1,231 @@
|
||||||
|
<script lang="ts">
|
||||||
|
import { enhance } from '$app/forms';
|
||||||
|
import type { SubmitFunction } from '@sveltejs/kit';
|
||||||
|
import { formatDateTime, toZonedDatetimeInput } from '$lib/calendar';
|
||||||
|
import { confirmSubmit } from '$lib/admin/confirm';
|
||||||
|
import Modal from '$lib/admin/Modal.svelte';
|
||||||
|
import { formatDuration } from '$shared/items';
|
||||||
|
|
||||||
|
let { data, form } = $props();
|
||||||
|
let passes = $derived(data.passes || []);
|
||||||
|
type Pass = (typeof passes)[number];
|
||||||
|
|
||||||
|
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
|
||||||
|
|
||||||
|
const dateOnly = (iso: string) => (iso ? toZonedDatetimeInput(iso, data.timezone).slice(0, 10) : '');
|
||||||
|
const expired = (pass: Pass) => !!pass.expiresAt && Date.parse(pass.expiresAt) <= Date.now();
|
||||||
|
const bookable = (pass: Pass) => pass.parts.filter((p) => p.redeemable);
|
||||||
|
const partLabel = (p: Pass['parts'][number]) => `${p.name}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`;
|
||||||
|
|
||||||
|
function passStatus(pass: Pass): { label: string; badge: string } {
|
||||||
|
if (pass.status === 'void') return { label: 'Void', badge: 'badge-ghost' };
|
||||||
|
if (expired(pass)) return { label: 'Expired', badge: 'badge-warning' };
|
||||||
|
if (bookable(pass).every((p) => p.left === 0 && p.held === 0)) return { label: 'Used up', badge: 'badge-info badge-soft' };
|
||||||
|
return { label: 'Active', badge: 'badge-success' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Manage one code ──
|
||||||
|
let managing = $state<Pass | null>(null);
|
||||||
|
let showManage = $state(false);
|
||||||
|
let manageError = $state('');
|
||||||
|
let expiryDraft = $state('');
|
||||||
|
|
||||||
|
function manage(pass: Pass) {
|
||||||
|
managing = pass;
|
||||||
|
expiryDraft = dateOnly(pass.expiresAt);
|
||||||
|
manageError = '';
|
||||||
|
showManage = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errors stay in the open modal; a success closes it and reloads the list.
|
||||||
|
const submitManage: SubmitFunction = () => {
|
||||||
|
manageError = '';
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'failure') {
|
||||||
|
manageError = String(result.data?.message || 'Could not save.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showManage = false;
|
||||||
|
await update();
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Issue a code ──
|
||||||
|
let showIssue = $state(false);
|
||||||
|
let issueError = $state('');
|
||||||
|
let issueBundle = $state('');
|
||||||
|
let issueMonths = $state('');
|
||||||
|
let issued = $derived(form && 'issued' in form ? String(form.issued) : '');
|
||||||
|
|
||||||
|
function openIssue() {
|
||||||
|
issueError = '';
|
||||||
|
issueBundle = data.bundles[0]?.id ?? '';
|
||||||
|
issueMonths = String(data.bundles[0]?.validMonths ?? '');
|
||||||
|
showIssue = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitIssue: SubmitFunction = () => {
|
||||||
|
issueError = '';
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'failure') {
|
||||||
|
issueError = String(result.data?.message || 'Could not issue the code.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showIssue = false;
|
||||||
|
await update();
|
||||||
|
};
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Vouchers & codes | CMS</title></svelte:head>
|
||||||
|
|
||||||
|
<div class="space-y-6">
|
||||||
|
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||||
|
<div>
|
||||||
|
<h1 class="text-3xl font-bold">Vouchers & codes</h1>
|
||||||
|
<p class="max-w-3xl text-base-content/60">
|
||||||
|
A code is made for every bundle or voucher bought (set them up under Services & products). Whoever has the code enters it in the basket, and the sessions it includes are then already paid for. Places used and left are counted from bookings; a refunded booking gives its place back.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" type="button" disabled={!data.bundles.length} onclick={openIssue}>Issue a code</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
|
||||||
|
{#if issued}<div class="alert alert-success" role="status">Code <strong class="font-mono">{issued}</strong> issued — send it to whoever it’s for.</div>{/if}
|
||||||
|
{#if data.passesError}<div class="alert alert-error" role="alert">Could not load the codes — is the database reachable?</div>{/if}
|
||||||
|
{#if !data.bundles.length}<div class="alert" role="status">No bundles yet — add one under Services & products (type “Bundle / voucher”).</div>{/if}
|
||||||
|
|
||||||
|
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||||
|
<form method="GET" class="mb-4 flex flex-wrap gap-2">
|
||||||
|
<input class="input w-80 max-w-full" type="search" name="q" placeholder="Code, email, name or bundle" aria-label="Search codes" value={data.q} />
|
||||||
|
<button class="btn" type="submit">Search</button>
|
||||||
|
{#if data.q}<a class="btn btn-ghost" href="/passes">Show all</a>{/if}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th>Code</th><th>Bundle</th><th>Bought by / for</th><th>Left to book</th><th>Expires</th><th>Status</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{#each passes as pass (pass.id)}
|
||||||
|
{@const s = passStatus(pass)}
|
||||||
|
<tr>
|
||||||
|
<td class="font-mono font-semibold tracking-wider whitespace-nowrap">{pass.code}</td>
|
||||||
|
<td>{pass.name}</td>
|
||||||
|
<td>
|
||||||
|
<span class="block">{pass.email || (pass.anonymisedAt ? 'Anonymised' : pass.order ? '—' : 'Issued here')}</span>
|
||||||
|
{#if pass.recipientName}<span class="block text-sm text-base-content/60">for {pass.recipientName}</span>{/if}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{#each bookable(pass) as part (`${part.item}|${part.minutes}`)}
|
||||||
|
<span class="block whitespace-nowrap">{part.left}/{part.count} {partLabel(part)}{part.held ? ` · ${part.held} in a basket` : ''}</span>
|
||||||
|
{/each}
|
||||||
|
</td>
|
||||||
|
<td class="whitespace-nowrap">{pass.expiresAt ? dateOnly(pass.expiresAt) : 'Never'}</td>
|
||||||
|
<td><span class="badge {s.badge}">{s.label}</span></td>
|
||||||
|
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => manage(pass)}>Manage</button></td>
|
||||||
|
</tr>
|
||||||
|
{:else}
|
||||||
|
<tr><td colspan="7" class="py-10 text-center text-base-content/60">{data.q ? 'No codes match that search.' : 'No codes yet — they appear here when a bundle is bought.'}</td></tr>
|
||||||
|
{/each}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{#if passes.length === 200}<p class="mt-2 text-sm text-base-content/60">Showing the newest 200 — search to find older codes.</p>{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Modal bind:open={showManage} title={managing ? `Code ${managing.code}` : 'Code'} wide>
|
||||||
|
{#if managing}
|
||||||
|
{#if manageError}<div class="alert alert-error mb-3 text-sm" role="alert">{manageError}</div>{/if}
|
||||||
|
<p class="font-semibold">{managing.name}{managing.recipientName ? ` · for ${managing.recipientName}` : ''}</p>
|
||||||
|
{#if managing.message}<p class="mt-1 text-sm italic text-base-content/70">“{managing.message}”</p>{/if}
|
||||||
|
<p class="mt-1 text-sm text-base-content/60">
|
||||||
|
{managing.created ? `Created ${formatDateTime(managing.created, data.timezone)}` : ''}{managing.order ? ` · order ${managing.order}` : ' · issued here'}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table class="table table-sm mt-3">
|
||||||
|
<thead><tr><th>Part</th><th>Used</th><th>In a basket</th><th>Left</th><th class="text-right">Share of the price</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{#each managing.parts as part (`${part.item}|${part.minutes}`)}
|
||||||
|
<tr>
|
||||||
|
<td>{part.count}× {partLabel(part)}</td>
|
||||||
|
{#if part.redeemable}
|
||||||
|
<td>{part.used}</td><td>{part.held}</td><td>{part.left}</td>
|
||||||
|
{:else}
|
||||||
|
<td colspan="3" class="text-base-content/60">Handed over with the purchase</td>
|
||||||
|
{/if}
|
||||||
|
<td class="text-right">{money.format(part.value)}{part.count > 1 ? ` (${money.format(part.value / part.count)} each)` : ''}</td>
|
||||||
|
</tr>
|
||||||
|
{/each}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<p class="mt-1 text-xs text-base-content/60">The share of the price is what each part is worth for a partial refund (refund in Stripe, then mark the booking’s order refunded to give its place back).</p>
|
||||||
|
|
||||||
|
<form method="POST" action="?/expiry" use:enhance={submitManage} class="mt-4 flex flex-wrap items-end gap-2">
|
||||||
|
<input type="hidden" name="id" value={managing.id} />
|
||||||
|
<label class="fieldset py-0">
|
||||||
|
<span class="fieldset-legend">Expires ({data.timezone})</span>
|
||||||
|
<input class="input w-48" type="date" name="expiresAt" bind:value={expiryDraft} />
|
||||||
|
</label>
|
||||||
|
<button class="btn" type="submit">Save expiry</button>
|
||||||
|
<button class="btn btn-ghost" type="submit" name="never" value="1">Never expires</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="modal-action justify-between">
|
||||||
|
<form method="POST" action="?/status" use:enhance={submitManage}>
|
||||||
|
<input type="hidden" name="id" value={managing.id} />
|
||||||
|
{#if managing.status === 'void'}
|
||||||
|
<input type="hidden" name="status" value="active" />
|
||||||
|
<button class="btn btn-outline" type="submit">Reactivate</button>
|
||||||
|
{:else}
|
||||||
|
<input type="hidden" name="status" value="void" />
|
||||||
|
<button class="btn btn-error btn-outline" type="submit" onclick={confirmSubmit(`Void ${managing.code}? It can no longer be used (bookings already made stay).`)}>Void code</button>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
<button class="btn" type="button" onclick={() => (showManage = false)}>Close</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal bind:open={showIssue} title="Issue a code">
|
||||||
|
<form method="POST" action="?/issue" use:enhance={submitIssue} class="space-y-1">
|
||||||
|
{#if issueError}<div class="alert alert-error mb-2 text-sm" role="alert">{issueError}</div>{/if}
|
||||||
|
<p class="text-sm text-base-content/70">A code without a purchase — a gift from you, or a replacement. Nothing is charged.</p>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Bundle</span>
|
||||||
|
<select
|
||||||
|
class="select w-full"
|
||||||
|
name="itemId"
|
||||||
|
required
|
||||||
|
value={issueBundle}
|
||||||
|
onchange={(e) => {
|
||||||
|
issueBundle = e.currentTarget.value;
|
||||||
|
issueMonths = String(data.bundles.find((b) => b.id === issueBundle)?.validMonths ?? '');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{#each data.bundles as bundle (bundle.id)}<option value={bundle.id}>{bundle.name}{bundle.active ? '' : ' (inactive)'}</option>{/each}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Valid for (months)</span>
|
||||||
|
<input class="input w-32" type="number" min="0" max="120" step="1" name="months" bind:value={issueMonths} />
|
||||||
|
<span class="label">0 = no expiry.</span>
|
||||||
|
</label>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">For <span class="font-normal text-base-content/50">(optional)</span></span>
|
||||||
|
<input class="input w-full" name="recipientName" maxlength="180" />
|
||||||
|
</label>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Email <span class="font-normal text-base-content/50">(optional, to find it again)</span></span>
|
||||||
|
<input class="input w-full" type="email" name="email" maxlength="320" />
|
||||||
|
</label>
|
||||||
|
<label class="fieldset">
|
||||||
|
<span class="fieldset-legend">Note <span class="font-normal text-base-content/50">(optional)</span></span>
|
||||||
|
<input class="input w-full" name="message" maxlength="1000" />
|
||||||
|
</label>
|
||||||
|
<div class="modal-action">
|
||||||
|
<button class="btn" type="button" onclick={() => (showIssue = false)}>Cancel</button>
|
||||||
|
<button class="btn btn-primary" type="submit">Issue code</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit';
|
import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { env } from '$env/dynamic/private';
|
import { env } from '$env/dynamic/private';
|
||||||
import { getFileUrl } from '$lib/pb';
|
import { getFileUrl } from '$lib/pb';
|
||||||
import type { Basket, BasketLine, OrderRecord } from '$lib/types';
|
import type { Basket, BasketLine, OrderRecord, PassSummary } from '$lib/types';
|
||||||
import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email';
|
import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email';
|
||||||
|
|
||||||
// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All
|
// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All
|
||||||
|
|
@ -51,7 +51,7 @@ export function postJson<T>(path: string, data: unknown): Promise<T> {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null;
|
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[]; pass?: PassSummary | null } | null;
|
||||||
|
|
||||||
/** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */
|
/** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */
|
||||||
const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString();
|
const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString();
|
||||||
|
|
@ -59,7 +59,7 @@ const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).t
|
||||||
/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */
|
/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */
|
||||||
export function mapBasket(payload: BasketPayload): Basket | null {
|
export function mapBasket(payload: BasketPayload): Basket | null {
|
||||||
if (!payload) return null;
|
if (!payload) return null;
|
||||||
const { record, lines } = payload;
|
const { record, lines, pass } = payload;
|
||||||
const mappedLines: BasketLine[] = lines.map((line) => {
|
const mappedLines: BasketLine[] = lines.map((line) => {
|
||||||
const item = line.expand?.item;
|
const item = line.expand?.item;
|
||||||
const slot = line.expand?.slot;
|
const slot = line.expand?.slot;
|
||||||
|
|
@ -79,6 +79,10 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
||||||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||||
slotKind: slot?.kind,
|
slotKind: slot?.kind,
|
||||||
slotCapacity: slot?.capacity,
|
slotCapacity: slot?.capacity,
|
||||||
|
passCovered: !!line.pass,
|
||||||
|
giftTo: line.giftTo || '',
|
||||||
|
giftMessage: line.giftMessage || '',
|
||||||
|
bundle: line.bundle || undefined,
|
||||||
heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined
|
heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
@ -90,6 +94,7 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
||||||
customerDetails: record.customerDetails || null,
|
customerDetails: record.customerDetails || null,
|
||||||
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
||||||
lines: mappedLines,
|
lines: mappedLines,
|
||||||
|
pass: pass ?? null,
|
||||||
serverNow: Date.now()
|
serverNow: Date.now()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -102,7 +107,7 @@ export async function getBasket(basketId: string | undefined): Promise<Basket |
|
||||||
return mapBasket(basket);
|
return mapBasket(basket);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[]): OrderRecord {
|
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[], passes: PassSummary[] = []): OrderRecord {
|
||||||
return {
|
return {
|
||||||
id: order.id,
|
id: order.id,
|
||||||
basket: order.basket,
|
basket: order.basket,
|
||||||
|
|
@ -122,8 +127,10 @@ export function mapOrder(order: Record<string, any>, lines: Record<string, any>[
|
||||||
name: l.name,
|
name: l.name,
|
||||||
price: l.price,
|
price: l.price,
|
||||||
start: l.start || null,
|
start: l.start || null,
|
||||||
minutes: l.minutes || null
|
minutes: l.minutes || null,
|
||||||
}))
|
passCode: l.passCode || ''
|
||||||
|
})),
|
||||||
|
passes
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
||||||
minutes: body.minutes,
|
minutes: body.minutes,
|
||||||
start: body.start,
|
start: body.start,
|
||||||
seats: body.seats,
|
seats: body.seats,
|
||||||
|
code: body.code,
|
||||||
|
giftTo: body.giftTo,
|
||||||
|
giftMessage: body.giftMessage,
|
||||||
lineId: body.lineId,
|
lineId: body.lineId,
|
||||||
quantity: body.quantity,
|
quantity: body.quantity,
|
||||||
basketId: cookies.get(BASKET_COOKIE) || ''
|
basketId: cookies.get(BASKET_COOKIE) || ''
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,15 @@
|
||||||
import { json, error } from '@sveltejs/kit';
|
import { json, error } from '@sveltejs/kit';
|
||||||
import type { RequestHandler } from './$types';
|
import type { RequestHandler } from './$types';
|
||||||
import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
|
import { BASKET_COOKIE, jsonErrors, postJson, sendAndRecordOrderEmails } from '$lib/server/shop';
|
||||||
|
import type { OrderEmailData } from '$lib/server/email';
|
||||||
|
|
||||||
|
type CheckoutResult = { clientSecret: string } | { free: true; orderId: string; orderEmail: OrderEmailData };
|
||||||
|
|
||||||
// Starts payment: PocketBase re-validates the basket, extends slot holds and
|
// Starts payment: PocketBase re-validates the basket, extends slot holds and
|
||||||
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop).
|
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). When codes
|
||||||
|
// cover the whole basket there is nothing to pay: PocketBase creates the
|
||||||
|
// order straight away, and the booking emails are sent from here (as the
|
||||||
|
// Stripe webhook route does after a payment).
|
||||||
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
||||||
let body: Record<string, unknown>;
|
let body: Record<string, unknown>;
|
||||||
try {
|
try {
|
||||||
|
|
@ -12,12 +18,16 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
||||||
throw error(400, 'Invalid JSON body');
|
throw error(400, 'Invalid JSON body');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
|
const result = await postJson<CheckoutResult>('/checkout', {
|
||||||
basketId: cookies.get(BASKET_COOKIE) || '',
|
basketId: cookies.get(BASKET_COOKIE) || '',
|
||||||
name: body.name,
|
name: body.name,
|
||||||
email: body.email,
|
email: body.email,
|
||||||
phone: body.phone,
|
phone: body.phone,
|
||||||
notes: body.notes
|
notes: body.notes
|
||||||
});
|
});
|
||||||
return json({ clientSecret });
|
if ('free' in result) {
|
||||||
|
void sendAndRecordOrderEmails(result.orderEmail);
|
||||||
|
return json({ free: true, orderId: result.orderId });
|
||||||
|
}
|
||||||
|
return json({ clientSecret: result.clientSecret });
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,27 @@
|
||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
|
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
|
||||||
|
import type { PassSummary } from '$lib/types';
|
||||||
|
|
||||||
type OrderStatus =
|
type OrderStatus =
|
||||||
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
|
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
|
||||||
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
|
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[]; passes: PassSummary[] };
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ url, cookies }) => {
|
export const load: PageServerLoad = async ({ url, cookies }) => {
|
||||||
|
// After a Stripe payment: ?payment_intent=… (checked with Stripe by
|
||||||
|
// PocketBase; the webhook may not have created the order yet). An order
|
||||||
|
// paid entirely with codes: ?order=…, which PocketBase only shows to the
|
||||||
|
// basket it came from (this visitor's cookie).
|
||||||
const intentId = url.searchParams.get('payment_intent');
|
const intentId = url.searchParams.get('payment_intent');
|
||||||
if (!intentId) return { state: 'missing' as const };
|
const orderId = url.searchParams.get('order');
|
||||||
|
let query: string;
|
||||||
|
if (intentId) query = `payment_intent=${encodeURIComponent(intentId)}`;
|
||||||
|
else if (orderId) query = `order=${encodeURIComponent(orderId)}&basket=${encodeURIComponent(cookies.get(BASKET_COOKIE) || '')}`;
|
||||||
|
else return { state: 'missing' as const };
|
||||||
|
|
||||||
// PocketBase checks the intent with Stripe and looks up the order (the
|
const status = await shopFetch<OrderStatus>(`/order?${query}`);
|
||||||
// webhook is the source of truth and may not have landed yet).
|
|
||||||
const status = await shopFetch<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`);
|
|
||||||
if (status.state !== 'paid') return { state: status.state };
|
if (status.state !== 'paid') return { state: status.state };
|
||||||
|
|
||||||
cookies.delete(BASKET_COOKIE, { path: '/' });
|
// Keep the cookie for a code-paid order: it is what lets this page show it on reload.
|
||||||
return { state: 'paid' as const, order: mapOrder(status.order, status.lines) };
|
if (intentId) cookies.delete(BASKET_COOKIE, { path: '/' });
|
||||||
|
return { state: 'paid' as const, order: mapOrder(status.order, status.lines, status.passes) };
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { formatInstant, formatPrice } from '$shared/calendar';
|
import { formatInstant, formatPrice } from '$shared/calendar';
|
||||||
|
import { formatDuration } from '$shared/items';
|
||||||
|
|
||||||
let { data } = $props();
|
let { data } = $props();
|
||||||
|
|
||||||
|
|
@ -32,6 +33,9 @@
|
||||||
{#if line.start}
|
{#if line.start}
|
||||||
<div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div>
|
<div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if line.passCode}
|
||||||
|
<div class="text-sm text-charcoal/60">Paid with code {line.passCode}</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<span>{formatPrice(line.price * line.quantity, data.currency)}</span>
|
<span>{formatPrice(line.price * line.quantity, data.currency)}</span>
|
||||||
</li>
|
</li>
|
||||||
|
|
@ -42,6 +46,28 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#if data.order.passes?.length}
|
||||||
|
<!-- Bundles bought: their codes (also in the confirmation email). -->
|
||||||
|
<div class="mt-6 rounded-box border border-sage/40 bg-sage/10 p-6 text-left">
|
||||||
|
<h2 class="font-serif text-xl">Your {data.order.passes.length === 1 ? 'code' : 'codes'}</h2>
|
||||||
|
<p class="mt-1 text-sm text-charcoal/70">Enter a code in the basket when you book — the sessions it includes are then already paid for.</p>
|
||||||
|
{#each data.order.passes as pass (pass.id)}
|
||||||
|
<div class="mt-4 rounded-xl bg-white p-4">
|
||||||
|
<div class="flex flex-wrap items-baseline justify-between gap-2">
|
||||||
|
<span class="font-mono text-2xl font-semibold tracking-widest">{pass.code}</span>
|
||||||
|
<span class="text-sm text-charcoal/60">{pass.expiresAt ? `Valid until ${formatInstant(pass.expiresAt, data.timezone, { day: 'numeric', month: 'long', year: 'numeric' })}` : 'No expiry'}</span>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 font-semibold">{pass.name}{pass.recipientName ? ` · for ${pass.recipientName}` : ''}</p>
|
||||||
|
<ul class="mt-1 text-sm text-charcoal/70">
|
||||||
|
{#each pass.parts as part (`${part.item}|${part.minutes}`)}
|
||||||
|
<li>{part.count}× {part.name}{part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with your order'}</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Book another</a>
|
<a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Book another</a>
|
||||||
{:else if data.state === 'processing'}
|
{:else if data.state === 'processing'}
|
||||||
<h1 class="font-serif text-4xl">Processing your payment…</h1>
|
<h1 class="font-serif text-4xl">Processing your payment…</h1>
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ export type BasketStore = ReturnType<typeof createBasketStore>;
|
||||||
export function createBasketStore(initial: Basket | null) {
|
export function createBasketStore(initial: Basket | null) {
|
||||||
let lines = $state<BasketLine[]>(initial?.lines ?? []);
|
let lines = $state<BasketLine[]>(initial?.lines ?? []);
|
||||||
let status = $state<Basket['status']>(initial?.status ?? 'active');
|
let status = $state<Basket['status']>(initial?.status ?? 'active');
|
||||||
|
let pass = $state<Basket['pass']>(initial?.pass ?? null);
|
||||||
// Browser clock minus server clock, so hold countdowns survive a wrong clock.
|
// Browser clock minus server clock, so hold countdowns survive a wrong clock.
|
||||||
let clockOffset = $state(clockOffsetOf(initial));
|
let clockOffset = $state(clockOffsetOf(initial));
|
||||||
|
|
||||||
|
|
@ -40,6 +41,7 @@ export function createBasketStore(initial: Basket | null) {
|
||||||
function applyBasket(basket: Basket | null) {
|
function applyBasket(basket: Basket | null) {
|
||||||
lines = basket?.lines ?? [];
|
lines = basket?.lines ?? [];
|
||||||
status = basket?.status ?? 'active';
|
status = basket?.status ?? 'active';
|
||||||
|
pass = basket?.pass ?? null;
|
||||||
clockOffset = clockOffsetOf(basket);
|
clockOffset = clockOffsetOf(basket);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -93,6 +95,20 @@ export function createBasketStore(initial: Basket | null) {
|
||||||
await applySlotChange(await callApi({ action: 'renew_holds' }));
|
await applySlotChange(await callApi({ action: 'renew_holds' }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Apply a bundle/voucher code: the bookings it covers cost nothing. */
|
||||||
|
async function applyCode(code: string) {
|
||||||
|
applyBasket(await callApi({ action: 'apply_code', code }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeCode() {
|
||||||
|
applyBasket(await callApi({ action: 'remove_code' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Who a bundle in the basket is for (empty: not a gift). */
|
||||||
|
async function setGift(lineId: string, giftTo: string, giftMessage: string) {
|
||||||
|
applyBasket(await callApi({ action: 'set_gift', lineId, giftTo, giftMessage }));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
get lines() {
|
get lines() {
|
||||||
return lines;
|
return lines;
|
||||||
|
|
@ -109,13 +125,19 @@ export function createBasketStore(initial: Basket | null) {
|
||||||
get holdDeadline() {
|
get holdDeadline() {
|
||||||
return holdDeadline;
|
return holdDeadline;
|
||||||
},
|
},
|
||||||
|
get pass() {
|
||||||
|
return pass;
|
||||||
|
},
|
||||||
refresh,
|
refresh,
|
||||||
syncFrom,
|
syncFrom,
|
||||||
addItemLine,
|
addItemLine,
|
||||||
addSlotLine,
|
addSlotLine,
|
||||||
updateQuantity,
|
updateQuantity,
|
||||||
removeLine,
|
removeLine,
|
||||||
renewHolds
|
renewHolds,
|
||||||
|
applyCode,
|
||||||
|
removeCode,
|
||||||
|
setGift
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -47,14 +47,64 @@
|
||||||
// Prices in the shop currency (STRIPE_CURRENCY, via layout data).
|
// Prices in the shop currency (STRIPE_CURRENCY, via layout data).
|
||||||
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
|
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
|
||||||
|
|
||||||
|
/** Codes cover everything: the order is confirmed without a payment step. */
|
||||||
|
const nothingToPay = $derived(basket.lines.length > 0 && basket.total === 0);
|
||||||
|
|
||||||
const payLabel = $derived(
|
const payLabel = $derived(
|
||||||
payState === 'confirming'
|
payState === 'confirming'
|
||||||
? 'Confirming…'
|
? 'Confirming…'
|
||||||
: payState === 'creating'
|
: payState === 'creating'
|
||||||
? 'Preparing payment…'
|
? nothingToPay
|
||||||
|
? 'Confirming…'
|
||||||
|
: 'Preparing payment…'
|
||||||
|
: nothingToPay
|
||||||
|
? 'Confirm booking'
|
||||||
: `Pay ${formatPrice(basket.total, currency)}`
|
: `Pay ${formatPrice(basket.total, currency)}`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ── Bundle/voucher code ──
|
||||||
|
let codeInput = $state('');
|
||||||
|
let codeError = $state('');
|
||||||
|
let codeBusy = $state(false);
|
||||||
|
|
||||||
|
async function applyCode() {
|
||||||
|
if (!codeInput.trim() || codeBusy) return;
|
||||||
|
codeBusy = true;
|
||||||
|
codeError = '';
|
||||||
|
try {
|
||||||
|
await basket.applyCode(codeInput.trim());
|
||||||
|
codeInput = '';
|
||||||
|
} catch (e) {
|
||||||
|
codeError = e instanceof Error ? e.message : 'Could not apply the code.';
|
||||||
|
} finally {
|
||||||
|
codeBusy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeCode() {
|
||||||
|
codeBusy = true;
|
||||||
|
codeError = '';
|
||||||
|
try {
|
||||||
|
await basket.removeCode();
|
||||||
|
} catch (e) {
|
||||||
|
codeError = e instanceof Error ? e.message : 'Could not remove the code.';
|
||||||
|
} finally {
|
||||||
|
codeBusy = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Gifts (bundle lines) ──
|
||||||
|
let giftOpen = $state<Record<string, boolean>>({});
|
||||||
|
|
||||||
|
async function saveGift(line: BasketLine, giftTo: string, giftMessage: string) {
|
||||||
|
if (giftTo === (line.giftTo ?? '') && giftMessage === (line.giftMessage ?? '')) return;
|
||||||
|
try {
|
||||||
|
await basket.setGift(line.id, giftTo, giftMessage);
|
||||||
|
} catch (e) {
|
||||||
|
errorMsg = e instanceof Error ? e.message : 'Could not save the gift details.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||||
|
|
||||||
/** "Fri 15 Jan, 10:00" in the studio's timezone. */
|
/** "Fri 15 Jan, 10:00" in the studio's timezone. */
|
||||||
|
|
@ -179,7 +229,13 @@
|
||||||
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
|
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const { clientSecret } = await res.json();
|
const result = await res.json();
|
||||||
|
if (result.free) {
|
||||||
|
// Paid in full with a code: the order exists, no payment step.
|
||||||
|
goto('/checkout/return?order=' + encodeURIComponent(result.orderId));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { clientSecret } = result;
|
||||||
// Starting payment holds the slots longer; show the new countdown.
|
// Starting payment holds the slots longer; show the new countdown.
|
||||||
await basket.refresh();
|
await basket.refresh();
|
||||||
|
|
||||||
|
|
@ -349,11 +405,45 @@
|
||||||
{#if line.lineType === 'slot' && line.start}
|
{#if line.lineType === 'slot' && line.start}
|
||||||
<p class="text-sm text-fg-body/70">{formatSlotTime(line.start)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</p>
|
<p class="text-sm text-fg-body/70">{formatSlotTime(line.start)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</p>
|
||||||
{/if}
|
{/if}
|
||||||
{#if line.itemPrice == null}
|
{#if line.passCovered}
|
||||||
|
<p class="text-sm font-medium text-sage-dark">Paid with your code</p>
|
||||||
|
{:else if line.itemPrice == null}
|
||||||
<p class="text-sm text-terracotta">No longer offered at this length — please remove it and pick again.</p>
|
<p class="text-sm text-terracotta">No longer offered at this length — please remove it and pick again.</p>
|
||||||
{:else}
|
{:else}
|
||||||
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice, currency)}</p>
|
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice, currency)}</p>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if line.bundle}
|
||||||
|
<p class="text-sm text-fg-body/70">
|
||||||
|
{line.bundle.parts.map((p) => `${p.count}× ${p.name}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', ')}{line.bundle.validMonths
|
||||||
|
? ` · valid ${line.bundle.validMonths} months`
|
||||||
|
: ''}
|
||||||
|
</p>
|
||||||
|
{#if giftOpen[line.id] || line.giftTo}
|
||||||
|
<div class="mt-2 grid gap-2 sm:grid-cols-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
maxlength="180"
|
||||||
|
placeholder="For (their name)"
|
||||||
|
aria-label="Who the gift is for"
|
||||||
|
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
|
||||||
|
value={line.giftTo ?? ''}
|
||||||
|
onchange={(e) => saveGift(line, e.currentTarget.value.trim(), line.giftMessage ?? '')}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
maxlength="1000"
|
||||||
|
placeholder="Message (optional)"
|
||||||
|
aria-label="Gift message"
|
||||||
|
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
|
||||||
|
value={line.giftMessage ?? ''}
|
||||||
|
onchange={(e) => saveGift(line, line.giftTo ?? '', e.currentTarget.value.trim())}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-fg-body/60">Shown with the code in your confirmation email — forward it to them, or print it.</p>
|
||||||
|
{:else}
|
||||||
|
<button type="button" class="mt-1 text-sm text-sage-dark underline underline-offset-2" onclick={() => (giftOpen[line.id] = true)}>This is a gift</button>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
|
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
|
||||||
|
|
@ -406,6 +496,50 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Bundle / voucher code: covers bookings of the same service and length. -->
|
||||||
|
<div class="mt-4 rounded-2xl border border-charcoal/10 bg-white p-5">
|
||||||
|
{#if basket.pass}
|
||||||
|
{@const left = basket.pass.parts.filter((p) => p.redeemable)}
|
||||||
|
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<p class="font-medium">Code <span class="font-mono tracking-wider">{basket.pass.code}</span> · {basket.pass.name}</p>
|
||||||
|
<p class="text-sm text-fg-body/70">
|
||||||
|
{left.map((p) => `${p.left} × ${p.name} (${formatDuration(p.minutes ?? 0)})`).join(', ')} left after this basket{basket.pass.expiresAt
|
||||||
|
? ` · valid until ${formatInstant(basket.pass.expiresAt, timezone, { day: 'numeric', month: 'long', year: 'numeric' })}`
|
||||||
|
: ''}.
|
||||||
|
</p>
|
||||||
|
{#if !basket.lines.some((l) => l.passCovered)}
|
||||||
|
<p class="mt-1 text-sm text-terracotta">Nothing in your basket matches this code — book one of the sessions above, at the same length.</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<button type="button" class="text-sm text-fg-body/70 underline underline-offset-2 disabled:opacity-50" disabled={codeBusy} onclick={removeCode}>Remove code</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<form
|
||||||
|
class="flex flex-wrap items-center gap-2"
|
||||||
|
onsubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
applyCode();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<label class="text-sm font-medium" for="checkout-code">Have a bundle or voucher code?</label>
|
||||||
|
<input
|
||||||
|
id="checkout-code"
|
||||||
|
type="text"
|
||||||
|
autocomplete="off"
|
||||||
|
spellcheck="false"
|
||||||
|
placeholder="ABCD-2345"
|
||||||
|
class="w-36 rounded-xl border border-charcoal/15 bg-white px-3 py-2 font-mono tracking-wider uppercase focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||||
|
bind:value={codeInput}
|
||||||
|
/>
|
||||||
|
<button type="submit" class="rounded-full border border-charcoal/20 px-4 py-2 text-sm font-medium transition hover:bg-charcoal/5 disabled:opacity-50" disabled={codeBusy || !codeInput.trim()}>
|
||||||
|
{codeBusy ? 'Checking…' : 'Apply'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
{#if codeError}<p class="mt-2 text-sm text-terracotta" role="alert">{codeError}</p>{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="mt-10 grid gap-10 md:grid-cols-2">
|
<div class="mt-10 grid gap-10 md:grid-cols-2">
|
||||||
<!-- Customer details -->
|
<!-- Customer details -->
|
||||||
<form
|
<form
|
||||||
|
|
@ -519,7 +653,9 @@
|
||||||
|
|
||||||
{#if payState === 'idle' && !errorMsg}
|
{#if payState === 'idle' && !errorMsg}
|
||||||
<p class="mt-4 text-sm text-fg-body/70">
|
<p class="mt-4 text-sm text-fg-body/70">
|
||||||
Fill in your details and press Pay to continue to secure payment.
|
{nothingToPay
|
||||||
|
? 'Nothing to pay — your code covers everything. Fill in your details and press Confirm booking.'
|
||||||
|
: 'Fill in your details and press Pay to continue to secure payment.'}
|
||||||
</p>
|
</p>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,7 @@
|
||||||
|
|
||||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||||
let result: ItemRecord[] = items;
|
let result: ItemRecord[] = items;
|
||||||
if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
|
if (data.itemTypeFilter && data.itemTypeFilter !== 'all') {
|
||||||
result = result.filter((i) => i.type === data.itemTypeFilter);
|
result = result.filter((i) => i.type === data.itemTypeFilter);
|
||||||
}
|
}
|
||||||
if (data.itemIds?.length) {
|
if (data.itemIds?.length) {
|
||||||
|
|
@ -63,6 +63,9 @@
|
||||||
|
|
||||||
let isList = $derived(data.layout === 'list');
|
let isList = $derived(data.layout === 'list');
|
||||||
|
|
||||||
|
/** Item id → name, for what bundles contain. */
|
||||||
|
let itemNames = $derived(new Map(items.map((item: ItemRecord) => [item.id, item.name])));
|
||||||
|
|
||||||
/** Changes whenever the basket's bookings do, so open pickers reload (a booking blocks other times). */
|
/** Changes whenever the basket's bookings do, so open pickers reload (a booking blocks other times). */
|
||||||
let basketBookingsKey = $derived(
|
let basketBookingsKey = $derived(
|
||||||
basket.lines
|
basket.lines
|
||||||
|
|
@ -290,7 +293,7 @@
|
||||||
{@const isService = item.type === 'item_with_time'}
|
{@const isService = item.type === 'item_with_time'}
|
||||||
{@const duration = isService ? selectedDuration(item, ui) : null}
|
{@const duration = isService ? selectedDuration(item, ui) : null}
|
||||||
{@const bookable = !isService || !!duration}
|
{@const bookable = !isService || !!duration}
|
||||||
{@const soldOut = !isService && item.stock === 0}
|
{@const soldOut = item.type === 'item' && item.stock === 0}
|
||||||
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
|
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
|
||||||
<article
|
<article
|
||||||
class={isList
|
class={isList
|
||||||
|
|
@ -319,6 +322,17 @@
|
||||||
{#if item.description}
|
{#if item.description}
|
||||||
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
|
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
|
||||||
{/if}
|
{/if}
|
||||||
|
{#if item.type === 'bundle'}
|
||||||
|
<!-- What the bundle contains; its code books the sessions later. -->
|
||||||
|
<ul class="mt-2 space-y-0.5 text-sm text-charcoal/80">
|
||||||
|
{#each item.bundleParts as part (`${part.item}|${part.minutes}`)}
|
||||||
|
<li>{part.count}× {itemNames.get(part.item) ?? 'Item'}{part.minutes ? ` (${formatDuration(part.minutes)})` : ''}</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
<p class="mt-1 text-xs text-charcoal/60">
|
||||||
|
You get a code to book the sessions whenever suits you{item.validMonths ? ` — valid ${item.validMonths} months` : ''}. It can be given as a gift.
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<div class="mt-auto pt-3">
|
<div class="mt-auto pt-3">
|
||||||
{#if isService && item.durations.length > 1}
|
{#if isService && item.durations.length > 1}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types';
|
import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types';
|
||||||
|
import { formatDuration } from '../items';
|
||||||
|
|
||||||
// Pure email rendering — no server or browser APIs, so the admin editor can
|
// Pure email rendering — no server or browser APIs, so the admin editor can
|
||||||
// render its live preview client-side with exactly the code that sends.
|
// render its live preview client-side with exactly the code that sends.
|
||||||
|
|
@ -12,6 +13,18 @@ export type EmailLine = {
|
||||||
quantity: number;
|
quantity: number;
|
||||||
start: string | null;
|
start: string | null;
|
||||||
end: string | null;
|
end: string | null;
|
||||||
|
/** The code that paid for this booking. */
|
||||||
|
passCode?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A bundle/voucher code bought in this order. */
|
||||||
|
export type EmailPass = {
|
||||||
|
code: string; // ABCD-2345
|
||||||
|
name: string;
|
||||||
|
expiresAt: string; // ISO, '' = no expiry
|
||||||
|
recipientName: string;
|
||||||
|
message: string;
|
||||||
|
parts: { name: string; minutes: number | null; count: number }[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type EmailContext = {
|
export type EmailContext = {
|
||||||
|
|
@ -20,6 +33,8 @@ export type EmailContext = {
|
||||||
currency: string;
|
currency: string;
|
||||||
customer: CustomerDetails;
|
customer: CustomerDetails;
|
||||||
lines: EmailLine[];
|
lines: EmailLine[];
|
||||||
|
/** Codes bought in this order — shown under the booking details. */
|
||||||
|
passes?: EmailPass[];
|
||||||
business: FooterGlobal;
|
business: FooterGlobal;
|
||||||
colors: ColorsGlobal;
|
colors: ColorsGlobal;
|
||||||
siteUrl: string;
|
siteUrl: string;
|
||||||
|
|
@ -97,6 +112,20 @@ function formatTime(iso: string, timezone: string): string {
|
||||||
}).format(new Date(iso));
|
}).format(new Date(iso));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatDate(iso: string, timezone: string): string {
|
||||||
|
return new Intl.DateTimeFormat('en-GB', { timeZone: safeTimeZone(timezone), day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Valid until 25 October 2027" / "No expiry". */
|
||||||
|
function passValidity(pass: EmailPass, timezone: string) {
|
||||||
|
return pass.expiresAt ? `Valid until ${formatDate(pass.expiresAt, timezone)}` : 'No expiry';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "3× Massage (1 hour)" / "1× Oil — handed over with this order". */
|
||||||
|
function passPartLabel(part: EmailPass['parts'][number]) {
|
||||||
|
return `${part.count}× ${part.name}${part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with this order'}`;
|
||||||
|
}
|
||||||
|
|
||||||
/** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */
|
/** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */
|
||||||
export function formatLineWhen(line: EmailLine, timezone: string): string {
|
export function formatLineWhen(line: EmailLine, timezone: string): string {
|
||||||
if (!line.start) return '';
|
if (!line.start) return '';
|
||||||
|
|
@ -236,6 +265,7 @@ function renderBookingDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||||
<td valign="top" style="${cell}padding:10px 12px 10px 0;border-bottom:1px solid ${BORDER};">
|
<td valign="top" style="${cell}padding:10px 12px 10px 0;border-bottom:1px solid ${BORDER};">
|
||||||
<div style="font-size:16px;font-weight:600;line-height:1.4;">${escapeHtml(qty + line.name)}</div>
|
<div style="font-size:16px;font-weight:600;line-height:1.4;">${escapeHtml(qty + line.name)}</div>
|
||||||
${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">${escapeHtml(when)}</div>` : ''}
|
${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">${escapeHtml(when)}</div>` : ''}
|
||||||
|
${line.passCode ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">Paid with code ${escapeHtml(line.passCode)}</div>` : ''}
|
||||||
</td>
|
</td>
|
||||||
<td valign="top" align="right" style="${cell}padding:10px 0;border-bottom:1px solid ${BORDER};font-size:15px;white-space:nowrap;">${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))}</td>
|
<td valign="top" align="right" style="${cell}padding:10px 0;border-bottom:1px solid ${BORDER};font-size:15px;white-space:nowrap;">${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))}</td>
|
||||||
</tr>`;
|
</tr>`;
|
||||||
|
|
@ -243,7 +273,25 @@ ${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheadi
|
||||||
.join('');
|
.join('');
|
||||||
const total = `<tr><td style="${cell}padding:12px 12px 0 0;font-size:16px;font-weight:700;">Total paid</td><td align="right" style="${cell}padding:12px 0 0;font-size:16px;font-weight:700;white-space:nowrap;">${escapeHtml(formatMoney(ctx.total, ctx.currency))}</td></tr>`;
|
const total = `<tr><td style="${cell}padding:12px 12px 0 0;font-size:16px;font-weight:700;">Total paid</td><td align="right" style="${cell}padding:12px 0 0;font-size:16px;font-weight:700;white-space:nowrap;">${escapeHtml(formatMoney(ctx.total, ctx.currency))}</td></tr>`;
|
||||||
const table = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${lines}${total}</table>`;
|
const table = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${lines}${total}</table>`;
|
||||||
return boxed(sectionTitle(block.data.title ?? '', ctx) + table, ctx);
|
return boxed(sectionTitle(block.data.title ?? '', ctx) + table + renderPasses(ctx), ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The codes an order bought, under its booking details. */
|
||||||
|
function renderPasses(ctx: EmailContext): string {
|
||||||
|
if (!ctx.passes?.length) return '';
|
||||||
|
const small = `font-family:${FONT_BODY};font-size:14px;line-height:1.5;color:${ctx.colors.subheading};margin:4px 0 0;`;
|
||||||
|
const cards = ctx.passes
|
||||||
|
.map(
|
||||||
|
(pass) => `<div style="margin:12px 0 0;padding:14px 16px;border:1px dashed ${ctx.colors.accent};border-radius:8px;">
|
||||||
|
<div style="font-family:'Courier New',Courier,monospace;font-size:24px;font-weight:700;letter-spacing:3px;color:${ctx.colors.text};">${escapeHtml(pass.code)}</div>
|
||||||
|
<div style="font-family:${FONT_BODY};font-size:16px;font-weight:600;line-height:1.4;color:${ctx.colors.text};margin:6px 0 0;">${escapeHtml(pass.name)}${pass.recipientName ? ` · for ${escapeHtml(pass.recipientName)}` : ''}</div>
|
||||||
|
${pass.message ? `<p style="${small}font-style:italic;">“${escapeHtml(pass.message).replace(/\n/g, '<br>')}”</p>` : ''}
|
||||||
|
<p style="${small}">${pass.parts.map((part) => escapeHtml(passPartLabel(part))).join('<br>')}</p>
|
||||||
|
<p style="${small}">${escapeHtml(passValidity(pass, ctx.timezone))}. Enter the code in the basket when booking.</p>
|
||||||
|
</div>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
return `<div style="font-family:${FONT_BODY};font-size:16px;font-weight:700;color:${ctx.colors.text};margin:20px 0 0;">Your ${ctx.passes.length === 1 ? 'code' : 'codes'}</div>${cards}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string {
|
function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||||
|
|
@ -323,9 +371,20 @@ function renderBlockText(block: EmailBlock, ctx: EmailContext, values: Record<st
|
||||||
const lines = ctx.lines.map((line) => {
|
const lines = ctx.lines.map((line) => {
|
||||||
const when = formatLineWhen(line, ctx.timezone);
|
const when = formatLineWhen(line, ctx.timezone);
|
||||||
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||||
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}`;
|
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}${line.passCode ? `\n Paid with code ${line.passCode}` : ''}`;
|
||||||
});
|
});
|
||||||
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}`;
|
const passes = (ctx.passes ?? []).map((pass) =>
|
||||||
|
[
|
||||||
|
`\n${pass.code} — ${pass.name}${pass.recipientName ? ` (for ${pass.recipientName})` : ''}`,
|
||||||
|
pass.message && `"${pass.message}"`,
|
||||||
|
...pass.parts.map((part) => ` ${passPartLabel(part)}`),
|
||||||
|
` ${passValidity(pass, ctx.timezone)}. Enter the code in the basket when booking.`
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n')
|
||||||
|
);
|
||||||
|
const codes = passes.length ? `\n\nYOUR ${passes.length === 1 ? 'CODE' : 'CODES'}${passes.join('\n')}` : '';
|
||||||
|
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}${codes}`;
|
||||||
}
|
}
|
||||||
case 'customer_details': {
|
case 'customer_details': {
|
||||||
const { name, email, phone, notes } = ctx.customer;
|
const { name, email, phone, notes } = ctx.customer;
|
||||||
|
|
|
||||||
|
|
@ -27,3 +27,8 @@ export function formatDuration(minutes: number) {
|
||||||
export function lowestPrice(durations: ItemDuration[]) {
|
export function lowestPrice(durations: ItemDuration[]) {
|
||||||
return durations.length ? Math.min(...durations.map((d) => d.price)) : null;
|
return durations.length ? Math.min(...durations.map((d) => d.price)) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A stored code `ABCD2345` → `ABCD-2345`, as shown to people (the shop hooks format it the same way). */
|
||||||
|
export function formatCode(code: string) {
|
||||||
|
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,8 @@ import {
|
||||||
type FooterGlobal
|
type FooterGlobal
|
||||||
} from '../../types';
|
} from '../../types';
|
||||||
import { normalizeEmailTemplate } from '../../email/defaults';
|
import { normalizeEmailTemplate } from '../../email/defaults';
|
||||||
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine } from '../../email/render';
|
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine, type EmailPass } from '../../email/render';
|
||||||
|
import { formatCode } from '../../items';
|
||||||
import { buildIcs } from './ics';
|
import { buildIcs } from './ics';
|
||||||
import { sendEmail, type SendResult } from './transport';
|
import { sendEmail, type SendResult } from './transport';
|
||||||
|
|
||||||
|
|
@ -113,8 +114,10 @@ function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSetting
|
||||||
*/
|
*/
|
||||||
export type OrderEmailData = {
|
export type OrderEmailData = {
|
||||||
order: Record<string, any>;
|
order: Record<string, any>;
|
||||||
/** order_lines with `expand.slot` and `expand.item` */
|
/** order_lines with `expand.slot`, `expand.item` and `expand.pass` */
|
||||||
lines: Record<string, any>[];
|
lines: Record<string, any>[];
|
||||||
|
/** passes this order bought (codes) */
|
||||||
|
passes?: Record<string, any>[];
|
||||||
templates: Partial<Record<EmailTemplateKey, Record<string, any> | null>>;
|
templates: Partial<Record<EmailTemplateKey, Record<string, any> | null>>;
|
||||||
footer: Partial<FooterGlobal> | null;
|
footer: Partial<FooterGlobal> | null;
|
||||||
colors: Partial<ColorsGlobal> | null;
|
colors: Partial<ColorsGlobal> | null;
|
||||||
|
|
@ -132,15 +135,16 @@ export async function loadOrderEmailData(pb: PocketBase, orderId: string): Promi
|
||||||
.collection('email_templates')
|
.collection('email_templates')
|
||||||
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
||||||
.catch(() => null);
|
.catch(() => null);
|
||||||
const [order, lines, customer_confirmation, client_alert, footer, colors] = await Promise.all([
|
const [order, lines, passes, customer_confirmation, client_alert, footer, colors] = await Promise.all([
|
||||||
pb.collection('orders').getOne(orderId),
|
pb.collection('orders').getOne(orderId),
|
||||||
pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' }),
|
pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item,pass', sort: 'start' }),
|
||||||
|
pb.collection('passes').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), sort: 'created' }),
|
||||||
template('customer_confirmation'),
|
template('customer_confirmation'),
|
||||||
template('client_alert'),
|
template('client_alert'),
|
||||||
globalData('footer'),
|
globalData('footer'),
|
||||||
globalData('colors')
|
globalData('colors')
|
||||||
]);
|
]);
|
||||||
return { order, lines, templates: { customer_confirmation, client_alert }, footer, colors };
|
return { order, lines, passes, templates: { customer_confirmation, client_alert }, footer, colors };
|
||||||
}
|
}
|
||||||
|
|
||||||
function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
||||||
|
|
@ -159,10 +163,24 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
||||||
price: Number(line.price) || 0,
|
price: Number(line.price) || 0,
|
||||||
quantity: Number(line.quantity) || 1,
|
quantity: Number(line.quantity) || 1,
|
||||||
start,
|
start,
|
||||||
end
|
end,
|
||||||
|
passCode: line.expand?.pass?.code ? formatCode(String(line.expand.pass.code)) : undefined
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const passes: EmailPass[] = (data.passes ?? []).map((pass) => ({
|
||||||
|
code: formatCode(String(pass.code || '')),
|
||||||
|
name: String(pass.name || ''),
|
||||||
|
expiresAt: pass.expiresAt ? new Date(String(pass.expiresAt).replace(' ', 'T')).toISOString() : '',
|
||||||
|
recipientName: String(pass.recipientName || ''),
|
||||||
|
message: String(pass.message || ''),
|
||||||
|
parts: (Array.isArray(pass.parts) ? pass.parts : []).map((part: Record<string, any>) => ({
|
||||||
|
name: String(part.name || ''),
|
||||||
|
minutes: part.minutes ? Number(part.minutes) : null,
|
||||||
|
count: Number(part.count) || 0
|
||||||
|
}))
|
||||||
|
}));
|
||||||
|
|
||||||
const details = (order.customerDetails || {}) as Partial<CustomerDetails>;
|
const details = (order.customerDetails || {}) as Partial<CustomerDetails>;
|
||||||
const customer: CustomerDetails = {
|
const customer: CustomerDetails = {
|
||||||
name: String(details.name || ''),
|
name: String(details.name || ''),
|
||||||
|
|
@ -176,6 +194,7 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
||||||
total: Number(order.total) || 0,
|
total: Number(order.total) || 0,
|
||||||
customer,
|
customer,
|
||||||
lines,
|
lines,
|
||||||
|
passes,
|
||||||
...settings
|
...settings
|
||||||
};
|
};
|
||||||
return { ctx, lineIds: lineRecords.map((line) => line.id) };
|
return { ctx, lineIds: lineRecords.map((line) => line.id) };
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,19 @@
|
||||||
import type PocketBase from 'pocketbase';
|
import type PocketBase from 'pocketbase';
|
||||||
import { getFileUrl } from '../pb';
|
import { getFileUrl } from '../pb';
|
||||||
import { parseDurations } from '../items';
|
import { parseDurations } from '../items';
|
||||||
import type { BookableTime, ItemRecord } from '../types';
|
import type { BookableTime, BundlePart, ItemRecord, ItemType } from '../types';
|
||||||
|
|
||||||
|
/** A bundle's `bundleParts` field (JSON) → valid parts. */
|
||||||
|
export function parseBundleParts(raw: unknown): BundlePart[] {
|
||||||
|
return (Array.isArray(raw) ? raw : [])
|
||||||
|
.map((p) => ({ item: String(p?.item || ''), minutes: p?.minutes ? Math.floor(Number(p.minutes)) : null, count: Math.floor(Number(p?.count)) || 0 }))
|
||||||
|
.filter((p) => p.item && p.count > 0);
|
||||||
|
}
|
||||||
|
|
||||||
/** An `items` record (with `expand.image`) → `ItemRecord`. */
|
/** An `items` record (with `expand.image`) → `ItemRecord`. */
|
||||||
export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
||||||
const media = record.expand?.image;
|
const media = record.expand?.image;
|
||||||
const type = record.type === 'item_with_time' ? 'item_with_time' : 'item';
|
const type: ItemType = record.type === 'item_with_time' || record.type === 'bundle' ? record.type : 'item';
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
id: record.id,
|
||||||
name: String(record.name || ''),
|
name: String(record.name || ''),
|
||||||
|
|
@ -15,8 +22,11 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
||||||
image: String(record.image || ''),
|
image: String(record.image || ''),
|
||||||
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
|
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
|
||||||
type,
|
type,
|
||||||
stock: record.stock ?? null,
|
// null = unlimited: PocketBase reads an empty number back as 0, so `trackStock` says whether it counts.
|
||||||
|
stock: type === 'item' && record.trackStock ? Number(record.stock) || 0 : null,
|
||||||
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
|
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,
|
bufferMinutes: record.bufferMinutes ?? null,
|
||||||
capacity: record.capacity ?? null,
|
capacity: record.capacity ?? null,
|
||||||
active: record.active !== false
|
active: record.active !== false
|
||||||
|
|
|
||||||
|
|
@ -117,11 +117,14 @@ export const defaultPrivacy: PrivacyGlobal = {
|
||||||
|
|
||||||
// ── Commerce types ─────────────────────────────────────────────────────
|
// ── Commerce types ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
export type ItemType = 'item' | 'item_with_time';
|
export type ItemType = 'item' | 'item_with_time' | 'bundle';
|
||||||
|
|
||||||
/** One length a service can be booked for, and its price. */
|
/** One length a service can be booked for, and its price. */
|
||||||
export type ItemDuration = { minutes: number; price: number };
|
export type ItemDuration = { minutes: number; price: number };
|
||||||
|
|
||||||
|
/** Part of a bundle: a service at one length (`minutes`), or a product (`minutes` null), `count` times. */
|
||||||
|
export type BundlePart = { item: string; minutes: number | null; count: number };
|
||||||
|
|
||||||
export type ItemRecord = {
|
export type ItemRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
|
@ -133,6 +136,8 @@ export type ItemRecord = {
|
||||||
type: ItemType;
|
type: ItemType;
|
||||||
stock: number | null;
|
stock: number | null;
|
||||||
durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
|
durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
|
||||||
|
bundleParts: BundlePart[]; // bundle: what it contains
|
||||||
|
validMonths: number | null; // bundle: how long its code can be used after purchase (null: no expiry)
|
||||||
bufferMinutes: number | null; // get-ready time after each appointment
|
bufferMinutes: number | null; // get-ready time after each appointment
|
||||||
capacity: number | null; // places in a new group session (>1 = group)
|
capacity: number | null; // places in a new group session (>1 = group)
|
||||||
active: boolean;
|
active: boolean;
|
||||||
|
|
@ -158,6 +163,32 @@ export type BookableTime = {
|
||||||
free: number; // places still bookable
|
free: number; // places still bookable
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** A part of a code (pass) with its share of the price and what's left to book. */
|
||||||
|
export type PassPart = {
|
||||||
|
item: string;
|
||||||
|
name: string;
|
||||||
|
minutes: number | null;
|
||||||
|
count: number;
|
||||||
|
value: number;
|
||||||
|
/** Services are booked with the code; products were handed over with the purchase. */
|
||||||
|
redeemable: boolean;
|
||||||
|
used: number;
|
||||||
|
held: number;
|
||||||
|
left: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A bundle/voucher code as the customer and the admin see it. */
|
||||||
|
export type PassSummary = {
|
||||||
|
id: string;
|
||||||
|
code: string; // ABCD-2345
|
||||||
|
name: string;
|
||||||
|
expiresAt: string; // ISO, '' = no expiry
|
||||||
|
status: 'active' | 'void';
|
||||||
|
recipientName: string;
|
||||||
|
message: string;
|
||||||
|
parts: PassPart[];
|
||||||
|
};
|
||||||
|
|
||||||
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
||||||
|
|
||||||
export type BasketLine = {
|
export type BasketLine = {
|
||||||
|
|
@ -178,6 +209,13 @@ export type BasketLine = {
|
||||||
itemImageUrl?: string;
|
itemImageUrl?: string;
|
||||||
slotKind?: SlotKind;
|
slotKind?: SlotKind;
|
||||||
slotCapacity?: number;
|
slotCapacity?: number;
|
||||||
|
/** Slot lines: the basket's code pays for this booking. */
|
||||||
|
passCovered?: boolean;
|
||||||
|
/** Bundle lines: who it's for (shown with its code in the confirmation email). */
|
||||||
|
giftTo?: string;
|
||||||
|
giftMessage?: string;
|
||||||
|
/** Bundle lines: what's in it. */
|
||||||
|
bundle?: { validMonths: number; parts: { item: string; name: string; minutes: number | null; count: number; value: number }[] };
|
||||||
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
|
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
|
||||||
heldUntil?: string;
|
heldUntil?: string;
|
||||||
};
|
};
|
||||||
|
|
@ -190,6 +228,8 @@ export type Basket = {
|
||||||
customerDetails: CustomerDetails | null;
|
customerDetails: CustomerDetails | null;
|
||||||
stripePaymentIntentId: string | null;
|
stripePaymentIntentId: string | null;
|
||||||
lines: BasketLine[];
|
lines: BasketLine[];
|
||||||
|
/** The code applied at checkout, with what it has left. */
|
||||||
|
pass?: PassSummary | null;
|
||||||
/** Server clock (epoch ms) when this was read, so browsers with a wrong clock count holds down correctly. */
|
/** Server clock (epoch ms) when this was read, so browsers with a wrong clock count holds down correctly. */
|
||||||
serverNow?: number;
|
serverNow?: number;
|
||||||
};
|
};
|
||||||
|
|
@ -214,6 +254,8 @@ export type OrderRecord = {
|
||||||
customerEmailSentAt?: string;
|
customerEmailSentAt?: string;
|
||||||
clientEmailSentAt?: string;
|
clientEmailSentAt?: string;
|
||||||
emailError?: string;
|
emailError?: string;
|
||||||
|
/** Codes this order bought. */
|
||||||
|
passes?: PassSummary[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type OrderLine = {
|
export type OrderLine = {
|
||||||
|
|
@ -228,6 +270,8 @@ export type OrderLine = {
|
||||||
start: string | null;
|
start: string | null;
|
||||||
/** Slot lines: the booked length. */
|
/** Slot lines: the booked length. */
|
||||||
minutes: number | null;
|
minutes: number | null;
|
||||||
|
/** The code that paid for this booking ('' if none). */
|
||||||
|
passCode?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Block data types ──────────────────────────────────────────────────
|
// ── Block data types ──────────────────────────────────────────────────
|
||||||
|
|
|
||||||
|
|
@ -328,9 +328,12 @@
|
||||||
{ "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
{ "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
||||||
{ "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||||
{ "id": "rel_itemimage01", "name": "image", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_media00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_itemimage01", "name": "image", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_media00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] },
|
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time", "bundle"] },
|
||||||
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||||
|
{ "id": "bool_itemtrackst", "name": "trackStock", "type": "bool", "system": false, "required": false, "presentable": false, "hidden": false },
|
||||||
{ "id": "json_itemdurations", "name": "durations", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 },
|
{ "id": "json_itemdurations", "name": "durations", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 },
|
||||||
|
{ "id": "json_itembundle1", "name": "bundleParts", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 },
|
||||||
|
{ "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_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_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
|
||||||
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
|
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
|
||||||
|
|
@ -387,6 +390,7 @@
|
||||||
{ "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
|
{ "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, "options": { "maxSize": 100000 } },
|
||||||
{ "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } },
|
{ "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},
|
{"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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
|
|
@ -416,13 +420,17 @@
|
||||||
{ "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
{ "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
||||||
{ "id": "date_blstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
{ "id": "date_blstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
||||||
{ "id": "num_blminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
|
{ "id": "num_blminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
|
||||||
|
{ "id": "rel_blpass000001", "name": "pass", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_passes00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 },
|
||||||
|
{ "id": "text_blgiftto001", "name": "giftTo", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" },
|
||||||
|
{ "id": "text_blgiftmsg01", "name": "giftMessage", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 1000, "pattern": "" },
|
||||||
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
|
{"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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
|
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
|
||||||
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)",
|
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)",
|
||||||
"CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)"
|
"CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)",
|
||||||
|
"CREATE INDEX `idx_basket_lines_pass` ON `basket_lines` (`pass`)"
|
||||||
],
|
],
|
||||||
"autodate": true,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
|
@ -442,9 +450,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": "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": "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, "options": { "maxSize": 100000 } },
|
||||||
{ "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "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": "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": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } },
|
{ "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } },
|
||||||
{ "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
{ "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
{ "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
{ "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
||||||
|
|
@ -477,16 +485,18 @@
|
||||||
{ "id": "num_olquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
|
{ "id": "num_olquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
|
||||||
{ "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] },
|
{ "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] },
|
||||||
{ "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
|
{ "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
|
||||||
{ "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||||
{ "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
{ "id": "num_olminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
|
{ "id": "num_olminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
|
||||||
|
{ "id": "rel_olpass000001", "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},
|
{"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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)",
|
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)",
|
||||||
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)",
|
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)",
|
||||||
"CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)"
|
"CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)",
|
||||||
|
"CREATE INDEX `idx_order_lines_pass` ON `order_lines` (`pass`)"
|
||||||
],
|
],
|
||||||
"autodate": true,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
|
@ -516,5 +526,37 @@
|
||||||
],
|
],
|
||||||
"autodate": true,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "pbc_passes00001",
|
||||||
|
"name": "passes",
|
||||||
|
"type": "base",
|
||||||
|
"system": false,
|
||||||
|
"listRule": "@request.auth.id != ''",
|
||||||
|
"viewRule": "@request.auth.id != ''",
|
||||||
|
"createRule": null,
|
||||||
|
"updateRule": null,
|
||||||
|
"deleteRule": null,
|
||||||
|
"fields": [
|
||||||
|
{ "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_passcode001", "name": "code", "type": "text", "system": false, "required": true, "presentable": true, "hidden": false, "min": 6, "max": 20, "pattern": "^[A-Z0-9]+$" },
|
||||||
|
{ "id": "rel_passitem0001", "name": "item", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 },
|
||||||
|
{ "id": "rel_passorder001", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 },
|
||||||
|
{ "id": "text_passname001", "name": "name", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" },
|
||||||
|
{ "id": "json_passparts01", "name": "parts", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 },
|
||||||
|
{ "id": "text_passemail01", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 320, "pattern": "" },
|
||||||
|
{ "id": "text_passrecip01", "name": "recipientName", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" },
|
||||||
|
{ "id": "text_passmessag1", "name": "message", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 1000, "pattern": "" },
|
||||||
|
{ "id": "date_passexpire1", "name": "expiresAt", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
||||||
|
{ "id": "sel_passstatus01", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["active", "void"] },
|
||||||
|
{ "id": "date_passanonym1", "name": "anonymisedAt", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
||||||
|
{"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}
|
||||||
|
],
|
||||||
|
"indexes": [
|
||||||
|
"CREATE UNIQUE INDEX `idx_passes_code` ON `passes` (`code`)",
|
||||||
|
"CREATE INDEX `idx_passes_order` ON `passes` (`order`)",
|
||||||
|
"CREATE INDEX `idx_passes_email` ON `passes` (`email`)"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,11 @@
|
||||||
// - baskets.email + baskets.customerDetails — set when checkout starts. A
|
// - baskets.email + baskets.customerDetails — set when checkout starts. A
|
||||||
// paid basket's copy is cleared once the order exists; a basket that was
|
// paid basket's copy is cleared once the order exists; a basket that was
|
||||||
// never paid for is deleted after `abandonedBasketDays`.
|
// never paid for is deleted after `abandonedBasketDays`.
|
||||||
|
// - passes.email (the buyer), recipientName and message (who a bundle or
|
||||||
|
// voucher is for). Erasure anonymises a pass but keeps its code working —
|
||||||
|
// it was paid for. Retention anonymises it with the orders, once it has
|
||||||
|
// expired or has nothing left to book.
|
||||||
|
// - basket_lines.giftTo / giftMessage — deleted with the basket.
|
||||||
// Outside this database: Stripe (receipt email, payment) and the email
|
// Outside this database: Stripe (receipt email, payment) and the email
|
||||||
// provider's send logs. Those are handled in their own dashboards.
|
// provider's send logs. Those are handled in their own dashboards.
|
||||||
|
|
||||||
|
|
@ -62,19 +67,40 @@ function settings(app) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Orders and unpaid baskets whose email is `email` (case-insensitive, exact). */
|
/** Orders, unpaid baskets and bought codes whose email is `email` (case-insensitive, exact). */
|
||||||
function customerRecords(app, email) {
|
function customerRecords(app, email) {
|
||||||
const wanted = normaliseEmail(email);
|
const wanted = normaliseEmail(email);
|
||||||
if (!wanted) return { orders: [], baskets: [] };
|
if (!wanted) return { orders: [], baskets: [], passes: [] };
|
||||||
// `~` is a case-insensitive LIKE, but also a substring match (and `_` is a
|
// `~` is a case-insensitive LIKE, but also a substring match (and `_` is a
|
||||||
// wildcard), so narrow it to the exact address here.
|
// wildcard), so narrow it to the exact address here.
|
||||||
const same = (record) => normaliseEmail(record.getString('email')) === wanted;
|
const same = (record) => normaliseEmail(record.getString('email')) === wanted;
|
||||||
return {
|
return {
|
||||||
orders: app.findRecordsByFilter('orders', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same),
|
orders: app.findRecordsByFilter('orders', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same),
|
||||||
baskets: app.findRecordsByFilter('baskets', "email ~ {:email} && status != 'completed'", '-updated', 0, 0, { email: wanted }).filter(same)
|
baskets: app.findRecordsByFilter('baskets', "email ~ {:email} && status != 'completed'", '-updated', 0, 0, { email: wanted }).filter(same),
|
||||||
|
passes: app.findRecordsByFilter('passes', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Keep the code (it was paid for); drop who bought it and who it's for. */
|
||||||
|
function anonymisePass(app, pass) {
|
||||||
|
pass.set('email', '');
|
||||||
|
pass.set('recipientName', '');
|
||||||
|
pass.set('message', '');
|
||||||
|
pass.set('anonymisedAt', new Date().toISOString());
|
||||||
|
app.save(pass);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a pass can't be used any more: expired, void, or every booking used. */
|
||||||
|
function passFinished(app, pass) {
|
||||||
|
const expires = Date.parse(pass.getString('expiresAt').replace(' ', 'T'));
|
||||||
|
if (pass.getString('status') !== 'active' || expires <= Date.now()) return true;
|
||||||
|
const parts = JSON.parse(toString(pass.get('parts')) || '[]') || [];
|
||||||
|
let booked = 0;
|
||||||
|
for (const line of app.findRecordsByFilter('order_lines', "pass = {:pass} && order.status != 'refunded'", '', 0, 0, { pass: pass.id })) booked += line.getInt('quantity');
|
||||||
|
const bookable = parts.filter((p) => p.minutes).reduce((n, p) => n + p.count, 0);
|
||||||
|
return booked >= bookable;
|
||||||
|
}
|
||||||
|
|
||||||
function hasUpcomingBooking(app, orderId) {
|
function hasUpcomingBooking(app, orderId) {
|
||||||
return app.findRecordsByFilter('order_lines', "order = {:order} && lineType = 'slot' && start > {:now}", '', 1, 0, { order: orderId, now: pbDate(Date.now()) }).length > 0;
|
return app.findRecordsByFilter('order_lines', "order = {:order} && lineType = 'slot' && start > {:now}", '', 1, 0, { order: orderId, now: pbDate(Date.now()) }).length > 0;
|
||||||
}
|
}
|
||||||
|
|
@ -97,7 +123,7 @@ function clearBasketDetails(app, basket) {
|
||||||
|
|
||||||
function applyRetention(app) {
|
function applyRetention(app) {
|
||||||
const { abandonedBasketDays, anonymiseOrdersAfterMonths } = settings(app);
|
const { abandonedBasketDays, anonymiseOrdersAfterMonths } = settings(app);
|
||||||
const counts = { basketsDeleted: 0, basketsCleared: 0, ordersAnonymised: 0 };
|
const counts = { basketsDeleted: 0, basketsCleared: 0, ordersAnonymised: 0, passesAnonymised: 0 };
|
||||||
|
|
||||||
// Unpaid baskets (their lines cascade). Active ones expire after a day
|
// Unpaid baskets (their lines cascade). Active ones expire after a day
|
||||||
// and are swept to `abandoned`, so `updated` is when they were last used.
|
// and are swept to `abandoned`, so `updated` is when they were last used.
|
||||||
|
|
@ -134,9 +160,20 @@ function applyRetention(app) {
|
||||||
console.error('[privacy] could not anonymise order', order.id, e);
|
console.error('[privacy] could not anonymise order', order.id, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Codes: same age, and only once they can't be used any more (whoever
|
||||||
|
// holds one may still need it looked up).
|
||||||
|
for (const pass of app.findRecordsByFilter('passes', "anonymisedAt = '' && created < {:cutoff}", '', 0, 0, { cutoff: pbDate(cutoff.getTime()) })) {
|
||||||
|
if (!passFinished(app, pass)) continue;
|
||||||
|
try {
|
||||||
|
anonymisePass(app, pass);
|
||||||
|
counts.passesAnonymised++;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[privacy] could not anonymise pass', pass.id, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (counts.basketsDeleted || counts.basketsCleared || counts.ordersAnonymised) {
|
if (counts.basketsDeleted || counts.basketsCleared || counts.ordersAnonymised || counts.passesAnonymised) {
|
||||||
console.log('[privacy] retention:', JSON.stringify(counts));
|
console.log('[privacy] retention:', JSON.stringify(counts));
|
||||||
}
|
}
|
||||||
return counts;
|
return counts;
|
||||||
|
|
@ -176,7 +213,7 @@ function searchCustomers(app, query) {
|
||||||
|
|
||||||
/** Everything stored about one customer — the admin's detail view and the GDPR export. */
|
/** Everything stored about one customer — the admin's detail view and the GDPR export. */
|
||||||
function customerData(app, email) {
|
function customerData(app, email) {
|
||||||
const { orders, baskets } = customerRecords(app, email);
|
const { orders, baskets, passes } = customerRecords(app, email);
|
||||||
return {
|
return {
|
||||||
email: normaliseEmail(email),
|
email: normaliseEmail(email),
|
||||||
exportedAt: new Date().toISOString(),
|
exportedAt: new Date().toISOString(),
|
||||||
|
|
@ -199,6 +236,16 @@ function customerData(app, email) {
|
||||||
}))
|
}))
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
// Bundle/voucher codes bought with this email, and who they are for.
|
||||||
|
codes: passes.map((pass) => ({
|
||||||
|
code: pass.getString('code'),
|
||||||
|
name: pass.getString('name'),
|
||||||
|
created: pass.getString('created'),
|
||||||
|
expiresAt: pass.getString('expiresAt'),
|
||||||
|
status: pass.getString('status'),
|
||||||
|
recipientName: pass.getString('recipientName'),
|
||||||
|
message: pass.getString('message')
|
||||||
|
})),
|
||||||
// Checkouts that were started but never paid for.
|
// Checkouts that were started but never paid for.
|
||||||
unpaidBaskets: baskets.map((basket) => ({
|
unpaidBaskets: baskets.map((basket) => ({
|
||||||
id: basket.id,
|
id: basket.id,
|
||||||
|
|
@ -229,24 +276,36 @@ function updateCustomer(app, body) {
|
||||||
|
|
||||||
let updated = 0;
|
let updated = 0;
|
||||||
app.runInTransaction((tx) => {
|
app.runInTransaction((tx) => {
|
||||||
const { orders, baskets } = customerRecords(tx, email);
|
const { orders, baskets, passes } = customerRecords(tx, email);
|
||||||
if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email');
|
if (!orders.length && !baskets.length && !passes.length) throw new NotFoundError('No customer with that email');
|
||||||
for (const record of [...orders, ...baskets]) {
|
for (const record of [...orders, ...baskets]) {
|
||||||
record.set('customerDetails', Object.assign(details(record), patch));
|
record.set('customerDetails', Object.assign(details(record), patch));
|
||||||
if (patch.email) record.set('email', patch.email);
|
if (patch.email) record.set('email', patch.email);
|
||||||
tx.save(record);
|
tx.save(record);
|
||||||
updated++;
|
updated++;
|
||||||
}
|
}
|
||||||
|
// Codes only hold the email.
|
||||||
|
if (patch.email) {
|
||||||
|
for (const pass of passes) {
|
||||||
|
pass.set('email', patch.email);
|
||||||
|
tx.save(pass);
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
return { updated, email: patch.email ? normaliseEmail(patch.email) : email };
|
return { updated, email: patch.email ? normaliseEmail(patch.email) : email };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Right to erasure: anonymise the customer's orders and delete their unpaid baskets. */
|
/** Right to erasure: anonymise the customer's orders and codes, and delete their unpaid baskets. */
|
||||||
function eraseCustomer(app, body) {
|
function eraseCustomer(app, body) {
|
||||||
const counts = { ordersAnonymised: 0, basketsDeleted: 0 };
|
const counts = { ordersAnonymised: 0, basketsDeleted: 0, passesAnonymised: 0 };
|
||||||
app.runInTransaction((tx) => {
|
app.runInTransaction((tx) => {
|
||||||
const { orders, baskets } = customerRecords(tx, body.email);
|
const { orders, baskets, passes } = customerRecords(tx, body.email);
|
||||||
if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email');
|
if (!orders.length && !baskets.length && !passes.length) throw new NotFoundError('No customer with that email');
|
||||||
|
for (const pass of passes) {
|
||||||
|
anonymisePass(tx, pass);
|
||||||
|
counts.passesAnonymised++;
|
||||||
|
}
|
||||||
for (const order of orders) {
|
for (const order of orders) {
|
||||||
anonymiseOrder(tx, order);
|
anonymiseOrder(tx, order);
|
||||||
counts.ordersAnonymised++;
|
counts.ordersAnonymised++;
|
||||||
|
|
|
||||||
|
|
@ -41,7 +41,28 @@ routerAdd('POST', '/api/shop/stripe-webhook', (e) => {
|
||||||
|
|
||||||
routerAdd('GET', '/api/shop/order', (e) => {
|
routerAdd('GET', '/api/shop/order', (e) => {
|
||||||
const shop = require(`${__hooks}/shop/lib.js`);
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
return e.json(200, shop.orderStatus($app, e.request.url.query().get('payment_intent')));
|
const query = e.request.url.query();
|
||||||
|
return e.json(200, shop.orderStatus($app, query.get('payment_intent'), { orderId: query.get('order'), basketId: query.get('basket') }));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Bundle/voucher codes, for the signed-in admin (Vouchers & codes page).
|
||||||
|
// Customers only use codes through their basket (`apply_code`).
|
||||||
|
routerAdd('GET', '/api/shop/passes', (e) => {
|
||||||
|
if (!e.auth) throw new UnauthorizedError('Sign in to see codes');
|
||||||
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
|
return e.json(200, { passes: shop.listPasses($app, e.request.url.query().get('q')) });
|
||||||
|
});
|
||||||
|
|
||||||
|
routerAdd('POST', '/api/shop/passes/update', (e) => {
|
||||||
|
if (!e.auth) throw new UnauthorizedError('Sign in to change codes');
|
||||||
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
|
return e.json(200, { pass: shop.updatePass($app, e.requestInfo().body) });
|
||||||
|
});
|
||||||
|
|
||||||
|
routerAdd('POST', '/api/shop/passes/issue', (e) => {
|
||||||
|
if (!e.auth) throw new UnauthorizedError('Sign in to issue codes');
|
||||||
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
|
return e.json(200, { pass: shop.issuePass($app, e.requestInfo().body) });
|
||||||
});
|
});
|
||||||
|
|
||||||
routerAdd('POST', '/api/shop/order-email-status', (e) => {
|
routerAdd('POST', '/api/shop/order-email-status', (e) => {
|
||||||
|
|
|
||||||
|
|
@ -423,6 +423,271 @@ function guardedTransaction(app, fallback, fn) {
|
||||||
if (refusal) throw refusal;
|
if (refusal) throw refusal;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Bundles and codes ───────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// A bundle is an item (type `bundle`) with its own price, made of parts: a
|
||||||
|
// service at one length × count, or a product × count. Buying one creates a
|
||||||
|
// pass with a code. Its service parts are booked later — by whoever has the
|
||||||
|
// code, until it expires — at no charge; product parts are handed over with
|
||||||
|
// the purchase (stock is taken then).
|
||||||
|
//
|
||||||
|
// A pass keeps a snapshot of its parts with each part's share of the price
|
||||||
|
// (`value`, for refunds). What's used is never stored: it is counted from
|
||||||
|
// order lines (not refunded) and live basket holds pointing at the pass,
|
||||||
|
// like slot availability. A basket line gets `pass` when a code covers it;
|
||||||
|
// that line then costs nothing.
|
||||||
|
|
||||||
|
/** Codes are 8 characters from this alphabet (no 0/O or 1/I to misread). */
|
||||||
|
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||||
|
const CODE_LENGTH = 8;
|
||||||
|
|
||||||
|
function isBundle(item) {
|
||||||
|
return !!item && item.getString('type') === 'bundle';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bundle's parts, `[{ item, minutes (null: a product), count }]`; invalid entries are left out. */
|
||||||
|
function bundleParts(item) {
|
||||||
|
const list = jsonValue(item.get('bundleParts'), []);
|
||||||
|
return (Array.isArray(list) ? list : [])
|
||||||
|
.map((p) => ({ item: String((p && p.item) || ''), minutes: p && p.minutes ? Math.floor(Number(p.minutes)) : null, count: Math.floor(Number(p && p.count)) || 0 }))
|
||||||
|
.filter((p) => p.item && p.count > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A bundle's parts with names and each part's share of the bundle price
|
||||||
|
* (`value`, all its units together): the price split in proportion to what
|
||||||
|
* the parts cost on their own (evenly when those are all 0), in cents, with
|
||||||
|
* the rounding on the last part. Throws an ApiError when a part can't be
|
||||||
|
* sold — unless `lenient` (an order being created after payment), which
|
||||||
|
* keeps the part with what it can find.
|
||||||
|
*/
|
||||||
|
function bundleSnapshot(app, bundle, lenient) {
|
||||||
|
const name = bundle.getString('name');
|
||||||
|
const parts = bundleParts(bundle).map((part) => {
|
||||||
|
const item = findOrNull(app, 'items', part.item);
|
||||||
|
const own = !item ? null : isService(item) ? unitPrice(item, part.minutes) : item.getFloat('price');
|
||||||
|
if (own === null && !lenient) throw conflict(`"${name}" can't be bought right now — one of its parts is no longer offered`);
|
||||||
|
return { item: part.item, name: item ? item.getString('name') : 'Unknown item', minutes: isService(item) ? part.minutes : null, count: part.count, ownCents: Math.round((own || 0) * 100) };
|
||||||
|
});
|
||||||
|
if (!parts.length && !lenient) throw conflict(`"${name}" has nothing in it yet`);
|
||||||
|
const totalCents = Math.round(bundle.getFloat('price') * 100);
|
||||||
|
const units = parts.reduce((n, p) => n + p.count, 0);
|
||||||
|
const listCents = parts.reduce((sum, p) => sum + p.ownCents * p.count, 0);
|
||||||
|
let assigned = 0;
|
||||||
|
parts.forEach((p, i) => {
|
||||||
|
const share = listCents > 0 ? (p.ownCents * p.count) / listCents : p.count / units;
|
||||||
|
const cents = i === parts.length - 1 ? totalCents - assigned : Math.round(totalCents * share);
|
||||||
|
assigned += cents;
|
||||||
|
p.value = cents / 100;
|
||||||
|
delete p.ownCents;
|
||||||
|
});
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normaliseCode(value) {
|
||||||
|
return String(value || '')
|
||||||
|
.toUpperCase()
|
||||||
|
.replace(/[^A-Z0-9]/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `ABCD2345` → `ABCD-2345`, as shown to people (formatCode in packages/shared/src/items.ts does the same). */
|
||||||
|
function formatCode(code) {
|
||||||
|
return code.length === CODE_LENGTH ? code.slice(0, 4) + '-' + code.slice(4) : code;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findPassByCode(app, code) {
|
||||||
|
const normalised = normaliseCode(code);
|
||||||
|
if (!normalised) return null;
|
||||||
|
return findAll(app, 'passes', 'code = {:code}', { code: normalised })[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function newCode(app) {
|
||||||
|
for (let attempt = 0; attempt < 10; attempt++) {
|
||||||
|
const code = $security.randomStringWithAlphabet(CODE_LENGTH, CODE_ALPHABET);
|
||||||
|
if (!findPassByCode(app, code)) return code;
|
||||||
|
}
|
||||||
|
throw new InternalServerError('Could not create a unique code');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Epoch ms `months` from now, or '' for no expiry. */
|
||||||
|
function expiryIn(months) {
|
||||||
|
if (!(months > 0)) return '';
|
||||||
|
const date = new Date();
|
||||||
|
date.setUTCMonth(date.getUTCMonth() + months);
|
||||||
|
return date.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why a pass can't be used now (an ApiError), or null. */
|
||||||
|
function passProblem(pass) {
|
||||||
|
if (!pass) return new NotFoundError('That code was not found — check it and try again');
|
||||||
|
if (pass.getString('status') !== 'active') return conflict('That code is no longer valid');
|
||||||
|
const expires = toMs(pass.getString('expiresAt'));
|
||||||
|
if (expires <= Date.now()) return conflict(`That code expired on ${new Date(expires).toISOString().slice(0, 10)}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A pass's parts with what's used (paid bookings), held (live basket holds)
|
||||||
|
* and left. Product parts were handed over with the purchase: nothing left
|
||||||
|
* to redeem. `options.excludeLineId` leaves one basket line out.
|
||||||
|
*/
|
||||||
|
function passCredits(app, pass, options) {
|
||||||
|
const opts = options || {};
|
||||||
|
const parts = jsonValue(pass.get('parts'), []);
|
||||||
|
const key = (item, minutes) => item + '|' + (minutes || 0);
|
||||||
|
const used = {};
|
||||||
|
const held = {};
|
||||||
|
for (const line of findAll(app, 'order_lines', "pass = {:pass} && order.status != 'refunded'", { pass: pass.id })) {
|
||||||
|
const k = key(line.getString('item'), line.getInt('minutes'));
|
||||||
|
used[k] = (used[k] || 0) + line.getInt('quantity');
|
||||||
|
}
|
||||||
|
for (const line of findAll(app, 'basket_lines', 'pass = {:pass} && heldUntil > {:now}', { pass: pass.id, now: pbDate(Date.now()) })) {
|
||||||
|
if (line.id === opts.excludeLineId) continue;
|
||||||
|
const k = key(line.getString('item'), line.getInt('minutes'));
|
||||||
|
held[k] = (held[k] || 0) + line.getInt('quantity');
|
||||||
|
}
|
||||||
|
return (Array.isArray(parts) ? parts : []).map((part) => {
|
||||||
|
const k = key(part.item, part.minutes);
|
||||||
|
const redeemable = !!part.minutes;
|
||||||
|
return Object.assign({}, part, {
|
||||||
|
redeemable,
|
||||||
|
used: redeemable ? used[k] || 0 : part.count,
|
||||||
|
held: held[k] || 0,
|
||||||
|
left: redeemable ? Math.max(0, part.count - (used[k] || 0) - (held[k] || 0)) : 0
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a pass is shown to the customer and the admin. */
|
||||||
|
function passSummary(app, pass) {
|
||||||
|
return {
|
||||||
|
id: pass.id,
|
||||||
|
code: formatCode(pass.getString('code')),
|
||||||
|
name: pass.getString('name'),
|
||||||
|
expiresAt: pass.getString('expiresAt') ? new Date(toMs(pass.getString('expiresAt'))).toISOString() : '',
|
||||||
|
status: pass.getString('status'),
|
||||||
|
recipientName: pass.getString('recipientName'),
|
||||||
|
message: pass.getString('message'),
|
||||||
|
parts: passCredits(app, pass).map((p) => ({ item: p.item, name: p.name, minutes: p.minutes, count: p.count, value: p.value, redeemable: p.redeemable, used: p.used, held: p.held, left: p.left }))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Let the basket's code cover its bookings that match a part with places
|
||||||
|
* left (same service and length), oldest line first. Lines already covered
|
||||||
|
* stay covered. Call inside the transaction that added the lines.
|
||||||
|
*/
|
||||||
|
function coverWithPass(app, basket) {
|
||||||
|
const pass = findOrNull(app, 'passes', basket.getString('pass'));
|
||||||
|
if (!pass || passProblem(pass)) return;
|
||||||
|
const credits = passCredits(app, pass);
|
||||||
|
const lines = findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot' && pass = ''", { basket: basket.id }, 'created');
|
||||||
|
for (const line of lines) {
|
||||||
|
const part = credits.find((p) => p.redeemable && p.item === line.getString('item') && p.minutes === line.getInt('minutes') && p.left >= line.getInt('quantity'));
|
||||||
|
if (!part) continue;
|
||||||
|
part.left -= line.getInt('quantity');
|
||||||
|
line.set('pass', pass.id);
|
||||||
|
app.save(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function uncoverLines(app, basketId) {
|
||||||
|
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && pass != ''", { basket: basketId })) {
|
||||||
|
line.set('pass', '');
|
||||||
|
app.save(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The passes an order bought, as shown on the confirmation page and in emails. */
|
||||||
|
function orderPasses(app, orderId) {
|
||||||
|
return findAll(app, 'passes', 'order = {:order}', { order: orderId }, 'created').map((pass) => passSummary(app, pass));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Units of each product the basket needs: product lines plus products inside bundles. */
|
||||||
|
function productNeeds(app, lines, extra) {
|
||||||
|
const needs = {};
|
||||||
|
const add = (id, n) => (needs[id] = (needs[id] || 0) + n);
|
||||||
|
for (const line of lines.concat(extra || [])) {
|
||||||
|
if (line.getString('lineType') !== 'item') continue;
|
||||||
|
const item = findOrNull(app, 'items', line.getString('item'));
|
||||||
|
if (!item) continue;
|
||||||
|
if (isBundle(item)) {
|
||||||
|
for (const part of bundleParts(item)) {
|
||||||
|
const partItem = findOrNull(app, 'items', part.item);
|
||||||
|
if (partItem && !isService(partItem)) add(part.item, part.count * line.getInt('quantity'));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
add(item.id, line.getInt('quantity'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return needs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An ApiError when stock can't cover `needs`, or null. */
|
||||||
|
function stockProblem(app, needs) {
|
||||||
|
for (const id of Object.keys(needs)) {
|
||||||
|
const item = findOrNull(app, 'items', id);
|
||||||
|
if (!item) continue;
|
||||||
|
if (item.getBool('trackStock') && needs[id] > item.getInt('stock')) {
|
||||||
|
return conflict(item.getInt('stock') > 0 ? `Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock` : `"${item.getString('name')}" is sold out`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Admin: codes ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Codes for the admin, newest first; `query` matches the code, email, recipient or bundle name. */
|
||||||
|
function listPasses(app, query) {
|
||||||
|
const q = String(query || '').trim();
|
||||||
|
const code = normaliseCode(q);
|
||||||
|
const filter = q ? '(code ~ {:code} || email ~ {:q} || recipientName ~ {:q} || name ~ {:q})' : "id != ''";
|
||||||
|
return findAll(app, 'passes', filter, { q, code: code || q }, '-created')
|
||||||
|
.slice(0, 200)
|
||||||
|
.map((pass) => Object.assign(passSummary(app, pass), { email: pass.getString('email'), order: pass.getString('order'), created: pass.getString('created'), anonymisedAt: pass.getString('anonymisedAt') }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Void/reactivate a code or change when it expires. `body`: { id, status?, expiresAt? (ISO or '' for never) }. */
|
||||||
|
function updatePass(app, body) {
|
||||||
|
const pass = findOrNull(app, 'passes', String(body.id || ''));
|
||||||
|
if (!pass) throw new NotFoundError('Code not found');
|
||||||
|
if (body.status !== undefined) {
|
||||||
|
if (body.status !== 'active' && body.status !== 'void') throw new BadRequestError('Unknown status');
|
||||||
|
pass.set('status', body.status);
|
||||||
|
}
|
||||||
|
if (body.expiresAt !== undefined) {
|
||||||
|
const ms = toMs(body.expiresAt);
|
||||||
|
if (body.expiresAt !== '' && Number.isNaN(ms)) throw new BadRequestError('Invalid expiry date');
|
||||||
|
pass.set('expiresAt', body.expiresAt === '' ? '' : new Date(ms).toISOString());
|
||||||
|
}
|
||||||
|
app.save(pass);
|
||||||
|
return passSummary(app, pass);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Issue a code without a purchase (a gift from the studio, a replacement).
|
||||||
|
* `body`: { itemId (a bundle), email?, recipientName?, message?, months? }.
|
||||||
|
*/
|
||||||
|
function issuePass(app, body) {
|
||||||
|
const bundle = findOrNull(app, 'items', String(body.itemId || ''));
|
||||||
|
if (!isBundle(bundle)) throw new BadRequestError('Choose a bundle');
|
||||||
|
const months = body.months === undefined || body.months === '' ? bundle.getInt('validMonths') : Math.floor(Number(body.months));
|
||||||
|
if (!(months >= 0 && months <= 120)) throw new BadRequestError('Valid for 0 (no expiry) to 120 months');
|
||||||
|
const pass = newRecord(app, 'passes', {
|
||||||
|
code: newCode(app),
|
||||||
|
item: bundle.id,
|
||||||
|
name: bundle.getString('name'),
|
||||||
|
parts: bundleSnapshot(app, bundle),
|
||||||
|
email: String(body.email || '').trim().slice(0, 320),
|
||||||
|
recipientName: String(body.recipientName || '').trim().slice(0, 180),
|
||||||
|
message: String(body.message || '').trim().slice(0, 1000),
|
||||||
|
expiresAt: expiryIn(months),
|
||||||
|
status: 'active'
|
||||||
|
});
|
||||||
|
app.save(pass);
|
||||||
|
return passSummary(app, pass);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Holds and baskets ───────────────────────────────────────────────────
|
// ── Holds and baskets ───────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -461,21 +726,26 @@ function basketLines(app, basketId) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The basket as returned to the public app, which maps it to the `Basket`
|
* The basket as returned to the public app, which maps it to the `Basket`
|
||||||
* type. Each line also gets `unitPrice` (null: the service is no longer
|
* type. Each line also gets `unitPrice` (0 when a code covers it; null: the
|
||||||
* offered at that length) and, for a booking, `end`.
|
* service is no longer offered at that length), for a booking `end`, and
|
||||||
|
* for a bundle `bundle` (its parts and validity). `pass` is the applied
|
||||||
|
* code with what it has left.
|
||||||
*/
|
*/
|
||||||
function basketPayload(app, basket) {
|
function basketPayload(app, basket) {
|
||||||
if (!basket) return null;
|
if (!basket) return null;
|
||||||
const lines = basketLines(app, basket.id);
|
const lines = basketLines(app, basket.id);
|
||||||
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
|
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
|
||||||
|
const pass = findOrNull(app, 'passes', basket.getString('pass'));
|
||||||
return {
|
return {
|
||||||
record: plain(basket),
|
record: plain(basket),
|
||||||
|
pass: pass ? passSummary(app, pass) : null,
|
||||||
lines: lines.map((line) => {
|
lines: lines.map((line) => {
|
||||||
const json = plain(line);
|
const json = plain(line);
|
||||||
const item = line.expandedOne('item');
|
const item = line.expandedOne('item');
|
||||||
json.unitPrice = item ? unitPrice(item, line.getInt('minutes')) : null;
|
json.unitPrice = line.getString('pass') ? 0 : item ? unitPrice(item, line.getInt('minutes')) : null;
|
||||||
const start = toMs(line.getString('start'));
|
const start = toMs(line.getString('start'));
|
||||||
if (!Number.isNaN(start)) json.end = new Date(start + line.getInt('minutes') * MINUTE_MS).toISOString();
|
if (!Number.isNaN(start)) json.end = new Date(start + line.getInt('minutes') * MINUTE_MS).toISOString();
|
||||||
|
if (isBundle(item)) json.bundle = { validMonths: item.getInt('validMonths'), parts: bundleSnapshot(app, item, true) };
|
||||||
return json;
|
return json;
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
@ -512,6 +782,12 @@ function extendBasketHolds(app, basketId, durationMs) {
|
||||||
app.runInTransaction((tx) => {
|
app.runInTransaction((tx) => {
|
||||||
const fresh = tx.findRecordById('basket_lines', line.id);
|
const fresh = tx.findRecordById('basket_lines', line.id);
|
||||||
if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return;
|
if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return;
|
||||||
|
// A code's places may have been used up meanwhile: then the time is let go too.
|
||||||
|
const pass = findOrNull(tx, 'passes', fresh.getString('pass'));
|
||||||
|
if (pass) {
|
||||||
|
const part = passCredits(tx, pass, { excludeLineId: fresh.id }).find((p) => p.redeemable && p.item === fresh.getString('item') && p.minutes === fresh.getInt('minutes'));
|
||||||
|
if (passProblem(pass) || !part || part.left < fresh.getInt('quantity')) return;
|
||||||
|
}
|
||||||
fresh.set('heldUntil', until);
|
fresh.set('heldUntil', until);
|
||||||
tx.save(fresh);
|
tx.save(fresh);
|
||||||
});
|
});
|
||||||
|
|
@ -530,7 +806,7 @@ function basketAction(app, body) {
|
||||||
|
|
||||||
const action = String(body.action || '');
|
const action = String(body.action || '');
|
||||||
let basket = loadActiveBasket(app, body.basketId);
|
let basket = loadActiveBasket(app, body.basketId);
|
||||||
if (!basket && (action === 'add_item' || action === 'add_slot')) basket = createBasket(app);
|
if (!basket && (action === 'add_item' || action === 'add_slot' || action === 'apply_code')) basket = createBasket(app);
|
||||||
if (!basket) throw new BadRequestError('No active basket — add an item first');
|
if (!basket) throw new BadRequestError('No active basket — add an item first');
|
||||||
const lines = basketLines(app, basket.id);
|
const lines = basketLines(app, basket.id);
|
||||||
|
|
||||||
|
|
@ -540,14 +816,17 @@ function basketAction(app, body) {
|
||||||
const quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1);
|
const quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1);
|
||||||
const item = findOrNull(app, 'items', itemId);
|
const item = findOrNull(app, 'items', itemId);
|
||||||
if (!item || !item.getBool('active')) throw new NotFoundError('Item not found');
|
if (!item || !item.getBool('active')) throw new NotFoundError('Item not found');
|
||||||
if (item.getString('type') !== 'item') throw new BadRequestError('Use add_slot for bookable services');
|
if (isService(item)) throw new BadRequestError('Use add_slot for bookable services');
|
||||||
|
if (isBundle(item)) bundleSnapshot(app, item); // throws if it can't be sold
|
||||||
|
|
||||||
|
// Stock for products, including those inside bundles, across the whole basket.
|
||||||
const existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId);
|
const existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId);
|
||||||
const newQty = (existing ? existing.getInt('quantity') : 0) + quantity;
|
const adding = newRecord(app, 'basket_lines', { basket: basket.id, item: itemId, quantity, lineType: 'item' });
|
||||||
const stock = item.get('stock');
|
const problem = stockProblem(app, productNeeds(app, lines, [adding]));
|
||||||
if (stock != null && stock !== '' && newQty > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
if (problem) throw problem;
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
|
const newQty = existing.getInt('quantity') + quantity;
|
||||||
existing.set('quantity', newQty);
|
existing.set('quantity', newQty);
|
||||||
app.save(existing);
|
app.save(existing);
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -587,7 +866,10 @@ function basketAction(app, body) {
|
||||||
});
|
});
|
||||||
line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1));
|
line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1));
|
||||||
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||||
|
// More places than the code covers: this line is paid for instead.
|
||||||
|
if (existing && existing.getString('pass')) existing.set('pass', '');
|
||||||
tx.save(line);
|
tx.save(line);
|
||||||
|
coverWithPass(tx, tx.findRecordById('baskets', basket.id));
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -607,18 +889,59 @@ function basketAction(app, body) {
|
||||||
if (check.error) return check.error;
|
if (check.error) return check.error;
|
||||||
fresh.set('quantity', quantity);
|
fresh.set('quantity', quantity);
|
||||||
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||||
|
fresh.set('pass', ''); // re-covered below if the code has enough places
|
||||||
tx.save(fresh);
|
tx.save(fresh);
|
||||||
|
coverWithPass(tx, tx.findRecordById('baskets', basket.id));
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const item = findOrNull(app, 'items', line.getString('item'));
|
const others = lines.filter((l) => l.id !== line.id);
|
||||||
const stock = item ? item.get('stock') : null;
|
const changed = newRecord(app, 'basket_lines', { basket: basket.id, item: line.getString('item'), quantity, lineType: 'item' });
|
||||||
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
const problem = stockProblem(app, productNeeds(app, others, [changed]));
|
||||||
|
if (problem) throw problem;
|
||||||
line.set('quantity', quantity);
|
line.set('quantity', quantity);
|
||||||
app.save(line);
|
app.save(line);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'apply_code': {
|
||||||
|
// A bundle/voucher code: bookings it covers cost nothing.
|
||||||
|
guardedTransaction(app, 'Could not apply the code — please try again', (tx) => {
|
||||||
|
const pass = findPassByCode(tx, body.code);
|
||||||
|
const problem = passProblem(pass);
|
||||||
|
if (problem) return problem;
|
||||||
|
const fresh = tx.findRecordById('baskets', basket.id);
|
||||||
|
if (fresh.getString('pass') !== pass.id) uncoverLines(tx, basket.id);
|
||||||
|
fresh.set('pass', pass.id);
|
||||||
|
tx.save(fresh);
|
||||||
|
coverWithPass(tx, fresh);
|
||||||
|
});
|
||||||
|
basket = app.findRecordById('baskets', basket.id);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'remove_code': {
|
||||||
|
guardedTransaction(app, 'Could not remove the code — please try again', (tx) => {
|
||||||
|
uncoverLines(tx, basket.id);
|
||||||
|
const fresh = tx.findRecordById('baskets', basket.id);
|
||||||
|
fresh.set('pass', '');
|
||||||
|
tx.save(fresh);
|
||||||
|
});
|
||||||
|
basket = app.findRecordById('baskets', basket.id);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'set_gift': {
|
||||||
|
// Who a bundle is for: shown with its code in the confirmation email.
|
||||||
|
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||||
|
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||||
|
if (!isBundle(findOrNull(app, 'items', line.getString('item')))) throw new BadRequestError('Only bundles and vouchers can be gifts');
|
||||||
|
line.set('giftTo', String(body.giftTo || '').trim().slice(0, 180));
|
||||||
|
line.set('giftMessage', String(body.giftMessage || '').trim().slice(0, 1000));
|
||||||
|
app.save(line);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case 'renew_holds': {
|
case 'renew_holds': {
|
||||||
// "Keep my reservation" at checkout. Holds that already lapsed were
|
// "Keep my reservation" at checkout. Holds that already lapsed were
|
||||||
// swept above; the customer is told and picks the time again.
|
// swept above; the customer is told and picks the time again.
|
||||||
|
|
@ -684,7 +1007,9 @@ function currency() {
|
||||||
/**
|
/**
|
||||||
* Start (or resume) payment for a basket: validate every line against the
|
* Start (or resume) payment for a basket: validate every line against the
|
||||||
* database (the source of truth for the total), then create or update the
|
* database (the source of truth for the total), then create or update the
|
||||||
* Stripe PaymentIntent. Returns the client secret for Stripe Elements.
|
* Stripe PaymentIntent. Returns `{ clientSecret }` for Stripe Elements — or,
|
||||||
|
* when codes cover everything (total 0), creates the order at once and
|
||||||
|
* returns `{ free: true, orderId, orderEmail }` (no payment step).
|
||||||
*/
|
*/
|
||||||
function startCheckout(app, body) {
|
function startCheckout(app, body) {
|
||||||
const basketId = String(body.basketId || '');
|
const basketId = String(body.basketId || '');
|
||||||
|
|
@ -708,6 +1033,15 @@ function startCheckout(app, body) {
|
||||||
if (!customer.name) throw new BadRequestError('Name is required');
|
if (!customer.name) throw new BadRequestError('Name is required');
|
||||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email is required');
|
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email is required');
|
||||||
|
|
||||||
|
// A code voided or expired since it was applied stops covering anything.
|
||||||
|
const applied = findOrNull(app, 'passes', basket.getString('pass'));
|
||||||
|
if (basket.getString('pass') && passProblem(applied)) {
|
||||||
|
uncoverLines(app, basket.id);
|
||||||
|
basket.set('pass', '');
|
||||||
|
app.save(basket);
|
||||||
|
throw conflict(`Your code ${applied ? formatCode(applied.getString('code')) + ' ' : ''}can no longer be used — the bookings it covered are now charged. Please check your basket.`);
|
||||||
|
}
|
||||||
|
|
||||||
let totalCents = 0;
|
let totalCents = 0;
|
||||||
const summary = [];
|
const summary = [];
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
|
|
@ -719,18 +1053,36 @@ function startCheckout(app, body) {
|
||||||
if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) {
|
if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) {
|
||||||
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
|
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
|
||||||
}
|
}
|
||||||
} else {
|
} else if (isBundle(item)) {
|
||||||
const stock = item.get('stock');
|
bundleSnapshot(app, item); // throws if it can't be sold
|
||||||
if (stock != null && stock !== '' && item.getInt('stock') < quantity) {
|
|
||||||
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
|
|
||||||
}
|
}
|
||||||
}
|
const price = line.getString('pass') ? 0 : unitPrice(item, line.getInt('minutes'));
|
||||||
const price = unitPrice(item, line.getInt('minutes'));
|
|
||||||
if (price === null) throw conflict(`"${item.getString('name')}" is no longer offered for ${line.getInt('minutes')} minutes — please pick it again`);
|
if (price === null) throw conflict(`"${item.getString('name')}" is no longer offered for ${line.getInt('minutes')} minutes — please pick it again`);
|
||||||
totalCents += Math.round(price * 100) * quantity;
|
totalCents += Math.round(price * 100) * quantity;
|
||||||
summary.push(`${quantity}× ${item.getString('name')}`);
|
summary.push(`${quantity}× ${item.getString('name')}`);
|
||||||
}
|
}
|
||||||
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
|
const stock = stockProblem(app, productNeeds(app, lines));
|
||||||
|
if (stock) throw stock;
|
||||||
|
|
||||||
|
basket.set('email', customer.email);
|
||||||
|
basket.set('customerDetails', customer);
|
||||||
|
if (totalCents === 0) {
|
||||||
|
// Everything is covered by a code: confirm without a payment. A payment
|
||||||
|
// started before the code was applied is cancelled, so it can't be paid too.
|
||||||
|
const staleIntent = basket.getString('stripePaymentIntentId');
|
||||||
|
if (staleIntent) {
|
||||||
|
try {
|
||||||
|
stripe('POST', '/v1/payment_intents/' + encodeURIComponent(staleIntent) + '/cancel', {});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[shop] could not cancel payment', staleIntent, e);
|
||||||
|
}
|
||||||
|
basket.set('stripePaymentIntentId', '');
|
||||||
|
}
|
||||||
|
app.save(basket);
|
||||||
|
const orderId = createOrder(app, basket.id, { intentId: '', total: 0, receiptEmail: customer.email });
|
||||||
|
if (!orderId) throw conflict('This basket was already checked out');
|
||||||
|
return { free: true, orderId, orderEmail: orderEmailData(app, orderId) };
|
||||||
|
}
|
||||||
|
|
||||||
let intent = null;
|
let intent = null;
|
||||||
const existingId = basket.getString('stripePaymentIntentId');
|
const existingId = basket.getString('stripePaymentIntentId');
|
||||||
|
|
@ -764,8 +1116,6 @@ function startCheckout(app, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
basket.set('stripePaymentIntentId', intent.id);
|
basket.set('stripePaymentIntentId', intent.id);
|
||||||
basket.set('email', customer.email);
|
|
||||||
basket.set('customerDetails', customer);
|
|
||||||
app.save(basket);
|
app.save(basket);
|
||||||
return { clientSecret: intent.client_secret };
|
return { clientSecret: intent.client_secret };
|
||||||
}
|
}
|
||||||
|
|
@ -821,46 +1171,87 @@ function handleStripeWebhook(app, rawBody, signature) {
|
||||||
function createOrderFromIntent(app, intent) {
|
function createOrderFromIntent(app, intent) {
|
||||||
const basketId = intent.metadata && intent.metadata.basket_id;
|
const basketId = intent.metadata && intent.metadata.basket_id;
|
||||||
if (!basketId || !intent.id) return null; // not one of ours
|
if (!basketId || !intent.id) return null; // not one of ours
|
||||||
|
return createOrder(app, basketId, { intentId: intent.id, total: intent.amount / 100, receiptEmail: intent.receipt_email });
|
||||||
|
}
|
||||||
|
|
||||||
|
function takeStock(app, item, quantity) {
|
||||||
|
if (!item || !item.getBool('trackStock')) return;
|
||||||
|
item.set('stock', Math.max(0, item.getInt('stock') - quantity));
|
||||||
|
app.save(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turn a basket into an order: after a Stripe payment (`payment.intentId`,
|
||||||
|
* idempotent per intent) or with nothing to pay (`intentId` '', only while
|
||||||
|
* the basket is still active). Bundles become passes with new codes.
|
||||||
|
* Returns the new order id, or null if there was nothing to do.
|
||||||
|
*/
|
||||||
|
function createOrder(app, basketId, payment) {
|
||||||
let orderId = null;
|
let orderId = null;
|
||||||
app.runInTransaction((tx) => {
|
app.runInTransaction((tx) => {
|
||||||
const existing = findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: intent.id });
|
if (payment.intentId && findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: payment.intentId }).length) return; // Stripe retried — already handled
|
||||||
if (existing.length) return; // Stripe retried — already handled
|
|
||||||
const basket = findOrNull(tx, 'baskets', basketId);
|
const basket = findOrNull(tx, 'baskets', basketId);
|
||||||
if (!basket) return;
|
if (!basket) return;
|
||||||
|
if (!payment.intentId && basket.getString('status') !== 'active') return;
|
||||||
|
|
||||||
const lines = basketLines(tx, basketId);
|
const lines = basketLines(tx, basketId);
|
||||||
const order = newRecord(tx, 'orders', {
|
const order = newRecord(tx, 'orders', {
|
||||||
basket: basketId,
|
basket: basketId,
|
||||||
email: basket.getString('email') || intent.receipt_email || '',
|
email: basket.getString('email') || payment.receiptEmail || '',
|
||||||
customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {},
|
customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {},
|
||||||
total: intent.amount / 100,
|
total: payment.total,
|
||||||
status: 'paid',
|
status: 'paid',
|
||||||
stripePaymentIntentId: intent.id
|
stripePaymentIntentId: payment.intentId
|
||||||
});
|
});
|
||||||
tx.save(order);
|
tx.save(order);
|
||||||
|
|
||||||
// Snapshot lines and decrement stock. A booked time moves from the
|
// Snapshot lines and decrement stock. A booked time moves from the
|
||||||
// basket line (a hold) to the order line (a booking) in this same
|
// basket line (a hold) to the order line (a booking) in this same
|
||||||
// transaction, so availability never sees it free in between.
|
// transaction, so availability never sees it free in between; the
|
||||||
|
// same goes for a code's places (`pass`).
|
||||||
|
const orderLine = (fields) => tx.save(newRecord(tx, 'order_lines', Object.assign({ order: order.id }, fields)));
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
const item = findOrNull(tx, 'items', line.getString('item'));
|
const item = findOrNull(tx, 'items', line.getString('item'));
|
||||||
tx.save(
|
const name = item ? item.getString('name') : 'Unknown item';
|
||||||
newRecord(tx, 'order_lines', {
|
const quantity = line.getInt('quantity');
|
||||||
order: order.id,
|
orderLine({
|
||||||
item: line.getString('item'),
|
item: line.getString('item'),
|
||||||
slot: line.getString('slot'),
|
slot: line.getString('slot'),
|
||||||
quantity: line.getInt('quantity'),
|
pass: line.getString('pass'),
|
||||||
|
quantity,
|
||||||
lineType: line.getString('lineType'),
|
lineType: line.getString('lineType'),
|
||||||
name: item ? item.getString('name') : 'Unknown item',
|
name,
|
||||||
price: (item && unitPrice(item, line.getInt('minutes'))) || 0,
|
price: line.getString('pass') ? 0 : (item && unitPrice(item, line.getInt('minutes'))) || 0,
|
||||||
start: line.getString('start'),
|
start: line.getString('start'),
|
||||||
minutes: line.getInt('minutes')
|
minutes: line.getInt('minutes')
|
||||||
|
});
|
||||||
|
if (line.getString('lineType') !== 'item' || !item) continue;
|
||||||
|
if (!isBundle(item)) {
|
||||||
|
takeStock(tx, item, quantity);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// A bundle: one pass (code) per unit bought; its products go with this order.
|
||||||
|
const parts = bundleSnapshot(tx, item, true);
|
||||||
|
for (let i = 0; i < quantity; i++) {
|
||||||
|
tx.save(
|
||||||
|
newRecord(tx, 'passes', {
|
||||||
|
code: newCode(tx),
|
||||||
|
item: item.id,
|
||||||
|
order: order.id,
|
||||||
|
name,
|
||||||
|
parts,
|
||||||
|
email: order.getString('email'),
|
||||||
|
recipientName: line.getString('giftTo'),
|
||||||
|
message: line.getString('giftMessage'),
|
||||||
|
expiresAt: expiryIn(item.getInt('validMonths')),
|
||||||
|
status: 'active'
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
|
}
|
||||||
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
|
for (const part of parts) {
|
||||||
tx.save(item);
|
if (part.minutes) continue;
|
||||||
|
orderLine({ item: part.item, quantity: part.count * quantity, lineType: 'item', name: `${part.name} (in ${name})`, price: 0 });
|
||||||
|
takeStock(tx, findOrNull(tx, 'items', part.item), part.count * quantity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -898,10 +1289,11 @@ function emailTemplate(app, key) {
|
||||||
function orderEmailData(app, orderId) {
|
function orderEmailData(app, orderId) {
|
||||||
const order = app.findRecordById('orders', orderId);
|
const order = app.findRecordById('orders', orderId);
|
||||||
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start');
|
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start');
|
||||||
for (const line of lines) app.expandRecord(line, ['slot', 'item'], null);
|
for (const line of lines) app.expandRecord(line, ['slot', 'item', 'pass'], null);
|
||||||
return {
|
return {
|
||||||
order: plain(order),
|
order: plain(order),
|
||||||
lines: lines.map(plain),
|
lines: lines.map(plain),
|
||||||
|
passes: findAll(app, 'passes', 'order = {:order}', { order: orderId }, 'created').map(plain),
|
||||||
templates: {
|
templates: {
|
||||||
customer_confirmation: emailTemplate(app, 'customer_confirmation'),
|
customer_confirmation: emailTemplate(app, 'customer_confirmation'),
|
||||||
client_alert: emailTemplate(app, 'client_alert')
|
client_alert: emailTemplate(app, 'client_alert')
|
||||||
|
|
@ -911,11 +1303,32 @@ function orderEmailData(app, orderId) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A paid order as the result page shows it: lines (with the code that paid each) and the codes it bought. */
|
||||||
|
function paidOrder(app, order) {
|
||||||
|
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id');
|
||||||
|
return {
|
||||||
|
state: 'paid',
|
||||||
|
order: plain(order),
|
||||||
|
lines: lines.map((line) => {
|
||||||
|
const pass = findOrNull(app, 'passes', line.getString('pass'));
|
||||||
|
return Object.assign(plain(line), { passCode: pass ? formatCode(pass.getString('code')) : '' });
|
||||||
|
}),
|
||||||
|
passes: orderPasses(app, order.id)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Payment result page. The PaymentIntent id comes from Stripe's redirect;
|
* Payment result page. After a payment, `paymentIntentId` comes from
|
||||||
* it is checked with Stripe first, so made-up ids reveal nothing.
|
* Stripe's redirect and is checked with Stripe first, so made-up ids reveal
|
||||||
|
* nothing. An order with nothing to pay is looked up by `orderId` plus the
|
||||||
|
* customer's `basketId` (their cookie — the bearer secret for that basket).
|
||||||
*/
|
*/
|
||||||
function orderStatus(app, paymentIntentId) {
|
function orderStatus(app, paymentIntentId, free) {
|
||||||
|
if (free && free.orderId) {
|
||||||
|
const order = findOrNull(app, 'orders', String(free.orderId));
|
||||||
|
if (!order || !free.basketId || order.getString('basket') !== String(free.basketId)) return { state: 'missing' };
|
||||||
|
return paidOrder(app, order);
|
||||||
|
}
|
||||||
const id = String(paymentIntentId || '');
|
const id = String(paymentIntentId || '');
|
||||||
if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' };
|
if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' };
|
||||||
let intent;
|
let intent;
|
||||||
|
|
@ -931,9 +1344,7 @@ function orderStatus(app, paymentIntentId) {
|
||||||
if (intent.status === 'succeeded') return { state: 'processing' };
|
if (intent.status === 'succeeded') return { state: 'processing' };
|
||||||
return { state: intent.status === 'canceled' ? 'canceled' : 'failed' };
|
return { state: intent.status === 'canceled' ? 'canceled' : 'failed' };
|
||||||
}
|
}
|
||||||
const order = orders[0];
|
return paidOrder(app, orders[0]);
|
||||||
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id');
|
|
||||||
return { state: 'paid', order: plain(order), lines: lines.map(plain) };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -953,6 +1364,9 @@ function recordEmailStatus(app, secretHeader, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
listPasses,
|
||||||
|
updatePass,
|
||||||
|
issuePass,
|
||||||
bookableTimes,
|
bookableTimes,
|
||||||
slotDetails,
|
slotDetails,
|
||||||
sweepExpiredHolds,
|
sweepExpiredHolds,
|
||||||
|
|
|
||||||
159
pocketbase/pb_migrations/1793200000_bundles_and_passes.js
Normal file
159
pocketbase/pb_migrations/1793200000_bundles_and_passes.js
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
// Bundles and codes (vouchers).
|
||||||
|
//
|
||||||
|
// - items.type gains `bundle`: a shop item with its own price made of
|
||||||
|
// `bundleParts` ([{ item, minutes, count }] — a service at one length, or
|
||||||
|
// a product with minutes null), valid for `validMonths` after purchase.
|
||||||
|
// - passes: one per bundle bought (or issued by hand in the admin). `code`
|
||||||
|
// is what the customer types; `parts` is a snapshot of the bundle with
|
||||||
|
// each unit's share of the price (`value`). How much of a pass is used is
|
||||||
|
// never stored: it is counted from order lines and live basket holds that
|
||||||
|
// point at it (pb_hooks/shop/lib.js, passCredits).
|
||||||
|
// - baskets.pass: the code applied at checkout. basket_lines.pass /
|
||||||
|
// order_lines.pass: the pass that pays for that booking.
|
||||||
|
// - basket_lines.giftTo / giftMessage: who a bundle in the basket is for.
|
||||||
|
// - items.trackStock: whether `stock` is enforced. PocketBase can't store an
|
||||||
|
// empty number (it reads back as 0), so "unlimited when empty" never
|
||||||
|
// worked — every product without stock was sold out. Existing products
|
||||||
|
// get trackStock = true: nothing that sells today changes; clearing the
|
||||||
|
// stock field in the admin makes a product unlimited.
|
||||||
|
// - Not required any more, as PocketBase counts 0 / '' as blank:
|
||||||
|
// order_lines.price (a booking paid with a code, or a product inside a
|
||||||
|
// bundle, costs 0), orders.total and orders.stripePaymentIntentId (an
|
||||||
|
// order fully paid with codes has no payment).
|
||||||
|
//
|
||||||
|
// Commerce writes stay superuser-only (the shop hooks); signed-in admins
|
||||||
|
// can read passes and change them through /api/shop/passes/*.
|
||||||
|
|
||||||
|
function find(app, name) {
|
||||||
|
try {
|
||||||
|
return app.findCollectionByNameOrId(name);
|
||||||
|
} catch (e) {
|
||||||
|
return null; // fresh install: pb_schema.json (already in this shape) is imported later
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const AUTH_ONLY = "@request.auth.id != ''";
|
||||||
|
|
||||||
|
migrate(
|
||||||
|
(app) => {
|
||||||
|
const items = find(app, 'items');
|
||||||
|
const orders = find(app, 'orders');
|
||||||
|
const baskets = find(app, 'baskets');
|
||||||
|
const basketLines = find(app, 'basket_lines');
|
||||||
|
const orderLines = find(app, 'order_lines');
|
||||||
|
if (!items || !orders || !baskets || !basketLines || !orderLines) return;
|
||||||
|
|
||||||
|
const type = items.fields.getByName('type');
|
||||||
|
if (type && type.values.indexOf('bundle') < 0) type.values = [...type.values, 'bundle'];
|
||||||
|
if (!items.fields.getByName('trackStock')) {
|
||||||
|
items.fields.add(new BoolField({ id: 'bool_itemtrackst', name: 'trackStock' }));
|
||||||
|
app.save(items);
|
||||||
|
for (const item of app.findRecordsByFilter('items', "type = 'item'", '', 0, 0)) {
|
||||||
|
item.set('trackStock', true);
|
||||||
|
try {
|
||||||
|
app.saveNoValidate(item);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`[migration] could not set trackStock on item ${item.id}: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!items.fields.getByName('bundleParts')) {
|
||||||
|
items.fields.add(new JSONField({ id: 'json_itembundle1', name: 'bundleParts', maxSize: 20000 }));
|
||||||
|
items.fields.add(new NumberField({ id: 'num_itemvalidmo1', name: 'validMonths', min: 1, max: 120, onlyInt: true }));
|
||||||
|
}
|
||||||
|
app.save(items);
|
||||||
|
|
||||||
|
let passes = find(app, 'passes');
|
||||||
|
if (!passes) {
|
||||||
|
passes = new Collection({
|
||||||
|
id: 'pbc_passes00001',
|
||||||
|
type: 'base',
|
||||||
|
name: 'passes',
|
||||||
|
listRule: AUTH_ONLY,
|
||||||
|
viewRule: AUTH_ONLY,
|
||||||
|
createRule: null,
|
||||||
|
updateRule: null,
|
||||||
|
deleteRule: null,
|
||||||
|
fields: [
|
||||||
|
{ id: 'text_passcode001', name: 'code', type: 'text', required: true, min: 6, max: 20, pattern: '^[A-Z0-9]+$' },
|
||||||
|
{ id: 'rel_passitem0001', name: 'item', type: 'relation', collectionId: items.id, maxSelect: 1, cascadeDelete: false },
|
||||||
|
{ id: 'rel_passorder001', name: 'order', type: 'relation', collectionId: orders.id, maxSelect: 1, cascadeDelete: false },
|
||||||
|
{ id: 'text_passname001', name: 'name', type: 'text', max: 180 },
|
||||||
|
{ id: 'json_passparts01', name: 'parts', type: 'json', maxSize: 20000 },
|
||||||
|
{ id: 'text_passemail01', name: 'email', type: 'text', max: 320 },
|
||||||
|
{ id: 'text_passrecip01', name: 'recipientName', type: 'text', max: 180 },
|
||||||
|
{ id: 'text_passmessag1', name: 'message', type: 'text', max: 1000 },
|
||||||
|
{ id: 'date_passexpire1', name: 'expiresAt', type: 'date' },
|
||||||
|
{ id: 'sel_passstatus01', name: 'status', type: 'select', required: true, maxSelect: 1, values: ['active', 'void'] },
|
||||||
|
{ id: 'date_passanonym1', name: 'anonymisedAt', type: 'date' },
|
||||||
|
{ id: 'autodate_created', name: 'created', type: 'autodate', onCreate: true, onUpdate: false },
|
||||||
|
{ id: 'autodate_updated', name: 'updated', type: 'autodate', onCreate: true, onUpdate: true }
|
||||||
|
],
|
||||||
|
indexes: ['CREATE UNIQUE INDEX `idx_passes_code` ON `passes` (`code`)', 'CREATE INDEX `idx_passes_order` ON `passes` (`order`)', 'CREATE INDEX `idx_passes_email` ON `passes` (`email`)']
|
||||||
|
});
|
||||||
|
app.save(passes);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!baskets.fields.getByName('pass')) {
|
||||||
|
baskets.fields.add(new RelationField({ id: 'rel_basketpass01', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false }));
|
||||||
|
app.save(baskets);
|
||||||
|
}
|
||||||
|
if (!basketLines.fields.getByName('pass')) {
|
||||||
|
basketLines.fields.add(new RelationField({ id: 'rel_blpass000001', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false }));
|
||||||
|
basketLines.fields.add(new TextField({ id: 'text_blgiftto001', name: 'giftTo', max: 180 }));
|
||||||
|
basketLines.fields.add(new TextField({ id: 'text_blgiftmsg01', name: 'giftMessage', max: 1000 }));
|
||||||
|
basketLines.indexes = [...basketLines.indexes, 'CREATE INDEX `idx_basket_lines_pass` ON `basket_lines` (`pass`)'];
|
||||||
|
app.save(basketLines);
|
||||||
|
}
|
||||||
|
for (const [collection, name] of [[orderLines, 'price'], [orders, 'total'], [orders, 'stripePaymentIntentId']]) {
|
||||||
|
const field = collection.fields.getByName(name);
|
||||||
|
if (field && field.required) {
|
||||||
|
field.required = false;
|
||||||
|
app.save(collection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!orderLines.fields.getByName('pass')) {
|
||||||
|
orderLines.fields.add(new RelationField({ id: 'rel_olpass000001', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false }));
|
||||||
|
orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_pass` ON `order_lines` (`pass`)'];
|
||||||
|
app.save(orderLines);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(app) => {
|
||||||
|
const orderLines = find(app, 'order_lines');
|
||||||
|
if (orderLines && orderLines.fields.getByName('pass')) {
|
||||||
|
orderLines.fields.removeByName('pass');
|
||||||
|
orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_pass'));
|
||||||
|
app.save(orderLines);
|
||||||
|
}
|
||||||
|
const basketLines = find(app, 'basket_lines');
|
||||||
|
if (basketLines && basketLines.fields.getByName('pass')) {
|
||||||
|
for (const name of ['pass', 'giftTo', 'giftMessage']) basketLines.fields.removeByName(name);
|
||||||
|
basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_pass'));
|
||||||
|
app.save(basketLines);
|
||||||
|
}
|
||||||
|
const baskets = find(app, 'baskets');
|
||||||
|
if (baskets && baskets.fields.getByName('pass')) {
|
||||||
|
baskets.fields.removeByName('pass');
|
||||||
|
app.save(baskets);
|
||||||
|
}
|
||||||
|
const passes = find(app, 'passes');
|
||||||
|
if (passes) app.delete(passes);
|
||||||
|
const items = find(app, 'items');
|
||||||
|
if (items) {
|
||||||
|
// Bundles can't exist without the type: make them inactive products.
|
||||||
|
for (const item of app.findRecordsByFilter('items', "type = 'bundle'", '', 0, 0)) {
|
||||||
|
item.set('type', 'item');
|
||||||
|
item.set('active', false);
|
||||||
|
app.saveNoValidate(item);
|
||||||
|
}
|
||||||
|
const type = items.fields.getByName('type');
|
||||||
|
if (type) type.values = type.values.filter((value) => value !== 'bundle');
|
||||||
|
for (const name of ['bundleParts', 'validMonths', 'trackStock']) {
|
||||||
|
if (items.fields.getByName(name)) items.fields.removeByName(name);
|
||||||
|
}
|
||||||
|
app.save(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue