uh oh stinky
This commit is contained in:
347
components/dashboard/promotions/EditPromotionForm.tsx
Normal file
347
components/dashboard/promotions/EditPromotionForm.tsx
Normal file
@@ -0,0 +1,347 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Save, X, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { Promotion, PromotionFormData } from '@/lib/types/promotion';
|
||||
import { fetchClient } from '@/lib/client-service';
|
||||
|
||||
// Form schema validation with Zod (same as NewPromotionForm)
|
||||
const formSchema = z.object({
|
||||
code: z.string()
|
||||
.min(3, 'Code must be at least 3 characters')
|
||||
.max(20, 'Code cannot exceed 20 characters')
|
||||
.regex(/^[A-Za-z0-9]+$/, 'Only letters and numbers are allowed'),
|
||||
discountType: z.enum(['percentage', 'fixed']),
|
||||
discountValue: z.coerce.number()
|
||||
.positive('Discount value must be positive')
|
||||
.refine(val => val <= 100, {
|
||||
message: 'Percentage discount cannot exceed 100%',
|
||||
path: ['discountValue'],
|
||||
// Only validate this rule if discount type is percentage
|
||||
params: { type: 'percentage' },
|
||||
}),
|
||||
minOrderAmount: z.coerce.number()
|
||||
.min(0, 'Minimum order amount cannot be negative'),
|
||||
maxUsage: z.coerce.number()
|
||||
.nullable()
|
||||
.optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
startDate: z.string().optional(),
|
||||
endDate: z.string().nullable().optional(),
|
||||
description: z.string().max(200, 'Description cannot exceed 200 characters').optional(),
|
||||
});
|
||||
|
||||
interface EditPromotionFormProps {
|
||||
promotion: Promotion;
|
||||
onSuccess: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export default function EditPromotionForm({ promotion, onSuccess, onCancel }: EditPromotionFormProps) {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// Format dates from ISO to YYYY-MM-DD for input elements
|
||||
const formatDateForInput = (dateString: string | null) => {
|
||||
if (!dateString) return '';
|
||||
return new Date(dateString).toISOString().split('T')[0];
|
||||
};
|
||||
|
||||
// Initialize form with promotion values
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
code: promotion.code,
|
||||
discountType: promotion.discountType,
|
||||
discountValue: promotion.discountValue,
|
||||
minOrderAmount: promotion.minOrderAmount,
|
||||
maxUsage: promotion.maxUsage,
|
||||
isActive: promotion.isActive,
|
||||
description: promotion.description,
|
||||
startDate: formatDateForInput(promotion.startDate),
|
||||
endDate: formatDateForInput(promotion.endDate),
|
||||
},
|
||||
});
|
||||
|
||||
// Form submission handler
|
||||
async function onSubmit(data: z.infer<typeof formSchema>) {
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await fetchClient(`/promotions/${promotion._id}`, {
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Promotion updated successfully',
|
||||
});
|
||||
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
console.error('Error updating promotion:', error);
|
||||
// Error toast is already shown by fetchClient
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="code"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Promotion Code</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="SUMMER20"
|
||||
{...field}
|
||||
onChange={(e) => field.onChange(e.target.value.toUpperCase())}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Enter a unique code for your promotion. Only letters and numbers.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="discountType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Discount Type</FormLabel>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a discount type" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="percentage">Percentage (%)</SelectItem>
|
||||
<SelectItem value="fixed">Fixed Amount (£)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="discountValue"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Discount Value</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
step={form.watch('discountType') === 'percentage' ? '1' : '0.01'}
|
||||
min={0}
|
||||
max={form.watch('discountType') === 'percentage' ? 100 : undefined}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{form.watch('discountType') === 'percentage'
|
||||
? 'Enter a percentage (1-100%)'
|
||||
: 'Enter an amount in £'}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="minOrderAmount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Minimum Order Amount (£)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" step="0.01" min="0" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Minimum purchase required
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="maxUsage"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Maximum Usage Count</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="Unlimited"
|
||||
{...field}
|
||||
value={field.value === null ? '' : field.value}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
field.onChange(value === '' ? null : parseInt(value, 10));
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Leave empty for unlimited usage (currently used: {promotion.usageCount} times)
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="startDate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Start Date</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="endDate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>End Date (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="date"
|
||||
{...field}
|
||||
value={field.value || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
field.onChange(value === '' ? null : value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Leave empty for no expiration
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isActive"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="text-base">Active Status</FormLabel>
|
||||
<FormDescription>
|
||||
Enable or disable this promotion
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Enter a brief description for this promotion"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Internal notes about this promotion
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Updating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
Update Promotion
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
340
components/dashboard/promotions/NewPromotionForm.tsx
Normal file
340
components/dashboard/promotions/NewPromotionForm.tsx
Normal file
@@ -0,0 +1,340 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Plus, Save, X, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { PromotionFormData } from '@/lib/types/promotion';
|
||||
import { fetchClient } from '@/lib/client-service';
|
||||
|
||||
// Form schema validation with Zod
|
||||
const formSchema = z.object({
|
||||
code: z.string()
|
||||
.min(3, 'Code must be at least 3 characters')
|
||||
.max(20, 'Code cannot exceed 20 characters')
|
||||
.regex(/^[A-Za-z0-9]+$/, 'Only letters and numbers are allowed'),
|
||||
discountType: z.enum(['percentage', 'fixed']),
|
||||
discountValue: z.coerce.number()
|
||||
.positive('Discount value must be positive')
|
||||
.refine(val => val <= 100, {
|
||||
message: 'Percentage discount cannot exceed 100%',
|
||||
path: ['discountValue'],
|
||||
// Only validate this rule if discount type is percentage
|
||||
params: { type: 'percentage' },
|
||||
}),
|
||||
minOrderAmount: z.coerce.number()
|
||||
.min(0, 'Minimum order amount cannot be negative'),
|
||||
maxUsage: z.coerce.number()
|
||||
.nullable()
|
||||
.optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
startDate: z.string().optional(),
|
||||
endDate: z.string().nullable().optional(),
|
||||
description: z.string().max(200, 'Description cannot exceed 200 characters').optional(),
|
||||
});
|
||||
|
||||
interface NewPromotionFormProps {
|
||||
onSuccess: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export default function NewPromotionForm({ onSuccess, onCancel }: NewPromotionFormProps) {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// Initialize form with default values
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
code: '',
|
||||
discountType: 'percentage',
|
||||
discountValue: 10,
|
||||
minOrderAmount: 0,
|
||||
maxUsage: null,
|
||||
isActive: true,
|
||||
description: '',
|
||||
startDate: new Date().toISOString().split('T')[0], // Today
|
||||
endDate: null,
|
||||
},
|
||||
});
|
||||
|
||||
// Form submission handler
|
||||
async function onSubmit(data: z.infer<typeof formSchema>) {
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await fetchClient('/promotions', {
|
||||
method: 'POST',
|
||||
body: data,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Promotion created successfully',
|
||||
});
|
||||
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
console.error('Error creating promotion:', error);
|
||||
// Error toast is already shown by fetchClient
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="code"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Promotion Code</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="SUMMER20"
|
||||
{...field}
|
||||
onChange={(e) => field.onChange(e.target.value.toUpperCase())}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Enter a unique code for your promotion. Only letters and numbers.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="discountType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Discount Type</FormLabel>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={field.value}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a discount type" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="percentage">Percentage (%)</SelectItem>
|
||||
<SelectItem value="fixed">Fixed Amount (£)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="discountValue"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Discount Value</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
step={form.watch('discountType') === 'percentage' ? '1' : '0.01'}
|
||||
min={0}
|
||||
max={form.watch('discountType') === 'percentage' ? 100 : undefined}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
{form.watch('discountType') === 'percentage'
|
||||
? 'Enter a percentage (1-100%)'
|
||||
: 'Enter an amount in £'}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="minOrderAmount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Minimum Order Amount (£)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" step="0.01" min="0" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Minimum purchase required
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="maxUsage"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Maximum Usage Count</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
placeholder="Unlimited"
|
||||
{...field}
|
||||
value={field.value === null ? '' : field.value}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
field.onChange(value === '' ? null : parseInt(value, 10));
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Leave empty for unlimited usage
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="startDate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Start Date</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="endDate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>End Date (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="date"
|
||||
{...field}
|
||||
value={field.value || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
field.onChange(value === '' ? null : value);
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Leave empty for no expiration
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isActive"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="text-base">Active Status</FormLabel>
|
||||
<FormDescription>
|
||||
Enable or disable this promotion
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Enter a brief description for this promotion"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Internal notes about this promotion
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onCancel}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Promotion
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
286
components/dashboard/promotions/PromotionsList.tsx
Normal file
286
components/dashboard/promotions/PromotionsList.tsx
Normal file
@@ -0,0 +1,286 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Tag, RefreshCw, Trash, Edit, Check, X } from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Promotion } from '@/lib/types/promotion';
|
||||
import { fetchClient } from '@/lib/client-service';
|
||||
import NewPromotionForm from './NewPromotionForm';
|
||||
import EditPromotionForm from './EditPromotionForm';
|
||||
|
||||
export default function PromotionsList() {
|
||||
const router = useRouter();
|
||||
const [promotions, setPromotions] = useState<Promotion[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showNewDialog, setShowNewDialog] = useState(false);
|
||||
const [editingPromotion, setEditingPromotion] = useState<Promotion | null>(null);
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [promotionToDelete, setPromotionToDelete] = useState<string | null>(null);
|
||||
|
||||
// Load promotions on mount
|
||||
useEffect(() => {
|
||||
loadPromotions();
|
||||
}, []);
|
||||
|
||||
async function loadPromotions() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetchClient<Promotion[]>('/promotions');
|
||||
setPromotions(response || []);
|
||||
} catch (error) {
|
||||
console.error('Error loading promotions:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to load promotions',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function deletePromotion(id: string) {
|
||||
try {
|
||||
await fetchClient(`/promotions/${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Promotion deleted successfully',
|
||||
});
|
||||
|
||||
// Refresh the list
|
||||
loadPromotions();
|
||||
} catch (error) {
|
||||
console.error('Error deleting promotion:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to delete promotion',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setShowDeleteDialog(false);
|
||||
setPromotionToDelete(null);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOpenEditDialog(promotion: Promotion) {
|
||||
setEditingPromotion(promotion);
|
||||
}
|
||||
|
||||
function handleCloseEditDialog() {
|
||||
setEditingPromotion(null);
|
||||
}
|
||||
|
||||
function handleCreateComplete() {
|
||||
setShowNewDialog(false);
|
||||
loadPromotions();
|
||||
}
|
||||
|
||||
function handleEditComplete() {
|
||||
setEditingPromotion(null);
|
||||
loadPromotions();
|
||||
}
|
||||
|
||||
function formatDate(dateString: string | null) {
|
||||
if (!dateString) return 'No end date';
|
||||
return new Date(dateString).toLocaleDateString();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-semibold">Your Promotions</h2>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={loadPromotions} variant="outline" size="sm">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button onClick={() => setShowNewDialog(true)} size="sm">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Promotion
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<RefreshCw className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
) : promotions.length === 0 ? (
|
||||
<div className="flex flex-col justify-center items-center h-64 text-center p-6">
|
||||
<Tag className="h-12 w-12 mb-4 text-muted-foreground" />
|
||||
<h3 className="text-lg font-medium">No promotions yet</h3>
|
||||
<p className="text-muted-foreground mt-1 mb-4">
|
||||
Create your first promotion to offer discounts to your customers
|
||||
</p>
|
||||
<Button onClick={() => setShowNewDialog(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Promotion
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Value</TableHead>
|
||||
<TableHead>Min. Order</TableHead>
|
||||
<TableHead>Usage</TableHead>
|
||||
<TableHead>Valid Until</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{promotions.map((promotion) => (
|
||||
<TableRow key={promotion._id}>
|
||||
<TableCell className="font-medium">{promotion.code}</TableCell>
|
||||
<TableCell>
|
||||
{promotion.discountType === 'percentage' ? 'Percentage' : 'Fixed Amount'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{promotion.discountType === 'percentage'
|
||||
? `${promotion.discountValue}%`
|
||||
: `£${promotion.discountValue.toFixed(2)}`}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{promotion.minOrderAmount > 0
|
||||
? `£${promotion.minOrderAmount.toFixed(2)}`
|
||||
: 'None'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{promotion.usageCount} / {promotion.maxUsage || '∞'}
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(promotion.endDate)}</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={promotion.isActive ? 'default' : 'secondary'}
|
||||
className={promotion.isActive ? 'bg-green-500' : ''}
|
||||
>
|
||||
{promotion.isActive ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
onClick={() => handleOpenEditDialog(promotion)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setPromotionToDelete(promotion._id);
|
||||
setShowDeleteDialog(true);
|
||||
}}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-red-500 hover:text-red-600"
|
||||
>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* New Promotion Dialog */}
|
||||
<Dialog open={showNewDialog} onOpenChange={setShowNewDialog}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New Promotion</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a promotional code to offer discounts to your customers.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<NewPromotionForm onSuccess={handleCreateComplete} onCancel={() => setShowNewDialog(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Edit Promotion Dialog */}
|
||||
<Dialog open={!!editingPromotion} onOpenChange={() => editingPromotion && handleCloseEditDialog()}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Promotion</DialogTitle>
|
||||
<DialogDescription>
|
||||
Modify this promotional code's details.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{editingPromotion && (
|
||||
<EditPromotionForm
|
||||
promotion={editingPromotion}
|
||||
onSuccess={handleEditComplete}
|
||||
onCancel={handleCloseEditDialog}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirm Deletion</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete this promotion? This action cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowDeleteDialog(false)}
|
||||
>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => promotionToDelete && deletePromotion(promotionToDelete)}
|
||||
>
|
||||
<Trash className="h-4 w-4 mr-2" />
|
||||
Delete
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
62
components/dashboard/promotions/PromotionsPageSkeleton.tsx
Normal file
62
components/dashboard/promotions/PromotionsPageSkeleton.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
|
||||
export default function PromotionsPageSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-xl font-semibold">Your Promotions</h2>
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-9 w-24" />
|
||||
<Skeleton className="h-9 w-32" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Value</TableHead>
|
||||
<TableHead>Min. Order</TableHead>
|
||||
<TableHead>Usage</TableHead>
|
||||
<TableHead>Valid Until</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{Array.from({ length: 5 }).map((_, index) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell><Skeleton className="h-4 w-16" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-20" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-12" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-16" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-12" /></TableCell>
|
||||
<TableCell><Skeleton className="h-4 w-24" /></TableCell>
|
||||
<TableCell><Skeleton className="h-6 w-16 rounded-full" /></TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user