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

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