Shop: show the bundle's separate price as a saving; hide unsellable bundles
Bundle cards show what the parts cost one by one, crossed out when it's more than the bundle price. Bundles with a part that isn't on sale are left out of the shop data, so their parts always have names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
parent
338aef9e01
commit
23c5b70a93
5 changed files with 32 additions and 5 deletions
|
|
@ -135,7 +135,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
|
|||
- **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules.
|
||||
- **Slot availability** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*.
|
||||
- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email`, `passes.email`/`recipientName`/`message` and (during checkout) `baskets` / `basket_lines.giftTo`/`giftMessage`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*.
|
||||
- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*.
|
||||
- **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. Bundle parts are JSON, not relations: the `onRecordDelete` hook on `items` (`deleteBlocker`) keeps parts that bundles or codes still need from being deleted, and a bundle with an inactive part isn't sold. 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).
|
||||
|
||||
### Styling
|
||||
|
|
|
|||
|
|
@ -181,6 +181,8 @@ A **bundle** (Services & products → type *Bundle / voucher*) has its own price
|
|||
- **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.
|
||||
- **Shown in the shop** with what the parts cost bought one by one, crossed out when that's more than the bundle price (`bundleListPrice` in `packages/shared/src/items.ts`).
|
||||
- **Parts that go away**: a service or product can't be deleted while a bundle contains it, or while a usable code still has sessions of it to book or held (an `onRecordDelete` hook, `deleteBlocker` — bundle parts are JSON, so the database wouldn't stop it). Making it inactive is allowed: a bundle with an inactive part (or a length the service no longer offers) is hidden from the shop and can't be bought or issued; the admin items list marks it *Not on sale* and says why. Codes keep their own snapshot of names and prices, but can't book an inactive service — the items list shows how many codes are still waiting for it.
|
||||
- **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.
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
import type { BasketLine, BookableTime, ShopBlockData, ItemRecord } from '$shared/types';
|
||||
import { getBasketContext } from '$shared/basket.svelte';
|
||||
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
|
||||
import { formatDuration, lowestPrice } from '$shared/items';
|
||||
import { bundleListPrice, formatDuration, lowestPrice } from '$shared/items';
|
||||
import { addDaysToKey, formatDateKey } from '$shared/slots';
|
||||
|
||||
let { data = {}, items = [] } = $props<{
|
||||
|
|
@ -342,8 +342,13 @@
|
|||
<span class="text-xs text-charcoal/60">{formatDuration(item.durations[0].minutes)} – {formatDuration(item.durations[item.durations.length - 1].minutes)}</span>
|
||||
</div>
|
||||
{:else}
|
||||
{@const listPrice = item.type === 'bundle' ? bundleListPrice(item.bundleParts, items) : null}
|
||||
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span class="text-lg font-semibold text-sage-dark">{formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)}</span>
|
||||
{#if listPrice != null && listPrice > item.price}
|
||||
<!-- What the parts cost one by one: the bundle is a saving. -->
|
||||
<s class="text-sm text-charcoal/50"><span class="sr-only">Bought separately: </span>{formatPrice(listPrice, currency)}</s>
|
||||
{/if}
|
||||
{#if duration}
|
||||
<span class="text-xs text-charcoal/60">{formatDuration(duration.minutes)}</span>
|
||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
// the Shop block and the checkout. Which duration costs what is decided
|
||||
// (and charged) by the shop hooks in PocketBase; this only reads and shows it.
|
||||
|
||||
import type { ItemDuration } from './types';
|
||||
import type { BundlePart, ItemDuration, ItemRecord } from './types';
|
||||
|
||||
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
|
||||
export function parseDurations(raw: unknown): ItemDuration[] {
|
||||
|
|
@ -32,3 +32,20 @@ export function lowestPrice(durations: ItemDuration[]) {
|
|||
export function formatCode(code: string) {
|
||||
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a bundle's parts cost bought one by one (each service at the part's
|
||||
* length), to show next to the bundle price — or null when a part isn't on
|
||||
* sale (not in `items`, or a length the service no longer has).
|
||||
*/
|
||||
export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) {
|
||||
let total = 0;
|
||||
for (const part of parts) {
|
||||
const item = items.find((candidate) => candidate.id === part.item);
|
||||
if (!item || item.type === 'bundle') return null;
|
||||
const unit = item.type === 'item_with_time' ? item.durations.find((d) => d.minutes === part.minutes)?.price : item.price;
|
||||
if (unit == null) return null;
|
||||
total += unit * part.count;
|
||||
}
|
||||
return Math.round(total * 100) / 100;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type PocketBase from 'pocketbase';
|
||||
import { getFileUrl } from '../pb';
|
||||
import { parseDurations } from '../items';
|
||||
import { bundleListPrice, parseDurations } from '../items';
|
||||
import type { BookableTime, BundlePart, ItemRecord, ItemType } from '../types';
|
||||
|
||||
/** A bundle's `bundleParts` field (JSON) → valid parts. */
|
||||
|
|
@ -42,7 +42,10 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
|||
*/
|
||||
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
|
||||
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
|
||||
return { items: records.map(mapItemRecord) };
|
||||
const items = records.map(mapItemRecord);
|
||||
// A bundle with a part that isn't on sale (inactive, deleted, or a length
|
||||
// the service dropped) can't be bought — the shop hook refuses it too.
|
||||
return { items: items.filter((item) => item.type !== 'bundle' || bundleListPrice(item.bundleParts, items) !== null) };
|
||||
}
|
||||
|
||||
export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string };
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue