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, allowNull: false,
defaultValue: false, defaultValue: false,
}, },
unavailablePeriods: {
type: DataTypes.JSONB,
defaultValue: [],
},
availableAfter: { availableAfter: {
type: DataTypes.STRING, type: DataTypes.STRING,
defaultValue: "09:00", defaultValue: "09:00",

View File

@@ -39,6 +39,12 @@ const Rental = sequelize.define('Rental', {
type: DataTypes.DATE, type: DataTypes.DATE,
allowNull: false allowNull: false
}, },
startTime: {
type: DataTypes.STRING
},
endTime: {
type: DataTypes.STRING
},
totalAmount: { totalAmount: {
type: DataTypes.DECIMAL(10, 2), type: DataTypes.DECIMAL(10, 2),
allowNull: false allowNull: false
@@ -61,6 +67,50 @@ const Rental = sequelize.define('Rental', {
notes: { notes: {
type: DataTypes.TEXT 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: { rating: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
validate: { validate: {

View File

@@ -4,10 +4,53 @@ const { Rental, Item, User } = require('../models'); // Import from models/index
const { authenticateToken } = require('../middleware/auth'); const { authenticateToken } = require('../middleware/auth');
const router = express.Router(); 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) => { router.get('/my-rentals', authenticateToken, async (req, res) => {
try { try {
const rentals = await Rental.findAll({ const rentals = await Rental.findAll({
where: { renterId: req.user.id }, where: { renterId: req.user.id },
// Remove explicit attributes to let Sequelize handle missing columns gracefully
include: [ include: [
{ model: Item, as: 'item' }, { model: Item, as: 'item' },
{ model: User, as: 'owner', attributes: ['id', 'username', 'firstName', 'lastName'] } { model: User, as: 'owner', attributes: ['id', 'username', 'firstName', 'lastName'] }
@@ -15,8 +58,10 @@ router.get('/my-rentals', authenticateToken, async (req, res) => {
order: [['createdAt', 'DESC']] order: [['createdAt', 'DESC']]
}); });
console.log('My-rentals data:', rentals.length > 0 ? rentals[0].toJSON() : 'No rentals');
res.json(rentals); res.json(rentals);
} catch (error) { } catch (error) {
console.error('Error in my-rentals route:', error);
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}); });
@@ -25,6 +70,7 @@ router.get('/my-listings', authenticateToken, async (req, res) => {
try { try {
const rentals = await Rental.findAll({ const rentals = await Rental.findAll({
where: { ownerId: req.user.id }, where: { ownerId: req.user.id },
// Remove explicit attributes to let Sequelize handle missing columns gracefully
include: [ include: [
{ model: Item, as: 'item' }, { model: Item, as: 'item' },
{ model: User, as: 'renter', attributes: ['id', 'username', 'firstName', 'lastName'] } { model: User, as: 'renter', attributes: ['id', 'username', 'firstName', 'lastName'] }
@@ -32,15 +78,17 @@ router.get('/my-listings', authenticateToken, async (req, res) => {
order: [['createdAt', 'DESC']] order: [['createdAt', 'DESC']]
}); });
console.log('My-listings rentals:', rentals.length > 0 ? rentals[0].toJSON() : 'No rentals');
res.json(rentals); res.json(rentals);
} catch (error) { } catch (error) {
console.error('Error in my-listings route:', error);
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}); });
router.post('/', authenticateToken, async (req, res) => { router.post('/', authenticateToken, async (req, res) => {
try { 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); const item = await Item.findByPk(itemId);
if (!item) { if (!item) {
@@ -79,6 +127,8 @@ router.post('/', authenticateToken, async (req, res) => {
ownerId: item.ownerId, ownerId: item.ownerId,
startDate, startDate,
endDate, endDate,
startTime,
endTime,
totalAmount, totalAmount,
deliveryMethod, deliveryMethod,
deliveryAddress, 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) => { router.post('/:id/review', authenticateToken, async (req, res) => {
try { try {
const { rating, review } = req.body; const { rating, review } = req.body;

View File

@@ -310,7 +310,7 @@ const AuthModal: React.FC<AuthModalProps> = ({
<input <input
type="tel" type="tel"
className="form-control" className="form-control"
placeholder="(555) 123-4567" placeholder="(123) 456-7890"
value={phoneNumber} value={phoneNumber}
onChange={handlePhoneChange} onChange={handlePhoneChange}
required required

File diff suppressed because it is too large Load Diff

View File

@@ -148,18 +148,18 @@ const Navbar: React.FC = () => {
<li> <li>
<Link className="dropdown-item" to="/my-rentals"> <Link className="dropdown-item" to="/my-rentals">
<i className="bi bi-calendar-check me-2"></i> <i className="bi bi-calendar-check me-2"></i>
Rentals Renting
</Link> </Link>
</li> </li>
<li> <li>
<Link className="dropdown-item" to="/my-listings"> <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> </Link>
</li> </li>
<li> <li>
<Link className="dropdown-item" to="/my-requests"> <Link className="dropdown-item" to="/my-requests">
<i className="bi bi-clipboard-check me-2"></i> <i className="bi bi-clipboard-check me-2"></i>
Requests Looking For
</Link> </Link>
</li> </li>
<li> <li>

View File

@@ -2,16 +2,17 @@ import React, { useState } from 'react';
import { rentalAPI } from '../services/api'; import { rentalAPI } from '../services/api';
import { Rental } from '../types'; import { Rental } from '../types';
interface ReviewModalProps { interface ReviewItemModalProps {
show: boolean; show: boolean;
onClose: () => void; onClose: () => void;
rental: Rental; rental: Rental;
onSuccess: () => void; 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 [rating, setRating] = useState(5);
const [review, setReview] = useState(''); const [review, setReview] = useState('');
const [privateMessage, setPrivateMessage] = useState('');
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -21,16 +22,25 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
setSubmitting(true); setSubmitting(true);
try { try {
await rentalAPI.addReview(rental.id, { const response = await rentalAPI.reviewItem(rental.id, {
rating, rating,
review review,
privateMessage
}); });
// Reset form // Reset form
setRating(5); setRating(5);
setReview(''); setReview('');
setPrivateMessage('');
onSuccess(); onSuccess();
onClose(); 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) { } catch (err: any) {
setError(err.response?.data?.error || 'Failed to submit review'); setError(err.response?.data?.error || 'Failed to submit review');
} finally { } finally {
@@ -49,7 +59,7 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
<div className="modal-dialog modal-dialog-centered"> <div className="modal-dialog modal-dialog-centered">
<div className="modal-content"> <div className="modal-content">
<div className="modal-header"> <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> <button type="button" className="btn-close" onClick={onClose}></button>
</div> </div>
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
@@ -96,7 +106,9 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
</div> </div>
<div className="mb-3"> <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 <textarea
className="form-control" className="form-control"
id="review" id="review"
@@ -108,7 +120,25 @@ const ReviewModal: React.FC<ReviewModalProps> = ({ show, onClose, rental, onSucc
disabled={submitting} disabled={submitting}
></textarea> ></textarea>
<small className="text-muted"> <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> </small>
</div> </div>
</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); setTotalCost(cost);
}; };
const generateTimeOptions = () => { const generateTimeOptions = (item: Item | null, selectedDate: string) => {
const options = []; 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++) { for (let hour = 0; hour < 24; hour++) {
const time24 = `${hour.toString().padStart(2, "0")}:00`; const time24 = `${hour.toString().padStart(2, "0")}:00`;
// 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 hour12 = hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;
const period = hour < 12 ? "AM" : "PM"; const period = hour < 12 ? "AM" : "PM";
const time12 = `${hour12}:00 ${period}`; const time12 = `${hour12}:00 ${period}`;
options.push({ value: time24, label: time12 }); 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; return options;
}; };
@@ -126,6 +191,34 @@ const ItemDetail: React.FC = () => {
calculateTotalCost(); calculateTotalCost();
}, [rentalDates, item]); }, [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) { if (loading) {
return ( return (
<div className="container mt-5"> <div className="container mt-5">
@@ -392,8 +485,9 @@ const ItemDetail: React.FC = () => {
handleDateTimeChange("startTime", e.target.value) handleDateTimeChange("startTime", e.target.value)
} }
style={{ flex: '1 1 50%' }} 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 key={option.value} value={option.value}>
{option.label} {option.label}
</option> </option>
@@ -425,8 +519,9 @@ const ItemDetail: React.FC = () => {
handleDateTimeChange("endTime", e.target.value) handleDateTimeChange("endTime", e.target.value)
} }
style={{ flex: '1 1 50%' }} 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 key={option.value} value={option.value}>
{option.label} {option.label}
</option> </option>

View File

@@ -4,18 +4,43 @@ import { useAuth } from "../contexts/AuthContext";
import api from "../services/api"; import api from "../services/api";
import { Item, Rental } from "../types"; import { Item, Rental } from "../types";
import { rentalAPI } from "../services/api"; import { rentalAPI } from "../services/api";
import ReviewRenterModal from "../components/ReviewRenterModal";
const MyListings: React.FC = () => { 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 { user } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const [listings, setListings] = useState<Item[]>([]); const [listings, setListings] = useState<Item[]>([]);
const [rentals, setRentals] = useState<Rental[]>([]); const [ownerRentals, setOwnerRentals] = useState<Rental[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(""); const [error, setError] = useState("");
// Owner rental management state
const [showReviewRenterModal, setShowReviewRenterModal] = useState(false);
const [selectedRentalForReview, setSelectedRentalForReview] = useState<Rental | null>(null);
useEffect(() => { useEffect(() => {
fetchMyListings(); fetchMyListings();
fetchRentalRequests(); fetchOwnerRentals();
}, [user]); }, [user]);
const fetchMyListings = async () => { const fetchMyListings = async () => {
@@ -23,7 +48,7 @@ const MyListings: React.FC = () => {
try { try {
setLoading(true); setLoading(true);
setError(""); // Clear any previous errors setError("");
const response = await api.get("/items"); const response = await api.get("/items");
// Filter items to only show ones owned by current user // Filter items to only show ones owned by current user
@@ -33,7 +58,6 @@ const MyListings: React.FC = () => {
setListings(myItems); setListings(myItems);
} catch (err: any) { } catch (err: any) {
console.error("Error fetching listings:", err); console.error("Error fetching listings:", err);
// Only show error for actual API failures
if (err.response && err.response.status >= 500) { if (err.response && err.response.status >= 500) {
setError("Failed to get your listings. Please try again later."); setError("Failed to get your listings. Please try again later.");
} }
@@ -70,40 +94,64 @@ const MyListings: React.FC = () => {
} }
}; };
const fetchRentalRequests = async () => { const fetchOwnerRentals = async () => {
if (!user) return;
try { try {
const response = await rentalAPI.getMyListings(); const response = await rentalAPI.getMyListings();
setRentals(response.data); console.log("Owner rentals data from backend:", response.data);
} catch (err) { setOwnerRentals(response.data);
console.error("Error fetching rental requests:", err); } catch (err: any) {
console.error("Failed to fetch owner rentals:", err);
} }
}; };
// Owner functionality handlers
const handleAcceptRental = async (rentalId: string) => { const handleAcceptRental = async (rentalId: string) => {
try { try {
await rentalAPI.updateRentalStatus(rentalId, "confirmed"); await rentalAPI.updateRentalStatus(rentalId, "confirmed");
// Refresh the rentals list fetchOwnerRentals();
fetchRentalRequests();
} catch (err) { } catch (err) {
console.error("Failed to accept rental request:", err); console.error("Failed to accept rental request:", err);
alert("Failed to accept rental request");
} }
}; };
const handleRejectRental = async (rentalId: string) => { const handleRejectRental = async (rentalId: string) => {
try { try {
await api.put(`/rentals/${rentalId}/status`, { await rentalAPI.updateRentalStatus(rentalId, "cancelled");
status: "cancelled", fetchOwnerRentals();
rejectionReason: "Request declined by owner",
});
// Refresh the rentals list
fetchRentalRequests();
} catch (err) { } catch (err) {
console.error("Failed to reject rental request:", 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) { if (loading) {
return ( return (
<div className="container mt-4"> <div className="container mt-4">
@@ -119,7 +167,7 @@ const MyListings: React.FC = () => {
return ( return (
<div className="container mt-4"> <div className="container mt-4">
<div className="d-flex justify-content-between align-items-center mb-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"> <Link to="/create-item" className="btn btn-primary">
Add New Item Add New Item
</Link> </Link>
@@ -131,25 +179,102 @@ const MyListings: React.FC = () => {
</div> </div>
)} )}
{(() => { {/* Rental Requests Section - Moved to top for priority */}
const pendingCount = rentals.filter( {allOwnerRentals.length > 0 && (
(r) => r.status === "pending" <div className="mb-5">
).length; <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) { {rental.renter && (
return ( <p className="mb-1 text-dark small">
<div <strong>Renter:</strong> {rental.renter.firstName} {rental.renter.lastName}
className="alert alert-info d-flex align-items-center" </p>
role="alert" )}
>
<i className="bi bi-bell-fill me-2"></i> <div className="mb-2">
You have {pendingCount} pending rental request <span className={`badge ${
{pendingCount > 1 ? "s" : ""} to review. 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> </div>
);
} <p className="mb-1 text-dark small">
return null; <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 ? ( {listings.length === 0 ? (
<div className="text-center py-5"> <div className="text-center py-5">
@@ -167,11 +292,7 @@ const MyListings: React.FC = () => {
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={(e: React.MouseEvent<HTMLDivElement>) => { onClick={(e: React.MouseEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
if ( if (target.closest("button") || target.closest("a")) {
target.closest("button") ||
target.closest("a") ||
target.closest(".rental-requests")
) {
return; return;
} }
navigate(`/items/${item.id}`); navigate(`/items/${item.id}`);
@@ -202,16 +323,52 @@ const MyListings: React.FC = () => {
</div> </div>
<div className="mb-3"> <div className="mb-3">
{item.pricePerDay && ( {(() => {
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);
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="text-success small fw-bold">
Free to Borrow
</div>
);
}
return (
<>
{item.pricePerDay && Number(item.pricePerDay) > 0 && (
<div className="text-muted small"> <div className="text-muted small">
${item.pricePerDay}/day ${item.pricePerDay}/day
</div> </div>
)} )}
{item.pricePerHour && ( {item.pricePerHour && Number(item.pricePerHour) > 0 && (
<div className="text-muted small"> <div className="text-muted small">
${item.pricePerHour}/hour ${item.pricePerHour}/hour
</div> </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>
<div className="d-flex gap-2"> <div className="d-flex gap-2">
@@ -236,135 +393,25 @@ const MyListings: React.FC = () => {
Delete Delete
</button> </button>
</div> </div>
{(() => {
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)
);
if (
pendingRentals.length > 0 ||
acceptedRentals.length > 0
) {
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> </div>
</div> </div>
))} ))}
</> </div>
)} )}
{acceptedRentals.length > 0 && (
<> {/* Review Modal */}
<h6 className="text-success mb-2 mt-3"> {selectedRentalForReview && (
<i className="bi bi-check-circle-fill"></i>{" "} <ReviewRenterModal
Accepted Rentals ({acceptedRentals.length}) show={showReviewRenterModal}
</h6> onClose={() => {
{acceptedRentals.map((rental) => ( setShowReviewRenterModal(false);
<div setSelectedRentalForReview(null);
key={rental.id} }}
className="border rounded p-2 mb-2 bg-light" rental={selectedRentalForReview}
> onSuccess={handleReviewRenterSuccess}
<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>
);
}
return null;
})()}
</div>
</div>
</div>
))}
</div>
)} )}
</div> </div>
); );

View File

@@ -3,15 +3,35 @@ import { Link } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext"; import { useAuth } from "../contexts/AuthContext";
import { rentalAPI } from "../services/api"; import { rentalAPI } from "../services/api";
import { Rental } from "../types"; import { Rental } from "../types";
import ReviewModal from "../components/ReviewModal"; import ReviewItemModal from "../components/ReviewModal";
import ConfirmationModal from "../components/ConfirmationModal"; import ConfirmationModal from "../components/ConfirmationModal";
const MyRentals: React.FC = () => { 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 { user } = useAuth();
const [rentals, setRentals] = useState<Rental[]>([]); const [rentals, setRentals] = useState<Rental[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<"active" | "past">("active");
const [showReviewModal, setShowReviewModal] = useState(false); const [showReviewModal, setShowReviewModal] = useState(false);
const [selectedRental, setSelectedRental] = useState<Rental | null>(null); const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
const [showCancelModal, setShowCancelModal] = useState(false); const [showCancelModal, setShowCancelModal] = useState(false);
@@ -25,6 +45,10 @@ const MyRentals: React.FC = () => {
const fetchRentals = async () => { const fetchRentals = async () => {
try { try {
const response = await rentalAPI.getMyRentals(); 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); setRentals(response.data);
} catch (err: any) { } catch (err: any) {
setError(err.response?.data?.message || "Failed to fetch rentals"); setError(err.response?.data?.message || "Failed to fetch rentals");
@@ -44,7 +68,7 @@ const MyRentals: React.FC = () => {
setCancelling(true); setCancelling(true);
try { try {
await rentalAPI.updateRentalStatus(rentalToCancel, "cancelled"); await rentalAPI.updateRentalStatus(rentalToCancel, "cancelled");
fetchRentals(); // Refresh the list fetchRentals();
setShowCancelModal(false); setShowCancelModal(false);
setRentalToCancel(null); setRentalToCancel(null);
} catch (err: any) { } catch (err: any) {
@@ -60,19 +84,14 @@ const MyRentals: React.FC = () => {
}; };
const handleReviewSuccess = () => { const handleReviewSuccess = () => {
fetchRentals(); // Refresh to show the review has been added fetchRentals();
alert("Thank you for your review!"); alert("Thank you for your review!");
}; };
// Filter rentals based on status // Filter rentals - only show active rentals (pending, confirmed, active)
const activeRentals = rentals.filter((r) => const renterActiveRentals = rentals.filter((r) =>
["pending", "confirmed", "active"].includes(r.status) ["pending", "confirmed", "active"].includes(r.status)
); );
const pastRentals = rentals.filter((r) =>
["completed", "cancelled"].includes(r.status)
);
const displayedRentals = activeTab === "active" ? activeRentals : pastRentals;
if (loading) { if (loading) {
return ( return (
@@ -100,39 +119,17 @@ const MyRentals: React.FC = () => {
<div className="container mt-4"> <div className="container mt-4">
<h1>My Rentals</h1> <h1>My Rentals</h1>
<ul className="nav nav-tabs mb-4"> {renterActiveRentals.length === 0 ? (
<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 ? (
<div className="text-center py-5"> <div className="text-center py-5">
<p className="text-muted"> <h5 className="text-muted">No Active Rental Requests</h5>
{activeTab === "active" <p className="text-muted">You don't have any rental requests at the moment.</p>
? "You don't have any active rentals." <Link to="/items" className="btn btn-primary">
: "You don't have any past rentals."}
</p>
<Link to="/items" className="btn btn-primary mt-3">
Browse Items to Rent Browse Items to Rent
</Link> </Link>
</div> </div>
) : ( ) : (
<div className="row"> <div className="row">
{displayedRentals.map((rental) => ( {renterActiveRentals.map((rental) => (
<div key={rental.id} className="col-md-6 col-lg-4 mb-4"> <div key={rental.id} className="col-md-6 col-lg-4 mb-4">
<Link <Link
to={rental.item ? `/items/${rental.item.id}` : "#"} to={rental.item ? `/items/${rental.item.id}` : "#"}
@@ -144,10 +141,7 @@ const MyRentals: React.FC = () => {
} }
}} }}
> >
<div <div className="card h-100" style={{ cursor: rental.item ? "pointer" : "default" }}>
className="card h-100"
style={{ cursor: rental.item ? "pointer" : "default" }}
>
{rental.item?.images && rental.item.images[0] && ( {rental.item?.images && rental.item.images[0] && (
<img <img
src={rental.item.images[0]} src={rental.item.images[0]}
@@ -162,21 +156,12 @@ const MyRentals: React.FC = () => {
</h5> </h5>
<div className="mb-2"> <div className="mb-2">
<span <span className={`badge ${
className={`badge ${ rental.status === "active" ? "bg-success" :
rental.status === "active" rental.status === "pending" ? "bg-warning" :
? "bg-success" rental.status === "confirmed" ? "bg-info" : "bg-danger"
: rental.status === "pending" }`}>
? "bg-warning" {rental.status.charAt(0).toUpperCase() + rental.status.slice(1)}
: rental.status === "confirmed"
? "bg-info"
: rental.status === "completed"
? "bg-secondary"
: "bg-danger"
}`}
>
{rental.status.charAt(0).toUpperCase() +
rental.status.slice(1)}
</span> </span>
{rental.paymentStatus === "paid" && ( {rental.paymentStatus === "paid" && (
<span className="badge bg-success ms-2">Paid</span> <span className="badge bg-success ms-2">Paid</span>
@@ -186,33 +171,32 @@ const MyRentals: React.FC = () => {
<p className="mb-1 text-dark"> <p className="mb-1 text-dark">
<strong>Rental Period:</strong> <strong>Rental Period:</strong>
<br /> <br />
{new Date(rental.startDate).toLocaleDateString()} -{" "} <strong>Start:</strong> {formatDateTime(rental.startDate, rental.startTime)}
{new Date(rental.endDate).toLocaleDateString()} <br />
<strong>End:</strong> {formatDateTime(rental.endDate, rental.endTime)}
</p> </p>
<p className="mb-1 text-dark"> <p className="mb-1 text-dark">
<strong>Total:</strong> ${rental.totalAmount} <strong>Total:</strong> ${rental.totalAmount}
</p> </p>
<p className="mb-1 text-dark">
<strong>Delivery:</strong>{" "}
{rental.deliveryMethod === "pickup"
? "Pick-up"
: "Delivery"}
</p>
{rental.owner && ( {rental.owner && (
<p className="mb-1 text-dark"> <p className="mb-1 text-dark">
<strong>Owner:</strong> {rental.owner.firstName}{" "} <strong>Owner:</strong> {rental.owner.firstName} {rental.owner.lastName}
{rental.owner.lastName}
</p> </p>
)} )}
{rental.status === "cancelled" && {rental.renterPrivateMessage && rental.renterReviewVisible && (
rental.rejectionReason && ( <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"> <div className="alert alert-warning mt-2 mb-1 p-2 small">
<strong>Rejection reason:</strong>{" "} <strong>Rejection reason:</strong> {rental.rejectionReason}
{rental.rejectionReason}
</div> </div>
)} )}
@@ -225,15 +209,27 @@ const MyRentals: React.FC = () => {
Cancel Cancel
</button> </button>
)} )}
{rental.status === "completed" && !rental.rating && ( {rental.status === "active" && !rental.itemRating && !rental.itemReviewSubmittedAt && (
<button <button
className="btn btn-sm btn-primary" className="btn btn-sm btn-primary"
onClick={() => handleReviewClick(rental)} onClick={() => handleReviewClick(rental)}
> >
Leave Review Review
</button> </button>
)} )}
{rental.status === "completed" && rental.rating && ( {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"> <div className="text-success small">
<i className="bi bi-check-circle-fill me-1"></i> <i className="bi bi-check-circle-fill me-1"></i>
Reviewed ({rental.rating}/5) Reviewed ({rental.rating}/5)
@@ -248,8 +244,9 @@ const MyRentals: React.FC = () => {
</div> </div>
)} )}
{/* Review Modal */}
{selectedRental && ( {selectedRental && (
<ReviewModal <ReviewItemModal
show={showReviewModal} show={showReviewModal}
onClose={() => { onClose={() => {
setShowReviewModal(false); setShowReviewModal(false);

View File

@@ -4,6 +4,8 @@ import { userAPI, itemAPI, rentalAPI, addressAPI } from "../services/api";
import { User, Item, Rental, Address } from "../types"; import { User, Item, Rental, Address } from "../types";
import { getImageUrl } from "../utils/imageUrl"; import { getImageUrl } from "../utils/imageUrl";
import AvailabilitySettings from "../components/AvailabilitySettings"; import AvailabilitySettings from "../components/AvailabilitySettings";
import ReviewItemModal from "../components/ReviewModal";
import ReviewRenterModal from "../components/ReviewRenterModal";
const Profile: React.FC = () => { const Profile: React.FC = () => {
const { user, updateUser, logout } = useAuth(); const { user, updateUser, logout } = useAuth();
@@ -60,11 +62,21 @@ const Profile: React.FC = () => {
country: "US", 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(() => { useEffect(() => {
fetchProfile(); fetchProfile();
fetchStats(); fetchStats();
fetchUserAddresses(); fetchUserAddresses();
fetchUserAvailability(); fetchUserAvailability();
fetchRentalHistory();
}, []); }, []);
const fetchUserAvailability = async () => { 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 = ( const handleChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => { ) => {
@@ -472,6 +551,15 @@ const Profile: React.FC = () => {
<i className="bi bi-gear me-2"></i> <i className="bi bi-gear me-2"></i>
Owner Settings Owner Settings
</button> </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 <button
className={`list-group-item list-group-item-action ${ className={`list-group-item list-group-item-action ${
activeSection === "personal-info" ? "active" : "" activeSection === "personal-info" ? "active" : ""
@@ -677,6 +765,225 @@ const Profile: React.FC = () => {
</div> </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 */} {/* Personal Information Section */}
{activeSection === "personal-info" && ( {activeSection === "personal-info" && (
<div> <div>
@@ -710,7 +1017,7 @@ const Profile: React.FC = () => {
name="phone" name="phone"
value={formData.phone} value={formData.phone}
onChange={handleChange} onChange={handleChange}
placeholder="+1 (555) 123-4567" placeholder="(123) 456-7890"
disabled={!editing} disabled={!editing}
/> />
</div> </div>
@@ -1022,6 +1329,31 @@ const Profile: React.FC = () => {
)} )}
</div> </div>
</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> </div>
); );
}; };

View File

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

View File

@@ -78,7 +78,10 @@ export const rentalAPI = {
getMyListings: () => api.get("/rentals/my-listings"), getMyListings: () => api.get("/rentals/my-listings"),
updateRentalStatus: (id: string, status: string) => updateRentalStatus: (id: string, status: string) =>
api.put(`/rentals/${id}/status`, { status }), 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 = { export const messageAPI = {

View File

@@ -78,13 +78,6 @@ export interface Item {
minimumRentalDays: number; minimumRentalDays: number;
maximumRentalDays?: number; maximumRentalDays?: number;
needsTraining?: boolean; needsTraining?: boolean;
unavailablePeriods?: Array<{
id: string;
startDate: Date;
endDate: Date;
startTime?: string;
endTime?: string;
}>;
availableAfter?: string; availableAfter?: string;
availableBefore?: string; availableBefore?: string;
specifyTimesPerDay?: boolean; specifyTimesPerDay?: boolean;
@@ -110,6 +103,8 @@ export interface Rental {
ownerId: string; ownerId: string;
startDate: string; startDate: string;
endDate: string; endDate: string;
startTime?: string;
endTime?: string;
totalAmount: number; totalAmount: number;
status: "pending" | "confirmed" | "active" | "completed" | "cancelled"; status: "pending" | "confirmed" | "active" | "completed" | "cancelled";
paymentStatus: "pending" | "paid" | "refunded"; paymentStatus: "pending" | "paid" | "refunded";
@@ -119,6 +114,18 @@ export interface Rental {
rating?: number; rating?: number;
review?: string; review?: string;
rejectionReason?: 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; item?: Item;
renter?: User; renter?: User;
owner?: User; owner?: User;