Last active
April 12, 2025 11:55
-
-
Save teodoryantcheff/3c64916570bb16a3ecceaf15850d0e07 to your computer and use it in GitHub Desktop.
Brain dump. Code courtesy of Grok
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from dataclasses import dataclass | |
from typing import Dict, List, Optional, Union | |
import os | |
from abc import ABC, abstractmethod | |
# import requests | |
from unittest.mock import Mock | |
# External service interface for base price | |
class BasePriceService: | |
def __init__(self, endpoint: str = "https://api.example.com/base_price"): | |
self.endpoint = endpoint | |
def get_base_price(self) -> int: | |
"""Fetch base price in cents from external service.""" | |
# try: | |
# response = requests.get(self.endpoint, timeout=5) | |
# response.raise_for_status() | |
# return int(response.json().get("base_price_cents", 1000)) | |
# except (requests.RequestException, ValueError) as e: | |
# print(f"Failed to fetch base price: {e}. Using default 1000 cents.") | |
# return 1000 | |
return 1000 | |
# Configuration file handling | |
class PricingConfig: | |
def __init__(self, config_file: str = "pricing_config.json"): | |
self.config_file = config_file | |
self.config = self._load_config() | |
def _load_config(self) -> Dict: | |
default_config = { | |
"modifier_groups": { | |
"service_options": { | |
"display_name": "Service Options", | |
"description": "Choose additional services for your order", | |
"is_selectable": True, | |
"modifiers": { | |
"processing": { | |
"type": "ServiceFee", | |
"amount_cents": 50, | |
"display_name": "Processing Fee", | |
"description": "Standard transaction processing fee", | |
"is_selectable": True | |
}, | |
"priority": { | |
"type": "ServiceFee", | |
"amount_cents": 200, | |
"display_name": "Priority Handling", | |
"description": "Expedited order processing", | |
"is_selectable": True | |
} | |
} | |
}, | |
"promotions": { | |
"display_name": "Promotions", | |
"description": "Available discounts for your order", | |
"is_selectable": True, | |
"modifiers": { | |
"bulk": { | |
"type": "Discount", | |
"amount_cents": 0, | |
"conditions": [ | |
{"type": "quantity", "threshold": 10} | |
], | |
"rate_percent": 10, | |
"display_name": "Bulk Discount", | |
"description": "Discount for orders of 10 or more items", | |
"is_selectable": True | |
}, | |
"loyalty": { | |
"type": "Discount", | |
"amount_cents": 0, | |
"conditions": [ | |
{"type": "customer_years", "threshold": 2} | |
], | |
"rate_percent": 5, | |
"display_name": "Loyalty Discount", | |
"description": "Discount for customers with 2+ years", | |
"is_selectable": False | |
}, | |
"price_tier": { | |
"type": "PriceBin", | |
"amount_cents": 0, | |
"bins": [ | |
{"min_total_cents": 10000, "rate_percent": 5}, | |
{"min_total_cents": 20000, "rate_percent": 10} | |
], | |
"display_name": "Price Tier Discount", | |
"description": "Discount based on order total", | |
"is_selectable": False | |
} | |
} | |
} | |
} | |
} | |
if os.path.exists(self.config_file): | |
try: | |
with open(self.config_file, 'r') as f: | |
return json.load(f) | |
except json.JSONDecodeError: | |
print("Invalid config file, using default configuration") | |
return default_config | |
return default_config | |
def save_config(self): | |
with open(self.config_file, 'w') as f: | |
json.dump(self.config, f, indent=2) | |
def get_selectable_modifiers(self) -> List[Dict]: | |
"""Return list of selectable modifiers for front-end, grouped by ModifierGroup.""" | |
groups = [] | |
for group_name, group_data in self.config.get("modifier_groups", {}).items(): | |
if group_data.get("is_selectable", False): | |
modifiers = [] | |
for mod_name, mod_data in group_data.get("modifiers", {}).items(): | |
if mod_data.get("is_selectable", False): | |
modifier = { | |
"name": mod_name, | |
"type": mod_data["type"], | |
"display_name": mod_data.get("display_name", mod_name), | |
"description": mod_data.get("description", ""), | |
"amount_cents": mod_data.get("amount_cents"), | |
"rate_percent": mod_data.get("rate_percent"), | |
"conditions": mod_data.get("conditions", []), | |
"bins": mod_data.get("bins", []) | |
} | |
modifiers.append(modifier) | |
if modifiers: # Only include groups with selectable modifiers | |
groups.append({ | |
"name": group_name, | |
"display_name": group_data.get("display_name", group_name), | |
"description": group_data.get("description", ""), | |
"modifiers": modifiers | |
}) | |
return groups | |
# Condition evaluation for modifiers | |
class Condition: | |
@staticmethod | |
def evaluate(condition: Dict, context: Dict) -> bool: | |
"""Evaluate if a condition is met based on context.""" | |
condition_type = condition.get("type") | |
threshold = condition.get("threshold", 0) | |
if condition_type == "quantity": | |
return context.get("quantity", 0) >= threshold | |
elif condition_type == "customer_years": | |
return context.get("customer_years", 0) >= threshold | |
return False | |
# Price Modifier base class | |
class PriceModifier(ABC): | |
def __init__(self, amount_cents: int, display_name: str = "", description: str = "", is_selectable: bool = True, | |
conditions: List[Dict] = None): | |
self.amount_cents = amount_cents | |
self.display_name = display_name | |
self.description = description | |
self.is_selectable = is_selectable | |
self.conditions = conditions or [] | |
@abstractmethod | |
def apply(self, base_total: int, context: Dict) -> int: | |
"""Apply the modifier to the base total, returning amount in cents.""" | |
pass | |
@abstractmethod | |
def to_dict(self) -> Dict: | |
"""Serialize to dictionary.""" | |
pass | |
@classmethod | |
@abstractmethod | |
def from_dict(cls, data: Dict) -> 'PriceModifier': | |
"""Deserialize from dictionary.""" | |
pass | |
def is_applicable(self, context: Dict) -> bool: | |
"""Check if all conditions are met.""" | |
if not self.conditions: | |
return True | |
return all(Condition.evaluate(cond, context) for cond in self.conditions) | |
# Service Fee implementation | |
@dataclass | |
class ServiceFee(PriceModifier): | |
amount_cents: int | |
display_name: str = "Service Fee" | |
description: str = "" | |
is_selectable: bool = True | |
conditions: List[Dict] = None | |
def apply(self, base_total: int, context: Dict) -> int: | |
if self.is_applicable(context): | |
return self.amount_cents | |
return 0 | |
def to_dict(self) -> Dict: | |
return { | |
"type": "ServiceFee", | |
"amount_cents": self.amount_cents, | |
"display_name": self.display_name, | |
"description": self.description, | |
"is_selectable": self.is_selectable, | |
"conditions": self.conditions or [] | |
} | |
@classmethod | |
def from_dict(cls, data: Dict) -> 'ServiceFee': | |
return cls( | |
amount_cents=data["amount_cents"], | |
display_name=data.get("display_name", "Service Fee"), | |
description=data.get("description", ""), | |
is_selectable=data.get("is_selectable", True), | |
conditions=data.get("conditions", []) | |
) | |
# Discount implementation | |
@dataclass | |
class Discount(PriceModifier): | |
rate_percent: int | |
amount_cents: int = 0 | |
display_name: str = "Discount" | |
description: str = "" | |
is_selectable: bool = True | |
conditions: List[Dict] = None | |
def apply(self, base_total: int, context: Dict) -> int: | |
if self.is_applicable(context): | |
return (base_total * self.rate_percent) // 100 | |
return 0 | |
def to_dict(self) -> Dict: | |
return { | |
"type": "Discount", | |
"amount_cents": self.amount_cents, | |
"rate_percent": self.rate_percent, | |
"display_name": self.display_name, | |
"description": self.description, | |
"is_selectable": self.is_selectable, | |
"conditions": self.conditions or [] | |
} | |
@classmethod | |
def from_dict(cls, data: Dict) -> 'Discount': | |
return cls( | |
amount_cents=data.get("amount_cents", 0), | |
rate_percent=data["rate_percent"], | |
display_name=data.get("display_name", "Discount"), | |
description=data.get("description", ""), | |
is_selectable=data.get("is_selectable", True), | |
conditions=data.get("conditions", []) | |
) | |
# Price Bin implementation | |
@dataclass | |
class PriceBin(PriceModifier): | |
bins: List[Dict] | |
amount_cents: int = 0 | |
display_name: str = "Price Bin Discount" | |
description: str = "" | |
is_selectable: bool = False | |
conditions: List[Dict] = None | |
def apply(self, base_total: int, context: Dict) -> int: | |
if not self.is_applicable(context): | |
return 0 | |
applicable_rate = 0 | |
for bin in sorted(self.bins, key=lambda x: x["min_total_cents"], reverse=True): | |
if base_total >= bin["min_total_cents"]: | |
applicable_rate = bin["rate_percent"] | |
break | |
return (base_total * applicable_rate) // 100 | |
def to_dict(self) -> Dict: | |
return { | |
"type": "PriceBin", | |
"amount_cents": self.amount_cents, | |
"bins": self.bins, | |
"display_name": self.display_name, | |
"description": self.description, | |
"is_selectable": self.is_selectable, | |
"conditions": self.conditions or [] | |
} | |
@classmethod | |
def from_dict(cls, data: Dict) -> 'PriceBin': | |
return cls( | |
amount_cents=data.get("amount_cents", 0), | |
bins=data["bins"], | |
display_name=data.get("display_name", "Price Bin Discount"), | |
description=data.get("description", ""), | |
is_selectable=data.get("is_selectable", False), | |
conditions=data.get("conditions", []) | |
) | |
# Price Modifier factory | |
class PriceModifierFactory: | |
@staticmethod | |
def create(data: Dict) -> PriceModifier: | |
modifier_type = data.get("type") | |
if modifier_type == "ServiceFee": | |
return ServiceFee.from_dict(data) | |
elif modifier_type == "Discount": | |
return Discount.from_dict(data) | |
elif modifier_type == "PriceBin": | |
return PriceBin.from_dict(data) | |
raise ValueError(f"Unknown modifier type: {modifier_type}") | |
@dataclass | |
class PriceComponents: | |
base: int | |
fees: int | |
discount: int | |
fee_breakdown: Dict[str, int] | |
discount_breakdown: Dict[str, int] | |
class PricingEngine: | |
def __init__(self, config: PricingConfig, base_price_service: Optional[BasePriceService] = None, | |
static_base_price: Optional[int] = None): | |
self.config = config | |
self.base_price_service = base_price_service | |
self.static_base_price = static_base_price | |
self.modifiers: Dict[str, PriceModifier] = self._load_modifiers() | |
def _load_modifiers(self) -> Dict[str, PriceModifier]: | |
modifiers = {} | |
for group_name, group_data in self.config.config.get("modifier_groups", {}).items(): | |
for name, data in group_data.get("modifiers", {}).items(): | |
modifiers[f"{group_name}:{name}"] = PriceModifierFactory.create(data) | |
return modifiers | |
def get_base_price(self) -> int: | |
"""Get base price, preferring static value for testing if provided.""" | |
if self.static_base_price is not None: | |
return self.static_base_price | |
if self.base_price_service is not None: | |
return self.base_price_service.get_base_price() | |
return 1000 # Fallback default | |
def calculate_price(self, | |
quantity: int = 1, | |
modifier_types: List[str] = None, | |
manual_adjustment_cents: Optional[int] = None) -> PriceComponents: | |
"""Calculate total price with all components in cents.""" | |
if modifier_types is None: | |
modifier_types = [] | |
# Get base price | |
base_price = self.get_base_price() | |
base_total = base_price * quantity | |
# Context for condition evaluation | |
context = {"quantity": quantity, "customer_years": 0} | |
# Calculate fees | |
total_fees = 0 | |
fee_breakdown = {} | |
# Apply configured modifiers | |
for modifier_type in modifier_types: | |
modifier = self.modifiers.get(modifier_type) | |
if modifier: | |
amount = modifier.apply(base_total, context) | |
if isinstance(modifier, ServiceFee): | |
total_fees += amount | |
if amount > 0: | |
fee_breakdown[modifier_type] = amount | |
elif isinstance(modifier, (Discount, PriceBin)): | |
pass | |
else: | |
print(f"Warning: Modifier type '{modifier_type}' not found") | |
# Handle manual adjustment | |
if manual_adjustment_cents is not None: | |
total_fees += manual_adjustment_cents | |
fee_breakdown["manual_adjustment"] = manual_adjustment_cents | |
# Calculate discounts | |
total_discount = 0 | |
discount_breakdown = {} | |
for name, modifier in self.modifiers.items(): | |
if isinstance(modifier, (Discount, PriceBin)): | |
amount = modifier.apply(base_total, context) | |
if amount > 0: | |
total_discount += amount | |
discount_breakdown[name] = amount | |
return PriceComponents( | |
base=base_total, | |
fees=total_fees, | |
discount=total_discount, | |
fee_breakdown=fee_breakdown, | |
discount_breakdown=discount_breakdown | |
) | |
def get_total(self, components: PriceComponents) -> int: | |
"""Calculate final total from price components in cents.""" | |
return components.base + components.fees - components.discount | |
# Example usage | |
def main(): | |
# Initialize configuration | |
config = PricingConfig() | |
# Create pricing engine with static base price for testing | |
engine_static = PricingEngine(config, static_base_price=1500) | |
# Create pricing engine with mock service for demo | |
mock_service = Mock(spec=BasePriceService) | |
mock_service.get_base_price.return_value = 1200 | |
engine_service = PricingEngine(config, base_price_service=mock_service) | |
# Demonstrate front-end modifier listing | |
print("\nSelectable Modifiers for Front-End:") | |
for group in config.get_selectable_modifiers(): | |
print(f"\nGroup: {group['display_name']} - {group['description']}") | |
for modifier in group["modifiers"]: | |
print(f"- {modifier['display_name']}: {modifier['description']}") | |
print(f" Name: {modifier['name']}, Type: {modifier['type']}") | |
if modifier.get("amount_cents"): | |
print(f" Amount: ${modifier['amount_cents'] / 100:.2f}") | |
if modifier.get("rate_percent"): | |
print(f" Rate: {modifier['rate_percent']}%") | |
if modifier["conditions"]: | |
print(f" Conditions: {modifier['conditions']}") | |
if modifier["bins"]: | |
print(f" Bins: {modifier['bins']}") | |
# Example calculations | |
scenarios = [ | |
{ | |
"desc": "Single item with processing fee (static price)", | |
"engine": engine_static, | |
"quantity": 1, | |
"modifier_types": ["service_options:processing"], | |
"manual_adjustment_cents": None | |
}, | |
{ | |
"desc": "Bulk order with fees and discounts (service price)", | |
"engine": engine_service, | |
"quantity": 15, | |
"modifier_types": ["service_options:processing", "service_options:priority", "promotions:bulk"], | |
"manual_adjustment_cents": 100 | |
}, | |
{ | |
"desc": "Large order triggering price bin discount (static price)", | |
"engine": engine_static, | |
"quantity": 20, | |
"modifier_types": [], | |
"manual_adjustment_cents": -200 | |
} | |
] | |
for scenario in scenarios: | |
print(f"\nPricing for: {scenario['desc']}") | |
components = scenario["engine"].calculate_price( | |
quantity=scenario["quantity"], | |
modifier_types=scenario["modifier_types"], | |
manual_adjustment_cents=scenario["manual_adjustment_cents"] | |
) | |
print(f"Base Price: ${components.base / 100:.2f}") | |
print("Fees Breakdown:") | |
for fee_type, amount in components.fee_breakdown.items(): | |
print(f" {fee_type}: ${amount / 100:.2f}") | |
print(f"Total Fees: ${components.fees / 100:.2f}") | |
print("Discounts Breakdown:") | |
for discount_type, amount in components.discount_breakdown.items(): | |
print(f" {discount_type}: ${amount / 100:.2f}") | |
print(f"Total Discount: ${components.discount / 100:.2f}") | |
print(f"Total: ${scenario['engine'].get_total(components) / 100:.2f}") | |
if __name__ == "__main__": | |
main() | |
# Pytest tests | |
import pytest | |
@pytest.fixture | |
def pricing_engine(): | |
config = PricingConfig() | |
return PricingEngine(config, static_base_price=1000) | |
@pytest.fixture | |
def config(): | |
return PricingConfig() | |
def test_service_fee_application(pricing_engine): | |
components = pricing_engine.calculate_price(quantity=1, modifier_types=["service_options:processing"]) | |
assert components.fees == 50 | |
assert components.fee_breakdown["service_options:processing"] == 50 | |
def test_discount_application(pricing_engine): | |
components = pricing_engine.calculate_price(quantity=15, modifier_types=["promotions:bulk"]) | |
expected_discount = (1000 * 15 * 10) // 100 # 10% of 15000 cents | |
assert components.discount == expected_discount | |
assert components.discount_breakdown["promotions:bulk"] == expected_discount | |
def test_loyalty_discount(pricing_engine): | |
components = pricing_engine.calculate_price(quantity=1) | |
assert components.discount == 0 # No loyalty discount without customer_years | |
pricing_engine.modifiers["promotions:loyalty"].conditions = [{"type": "customer_years", "threshold": 0}] | |
components = pricing_engine.calculate_price(quantity=1) | |
expected_discount = (1000 * 5) // 100 # 5% of 1000 cents | |
assert components.discount == expected_discount | |
def test_price_bin_discount(pricing_engine): | |
components = pricing_engine.calculate_price(quantity=10) | |
expected_discount = (1000 * 10 * 5) // 100 # 5% of 10000 cents | |
assert components.discount == expected_discount | |
assert components.discount_breakdown["promotions:price_tier"] == expected_discount | |
components = pricing_engine.calculate_price(quantity=25) | |
expected_discount = (1000 * 25 * 10) // 100 # 10% of 25000 cents | |
assert components.discount == expected_discount | |
assert components.discount_breakdown["promotions:price_tier"] == expected_discount | |
def test_manual_adjustment(pricing_engine): | |
components = pricing_engine.calculate_price(quantity=1, manual_adjustment_cents=100) | |
assert components.fees == 100 | |
assert components.fee_breakdown["manual_adjustment"] == 100 | |
def test_serialization_service_fee(): | |
fee = ServiceFee(amount_cents=50, display_name="Test Fee", description="Test", is_selectable=True, conditions=[]) | |
serialized = fee.to_dict() | |
deserialized = ServiceFee.from_dict(serialized) | |
assert fee.amount_cents == deserialized.amount_cents | |
assert fee.display_name == deserialized.display_name | |
assert fee.description == deserialized.description | |
assert fee.is_selectable == deserialized.is_selectable | |
assert fee.conditions == deserialized.conditions | |
def test_serialization_discount(): | |
discount = Discount(rate_percent=10, amount_cents=0, display_name="Test Discount", description="Test", | |
is_selectable=True, conditions=[{"type": "quantity", "threshold": 5}]) | |
serialized = discount.to_dict() | |
deserialized = Discount.from_dict(serialized) | |
assert discount.rate_percent == deserialized.rate_percent | |
assert discount.amount_cents == deserialized.amount_cents | |
assert discount.display_name == deserialized.display_name | |
assert discount.description == deserialized.description | |
assert discount.is_selectable == deserialized.is_selectable | |
assert discount.conditions == deserialized.conditions | |
def test_serialization_price_bin(): | |
price_bin = PriceBin(bins=[{"min_total_cents": 10000, "rate_percent": 5}], amount_cents=0, display_name="Test Bin", | |
description="Test", is_selectable=False, conditions=[]) | |
serialized = price_bin.to_dict() | |
deserialized = PriceBin.from_dict(serialized) | |
assert price_bin.bins == deserialized.bins | |
assert price_bin.amount_cents == deserialized.amount_cents | |
assert price_bin.display_name == deserialized.display_name | |
assert price_bin.description == deserialized.description | |
assert price_bin.is_selectable == deserialized.is_selectable | |
assert price_bin.conditions == deserialized.conditions | |
def test_selectable_modifiers(config): | |
selectable = config.get_selectable_modifiers() | |
assert len(selectable) == 2 # service_options, promotions | |
service_group = next(g for g in selectable if g["name"] == "service_options") | |
assert len(service_group["modifiers"]) == 2 # processing, priority | |
promo_group = next(g for g in selectable if g["name"] == "promotions") | |
assert len(promo_group["modifiers"]) == 1 # bulk | |
assert any(m["name"] == "processing" and m["display_name"] == "Processing Fee" for m in service_group["modifiers"]) | |
assert any(m["name"] == "bulk" and m["rate_percent"] == 10 for m in promo_group["modifiers"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment