askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/services/calculate_order_total.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
calculate_order_total.py · 4.4 KB · 123 lines
1#!/usr/bin/env python3
2"""
3AI-Generated Service: calculate_order_total
4Description: Calculate tax based on customer location
5Generated: 2025-09-19T10:30:00.000000
6"""
7
8from typing import Dict, Any, List
9import json
10from datetime import datetime
11
12async def calculate_order_total(data: Dict[str, Any]) -> Dict[str, Any]:
13 """
14 Calculate order total with tax based on customer location.
15
16 Inputs: items, customer_location, apply_discounts
17 Outputs: subtotal, tax_amount, discount_amount, total, tax_rate
18 """
19
20 try:
21 # Extract inputs
22 items = data.get('items', [])
23 customer_location = data.get('customer_location', {})
24 apply_discounts = data.get('apply_discounts', True)
25
26 # Calculate subtotal
27 subtotal = 0
28 for item in items:
29 price = item.get('price', 0)
30 quantity = item.get('quantity', 1)
31 subtotal += price * quantity
32
33 # Determine tax rate based on location
34 state = customer_location.get('state', 'CA')
35 tax_rates = {
36 'CA': 0.0725, # California
37 'TX': 0.0625, # Texas
38 'NY': 0.08, # New York
39 'FL': 0.06, # Florida
40 'WA': 0.065, # Washington
41 'OR': 0, # Oregon (no sales tax)
42 'MT': 0, # Montana (no sales tax)
43 'NH': 0, # New Hampshire (no sales tax)
44 'DE': 0, # Delaware (no sales tax)
45 'AK': 0, # Alaska (no sales tax)
46 }
47
48 # Add city tax for certain locations
49 city = customer_location.get('city', '').upper()
50 city_tax = 0
51 if state == 'CA' and city == 'SAN FRANCISCO':
52 city_tax = 0.01 # Additional 1% for SF
53 elif state == 'NY' and city == 'NEW YORK':
54 city_tax = 0.045 # NYC additional tax
55 elif state == 'WA' and city == 'SEATTLE':
56 city_tax = 0.0365 # Seattle additional tax
57
58 base_tax_rate = tax_rates.get(state, 0.05) # Default 5% for unknown states
59 total_tax_rate = base_tax_rate + city_tax
60
61 # Calculate tax
62 tax_amount = subtotal * total_tax_rate
63
64 # Apply discounts
65 discount_amount = 0
66 if apply_discounts:
67 # Volume discount
68 if subtotal > 1000:
69 discount_amount = subtotal * 0.10 # 10% off for orders over $1000
70 elif subtotal > 500:
71 discount_amount = subtotal * 0.05 # 5% off for orders over $500
72
73 # Loyalty discount (if customer data provided)
74 if data.get('customer_tier') == 'gold':
75 discount_amount += subtotal * 0.05 # Additional 5% for gold members
76 elif data.get('customer_tier') == 'platinum':
77 discount_amount += subtotal * 0.10 # Additional 10% for platinum
78
79 # Calculate final total
80 total = subtotal - discount_amount + tax_amount
81
82 result = {
83 'subtotal': round(subtotal, 2),
84 'tax_amount': round(tax_amount, 2),
85 'tax_rate': round(total_tax_rate * 100, 2), # As percentage
86 'discount_amount': round(discount_amount, 2),
87 'total': round(total, 2),
88 'location_used': f"{city}, {state}" if city else state,
89 'discounts_applied': []
90 }
91
92 # List applied discounts
93 if discount_amount > 0:
94 if subtotal > 1000:
95 result['discounts_applied'].append('Volume discount (10%)')
96 elif subtotal > 500:
97 result['discounts_applied'].append('Volume discount (5%)')
98
99 if data.get('customer_tier') == 'gold':
100 result['discounts_applied'].append('Gold member discount (5%)')
101 elif data.get('customer_tier') == 'platinum':
102 result['discounts_applied'].append('Platinum member discount (10%)')
103
104 return {
105 "success": True,
106 "timestamp": datetime.now().isoformat(),
107 "data": result
108 }
109
110 except Exception as e:
111 return {
112 "success": False,
113 "error": str(e),
114 "timestamp": datetime.now().isoformat()
115 }
116
117# Synchronous wrapper
118def calculate_order_total_sync(data: Dict[str, Any]) -> Dict[str, Any]:
119 """Synchronous wrapper for the async function"""
120 import asyncio
121 return asyncio.run(calculate_order_total(data))
122
123__all__ = ['calculate_order_total', 'calculate_order_total_sync']