refund and delayed charge
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
const cron = require("node-cron");
|
||||
const PayoutService = require("../services/payoutService");
|
||||
|
||||
const paymentsSchedule = "31 * * * *"; // Run every hour at minute 0
|
||||
const paymentsSchedule = "0 * * * *"; // Run every hour at minute 0
|
||||
const retrySchedule = "0 7 * * *"; // Retry failed payouts once daily at 7 AM
|
||||
|
||||
class PayoutProcessor {
|
||||
|
||||
@@ -43,18 +43,10 @@ const Rental = sequelize.define("Rental", {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
baseRentalAmount: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
platformFee: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
processingFee: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
},
|
||||
payoutAmount: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
allowNull: false,
|
||||
@@ -83,6 +75,28 @@ const Rental = sequelize.define("Rental", {
|
||||
stripeTransferId: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
// Refund tracking fields
|
||||
refundAmount: {
|
||||
type: DataTypes.DECIMAL(10, 2),
|
||||
},
|
||||
refundProcessedAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
refundReason: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
stripeRefundId: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
cancelledBy: {
|
||||
type: DataTypes.ENUM("renter", "owner"),
|
||||
},
|
||||
cancelledAt: {
|
||||
type: DataTypes.DATE,
|
||||
},
|
||||
stripePaymentMethodId: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
deliveryMethod: {
|
||||
type: DataTypes.ENUM("pickup", "delivery"),
|
||||
defaultValue: "pickup",
|
||||
|
||||
@@ -102,6 +102,10 @@ const User = sequelize.define('User', {
|
||||
stripeConnectedAccountId: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true
|
||||
},
|
||||
stripeCustomerId: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true
|
||||
}
|
||||
}, {
|
||||
hooks: {
|
||||
|
||||
@@ -3,6 +3,7 @@ const { Op } = require("sequelize");
|
||||
const { Rental, Item, User } = require("../models"); // Import from models/index.js to get models with associations
|
||||
const { authenticateToken } = require("../middleware/auth");
|
||||
const FeeCalculator = require("../utils/feeCalculator");
|
||||
const RefundService = require("../services/refundService");
|
||||
const router = express.Router();
|
||||
|
||||
// Helper function to check and update review visibility
|
||||
@@ -103,7 +104,7 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
deliveryMethod,
|
||||
deliveryAddress,
|
||||
notes,
|
||||
paymentStatus,
|
||||
stripePaymentMethodId,
|
||||
} = req.body;
|
||||
|
||||
const item = await Item.findByPk(itemId);
|
||||
@@ -115,7 +116,7 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
return res.status(400).json({ error: "Item is not available" });
|
||||
}
|
||||
|
||||
let rentalStartDateTime, rentalEndDateTime, baseRentalAmount;
|
||||
let rentalStartDateTime, rentalEndDateTime, totalAmount;
|
||||
|
||||
// New UTC datetime format
|
||||
rentalStartDateTime = new Date(startDateTime);
|
||||
@@ -128,11 +129,11 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
|
||||
// Calculate base amount based on duration
|
||||
if (item.pricePerHour && diffHours <= 24) {
|
||||
baseRentalAmount = diffHours * Number(item.pricePerHour);
|
||||
totalAmount = diffHours * Number(item.pricePerHour);
|
||||
} else if (item.pricePerDay) {
|
||||
baseRentalAmount = diffDays * Number(item.pricePerDay);
|
||||
totalAmount = diffDays * Number(item.pricePerDay);
|
||||
} else {
|
||||
baseRentalAmount = 0;
|
||||
totalAmount = 0;
|
||||
}
|
||||
|
||||
// Check for overlapping rentals using datetime ranges
|
||||
@@ -178,7 +179,12 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
}
|
||||
|
||||
// Calculate fees using FeeCalculator
|
||||
const fees = FeeCalculator.calculateRentalFees(baseRentalAmount);
|
||||
const fees = FeeCalculator.calculateRentalFees(totalAmount);
|
||||
|
||||
// Validate that payment method was provided
|
||||
if (!stripePaymentMethodId) {
|
||||
return res.status(400).json({ error: "Payment method is required" });
|
||||
}
|
||||
|
||||
const rental = await Rental.create({
|
||||
itemId,
|
||||
@@ -187,14 +193,14 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
startDateTime: rentalStartDateTime,
|
||||
endDateTime: rentalEndDateTime,
|
||||
totalAmount: fees.totalChargedAmount,
|
||||
baseRentalAmount: fees.baseRentalAmount,
|
||||
platformFee: fees.platformFee,
|
||||
processingFee: fees.processingFee,
|
||||
payoutAmount: fees.payoutAmount,
|
||||
paymentStatus: paymentStatus || "pending",
|
||||
paymentStatus: "pending",
|
||||
status: "pending",
|
||||
deliveryMethod,
|
||||
deliveryAddress,
|
||||
notes,
|
||||
stripePaymentMethodId,
|
||||
});
|
||||
|
||||
const rentalWithDetails = await Rental.findByPk(rental.id, {
|
||||
@@ -222,7 +228,21 @@ router.post("/", authenticateToken, async (req, res) => {
|
||||
router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { status } = req.body;
|
||||
const rental = await Rental.findByPk(req.params.id);
|
||||
const rental = await Rental.findByPk(req.params.id, {
|
||||
include: [
|
||||
{ model: Item, as: "item" },
|
||||
{
|
||||
model: User,
|
||||
as: "owner",
|
||||
attributes: ["id", "username", "firstName", "lastName"],
|
||||
},
|
||||
{
|
||||
model: User,
|
||||
as: "renter",
|
||||
attributes: ["id", "username", "firstName", "lastName", "stripeCustomerId"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!rental) {
|
||||
return res.status(404).json({ error: "Rental not found" });
|
||||
@@ -232,6 +252,69 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
return res.status(403).json({ error: "Unauthorized" });
|
||||
}
|
||||
|
||||
// If owner is approving a pending rental, charge the stored payment method
|
||||
if (status === "confirmed" && rental.status === "pending" && rental.ownerId === req.user.id) {
|
||||
if (!rental.stripePaymentMethodId) {
|
||||
return res.status(400).json({ error: "No payment method found for this rental" });
|
||||
}
|
||||
|
||||
try {
|
||||
// Import StripeService to process the payment
|
||||
const StripeService = require("../services/stripeService");
|
||||
|
||||
// Check if renter has a stripe customer ID
|
||||
if (!rental.renter.stripeCustomerId) {
|
||||
return res.status(400).json({ error: "Renter does not have a Stripe customer account" });
|
||||
}
|
||||
|
||||
// Create payment intent and charge the stored payment method
|
||||
const paymentResult = await StripeService.chargePaymentMethod(
|
||||
rental.stripePaymentMethodId,
|
||||
rental.totalAmount,
|
||||
rental.renter.stripeCustomerId,
|
||||
{
|
||||
rentalId: rental.id,
|
||||
itemName: rental.item.name,
|
||||
renterId: rental.renterId,
|
||||
ownerId: rental.ownerId,
|
||||
}
|
||||
);
|
||||
|
||||
// Update rental with payment completion
|
||||
await rental.update({
|
||||
status: "confirmed",
|
||||
paymentStatus: "paid",
|
||||
stripePaymentIntentId: paymentResult.paymentIntentId,
|
||||
});
|
||||
|
||||
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);
|
||||
return;
|
||||
} catch (paymentError) {
|
||||
console.error("Payment failed during approval:", paymentError);
|
||||
// Keep rental as pending, but inform of payment failure
|
||||
return res.status(400).json({
|
||||
error: "Payment failed during approval",
|
||||
details: paymentError.message
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await rental.update({ status });
|
||||
|
||||
const updatedRental = await Rental.findByPk(rental.id, {
|
||||
@@ -393,13 +476,13 @@ router.post("/:id/mark-completed", authenticateToken, async (req, res) => {
|
||||
// Calculate fees for rental pricing display
|
||||
router.post("/calculate-fees", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { baseAmount } = req.body;
|
||||
const { totalAmount } = req.body;
|
||||
|
||||
if (!baseAmount || baseAmount <= 0) {
|
||||
if (!totalAmount || totalAmount <= 0) {
|
||||
return res.status(400).json({ error: "Valid base amount is required" });
|
||||
}
|
||||
|
||||
const fees = FeeCalculator.calculateRentalFees(baseAmount);
|
||||
const fees = FeeCalculator.calculateRentalFees(totalAmount);
|
||||
const displayFees = FeeCalculator.formatFeesForDisplay(fees);
|
||||
|
||||
res.json({
|
||||
@@ -422,7 +505,7 @@ router.get("/earnings/status", authenticateToken, async (req, res) => {
|
||||
},
|
||||
attributes: [
|
||||
"id",
|
||||
"baseRentalAmount",
|
||||
"totalAmount",
|
||||
"platformFee",
|
||||
"payoutAmount",
|
||||
"payoutStatus",
|
||||
@@ -440,4 +523,56 @@ router.get("/earnings/status", authenticateToken, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Get refund preview (what would happen if cancelled now)
|
||||
router.get("/:id/refund-preview", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const preview = await RefundService.getRefundPreview(
|
||||
req.params.id,
|
||||
req.user.id
|
||||
);
|
||||
res.json(preview);
|
||||
} catch (error) {
|
||||
console.error("Error getting refund preview:", error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Cancel rental with refund processing
|
||||
router.post("/:id/cancel", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { reason } = req.body;
|
||||
|
||||
const result = await RefundService.processCancellation(
|
||||
req.params.id,
|
||||
req.user.id,
|
||||
reason
|
||||
);
|
||||
|
||||
// Return the updated rental with refund information
|
||||
const updatedRental = await Rental.findByPk(result.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({
|
||||
rental: updatedRental,
|
||||
refund: result.refund,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error cancelling rental:", error);
|
||||
res.status(400).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -4,66 +4,6 @@ const { User, Item } = require("../models");
|
||||
const StripeService = require("../services/stripeService");
|
||||
const router = express.Router();
|
||||
|
||||
router.post("/create-checkout-session", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { itemName, total, return_url, rentalData } = req.body;
|
||||
|
||||
if (!itemName) {
|
||||
return res.status(400).json({ error: "No item name found" });
|
||||
}
|
||||
if (total == null || total === undefined) {
|
||||
return res.status(400).json({ error: "No total found" });
|
||||
}
|
||||
if (!return_url) {
|
||||
return res.status(400).json({ error: "No return_url found" });
|
||||
}
|
||||
|
||||
// Validate rental data and user authorization
|
||||
if (rentalData && rentalData.itemId) {
|
||||
const item = await Item.findByPk(rentalData.itemId);
|
||||
|
||||
if (!item) {
|
||||
return res.status(404).json({ error: "Item not found" });
|
||||
}
|
||||
|
||||
if (!item.availability) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Item is not available for rent" });
|
||||
}
|
||||
|
||||
// Check if user is trying to rent their own item
|
||||
if (item.ownerId === req.user.id) {
|
||||
return res.status(400).json({ error: "You cannot rent your own item" });
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare metadata - Stripe metadata keys must be strings
|
||||
const metadata = rentalData
|
||||
? {
|
||||
itemId: rentalData.itemId,
|
||||
renterId: req.user.id.toString(), // Add authenticated user ID
|
||||
startDateTime: rentalData.startDateTime,
|
||||
endDateTime: rentalData.endDateTime,
|
||||
totalAmount: rentalData.totalAmount.toString(),
|
||||
deliveryMethod: rentalData.deliveryMethod,
|
||||
}
|
||||
: { renterId: req.user.id.toString() };
|
||||
|
||||
const session = await StripeService.createCheckoutSession({
|
||||
item_name: itemName,
|
||||
total: total,
|
||||
return_url: return_url,
|
||||
metadata: metadata,
|
||||
});
|
||||
|
||||
res.json({ clientSecret: session.client_secret });
|
||||
} catch (error) {
|
||||
console.error("Error creating checkout session:", error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get checkout session status
|
||||
router.get("/checkout-session/:sessionId", async (req, res) => {
|
||||
try {
|
||||
@@ -75,6 +15,7 @@ router.get("/checkout-session/:sessionId", async (req, res) => {
|
||||
status: session.status,
|
||||
payment_status: session.payment_status,
|
||||
customer_email: session.customer_details?.email,
|
||||
setup_intent: session.setup_intent,
|
||||
metadata: session.metadata,
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -179,4 +120,54 @@ router.get("/account-status", authenticateToken, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Create embedded setup checkout session for collecting payment method
|
||||
router.post("/create-setup-checkout-session", authenticateToken, async (req, res) => {
|
||||
try {
|
||||
const { rentalData } = req.body;
|
||||
|
||||
const user = await User.findByPk(req.user.id);
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).json({ error: "User not found" });
|
||||
}
|
||||
|
||||
// Create or get Stripe customer
|
||||
let stripeCustomerId = user.stripeCustomerId;
|
||||
|
||||
if (!stripeCustomerId) {
|
||||
// Create new Stripe customer
|
||||
const customer = await StripeService.createCustomer({
|
||||
email: user.email,
|
||||
name: `${user.firstName} ${user.lastName}`,
|
||||
metadata: {
|
||||
userId: user.id.toString()
|
||||
}
|
||||
});
|
||||
|
||||
stripeCustomerId = customer.id;
|
||||
|
||||
// Save customer ID to user record
|
||||
await user.update({ stripeCustomerId });
|
||||
}
|
||||
|
||||
// Add rental data to metadata if provided
|
||||
const metadata = rentalData ? {
|
||||
rentalData: JSON.stringify(rentalData)
|
||||
} : {};
|
||||
|
||||
const session = await StripeService.createSetupCheckoutSession({
|
||||
customerId: stripeCustomerId,
|
||||
metadata
|
||||
});
|
||||
|
||||
res.json({
|
||||
clientSecret: session.client_secret,
|
||||
sessionId: session.id
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error creating setup checkout session:", error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -57,7 +57,7 @@ class PayoutService {
|
||||
metadata: {
|
||||
rentalId: rental.id,
|
||||
ownerId: rental.ownerId,
|
||||
baseAmount: rental.baseRentalAmount.toString(),
|
||||
totalAmount: rental.totalAmount.toString(),
|
||||
platformFee: rental.platformFee.toString(),
|
||||
startDateTime: rental.startDateTime.toISOString(),
|
||||
endDateTime: rental.endDateTime.toISOString(),
|
||||
|
||||
229
backend/services/refundService.js
Normal file
229
backend/services/refundService.js
Normal file
@@ -0,0 +1,229 @@
|
||||
const { Rental } = require("../models");
|
||||
const StripeService = require("./stripeService");
|
||||
|
||||
class RefundService {
|
||||
/**
|
||||
* Calculate refund amount based on policy and who cancelled
|
||||
* @param {Object} rental - Rental instance
|
||||
* @param {string} cancelledBy - 'renter' or 'owner'
|
||||
* @returns {Object} - { refundAmount, refundPercentage, reason }
|
||||
*/
|
||||
static calculateRefundAmount(rental, cancelledBy) {
|
||||
const totalAmount = rental.totalAmount;
|
||||
let refundPercentage = 0;
|
||||
let reason = "";
|
||||
|
||||
if (cancelledBy === "owner") {
|
||||
// Owner cancellation = full refund
|
||||
refundPercentage = 1.0;
|
||||
reason = "Full refund - cancelled by owner";
|
||||
} else if (cancelledBy === "renter") {
|
||||
// Calculate based on time until rental start
|
||||
const now = new Date();
|
||||
const startDateTime = new Date(rental.startDateTime);
|
||||
const hoursUntilStart = (startDateTime - now) / (1000 * 60 * 60);
|
||||
|
||||
if (hoursUntilStart < 24) {
|
||||
refundPercentage = 0.0;
|
||||
reason = "No refund - cancelled within 24 hours of start time";
|
||||
} else if (hoursUntilStart < 48) {
|
||||
refundPercentage = 0.5;
|
||||
reason = "50% refund - cancelled between 24-48 hours of start time";
|
||||
} else {
|
||||
refundPercentage = 1.0;
|
||||
reason = "Full refund - cancelled more than 48 hours before start time";
|
||||
}
|
||||
}
|
||||
|
||||
const refundAmount = parseFloat((totalAmount * refundPercentage).toFixed(2));
|
||||
|
||||
return {
|
||||
refundAmount,
|
||||
refundPercentage,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate if a rental can be cancelled
|
||||
* @param {Object} rental - Rental instance
|
||||
* @param {string} userId - User ID attempting to cancel
|
||||
* @returns {Object} - { canCancel, reason, cancelledBy }
|
||||
*/
|
||||
static validateCancellationEligibility(rental, userId) {
|
||||
// Check if rental is already cancelled
|
||||
if (rental.status === "cancelled") {
|
||||
return {
|
||||
canCancel: false,
|
||||
reason: "Rental is already cancelled",
|
||||
cancelledBy: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if rental is completed
|
||||
if (rental.status === "completed") {
|
||||
return {
|
||||
canCancel: false,
|
||||
reason: "Cannot cancel completed rental",
|
||||
cancelledBy: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if rental is active
|
||||
if (rental.status === "active") {
|
||||
return {
|
||||
canCancel: false,
|
||||
reason: "Cannot cancel active rental",
|
||||
cancelledBy: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if user has permission to cancel
|
||||
let cancelledBy = null;
|
||||
if (rental.renterId === userId) {
|
||||
cancelledBy = "renter";
|
||||
} else if (rental.ownerId === userId) {
|
||||
cancelledBy = "owner";
|
||||
} else {
|
||||
return {
|
||||
canCancel: false,
|
||||
reason: "You are not authorized to cancel this rental",
|
||||
cancelledBy: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Check payment status
|
||||
if (rental.paymentStatus !== "paid") {
|
||||
return {
|
||||
canCancel: false,
|
||||
reason: "Cannot cancel rental that hasn't been paid",
|
||||
cancelledBy: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
canCancel: true,
|
||||
reason: "Cancellation allowed",
|
||||
cancelledBy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the full cancellation and refund
|
||||
* @param {string} rentalId - Rental ID
|
||||
* @param {string} userId - User ID cancelling
|
||||
* @param {string} cancellationReason - Optional reason provided by user
|
||||
* @returns {Object} - Updated rental with refund information
|
||||
*/
|
||||
static async processCancellation(rentalId, userId, cancellationReason = null) {
|
||||
const rental = await Rental.findByPk(rentalId);
|
||||
|
||||
if (!rental) {
|
||||
throw new Error("Rental not found");
|
||||
}
|
||||
|
||||
// Validate cancellation eligibility
|
||||
const eligibility = this.validateCancellationEligibility(rental, userId);
|
||||
if (!eligibility.canCancel) {
|
||||
throw new Error(eligibility.reason);
|
||||
}
|
||||
|
||||
// Calculate refund amount
|
||||
const refundCalculation = this.calculateRefundAmount(
|
||||
rental,
|
||||
eligibility.cancelledBy
|
||||
);
|
||||
|
||||
let stripeRefundId = null;
|
||||
let refundProcessedAt = null;
|
||||
|
||||
// Process refund with Stripe if amount > 0 and we have payment intent ID
|
||||
if (
|
||||
refundCalculation.refundAmount > 0 &&
|
||||
rental.stripePaymentIntentId
|
||||
) {
|
||||
try {
|
||||
const refund = await StripeService.createRefund({
|
||||
paymentIntentId: rental.stripePaymentIntentId,
|
||||
amount: refundCalculation.refundAmount,
|
||||
metadata: {
|
||||
rentalId: rental.id,
|
||||
cancelledBy: eligibility.cancelledBy,
|
||||
refundReason: refundCalculation.reason,
|
||||
},
|
||||
});
|
||||
|
||||
stripeRefundId = refund.id;
|
||||
refundProcessedAt = new Date();
|
||||
} catch (error) {
|
||||
console.error("Error processing Stripe refund:", error);
|
||||
throw new Error(`Failed to process refund: ${error.message}`);
|
||||
}
|
||||
} else if (refundCalculation.refundAmount > 0) {
|
||||
// Log warning if we should refund but don't have payment intent
|
||||
console.warn(
|
||||
`Refund amount calculated but no payment intent ID for rental ${rentalId}`
|
||||
);
|
||||
}
|
||||
|
||||
// Update rental with cancellation and refund info
|
||||
const updatedRental = await rental.update({
|
||||
status: "cancelled",
|
||||
cancelledBy: eligibility.cancelledBy,
|
||||
cancelledAt: new Date(),
|
||||
refundAmount: refundCalculation.refundAmount,
|
||||
refundProcessedAt,
|
||||
refundReason:
|
||||
cancellationReason || refundCalculation.reason,
|
||||
stripeRefundId,
|
||||
// Reset payout status since rental is cancelled
|
||||
payoutStatus: "pending",
|
||||
});
|
||||
|
||||
return {
|
||||
rental: updatedRental,
|
||||
refund: {
|
||||
amount: refundCalculation.refundAmount,
|
||||
percentage: refundCalculation.refundPercentage,
|
||||
reason: refundCalculation.reason,
|
||||
processed: !!refundProcessedAt,
|
||||
stripeRefundId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get refund preview without processing
|
||||
* @param {string} rentalId - Rental ID
|
||||
* @param {string} userId - User ID requesting preview
|
||||
* @returns {Object} - Preview of refund calculation
|
||||
*/
|
||||
static async getRefundPreview(rentalId, userId) {
|
||||
const rental = await Rental.findByPk(rentalId);
|
||||
|
||||
if (!rental) {
|
||||
throw new Error("Rental not found");
|
||||
}
|
||||
|
||||
const eligibility = this.validateCancellationEligibility(rental, userId);
|
||||
if (!eligibility.canCancel) {
|
||||
throw new Error(eligibility.reason);
|
||||
}
|
||||
|
||||
const refundCalculation = this.calculateRefundAmount(
|
||||
rental,
|
||||
eligibility.cancelledBy
|
||||
);
|
||||
|
||||
return {
|
||||
canCancel: true,
|
||||
cancelledBy: eligibility.cancelledBy,
|
||||
refundAmount: refundCalculation.refundAmount,
|
||||
refundPercentage: refundCalculation.refundPercentage,
|
||||
reason: refundCalculation.reason,
|
||||
totalAmount: rental.totalAmount,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RefundService;
|
||||
@@ -1,44 +1,12 @@
|
||||
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
|
||||
|
||||
class StripeService {
|
||||
static async createCheckoutSession({
|
||||
item_name,
|
||||
total,
|
||||
return_url,
|
||||
metadata = {},
|
||||
}) {
|
||||
try {
|
||||
const sessionConfig = {
|
||||
line_items: [
|
||||
{
|
||||
price_data: {
|
||||
currency: "usd",
|
||||
product_data: {
|
||||
name: item_name,
|
||||
},
|
||||
unit_amount: total * 100,
|
||||
},
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
mode: "payment",
|
||||
ui_mode: "embedded",
|
||||
return_url: return_url,
|
||||
metadata: metadata,
|
||||
};
|
||||
|
||||
const session = await stripe.checkout.sessions.create(sessionConfig);
|
||||
|
||||
return session;
|
||||
} catch (error) {
|
||||
console.error("Error creating checkout session:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async getCheckoutSession(sessionId) {
|
||||
try {
|
||||
return await stripe.checkout.sessions.retrieve(sessionId);
|
||||
return await stripe.checkout.sessions.retrieve(sessionId, {
|
||||
expand: ['setup_intent', 'setup_intent.payment_method']
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error retrieving checkout session:", error);
|
||||
throw error;
|
||||
@@ -115,6 +83,97 @@ class StripeService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async createRefund({
|
||||
paymentIntentId,
|
||||
amount,
|
||||
metadata = {},
|
||||
reason = "requested_by_customer",
|
||||
}) {
|
||||
try {
|
||||
const refund = await stripe.refunds.create({
|
||||
payment_intent: paymentIntentId,
|
||||
amount: Math.round(amount * 100), // Convert to cents
|
||||
metadata,
|
||||
reason,
|
||||
});
|
||||
|
||||
return refund;
|
||||
} catch (error) {
|
||||
console.error("Error creating refund:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async getRefund(refundId) {
|
||||
try {
|
||||
return await stripe.refunds.retrieve(refundId);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving refund:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async chargePaymentMethod(paymentMethodId, amount, customerId, metadata = {}) {
|
||||
try {
|
||||
// Create a payment intent with the stored payment method
|
||||
const paymentIntent = await stripe.paymentIntents.create({
|
||||
amount: Math.round(amount * 100), // Convert to cents
|
||||
currency: "usd",
|
||||
payment_method: paymentMethodId,
|
||||
customer: customerId, // Include customer ID
|
||||
confirm: true, // Automatically confirm the payment
|
||||
return_url: `${process.env.FRONTEND_URL || 'http://localhost:3000'}/payment-complete`,
|
||||
metadata,
|
||||
});
|
||||
|
||||
return {
|
||||
paymentIntentId: paymentIntent.id,
|
||||
status: paymentIntent.status,
|
||||
clientSecret: paymentIntent.client_secret,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error charging payment method:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async createCustomer({ email, name, metadata = {} }) {
|
||||
try {
|
||||
const customer = await stripe.customers.create({
|
||||
email,
|
||||
name,
|
||||
metadata,
|
||||
});
|
||||
|
||||
return customer;
|
||||
} catch (error) {
|
||||
console.error("Error creating customer:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static async createSetupCheckoutSession({ customerId, metadata = {} }) {
|
||||
try {
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
customer: customerId,
|
||||
payment_method_types: ['card', 'us_bank_account', 'link'],
|
||||
mode: 'setup',
|
||||
ui_mode: 'embedded',
|
||||
redirect_on_completion: 'never',
|
||||
metadata: {
|
||||
type: 'payment_method_setup',
|
||||
...metadata
|
||||
}
|
||||
});
|
||||
|
||||
return session;
|
||||
} catch (error) {
|
||||
console.error("Error creating setup checkout session:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StripeService;
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
class FeeCalculator {
|
||||
static calculateRentalFees(baseAmount) {
|
||||
static calculateRentalFees(totalAmount) {
|
||||
const platformFeeRate = 0.2;
|
||||
const stripeRate = 0.029;
|
||||
const stripeFixedFee = 0.3;
|
||||
|
||||
const platformFee = baseAmount * platformFeeRate;
|
||||
const processingFee = baseAmount * stripeRate + stripeFixedFee;
|
||||
const platformFee = totalAmount * platformFeeRate;
|
||||
|
||||
return {
|
||||
baseRentalAmount: parseFloat(baseAmount.toFixed(2)),
|
||||
totalAmount: parseFloat(totalAmount.toFixed(2)),
|
||||
platformFee: parseFloat(platformFee.toFixed(2)),
|
||||
processingFee: parseFloat(processingFee.toFixed(2)),
|
||||
totalChargedAmount: parseFloat((baseAmount + processingFee).toFixed(2)),
|
||||
payoutAmount: parseFloat((baseAmount - platformFee).toFixed(2)),
|
||||
totalChargedAmount: parseFloat(totalAmount.toFixed(2)),
|
||||
payoutAmount: parseFloat((totalAmount - platformFee).toFixed(2)),
|
||||
};
|
||||
}
|
||||
|
||||
static formatFeesForDisplay(fees) {
|
||||
return {
|
||||
baseRental: `$${fees.baseRentalAmount.toFixed(2)}`,
|
||||
totalAmount: `$${fees.totalAmount.toFixed(2)}`,
|
||||
platformFee: `$${fees.platformFee.toFixed(2)} (20%)`,
|
||||
processingFee: `$${fees.processingFee.toFixed(2)} (2.9% + $0.30)`,
|
||||
totalCharge: `$${fees.totalChargedAmount.toFixed(2)}`,
|
||||
ownerPayout: `$${fees.payoutAmount.toFixed(2)}`,
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
128
frontend/src/components/EmbeddedStripeCheckout.tsx
Normal file
128
frontend/src/components/EmbeddedStripeCheckout.tsx
Normal 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;
|
||||
252
frontend/src/components/RentalCancellationModal.tsx
Normal file
252
frontend/src/components/RentalCancellationModal.tsx
Normal 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;
|
||||
@@ -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;
|
||||
@@ -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,12 +111,38 @@ 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);
|
||||
|
||||
// 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("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRejectRental = async (rentalId: string) => {
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
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);
|
||||
} catch (err: any) {
|
||||
alert("Failed to cancel rental");
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
}
|
||||
};
|
||||
|
||||
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 && (
|
||||
{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
|
||||
{rentalToCancel && (
|
||||
<RentalCancellationModal
|
||||
show={showCancelModal}
|
||||
onClose={() => {
|
||||
onHide={() => {
|
||||
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}
|
||||
rental={rentalToCancel}
|
||||
onCancellationComplete={handleCancellationComplete}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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,43 +195,70 @@ const RentItem: React.FC = () => {
|
||||
|
||||
<div className="row">
|
||||
<div className="col-md-8">
|
||||
{completed ? (
|
||||
<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
|
||||
}
|
||||
/>
|
||||
|
||||
<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
|
||||
type="button"
|
||||
className="btn btn-secondary mt-2"
|
||||
onClick={() => navigate(`/items/${id}`)}
|
||||
className="btn btn-primary me-2"
|
||||
onClick={() => navigate("/my-rentals")}
|
||||
>
|
||||
Cancel
|
||||
View My Rentals
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-outline-secondary"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
Continue Browsing
|
||||
</button>
|
||||
</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">
|
||||
<div className="card">
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user