Compare commits
4 Commits
e593ae595b
...
84f0f3137c
| Author | SHA1 | Date | |
|---|---|---|---|
| 84f0f3137c | |||
|
|
6bcb6c5414 | ||
|
|
85afc8c840 | ||
|
|
0297e6e3e5 |
@ -11,9 +11,12 @@ import {
|
|||||||
X,
|
X,
|
||||||
Loader2,
|
Loader2,
|
||||||
User,
|
User,
|
||||||
|
Settings,
|
||||||
|
Check,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useAppTheme } from "@/components/ThemeProvider";
|
import { useAppTheme } from "@/components/ThemeProvider";
|
||||||
import { listAppointments, scheduleAppointment, rejectAppointment } from "@/lib/actions/appointments";
|
import { listAppointments, scheduleAppointment, rejectAppointment } from "@/lib/actions/appointments";
|
||||||
|
import { useAppointments } from "@/hooks/useAppointments";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@ -46,6 +49,171 @@ export default function Booking() {
|
|||||||
const { theme } = useAppTheme();
|
const { theme } = useAppTheme();
|
||||||
const isDark = theme === "dark";
|
const isDark = theme === "dark";
|
||||||
|
|
||||||
|
// Availability management
|
||||||
|
const { adminAvailability, isLoadingAdminAvailability, updateAvailability, isUpdatingAvailability, refetchAdminAvailability } = useAppointments();
|
||||||
|
const [selectedDays, setSelectedDays] = useState<number[]>([]);
|
||||||
|
const [availabilityDialogOpen, setAvailabilityDialogOpen] = useState(false);
|
||||||
|
const [dayTimeRanges, setDayTimeRanges] = useState<Record<number, { startTime: string; endTime: string }>>({});
|
||||||
|
|
||||||
|
const daysOfWeek = [
|
||||||
|
{ value: 0, label: "Monday" },
|
||||||
|
{ value: 1, label: "Tuesday" },
|
||||||
|
{ value: 2, label: "Wednesday" },
|
||||||
|
{ value: 3, label: "Thursday" },
|
||||||
|
{ value: 4, label: "Friday" },
|
||||||
|
{ value: 5, label: "Saturday" },
|
||||||
|
{ value: 6, label: "Sunday" },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Load time ranges from localStorage on mount
|
||||||
|
useEffect(() => {
|
||||||
|
const savedTimeRanges = localStorage.getItem("adminAvailabilityTimeRanges");
|
||||||
|
if (savedTimeRanges) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(savedTimeRanges);
|
||||||
|
setDayTimeRanges(parsed);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse saved time ranges:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Initialize selected days and time ranges when availability is loaded
|
||||||
|
useEffect(() => {
|
||||||
|
if (adminAvailability?.available_days) {
|
||||||
|
setSelectedDays(adminAvailability.available_days);
|
||||||
|
// Load saved time ranges or use defaults
|
||||||
|
const savedTimeRanges = localStorage.getItem("adminAvailabilityTimeRanges");
|
||||||
|
let initialRanges: Record<number, { startTime: string; endTime: string }> = {};
|
||||||
|
|
||||||
|
if (savedTimeRanges) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(savedTimeRanges);
|
||||||
|
// Only use saved ranges for days that are currently available
|
||||||
|
adminAvailability.available_days.forEach((day) => {
|
||||||
|
initialRanges[day] = parsed[day] || { startTime: "09:00", endTime: "17:00" };
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// If parsing fails, use defaults
|
||||||
|
adminAvailability.available_days.forEach((day) => {
|
||||||
|
initialRanges[day] = { startTime: "09:00", endTime: "17:00" };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No saved ranges, use defaults
|
||||||
|
adminAvailability.available_days.forEach((day) => {
|
||||||
|
initialRanges[day] = { startTime: "09:00", endTime: "17:00" };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setDayTimeRanges(initialRanges);
|
||||||
|
}
|
||||||
|
}, [adminAvailability]);
|
||||||
|
|
||||||
|
// Generate time slots for time picker
|
||||||
|
const generateTimeSlots = () => {
|
||||||
|
const slots = [];
|
||||||
|
for (let hour = 0; hour < 24; hour++) {
|
||||||
|
for (let minute = 0; minute < 60; minute += 30) {
|
||||||
|
const timeString = `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
|
||||||
|
slots.push(timeString);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
};
|
||||||
|
|
||||||
|
const timeSlotsForPicker = generateTimeSlots();
|
||||||
|
|
||||||
|
const handleDayToggle = (day: number) => {
|
||||||
|
setSelectedDays((prev) => {
|
||||||
|
const newDays = prev.includes(day)
|
||||||
|
? prev.filter((d) => d !== day)
|
||||||
|
: [...prev, day].sort();
|
||||||
|
|
||||||
|
// Initialize time range for newly added day
|
||||||
|
if (!prev.includes(day) && !dayTimeRanges[day]) {
|
||||||
|
setDayTimeRanges((prevRanges) => ({
|
||||||
|
...prevRanges,
|
||||||
|
[day]: { startTime: "09:00", endTime: "17:00" },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove time range for removed day
|
||||||
|
if (prev.includes(day)) {
|
||||||
|
setDayTimeRanges((prevRanges) => {
|
||||||
|
const newRanges = { ...prevRanges };
|
||||||
|
delete newRanges[day];
|
||||||
|
return newRanges;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return newDays;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTimeRangeChange = (day: number, field: "startTime" | "endTime", value: string) => {
|
||||||
|
setDayTimeRanges((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[day]: {
|
||||||
|
...prev[day],
|
||||||
|
[field]: value,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveAvailability = async () => {
|
||||||
|
if (selectedDays.length === 0) {
|
||||||
|
toast.error("Please select at least one available day");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate all time ranges
|
||||||
|
for (const day of selectedDays) {
|
||||||
|
const timeRange = dayTimeRanges[day];
|
||||||
|
if (!timeRange || !timeRange.startTime || !timeRange.endTime) {
|
||||||
|
toast.error(`Please set time range for ${daysOfWeek.find(d => d.value === day)?.label}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (timeRange.startTime >= timeRange.endTime) {
|
||||||
|
toast.error(`End time must be after start time for ${daysOfWeek.find(d => d.value === day)?.label}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Ensure selectedDays is an array of numbers
|
||||||
|
const daysToSave = selectedDays.map(day => Number(day)).sort();
|
||||||
|
await updateAvailability({ available_days: daysToSave });
|
||||||
|
|
||||||
|
// Save time ranges to localStorage
|
||||||
|
localStorage.setItem("adminAvailabilityTimeRanges", JSON.stringify(dayTimeRanges));
|
||||||
|
|
||||||
|
toast.success("Availability updated successfully!");
|
||||||
|
// Refresh availability data
|
||||||
|
if (refetchAdminAvailability) {
|
||||||
|
await refetchAdminAvailability();
|
||||||
|
}
|
||||||
|
setAvailabilityDialogOpen(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to update availability:", error);
|
||||||
|
const errorMessage = error instanceof Error ? error.message : "Failed to update availability";
|
||||||
|
toast.error(errorMessage);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenAvailabilityDialog = () => {
|
||||||
|
if (adminAvailability?.available_days) {
|
||||||
|
setSelectedDays(adminAvailability.available_days);
|
||||||
|
// Initialize time ranges for each day
|
||||||
|
const initialRanges: Record<number, { startTime: string; endTime: string }> = {};
|
||||||
|
adminAvailability.available_days.forEach((day) => {
|
||||||
|
initialRanges[day] = dayTimeRanges[day] || { startTime: "09:00", endTime: "17:00" };
|
||||||
|
});
|
||||||
|
setDayTimeRanges(initialRanges);
|
||||||
|
}
|
||||||
|
setAvailabilityDialogOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchBookings = async () => {
|
const fetchBookings = async () => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@ -235,7 +403,16 @@ export default function Booking() {
|
|||||||
Manage and view all appointment bookings
|
Manage and view all appointment bookings
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={handleOpenAvailabilityDialog}
|
||||||
|
variant="outline"
|
||||||
|
className={`flex items-center gap-2 ${isDark ? "border-gray-700 hover:bg-gray-800" : "border-gray-300 hover:bg-gray-50"}`}
|
||||||
|
>
|
||||||
|
<Settings className="w-4 h-4" />
|
||||||
|
Manage Availability
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Search Bar */}
|
{/* Search Bar */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search className={`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${isDark ? "text-gray-400" : "text-gray-500"}`} />
|
<Search className={`absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 ${isDark ? "text-gray-400" : "text-gray-500"}`} />
|
||||||
@ -249,6 +426,60 @@ export default function Booking() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Available Days Display Card */}
|
||||||
|
{adminAvailability && (
|
||||||
|
<div className={`mb-4 sm:mb-6 rounded-lg border p-4 sm:p-5 ${isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"}`}>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<div className={`p-2 rounded-lg ${isDark ? "bg-rose-500/20" : "bg-rose-50"}`}>
|
||||||
|
<CalendarCheck className={`w-5 h-5 ${isDark ? "text-rose-400" : "text-rose-600"}`} />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h3 className={`text-sm font-semibold mb-3 ${isDark ? "text-white" : "text-gray-900"}`}>
|
||||||
|
Weekly Availability
|
||||||
|
</h3>
|
||||||
|
{adminAvailability.available_days_display && adminAvailability.available_days_display.length > 0 ? (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{adminAvailability.available_days.map((dayNum, index) => {
|
||||||
|
const dayName = daysOfWeek.find(d => d.value === dayNum)?.label || adminAvailability.available_days_display[index];
|
||||||
|
const timeRange = dayTimeRanges[dayNum] || { startTime: "09:00", endTime: "17:00" };
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={dayNum}
|
||||||
|
className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-sm whitespace-nowrap ${
|
||||||
|
isDark
|
||||||
|
? "bg-rose-500/10 text-rose-200 border border-rose-500/20"
|
||||||
|
: "bg-rose-50 text-rose-700 border border-rose-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Check className={`w-3.5 h-3.5 shrink-0 ${isDark ? "text-rose-400" : "text-rose-600"}`} />
|
||||||
|
<span className="font-medium shrink-0">{dayName}</span>
|
||||||
|
<span className={`text-sm shrink-0 ${isDark ? "text-rose-300" : "text-rose-600"}`}>
|
||||||
|
({new Date(`2000-01-01T${timeRange.startTime}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})}{" "}
|
||||||
|
-{" "}
|
||||||
|
{new Date(`2000-01-01T${timeRange.endTime}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})})
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className={`text-sm ${isDark ? "text-gray-400" : "text-gray-500"}`}>
|
||||||
|
No availability set. Click "Manage Availability" to set your available days.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex items-center justify-center py-12">
|
<div className="flex items-center justify-center py-12">
|
||||||
<div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${isDark ? "border-gray-600" : "border-gray-400"}`}></div>
|
<div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${isDark ? "border-gray-600" : "border-gray-400"}`}></div>
|
||||||
@ -581,6 +812,202 @@ export default function Booking() {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
{/* Availability Management Dialog */}
|
||||||
|
<Dialog open={availabilityDialogOpen} onOpenChange={setAvailabilityDialogOpen}>
|
||||||
|
<DialogContent className={`max-w-2xl max-h-[90vh] overflow-y-auto ${isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"}`}>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className={`text-xl sm:text-2xl font-semibold ${isDark ? "text-white" : "text-gray-900"}`}>
|
||||||
|
Manage Weekly Availability
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-6 py-4">
|
||||||
|
{isLoadingAdminAvailability ? (
|
||||||
|
<div className="flex items-center justify-center py-8">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin text-rose-600" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{/* Days Selection with Time Ranges */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className={`text-sm font-medium mb-3 block ${isDark ? "text-gray-300" : "text-gray-700"}`}>
|
||||||
|
Available Days & Times *
|
||||||
|
</label>
|
||||||
|
<p className={`text-xs mb-3 ${isDark ? "text-gray-400" : "text-gray-500"}`}>
|
||||||
|
Select days and set time ranges for each day
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{daysOfWeek.map((day) => {
|
||||||
|
const isSelected = selectedDays.includes(day.value);
|
||||||
|
const timeRange = dayTimeRanges[day.value] || { startTime: "09:00", endTime: "17:00" };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={day.value}
|
||||||
|
className={`rounded-lg border p-4 transition-all ${
|
||||||
|
isSelected
|
||||||
|
? isDark
|
||||||
|
? "bg-rose-500/10 border-rose-500/30"
|
||||||
|
: "bg-rose-50 border-rose-200"
|
||||||
|
: isDark
|
||||||
|
? "bg-gray-700/50 border-gray-600"
|
||||||
|
: "bg-gray-50 border-gray-200"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-4 mb-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleDayToggle(day.value)}
|
||||||
|
className={`flex items-center gap-2 flex-1 ${
|
||||||
|
isSelected ? "cursor-pointer" : "cursor-pointer"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`w-5 h-5 rounded border-2 flex items-center justify-center flex-shrink-0 ${
|
||||||
|
isSelected
|
||||||
|
? isDark
|
||||||
|
? "bg-rose-600 border-rose-500"
|
||||||
|
: "bg-rose-500 border-rose-500"
|
||||||
|
: isDark
|
||||||
|
? "border-gray-500"
|
||||||
|
: "border-gray-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isSelected && <Check className="w-3 h-3 text-white" />}
|
||||||
|
</div>
|
||||||
|
<span className={`text-sm font-medium ${isDark ? "text-white" : "text-gray-900"}`}>
|
||||||
|
{day.label}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isSelected && (
|
||||||
|
<div className="mt-3 pt-3 border-t border-gray-300 dark:border-gray-600">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
{/* Start Time */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className={`text-xs font-medium ${isDark ? "text-gray-400" : "text-gray-600"}`}>
|
||||||
|
Start Time
|
||||||
|
</label>
|
||||||
|
<Select
|
||||||
|
value={timeRange.startTime}
|
||||||
|
onValueChange={(value) => handleTimeRangeChange(day.value, "startTime", value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className={`h-9 text-sm ${isDark ? "bg-gray-700 border-gray-600 text-white" : "bg-white border-gray-300"}`}>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className={isDark ? "bg-gray-800 border-gray-700" : "bg-white"}>
|
||||||
|
{timeSlotsForPicker.map((time) => (
|
||||||
|
<SelectItem
|
||||||
|
key={time}
|
||||||
|
value={time}
|
||||||
|
className={isDark ? "text-white hover:bg-gray-700" : ""}
|
||||||
|
>
|
||||||
|
{new Date(`2000-01-01T${time}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* End Time */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className={`text-xs font-medium ${isDark ? "text-gray-400" : "text-gray-600"}`}>
|
||||||
|
End Time
|
||||||
|
</label>
|
||||||
|
<Select
|
||||||
|
value={timeRange.endTime}
|
||||||
|
onValueChange={(value) => handleTimeRangeChange(day.value, "endTime", value)}
|
||||||
|
>
|
||||||
|
<SelectTrigger className={`h-9 text-sm ${isDark ? "bg-gray-700 border-gray-600 text-white" : "bg-white border-gray-300"}`}>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className={isDark ? "bg-gray-800 border-gray-700" : "bg-white"}>
|
||||||
|
{timeSlotsForPicker.map((time) => (
|
||||||
|
<SelectItem
|
||||||
|
key={time}
|
||||||
|
value={time}
|
||||||
|
className={isDark ? "text-white hover:bg-gray-700" : ""}
|
||||||
|
>
|
||||||
|
{new Date(`2000-01-01T${time}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Time Range Preview */}
|
||||||
|
<div className={`mt-2 p-2 rounded text-xs ${isDark ? "bg-gray-800/50 text-gray-300" : "bg-white text-gray-600"}`}>
|
||||||
|
{new Date(`2000-01-01T${timeRange.startTime}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})}{" "}
|
||||||
|
-{" "}
|
||||||
|
{new Date(`2000-01-01T${timeRange.endTime}`).toLocaleTimeString("en-US", {
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: true,
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
setAvailabilityDialogOpen(false);
|
||||||
|
if (adminAvailability?.available_days) {
|
||||||
|
setSelectedDays(adminAvailability.available_days);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={isUpdatingAvailability}
|
||||||
|
className={isDark ? "border-gray-700 text-gray-300 hover:bg-gray-700" : ""}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleSaveAvailability}
|
||||||
|
disabled={isUpdatingAvailability || selectedDays.length === 0}
|
||||||
|
className="bg-gradient-to-r from-rose-500 to-pink-600 hover:from-rose-600 hover:to-pink-700 text-white"
|
||||||
|
>
|
||||||
|
{isUpdatingAvailability ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||||
|
Saving...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Check className="w-4 h-4 mr-2" />
|
||||||
|
Save Availability
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import {
|
|||||||
InputOTPGroup,
|
InputOTPGroup,
|
||||||
InputOTPSlot,
|
InputOTPSlot,
|
||||||
} from "@/components/ui/input-otp";
|
} from "@/components/ui/input-otp";
|
||||||
import { Heart, Eye, EyeOff, X, Loader2, CheckCircle2 } from "lucide-react";
|
import { Heart, Eye, EyeOff, X, Loader2, CheckCircle2, Mail } from "lucide-react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
@ -34,6 +34,7 @@ function LoginContent() {
|
|||||||
const [showPassword2, setShowPassword2] = useState(false);
|
const [showPassword2, setShowPassword2] = useState(false);
|
||||||
const [rememberMe, setRememberMe] = useState(false);
|
const [rememberMe, setRememberMe] = useState(false);
|
||||||
const [registeredEmail, setRegisteredEmail] = useState("");
|
const [registeredEmail, setRegisteredEmail] = useState("");
|
||||||
|
const [showResendOtp, setShowResendOtp] = useState(false);
|
||||||
|
|
||||||
// Login form data
|
// Login form data
|
||||||
const [loginData, setLoginData] = useState<LoginInput>({
|
const [loginData, setLoginData] = useState<LoginInput>({
|
||||||
@ -164,6 +165,15 @@ function LoginContent() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errorMessage = error instanceof Error ? error.message : "Login failed. Please try again.";
|
const errorMessage = error instanceof Error ? error.message : "Login failed. Please try again.";
|
||||||
toast.error(errorMessage);
|
toast.error(errorMessage);
|
||||||
|
|
||||||
|
// Check if error is about email verification
|
||||||
|
if (errorMessage.toLowerCase().includes("verify your email") ||
|
||||||
|
errorMessage.toLowerCase().includes("email address before logging")) {
|
||||||
|
setShowResendOtp(true);
|
||||||
|
} else {
|
||||||
|
setShowResendOtp(false);
|
||||||
|
}
|
||||||
|
|
||||||
setErrors({});
|
setErrors({});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -479,6 +489,56 @@ function LoginContent() {
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Resend OTP - Show when email verification error occurs */}
|
||||||
|
{showResendOtp && (
|
||||||
|
<div className={`p-4 rounded-lg border ${isDark ? 'bg-yellow-900/20 border-yellow-800' : 'bg-yellow-50 border-yellow-200'}`}>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<Mail className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-yellow-400' : 'text-yellow-600'}`} />
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className={`text-sm font-medium ${isDark ? 'text-yellow-200' : 'text-yellow-900'}`}>
|
||||||
|
Email verification required
|
||||||
|
</p>
|
||||||
|
<p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-yellow-300' : 'text-yellow-700'}`}>
|
||||||
|
Please verify your email address before logging in. We can resend the verification code to {loginData.email}.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="link"
|
||||||
|
onClick={async () => {
|
||||||
|
if (!loginData.email) {
|
||||||
|
toast.error("Email address is required to resend OTP.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await resendOtpMutation.mutateAsync({
|
||||||
|
email: loginData.email,
|
||||||
|
context: "registration"
|
||||||
|
});
|
||||||
|
toast.success("OTP resent successfully! Please check your email.");
|
||||||
|
setShowResendOtp(false);
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Failed to resend OTP. Please try again.";
|
||||||
|
toast.error(errorMessage);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={resendOtpMutation.isPending}
|
||||||
|
className={`h-auto p-0 mt-2 text-xs sm:text-sm font-medium ${isDark ? 'text-yellow-400 hover:text-yellow-300' : 'text-yellow-700 hover:text-yellow-800'}`}
|
||||||
|
>
|
||||||
|
{resendOtpMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-3 h-3 mr-1 animate-spin inline" />
|
||||||
|
Sending...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Resend verification code"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Remember Me & Forgot Password */}
|
{/* Remember Me & Forgot Password */}
|
||||||
<div className="flex items-center justify-between text-sm">
|
<div className="flex items-center justify-between text-sm">
|
||||||
<label className="flex items-center gap-2 cursor-pointer">
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
|
|||||||
@ -29,6 +29,7 @@ import Link from "next/link";
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { LoginDialog } from "@/components/LoginDialog";
|
import { LoginDialog } from "@/components/LoginDialog";
|
||||||
|
import { SignupDialog } from "@/components/SignupDialog";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useAppointments } from "@/hooks/useAppointments";
|
import { useAppointments } from "@/hooks/useAppointments";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
@ -92,6 +93,8 @@ export default function BookNowPage() {
|
|||||||
const [booking, setBooking] = useState<Booking | null>(null);
|
const [booking, setBooking] = useState<Booking | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [showLoginDialog, setShowLoginDialog] = useState(false);
|
const [showLoginDialog, setShowLoginDialog] = useState(false);
|
||||||
|
const [showSignupDialog, setShowSignupDialog] = useState(false);
|
||||||
|
const [loginPrefillEmail, setLoginPrefillEmail] = useState<string | undefined>(undefined);
|
||||||
|
|
||||||
const handleLogout = () => {
|
const handleLogout = () => {
|
||||||
logout();
|
logout();
|
||||||
@ -121,6 +124,30 @@ export default function BookNowPage() {
|
|||||||
await submitBooking();
|
await submitBooking();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleSignupSuccess = async () => {
|
||||||
|
// Close signup dialog
|
||||||
|
setShowSignupDialog(false);
|
||||||
|
// After successful signup, proceed with booking submission
|
||||||
|
await submitBooking();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSwitchToSignup = () => {
|
||||||
|
// Close login dialog and open signup dialog
|
||||||
|
setShowLoginDialog(false);
|
||||||
|
setTimeout(() => {
|
||||||
|
setShowSignupDialog(true);
|
||||||
|
}, 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSwitchToLogin = (email?: string) => {
|
||||||
|
// Close signup dialog and open login dialog with email prefilled
|
||||||
|
setShowSignupDialog(false);
|
||||||
|
setLoginPrefillEmail(email);
|
||||||
|
setTimeout(() => {
|
||||||
|
setShowLoginDialog(true);
|
||||||
|
}, 100);
|
||||||
|
};
|
||||||
|
|
||||||
const submitBooking = async () => {
|
const submitBooking = async () => {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
@ -693,8 +720,23 @@ export default function BookNowPage() {
|
|||||||
{/* Login Dialog */}
|
{/* Login Dialog */}
|
||||||
<LoginDialog
|
<LoginDialog
|
||||||
open={showLoginDialog}
|
open={showLoginDialog}
|
||||||
onOpenChange={setShowLoginDialog}
|
onOpenChange={(open) => {
|
||||||
|
setShowLoginDialog(open);
|
||||||
|
if (!open) {
|
||||||
|
setLoginPrefillEmail(undefined);
|
||||||
|
}
|
||||||
|
}}
|
||||||
onLoginSuccess={handleLoginSuccess}
|
onLoginSuccess={handleLoginSuccess}
|
||||||
|
onSwitchToSignup={handleSwitchToSignup}
|
||||||
|
prefillEmail={loginPrefillEmail}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Signup Dialog */}
|
||||||
|
<SignupDialog
|
||||||
|
open={showSignupDialog}
|
||||||
|
onOpenChange={setShowSignupDialog}
|
||||||
|
onSignupSuccess={handleSignupSuccess}
|
||||||
|
onSwitchToLogin={handleSwitchToLogin}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@ -11,12 +11,13 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Eye, EyeOff, Loader2, X } from "lucide-react";
|
import { Eye, EyeOff, Loader2, X, Mail } from "lucide-react";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { loginSchema, type LoginInput } from "@/lib/schema/auth";
|
import { loginSchema, type LoginInput } from "@/lib/schema/auth";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { ForgotPasswordDialog } from "./ForgotPasswordDialog";
|
import { ForgotPasswordDialog } from "./ForgotPasswordDialog";
|
||||||
|
import { VerifyOtpDialog } from "./VerifyOtpDialog";
|
||||||
|
|
||||||
interface LoginDialogProps {
|
interface LoginDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@ -38,6 +39,8 @@ export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail,
|
|||||||
});
|
});
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
const [forgotPasswordDialogOpen, setForgotPasswordDialogOpen] = useState(false);
|
const [forgotPasswordDialogOpen, setForgotPasswordDialogOpen] = useState(false);
|
||||||
|
const [showResendOtp, setShowResendOtp] = useState(false);
|
||||||
|
const [verifyOtpDialogOpen, setVerifyOtpDialogOpen] = useState(false);
|
||||||
|
|
||||||
// Pre-fill email if provided
|
// Pre-fill email if provided
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -63,6 +66,7 @@ export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail,
|
|||||||
if (result.tokens && result.user) {
|
if (result.tokens && result.user) {
|
||||||
toast.success("Login successful!");
|
toast.success("Login successful!");
|
||||||
setShowPassword(false);
|
setShowPassword(false);
|
||||||
|
setShowResendOtp(false);
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
// Reset form
|
// Reset form
|
||||||
setLoginData({ email: "", password: "" });
|
setLoginData({ email: "", password: "" });
|
||||||
@ -73,13 +77,48 @@ export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail,
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errorMessage = err instanceof Error ? err.message : "Login failed. Please try again.";
|
const errorMessage = err instanceof Error ? err.message : "Login failed. Please try again.";
|
||||||
toast.error(errorMessage);
|
toast.error(errorMessage);
|
||||||
|
|
||||||
|
// Check if error is about email verification
|
||||||
|
if (errorMessage.toLowerCase().includes("verify your email") ||
|
||||||
|
errorMessage.toLowerCase().includes("email address before logging")) {
|
||||||
|
setShowResendOtp(true);
|
||||||
|
} else {
|
||||||
|
setShowResendOtp(false);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle resend OTP - just open the verification dialog (it will auto-send OTP)
|
||||||
|
const handleResendOtp = () => {
|
||||||
|
if (!loginData.email) {
|
||||||
|
toast.error("Email address is required to resend OTP.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close login dialog and open OTP verification dialog
|
||||||
|
// The VerifyOtpDialog will automatically send the OTP when it opens
|
||||||
|
setShowResendOtp(false);
|
||||||
|
onOpenChange(false);
|
||||||
|
setTimeout(() => {
|
||||||
|
setVerifyOtpDialogOpen(true);
|
||||||
|
}, 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle OTP verification success
|
||||||
|
const handleOtpVerificationSuccess = () => {
|
||||||
|
// After successful verification, user can try logging in again
|
||||||
|
setVerifyOtpDialogOpen(false);
|
||||||
|
// Optionally reopen login dialog
|
||||||
|
setTimeout(() => {
|
||||||
|
onOpenChange(true);
|
||||||
|
}, 100);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reset form when dialog closes
|
// Reset form when dialog closes
|
||||||
const handleDialogChange = (isOpen: boolean) => {
|
const handleDialogChange = (isOpen: boolean) => {
|
||||||
if (!isOpen) {
|
if (!isOpen) {
|
||||||
setLoginData({ email: "", password: "" });
|
setLoginData({ email: "", password: "" });
|
||||||
|
setShowResendOtp(false);
|
||||||
}
|
}
|
||||||
onOpenChange(isOpen);
|
onOpenChange(isOpen);
|
||||||
};
|
};
|
||||||
@ -181,6 +220,31 @@ export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail,
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
{/* Resend OTP - Show when email verification error occurs */}
|
||||||
|
{showResendOtp && (
|
||||||
|
<div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-yellow-900/20 border-yellow-800' : 'bg-yellow-50 border-yellow-200'}`}>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<Mail className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-yellow-400' : 'text-yellow-600'}`} />
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className={`text-sm font-medium ${isDark ? 'text-yellow-200' : 'text-yellow-900'}`}>
|
||||||
|
Email verification required
|
||||||
|
</p>
|
||||||
|
<p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-yellow-300' : 'text-yellow-700'}`}>
|
||||||
|
Please verify your email address before logging in. We can resend the verification code to {loginData.email}.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="link"
|
||||||
|
onClick={handleResendOtp}
|
||||||
|
className={`h-auto p-0 mt-2 text-xs sm:text-sm font-medium ${isDark ? 'text-yellow-400 hover:text-yellow-300' : 'text-yellow-700 hover:text-yellow-800'}`}
|
||||||
|
>
|
||||||
|
Resend verification code
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Forgot Password */}
|
{/* Forgot Password */}
|
||||||
<div className="flex items-center justify-end text-xs sm:text-sm">
|
<div className="flex items-center justify-end text-xs sm:text-sm">
|
||||||
<Button
|
<Button
|
||||||
@ -224,6 +288,15 @@ export function LoginDialog({ open, onOpenChange, onLoginSuccess, prefillEmail,
|
|||||||
open={forgotPasswordDialogOpen}
|
open={forgotPasswordDialogOpen}
|
||||||
onOpenChange={setForgotPasswordDialogOpen}
|
onOpenChange={setForgotPasswordDialogOpen}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Verify OTP Dialog */}
|
||||||
|
<VerifyOtpDialog
|
||||||
|
open={verifyOtpDialogOpen}
|
||||||
|
onOpenChange={setVerifyOtpDialogOpen}
|
||||||
|
email={loginData.email}
|
||||||
|
context="registration"
|
||||||
|
onVerificationSuccess={handleOtpVerificationSuccess}
|
||||||
|
/>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
329
components/VerifyOtpDialog.tsx
Normal file
329
components/VerifyOtpDialog.tsx
Normal file
@ -0,0 +1,329 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useAppTheme } from "@/components/ThemeProvider";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
InputOTP,
|
||||||
|
InputOTPGroup,
|
||||||
|
InputOTPSlot,
|
||||||
|
} from "@/components/ui/input-otp";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Loader2, X, CheckCircle2 } from "lucide-react";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { verifyOtpSchema, type VerifyOtpInput } from "@/lib/schema/auth";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
interface VerifyOtpDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
email: string;
|
||||||
|
context?: "registration" | "password_reset";
|
||||||
|
onVerificationSuccess?: () => void;
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function VerifyOtpDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
email: initialEmail,
|
||||||
|
context = "registration",
|
||||||
|
onVerificationSuccess,
|
||||||
|
title = "Verify your email",
|
||||||
|
description = "Enter the verification code sent to your email"
|
||||||
|
}: VerifyOtpDialogProps) {
|
||||||
|
const { theme } = useAppTheme();
|
||||||
|
const isDark = theme === "dark";
|
||||||
|
const { verifyOtp, verifyOtpMutation, resendOtpMutation } = useAuth();
|
||||||
|
const [otpData, setOtpData] = useState<VerifyOtpInput>({
|
||||||
|
email: initialEmail,
|
||||||
|
otp: "",
|
||||||
|
});
|
||||||
|
const [email, setEmail] = useState(initialEmail);
|
||||||
|
const [otpSent, setOtpSent] = useState(false);
|
||||||
|
const [isSendingOtp, setIsSendingOtp] = useState(false);
|
||||||
|
|
||||||
|
// Update email when prop changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (initialEmail) {
|
||||||
|
setEmail(initialEmail);
|
||||||
|
setOtpData(prev => ({ ...prev, email: initialEmail }));
|
||||||
|
}
|
||||||
|
}, [initialEmail]);
|
||||||
|
|
||||||
|
// Automatically send OTP when dialog opens
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && !otpSent) {
|
||||||
|
const emailToSend = initialEmail || email;
|
||||||
|
if (emailToSend) {
|
||||||
|
setIsSendingOtp(true);
|
||||||
|
resendOtpMutation.mutateAsync({
|
||||||
|
email: emailToSend,
|
||||||
|
context
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
toast.success("Verification code sent! Please check your email.");
|
||||||
|
setOtpSent(true);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Failed to send verification code";
|
||||||
|
toast.error(errorMessage);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
// Still allow user to manually resend
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset when dialog closes
|
||||||
|
if (!open) {
|
||||||
|
setOtpSent(false);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [open, initialEmail, email, context, otpSent]);
|
||||||
|
|
||||||
|
const handleVerifyOtp = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const emailToVerify = email || otpData.email;
|
||||||
|
if (!emailToVerify) {
|
||||||
|
toast.error("Email address is required");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const validation = verifyOtpSchema.safeParse({
|
||||||
|
email: emailToVerify,
|
||||||
|
otp: otpData.otp,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!validation.success) {
|
||||||
|
const firstError = validation.error.issues[0];
|
||||||
|
toast.error(firstError.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await verifyOtp({
|
||||||
|
email: emailToVerify,
|
||||||
|
otp: otpData.otp,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.message || result.tokens) {
|
||||||
|
toast.success("Email verified successfully!");
|
||||||
|
// Reset form
|
||||||
|
setOtpData({ email: emailToVerify, otp: "" });
|
||||||
|
onOpenChange(false);
|
||||||
|
// Call success callback if provided
|
||||||
|
if (onVerificationSuccess) {
|
||||||
|
onVerificationSuccess();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "OTP verification failed. Please try again.";
|
||||||
|
toast.error(errorMessage);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResendOtp = async () => {
|
||||||
|
const emailToResend = email || otpData.email;
|
||||||
|
if (!emailToResend) {
|
||||||
|
toast.error("Email address is required");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsSendingOtp(true);
|
||||||
|
await resendOtpMutation.mutateAsync({
|
||||||
|
email: emailToResend,
|
||||||
|
context
|
||||||
|
});
|
||||||
|
toast.success("OTP resent successfully! Please check your email.");
|
||||||
|
setOtpSent(true);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
} catch (err) {
|
||||||
|
const errorMessage = err instanceof Error ? err.message : "Failed to resend OTP";
|
||||||
|
toast.error(errorMessage);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOtpChange = (field: keyof VerifyOtpInput, value: string) => {
|
||||||
|
setOtpData((prev) => ({ ...prev, [field]: value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Reset form when dialog closes
|
||||||
|
const handleDialogChange = (isOpen: boolean) => {
|
||||||
|
if (!isOpen) {
|
||||||
|
setOtpData({ email: initialEmail || "", otp: "" });
|
||||||
|
setOtpSent(false);
|
||||||
|
setIsSendingOtp(false);
|
||||||
|
}
|
||||||
|
onOpenChange(isOpen);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleDialogChange}>
|
||||||
|
<DialogContent
|
||||||
|
showCloseButton={false}
|
||||||
|
className={`max-w-md max-h-[90vh] overflow-hidden flex flex-col p-0 ${isDark ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}`}
|
||||||
|
>
|
||||||
|
{/* Header with Close Button - Fixed */}
|
||||||
|
<div className="flex items-start justify-between p-6 pb-4 flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<DialogHeader className="flex-1 pr-2">
|
||||||
|
<DialogTitle className="text-2xl sm:text-3xl font-bold bg-gradient-to-r from-rose-600 via-pink-600 to-rose-600 bg-clip-text text-transparent">
|
||||||
|
{title}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription className={`text-sm sm:text-base mt-1 ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>
|
||||||
|
{description}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{/* Close Button */}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleDialogChange(false)}
|
||||||
|
className={`flex-shrink-0 w-8 h-8 rounded-full ${isDark ? 'text-gray-400 hover:text-gray-300 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'}`}
|
||||||
|
aria-label="Close"
|
||||||
|
>
|
||||||
|
<X className="w-5 h-5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Scrollable Content */}
|
||||||
|
<div className="overflow-y-auto flex-1 px-6">
|
||||||
|
<form className="space-y-4 sm:space-y-5 py-4 sm:py-6" onSubmit={handleVerifyOtp}>
|
||||||
|
{/* Loading indicator while sending */}
|
||||||
|
{isSendingOtp && !otpSent && (
|
||||||
|
<div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-yellow-900/20 border-yellow-800' : 'bg-yellow-50 border-yellow-200'}`}>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Loader2 className="w-5 h-5 animate-spin text-yellow-600" />
|
||||||
|
<p className={`text-sm font-medium ${isDark ? 'text-yellow-200' : 'text-yellow-900'}`}>
|
||||||
|
Sending verification code...
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Success message after sending */}
|
||||||
|
{otpSent && (
|
||||||
|
<div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-blue-900/20 border-blue-800' : 'bg-blue-50 border-blue-200'}`}>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<CheckCircle2 className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-blue-400' : 'text-blue-600'}`} />
|
||||||
|
<div>
|
||||||
|
<p className={`text-sm font-medium ${isDark ? 'text-blue-200' : 'text-blue-900'}`}>
|
||||||
|
Check your email
|
||||||
|
</p>
|
||||||
|
<p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-blue-300' : 'text-blue-700'}`}>
|
||||||
|
We've sent a 6-digit verification code to {email || otpData.email || "your email address"}.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Show info message if OTP hasn't been sent yet but dialog is open */}
|
||||||
|
{!isSendingOtp && !otpSent && (
|
||||||
|
<div className={`p-3 sm:p-4 rounded-lg border ${isDark ? 'bg-blue-900/20 border-blue-800' : 'bg-blue-50 border-blue-200'}`}>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<CheckCircle2 className={`w-5 h-5 mt-0.5 flex-shrink-0 ${isDark ? 'text-blue-400' : 'text-blue-600'}`} />
|
||||||
|
<div>
|
||||||
|
<p className={`text-sm font-medium ${isDark ? 'text-blue-200' : 'text-blue-900'}`}>
|
||||||
|
Enter verification code
|
||||||
|
</p>
|
||||||
|
<p className={`text-xs sm:text-sm mt-1 ${isDark ? 'text-blue-300' : 'text-blue-700'}`}>
|
||||||
|
Enter the 6-digit verification code sent to {email || otpData.email || "your email address"}.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Email Field (if not provided or editable) */}
|
||||||
|
{!initialEmail && (
|
||||||
|
<div className="space-y-1.5 sm:space-y-2">
|
||||||
|
<label htmlFor="verify-email" className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
|
||||||
|
Email address *
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="verify-email"
|
||||||
|
type="email"
|
||||||
|
placeholder="Email address"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => {
|
||||||
|
setEmail(e.target.value);
|
||||||
|
handleOtpChange("email", e.target.value);
|
||||||
|
}}
|
||||||
|
className={`h-11 sm:h-12 text-sm sm:text-base ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900'}`}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* OTP Field */}
|
||||||
|
<div className="space-y-1.5 sm:space-y-2">
|
||||||
|
<label className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-black'}`}>
|
||||||
|
Verification Code *
|
||||||
|
</label>
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<InputOTP
|
||||||
|
maxLength={6}
|
||||||
|
value={otpData.otp}
|
||||||
|
onChange={(value) => handleOtpChange("otp", value)}
|
||||||
|
>
|
||||||
|
<InputOTPGroup className="gap-2 sm:gap-3">
|
||||||
|
<InputOTPSlot index={0} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
<InputOTPSlot index={1} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
<InputOTPSlot index={2} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
<InputOTPSlot index={3} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
<InputOTPSlot index={4} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
<InputOTPSlot index={5} className="h-12 w-12 sm:h-14 sm:w-14 text-lg sm:text-xl font-semibold" />
|
||||||
|
</InputOTPGroup>
|
||||||
|
</InputOTP>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Resend OTP */}
|
||||||
|
<div className="text-center">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="link"
|
||||||
|
onClick={handleResendOtp}
|
||||||
|
disabled={resendOtpMutation.isPending}
|
||||||
|
className={`h-auto p-0 text-xs sm:text-sm font-medium ${isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-700'}`}
|
||||||
|
>
|
||||||
|
{resendOtpMutation.isPending ? "Sending..." : "Didn't receive the code? Resend"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Submit Button */}
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={verifyOtpMutation.isPending}
|
||||||
|
className="w-full h-11 sm:h-12 text-sm sm:text-base font-semibold bg-gradient-to-r from-rose-500 to-pink-600 hover:from-rose-600 hover:to-pink-700 text-white shadow-lg hover:shadow-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed mt-4 sm:mt-6"
|
||||||
|
>
|
||||||
|
{verifyOtpMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||||
|
Verifying...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Verify Email"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@ -287,7 +287,7 @@ export async function getAdminAvailability(): Promise<AdminAvailability> {
|
|||||||
throw new Error("Authentication required.");
|
throw new Error("Authentication required.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await fetch(`${API_ENDPOINTS.meetings.base}admin/availability/`, {
|
const response = await fetch(API_ENDPOINTS.meetings.adminAvailability, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@ -295,14 +295,30 @@ export async function getAdminAvailability(): Promise<AdminAvailability> {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const data: AdminAvailability = await response.json();
|
const data: any = await response.json();
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorMessage = extractErrorMessage(data as unknown as ApiError);
|
const errorMessage = extractErrorMessage(data as unknown as ApiError);
|
||||||
throw new Error(errorMessage);
|
throw new Error(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
// Handle both string and array formats for available_days
|
||||||
|
let availableDays: number[] = [];
|
||||||
|
if (typeof data.available_days === 'string') {
|
||||||
|
try {
|
||||||
|
availableDays = JSON.parse(data.available_days);
|
||||||
|
} catch {
|
||||||
|
// If parsing fails, try splitting by comma
|
||||||
|
availableDays = data.available_days.split(',').map((d: string) => parseInt(d.trim())).filter((d: number) => !isNaN(d));
|
||||||
|
}
|
||||||
|
} else if (Array.isArray(data.available_days)) {
|
||||||
|
availableDays = data.available_days;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
available_days: availableDays,
|
||||||
|
available_days_display: data.available_days_display || [],
|
||||||
|
} as AdminAvailability;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update admin availability
|
// Update admin availability
|
||||||
@ -315,23 +331,58 @@ export async function updateAdminAvailability(
|
|||||||
throw new Error("Authentication required.");
|
throw new Error("Authentication required.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await fetch(`${API_ENDPOINTS.meetings.base}admin/availability/`, {
|
// Ensure available_days is an array of numbers
|
||||||
|
const payload = {
|
||||||
|
available_days: Array.isArray(input.available_days)
|
||||||
|
? input.available_days.map(day => Number(day))
|
||||||
|
: input.available_days
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(API_ENDPOINTS.meetings.adminAvailability, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
Authorization: `Bearer ${tokens.access}`,
|
Authorization: `Bearer ${tokens.access}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify(input),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data: AdminAvailability = await response.json();
|
let data: any;
|
||||||
|
try {
|
||||||
|
data = await response.json();
|
||||||
|
} catch (parseError) {
|
||||||
|
// If response is not JSON, use status text
|
||||||
|
throw new Error(response.statusText || "Failed to update availability");
|
||||||
|
}
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorMessage = extractErrorMessage(data as unknown as ApiError);
|
const errorMessage = extractErrorMessage(data as unknown as ApiError);
|
||||||
|
console.error("Availability update error:", {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
data,
|
||||||
|
payload
|
||||||
|
});
|
||||||
throw new Error(errorMessage);
|
throw new Error(errorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
// Handle both string and array formats for available_days in response
|
||||||
|
let availableDays: number[] = [];
|
||||||
|
if (typeof data.available_days === 'string') {
|
||||||
|
try {
|
||||||
|
availableDays = JSON.parse(data.available_days);
|
||||||
|
} catch {
|
||||||
|
// If parsing fails, try splitting by comma
|
||||||
|
availableDays = data.available_days.split(',').map((d: string) => parseInt(d.trim())).filter((d: number) => !isNaN(d));
|
||||||
|
}
|
||||||
|
} else if (Array.isArray(data.available_days)) {
|
||||||
|
availableDays = data.available_days;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
available_days: availableDays,
|
||||||
|
available_days_display: data.available_days_display || [],
|
||||||
|
} as AdminAvailability;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get appointment stats (Admin only)
|
// Get appointment stats (Admin only)
|
||||||
|
|||||||
@ -20,6 +20,7 @@ export const API_ENDPOINTS = {
|
|||||||
createAppointment: `${API_BASE_URL}/meetings/appointments/create/`,
|
createAppointment: `${API_BASE_URL}/meetings/appointments/create/`,
|
||||||
listAppointments: `${API_BASE_URL}/meetings/appointments/`,
|
listAppointments: `${API_BASE_URL}/meetings/appointments/`,
|
||||||
userAppointments: `${API_BASE_URL}/meetings/user/appointments/`,
|
userAppointments: `${API_BASE_URL}/meetings/user/appointments/`,
|
||||||
|
adminAvailability: `${API_BASE_URL}/meetings/admin/availability/`,
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user