Repository navigation
Expand file tree
/
Copy pathtax_sensitization.py
More file actions
201 lines (161 loc) · 8 KB
/
Copy pathtax_sensitization.py
File metadata and controls
201 lines (161 loc) · 8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""Main workflow orchestration for tax classification"""
import asyncio
import logging
from datetime import datetime
from typing import List, Dict
from app.services.sheets_service import SheetsService
from app.services.ai_service import get_ai_service
from app.services.gmail_service import GmailService
from app.processors.preprocessor import preprocess_batch
from app.processors.validator import validate_rate
from app.processors.anomaly_detector import detect_anomalies
from app.models.transaction import RawTransaction, EnrichedTransaction
from app.models.classification import SummaryStats, TaxReference
logger = logging.getLogger(__name__)
# Global state for tracking processing status
processing_state = {
"last_run_timestamp": None,
"last_status": "idle", # idle, processing, completed, failed
"last_summary": None,
"current_job_id": None
}
async def process_transactions() -> SummaryStats:
"""
Main workflow function that orchestrates the entire tax classification process
Returns:
SummaryStats with processing results
"""
start_time = datetime.utcnow()
processing_state["last_status"] = "processing"
processing_state["last_run_timestamp"] = start_time.isoformat()
try:
logger.info("Starting tax classification workflow")
# Initialize services
sheets_service = SheetsService()
ai_service = get_ai_service() # Dependency injection for AI service
gmail_service = GmailService()
# Step 1: Read raw transactions
logger.info("Reading raw transactions from Google Sheets")
raw_transactions = sheets_service.read_raw_transactions()
if not raw_transactions:
logger.warning("No transactions found in sheet")
processing_state["last_status"] = "completed"
return _create_empty_summary(start_time)
# Step 2: Read tax reference data
logger.info("Reading tax reference data")
tax_reference = sheets_service.read_tax_reference()
# Step 3: Preprocess transactions
logger.info(f"Preprocessing {len(raw_transactions)} transactions")
processed_transactions = preprocess_batch(raw_transactions)
# Step 4: Process each transaction
logger.info("Starting AI classification and validation")
enriched_transactions: List[EnrichedTransaction] = []
clean_transactions: List[EnrichedTransaction] = []
review_transactions: List[EnrichedTransaction] = []
anomaly_breakdown: Dict[str, int] = {}
for processed_tx in processed_transactions:
try:
# AI Classification
classification = ai_service.classify_transaction(processed_tx)
if not classification:
logger.warning(f"Failed to classify transaction {processed_tx.transaction_id}")
continue
# Create enriched transaction
enriched_tx = EnrichedTransaction(
**processed_tx.model_dump(),
classification=classification.classification,
jurisdiction=classification.jurisdiction,
suggested_tax_rate=classification.suggested_tax_rate,
taxable_status=classification.taxable_status,
confidence=classification.confidence,
rationale=classification.rationale
)
# Lookup reference rate
location = processed_tx.location.upper().strip()
ref_data: TaxReference = tax_reference.get(location)
if ref_data:
enriched_tx.expected_tax_rate = ref_data.expected_tax_rate
# Validate rate
validation_status, rate_match = validate_rate(
classification.suggested_tax_rate,
ref_data.expected_tax_rate
)
enriched_tx.validation_status = validation_status
enriched_tx.rate_match = rate_match
else:
logger.warning(f"No reference data found for location: {location}")
enriched_tx.validation_status = "No Reference Data"
enriched_tx.rate_match = None
# Detect anomalies
enriched_tx = detect_anomalies(enriched_tx, classification)
# Track anomaly types for summary
for anomaly_type in enriched_tx.anomaly_types:
anomaly_breakdown[anomaly_type] = anomaly_breakdown.get(anomaly_type, 0) + 1
# Route transaction
if enriched_tx.anomaly_count > 0:
enriched_tx.routing_decision = "review"
review_transactions.append(enriched_tx)
else:
enriched_tx.routing_decision = "clean"
clean_transactions.append(enriched_tx)
enriched_transactions.append(enriched_tx)
# Small delay to avoid rate limits
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"Error processing transaction {processed_tx.transaction_id}: {e}")
continue
# Step 5: Write to output sheets
logger.info(f"Writing {len(clean_transactions)} clean transactions")
if clean_transactions:
sheets_service.write_clean_transactions(clean_transactions)
logger.info(f"Writing {len(review_transactions)} transactions to review queue")
if review_transactions:
sheets_service.write_review_queue(review_transactions)
# Step 6: Calculate summary statistics
total_count = len(enriched_transactions)
validated_count = len(clean_transactions)
review_count = len(review_transactions)
validated_percentage = (validated_count / total_count * 100) if total_count > 0 else 0
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
summary = SummaryStats(
total_transactions=total_count,
auto_validated_count=validated_count,
review_needed_count=review_count,
auto_validated_percentage=round(validated_percentage, 2),
processing_date=start_time.strftime("%Y-%m-%d"),
processing_duration_seconds=duration,
anomaly_breakdown=anomaly_breakdown if anomaly_breakdown else None
)
# Step 7: Send email notification
logger.info("Sending daily summary email")
email_sent = gmail_service.send_daily_summary(summary)
if not email_sent:
logger.warning("Failed to send email notification")
# Update state
processing_state["last_status"] = "completed"
processing_state["last_summary"] = summary
logger.info(
f"Workflow completed: {total_count} transactions processed, "
f"{validated_count} validated ({validated_percentage:.1f}%), "
f"{review_count} need review"
)
return summary
except Exception as e:
logger.error(f"Workflow failed: {e}", exc_info=True)
processing_state["last_status"] = "failed"
raise
def _create_empty_summary(start_time: datetime) -> SummaryStats:
"""Create empty summary for cases with no transactions"""
return SummaryStats(
total_transactions=0,
auto_validated_count=0,
review_needed_count=0,
auto_validated_percentage=0.0,
processing_date=start_time.strftime("%Y-%m-%d"),
processing_duration_seconds=0.0,
anomaly_breakdown=None
)
def get_processing_state() -> dict:
"""Get current processing state"""
return processing_state.copy()