feat(frontend): add apiFetch wrapper for automatic auth token injection
Centralizes auth token management into a reusable apiFetch() helper and getAuthHeaders() utility, eliminating inline Bearer token logic across all frontend files. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
@@ -30,6 +30,10 @@
|
||||
});
|
||||
|
||||
// Verify email address
|
||||
// TODO: `/api/verify-email` doesn't exist in the backend. The correct endpoints are
|
||||
// `POST /api/verify/generate` (send verification code) and `POST /api/verify/check` (verify code).
|
||||
// This call silently 404s. Fix required — either add the missing backend route or refactor
|
||||
// to use `/api/verify/generate` + `/api/verify/check`.
|
||||
async function verify_email() {
|
||||
const loadingToast = toast.loading('Verifying email address...');
|
||||
const response = await fetch('/api/verify-email', {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { browser } from '$app/environment';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { sanitizeText } from '$lib/utils/toast-safe';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import UserBookingModal from '$lib/components/account/UserBookingModal.svelte';
|
||||
import { isValidUKPhone, formatPhoneDisplay, toE164UK } from '$lib/utils/phone';
|
||||
import { savedCardsStore, type SavedCard } from '$lib/stores/savedCards.svelte';
|
||||
@@ -134,9 +135,8 @@
|
||||
|
||||
async function deleteCard(card: SavedCard) {
|
||||
try {
|
||||
const res = await fetch(`/api/user/payment-methods/${card.id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
const res = await apiFetch(`/api/user/payment-methods/${card.id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (res.ok) {
|
||||
toast.success('Card removed');
|
||||
@@ -259,9 +259,7 @@
|
||||
async function fetchGiftCardBalance() {
|
||||
loadingBalance = true;
|
||||
try {
|
||||
const res = await fetch('/api/user/giftcards/balance', {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const res = await apiFetch('/api/user/giftcards/balance');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
giftCardBalance = data.balance;
|
||||
@@ -280,12 +278,9 @@
|
||||
}
|
||||
redeemingGiftCard = true;
|
||||
try {
|
||||
const res = await fetch('/api/user/giftcards/redeem', {
|
||||
const res = await apiFetch('/api/user/giftcards/redeem', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code: giftCardCode })
|
||||
});
|
||||
if (res.ok) {
|
||||
@@ -334,12 +329,9 @@
|
||||
|
||||
const idempotencyKey = generateIdempotencyKey();
|
||||
|
||||
const res = await fetch('/api/user/giftcards/buy', {
|
||||
const res = await apiFetch('/api/user/giftcards/buy', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
amount: buyAmount * 100, // cents
|
||||
recipient_type: buyRecipientType,
|
||||
@@ -565,12 +557,9 @@
|
||||
}
|
||||
addingCard = true;
|
||||
try {
|
||||
const res = await fetch('/api/user/payment-methods', {
|
||||
const res = await apiFetch('/api/user/payment-methods', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
card_number: cardNum,
|
||||
expiry: newCardExpiry,
|
||||
@@ -598,9 +587,7 @@
|
||||
|
||||
async function fetchNotifPrefs() {
|
||||
try {
|
||||
const res = await fetch('/api/user/notification-preferences', {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const res = await apiFetch('/api/user/notification-preferences');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
notifPrefs.emailEnabled = data.emailEnabled ?? true;
|
||||
@@ -614,12 +601,9 @@
|
||||
|
||||
async function saveNotifPrefs() {
|
||||
try {
|
||||
await fetch('/api/user/notification-preferences', {
|
||||
await apiFetch('/api/user/notification-preferences', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(notifPrefs)
|
||||
});
|
||||
} catch {
|
||||
@@ -700,11 +684,8 @@
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', blob, 'profile.jpg');
|
||||
const uploadResponse = await fetch('/api/user/profile-picture', {
|
||||
const uploadResponse = await apiFetch('/api/user/profile-picture', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
if (uploadResponse.ok) {
|
||||
@@ -765,12 +746,9 @@
|
||||
const loadingToast = toast.loading('Updating phone number...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
const response = await apiFetch('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: userData?.firstName,
|
||||
lastName: userData?.lastName,
|
||||
@@ -868,12 +846,9 @@
|
||||
const loadingToast = toast.loading('Updating name...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
const response = await apiFetch('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: newFirstName,
|
||||
lastName: newLastName,
|
||||
@@ -947,9 +922,7 @@
|
||||
|
||||
async function fetchGdprExportStatus() {
|
||||
try {
|
||||
const res = await fetch('/api/user/gdpr-export', {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const res = await apiFetch('/api/user/gdpr-export');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.export_metadata?.exported_at) {
|
||||
@@ -975,12 +948,9 @@
|
||||
|
||||
loadingUser = true;
|
||||
try {
|
||||
const response = await fetch('/api/user/profile', {
|
||||
const response = await apiFetch('/api/user/profile', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
@@ -1017,12 +987,9 @@
|
||||
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Europe/London' });
|
||||
|
||||
// Fetch more items (e.g. 10) to ensure we find upcoming ones even if the first few are past
|
||||
const response = await fetch(`/api/bookings?start_date=${today}&per_page=10&page=1`, {
|
||||
const response = await apiFetch(`/api/bookings?start_date=${today}&per_page=10&page=1`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -1059,12 +1026,9 @@
|
||||
loadingPast = true;
|
||||
try {
|
||||
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Europe/London' });
|
||||
const response = await fetch(`/api/bookings?end_date=${today}&per_page=10&page=${page}`, {
|
||||
const response = await apiFetch(`/api/bookings?end_date=${today}&per_page=10&page=${page}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -1175,12 +1139,9 @@
|
||||
const loadingToast = toast.loading('Changing password...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/user/change-password', {
|
||||
const response = await apiFetch('/api/user/change-password', {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
current_password: passwordData.current,
|
||||
new_password: passwordData.new
|
||||
@@ -1228,11 +1189,8 @@
|
||||
const loadingToast = toast.loading('Deleting account...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/user/account', {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
const response = await apiFetch('/api/user/account', {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
@@ -1291,6 +1249,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { browser } from '$app/environment';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton';
|
||||
|
||||
@@ -122,14 +123,9 @@
|
||||
async function loadSharedData() {
|
||||
try {
|
||||
const [hoursRes, servicesRes] = await Promise.all([
|
||||
fetch('/api/scheduling/default-hours', {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
}),
|
||||
fetch('/api/admin/services', {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
apiFetch('/api/scheduling/default-hours'),
|
||||
apiFetch('/api/admin/services', {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
]);
|
||||
|
||||
@@ -165,6 +161,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
@@ -340,11 +340,8 @@
|
||||
onRefresh={async () => {
|
||||
if (!browser) return;
|
||||
try {
|
||||
const r = await fetch('/api/admin/services', {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
const r = await apiFetch('/api/admin/services', {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
if (r.ok) {
|
||||
services = await r.json();
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { cubicOut } from 'svelte/easing';
|
||||
import { browser } from '$app/environment';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Checkbox } from '$lib/components/ui/checkbox';
|
||||
@@ -138,9 +139,7 @@
|
||||
per_page: perPage.toString(),
|
||||
include_acknowledged: includeAcknowledged.toString()
|
||||
});
|
||||
const response = await fetch(`/api/admin/notifications?${params}`, {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const response = await apiFetch(`/api/admin/notifications?${params}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed: ${response.status}`);
|
||||
}
|
||||
@@ -155,21 +154,16 @@
|
||||
}
|
||||
|
||||
async function fetchBookingDetails(bookingId: string): Promise<Booking | null> {
|
||||
const response = await fetch(`/api/admin/bookings/${bookingId}`, {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const response = await apiFetch(`/api/admin/bookings/${bookingId}`);
|
||||
if (!response.ok) return null;
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function handleAction(notification: Notification) {
|
||||
if (!notification.acknowledged_at) {
|
||||
await fetch(`/api/admin/notifications/${notification.id}/acknowledge`, {
|
||||
await apiFetch(`/api/admin/notifications/${notification.id}/acknowledge`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
@@ -192,11 +186,8 @@
|
||||
}
|
||||
} else if (action === 'edit_approve' && notification.booking_id) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/admin/bookings/${notification.booking_id}/edit-request`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
}
|
||||
const response = await apiFetch(
|
||||
`/api/admin/bookings/${notification.booking_id}/edit-request`
|
||||
);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
@@ -219,12 +210,9 @@
|
||||
|
||||
async function handleAcknowledge(notification: Notification) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/notifications/${notification.id}/acknowledge`, {
|
||||
const response = await apiFetch(`/api/admin/notifications/${notification.id}/acknowledge`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
if (!response.ok) {
|
||||
toast.error('Failed to acknowledge notification');
|
||||
@@ -351,6 +339,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// ============================================================
|
||||
import { goto } from '$app/navigation';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { browser } from '$app/environment';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
@@ -230,15 +231,9 @@
|
||||
const endStr = formatDate(end);
|
||||
|
||||
const [bookingsRes, whRes, blockersRes] = await Promise.all([
|
||||
fetch(`/api/admin/bookings?start_date=${startStr}&end_date=${endStr}&per_page=500`, {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
}),
|
||||
fetch(`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`, {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
}),
|
||||
fetch(`/api/admin/time-blockers?start=${startStr}&end=${endStr}`, {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
})
|
||||
apiFetch(`/api/admin/bookings?start_date=${startStr}&end_date=${endStr}&per_page=500`),
|
||||
apiFetch(`/api/scheduling/working-hours?start=${startStr}&end=${endStr}`),
|
||||
apiFetch(`/api/admin/time-blockers?start=${startStr}&end=${endStr}`)
|
||||
]);
|
||||
|
||||
if (bookingsRes.ok) {
|
||||
@@ -445,6 +440,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
|
||||
@@ -1,397 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/stores';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { SvelteDate } from 'svelte/reactivity';
|
||||
|
||||
// Types
|
||||
type Service = {
|
||||
id: string;
|
||||
service_name: string;
|
||||
price: number;
|
||||
duration_minutes: number;
|
||||
override_price?: number;
|
||||
};
|
||||
|
||||
type Booking = {
|
||||
id: string;
|
||||
start_time: string;
|
||||
status: string;
|
||||
services: Service[];
|
||||
deposit_required: boolean;
|
||||
deposit_amount?: number;
|
||||
deposit_deadline?: string;
|
||||
duration_minutes: number;
|
||||
};
|
||||
|
||||
type PaymentSummary = {
|
||||
total_amount: number;
|
||||
paid_amount: number;
|
||||
refunded_amount: number;
|
||||
remaining_amount: number;
|
||||
total_vat_amount: number;
|
||||
total_net_amount: number;
|
||||
payments: Array<{
|
||||
id: string;
|
||||
status: string;
|
||||
amount: number;
|
||||
payment_type: string;
|
||||
}>;
|
||||
refunds: Array<{
|
||||
id: string;
|
||||
status: string;
|
||||
amount: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
// State
|
||||
let booking = $state<Booking | null>(null);
|
||||
let paymentSummary = $state<PaymentSummary | null>(null);
|
||||
let loading = $state(true);
|
||||
let error = $state<string | null>(null);
|
||||
|
||||
// Get booking ID from URL
|
||||
const bookingId = $derived($page.params.id);
|
||||
|
||||
// Derived values
|
||||
const totalDuration = $derived(
|
||||
booking?.services?.reduce((sum, s) => sum + s.duration_minutes, 0) ?? 0
|
||||
);
|
||||
|
||||
const totalPrice = $derived(booking?.services?.reduce((sum, s) => sum + s.price, 0) ?? 0);
|
||||
|
||||
const hasPaidDeposit = $derived(() => {
|
||||
if (!paymentSummary?.payments) return false;
|
||||
return paymentSummary.payments.some(
|
||||
(p) => p.status === 'completed' && (p.payment_type === 'deposit' || p.payment_type === 'full')
|
||||
);
|
||||
});
|
||||
|
||||
const hasPaidAnything = $derived(() => {
|
||||
if (!paymentSummary?.payments) return false;
|
||||
return paymentSummary.payments.some((p) => p.status === 'completed');
|
||||
});
|
||||
|
||||
// Format functions
|
||||
function formatDate(dateStr: string): string {
|
||||
const date = new SvelteDate(dateStr);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
weekday: 'long',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric'
|
||||
});
|
||||
}
|
||||
|
||||
function formatTime(dateStr: string): string {
|
||||
const date = new SvelteDate(dateStr);
|
||||
return date.toLocaleTimeString('en-GB', {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function formatDuration(minutes: number): string {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const remainingMinutes = minutes % 60;
|
||||
|
||||
if (hours === 0) {
|
||||
return `${remainingMinutes} minutes`;
|
||||
} else if (remainingMinutes === 0) {
|
||||
return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
|
||||
} else {
|
||||
return `${hours} ${hours === 1 ? 'hour' : 'hours'} ${remainingMinutes} minutes`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPounds(pounds: number): string {
|
||||
return `£${pounds.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatPence(pence: number): string {
|
||||
return `£${(pence / 100).toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatDeadline(dateStr: string): string {
|
||||
const date = new SvelteDate(dateStr);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch data
|
||||
async function fetchBookingData() {
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
try {
|
||||
// Fetch booking details
|
||||
const bookingResponse = await fetch(`/api/bookings/${bookingId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!bookingResponse.ok) {
|
||||
if (bookingResponse.status === 404) {
|
||||
throw new Error('Booking not found');
|
||||
}
|
||||
throw new Error('Failed to load booking');
|
||||
}
|
||||
|
||||
booking = await bookingResponse.json();
|
||||
|
||||
// Fetch payment summary
|
||||
const paymentResponse = await fetch(`/api/bookings/${bookingId}/payment-summary`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
|
||||
if (paymentResponse.ok) {
|
||||
paymentSummary = await paymentResponse.json();
|
||||
}
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : 'An error occurred';
|
||||
toast.error(error);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize
|
||||
$effect(() => {
|
||||
if (bookingId) {
|
||||
fetchBookingData();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Booking Confirmed - Crussell</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="mx-auto max-w-2xl p-6">
|
||||
{#if loading}
|
||||
<div class="space-y-6">
|
||||
<div class="text-center">
|
||||
<Skeleton class="mx-auto h-12 w-64" />
|
||||
<Skeleton class="mx-auto mt-2 h-6 w-48" />
|
||||
</div>
|
||||
<Card.Root>
|
||||
<Card.Content class="space-y-4 pt-6">
|
||||
<Skeleton class="h-8 w-full" />
|
||||
<Skeleton class="h-20 w-full" />
|
||||
<Skeleton class="h-16 w-full" />
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
{:else if error}
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="text-red-600">Error</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<p class="text-gray-600">{error}</p>
|
||||
<Button class="mt-4" onclick={() => (window.location.href = '/')}>Return Home</Button>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
{:else if booking}
|
||||
<div class="mb-8 text-center">
|
||||
<div
|
||||
class="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-green-100"
|
||||
>
|
||||
<svg
|
||||
class="h-10 w-10 text-green-600"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
</div>
|
||||
<h1 class="text-3xl font-bold text-gray-900">Booking Confirmed!</h1>
|
||||
<p class="mt-2 text-gray-600">Your appointment has been successfully booked</p>
|
||||
</div>
|
||||
|
||||
<Card.Root class="mb-6">
|
||||
<Card.Header>
|
||||
<Card.Title>Appointment Details</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content class="space-y-4">
|
||||
<div class="flex items-center justify-between border-b pb-4">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-500">Date</div>
|
||||
<div class="text-lg font-semibold">{formatDate(booking.start_time)}</div>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<div class="text-sm font-medium text-gray-500">Time</div>
|
||||
<div class="text-lg font-semibold">{formatTime(booking.start_time)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between border-b pb-4">
|
||||
<div class="text-sm font-medium text-gray-500">Estimated Duration</div>
|
||||
<div class="font-semibold">{formatDuration(totalDuration)}</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="mb-3 text-sm font-medium text-gray-500">Services</div>
|
||||
<div class="space-y-2">
|
||||
{#each booking.services as service (service.id)}
|
||||
<div class="flex justify-between rounded bg-gray-50 p-3">
|
||||
<div>
|
||||
<div class="font-medium">{service.service_name}</div>
|
||||
<div class="text-sm text-gray-500">
|
||||
{service.duration_minutes} mins
|
||||
</div>
|
||||
</div>
|
||||
<div class="font-semibold">
|
||||
{formatPounds(service.price)}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between border-t pt-4">
|
||||
<div class="text-lg font-semibold">Total</div>
|
||||
<div class="text-lg font-bold">{formatPounds(totalPrice)}</div>
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>Payment</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
{#if booking.deposit_required}
|
||||
{#if hasPaidDeposit()}
|
||||
<div class="flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 p-4">
|
||||
<svg
|
||||
class="h-6 w-6 text-green-600"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
<div>
|
||||
<div class="font-semibold text-green-800">Deposit Paid</div>
|
||||
<div class="text-sm text-green-700">
|
||||
Your deposit of {formatPounds(booking.deposit_amount ?? 0)} has been paid
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if paymentSummary && paymentSummary.remaining_amount > 0}
|
||||
<div class="mt-4 rounded-lg bg-gray-50 p-4">
|
||||
<div class="flex justify-between">
|
||||
<span class="text-gray-600">Remaining Balance</span>
|
||||
<span class="font-semibold">{formatPence(paymentSummary.remaining_amount)}</span>
|
||||
</div>
|
||||
<p class="mt-2 text-sm text-gray-500">
|
||||
You can pay the remaining balance on the day of your appointment
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="space-y-4">
|
||||
<div class="rounded-lg border border-amber-200 bg-amber-50 p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="font-semibold text-amber-800">Deposit Required</div>
|
||||
<div class="text-sm text-amber-700">
|
||||
To secure your booking, please pay a deposit of {formatPounds(
|
||||
booking.deposit_amount ?? 0
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-2xl font-bold text-amber-800">
|
||||
{formatPounds(booking.deposit_amount ?? 0)}
|
||||
</div>
|
||||
</div>
|
||||
{#if booking.deposit_deadline}
|
||||
<div class="mt-2 text-sm text-amber-600">
|
||||
Please pay before {formatDeadline(booking.deposit_deadline)}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Button class="w-full" onclick={() => toast.info('Payment integration coming soon')}>
|
||||
Pay Deposit Now
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="space-y-4">
|
||||
<div class="rounded-lg bg-gray-50 p-4">
|
||||
<p class="text-gray-600">
|
||||
You can pay on the day, but if you'd prefer you can pay ahead here
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if hasPaidAnything()}
|
||||
<div
|
||||
class="flex items-center gap-3 rounded-lg border border-green-200 bg-green-50 p-4"
|
||||
>
|
||||
<svg
|
||||
class="h-6 w-6 text-green-600"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<path d="M20 6L9 17l-5-5" stroke-linecap="round" stroke-linejoin="round" />
|
||||
</svg>
|
||||
<div>
|
||||
<div class="font-semibold text-green-800">Paid</div>
|
||||
<div class="text-sm text-green-700">
|
||||
{formatPence(paymentSummary?.paid_amount ?? 0)} paid
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{#if paymentSummary && paymentSummary.total_vat_amount > 0}
|
||||
<div class="mt-2 rounded-lg bg-gray-50 p-3">
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-gray-600">Net amount</span>
|
||||
<span class="font-medium">{formatPence(paymentSummary.total_net_amount)}</span>
|
||||
</div>
|
||||
<div class="flex justify-between text-sm">
|
||||
<span class="text-gray-600">VAT</span>
|
||||
<span class="font-medium">{formatPence(paymentSummary.total_vat_amount)}</span>
|
||||
</div>
|
||||
<div
|
||||
class="mt-1 flex justify-between border-t border-gray-200 pt-1 text-sm font-semibold"
|
||||
>
|
||||
<span class="text-gray-800">Total paid</span>
|
||||
<span class="text-gray-800">{formatPence(paymentSummary.paid_amount)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<Button class="w-full" onclick={() => toast.info('Payment integration coming soon')}>
|
||||
Pay Now
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<div class="mt-6 flex flex-col gap-4 sm:flex-row sm:justify-center">
|
||||
<Button variant="outline" onclick={() => (window.location.href = '/schedule')}>
|
||||
View My Bookings
|
||||
</Button>
|
||||
<Button variant="ghost" onclick={() => (window.location.href = '/')}>Return Home</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { browser } from '$app/environment';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
@@ -228,9 +229,7 @@
|
||||
async function fetchGdprData() {
|
||||
stopPolling();
|
||||
try {
|
||||
const res = await fetch('/api/user/gdpr-export', {
|
||||
headers: { Authorization: `Bearer ${authStore.currentToken}` }
|
||||
});
|
||||
const res = await apiFetch('/api/user/gdpr-export');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (data.status === 'generating') {
|
||||
@@ -481,6 +480,27 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously before any rendering, preventing a flash of protected content.
|
||||
// The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
window.location.replace('/login');
|
||||
return;
|
||||
}
|
||||
var payload = JSON.parse(atob(token.split('.')[1]));
|
||||
if (payload.exp * 1000 <= Date.now()) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<title>Your Personal Data — Crussell</title>
|
||||
</svelte:head>
|
||||
|
||||
|
||||
@@ -270,6 +270,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (token) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { SvelteDate } from 'svelte/reactivity';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
|
||||
// Types
|
||||
type Service = {
|
||||
@@ -103,11 +104,7 @@
|
||||
error = null;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/bookings/${bookingId}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
const response = await apiFetch(`/api/bookings/${bookingId}`);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
@@ -164,12 +161,9 @@
|
||||
try {
|
||||
const amountInPence = Math.round(tipAmount * 100);
|
||||
|
||||
const response = await fetch(`/api/bookings/${bookingId}/tip`, {
|
||||
const response = await apiFetch(`/api/bookings/${bookingId}/tip`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
amount: amountInPence,
|
||||
card_token: 'placeholder'
|
||||
@@ -226,6 +220,27 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously before any rendering, preventing a flash of protected content.
|
||||
// The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
window.location.replace('/login');
|
||||
return;
|
||||
}
|
||||
var payload = JSON.parse(atob(token.split('.')[1]));
|
||||
if (payload.exp * 1000 <= Date.now()) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<title>Leave a Tip - Crussell</title>
|
||||
</svelte:head>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { Button } from '$lib/components/ui/button/index.js';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton/index.js';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { formatDuration } from '$lib/utils/format';
|
||||
|
||||
type Service = {
|
||||
@@ -23,12 +23,9 @@
|
||||
async function fetchServices() {
|
||||
servicesLoading = true;
|
||||
try {
|
||||
const response = await fetch('/api/services', {
|
||||
const response = await apiFetch('/api/services', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { resolve } from '$app/paths';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { ensureBusinessInfo, getBusinessInfo } from '$lib/stores/businessInfo.svelte';
|
||||
import { browser } from '$app/environment';
|
||||
import { toast } from 'svelte-sonner';
|
||||
@@ -39,11 +40,8 @@
|
||||
loading = true;
|
||||
try {
|
||||
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Europe/London' });
|
||||
const response = await fetch(`/api/bookings?start_date=${today}&per_page=50&page=1`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
const response = await apiFetch(`/api/bookings?start_date=${today}&per_page=50&page=1`, {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
if (!response.ok) {
|
||||
toast.error('Failed to load bookings');
|
||||
@@ -180,6 +178,30 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously before any rendering, preventing a flash of protected content.
|
||||
// The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
window.location.replace('/login');
|
||||
return;
|
||||
}
|
||||
var payload = JSON.parse(atob(token.split('.')[1]));
|
||||
if (payload.exp * 1000 <= Date.now()) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</svelte:head>
|
||||
|
||||
{#if pageState === 'loading'}
|
||||
<div class="mx-auto max-w-4xl px-4 py-8 md:px-8 md:py-12">
|
||||
<div class="animate-pulse space-y-6">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { goto } from '$app/navigation';
|
||||
import { browser } from '$app/environment';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { apiFetch } from '$lib/utils/api';
|
||||
import { SvelteDate } from 'svelte/reactivity';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
@@ -131,12 +132,9 @@
|
||||
try {
|
||||
const amountInPence = Math.round(tipAmount * 100);
|
||||
|
||||
const response = await fetch(`/api/bookings/${booking.id}/tip`, {
|
||||
const response = await apiFetch(`/api/bookings/${booking.id}/tip`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
amount: amountInPence,
|
||||
card_token: 'placeholder'
|
||||
@@ -192,11 +190,7 @@
|
||||
error = null;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/bookings', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
const response = await apiFetch('/api/bookings');
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load your bookings');
|
||||
@@ -231,11 +225,7 @@
|
||||
}
|
||||
|
||||
// Fetch full booking details (includes payments for tips tracking)
|
||||
const detailsResp = await fetch(`/api/bookings/${pastBooking.id}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
const detailsResp = await apiFetch(`/api/bookings/${pastBooking.id}`);
|
||||
|
||||
if (!detailsResp.ok) {
|
||||
throw new Error('Failed to load booking details');
|
||||
@@ -251,6 +241,27 @@
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously before any rendering, preventing a flash of protected content.
|
||||
// The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
window.location.replace('/login');
|
||||
return;
|
||||
}
|
||||
var payload = JSON.parse(atob(token.split('.')[1]));
|
||||
if (payload.exp * 1000 <= Date.now()) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
window.location.replace('/login');
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<title>Leave a Tip - Crussell</title>
|
||||
</svelte:head>
|
||||
|
||||
|
||||
@@ -83,6 +83,10 @@
|
||||
<svelte:head>
|
||||
<script>
|
||||
(function () {
|
||||
// Pre-hydration auth guard: reads localStorage directly because the Svelte
|
||||
// authStore hasn't initialized yet at this point (async+$state). This runs
|
||||
// synchronously in <svelte:head> before any rendering, preventing a flash
|
||||
// of protected content. The authStore handles post-hydration auth.
|
||||
try {
|
||||
var token = localStorage.getItem('authToken');
|
||||
if (!token) {
|
||||
|
||||
Reference in New Issue
Block a user