from app.db.models import MerchantCache # In-memory dictionary for instant lookups _cache = {} def load_cache_from_db(db): global _cache _cache.clear() # Clear it in case of reload rows = db.query(MerchantCache).all() for row in rows: cache_key = f"{row.user_id}_{row.merchant_key}" _cache[cache_key] = { "clean_name": row.clean_name, "category": row.category, "irs_line": row.irs_line, "confidence": row.confidence, "source": row.source, } print(f"📦 Loaded {len(_cache)} user-specific merchants from Supabase into memory.") def get_from_cache(user_id: str, merchant_key: str): """ Check if WE (this specific company) already know this merchant. """ cache_key = f"{user_id}_{merchant_key}" return _cache.get(cache_key, None) def save_to_cache(user_id, merchant_key, clean_name, category, irs_line, confidence, source, db): """ Saves a new merchant to BOTH memory and Supabase for this specific user. """ cache_key = f"{user_id}_{merchant_key}" # 1. Save to in-memory dict (instant future lookups) _cache[cache_key] = { "clean_name": clean_name, "category": category, "irs_line": irs_line, "confidence": confidence, "source": source, } # 2. Save to Supabase (survives server restarts) db_record = db.query(MerchantCache).filter( MerchantCache.merchant_key == merchant_key, MerchantCache.user_id == user_id ).first() if db_record: # Update existing record db_record.clean_name = clean_name db_record.category = category db_record.irs_line = irs_line db_record.confidence = confidence db_record.source = source else: # Create new record db_record = MerchantCache( user_id=user_id, merchant_key=merchant_key, clean_name=clean_name, category=category, irs_line=irs_line, confidence=confidence, source=source, ) db.add(db_record) db.commit() print(f" 💾 Saved [{merchant_key}] to Company Cache (memory + Supabase)")