db4bc9bfe1
Co-authored-by: Cursor <cursoragent@cursor.com>
67 lines
1.8 KiB
JavaScript
67 lines
1.8 KiB
JavaScript
const promoService = require('./promo');
|
|
const loyaltyService = require('./loyalty');
|
|
|
|
async function buildCartPricing(items, session, userId) {
|
|
const subtotal = items.reduce((s, i) => s + i.line_total, 0);
|
|
|
|
let promo = null;
|
|
let promoDiscount = 0;
|
|
let promoError = null;
|
|
|
|
if (session.appliedPromoCode) {
|
|
promo = await promoService.findPromoByCode(session.appliedPromoCode);
|
|
const check = promoService.validatePromo(promo, subtotal);
|
|
if (!check.ok) {
|
|
promoError = check.error;
|
|
promo = null;
|
|
delete session.appliedPromoCode;
|
|
} else {
|
|
promoDiscount = promoService.calcPromoDiscountCents(promo, subtotal);
|
|
}
|
|
}
|
|
|
|
const afterPromo = Math.max(0, subtotal - promoDiscount);
|
|
|
|
let loyaltyBalance = 0;
|
|
let loyaltyDiscount = 0;
|
|
let loyaltyPointsUsed = 0;
|
|
|
|
if (userId) {
|
|
loyaltyBalance = await loyaltyService.getBalance(userId);
|
|
const requested = session.loyaltyPointsToUse ?? 0;
|
|
loyaltyDiscount = loyaltyService.calcLoyaltyDiscountCents(
|
|
requested,
|
|
loyaltyBalance,
|
|
afterPromo
|
|
);
|
|
loyaltyPointsUsed = loyaltyService.pointsForDiscount(loyaltyDiscount);
|
|
}
|
|
|
|
const total = Math.max(0, afterPromo - loyaltyDiscount);
|
|
const pointsEarned =
|
|
userId && total > 0 ? loyaltyService.calcEarnedPoints(total) : 0;
|
|
|
|
return {
|
|
subtotal,
|
|
promoDiscount,
|
|
loyaltyDiscount,
|
|
loyaltyPointsUsed,
|
|
loyaltyPointsUsedDisplay: loyaltyPointsUsed,
|
|
loyaltyBalance,
|
|
pointsEarned,
|
|
total,
|
|
promo: promo
|
|
? {
|
|
code: promo.code,
|
|
description: promo.description,
|
|
discount_type: promo.discount_type,
|
|
discount_value: promo.discount_value,
|
|
expires_at: promo.expires_at,
|
|
}
|
|
: null,
|
|
promoError,
|
|
};
|
|
}
|
|
|
|
module.exports = { buildCartPricing };
|