Admin: bundles under Services & products, Vouchers & codes page
Bundles are edited with their parts (service at a length, or product, × count), price and validity. /passes lists codes with used/held/left and each part's share of the price; codes can be voided, reactivated, given a new expiry, or issued without a purchase. Orders show codes bought and bookings paid with a code; the customer page lists codes and erasure covers them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
parent
e824f16e31
commit
df840b7fd7
14 changed files with 543 additions and 27 deletions
|
|
@ -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
|
||||||
.collection('order_lines')
|
? await Promise.all([
|
||||||
.getFullList({ sort: 'start' })
|
locals.pb
|
||||||
.catch(() => [])
|
.collection('order_lines')
|
||||||
: [];
|
.getFullList({ sort: 'start', expand: 'pass' })
|
||||||
|
.catch(() => []),
|
||||||
|
locals.pb
|
||||||
|
.collection('passes')
|
||||||
|
.getFullList({ filter: "order != ''", sort: 'created', fields: 'order,code,name,recipientName' })
|
||||||
|
.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>
|
||||||
Loading…
Add table
Add a link
Reference in a new issue