refund and delayed charge

This commit is contained in:
jackiettran
2025-09-04 16:44:47 -04:00
parent b59fc07fc3
commit b22e4fa910
19 changed files with 1255 additions and 594 deletions

View File

@@ -23,7 +23,6 @@ import ItemRequestDetail from './pages/ItemRequestDetail';
import CreateItemRequest from './pages/CreateItemRequest';
import MyRequests from './pages/MyRequests';
import EarningsDashboard from './pages/EarningsDashboard';
import CheckoutReturn from './components/CheckoutReturn';
import PrivateRoute from './components/PrivateRoute';
import './App.css';
@@ -131,14 +130,6 @@ function App() {
<EarningsDashboard />
</PrivateRoute>
}
/>
<Route
path="/checkout/return"
element={
<PrivateRoute>
<CheckoutReturn />
</PrivateRoute>
}
/>
</Routes>
</main>

View File

@@ -1,254 +0,0 @@
import React, { useState, useEffect, useRef } from "react";
import { useSearchParams, useNavigate } from "react-router-dom";
import { stripeAPI, rentalAPI } from "../services/api";
const CheckoutReturn: React.FC = () => {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const [status, setStatus] = useState<
"loading" | "success" | "error" | "failed" | "rental_error"
>("loading");
const [error, setError] = useState<string | null>(null);
const [processing, setProcessing] = useState(false);
const [itemId, setItemId] = useState<string | null>(null);
const [sessionMetadata, setSessionMetadata] = useState<any>(null);
const hasProcessed = useRef(false);
useEffect(() => {
if (hasProcessed.current) return;
const sessionId = searchParams.get("session_id");
if (!sessionId) {
setStatus("error");
setError("No session ID found in URL");
return;
}
hasProcessed.current = true;
checkSessionStatus(sessionId);
}, [searchParams]);
const createRental = async (metadata: any) => {
try {
if (!metadata || !metadata.itemId) {
throw new Error("No rental data found in Stripe metadata");
}
// Convert metadata back to proper types
const rentalData = {
itemId: metadata.itemId,
startDateTime: metadata.startDateTime,
endDateTime: metadata.endDateTime,
totalAmount: parseFloat(metadata.totalAmount),
deliveryMethod: metadata.deliveryMethod,
paymentStatus: "paid", // Set since payment already succeeded
};
const response = await rentalAPI.createRental(rentalData);
return response;
} catch (error: any) {
const errorMessage =
error.response?.data?.message ||
error.message ||
"Failed to create rental";
console.error("Rental creation error:", errorMessage);
throw new Error(errorMessage);
}
};
const checkSessionStatus = async (sessionId: string) => {
try {
setProcessing(true);
// Get checkout session status
const response = await stripeAPI.getCheckoutSession(sessionId);
const { status: sessionStatus, payment_status, metadata } = response.data;
// Store metadata for retry functionality
setSessionMetadata(metadata);
if (metadata?.itemId) {
setItemId(metadata.itemId);
}
if (sessionStatus === "complete" && payment_status === "paid") {
// Payment was successful - now create the rental
try {
const rentalResult = await createRental(metadata);
setStatus("success");
} catch (rentalError: any) {
// Payment succeeded but rental creation failed
setStatus("rental_error");
setError(rentalError.message || "Failed to create rental record");
}
} else if (sessionStatus === "open") {
// Payment was not completed
setStatus("failed");
setError("Payment was not completed. Please try again.");
} else {
setStatus("error");
setError("Payment failed or was cancelled.");
}
} catch (error: any) {
setStatus("error");
setError(
error.response?.data?.error || "Failed to verify payment status"
);
} finally {
setProcessing(false);
}
};
const handleRetry = () => {
// Go back to the item page to try payment again
if (itemId) {
navigate(`/items/${itemId}`);
} else {
navigate("/");
}
};
const handleRetryRentalCreation = async () => {
setProcessing(true);
try {
await createRental(sessionMetadata);
setStatus("success");
setError(null);
} catch (error: any) {
setError(error.message || "Failed to create rental record");
} finally {
setProcessing(false);
}
};
const handleGoToRentals = () => {
navigate("/my-rentals");
};
if (status === "loading" || processing) {
return (
<div className="container mt-5">
<div className="row justify-content-center">
<div className="col-md-6 text-center">
<div className="spinner-border mb-3" role="status">
<span className="visually-hidden">Loading...</span>
</div>
<h3>Processing your payment...</h3>
<p className="text-muted">
Please wait while we confirm your payment and set up your rental.
</p>
</div>
</div>
</div>
);
}
if (status === "success") {
return (
<div className="container mt-5">
<div className="row justify-content-center">
<div className="col-md-6 text-center">
<div className="alert alert-success p-4">
<i className="bi bi-check-circle-fill display-1 text-success mb-3"></i>
<h2>Payment Successful!</h2>
<p className="mb-4">
Your rental has been confirmed. You can view the details in your
rentals page.
</p>
<div className="d-grid gap-2 d-md-block">
<button
className="btn btn-primary btn-lg me-2"
onClick={handleGoToRentals}
>
View My Rentals
</button>
<button
className="btn btn-outline-secondary btn-lg"
onClick={() => navigate("/")}
>
Continue Browsing
</button>
</div>
</div>
</div>
</div>
</div>
);
}
if (status === "rental_error") {
return (
<div className="container mt-5">
<div className="row justify-content-center">
<div className="col-md-6 text-center">
<div className="alert alert-warning p-4">
<i className="bi bi-exclamation-triangle-fill display-1 text-warning mb-3"></i>
<h2>Payment Successful - Rental Setup Issue</h2>
<p className="mb-4">
Your payment was processed successfully, but we encountered an
issue creating your rental record:
<br />
<strong>{error}</strong>
</p>
<div className="d-grid gap-2 d-md-block">
<button
className="btn btn-primary btn-lg me-2"
onClick={handleRetryRentalCreation}
disabled={processing}
>
{processing ? "Retrying..." : "Retry Rental Creation"}
</button>
<button
className="btn btn-outline-secondary btn-lg"
onClick={() => navigate("/")}
>
Contact Support
</button>
</div>
</div>
</div>
</div>
</div>
);
}
if (status === "failed" || status === "error") {
return (
<div className="container mt-5">
<div className="row justify-content-center">
<div className="col-md-6 text-center">
<div className="alert alert-danger p-4">
<i className="bi bi-exclamation-triangle-fill display-1 text-danger mb-3"></i>
<h2>
{status === "failed" ? "Payment Incomplete" : "Payment Error"}
</h2>
<p className="mb-4">
{error || "There was an issue processing your payment."}
</p>
<div className="d-grid gap-2 d-md-block">
<button
className="btn btn-primary btn-lg me-2"
onClick={handleRetry}
>
Try Again
</button>
<button
className="btn btn-outline-secondary btn-lg"
onClick={() => navigate("/")}
>
Go Home
</button>
</div>
</div>
</div>
</div>
</div>
);
}
return null;
};
export default CheckoutReturn;

