Coverage for app/delivery_fee/fee_calculator.py: 92%

24 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-11-27 09:26 +0000

1from app.delivery_fee.fee_calculation_steps import DeliveryFeeCalculationStep 

2from app.delivery_fee.fee_transformers import DeliveryFeeTransformer 

3from app.delivery_fee.models import OrderInfo, DeliveryFee 

4from app.delivery_fee.utility_meta_classes import ThreadSafeSingletonMeta 

5import app.delivery_fee.settings as settings 

6 

7 

8class DeliveryFeeCalculator(metaclass=ThreadSafeSingletonMeta): 

9 """Calculates delivery fee. This is singleton class. This means only the first 

10 instance of this class will be used throughout the application.""" 

11 

12 def __init__(self, calculation_steps: list[DeliveryFeeCalculationStep] | None = None, 

13 transformers: list[DeliveryFeeTransformer] | None = None, 

14 calculation_configurations: None = None): 

15 self.calculation_steps = calculation_steps 

16 if calculation_steps is None: 

17 self.calculation_steps = settings.ALL_CALCULATION_STEPS 

18 

19 self.transformers = transformers 

20 if transformers is None: 

21 self.transformers = settings.ALL_FEE_TRANSFORMERS 

22 

23 # This is a plan for future, so that parameters can be changed easily. 

24 # And may be in the future we can have different configurations for 

25 # different users depending on country, city, etc. 

26 self.calculation_configurations = calculation_configurations 

27 if calculation_configurations is None: 

28 self.calculation_configurations = None 

29 

30 def calculate(self, order_info: OrderInfo) -> DeliveryFee: 

31 calculated_fee = DeliveryFee(delivery_fee=0) 

32 

33 # Follow all the steps to calculate the delivery fee. 

34 for step in self.calculation_steps: 

35 calculated_fee += step.calculate(order_info) 

36 

37 # Apply all the transformations to the calculated delivery fee. 

38 for transformer in self.transformers: 

39 calculated_fee = transformer.transform(order_info, calculated_fee) 

40 

41 return calculated_fee 

42 

43 

44# Delivery calculator singleton. 

45DELIVERY_FEE_CALCULATOR = DeliveryFeeCalculator( 

46 settings.ALL_CALCULATION_STEPS, settings.ALL_FEE_TRANSFORMERS)