fix(edge-fn): replace getClaims with adminClient.auth.getUser(token)
fix(edge-fn): use user.id instead of claims.sub; fixes 500s and false cert_required fix(migrations): drop broad reservations SELECT policy; add reservation_slots view with security_invoker=false fix(tests): correct weekSlot() keys from start/end to start_time/end_time fix(tests): spread overlap test slots across separate ISO weeks fix(tests): update e2e assertion to match actual authenticated home text fix(app): hide IonMenu before user is authenticated feat(dx): add test:all script running unit, integration, and e2e in sequence docs(claude-md): document SELinux fix, Edge Function auth pattern, security_invoker behaviour
This commit is contained in:
4
.envrc
Normal file
4
.envrc
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export SUPABASE_URL=$(npx supabase status 2>/dev/null | grep -oP '(?<=Project URL │ )\S+')
|
||||||
|
export SUPABASE_SERVICE_ROLE_KEY=$(npx supabase status 2>/dev/null | grep -oP '(?<=Secret │ )\S+')
|
||||||
|
export SUPABASE_KEY=$(npx supabase status 2>/dev/null | grep -oP '(?<=Publishable │ )\S+')
|
||||||
|
|
||||||
3
.vscode/extensions.json
vendored
Normal file
3
.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"recommendations": ["denoland.vscode-deno"]
|
||||||
|
}
|
||||||
24
.vscode/settings.json
vendored
Normal file
24
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"deno.enablePaths": [
|
||||||
|
"supabase/functions"
|
||||||
|
],
|
||||||
|
"deno.lint": true,
|
||||||
|
"deno.unstable": [
|
||||||
|
"bare-node-builtins",
|
||||||
|
"byonm",
|
||||||
|
"sloppy-imports",
|
||||||
|
"unsafe-proto",
|
||||||
|
"webgpu",
|
||||||
|
"broadcast-channel",
|
||||||
|
"worker-options",
|
||||||
|
"cron",
|
||||||
|
"kv",
|
||||||
|
"ffi",
|
||||||
|
"fs",
|
||||||
|
"http",
|
||||||
|
"net"
|
||||||
|
],
|
||||||
|
"[typescript]": {
|
||||||
|
"editor.defaultFormatter": "denoland.vscode-deno"
|
||||||
|
}
|
||||||
|
}
|
||||||
10
CLAUDE.md
10
CLAUDE.md
@@ -41,6 +41,16 @@ You work with Patrick, a Solutions Architect, on the OYS Borrow a Boat app (oysq
|
|||||||
- Types in `types/supabase.ts` — regenerate with: `npx supabase gen types typescript --project-id YOUR_ID > types/supabase.ts`
|
- Types in `types/supabase.ts` — regenerate with: `npx supabase gen types typescript --project-id YOUR_ID > types/supabase.ts`
|
||||||
- `useSupabaseClient<Database>()` typed against `types/supabase.ts`
|
- `useSupabaseClient<Database>()` typed against `types/supabase.ts`
|
||||||
|
|
||||||
|
### Edge Functions
|
||||||
|
- Located in `supabase/functions/<name>/` — each function has its own `deno.json`
|
||||||
|
- Auth pattern: extract Bearer token → `adminClient.auth.getUser(token)` (pass JWT directly to service-role client). Do NOT create a separate userClient with the anon key.
|
||||||
|
- Use `SUPABASE_SERVICE_ROLE_KEY` (adminClient) for all DB operations inside functions; the caller's identity comes from JWT claims (`claims.sub` = user ID).
|
||||||
|
- **SELinux (Fedora/RHEL local dev)**: Before running `supabase functions serve`, label the project directory for container access:
|
||||||
|
```
|
||||||
|
sudo chcon -Rt container_file_t $(pwd)
|
||||||
|
```
|
||||||
|
This must be applied after any `git clone` or directory move. Failure symptom: function bootstrap error with no useful stderr output.
|
||||||
|
|
||||||
### Icons
|
### Icons
|
||||||
- Ionicons only (`ionicons/icons`) — no PrimeIcons
|
- Ionicons only (`ionicons/icons`) — no PrimeIcons
|
||||||
- Always import individual icon names from `ionicons/icons` (tree-shakeable)
|
- Always import individual icon names from `ionicons/icons` (tree-shakeable)
|
||||||
|
|||||||
19
app/app.vue
19
app/app.vue
@@ -1,6 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<IonApp>
|
<IonApp>
|
||||||
<IonMenu content-id="main-content" menu-id="main-menu">
|
<IonSplitPane content-id="main-content">
|
||||||
|
<IonMenu v-if="authStore.user" content-id="main-content" menu-id="main-menu">
|
||||||
<IonHeader>
|
<IonHeader>
|
||||||
<IonToolbar color="primary">
|
<IonToolbar color="primary">
|
||||||
<IonTitle>OYS Borrow a Boat</IonTitle>
|
<IonTitle>OYS Borrow a Boat</IonTitle>
|
||||||
@@ -35,9 +36,13 @@
|
|||||||
<IonItemDivider>
|
<IonItemDivider>
|
||||||
<IonLabel>Management</IonLabel>
|
<IonLabel>Management</IonLabel>
|
||||||
</IonItemDivider>
|
</IonItemDivider>
|
||||||
<IonItem button router-link="/schedule/manage" router-direction="root" @click="closeMenu">
|
<IonItem button router-link="/admin/intervals" router-direction="root" @click="closeMenu">
|
||||||
<IonIcon slot="start" :icon="calendarNumberOutline" />
|
<IonIcon slot="start" :icon="calendarNumberOutline" />
|
||||||
<IonLabel>Manage Schedule</IonLabel>
|
<IonLabel>Manage Slots</IonLabel>
|
||||||
|
</IonItem>
|
||||||
|
<IonItem button router-link="/admin/templates" router-direction="root" @click="closeMenu">
|
||||||
|
<IonIcon slot="start" :icon="layersOutline" />
|
||||||
|
<IonLabel>Templates</IonLabel>
|
||||||
</IonItem>
|
</IonItem>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -51,6 +56,10 @@
|
|||||||
<IonIcon slot="start" :icon="constructOutline" />
|
<IonIcon slot="start" :icon="constructOutline" />
|
||||||
<IonLabel>Manage Boats</IonLabel>
|
<IonLabel>Manage Boats</IonLabel>
|
||||||
</IonItem>
|
</IonItem>
|
||||||
|
<IonItem button router-link="/admin/config" router-direction="root" @click="closeMenu">
|
||||||
|
<IonIcon slot="start" :icon="settingsOutline" />
|
||||||
|
<IonLabel>Booking Rules</IonLabel>
|
||||||
|
</IonItem>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Sign out -->
|
<!-- Sign out -->
|
||||||
@@ -65,18 +74,20 @@
|
|||||||
</IonMenu>
|
</IonMenu>
|
||||||
|
|
||||||
<IonRouterOutlet id="main-content" />
|
<IonRouterOutlet id="main-content" />
|
||||||
|
</IonSplitPane>
|
||||||
</IonApp>
|
</IonApp>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import {
|
||||||
IonApp, IonMenu, IonHeader, IonToolbar, IonTitle,
|
IonApp, IonSplitPane, IonMenu, IonHeader, IonToolbar, IonTitle,
|
||||||
IonContent, IonList, IonItem, IonItemDivider, IonIcon, IonLabel, IonNote,
|
IonContent, IonList, IonItem, IonItemDivider, IonIcon, IonLabel, IonNote,
|
||||||
IonRouterOutlet, menuController,
|
IonRouterOutlet, menuController,
|
||||||
} from '@ionic/vue'
|
} from '@ionic/vue'
|
||||||
import {
|
import {
|
||||||
homeOutline, calendarOutline, boatOutline, personOutline,
|
homeOutline, calendarOutline, boatOutline, personOutline,
|
||||||
bookOutline, calendarNumberOutline, peopleOutline, constructOutline, logOutOutline,
|
bookOutline, calendarNumberOutline, peopleOutline, constructOutline, logOutOutline,
|
||||||
|
layersOutline, settingsOutline,
|
||||||
} from 'ionicons/icons'
|
} from 'ionicons/icons'
|
||||||
import { useAuthStore } from '~/stores/auth'
|
import { useAuthStore } from '~/stores/auth'
|
||||||
|
|
||||||
|
|||||||
278
app/pages/admin/config.vue
Normal file
278
app/pages/admin/config.vue
Normal file
@@ -0,0 +1,278 @@
|
|||||||
|
<template>
|
||||||
|
<IonPage>
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar color="primary">
|
||||||
|
<IonButtons slot="start">
|
||||||
|
<IonMenuButton />
|
||||||
|
</IonButtons>
|
||||||
|
<IonTitle>Booking Rules</IonTitle>
|
||||||
|
<IonButtons slot="end">
|
||||||
|
<IonButton :disabled="!dirty || saving" @click="saveAll">
|
||||||
|
<IonSpinner v-if="saving" name="crescent" slot="icon-only" />
|
||||||
|
<IonIcon v-else slot="icon-only" :icon="saveOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</IonButtons>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<div v-if="loading" class="ion-text-center ion-padding">
|
||||||
|
<IonSpinner name="crescent" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<IonCard>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>Weekly Limits</IonCardTitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel>
|
||||||
|
<h3>Max sessions per week</h3>
|
||||||
|
<p>Pre-booked sessions allowed per member per ISO week (Mon–Sun)</p>
|
||||||
|
</IonLabel>
|
||||||
|
<IonInput
|
||||||
|
slot="end"
|
||||||
|
type="number"
|
||||||
|
:value="local.max_sessions_per_week"
|
||||||
|
class="config-input"
|
||||||
|
:min="1"
|
||||||
|
:max="14"
|
||||||
|
@ion-input="set('max_sessions_per_week', $event.detail.value)"
|
||||||
|
/>
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
|
||||||
|
<IonCard>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>Weekend / Holiday Limits</IonCardTitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel>
|
||||||
|
<h3>Max weekend sessions per period</h3>
|
||||||
|
<p>Max Sat/Sun/holiday pre-bookings per alternating period</p>
|
||||||
|
</IonLabel>
|
||||||
|
<IonInput
|
||||||
|
slot="end"
|
||||||
|
type="number"
|
||||||
|
:value="local.max_weekend_sessions_per_period"
|
||||||
|
class="config-input"
|
||||||
|
:min="1"
|
||||||
|
:max="10"
|
||||||
|
@ion-input="set('max_weekend_sessions_per_period', $event.detail.value)"
|
||||||
|
/>
|
||||||
|
</IonItem>
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel>
|
||||||
|
<h3>Weekend period length (weeks)</h3>
|
||||||
|
<p>Number of weeks in each alternating period (default: 2 = every other weekend)</p>
|
||||||
|
</IonLabel>
|
||||||
|
<IonInput
|
||||||
|
slot="end"
|
||||||
|
type="number"
|
||||||
|
:value="local.weekend_period_weeks"
|
||||||
|
class="config-input"
|
||||||
|
:min="1"
|
||||||
|
:max="8"
|
||||||
|
@ion-input="set('weekend_period_weeks', $event.detail.value)"
|
||||||
|
/>
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
|
||||||
|
<IonCard>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>Open Session Window</IonCardTitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel>
|
||||||
|
<h3>Advance hours for open sessions</h3>
|
||||||
|
<p>Pre-booking limits are waived for sessions starting within this many hours</p>
|
||||||
|
</IonLabel>
|
||||||
|
<IonInput
|
||||||
|
slot="end"
|
||||||
|
type="number"
|
||||||
|
:value="local.open_session_advance_hours"
|
||||||
|
class="config-input"
|
||||||
|
:min="1"
|
||||||
|
:max="72"
|
||||||
|
@ion-input="set('open_session_advance_hours', $event.detail.value)"
|
||||||
|
/>
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
|
||||||
|
<IonCard>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>Holidays</IonCardTitle>
|
||||||
|
<IonCardSubtitle>Counted as weekend days for booking limits</IonCardSubtitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem v-for="h in holidays" :key="h.date">
|
||||||
|
<IonLabel>
|
||||||
|
<h3>{{ h.name }}</h3>
|
||||||
|
<p>{{ h.date }}</p>
|
||||||
|
</IonLabel>
|
||||||
|
<IonButton slot="end" fill="clear" color="danger" @click="deleteHoliday(h.date)">
|
||||||
|
<IonIcon slot="icon-only" :icon="trashOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
<div class="add-holiday-row">
|
||||||
|
<IonInput v-model="newHoliday.date" type="date" placeholder="Date" class="holiday-date-input" />
|
||||||
|
<IonInput v-model="newHoliday.name" placeholder="Name (e.g. Canada Day)" class="holiday-name-input" />
|
||||||
|
<IonButton @click="addHoliday" :disabled="!newHoliday.date || !newHoliday.name">
|
||||||
|
<IonIcon slot="icon-only" :icon="addOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</div>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<IonToast
|
||||||
|
v-model:is-open="toast.show"
|
||||||
|
:message="toast.message"
|
||||||
|
:color="toast.color"
|
||||||
|
:duration="2500"
|
||||||
|
position="bottom"
|
||||||
|
/>
|
||||||
|
</IonContent>
|
||||||
|
</IonPage>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import {
|
||||||
|
IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButtons,
|
||||||
|
IonMenuButton, IonButton, IonIcon, IonCard, IonCardHeader, IonCardTitle,
|
||||||
|
IonCardSubtitle, IonCardContent, IonList, IonItem, IonLabel, IonInput,
|
||||||
|
IonSpinner, IonToast,
|
||||||
|
} from '@ionic/vue'
|
||||||
|
import { saveOutline, trashOutline, addOutline } from 'ionicons/icons'
|
||||||
|
import type { Database } from '~/types/supabase'
|
||||||
|
|
||||||
|
type ConfigKey = 'max_sessions_per_week' | 'max_weekend_sessions_per_period' | 'weekend_period_weeks' | 'open_session_advance_hours'
|
||||||
|
type Holiday = { date: string; name: string }
|
||||||
|
|
||||||
|
definePageMeta({ layout: false, middleware: ['auth'] })
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const supabase = useSupabaseClient() as any
|
||||||
|
|
||||||
|
const loading = ref(true)
|
||||||
|
const saving = ref(false)
|
||||||
|
const dirty = ref(false)
|
||||||
|
const toast = reactive({ show: false, message: '', color: 'success' })
|
||||||
|
const holidays = ref<Holiday[]>([])
|
||||||
|
const newHoliday = reactive({ date: '', name: '' })
|
||||||
|
|
||||||
|
const local = reactive<Record<ConfigKey, number>>({
|
||||||
|
max_sessions_per_week: 2,
|
||||||
|
max_weekend_sessions_per_period: 1,
|
||||||
|
weekend_period_weeks: 2,
|
||||||
|
open_session_advance_hours: 24,
|
||||||
|
})
|
||||||
|
|
||||||
|
const original = reactive<Record<ConfigKey, number>>({ ...local })
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([fetchConfig(), fetchHolidays()])
|
||||||
|
loading.value = false
|
||||||
|
})
|
||||||
|
|
||||||
|
async function fetchConfig() {
|
||||||
|
const { data } = await supabase
|
||||||
|
.from('booking_config')
|
||||||
|
.select('key, value')
|
||||||
|
|
||||||
|
for (const row of (data ?? []) as { key: string; value: unknown }[]) {
|
||||||
|
const k = row.key as ConfigKey
|
||||||
|
if (k in local) {
|
||||||
|
local[k] = Number(row.value)
|
||||||
|
original[k] = Number(row.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchHolidays() {
|
||||||
|
const { data } = await supabase
|
||||||
|
.from('holidays')
|
||||||
|
.select('date, name')
|
||||||
|
.order('date', { ascending: true })
|
||||||
|
holidays.value = (data ?? []) as Holiday[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function set(key: ConfigKey, value: string | number | null | undefined) {
|
||||||
|
const n = Number(value)
|
||||||
|
if (!isNaN(n) && n > 0) {
|
||||||
|
local[key] = n
|
||||||
|
dirty.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveAll() {
|
||||||
|
saving.value = true
|
||||||
|
const upserts = (Object.keys(local) as ConfigKey[]).map(k => ({ key: k, value: local[k] }))
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('booking_config')
|
||||||
|
.upsert(upserts, { onConflict: 'key' })
|
||||||
|
|
||||||
|
saving.value = false
|
||||||
|
if (error) { showToast('Save failed: ' + error.message, 'danger'); return }
|
||||||
|
Object.assign(original, local)
|
||||||
|
dirty.value = false
|
||||||
|
showToast('Booking rules saved', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addHoliday() {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('holidays')
|
||||||
|
.insert({ date: newHoliday.date, name: newHoliday.name })
|
||||||
|
if (error) { showToast('Failed: ' + error.message, 'danger'); return }
|
||||||
|
newHoliday.date = ''
|
||||||
|
newHoliday.name = ''
|
||||||
|
await fetchHolidays()
|
||||||
|
showToast('Holiday added', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteHoliday(date: string) {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('holidays')
|
||||||
|
.delete()
|
||||||
|
.eq('date', date)
|
||||||
|
if (error) { showToast('Failed: ' + error.message, 'danger'); return }
|
||||||
|
await fetchHolidays()
|
||||||
|
showToast('Holiday removed', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToast(message: string, color: string) {
|
||||||
|
toast.message = message
|
||||||
|
toast.color = color
|
||||||
|
toast.show = true
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.config-input {
|
||||||
|
text-align: right;
|
||||||
|
max-width: 80px;
|
||||||
|
}
|
||||||
|
.add-holiday-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
.holiday-date-input { flex: 0 0 160px; }
|
||||||
|
.holiday-name-input { flex: 1; }
|
||||||
|
</style>
|
||||||
351
app/pages/admin/intervals.vue
Normal file
351
app/pages/admin/intervals.vue
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
<template>
|
||||||
|
<IonPage>
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar color="primary">
|
||||||
|
<IonButtons slot="start">
|
||||||
|
<IonMenuButton />
|
||||||
|
</IonButtons>
|
||||||
|
<IonTitle>Manage Slots</IonTitle>
|
||||||
|
<IonButtons slot="end">
|
||||||
|
<IonButton @click="showAddSlot = true">
|
||||||
|
<IonIcon slot="icon-only" :icon="addOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</IonButtons>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<!-- Date selector -->
|
||||||
|
<h3 class="section-title">Date</h3>
|
||||||
|
<div class="date-strip">
|
||||||
|
<button
|
||||||
|
v-for="d in dateOptions"
|
||||||
|
:key="d.iso"
|
||||||
|
class="date-chip"
|
||||||
|
:class="{ active: selectedDate === d.iso }"
|
||||||
|
@click="selectedDate = d.iso"
|
||||||
|
>
|
||||||
|
<span class="day-name">{{ d.dayName }}</span>
|
||||||
|
<span class="day-num">{{ d.dayNum }}</span>
|
||||||
|
<span class="month">{{ d.month }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="loading" class="ion-text-center ion-padding">
|
||||||
|
<IonSpinner name="crescent" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<IonCard v-for="boat in boats" :key="boat.id" class="boat-card">
|
||||||
|
<IonCardHeader>
|
||||||
|
<div class="boat-header">
|
||||||
|
<div>
|
||||||
|
<IonCardTitle>{{ boat.display_name || boat.name }}</IonCardTitle>
|
||||||
|
<IonCardSubtitle v-if="boat.class">{{ boat.class }}</IonCardSubtitle>
|
||||||
|
</div>
|
||||||
|
<IonToggle
|
||||||
|
:checked="boat.booking_available"
|
||||||
|
:enable-on-off-labels="true"
|
||||||
|
color="success"
|
||||||
|
@ion-change="toggleBoatAvailability(boat, $event.detail.checked)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<p v-if="!boat.booking_available" class="out-of-service">
|
||||||
|
<IonIcon :icon="constructOutline" /> Out of service
|
||||||
|
</p>
|
||||||
|
<div class="apply-template-row">
|
||||||
|
<IonSelect
|
||||||
|
placeholder="Apply template..."
|
||||||
|
interface="action-sheet"
|
||||||
|
@ion-change="applyTemplate(boat.id, $event.detail.value)"
|
||||||
|
>
|
||||||
|
<IonSelectOption v-for="t in templates" :key="t.id" :value="t.id">
|
||||||
|
{{ t.name }}
|
||||||
|
</IonSelectOption>
|
||||||
|
</IonSelect>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="slotsByBoat[boat.id]?.length === 0" class="empty-text">No slots for this date.</p>
|
||||||
|
<IonList v-else lines="full">
|
||||||
|
<IonItem v-for="slot in slotsByBoat[boat.id]" :key="slot.id">
|
||||||
|
<IonIcon slot="start" :icon="timeOutline" />
|
||||||
|
<IonLabel>{{ formatTime(slot.start_time) }} – {{ formatTime(slot.end_time) }}</IonLabel>
|
||||||
|
<IonButton
|
||||||
|
slot="end"
|
||||||
|
fill="clear"
|
||||||
|
color="danger"
|
||||||
|
@click="deleteSlot(slot.id)"
|
||||||
|
>
|
||||||
|
<IonIcon slot="icon-only" :icon="trashOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Add slot modal -->
|
||||||
|
<IonModal :is-open="showAddSlot" @did-dismiss="showAddSlot = false">
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar>
|
||||||
|
<IonTitle>Add Slot</IonTitle>
|
||||||
|
<IonButtons slot="end">
|
||||||
|
<IonButton @click="showAddSlot = false">Cancel</IonButton>
|
||||||
|
</IonButtons>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">Boat</IonLabel>
|
||||||
|
<IonSelect v-model="newSlot.boatId" placeholder="Select boat" interface="action-sheet">
|
||||||
|
<IonSelectOption v-for="b in boats" :key="b.id" :value="b.id">
|
||||||
|
{{ b.display_name || b.name }}
|
||||||
|
</IonSelectOption>
|
||||||
|
</IonSelect>
|
||||||
|
</IonItem>
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">Start Time</IonLabel>
|
||||||
|
<IonInput v-model="newSlot.startTime" type="time" />
|
||||||
|
</IonItem>
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">End Time</IonLabel>
|
||||||
|
<IonInput v-model="newSlot.endTime" type="time" />
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
<IonButton
|
||||||
|
expand="block"
|
||||||
|
class="ion-margin-top"
|
||||||
|
:disabled="!newSlot.boatId || !newSlot.startTime || !newSlot.endTime || addingSlot"
|
||||||
|
@click="addSlot"
|
||||||
|
>
|
||||||
|
<IonSpinner v-if="addingSlot" name="crescent" slot="start" />
|
||||||
|
Add Slot
|
||||||
|
</IonButton>
|
||||||
|
</IonContent>
|
||||||
|
</IonModal>
|
||||||
|
|
||||||
|
<IonToast
|
||||||
|
v-model:is-open="toast.show"
|
||||||
|
:message="toast.message"
|
||||||
|
:color="toast.color"
|
||||||
|
:duration="2500"
|
||||||
|
position="bottom"
|
||||||
|
/>
|
||||||
|
</IonContent>
|
||||||
|
</IonPage>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import {
|
||||||
|
IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButtons,
|
||||||
|
IonMenuButton, IonButton, IonIcon, IonCard, IonCardHeader, IonCardTitle,
|
||||||
|
IonCardSubtitle, IonCardContent, IonList, IonItem, IonLabel, IonToggle,
|
||||||
|
IonSelect, IonSelectOption, IonSpinner, IonModal, IonInput, IonToast,
|
||||||
|
} from '@ionic/vue'
|
||||||
|
import {
|
||||||
|
addOutline, timeOutline, trashOutline, constructOutline,
|
||||||
|
} from 'ionicons/icons'
|
||||||
|
import type { Database, TimeTuple } from '~/types/supabase'
|
||||||
|
|
||||||
|
type Boat = Database['public']['Tables']['boats']['Row']
|
||||||
|
type Interval = Database['public']['Tables']['intervals']['Row']
|
||||||
|
type Template = Database['public']['Tables']['interval_templates']['Row']
|
||||||
|
|
||||||
|
definePageMeta({ layout: false, middleware: ['auth'] })
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const supabase = useSupabaseClient() as any
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const addingSlot = ref(false)
|
||||||
|
const showAddSlot = ref(false)
|
||||||
|
const selectedDate = ref(todayIso())
|
||||||
|
const boats = ref<Boat[]>([])
|
||||||
|
const templates = ref<Template[]>([])
|
||||||
|
const slotsByBoat = ref<Record<string, Interval[]>>({})
|
||||||
|
const toast = reactive({ show: false, message: '', color: 'success' })
|
||||||
|
|
||||||
|
const newSlot = reactive({ boatId: '', startTime: '08:00', endTime: '12:00' })
|
||||||
|
|
||||||
|
const dateOptions = computed(() => {
|
||||||
|
const out = []
|
||||||
|
const base = new Date()
|
||||||
|
for (let i = 0; i < 14; i++) {
|
||||||
|
const d = new Date(base)
|
||||||
|
d.setDate(base.getDate() + i)
|
||||||
|
out.push({
|
||||||
|
iso: toIso(d),
|
||||||
|
dayName: d.toLocaleDateString('en-CA', { weekday: 'short' }),
|
||||||
|
dayNum: d.getDate(),
|
||||||
|
month: d.toLocaleDateString('en-CA', { month: 'short' }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([fetchBoats(), fetchTemplates()])
|
||||||
|
await fetchSlots()
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(selectedDate, fetchSlots)
|
||||||
|
|
||||||
|
async function fetchBoats() {
|
||||||
|
const { data } = await supabase.from('boats').select('*').order('name')
|
||||||
|
boats.value = data ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchTemplates() {
|
||||||
|
const { data } = await supabase.from('interval_templates').select('*').order('name')
|
||||||
|
templates.value = data ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchSlots() {
|
||||||
|
loading.value = true
|
||||||
|
const dayStart = selectedDate.value + 'T00:00:00Z'
|
||||||
|
const dayEnd = selectedDate.value + 'T23:59:59Z'
|
||||||
|
|
||||||
|
const { data } = await supabase
|
||||||
|
.from('intervals')
|
||||||
|
.select('*')
|
||||||
|
.gte('start_time', dayStart)
|
||||||
|
.lte('start_time', dayEnd)
|
||||||
|
.order('start_time', { ascending: true })
|
||||||
|
|
||||||
|
const grouped: Record<string, Interval[]> = {}
|
||||||
|
for (const boat of boats.value) grouped[boat.id] = []
|
||||||
|
for (const slot of (data ?? []) as Interval[]) {
|
||||||
|
if (!grouped[slot.boat_id]) grouped[slot.boat_id] = []
|
||||||
|
grouped[slot.boat_id]!.push(slot)
|
||||||
|
}
|
||||||
|
slotsByBoat.value = grouped
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addSlot() {
|
||||||
|
addingSlot.value = true
|
||||||
|
const start = new Date(`${selectedDate.value}T${newSlot.startTime}:00`)
|
||||||
|
const end = new Date(`${selectedDate.value}T${newSlot.endTime}:00`)
|
||||||
|
|
||||||
|
const { error } = await supabase.from('intervals').insert({
|
||||||
|
boat_id: newSlot.boatId,
|
||||||
|
start_time: start.toISOString(),
|
||||||
|
end_time: end.toISOString(),
|
||||||
|
})
|
||||||
|
|
||||||
|
addingSlot.value = false
|
||||||
|
if (error) {
|
||||||
|
showToast('Failed to add slot: ' + error.message, 'danger')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
showAddSlot.value = false
|
||||||
|
newSlot.boatId = ''
|
||||||
|
await fetchSlots()
|
||||||
|
showToast('Slot added', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteSlot(id: string) {
|
||||||
|
const { error } = await supabase.from('intervals').delete().eq('id', id)
|
||||||
|
if (error) { showToast('Failed to delete: ' + error.message, 'danger'); return }
|
||||||
|
await fetchSlots()
|
||||||
|
showToast('Slot removed', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleBoatAvailability(boat: Boat, available: boolean) {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('boats')
|
||||||
|
.update({ booking_available: available })
|
||||||
|
.eq('id', boat.id)
|
||||||
|
if (error) { showToast('Update failed: ' + error.message, 'danger'); return }
|
||||||
|
boat.booking_available = available
|
||||||
|
showToast(available ? 'Boat back in service' : 'Boat out of service', available ? 'success' : 'warning')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyTemplate(boatId: string, templateId: string) {
|
||||||
|
const template = templates.value.find(t => t.id === templateId)
|
||||||
|
if (!template) return
|
||||||
|
|
||||||
|
const inserts = (template.time_tuples as TimeTuple[]).map(([start, end]) => ({
|
||||||
|
boat_id: boatId,
|
||||||
|
start_time: new Date(`${selectedDate.value}T${start}:00`).toISOString(),
|
||||||
|
end_time: new Date(`${selectedDate.value}T${end}:00`).toISOString(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const { error } = await supabase.from('intervals').insert(inserts)
|
||||||
|
if (error) { showToast('Failed to apply template: ' + error.message, 'danger'); return }
|
||||||
|
await fetchSlots()
|
||||||
|
showToast(`Template "${template.name}" applied`, 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToast(message: string, color: string) {
|
||||||
|
toast.message = message
|
||||||
|
toast.color = color
|
||||||
|
toast.show = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function todayIso() { return toIso(new Date()) }
|
||||||
|
function toIso(d: Date) { return d.toISOString().slice(0, 10) }
|
||||||
|
function formatTime(iso: string) {
|
||||||
|
return new Date(iso).toLocaleTimeString('en-CA', { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.section-title { font-size: 1rem; font-weight: 600; margin: 0 0 0.5rem; }
|
||||||
|
|
||||||
|
.date-strip {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
scrollbar-width: none;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
.date-strip::-webkit-scrollbar { display: none; }
|
||||||
|
|
||||||
|
.date-chip {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
min-width: 52px;
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
border: 1px solid var(--ion-color-light-shade);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: var(--ion-color-light);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
gap: 2px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.date-chip.active {
|
||||||
|
background: var(--ion-color-primary);
|
||||||
|
color: white;
|
||||||
|
border-color: var(--ion-color-primary);
|
||||||
|
}
|
||||||
|
.day-name { font-weight: 600; text-transform: uppercase; font-size: 0.65rem; }
|
||||||
|
.day-num { font-size: 1.1rem; font-weight: 700; }
|
||||||
|
.month { font-size: 0.65rem; }
|
||||||
|
|
||||||
|
.boat-card { margin: 0 0 1rem; }
|
||||||
|
.boat-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.out-of-service {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
color: var(--ion-color-danger);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.apply-template-row { margin-bottom: 0.75rem; }
|
||||||
|
|
||||||
|
.empty-text { color: var(--ion-color-medium); font-size: 0.9rem; }
|
||||||
|
</style>
|
||||||
262
app/pages/admin/templates.vue
Normal file
262
app/pages/admin/templates.vue
Normal file
@@ -0,0 +1,262 @@
|
|||||||
|
<template>
|
||||||
|
<IonPage>
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar color="primary">
|
||||||
|
<IonButtons slot="start">
|
||||||
|
<IonMenuButton />
|
||||||
|
</IonButtons>
|
||||||
|
<IonTitle>Interval Templates</IonTitle>
|
||||||
|
<IonButtons slot="end">
|
||||||
|
<IonButton @click="openCreate">
|
||||||
|
<IonIcon slot="icon-only" :icon="addOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</IonButtons>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<div v-if="loading" class="ion-text-center ion-padding">
|
||||||
|
<IonSpinner name="crescent" />
|
||||||
|
</div>
|
||||||
|
<p v-else-if="templates.length === 0" class="empty-text">No templates yet. Create one to get started.</p>
|
||||||
|
<IonCard v-else v-for="t in templates" :key="t.id" class="template-card">
|
||||||
|
<IonCardHeader>
|
||||||
|
<div class="template-header">
|
||||||
|
<IonCardTitle>{{ t.name }}</IonCardTitle>
|
||||||
|
<div class="header-actions">
|
||||||
|
<IonButton fill="clear" @click="openEdit(t)">
|
||||||
|
<IonIcon slot="icon-only" :icon="pencilOutline" />
|
||||||
|
</IonButton>
|
||||||
|
<IonButton fill="clear" color="danger" @click="confirmDelete(t)">
|
||||||
|
<IonIcon slot="icon-only" :icon="trashOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<div class="time-tuple-list">
|
||||||
|
<span v-for="(tuple, i) in (t.time_tuples as TimeTuple[])" :key="i" class="time-tuple-chip">
|
||||||
|
{{ tuple[0] }}–{{ tuple[1] }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
|
||||||
|
<!-- Create/Edit modal -->
|
||||||
|
<IonModal :is-open="showModal" @did-dismiss="closeModal">
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar>
|
||||||
|
<IonTitle>{{ editing ? 'Edit Template' : 'New Template' }}</IonTitle>
|
||||||
|
<IonButtons slot="end">
|
||||||
|
<IonButton @click="closeModal">Cancel</IonButton>
|
||||||
|
</IonButtons>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<IonList lines="full">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">Template Name</IonLabel>
|
||||||
|
<IonInput v-model="form.name" placeholder="e.g. Weekday Standard" />
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
|
||||||
|
<h4 class="section-title ion-margin-top">Time Slots</h4>
|
||||||
|
<div
|
||||||
|
v-for="(tuple, i) in form.tuples"
|
||||||
|
:key="i"
|
||||||
|
class="tuple-row"
|
||||||
|
>
|
||||||
|
<IonInput
|
||||||
|
class="time-input"
|
||||||
|
type="time"
|
||||||
|
:value="tuple[0]"
|
||||||
|
@ion-input="tuple[0] = ($event.detail.value as string)"
|
||||||
|
/>
|
||||||
|
<span class="tuple-dash">–</span>
|
||||||
|
<IonInput
|
||||||
|
class="time-input"
|
||||||
|
type="time"
|
||||||
|
:value="tuple[1]"
|
||||||
|
@ion-input="tuple[1] = ($event.detail.value as string)"
|
||||||
|
/>
|
||||||
|
<IonButton fill="clear" color="danger" @click="removeTuple(i)">
|
||||||
|
<IonIcon slot="icon-only" :icon="closeOutline" />
|
||||||
|
</IonButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<IonButton expand="block" fill="outline" class="ion-margin-top" @click="addTuple">
|
||||||
|
<IonIcon slot="start" :icon="addOutline" />
|
||||||
|
Add Time Slot
|
||||||
|
</IonButton>
|
||||||
|
|
||||||
|
<IonButton
|
||||||
|
expand="block"
|
||||||
|
class="ion-margin-top"
|
||||||
|
:disabled="!form.name || form.tuples.length === 0 || saving"
|
||||||
|
@click="saveTemplate"
|
||||||
|
>
|
||||||
|
<IonSpinner v-if="saving" name="crescent" slot="start" />
|
||||||
|
Save Template
|
||||||
|
</IonButton>
|
||||||
|
</IonContent>
|
||||||
|
</IonModal>
|
||||||
|
|
||||||
|
<IonAlert
|
||||||
|
:is-open="deleteAlert.show"
|
||||||
|
header="Delete Template"
|
||||||
|
:message="`Delete '${deleteAlert.name}'? This cannot be undone.`"
|
||||||
|
:buttons="[
|
||||||
|
{ text: 'Cancel', role: 'cancel', handler: () => { deleteAlert.show = false } },
|
||||||
|
{ text: 'Delete', role: 'destructive', handler: () => deleteTemplate() },
|
||||||
|
]"
|
||||||
|
@did-dismiss="deleteAlert.show = false"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<IonToast
|
||||||
|
v-model:is-open="toast.show"
|
||||||
|
:message="toast.message"
|
||||||
|
:color="toast.color"
|
||||||
|
:duration="2500"
|
||||||
|
position="bottom"
|
||||||
|
/>
|
||||||
|
</IonContent>
|
||||||
|
</IonPage>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import {
|
||||||
|
IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButtons,
|
||||||
|
IonMenuButton, IonButton, IonIcon, IonCard, IonCardHeader, IonCardTitle,
|
||||||
|
IonCardContent, IonList, IonItem, IonLabel, IonInput, IonSpinner,
|
||||||
|
IonModal, IonAlert, IonToast,
|
||||||
|
} from '@ionic/vue'
|
||||||
|
import { addOutline, pencilOutline, trashOutline, closeOutline } from 'ionicons/icons'
|
||||||
|
import type { Database, TimeTuple } from '~/types/supabase'
|
||||||
|
|
||||||
|
type Template = Database['public']['Tables']['interval_templates']['Row']
|
||||||
|
|
||||||
|
definePageMeta({ layout: false, middleware: ['auth'] })
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const supabase = useSupabaseClient() as any
|
||||||
|
|
||||||
|
const loading = ref(true)
|
||||||
|
const saving = ref(false)
|
||||||
|
const showModal = ref(false)
|
||||||
|
const editing = ref<Template | null>(null)
|
||||||
|
const templates = ref<Template[]>([])
|
||||||
|
const toast = reactive({ show: false, message: '', color: 'success' })
|
||||||
|
const deleteAlert = reactive({ show: false, id: '', name: '' })
|
||||||
|
|
||||||
|
const form = reactive<{ name: string; tuples: [string, string][] }>({
|
||||||
|
name: '',
|
||||||
|
tuples: [['08:00', '12:00']],
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(fetchTemplates)
|
||||||
|
|
||||||
|
async function fetchTemplates() {
|
||||||
|
loading.value = true
|
||||||
|
const { data } = await supabase.from('interval_templates').select('*').order('name')
|
||||||
|
templates.value = data ?? []
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
editing.value = null
|
||||||
|
form.name = ''
|
||||||
|
form.tuples = [['08:00', '12:00']]
|
||||||
|
showModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(t: Template) {
|
||||||
|
editing.value = t
|
||||||
|
form.name = t.name
|
||||||
|
form.tuples = (t.time_tuples as TimeTuple[]).map(tuple => [tuple[0], tuple[1]])
|
||||||
|
showModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
showModal.value = false
|
||||||
|
editing.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
function addTuple() {
|
||||||
|
form.tuples.push(['13:00', '17:00'])
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTuple(i: number) {
|
||||||
|
form.tuples.splice(i, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTemplate() {
|
||||||
|
saving.value = true
|
||||||
|
const payload = {
|
||||||
|
name: form.name,
|
||||||
|
time_tuples: form.tuples as TimeTuple[],
|
||||||
|
}
|
||||||
|
|
||||||
|
let error
|
||||||
|
if (editing.value) {
|
||||||
|
;({ error } = await supabase.from('interval_templates').update(payload).eq('id', editing.value.id))
|
||||||
|
} else {
|
||||||
|
;({ error } = await supabase.from('interval_templates').insert(payload))
|
||||||
|
}
|
||||||
|
|
||||||
|
saving.value = false
|
||||||
|
if (error) { showToast('Save failed: ' + error.message, 'danger'); return }
|
||||||
|
|
||||||
|
closeModal()
|
||||||
|
await fetchTemplates()
|
||||||
|
showToast(editing.value ? 'Template updated' : 'Template created', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmDelete(t: Template) {
|
||||||
|
deleteAlert.id = t.id
|
||||||
|
deleteAlert.name = t.name
|
||||||
|
deleteAlert.show = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteTemplate() {
|
||||||
|
const { error } = await supabase.from('interval_templates').delete().eq('id', deleteAlert.id)
|
||||||
|
deleteAlert.show = false
|
||||||
|
if (error) { showToast('Delete failed: ' + error.message, 'danger'); return }
|
||||||
|
await fetchTemplates()
|
||||||
|
showToast('Template deleted', 'success')
|
||||||
|
}
|
||||||
|
|
||||||
|
function showToast(message: string, color: string) {
|
||||||
|
toast.message = message
|
||||||
|
toast.color = color
|
||||||
|
toast.show = true
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.template-card { margin: 0 0 1rem; }
|
||||||
|
.template-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.header-actions { display: flex; }
|
||||||
|
.time-tuple-list { display: flex; flex-wrap: wrap; gap: 0.5rem; }
|
||||||
|
.time-tuple-chip {
|
||||||
|
padding: 0.3rem 0.75rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
background: var(--ion-color-light);
|
||||||
|
border: 1px solid var(--ion-color-light-shade);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.section-title { font-size: 0.95rem; font-weight: 600; margin: 0 0 0.5rem; }
|
||||||
|
.tuple-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
.time-input { flex: 1; }
|
||||||
|
.tuple-dash { font-weight: 600; }
|
||||||
|
.empty-text { color: var(--ion-color-medium); text-align: center; padding: 2rem 0; }
|
||||||
|
</style>
|
||||||
391
app/pages/reservations/create.vue
Normal file
391
app/pages/reservations/create.vue
Normal file
@@ -0,0 +1,391 @@
|
|||||||
|
<template>
|
||||||
|
<IonPage>
|
||||||
|
<IonHeader>
|
||||||
|
<IonToolbar color="primary">
|
||||||
|
<IonButtons slot="start">
|
||||||
|
<IonBackButton default-href="/" />
|
||||||
|
</IonButtons>
|
||||||
|
<IonTitle>New Reservation</IonTitle>
|
||||||
|
</IonToolbar>
|
||||||
|
</IonHeader>
|
||||||
|
|
||||||
|
<IonContent class="ion-padding">
|
||||||
|
<!-- Step 1: Pick a date and select a slot -->
|
||||||
|
<template v-if="step === 1">
|
||||||
|
<h3 class="section-title">Select Date</h3>
|
||||||
|
|
||||||
|
<!-- Horizontal date strip -->
|
||||||
|
<div class="date-strip">
|
||||||
|
<button
|
||||||
|
v-for="d in dateOptions"
|
||||||
|
:key="d.iso"
|
||||||
|
class="date-chip"
|
||||||
|
:class="{ active: selectedDate === d.iso }"
|
||||||
|
@click="selectedDate = d.iso"
|
||||||
|
>
|
||||||
|
<span class="day-name">{{ d.dayName }}</span>
|
||||||
|
<span class="day-num">{{ d.dayNum }}</span>
|
||||||
|
<span class="month">{{ d.month }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3 class="section-title ion-margin-top">Available Slots</h3>
|
||||||
|
|
||||||
|
<div v-if="loadingSlots" class="ion-text-center ion-padding">
|
||||||
|
<IonSpinner name="crescent" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-else-if="availableByBoat.length === 0" class="empty-text">
|
||||||
|
No available slots for this date.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<IonCard
|
||||||
|
v-for="entry in availableByBoat"
|
||||||
|
:key="entry.boat.id"
|
||||||
|
class="boat-card"
|
||||||
|
>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>{{ entry.boat.display_name || entry.boat.name }}</IonCardTitle>
|
||||||
|
<IonCardSubtitle v-if="entry.boat.class">{{ entry.boat.class }}</IonCardSubtitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<div v-if="!entry.certified" class="cert-warning">
|
||||||
|
<IonIcon :icon="warningOutline" color="warning" />
|
||||||
|
<span>You are not certified for this boat.</span>
|
||||||
|
</div>
|
||||||
|
<div class="slot-chips">
|
||||||
|
<button
|
||||||
|
v-for="slot in entry.slots"
|
||||||
|
:key="slot.id"
|
||||||
|
class="slot-chip"
|
||||||
|
:disabled="!entry.certified"
|
||||||
|
@click="selectSlot(entry.boat, slot)"
|
||||||
|
>
|
||||||
|
{{ formatSlotTime(slot.start_time) }}–{{ formatSlotTime(slot.end_time) }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Step 2: Confirm details -->
|
||||||
|
<template v-else>
|
||||||
|
<IonCard>
|
||||||
|
<IonCardHeader>
|
||||||
|
<IonCardTitle>{{ selectedBoat?.display_name || selectedBoat?.name }}</IonCardTitle>
|
||||||
|
<IonCardSubtitle v-if="selectedBoat?.class">{{ selectedBoat.class }}</IonCardSubtitle>
|
||||||
|
</IonCardHeader>
|
||||||
|
<IonCardContent>
|
||||||
|
<div class="time-summary">
|
||||||
|
<div class="time-row">
|
||||||
|
<IonIcon :icon="timeOutline" />
|
||||||
|
<span>{{ formatFull(selectedSlot!.start_time) }} – {{ formatSlotTime(selectedSlot!.end_time) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</IonCardContent>
|
||||||
|
</IonCard>
|
||||||
|
|
||||||
|
<IonList lines="full" class="ion-margin-top">
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">Reason</IonLabel>
|
||||||
|
<IonSelect v-model="form.reason" placeholder="Select reason" interface="action-sheet">
|
||||||
|
<IonSelectOption v-for="r in reasonOptions" :key="r" :value="r">{{ r }}</IonSelectOption>
|
||||||
|
</IonSelect>
|
||||||
|
</IonItem>
|
||||||
|
<IonItem>
|
||||||
|
<IonLabel position="stacked">Additional Comments (optional)</IonLabel>
|
||||||
|
<IonTextarea v-model="form.comment" :rows="3" placeholder="Any notes..." />
|
||||||
|
</IonItem>
|
||||||
|
</IonList>
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<IonButton fill="outline" @click="step = 1">Back</IonButton>
|
||||||
|
<IonButton
|
||||||
|
:disabled="!form.reason || submitting"
|
||||||
|
@click="submitReservation"
|
||||||
|
>
|
||||||
|
<IonSpinner v-if="submitting" name="crescent" slot="start" />
|
||||||
|
Confirm Booking
|
||||||
|
</IonButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<IonToast
|
||||||
|
v-model:is-open="toast.show"
|
||||||
|
:message="toast.message"
|
||||||
|
:color="toast.color"
|
||||||
|
:duration="3000"
|
||||||
|
position="bottom"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</IonContent>
|
||||||
|
</IonPage>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import {
|
||||||
|
IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButtons,
|
||||||
|
IonBackButton, IonCard, IonCardHeader, IonCardTitle, IonCardSubtitle,
|
||||||
|
IonCardContent, IonList, IonItem, IonLabel, IonSelect, IonSelectOption,
|
||||||
|
IonTextarea, IonButton, IonSpinner, IonIcon, IonToast,
|
||||||
|
} from '@ionic/vue'
|
||||||
|
import { timeOutline, warningOutline } from 'ionicons/icons'
|
||||||
|
import { useAuthStore } from '~/stores/auth'
|
||||||
|
import type { Database } from '~/types/supabase'
|
||||||
|
|
||||||
|
type Boat = Database['public']['Tables']['boats']['Row']
|
||||||
|
type Interval = Database['public']['Tables']['intervals']['Row']
|
||||||
|
|
||||||
|
definePageMeta({ layout: false })
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const supabase = useSupabaseClient() as any
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const step = ref<1 | 2>(1)
|
||||||
|
const loadingSlots = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const selectedDate = ref(todayIso())
|
||||||
|
const selectedBoat = ref<Boat | null>(null)
|
||||||
|
const selectedSlot = ref<Interval | null>(null)
|
||||||
|
const toast = reactive({ show: false, message: '', color: 'success' })
|
||||||
|
|
||||||
|
const form = reactive({ reason: '', comment: '' })
|
||||||
|
const reasonOptions = ['Open Sail', 'Private Sail', 'Racing', 'Training', 'Other']
|
||||||
|
|
||||||
|
// 14-day date strip starting today
|
||||||
|
const dateOptions = computed(() => {
|
||||||
|
const out = []
|
||||||
|
const base = new Date()
|
||||||
|
for (let i = 0; i < 14; i++) {
|
||||||
|
const d = new Date(base)
|
||||||
|
d.setDate(base.getDate() + i)
|
||||||
|
out.push({
|
||||||
|
iso: toIso(d),
|
||||||
|
dayName: d.toLocaleDateString('en-CA', { weekday: 'short' }),
|
||||||
|
dayNum: d.getDate(),
|
||||||
|
month: d.toLocaleDateString('en-CA', { month: 'short' }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
|
||||||
|
interface BoatSlotEntry {
|
||||||
|
boat: Boat
|
||||||
|
slots: Interval[]
|
||||||
|
certified: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const availableByBoat = ref<BoatSlotEntry[]>([])
|
||||||
|
|
||||||
|
watch(selectedDate, loadSlots, { immediate: true })
|
||||||
|
|
||||||
|
async function loadSlots() {
|
||||||
|
loadingSlots.value = true
|
||||||
|
availableByBoat.value = []
|
||||||
|
|
||||||
|
const dayStart = selectedDate.value + 'T00:00:00Z'
|
||||||
|
const dayEnd = selectedDate.value + 'T23:59:59Z'
|
||||||
|
|
||||||
|
// Load available intervals + boats (booking_available = true) for selected date
|
||||||
|
const { data: intervals, error } = await supabase
|
||||||
|
.from('intervals')
|
||||||
|
.select('*, boats!inner(id, name, display_name, class, img_src, booking_available, required_certs, max_passengers, defects, year, icon_src, created_at)')
|
||||||
|
.gte('start_time', dayStart)
|
||||||
|
.lte('start_time', dayEnd)
|
||||||
|
.eq('boats.booking_available', true)
|
||||||
|
.order('start_time', { ascending: true })
|
||||||
|
|
||||||
|
if (error) { loadingSlots.value = false; return }
|
||||||
|
|
||||||
|
// Load booked slots via reservation_slots view (hides personal details)
|
||||||
|
const { data: bookedSlots } = await supabase
|
||||||
|
.from('reservation_slots')
|
||||||
|
.select('boat_id, start_time, end_time')
|
||||||
|
.gte('start_time', dayStart)
|
||||||
|
.lte('start_time', dayEnd)
|
||||||
|
|
||||||
|
const booked = new Set<string>()
|
||||||
|
for (const r of (bookedSlots ?? []) as { boat_id: string; start_time: string; end_time: string }[]) {
|
||||||
|
booked.add(`${r.boat_id}|${r.start_time}|${r.end_time}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const memberCerts: string[] = auth.member?.certifications ?? []
|
||||||
|
|
||||||
|
// Group by boat, filtering out booked slots
|
||||||
|
const byBoat = new Map<string, BoatSlotEntry>()
|
||||||
|
for (const row of intervals ?? []) {
|
||||||
|
const boat = (row as unknown as { boats: Boat }).boats
|
||||||
|
const key = `${boat.id}|${row.start_time}|${row.end_time}`
|
||||||
|
if (booked.has(key)) continue
|
||||||
|
|
||||||
|
if (!byBoat.has(boat.id)) {
|
||||||
|
byBoat.set(boat.id, {
|
||||||
|
boat,
|
||||||
|
slots: [],
|
||||||
|
certified: boat.required_certs.length === 0 ||
|
||||||
|
boat.required_certs.every(c => memberCerts.includes(c)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
byBoat.get(boat.id)!.slots.push(row as Interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
availableByBoat.value = Array.from(byBoat.values())
|
||||||
|
loadingSlots.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectSlot(boat: Boat, slot: Interval) {
|
||||||
|
selectedBoat.value = boat
|
||||||
|
selectedSlot.value = slot
|
||||||
|
form.reason = ''
|
||||||
|
form.comment = ''
|
||||||
|
step.value = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitReservation() {
|
||||||
|
if (!auth.user || !selectedBoat.value || !selectedSlot.value) return
|
||||||
|
submitting.value = true
|
||||||
|
|
||||||
|
const { data: sessionData } = await supabase.auth.getSession()
|
||||||
|
const accessToken = sessionData.session?.access_token ?? ''
|
||||||
|
|
||||||
|
const response = await supabase.functions.invoke('create-reservation', {
|
||||||
|
body: {
|
||||||
|
boat_id: selectedBoat.value.id,
|
||||||
|
start_time: selectedSlot.value.start_time,
|
||||||
|
end_time: selectedSlot.value.end_time,
|
||||||
|
reason: form.reason,
|
||||||
|
comment: form.comment,
|
||||||
|
},
|
||||||
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
|
})
|
||||||
|
|
||||||
|
submitting.value = false
|
||||||
|
|
||||||
|
if (response.error || (response.data as { error?: { code: string; message: string } })?.error) {
|
||||||
|
const apiError = (response.data as { error?: { code: string; message: string } })?.error
|
||||||
|
const codeMessages: Record<string, string> = {
|
||||||
|
cert_required: 'You are not certified for this boat.',
|
||||||
|
slot_taken: 'This slot was just booked by someone else.',
|
||||||
|
booking_limit_weekly: apiError?.message ?? 'Weekly booking limit reached.',
|
||||||
|
booking_limit_weekend: apiError?.message ?? 'Weekend booking limit reached.',
|
||||||
|
boat_unavailable: 'This boat is currently out of service.',
|
||||||
|
}
|
||||||
|
toast.message = (apiError?.code && codeMessages[apiError.code]) || apiError?.message || 'Failed to create reservation.'
|
||||||
|
toast.color = 'danger'
|
||||||
|
toast.show = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
toast.message = 'Reservation created!'
|
||||||
|
toast.color = 'success'
|
||||||
|
toast.show = true
|
||||||
|
setTimeout(() => router.push('/'), 1500)
|
||||||
|
}
|
||||||
|
|
||||||
|
function todayIso() {
|
||||||
|
return toIso(new Date())
|
||||||
|
}
|
||||||
|
|
||||||
|
function toIso(d: Date) {
|
||||||
|
return d.toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSlotTime(iso: string) {
|
||||||
|
return new Date(iso).toLocaleTimeString('en-CA', { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFull(iso: string) {
|
||||||
|
return new Date(iso).toLocaleDateString('en-CA', { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.section-title {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.date-strip {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding-bottom: 0.5rem;
|
||||||
|
scrollbar-width: none;
|
||||||
|
}
|
||||||
|
.date-strip::-webkit-scrollbar { display: none; }
|
||||||
|
|
||||||
|
.date-chip {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
min-width: 52px;
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
border: 1px solid var(--ion-color-light-shade);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: var(--ion-color-light);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
gap: 2px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.date-chip.active {
|
||||||
|
background: var(--ion-color-primary);
|
||||||
|
color: white;
|
||||||
|
border-color: var(--ion-color-primary);
|
||||||
|
}
|
||||||
|
.day-name { font-weight: 600; text-transform: uppercase; font-size: 0.65rem; }
|
||||||
|
.day-num { font-size: 1.1rem; font-weight: 700; }
|
||||||
|
.month { font-size: 0.65rem; }
|
||||||
|
|
||||||
|
.boat-card { margin: 0 0 1rem; }
|
||||||
|
|
||||||
|
.cert-warning {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
color: var(--ion-color-warning-shade);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slot-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
.slot-chip {
|
||||||
|
padding: 0.4rem 0.75rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
border: 1px solid var(--ion-color-primary);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ion-color-primary);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.slot-chip:disabled {
|
||||||
|
border-color: var(--ion-color-medium);
|
||||||
|
color: var(--ion-color-medium);
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
.slot-chip:not(:disabled):hover {
|
||||||
|
background: var(--ion-color-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.time-summary { display: flex; flex-direction: column; gap: 0.4rem; }
|
||||||
|
.time-row { display: flex; align-items: center; gap: 0.5rem; font-size: 0.95rem; }
|
||||||
|
|
||||||
|
.empty-text { color: var(--ion-color-medium); text-align: center; padding: 2rem 0; }
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.75rem;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -190,6 +190,37 @@ export type Database = {
|
|||||||
created_at?: string
|
created_at?: string
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
booking_config: {
|
||||||
|
Row: {
|
||||||
|
key: string
|
||||||
|
value: Json
|
||||||
|
description: string | null
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
key: string
|
||||||
|
value: Json
|
||||||
|
description?: string | null
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
key?: string
|
||||||
|
value?: Json
|
||||||
|
description?: string | null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
holidays: {
|
||||||
|
Row: {
|
||||||
|
date: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
date: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
date?: string
|
||||||
|
name?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
reference_docs: {
|
reference_docs: {
|
||||||
Row: {
|
Row: {
|
||||||
id: string
|
id: string
|
||||||
@@ -221,7 +252,15 @@ export type Database = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Views: {
|
Views: {
|
||||||
[_ in never]: never
|
reservation_slots: {
|
||||||
|
Row: {
|
||||||
|
id: string
|
||||||
|
boat_id: string
|
||||||
|
start_time: string
|
||||||
|
end_time: string
|
||||||
|
status: ReservationStatus
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Functions: {
|
Functions: {
|
||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
|
|||||||
73
docs/archive/handoffs/handoff-2026-04-20-home-page.md
Normal file
73
docs/archive/handoffs/handoff-2026-04-20-home-page.md
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
# Session Handoff: Home Page Content + E2E Fixes
|
||||||
|
**Date:** 2026-04-20
|
||||||
|
**Session Duration:** ~1.5 hours
|
||||||
|
**Session Focus:** Build authenticated home page; fix E2E test issues from prior session
|
||||||
|
**Context Usage at Handoff:** Low
|
||||||
|
|
||||||
|
## What Was Accomplished
|
||||||
|
|
||||||
|
1. **Playwright E2E: fixed selector issues** — `IonButton router-link` renders as role=`link` not `button`; `IonInput` label not associated via `for`/`id`, use `getByPlaceholder` instead
|
||||||
|
2. **Playwright E2E: fixed magic link redirect** — `supabase/config.toml` had wrong `site_url` (`127.0.0.1` → `localhost`) and missing `/auth/callback` in `additional_redirect_urls`; also added server-side redirect follow via `fetch(magicLink, { redirect: 'manual' })` to avoid browser connecting to Supabase local port
|
||||||
|
3. **E2E tests passing: 2/2** — splash→login→magic link→home flow + protected route redirect
|
||||||
|
4. **Home page built** → `app/pages/index.vue` — Welcome heading, upcoming reservations card, Create Reservation button, inline PrimeVue DatePicker calendar
|
||||||
|
5. **WeatherWidget component created** → `app/components/WeatherWidget.vue` — Open-Meteo (free, no key), shows temp/conditions/wind in knots; 10-minute `localStorage` cache to avoid API overload
|
||||||
|
6. **Marina coordinates set**: `43.4412629, -79.6696725` (Oakville/Bronte Harbour)
|
||||||
|
7. **`IonSplitPane` added** to `app/app.vue` — sidebar open by default on desktop (≥992px); user reverted `auto-hide="false"` on `IonMenuButton` in `index.vue` — desktop sidebar toggle behavior is OPEN
|
||||||
|
|
||||||
|
## Exact State of Work in Progress
|
||||||
|
|
||||||
|
- Desktop sidebar toggle: `IonSplitPane` is in `app.vue` but `auto-hide="false"` was reverted from `index.vue`; sidebar opens on desktop but hamburger icon hides — revisit next session if needed
|
||||||
|
- `/reservations/create` route: wired up as `router-link` on Create Reservation button but page does not exist yet
|
||||||
|
|
||||||
|
## Decisions Made This Session
|
||||||
|
|
||||||
|
- **Open-Meteo for weather** BECAUSE free, no API key, client-side CORS allowed, updates every 15 min — STATUS: confirmed
|
||||||
|
- **10-minute `localStorage` cache for weather** BECAUSE Open-Meteo updates every 15 min; survives page refresh — STATUS: confirmed
|
||||||
|
- **Server-side redirect follow for E2E magic link** BECAUSE Playwright Chromium headless shell cannot reach `127.0.0.1:54321` (Supabase local auth); Node.js `fetch` can — STATUS: confirmed
|
||||||
|
|
||||||
|
## Key Numbers Generated or Discovered This Session
|
||||||
|
|
||||||
|
- Weather cache TTL: 10 minutes (`600_000` ms)
|
||||||
|
- Open-Meteo wind unit: knots (`wind_speed_unit=kn`)
|
||||||
|
- Marina coordinates: `43.4412629, -79.6696725`
|
||||||
|
- `IonSplitPane` desktop breakpoint: `lg` = 992px (Ionic default)
|
||||||
|
- E2E tests: 2/2 passing
|
||||||
|
|
||||||
|
## Files Created or Modified
|
||||||
|
|
||||||
|
| File Path | Action | Description |
|
||||||
|
|-----------|--------|-------------|
|
||||||
|
| `app/pages/index.vue` | Modified | Full home content: welcome, reservations card, create button, calendar |
|
||||||
|
| `app/components/WeatherWidget.vue` | Created | Open-Meteo weather card with localStorage cache |
|
||||||
|
| `app/app.vue` | Modified | Added `IonSplitPane` wrapping menu + router outlet |
|
||||||
|
| `supabase/config.toml` | Modified | `site_url` → `http://localhost:3000`; added `/auth/callback` to `additional_redirect_urls` |
|
||||||
|
| `tests/e2e/auth.spec.ts` | Modified | Fixed selectors; added server-side redirect follow for magic link |
|
||||||
|
| `docs/summaries/handoff-2026-04-19-playwright-e2e-setup.md` | Created | Prior session handoff (Playwright setup) |
|
||||||
|
|
||||||
|
## What the NEXT Session Should Do
|
||||||
|
|
||||||
|
1. **Build `app/pages/reservations/create.vue`** — reservation creation form
|
||||||
|
- Fields needed: boat selection, date/time (start + end), reason, passengers (member_ids)
|
||||||
|
- Schema ref: `app/types/supabase.ts` → `reservations` table Insert type
|
||||||
|
- On submit: `supabase.from('reservations').insert(...)` with `user_id = user.value.id`, default `status = 'pending'`
|
||||||
|
- On success: navigate to `/` or a reservation detail page
|
||||||
|
2. Read `app/types/supabase.ts` for boats + reservations schema before writing the form
|
||||||
|
3. Read `app/stores/auth.ts` for `user` ref and `member` data (member_ids on the reservation)
|
||||||
|
|
||||||
|
## Open Questions Requiring User Input
|
||||||
|
|
||||||
|
- [ ] **Desktop hamburger behaviour** — `IonSplitPane` is active but user reverted `auto-hide="false"`; should the hamburger be visible on desktop to allow closing the sidebar, or hidden when sidebar is open? Impacts `IonMenuButton` props on every page
|
||||||
|
- [ ] **Reservation form: boat selection** — should the user pick from all `booking_available = true` boats, or filtered by their certifications (`member.certifications` vs `boat.required_certs`)? Impacts query in create form
|
||||||
|
- [ ] **Reservation form: time selection** — free-form time pickers, or constrained to `interval_templates`? Impacts form UI significantly
|
||||||
|
- [ ] **After reservation created** — navigate to reservation detail, home page, or show confirmation inline?
|
||||||
|
|
||||||
|
## Assumptions That Need Validation
|
||||||
|
|
||||||
|
- ASSUMED: `supabase stop && supabase start` was run after `config.toml` change — E2E tests pass so this is confirmed
|
||||||
|
- ASSUMED: PrimeVue `DatePicker` inline renders correctly in Ionic card on mobile — not manually tested in browser since session end
|
||||||
|
|
||||||
|
## Files to Load Next Session
|
||||||
|
|
||||||
|
- `app/types/supabase.ts` — boats + reservations schema for form fields
|
||||||
|
- `app/stores/auth.ts` — user/member refs for form submission
|
||||||
|
- `app/pages/index.vue` — reference for page structure pattern
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
# Session Handoff: Integration Test Debugging
|
||||||
|
**Date:** 2026-04-20
|
||||||
|
**Session Duration:** ~1.5 hours
|
||||||
|
**Session Focus:** Debug and fix failing integration tests for auth and booking-constraints suites; fix Edge Function boot failure; fix members RLS infinite recursion
|
||||||
|
**Context Usage at Handoff:** High
|
||||||
|
|
||||||
|
## What Was Accomplished
|
||||||
|
|
||||||
|
1. **Fixed `verifyOtp` API misuse in both test files** — `token` param is for 6-digit OTP codes; `token_hash` param is for hashed magic link tokens. Changed in both test files.
|
||||||
|
- `tests/integration/auth-session.test.ts` (2 call sites)
|
||||||
|
- `tests/integration/booking-constraints.test.ts` (1 call site in `getSessionToken`)
|
||||||
|
|
||||||
|
2. **Fixed `futureSlot()` key mismatch** in booking-constraints test — returned `{ start, end }` but `callCreateReservation` expected `{ start_time, end_time }`. Renamed keys in `futureSlot()` return value; updated 2 `directInsertReservation` call sites that used `slot.start`/`slot.end`.
|
||||||
|
|
||||||
|
3. **Added `@types/node` and test tsconfig** — Nuxt-generated tsconfig has `"types": []`, causing `process` to be unresolved in test files.
|
||||||
|
- Added `@types/node` as dev dependency
|
||||||
|
- Created `tests/tsconfig.json` extending root with `"types": ["node", "vitest/globals"]`
|
||||||
|
- Added `typecheck: { tsconfig: './tests/tsconfig.json' }` to `vitest.integration.config.ts`
|
||||||
|
|
||||||
|
4. **Fixed members RLS infinite recursion (42P17)** — Policies "Admins can read all members" and "Admins can manage all members" queried `members` from within a `members` RLS policy, causing infinite recursion. Created new migration with two `SECURITY DEFINER` helper functions:
|
||||||
|
- `public.current_user_role() → text`
|
||||||
|
- `public.current_user_has_role(roles text[]) → boolean`
|
||||||
|
- Replaced all inline `EXISTS (SELECT 1 FROM members WHERE ...)` admin checks in ALL tables with `public.current_user_has_role(...)` calls
|
||||||
|
- Migration: `supabase/migrations/20260420170418_fix_members_rls_recursion.sql`
|
||||||
|
|
||||||
|
5. **Removed broken import from Edge Function** — `import "@supabase/functions-js/edge-runtime.d.ts"` is not a valid Deno runtime import. Removed it. Also tried `/// <reference types="..." />` which also failed.
|
||||||
|
|
||||||
|
6. **Switched Edge Function import from `jsr:` to `npm:`** — `jsr:@supabase/supabase-js@2` cache is lost on container restart in the podman-based local dev setup. Changed to `npm:@supabase/supabase-js@2`.
|
||||||
|
|
||||||
|
7. **Removed `entrypoint` from config.toml** — `entrypoint` field may not be supported/correctly handled by supabase-edge-runtime 1.73.3 (podman variant). Removed it; function now relies on default `index.ts` convention.
|
||||||
|
|
||||||
|
8. **Set `verify_jwt = false` in config.toml** — Edge runtime 1.73.3 `verifyHybridJWT` fails with `TypeError: Invalid Token or Protected Header formatting` on ES256 JWTs (new `sb_publishable_*` / `sb_secret_*` key format). Disabled edge-level JWT verification; the function handles auth itself via `userClient.auth.getUser()`.
|
||||||
|
|
||||||
|
## Exact State of Work in Progress
|
||||||
|
|
||||||
|
- **Edge Function still returns BOOT_ERROR** — Even after all the above changes, the edge runtime container still fails with `worker boot error: failed to bootstrap runtime: failed to determine entrypoint`. Investigation showed the function source files are NOT mounted inside the container (`find / -name index.ts` inside the container showed only Deno npm cache, no project files). Root cause: likely a podman volume mount issue specific to this host environment. Session was interrupted before resolving this.
|
||||||
|
|
||||||
|
- **Integration tests NOT yet passing** — All 15 booking-constraints tests still fail with 503 (Edge Function BOOT_ERROR). The auth-session tests (5 tests) status is unknown for this session.
|
||||||
|
|
||||||
|
## Decisions Made This Session
|
||||||
|
|
||||||
|
- **`verify_jwt = false` for create-reservation** BECAUSE: edge-runtime 1.73.3 with podman does not correctly verify ES256 JWTs from new `sb_publishable_*` key format; function verifies auth internally via `auth.getUser()` anyway — STATUS: confirmed
|
||||||
|
- **`npm:` over `jsr:` for supabase-js import** BECAUSE: JSR cache is not persistent across podman container restarts in this local dev setup — STATUS: confirmed
|
||||||
|
- **SECURITY DEFINER functions for role checks** BECAUSE: inline `EXISTS (SELECT 1 FROM members ...)` in members RLS policies causes infinite recursion — STATUS: confirmed, migration applied
|
||||||
|
|
||||||
|
## Key Numbers Generated or Discovered This Session
|
||||||
|
|
||||||
|
- supabase-js SDK version installed: **2.100.0**
|
||||||
|
- Supabase CLI version: **2.92.1**
|
||||||
|
- supabase-edge-runtime version: **1.73.3** (compatible with Deno v2.1.4)
|
||||||
|
- Publishable key prefix: `sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH`
|
||||||
|
- Secret key prefix: `sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz`
|
||||||
|
- Access tokens are **ES256** (not HS256) — `eyJhbGciOiJFUzI1NiIs...`
|
||||||
|
- New migration timestamp: **20260420170418**
|
||||||
|
|
||||||
|
## Files Created or Modified
|
||||||
|
|
||||||
|
| File Path | Action | Description |
|
||||||
|
|-----------|--------|-------------|
|
||||||
|
| `tests/integration/auth-session.test.ts` | Modified | Fixed `verifyOtp` to use `token_hash` (2 call sites) |
|
||||||
|
| `tests/integration/booking-constraints.test.ts` | Modified | Fixed `verifyOtp` to use `token_hash`; renamed `futureSlot` keys to `start_time`/`end_time`; removed unused `beforeEach` import |
|
||||||
|
| `tests/tsconfig.json` | Created | Test-scoped tsconfig adding `node` + `vitest/globals` types |
|
||||||
|
| `vitest.integration.config.ts` | Modified | Added `typecheck.tsconfig` pointing to `tests/tsconfig.json` |
|
||||||
|
| `supabase/migrations/20260420170418_fix_members_rls_recursion.sql` | Created | SECURITY DEFINER helpers + fixed RLS policies for all tables |
|
||||||
|
| `supabase/functions/create-reservation/index.ts` | Modified | Removed bad `import`; changed `jsr:` → `npm:` for supabase-js |
|
||||||
|
| `supabase/functions/create-reservation/deno.json` | Modified | Updated import map to `npm:@supabase/supabase-js@^2` |
|
||||||
|
| `supabase/config.toml` | Modified | `verify_jwt = false`; removed `entrypoint` field |
|
||||||
|
|
||||||
|
## What the NEXT Session Should Do
|
||||||
|
|
||||||
|
1. **Diagnose Edge Function mount issue first** — Run `podman inspect supabase_edge_runtime_oysqn.app` and check the `Mounts` array. The function source files (`supabase/functions/`) must be visible inside the container. If they are not mounted, this is likely a podman rootless socket or SELinux label issue on the host. Try `npx supabase stop && npx supabase start` to re-create the container with correct mounts.
|
||||||
|
|
||||||
|
2. **If supabase restart doesn't fix mounts** — Try `npx supabase functions serve` in a separate terminal (it spins up its own Deno process outside Docker, bypassing the container). Then run `yarn test:integration` — this tests the exact same function code via the same URL. If this works, the issue is confirmed as a container mount problem, not a code problem.
|
||||||
|
|
||||||
|
3. **After Edge Function works** — Run `yarn test:integration` and expect all 15 booking-constraints tests + all auth-session tests to pass. Fix any remaining failures (expected to be minor after the above fixes).
|
||||||
|
|
||||||
|
4. **Then**: build `/admin/reservations` view — list all upcoming reservations with boat/time/member/status; ability to confirm, cancel, or modify
|
||||||
|
|
||||||
|
5. **Then**: test full member booking flow in browser (`yarn dev`, create test intervals via admin, attempt booking as member, verify Edge Function error messages surface correctly)
|
||||||
|
|
||||||
|
## Open Questions Requiring User Input
|
||||||
|
|
||||||
|
- [ ] **Why are supabase function files not mounted in podman container?** — May require `--security-opt label=disable` or `:z` volume label for SELinux compatibility. Impacts all Edge Function development.
|
||||||
|
- [ ] **Adjacent-session double-booking (Rule 6)** — exact logic needed (carried over from previous session)
|
||||||
|
- [ ] **`useSupabaseClient` typing** — all admin pages use `as any` cast (carried over)
|
||||||
|
- [ ] **Crew requirement (Rule 8)** — not implemented (carried over)
|
||||||
|
- [ ] **PCOC / cert code strings** — values for `boats.required_certs` not defined (carried over)
|
||||||
|
|
||||||
|
## Assumptions That Need Validation
|
||||||
|
|
||||||
|
- ASSUMED: `npm:@supabase/supabase-js@2` is resolvable in the podman edge runtime container (npm cache may also be missing) — validate by getting the function to boot
|
||||||
|
- ASSUMED: `verify_jwt = false` is acceptable for production deployment (auth is validated in function code) — validate with security review before prod
|
||||||
|
- ASSUMED: `tests/tsconfig.json` approach for `@types/node` is the right fix and doesn't break other test types — validate by running full test suite
|
||||||
|
- All assumptions from previous session still apply (half-open interval semantics, ISO week definition, 2026-01-05 period epoch)
|
||||||
|
|
||||||
|
## Files to Load Next Session
|
||||||
|
|
||||||
|
- `supabase/functions/create-reservation/index.ts` — to debug boot issue or extend
|
||||||
|
- `supabase/config.toml` — to review/revert `verify_jwt` setting after boot is fixed
|
||||||
|
- `supabase/migrations/20260420170418_fix_members_rls_recursion.sql` — if RLS issues resurface
|
||||||
|
- `tests/integration/booking-constraints.test.ts` — to run and review after boot fix
|
||||||
135
docs/archive/handoffs/handoff-2026-04-20-reservations.md
Normal file
135
docs/archive/handoffs/handoff-2026-04-20-reservations.md
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
# Session Handoff: Boat Reservation System
|
||||||
|
**Date:** 2026-04-20
|
||||||
|
**Session Duration:** ~3 hours
|
||||||
|
**Session Focus:** Implement full boat reservation system: member booking flow, admin slot/template management, configurable booking rules via Edge Function + DB, and integration tests
|
||||||
|
**Context Usage at Handoff:** High
|
||||||
|
|
||||||
|
## What Was Accomplished
|
||||||
|
|
||||||
|
1. **DB migration 1: Overlap constraint + cert trigger** → `supabase/migrations/20260420115333_reservations_overlap_and_cert_check.sql`
|
||||||
|
- `btree_gist` extension enabled
|
||||||
|
- `EXCLUDE USING gist (boat_id WITH =, tstzrange(start_time, end_time, '[)') WITH &&)` on `reservations`
|
||||||
|
- `enforce_reservation_cert_check()` trigger (BEFORE INSERT) — raises exception if `member.certifications` does not contain all `boat.required_certs`
|
||||||
|
- `member_has_cert_for_boat(uuid, uuid)` helper function
|
||||||
|
|
||||||
|
2. **DB migration 2: Booking rules + RBAC** → `supabase/migrations/20260420132336_booking_rules_and_rbac.sql`
|
||||||
|
- `booking_config` table (key/value, admin-editable) — RLS: authenticated read, admin write
|
||||||
|
- `holidays` table (date, name) — RLS same as above
|
||||||
|
- `is_weekend_or_holiday(date)` DB helper function
|
||||||
|
- Dropped `"Users can create own reservations"` RLS policy — direct INSERT blocked for `authenticated` role
|
||||||
|
- `reservation_slots` view (security_invoker=true) — exposes only `id, boat_id, start_time, end_time, status`
|
||||||
|
- Default config seeded: max_sessions_per_week=2, max_weekend_sessions_per_period=1, weekend_period_weeks=2, open_session_advance_hours=24
|
||||||
|
- 2026 Ontario sailing-season holidays seeded (Victoria Day through Thanksgiving)
|
||||||
|
|
||||||
|
3. **Edge Function: create-reservation** → `supabase/functions/create-reservation/index.ts`
|
||||||
|
- POST endpoint enforcing: cert check, boat availability, weekly pre-booking limit, weekend/holiday limit, open-session window bypass
|
||||||
|
- Reads all rule parameters from `booking_config` at runtime (no redeployment needed for config changes)
|
||||||
|
- Uses service_role key for insert (bypasses RLS); caller authenticated via JWT in Authorization header
|
||||||
|
- DB overlap exclusion constraint + cert trigger remain as final safety net
|
||||||
|
- Error response shape: `{ error: { code: string, message: string } }` with specific codes: `cert_required`, `slot_taken`, `booking_limit_weekly`, `booking_limit_weekend`, `boat_unavailable`
|
||||||
|
|
||||||
|
4. **Member reservation creation page** → `app/pages/reservations/create.vue`
|
||||||
|
- Step 1: 14-day horizontal date strip → available slots grouped by boat (reads `intervals` + `reservation_slots` view)
|
||||||
|
- Boats the member is not certified for shown with warning and slots disabled
|
||||||
|
- Step 2: Confirm slot → reason (select) + comment (textarea) → calls Edge Function
|
||||||
|
- Error handling maps all Edge Function error codes to user-friendly messages
|
||||||
|
|
||||||
|
5. **Admin: Manage Slots page** → `app/pages/admin/intervals.vue`
|
||||||
|
- 14-day date strip + per-boat accordion showing intervals
|
||||||
|
- Inline boat out-of-service toggle (IonToggle → updates `boats.booking_available`)
|
||||||
|
- Apply template dropdown per boat (creates intervals from `interval_templates.time_tuples`)
|
||||||
|
- Add Slot modal (boat select + time range inputs)
|
||||||
|
- Delete slot (trash button per row)
|
||||||
|
|
||||||
|
6. **Admin: Interval Templates page** → `app/pages/admin/templates.vue`
|
||||||
|
- Full CRUD: create/edit (modal with dynamic time-tuple list) / delete (IonAlert confirm)
|
||||||
|
- Time tuples displayed as chips showing HH:MM–HH:MM
|
||||||
|
|
||||||
|
7. **Admin: Booking Rules config page** → `app/pages/admin/config.vue`
|
||||||
|
- Editable numeric fields for all 4 config keys
|
||||||
|
- Holidays list with add/delete
|
||||||
|
- Save button with dirty tracking
|
||||||
|
|
||||||
|
8. **Nav wired up** → `app/app.vue`
|
||||||
|
- Boatswain+Admin: "Manage Slots" → `/admin/intervals`, "Templates" → `/admin/templates`
|
||||||
|
- Admin only: "Booking Rules" → `/admin/config`
|
||||||
|
- New icons added: `layersOutline`, `settingsOutline`
|
||||||
|
|
||||||
|
9. **Types updated** → `app/types/supabase.ts`
|
||||||
|
- Added `booking_config`, `holidays` to `Database.public.Tables`
|
||||||
|
- Added `reservation_slots` to `Database.public.Views`
|
||||||
|
|
||||||
|
10. **Integration tests** → `tests/integration/booking-constraints.test.ts`
|
||||||
|
- 6 describe blocks: overlap constraint, certification check, out-of-service, weekly limit, weekend limit, open-session window bypass, RBAC visibility
|
||||||
|
- Each creates isolated test users/boats, cleans up in afterAll
|
||||||
|
- Runs against local Supabase + Edge Functions via `yarn test:integration`
|
||||||
|
- Requires: `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_KEY` env vars; Edge Functions served with `npx supabase functions serve`
|
||||||
|
|
||||||
|
## Exact State of Work in Progress
|
||||||
|
|
||||||
|
- Edge Function not yet tested end-to-end in browser (requires `npx supabase functions serve`)
|
||||||
|
- Integration tests written but not yet run — need `supabase functions serve` running
|
||||||
|
- Adjacent-session double-booking rule (Rule 6 from guidelines) NOT YET IMPLEMENTED — marked OPEN below
|
||||||
|
|
||||||
|
## Decisions Made This Session
|
||||||
|
|
||||||
|
- **Option C hybrid architecture** BECAUSE: rule logic in TypeScript (maintainable, no SQL migrations for rule changes), DB constraints for integrity invariants (overlap exclusion, cert check) that must be atomic and bypass-proof — STATUS: confirmed
|
||||||
|
- **Direct INSERT locked for authenticated role** BECAUSE: members must go through Edge Function to enforce booking rules; admins retain direct access via "Admins can manage all reservations" policy — STATUS: confirmed
|
||||||
|
- **`reservation_slots` view** BECAUSE: column-level RBAC — members can see that a slot is taken (boat/time/status) without seeing user_id, reason, comment, member_ids of other members' bookings — STATUS: confirmed
|
||||||
|
- **`useSupabaseClient() as any`** in all new admin pages BECAUSE: `useSupabaseClient<Database>()` generic does not propagate through mutations in this Nuxt/@nuxtjs/supabase v1.5 setup; existing codebase uses cast pattern — STATUS: confirmed workaround
|
||||||
|
- **Open-session bookings counted separately** BECAUSE: Rule 7 says "pre-book 2 sessions per week" — bookings made within `open_session_advance_hours` of start time bypass the weekly and weekend limits; pre-booking count inferred from `(start_time - created_at) > advance_hours` — STATUS: confirmed
|
||||||
|
|
||||||
|
## Key Numbers Generated or Discovered This Session
|
||||||
|
|
||||||
|
- Default max_sessions_per_week: **2**
|
||||||
|
- Default max_weekend_sessions_per_period: **1**
|
||||||
|
- Default weekend_period_weeks: **2**
|
||||||
|
- Default open_session_advance_hours: **24**
|
||||||
|
- Period epoch (fixed): **2026-01-05** (Monday of ISO week 2, 2026)
|
||||||
|
- Holidays seeded: **5** (Victoria Day, Canada Day, Civic Holiday, Labour Day, Thanksgiving)
|
||||||
|
- Overlap constraint type: `tstzrange(start_time, end_time, '[)')` — half-open interval (end exclusive)
|
||||||
|
- Integration test describe blocks: **6**
|
||||||
|
- Migration files created this session: **2**
|
||||||
|
|
||||||
|
## Files Created or Modified
|
||||||
|
|
||||||
|
| File Path | Action | Description |
|
||||||
|
|-----------|--------|-------------|
|
||||||
|
| `supabase/migrations/20260420115333_reservations_overlap_and_cert_check.sql` | Created | Overlap exclusion constraint, cert check trigger, member_has_cert_for_boat() |
|
||||||
|
| `supabase/migrations/20260420132336_booking_rules_and_rbac.sql` | Created | booking_config, holidays tables, is_weekend_or_holiday(), reservation_slots view, drop direct INSERT policy |
|
||||||
|
| `supabase/functions/create-reservation/index.ts` | Created | Edge Function — all booking rule enforcement in TypeScript |
|
||||||
|
| `app/pages/reservations/create.vue` | Created | Member reservation creation: date strip → slot picker → confirm form → Edge Function call |
|
||||||
|
| `app/pages/admin/intervals.vue` | Created | Admin interval management: date strip, per-boat slot list, service toggle, template apply |
|
||||||
|
| `app/pages/admin/templates.vue` | Created | Admin interval template CRUD |
|
||||||
|
| `app/pages/admin/config.vue` | Created | Admin booking rules config: numeric params + holidays management |
|
||||||
|
| `app/app.vue` | Modified | Added nav links for /admin/intervals, /admin/templates, /admin/config; added layersOutline, settingsOutline icons |
|
||||||
|
| `app/types/supabase.ts` | Modified | Added booking_config, holidays tables; reservation_slots view |
|
||||||
|
| `tests/integration/booking-constraints.test.ts` | Created | Integration tests for all booking constraints |
|
||||||
|
|
||||||
|
## What the NEXT Session Should Do
|
||||||
|
|
||||||
|
1. **Run integration tests**: `npx supabase functions serve` in one terminal, then `yarn test:integration` — expect all 6 describe blocks to pass; fix any failures before proceeding
|
||||||
|
2. **Implement adjacent-session rule (Rule 6)**: A member may book a second adjoining session for the same boat on the day of sail only if no other member has booked it. Add check in Edge Function: if `(start_time - now) <= open_session_advance_hours AND booking is adjacent to caller's existing booking for same boat AND no other user has the adjacent slot` → allow double-booking. Otherwise, a member booking an adjacent session is subject to normal rules.
|
||||||
|
3. **Build admin reservations view**: `/admin/reservations` — list all upcoming reservations with boat/time/member/status; ability to confirm, cancel, or modify
|
||||||
|
4. **Test the full member booking flow in browser** — run `yarn dev`, create test intervals via admin, attempt to book as member, verify Edge Function error messages surface correctly
|
||||||
|
|
||||||
|
## Open Questions Requiring User Input
|
||||||
|
|
||||||
|
- [ ] **Adjacent-session double-booking (Rule 6)** — exact logic needed: does "day of sail" mean within `open_session_advance_hours`? Does the system automatically allow it if the adjacent slot is free, or does the member explicitly opt in? Impacts Edge Function logic
|
||||||
|
- [ ] **`useSupabaseClient` typing** — should we investigate properly typing the client (e.g., by configuring `supabase.types` in nuxt.config.ts to point at `types/supabase.ts`)? Currently all new pages use `as any`. Impacts type safety
|
||||||
|
- [ ] **Crew requirement (Rule 8)** — "must have at least one experienced crew member certified as helmsperson on board." Can this be enforced in the app? Members would need to name their crew at booking time. Currently not implemented. Impacts reservation form UX
|
||||||
|
- [ ] **PCOC / Basic Cruising cert codes** — what strings go in `boats.required_certs` and `members.certifications`? (e.g., `'pcoc'`, `'cya-basic-cruising'`?) Impacts cert check behavior
|
||||||
|
|
||||||
|
## Assumptions That Need Validation
|
||||||
|
|
||||||
|
- ASSUMED: `npx supabase functions serve` is available in local dev and tests will reach `http://localhost:54321/functions/v1/create-reservation` — validate by running tests
|
||||||
|
- ASSUMED: `tstzrange(start_time, end_time, '[)')` half-open intervals match the club's intent (booking a morning slot 09:00–12:30 does not block a 12:30 afternoon slot) — validate with Patrick
|
||||||
|
- ASSUMED: ISO week (Monday–Sunday) is the correct "week" definition for the 2/week limit — validate with club guidelines
|
||||||
|
- ASSUMED: 2-week period epoch of 2026-01-05 aligns correctly with the club's alternating weekend schedule — validate with program administrator
|
||||||
|
|
||||||
|
## Files to Load Next Session
|
||||||
|
|
||||||
|
- `supabase/functions/create-reservation/index.ts` — to debug test failures or extend with adjacent-session rule
|
||||||
|
- `tests/integration/booking-constraints.test.ts` — to run and review test results
|
||||||
|
- `app/pages/reservations/create.vue` — to test browser flow and fix any UX issues
|
||||||
|
- `app/types/supabase.ts` — if adding new tables or fixing type issues
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Session Handoff: Edge Functions, Auth Pattern, and Test Fixes
|
||||||
|
**Date:** 2026-04-20
|
||||||
|
**Session Duration:** ~2 hours
|
||||||
|
**Session Focus:** Fix create-reservation Edge Function auth, resolve 12 failing integration tests, fix RBAC RLS, add SELinux dev docs
|
||||||
|
**Context Usage at Handoff:** ~60%
|
||||||
|
|
||||||
|
## What Was Accomplished
|
||||||
|
1. Diagnosed and fixed SELinux blocking Edge Functions locally → documented fix in `CLAUDE.md`
|
||||||
|
2. Updated Edge Function auth from `userClient.auth.getUser()` (anon key + auth header) to `adminClient.auth.getUser(token)` (service role + JWT arg) → `supabase/functions/create-reservation/index.ts`
|
||||||
|
3. Fixed `weekSlot()` test helper returning `{start, end}` instead of `{start_time, end_time}` → `tests/integration/booking-constraints.test.ts`
|
||||||
|
4. Fixed overlap tests using days 30/31/32 (same ISO week, hitting weekly pre-booking limit before DB overlap constraint fires) → spread across days 14/21/28 (different weeks)
|
||||||
|
5. Fixed RBAC: `"Authenticated users can read non-private reservation slots"` policy on `reservations` was never dropped when `reservation_slots` view was created → new migration drops it
|
||||||
|
6. Fixed `reservation_slots` view from `security_invoker = true` to `security_invoker = false` so it reads as owner, not caller → new migration recreates view + grants
|
||||||
|
7. Fixed E2E test asserting `"Welcome to OYS Borrow a Boat"` (doesn't exist) → changed to `"Upcoming Reservations"` which is always present when authenticated
|
||||||
|
8. Added `v-if="authStore.user"` to `IonMenu` in `app.vue` — menu not rendered before login
|
||||||
|
9. Added `yarn test:all` script (unit → integration → e2e in sequence)
|
||||||
|
|
||||||
|
## Decisions Made This Session
|
||||||
|
- **Use `adminClient.auth.getUser(token)`** (not `getClaims`) BECAUSE `getClaims` is not reliably available in `npm:@supabase/supabase-js@2` Deno import and its return shape is undocumented for that context — STATUS: confirmed
|
||||||
|
- **`reservation_slots` view uses `security_invoker = false`** BECAUSE `security_invoker = true` caused it to apply the calling user's RLS (returning 0 rows for non-owners after broad policy was dropped) — STATUS: confirmed
|
||||||
|
- **Overlap tests use weeks 14/21/28 days ahead** BECAUSE original days 30/31/32 fell in the same ISO week; direct insert on day+31 consumed the 2nd weekly pre-booking slot, blocking the day+32 "different time" test — STATUS: confirmed
|
||||||
|
|
||||||
|
## Key Numbers Generated or Discovered This Session
|
||||||
|
- Integration tests before: 12 failed / 8 passed (20 total)
|
||||||
|
- Integration tests after: 0 failed / 20 passed (ASSUMED — verify with `yarn test:integration`)
|
||||||
|
- E2E tests: 1 failed / 1 passed → 2 passed after auth text fix (ASSUMED — verify with `yarn test:e2e`)
|
||||||
|
|
||||||
|
## Files Created or Modified
|
||||||
|
| File Path | Action | Description |
|
||||||
|
|-----------|--------|-------------|
|
||||||
|
| `supabase/functions/create-reservation/index.ts` | Modified | Auth: `getClaims` → `adminClient.auth.getUser(token)`; `claims.sub` → `user.id` |
|
||||||
|
| `tests/integration/booking-constraints.test.ts` | Modified | `weekSlot` key names fixed; overlap test days spread across weeks |
|
||||||
|
| `tests/e2e/auth.spec.ts` | Modified | Assertion changed from missing text to `"Upcoming Reservations"` |
|
||||||
|
| `app/app.vue` | Modified | `v-if="authStore.user"` on `IonMenu` |
|
||||||
|
| `package.json` | Modified | Added `test:all` script |
|
||||||
|
| `CLAUDE.md` | Modified | Added Edge Functions section: SELinux fix, auth pattern, `security_invoker` note |
|
||||||
|
| `supabase/migrations/20260420180000_drop_open_reservations_read_policy.sql` | Created | Drops `"Authenticated users can read non-private reservation slots"` policy |
|
||||||
|
| `supabase/migrations/20260420190000_fix_reservation_slots_view.sql` | Created | Recreates `reservation_slots` with `security_invoker = false`; grants SELECT to authenticated |
|
||||||
|
| `supabase/migrations/20260420132336_booking_rules_and_rbac.sql` | Modified | Fixed original view creation to `security_invoker = false` + added GRANT for `db reset` consistency |
|
||||||
|
|
||||||
|
## What the NEXT Session Should Do
|
||||||
|
1. **First**: Verify all tests pass — `yarn test:all` (requires local Supabase running with functions served)
|
||||||
|
2. **Then**: Work on reservations UI — `app/pages/reservations/` exists but contents unknown; likely needs create/list/detail pages wired to the Edge Function
|
||||||
|
|
||||||
|
## Open Questions Requiring User Input
|
||||||
|
- [ ] What pages exist under `app/pages/reservations/`? Are they scaffolded or complete? — impacts next UI session scope
|
||||||
|
- [ ] Are there additional Edge Functions planned (e.g., cancel-reservation, admin endpoints)? — impacts function auth pattern reuse
|
||||||
|
|
||||||
|
## Assumptions That Need Validation
|
||||||
|
- ASSUMED: `yarn test:all` passes cleanly after migrations applied — validate by running `npx supabase migration up && yarn test:all`
|
||||||
|
- ASSUMED: `reservation_slots` view grant is sufficient for anon client queries in tests — validate by observing RBAC test pass
|
||||||
|
|
||||||
|
## Files to Load Next Session
|
||||||
|
- `docs/summaries/handoff-2026-04-20-edge-functions-auth-and-test-fixes.md` — this file
|
||||||
|
- `supabase/functions/create-reservation/index.ts` — if continuing Edge Function work
|
||||||
|
- `app/pages/reservations/` — if working on reservations UI
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
"preview": "nuxt preview",
|
"preview": "nuxt preview",
|
||||||
"postinstall": "nuxt prepare",
|
"postinstall": "nuxt prepare",
|
||||||
"typecheck": "nuxt typecheck",
|
"typecheck": "nuxt typecheck",
|
||||||
|
"test:all": "yarn test && yarn test:integration && yarn test:e2e",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
"test:integration": "vitest run --config vitest.integration.config.ts",
|
"test:integration": "vitest run --config vitest.integration.config.ts",
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nuxt/test-utils": "^4.0.2",
|
"@nuxt/test-utils": "^4.0.2",
|
||||||
"@playwright/test": "^1.59.1",
|
"@playwright/test": "^1.59.1",
|
||||||
|
"@types/node": "^25.6.0",
|
||||||
"@vite-pwa/nuxt": "^1.1.1",
|
"@vite-pwa/nuxt": "^1.1.1",
|
||||||
"@vue/test-utils": "^2.4.6",
|
"@vue/test-utils": "^2.4.6",
|
||||||
"happy-dom": "^20.8.9",
|
"happy-dom": "^20.8.9",
|
||||||
|
|||||||
@@ -87,4 +87,4 @@ Error generating stack: `+l.message+`
|
|||||||
<div id='root'></div>
|
<div id='root'></div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
<template id="playwrightReportBase64">data:application/zip;base64,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</template>
|
<template id="playwrightReportBase64">data:application/zip;base64,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</template>
|
||||||
@@ -394,3 +394,9 @@ s3_secret_key = "env(S3_SECRET_KEY)"
|
|||||||
# declarative_schema_path = "./declarative"
|
# declarative_schema_path = "./declarative"
|
||||||
# JSON string passed through to pg-delta SQL formatting.
|
# JSON string passed through to pg-delta SQL formatting.
|
||||||
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
|
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
|
||||||
|
|
||||||
|
[functions.create-reservation]
|
||||||
|
enabled = true
|
||||||
|
verify_jwt = false
|
||||||
|
import_map = "./functions/create-reservation/deno.json"
|
||||||
|
|
||||||
|
|||||||
3
supabase/functions/create-reservation/.npmrc
Normal file
3
supabase/functions/create-reservation/.npmrc
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Configuration for private npm package dependencies
|
||||||
|
# For more information on using private registries with Edge Functions, see:
|
||||||
|
# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
|
||||||
5
supabase/functions/create-reservation/deno.json
Normal file
5
supabase/functions/create-reservation/deno.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"imports": {
|
||||||
|
"@supabase/functions-js": "jsr:@supabase/functions-js@^2"
|
||||||
|
}
|
||||||
|
}
|
||||||
261
supabase/functions/create-reservation/index.ts
Normal file
261
supabase/functions/create-reservation/index.ts
Normal file
@@ -0,0 +1,261 @@
|
|||||||
|
import { createClient } from "npm:@supabase/supabase-js@2"
|
||||||
|
|
||||||
|
interface CreateReservationBody {
|
||||||
|
boat_id: string
|
||||||
|
start_time: string // ISO 8601
|
||||||
|
end_time: string // ISO 8601
|
||||||
|
reason?: string
|
||||||
|
comment?: string
|
||||||
|
member_ids?: string[]
|
||||||
|
guest_ids?: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookingConfig {
|
||||||
|
max_sessions_per_week: number
|
||||||
|
max_weekend_sessions_per_period: number
|
||||||
|
weekend_period_weeks: number
|
||||||
|
open_session_advance_hours: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReservationRow {
|
||||||
|
boat_id: string
|
||||||
|
start_time: string
|
||||||
|
end_time: string
|
||||||
|
created_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns ISO date string for the Monday of the ISO week containing `d`.
|
||||||
|
function isoWeekStart(d: Date): Date {
|
||||||
|
const day = d.getUTCDay() || 7 // treat Sunday as 7
|
||||||
|
const monday = new Date(d)
|
||||||
|
monday.setUTCDate(d.getUTCDate() - (day - 1))
|
||||||
|
monday.setUTCHours(0, 0, 0, 0)
|
||||||
|
return monday
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fixed epoch: first Monday of 2026 (2026-01-05)
|
||||||
|
const PERIOD_EPOCH = new Date('2026-01-05T00:00:00Z')
|
||||||
|
|
||||||
|
function weeksSince(d: Date, epoch: Date): number {
|
||||||
|
return Math.floor((isoWeekStart(d).getTime() - epoch.getTime()) / (7 * 24 * 60 * 60 * 1000))
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWeekendOrHoliday(date: Date, holidays: Set<string>): boolean {
|
||||||
|
const dow = date.getUTCDay() // 0=Sun, 6=Sat
|
||||||
|
const iso = date.toISOString().slice(0, 10)
|
||||||
|
return dow === 0 || dow === 6 || holidays.has(iso)
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorResponse(code: string, message: string, status = 422): Response {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: { code, message } }),
|
||||||
|
{ status, headers: { 'Content-Type': 'application/json' } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.serve(async (req: Request) => {
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
return new Response(null, {
|
||||||
|
headers: {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method !== 'POST') {
|
||||||
|
return errorResponse('method_not_allowed', 'POST only', 405)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticate the caller via local JWT verification (no network round-trip)
|
||||||
|
const authHeader = req.headers.get('Authorization')
|
||||||
|
if (!authHeader) return errorResponse('unauthorized', 'Missing Authorization header', 401)
|
||||||
|
|
||||||
|
const token = authHeader.replace('Bearer ', '')
|
||||||
|
|
||||||
|
// Service-role client for reads + insert (bypasses RLS)
|
||||||
|
const adminClient = createClient(
|
||||||
|
Deno.env.get('SUPABASE_URL')!,
|
||||||
|
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
||||||
|
{ auth: { autoRefreshToken: false, persistSession: false } },
|
||||||
|
)
|
||||||
|
|
||||||
|
const { data: { user }, error: authError } = await adminClient.auth.getUser(token)
|
||||||
|
if (authError || !user) return errorResponse('unauthorized', 'Invalid session', 401)
|
||||||
|
|
||||||
|
const userId = user.id
|
||||||
|
|
||||||
|
// Parse body
|
||||||
|
let body: CreateReservationBody
|
||||||
|
try {
|
||||||
|
body = await req.json()
|
||||||
|
} catch {
|
||||||
|
return errorResponse('invalid_body', 'Request body must be JSON', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { boat_id, start_time, end_time, reason = '', comment = '', member_ids = [], guest_ids = [] } = body
|
||||||
|
|
||||||
|
if (!boat_id || !start_time || !end_time) {
|
||||||
|
return errorResponse('missing_fields', 'boat_id, start_time, and end_time are required', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
const startDate = new Date(start_time)
|
||||||
|
const endDate = new Date(end_time)
|
||||||
|
|
||||||
|
if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
|
||||||
|
return errorResponse('invalid_dates', 'start_time and end_time must be valid ISO 8601 timestamps', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endDate <= startDate) {
|
||||||
|
return errorResponse('invalid_dates', 'end_time must be after start_time', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 1. Load booking config ──────────────────────────────────────────────────
|
||||||
|
const { data: configRows, error: configErr } = await adminClient
|
||||||
|
.from('booking_config')
|
||||||
|
.select('key, value')
|
||||||
|
|
||||||
|
if (configErr) return errorResponse('config_error', 'Failed to load booking config', 500)
|
||||||
|
|
||||||
|
const config: BookingConfig = {
|
||||||
|
max_sessions_per_week: 2,
|
||||||
|
max_weekend_sessions_per_period: 1,
|
||||||
|
weekend_period_weeks: 2,
|
||||||
|
open_session_advance_hours: 24,
|
||||||
|
}
|
||||||
|
for (const row of configRows ?? []) {
|
||||||
|
const k = row.key as keyof BookingConfig
|
||||||
|
if (k in config) (config as Record<string, number>)[k] = Number(row.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 2. Load holidays ────────────────────────────────────────────────────────
|
||||||
|
const { data: holidayRows } = await adminClient.from('holidays').select('date')
|
||||||
|
const holidays = new Set<string>((holidayRows ?? []).map((h: { date: string }) => h.date))
|
||||||
|
|
||||||
|
// ── 3. Certification check ─────────────────────────────────────────────────
|
||||||
|
const { data: boat, error: boatErr } = await adminClient
|
||||||
|
.from('boats')
|
||||||
|
.select('required_certs, booking_available')
|
||||||
|
.eq('id', boat_id)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (boatErr || !boat) return errorResponse('not_found', 'Boat not found', 404)
|
||||||
|
if (!boat.booking_available) return errorResponse('boat_unavailable', 'This boat is currently out of service', 422)
|
||||||
|
|
||||||
|
if (boat.required_certs.length > 0) {
|
||||||
|
const { data: member } = await adminClient
|
||||||
|
.from('members')
|
||||||
|
.select('certifications')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
const memberCerts: string[] = member?.certifications ?? []
|
||||||
|
const missing = boat.required_certs.filter((c: string) => !memberCerts.includes(c))
|
||||||
|
if (missing.length > 0) {
|
||||||
|
return errorResponse(
|
||||||
|
'cert_required',
|
||||||
|
`You are not certified for this boat. Missing: ${missing.join(', ')}`,
|
||||||
|
422,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 4. Open-session window check ───────────────────────────────────────────
|
||||||
|
const advanceMs = config.open_session_advance_hours * 60 * 60 * 1000
|
||||||
|
const isOpenSession = startDate.getTime() - Date.now() <= advanceMs
|
||||||
|
|
||||||
|
if (!isOpenSession) {
|
||||||
|
// ── 5. Weekly pre-booking limit ─────────────────────────────────────────
|
||||||
|
const weekStart = isoWeekStart(startDate)
|
||||||
|
const weekEnd = new Date(weekStart.getTime() + 7 * 24 * 60 * 60 * 1000)
|
||||||
|
|
||||||
|
const { data: weekReservations } = await adminClient
|
||||||
|
.from('reservations')
|
||||||
|
.select('start_time, created_at')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.gte('start_time', weekStart.toISOString())
|
||||||
|
.lt('start_time', weekEnd.toISOString())
|
||||||
|
|
||||||
|
const preBookingsThisWeek = (weekReservations as ReservationRow[] ?? []).filter(r => {
|
||||||
|
const rStart = new Date(r.start_time).getTime()
|
||||||
|
const rCreated = new Date(r.created_at).getTime()
|
||||||
|
return (rStart - rCreated) > advanceMs
|
||||||
|
})
|
||||||
|
|
||||||
|
if (preBookingsThisWeek.length >= config.max_sessions_per_week) {
|
||||||
|
return errorResponse(
|
||||||
|
'booking_limit_weekly',
|
||||||
|
`You have reached the maximum of ${config.max_sessions_per_week} pre-booked sessions for this week.`,
|
||||||
|
422,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 6. Weekend / holiday session limit ──────────────────────────────────
|
||||||
|
if (isWeekendOrHoliday(startDate, holidays)) {
|
||||||
|
const w = weeksSince(startDate, PERIOD_EPOCH)
|
||||||
|
const periodIndex = Math.floor(w / config.weekend_period_weeks)
|
||||||
|
const periodStart = new Date(
|
||||||
|
PERIOD_EPOCH.getTime() + periodIndex * config.weekend_period_weeks * 7 * 24 * 60 * 60 * 1000,
|
||||||
|
)
|
||||||
|
const periodEnd = new Date(
|
||||||
|
periodStart.getTime() + config.weekend_period_weeks * 7 * 24 * 60 * 60 * 1000,
|
||||||
|
)
|
||||||
|
|
||||||
|
const { data: periodReservations } = await adminClient
|
||||||
|
.from('reservations')
|
||||||
|
.select('start_time, created_at')
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.gte('start_time', periodStart.toISOString())
|
||||||
|
.lt('start_time', periodEnd.toISOString())
|
||||||
|
|
||||||
|
const weekendPreBookings = (periodReservations as ReservationRow[] ?? []).filter(r => {
|
||||||
|
const rStart = new Date(r.start_time)
|
||||||
|
const rCreated = new Date(r.created_at).getTime()
|
||||||
|
return (
|
||||||
|
isWeekendOrHoliday(rStart, holidays) &&
|
||||||
|
(rStart.getTime() - rCreated) > advanceMs
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (weekendPreBookings.length >= config.max_weekend_sessions_per_period) {
|
||||||
|
return errorResponse(
|
||||||
|
'booking_limit_weekend',
|
||||||
|
`You have reached the maximum of ${config.max_weekend_sessions_per_period} weekend session(s) per ${config.weekend_period_weeks}-week period.`,
|
||||||
|
422,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 7. Insert — DB overlap constraint and cert trigger are the final safety net
|
||||||
|
const { data: reservation, error: insertErr } = await adminClient
|
||||||
|
.from('reservations')
|
||||||
|
.insert({
|
||||||
|
boat_id,
|
||||||
|
user_id: userId,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
reason,
|
||||||
|
comment,
|
||||||
|
member_ids,
|
||||||
|
guest_ids,
|
||||||
|
status: 'pending',
|
||||||
|
})
|
||||||
|
.select()
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (insertErr) {
|
||||||
|
if (insertErr.message.includes('no_overlapping_reservations') || insertErr.message.includes('overlapping')) {
|
||||||
|
return errorResponse('slot_taken', 'This slot was just booked by someone else. Please choose another.', 409)
|
||||||
|
}
|
||||||
|
if (insertErr.message.includes('certifications')) {
|
||||||
|
return errorResponse('cert_required', 'You are not certified for this boat.', 422)
|
||||||
|
}
|
||||||
|
return errorResponse('insert_failed', insertErr.message, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ reservation }),
|
||||||
|
{ status: 201, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } },
|
||||||
|
)
|
||||||
|
})
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
-- Overlap prevention for reservations using btree_gist exclusion constraint
|
||||||
|
create extension if not exists btree_gist;
|
||||||
|
|
||||||
|
alter table public.reservations
|
||||||
|
add constraint no_overlapping_reservations
|
||||||
|
exclude using gist (
|
||||||
|
boat_id with =,
|
||||||
|
tstzrange(start_time, end_time, '[)') with &&
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Function: check member has required certs for a boat
|
||||||
|
create or replace function public.member_has_cert_for_boat(p_user_id uuid, p_boat_id uuid)
|
||||||
|
returns boolean
|
||||||
|
language sql
|
||||||
|
stable
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select
|
||||||
|
case
|
||||||
|
when array_length(b.required_certs, 1) is null or array_length(b.required_certs, 1) = 0
|
||||||
|
then true
|
||||||
|
else
|
||||||
|
coalesce(
|
||||||
|
(select m.certifications @> b.required_certs
|
||||||
|
from public.members m
|
||||||
|
where m.user_id = p_user_id),
|
||||||
|
false
|
||||||
|
)
|
||||||
|
end
|
||||||
|
from public.boats b
|
||||||
|
where b.id = p_boat_id;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Trigger: enforce cert check on reservation insert
|
||||||
|
create or replace function public.enforce_reservation_cert_check()
|
||||||
|
returns trigger
|
||||||
|
language plpgsql
|
||||||
|
security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
begin
|
||||||
|
if not coalesce(public.member_has_cert_for_boat(new.user_id, new.boat_id), false) then
|
||||||
|
raise exception 'Member does not have required certifications for this boat';
|
||||||
|
end if;
|
||||||
|
return new;
|
||||||
|
end;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create trigger check_reservation_certs
|
||||||
|
before insert on public.reservations
|
||||||
|
for each row execute function public.enforce_reservation_cert_check();
|
||||||
|
|
||||||
|
grant execute on function public.member_has_cert_for_boat(uuid, uuid) to authenticated;
|
||||||
104
supabase/migrations/20260420132336_booking_rules_and_rbac.sql
Normal file
104
supabase/migrations/20260420132336_booking_rules_and_rbac.sql
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- BOOKING CONFIG: configurable rule parameters (read by Edge Function)
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
create table public.booking_config (
|
||||||
|
key text primary key,
|
||||||
|
value jsonb not null,
|
||||||
|
description text
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.booking_config enable row level security;
|
||||||
|
|
||||||
|
create policy "Authenticated users can read booking config" on public.booking_config
|
||||||
|
for select using (auth.role() = 'authenticated');
|
||||||
|
|
||||||
|
create policy "Admins can manage booking config" on public.booking_config
|
||||||
|
for all using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.members
|
||||||
|
where user_id = auth.uid() and role in ('admin', 'boatswain')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
insert into public.booking_config (key, value, description) values
|
||||||
|
('max_sessions_per_week', '2', 'Max pre-booked sessions per member per ISO week (Mon–Sun)'),
|
||||||
|
('max_weekend_sessions_per_period', '1', 'Max weekend/holiday sessions per alternating period'),
|
||||||
|
('weekend_period_weeks', '2', 'Number of weeks in the alternating weekend period'),
|
||||||
|
('open_session_advance_hours', '24', 'Hours before session start where pre-booking limits are waived');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- HOLIDAYS: configurable statutory holiday list
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
create table public.holidays (
|
||||||
|
date date primary key,
|
||||||
|
name text not null
|
||||||
|
);
|
||||||
|
|
||||||
|
alter table public.holidays enable row level security;
|
||||||
|
|
||||||
|
create policy "Authenticated users can read holidays" on public.holidays
|
||||||
|
for select using (auth.role() = 'authenticated');
|
||||||
|
|
||||||
|
create policy "Admins can manage holidays" on public.holidays
|
||||||
|
for all using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.members
|
||||||
|
where user_id = auth.uid() and role in ('admin', 'boatswain')
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Ontario statutory + civic holidays for 2026 sailing season
|
||||||
|
insert into public.holidays (date, name) values
|
||||||
|
('2026-05-18', 'Victoria Day'),
|
||||||
|
('2026-07-01', 'Canada Day'),
|
||||||
|
('2026-08-03', 'Civic Holiday'),
|
||||||
|
('2026-09-07', 'Labour Day'),
|
||||||
|
('2026-10-12', 'Thanksgiving');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- HELPER: is_weekend_or_holiday (used by Edge Function via RPC)
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
create or replace function public.is_weekend_or_holiday(p_date date)
|
||||||
|
returns boolean
|
||||||
|
language sql stable security definer
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select
|
||||||
|
extract(dow from p_date) in (0, 6)
|
||||||
|
or exists (select 1 from public.holidays where date = p_date);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
grant execute on function public.is_weekend_or_holiday(date) to authenticated;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- LOCK DIRECT INSERT: revoke INSERT on reservations from authenticated
|
||||||
|
--
|
||||||
|
-- Members must create reservations through the create-reservation Edge Function.
|
||||||
|
-- The Edge Function uses the service_role key (bypasses RLS).
|
||||||
|
-- Admins retain direct INSERT/UPDATE/DELETE via their existing "all" policy.
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
drop policy if exists "Users can create own reservations" on public.reservations;
|
||||||
|
|
||||||
|
-- Admins can still manage directly; members go through the Edge Function.
|
||||||
|
-- The overlap exclusion constraint and cert check trigger remain as DB-level safety nets.
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- RBAC VIEW: reservation_slots
|
||||||
|
--
|
||||||
|
-- Exposes only boat_id, start_time, end_time, status to all authenticated users.
|
||||||
|
-- Hides user_id, reason, comment, member_ids, guest_ids.
|
||||||
|
-- Members use this view to check slot availability.
|
||||||
|
-- Admins query the reservations table directly for full management.
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
create view public.reservation_slots
|
||||||
|
with (security_invoker = false)
|
||||||
|
as
|
||||||
|
select id, boat_id, start_time, end_time, status
|
||||||
|
from public.reservations;
|
||||||
|
|
||||||
|
grant select on public.reservation_slots to authenticated;
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
-- Fix infinite recursion in members RLS.
|
||||||
|
--
|
||||||
|
-- The original "Admins can read all members" and "Admins can manage all members"
|
||||||
|
-- policies check role by querying members itself, which causes infinite recursion
|
||||||
|
-- when any authenticated user accesses the members table.
|
||||||
|
--
|
||||||
|
-- Solution: SECURITY DEFINER helper functions that bypass RLS to check the caller's
|
||||||
|
-- role, then reference those functions from the policies.
|
||||||
|
|
||||||
|
create or replace function public.current_user_role()
|
||||||
|
returns text
|
||||||
|
language sql
|
||||||
|
security definer
|
||||||
|
stable
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select role from public.members where user_id = auth.uid() limit 1;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create or replace function public.current_user_has_role(roles text[])
|
||||||
|
returns boolean
|
||||||
|
language sql
|
||||||
|
security definer
|
||||||
|
stable
|
||||||
|
set search_path = public
|
||||||
|
as $$
|
||||||
|
select exists (
|
||||||
|
select 1 from public.members
|
||||||
|
where user_id = auth.uid() and role = any(roles)
|
||||||
|
);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Drop the recursive policies on members
|
||||||
|
drop policy if exists "Admins can read all members" on public.members;
|
||||||
|
drop policy if exists "Admins can manage all members" on public.members;
|
||||||
|
|
||||||
|
-- Replace with non-recursive equivalents using the SECURITY DEFINER helper
|
||||||
|
create policy "Admins can read all members" on public.members
|
||||||
|
for select using (public.current_user_has_role(array['admin', 'boatswain', 'instructor']));
|
||||||
|
|
||||||
|
create policy "Admins can manage all members" on public.members
|
||||||
|
for all using (public.current_user_has_role(array['admin']));
|
||||||
|
|
||||||
|
-- Also fix all other tables that query members inline (same recursion risk)
|
||||||
|
drop policy if exists "Admins can manage boats" on public.boats;
|
||||||
|
create policy "Admins can manage boats" on public.boats
|
||||||
|
for all using (public.current_user_has_role(array['admin', 'boatswain']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can manage interval templates" on public.interval_templates;
|
||||||
|
create policy "Admins can manage interval templates" on public.interval_templates
|
||||||
|
for all using (public.current_user_has_role(array['admin', 'boatswain']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can manage intervals" on public.intervals;
|
||||||
|
create policy "Admins can manage intervals" on public.intervals
|
||||||
|
for all using (public.current_user_has_role(array['admin', 'boatswain']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can read all reservations" on public.reservations;
|
||||||
|
create policy "Admins can read all reservations" on public.reservations
|
||||||
|
for select using (public.current_user_has_role(array['admin', 'boatswain']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can manage all reservations" on public.reservations;
|
||||||
|
create policy "Admins can manage all reservations" on public.reservations
|
||||||
|
for all using (public.current_user_has_role(array['admin', 'boatswain']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can manage reference docs" on public.reference_docs;
|
||||||
|
create policy "Admins can manage reference docs" on public.reference_docs
|
||||||
|
for all using (public.current_user_has_role(array['admin']));
|
||||||
|
|
||||||
|
-- booking_config and holidays policies (added in later migration, same pattern)
|
||||||
|
drop policy if exists "Admins can manage booking config" on public.booking_config;
|
||||||
|
create policy "Admins can manage booking config" on public.booking_config
|
||||||
|
for all using (public.current_user_has_role(array['admin']));
|
||||||
|
|
||||||
|
drop policy if exists "Admins can manage holidays" on public.holidays;
|
||||||
|
create policy "Admins can manage holidays" on public.holidays
|
||||||
|
for all using (public.current_user_has_role(array['admin']));
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Drop the overly-broad SELECT policy that allowed any authenticated user to read
|
||||||
|
-- all reservations. Non-owner visibility is now handled by the reservation_slots
|
||||||
|
-- view (security_invoker, exposes only id/boat_id/start_time/end_time/status).
|
||||||
|
drop policy if exists "Authenticated users can read non-private reservation slots" on public.reservations;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- The reservation_slots view was created with security_invoker=true, which means
|
||||||
|
-- it evaluates RLS as the calling user. After removing the broad select policy,
|
||||||
|
-- other members see 0 rows. Switch to security_definer so the view runs as the
|
||||||
|
-- owner (bypassing RLS), while still exposing only the safe columns.
|
||||||
|
|
||||||
|
drop view if exists public.reservation_slots;
|
||||||
|
|
||||||
|
create view public.reservation_slots
|
||||||
|
with (security_invoker = false)
|
||||||
|
as
|
||||||
|
select id, boat_id, start_time, end_time, status
|
||||||
|
from public.reservations;
|
||||||
|
|
||||||
|
grant select on public.reservation_slots to authenticated;
|
||||||
@@ -35,7 +35,7 @@ test.describe('Auth flow', () => {
|
|||||||
|
|
||||||
// Auth callback redirects to home (authenticated state)
|
// Auth callback redirects to home (authenticated state)
|
||||||
await expect(page).toHaveURL('/')
|
await expect(page).toHaveURL('/')
|
||||||
await expect(page.getByText('Welcome to OYS Borrow a Boat')).toBeVisible()
|
await expect(page.getByText('Upcoming Reservations')).toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
test('unauthenticated access to protected route redirects to splash', async ({ page }) => {
|
test('unauthenticated access to protected route redirects to splash', async ({ page }) => {
|
||||||
|
|||||||
@@ -86,8 +86,7 @@ describe('magic link login — session creation', () => {
|
|||||||
// and /auth/callback calls supabase.auth.verifyOtp (hash-based) or
|
// and /auth/callback calls supabase.auth.verifyOtp (hash-based) or
|
||||||
// supabase.auth.exchangeCodeForSession (PKCE)
|
// supabase.auth.exchangeCodeForSession (PKCE)
|
||||||
const { data: sessionData, error: sessionError } = await anonClient.auth.verifyOtp({
|
const { data: sessionData, error: sessionError } = await anonClient.auth.verifyOtp({
|
||||||
email: TEST_EMAIL,
|
token_hash: token!,
|
||||||
token: token!,
|
|
||||||
type: 'magiclink',
|
type: 'magiclink',
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -104,8 +103,7 @@ describe('magic link login — session creation', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const { data: sessionData } = await anonClient.auth.verifyOtp({
|
const { data: sessionData } = await anonClient.auth.verifyOtp({
|
||||||
email: TEST_EMAIL,
|
token_hash: linkData.properties!.hashed_token!,
|
||||||
token: linkData.properties!.hashed_token!,
|
|
||||||
type: 'magiclink',
|
type: 'magiclink',
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
461
tests/integration/booking-constraints.test.ts
Normal file
461
tests/integration/booking-constraints.test.ts
Normal file
@@ -0,0 +1,461 @@
|
|||||||
|
/**
|
||||||
|
* Integration tests for booking constraints enforced by the create-reservation Edge Function
|
||||||
|
* and the database (overlap exclusion constraint, cert check trigger).
|
||||||
|
*
|
||||||
|
* Requires local Supabase running with Edge Functions served:
|
||||||
|
* npx supabase start
|
||||||
|
* npx supabase functions serve
|
||||||
|
*
|
||||||
|
* Run with:
|
||||||
|
* yarn test:integration
|
||||||
|
*
|
||||||
|
* Each describe block creates isolated test users and cleans up after itself.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||||
|
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
|
||||||
|
|
||||||
|
const SUPABASE_URL = process.env.SUPABASE_URL ?? 'http://localhost:54321'
|
||||||
|
const SUPABASE_ANON_KEY = process.env.SUPABASE_KEY ?? ''
|
||||||
|
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY ?? ''
|
||||||
|
const FUNCTIONS_URL = `${SUPABASE_URL}/functions/v1`
|
||||||
|
|
||||||
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
let adminClient: SupabaseClient
|
||||||
|
|
||||||
|
function makeAnonClient() {
|
||||||
|
return createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||||||
|
auth: { autoRefreshToken: false, persistSession: false },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createTestUser(email: string, certifications: string[] = [], role = 'member') {
|
||||||
|
const { data, error } = await adminClient.auth.admin.createUser({
|
||||||
|
email,
|
||||||
|
email_confirm: true,
|
||||||
|
})
|
||||||
|
if (error || !data.user) throw new Error(`Failed to create user: ${error?.message}`)
|
||||||
|
const userId = data.user.id
|
||||||
|
|
||||||
|
await adminClient.from('members').upsert({
|
||||||
|
user_id: userId,
|
||||||
|
email,
|
||||||
|
certifications,
|
||||||
|
role,
|
||||||
|
first_name: 'Test',
|
||||||
|
last_name: 'User',
|
||||||
|
}, { onConflict: 'user_id' })
|
||||||
|
|
||||||
|
return userId
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getSessionToken(email: string): Promise<string> {
|
||||||
|
const anon = makeAnonClient()
|
||||||
|
const { data: linkData } = await adminClient.auth.admin.generateLink({
|
||||||
|
type: 'magiclink',
|
||||||
|
email,
|
||||||
|
})
|
||||||
|
const { data: sessionData } = await anon.auth.verifyOtp({
|
||||||
|
token_hash: linkData.properties!.hashed_token!,
|
||||||
|
type: 'magiclink',
|
||||||
|
})
|
||||||
|
return sessionData.session!.access_token
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callCreateReservation(
|
||||||
|
token: string,
|
||||||
|
body: {
|
||||||
|
boat_id: string
|
||||||
|
start_time: string
|
||||||
|
end_time: string
|
||||||
|
reason?: string
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const res = await fetch(`${FUNCTIONS_URL}/create-reservation`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`,
|
||||||
|
'apikey': SUPABASE_ANON_KEY,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ reason: 'Open Sail', ...body }),
|
||||||
|
})
|
||||||
|
const json = await res.json()
|
||||||
|
return { status: res.status, body: json }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createTestBoat(requiredCerts: string[] = [], available = true): Promise<string> {
|
||||||
|
const { data, error } = await adminClient.from('boats').insert({
|
||||||
|
name: `Test Boat ${Date.now()}`,
|
||||||
|
required_certs: requiredCerts,
|
||||||
|
booking_available: available,
|
||||||
|
max_passengers: 6,
|
||||||
|
}).select('id').single()
|
||||||
|
if (error) throw new Error(`Failed to create boat: ${error.message}`)
|
||||||
|
return data.id
|
||||||
|
}
|
||||||
|
|
||||||
|
async function directInsertReservation(boatId: string, userId: string, start: string, end: string) {
|
||||||
|
const { error } = await adminClient.from('reservations').insert({
|
||||||
|
boat_id: boatId,
|
||||||
|
user_id: userId,
|
||||||
|
start_time: start,
|
||||||
|
end_time: end,
|
||||||
|
reason: 'Test',
|
||||||
|
status: 'confirmed',
|
||||||
|
})
|
||||||
|
return error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Future Monday 09:00–12:30 (within current ISO week, far enough ahead)
|
||||||
|
function futureSlot(daysAhead: number, hour = 9, endHour = 12, endMin = 30): { start_time: string; end_time: string } {
|
||||||
|
const d = new Date()
|
||||||
|
d.setUTCDate(d.getUTCDate() + daysAhead)
|
||||||
|
d.setUTCHours(hour, 0, 0, 0)
|
||||||
|
const e = new Date(d)
|
||||||
|
e.setUTCHours(endHour, endMin, 0, 0)
|
||||||
|
return { start_time: d.toISOString(), end_time: e.toISOString() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Test Suite ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
if (!SUPABASE_SERVICE_ROLE_KEY) {
|
||||||
|
throw new Error('SUPABASE_SERVICE_ROLE_KEY is required. Run: npx supabase status')
|
||||||
|
}
|
||||||
|
adminClient = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, {
|
||||||
|
auth: { autoRefreshToken: false, persistSession: false },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Overlap constraint (DB-level) ─────────────────────────────────────────────
|
||||||
|
describe('overlap constraint', () => {
|
||||||
|
const email = `test-overlap-${Date.now()}@oysqn.test`
|
||||||
|
let userId: string
|
||||||
|
let boatId: string
|
||||||
|
let token: string
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
userId = await createTestUser(email)
|
||||||
|
boatId = await createTestBoat()
|
||||||
|
token = await getSessionToken(email)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userId)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows first booking for a slot', async () => {
|
||||||
|
const slot = futureSlot(14)
|
||||||
|
const { status } = await callCreateReservation(token, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects an overlapping booking for the same boat', async () => {
|
||||||
|
// Use a different week from the first test so the weekly pre-booking limit isn't reached
|
||||||
|
const slot = futureSlot(21)
|
||||||
|
// Book once directly via admin
|
||||||
|
await directInsertReservation(boatId, userId, slot.start_time, slot.end_time)
|
||||||
|
// Second booking for same slot via Edge Function — DB exclusion constraint fires
|
||||||
|
const { status, body } = await callCreateReservation(token, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(409)
|
||||||
|
expect(body.error.code).toBe('slot_taken')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows a booking on the same boat at a different time', async () => {
|
||||||
|
// Third distinct week — no pre-booking limit conflict, different time slot
|
||||||
|
const slot = futureSlot(28, 13, 16, 30)
|
||||||
|
const { status } = await callCreateReservation(token, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Certification check (DB trigger + Edge Function) ─────────────────────────
|
||||||
|
describe('certification check', () => {
|
||||||
|
const emailNoCert = `test-nocert-${Date.now()}@oysqn.test`
|
||||||
|
const emailCert = `test-cert-${Date.now()}@oysqn.test`
|
||||||
|
let userNoCert: string
|
||||||
|
let userCert: string
|
||||||
|
let boatId: string
|
||||||
|
let tokenNoCert: string
|
||||||
|
let tokenCert: string
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
boatId = await createTestBoat(['j27'])
|
||||||
|
userNoCert = await createTestUser(emailNoCert, [])
|
||||||
|
userCert = await createTestUser(emailCert, ['j27'])
|
||||||
|
tokenNoCert = await getSessionToken(emailNoCert)
|
||||||
|
tokenCert = await getSessionToken(emailCert)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userNoCert)
|
||||||
|
await adminClient.auth.admin.deleteUser(userCert)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects booking when member lacks required cert', async () => {
|
||||||
|
const slot = futureSlot(35)
|
||||||
|
const { status, body } = await callCreateReservation(tokenNoCert, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(422)
|
||||||
|
expect(body.error.code).toBe('cert_required')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows booking when member has required cert', async () => {
|
||||||
|
const slot = futureSlot(36)
|
||||||
|
const { status } = await callCreateReservation(tokenCert, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows booking on a boat with no cert requirements', async () => {
|
||||||
|
const openBoat = await createTestBoat([])
|
||||||
|
const slot = futureSlot(37)
|
||||||
|
const { status } = await callCreateReservation(tokenNoCert, { boat_id: openBoat, ...slot })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
await adminClient.from('boats').delete().eq('id', openBoat)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Out-of-service check ──────────────────────────────────────────────────────
|
||||||
|
describe('boat out-of-service check', () => {
|
||||||
|
const email = `test-oos-${Date.now()}@oysqn.test`
|
||||||
|
let userId: string
|
||||||
|
let boatId: string
|
||||||
|
let token: string
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
boatId = await createTestBoat([], false) // booking_available = false
|
||||||
|
userId = await createTestUser(email)
|
||||||
|
token = await getSessionToken(email)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userId)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects booking when boat is out of service', async () => {
|
||||||
|
const slot = futureSlot(40)
|
||||||
|
const { status, body } = await callCreateReservation(token, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(422)
|
||||||
|
expect(body.error.code).toBe('boat_unavailable')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Weekly session limit ──────────────────────────────────────────────────────
|
||||||
|
describe('weekly session limit', () => {
|
||||||
|
const email = `test-weekly-${Date.now()}@oysqn.test`
|
||||||
|
let userId: string
|
||||||
|
let boatId: string
|
||||||
|
let token: string
|
||||||
|
|
||||||
|
// Use a fixed far-future week so existing data doesn't interfere
|
||||||
|
// Monday 2026-06-08 (week with no holidays)
|
||||||
|
const WEEK_BASE = new Date('2026-06-08T09:00:00Z')
|
||||||
|
|
||||||
|
function weekSlot(dayOffset: number, hour = 9): { start_time: string; end_time: string } {
|
||||||
|
const s = new Date(WEEK_BASE)
|
||||||
|
s.setUTCDate(WEEK_BASE.getUTCDate() + dayOffset)
|
||||||
|
s.setUTCHours(hour, 0, 0, 0)
|
||||||
|
const e = new Date(s)
|
||||||
|
e.setUTCHours(hour + 3, 30, 0, 0)
|
||||||
|
return { start_time: s.toISOString(), end_time: e.toISOString() }
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
userId = await createTestUser(email)
|
||||||
|
boatId = await createTestBoat()
|
||||||
|
token = await getSessionToken(email)
|
||||||
|
|
||||||
|
// Set max_sessions_per_week to 2 (should already be the default)
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'max_sessions_per_week', value: 2 }, { onConflict: 'key' })
|
||||||
|
// Set advance hours to 1 so our far-future bookings count as pre-bookings
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 1 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userId)
|
||||||
|
// Restore default
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 24 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows first pre-booking of the week', async () => {
|
||||||
|
const { status } = await callCreateReservation(token, { boat_id: boatId, ...weekSlot(0) })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows second pre-booking of the week', async () => {
|
||||||
|
const { status } = await callCreateReservation(token, { boat_id: boatId, ...weekSlot(1) })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects third pre-booking of the week', async () => {
|
||||||
|
const { status, body } = await callCreateReservation(token, { boat_id: boatId, ...weekSlot(2) })
|
||||||
|
expect(status).toBe(422)
|
||||||
|
expect(body.error.code).toBe('booking_limit_weekly')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Weekend session limit ─────────────────────────────────────────────────────
|
||||||
|
describe('weekend session limit', () => {
|
||||||
|
const email = `test-weekend-${Date.now()}@oysqn.test`
|
||||||
|
let userId: string
|
||||||
|
let boatId: string
|
||||||
|
let token: string
|
||||||
|
|
||||||
|
// 2026-06-13 (Saturday) and 2026-06-14 (Sunday) — same 2-week period
|
||||||
|
// 2026-06-20 (Saturday) — same 2-week period as June 13 (period weeks = 2)
|
||||||
|
const SAT1 = '2026-06-13T09:00:00Z'
|
||||||
|
const SAT1_END = '2026-06-13T12:30:00Z'
|
||||||
|
const SUN1 = '2026-06-14T09:00:00Z'
|
||||||
|
const SUN1_END = '2026-06-14T12:30:00Z'
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
userId = await createTestUser(email)
|
||||||
|
boatId = await createTestBoat()
|
||||||
|
token = await getSessionToken(email)
|
||||||
|
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'max_weekend_sessions_per_period', value: 1 }, { onConflict: 'key' })
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'weekend_period_weeks', value: 2 }, { onConflict: 'key' })
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 1 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userId)
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 24 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows first weekend booking in the period', async () => {
|
||||||
|
const { status } = await callCreateReservation(token, {
|
||||||
|
boat_id: boatId, start_time: SAT1, end_time: SAT1_END,
|
||||||
|
})
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects second weekend booking in the same period', async () => {
|
||||||
|
const { status, body } = await callCreateReservation(token, {
|
||||||
|
boat_id: boatId, start_time: SUN1, end_time: SUN1_END,
|
||||||
|
})
|
||||||
|
expect(status).toBe(422)
|
||||||
|
expect(body.error.code).toBe('booking_limit_weekend')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Open-session window bypass ────────────────────────────────────────────────
|
||||||
|
describe('open-session window bypasses pre-booking limits', () => {
|
||||||
|
const email = `test-opensession-${Date.now()}@oysqn.test`
|
||||||
|
let userId: string
|
||||||
|
let boatId: string
|
||||||
|
let token: string
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
userId = await createTestUser(email)
|
||||||
|
boatId = await createTestBoat()
|
||||||
|
token = await getSessionToken(email)
|
||||||
|
|
||||||
|
// Set limit to 0 pre-bookings/week so only open sessions can go through
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'max_sessions_per_week', value: 0 }, { onConflict: 'key' })
|
||||||
|
// Open session window: 9999 hours (everything is an open session)
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 9999 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(userId)
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'max_sessions_per_week', value: 2 }, { onConflict: 'key' })
|
||||||
|
await adminClient.from('booking_config')
|
||||||
|
.upsert({ key: 'open_session_advance_hours', value: 24 }, { onConflict: 'key' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('allows booking even when pre-booking limit is 0, because slot is within open-session window', async () => {
|
||||||
|
const slot = futureSlot(1)
|
||||||
|
const { status } = await callCreateReservation(token, { boat_id: boatId, ...slot })
|
||||||
|
expect(status).toBe(201)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── RBAC visibility: reservation_slots view ───────────────────────────────────
|
||||||
|
describe('RBAC: reservation_slots view', () => {
|
||||||
|
const emailOwner = `test-rbac-owner-${Date.now()}@oysqn.test`
|
||||||
|
const emailOther = `test-rbac-other-${Date.now()}@oysqn.test`
|
||||||
|
let ownerUserId: string
|
||||||
|
let otherUserId: string
|
||||||
|
let boatId: string
|
||||||
|
let ownerToken: string
|
||||||
|
let otherToken: string
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
boatId = await createTestBoat()
|
||||||
|
ownerUserId = await createTestUser(emailOwner)
|
||||||
|
otherUserId = await createTestUser(emailOther)
|
||||||
|
ownerToken = await getSessionToken(emailOwner)
|
||||||
|
otherToken = await getSessionToken(emailOther)
|
||||||
|
|
||||||
|
// Create a reservation for ownerUser directly via admin
|
||||||
|
const slot = futureSlot(50)
|
||||||
|
await directInsertReservation(boatId, ownerUserId, slot.start_time, slot.end_time)
|
||||||
|
})
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await adminClient.from('reservations').delete().eq('boat_id', boatId)
|
||||||
|
await adminClient.from('boats').delete().eq('id', boatId)
|
||||||
|
await adminClient.auth.admin.deleteUser(ownerUserId)
|
||||||
|
await adminClient.auth.admin.deleteUser(otherUserId)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('owner can see full reservation details', async () => {
|
||||||
|
const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||||||
|
auth: { autoRefreshToken: false, persistSession: false },
|
||||||
|
global: { headers: { Authorization: `Bearer ${ownerToken}` } },
|
||||||
|
})
|
||||||
|
const { data, error } = await client.from('reservations').select('*').eq('boat_id', boatId)
|
||||||
|
expect(error).toBeNull()
|
||||||
|
expect(data).toHaveLength(1)
|
||||||
|
expect(data![0].user_id).toBeDefined()
|
||||||
|
expect(data![0].reason).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('other member sees the slot via reservation_slots (boat/time/status only)', async () => {
|
||||||
|
const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||||||
|
auth: { autoRefreshToken: false, persistSession: false },
|
||||||
|
global: { headers: { Authorization: `Bearer ${otherToken}` } },
|
||||||
|
})
|
||||||
|
// reservation_slots view — should return the row
|
||||||
|
const { data: slots, error: slotsErr } = await client
|
||||||
|
.from('reservation_slots' as never)
|
||||||
|
.select('id, boat_id, start_time, end_time, status')
|
||||||
|
.eq('boat_id', boatId)
|
||||||
|
expect(slotsErr).toBeNull()
|
||||||
|
expect(slots).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('other member cannot see personal details of owner reservation via direct table query', async () => {
|
||||||
|
const client = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
|
||||||
|
auth: { autoRefreshToken: false, persistSession: false },
|
||||||
|
global: { headers: { Authorization: `Bearer ${otherToken}` } },
|
||||||
|
})
|
||||||
|
// Should return 0 rows — RLS "Users can read own reservations" blocks other members
|
||||||
|
const { data } = await client.from('reservations').select('*').eq('boat_id', boatId)
|
||||||
|
const ownerRows = (data ?? []).filter((r: { user_id: string }) => r.user_id === ownerUserId)
|
||||||
|
expect(ownerRows).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
6
tests/tsconfig.json
Normal file
6
tests/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"extends": "../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"types": ["node", "vitest/globals"]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ export default defineConfig({
|
|||||||
environment: 'node',
|
environment: 'node',
|
||||||
include: ['tests/integration/**/*.test.ts'],
|
include: ['tests/integration/**/*.test.ts'],
|
||||||
testTimeout: 30000,
|
testTimeout: 30000,
|
||||||
|
typecheck: { tsconfig: './tests/tsconfig.json' },
|
||||||
},
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
@@ -2847,7 +2847,7 @@
|
|||||||
dependencies:
|
dependencies:
|
||||||
undici-types "~7.18.0"
|
undici-types "~7.18.0"
|
||||||
|
|
||||||
"@types/node@>=20.0.0":
|
"@types/node@>=20.0.0", "@types/node@^25.6.0":
|
||||||
version "25.6.0"
|
version "25.6.0"
|
||||||
resolved "https://registry.yarnpkg.com/@types/node/-/node-25.6.0.tgz#4e09bad9b469871f2d0f68140198cbd714f4edca"
|
resolved "https://registry.yarnpkg.com/@types/node/-/node-25.6.0.tgz#4e09bad9b469871f2d0f68140198cbd714f4edca"
|
||||||
integrity sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==
|
integrity sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==
|
||||||
|
|||||||
Reference in New Issue
Block a user