refactor mylistings and my rentals

This commit is contained in:
jackiettran
2025-11-01 22:33:59 -04:00
parent 16272ba373
commit 6d0beccea0
14 changed files with 42 additions and 42 deletions

View File

@@ -0,0 +1,473 @@
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext";
import { rentalAPI, conditionCheckAPI } from "../services/api";
import { Rental } from "../types";
import ReviewItemModal from "../components/ReviewModal";
import RentalCancellationModal from "../components/RentalCancellationModal";
import ConditionCheckModal from "../components/ConditionCheckModal";
const Renting: 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 = (dateTimeString: string) => {
const date = new Date(dateTimeString);
return date
.toLocaleDateString("en-US", {
month: "2-digit",
day: "2-digit",
year: "numeric",
hour: "numeric",
minute: "2-digit",
hour12: true,
})
.replace(",", "");
};
const { user } = useAuth();
const [rentals, setRentals] = useState<Rental[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [showReviewModal, setShowReviewModal] = useState(false);
const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
const [showCancelModal, setShowCancelModal] = useState(false);
const [rentalToCancel, setRentalToCancel] = useState<Rental | null>(null);
const [showConditionCheckModal, setShowConditionCheckModal] = useState(false);
const [conditionCheckData, setConditionCheckData] = useState<{
rental: Rental;
checkType: string;
} | null>(null);
const [availableChecks, setAvailableChecks] = useState<any[]>([]);
const [conditionChecks, setConditionChecks] = useState<any[]>([]);
useEffect(() => {
fetchRentals();
fetchAvailableChecks();
}, []);
useEffect(() => {
if (rentals.length > 0) {
fetchConditionChecks();
}
}, [rentals]);
const fetchRentals = async () => {
try {
const response = await rentalAPI.getRentals();
setRentals(response.data);
} catch (err: any) {
setError(err.response?.data?.message || "Failed to fetch rentals");
} finally {
setLoading(false);
}
};
const fetchAvailableChecks = async () => {
try {
const response = await conditionCheckAPI.getAvailableChecks();
const checks = Array.isArray(response.data.availableChecks)
? response.data.availableChecks
: [];
setAvailableChecks(checks);
} catch (err: any) {
console.error("Failed to fetch available checks:", err);
setAvailableChecks([]);
}
};
const fetchConditionChecks = async () => {
try {
// Fetch condition checks for all rentals
const allChecks: any[] = [];
for (const rental of rentals) {
try {
const response = await conditionCheckAPI.getConditionChecks(
rental.id
);
const checks = Array.isArray(response.data.conditionChecks)
? response.data.conditionChecks
: [];
allChecks.push(...checks);
} catch (err) {
// Continue even if one rental fails
console.error(`Failed to fetch checks for rental ${rental.id}:`, err);
}
}
setConditionChecks(allChecks);
} catch (err: any) {
console.error("Failed to fetch condition checks:", err);
setConditionChecks([]);
}
};
const handleCancelClick = (rental: Rental) => {
setRentalToCancel(rental);
setShowCancelModal(true);
};
const handleCancellationComplete = (updatedRental: Rental) => {
// Update the rental in the list
setRentals((prev) =>
prev.map((rental) =>
rental.id === updatedRental.id ? updatedRental : rental
)
);
setShowCancelModal(false);
setRentalToCancel(null);
};
const handleReviewClick = (rental: Rental) => {
setSelectedRental(rental);
setShowReviewModal(true);
};
const handleReviewSuccess = () => {
fetchRentals();
alert("Thank you for your review!");
};
const handleConditionCheck = (rental: Rental, checkType: string) => {
setConditionCheckData({ rental, checkType });
setShowConditionCheckModal(true);
};
const handleConditionCheckSuccess = () => {
fetchAvailableChecks();
fetchConditionChecks();
alert("Condition check submitted successfully!");
};
const getAvailableChecksForRental = (rentalId: string) => {
if (!Array.isArray(availableChecks)) return [];
return availableChecks.filter(
(check) =>
check.rentalId === rentalId &&
(check.checkType === "rental_start_renter" ||
check.checkType === "rental_end_renter")
);
};
const getCompletedChecksForRental = (rentalId: string) => {
if (!Array.isArray(conditionChecks)) return [];
return conditionChecks.filter(
(check) =>
check.rentalId === rentalId &&
(check.checkType === "rental_start_renter" ||
check.checkType === "rental_end_renter")
);
};
// Filter rentals - show active and declined rentals
const renterActiveRentals = rentals.filter((r) =>
["pending", "confirmed", "declined", "active"].includes(r.status)
);
if (loading) {
return (
<div className="container mt-5">
<div className="text-center">
<div className="spinner-border" role="status">
<span className="visually-hidden">Loading...</span>
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="container mt-5">
<div className="alert alert-danger" role="alert">
{error}
</div>
</div>
);
}
return (
<div className="container mt-4">
<h1>My Rentals</h1>
{renterActiveRentals.length === 0 ? (
<div className="text-center py-5">
<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">
{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();
}
}}
>
<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>
<div className="mb-2">
<span
className={`badge ${
rental.status === "active"
? "bg-success"
: rental.status === "pending"
? "bg-warning"
: rental.status === "confirmed"
? "bg-info"
: rental.status === "declined"
? "bg-secondary"
: "bg-danger"
}`}
>
{rental.status === "pending"
? "Awaiting Owner Approval"
: rental.status === "confirmed"
? "Confirmed & Paid"
: rental.status === "declined"
? "Declined by Owner"
: rental.status.charAt(0).toUpperCase() +
rental.status.slice(1)}
</span>
</div>
<p className="mb-1 text-dark">
<strong>Rental Period:</strong>
<br />
<strong>Start:</strong>{" "}
{formatDateTime(rental.startDateTime)}
<br />
<strong>End:</strong> {formatDateTime(rental.endDateTime)}
</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 === "declined" && rental.declineReason && (
<div className="alert alert-warning mt-2 mb-1 p-2 small">
<strong>Decline reason:</strong>{" "}
{rental.declineReason}
</div>
)}
{rental.status === "cancelled" && (
<>
{rental.refundAmount !== undefined && (
<div className="alert alert-info mt-2 mb-1 p-2 small">
<strong>
<i className="bi bi-arrow-return-left me-1"></i>
Refund:
</strong>{" "}
${rental.refundAmount?.toFixed(2) || "0.00"}
{rental.refundProcessedAt && (
<small className="d-block text-muted mt-1">
Processed:{" "}
{new Date(
rental.refundProcessedAt
).toLocaleDateString()}
</small>
)}
{rental.refundReason && (
<small className="d-block mt-1">
{rental.refundReason}
</small>
)}
</div>
)}
</>
)}
<div className="d-flex flex-column gap-2 mt-3">
<div className="d-flex gap-2">
{(rental.status === "pending" ||
rental.status === "confirmed") && (
<button
className="btn btn-sm btn-danger"
onClick={() => handleCancelClick(rental)}
>
Cancel
</button>
)}
{rental.status === "active" &&
!rental.itemRating &&
!rental.itemReviewSubmittedAt && (
<button
className="btn btn-sm btn-primary"
onClick={() => handleReviewClick(rental)}
>
Review
</button>
)}
</div>
{/* Condition Check Status */}
{getCompletedChecksForRental(rental.id).length > 0 && (
<div className="mb-2">
{getCompletedChecksForRental(rental.id).map(
(check) => (
<div
key={`${rental.id}-${check.checkType}-status`}
className="text-success small"
>
<i className="bi bi-camera-fill me-1"></i>
{check.checkType === "rental_start_renter"
? "Start Check Completed"
: "End Check Completed"}
<small className="text-muted ms-2">
{new Date(
check.createdAt
).toLocaleDateString()}
</small>
</div>
)
)}
</div>
)}
{/* Condition Check Buttons */}
{getAvailableChecksForRental(rental.id).map((check) => (
<button
key={`${rental.id}-${check.checkType}`}
className="btn btn-sm btn-outline-primary"
onClick={() =>
handleConditionCheck(rental, check.checkType)
}
>
<i className="bi bi-camera me-2" />
{check.checkType === "rental_start_renter"
? "Submit Start Check"
: "Submit End Check"}
</button>
))}
{/* Review Status */}
{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>
</Link>
</div>
))}
</div>
)}
{/* Review Modal */}
{selectedRental && (
<ReviewItemModal
show={showReviewModal}
onClose={() => {
setShowReviewModal(false);
setSelectedRental(null);
}}
rental={selectedRental}
onSuccess={handleReviewSuccess}
/>
)}
{rentalToCancel && (
<RentalCancellationModal
show={showCancelModal}
onHide={() => {
setShowCancelModal(false);
setRentalToCancel(null);
}}
rental={rentalToCancel}
onCancellationComplete={handleCancellationComplete}
/>
)}
{/* Condition Check Modal */}
{conditionCheckData && (
<ConditionCheckModal
show={showConditionCheckModal}
onHide={() => {
setShowConditionCheckModal(false);
setConditionCheckData(null);
}}
rentalId={conditionCheckData.rental.id}
checkType={conditionCheckData.checkType}
itemName={conditionCheckData.rental.item?.name || "Item"}
onSuccess={handleConditionCheckSuccess}
/>
)}
</div>
);
};
export default Renting;