View File

@@ -0,0 +1,128 @@
import React, { useState, useEffect, useCallback, useRef } from "react";
import { loadStripe } from "@stripe/stripe-js";
import {
EmbeddedCheckoutProvider,
EmbeddedCheckout,
} from "@stripe/react-stripe-js";
import { stripeAPI, rentalAPI } from "../services/api";
const stripePromise = loadStripe(
process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY || ""
);
interface EmbeddedStripeCheckoutProps {
rentalData: any;
onSuccess: () => void;
onError: (error: string) => void;
}
const EmbeddedStripeCheckout: React.FC<EmbeddedStripeCheckoutProps> = ({
rentalData,
onSuccess,
onError,
}) => {
const [clientSecret, setClientSecret] = useState<string>("");
const [creating, setCreating] = useState(false);
const [sessionId, setSessionId] = useState<string>("");
const createCheckoutSession = useCallback(async () => {
try {
setCreating(true);
const response = await stripeAPI.createSetupCheckoutSession({
rentalData
});
setClientSecret(response.data.clientSecret);
setSessionId(response.data.sessionId);
} catch (error: any) {
onError(
error.response?.data?.error || "Failed to create checkout session"
);
} finally {
setCreating(false);
}
}, [rentalData, onError]);
useEffect(() => {
createCheckoutSession();
}, [createCheckoutSession]);
const handleComplete = useCallback(() => {
// For embedded checkout, we need to retrieve the session to get payment method
(async () => {
try {
if (!sessionId) {
throw new Error("No session ID available");
}
// Get the completed checkout session
const sessionResponse = await stripeAPI.getCheckoutSession(sessionId);
const { status: sessionStatus, setup_intent } = sessionResponse.data;
if (sessionStatus !== "complete") {
throw new Error("Payment setup was not completed");
}
if (!setup_intent?.payment_method) {
throw new Error("No payment method found in setup intent");
}
// Extract payment method ID - handle both string ID and object cases
const paymentMethodId = typeof setup_intent.payment_method === 'string'
? setup_intent.payment_method
: setup_intent.payment_method.id;
if (!paymentMethodId) {
throw new Error("No payment method ID found");
}
// Create the rental with the payment method ID
const rentalPayload = {
...rentalData,
stripePaymentMethodId: paymentMethodId
};
await rentalAPI.createRental(rentalPayload);
onSuccess();
} catch (error: any) {
onError(error.response?.data?.error || error.message || "Failed to complete rental request");
}
})();
}, [sessionId, rentalData, onSuccess, onError]);
if (creating) {
return (
<div className="text-center py-4">
<div className="spinner-border mb-3" role="status">
<span className="visually-hidden">Loading...</span>
</div>
<p>Preparing secure checkout...</p>
</div>
);
}
if (!clientSecret) {
return (
<div className="text-center py-4">
<p className="text-muted">Unable to load checkout</p>
</div>
);
}
return (
<div id="embedded-checkout">
<EmbeddedCheckoutProvider
stripe={stripePromise}
options={{
clientSecret,
onComplete: handleComplete
}}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
</div>
);
};
export default EmbeddedStripeCheckout;

