pricing tiers
This commit is contained in:
62
backend/utils/rentalDurationCalculator.js
Normal file
62
backend/utils/rentalDurationCalculator.js
Normal file
@@ -0,0 +1,62 @@
|
||||
class RentalDurationCalculator {
|
||||
/**
|
||||
* Calculate rental cost based on duration and item pricing tiers
|
||||
* @param {Date|string} startDateTime - Rental start date/time
|
||||
* @param {Date|string} endDateTime - Rental end date/time
|
||||
* @param {Object} item - Item object with pricing information
|
||||
* @returns {number} Total rental cost
|
||||
*/
|
||||
static calculateRentalCost(startDateTime, endDateTime, item) {
|
||||
const rentalStartDateTime = new Date(startDateTime);
|
||||
const rentalEndDateTime = new Date(endDateTime);
|
||||
|
||||
// Calculate rental duration
|
||||
const diffMs = rentalEndDateTime.getTime() - rentalStartDateTime.getTime();
|
||||
const diffHours = Math.ceil(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
|
||||
const diffWeeks = Math.ceil(diffDays / 7);
|
||||
|
||||
// Calculate difference in calendar months
|
||||
let diffMonths = (rentalEndDateTime.getFullYear() - rentalStartDateTime.getFullYear()) * 12;
|
||||
diffMonths += rentalEndDateTime.getMonth() - rentalStartDateTime.getMonth();
|
||||
|
||||
// Add 1 if we're past the start day/time in the end month
|
||||
if (rentalEndDateTime.getDate() > rentalStartDateTime.getDate()) {
|
||||
diffMonths += 1;
|
||||
} else if (rentalEndDateTime.getDate() === rentalStartDateTime.getDate() &&
|
||||
rentalEndDateTime.getTime() > rentalStartDateTime.getTime()) {
|
||||
diffMonths += 1;
|
||||
}
|
||||
|
||||
diffMonths = Math.max(1, diffMonths);
|
||||
|
||||
// Calculate base amount based on duration (tiered pricing)
|
||||
let totalAmount;
|
||||
|
||||
if (item.pricePerHour && diffHours <= 24) {
|
||||
// Use hourly rate for rentals <= 24 hours
|
||||
totalAmount = diffHours * Number(item.pricePerHour);
|
||||
} else if (diffDays <= 7 && item.pricePerDay) {
|
||||
// Use daily rate for rentals <= 7 days
|
||||
totalAmount = diffDays * Number(item.pricePerDay);
|
||||
} else if (diffMonths <= 1 && item.pricePerWeek) {
|
||||
// Use weekly rate for rentals <= 1 calendar month
|
||||
totalAmount = diffWeeks * Number(item.pricePerWeek);
|
||||
} else if (diffMonths > 1 && item.pricePerMonth) {
|
||||
// Use monthly rate for rentals > 1 calendar month
|
||||
totalAmount = diffMonths * Number(item.pricePerMonth);
|
||||
} else if (item.pricePerWeek) {
|
||||
// Fallback to weekly rate if monthly not available
|
||||
totalAmount = diffWeeks * Number(item.pricePerWeek);
|
||||
} else if (item.pricePerDay) {
|
||||
// Fallback to daily rate
|
||||
totalAmount = diffDays * Number(item.pricePerDay);
|
||||
} else {
|
||||
totalAmount = 0;
|
||||
}
|
||||
|
||||
return totalAmount;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RentalDurationCalculator;
|
||||
Reference in New Issue
Block a user