Files
SweetHome/app/owner/bookings/page.js

597 lines
25 KiB
JavaScript
Raw Normal View History

"use client";
import { useState, useEffect, useMemo } from "react";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { Calendar, User, Mail, Phone, CheckCircle, XCircle, Clock, MapPin, Bed, Bath, Square, CalendarDays, ChevronLeft, ChevronRight, Eye, Loader2, Search } from "lucide-react";
import toast, { Toaster } from "react-hot-toast";
import { getMyRentListings, getOwnerReservationRequests } from "@/app/utils/api";
import useAuth from "@/app/hooks/useAuth";
import Loading from "@/app/loading";
const OwnerBookingCalendar = ({ property, onDateSelect, selectedDates }) => {
const { t } = useTranslation();
const [currentMonth, setCurrentMonth] = useState(new Date());
const [hoverDate, setHoverDate] = useState(null);
const daysInMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0).getDate();
const firstDayOfMonth = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), 1).getDay();
const monthNames = [t("january"), t("february"), t("march"), t("april"), t("may"), t("june"), t("july"), t("august"), t("september"), t("october"), t("november"), t("december")];
const dayNames = [t("dayFull.sunday"), t("dayFull.monday"), t("dayFull.tuesday"), t("dayFull.wednesday"), t("dayFull.thursday"), t("dayFull.friday"), t("dayFull.saturday")];
const isDateBooked = (date) => {
if (!property?.bookings || !Array.isArray(property.bookings)) return false;
return property.bookings.some((booking) => {
const start = new Date(booking.startDate);
const end = new Date(booking.endDate);
return date >= start && date <= end;
});
};
const isDateSelected = (date) => {
if (!selectedDates) return false;
const dateStr = date.toISOString().split("T")[0];
return dateStr === selectedDates.start || dateStr === selectedDates.end;
};
const isInRange = (date) => {
if (!selectedDates?.start || !selectedDates?.end) return false;
const dateStr = date.toISOString().split("T")[0];
return dateStr > selectedDates.start && dateStr < selectedDates.end;
};
const handleDateClick = (date) => {
if (isDateBooked(date)) return;
onDateSelect?.(date);
};
const renderDays = () => {
const days = [];
const totalDays = daysInMonth + firstDayOfMonth;
for (let i = 0; i < totalDays; i++) {
if (i < firstDayOfMonth) {
days.push(<div key={`empty-${i}`} className="p-2" />);
} else {
const dayNumber = i - firstDayOfMonth + 1;
const date = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), dayNumber);
const isBooked = isDateBooked(date);
const isSelected = isDateSelected(date);
const inRange = isInRange(date);
const isToday = date.toDateString() === new Date().toDateString();
days.push(
<button
key={dayNumber}
onClick={() => handleDateClick(date)}
disabled={isBooked}
onMouseEnter={() => setHoverDate(dayNumber)}
onMouseLeave={() => setHoverDate(null)}
className={`
p-2 rounded-lg text-center text-sm transition-all relative
${isBooked ? "bg-red-100 text-red-500 cursor-not-allowed line-through" : ""}
${isSelected ? "bg-amber-500 text-white shadow-md" : ""}
${inRange ? "bg-amber-100" : ""}
${!isBooked && !isSelected ? "hover:bg-amber-50 hover:text-amber-600 cursor-pointer" : ""}
${isToday && !isSelected && !isBooked ? "border-2 border-amber-500" : ""}
`}
>
{dayNumber}
{isBooked && <span className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full" />}
</button>,
);
}
}
return days;
};
return (
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
<div className="flex items-center justify-between mb-6">
<button onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1))} className="p-2 hover:bg-gray-100 rounded-xl transition-colors">
<ChevronRight className="w-5 h-5 text-gray-600" />
</button>
<h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
<CalendarDays className="w-5 h-5 text-amber-500" />
{monthNames[currentMonth.getMonth()]} {currentMonth.getFullYear()}
</h3>
<button onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1))} className="p-2 hover:bg-gray-100 rounded-xl transition-colors">
<ChevronLeft className="w-5 h-5 text-gray-600" />
</button>
</div>
<div className="grid grid-cols-7 gap-1 mb-3 text-center text-sm font-medium text-gray-500">
{dayNames.map((name, i) => (
<div key={i}>{name}</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">{renderDays()}</div>
<div className="flex flex-wrap gap-4 mt-6 pt-4 border-t border-gray-200 text-xs">
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-red-100 rounded" />
<span className="text-gray-600">{t("booked")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-amber-500 rounded" />
<span className="text-gray-600">{t("selected")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-amber-100 rounded" />
<span className="text-gray-600">{t("inRange")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 border-2 border-amber-500 rounded" />
<span className="text-gray-600">{t("today")}</span>
</div>
</div>
</div>
);
};
const BookingCard = ({ booking, onViewDetails }) => {
const { t } = useTranslation();
const formatCurrency = (amount) => {
return (amount || 0).toLocaleString() + " " + t("syp");
};
const getStatusBadge = (status) => {
const statusConfig = {
pending: { label: t("pending"), color: "bg-yellow-100 text-yellow-800", icon: Clock },
confirmed: { label: t("confirmed"), color: "bg-green-100 text-green-800", icon: CheckCircle },
cancelled: { label: t("cancelled"), color: "bg-red-100 text-red-800", icon: XCircle },
completed: { label: t("completed"), color: "bg-gray-100 text-gray-800", icon: CheckCircle },
};
const config = statusConfig[status] || statusConfig.pending;
const Icon = config.icon;
return (
<span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium ${config.color}`}>
<Icon className="w-3.5 h-3.5" />
{config.label}
</span>
);
};
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-2xl shadow-sm hover:shadow-md transition-all border border-gray-200 overflow-hidden flex flex-col justify-between"
>
<div className="p-5">
<div className="flex justify-between items-start mb-4 gap-2">
<div>
<div className="flex items-center gap-2 mb-2 flex-wrap">
<h3 className="font-bold text-gray-900">{booking.propertyTitle}</h3>
{getStatusBadge(booking.status)}
</div>
<div className="flex items-center gap-1 text-gray-500 text-sm line-clamp-1">
<MapPin className="w-4 h-4 shrink-0 text-amber-500" />
<span>{booking.location}</span>
</div>
</div>
<div className="text-left shrink-0">
<div className="text-lg font-bold text-amber-600">{formatCurrency(booking.dailyRent)}</div>
<div className="text-xs text-gray-500">{t("dailyRent")}</div>
</div>
</div>
<div className="bg-gray-50 rounded-xl p-3 mb-4 grid grid-cols-3 gap-2 text-center text-xs">
<div className="flex items-center justify-center gap-1 text-gray-700">
<Bed className="w-4 h-4 text-amber-500" />
<span>
{booking.propertyDetails?.bedrooms} {t("rooms")}
</span>
</div>
<div className="flex items-center justify-center gap-1 text-gray-700">
<Bath className="w-4 h-4 text-amber-500" />
<span>
{booking.propertyDetails?.bathrooms} {t("baths")}
</span>
</div>
<div className="flex items-center justify-center gap-1 text-gray-700">
<Square className="w-4 h-4 text-amber-500" />
<span>
{booking.propertyDetails?.area} {t("sqm")}
</span>
</div>
</div>
{booking.tenantName && (
<div className="bg-amber-50/50 border border-amber-100 rounded-xl p-3 mb-4">
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-amber-100 rounded-full flex items-center justify-center shrink-0">
<User className="w-4 h-4 text-amber-600" />
</div>
<div className="overflow-hidden text-xs">
<p className="font-semibold text-gray-900 truncate">{booking.tenantName}</p>
<div className="flex items-center gap-3 text-gray-500 mt-0.5">
{booking.tenantPhone && (
<span className="flex items-center gap-1">
<Phone className="w-3 h-3" />
{booking.tenantPhone}
</span>
)}
{booking.tenantEmail && (
<span className="flex items-center gap-1">
<Mail className="w-3 h-3" />
{booking.tenantEmail}
</span>
)}
</div>
</div>
</div>
</div>
)}
<div className="grid grid-cols-2 gap-3 mb-4 text-center">
<div className="bg-gray-50 p-2 rounded-lg">
<div className="text-xs text-gray-500">{t("monthlyRent")}</div>
<div className="text-sm font-semibold text-gray-800">{formatCurrency(booking.monthlyRent)}</div>
</div>
<div className="bg-gray-50 p-2 rounded-lg">
<div className="text-xs text-gray-500">{t("deposit")}</div>
<div className="text-sm font-semibold text-gray-800">{formatCurrency(booking.deposit)}</div>
</div>
</div>
</div>
<div className="p-5 pt-0">
<button
onClick={() => onViewDetails(booking)}
className="w-full bg-gray-100 text-gray-700 py-2.5 rounded-xl text-sm font-medium hover:bg-gray-200 transition-colors flex items-center justify-center gap-2"
>
<Eye className="w-4 h-4" />
{t("details")}
</button>
</div>
</motion.div>
);
};
const BookingDetailsModal = ({ booking, isOpen, onClose }) => {
const { t } = useTranslation();
if (!isOpen || !booking) return null;
const formatCurrency = (amount) => {
return (amount || 0).toLocaleString() + " " + t("syp");
};
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50"
onClick={onClose}
>
<motion.div
initial={{ scale: 0.95, y: 20 }}
animate={{ scale: 1, y: 0 }}
exit={{ scale: 0.95, y: 20 }}
className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="sticky top-0 bg-gradient-to-r from-amber-500 to-amber-600 p-6 text-white z-10 flex justify-between items-center">
<div>
<h2 className="text-xl font-bold">{t("bookingDetails")}</h2>
<p className="text-amber-100 text-sm mt-0.5"># {booking.id}</p>
</div>
<button onClick={onClose} className="p-1 hover:bg-white/20 rounded-full transition-colors">
<XCircle className="w-6 h-6" />
</button>
</div>
<div className="p-6 space-y-6">
{booking.images && booking.images.length > 0 && (
<div className="grid grid-cols-2 gap-3">
{booking.images.map((img, idx) => (
<img key={idx} src={img} alt={`property-${idx}`} className="w-full h-36 object-cover rounded-xl border border-gray-100 shadow-sm" />
))}
</div>
)}
<div className="bg-gray-50 p-4 rounded-xl space-y-2">
<h3 className="font-bold text-gray-900 mb-2">{t("propertyInfo")}</h3>
<p className="text-sm">
<span className="text-gray-500">{t("location")}:</span> {booking.location}
</p>
<p className="text-sm">
<span className="text-gray-500">{t("description")}:</span> {booking.parsedDetails?.description || "-"}
</p>
<div className="flex gap-2 pt-2 flex-wrap">
<span className="text-xs bg-white border border-gray-200 px-3 py-1.5 rounded-lg font-medium">
{booking.propertyDetails?.bedrooms} {t("rooms")}
</span>
<span className="text-xs bg-white border border-gray-200 px-3 py-1.5 rounded-lg font-medium">
{booking.propertyDetails?.bathrooms} {t("bathrooms")}
</span>
<span className="text-xs bg-white border border-gray-200 px-3 py-1.5 rounded-lg font-medium">
{booking.propertyDetails?.salons} {t("salons")}
</span>
<span className="text-xs bg-white border border-gray-200 px-3 py-1.5 rounded-lg font-medium">
{booking.propertyDetails?.area} {t("sqm")}
</span>
</div>
</div>
<div className="bg-amber-50/60 border border-amber-200/60 p-4 rounded-xl space-y-2">
<h3 className="font-bold text-amber-900 mb-2">{t("financialInfo")}</h3>
<div className="flex justify-between text-sm">
<span className="text-gray-600">{t("dailyRent")}</span>
<span className="font-semibold text-gray-900">{formatCurrency(booking.dailyRent)}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-gray-600">{t("monthlyRent")}</span>
<span className="font-semibold text-gray-900">{formatCurrency(booking.monthlyRent)}</span>
</div>
<div className="flex justify-between text-sm pt-2 border-t border-amber-200 font-bold">
<span className="text-gray-900">{t("deposit")}</span>
<span className="text-amber-600 text-base">{formatCurrency(booking.deposit)}</span>
</div>
</div>
{booking.parsedDetails?.services && (
<div className="bg-gray-50 p-4 rounded-xl">
<h3 className="font-bold text-gray-900 mb-2">{t("services")}</h3>
<div className="flex flex-wrap gap-2">
{booking.parsedDetails.services.map((srv, i) => (
<span key={i} className="text-xs bg-amber-100 text-amber-800 px-2.5 py-1 rounded-md font-medium">
{srv}
</span>
))}
</div>
</div>
)}
</div>
</motion.div>
</motion.div>
);
};
export default function OwnerBookingsPage() {
const { t, i18n } = useTranslation();
const router = useRouter();
const { name, isOwner } = useAuth();
const [bookings, setBookings] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedBooking, setSelectedBooking] = useState(null);
const [filterStatus, setFilterStatus] = useState("all");
const [searchTerm, setSearchTerm] = useState("");
const [dateRange, setDateRange] = useState({ start: "", end: "" });
const [showCalendar, setShowCalendar] = useState(false);
const isRtl = i18n.language === "ar";
useEffect(() => {
if (isOwner) {
fetchData();
} else {
router.push("/auth/choose-role");
}
}, [isOwner, router]);
const fetchData = async () => {
try {
const response = await getOwnerReservationRequests();
let rawData = response;
if (response && response.data) {
rawData = response.data;
}
// تحويل البيانات إلى مصفوفة وتصفية العناصر الفارغة (null أو undefined)
const rawList = Array.isArray(rawData) ? rawData : rawData ? [rawData] : [];
const list = rawList.filter(Boolean);
const mappedBookings = list.map((item) => {
let parsedDetails = {};
try {
if (item?.propertyInformation?.detailsJSON) {
parsedDetails = JSON.parse(item.propertyInformation.detailsJSON);
}
} catch (e) {
console.error("Error parsing detailsJSON", e);
}
const statusMap = {
0: "pending",
1: "confirmed",
2: "completed",
3: "cancelled",
};
const statusKey = statusMap[item?.propertyInformation?.status] || "pending";
return {
id: item?.id,
dailyRent: item?.dailyRent,
monthlyRent: item?.monthlyRent,
deposit: item?.deposit,
createdAt: item?.createdAt,
startDate: item?.createdAt?.split("T")[0],
status: statusKey,
propertyTitle: parsedDetails.description || `${t("property")} #${item?.id}`,
location: item?.propertyInformation?.address || "",
images: item?.propertyInformation?.images || [],
propertyDetails: {
bedrooms: item?.propertyInformation?.numberOfBedRooms || 0,
bathrooms: item?.propertyInformation?.numberOfBathRooms || 0,
salons: item?.propertyInformation?.numberOfSalons || 0,
area: item?.propertyInformation?.space || 0,
},
parsedDetails,
tenantName: item?.tenantName || null,
tenantPhone: item?.tenantPhone || null,
tenantEmail: item?.tenantEmail || null,
};
});
setBookings(mappedBookings);
} catch (error) {
console.error("Error loading listings:", error);
setBookings([]);
} finally {
setIsLoading(false);
}
};
const filteredBookings = useMemo(() => {
return bookings.filter((booking) => {
const matchesStatus = filterStatus === "all" || booking.status === filterStatus;
const matchesSearch =
!searchTerm ||
booking.tenantName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
booking.propertyTitle?.toLowerCase().includes(searchTerm.toLowerCase()) ||
booking.location?.toLowerCase().includes(searchTerm.toLowerCase()) ||
String(booking.id).includes(searchTerm);
const bookingDate = new Date(booking.startDate || booking.createdAt);
const matchesStart = !dateRange.start || bookingDate >= new Date(dateRange.start);
const matchesEnd = !dateRange.end || bookingDate <= new Date(dateRange.end);
return matchesStatus && matchesSearch && matchesStart && matchesEnd;
});
}, [bookings, filterStatus, searchTerm, dateRange]);
const statusCounts = useMemo(() => {
return {
all: bookings.length,
pending: bookings.filter((b) => b.status === "pending").length,
confirmed: bookings.filter((b) => b.status === "confirmed").length,
completed: bookings.filter((b) => b.status === "completed").length,
cancelled: bookings.filter((b) => b.status === "cancelled").length,
};
}, [bookings]);
if (isLoading) {
return (
<Loading/>
);
}
return (
<div className="min-h-screen bg-gray-50 py-8" dir={isRtl ? "rtl" : "ltr"}>
<Toaster position="top-center" reverseOrder={false} />
<BookingDetailsModal booking={selectedBooking} isOpen={!!selectedBooking} onClose={() => setSelectedBooking(null)} />
<div className="container mx-auto px-4">
<div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">{t("myBookings")}</h1>
<p className="text-gray-600">{t("welcomeBookings", { name: name, count: bookings.length })}</p>
</div>
<button
onClick={() => setShowCalendar(!showCalendar)}
className="px-4 py-2 bg-white border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-50 transition-colors flex items-center gap-2 shadow-sm"
>
<Calendar className="w-5 h-5" />
{showCalendar ? t("hideCalendar") : t("showCalendar")}
</button>
</div>
<div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
{[
{ id: "all", label: "allBookings", count: statusCounts.all, color: "text-gray-900", active: "border-gray-900 bg-gray-50" },
{ id: "pending", label: "pending", count: statusCounts.pending, color: "text-yellow-600", active: "border-yellow-500 bg-yellow-50" },
{ id: "confirmed", label: "confirmed", count: statusCounts.confirmed, color: "text-green-600", active: "border-green-500 bg-green-50" },
{ id: "completed", label: "completed", count: statusCounts.completed, color: "text-gray-600", active: "border-gray-500 bg-gray-50" },
{ id: "cancelled", label: "cancelled", count: statusCounts.cancelled, color: "text-red-600", active: "border-red-500 bg-red-50" },
].map((item, index) => (
<motion.div
key={item.id}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05 * (index + 1) }}
className={`bg-white rounded-xl shadow-sm p-4 text-center border cursor-pointer hover:shadow-md transition-all ${filterStatus === item.id ? item.active : "border-gray-200"}`}
onClick={() => setFilterStatus(item.id)}
>
<div className={`text-2xl font-bold ${item.color}`}>{item.count}</div>
<div className="text-sm text-gray-600">{t(item.label)}</div>
</motion.div>
))}
</div>
<div className="flex flex-col md:flex-row gap-4 mb-6">
<div className="flex-1 relative">
<Search className={`absolute top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 ${isRtl ? "right-3" : "left-3"}`} />
<input
type="text"
placeholder={t("searchBookings")}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className={`w-full py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500 ${isRtl ? "pr-10 pl-4" : "pl-10 pr-4"}`}
/>
</div>
<div className="flex flex-wrap md:flex-nowrap gap-3">
<input
type="date"
value={dateRange.start}
onChange={(e) => setDateRange({ ...dateRange, start: e.target.value })}
className="px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500"
/>
<input
type="date"
value={dateRange.end}
onChange={(e) => setDateRange({ ...dateRange, end: e.target.value })}
className="px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-500"
/>
{(dateRange.start || dateRange.end) && (
<button onClick={() => setDateRange({ start: "", end: "" })} className="px-4 py-3 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition-colors">
{t("clear")}
</button>
)}
</div>
</div>
{showCalendar && (
<motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="mb-6">
<OwnerBookingCalendar property={{ bookings }} />
</motion.div>
)}
{filteredBookings.length === 0 ? (
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="bg-white rounded-2xl p-12 text-center border-2 border-dashed border-gray-300">
<div className="w-24 h-24 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-4">
<Calendar className="w-12 h-12 text-amber-600" />
</div>
<h3 className="text-xl font-bold text-gray-900 mb-2">{t("noBookings")}</h3>
<p className="text-gray-600 mb-4">{filterStatus !== "all" || searchTerm || dateRange.start || dateRange.end ? t("noBookingsInCategory") : t("noBookingsReceived")}</p>
{(filterStatus !== "all" || searchTerm || dateRange.start || dateRange.end) && (
<button
onClick={() => {
setFilterStatus("all");
setSearchTerm("");
setDateRange({ start: "", end: "" });
}}
className="inline-flex items-center gap-2 bg-amber-500 text-white px-6 py-3 rounded-xl font-medium hover:bg-amber-600 transition-colors"
>
{t("viewAllBookings")}
</button>
)}
</motion.div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{filteredBookings.map((booking) => (
<BookingCard key={booking.id} booking={booking} onViewDetails={setSelectedBooking} />
))}
</div>
)}
</div>
</div>
);
}