refactor: move discounts into admin panel as component, rebuild modal with proper field handling
- DiscountsManagement component integrated into admin/+page.svelte - Removed standalone /admin/discounts route - Modal rebuilt with toggle buttons for campaign type, conditional field groups - Milestone unit auto-restricted based on milestone type (bookings-only for count types, months/years for anniversary) - Mobile-first: card layout on mobile, table on desktop (md: breakpoint) - Native select elements instead of broken bits-ui Select components
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
import HolidayHours from '$lib/components/admin/HolidayHours.svelte';
|
||||
import WeeklySchedule from '$lib/components/admin/WeeklySchedule.svelte';
|
||||
import ServicesManagement from '$lib/components/admin/ServicesManagement.svelte';
|
||||
import DiscountsManagement from '$lib/components/admin/DiscountsManagement.svelte';
|
||||
import UserModal from '$lib/components/admin/UserModal.svelte';
|
||||
import BookingModal from '$lib/components/admin/BookingModal.svelte';
|
||||
|
||||
@@ -209,6 +210,48 @@
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Discounts Management Card Skeleton -->
|
||||
<div class="rounded-lg border p-6">
|
||||
<div class="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div class="space-y-2">
|
||||
<Skeleton class="h-6 w-40" />
|
||||
<Skeleton class="h-4 w-64" />
|
||||
</div>
|
||||
<Skeleton class="h-10 w-32" />
|
||||
</div>
|
||||
<div class="mt-4 hidden w-full overflow-x-auto md:block">
|
||||
<table class="w-full table-auto border-collapse text-sm">
|
||||
<thead>
|
||||
<tr class="border-b text-left text-xs text-gray-500">
|
||||
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-20" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-40" /></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each Array(2) as _, i (i)}
|
||||
<tr class="border-b">
|
||||
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-24" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-16" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
|
||||
<td class="py-3">
|
||||
<div class="flex justify-end gap-2">
|
||||
<Skeleton class="h-8 w-16" />
|
||||
<Skeleton class="h-8 w-16" />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if pageState === 'authorized'}
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-6">
|
||||
@@ -227,6 +270,7 @@
|
||||
<HolidayHours />
|
||||
<WeeklySchedule />
|
||||
<ServicesManagement />
|
||||
<DiscountsManagement />
|
||||
</div>
|
||||
|
||||
<!-- Modals -->
|
||||
|
||||
@@ -1,978 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { authStore } from '$lib/stores/auth.svelte';
|
||||
import { browser } from '$app/environment';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
// UI Components
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import * as Label from '$lib/components/ui/label';
|
||||
import * as Textarea from '$lib/components/ui/textarea';
|
||||
import { Skeleton } from '$lib/components/ui/skeleton';
|
||||
import * as Modal from '$lib/components/ui/dialog';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
|
||||
// Types from booking.ts
|
||||
import type {
|
||||
DiscountCampaign,
|
||||
CampaignStats,
|
||||
CampaignType,
|
||||
MilestoneType,
|
||||
MilestoneUnit,
|
||||
DiscountCampaignScope,
|
||||
DiscountCampaignStatus
|
||||
} from '$lib/types/booking';
|
||||
|
||||
// =============== Auth & Permissions ===============
|
||||
let pageState = $state<'loading' | 'authorized' | 'unauthorized'>('loading');
|
||||
|
||||
$effect(() => {
|
||||
if (!browser) return;
|
||||
|
||||
if (authStore.isLoading) {
|
||||
pageState = 'loading';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authStore.isAuthenticated) {
|
||||
pageState = 'unauthorized';
|
||||
goto('/login', { replaceState: true });
|
||||
return;
|
||||
}
|
||||
|
||||
if (authStore.currentUser?.role !== 'admin') {
|
||||
pageState = 'unauthorized';
|
||||
goto('/', { replaceState: true });
|
||||
return;
|
||||
}
|
||||
|
||||
pageState = 'authorized';
|
||||
});
|
||||
|
||||
// =============== State ===============
|
||||
let campaigns = $state<DiscountCampaign[]>([]);
|
||||
let campaignsLoading = $state(true);
|
||||
let campaignActionInProgress = $state<string | null>(null);
|
||||
|
||||
// Create Modal State
|
||||
let showCreateModal = $state(false);
|
||||
let creatingCampaign = $state(false);
|
||||
let newCampaign = $state({
|
||||
name: '',
|
||||
description: '',
|
||||
campaign_type: 'time_based' as CampaignType,
|
||||
discount_percent: 10,
|
||||
scope: 'all_bookings' as DiscountCampaignScope,
|
||||
start_date: '',
|
||||
end_date: '',
|
||||
milestone_type: 'per_user_booking_count' as MilestoneType,
|
||||
milestone_value: 0,
|
||||
milestone_unit: 'bookings' as MilestoneUnit,
|
||||
max_redemptions: 0
|
||||
});
|
||||
|
||||
let formErrors = $state<Record<string, string>>({});
|
||||
|
||||
// Stats Modal State
|
||||
let showStatsModal = $state(false);
|
||||
let selectedCampaign = $state<DiscountCampaign | null>(null);
|
||||
let campaignStats = $state<CampaignStats | null>(null);
|
||||
let statsLoading = $state(false);
|
||||
|
||||
// =============== Validations ===============
|
||||
function validateName(name: string): string {
|
||||
if (!name.trim()) return 'Campaign name is required';
|
||||
if (name.length > 100) return 'Name must be 100 characters or less';
|
||||
return '';
|
||||
}
|
||||
|
||||
function validateDiscount(percent: number): string {
|
||||
if (isNaN(percent)) return 'Discount must be a valid number';
|
||||
if (percent <= 0) return 'Discount must be greater than 0';
|
||||
if (percent > 100) return 'Discount must be 100 or less';
|
||||
return '';
|
||||
}
|
||||
|
||||
function validateDates(start: string, end: string): string {
|
||||
if (!start) return 'Start date is required';
|
||||
if (!end) return 'End date is required';
|
||||
const startTime = new Date(start).getTime();
|
||||
const endTime = new Date(end).getTime();
|
||||
if (isNaN(startTime)) return 'Invalid start date format';
|
||||
if (isNaN(endTime)) return 'Invalid end date format';
|
||||
if (endTime <= startTime) return 'End date must be after start date';
|
||||
return '';
|
||||
}
|
||||
|
||||
function validateMilestone(value: number, type: MilestoneType | undefined): string {
|
||||
if (type === undefined) return '';
|
||||
if (value <= 0) return 'Milestone value must be greater than 0';
|
||||
return '';
|
||||
}
|
||||
|
||||
let isFormValid = $derived.by(() => {
|
||||
const nameError = validateName(newCampaign.name);
|
||||
const discountError = validateDiscount(newCampaign.discount_percent);
|
||||
|
||||
if (nameError || discountError) return false;
|
||||
|
||||
if (newCampaign.campaign_type === 'time_based') {
|
||||
const dateError = validateDates(newCampaign.start_date, newCampaign.end_date);
|
||||
if (dateError) return false;
|
||||
}
|
||||
|
||||
if (newCampaign.campaign_type === 'milestone') {
|
||||
const milestoneError = validateMilestone(newCampaign.milestone_value, newCampaign.milestone_type);
|
||||
if (milestoneError) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// =============== API Functions ===============
|
||||
async function fetchCampaigns() {
|
||||
campaignsLoading = true;
|
||||
try {
|
||||
const response = await fetch('/api/admin/discount-campaigns', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
campaigns = data;
|
||||
} else {
|
||||
toast.error('Failed to load campaigns');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching campaigns:', err);
|
||||
toast.error('Network error loading campaigns');
|
||||
} finally {
|
||||
campaignsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function activateCampaign(campaignId: string) {
|
||||
campaignActionInProgress = campaignId;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
body: JSON.stringify({ status: 'active' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('Campaign activated');
|
||||
await fetchCampaigns();
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
toast.error(`Failed to activate: ${errorText}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error activating campaign:', err);
|
||||
toast.error('Network error');
|
||||
} finally {
|
||||
campaignActionInProgress = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function completeCampaign(campaignId: string) {
|
||||
campaignActionInProgress = campaignId;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
body: JSON.stringify({ status: 'completed' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('Campaign completed');
|
||||
await fetchCampaigns();
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
toast.error(`Failed to complete: ${errorText}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error completing campaign:', err);
|
||||
toast.error('Network error');
|
||||
} finally {
|
||||
campaignActionInProgress = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelCampaign(campaignId: string) {
|
||||
if (!confirm('Are you sure you want to cancel this campaign? This action cannot be undone.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
campaignActionInProgress = campaignId;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('Campaign cancelled');
|
||||
await fetchCampaigns();
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
toast.error(`Failed to cancel: ${errorText}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error cancelling campaign:', err);
|
||||
toast.error('Network error');
|
||||
} finally {
|
||||
campaignActionInProgress = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCampaignStats(campaignId: string) {
|
||||
statsLoading = true;
|
||||
try {
|
||||
const response = await fetch(`/api/admin/discount-campaigns/${campaignId}/stats`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
campaignStats = await response.json();
|
||||
} else {
|
||||
toast.error('Failed to load campaign stats');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching stats:', err);
|
||||
toast.error('Network error loading stats');
|
||||
} finally {
|
||||
statsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function createCampaign() {
|
||||
// Validate
|
||||
const nameError = validateName(newCampaign.name);
|
||||
const discountError = validateDiscount(newCampaign.discount_percent);
|
||||
|
||||
if (nameError || discountError) {
|
||||
toast.error('Please fix validation errors');
|
||||
return;
|
||||
}
|
||||
|
||||
creatingCampaign = true;
|
||||
const loadingToast = toast.loading('Creating campaign...');
|
||||
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
name: newCampaign.name.trim(),
|
||||
description: newCampaign.description.trim() || undefined,
|
||||
campaign_type: newCampaign.campaign_type,
|
||||
discount_percent: newCampaign.discount_percent
|
||||
};
|
||||
|
||||
if (newCampaign.campaign_type === 'time_based') {
|
||||
payload.scope = newCampaign.scope;
|
||||
payload.start_date = new Date(newCampaign.start_date).toISOString();
|
||||
payload.end_date = new Date(newCampaign.end_date).toISOString();
|
||||
} else if (newCampaign.campaign_type === 'milestone') {
|
||||
payload.milestone_type = newCampaign.milestone_type;
|
||||
payload.milestone_value = newCampaign.milestone_value;
|
||||
payload.milestone_unit = newCampaign.milestone_unit;
|
||||
}
|
||||
|
||||
if (newCampaign.max_redemptions > 0) {
|
||||
payload.max_redemptions = newCampaign.max_redemptions;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/admin/discount-campaigns', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authStore.currentToken}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('Campaign created successfully!', { id: loadingToast });
|
||||
resetForm();
|
||||
showCreateModal = false;
|
||||
await fetchCampaigns();
|
||||
} 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: ${errorText}`, { id: loadingToast });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error creating campaign:', err);
|
||||
toast.error('Network error', { id: loadingToast });
|
||||
} finally {
|
||||
creatingCampaign = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
newCampaign = {
|
||||
name: '',
|
||||
description: '',
|
||||
campaign_type: 'time_based',
|
||||
discount_percent: 10,
|
||||
scope: 'all_bookings',
|
||||
start_date: '',
|
||||
end_date: '',
|
||||
milestone_type: 'per_user_booking_count',
|
||||
milestone_value: 0,
|
||||
milestone_unit: 'bookings',
|
||||
max_redemptions: 0
|
||||
};
|
||||
formErrors = {};
|
||||
}
|
||||
|
||||
function openCreateModal() {
|
||||
resetForm();
|
||||
showCreateModal = true;
|
||||
}
|
||||
|
||||
async function openStatsModal(campaign: DiscountCampaign) {
|
||||
selectedCampaign = campaign;
|
||||
campaignStats = null;
|
||||
showStatsModal = true;
|
||||
await fetchCampaignStats(campaign.id);
|
||||
}
|
||||
|
||||
// =============== Helpers ===============
|
||||
function getStatusBadgeVariant(status: DiscountCampaignStatus): 'default' | 'secondary' | 'destructive' | 'outline' {
|
||||
switch (status) {
|
||||
case 'draft':
|
||||
return 'secondary';
|
||||
case 'active':
|
||||
return 'default';
|
||||
case 'completed':
|
||||
return 'outline';
|
||||
case 'cancelled':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'secondary';
|
||||
}
|
||||
}
|
||||
|
||||
function getCampaignTypeLabel(type: CampaignType, milestoneType?: MilestoneType): string {
|
||||
if (type === 'time_based') return 'Time-based';
|
||||
if (type === 'milestone') {
|
||||
switch (milestoneType) {
|
||||
case 'per_user_booking_count':
|
||||
return 'Milestone: Per-user';
|
||||
case 'global_booking_count':
|
||||
return 'Milestone: Global';
|
||||
case 'anniversary':
|
||||
return 'Milestone: Anniversary';
|
||||
default:
|
||||
return 'Milestone';
|
||||
}
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
// =============== Lifecycle ===============
|
||||
$effect(() => {
|
||||
if (pageState === 'authorized') {
|
||||
fetchCampaigns();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if pageState === 'loading'}
|
||||
<!-- Loading Skeleton -->
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-6">
|
||||
<div class="mb-8 flex items-center justify-between">
|
||||
<div class="space-y-2">
|
||||
<Skeleton class="h-8 w-64" />
|
||||
<Skeleton class="h-4 w-96" />
|
||||
</div>
|
||||
<Skeleton class="h-10 w-40" />
|
||||
</div>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Skeleton class="h-6 w-48" />
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<table class="w-full table-auto">
|
||||
<thead>
|
||||
<tr class="border-b text-left text-xs text-gray-500">
|
||||
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-20" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-24" /></th>
|
||||
<th class="py-3"><Skeleton class="h-4 w-16" /></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each Array(3) as _, i (i)}
|
||||
<tr class="border-b">
|
||||
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
|
||||
<td class="py-3"><Skeleton class="h-5 w-20" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-12" /></td>
|
||||
<td class="py-3"><Skeleton class="h-5 w-16" /></td>
|
||||
<td class="py-3"><Skeleton class="h-4 w-8" /></td>
|
||||
<td class="py-3">
|
||||
<div class="flex gap-2">
|
||||
<Skeleton class="h-8 w-20" />
|
||||
<Skeleton class="h-8 w-16" />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
{:else if pageState === 'authorized'}
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-6">
|
||||
<!-- Header -->
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Discount Campaigns</h1>
|
||||
<p class="text-gray-600">Create and manage discount campaigns for your customers</p>
|
||||
</div>
|
||||
<Button onclick={openCreateModal}>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
class="mr-2 h-4 w-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
>
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
Create Campaign
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Campaigns List -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title>All Campaigns</Card.Title>
|
||||
<Card.Description>View and manage your discount campaigns</Card.Description>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
<!-- Desktop Table -->
|
||||
<div class="hidden w-full overflow-x-auto md:block">
|
||||
<table class="w-full table-auto border-collapse text-sm">
|
||||
<thead>
|
||||
<tr class="border-b text-left text-xs text-gray-500">
|
||||
<th class="w-[25%] py-3 font-medium">Name</th>
|
||||
<th class="w-[15%] py-3 font-medium">Type</th>
|
||||
<th class="w-[10%] py-3 text-right font-medium">Discount</th>
|
||||
<th class="w-[12%] py-3 text-center font-medium">Status</th>
|
||||
<th class="w-[12%] py-3 text-center font-medium">Redeemed</th>
|
||||
<th class="w-[26%] py-3 text-center font-medium">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#if campaignsLoading}
|
||||
{#each Array(3) as _, i (i)}
|
||||
<tr class="border-b">
|
||||
<td class="py-3"><Skeleton class="h-4 w-32" /></td>
|
||||
<td class="py-3"><Skeleton class="h-5 w-20" /></td>
|
||||
<td class="py-3 text-right"><Skeleton class="ml-auto h-4 w-12" /></td>
|
||||
<td class="py-3 text-center"><Skeleton class="mx-auto h-5 w-16" /></td>
|
||||
<td class="py-3 text-center"><Skeleton class="mx-auto h-4 w-8" /></td>
|
||||
<td class="py-3">
|
||||
<div class="flex justify-center gap-2">
|
||||
<Skeleton class="h-8 w-20" />
|
||||
<Skeleton class="h-8 w-16" />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
{:else}
|
||||
{#each campaigns as campaign (campaign.id)}
|
||||
<tr class="border-b hover:bg-gray-50">
|
||||
<td class="py-3">
|
||||
<div class="font-medium">{campaign.name}</div>
|
||||
{#if campaign.description}
|
||||
<div class="text-xs text-gray-500 line-clamp-1">{campaign.description}</div>
|
||||
{/if}
|
||||
</td>
|
||||
<td class="py-3">
|
||||
<span
|
||||
class="inline-flex items-center rounded-full bg-blue-100 px-2 py-1 text-xs font-medium text-blue-800"
|
||||
>
|
||||
{getCampaignTypeLabel(
|
||||
campaign.campaign_type,
|
||||
campaign.milestone_type as MilestoneType
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 text-right font-medium">{campaign.discount_percent}%</td>
|
||||
<td class="py-3 text-center">
|
||||
<span
|
||||
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {getStatusBadgeVariant(
|
||||
campaign.status
|
||||
) === 'default'
|
||||
? 'bg-emerald-100 text-emerald-800'
|
||||
: getStatusBadgeVariant(campaign.status) === 'secondary'
|
||||
? 'bg-gray-100 text-gray-800'
|
||||
: getStatusBadgeVariant(campaign.status) === 'destructive'
|
||||
? 'bg-red-100 text-red-800'
|
||||
: 'bg-blue-100 text-blue-800'}"
|
||||
>
|
||||
{campaign.status}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 text-center">
|
||||
{campaign.times_redeemed}
|
||||
{campaign.max_redemptions ? `/${campaign.max_redemptions}` : '/∞'}
|
||||
</td>
|
||||
<td class="py-3">
|
||||
<div class="flex justify-center gap-2">
|
||||
{#if campaign.status === 'draft'}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => activateCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
>
|
||||
{campaignActionInProgress === campaign.id
|
||||
? '...'
|
||||
: 'Activate'}
|
||||
</Button>
|
||||
{:else if campaign.status === 'active'}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => completeCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
>
|
||||
{campaignActionInProgress === campaign.id
|
||||
? '...'
|
||||
: 'Complete'}
|
||||
</Button>
|
||||
{:else}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled
|
||||
class="opacity-50"
|
||||
>
|
||||
{campaign.status}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => openStatsModal(campaign)}
|
||||
>
|
||||
Stats
|
||||
</Button>
|
||||
{#if campaign.status !== 'cancelled'}
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onclick={() => cancelCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
{/if}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Mobile Cards -->
|
||||
<div class="space-y-4 md:hidden">
|
||||
{#if campaignsLoading}
|
||||
{#each Array(3) as _, i (i)}
|
||||
<div class="rounded-lg border p-4">
|
||||
<div class="space-y-3">
|
||||
<Skeleton class="h-5 w-32" />
|
||||
<Skeleton class="h-4 w-48" />
|
||||
<div class="flex gap-2">
|
||||
<Skeleton class="h-8 w-16" />
|
||||
<Skeleton class="h-8 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{:else}
|
||||
{#each campaigns as campaign (campaign.id)}
|
||||
<div class="rounded-lg border p-4 hover:bg-gray-50">
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 class="font-medium">{campaign.name}</h3>
|
||||
{#if campaign.description}
|
||||
<p class="text-sm text-gray-500">{campaign.description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
<span
|
||||
class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium {getStatusBadgeVariant(
|
||||
campaign.status
|
||||
) === 'default'
|
||||
? 'bg-emerald-100 text-emerald-800'
|
||||
: getStatusBadgeVariant(campaign.status) === 'secondary'
|
||||
? 'bg-gray-100 text-gray-800'
|
||||
: getStatusBadgeVariant(campaign.status) === 'destructive'
|
||||
? 'bg-red-100 text-red-800'
|
||||
: 'bg-blue-100 text-blue-800'}"
|
||||
>
|
||||
{campaign.status}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2 text-sm">
|
||||
<span class="font-medium">{campaign.discount_percent}% off</span>
|
||||
<span class="text-gray-500">•</span>
|
||||
<span class="text-gray-600">
|
||||
{getCampaignTypeLabel(
|
||||
campaign.campaign_type,
|
||||
campaign.milestone_type as MilestoneType
|
||||
)}
|
||||
</span>
|
||||
<span class="text-gray-500">•</span>
|
||||
<span class="text-gray-600">
|
||||
{campaign.times_redeemed}
|
||||
{campaign.max_redemptions ? `/${campaign.max_redemptions}` : '/∞'}
|
||||
redeemed
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2 pt-2">
|
||||
{#if campaign.status === 'draft'}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => activateCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
class="flex-1"
|
||||
>
|
||||
{campaignActionInProgress === campaign.id ? '...' : 'Activate'}
|
||||
</Button>
|
||||
{:else if campaign.status === 'active'}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => completeCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
class="flex-1"
|
||||
>
|
||||
{campaignActionInProgress === campaign.id ? '...' : 'Complete'}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onclick={() => openStatsModal(campaign)}
|
||||
class="flex-1"
|
||||
>
|
||||
Stats
|
||||
</Button>
|
||||
{#if campaign.status !== 'cancelled'}
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onclick={() => cancelCampaign(campaign.id)}
|
||||
disabled={campaignActionInProgress === campaign.id}
|
||||
class="flex-1"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if !campaignsLoading && campaigns.length === 0}
|
||||
<div class="py-8 text-center text-gray-500">
|
||||
No campaigns found. Click "Create Campaign" to create your first campaign.
|
||||
</div>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
|
||||
<!-- Create Campaign Modal -->
|
||||
<Modal.Root bind:open={showCreateModal}>
|
||||
<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">Create Campaign</Modal.Title>
|
||||
<Modal.Description>Create a new discount campaign for your customers.</Modal.Description>
|
||||
</Modal.Header>
|
||||
|
||||
<div class="space-y-4 px-4 pb-4">
|
||||
<!-- Campaign Name -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="campaign-name">Campaign Name *</Label.Root>
|
||||
<Input
|
||||
id="campaign-name"
|
||||
type="text"
|
||||
maxlength={100}
|
||||
placeholder="e.g., Summer Sale, New Year Discount"
|
||||
bind:value={newCampaign.name}
|
||||
/>
|
||||
{#if formErrors.name}
|
||||
<p class="text-sm text-red-600">{formErrors.name}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="milestone-unit">Milestone Unit</Label.Root>
|
||||
<Select.Root type="single" value={newCampaign.milestone_unit} onValueChange={(v: string) => { newCampaign.milestone_unit = v as MilestoneUnit; }}>
|
||||
<Select.Trigger id="milestone-unit" disabled />
|
||||
<Select.Content>
|
||||
<Select.Item value="bookings">Bookings</Select.Item>
|
||||
<Select.Item value="months">Months</Select.Item>
|
||||
<Select.Item value="years">Years</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
<!-- Campaign Type -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="campaign-type">Campaign Type *</Label.Root>
|
||||
<Select.Root type="single" value={newCampaign.campaign_type} onValueChange={(v: string) => { newCampaign.campaign_type = v as CampaignType; }}>
|
||||
<Select.Trigger id="campaign-type" />
|
||||
<Select.Content>
|
||||
<Select.Item value="time_based">Time-based</Select.Item>
|
||||
<Select.Item value="milestone">Milestone</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
<!-- Discount Percent -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="discount-percent">Discount Percent *</Label.Root>
|
||||
<Input
|
||||
id="discount-percent"
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
bind:value={newCampaign.discount_percent}
|
||||
/>
|
||||
<p class="text-xs text-gray-500">Percentage off the booking total</p>
|
||||
</div>
|
||||
|
||||
<!-- Conditional Fields: Time-based -->
|
||||
{#if newCampaign.campaign_type === 'time_based'}
|
||||
<!-- Scope -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="scope">Scope</Label.Root>
|
||||
<Select.Root type="single" value={newCampaign.scope} onValueChange={(v: string) => { newCampaign.scope = v as DiscountCampaignScope; }}>
|
||||
<Select.Trigger id="scope" />
|
||||
<Select.Content>
|
||||
<Select.Item value="all_bookings">All bookings</Select.Item>
|
||||
<Select.Item value="first_booking_only">First booking only</Select.Item>
|
||||
<Select.Item value="new_customers_only">New customers only</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
<!-- Start Date -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="start-date">Start Date *</Label.Root>
|
||||
<Input
|
||||
id="start-date"
|
||||
type="datetime-local"
|
||||
bind:value={newCampaign.start_date}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- End Date -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="end-date">End Date *</Label.Root>
|
||||
<Input
|
||||
id="end-date"
|
||||
type="datetime-local"
|
||||
bind:value={newCampaign.end_date}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Conditional Fields: Milestone -->
|
||||
{#if newCampaign.campaign_type === 'milestone'}
|
||||
<!-- Milestone Type -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="milestone-type">Milestone Type *</Label.Root>
|
||||
<Select.Root type="single" value={newCampaign.milestone_type} onValueChange={(v: string) => {
|
||||
newCampaign.milestone_type = v as MilestoneType;
|
||||
if (v === 'anniversary') {
|
||||
newCampaign.milestone_unit = 'years';
|
||||
} else if (v === 'global_booking_count') {
|
||||
newCampaign.milestone_unit = 'bookings';
|
||||
} else {
|
||||
newCampaign.milestone_unit = 'bookings';
|
||||
}
|
||||
}}>
|
||||
<Select.Trigger id="milestone-type" />
|
||||
<Select.Content>
|
||||
<Select.Item value="per_user_booking_count"
|
||||
>Per-user booking count</Select.Item
|
||||
>
|
||||
<Select.Item value="global_booking_count">Global booking count</Select.Item>
|
||||
<Select.Item value="anniversary">Anniversary</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
|
||||
<!-- Milestone Value -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="milestone-value">Milestone Value *</Label.Root>
|
||||
<Input
|
||||
id="milestone-value"
|
||||
type="number"
|
||||
min="1"
|
||||
bind:value={newCampaign.milestone_value}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Milestone Unit -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="milestone-unit">Milestone Unit</Label.Root>
|
||||
<Select.Root type="single" value={newCampaign.milestone_unit} onValueChange={(v: string) => { newCampaign.milestone_unit = v as MilestoneUnit; }}>
|
||||
<Select.Trigger id="milestone-unit" disabled />
|
||||
<Select.Content>
|
||||
<Select.Item value="bookings">Bookings</Select.Item>
|
||||
<Select.Item value="months">Months</Select.Item>
|
||||
<Select.Item value="years">Years</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Max Redemptions -->
|
||||
<div class="space-y-2">
|
||||
<Label.Root for="max-redemptions">Max Redemptions</Label.Root>
|
||||
<Input
|
||||
id="max-redemptions"
|
||||
type="number"
|
||||
min="0"
|
||||
bind:value={newCampaign.max_redemptions}
|
||||
/>
|
||||
<p class="text-xs text-gray-500">Leave at 0 for unlimited</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal.Footer class="flex items-center justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={() => {
|
||||
showCreateModal = false;
|
||||
resetForm();
|
||||
}}
|
||||
disabled={creatingCampaign}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onclick={createCampaign} disabled={creatingCampaign || !isFormValid}>
|
||||
{creatingCampaign ? 'Creating...' : 'Create Campaign'}
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal.Content>
|
||||
</Modal.Root>
|
||||
|
||||
<!-- Stats Modal -->
|
||||
<Modal.Root bind:open={showStatsModal}>
|
||||
<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">
|
||||
Campaign Stats
|
||||
</Modal.Title>
|
||||
<Modal.Description>
|
||||
{selectedCampaign?.name || 'Campaign'} statistics
|
||||
</Modal.Description>
|
||||
</Modal.Header>
|
||||
|
||||
<div class="space-y-4 px-4 pb-4">
|
||||
{#if statsLoading}
|
||||
<div class="space-y-4">
|
||||
<Skeleton class="h-20 w-full" />
|
||||
<Skeleton class="h-20 w-full" />
|
||||
</div>
|
||||
{:else if campaignStats}
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<!-- Total Discount Amount -->
|
||||
<div class="rounded-lg border p-4">
|
||||
<div class="text-sm text-gray-500">Total Discount Given</div>
|
||||
<div class="text-2xl font-bold">
|
||||
£{campaignStats.total_discount_amount.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bookings Discounted -->
|
||||
<div class="rounded-lg border p-4">
|
||||
<div class="text-sm text-gray-500">Bookings Discounted</div>
|
||||
<div class="text-2xl font-bold">
|
||||
{campaignStats.booking_count}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Campaign Details -->
|
||||
<div class="rounded-lg border p-4">
|
||||
<div class="text-sm font-medium">Campaign Details</div>
|
||||
<div class="mt-2 space-y-1 text-sm">
|
||||
<div class="flex justify-between">
|
||||
<span class="text-gray-500">Discount:</span>
|
||||
<span class="font-medium">
|
||||
{campaignStats.campaign.discount_percent}%
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span class="text-gray-500">Status:</span>
|
||||
<span class="font-medium capitalize">
|
||||
{campaignStats.campaign.status}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span class="text-gray-500">Redeemed:</span>
|
||||
<span class="font-medium">
|
||||
{campaignStats.campaign.times_redeemed}
|
||||
{campaignStats.campaign.max_redemptions
|
||||
? `/${campaignStats.campaign.max_redemptions}`
|
||||
: '/∞'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="py-8 text-center text-gray-500">
|
||||
No stats available for this campaign.
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal.Footer class="flex items-center justify-end gap-2">
|
||||
<Button variant="outline" onclick={() => (showStatsModal = false)}>
|
||||
Close
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal.Content>
|
||||
</Modal.Root>
|
||||
{/if}
|
||||
Reference in New Issue
Block a user