refund and delayed charge
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user