Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
detect_fraud.py · 7.7 KB · 202 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | AI-Generated Service: detect_fraud |
| 4 | Description: Score orders for fraud risk using multiple signals |
| 5 | Generated: 2025-09-19T10:32:00.000000 |
| 6 | """ |
| 7 | |
| 8 | from typing import Dict, Any, List, Optional |
| 9 | import json |
| 10 | from datetime import datetime, timedelta |
| 11 | import hashlib |
| 12 | import random |
| 13 | |
| 14 | async def detect_fraud(data: Dict[str, Any]) -> Dict[str, Any]: |
| 15 | """ |
| 16 | Analyze transaction data for fraud indicators and return a risk score. |
| 17 | |
| 18 | Inputs: order_data, customer_data, payment_data, shipping_data |
| 19 | Outputs: fraud_score, risk_level, signals_detected, action_recommended, reason_codes |
| 20 | """ |
| 21 | |
| 22 | try: |
| 23 | # Extract inputs |
| 24 | order_data = data.get('order_data', {}) |
| 25 | customer_data = data.get('customer_data', {}) |
| 26 | payment_data = data.get('payment_data', {}) |
| 27 | shipping_data = data.get('shipping_data', {}) |
| 28 | |
| 29 | # Initialize fraud scoring |
| 30 | fraud_score = 0 |
| 31 | signals_detected = [] |
| 32 | reason_codes = [] |
| 33 | |
| 34 | # 1. Check order value anomalies |
| 35 | order_total = order_data.get('total', 0) |
| 36 | avg_order_value = customer_data.get('average_order_value', 100) |
| 37 | |
| 38 | if order_total > avg_order_value * 5: |
| 39 | fraud_score += 25 |
| 40 | signals_detected.append('High order value') |
| 41 | reason_codes.append('HIGH_ORDER_VALUE') |
| 42 | elif order_total > avg_order_value * 3: |
| 43 | fraud_score += 15 |
| 44 | signals_detected.append('Elevated order value') |
| 45 | reason_codes.append('ELEVATED_ORDER_VALUE') |
| 46 | |
| 47 | # 2. Check customer history |
| 48 | account_age_days = customer_data.get('account_age_days', 0) |
| 49 | previous_orders = customer_data.get('previous_orders', 0) |
| 50 | |
| 51 | if account_age_days < 1: |
| 52 | fraud_score += 30 |
| 53 | signals_detected.append('New account') |
| 54 | reason_codes.append('NEW_ACCOUNT') |
| 55 | elif account_age_days < 7: |
| 56 | fraud_score += 15 |
| 57 | signals_detected.append('Recent account') |
| 58 | reason_codes.append('RECENT_ACCOUNT') |
| 59 | |
| 60 | if previous_orders == 0 and order_total > 500: |
| 61 | fraud_score += 20 |
| 62 | signals_detected.append('First order high value') |
| 63 | reason_codes.append('FIRST_ORDER_HIGH_VALUE') |
| 64 | |
| 65 | # 3. Check payment method risks |
| 66 | payment_method = payment_data.get('method', 'card') |
| 67 | card_verification_failed = payment_data.get('cvv_verification_failed', False) |
| 68 | billing_zip_mismatch = payment_data.get('billing_zip_mismatch', False) |
| 69 | |
| 70 | if payment_method == 'prepaid_card': |
| 71 | fraud_score += 15 |
| 72 | signals_detected.append('Prepaid card used') |
| 73 | reason_codes.append('PREPAID_CARD') |
| 74 | |
| 75 | if card_verification_failed: |
| 76 | fraud_score += 35 |
| 77 | signals_detected.append('Card verification failed') |
| 78 | reason_codes.append('CVV_FAILED') |
| 79 | |
| 80 | if billing_zip_mismatch: |
| 81 | fraud_score += 25 |
| 82 | signals_detected.append('Billing ZIP mismatch') |
| 83 | reason_codes.append('ZIP_MISMATCH') |
| 84 | |
| 85 | # 4. Check shipping address risks |
| 86 | billing_shipping_mismatch = shipping_data.get('different_from_billing', False) |
| 87 | po_box_address = shipping_data.get('is_po_box', False) |
| 88 | high_risk_country = shipping_data.get('country') in ['NG', 'RO', 'PK', 'ID'] |
| 89 | |
| 90 | if billing_shipping_mismatch: |
| 91 | fraud_score += 10 |
| 92 | signals_detected.append('Billing/shipping mismatch') |
| 93 | reason_codes.append('ADDRESS_MISMATCH') |
| 94 | |
| 95 | if po_box_address and order_total > 200: |
| 96 | fraud_score += 15 |
| 97 | signals_detected.append('PO Box for high value order') |
| 98 | reason_codes.append('PO_BOX_HIGH_VALUE') |
| 99 | |
| 100 | if high_risk_country: |
| 101 | fraud_score += 30 |
| 102 | signals_detected.append('High risk country') |
| 103 | reason_codes.append('HIGH_RISK_COUNTRY') |
| 104 | |
| 105 | # 5. Check velocity patterns |
| 106 | orders_last_hour = customer_data.get('orders_last_hour', 0) |
| 107 | orders_last_day = customer_data.get('orders_last_day', 0) |
| 108 | |
| 109 | if orders_last_hour > 3: |
| 110 | fraud_score += 40 |
| 111 | signals_detected.append('High order velocity') |
| 112 | reason_codes.append('VELOCITY_HOUR') |
| 113 | elif orders_last_day > 10: |
| 114 | fraud_score += 25 |
| 115 | signals_detected.append('Elevated daily orders') |
| 116 | reason_codes.append('VELOCITY_DAY') |
| 117 | |
| 118 | # 6. Check device fingerprint |
| 119 | device_data = data.get('device_data', {}) |
| 120 | vpn_detected = device_data.get('vpn_detected', False) |
| 121 | multiple_accounts_same_device = device_data.get('multiple_accounts', False) |
| 122 | |
| 123 | if vpn_detected: |
| 124 | fraud_score += 20 |
| 125 | signals_detected.append('VPN detected') |
| 126 | reason_codes.append('VPN_DETECTED') |
| 127 | |
| 128 | if multiple_accounts_same_device: |
| 129 | fraud_score += 35 |
| 130 | signals_detected.append('Multiple accounts on device') |
| 131 | reason_codes.append('MULTI_ACCOUNT_DEVICE') |
| 132 | |
| 133 | # 7. Email analysis |
| 134 | email = customer_data.get('email', '') |
| 135 | if email: |
| 136 | disposable_email = any(domain in email.lower() for domain in ['tempmail', 'guerrillamail', '10minutemail']) |
| 137 | if disposable_email: |
| 138 | fraud_score += 25 |
| 139 | signals_detected.append('Disposable email') |
| 140 | reason_codes.append('DISPOSABLE_EMAIL') |
| 141 | |
| 142 | # Cap fraud score at 100 |
| 143 | fraud_score = min(fraud_score, 100) |
| 144 | |
| 145 | # Determine risk level and action |
| 146 | if fraud_score >= 75: |
| 147 | risk_level = 'critical' |
| 148 | action_recommended = 'block' |
| 149 | elif fraud_score >= 50: |
| 150 | risk_level = 'high' |
| 151 | action_recommended = 'manual_review' |
| 152 | elif fraud_score >= 30: |
| 153 | risk_level = 'medium' |
| 154 | action_recommended = 'additional_verification' |
| 155 | elif fraud_score >= 15: |
| 156 | risk_level = 'low' |
| 157 | action_recommended = 'monitor' |
| 158 | else: |
| 159 | risk_level = 'minimal' |
| 160 | action_recommended = 'approve' |
| 161 | |
| 162 | result = { |
| 163 | 'fraud_score': fraud_score, |
| 164 | 'risk_level': risk_level, |
| 165 | 'signals_detected': signals_detected, |
| 166 | 'action_recommended': action_recommended, |
| 167 | 'reason_codes': reason_codes, |
| 168 | 'confidence': round(0.7 + (len(signals_detected) * 0.03), 2), # Higher confidence with more signals |
| 169 | 'review_priority': 'urgent' if fraud_score >= 75 else ('high' if fraud_score >= 50 else 'normal'), |
| 170 | 'estimated_loss_prevented': round(order_total * (fraud_score / 100), 2) if fraud_score >= 50 else 0 |
| 171 | } |
| 172 | |
| 173 | # Add detailed breakdown |
| 174 | result['score_breakdown'] = { |
| 175 | 'order_risk': min(40, sum(1 for code in reason_codes if 'ORDER' in code or 'VALUE' in code) * 15), |
| 176 | 'customer_risk': min(30, sum(1 for code in reason_codes if 'ACCOUNT' in code) * 15), |
| 177 | 'payment_risk': min(35, sum(1 for code in reason_codes if 'CARD' in code or 'CVV' in code or 'ZIP' in code) * 15), |
| 178 | 'shipping_risk': min(25, sum(1 for code in reason_codes if 'ADDRESS' in code or 'PO_BOX' in code or 'COUNTRY' in code) * 10), |
| 179 | 'velocity_risk': min(40, sum(1 for code in reason_codes if 'VELOCITY' in code) * 25), |
| 180 | 'device_risk': min(35, sum(1 for code in reason_codes if 'VPN' in code or 'DEVICE' in code) * 20) |
| 181 | } |
| 182 | |
| 183 | return { |
| 184 | "success": True, |
| 185 | "timestamp": datetime.now().isoformat(), |
| 186 | "data": result |
| 187 | } |
| 188 | |
| 189 | except Exception as e: |
| 190 | return { |
| 191 | "success": False, |
| 192 | "error": str(e), |
| 193 | "timestamp": datetime.now().isoformat() |
| 194 | } |
| 195 | |
| 196 | # Synchronous wrapper |
| 197 | def detect_fraud_sync(data: Dict[str, Any]) -> Dict[str, Any]: |
| 198 | """Synchronous wrapper for the async function""" |
| 199 | import asyncio |
| 200 | return asyncio.run(detect_fraud(data)) |
| 201 | |
| 202 | __all__ = ['detect_fraud', 'detect_fraud_sync'] |