Add, toggle, and delete services

This commit is contained in:
2025-10-18 23:35:07 +01:00
parent 0a90126f93
commit 9630afe00d
2 changed files with 360 additions and 38 deletions
+358 -36
View File
@@ -1,5 +1,4 @@
<script lang="ts">
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { authStore } from '$lib/stores/auth.svelte';
// shadcn-svelte components
@@ -491,7 +490,6 @@
let services = $state<Service[]>([]);
let servicesLoading = $state(true);
let servicesUpdating = $state<Record<string, boolean>>({});
let showServiceModal = $state(false);
// Fetch services from API
async function fetchServices() {
@@ -525,7 +523,7 @@
// Toggle service active status
async function toggleService(serviceId: string) {
servicesUpdating[serviceId] = true;
console.log('toggling', serviceId);
try {
const response = await fetch(`/api/admin/services/${serviceId}/toggle`, {
method: 'PUT',
@@ -582,11 +580,232 @@
}
}
// =============== Service Creation ===============
let showServiceModal = $state(false);
let creatingService = $state(false);
let newService = $state({
name: '',
description: '',
price: '',
duration_minutes: 60,
patch_test_duration_hours: 0,
minimum_age_required: 0
});
let serviceErrors = $state({
name: '',
price: '',
duration_minutes: '',
patch_test_duration_hours: '',
minimum_age_required: ''
});
// Correct $derived syntax
let isFormValid = $derived(
newService.name.trim() !== '' &&
/^\d+(\.\d{1,2})?$/.test(newService.price) &&
parseFloat(newService.price) > 0 &&
Number.isInteger(newService.duration_minutes) &&
newService.duration_minutes > 0 &&
Number.isInteger(newService.patch_test_duration_hours) &&
newService.patch_test_duration_hours >= 0 &&
Number.isInteger(newService.minimum_age_required) &&
newService.minimum_age_required >= 0 &&
newService.minimum_age_required <= 100
);
// Validation functions (unchanged)
function validatePrice(price: string): string {
// First check if it's a valid number format (allows only digits and one decimal point)
const validFormat = /^\d*\.?\d*$/.test(price);
if (!validFormat) {
return 'Price must be a valid number (e.g., 4.50)';
}
const numPrice = parseFloat(price);
if (isNaN(numPrice)) {
return 'Price must be a valid number';
}
if (numPrice <= 0) {
return 'Price must be greater than 0';
}
// Check for exactly 0-2 decimal places
const decimalRegex = /^\d+(\.\d{1,2})?$/;
if (!decimalRegex.test(price)) {
return 'Price can have up to 2 decimal places';
}
return '';
}
function validateDuration(value: number, field: string): string {
if (isNaN(value)) {
return 'Must be a valid number';
}
if (!Number.isInteger(value)) {
return 'Must be a whole number';
}
if (field === 'duration_minutes' && value <= 0) {
return 'Duration must be greater than 0';
}
if (field === 'patch_test_duration_hours' && value < 0) {
return 'Cannot be negative';
}
if (field === 'minimum_age_required' && (value < 0 || value > 100)) {
return 'Must be between 0 and 100';
}
return '';
}
function validateName(name: string): string {
if (!name.trim()) {
return 'Service name is required';
}
return '';
}
// Update all errors at once
function updateAllErrors() {
serviceErrors = {
name: validateName(newService.name),
price: validatePrice(newService.price),
duration_minutes: validateDuration(newService.duration_minutes, 'duration_minutes'),
patch_test_duration_hours: validateDuration(
newService.patch_test_duration_hours,
'patch_test_duration_hours'
),
minimum_age_required: validateDuration(
newService.minimum_age_required,
'minimum_age_required'
)
};
}
// Individual field validation functions
function validateNameField() {
serviceErrors.name = validateName(newService.name);
}
function validatePriceField() {
serviceErrors.price = validatePrice(newService.price);
}
function validateDurationField() {
serviceErrors.duration_minutes = validateDuration(
newService.duration_minutes,
'duration_minutes'
);
}
function validatePatchTestField() {
serviceErrors.patch_test_duration_hours = validateDuration(
newService.patch_test_duration_hours,
'patch_test_duration_hours'
);
}
function validateMinimumAgeField() {
serviceErrors.minimum_age_required = validateDuration(
newService.minimum_age_required,
'minimum_age_required'
);
}
// Create new service
function createNewService() {
// TODO: Implement service creation modal
toast.info('Service creation modal would open here');
// showServiceModal = true;
async function createService() {
// Update all errors before final validation
updateAllErrors();
// Check if any errors exist
const hasErrors = Object.values(serviceErrors).some((error) => error !== '');
if (hasErrors) {
toast.error('Please fix the validation errors before submitting');
return;
}
// Additional safety check with the derived property
if (!isFormValid) {
toast.error('Form validation failed');
return;
}
creatingService = true;
const loadingToast = toast.loading('Creating service...');
try {
const payload = {
name: newService.name.trim(),
description: newService.description.trim() || undefined,
price: parseFloat(newService.price),
duration_minutes: newService.duration_minutes,
patch_test_duration_hours: newService.patch_test_duration_hours,
minimum_age_required: newService.minimum_age_required
};
const response = await fetch('/api/admin/services', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.currentToken}`
},
body: JSON.stringify(payload)
});
if (response.ok) {
const createdService = await response.json();
toast.success('Service created successfully!', { id: loadingToast });
// Reset form and close modal
resetServiceForm();
showServiceModal = false;
// Refresh services list
await fetchServices();
} else if (response.status === 409) {
toast.error('A service with this name already exists', { id: loadingToast });
} else if (response.status === 400) {
const errorText = await response.text();
toast.error(`Validation error: ${errorText}`, { id: loadingToast });
} else {
const errorText = await response.text();
toast.error(`Failed to create service: ${errorText}`, { id: loadingToast });
}
} catch (err) {
console.error('Error creating service:', err);
toast.error('Network error creating service', { id: loadingToast });
} finally {
creatingService = false;
}
}
function resetServiceForm() {
newService = {
name: '',
description: '',
price: '',
duration_minutes: 60,
patch_test_duration_hours: 0,
minimum_age_required: 0
};
serviceErrors = {
name: '',
price: '',
duration_minutes: '',
patch_test_duration_hours: '',
minimum_age_required: ''
};
}
function openServiceModal() {
resetServiceForm();
showServiceModal = true;
}
// Fetch services on component mount
@@ -1047,7 +1266,7 @@
</Card.Header>
<Card.Content class="space-y-4">
<div class="flex items-center justify-between">
<Button onclick={createNewService}>Add Service</Button>
<Button onclick={openServiceModal}>Add Service</Button>
</div>
<!-- Desktop Table -->
@@ -1418,43 +1637,146 @@
{/if}
<!-- Booking Modal -->
{#if selectedBooking}
<Modal.Root bind:open={showBookingModal}>
{#if showServiceModal}
<!-- Add Service Modal -->
<Modal.Root bind:open={showServiceModal}>
<Modal.Content class="max-h-[90vh] max-w-sm overflow-y-auto md:max-w-lg">
<Modal.Header>
<Modal.Title class="text-lg font-semibold">Booking {selectedBooking.id}</Modal.Title>
<Modal.Title class="text-lg font-semibold">Add New Service</Modal.Title>
<Modal.Description>Create a new service that customers can book.</Modal.Description>
</Modal.Header>
<div class="px-4 pb-4">
<div>
<div class="text-sm text-gray-500">Start</div>
<div class="font-medium">{new Date(selectedBooking.start_time).toLocaleString()}</div>
<div class="mt-2 text-sm text-gray-500">Status</div>
<div class="font-medium">{selectedBooking.status}</div>
<div class="mt-2 text-sm text-gray-500">Services</div>
<div class="font-medium">{selectedBooking.services?.map((s) => s.name).join(', ')}</div>
{#if selectedBooking.user_id}
<div class="mt-2 text-sm text-gray-500">Booked by</div>
<Button
variant="link"
class="h-auto p-0"
onclick={() => {
showBookingModal = false;
openUserModal(selectedBooking!.user_id!);
}}
>
{users.find((u) => u.id === selectedBooking!.user_id)?.fn ||
selectedBooking.user_id}
</Button>
<div class="space-y-4 px-4 pb-4">
<!-- Service Name -->
<div class="space-y-2">
<label for="service-name" class="text-sm font-medium">Service Name *</label>
<Input
id="service-name"
type="text"
placeholder="e.g., Haircut, Color, Blowdry"
bind:value={newService.name}
onblur={validateNameField}
class="w-full border-red-500={serviceErrors.name}"
/>
{#if serviceErrors.name}
<p class="text-sm text-red-600">{serviceErrors.name}</p>
{/if}
</div>
<!-- Description -->
<div class="space-y-2">
<label for="service-description" class="text-sm font-medium">Description</label>
<Input
id="service-description"
type="text"
placeholder="Brief description of the service"
bind:value={newService.description}
class="w-full"
/>
</div>
<!-- Price and Duration - Side by side on desktop -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<!-- Price -->
<div class="space-y-2">
<label for="service-price" class="text-sm font-medium">Price (£) *</label>
<div class="relative">
<span class="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-gray-500">£</span
>
<Input
id="service-price"
type="number"
step="0.01"
min="0"
placeholder="0.00"
bind:value={newService.price}
onblur={validatePriceField}
class="w-full pl-8 border-red-500={serviceErrors.price}"
/>
</div>
{#if serviceErrors.price}
<p class="text-sm text-red-600">{serviceErrors.price}</p>
{/if}
</div>
<!-- Duration -->
<div class="space-y-2">
<label for="service-duration" class="text-sm font-medium">Duration (minutes) *</label>
<Input
id="service-duration"
type="number"
min="1"
step="1"
placeholder="60"
bind:value={newService.duration_minutes}
onblur={validateDurationField}
class="w-full border-red-500={serviceErrors.duration_minutes}"
/>
{#if serviceErrors.duration_minutes}
<p class="text-sm text-red-600">{serviceErrors.duration_minutes}</p>
{/if}
</div>
</div>
<!-- Patch Test and Minimum Age - Side by side on desktop -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<!-- Patch Test Duration -->
<div class="space-y-2">
<label for="patch-test-duration" class="text-sm font-medium"
>Patch Test Duration (hours)</label
>
<Input
id="patch-test-duration"
type="number"
min="0"
step="1"
placeholder="0"
bind:value={newService.patch_test_duration_hours}
onblur={validatePatchTestField}
class="w-full border-red-500={serviceErrors.patch_test_duration_hours}"
/>
{#if serviceErrors.patch_test_duration_hours}
<p class="text-sm text-red-600">{serviceErrors.patch_test_duration_hours}</p>
{/if}
<p class="text-xs text-gray-500">Hours required before service (0 for none)</p>
</div>
<!-- Minimum Age -->
<div class="space-y-2">
<label for="minimum-age" class="text-sm font-medium">Minimum Age</label>
<Input
id="minimum-age"
type="number"
min="0"
max="100"
step="1"
placeholder="0"
bind:value={newService.minimum_age_required}
onblur={validateMinimumAgeField}
class="w-full border-red-500={serviceErrors.minimum_age_required}"
/>
{#if serviceErrors.minimum_age_required}
<p class="text-sm text-red-600">{serviceErrors.minimum_age_required}</p>
{/if}
<p class="text-xs text-gray-500">0 for no age restriction</p>
</div>
</div>
</div>
<Modal.Footer class="flex items-center justify-end gap-2">
<Button onclick={() => (showBookingModal = false)}>Close</Button>
<Button
variant="outline"
onclick={() => {
showServiceModal = false;
resetServiceForm();
}}
disabled={creatingService}
>
Cancel
</Button>
<Button onclick={createService} disabled={creatingService || !isFormValid}>
{creatingService ? 'Creating...' : 'Create Service'}
</Button>
</Modal.Footer>
</Modal.Content>
</Modal.Root>