49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
import { CartData, Discount } from "../../model";
|
|
import { findDiscountFactor } from "./findDiscountFactor";
|
|
|
|
|
|
export function applyServiceDiscounts(
|
|
cartData: CartData,
|
|
discounts: Discount[],
|
|
) {
|
|
cartData.services.forEach(service => {
|
|
service.tariffs.map(tariff => {
|
|
tariff.privileges.forEach(privilege => {
|
|
const privilegeDiscount = findServiceDiscount(privilege.serviceKey, privilege.price, discounts);
|
|
if (!privilegeDiscount) return;
|
|
|
|
const discountAmount = privilege.price * (1 - findDiscountFactor(privilegeDiscount));
|
|
privilege.price -= discountAmount;
|
|
cartData.allAppliedDiscounts.push(privilegeDiscount);
|
|
service.appliedServiceDiscount = privilegeDiscount;
|
|
|
|
tariff.price -= discountAmount;
|
|
service.price -= discountAmount;
|
|
cartData.priceAfterDiscounts -= discountAmount;
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
export function findServiceDiscount(
|
|
serviceKey: string,
|
|
currentPrice: number,
|
|
discounts: Discount[],
|
|
): Discount | null {
|
|
const applicableDiscounts = discounts.filter(discount => {
|
|
return (
|
|
discount.Layer === 2 &&
|
|
discount.Condition.Group === serviceKey &&
|
|
currentPrice >= discount.Condition.PriceFrom
|
|
);
|
|
});
|
|
|
|
if (!applicableDiscounts.length) return null;
|
|
|
|
const maxValueDiscount = applicableDiscounts.reduce((prev, current) => {
|
|
return current.Condition.PriceFrom > prev.Condition.PriceFrom ? current : prev;
|
|
});
|
|
|
|
return maxValueDiscount;
|
|
}
|