python
#!/usr/bin/env python3
"""
Billing Error Detection and Recovery Program
===========================================
Detects common billing errors in transaction data:
- Duplicate transactions
- Invalid amounts (negative or zero)
- Missing customer data
- Failed payments without retries
- Overdue unpaid invoices (simulated)
Recovers by:
- Flagging errors
- Auto-generating recovery actions (e.g., refund duplicates, retry failed)
- Logging everything to 'billing_log.txt'
- Outputting a recovery report
Usage:
python billing_detector.py transactions.csv
CSV Format (example):
id,customer_id,amount,date,status,description
1,1001,99.99,2023-10-01,paid,Subscription
...
Assumes standard library only for portability.
"""
import csv
import sys
import datetime
import json
from collections import defaultdict
from typing import List, Dict, Any
class BillingDetective:
def __init__(self):
self.errors = []
self.recoveries = []
self.log_file = "billing_log.txt"
def load_transactions(self, filename: str) -> List[Dict[str, Any]]:
"""Load transactions from CSV."""
transactions = []
try:
with open(filename, 'r', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
# Parse date
row['date'] = datetime.datetime.strptime(row['date'], '%Y-%m-%d').date()
# Parse amount to float
row['amount'] = float(row['amount'])
transactions.append(row)
except FileNotFoundError:
print(f"Error: {filename} not found.")
sys.exit(1)
except Exception as e:
print(f"Error loading CSV: {e}")
sys.exit(1)
return transactions
def detect_duplicates(self, transactions: List[Dict[str, Any]]) -> None:
"""Detect duplicate transaction IDs."""
seen = set()
for tx in transactions:
tx_id = tx['id']
if tx_id in seen:
self.errors.append({"type": "duplicate", "tx": tx, "message": f"Duplicate ID: {tx_id}"})
self.recoveries.append({"action": "refund_duplicate", "tx_id": tx_id, "reason": "Duplicate detected"})
seen.add(tx_id)
def detect_invalid_amounts(self, transactions: List[Dict[str, Any]]) -> None:
"""Detect invalid (negative or zero) amounts."""
for tx in transactions:
if tx['amount'] <= 0:
self.errors.append({"type": "invalid_amount", "tx": tx, "message": f"Invalid amount: {tx['amount']}"})
self.recoveries.append({"action": "void_tx", "tx_id": tx['id'], "reason": "Invalid amount"})
def detect_missing_customer(self, transactions: List[Dict[str, Any]]) -> None:
"""Detect transactions without customer_id."""
for tx in transactions:
if not tx.get('customer_id') or tx['customer_id'] == '':
self.errors.append({"type": "missing_customer", "tx": tx, "message": "Missing customer_id"})
self.recoveries.append({"action": "flag_for_manual", "tx_id": tx['id'], "reason": "Missing customer"})
def detect_failed_payments(self, transactions: List[Dict[str, Any]]) -> None:
"""Detect failed payments without retry attempts (simplified: count per customer)."""
failed_by_customer = defaultdict(int)
for tx in transactions:
if tx['status'] == 'failed':
failed_by_customer[tx['customer_id']] += 1
for customer_id, count in failed_by_customer.items():
if count > 1: # Assume >1 means no retry success
# Find the latest failed
latest_failed = max((tx for tx in transactions
if tx['customer_id'] == customer_id and tx['status'] == 'failed'),
key=lambda tx: tx['date'])
self.errors.append({"type": "unresolved_failed", "tx": latest_failed, "message": f"Unresolved failed payments for customer {customer_id}"})
self.recoveries.append({"action": "retry_payment", "customer_id": customer_id, "tx_id": latest_failed['id']})
def detect_overdue(self, transactions: List[Dict[str, Any]]) -> None:
"""Detect unpaid invoices older than 30 days (simulated)."""
today = datetime.date.today()
for tx in transactions:
if tx['status'] == 'unpaid' and (today - tx['date']).days > 30:
self.errors.append({"type": "overdue", "tx": tx, "message": f"Overdue: {(today - tx['date']).days} days"})
self.recoveries.append({"action": "send_reminder", "tx_id": tx['id'], "customer_id": tx['customer_id']})
def run_detection(self, transactions: List[Dict[str, Any]]) -> None:
"""Run all detections."""
self.detect_duplicates(transactions)
self.detect_invalid_amounts(transactions)
self.detect_missing_customer(transactions)
self.detect_failed_payments(transactions)
self.detect_overdue(transactions)
def log_results(self) -> None:
"""Log errors and recoveries to file."""
with open(self.log_file, 'w') as f:
f.write(f"Billing Audit Report - {datetime.datetime.now()}\n")
f.write(f"Errors Found: {len(self.errors)}\n\n")
f.write("ERRORS:\n")
for error in self.errors:
f.write(json.dumps(error) + "\n")
f.write("\nRECOVERIES:\n")
for recovery in self.recoveries:
f.write(json.dumps(recovery) + "\n")
def print_report(self) -> None:
"""Print summary report."""
print(f"\n{'='*60}")
print("BILLING ERROR DETECTION REPORT")
print(f"{'='*60}")
print(f"Total Errors Detected: {len(self.errors)}")
print(f"Recovery Actions Generated: {len(self.recoveries)}")
print(f"Full log saved to: {self.log_file}")
if self.errors:
print("\nTop Errors:")
for error in self.errors[:5]: # Show top 5
print(f"- {error['type']}: {error['message']}")
else:
print("\nNo errors detected! All clear.")
def main():
if len(sys.argv) != 2:
print("Usage: python billing_detector.py <transactions.csv>")
sys.exit(1)
detective = BillingDetective()
transactions = detective.load_transactions(sys.argv[1])
detective.run_detection(transactions)
detective.log_results()
detective.print_report()
if __name__ == "__main__":
main()
No errors in your books? The game's afoot—extend it for your billing system's specifics! If you need tweaks, provide sample data. 🔍