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">
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import type { ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
||||
import { page } from '$app/state';
|
||||
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
||||
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<{
|
||||
data: ShopBlockData;
|
||||
|
|
@ -21,14 +22,16 @@
|
|||
errorMsg = $state<string | null>(null);
|
||||
justAdded = $state(false);
|
||||
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>>({});
|
||||
|
||||
const months = getCurrentAndNextMonths();
|
||||
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
|
||||
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
/** The picker shows this many months side by side; the arrows move one month. */
|
||||
const MONTHS_SHOWN = 2;
|
||||
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
||||
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||
|
||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||
let result: ItemRecord[] = items;
|
||||
|
|
@ -44,13 +47,23 @@
|
|||
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[]>>>(() => {
|
||||
const map = new Map<string, Map<string, SlotRecord[]>>();
|
||||
for (const slot of slots) {
|
||||
const day = new Date(slot.start);
|
||||
if (Number.isNaN(day.getTime())) continue;
|
||||
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
|
||||
for (const slot of shownSlots) {
|
||||
const key = zonedDateKey(slot.start, timezone);
|
||||
if (!key) continue;
|
||||
let itemMap = map.get(slot.item);
|
||||
if (!itemMap) {
|
||||
itemMap = new Map();
|
||||
|
|
@ -70,6 +83,18 @@
|
|||
|
||||
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.
|
||||
$effect(() => {
|
||||
for (const item of visibleItems) {
|
||||
|
|
@ -84,6 +109,15 @@
|
|||
state.errorMsg = null;
|
||||
state.justAdded = false;
|
||||
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) {
|
||||
|
|
@ -111,11 +145,10 @@
|
|||
state.pendingSlotId = slotId;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
// The store reloads the listing afterwards: a booking can block other
|
||||
// times (one practitioner) or fill a group session.
|
||||
await basket.addSlotLine(slotId);
|
||||
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) {
|
||||
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
|
||||
} 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) {
|
||||
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>
|
||||
|
||||
|
|
@ -178,7 +234,7 @@
|
|||
{/if}
|
||||
|
||||
<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}
|
||||
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||
|
|
@ -245,8 +301,53 @@
|
|||
</div>
|
||||
|
||||
{#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'}>
|
||||
<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">
|
||||
{#each months as month (month.label)}
|
||||
<div>
|
||||
|
|
@ -282,34 +383,64 @@
|
|||
|
||||
{#if 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">
|
||||
{#each daySlots as slot (slot.id)}
|
||||
{@const seatsInBasket = basket.lines.find((l) => l.slot === slot.id)?.quantity ?? 0}
|
||||
{@const slotInBasket = seatsInBasket > 0}
|
||||
{@const line = basket.lines.find((l) => l.slot === slot.id)}
|
||||
{@const isGroup = slot.capacity > 1}
|
||||
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
|
||||
{#if isGroup && line}
|
||||
<!-- Places in a group session already in the basket: − / + -->
|
||||
<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">
|
||||
<span>{label} · {placesLeft(slot.free)}</span>
|
||||
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={(slotInBasket && !isGroup) || ui.adding}
|
||||
title={isGroup && slotInBasket ? 'Add another place' : undefined}
|
||||
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 fewer"
|
||||
disabled={ui.adding}
|
||||
onclick={() => changeSeats(item.id, line, -1)}
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
|
||||
{#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if}
|
||||
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span>
|
||||
</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 {slotInBasket
|
||||
? `border-transparent bg-sage/15 text-sage-dark ${isGroup ? 'hover:bg-sage/30' : 'cursor-not-allowed'}`
|
||||
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 &&
|
||||
!slotInBasket
|
||||
!line
|
||||
? 'cursor-wait'
|
||||
: ''}"
|
||||
>
|
||||
{#if ui.pendingSlotId === slot.id}
|
||||
<span class="loading loading-spinner loading-xs"></span>
|
||||
{/if}
|
||||
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{isGroup
|
||||
? ` · ${slot.free} ${slot.free === 1 ? 'place' : 'places'} left`
|
||||
: ''}{slotInBasket ? (isGroup ? ` · ${seatsInBasket} in basket` : ' · In basket') : ''}
|
||||
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
{:else if anyShown}
|
||||
<p class="mt-4 text-sm text-charcoal/60">
|
||||
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
||||
</p>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue