52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
import { CartData, Discount } from "../../model";
|
|
import { findDiscountFactor } from "./findDiscountFactor";
|
|
|
|
|
|
export function applyPrivilegeDiscounts(
|
|
cartData: CartData,
|
|
discounts: Discount[],
|
|
) {
|
|
cartData.services.forEach(service => {
|
|
service.tariffs.forEach(tariff => {
|
|
tariff.privileges.forEach(privilege => {
|
|
const privilegeDiscount = findPrivilegeDiscount(privilege.privilegeId, privilege.price, discounts);
|
|
if (!privilegeDiscount) return;
|
|
|
|
const discountAmount = privilege.price * (1 - findDiscountFactor(privilegeDiscount));
|
|
privilege.price -= discountAmount;
|
|
cartData.allAppliedDiscounts.push(privilegeDiscount);
|
|
privilege.appliedPrivilegeDiscount = privilegeDiscount;
|
|
|
|
tariff.price -= discountAmount;
|
|
service.price -= discountAmount;
|
|
cartData.priceAfterDiscounts -= discountAmount;
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
export function findPrivilegeDiscount(
|
|
privilegeId: string,
|
|
privilegePrice: number,
|
|
discounts: Discount[],
|
|
): Discount | null {
|
|
const applicableDiscounts = discounts.filter(discount => {
|
|
const conditionMinPrice = parseFloat(discount.Condition.Term);
|
|
if (!isFinite(conditionMinPrice)) throw new Error(`Couldn't parse Discount.Condition.Term: ${discount.Condition.Term}`);
|
|
|
|
return (
|
|
discount.Layer === 1 &&
|
|
privilegeId === discount.Condition.Product &&
|
|
privilegePrice >= conditionMinPrice
|
|
);
|
|
});
|
|
|
|
if (!applicableDiscounts.length) return null;
|
|
|
|
const maxValueDiscount = applicableDiscounts.reduce((prev, current) =>
|
|
parseFloat(current.Condition.Term) > parseFloat(prev.Condition.Term) ? current : prev
|
|
);
|
|
|
|
return maxValueDiscount;
|
|
}
|