View File

@@ -0,0 +1,252 @@
import React, { useState, useEffect, useCallback } from "react";
import { rentalAPI } from "../services/api";
import { RefundPreview, Rental } from "../types";
interface RentalCancellationModalProps {
show: boolean;
onHide: () => void;
rental: Rental;
onCancellationComplete: (updatedRental: Rental) => void;
}
const RentalCancellationModal: React.FC<RentalCancellationModalProps> = ({
show,
onHide,
rental,
onCancellationComplete,
}) => {
const [refundPreview, setRefundPreview] = useState<RefundPreview | null>(
null
);
const [loading, setLoading] = useState(false);
const [processing, setProcessing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [reason, setReason] = useState("");
useEffect(() => {
if (show && rental) {
loadRefundPreview();
}
}, [show, rental]);
const loadRefundPreview = async () => {
try {
setLoading(true);
setError(null);
const response = await rentalAPI.getRefundPreview(rental.id);
setRefundPreview(response.data);
} catch (error: any) {
setError(
error.response?.data?.error || "Failed to calculate refund preview"
);
} finally {
setLoading(false);
}
};
const handleCancel = async () => {
if (!refundPreview) return;
try {
setProcessing(true);
setError(null);
const response = await rentalAPI.cancelRental(rental.id, reason.trim());
onCancellationComplete(response.data.rental);
onHide();
} catch (error: any) {
setError(error.response?.data?.error || "Failed to cancel rental");
} finally {
setProcessing(false);
}
};
const formatCurrency = (amount: number | string | undefined) => {
const numAmount = Number(amount) || 0;
return `$${numAmount.toFixed(2)}`;
};
const getRefundColor = (percentage: number) => {
if (percentage === 0) return "danger";
if (percentage === 0.5) return "warning";
return "success";
};
const handleBackdropClick = useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
onHide();
}
},
[onHide]
);
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.key === "Escape") {
onHide();
}
},
[onHide]
);
useEffect(() => {
if (show) {
document.addEventListener("keydown", handleKeyDown);
document.body.style.overflow = "hidden";
} else {
document.removeEventListener("keydown", handleKeyDown);
document.body.style.overflow = "unset";
}
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.body.style.overflow = "unset";
};
}, [show, handleKeyDown]);
if (!show) return null;
return (
<div
className="modal d-block"
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
onClick={handleBackdropClick}
>
<div className="modal-dialog modal-lg modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Cancel Rental</h5>
<button
type="button"
className="btn-close"
onClick={onHide}
aria-label="Close"
></button>
</div>
<div className="modal-body">
{loading && (
<div className="text-center py-4">
<div className="spinner-border me-2" role="status">
<span className="visually-hidden">Loading...</span>
</div>
Calculating refund...
</div>
)}
{error && (
<div className="alert alert-danger mb-3" role="alert">
{error}
</div>
)}
{refundPreview && !loading && (
<>
<div className="mb-4">
<h5>Rental Details</h5>
<div className="bg-light p-3 rounded">
<p>
<strong>Item:</strong> {rental.item?.name}
</p>
<p>
<strong>Start:</strong>{" "}
{new Date(rental.startDateTime).toLocaleString()}
</p>
<p>
<strong>End:</strong>{" "}
{new Date(rental.endDateTime).toLocaleString()}
</p>
<p>
<strong>Total Amount:</strong>{" "}
{formatCurrency(rental.totalAmount)}
</p>
</div>
</div>
<div className="mb-4">
<h5>Refund Information</h5>
<div
className={`alert alert-${getRefundColor(
refundPreview.refundPercentage
)}`}
>
<div className="d-flex justify-content-between align-items-center">
<div>
<strong>Refund Amount:</strong>{" "}
{formatCurrency(refundPreview.refundAmount)}
</div>
<div>
<strong>
{Math.round(refundPreview.refundPercentage * 100)}%
</strong>
</div>
</div>
<hr />
<small>{refundPreview.reason}</small>
</div>
</div>
<form>
<div className="mb-3">
<label className="form-label">
Cancellation Reason (Optional)
</label>
<textarea
className="form-control"
rows={3}
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="Please provide a reason for cancellation..."
maxLength={500}
/>
<div className="form-text text-muted">
{reason.length}/500 characters
</div>
</div>
</form>
</>
)}
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onHide}
disabled={processing}
>
Keep Rental
</button>
{refundPreview && (
<button
type="button"
className="btn btn-danger"
onClick={handleCancel}
disabled={processing || loading}
>
{processing ? (
<>
<div
className="spinner-border spinner-border-sm me-2"
role="status"
>
<span className="visually-hidden">Loading...</span>
</div>
Processing...
</>
) : (
`Cancel with ${
refundPreview.refundAmount > 0
? `Refund ${formatCurrency(refundPreview.refundAmount)}`
: "No Refund"
}`
)}
</button>
)}
</div>
</div>
</div>
</div>
);
};
export default RentalCancellationModal;

