diff --git a/AGENTS.md b/AGENTS.md index e14c23f..779bfcb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,5 +201,5 @@ cd app-public && npm run build - `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency. - Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. - `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials. -- Shop order: `items.priority` (higher first) is *Recommended*. It's set by dragging the `/items` list (`?/reorder` renumbers n…1), not typed in the item form; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`. +- Shop order: `items.priority` (higher first) is *Recommended*; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`. - Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`). The Shop block fetches bookable times itself, per service and length, from `GET /api/slots` in each app (a proxy to `GET /api/shop/slots`); if it has nothing to show it says "Nothing is available". diff --git a/README.md b/README.md index 3500777..c11774f 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ If schema import fails because of a PocketBase version mismatch, create these co Commerce collections (see the Stripe section above for context): -- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name; set by dragging the `/items` list, never typed), `active` bool +- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name), `active` bool - `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text, `pass` relation→passes (the code applied at checkout) - `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold), `pass` relation→passes (the code paying for this booking), `giftTo` / `giftMessage` text (who a bundle is for) @@ -159,7 +159,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - `/pages` — list/create pages - `/pages/[slug]` — block editor with draft preview. Text is edited visually (headings, bold, italic, strikethrough, links, lists, pull quotes, lines; alignment and a small *footnote* size per block). Layouts have their own blocks: **Cards** (pictures or numbered steps, optionally linked — e.g. *Who I work with*, *Read next*, *How it works*) and **FAQ** (questions that open to show the answer). An **HTML** block takes raw HTML for embeds and one-offs (inline styles only; anything it loads from another site shares visitors' IPs). Every block has an *Anchor*, so a button or link to `#prices` jumps to it. - `/calendar` — events shown by Upcoming Calendar blocks -- `/items` — services, products and bundles shown in Shop blocks, listed in shop order. Drag a row by its ⠿ handle (or focus the handle and press ↑/↓), then *Save order*: the `?/reorder` action stores it as `items.priority` (n…1, first = highest), writing only what changed. New items go to the end +- `/items` — services, products and bundles shown in Shop blocks, listed in shop order (highest *Priority in the shop* first, then by name) - Shop block order: *Recommended* (by priority), *Most popular*, *Price: low to high / high to low*, *Name (A–Z)*, chosen per block (`sort`); *Let visitors sort* (`showSort`) adds a "Sort by" menu that starts at that order. *Most popular* = units in paid orders over the last 90 days, from `GET /api/shop/popular` (public; item ids best-selling first, never the numbers; refunded orders and products handed over inside a bundle don't count, bookings paid with a code do). Items without recent sales follow in Recommended order, and the menu leaves the choice out until something has sold. Chosen items (`itemIds`) follow the block's order too, not the order they were picked in. - `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). No two slots may overlap (windows and group sessions alike); bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it. - `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them. diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index 3dc2dfc..8b01870 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -28,7 +28,7 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } { return durations.sort((a, b) => a.minutes - b.minutes); } -/** Priorities go from -this to this (the field's limits in pb_schema.json). Set by dragging the list (?/reorder), never typed. */ +/** Priorities go from -this to this (the field's limits in pb_schema.json). */ const MAX_PRIORITY = 1000; /** Most units of one thing a bundle can hold. */ @@ -69,6 +69,9 @@ function itemPayload(data: FormData, items: Record[]) { const rawStock = String(data.get('stock') ?? '').trim(); const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); const rawCapacity = String(data.get('capacity') ?? '').trim(); + const rawPriority = String(data.get('priority') ?? '').trim(); + const priority = rawPriority === '' ? 0 : Number(rawPriority); + if (!Number.isInteger(priority) || Math.abs(priority) > MAX_PRIORITY) return { error: `Priority: a whole number from -${MAX_PRIORITY} to ${MAX_PRIORITY} (0 = normal).` }; let price: number; let durations: ItemDuration[] = []; @@ -113,6 +116,7 @@ function itemPayload(data: FormData, items: Record[]) { validMonths, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, capacity: Number.isNaN(capacity) ? null : capacity, + priority, active: String(data.get('active')) === 'true' } }; @@ -120,7 +124,7 @@ function itemPayload(data: FormData, items: Record[]) { /** Every item, for checking what a bundle may contain. */ function allItems(pb: App.Locals['pb']) { - return pb.collection('items').getFullList({ fields: 'id,name,type,durations,priority' }).catch(() => []); + return pb.collection('items').getFullList({ fields: 'id,name,type,durations' }).catch(() => []); } export const load: PageServerLoad = async ({ locals }) => { @@ -136,13 +140,9 @@ export const load: PageServerLoad = async ({ locals }) => { export const actions: Actions = { create: async ({ request, locals }) => { - const items = await allItems(locals.pb); - const result = itemPayload(await request.formData(), items); + const result = itemPayload(await request.formData(), await allItems(locals.pb)); if ('error' in result) return fail(400, { message: result.error }); - // New items go to the end of the shop order; drag them up from there. - const lowest = items.length ? Math.min(...items.map((item) => Number(item.priority) || 0)) : 1; - const priority = Math.max(-MAX_PRIORITY, lowest - 1); - const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create({ ...result.payload, priority })); + const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload)); if (!created.ok) return created.failure; return { ok: true }; }, @@ -156,33 +156,6 @@ export const actions: Actions = { if (!updated.ok) return updated.failure; return { ok: true }; }, - /** - * The list's new order (`order`: JSON item ids, first = shown first) → - * priorities n…1. Only items whose priority changes are written; items - * missing from the list (added meanwhile) go after it. - */ - reorder: async ({ request, locals }) => { - let ids: unknown; - try { - ids = JSON.parse(String((await request.formData()).get('order') || '[]')); - } catch { - ids = null; - } - if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string')) return fail(400, { message: 'Could not read the new order — reload the page and try again.' }); - const records = await locals.pb.collection('items').getFullList({ fields: 'id,priority', sort: '-priority,name' }); - const known = new Set(records.map((record) => record.id)); - const listed = [...new Set(ids as string[])].filter((id) => known.has(id)); - const ordered = [...listed, ...records.map((record) => record.id).filter((id) => !listed.includes(id))]; - if (ordered.length > MAX_PRIORITY) return fail(400, { message: `The order can only be set for up to ${MAX_PRIORITY} items.` }); - const current = new Map(records.map((record) => [record.id, Number(record.priority) || 0])); - for (const [index, id] of ordered.entries()) { - const priority = ordered.length - index; - if (current.get(id) === priority) continue; - const saved = await attempt('Could not save the order.', () => locals.pb.collection('items').update(id, { priority })); - if (!saved.ok) return saved.failure; - } - return { ok: true, message: 'Order saved.' }; - }, delete: async ({ request, locals }) => { const data = await request.formData(); const id = String(data.get('id') || ''); diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index 4c22739..b0b65e4 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -1,10 +1,7 @@