import enum
import json
from datetime import date, timedelta
from typing import Dict, List, Optional, Any
from pydantic import BaseModel, Field
from fastapi import FastAPI, HTTPException, BackgroundTasks
import random
# --- 1. Data Models & Schemas ---
class EventType(str, enum.Enum):
TIME_ENTRY = "time_entry"
PAYROLL_RUN = "payroll_run"
ADDRESS_CHANGE = "address_change"
class Currency(str, enum.Enum):
USD = "USD"
EUR = "EUR"
GBP = "GBP"
class EmployeeEvent(BaseModel):
employee_id: str
event_type: EventType
country_code: str # ISO 3166-1 alpha-2 (e.g., US, DE, UK)
gross_pay: float
currency: Currency
days_worked_in_country: int
timestamp: str
class AlertSeverity(str, enum.Enum):
CRITICAL = "critical" # Compliance breach (e.g., threshold exceeded)
WARNING = "warning" # Variance detected
INFO = "info" # Filing ready
class Alert(BaseModel):
employee_id: str
severity: AlertSeverity
message: str
metric: str
value: Any
# --- 2. The Logic Mesh (Rules Engine) ---
class TaxRuleEngine:
"""
Abstract base for country-specific logic.
In a real mesh, these would be microservices or serverless functions.
"""
def __init__(self, country_code: str, thresholds: dict, rates: dict):
self.country_code = country_code
self.thresholds = thresholds
self.rates = rates
def calculate_tax(self, gross: float, days: int) -> float:
raise NotImplementedError
def check_compliance(self, gross: float, days: int) -> Optional[Alert]:
raise NotImplementedError
class USATaxEngine(TaxRuleEngine):
def calculate_tax(self, gross: float, days: int) -> float:
# Simplified progressive tax logic
rate = self.rates.get('standard', 0.25)
return gross * rate
def check_compliance(self, gross: float, days: int) -> Optional[Alert]:
# Example: Check specific state nexus rules (simplified)
if days > self.thresholds.get('nexus_days', 180):
return None # Safe
return None
class UKTaxEngine(TaxRuleEngine):
def calculate_tax(self, gross: float, days: int) -> float:
# UK PAYE simulation
allowance = self.rates.get('personal_allowance', 12570)
taxable = max(0, gross - allowance)
return taxable * self.rates.get('basic_rate', 0.20)
def check_compliance(self, gross: float, days: int) -> Optional[Alert]:
# Check for Permanent Establishment risk
if days > self.thresholds.get('pe_days', 45):
return Alert(
employee_id="SYSTEM",
severity=AlertSeverity.WARNING,
message=f"UK Permanent Establishment risk detected ({days} days).",
metric="days_worked",
value=days
)
return None
# --- 3. The Mesh Controller ---
class PayrollTaxMesh:
def __init__(self):
# Initialize Country Engines
self.engines = {
"US": USATaxEngine("US", {'nexus_days': 180}, {'standard': 0.25}),
"UK": UKTaxEngine("UK", {'pe_days': 45}, {'personal_allowance': 12570, 'basic_rate': 0.20}),
# Add more countries here...
}
self.variance_threshold = 0.10 # 10% variance triggers alert
async def process_event(self, event: EmployeeEvent, history: Dict):
"""
Routes the event to the appropriate jurisdiction engine,
checks thresholds, and calculates variance.
"""
# 1. Currency Normalization (Mock)
normalized_gross = self._convert_currency(event.gross_pay, event.currency, Currency.USD)
# 2. Retrieve Country Engine
engine = self.engines.get(event.country_code)
if not engine:
raise HTTPException(status_code=400, detail=f"Unsupported Jurisdiction: {event.country_code}")
# 3. Run Compliance Checks (Thresholds)
alert = engine.check_compliance(normalized_gross, event.days_worked_in_country)
if alert:
self._trigger_alert(alert)
# 4. Calculate Tax
calculated_tax = engine.calculate_tax(normalized_gross, event.days_worked_in_country)
# 5. Real-time Variance Check (Anomaly Detection)
# Compare against historical average for this employee
hist_data = history.get(event.employee_id, [])
if hist_data:
avg_past_tax = sum(hist_data) / len(hist_data)
variance = abs(calculated_tax - avg_past_tax) / avg_past_tax if avg_past_tax > 0 else 0
if variance > self.variance_threshold:
self._trigger_alert(Alert(
employee_id=event.employee_id,
severity=AlertSeverity.WARNING,
message=f"Tax variance of {variance:.1%} detected vs historical average.",
metric="variance",
value=variance
))
# 6. Generate Filing Payload
filing_payload = self._generate_filing_payload(event, calculated_tax)
return {
"status": "processed",
"jurisdiction": event.country_code,
"tax_withheld": round(calculated_tax, 2),
"currency": "USD",
"filing_payload": filing_payload
}
def _convert_currency(self, amount: float, source: Currency, target: Currency) -> float:
# Mock conversion rates
rates = { Currency.USD: 1.0, Currency.EUR: 1.1, Currency.GBP: 1.25 }
return amount * rates[source]
def _trigger_alert(self, alert: Alert):
# In production: Push to SNS, Kafka, or Webhook
print(f"🚨 ALERT [{alert.severity.value.upper()}]: {alert.message}")
def _generate_filing_payload(self, event: EmployeeEvent, tax: float) -> dict:
# Structured data for government gateway or ERP posting
return {
"filing_id": f"{event.country_code}-{event.employee_id}-{date.today().year}",
"amount": tax,
"due_date": str(date.today() + timedelta(days=30)),
"status": "DRAFT"
}
# --- 4. API Interface ---
app = FastAPI(title="Cross-Border Payroll Mesh")
mesh = PayrollTaxMesh()
# Mock Database
employee_history = {
"EMP_001": [5000.0, 5050.0, 4900.0], # Historical taxes paid
"EMP_002": [2000.0, 2100.0]
}
@app.post("/webhooks/payroll-event")
async def ingest_event(event: EmployeeEvent, background_tasks: BackgroundTasks):
"""
Ingests a payroll or time-tracking event into the mesh.
"""
# Process asynchronously to handle latency in external APIs
result = await mesh.process_event(event, employee_history)
# Update mock history
if event.employee_id in employee_history:
employee_history[event.employee_id].append(result['tax_withheld'])
return result
@app.get("/health")
def health():
return {"status": "Mesh Operational", "jurisdictions": list(mesh.engines.keys())}