View File

@@ -1,103 +0,0 @@
import React, { useState, useEffect, useCallback, useRef } from "react";
import { loadStripe } from "@stripe/stripe-js";
import {
EmbeddedCheckoutProvider,
EmbeddedCheckout,
Elements,
useStripe,
useElements,
} from "@stripe/react-stripe-js";
import { stripeAPI } from "../services/api";
const stripePromise = loadStripe(
process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY || ""
);
interface PaymentFormProps {
itemName: string;
total: number;
rentalData: any;
onSuccess: () => void;
onError: (error: string) => void;
disabled?: boolean;
}
const PaymentForm: React.FC<PaymentFormProps> = ({
itemName,
total,
rentalData,
onSuccess,
onError,
disabled,
}) => {
// const stripe = useStripe();
// const elements = useElements();
// const [processing, setProcessing] = useState(false);
const [clientSecret, setClientSecret] = useState<string>("");
const hasCreatedSession = useRef(false);
const createCheckoutSession = useCallback(async () => {
if (hasCreatedSession.current) return;
try {
hasCreatedSession.current = true;
const return_url = `${window.location.origin}/checkout/return?session_id={CHECKOUT_SESSION_ID}`;
const requestData = {
itemName,
total,
return_url,
rentalData,
};
const response = await stripeAPI.createCheckoutSession(requestData);
setClientSecret(response.data.clientSecret);
} catch (error: any) {
hasCreatedSession.current = false; // Reset on error so it can be retried
onError(
error.response?.data?.error || "Failed to create checkout session"
);
}
}, [itemName, total, rentalData, onError]);
useEffect(() => {
if (itemName && total > 0 && !clientSecret) {
createCheckoutSession();
}
}, [itemName, total, clientSecret, createCheckoutSession]);
return (
<div id="checkout">
{clientSecret && (
<EmbeddedCheckoutProvider
key={clientSecret}
stripe={stripePromise}
options={{ clientSecret }}
>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
)}
{!clientSecret && (
<div className="text-center">
<div className="spinner-border" role="status">
<span className="visually-hidden">Loading payment...</span>
</div>
<p className="mt-2">Preparing payment...</p>
</div>
)}
</div>
);
};
interface StripePaymentFormProps extends PaymentFormProps {}
const StripePaymentForm: React.FC<StripePaymentFormProps> = (props) => {
return (
<Elements stripe={stripePromise}>
<PaymentForm {...props} />
</Elements>
);
};
export default StripePaymentForm;

