restructuring for rental requests. started double blind reviews
This commit is contained in:
1 parent
022c0b9c06
commit
5d85f77a19
15 files changed
+1305
-1403
No files matched your search
@@ -310,7 +310,7 @@ const AuthModal: React.FC<AuthModalProps> = ({
|
||||
<input
|
||||
type="tel"
|
||||
className="form-control"
|
||||
placeholder="(555) 123-4567"
|
||||
placeholder="(123) 456-7890"
|
||||
value={phoneNumber}
|
||||
onChange={handlePhoneChange}
|
||||
required
|
||||
|
||||
@@ -1,1000 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
interface UnavailablePeriod {
|
||||
id: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
isRentalSelection?: boolean;
|
||||
isAcceptedRental?: boolean;
|
||||
}
|
||||
|
||||
interface AvailabilityCalendarProps {
|
||||
unavailablePeriods: UnavailablePeriod[];
|
||||
onPeriodsChange: (periods: UnavailablePeriod[]) => void;
|
||||
mode: 'owner' | 'renter'; // Clear mode distinction
|
||||
onRentalSelect?: (period: { startDate: Date; endDate: Date; startTime?: string; endTime?: string }) => void;
|
||||
selectedRentalPeriod?: UnavailablePeriod; // External selection to display
|
||||
}
|
||||
|
||||
type ViewType = 'month' | 'week' | 'day';
|
||||
|
||||
const AvailabilityCalendar: React.FC<AvailabilityCalendarProps> = ({
|
||||
unavailablePeriods,
|
||||
onPeriodsChange,
|
||||
mode,
|
||||
onRentalSelect,
|
||||
selectedRentalPeriod: externalSelectedPeriod
|
||||
}) => {
|
||||
const [currentDate, setCurrentDate] = useState(new Date());
|
||||
const [viewType, setViewType] = useState<ViewType>('month');
|
||||
const [selectionStart, setSelectionStart] = useState<Date | null>(null);
|
||||
const [selectionStartHour, setSelectionStartHour] = useState<number | null>(null);
|
||||
const [internalSelectedPeriod, setInternalSelectedPeriod] = useState<UnavailablePeriod | null>(null);
|
||||
const [ownerSelectionStart, setOwnerSelectionStart] = useState<Date | null>(null);
|
||||
const [ownerSelectionStartHour, setOwnerSelectionStartHour] = useState<number | null>(null);
|
||||
|
||||
// Use external selection if provided, otherwise use internal
|
||||
const selectedRentalPeriod = externalSelectedPeriod || internalSelectedPeriod;
|
||||
|
||||
const getDaysInMonth = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = date.getMonth();
|
||||
const firstDay = new Date(year, month, 1);
|
||||
const lastDay = new Date(year, month + 1, 0);
|
||||
const daysInMonth = lastDay.getDate();
|
||||
const startingDayOfWeek = firstDay.getDay();
|
||||
|
||||
const days: (Date | null)[] = [];
|
||||
|
||||
// Add empty cells for days before month starts
|
||||
for (let i = 0; i < startingDayOfWeek; i++) {
|
||||
days.push(null);
|
||||
}
|
||||
|
||||
// Add all days in month
|
||||
for (let i = 1; i <= daysInMonth; i++) {
|
||||
days.push(new Date(year, month, i));
|
||||
}
|
||||
|
||||
return days;
|
||||
};
|
||||
|
||||
const getWeekDays = (date: Date) => {
|
||||
const startOfWeek = new Date(date);
|
||||
const day = startOfWeek.getDay();
|
||||
const diff = startOfWeek.getDate() - day;
|
||||
startOfWeek.setDate(diff);
|
||||
|
||||
const days: Date[] = [];
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const day = new Date(startOfWeek);
|
||||
day.setDate(startOfWeek.getDate() + i);
|
||||
days.push(day);
|
||||
}
|
||||
return days;
|
||||
};
|
||||
|
||||
const isDateInPeriod = (date: Date, period: UnavailablePeriod) => {
|
||||
const start = new Date(period.startDate);
|
||||
const end = new Date(period.endDate);
|
||||
const checkDate = new Date(date);
|
||||
|
||||
// Normalize all dates to midnight for comparison
|
||||
start.setHours(0, 0, 0, 0);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
checkDate.setHours(0, 0, 0, 0);
|
||||
|
||||
// Basic date range check
|
||||
return checkDate >= start && checkDate <= end;
|
||||
};
|
||||
|
||||
const isDateUnavailable = (date: Date) => {
|
||||
return unavailablePeriods.some(period => {
|
||||
const start = new Date(period.startDate);
|
||||
const end = new Date(period.endDate);
|
||||
start.setHours(0, 0, 0, 0);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
const checkDate = new Date(date);
|
||||
checkDate.setHours(0, 0, 0, 0);
|
||||
return checkDate >= start && checkDate <= end;
|
||||
});
|
||||
};
|
||||
|
||||
const isDateFullyUnavailable = (date: Date) => {
|
||||
// Check if there's a period that covers the entire day without specific times
|
||||
const hasFullDayPeriod = unavailablePeriods.some(period => {
|
||||
const start = new Date(period.startDate);
|
||||
const end = new Date(period.endDate);
|
||||
const checkDate = new Date(date);
|
||||
|
||||
start.setHours(0, 0, 0, 0);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
checkDate.setHours(0, 0, 0, 0);
|
||||
|
||||
return checkDate >= start && checkDate <= end && !period.startTime && !period.endTime;
|
||||
});
|
||||
|
||||
if (hasFullDayPeriod) return true;
|
||||
|
||||
// Check if all 24 hours are covered by hour-specific periods
|
||||
const dateStr = date.toISOString().split('T')[0];
|
||||
const hoursWithPeriods = new Set<number>();
|
||||
|
||||
unavailablePeriods.forEach(period => {
|
||||
const periodDateStr = new Date(period.startDate).toISOString().split('T')[0];
|
||||
if (periodDateStr === dateStr && period.startTime && period.endTime) {
|
||||
const startHour = parseInt(period.startTime.split(':')[0]);
|
||||
const endHour = parseInt(period.endTime.split(':')[0]);
|
||||
for (let h = startHour; h <= endHour; h++) {
|
||||
hoursWithPeriods.add(h);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return hoursWithPeriods.size === 24;
|
||||
};
|
||||
|
||||
const isDatePartiallyUnavailable = (date: Date) => {
|
||||
return isDateUnavailable(date) && !isDateFullyUnavailable(date);
|
||||
};
|
||||
|
||||
const isHourUnavailable = (date: Date, hour: number) => {
|
||||
return unavailablePeriods.some(period => {
|
||||
const start = new Date(period.startDate);
|
||||
const end = new Date(period.endDate);
|
||||
|
||||
// Check if date is within period
|
||||
const dateOnly = new Date(date);
|
||||
dateOnly.setHours(0, 0, 0, 0);
|
||||
start.setHours(0, 0, 0, 0);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
|
||||
if (dateOnly < start || dateOnly > end) return false;
|
||||
|
||||
// If no specific times, entire day is unavailable
|
||||
if (!period.startTime || !period.endTime) return true;
|
||||
|
||||
// Check specific hour
|
||||
const startHour = parseInt(period.startTime.split(':')[0]);
|
||||
const endHour = parseInt(period.endTime.split(':')[0]);
|
||||
|
||||
return hour >= startHour && hour <= endHour;
|
||||
});
|
||||
};
|
||||
|
||||
const handleHourClick = (date: Date, hour: number) => {
|
||||
if (mode !== 'renter') return;
|
||||
|
||||
// Check if this hour is unavailable
|
||||
if (isHourUnavailable(date, hour)) return;
|
||||
|
||||
if (!selectionStart || !selectionStartHour) {
|
||||
// First click - set start date and hour
|
||||
setSelectionStart(date);
|
||||
setSelectionStartHour(hour);
|
||||
setInternalSelectedPeriod(null);
|
||||
} else {
|
||||
// Second click - complete selection
|
||||
const startDate = new Date(selectionStart);
|
||||
const endDate = new Date(date);
|
||||
|
||||
// Determine which date/hour comes first
|
||||
let finalStart, finalEnd, startHour, endHour;
|
||||
|
||||
if (startDate.toDateString() === endDate.toDateString()) {
|
||||
// Same day - compare hours
|
||||
if (selectionStartHour <= hour) {
|
||||
finalStart = startDate;
|
||||
finalEnd = endDate;
|
||||
startHour = selectionStartHour;
|
||||
endHour = hour;
|
||||
} else {
|
||||
finalStart = endDate;
|
||||
finalEnd = startDate;
|
||||
startHour = hour;
|
||||
endHour = selectionStartHour;
|
||||
}
|
||||
} else if (startDate < endDate) {
|
||||
finalStart = startDate;
|
||||
finalEnd = endDate;
|
||||
startHour = selectionStartHour;
|
||||
endHour = hour;
|
||||
} else {
|
||||
finalStart = endDate;
|
||||
finalEnd = startDate;
|
||||
startHour = hour;
|
||||
endHour = selectionStartHour;
|
||||
}
|
||||
|
||||
// Set the hours
|
||||
finalStart.setHours(startHour, 0, 0, 0);
|
||||
finalEnd.setHours(endHour, 59, 59, 999);
|
||||
|
||||
// Check if any hour in range is unavailable
|
||||
let current = new Date(finalStart);
|
||||
let hasUnavailable = false;
|
||||
|
||||
while (current <= finalEnd) {
|
||||
const currentHour = current.getHours();
|
||||
if (isHourUnavailable(current, currentHour)) {
|
||||
hasUnavailable = true;
|
||||
break;
|
||||
}
|
||||
current.setHours(current.getHours() + 1);
|
||||
}
|
||||
|
||||
if (hasUnavailable) {
|
||||
// Range contains unavailable hours, reset
|
||||
setSelectionStart(null);
|
||||
setSelectionStartHour(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create rental selection
|
||||
const rentalPeriod: UnavailablePeriod = {
|
||||
id: 'rental-selection',
|
||||
startDate: finalStart,
|
||||
endDate: finalEnd,
|
||||
startTime: `${startHour.toString().padStart(2, '0')}:00`,
|
||||
endTime: `${endHour.toString().padStart(2, '0')}:00`,
|
||||
isRentalSelection: true
|
||||
};
|
||||
|
||||
setInternalSelectedPeriod(rentalPeriod);
|
||||
setSelectionStart(null);
|
||||
setSelectionStartHour(null);
|
||||
|
||||
// Notify parent
|
||||
if (onRentalSelect) {
|
||||
onRentalSelect({
|
||||
startDate: finalStart,
|
||||
endDate: finalEnd,
|
||||
startTime: `${startHour.toString().padStart(2, '0')}:00`,
|
||||
endTime: `${endHour.toString().padStart(2, '0')}:00`
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDateClick = (date: Date) => {
|
||||
if (mode === 'owner') {
|
||||
// OWNER MODE: Toggle unavailability for dates
|
||||
// Check if this date has an accepted rental - can't modify those
|
||||
const hasAcceptedRental = unavailablePeriods.some(p =>
|
||||
p.isAcceptedRental && isDateInPeriod(date, p)
|
||||
);
|
||||
|
||||
if (hasAcceptedRental) {
|
||||
return; // Can't modify dates with accepted rentals
|
||||
}
|
||||
|
||||
// Check if this date is part of any unavailable period
|
||||
const isUnavailable = isDateUnavailable(date);
|
||||
|
||||
if (isUnavailable && !ownerSelectionStart) {
|
||||
// Single click on an unavailable date - split periods to make just this date available
|
||||
const updatedPeriods: UnavailablePeriod[] = [];
|
||||
|
||||
unavailablePeriods.forEach(period => {
|
||||
if (period.isAcceptedRental || !isDateInPeriod(date, period)) {
|
||||
// Keep accepted rentals and periods that don't contain this date
|
||||
updatedPeriods.push(period);
|
||||
} else {
|
||||
// Split the period around this date
|
||||
const periodStart = new Date(period.startDate);
|
||||
const periodEnd = new Date(period.endDate);
|
||||
const targetDate = new Date(date);
|
||||
|
||||
periodStart.setHours(0, 0, 0, 0);
|
||||
periodEnd.setHours(0, 0, 0, 0);
|
||||
targetDate.setHours(0, 0, 0, 0);
|
||||
|
||||
// If there are dates before the target date, create a period for them
|
||||
if (periodStart < targetDate) {
|
||||
const beforeDate = new Date(targetDate);
|
||||
beforeDate.setDate(beforeDate.getDate() - 1);
|
||||
updatedPeriods.push({
|
||||
id: Date.now().toString() + '-before',
|
||||
startDate: periodStart,
|
||||
endDate: beforeDate,
|
||||
startTime: period.startTime,
|
||||
endTime: period.endTime
|
||||
});
|
||||
}
|
||||
|
||||
// If there are dates after the target date, create a period for them
|
||||
if (periodEnd > targetDate) {
|
||||
const afterDate = new Date(targetDate);
|
||||
afterDate.setDate(afterDate.getDate() + 1);
|
||||
updatedPeriods.push({
|
||||
id: Date.now().toString() + '-after',
|
||||
startDate: afterDate,
|
||||
endDate: periodEnd,
|
||||
startTime: period.startTime,
|
||||
endTime: period.endTime
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onPeriodsChange(updatedPeriods);
|
||||
setOwnerSelectionStart(null);
|
||||
} else if (!ownerSelectionStart) {
|
||||
// First click - start selection
|
||||
setOwnerSelectionStart(date);
|
||||
} else {
|
||||
// Second click - complete range selection
|
||||
const start = new Date(Math.min(ownerSelectionStart.getTime(), date.getTime()));
|
||||
const end = new Date(Math.max(ownerSelectionStart.getTime(), date.getTime()));
|
||||
|
||||
// Check if any date in range has accepted rental
|
||||
let current = new Date(start);
|
||||
let hasAcceptedInRange = false;
|
||||
while (current <= end) {
|
||||
if (unavailablePeriods.some(p => p.isAcceptedRental && isDateInPeriod(current, p))) {
|
||||
hasAcceptedInRange = true;
|
||||
break;
|
||||
}
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
|
||||
if (hasAcceptedInRange) {
|
||||
// Can't select range with accepted rentals
|
||||
setOwnerSelectionStart(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add new unavailable period for the range
|
||||
const newPeriod: UnavailablePeriod = {
|
||||
id: Date.now().toString(),
|
||||
startDate: start,
|
||||
endDate: end
|
||||
};
|
||||
onPeriodsChange([...unavailablePeriods, newPeriod]);
|
||||
setOwnerSelectionStart(null);
|
||||
}
|
||||
} else {
|
||||
// RENTER MODE: Select rental period
|
||||
// Check if date is unavailable
|
||||
if (isDateUnavailable(date)) {
|
||||
return; // Can't select unavailable dates
|
||||
}
|
||||
|
||||
if (!selectionStart) {
|
||||
// First click - set start date
|
||||
setSelectionStart(date);
|
||||
setSelectionStartHour(null); // Reset hour selection
|
||||
setInternalSelectedPeriod(null);
|
||||
} else {
|
||||
// Second click - complete selection
|
||||
const start = new Date(Math.min(selectionStart.getTime(), date.getTime()));
|
||||
const end = new Date(Math.max(selectionStart.getTime(), date.getTime()));
|
||||
|
||||
// Check if any date in range is unavailable
|
||||
let current = new Date(start);
|
||||
let hasUnavailable = false;
|
||||
while (current <= end) {
|
||||
if (isDateUnavailable(current)) {
|
||||
hasUnavailable = true;
|
||||
break;
|
||||
}
|
||||
current.setDate(current.getDate() + 1);
|
||||
}
|
||||
|
||||
if (hasUnavailable) {
|
||||
// Range contains unavailable dates, reset
|
||||
setSelectionStart(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create rental selection
|
||||
const rentalPeriod: UnavailablePeriod = {
|
||||
id: 'rental-selection',
|
||||
startDate: start,
|
||||
endDate: end,
|
||||
isRentalSelection: true
|
||||
};
|
||||
|
||||
setInternalSelectedPeriod(rentalPeriod);
|
||||
setSelectionStart(null);
|
||||
setSelectionStartHour(null);
|
||||
|
||||
// Notify parent if callback provided
|
||||
if (onRentalSelect) {
|
||||
onRentalSelect({
|
||||
startDate: start,
|
||||
endDate: end
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const toggleHourAvailability = (date: Date, hour: number) => {
|
||||
if (mode !== 'owner') return; // Only owners can toggle hour availability
|
||||
|
||||
// Check if this hour has an accepted rental
|
||||
const hasAcceptedRental = unavailablePeriods.some(p =>
|
||||
p.isAcceptedRental && isHourUnavailable(date, hour)
|
||||
);
|
||||
|
||||
if (hasAcceptedRental) {
|
||||
return; // Can't modify hours with accepted rentals
|
||||
}
|
||||
|
||||
const isUnavailable = isHourUnavailable(date, hour);
|
||||
|
||||
if (isUnavailable && !ownerSelectionStartHour) {
|
||||
// Make just this hour available by splitting periods
|
||||
const updatedPeriods: UnavailablePeriod[] = [];
|
||||
|
||||
unavailablePeriods.forEach(period => {
|
||||
if (period.isAcceptedRental || !isDateInPeriod(date, period)) {
|
||||
// Keep accepted rentals and periods that don't contain this date
|
||||
updatedPeriods.push(period);
|
||||
} else if (!period.startTime || !period.endTime) {
|
||||
// This is a full-day period, split it into hourly periods excluding this hour
|
||||
for (let h = 0; h < 24; h++) {
|
||||
if (h !== hour) {
|
||||
updatedPeriods.push({
|
||||
id: `${period.id}-hour-${h}`,
|
||||
startDate: date,
|
||||
endDate: date,
|
||||
startTime: `${h.toString().padStart(2, '0')}:00`,
|
||||
endTime: `${h.toString().padStart(2, '0')}:59`
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// This is an hourly period, check if it contains this hour
|
||||
const startHour = parseInt(period.startTime.split(':')[0]);
|
||||
const endHour = parseInt(period.endTime.split(':')[0]);
|
||||
|
||||
if (hour < startHour || hour > endHour) {
|
||||
// Hour is outside this period, keep the period
|
||||
updatedPeriods.push(period);
|
||||
} else {
|
||||
// Split the period around this hour
|
||||
if (startHour < hour) {
|
||||
updatedPeriods.push({
|
||||
id: period.id + '-before',
|
||||
startDate: period.startDate,
|
||||
endDate: period.endDate,
|
||||
startTime: period.startTime,
|
||||
endTime: `${(hour - 1).toString().padStart(2, '0')}:59`
|
||||
});
|
||||
}
|
||||
|
||||
if (endHour > hour) {
|
||||
updatedPeriods.push({
|
||||
id: period.id + '-after',
|
||||
startDate: period.startDate,
|
||||
endDate: period.endDate,
|
||||
startTime: `${(hour + 1).toString().padStart(2, '0')}:00`,
|
||||
endTime: period.endTime
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onPeriodsChange(updatedPeriods);
|
||||
setOwnerSelectionStart(null);
|
||||
setOwnerSelectionStartHour(null);
|
||||
} else if (!ownerSelectionStartHour) {
|
||||
// First click - start selection
|
||||
setOwnerSelectionStart(date);
|
||||
setOwnerSelectionStartHour(hour);
|
||||
} else {
|
||||
// Second click - complete selection
|
||||
const startDate = new Date(ownerSelectionStart!);
|
||||
const endDate = new Date(date);
|
||||
|
||||
// Determine which date/hour comes first
|
||||
let finalStart, finalEnd, startHour, endHour;
|
||||
|
||||
if (startDate.toDateString() === endDate.toDateString()) {
|
||||
// Same day - compare hours
|
||||
if (ownerSelectionStartHour <= hour) {
|
||||
finalStart = startDate;
|
||||
finalEnd = endDate;
|
||||
startHour = ownerSelectionStartHour;
|
||||
endHour = hour;
|
||||
} else {
|
||||
finalStart = endDate;
|
||||
finalEnd = startDate;
|
||||
startHour = hour;
|
||||
endHour = ownerSelectionStartHour;
|
||||
}
|
||||
} else if (startDate < endDate) {
|
||||
finalStart = startDate;
|
||||
finalEnd = endDate;
|
||||
startHour = ownerSelectionStartHour;
|
||||
endHour = hour;
|
||||
} else {
|
||||
finalStart = endDate;
|
||||
finalEnd = startDate;
|
||||
startHour = hour;
|
||||
endHour = ownerSelectionStartHour;
|
||||
}
|
||||
|
||||
// Check if any hour in range has accepted rental
|
||||
let current = new Date(finalStart);
|
||||
current.setHours(startHour, 0, 0, 0);
|
||||
const endDateTime = new Date(finalEnd);
|
||||
endDateTime.setHours(endHour, 59, 59, 999);
|
||||
let hasAcceptedInRange = false;
|
||||
|
||||
while (current <= endDateTime) {
|
||||
const currentHour = current.getHours();
|
||||
if (unavailablePeriods.some(p =>
|
||||
p.isAcceptedRental && isHourUnavailable(current, currentHour)
|
||||
)) {
|
||||
hasAcceptedInRange = true;
|
||||
break;
|
||||
}
|
||||
current.setHours(current.getHours() + 1);
|
||||
}
|
||||
|
||||
if (hasAcceptedInRange) {
|
||||
// Can't select range with accepted rentals
|
||||
setOwnerSelectionStart(null);
|
||||
setOwnerSelectionStartHour(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create unavailable period
|
||||
const newPeriod: UnavailablePeriod = {
|
||||
id: Date.now().toString(),
|
||||
startDate: finalStart,
|
||||
endDate: finalEnd,
|
||||
startTime: `${startHour.toString().padStart(2, '0')}:00`,
|
||||
endTime: `${endHour.toString().padStart(2, '0')}:59`
|
||||
};
|
||||
|
||||
onPeriodsChange([...unavailablePeriods, newPeriod]);
|
||||
setOwnerSelectionStart(null);
|
||||
setOwnerSelectionStartHour(null);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
};
|
||||
|
||||
const renderMonthView = () => {
|
||||
const days = getDaysInMonth(currentDate);
|
||||
const monthName = currentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
|
||||
|
||||
return (
|
||||
<>
|
||||
<h6 className="text-center mb-3">{monthName}</h6>
|
||||
<div className="d-grid" style={{ gridTemplateColumns: 'repeat(7, 1fr)', gap: '2px' }}>
|
||||
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
|
||||
<div key={day} className="text-center fw-bold p-2">
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
{days.map((date, index) => {
|
||||
let className = 'p-2 text-center';
|
||||
let title = '';
|
||||
let backgroundColor = undefined;
|
||||
|
||||
if (date) {
|
||||
className += ' border cursor-pointer';
|
||||
|
||||
if (mode === 'owner') {
|
||||
// OWNER VIEW
|
||||
const acceptedRental = unavailablePeriods.find(p =>
|
||||
p.isAcceptedRental && isDateInPeriod(date, p)
|
||||
);
|
||||
const isOwnerStart = ownerSelectionStart && date.getTime() === ownerSelectionStart.getTime();
|
||||
|
||||
if (acceptedRental) {
|
||||
className += ' text-white';
|
||||
title = 'Booked - This date has an accepted rental';
|
||||
backgroundColor = '#6f42c1';
|
||||
} else if (isOwnerStart) {
|
||||
className += ' bg-warning text-dark';
|
||||
title = 'Click another date to mark range as unavailable';
|
||||
} else if (isDateFullyUnavailable(date)) {
|
||||
className += ' bg-danger text-white';
|
||||
title = 'Unavailable - Click to make available';
|
||||
} else if (isDatePartiallyUnavailable(date)) {
|
||||
className += ' text-dark';
|
||||
title = 'Partially unavailable - Switch to week/day view for details';
|
||||
backgroundColor = '#ffeb3b';
|
||||
} else {
|
||||
className += ' bg-light';
|
||||
title = ownerSelectionStart ? 'Click to complete selection' : 'Click to start selecting unavailable dates';
|
||||
}
|
||||
} else {
|
||||
// RENTER VIEW
|
||||
let isInSelectedPeriod = false;
|
||||
if (selectedRentalPeriod) {
|
||||
// Special handling for rental selections with specific end times
|
||||
if (selectedRentalPeriod.endTime === '00:00') {
|
||||
// If end time is midnight, don't include the end date in highlighting
|
||||
const start = new Date(selectedRentalPeriod.startDate);
|
||||
const end = new Date(selectedRentalPeriod.endDate);
|
||||
const checkDate = new Date(date);
|
||||
|
||||
start.setHours(0, 0, 0, 0);
|
||||
end.setHours(0, 0, 0, 0);
|
||||
checkDate.setHours(0, 0, 0, 0);
|
||||
|
||||
// Exclude the end date if end time is 00:00
|
||||
isInSelectedPeriod = checkDate >= start && checkDate < end;
|
||||
} else {
|
||||
isInSelectedPeriod = isDateInPeriod(date, selectedRentalPeriod);
|
||||
}
|
||||
}
|
||||
const isSelectionStart = selectionStart && date.getTime() === selectionStart.getTime();
|
||||
|
||||
if (isDateFullyUnavailable(date)) {
|
||||
className += ' bg-danger text-white';
|
||||
} else if (isDatePartiallyUnavailable(date)) {
|
||||
className += ' text-dark';
|
||||
backgroundColor = '#ffeb3b';
|
||||
} else if (isInSelectedPeriod) {
|
||||
className += ' bg-success text-white';
|
||||
} else if (isSelectionStart) {
|
||||
className += ' bg-success bg-opacity-50 text-dark';
|
||||
} else {
|
||||
className += ' bg-light';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={className}
|
||||
onClick={() => date && handleDateClick(date)}
|
||||
style={{
|
||||
minHeight: '40px',
|
||||
cursor: date ? 'pointer' : 'default',
|
||||
backgroundColor: backgroundColor
|
||||
}}
|
||||
title={mode === 'owner' && date ? title : ''}
|
||||
>
|
||||
{date?.getDate()}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const renderWeekView = () => {
|
||||
const days = getWeekDays(currentDate);
|
||||
const weekRange = `${formatDate(days[0])} - ${formatDate(days[6])}`;
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h6 className="text-center mb-3">{weekRange}</h6>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table className="table table-bordered table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: '60px' }}>Time</th>
|
||||
{days.map((date, index) => (
|
||||
<th key={index} className="text-center" style={{ minWidth: '100px' }}>
|
||||
<div>{date.toLocaleDateString('en-US', { weekday: 'short' })}</div>
|
||||
<div>{date.getDate()}</div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{hours.map(hour => (
|
||||
<tr key={hour}>
|
||||
<td className="text-center small" style={{ paddingBottom: '12px' }}>
|
||||
{hour === 0 ? '12 AM' : hour === 12 ? '12 PM' : hour < 12 ? `${hour} AM` : `${hour - 12} PM`}
|
||||
</td>
|
||||
{days.map((date, dayIndex) => {
|
||||
const isUnavailable = isHourUnavailable(date, hour);
|
||||
const isClickable = mode === 'owner';
|
||||
const isOwnerSelectionStart = mode === 'owner' && ownerSelectionStart &&
|
||||
date.toDateString() === ownerSelectionStart.toDateString() &&
|
||||
hour === ownerSelectionStartHour;
|
||||
|
||||
// Check if this hour is in the selected period
|
||||
let isInSelectedPeriod = false;
|
||||
if (mode === 'renter' && selectedRentalPeriod) {
|
||||
const cellDate = new Date(date);
|
||||
cellDate.setHours(0, 0, 0, 0);
|
||||
const selStartDate = new Date(selectedRentalPeriod.startDate);
|
||||
selStartDate.setHours(0, 0, 0, 0);
|
||||
const selEndDate = new Date(selectedRentalPeriod.endDate);
|
||||
selEndDate.setHours(0, 0, 0, 0);
|
||||
|
||||
// Check if date is in range
|
||||
if (cellDate >= selStartDate && cellDate <= selEndDate) {
|
||||
// If times are specified, check hour range
|
||||
if (selectedRentalPeriod.startTime && selectedRentalPeriod.endTime) {
|
||||
const [startHour] = selectedRentalPeriod.startTime.split(':').map(Number);
|
||||
const [endHour] = selectedRentalPeriod.endTime.split(':').map(Number);
|
||||
|
||||
if (cellDate.getTime() === selStartDate.getTime() && cellDate.getTime() === selEndDate.getTime()) {
|
||||
// Same day - check if hour is in range (end hour is exclusive)
|
||||
isInSelectedPeriod = hour >= startHour && hour < endHour;
|
||||
} else if (cellDate.getTime() === selStartDate.getTime()) {
|
||||
// Start day - check if hour is after or at start hour
|
||||
isInSelectedPeriod = hour >= startHour;
|
||||
} else if (cellDate.getTime() === selEndDate.getTime()) {
|
||||
// End day - check if hour is before end hour (exclusive)
|
||||
isInSelectedPeriod = hour < endHour;
|
||||
} else {
|
||||
// Middle day - all hours selected
|
||||
isInSelectedPeriod = true;
|
||||
}
|
||||
} else {
|
||||
isInSelectedPeriod = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isSelectionStart = mode === 'renter' && selectionStart &&
|
||||
date.toDateString() === selectionStart.toDateString() &&
|
||||
hour === selectionStartHour;
|
||||
|
||||
let cellClass = 'text-center p-1';
|
||||
if (isUnavailable) {
|
||||
cellClass += ' bg-danger text-white';
|
||||
} else if (isInSelectedPeriod) {
|
||||
cellClass += ' bg-success text-white';
|
||||
} else if (isOwnerSelectionStart) {
|
||||
cellClass += ' bg-warning text-dark';
|
||||
} else if (isSelectionStart) {
|
||||
cellClass += ' bg-success bg-opacity-50 text-dark';
|
||||
} else {
|
||||
cellClass += ' bg-light';
|
||||
}
|
||||
cellClass += (isClickable || (mode === 'renter' && !isUnavailable)) ? ' cursor-pointer' : '';
|
||||
|
||||
return (
|
||||
<td
|
||||
key={dayIndex}
|
||||
className={cellClass}
|
||||
onClick={() => {
|
||||
if (mode === 'owner') {
|
||||
toggleHourAvailability(date, hour);
|
||||
} else if (mode === 'renter' && !isUnavailable) {
|
||||
handleHourClick(date, hour);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
cursor: (isClickable || (mode === 'renter' && !isUnavailable)) ? 'pointer' : 'default',
|
||||
height: '40px',
|
||||
borderLeft: dayIndex === 0 ? '1px solid #dee2e6' : 'none'
|
||||
}}
|
||||
title={
|
||||
mode === 'owner'
|
||||
? (isUnavailable ? 'Click to make this hour available' : (ownerSelectionStartHour !== null ? 'Click to complete selection' : 'Click to start selecting unavailable hours'))
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{isUnavailable && <span style={{ fontSize: '1.2rem' }}>×</span>}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const renderDayView = () => {
|
||||
const dayName = currentDate.toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h6 className="text-center mb-3">{dayName}</h6>
|
||||
<div style={{ maxHeight: '500px', overflowY: 'auto' }}>
|
||||
<table className="table table-bordered">
|
||||
<tbody>
|
||||
{hours.map(hour => {
|
||||
const isUnavailable = isHourUnavailable(currentDate, hour);
|
||||
const isClickable = mode === 'owner';
|
||||
const isOwnerSelectionStart = mode === 'owner' && ownerSelectionStart &&
|
||||
currentDate.toDateString() === ownerSelectionStart.toDateString() &&
|
||||
hour === ownerSelectionStartHour;
|
||||
|
||||
// Check if this hour is in the selected period
|
||||
let isInSelectedPeriod = false;
|
||||
if (mode === 'renter' && selectedRentalPeriod) {
|
||||
const cellDate = new Date(currentDate);
|
||||
cellDate.setHours(0, 0, 0, 0);
|
||||
const selStartDate = new Date(selectedRentalPeriod.startDate);
|
||||
selStartDate.setHours(0, 0, 0, 0);
|
||||
const selEndDate = new Date(selectedRentalPeriod.endDate);
|
||||
selEndDate.setHours(0, 0, 0, 0);
|
||||
|
||||
// Check if date is in range
|
||||
if (cellDate >= selStartDate && cellDate <= selEndDate) {
|
||||
// If times are specified, check hour range
|
||||
if (selectedRentalPeriod.startTime && selectedRentalPeriod.endTime) {
|
||||
const [startHour] = selectedRentalPeriod.startTime.split(':').map(Number);
|
||||
const [endHour] = selectedRentalPeriod.endTime.split(':').map(Number);
|
||||
|
||||
if (cellDate.getTime() === selStartDate.getTime() && cellDate.getTime() === selEndDate.getTime()) {
|
||||
// Same day - check if hour is in range (end hour is exclusive)
|
||||
isInSelectedPeriod = hour >= startHour && hour < endHour;
|
||||
} else if (cellDate.getTime() === selStartDate.getTime()) {
|
||||
// Start day - check if hour is after or at start hour
|
||||
isInSelectedPeriod = hour >= startHour;
|
||||
} else if (cellDate.getTime() === selEndDate.getTime()) {
|
||||
// End day - check if hour is before end hour (exclusive)
|
||||
isInSelectedPeriod = hour < endHour;
|
||||
} else {
|
||||
// Middle day - all hours selected
|
||||
isInSelectedPeriod = true;
|
||||
}
|
||||
} else {
|
||||
isInSelectedPeriod = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isSelectionStart = mode === 'renter' && selectionStart &&
|
||||
currentDate.toDateString() === selectionStart.toDateString() &&
|
||||
hour === selectionStartHour;
|
||||
|
||||
let cellClass = 'text-center p-3';
|
||||
if (isUnavailable) {
|
||||
cellClass += ' bg-danger text-white';
|
||||
} else if (isInSelectedPeriod) {
|
||||
cellClass += ' bg-success text-white';
|
||||
} else if (isOwnerSelectionStart) {
|
||||
cellClass += ' bg-warning text-dark';
|
||||
} else if (isSelectionStart) {
|
||||
cellClass += ' bg-success bg-opacity-50 text-dark';
|
||||
} else {
|
||||
cellClass += ' bg-light';
|
||||
}
|
||||
cellClass += (isClickable || (mode === 'renter' && !isUnavailable)) ? ' cursor-pointer' : '';
|
||||
|
||||
return (
|
||||
<tr key={hour}>
|
||||
<td className="text-center" style={{ width: '100px' }}>
|
||||
{hour === 0 ? '12:00 AM' : hour === 12 ? '12:00 PM' : hour < 12 ? `${hour}:00 AM` : `${hour - 12}:00 PM`}
|
||||
</td>
|
||||
<td
|
||||
className={cellClass}
|
||||
onClick={() => {
|
||||
if (mode === 'owner') {
|
||||
toggleHourAvailability(currentDate, hour);
|
||||
} else if (mode === 'renter' && !isUnavailable) {
|
||||
handleHourClick(currentDate, hour);
|
||||
}
|
||||
}}
|
||||
style={{ cursor: (isClickable || (mode === 'renter' && !isUnavailable)) ? 'pointer' : 'default' }}
|
||||
title={
|
||||
mode === 'owner'
|
||||
? (isUnavailable ? 'Click to make this hour available' : (ownerSelectionStartHour !== null ? 'Click to complete selection' : 'Click to start selecting unavailable hours'))
|
||||
: ''
|
||||
}
|
||||
>
|
||||
{isUnavailable ? 'Unavailable' : 'Available'}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const navigateDate = (direction: 'prev' | 'next') => {
|
||||
const newDate = new Date(currentDate);
|
||||
|
||||
switch (viewType) {
|
||||
case 'month':
|
||||
newDate.setMonth(newDate.getMonth() + (direction === 'next' ? 1 : -1));
|
||||
break;
|
||||
case 'week':
|
||||
newDate.setDate(newDate.getDate() + (direction === 'next' ? 7 : -7));
|
||||
break;
|
||||
case 'day':
|
||||
newDate.setDate(newDate.getDate() + (direction === 'next' ? 1 : -1));
|
||||
break;
|
||||
}
|
||||
|
||||
setCurrentDate(newDate);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="availability-calendar">
|
||||
<div className="d-flex justify-content-between align-items-center mb-3">
|
||||
<div className="btn-group" role="group">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${viewType === 'month' ? 'btn-primary' : 'btn-outline-primary'}`}
|
||||
onClick={() => setViewType('month')}
|
||||
>
|
||||
Month
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${viewType === 'week' ? 'btn-primary' : 'btn-outline-primary'}`}
|
||||
onClick={() => setViewType('week')}
|
||||
>
|
||||
Week
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-sm ${viewType === 'day' ? 'btn-primary' : 'btn-outline-primary'}`}
|
||||
onClick={() => setViewType('day')}
|
||||
>
|
||||
Day
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-outline-secondary me-2"
|
||||
onClick={() => navigateDate('prev')}
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-sm btn-outline-secondary"
|
||||
onClick={() => navigateDate('next')}
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="calendar-view mb-3">
|
||||
{viewType === 'month' && renderMonthView()}
|
||||
{viewType === 'week' && renderWeekView()}
|
||||
{viewType === 'day' && renderDayView()}
|
||||
</div>
|
||||
|
||||
<div className="text-muted small">
|
||||
<div className="d-flex gap-3 justify-content-center flex-wrap">
|
||||
<span><span className="badge bg-light text-dark">□</span> Available</span>
|
||||
{mode === 'renter' && selectedRentalPeriod && (
|
||||
<span><span className="badge bg-success">□</span> Your Selection</span>
|
||||
)}
|
||||
{mode === 'owner' && ownerSelectionStart && (
|
||||
<span><span className="badge bg-warning text-dark">□</span> Selection Start</span>
|
||||
)}
|
||||
{mode === 'owner' && (
|
||||
<span><span className="badge text-white" style={{ backgroundColor: '#6f42c1' }}>□</span> Booked Rental</span>
|
||||
)}
|
||||
{viewType === 'month' && (
|
||||
<span><span className="badge text-dark" style={{ backgroundColor: '#ffeb3b' }}>□</span> Partially Unavailable</span>
|
||||
)}
|
||||
<span><span className="badge bg-danger">□</span> {mode === 'owner' ? 'Marked Unavailable' : 'Not Available'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AvailabilityCalendar;
|
||||
@@ -148,18 +148,18 @@ const Navbar: React.FC = () => {
|
||||
<li>
|
||||
<Link className="dropdown-item" to="/my-rentals">
|
||||
<i className="bi bi-calendar-check me-2"></i>
|
||||
Rentals
|
||||
Renting
|
||||
</Link>
|
||||
</li>
|
||||
<li>
|
||||
<Link className="dropdown-item" to="/my-listings">
|
||||
<i className="bi bi-list-ul me-2"></i>Listings
|
||||
<i className="bi bi-list-ul me-2"></i>Owning
|
||||
</Link>
|
||||
</li>
|
||||
<li>
|
||||
<Link className="dropdown-item" to="/my-requests">
|
||||
<i className="bi bi-clipboard-check me-2"></i>
|
||||
Requests
|
||||
Looking For
|
||||
</Link>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
@@ -2,16 +2,17 @@ import React, { useState } from 'react';
|
||||
import { rentalAPI } from '../services/api';
|
||||
import { Rental } from '../types';
|
||||
|
||||
interface ReviewModalProps {
|
||||
interface ReviewItemModalProps {
|
||||
show: boolean;
|
||||
onClose: () => void;
|
||||
rental: Rental;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSuccess }) => {
|
||||
const ReviewItemModal: React.FC<ReviewItemModalProps> = ({ show, onClose, rental, onSuccess }) => {
|
||||
const [rating, setRating] = useState(5);
|
||||
const [review, setReview] = useState('');
|
||||
const [privateMessage, setPrivateMessage] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -21,16 +22,25 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
|
||||
setSubmitting(true);
|
||||
|
||||
try {
|
||||
await rentalAPI.addReview(rental.id, {
|
||||
const response = await rentalAPI.reviewItem(rental.id, {
|
||||
rating,
|
||||
review
|
||||
review,
|
||||
privateMessage
|
||||
});
|
||||
|
||||
// Reset form
|
||||
setRating(5);
|
||||
setReview('');
|
||||
setPrivateMessage('');
|
||||
onSuccess();
|
||||
onClose();
|
||||
|
||||
// Show success message based on review visibility
|
||||
if (response.data.reviewVisible) {
|
||||
alert('Review published successfully!');
|
||||
} else {
|
||||
alert('Review submitted! It will be published when both parties have reviewed or after 10 minutes.');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Failed to submit review');
|
||||
} finally {
|
||||
@@ -49,7 +59,7 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
|
||||
<div className="modal-dialog modal-dialog-centered">
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Review Your Rental</h5>
|
||||
<h5 className="modal-title">Review Item</h5>
|
||||
<button type="button" className="btn-close" onClick={onClose}></button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
@@ -96,7 +106,9 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label htmlFor="review" className="form-label">Your Review</label>
|
||||
<label htmlFor="review" className="form-label">
|
||||
Public Review <span className="text-danger">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
id="review"
|
||||
@@ -108,7 +120,25 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
|
||||
disabled={submitting}
|
||||
></textarea>
|
||||
<small className="text-muted">
|
||||
Tell others about the item condition, owner communication, and overall experience
|
||||
This will be visible to everyone. Tell others about the item condition, owner communication, and overall experience.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label htmlFor="privateMessage" className="form-label">
|
||||
Private Message to Owner <span className="text-muted">(Optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
id="privateMessage"
|
||||
rows={3}
|
||||
value={privateMessage}
|
||||
onChange={(e) => setPrivateMessage(e.target.value)}
|
||||
placeholder="Send a private message to the owner (only they will see this)..."
|
||||
disabled={submitting}
|
||||
></textarea>
|
||||
<small className="text-muted">
|
||||
This message will only be visible to the owner. Use this for specific feedback or suggestions.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
@@ -143,4 +173,4 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
|
||||
);
|
||||
};
|
||||
|
||||
export default ReviewModal;
|
||||
export default ReviewItemModal;
|
||||
@@ -0,0 +1,176 @@
|
||||
import React, { useState } from 'react';
|
||||
import { rentalAPI } from '../services/api';
|
||||
import { Rental } from '../types';
|
||||
|
||||
interface ReviewRenterModalProps {
|
||||
show: boolean;
|
||||
onClose: () => void;
|
||||
rental: Rental;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const ReviewRenterModal: React.FC<ReviewRenterModalProps> = ({ show, onClose, rental, onSuccess }) => {
|
||||
const [rating, setRating] = useState(5);
|
||||
const [review, setReview] = useState('');
|
||||
const [privateMessage, setPrivateMessage] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSubmitting(true);
|
||||
|
||||
try {
|
||||
const response = await rentalAPI.reviewRenter(rental.id, {
|
||||
rating,
|
||||
review,
|
||||
privateMessage
|
||||
});
|
||||
|
||||
// Reset form
|
||||
setRating(5);
|
||||
setReview('');
|
||||
setPrivateMessage('');
|
||||
onSuccess();
|
||||
onClose();
|
||||
|
||||
// Show success message based on review visibility
|
||||
if (response.data.reviewVisible) {
|
||||
alert('Review published successfully!');
|
||||
} else {
|
||||
alert('Review submitted! It will be published when both parties have reviewed or after 10 minutes.');
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.error || 'Failed to submit review');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStarClick = (value: number) => {
|
||||
setRating(value);
|
||||
};
|
||||
|
||||
if (!show) return null;
|
||||
|
||||
return (
|
||||
<div className="modal d-block" tabIndex={-1} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
|
||||
<div className="modal-dialog modal-dialog-centered">
|
||||
<div className="modal-content">
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Review Renter</h5>
|
||||
<button type="button" className="btn-close" onClick={onClose}></button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="modal-body">
|
||||
{rental.renter && (
|
||||
<div className="mb-4 text-center">
|
||||
<h6>{rental.renter.firstName} {rental.renter.lastName}</h6>
|
||||
<small className="text-muted">
|
||||
Rental period: {new Date(rental.startDate).toLocaleDateString()} to {new Date(rental.endDate).toLocaleDateString()}
|
||||
</small>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="alert alert-danger" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="form-label">Rating</label>
|
||||
<div className="d-flex justify-content-center gap-1" style={{ fontSize: '2rem' }}>
|
||||
{[1, 2, 3, 4, 5].map((star) => (
|
||||
<button
|
||||
key={star}
|
||||
type="button"
|
||||
className="btn btn-link p-0 text-decoration-none"
|
||||
onClick={() => handleStarClick(star)}
|
||||
style={{ color: star <= rating ? '#ffc107' : '#dee2e6' }}
|
||||
>
|
||||
<i className={`bi ${star <= rating ? 'bi-star-fill' : 'bi-star'}`}></i>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-center mt-2">
|
||||
<small className="text-muted">
|
||||
{rating === 1 && 'Poor'}
|
||||
{rating === 2 && 'Fair'}
|
||||
{rating === 3 && 'Good'}
|
||||
{rating === 4 && 'Very Good'}
|
||||
{rating === 5 && 'Excellent'}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label htmlFor="review" className="form-label">
|
||||
Public Review <span className="text-danger">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
id="review"
|
||||
rows={4}
|
||||
value={review}
|
||||
onChange={(e) => setReview(e.target.value)}
|
||||
placeholder="Share your experience with this renter..."
|
||||
required
|
||||
disabled={submitting}
|
||||
></textarea>
|
||||
<small className="text-muted">
|
||||
This will be visible to everyone. Consider communication, condition of returned item, timeliness, and overall experience.
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label htmlFor="privateMessage" className="form-label">
|
||||
Private Message to Renter <span className="text-muted">(Optional)</span>
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
id="privateMessage"
|
||||
rows={3}
|
||||
value={privateMessage}
|
||||
onChange={(e) => setPrivateMessage(e.target.value)}
|
||||
placeholder="Send a private message to the renter (only they will see this)..."
|
||||
disabled={submitting}
|
||||
></textarea>
|
||||
<small className="text-muted">
|
||||
This message will only be visible to the renter. Use this for specific feedback or suggestions.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onClose}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary"
|
||||
disabled={submitting || !review.trim()}
|
||||
>
|
||||
{submitting ? (
|
||||
<>
|
||||
<span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
|
||||
Submitting...
|
||||
</>
|
||||
) : (
|
||||
'Submit Review'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ReviewRenterModal;
|
||||
@@ -110,15 +110,80 @@ const ItemDetail: React.FC = () => {
|
||||
setTotalCost(cost);
|
||||
};
|
||||
|
||||
const generateTimeOptions = () => {
|
||||
const generateTimeOptions = (item: Item | null, selectedDate: string) => {
|
||||
const options = [];
|
||||
let availableAfter = "00:00";
|
||||
let availableBefore = "23:59";
|
||||
|
||||
console.log('generateTimeOptions called with:', {
|
||||
itemId: item?.id,
|
||||
selectedDate,
|
||||
hasItem: !!item
|
||||
});
|
||||
|
||||
// Determine time constraints only if we have both item and a valid selected date
|
||||
if (item && selectedDate && selectedDate.trim() !== "") {
|
||||
const date = new Date(selectedDate);
|
||||
const dayName = date.toLocaleDateString('en-US', { weekday: 'long' }).toLowerCase() as
|
||||
'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday';
|
||||
|
||||
console.log('Date analysis:', {
|
||||
selectedDate,
|
||||
dayName,
|
||||
specifyTimesPerDay: item.specifyTimesPerDay,
|
||||
hasWeeklyTimes: !!item.weeklyTimes,
|
||||
globalAvailableAfter: item.availableAfter,
|
||||
globalAvailableBefore: item.availableBefore
|
||||
});
|
||||
|
||||
// Use day-specific times if available
|
||||
if (item.specifyTimesPerDay && item.weeklyTimes && item.weeklyTimes[dayName]) {
|
||||
const dayTimes = item.weeklyTimes[dayName];
|
||||
availableAfter = dayTimes.availableAfter;
|
||||
availableBefore = dayTimes.availableBefore;
|
||||
console.log('Using day-specific times:', { availableAfter, availableBefore });
|
||||
}
|
||||
// Otherwise use global times
|
||||
else if (item.availableAfter && item.availableBefore) {
|
||||
availableAfter = item.availableAfter;
|
||||
availableBefore = item.availableBefore;
|
||||
console.log('Using global times:', { availableAfter, availableBefore });
|
||||
} else {
|
||||
console.log('No time constraints found, using default 24-hour availability');
|
||||
}
|
||||
} else {
|
||||
console.log('Missing item or selectedDate, using default 24-hour availability');
|
||||
}
|
||||
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
const time24 = `${hour.toString().padStart(2, "0")}:00`;
|
||||
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
|
||||
const period = hour < 12 ? "AM" : "PM";
|
||||
const time12 = `${hour12}:00 ${period}`;
|
||||
options.push({ value: time24, label: time12 });
|
||||
|
||||
// Ensure consistent format for comparison (normalize to HH:MM)
|
||||
const normalizedAvailableAfter = availableAfter.length === 5 ? availableAfter : availableAfter + ":00";
|
||||
const normalizedAvailableBefore = availableBefore.length === 5 ? availableBefore : availableBefore + ":00";
|
||||
|
||||
// Check if this time is within the available range
|
||||
if (time24 >= normalizedAvailableAfter && time24 <= normalizedAvailableBefore) {
|
||||
const hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
|
||||
const period = hour < 12 ? "AM" : "PM";
|
||||
const time12 = `${hour12}:00 ${period}`;
|
||||
options.push({ value: time24, label: time12 });
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Time filtering results:', {
|
||||
availableAfter,
|
||||
availableBefore,
|
||||
optionsGenerated: options.length,
|
||||
firstFewOptions: options.slice(0, 3)
|
||||
});
|
||||
|
||||
// If no options are available, return at least one option to prevent empty dropdown
|
||||
if (options.length === 0) {
|
||||
console.log('No valid time options found, showing Not Available');
|
||||
options.push({ value: "00:00", label: "Not Available" });
|
||||
}
|
||||
|
||||
return options;
|
||||
};
|
||||
|
||||
@@ -126,6 +191,34 @@ const ItemDetail: React.FC = () => {
|
||||
calculateTotalCost();
|
||||
}, [rentalDates, item]);
|
||||
|
||||
// Validate and adjust selected times based on item availability
|
||||
useEffect(() => {
|
||||
if (!item) return;
|
||||
|
||||
const validateAndAdjustTime = (date: string, currentTime: string) => {
|
||||
if (!date) return currentTime;
|
||||
|
||||
const availableOptions = generateTimeOptions(item, date);
|
||||
if (availableOptions.length === 0) return currentTime;
|
||||
|
||||
// If current time is not in available options, use the first available time
|
||||
const isCurrentTimeValid = availableOptions.some(option => option.value === currentTime);
|
||||
return isCurrentTimeValid ? currentTime : availableOptions[0].value;
|
||||
};
|
||||
|
||||
const adjustedStartTime = validateAndAdjustTime(rentalDates.startDate, rentalDates.startTime);
|
||||
const adjustedEndTime = validateAndAdjustTime(rentalDates.endDate || rentalDates.startDate, rentalDates.endTime);
|
||||
|
||||
// Update state if times have changed
|
||||
if (adjustedStartTime !== rentalDates.startTime || adjustedEndTime !== rentalDates.endTime) {
|
||||
setRentalDates(prev => ({
|
||||
...prev,
|
||||
startTime: adjustedStartTime,
|
||||
endTime: adjustedEndTime
|
||||
}));
|
||||
}
|
||||
}, [item, rentalDates.startDate, rentalDates.endDate]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="container mt-5">
|
||||
@@ -392,8 +485,9 @@ const ItemDetail: React.FC = () => {
|
||||
handleDateTimeChange("startTime", e.target.value)
|
||||
}
|
||||
style={{ flex: '1 1 50%' }}
|
||||
disabled={!!(rentalDates.startDate && generateTimeOptions(item, rentalDates.startDate).every(opt => opt.label === "Not Available"))}
|
||||
>
|
||||
{generateTimeOptions().map((option) => (
|
||||
{generateTimeOptions(item, rentalDates.startDate).map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
@@ -425,8 +519,9 @@ const ItemDetail: React.FC = () => {
|
||||
handleDateTimeChange("endTime", e.target.value)
|
||||
}
|
||||
style={{ flex: '1 1 50%' }}
|
||||
disabled={!!((rentalDates.endDate || rentalDates.startDate) && generateTimeOptions(item, rentalDates.endDate || rentalDates.startDate).every(opt => opt.label === "Not Available"))}
|
||||
>
|
||||
{generateTimeOptions().map((option) => (
|
||||
{generateTimeOptions(item, rentalDates.endDate || rentalDates.startDate).map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
|
||||
+273
-226
@@ -4,18 +4,43 @@ import { useAuth } from "../contexts/AuthContext";
|
||||
import api from "../services/api";
|
||||
import { Item, Rental } from "../types";
|
||||
import { rentalAPI } from "../services/api";
|
||||
import ReviewRenterModal from "../components/ReviewRenterModal";
|
||||
|
||||
const MyListings: React.FC = () => {
|
||||
// Helper function to format time
|
||||
const formatTime = (timeString?: string) => {
|
||||
if (!timeString || timeString.trim() === "") return "";
|
||||
try {
|
||||
const [hour, minute] = timeString.split(":");
|
||||
const hourNum = parseInt(hour);
|
||||
const hour12 = hourNum === 0 ? 12 : hourNum > 12 ? hourNum - 12 : hourNum;
|
||||
const period = hourNum < 12 ? "AM" : "PM";
|
||||
return `${hour12}:${minute} ${period}`;
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to format date and time together
|
||||
const formatDateTime = (dateString: string, timeString?: string) => {
|
||||
const date = new Date(dateString).toLocaleDateString();
|
||||
const formattedTime = formatTime(timeString);
|
||||
return formattedTime ? `${date} at ${formattedTime}` : date;
|
||||
};
|
||||
|
||||
const { user } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [listings, setListings] = useState<Item[]>([]);
|
||||
const [rentals, setRentals] = useState<Rental[]>([]);
|
||||
const [ownerRentals, setOwnerRentals] = useState<Rental[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
// Owner rental management state
|
||||
const [showReviewRenterModal, setShowReviewRenterModal] = useState(false);
|
||||
const [selectedRentalForReview, setSelectedRentalForReview] = useState<Rental | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMyListings();
|
||||
fetchRentalRequests();
|
||||
fetchOwnerRentals();
|
||||
}, [user]);
|
||||
|
||||
const fetchMyListings = async () => {
|
||||
@@ -23,7 +48,7 @@ const MyListings: React.FC = () => {
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(""); // Clear any previous errors
|
||||
setError("");
|
||||
const response = await api.get("/items");
|
||||
|
||||
// Filter items to only show ones owned by current user
|
||||
@@ -33,7 +58,6 @@ const MyListings: React.FC = () => {
|
||||
setListings(myItems);
|
||||
} catch (err: any) {
|
||||
console.error("Error fetching listings:", err);
|
||||
// Only show error for actual API failures
|
||||
if (err.response && err.response.status >= 500) {
|
||||
setError("Failed to get your listings. Please try again later.");
|
||||
}
|
||||
@@ -70,40 +94,64 @@ const MyListings: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const fetchRentalRequests = async () => {
|
||||
if (!user) return;
|
||||
|
||||
const fetchOwnerRentals = async () => {
|
||||
try {
|
||||
const response = await rentalAPI.getMyListings();
|
||||
setRentals(response.data);
|
||||
} catch (err) {
|
||||
console.error("Error fetching rental requests:", err);
|
||||
console.log("Owner rentals data from backend:", response.data);
|
||||
setOwnerRentals(response.data);
|
||||
} catch (err: any) {
|
||||
console.error("Failed to fetch owner rentals:", err);
|
||||
}
|
||||
};
|
||||
|
||||
// Owner functionality handlers
|
||||
const handleAcceptRental = async (rentalId: string) => {
|
||||
try {
|
||||
await rentalAPI.updateRentalStatus(rentalId, "confirmed");
|
||||
// Refresh the rentals list
|
||||
fetchRentalRequests();
|
||||
fetchOwnerRentals();
|
||||
} catch (err) {
|
||||
console.error("Failed to accept rental request:", err);
|
||||
alert("Failed to accept rental request");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRejectRental = async (rentalId: string) => {
|
||||
try {
|
||||
await api.put(`/rentals/${rentalId}/status`, {
|
||||
status: "cancelled",
|
||||
rejectionReason: "Request declined by owner",
|
||||
});
|
||||
// Refresh the rentals list
|
||||
fetchRentalRequests();
|
||||
await rentalAPI.updateRentalStatus(rentalId, "cancelled");
|
||||
fetchOwnerRentals();
|
||||
} catch (err) {
|
||||
console.error("Failed to reject rental request:", err);
|
||||
alert("Failed to reject rental request");
|
||||
}
|
||||
};
|
||||
|
||||
const handleCompleteClick = async (rental: Rental) => {
|
||||
try {
|
||||
console.log('Marking rental as completed:', rental.id);
|
||||
await rentalAPI.markAsCompleted(rental.id);
|
||||
|
||||
setSelectedRentalForReview(rental);
|
||||
setShowReviewRenterModal(true);
|
||||
|
||||
fetchOwnerRentals();
|
||||
} catch (err: any) {
|
||||
console.error('Error marking rental as completed:', err);
|
||||
alert("Failed to mark rental as completed: " + (err.response?.data?.error || err.message));
|
||||
}
|
||||
};
|
||||
|
||||
const handleReviewRenterSuccess = () => {
|
||||
fetchOwnerRentals();
|
||||
};
|
||||
|
||||
// Filter owner rentals
|
||||
const allOwnerRentals = ownerRentals.filter((r) =>
|
||||
["pending", "confirmed", "active"].includes(r.status)
|
||||
).sort((a, b) => {
|
||||
const statusOrder = { "pending": 0, "confirmed": 1, "active": 2 };
|
||||
return statusOrder[a.status as keyof typeof statusOrder] - statusOrder[b.status as keyof typeof statusOrder];
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="container mt-4">
|
||||
@@ -119,7 +167,7 @@ const MyListings: React.FC = () => {
|
||||
return (
|
||||
<div className="container mt-4">
|
||||
<div className="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Listings</h1>
|
||||
<h1>My Listings</h1>
|
||||
<Link to="/create-item" className="btn btn-primary">
|
||||
Add New Item
|
||||
</Link>
|
||||
@@ -131,26 +179,103 @@ const MyListings: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(() => {
|
||||
const pendingCount = rentals.filter(
|
||||
(r) => r.status === "pending"
|
||||
).length;
|
||||
{/* Rental Requests Section - Moved to top for priority */}
|
||||
{allOwnerRentals.length > 0 && (
|
||||
<div className="mb-5">
|
||||
<h4 className="mb-3">
|
||||
<i className="bi bi-calendar-check me-2"></i>
|
||||
Rental Requests ({allOwnerRentals.length})
|
||||
</h4>
|
||||
<div className="row">
|
||||
{allOwnerRentals.map((rental) => (
|
||||
<div key={rental.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<div className="card h-100">
|
||||
{rental.item?.images && rental.item.images[0] && (
|
||||
<img
|
||||
src={rental.item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
style={{ height: "200px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-dark">
|
||||
{rental.item ? rental.item.name : "Item Unavailable"}
|
||||
</h5>
|
||||
|
||||
if (pendingCount > 0) {
|
||||
return (
|
||||
<div
|
||||
className="alert alert-info d-flex align-items-center"
|
||||
role="alert"
|
||||
>
|
||||
<i className="bi bi-bell-fill me-2"></i>
|
||||
You have {pendingCount} pending rental request
|
||||
{pendingCount > 1 ? "s" : ""} to review.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()}
|
||||
{rental.renter && (
|
||||
<p className="mb-1 text-dark small">
|
||||
<strong>Renter:</strong> {rental.renter.firstName} {rental.renter.lastName}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mb-2">
|
||||
<span className={`badge ${
|
||||
rental.status === "active" ? "bg-success" :
|
||||
rental.status === "pending" ? "bg-warning" :
|
||||
rental.status === "confirmed" ? "bg-info" : "bg-danger"
|
||||
}`}>
|
||||
{rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="mb-1 text-dark small">
|
||||
<strong>Period:</strong>
|
||||
<br />
|
||||
{formatDateTime(rental.startDate, rental.startTime)} - {formatDateTime(rental.endDate, rental.endTime)}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 text-dark small">
|
||||
<strong>Total:</strong> ${rental.totalAmount}
|
||||
</p>
|
||||
|
||||
{rental.itemPrivateMessage && rental.itemReviewVisible && (
|
||||
<div className="alert alert-info mt-2 mb-2 p-2 small">
|
||||
<strong><i className="bi bi-envelope-fill me-1"></i>Private Note from Renter:</strong>
|
||||
<br />
|
||||
{rental.itemPrivateMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
{rental.status === "pending" && (
|
||||
<>
|
||||
<button
|
||||
className="btn btn-sm btn-success"
|
||||
onClick={() => handleAcceptRental(rental.id)}
|
||||
>
|
||||
Accept
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => handleRejectRental(rental.id)}
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{(rental.status === "active" || rental.status === "confirmed") && (
|
||||
<button
|
||||
className="btn btn-sm btn-success"
|
||||
onClick={() => handleCompleteClick(rental)}
|
||||
>
|
||||
Complete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h4 className="mb-3">
|
||||
<i className="bi bi-list-ul me-2"></i>
|
||||
My Items ({listings.length})
|
||||
</h4>
|
||||
|
||||
{listings.length === 0 ? (
|
||||
<div className="text-center py-5">
|
||||
<p className="text-muted">You haven't listed any items yet.</p>
|
||||
@@ -162,210 +287,132 @@ const MyListings: React.FC = () => {
|
||||
<div className="row">
|
||||
{listings.map((item) => (
|
||||
<div key={item.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<div
|
||||
className="card h-100"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (
|
||||
target.closest("button") ||
|
||||
target.closest("a") ||
|
||||
target.closest(".rental-requests")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
navigate(`/items/${item.id}`);
|
||||
}}
|
||||
>
|
||||
{item.images && item.images[0] && (
|
||||
<img
|
||||
src={item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={item.name}
|
||||
style={{ height: "200px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-dark">{item.name}</h5>
|
||||
<p className="card-text text-truncate text-dark">
|
||||
{item.description}
|
||||
</p>
|
||||
<div
|
||||
className="card h-100"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (target.closest("button") || target.closest("a")) {
|
||||
return;
|
||||
}
|
||||
navigate(`/items/${item.id}`);
|
||||
}}
|
||||
>
|
||||
{item.images && item.images[0] && (
|
||||
<img
|
||||
src={item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={item.name}
|
||||
style={{ height: "200px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-dark">{item.name}</h5>
|
||||
<p className="card-text text-truncate text-dark">
|
||||
{item.description}
|
||||
</p>
|
||||
|
||||
<div className="mb-2">
|
||||
<span
|
||||
className={`badge ${
|
||||
item.availability ? "bg-success" : "bg-secondary"
|
||||
}`}
|
||||
>
|
||||
{item.availability ? "Available" : "Not Available"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
{item.pricePerDay && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerDay}/day
|
||||
</div>
|
||||
)}
|
||||
{item.pricePerHour && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerHour}/hour
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="d-flex gap-2">
|
||||
<Link
|
||||
to={`/items/${item.id}/edit`}
|
||||
className="btn btn-sm btn-outline-primary"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => toggleAvailability(item)}
|
||||
className="btn btn-sm btn-outline-info"
|
||||
>
|
||||
{item.availability
|
||||
? "Mark Unavailable"
|
||||
: "Mark Available"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(item.id)}
|
||||
className="btn btn-sm btn-outline-danger"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<span
|
||||
className={`badge ${
|
||||
item.availability ? "bg-success" : "bg-secondary"
|
||||
}`}
|
||||
>
|
||||
{item.availability ? "Available" : "Not Available"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
{(() => {
|
||||
const pendingRentals = rentals.filter(
|
||||
(r) => r.itemId === item.id && r.status === "pending"
|
||||
);
|
||||
const acceptedRentals = rentals.filter(
|
||||
(r) =>
|
||||
r.itemId === item.id &&
|
||||
["confirmed", "active"].includes(r.status)
|
||||
);
|
||||
const hasAnyPositivePrice =
|
||||
(item.pricePerHour !== undefined && Number(item.pricePerHour) > 0) ||
|
||||
(item.pricePerDay !== undefined && Number(item.pricePerDay) > 0) ||
|
||||
(item.pricePerWeek !== undefined && Number(item.pricePerWeek) > 0) ||
|
||||
(item.pricePerMonth !== undefined && Number(item.pricePerMonth) > 0);
|
||||
|
||||
if (
|
||||
pendingRentals.length > 0 ||
|
||||
acceptedRentals.length > 0
|
||||
) {
|
||||
const hasAnyZeroPrice =
|
||||
(item.pricePerHour !== undefined && Number(item.pricePerHour) === 0) ||
|
||||
(item.pricePerDay !== undefined && Number(item.pricePerDay) === 0) ||
|
||||
(item.pricePerWeek !== undefined && Number(item.pricePerWeek) === 0) ||
|
||||
(item.pricePerMonth !== undefined && Number(item.pricePerMonth) === 0);
|
||||
|
||||
if (!hasAnyPositivePrice && hasAnyZeroPrice) {
|
||||
return (
|
||||
<div className="mt-3 border-top pt-3 rental-requests">
|
||||
{pendingRentals.length > 0 && (
|
||||
<>
|
||||
<h6 className="text-primary mb-2">
|
||||
<i className="bi bi-bell-fill"></i> Pending
|
||||
Requests ({pendingRentals.length})
|
||||
</h6>
|
||||
{pendingRentals.map((rental) => (
|
||||
<div
|
||||
key={rental.id}
|
||||
className="border rounded p-2 mb-2 bg-light"
|
||||
>
|
||||
<div className="d-flex justify-content-between align-items-start">
|
||||
<div className="small">
|
||||
<strong>
|
||||
{rental.renter?.firstName}{" "}
|
||||
{rental.renter?.lastName}
|
||||
</strong>
|
||||
<br />
|
||||
{new Date(
|
||||
rental.startDate
|
||||
).toLocaleDateString()}{" "}
|
||||
-{" "}
|
||||
{new Date(
|
||||
rental.endDate
|
||||
).toLocaleDateString()}
|
||||
<br />
|
||||
<span className="text-muted">
|
||||
${rental.totalAmount}
|
||||
</span>
|
||||
</div>
|
||||
<div className="d-flex gap-1">
|
||||
<button
|
||||
className="btn btn-success btn-sm"
|
||||
onClick={() =>
|
||||
handleAcceptRental(rental.id)
|
||||
}
|
||||
>
|
||||
Accept
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger btn-sm"
|
||||
onClick={() =>
|
||||
handleRejectRental(rental.id)
|
||||
}
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{acceptedRentals.length > 0 && (
|
||||
<>
|
||||
<h6 className="text-success mb-2 mt-3">
|
||||
<i className="bi bi-check-circle-fill"></i>{" "}
|
||||
Accepted Rentals ({acceptedRentals.length})
|
||||
</h6>
|
||||
{acceptedRentals.map((rental) => (
|
||||
<div
|
||||
key={rental.id}
|
||||
className="border rounded p-2 mb-2 bg-light"
|
||||
>
|
||||
<div className="small">
|
||||
<div className="d-flex justify-content-between align-items-start">
|
||||
<div>
|
||||
<strong>
|
||||
{rental.renter?.firstName}{" "}
|
||||
{rental.renter?.lastName}
|
||||
</strong>
|
||||
<br />
|
||||
{new Date(
|
||||
rental.startDate
|
||||
).toLocaleDateString()}{" "}
|
||||
-{" "}
|
||||
{new Date(
|
||||
rental.endDate
|
||||
).toLocaleDateString()}
|
||||
<br />
|
||||
<span className="text-muted">
|
||||
${rental.totalAmount}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={`badge ${
|
||||
rental.status === "active"
|
||||
? "bg-success"
|
||||
: "bg-info"
|
||||
}`}
|
||||
>
|
||||
{rental.status === "active"
|
||||
? "Active"
|
||||
: "Confirmed"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
<div className="text-success small fw-bold">
|
||||
Free to Borrow
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{item.pricePerDay && Number(item.pricePerDay) > 0 && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerDay}/day
|
||||
</div>
|
||||
)}
|
||||
{item.pricePerHour && Number(item.pricePerHour) > 0 && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerHour}/hour
|
||||
</div>
|
||||
)}
|
||||
{item.pricePerWeek && Number(item.pricePerWeek) > 0 && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerWeek}/week
|
||||
</div>
|
||||
)}
|
||||
{item.pricePerMonth && Number(item.pricePerMonth) > 0 && (
|
||||
<div className="text-muted small">
|
||||
${item.pricePerMonth}/month
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div className="d-flex gap-2">
|
||||
<Link
|
||||
to={`/items/${item.id}/edit`}
|
||||
className="btn btn-sm btn-outline-primary"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
<button
|
||||
onClick={() => toggleAvailability(item)}
|
||||
className="btn btn-sm btn-outline-info"
|
||||
>
|
||||
{item.availability
|
||||
? "Mark Unavailable"
|
||||
: "Mark Available"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(item.id)}
|
||||
className="btn btn-sm btn-outline-danger"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{/* Review Modal */}
|
||||
{selectedRentalForReview && (
|
||||
<ReviewRenterModal
|
||||
show={showReviewRenterModal}
|
||||
onClose={() => {
|
||||
setShowReviewRenterModal(false);
|
||||
setSelectedRentalForReview(null);
|
||||
}}
|
||||
rental={selectedRentalForReview}
|
||||
onSuccess={handleReviewRenterSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+140
-143
@@ -3,15 +3,35 @@ import { Link } from "react-router-dom";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
import { rentalAPI } from "../services/api";
|
||||
import { Rental } from "../types";
|
||||
import ReviewModal from "../components/ReviewModal";
|
||||
import ReviewItemModal from "../components/ReviewModal";
|
||||
import ConfirmationModal from "../components/ConfirmationModal";
|
||||
|
||||
const MyRentals: React.FC = () => {
|
||||
// Helper function to format time
|
||||
const formatTime = (timeString?: string) => {
|
||||
if (!timeString || timeString.trim() === "") return "";
|
||||
try {
|
||||
const [hour, minute] = timeString.split(":");
|
||||
const hourNum = parseInt(hour);
|
||||
const hour12 = hourNum === 0 ? 12 : hourNum > 12 ? hourNum - 12 : hourNum;
|
||||
const period = hourNum < 12 ? "AM" : "PM";
|
||||
return `${hour12}:${minute} ${period}`;
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to format date and time together
|
||||
const formatDateTime = (dateString: string, timeString?: string) => {
|
||||
const date = new Date(dateString).toLocaleDateString();
|
||||
const formattedTime = formatTime(timeString);
|
||||
return formattedTime ? `${date} at ${formattedTime}` : date;
|
||||
};
|
||||
|
||||
const { user } = useAuth();
|
||||
const [rentals, setRentals] = useState<Rental[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [activeTab, setActiveTab] = useState<"active" | "past">("active");
|
||||
const [showReviewModal, setShowReviewModal] = useState(false);
|
||||
const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
|
||||
const [showCancelModal, setShowCancelModal] = useState(false);
|
||||
@@ -25,6 +45,10 @@ const MyRentals: React.FC = () => {
|
||||
const fetchRentals = async () => {
|
||||
try {
|
||||
const response = await rentalAPI.getMyRentals();
|
||||
console.log("MyRentals data from backend:", response.data);
|
||||
if (response.data.length > 0) {
|
||||
console.log("First rental object:", response.data[0]);
|
||||
}
|
||||
setRentals(response.data);
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.message || "Failed to fetch rentals");
|
||||
@@ -44,7 +68,7 @@ const MyRentals: React.FC = () => {
|
||||
setCancelling(true);
|
||||
try {
|
||||
await rentalAPI.updateRentalStatus(rentalToCancel, "cancelled");
|
||||
fetchRentals(); // Refresh the list
|
||||
fetchRentals();
|
||||
setShowCancelModal(false);
|
||||
setRentalToCancel(null);
|
||||
} catch (err: any) {
|
||||
@@ -60,19 +84,14 @@ const MyRentals: React.FC = () => {
|
||||
};
|
||||
|
||||
const handleReviewSuccess = () => {
|
||||
fetchRentals(); // Refresh to show the review has been added
|
||||
fetchRentals();
|
||||
alert("Thank you for your review!");
|
||||
};
|
||||
|
||||
// Filter rentals based on status
|
||||
const activeRentals = rentals.filter((r) =>
|
||||
// Filter rentals - only show active rentals (pending, confirmed, active)
|
||||
const renterActiveRentals = rentals.filter((r) =>
|
||||
["pending", "confirmed", "active"].includes(r.status)
|
||||
);
|
||||
const pastRentals = rentals.filter((r) =>
|
||||
["completed", "cancelled"].includes(r.status)
|
||||
);
|
||||
|
||||
const displayedRentals = activeTab === "active" ? activeRentals : pastRentals;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -100,156 +119,134 @@ const MyRentals: React.FC = () => {
|
||||
<div className="container mt-4">
|
||||
<h1>My Rentals</h1>
|
||||
|
||||
<ul className="nav nav-tabs mb-4">
|
||||
<li className="nav-item">
|
||||
<button
|
||||
className={`nav-link ${activeTab === "active" ? "active" : ""}`}
|
||||
onClick={() => setActiveTab("active")}
|
||||
>
|
||||
Active Rentals ({activeRentals.length})
|
||||
</button>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<button
|
||||
className={`nav-link ${activeTab === "past" ? "active" : ""}`}
|
||||
onClick={() => setActiveTab("past")}
|
||||
>
|
||||
Past Rentals ({pastRentals.length})
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
{displayedRentals.length === 0 ? (
|
||||
{renterActiveRentals.length === 0 ? (
|
||||
<div className="text-center py-5">
|
||||
<p className="text-muted">
|
||||
{activeTab === "active"
|
||||
? "You don't have any active rentals."
|
||||
: "You don't have any past rentals."}
|
||||
</p>
|
||||
<Link to="/items" className="btn btn-primary mt-3">
|
||||
<h5 className="text-muted">No Active Rental Requests</h5>
|
||||
<p className="text-muted">You don't have any rental requests at the moment.</p>
|
||||
<Link to="/items" className="btn btn-primary">
|
||||
Browse Items to Rent
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="row">
|
||||
{displayedRentals.map((rental) => (
|
||||
<div key={rental.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<Link
|
||||
to={rental.item ? `/items/${rental.item.id}` : "#"}
|
||||
className="text-decoration-none"
|
||||
onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!rental.item || target.closest("button")) {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="card h-100"
|
||||
style={{ cursor: rental.item ? "pointer" : "default" }}
|
||||
{renterActiveRentals.map((rental) => (
|
||||
<div key={rental.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<Link
|
||||
to={rental.item ? `/items/${rental.item.id}` : "#"}
|
||||
className="text-decoration-none"
|
||||
onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (!rental.item || target.closest("button")) {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{rental.item?.images && rental.item.images[0] && (
|
||||
<img
|
||||
src={rental.item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
style={{ height: "200px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-dark">
|
||||
{rental.item ? rental.item.name : "Item Unavailable"}
|
||||
</h5>
|
||||
|
||||
<div className="mb-2">
|
||||
<span
|
||||
className={`badge ${
|
||||
rental.status === "active"
|
||||
? "bg-success"
|
||||
: rental.status === "pending"
|
||||
? "bg-warning"
|
||||
: rental.status === "confirmed"
|
||||
? "bg-info"
|
||||
: rental.status === "completed"
|
||||
? "bg-secondary"
|
||||
: "bg-danger"
|
||||
}`}
|
||||
>
|
||||
{rental.status.charAt(0).toUpperCase() +
|
||||
rental.status.slice(1)}
|
||||
</span>
|
||||
{rental.paymentStatus === "paid" && (
|
||||
<span className="badge bg-success ms-2">Paid</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Rental Period:</strong>
|
||||
<br />
|
||||
{new Date(rental.startDate).toLocaleDateString()} -{" "}
|
||||
{new Date(rental.endDate).toLocaleDateString()}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Total:</strong> ${rental.totalAmount}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Delivery:</strong>{" "}
|
||||
{rental.deliveryMethod === "pickup"
|
||||
? "Pick-up"
|
||||
: "Delivery"}
|
||||
</p>
|
||||
|
||||
{rental.owner && (
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Owner:</strong> {rental.owner.firstName}{" "}
|
||||
{rental.owner.lastName}
|
||||
</p>
|
||||
<div className="card h-100" style={{ cursor: rental.item ? "pointer" : "default" }}>
|
||||
{rental.item?.images && rental.item.images[0] && (
|
||||
<img
|
||||
src={rental.item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
style={{ height: "200px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-dark">
|
||||
{rental.item ? rental.item.name : "Item Unavailable"}
|
||||
</h5>
|
||||
|
||||
{rental.status === "cancelled" &&
|
||||
rental.rejectionReason && (
|
||||
<div className="mb-2">
|
||||
<span className={`badge ${
|
||||
rental.status === "active" ? "bg-success" :
|
||||
rental.status === "pending" ? "bg-warning" :
|
||||
rental.status === "confirmed" ? "bg-info" : "bg-danger"
|
||||
}`}>
|
||||
{rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
|
||||
</span>
|
||||
{rental.paymentStatus === "paid" && (
|
||||
<span className="badge bg-success ms-2">Paid</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Rental Period:</strong>
|
||||
<br />
|
||||
<strong>Start:</strong> {formatDateTime(rental.startDate, rental.startTime)}
|
||||
<br />
|
||||
<strong>End:</strong> {formatDateTime(rental.endDate, rental.endTime)}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Total:</strong> ${rental.totalAmount}
|
||||
</p>
|
||||
|
||||
{rental.owner && (
|
||||
<p className="mb-1 text-dark">
|
||||
<strong>Owner:</strong> {rental.owner.firstName} {rental.owner.lastName}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rental.renterPrivateMessage && rental.renterReviewVisible && (
|
||||
<div className="alert alert-info mt-2 mb-2 p-2 small">
|
||||
<strong><i className="bi bi-envelope-fill me-1"></i>Private Note from Owner:</strong>
|
||||
<br />
|
||||
{rental.renterPrivateMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{rental.status === "cancelled" && rental.rejectionReason && (
|
||||
<div className="alert alert-warning mt-2 mb-1 p-2 small">
|
||||
<strong>Rejection reason:</strong>{" "}
|
||||
{rental.rejectionReason}
|
||||
<strong>Rejection reason:</strong> {rental.rejectionReason}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
{rental.status === "pending" && (
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => handleCancelClick(rental.id)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
{rental.status === "completed" && !rental.rating && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => handleReviewClick(rental)}
|
||||
>
|
||||
Leave Review
|
||||
</button>
|
||||
)}
|
||||
{rental.status === "completed" && rental.rating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Reviewed ({rental.rating}/5)
|
||||
</div>
|
||||
)}
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
{rental.status === "pending" && (
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => handleCancelClick(rental.id)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
{rental.status === "active" && !rental.itemRating && !rental.itemReviewSubmittedAt && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => handleReviewClick(rental)}
|
||||
>
|
||||
Review
|
||||
</button>
|
||||
)}
|
||||
{rental.itemReviewSubmittedAt && !rental.itemReviewVisible && (
|
||||
<div className="text-info small">
|
||||
<i className="bi bi-clock me-1"></i>
|
||||
Review Submitted
|
||||
</div>
|
||||
)}
|
||||
{rental.itemReviewVisible && rental.itemRating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Review Published ({rental.itemRating}/5)
|
||||
</div>
|
||||
)}
|
||||
{rental.status === "completed" && rental.rating && !rental.itemRating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Reviewed ({rental.rating}/5)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Review Modal */}
|
||||
{selectedRental && (
|
||||
<ReviewModal
|
||||
<ReviewItemModal
|
||||
show={showReviewModal}
|
||||
onClose={() => {
|
||||
setShowReviewModal(false);
|
||||
@@ -278,4 +275,4 @@ const MyRentals: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default MyRentals;
|
||||
export default MyRentals;
|
||||
@@ -4,6 +4,8 @@ import { userAPI, itemAPI, rentalAPI, addressAPI } from "../services/api";
|
||||
import { User, Item, Rental, Address } from "../types";
|
||||
import { getImageUrl } from "../utils/imageUrl";
|
||||
import AvailabilitySettings from "../components/AvailabilitySettings";
|
||||
import ReviewItemModal from "../components/ReviewModal";
|
||||
import ReviewRenterModal from "../components/ReviewRenterModal";
|
||||
|
||||
const Profile: React.FC = () => {
|
||||
const { user, updateUser, logout } = useAuth();
|
||||
@@ -59,12 +61,22 @@ const Profile: React.FC = () => {
|
||||
zipCode: "",
|
||||
country: "US",
|
||||
});
|
||||
|
||||
// Rental history state
|
||||
const [pastRenterRentals, setPastRenterRentals] = useState<Rental[]>([]);
|
||||
const [pastOwnerRentals, setPastOwnerRentals] = useState<Rental[]>([]);
|
||||
const [rentalHistoryLoading, setRentalHistoryLoading] = useState(true);
|
||||
const [showReviewModal, setShowReviewModal] = useState(false);
|
||||
const [showReviewRenterModal, setShowReviewRenterModal] = useState(false);
|
||||
const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
|
||||
const [selectedRentalForReview, setSelectedRentalForReview] = useState<Rental | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProfile();
|
||||
fetchStats();
|
||||
fetchUserAddresses();
|
||||
fetchUserAvailability();
|
||||
fetchRentalHistory();
|
||||
}, []);
|
||||
|
||||
const fetchUserAvailability = async () => {
|
||||
@@ -141,6 +153,73 @@ const Profile: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Helper functions for rental history
|
||||
const formatTime = (timeString?: string) => {
|
||||
if (!timeString || timeString.trim() === "") return "";
|
||||
try {
|
||||
const [hour, minute] = timeString.split(":");
|
||||
const hourNum = parseInt(hour);
|
||||
const hour12 = hourNum === 0 ? 12 : hourNum > 12 ? hourNum - 12 : hourNum;
|
||||
const period = hourNum < 12 ? "AM" : "PM";
|
||||
return `${hour12}:${minute} ${period}`;
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const formatDateTime = (dateString: string, timeString?: string) => {
|
||||
const date = new Date(dateString).toLocaleDateString();
|
||||
const formattedTime = formatTime(timeString);
|
||||
return formattedTime ? `${date} at ${formattedTime}` : date;
|
||||
};
|
||||
|
||||
const fetchRentalHistory = async () => {
|
||||
try {
|
||||
// Fetch past rentals as a renter
|
||||
const renterResponse = await rentalAPI.getMyRentals();
|
||||
const pastRenterRentals = renterResponse.data.filter((r: Rental) =>
|
||||
["completed", "cancelled"].includes(r.status)
|
||||
);
|
||||
setPastRenterRentals(pastRenterRentals);
|
||||
|
||||
// Fetch past rentals as an owner
|
||||
const ownerResponse = await rentalAPI.getMyListings();
|
||||
const pastOwnerRentals = ownerResponse.data.filter((r: Rental) =>
|
||||
["completed", "cancelled"].includes(r.status)
|
||||
);
|
||||
setPastOwnerRentals(pastOwnerRentals);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch rental history:", err);
|
||||
} finally {
|
||||
setRentalHistoryLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReviewClick = (rental: Rental) => {
|
||||
setSelectedRental(rental);
|
||||
setShowReviewModal(true);
|
||||
};
|
||||
|
||||
const handleReviewSuccess = () => {
|
||||
fetchRentalHistory(); // Refresh to show updated review status
|
||||
alert("Thank you for your review!");
|
||||
};
|
||||
|
||||
const handleCompleteClick = async (rental: Rental) => {
|
||||
try {
|
||||
await rentalAPI.markAsCompleted(rental.id);
|
||||
setSelectedRentalForReview(rental);
|
||||
setShowReviewRenterModal(true);
|
||||
fetchRentalHistory(); // Refresh rental history
|
||||
} catch (err: any) {
|
||||
alert("Failed to mark rental as completed: " + (err.response?.data?.error || err.message));
|
||||
}
|
||||
};
|
||||
|
||||
const handleReviewRenterSuccess = () => {
|
||||
fetchRentalHistory(); // Refresh to show updated review status
|
||||
};
|
||||
|
||||
const handleChange = (
|
||||
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
|
||||
) => {
|
||||
@@ -472,6 +551,15 @@ const Profile: React.FC = () => {
|
||||
<i className="bi bi-gear me-2"></i>
|
||||
Owner Settings
|
||||
</button>
|
||||
<button
|
||||
className={`list-group-item list-group-item-action ${
|
||||
activeSection === "rental-history" ? "active" : ""
|
||||
}`}
|
||||
onClick={() => setActiveSection("rental-history")}
|
||||
>
|
||||
<i className="bi bi-clock-history me-2"></i>
|
||||
Rental History
|
||||
</button>
|
||||
<button
|
||||
className={`list-group-item list-group-item-action ${
|
||||
activeSection === "personal-info" ? "active" : ""
|
||||
@@ -677,6 +765,225 @@ const Profile: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rental History Section */}
|
||||
{activeSection === "rental-history" && (
|
||||
<div>
|
||||
<h4 className="mb-4">Rental History</h4>
|
||||
|
||||
{rentalHistoryLoading ? (
|
||||
<div className="text-center py-5">
|
||||
<div className="spinner-border" role="status">
|
||||
<span className="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* As Renter Section */}
|
||||
{pastRenterRentals.length > 0 && (
|
||||
<div className="mb-5">
|
||||
<h5 className="mb-3">
|
||||
<i className="bi bi-person me-2"></i>
|
||||
As Renter ({pastRenterRentals.length})
|
||||
</h5>
|
||||
<div className="row">
|
||||
{pastRenterRentals.map((rental) => (
|
||||
<div key={rental.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<div className="card h-100">
|
||||
{rental.item?.images && rental.item.images[0] && (
|
||||
<img
|
||||
src={rental.item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
style={{ height: "150px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h6 className="card-title">
|
||||
{rental.item ? rental.item.name : "Item Unavailable"}
|
||||
</h6>
|
||||
|
||||
<div className="mb-2">
|
||||
<span
|
||||
className={`badge ${
|
||||
rental.status === "completed" ? "bg-success" : "bg-danger"
|
||||
}`}
|
||||
>
|
||||
{rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="mb-1 small">
|
||||
<strong>Period:</strong>
|
||||
<br />
|
||||
<strong>Start:</strong> {formatDateTime(rental.startDate, rental.startTime)}
|
||||
<br />
|
||||
<strong>End:</strong> {formatDateTime(rental.endDate, rental.endTime)}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 small">
|
||||
<strong>Total:</strong> ${rental.totalAmount}
|
||||
</p>
|
||||
|
||||
{rental.owner && (
|
||||
<p className="mb-1 small">
|
||||
<strong>Owner:</strong> {rental.owner.firstName} {rental.owner.lastName}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rental.renterPrivateMessage && rental.renterReviewVisible && (
|
||||
<div className="alert alert-info mt-2 mb-2 p-2 small">
|
||||
<strong><i className="bi bi-envelope-fill me-1"></i>Private Note from Owner:</strong>
|
||||
<br />
|
||||
{rental.renterPrivateMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{rental.status === "cancelled" && rental.rejectionReason && (
|
||||
<div className="alert alert-warning mt-2 mb-1 p-2 small">
|
||||
<strong>Rejection reason:</strong> {rental.rejectionReason}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
{rental.status === "completed" && !rental.itemRating && !rental.itemReviewSubmittedAt && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => handleReviewClick(rental)}
|
||||
>
|
||||
Review
|
||||
</button>
|
||||
)}
|
||||
{rental.itemReviewSubmittedAt && !rental.itemReviewVisible && (
|
||||
<div className="text-info small">
|
||||
<i className="bi bi-clock me-1"></i>
|
||||
Review Submitted
|
||||
</div>
|
||||
)}
|
||||
{rental.itemReviewVisible && rental.itemRating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Review Published ({rental.itemRating}/5)
|
||||
</div>
|
||||
)}
|
||||
{rental.status === "completed" && rental.rating && !rental.itemRating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Reviewed ({rental.rating}/5)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* As Owner Section */}
|
||||
{pastOwnerRentals.length > 0 && (
|
||||
<div className="mb-5">
|
||||
<h5 className="mb-3">
|
||||
<i className="bi bi-house me-2"></i>
|
||||
As Owner ({pastOwnerRentals.length})
|
||||
</h5>
|
||||
<div className="row">
|
||||
{pastOwnerRentals.map((rental) => (
|
||||
<div key={rental.id} className="col-md-6 col-lg-4 mb-4">
|
||||
<div className="card h-100">
|
||||
{rental.item?.images && rental.item.images[0] && (
|
||||
<img
|
||||
src={rental.item.images[0]}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
style={{ height: "150px", objectFit: "cover" }}
|
||||
/>
|
||||
)}
|
||||
<div className="card-body">
|
||||
<h6 className="card-title">
|
||||
{rental.item ? rental.item.name : "Item Unavailable"}
|
||||
</h6>
|
||||
|
||||
{rental.renter && (
|
||||
<p className="mb-1 small">
|
||||
<strong>Renter:</strong> {rental.renter.firstName} {rental.renter.lastName}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mb-2">
|
||||
<span
|
||||
className={`badge ${
|
||||
rental.status === "completed" ? "bg-success" : "bg-danger"
|
||||
}`}
|
||||
>
|
||||
{rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="mb-1 small">
|
||||
<strong>Period:</strong>
|
||||
<br />
|
||||
{formatDateTime(rental.startDate, rental.startTime)} - {formatDateTime(rental.endDate, rental.endTime)}
|
||||
</p>
|
||||
|
||||
<p className="mb-1 small">
|
||||
<strong>Total:</strong> ${rental.totalAmount}
|
||||
</p>
|
||||
|
||||
{rental.itemPrivateMessage && rental.itemReviewVisible && (
|
||||
<div className="alert alert-info mt-2 mb-2 p-2 small">
|
||||
<strong><i className="bi bi-envelope-fill me-1"></i>Private Note from Renter:</strong>
|
||||
<br />
|
||||
{rental.itemPrivateMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="d-flex gap-2 mt-3">
|
||||
{rental.status === "completed" && !rental.renterRating && !rental.renterReviewSubmittedAt && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
onClick={() => {
|
||||
setSelectedRentalForReview(rental);
|
||||
setShowReviewRenterModal(true);
|
||||
}}
|
||||
>
|
||||
Review Renter
|
||||
</button>
|
||||
)}
|
||||
{rental.renterReviewSubmittedAt && !rental.renterReviewVisible && (
|
||||
<div className="text-info small">
|
||||
<i className="bi bi-clock me-1"></i>
|
||||
Review Submitted
|
||||
</div>
|
||||
)}
|
||||
{rental.renterReviewVisible && rental.renterRating && (
|
||||
<div className="text-success small">
|
||||
<i className="bi bi-check-circle-fill me-1"></i>
|
||||
Review Published ({rental.renterRating}/5)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{pastRenterRentals.length === 0 && pastOwnerRentals.length === 0 && (
|
||||
<div className="text-center py-5">
|
||||
<i className="bi bi-clock-history text-muted mb-3" style={{ fontSize: "3rem" }}></i>
|
||||
<h5 className="text-muted">No Rental History</h5>
|
||||
<p className="text-muted">Your completed rentals and rental requests will appear here.</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Personal Information Section */}
|
||||
{activeSection === "personal-info" && (
|
||||
<div>
|
||||
@@ -710,7 +1017,7 @@ const Profile: React.FC = () => {
|
||||
name="phone"
|
||||
value={formData.phone}
|
||||
onChange={handleChange}
|
||||
placeholder="+1 (555) 123-4567"
|
||||
placeholder="(123) 456-7890"
|
||||
disabled={!editing}
|
||||
/>
|
||||
</div>
|
||||
@@ -1022,6 +1329,31 @@ const Profile: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Review Modals */}
|
||||
{selectedRental && (
|
||||
<ReviewItemModal
|
||||
show={showReviewModal}
|
||||
onClose={() => {
|
||||
setShowReviewModal(false);
|
||||
setSelectedRental(null);
|
||||
}}
|
||||
rental={selectedRental}
|
||||
onSuccess={handleReviewSuccess}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedRentalForReview && (
|
||||
<ReviewRenterModal
|
||||
show={showReviewRenterModal}
|
||||
onClose={() => {
|
||||
setShowReviewRenterModal(false);
|
||||
setSelectedRentalForReview(null);
|
||||
}}
|
||||
rental={selectedRentalForReview}
|
||||
onSuccess={handleReviewRenterSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -312,7 +312,7 @@ const RentItem: React.FC = () => {
|
||||
name="cardName"
|
||||
value={formData.cardName}
|
||||
onChange={handleChange}
|
||||
placeholder="John Doe"
|
||||
placeholder=""
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -78,7 +78,10 @@ export const rentalAPI = {
|
||||
getMyListings: () => api.get("/rentals/my-listings"),
|
||||
updateRentalStatus: (id: string, status: string) =>
|
||||
api.put(`/rentals/${id}/status`, { status }),
|
||||
addReview: (id: string, data: any) => api.post(`/rentals/${id}/review`, data),
|
||||
markAsCompleted: (id: string) => api.post(`/rentals/${id}/mark-completed`),
|
||||
reviewRenter: (id: string, data: any) => api.post(`/rentals/${id}/review-renter`, data),
|
||||
reviewItem: (id: string, data: any) => api.post(`/rentals/${id}/review-item`, data),
|
||||
addReview: (id: string, data: any) => api.post(`/rentals/${id}/review`, data), // Legacy
|
||||
};
|
||||
|
||||
export const messageAPI = {
|
||||
|
||||
@@ -78,13 +78,6 @@ export interface Item {
|
||||
minimumRentalDays: number;
|
||||
maximumRentalDays?: number;
|
||||
needsTraining?: boolean;
|
||||
unavailablePeriods?: Array<{
|
||||
id: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
}>;
|
||||
availableAfter?: string;
|
||||
availableBefore?: string;
|
||||
specifyTimesPerDay?: boolean;
|
||||
@@ -110,6 +103,8 @@ export interface Rental {
|
||||
ownerId: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
totalAmount: number;
|
||||
status: "pending" | "confirmed" | "active" | "completed" | "cancelled";
|
||||
paymentStatus: "pending" | "paid" | "refunded";
|
||||
@@ -119,6 +114,18 @@ export interface Rental {
|
||||
rating?: number;
|
||||
review?: string;
|
||||
rejectionReason?: string;
|
||||
// New review fields
|
||||
itemRating?: number;
|
||||
itemReview?: string;
|
||||
itemReviewSubmittedAt?: string;
|
||||
itemReviewVisible?: boolean;
|
||||
renterRating?: number;
|
||||
renterReview?: string;
|
||||
renterReviewSubmittedAt?: string;
|
||||
renterReviewVisible?: boolean;
|
||||
// Private messages
|
||||
itemPrivateMessage?: string;
|
||||
renterPrivateMessage?: string;
|
||||
item?: Item;
|
||||
renter?: User;
|
||||
owner?: User;
|
||||
|
||||
Reference in new issue
Block a user