-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheets_service.py
More file actions
173 lines (153 loc) · 7.33 KB
/
Copy pathsheets_service.py
File metadata and controls
173 lines (153 loc) · 7.33 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
"""Google Sheets service using OAuth authentication"""
import gspread
from typing import List, Dict
import logging
from app.config import settings
from app.models.transaction import RawTransaction, EnrichedTransaction
from app.models.classification import TaxReference
from app.services.oauth_service import OAuthService
logger = logging.getLogger(__name__)
class SheetsService:
"""Service for Google Sheets operations using OAuth"""
def __init__(self):
"""Initialize Google Sheets client with OAuth"""
try:
oauth_service = OAuthService()
credentials = oauth_service.get_credentials()
self.client = gspread.authorize(credentials)
self.spreadsheet = self.client.open_by_key(settings.google_sheets_spreadsheet_id)
logger.info("Google Sheets client initialized successfully with OAuth")
except Exception as e:
logger.error(f"Failed to initialize Google Sheets client: {e}")
raise
def read_raw_transactions(self) -> List[RawTransaction]:
"""Read raw transactions from Google Sheets"""
try:
sheet = self.spreadsheet.worksheet(settings.raw_transactions_sheet_name)
records = sheet.get_all_records()
transactions = []
for record in records:
try:
transaction = RawTransaction(
transaction_id=str(record.get('transaction_id', '')),
transaction_date=record.get('transaction_date') or None,
description=str(record.get('description', '')),
amount=float(record.get('amount', 0)),
cost_center=record.get('cost_center') or None,
location=record.get('location') or None,
vendor_name=record.get('vendor_name') or None,
tax_code=record.get('tax_code') or None,
tax_amount=float(record['tax_amount']) if record.get('tax_amount') else None
)
transactions.append(transaction)
except Exception as e:
logger.warning(f"Failed to parse transaction {record.get('transaction_id')}: {e}")
continue
logger.info(f"Read {len(transactions)} transactions from sheet")
return transactions
except Exception as e:
logger.error(f"Failed to read raw transactions: {e}")
raise
def read_tax_reference(self) -> Dict[str, TaxReference]:
"""Read tax reference data and return as dictionary keyed by location"""
try:
sheet = self.spreadsheet.worksheet(settings.tax_reference_sheet_name)
records = sheet.get_all_records()
reference_data = {}
for record in records:
try:
location = str(record.get('location', '')).upper().strip()
if not location:
continue
ref = TaxReference(
location=location,
jurisdiction_name=record.get('jurisdiction_name') or None,
expected_tax_rate=str(record.get('expected_tax_rate', '0%')),
jurisdiction_code=record.get('jurisdiction_code') or None,
applies_to=record.get('applies_to') or None,
effective_date=record.get('effective_date') or None,
notes=record.get('notes') or None
)
reference_data[location] = ref
except Exception as e:
logger.warning(f"Failed to parse tax reference {record.get('location')}: {e}")
continue
logger.info(f"Read {len(reference_data)} tax reference entries")
return reference_data
except Exception as e:
logger.error(f"Failed to read tax reference: {e}")
raise
def write_clean_transactions(self, transactions: List[EnrichedTransaction]) -> None:
"""Write validated transactions to clean output sheet"""
try:
sheet = self.spreadsheet.worksheet(settings.clean_output_sheet_name)
# Prepare headers if sheet is empty
if len(sheet.get_all_values()) <= 1:
headers = [
'transaction_id', 'description', 'amount', 'location',
'ai_classification', 'suggested_tax_rate', 'validation_status',
'confidence', 'ai_rationale', 'processing_timestamp'
]
sheet.append_row(headers)
# Prepare rows
rows = []
for tx in transactions:
row = [
tx.transaction_id,
tx.description,
tx.amount,
tx.location,
tx.classification or '',
tx.suggested_tax_rate or '',
tx.validation_status or '',
tx.confidence or '',
tx.rationale or '',
tx.processing_timestamp
]
rows.append(row)
# Append all rows at once
if rows:
sheet.append_rows(rows)
logger.info(f"Wrote {len(rows)} clean transactions to sheet")
except Exception as e:
logger.error(f"Failed to write clean transactions: {e}")
raise
def write_review_queue(self, transactions: List[EnrichedTransaction]) -> None:
"""Write flagged transactions to review queue sheet"""
try:
sheet = self.spreadsheet.worksheet(settings.review_queue_sheet_name)
# Prepare headers if sheet is empty
if len(sheet.get_all_values()) <= 1:
headers = [
'transaction_id', 'description', 'amount', 'location',
'ai_classification', 'suggested_tax_rate', 'confidence',
'anomaly_type', 'anomaly_reason', 'ai_rationale',
'validation_status', 'processing_timestamp'
]
sheet.append_row(headers)
# Prepare rows
rows = []
for tx in transactions:
anomaly_types_str = ', '.join(tx.anomaly_types) if tx.anomaly_types else ''
row = [
tx.transaction_id,
tx.description,
tx.amount,
tx.location,
tx.classification or '',
tx.suggested_tax_rate or '',
tx.confidence or '',
anomaly_types_str,
f"Anomaly count: {tx.anomaly_count}",
tx.rationale or '',
tx.validation_status or '',
tx.processing_timestamp
]
rows.append(row)
# Append all rows at once
if rows:
sheet.append_rows(rows)
logger.info(f"Wrote {len(rows)} transactions to review queue")
except Exception as e:
logger.error(f"Failed to write review queue: {e}")
raise