-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefactored_calculator.py
More file actions
140 lines (111 loc) · 3.82 KB
/
refactored_calculator.py
File metadata and controls
140 lines (111 loc) · 3.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""
Refactored version based on these guidelines:
1. Create DiscountStrategy class hierarchy
2. Extract discount calculation methods
3. Simplify process_order with early returns
4. Add type hints and docstrings
"""
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
class DiscountStrategy(ABC):
"""Abstract base class for discount strategies."""
@abstractmethod
def calculate_discount(
self,
price: float,
customer_type: Optional[str],
is_holiday: bool,
discount_code: Optional[str] = None,
) -> float:
"""Return the final discounted price for a single item."""
class ElectronicsDiscountStrategy(DiscountStrategy):
"""Implement electronics discount logic."""
_HIGH_PRICE_RATES = {
(True, True): 0.7,
(True, False): 0.8,
(False, True): 0.85,
(False, False): 0.9,
}
_LOW_PRICE_RATES = {True: 0.9, False: 0.95}
def calculate_discount(
self,
price: float,
customer_type: Optional[str],
is_holiday: bool,
discount_code: Optional[str] = None,
) -> float:
is_premium = customer_type == "premium"
rate = self._select_rate(price, is_premium, is_holiday)
return price * rate
def _select_rate(self, price: float, is_premium: bool, is_holiday: bool) -> float:
if price > 1000:
return self._HIGH_PRICE_RATES[(is_premium, is_holiday)]
return self._LOW_PRICE_RATES[is_premium]
class ClothingDiscountStrategy(DiscountStrategy):
"""Implement clothing discount logic."""
_SUMMER_RATES = {True: 0.6, False: 0.7}
_STANDARD_RATES = {True: 0.85, False: 0.9}
def calculate_discount(
self,
price: float,
customer_type: Optional[str],
is_holiday: bool,
discount_code: Optional[str] = None,
) -> float:
is_premium = customer_type == "premium"
rates = self._SUMMER_RATES if discount_code == "SUMMER" else self._STANDARD_RATES
return price * rates[is_premium]
class DefaultDiscountStrategy(DiscountStrategy):
"""Implement default discount logic."""
def calculate_discount(
self,
price: float,
customer_type: Optional[str],
is_holiday: bool,
discount_code: Optional[str] = None,
) -> float:
rate = 0.9 if discount_code else 1.0
return price * rate
_STRATEGIES = {
"electronics": ElectronicsDiscountStrategy(),
"clothing": ClothingDiscountStrategy(),
}
def get_discount_strategy(category: str) -> DiscountStrategy:
"""Factory function to return appropriate strategy."""
return _STRATEGIES.get(category, DefaultDiscountStrategy())
def calculate_total(
items: List[Dict[str, Any]],
discount_code: Optional[str],
customer_type: str,
is_holiday: bool,
) -> float:
"""Calculate the discounted total for all items in the order."""
total = 0.0
for item in items:
category = item.get("category", "")
price = float(item.get("price", 0))
strategy = get_discount_strategy(category)
total += strategy.calculate_discount(
price=price,
customer_type=customer_type,
is_holiday=is_holiday,
discount_code=discount_code,
)
if discount_code == "VIP20":
total *= 0.8
return total
def process_order(order_data: Optional[Dict[str, Any]]) -> Optional[float]:
"""Validate order data and calculate the final total."""
try:
items = order_data["items"]
customer_type = order_data["customer"].get("type")
except (TypeError, KeyError, AttributeError):
return None
if not items:
return 0
return calculate_total(
items,
order_data.get("discount_code"),
customer_type,
order_data.get("is_holiday", False),
)