Slots: bulk tools, get-ready time, group places, and bookings block overlapping slots #3
1 changed files with 172 additions and 41 deletions
|
|
@ -1,8 +1,9 @@
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { invalidateAll } from '$app/navigation';
|
import { page } from '$app/state';
|
||||||
import type { ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
||||||
import { getBasketContext } from '$shared/basket.svelte';
|
import { getBasketContext } from '$shared/basket.svelte';
|
||||||
import { getCurrentAndNextMonths } from '$shared/calendar';
|
import { DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey } from '$shared/calendar';
|
||||||
|
import { formatDateKey } from '$shared/slots';
|
||||||
|
|
||||||
let { data = {}, items = [], slots = [] } = $props<{
|
let { data = {}, items = [], slots = [] } = $props<{
|
||||||
data: ShopBlockData;
|
data: ShopBlockData;
|
||||||
|
|
@ -21,14 +22,16 @@
|
||||||
errorMsg = $state<string | null>(null);
|
errorMsg = $state<string | null>(null);
|
||||||
justAdded = $state(false);
|
justAdded = $state(false);
|
||||||
pendingSlotId = $state<string | null>(null);
|
pendingSlotId = $state<string | null>(null);
|
||||||
|
/** Months from the current one to the first month shown in the picker. */
|
||||||
|
monthOffset = $state(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
let cardStates = $state<Record<string, CardState>>({});
|
let cardStates = $state<Record<string, CardState>>({});
|
||||||
|
|
||||||
const months = getCurrentAndNextMonths();
|
/** The picker shows this many months side by side; the arrows move one month. */
|
||||||
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
const MONTHS_SHOWN = 2;
|
||||||
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
|
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
||||||
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||||
|
|
||||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||||
let result: ItemRecord[] = items;
|
let result: ItemRecord[] = items;
|
||||||
|
|
@ -44,13 +47,23 @@
|
||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
|
// The listing leaves out full slots — including ones whose last places are
|
||||||
|
// in this visitor's own basket. Add those back (no places left) so the
|
||||||
|
// visitor still sees their times and can change or drop their places.
|
||||||
|
let shownSlots = $derived.by<SlotRecord[]>(() => {
|
||||||
|
const listed = new Set(slots.map((s: SlotRecord) => s.id));
|
||||||
|
const own = basket.lines
|
||||||
|
.filter((l) => l.lineType === 'slot' && l.slot && !listed.has(l.slot) && l.slotStart && Date.parse(l.slotStart) > Date.now())
|
||||||
|
.map((l) => ({ id: l.slot!, item: l.item, start: l.slotStart!, end: l.slotEnd ?? l.slotStart!, capacity: l.slotCapacity ?? 1, free: 0 }));
|
||||||
|
return own.length ? [...slots, ...own] : slots;
|
||||||
|
});
|
||||||
|
|
||||||
|
// item id -> day key ('YYYY-MM-DD', in the studio's timezone) -> slots on that day, sorted by start time
|
||||||
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
|
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
|
||||||
const map = new Map<string, Map<string, SlotRecord[]>>();
|
const map = new Map<string, Map<string, SlotRecord[]>>();
|
||||||
for (const slot of slots) {
|
for (const slot of shownSlots) {
|
||||||
const day = new Date(slot.start);
|
const key = zonedDateKey(slot.start, timezone);
|
||||||
if (Number.isNaN(day.getTime())) continue;
|
if (!key) continue;
|
||||||
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
|
|
||||||
let itemMap = map.get(slot.item);
|
let itemMap = map.get(slot.item);
|
||||||
if (!itemMap) {
|
if (!itemMap) {
|
||||||
itemMap = new Map();
|
itemMap = new Map();
|
||||||
|
|
@ -70,6 +83,18 @@
|
||||||
|
|
||||||
let isList = $derived(data.layout === 'list');
|
let isList = $derived(data.layout === 'list');
|
||||||
|
|
||||||
|
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
|
||||||
|
function monthOffsetOf(key: string) {
|
||||||
|
const today = new Date();
|
||||||
|
const [year, month] = key.split('-').map(Number);
|
||||||
|
return year * 12 + (month - 1) - (today.getFullYear() * 12 + today.getMonth());
|
||||||
|
}
|
||||||
|
|
||||||
|
function pickerMonths(offset: number) {
|
||||||
|
const first = addMonths(startOfMonth(new Date()), offset);
|
||||||
|
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1));
|
||||||
|
}
|
||||||
|
|
||||||
// Lazily create card state for whatever items are rendered.
|
// Lazily create card state for whatever items are rendered.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
for (const item of visibleItems) {
|
for (const item of visibleItems) {
|
||||||
|
|
@ -84,6 +109,15 @@
|
||||||
state.errorMsg = null;
|
state.errorMsg = null;
|
||||||
state.justAdded = false;
|
state.justAdded = false;
|
||||||
state.selectedDayKey = null;
|
state.selectedDayKey = null;
|
||||||
|
state.monthOffset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Show the month of the first available day and select it. */
|
||||||
|
function showFirstAvailable(itemId: string, key: string) {
|
||||||
|
const state = cardStates[itemId];
|
||||||
|
if (!state) return;
|
||||||
|
state.monthOffset = Math.max(0, monthOffsetOf(key));
|
||||||
|
state.selectedDayKey = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
function errorMessage(e: unknown, fallback: string) {
|
function errorMessage(e: unknown, fallback: string) {
|
||||||
|
|
@ -111,11 +145,10 @@
|
||||||
state.pendingSlotId = slotId;
|
state.pendingSlotId = slotId;
|
||||||
state.errorMsg = null;
|
state.errorMsg = null;
|
||||||
try {
|
try {
|
||||||
|
// The store reloads the listing afterwards: a booking can block other
|
||||||
|
// times (one practitioner) or fill a group session.
|
||||||
await basket.addSlotLine(slotId);
|
await basket.addSlotLine(slotId);
|
||||||
state.justAdded = true;
|
state.justAdded = true;
|
||||||
// A booking can block other times (one practitioner) or fill a
|
|
||||||
// group session — reload the listing so the picker shows that.
|
|
||||||
await invalidateAll();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
|
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -124,8 +157,31 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One place more or fewer in a group session already in the basket (0 removes it). */
|
||||||
|
async function changeSeats(itemId: string, line: BasketLine, delta: number) {
|
||||||
|
const state = cardStates[itemId];
|
||||||
|
if (!state || state.adding) return;
|
||||||
|
state.adding = true;
|
||||||
|
state.pendingSlotId = line.slot;
|
||||||
|
state.errorMsg = null;
|
||||||
|
try {
|
||||||
|
const seats = line.quantity + delta;
|
||||||
|
if (seats < 1) await basket.removeLine(line.id);
|
||||||
|
else await basket.updateQuantity(line.id, seats);
|
||||||
|
} catch (e) {
|
||||||
|
state.errorMsg = errorMessage(e, 'Could not change the number of places.');
|
||||||
|
} finally {
|
||||||
|
state.adding = false;
|
||||||
|
state.pendingSlotId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function formatTime(iso: string) {
|
function formatTime(iso: string) {
|
||||||
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
|
return formatInstant(iso, timezone, { hour: '2-digit', minute: '2-digit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function placesLeft(free: number) {
|
||||||
|
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left';
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
@ -178,7 +234,7 @@
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
|
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
|
||||||
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
|
<span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price)}</span>
|
||||||
{#if isService && item.duration != null}
|
{#if isService && item.duration != null}
|
||||||
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
||||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||||
|
|
@ -245,8 +301,53 @@
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if isService && ui?.pickerOpen && itemSlotsByDay}
|
{#if isService && ui?.pickerOpen && itemSlotsByDay}
|
||||||
|
{@const availableKeys = [...itemSlotsByDay.keys()].sort()}
|
||||||
|
{@const months = pickerMonths(ui.monthOffset)}
|
||||||
|
{@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey}
|
||||||
|
{@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey}
|
||||||
|
{@const anyShown = availableKeys.some((key) => key >= shownFrom && key <= shownTo)}
|
||||||
|
{@const lastOffset = monthOffsetOf(availableKeys[availableKeys.length - 1]) - (MONTHS_SHOWN - 1)}
|
||||||
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
|
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
|
||||||
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
|
<div class="mb-3 flex items-center justify-between gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
|
||||||
|
aria-label="Previous month"
|
||||||
|
disabled={ui.monthOffset <= 0}
|
||||||
|
onclick={() => ui.monthOffset--}
|
||||||
|
>
|
||||||
|
‹
|
||||||
|
</button>
|
||||||
|
<p class="text-sm font-medium text-charcoal/70">Select a date</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
|
||||||
|
aria-label="Next month"
|
||||||
|
disabled={ui.monthOffset >= lastOffset}
|
||||||
|
onclick={() => ui.monthOffset++}
|
||||||
|
>
|
||||||
|
›
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if !anyShown && availableKeys.length}
|
||||||
|
<!-- Nothing in the months on screen: say when the next date is, so
|
||||||
|
nobody books January thinking it is this month. -->
|
||||||
|
<div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal">
|
||||||
|
<span>
|
||||||
|
{availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'}
|
||||||
|
<strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>.
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark"
|
||||||
|
onclick={() => showFirstAvailable(item.id, availableKeys.find((key) => key > shownTo) ?? availableKeys[0])}
|
||||||
|
>
|
||||||
|
Go to {availableKeys[0] > shownTo ? 'first' : 'next'} available date →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<div class="grid gap-6 sm:grid-cols-2">
|
<div class="grid gap-6 sm:grid-cols-2">
|
||||||
{#each months as month (month.label)}
|
{#each months as month (month.label)}
|
||||||
<div>
|
<div>
|
||||||
|
|
@ -282,34 +383,64 @@
|
||||||
|
|
||||||
{#if ui.selectedDayKey}
|
{#if ui.selectedDayKey}
|
||||||
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
|
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
|
||||||
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
|
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">
|
||||||
|
Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
|
||||||
|
</p>
|
||||||
<div class="flex flex-wrap gap-2">
|
<div class="flex flex-wrap gap-2">
|
||||||
{#each daySlots as slot (slot.id)}
|
{#each daySlots as slot (slot.id)}
|
||||||
{@const seatsInBasket = basket.lines.find((l) => l.slot === slot.id)?.quantity ?? 0}
|
{@const line = basket.lines.find((l) => l.slot === slot.id)}
|
||||||
{@const slotInBasket = seatsInBasket > 0}
|
|
||||||
{@const isGroup = slot.capacity > 1}
|
{@const isGroup = slot.capacity > 1}
|
||||||
<button
|
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
|
||||||
type="button"
|
{#if isGroup && line}
|
||||||
disabled={(slotInBasket && !isGroup) || ui.adding}
|
<!-- Places in a group session already in the basket: − / + -->
|
||||||
title={isGroup && slotInBasket ? 'Add another place' : undefined}
|
<div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark">
|
||||||
onclick={() => addSlot(item.id, slot.id)}
|
<span>{label} · {placesLeft(slot.free)}</span>
|
||||||
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
|
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
|
||||||
? `border-transparent bg-sage/15 text-sage-dark ${isGroup ? 'hover:bg-sage/30' : 'cursor-not-allowed'}`
|
<button
|
||||||
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
|
type="button"
|
||||||
!slotInBasket
|
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
|
||||||
? 'cursor-wait'
|
aria-label="One place fewer"
|
||||||
: ''}"
|
disabled={ui.adding}
|
||||||
>
|
onclick={() => changeSeats(item.id, line, -1)}
|
||||||
{#if ui.pendingSlotId === slot.id}
|
>
|
||||||
<span class="loading loading-spinner loading-xs"></span>
|
−
|
||||||
{/if}
|
</button>
|
||||||
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{isGroup
|
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
|
||||||
? ` · ${slot.free} ${slot.free === 1 ? 'place' : 'places'} left`
|
{#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if}
|
||||||
: ''}{slotInBasket ? (isGroup ? ` · ${seatsInBasket} in basket` : ' · In basket') : ''}
|
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span>
|
||||||
</button>
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
|
||||||
|
aria-label="One place more"
|
||||||
|
disabled={ui.adding || slot.free <= 0}
|
||||||
|
onclick={() => changeSeats(item.id, line, 1)}
|
||||||
|
>
|
||||||
|
+
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!!line || ui.adding}
|
||||||
|
onclick={() => addSlot(item.id, slot.id)}
|
||||||
|
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {line
|
||||||
|
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
|
||||||
|
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
|
||||||
|
!line
|
||||||
|
? 'cursor-wait'
|
||||||
|
: ''}"
|
||||||
|
>
|
||||||
|
{#if ui.pendingSlotId === slot.id}
|
||||||
|
<span class="loading loading-spinner loading-xs"></span>
|
||||||
|
{/if}
|
||||||
|
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else if anyShown}
|
||||||
<p class="mt-4 text-sm text-charcoal/60">
|
<p class="mt-4 text-sm text-charcoal/60">
|
||||||
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
||||||
</p>
|
</p>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue