File size: 14,657 Bytes
4156f51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import os
import pickle
import logging
from typing import Optional
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

logger = logging.getLogger(__name__)

SCOPES = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.readonly"
]

_PROJECT_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "..", "..", "..")
)
_CREDENTIALS_PATH = os.path.join(_PROJECT_ROOT, "credentials.json")
_TOKEN_PATH = os.path.join(_PROJECT_ROOT, "token_sheets.pkl")
_LEDGER_ID_PATH = os.path.join(_PROJECT_ROOT, ".ledger_id")

# We will use these columns for the ledger
HEADERS = ["Date", "Vendor", "Category", "Total", "Payment Method", "Order ID", "Notes", "Message ID"]


def get_sheets_service():
    """Authenticate and return the Google Sheets API service."""
    import base64
    # Reconstruct files from Hugging Face Secrets if available
    # Support both naming conventions: SHEETS_TOKEN_B64 and TOKEN_SHEETS_B64
    sheets_token_b64 = os.environ.get("SHEETS_TOKEN_B64") or os.environ.get("TOKEN_SHEETS_B64")
    if sheets_token_b64 and not os.path.exists(_TOKEN_PATH):
        try:
            with open(_TOKEN_PATH, "wb") as f:
                f.write(base64.b64decode(sheets_token_b64))
            logger.info(f"[SHEETS] Reconstructed token_sheets.pkl from HF Secret")
        except Exception as e:
            logger.error(f"Failed to decode Sheets token secret: {e}")
            
    gcp_creds_b64 = os.environ.get("GCP_CREDENTIALS_B64")
    if gcp_creds_b64 and not os.path.exists(_CREDENTIALS_PATH):
        try:
            with open(_CREDENTIALS_PATH, "wb") as f:
                f.write(base64.b64decode(gcp_creds_b64))
            logger.info(f"[SHEETS] Reconstructed credentials.json from HF Secret")
        except Exception as e:
            logger.error(f"Failed to decode GCP_CREDENTIALS_B64: {e}")

    creds = None
    if os.path.exists(_TOKEN_PATH):
        with open(_TOKEN_PATH, "rb") as f:
            creds = pickle.load(f)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
            except Exception:
                os.remove(_TOKEN_PATH)
                creds = None

        if not creds:
            if not os.path.exists(_CREDENTIALS_PATH):
                raise FileNotFoundError(
                    f"Missing {_CREDENTIALS_PATH}. Please download it from Google Cloud Console."
                )
            flow = InstalledAppFlow.from_client_secrets_file(_CREDENTIALS_PATH, SCOPES)
            creds = flow.run_local_server(port=0)

        with open(_TOKEN_PATH, "wb") as f:
            pickle.dump(creds, f)

    return build("sheets", "v4", credentials=creds)


def find_spreadsheet_by_name(service, name: str) -> Optional[str]:
    """Search for a spreadsheet by name and return its ID."""
    try:
        from googleapiclient.discovery import build
        drive_service = build('drive', 'v3', credentials=service._http.credentials)
        # Search for both native sheets and also handle dummy/xlsx naming
        query = f"mimeType='application/vnd.google-apps.spreadsheet' and name contains '{name}' and trashed = false"
        results = drive_service.files().list(q=query, fields="files(id, name)").execute()
        files = results.get('files', [])
        if files:
            return files[0]['id']
    except Exception as e:
        logger.warning(f"[SHEETS] Auto-discovery failed: {e}")
    return None


def get_or_create_ledger(service) -> str:
    """Return the existing ledger ID or create a new one with headers."""
    if os.environ.get("SHEETS_LEDGER_ID"):
        return os.environ.get("SHEETS_LEDGER_ID")
        
    if os.path.exists(_LEDGER_ID_PATH):
        with open(_LEDGER_ID_PATH, "r") as f:
            spreadsheet_id = f.read().strip()
            if spreadsheet_id:
                return spreadsheet_id

    # Auto-discovery attempt before creating new
    discovered_id = find_spreadsheet_by_name(service, "Trace_Financial_Audit_Dummy_Sheet")
    if not discovered_id:
        discovered_id = find_spreadsheet_by_name(service, "Trace Financial Ledger")
    
    if discovered_id:
        with open(_LEDGER_ID_PATH, "w") as f:
            f.write(discovered_id)
        return discovered_id

    # Create a new spreadsheet
    spreadsheet = {
        'properties': {
            'title': 'Trace Financial Ledger'
        }
    }
    spreadsheet = service.spreadsheets().create(body=spreadsheet, fields='spreadsheetId').execute()
    spreadsheet_id = spreadsheet.get('spreadsheetId')
    
    # Save ID
    with open(_LEDGER_ID_PATH, "w") as f:
        f.write(spreadsheet_id)
        
    # Write headers
    body = {
        'values': [HEADERS]
    }
    service.spreadsheets().values().update(
        spreadsheetId=spreadsheet_id,
        range=f"A1:{chr(64 + len(HEADERS))}1",
        valueInputOption="RAW",
        body=body
    ).execute()
    
    # Optional: Make headers bold
    requests = [
        {
            "repeatCell": {
                "range": {
                    "sheetId": 0,
                    "startRowIndex": 0,
                    "endRowIndex": 1,
                    "startColumnIndex": 0,
                    "endColumnIndex": len(HEADERS)
                },
                "cell": {
                    "userEnteredFormat": {
                        "textFormat": {
                            "bold": True
                        }
                    }
                },
                "fields": "userEnteredFormat.textFormat.bold"
            }
        }
    ]
    service.spreadsheets().batchUpdate(
        spreadsheetId=spreadsheet_id,
        body={'requests': requests}
    ).execute()
    
    logger.info(f"[SHEETS] Created new ledger. ID: {spreadsheet_id}")
    return spreadsheet_id


def append_transactions(transactions: list[dict]) -> str:
    """
    Append new transactions to the Google Sheet ledger with deduplication.
    We return the URL of the Google Sheet.
    """
    if not transactions:
        return ""
        
    try:
        service = get_sheets_service()
        spreadsheet_id = get_or_create_ledger(service)
        
        # ── Step 1: Fetch existing Message IDs from all tabs to prevent duplicates ────────
        spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
        sheets = spreadsheet.get('sheets', [])
        
        existing_ids = set()
        for sheet in sheets:
            sheet_title = sheet.get('properties', {}).get('title')
            try:
                result = service.spreadsheets().values().get(
                    spreadsheetId=spreadsheet_id,
                    range=f"'{sheet_title}'!H:H" # Message ID is column H
                ).execute()
                for row in result.get('values', []):
                    if row:
                        existing_ids.add(row[0])
            except Exception as e:
                logger.warning(f"[SHEETS] Failed to fetch IDs from tab '{sheet_title}': {e}")
        
        # ── Step 2: Prepare new rows ────────────────────────────────────────
        rows = []
        for t in transactions:
            msg_id = t.get("id")
            if not msg_id or msg_id in existing_ids:
                continue # Skip duplicates or missing IDs
                
            import re
            amount_str = re.sub(r'[^\d.]', '', t.get("total") or "")
            amount = float(amount_str) if amount_str else 0.0
            
            # If no amount was found AND no useful metadata exists, skip
            has_useful_metadata = (
                t.get("vendor", "").lower() not in ("", "unknown")
                or t.get("subject", "").strip()
                or t.get("body_preview", "").strip()
            )
            if amount == 0 and not has_useful_metadata:
                continue
            
            # Extract notes from details
            details = []
            if t.get("details"):
                for k, v in t["details"].items():
                    if isinstance(v, list):
                        details.append(f"{k}: {len(v)} items")
                    else:
                        details.append(f"{k}: {v}")
            # Fallback: include subject/body preview for unparsed entries
            if not details:
                subj = t.get("subject", "").strip()
                if subj:
                    details.append(subj[:120])
                elif t.get("body_preview", "").strip():
                    details.append(t["body_preview"][:120])
            notes_str = " | ".join(details)
            
            row = [
                t.get("date", ""),
                t.get("vendor", ""),
                t.get("category", ""),
                amount,
                t.get("payment_method", "Unknown"),
                t.get("order_id", ""),
                notes_str,
                msg_id
            ]
            rows.append(row)
            
        if not rows:
            logger.info("[SHEETS] No new transactions to append.")
            return f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}"

        body = {
            'values': rows
        }
        result = service.spreadsheets().values().append(
            spreadsheetId=spreadsheet_id,
            range="A:H",
            valueInputOption="USER_ENTERED",
            insertDataOption="INSERT_ROWS",
            body=body
        ).execute()
        
        logger.info(f"[SHEETS] Appended {result.get('updates', {}).get('updatedRows', 0)} new rows.")
        return f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}"
        
    except Exception as e:
        logger.error(f"[SHEETS] Error appending to Sheets: {e}")
        return ""


def fetch_and_summarize() -> dict:
    """
    Fetch all rows from the Google Sheet and generate a summary.
    """
    try:
        service = get_sheets_service()
        spreadsheet_id = get_or_create_ledger(service)
        
        # Log metadata to help debugging
        spreadsheet = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
        title = spreadsheet.get('properties', {}).get('title')
        sheets = spreadsheet.get('sheets', [])
        logger.info(f"[SHEETS] Fetching from '{title}' (ID: {spreadsheet_id}) across {len(sheets)} tabs")
        
        all_rows = []
        for sheet in sheets:
            sheet_title = sheet.get('properties', {}).get('title')
            try:
                # Read the full range for each sheet
                result = service.spreadsheets().values().get(
                    spreadsheetId=spreadsheet_id,
                    range=f"'{sheet_title}'!A:H"
                ).execute()
                
                values = result.get('values', [])
                if not values:
                    continue
                    
                # Basic header detection: skip if first row, first column says "Date"
                if len(values[0]) > 0 and str(values[0][0]).strip().lower() == "date":
                    all_rows.extend(values[1:])
                else:
                    all_rows.extend(values)
            except Exception as e:
                logger.warning(f"[SHEETS] Failed to fetch tab '{sheet_title}': {e}")
                
        logger.info(f"[SHEETS] Found {len(all_rows)} total transaction rows across all tabs.")
        if not all_rows:
            logger.info("[SHEETS] Ledger is empty.")
            return {
                "total_spend": 0.0,
                "count": 0,
                "by_category": {},
                "by_vendor": {}
            }
            
        rows = all_rows
        
        total_spend = 0.0
        by_category = {}
        by_vendor = {}
        count = 0
        transactions = [] # Added to return the actual data
        
        import re
        for row in rows:
            # Basic validation: must have at least Date, Vendor, Category, Total
            if len(row) < 4:
                continue
                
            vendor = row[1] or "Unknown"
            category = row[2] or "unknown"
            
            # Extract amount from Column D (index 3)
            amount_val = row[3]
            if not amount_val:
                continue
                
            try:
                # Remove everything except digits and decimal point
                cleaned_amt = re.sub(r'[^\d.]', '', str(amount_val))
                if not cleaned_amt:
                    amount = 0.0
                else:
                    amount = float(cleaned_amt)
            except (ValueError, IndexError) as e:
                logger.warning(f"[SHEETS] Failed to parse amount '{amount_val}': {e}")
                amount = 0.0
                
            # Get Message ID from Column H (index 7)
            msg_id = row[7] if len(row) > 7 else None
                
            if amount > 0:
                total_spend += amount
                by_category[category] = by_category.get(category, 0) + amount
                by_vendor[vendor] = by_vendor.get(vendor, 0) + amount
                count += 1
                
                # Add to transactions list
                transactions.append({
                    "date": row[0],
                    "vendor": vendor,
                    "category": category,
                    "total": str(amount),
                    "payment_method": row[4] if len(row) > 4 else "Unknown",
                    "order_id": row[5] if len(row) > 5 else "",
                    "notes": row[6] if len(row) > 6 else "",
                    "id": msg_id,
                    "_source": "sheets"
                })
            
        summary = {
            "total_spend": round(total_spend, 2),
            "count": count,
            "by_category": {k: round(v, 2) for k, v in sorted(by_category.items(), key=lambda x: -x[1])},
            "by_vendor": {k: round(v, 2) for k, v in sorted(by_vendor.items(), key=lambda x: -x[1])},
            "transactions": transactions, # Include the list
            "sheet_url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}"
        }
        logger.info(f"[SHEETS] Fetched summary: β‚Ή{total_spend:,.2f} across {count} items.")
        return summary
        
    except Exception as e:
        logger.error(f"[SHEETS] Error fetching from Sheets: {e}")
        return {"error": str(e), "total_spend": 0.0}