Update app/db.py
Browse files
app/db.py
CHANGED
|
@@ -6,6 +6,7 @@ from typing import Dict, Iterable, List, Optional, Set
|
|
| 6 |
|
| 7 |
from bson import ObjectId
|
| 8 |
from dateutil.relativedelta import relativedelta
|
|
|
|
| 9 |
from pymongo import MongoClient
|
| 10 |
|
| 11 |
from .schemas import Transaction
|
|
@@ -108,3 +109,154 @@ def fetch_recent_transactions(user_id: str, months: int = 3) -> List[Transaction
|
|
| 108 |
logger.info("Fetched %d transactions from MongoDB for user_id=%s", len(transactions), user_id)
|
| 109 |
return transactions
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
from bson import ObjectId
|
| 8 |
from dateutil.relativedelta import relativedelta
|
| 9 |
+
from dateutil.tz import gettz
|
| 10 |
from pymongo import MongoClient
|
| 11 |
|
| 12 |
from .schemas import Transaction
|
|
|
|
| 109 |
logger.info("Fetched %d transactions from MongoDB for user_id=%s", len(transactions), user_id)
|
| 110 |
return transactions
|
| 111 |
|
| 112 |
+
|
| 113 |
+
def log_api_hit(user_id: Optional[str], status: str, response_time: float) -> None:
|
| 114 |
+
"""
|
| 115 |
+
Log API hit to MongoDB with the specified format.
|
| 116 |
+
Stores logs in 'expense' database, 'api_logs' collection (wallet sync > expense > api_logs).
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
user_id: Optional user identifier
|
| 120 |
+
status: Status of the API call ("success" or "error")
|
| 121 |
+
response_time: Response time in seconds
|
| 122 |
+
"""
|
| 123 |
+
try:
|
| 124 |
+
client = get_mongo_client()
|
| 125 |
+
# Use 'expense' database for API logs (same as transactions)
|
| 126 |
+
default_db = client.get_default_database()
|
| 127 |
+
db = default_db if default_db is not None else client["expense"]
|
| 128 |
+
collection = db["api_logs"]
|
| 129 |
+
|
| 130 |
+
# Get IST timezone
|
| 131 |
+
ist_tz = gettz("Asia/Kolkata")
|
| 132 |
+
ist_now = datetime.now(ist_tz)
|
| 133 |
+
|
| 134 |
+
# Format date as "DD-MM-YYYY HH:MM:SS:IST"
|
| 135 |
+
formatted_date = ist_now.strftime("%d-%m-%Y %H:%M:%S:IST")
|
| 136 |
+
|
| 137 |
+
log_doc = {
|
| 138 |
+
"name": "AI_FINANCIAL_INSIGHTS",
|
| 139 |
+
"status": status,
|
| 140 |
+
"date": formatted_date,
|
| 141 |
+
"response_time": round(response_time, 3),
|
| 142 |
+
"user_id": user_id,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
collection.insert_one(log_doc)
|
| 146 |
+
logger.debug("Logged API hit to MongoDB: user_id=%s, status=%s, response_time=%.3f", user_id, status, response_time)
|
| 147 |
+
except Exception as exc: # noqa: BLE001
|
| 148 |
+
# Don't fail the API if logging fails
|
| 149 |
+
logger.warning("Failed to log API hit to MongoDB: %s", exc)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# import logging
|
| 154 |
+
# import os
|
| 155 |
+
# from datetime import datetime
|
| 156 |
+
# from functools import lru_cache
|
| 157 |
+
# from typing import Dict, Iterable, List, Optional, Set
|
| 158 |
+
|
| 159 |
+
# from bson import ObjectId
|
| 160 |
+
# from dateutil.relativedelta import relativedelta
|
| 161 |
+
# from pymongo import MongoClient
|
| 162 |
+
|
| 163 |
+
# from .schemas import Transaction
|
| 164 |
+
|
| 165 |
+
# logger = logging.getLogger(__name__)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# @lru_cache(maxsize=1)
|
| 169 |
+
# def get_mongo_client() -> MongoClient:
|
| 170 |
+
# """Return a cached MongoClient instance."""
|
| 171 |
+
# uri = os.getenv("MONGODB_URI")
|
| 172 |
+
# if not uri:
|
| 173 |
+
# raise RuntimeError("MONGODB_URI environment variable is required for MongoDB access.")
|
| 174 |
+
# logger.info("Connecting to MongoDB host from URI")
|
| 175 |
+
# return MongoClient(uri)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# def _resolve_category_titles(category_ids: Set[ObjectId], db) -> Dict[ObjectId, str]:
|
| 179 |
+
# if not category_ids:
|
| 180 |
+
# return {}
|
| 181 |
+
# cursor = db["categories"].find({"_id": {"$in": list(category_ids)}}, {"title": 1})
|
| 182 |
+
# return {doc["_id"]: doc.get("title", "Uncategorized") for doc in cursor}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# def _resolve_currency_codes(currency_ids: Set[ObjectId], db) -> Dict[ObjectId, str]:
|
| 186 |
+
# if not currency_ids:
|
| 187 |
+
# return {}
|
| 188 |
+
# cursor = db["currencies"].find({"_id": {"$in": list(currency_ids)}}, {"code": 1})
|
| 189 |
+
# return {doc["_id"]: doc.get("code", "USD") for doc in cursor}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# def _safe_object_id(identifier: str) -> ObjectId:
|
| 193 |
+
# try:
|
| 194 |
+
# return ObjectId(identifier)
|
| 195 |
+
# except Exception as exc: # noqa: BLE001
|
| 196 |
+
# raise ValueError(f"Invalid Mongo ObjectId: {identifier}") from exc
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# def fetch_recent_transactions(user_id: str, months: int = 3) -> List[Transaction]:
|
| 200 |
+
# """
|
| 201 |
+
# Fetch up to `months` of recent expense transactions for a user.
|
| 202 |
+
|
| 203 |
+
# Returns an empty list if no data exists (new user scenario).
|
| 204 |
+
# """
|
| 205 |
+
# if months <= 0:
|
| 206 |
+
# return []
|
| 207 |
+
|
| 208 |
+
# client = get_mongo_client()
|
| 209 |
+
# default_db = client.get_default_database()
|
| 210 |
+
# db = default_db if default_db is not None else client["expense"]
|
| 211 |
+
# collection = db["transactions"]
|
| 212 |
+
|
| 213 |
+
# user_obj_id = _safe_object_id(user_id)
|
| 214 |
+
# start_date = datetime.utcnow() - relativedelta(months=months)
|
| 215 |
+
|
| 216 |
+
# query = {
|
| 217 |
+
# "user": user_obj_id,
|
| 218 |
+
# "date": {"$gte": start_date},
|
| 219 |
+
# "type": {"$in": ["EXPENSE", "TRANSFER"]},
|
| 220 |
+
# }
|
| 221 |
+
|
| 222 |
+
# projection = {
|
| 223 |
+
# "date": 1,
|
| 224 |
+
# "amount": 1,
|
| 225 |
+
# "currency": 1,
|
| 226 |
+
# "category": 1,
|
| 227 |
+
# }
|
| 228 |
+
# docs = list(collection.find(query, projection).sort("date", -1))
|
| 229 |
+
# if not docs:
|
| 230 |
+
# logger.info("No MongoDB transactions found for user_id=%s", user_id)
|
| 231 |
+
# return []
|
| 232 |
+
|
| 233 |
+
# category_ids = {doc["category"] for doc in docs if doc.get("category")}
|
| 234 |
+
# currency_ids = {doc["currency"] for doc in docs if doc.get("currency")}
|
| 235 |
+
|
| 236 |
+
# category_map = _resolve_category_titles(category_ids, db)
|
| 237 |
+
# currency_map = _resolve_currency_codes(currency_ids, db)
|
| 238 |
+
|
| 239 |
+
# transactions: List[Transaction] = []
|
| 240 |
+
# for doc in docs:
|
| 241 |
+
# date_value: Optional[datetime] = doc.get("date")
|
| 242 |
+
# if not date_value:
|
| 243 |
+
# continue
|
| 244 |
+
|
| 245 |
+
# category_name = category_map.get(doc.get("category"), "Uncategorized")
|
| 246 |
+
# currency_code = currency_map.get(doc.get("currency"), "USD")
|
| 247 |
+
|
| 248 |
+
# try:
|
| 249 |
+
# transactions.append(
|
| 250 |
+
# Transaction(
|
| 251 |
+
# timestamp=date_value,
|
| 252 |
+
# category=category_name,
|
| 253 |
+
# amount=float(doc.get("amount", 0)),
|
| 254 |
+
# currency=currency_code,
|
| 255 |
+
# )
|
| 256 |
+
# )
|
| 257 |
+
# except Exception as exc: # noqa: BLE001
|
| 258 |
+
# logger.warning("Skipping malformed transaction doc=%s error=%s", doc.get("_id"), exc)
|
| 259 |
+
|
| 260 |
+
# logger.info("Fetched %d transactions from MongoDB for user_id=%s", len(transactions), user_id)
|
| 261 |
+
# return transactions
|
| 262 |
+
|