View File

@@ -5,6 +5,7 @@ import api from "../services/api";
import { Item, Rental } from "../types";
import { rentalAPI } from "../services/api";
import ReviewRenterModal from "../components/ReviewRenterModal";
import RentalCancellationModal from "../components/RentalCancellationModal";
const MyListings: React.FC = () => {
// Helper function to format time
@@ -37,6 +38,10 @@ const MyListings: React.FC = () => {
const [showReviewRenterModal, setShowReviewRenterModal] = useState(false);
const [selectedRentalForReview, setSelectedRentalForReview] =
useState<Rental | null>(null);
const [showCancelModal, setShowCancelModal] = useState(false);
const [rentalToCancel, setRentalToCancel] = useState<Rental | null>(null);
const [isProcessingPayment, setIsProcessingPayment] = useState<string>("");
const [processingSuccess, setProcessingSuccess] = useState<string>("");
useEffect(() => {
fetchMyListings();
@@ -106,11 +111,37 @@ const MyListings: React.FC = () => {
// Owner functionality handlers
const handleAcceptRental = async (rentalId: string) => {
try {
await rentalAPI.updateRentalStatus(rentalId, "confirmed");
setIsProcessingPayment(rentalId);
const response = await rentalAPI.updateRentalStatus(
rentalId,
"confirmed"
);
// Check if payment processing was successful
if (response.data.paymentStatus === "paid") {
// Payment successful, rental confirmed
setProcessingSuccess(rentalId);
setTimeout(() => {
setProcessingSuccess("");
}, 3000);
}
fetchOwnerRentals();
} catch (err) {
} catch (err: any) {
console.error("Failed to accept rental request:", err);
alert("Failed to accept rental request");
// Check if it's a payment failure
if (err.response?.data?.error?.includes("Payment failed")) {
alert(
`Payment failed during approval: ${
err.response.data.details || "Unknown payment error"
}`
);
} else {
alert("Failed to accept rental request");
}
} finally {
setIsProcessingPayment("");
}
};
@@ -145,9 +176,27 @@ const MyListings: React.FC = () => {
fetchOwnerRentals();
};
const handleCancelClick = (rental: Rental) => {
setRentalToCancel(rental);
setShowCancelModal(true);
};
const handleCancellationComplete = (updatedRental: Rental) => {
// Update the rental in the owner rentals list
setOwnerRentals((prev) =>
prev.map((rental) =>
rental.id === updatedRental.id ? updatedRental : rental
)
);
setShowCancelModal(false);
setRentalToCancel(null);
};
// Filter owner rentals
const allOwnerRentals = ownerRentals
.filter((r) => ["pending", "confirmed", "active"].includes(r.status))
.filter((r) =>
["pending", "confirmed", "active", "cancelled"].includes(r.status)
)
.sort((a, b) => {
const statusOrder = { pending: 0, confirmed: 1, active: 2 };
return (
@@ -242,6 +291,35 @@ const MyListings: React.FC = () => {
<strong>Total:</strong> ${rental.totalAmount}
</p>
{rental.status === "cancelled" &&
rental.refundAmount !== undefined && (
<div className="alert alert-info mt-2 mb-2 p-2 small">
<strong>
<i className="bi bi-arrow-return-left me-1"></i>
Refund:
</strong>{" "}
${Number(rental.refundAmount || 0).toFixed(2)}
{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>
)}
{rental.cancelledBy && (
<small className="d-block text-muted mt-1">
Cancelled by: {rental.cancelledBy}
</small>
)}
</div>
)}
{rental.itemPrivateMessage && rental.itemReviewVisible && (
<div className="alert alert-info mt-2 mb-2 p-2 small">
<strong>
@@ -259,8 +337,28 @@ const MyListings: React.FC = () => {
<button
className="btn btn-sm btn-success"
onClick={() => handleAcceptRental(rental.id)}
disabled={isProcessingPayment === rental.id}
>
Accept
{isProcessingPayment === rental.id ? (
<>
<div
className="spinner-border spinner-border-sm me-2"
role="status"
>
<span className="visually-hidden">
Loading...
</span>
</div>
Processing Payment...
</>
) : processingSuccess === rental.id ? (
<>
<i className="bi bi-check-circle me-1"></i>
Payment Success!
</>
) : (
"Accept"
)}
</button>
<button
className="btn btn-sm btn-danger"
@@ -268,10 +366,31 @@ const MyListings: React.FC = () => {
>
Reject
</button>
<button
className="btn btn-sm btn-outline-danger"
onClick={() => handleCancelClick(rental)}
>
Cancel
</button>
</>
)}
{(rental.status === "active" ||
rental.status === "confirmed") && (
{rental.status === "confirmed" && (
<>
<button
className="btn btn-sm btn-success"
onClick={() => handleCompleteClick(rental)}
>
Complete
</button>
<button
className="btn btn-sm btn-outline-danger"
onClick={() => handleCancelClick(rental)}
>
Cancel
</button>
</>
)}
{rental.status === "active" && (
<button
className="btn btn-sm btn-success"
onClick={() => handleCompleteClick(rental)}
@@ -440,6 +559,19 @@ const MyListings: React.FC = () => {
onSuccess={handleReviewRenterSuccess}
/>
)}
{/* Cancellation Modal */}
{rentalToCancel && (
<RentalCancellationModal
show={showCancelModal}
onHide={() => {
setShowCancelModal(false);
setRentalToCancel(null);
}}
rental={rentalToCancel}
onCancellationComplete={handleCancellationComplete}
/>
)}
</div>
);
};

View File

@@ -4,7 +4,7 @@ import { useAuth } from "../contexts/AuthContext";
import { rentalAPI } from "../services/api";
import { Rental } from "../types";
import ReviewItemModal from "../components/ReviewModal";
import ConfirmationModal from "../components/ConfirmationModal";
import RentalCancellationModal from "../components/RentalCancellationModal";
const MyRentals: React.FC = () => {
// Helper function to format time
@@ -28,8 +28,7 @@ const MyRentals: React.FC = () => {
const [showReviewModal, setShowReviewModal] = useState(false);
const [selectedRental, setSelectedRental] = useState<Rental | null>(null);
const [showCancelModal, setShowCancelModal] = useState(false);
const [rentalToCancel, setRentalToCancel] = useState<string | null>(null);
const [cancelling, setCancelling] = useState(false);
const [rentalToCancel, setRentalToCancel] = useState<Rental | null>(null);
useEffect(() => {
fetchRentals();
@@ -46,25 +45,20 @@ const MyRentals: React.FC = () => {
}
};
const handleCancelClick = (rentalId: string) => {
setRentalToCancel(rentalId);
const handleCancelClick = (rental: Rental) => {
setRentalToCancel(rental);
setShowCancelModal(true);
};
const confirmCancelRental = async () => {
if (!rentalToCancel) return;
setCancelling(true);
try {
await rentalAPI.updateRentalStatus(rentalToCancel, "cancelled");
fetchRentals();
setShowCancelModal(false);
setRentalToCancel(null);
} catch (err: any) {
alert("Failed to cancel rental");
} finally {
setCancelling(false);
}
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) => {
@@ -161,8 +155,12 @@ const MyRentals: React.FC = () => {
: "bg-danger"
}`}
>
{rental.status.charAt(0).toUpperCase() +
rental.status.slice(1)}
{rental.status === "pending"
? "Awaiting Owner Approval"
: rental.status === "confirmed"
? "Confirmed & Paid"
: rental.status.charAt(0).toUpperCase() + rental.status.slice(1)
}
</span>
</div>
@@ -187,6 +185,14 @@ const MyRentals: React.FC = () => {
</p>
)}
{rental.status === "pending" && (
<div className="alert alert-info mt-2 mb-2 p-2 small">
<i className="bi bi-clock me-2"></i>
<strong>Awaiting Approval:</strong> Your payment method is saved.
You'll only be charged if the owner approves your request.
</div>
)}
{rental.renterPrivateMessage &&
rental.renterReviewVisible && (
<div className="alert alert-info mt-2 mb-2 p-2 small">
@@ -199,19 +205,39 @@ const MyRentals: React.FC = () => {
</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>
)}
{rental.status === "cancelled" && (
<>
{rental.rejectionReason && (
<div className="alert alert-warning mt-2 mb-1 p-2 small">
<strong>Rejection reason:</strong>{" "}
{rental.rejectionReason}
</div>
)}
{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 gap-2 mt-3">
{rental.status === "pending" && (
{(rental.status === "pending" || rental.status === "confirmed") && (
<button
className="btn btn-sm btn-danger"
onClick={() => handleCancelClick(rental.id)}
onClick={() => handleCancelClick(rental)}
>
Cancel
</button>
@@ -269,20 +295,17 @@ const MyRentals: React.FC = () => {
/>
)}
<ConfirmationModal
show={showCancelModal}
onClose={() => {
setShowCancelModal(false);
setRentalToCancel(null);
}}
onConfirm={confirmCancelRental}
title="Cancel Rental"
message="Are you sure you want to cancel this rental? This action cannot be undone."
confirmText="Yes, Cancel Rental"
cancelText="Keep Rental"
confirmButtonClass="btn-danger"
loading={cancelling}
/>
{rentalToCancel && (
<RentalCancellationModal
show={showCancelModal}
onHide={() => {
setShowCancelModal(false);
setRentalToCancel(null);
}}
rental={rentalToCancel}
onCancellationComplete={handleCancellationComplete}
/>
)}
</div>
);
};

View File

@@ -1,9 +1,9 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useRef } from "react";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import { Item } from "../types";
import { useAuth } from "../contexts/AuthContext";
import { itemAPI, rentalAPI } from "../services/api";
import StripePaymentForm from "../components/StripePaymentForm";
import EmbeddedStripeCheckout from "../components/EmbeddedStripeCheckout";
const RentItem: React.FC = () => {
const { id } = useParams<{ id: string }>();
@@ -27,6 +27,7 @@ const RentItem: React.FC = () => {
});
const [totalCost, setTotalCost] = useState(0);
const [completed, setCompleted] = useState(false);
const convertToUTC = (dateString: string, timeString: string): string => {
if (!dateString || !timeString) {
@@ -117,8 +118,29 @@ const RentItem: React.FC = () => {
}
};
const handlePaymentSuccess = () => {
console.log("Stripe checkout session created successfully");
const getRentalData = () => {
try {
const startDateTime = convertToUTC(
manualSelection.startDate,
manualSelection.startTime
);
const endDateTime = convertToUTC(
manualSelection.endDate,
manualSelection.endTime
);
return {
itemId: id,
startDateTime,
endDateTime,
deliveryMethod: formData.deliveryMethod,
deliveryAddress: formData.deliveryAddress,
totalAmount: totalCost,
};
} catch (error: any) {
setError(error.message);
return null;
}
};
const handleChange = (
@@ -173,42 +195,69 @@ const RentItem: React.FC = () => {
<div className="row">
<div className="col-md-8">
<div className="card mb-4">
<div className="card-body">
<h5 className="card-title">Payment</h5>
<StripePaymentForm
total={totalCost}
itemName={item.name}
rentalData={{
itemId: item.id,
startDateTime: convertToUTC(
manualSelection.startDate,
manualSelection.startTime
),
endDateTime: convertToUTC(
manualSelection.endDate,
manualSelection.endTime
),
totalAmount: totalCost,
deliveryMethod: "pickup",
}}
onSuccess={handlePaymentSuccess}
onError={(error) => setError(error)}
disabled={
!manualSelection.startDate || !manualSelection.endDate
}
/>
<button
type="button"
className="btn btn-secondary mt-2"
onClick={() => navigate(`/items/${id}`)}
>
Cancel
</button>
{completed ? (
<div className="card mb-4">
<div className="card-body text-center">
<div className="alert alert-success">
<i className="bi bi-check-circle-fill display-1 text-success mb-3"></i>
<h3>Rental Request Sent!</h3>
<p className="mb-3">
Your rental request has been submitted to the owner.
You'll only be charged if they approve your request.
</p>
<div className="d-grid gap-2 d-md-block">
<button
className="btn btn-primary me-2"
onClick={() => navigate("/my-rentals")}
>
View My Rentals
</button>
<button
className="btn btn-outline-secondary"
onClick={() => navigate("/")}
>
Continue Browsing
</button>
</div>
</div>
</div>
</div>
</div>
) : (
<div className="card mb-4">
<div className="card-body">
<h5 className="card-title">Complete Your Rental Request</h5>
<p className="text-muted small mb-3">
Add your payment method to complete your rental request.
You'll only be charged if the owner approves your request.
</p>
{!manualSelection.startDate || !manualSelection.endDate || !getRentalData() ? (
<div className="alert alert-info">
<i className="bi bi-info-circle me-2"></i>
Please complete the rental dates and details above to proceed with payment setup.
</div>
) : (
<>
<EmbeddedStripeCheckout
rentalData={getRentalData()}
onSuccess={() => setCompleted(true)}
onError={(error) => setError(error)}
/>
<div className="text-center mt-3">
<button
type="button"
className="btn btn-outline-secondary"
onClick={() => navigate(`/items/${id}`)}
>
Cancel Request
</button>
</div>
</>
)}
</div>
</div>
)}
</div>
<div className="col-md-4">

View File

@@ -84,6 +84,9 @@ export const rentalAPI = {
api.post(`/rentals/${id}/review-renter`, data),
reviewItem: (id: string, data: any) =>
api.post(`/rentals/${id}/review-item`, data),
getRefundPreview: (id: string) => api.get(`/rentals/${id}/refund-preview`),
cancelRental: (id: string, reason?: string) =>
api.post(`/rentals/${id}/cancel`, { reason }),
};
export const messageAPI = {
@@ -110,18 +113,15 @@ export const itemRequestAPI = {
};
export const stripeAPI = {
createCheckoutSession: (data: {
itemName: string;
total: number;
return_url: string;
rentalData?: any;
}) => api.post("/stripe/create-checkout-session", data),
getCheckoutSession: (sessionId: string) =>
api.get(`/stripe/checkout-session/${sessionId}`),
createConnectedAccount: () => api.post("/stripe/accounts"),
createAccountLink: (data: { refreshUrl: string; returnUrl: string }) =>
api.post("/stripe/account-links", data),
getAccountStatus: () => api.get("/stripe/account-status"),
createSetupCheckoutSession: (data: {
rentalData?: any;
}) => api.post("/stripe/create-setup-checkout-session", data),
};
export default api;

View File

@@ -106,12 +106,19 @@ export interface Rental {
endDateTime: string;
totalAmount: number;
// Fee tracking fields
baseRentalAmount?: number;
platformFee?: number;
processingFee?: number;
payoutAmount?: number;
status: "pending" | "confirmed" | "active" | "completed" | "cancelled";
paymentStatus: "pending" | "paid" | "refunded";
// Refund tracking fields
refundAmount?: number;
refundProcessedAt?: string;
refundReason?: string;
stripeRefundId?: string;
cancelledBy?: "renter" | "owner";
cancelledAt?: string;
stripePaymentIntentId?: string;
stripePaymentMethodId?: string;
// Payout status tracking
payoutStatus?: "pending" | "processing" | "completed" | "failed";
payoutProcessedAt?: string;
@@ -185,3 +192,12 @@ export interface ItemRequestResponse {
createdAt: string;
updatedAt: string;
}
export interface RefundPreview {
canCancel: boolean;
cancelledBy: "renter" | "owner";
refundAmount: number;
refundPercentage: number;
reason: string;
totalAmount: number;
}