restructuring for rental requests. started double blind reviews

This commit is contained in:
jackiettran
2025-08-22 20:18:22 -04:00
parent 022c0b9c06
commit 5d85f77a19
15 changed files with 1305 additions and 1403 deletions

View File

@@ -103,10 +103,6 @@ const Item = sequelize.define("Item", {
allowNull: false,
defaultValue: false,
},
unavailablePeriods: {
type: DataTypes.JSONB,
defaultValue: [],
},
availableAfter: {
type: DataTypes.STRING,
defaultValue: "09:00",

View File

@@ -39,6 +39,12 @@ const Rental = sequelize.define('Rental', {
type: DataTypes.DATE,
allowNull: false
},
startTime: {
type: DataTypes.STRING
},
endTime: {
type: DataTypes.STRING
},
totalAmount: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false
@@ -61,6 +67,50 @@ const Rental = sequelize.define('Rental', {
notes: {
type: DataTypes.TEXT
},
// Renter's review of the item (existing fields renamed for clarity)
itemRating: {
type: DataTypes.INTEGER,
validate: {
min: 1,
max: 5
}
},
itemReview: {
type: DataTypes.TEXT
},
itemReviewSubmittedAt: {
type: DataTypes.DATE
},
itemReviewVisible: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
// Owner's review of the renter
renterRating: {
type: DataTypes.INTEGER,
validate: {
min: 1,
max: 5
}
},
renterReview: {
type: DataTypes.TEXT
},
renterReviewSubmittedAt: {
type: DataTypes.DATE
},
renterReviewVisible: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
// Private messages (always visible to recipient)
itemPrivateMessage: {
type: DataTypes.TEXT
},
renterPrivateMessage: {
type: DataTypes.TEXT
},
// Legacy fields for backwards compatibility
rating: {
type: DataTypes.INTEGER,
validate: {

View File

@@ -4,10 +4,53 @@ const { Rental, Item, User } = require('../models'); // Import from models/index
const { authenticateToken } = require('../middleware/auth');
const router = express.Router();
// Helper function to check and update review visibility
const checkAndUpdateReviewVisibility = async (rental) => {
const now = new Date();
const tenMinutesInMs = 10 * 60 * 1000; // 10 minutes
let needsUpdate = false;
let updates = {};
// Check if both reviews are submitted
if (rental.itemReviewSubmittedAt && rental.renterReviewSubmittedAt) {
if (!rental.itemReviewVisible || !rental.renterReviewVisible) {
updates.itemReviewVisible = true;
updates.renterReviewVisible = true;
needsUpdate = true;
}
} else {
// Check item review visibility (10-minute rule)
if (rental.itemReviewSubmittedAt && !rental.itemReviewVisible) {
const timeSinceSubmission = now - new Date(rental.itemReviewSubmittedAt);
if (timeSinceSubmission >= tenMinutesInMs) {
updates.itemReviewVisible = true;
needsUpdate = true;
}
}
// Check renter review visibility (10-minute rule)
if (rental.renterReviewSubmittedAt && !rental.renterReviewVisible) {
const timeSinceSubmission = now - new Date(rental.renterReviewSubmittedAt);
if (timeSinceSubmission >= tenMinutesInMs) {
updates.renterReviewVisible = true;
needsUpdate = true;
}
}
}
if (needsUpdate) {
await rental.update(updates);
}
return rental;
};
router.get('/my-rentals', authenticateToken, async (req, res) => {
try {
const rentals = await Rental.findAll({
where: { renterId: req.user.id },
// Remove explicit attributes to let Sequelize handle missing columns gracefully
include: [
{ model: Item, as: 'item' },
{ model: User, as: 'owner', attributes: ['id', 'username', 'firstName', 'lastName'] }
@@ -15,8 +58,10 @@ router.get('/my-rentals', authenticateToken, async (req, res) => {
order: [['createdAt', 'DESC']]
});
console.log('My-rentals data:', rentals.length > 0 ? rentals[0].toJSON() : 'No rentals');
res.json(rentals);
} catch (error) {
console.error('Error in my-rentals route:', error);
res.status(500).json({ error: error.message });
}
});
@@ -25,6 +70,7 @@ router.get('/my-listings', authenticateToken, async (req, res) => {
try {
const rentals = await Rental.findAll({
where: { ownerId: req.user.id },
// Remove explicit attributes to let Sequelize handle missing columns gracefully
include: [
{ model: Item, as: 'item' },
{ model: User, as: 'renter', attributes: ['id', 'username', 'firstName', 'lastName'] }
@@ -32,15 +78,17 @@ router.get('/my-listings', authenticateToken, async (req, res) => {
order: [['createdAt', 'DESC']]
});
console.log('My-listings rentals:', rentals.length > 0 ? rentals[0].toJSON() : 'No rentals');
res.json(rentals);
} catch (error) {
console.error('Error in my-listings route:', error);
res.status(500).json({ error: error.message });
}
});
router.post('/', authenticateToken, async (req, res) => {
try {
const { itemId, startDate, endDate, deliveryMethod, deliveryAddress, notes } = req.body;
const { itemId, startDate, endDate, startTime, endTime, deliveryMethod, deliveryAddress, notes } = req.body;
const item = await Item.findByPk(itemId);
if (!item) {
@@ -79,6 +127,8 @@ router.post('/', authenticateToken, async (req, res) => {
ownerId: item.ownerId,
startDate,
endDate,
startTime,
endTime,
totalAmount,
deliveryMethod,
deliveryAddress,
@@ -128,6 +178,125 @@ router.put('/:id/status', authenticateToken, async (req, res) => {
}
});
// Owner reviews renter
router.post('/:id/review-renter', authenticateToken, async (req, res) => {
try {
const { rating, review, privateMessage } = req.body;
const rental = await Rental.findByPk(req.params.id);
if (!rental) {
return res.status(404).json({ error: 'Rental not found' });
}
if (rental.ownerId !== req.user.id) {
return res.status(403).json({ error: 'Only owners can review renters' });
}
if (rental.status !== 'completed') {
return res.status(400).json({ error: 'Can only review completed rentals' });
}
if (rental.renterReviewSubmittedAt) {
return res.status(400).json({ error: 'Renter review already submitted' });
}
// Submit the review and private message
await rental.update({
renterRating: rating,
renterReview: review,
renterReviewSubmittedAt: new Date(),
renterPrivateMessage: privateMessage
});
// Check and update visibility
const updatedRental = await checkAndUpdateReviewVisibility(rental);
res.json({
success: true,
reviewVisible: updatedRental.renterReviewVisible
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Renter reviews item
router.post('/:id/review-item', authenticateToken, async (req, res) => {
try {
const { rating, review, privateMessage } = req.body;
const rental = await Rental.findByPk(req.params.id);
if (!rental) {
return res.status(404).json({ error: 'Rental not found' });
}
if (rental.renterId !== req.user.id) {
return res.status(403).json({ error: 'Only renters can review items' });
}
if (rental.status !== 'completed') {
return res.status(400).json({ error: 'Can only review completed rentals' });
}
if (rental.itemReviewSubmittedAt) {
return res.status(400).json({ error: 'Item review already submitted' });
}
// Submit the review and private message
await rental.update({
itemRating: rating,
itemReview: review,
itemReviewSubmittedAt: new Date(),
itemPrivateMessage: privateMessage
});
// Check and update visibility
const updatedRental = await checkAndUpdateReviewVisibility(rental);
res.json({
success: true,
reviewVisible: updatedRental.itemReviewVisible
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Mark rental as completed (owner only)
router.post('/:id/mark-completed', authenticateToken, async (req, res) => {
try {
console.log('Mark completed endpoint hit for rental ID:', req.params.id);
const rental = await Rental.findByPk(req.params.id);
if (!rental) {
return res.status(404).json({ error: 'Rental not found' });
}
if (rental.ownerId !== req.user.id) {
return res.status(403).json({ error: 'Only owners can mark rentals as completed' });
}
if (!['active', 'confirmed'].includes(rental.status)) {
return res.status(400).json({ error: 'Can only mark active or confirmed rentals as completed' });
}
await rental.update({ status: 'completed' });
const updatedRental = await Rental.findByPk(rental.id, {
include: [
{ model: Item, as: 'item' },
{ model: User, as: 'owner', attributes: ['id', 'username', 'firstName', 'lastName'] },
{ model: User, as: 'renter', attributes: ['id', 'username', 'firstName', 'lastName'] }
]
});
res.json(updatedRental);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Legacy review endpoint (for backward compatibility)
router.post('/:id/review', authenticateToken, async (req, res) => {
try {
const { rating, review } = req.body;

View File

@@ -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

File diff suppressed because it is too large Load Diff

View File

@@ -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>

View File

@@ -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;

View File

@@ -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;

View File

@@ -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>

View File

@@ -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>
);
};

View File

@@ -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;

View File

@@ -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>
);
};

View File

@@ -312,7 +312,7 @@ const RentItem: React.FC = () => {
name="cardName"
value={formData.cardName}
onChange={handleChange}
placeholder="John Doe"
placeholder=""
required
/>
</div>

View File

@@ -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 = {

View File

@@ -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;