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;
|
||||
|
||||
Reference in New Issue
Block a user