diff --git a/.gitignore b/.gitignore index db7105648406e4a3746e99bfcc925b9b2748d55e..1e9e58c553e90ff68136db7d66b3d09faad4682f 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,5 @@ logs/ .vscode/ .idea/ venv/ +backend/firebase-service-account.json +backend/*firebase-adminsdk*.json diff --git a/Dockerfile b/Dockerfile index 3881d36db59ec0b2664edc33a0690649533558a2..a3ff0090734918103c849b6d9d553b15af189508 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,12 +3,24 @@ FROM node:18-alpine AS frontend-builder WORKDIR /app/frontend COPY frontend/package*.json ./ -RUN npm ci +RUN npm install COPY frontend/ . ARG VITE_API_URL=/api ENV VITE_API_URL=${VITE_API_URL} +ARG VITE_FIREBASE_API_KEY= +ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY} +ARG VITE_FIREBASE_AUTH_DOMAIN= +ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN} +ARG VITE_FIREBASE_PROJECT_ID= +ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID} +ARG VITE_FIREBASE_STORAGE_BUCKET= +ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET} +ARG VITE_FIREBASE_MESSAGING_SENDER_ID= +ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID} +ARG VITE_FIREBASE_APP_ID= +ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID} RUN npm run build # ============================================ @@ -22,13 +34,13 @@ WORKDIR /app # Install Nginx RUN apt-get update && apt-get install -y --no-install-recommends \ - nginx \ - && rm -rf /var/lib/apt/lists/* + nginx \ + && rm -rf /var/lib/apt/lists/* # Copy and install Python dependencies COPY backend/requirements.txt ./ RUN pip install --no-cache-dir --upgrade pip && \ - pip install --no-cache-dir -r requirements.txt + pip install --no-cache-dir -r requirements.txt # Copy backend code COPY backend/ ./backend/ @@ -43,7 +55,7 @@ COPY nginx-huggingface.conf /etc/nginx/conf.d/default.conf COPY docker-entrypoint.sh /app/ RUN chmod +x /app/docker-entrypoint.sh -# Create data directory for SQLite +# Create data directory for SQLite fallback RUN mkdir -p /app/data EXPOSE 7860 diff --git a/Dockerfile.huggingface b/Dockerfile.huggingface index 3881d36db59ec0b2664edc33a0690649533558a2..891d48632b2c67a20b4542fd105f61b81f75ee9a 100644 --- a/Dockerfile.huggingface +++ b/Dockerfile.huggingface @@ -3,12 +3,24 @@ FROM node:18-alpine AS frontend-builder WORKDIR /app/frontend COPY frontend/package*.json ./ -RUN npm ci +RUN npm install COPY frontend/ . ARG VITE_API_URL=/api ENV VITE_API_URL=${VITE_API_URL} +ARG VITE_FIREBASE_API_KEY= +ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY} +ARG VITE_FIREBASE_AUTH_DOMAIN= +ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN} +ARG VITE_FIREBASE_PROJECT_ID= +ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID} +ARG VITE_FIREBASE_STORAGE_BUCKET= +ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET} +ARG VITE_FIREBASE_MESSAGING_SENDER_ID= +ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID} +ARG VITE_FIREBASE_APP_ID= +ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID} RUN npm run build # ============================================ diff --git a/PWA_INSTALLATION_GUIDE.md b/PWA_INSTALLATION_GUIDE.md new file mode 100644 index 0000000000000000000000000000000000000000..c3bf7b2792dce9337dbe93972bf5e7e3815857a7 --- /dev/null +++ b/PWA_INSTALLATION_GUIDE.md @@ -0,0 +1,128 @@ +# PWA Installation Guide - SSC (Sculpt Soft Cricketers) + +## What is a PWA? + +A **Progressive Web App (PWA)** is a web application that can be installed on your device like a native app. It provides: +- ✅ Fast loading times +- ✅ Offline functionality +- ✅ Push notifications support +- ✅ Home screen icon +- ✅ Full-screen experience (no browser bar) + +--- + +## How to Install SSC App + +### **On Android (Chrome, Edge, Opera)** +1. **Look for the install banner** at the bottom of the screen + - Or tap the menu icon (⋮) in the top-right corner + +2. **Tap "Install" or "Install app"** + - Confirm any prompts + +3. **The app will be added to your home screen** + - You can now open it like any other app + +### **On iOS (Safari)** +1. **Tap the Share button** (square with arrow ↗️) + +2. **Scroll down and tap "Add to Home Screen"** + +3. **Enter a name** (or keep "SSC") + +4. **Tap "Add"** to confirm + +5. **The app will appear on your home screen** + - Open it anytime like a regular app + +### **On Desktop/Windows (Chrome, Edge)** +1. **Look for the install icon** in the address bar (usually on the right side) + - Or use the menu → "Install SSC" + +2. **Click the icon to install** + +3. **Confirm the installation** + +4. **The app will launch in a window** without the browser bar + +### **On macOS (Safari, Chrome)** +1. **Same as Desktop Windows steps above** + - Or use Safari menu → File → "Add to Dock" (if available) + +--- + +## Features After Installation + +Once installed, you get: + +### **✨ Better Performance** +- Faster loading from cache +- Works instantly on return visits + +### **📱 App Experience** +- No browser address bar +- Full screen experience +- Feels like a native app + +### **🌐 Offline Support** +- View previously loaded matches +- Queue actions while offline +- Auto-sync when reconnected + +### **🔔 Quick Access** +- Home screen icon +- App switcher access +- Faster than bookmarks + +--- + +## Troubleshooting + +### **"Install" option not showing?** +- **Android**: Make sure you're using Chrome, Edge, or Opera +- **iOS**: Must use Safari; Chrome doesn't support PWA installation on iOS +- **Desktop**: Try using Chrome or Edge instead of Firefox + +### **App not working offline?** +- Some features require internet (live scoring, sync) +- Basic match viewing should work offline +- Reload the app to force cache update + +### **Want to remove the app?** +- **Android**: Long-press the app icon → "Uninstall" +- **iOS**: Long-press the app icon → "Remove App" → "Remove from Home Screen" +- **Desktop**: Remove like any other application from your system + +--- + +## How PWA Works + +The app uses: +- **Service Worker**: Caches app files for faster loading +- **Manifest**: Defines app metadata (name, icons, colors) +- **HTTPS**: Secure connection for safe installation + +All your data is stored locally in your browser and synced with our servers when online. + +--- + +## Security & Privacy + +- ✅ All data encrypted in transit (HTTPS) +- ✅ Local storage is separate per device +- ✅ No tracking or ads +- ✅ Same privacy policy as web version + +--- + +## Questions? + +For technical issues: +1. **Clear app cache**: Settings → Apps → SSC → Storage → Clear Cache +2. **Reinstall**: Uninstall and install again from the address bar +3. **Update**: The app auto-updates in the background +4. **Fallback**: Visit the web version at https://ssc.app + +--- + +**Enjoy SSC in app form!** 🏏 diff --git a/PWA_SETUP_CHECK.sh b/PWA_SETUP_CHECK.sh new file mode 100644 index 0000000000000000000000000000000000000000..eba2d3f2efec5aea8ef6a113198bf7d658bc23ae --- /dev/null +++ b/PWA_SETUP_CHECK.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# PWA Checklist - Verify Installation + +echo "==========================================" +echo "SSC PWA Setup Verification" +echo "==========================================" +echo "" + +# Check manifest.json +echo "✓ Checking manifest.json..." +if [ -f "frontend/public/manifest.json" ]; then + echo " ✅ manifest.json exists" + if grep -q '"display": "standalone"' frontend/public/manifest.json; then + echo " ✅ display mode set to 'standalone'" + fi + if grep -q '"icons"' frontend/public/manifest.json; then + echo " ✅ icons configured" + fi +else + echo " ❌ manifest.json not found" +fi +echo "" + +# Check service-worker.js +echo "✓ Checking service-worker.js..." +if [ -f "frontend/public/service-worker.js" ]; then + echo " ✅ service-worker.js exists" + if grep -q "CACHE_NAME" frontend/public/service-worker.js; then + echo " ✅ caching strategy implemented" + fi + if grep -q "beforeinstallprompt" frontend/public/service-worker.js; then + echo " ✅ install prompt handler ready" + fi +else + echo " ❌ service-worker.js not found" +fi +echo "" + +# Check index.html +echo "✓ Checking index.html..." +if [ -f "frontend/index.html" ]; then + echo " ✅ index.html exists" + if grep -q 'manifest.json' frontend/index.html; then + echo " ✅ manifest.json link present" + fi + if grep -q 'meta name="theme-color"' frontend/index.html; then + echo " ✅ theme-color meta tag set" + fi + if grep -q 'apple-mobile-web-app-capable' frontend/index.html; then + echo " ✅ iOS PWA support configured" + fi +else + echo " ❌ index.html not found" +fi +echo "" + +# Check main.jsx service worker registration +echo "✓ Checking service worker registration..." +if grep -q "navigator.serviceWorker.register" frontend/src/main.jsx; then + echo " ✅ Service worker registration code present" +fi +if grep -q "beforeinstallprompt" frontend/src/main.jsx; then + echo " ✅ Install prompt handler in main.jsx" +fi +echo "" + +# Check PWA Install Guide component +echo "✓ Checking PWA components..." +if [ -f "frontend/src/components/PWAInstallGuide.jsx" ]; then + echo " ✅ PWAInstallGuide.jsx component exists" +fi +if grep -q "PWAInstallGuide" frontend/src/App.jsx; then + echo " ✅ PWAInstallGuide imported in App.jsx" +fi +echo "" + +echo "==========================================" +echo "PWA Setup Complete! ✅" +echo "==========================================" +echo "" +echo "Next steps:" +echo "1. Run: npm run dev" +echo "2. Visit: http://localhost:3000" +echo "3. Look for install prompt/button" +echo "4. On Android: Install from browser menu" +echo "5. On iOS: Use Share → Add to Home Screen" +echo "" diff --git a/backend/.env.example b/backend/.env.example index 87066bb570eee6113e658e9b330a30d81811232f..bd6ee98fbdeafc55b593eab210865b5de9d12322 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,4 +1,3 @@ -DATABASE_URL=sqlite:////app/data/ssc.db SECRET_KEY=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 @@ -14,3 +13,8 @@ API_TITLE=SSC API API_VERSION=1.0.0 DEBUG=False CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000 +FIREBASE_AUTH_ENABLED=True +FIREBASE_PROJECT_ID= +FIREBASE_WEB_API_KEY= +FIREBASE_SERVICE_ACCOUNT_PATH=./firebase-service-account.json +FIREBASE_SERVICE_ACCOUNT_JSON= diff --git a/backend/app/config.py b/backend/app/config.py index e1164aac705fc6947e0e3004220db49917814c80..f3f81454f363886f1aea51bcc7dfe7dc96f45c4d 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -24,9 +24,6 @@ def env_first_bool(keys: list[str], default: bool) -> bool: class Settings(BaseSettings): - # Database - DATABASE_URL: str = env_first(["DATABASE_URL", "DATABASEURL"], "sqlite:///./ssc.db") - # Security SECRET_KEY: str = env_first(["SECRET_KEY", "SECRETKEY"], "dev-secret-key-change-in-production") ALGORITHM: str = env_first(["ALGORITHM"], "HS256") @@ -63,6 +60,22 @@ class Settings(BaseSettings): "http://localhost:3000,http://127.0.0.1:3000", ) + # Firebase Auth integration + FIREBASE_AUTH_ENABLED: bool = env_first_bool( + ["FIREBASE_AUTH_ENABLED", "FIREBASEAUTHENABLED"], + False, + ) + FIREBASE_PROJECT_ID: str = env_first(["FIREBASE_PROJECT_ID", "FIREBASEPROJECTID"], "") + FIREBASE_WEB_API_KEY: str = env_first(["FIREBASE_WEB_API_KEY", "FIREBASEWEBAPIKEY"], "") + FIREBASE_SERVICE_ACCOUNT_PATH: str = env_first( + ["FIREBASE_SERVICE_ACCOUNT_PATH", "FIREBASESERVICEACCOUNTPATH"], + "", + ) + FIREBASE_SERVICE_ACCOUNT_JSON: str = env_first( + ["FIREBASE_SERVICE_ACCOUNT_JSON", "FIREBASESERVICEACCOUNTJSON"], + "", + ) + @property def cors_origins_list(self) -> list[str]: return [origin.strip() for origin in self.CORS_ORIGINS.split(",") if origin.strip()] diff --git a/backend/app/database.py b/backend/app/database.py index 67b4aa2c35a33c02e1d1865a98b40810a75d5256..40c7acaab902eaa1d17d4b3b48fe521096c3acc5 100644 --- a/backend/app/database.py +++ b/backend/app/database.py @@ -1,29 +1,21 @@ -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker, declarative_base -from app.config import settings +from contextlib import contextmanager -# Create engine -engine = create_engine( - settings.DATABASE_URL, - connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {} -) -# Create session factory -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +class _NoDatabase: + """Compatibility object for legacy dependencies while moving to Firestore-only.""" -# Base class for models -Base = declarative_base() + +@contextmanager +def _noop_db_context(): + yield _NoDatabase() def get_db(): - """Dependency for database session""" - db = SessionLocal() - try: + """Legacy dependency kept for backward compatibility with route signatures.""" + with _noop_db_context() as db: yield db - finally: - db.close() def init_db(): - """Initialize database with all tables""" - Base.metadata.create_all(bind=engine) + """No-op: Firestore does not require SQL table initialization.""" + return None diff --git a/backend/app/middleware/auth.py b/backend/app/middleware/auth.py index 5a1aa2e86efe0866ec2e5b1582ec9a90ea5289af..76c26bffc218ce74eedc7c40c51311098c6b61f9 100644 --- a/backend/app/middleware/auth.py +++ b/backend/app/middleware/auth.py @@ -1,36 +1,66 @@ from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials -from sqlalchemy.orm import Session from app.utils.auth import decode_token -from app.models import User -from app.database import get_db +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc security = HTTPBearer() async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), - db: Session = Depends(get_db) -) -> User: +): """Get current authenticated user""" token = credentials.credentials token_data = decode_token(token) email = token_data.get("email") + display_name = token_data.get("name") - user = db.query(User).filter(User.email == email).first() + user = first_doc(COLL.users, predicate=lambda row: row.get("email") == email) + + if user and user.get("updated_at") is None: + user["updated_at"] = now_utc() + + if not user and email: + inferred_name = display_name or email.split("@")[0] + user = create_doc( + COLL.users, + { + "name": inferred_name, + "email": email, + "password": "", + "role": "player", + "jersey_number": None, + "bio": None, + "runs": 0, + "matches": 0, + "wickets": 0, + "centuries": 0, + "half_centuries": 0, + "average_runs": 0.0, + "highest_score": 0, + "is_premium": False, + "premium_expiry": None, + "premium_start_date": None, + "is_active": True, + "created_at": now_utc(), + "updated_at": now_utc(), + "last_login": None, + }, + ) - if not user or not user.is_active: + if not user or not user.get("is_active", True): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", ) + update_doc(COLL.users, user["id"], {"updated_at": now_utc()}) - return user + return as_obj(user) async def get_admin_user( - current_user: User = Depends(get_current_user), -) -> User: + current_user = Depends(get_current_user), +): """Verify current user is admin""" if current_user.role != "admin": raise HTTPException( diff --git a/backend/app/routes/admin.py b/backend/app/routes/admin.py index 061b05d1433f4d0675e4035e1b0ff8f7073030cf..d0b8834904dac50c93c4f68dd26cddc899880051 100644 --- a/backend/app/routes/admin.py +++ b/backend/app/routes/admin.py @@ -1,144 +1,104 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import func -from sqlalchemy.orm import Session -from datetime import datetime +from datetime import datetime, timedelta from typing import List + from app.config import settings -from app.database import get_db -from app.models import User, Payment, FinanceTransaction, AdminChatMessage from app.schemas import AdminChatCreate, AdminChatResponse from app.middleware.auth import get_admin_user, get_current_user -from app.utils.logger import log_action, log_error +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc +from app.utils.logger import log_action router = APIRouter(prefix="/admin", tags=["Admin"]) @router.get("/users", response_model=List) -async def list_all_users( - skip: int = 0, - limit: int = 100, - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db) -): - """Get all users (admin only)""" - - users = db.query(User).offset(skip).limit(limit).all() +async def list_all_users(skip: int = 0, limit: int = 100, admin=Depends(get_admin_user)): + users = list_docs(COLL.users, sort_key="created_at", reverse=True, offset=skip, limit=limit) log_action("Admin viewed all users", user_id=admin.id) return [ { - "id": user.id, - "name": user.name, - "email": user.email, - "role": user.role, - "is_active": user.is_active, - "is_premium": user.is_premium, - "runs": user.runs, - "matches": user.matches, - "wickets": user.wickets, - "created_at": user.created_at, + "id": user.get("id"), + "name": user.get("name"), + "email": user.get("email"), + "role": user.get("role"), + "is_active": user.get("is_active", True), + "is_premium": user.get("is_premium", False), + "runs": user.get("runs", 0), + "matches": user.get("matches", 0), + "wickets": user.get("wickets", 0), + "created_at": user.get("created_at"), } for user in users ] @router.put("/users/{user_id}/premium") -async def toggle_user_premium( - user_id: int, - days: int = 30, - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db) -): - """Toggle user premium status (admin only)""" - - user = db.query(User).filter(User.id == user_id).first() +async def toggle_user_premium(user_id: int, days: int = 30, admin=Depends(get_admin_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id) if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="User not found" - ) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") - user.is_premium = not user.is_premium + is_premium = not user.get("is_premium", False) + patch = {"is_premium": is_premium, "updated_at": now_utc()} - if user.is_premium: - from datetime import datetime, timedelta - user.premium_expiry = datetime.utcnow() + timedelta(days=days) - user.premium_start_date = datetime.utcnow() + if is_premium: + from datetime import timedelta + patch["premium_expiry"] = now_utc() + timedelta(days=days) + patch["premium_start_date"] = now_utc() else: - user.premium_expiry = None + patch["premium_expiry"] = None - db.commit() - log_action("Admin toggled user premium", user_id=admin.id, - details=f"User {user_id}") + update_doc(COLL.users, user_id, patch) + log_action("Admin toggled user premium", user_id=admin.id, details=f"User {user_id}") - return {"message": f"User premium status updated"} + return {"message": "User premium status updated"} @router.delete("/users/{user_id}") -async def deactivate_user( - user_id: int, - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db) -): - """Deactivate user (admin only)""" - - user = db.query(User).filter(User.id == user_id).first() +async def deactivate_user(user_id: int, admin=Depends(get_admin_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id) if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="User not found" - ) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") - user.is_active = False - db.commit() + update_doc(COLL.users, user_id, {"is_active": False, "updated_at": now_utc()}) - log_action("Admin deactivated user", user_id=admin.id, - details=f"User {user_id}") + log_action("Admin deactivated user", user_id=admin.id, details=f"User {user_id}") return {"message": "User deactivated successfully"} @router.get("/stats") -async def get_system_stats( - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db) -): - """Get system statistics (admin only)""" - - total_users = db.query(User).count() - active_users = db.query(User).filter(User.is_active == True).count() - premium_users = db.query(User).filter(User.is_premium == True).count() - total_matches = sum([u.matches for u in db.query(User).all()]) - - paid_user_ids = { - row[0] - for row in db.query(Payment.user_id) - .filter(Payment.status == "completed") - .distinct() - .all() - } - active_players = db.query(User).filter(User.is_active == True, User.role == "player").all() - unpaid_players = [player for player in active_players if player.id not in paid_user_ids] +async def get_system_stats(admin=Depends(get_admin_user)): + users = list_docs(COLL.users) + payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed") + transactions = list_docs(COLL.finance_transactions) + chats = list_docs(COLL.admin_chat_messages) + + total_users = len(users) + active_users = len([u for u in users if u.get("is_active", True)]) + premium_users = len([u for u in users if u.get("is_premium", False)]) + total_matches = sum(int(u.get("matches", 0)) for u in users) + + paid_user_ids = {row.get("user_id") for row in payments} + active_players = [u for u in users if u.get("is_active", True) and u.get("role") == "player"] + unpaid_players = [u for u in active_players if u.get("id") not in paid_user_ids] pending_funds = len(unpaid_players) * settings.PREMIUM_COST - total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter( - Payment.status == "completed" - ).scalar() or 0.0 - manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "credit", - FinanceTransaction.category == "manual_credit", - ).scalar() or 0.0 - total_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "debit", - ).scalar() or 0.0 + total_collected = sum(float(row.get("amount", 0)) for row in payments) + manual_credits = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit" + ) + total_debits = sum(float(row.get("amount", 0)) for row in transactions if row.get("transaction_type") == "debit") funds_remaining = round((total_collected + manual_credits) - total_debits, 2) - unread_chat_messages = db.query(AdminChatMessage).filter( - AdminChatMessage.sender_role == "player", - AdminChatMessage.is_read == False, - ).count() + unread_chat_messages = len( + [m for m in chats if m.get("sender_role") == "player" and not m.get("is_read", False)] + ) log_action("Admin viewed system stats", user_id=admin.id) @@ -154,34 +114,26 @@ async def get_system_stats( @router.get("/chats") -async def get_chat_threads( - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db), -): - """Get admin chat thread summary by player.""" - players = db.query(User).filter(User.role == "player", User.is_active == True).all() +async def get_chat_threads(admin=Depends(get_admin_user)): + players = list_docs(COLL.users, predicate=lambda row: row.get("role") == "player" and row.get("is_active", True)) + chats = list_docs(COLL.admin_chat_messages, sort_key="created_at", reverse=True) threads = [] for player in players: - messages = db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == player.id - ).order_by(AdminChatMessage.created_at.desc()).limit(1).all() - - last_message = messages[0] if messages else None - unread_count = db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == player.id, - AdminChatMessage.sender_role == "player", - AdminChatMessage.is_read == False, - ).count() + player_messages = [m for m in chats if m.get("user_id") == player.get("id")] + last_message = player_messages[0] if player_messages else None + unread_count = len( + [m for m in player_messages if m.get("sender_role") == "player" and not m.get("is_read", False)] + ) threads.append( { - "user_id": player.id, - "name": player.name, - "email": player.email, + "user_id": player.get("id"), + "name": player.get("name"), + "email": player.get("email"), "unread_count": unread_count, - "last_message": last_message.message if last_message else None, - "last_message_at": last_message.created_at if last_message else None, + "last_message": last_message.get("message") if last_message else None, + "last_message_at": last_message.get("created_at") if last_message else None, } ) @@ -190,39 +142,29 @@ async def get_chat_threads( @router.get("/chats/{user_id}", response_model=list[AdminChatResponse]) -async def get_chat_thread( - user_id: int, - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db), -): - """Get full chat thread for a player.""" - user = db.query(User).filter(User.id == user_id, User.role == "player").first() +async def get_chat_thread(user_id: int, admin=Depends(get_admin_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id and row.get("role") == "player") if not user: raise HTTPException(status_code=404, detail="Player not found") - messages = db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == user_id - ).order_by(AdminChatMessage.created_at.asc()).all() + messages = list_docs( + COLL.admin_chat_messages, + predicate=lambda row: row.get("user_id") == user_id, + sort_key="created_at", + reverse=False, + ) - db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == user_id, - AdminChatMessage.sender_role == "player", - AdminChatMessage.is_read == False, - ).update({"is_read": True}) - db.commit() + for message in messages: + if message.get("sender_role") == "player" and not message.get("is_read", False): + update_doc(COLL.admin_chat_messages, message["id"], {"is_read": True}) + message["is_read"] = True - return messages + return [as_obj(row) for row in messages] @router.post("/chats/{user_id}", response_model=AdminChatResponse) -async def send_admin_chat_message( - user_id: int, - payload: AdminChatCreate, - admin: User = Depends(get_admin_user), - db: Session = Depends(get_db), -): - """Send a message from admin to a player.""" - user = db.query(User).filter(User.id == user_id, User.role == "player").first() +async def send_admin_chat_message(user_id: int, payload: AdminChatCreate, admin=Depends(get_admin_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id and row.get("role") == "player") if not user: raise HTTPException(status_code=404, detail="Player not found") @@ -230,60 +172,54 @@ async def send_admin_chat_message( if not message: raise HTTPException(status_code=400, detail="Message cannot be empty") - chat = AdminChatMessage( - user_id=user_id, - sender_role="admin", - message=message, - is_read=False, + chat = create_doc( + COLL.admin_chat_messages, + { + "user_id": user_id, + "sender_role": "admin", + "message": message, + "is_read": False, + "created_at": now_utc(), + }, ) - db.add(chat) - db.commit() - db.refresh(chat) log_action("Admin chat message sent", user_id=admin.id, details=f"to={user_id}") - return chat + return as_obj(chat) @router.get("/my-chat", response_model=list[AdminChatResponse]) -async def get_my_chat( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Get current player's chat with admin.""" - messages = db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == current_user.id - ).order_by(AdminChatMessage.created_at.asc()).all() +async def get_my_chat(current_user=Depends(get_current_user)): + messages = list_docs( + COLL.admin_chat_messages, + predicate=lambda row: row.get("user_id") == current_user.id, + sort_key="created_at", + reverse=False, + ) - db.query(AdminChatMessage).filter( - AdminChatMessage.user_id == current_user.id, - AdminChatMessage.sender_role == "admin", - AdminChatMessage.is_read == False, - ).update({"is_read": True}) - db.commit() + for message in messages: + if message.get("sender_role") == "admin" and not message.get("is_read", False): + update_doc(COLL.admin_chat_messages, message["id"], {"is_read": True}) + message["is_read"] = True - return messages + return [as_obj(row) for row in messages] @router.post("/my-chat", response_model=AdminChatResponse) -async def send_message_to_admin( - payload: AdminChatCreate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Send message to admin from current player.""" +async def send_message_to_admin(payload: AdminChatCreate, current_user=Depends(get_current_user)): message = payload.message.strip() if not message: raise HTTPException(status_code=400, detail="Message cannot be empty") - chat = AdminChatMessage( - user_id=current_user.id, - sender_role="player", - message=message, - is_read=False, + chat = create_doc( + COLL.admin_chat_messages, + { + "user_id": current_user.id, + "sender_role": "player", + "message": message, + "is_read": False, + "created_at": now_utc(), + }, ) - db.add(chat) - db.commit() - db.refresh(chat) log_action("Player chat message sent", user_id=current_user.id) - return chat + return as_obj(chat) diff --git a/backend/app/routes/auth.py b/backend/app/routes/auth.py index f2ebed972353f430c4c848e9e058b4eb5e8bbaf4..68929487865559279c9e5ce3d00544411bac8170 100644 --- a/backend/app/routes/auth.py +++ b/backend/app/routes/auth.py @@ -1,10 +1,8 @@ from fastapi import APIRouter, Depends, HTTPException, Request, status -from sqlalchemy.orm import Session from datetime import timedelta -from app.database import get_db -from app.models import User from app.schemas import UserRegister, UserLogin, Token, UserResponse from app.utils.auth import hash_password, verify_password, create_access_token +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc from app.utils.logger import log_action, log_error from slowapi import Limiter from slowapi.util import get_remote_address @@ -15,11 +13,11 @@ limiter = Limiter(key_func=get_remote_address) @router.post("/register", response_model=Token) @limiter.limit("5/minute") -async def register(request: Request, user_data: UserRegister, db: Session = Depends(get_db)): +async def register(request: Request, user_data: UserRegister): """Register a new player""" # Check if user already exists - existing_user = db.query(User).filter(User.email == user_data.email).first() + existing_user = first_doc(COLL.users, predicate=lambda row: row.get("email") == user_data.email) if existing_user: log_error(f"Registration failed: Email already exists", details=user_data.email) raise HTTPException( @@ -28,56 +26,70 @@ async def register(request: Request, user_data: UserRegister, db: Session = Depe ) # Create new user - new_user = User( - name=user_data.name, - email=user_data.email, - password=hash_password(user_data.password), - role="player" + new_user = create_doc( + COLL.users, + { + "name": user_data.name, + "email": user_data.email, + "password": hash_password(user_data.password), + "role": "player", + "jersey_number": None, + "bio": None, + "runs": 0, + "matches": 0, + "wickets": 0, + "centuries": 0, + "half_centuries": 0, + "average_runs": 0.0, + "highest_score": 0, + "is_premium": False, + "premium_expiry": None, + "premium_start_date": None, + "is_active": True, + "created_at": now_utc(), + "updated_at": now_utc(), + "last_login": None, + }, ) - db.add(new_user) - db.commit() - db.refresh(new_user) - # Create access token access_token = create_access_token( data={"sub": new_user.email}, expires_delta=timedelta(minutes=30) ) - log_action("User registered", user_id=new_user.id) + log_action("User registered", user_id=new_user["id"]) return { "access_token": access_token, "token_type": "bearer", - "user": UserResponse.model_validate(new_user) + "user": UserResponse.model_validate(as_obj(new_user)) } @router.post("/login", response_model=Token) @limiter.limit("10/minute") -async def login(request: Request, credentials: UserLogin, db: Session = Depends(get_db)): +async def login(request: Request, credentials: UserLogin): """Login a player""" - user = db.query(User).filter(User.email == credentials.email).first() + user = first_doc(COLL.users, predicate=lambda row: row.get("email") == credentials.email) - if not user or not verify_password(credentials.password, user.password): + if not user or not verify_password(credentials.password, user.get("password", "")): log_error("Login failed: Invalid credentials", details=credentials.email) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid email or password" ) - if not user.is_active: + if not user.get("is_active", True): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Account is deactivated" ) # Update last login - from datetime import datetime - user.last_login = datetime.utcnow() - db.commit() + update_doc(COLL.users, user["id"], {"last_login": now_utc(), "updated_at": now_utc()}) + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user["id"]) # Create access token access_token = create_access_token( @@ -85,10 +97,10 @@ async def login(request: Request, credentials: UserLogin, db: Session = Depends( expires_delta=timedelta(minutes=30) ) - log_action("User logged in", user_id=user.id) + log_action("User logged in", user_id=user["id"]) return { "access_token": access_token, "token_type": "bearer", - "user": UserResponse.model_validate(user) + "user": UserResponse.model_validate(as_obj(user)) } diff --git a/backend/app/routes/dashboard.py b/backend/app/routes/dashboard.py index 06b2e07bffc116f731337a6f30509ea8f4919c4a..82167eacd385219511ca39a5d4def57e8d8797e2 100644 --- a/backend/app/routes/dashboard.py +++ b/backend/app/routes/dashboard.py @@ -1,48 +1,79 @@ -from fastapi import APIRouter, Depends -from sqlalchemy import func -from sqlalchemy.orm import Session -from datetime import datetime +from fastapi import APIRouter from typing import List -from app.database import get_db -from app.models import User, PerformanceLog, Payment, FinanceTransaction +from datetime import datetime, timezone +from google.api_core.exceptions import ResourceExhausted + from app.schemas import UserResponse -from app.utils.premium import check_and_downgrade_premium +from app.utils.firestore_data import COLL, as_obj, list_docs, now_utc, update_doc, _parse_datetime, normalize_user +from app.utils.cache import get_cache router = APIRouter(prefix="/dashboard", tags=["Dashboard"]) -@router.get("/overview") -async def get_dashboard_overview(db: Session = Depends(get_db)): - """Get dashboard overview stats""" +def _check_and_downgrade(player: dict) -> dict: + expiry = player.get("premium_expiry") + if player.get("is_premium") and expiry: + # Parse expiry to timezone-aware datetime + expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry + + # Ensure expiry_dt is timezone-aware + if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None: + expiry_dt = expiry_dt.replace(tzinfo=timezone.utc) + + # Check if premium has expired + if expiry_dt and now_utc() >= expiry_dt: + # Use _doc_id (actual Firestore document ID) if available, otherwise use id + doc_id = player.get("_doc_id") or player.get("id") + player = update_doc(COLL.users, doc_id, {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}) or player + return player - total_players = db.query(User).filter(User.is_active == True).count() - premium_players = db.query(User).filter(User.is_premium == True).count() - total_matches = sum([p.matches for p in db.query(User).all()]) - total_runs = sum([p.runs for p in db.query(User).all()]) - return { - "total_players": total_players, - "premium_players": premium_players, - "total_matches": total_matches, - "total_runs": total_runs - } +@router.get("/overview") +async def get_dashboard_overview(): + cache = get_cache() + + def fetch_overview(): + players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True)) + total_players = len(players) + premium_players = len([p for p in players if p.get("is_premium")]) + total_matches = sum(int(p.get("matches", 0)) for p in players) + total_runs = sum(int(p.get("runs", 0)) for p in players) + + return { + "total_players": total_players, + "premium_players": premium_players, + "total_matches": total_matches, + "total_runs": total_runs, + } + + try: + return cache.get_or_fetch("dashboard_overview", fetch_overview, ttl_seconds=300) + except ResourceExhausted: + # Fall back to cached data if quota exceeded + cached = cache.get("dashboard_overview") + if cached: + return cached + raise @router.get("/extended-overview") -async def get_extended_overview(db: Session = Depends(get_db)): - """Get extended dashboard stats for real-world club overview.""" - players = db.query(User).filter(User.is_active == True, User.role == "player").all() +async def get_extended_overview(): + cache = get_cache() + + def fetch_extended_overview(): + players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player") - total_players = len(players) - premium_players = len([player for player in players if player.is_premium]) - total_matches = sum(player.matches for player in players) - total_runs = sum(player.runs for player in players) - total_wickets = sum(player.wickets for player in players) + total_players = len(players) + premium_players = len([player for player in players if player.get("is_premium")]) + total_matches = sum(int(player.get("matches", 0)) for player in players) + total_runs = sum(int(player.get("runs", 0)) for player in players) + total_wickets = sum(int(player.get("wickets", 0)) for player in players) - avg_runs_per_match = round(total_runs / total_matches, 2) if total_matches else 0.0 - premium_ratio = round((premium_players / total_players) * 100, 2) if total_players else 0.0 + avg_runs_per_match = round(total_runs / total_matches, 2) if total_matches else 0.0 + premium_ratio = round((premium_players / total_players) * 100, 2) if total_players else 0.0 - top_performance = db.query(PerformanceLog).order_by(PerformanceLog.performance_rating.desc()).first() + top_performance = list_docs(COLL.performance_logs, sort_key="performance_rating", reverse=True, limit=1) + top = top_performance[0] if top_performance else None return { "total_players": total_players, @@ -53,89 +84,97 @@ async def get_extended_overview(db: Session = Depends(get_db)): "avg_runs_per_match": avg_runs_per_match, "premium_ratio": premium_ratio, "top_performance": { - "match_date": top_performance.match_date if top_performance else None, - "performance_rating": top_performance.performance_rating if top_performance else 0, - "runs_scored": top_performance.runs_scored if top_performance else 0, - "wickets_taken": top_performance.wickets_taken if top_performance else 0, + "match_date": top.get("match_date") if top else None, + "performance_rating": top.get("performance_rating", 0) if top else 0, + "runs_scored": top.get("runs_scored", 0) if top else 0, + "wickets_taken": top.get("wickets_taken", 0) if top else 0, }, - } - - -@router.get("/featured-players", response_model=List[UserResponse]) -async def get_featured_players(db: Session = Depends(get_db)): - """Get featured premium players""" + } - # Get premium players, check expiry - premium_players = db.query(User).filter( - User.is_premium == True, - User.is_active == True - ).all() + try: + return cache.get_or_fetch("dashboard_extended_overview", fetch_extended_overview, ttl_seconds=300) + except ResourceExhausted: + # Fall back to cached data if quota exceeded + cached = cache.get("dashboard_extended_overview") + if cached: + return cached + raise - for player in premium_players: - check_and_downgrade_premium(db, player) - # Get only confirmed premium players, sorted by runs - featured = db.query(User).filter( - User.is_premium == True, - User.is_active == True - ).order_by(User.runs.desc()).limit(5).all() - - return featured +@router.get("/featured-players", response_model=List[UserResponse]) +async def get_featured_players(): + premium_players = list_docs( + COLL.users, + predicate=lambda row: row.get("is_premium") and row.get("is_active", True), + sort_key="runs", + reverse=True, + limit=5, + ) + return [normalize_user(_check_and_downgrade(row)) for row in premium_players] @router.get("/recent-players", response_model=List[UserResponse]) -async def get_recent_players(db: Session = Depends(get_db)): - """Get recently registered players""" - - recent = db.query(User).filter( - User.is_active == True - ).order_by(User.created_at.desc()).limit(10).all() - - return recent +async def get_recent_players(): + recent = list_docs( + COLL.users, + predicate=lambda row: row.get("is_active", True), + sort_key="created_at", + reverse=True, + limit=10, + ) + return [normalize_user(row) for row in recent] @router.get("/top-stats") -async def get_top_stats(db: Session = Depends(get_db)): - """Get top statistics""" - - top_scorer = db.query(User).filter(User.is_active == True).order_by( - User.runs.desc() - ).first() - - top_wicket_taker = db.query(User).filter(User.is_active == True).order_by( - User.wickets.desc() - ).first() +async def get_top_stats(): + cache = get_cache() + + def fetch_top_stats(): + # Fetch active players once and compute top scorers and wicket takers from same list + players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True)) + + # Sort by runs and get top scorer + top_scorers = sorted(players, key=lambda x: int(x.get("runs", 0)), reverse=True) + top_scorer = top_scorers[0] if top_scorers else None + + # Sort by wickets and get top wicket taker + top_wickets = sorted(players, key=lambda x: int(x.get("wickets", 0)), reverse=True) + top_wicket_taker = top_wickets[0] if top_wickets else None - return { - "top_scorer": { - "name": top_scorer.name if top_scorer else None, - "runs": top_scorer.runs if top_scorer else 0 - }, - "top_wicket_taker": { - "name": top_wicket_taker.name if top_wicket_taker else None, - "wickets": top_wicket_taker.wickets if top_wicket_taker else 0 + return { + "top_scorer": { + "name": top_scorer.get("name") if top_scorer else None, + "runs": top_scorer.get("runs", 0) if top_scorer else 0, + }, + "top_wicket_taker": { + "name": top_wicket_taker.get("name") if top_wicket_taker else None, + "wickets": top_wicket_taker.get("wickets", 0) if top_wicket_taker else 0, + }, } - } + + try: + return cache.get_or_fetch("dashboard_top_stats", fetch_top_stats, ttl_seconds=300) + except ResourceExhausted: + # Fall back to cached data if quota exceeded + cached = cache.get("dashboard_top_stats") + if cached: + return cached + raise @router.get("/charts") -async def get_dashboard_chart_data(db: Session = Depends(get_db)): - """Get chart-friendly dataset for player stats and match trend.""" - top_players = db.query(User).filter(User.is_active == True).order_by(User.runs.desc()).limit(6).all() - - recent_logs = db.query(PerformanceLog).order_by(PerformanceLog.match_date.desc()).limit(12).all() - recent_logs = list(reversed(recent_logs)) +async def get_dashboard_chart_data(): + top_players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True), sort_key="runs", reverse=True, limit=6) + recent_logs = list_docs(COLL.performance_logs, sort_key="match_date", reverse=False, limit=12) return { - "top_players_runs": [ - {"name": player.name, "runs": player.runs} for player in top_players - ], + "top_players_runs": [{"name": player.get("name"), "runs": player.get("runs", 0)} for player in top_players], "recent_match_trend": [ { - "label": log.match_date.strftime("%d %b"), - "runs": log.runs_scored, - "wickets": log.wickets_taken, - "rating": log.performance_rating, + "label": log.get("match_date").strftime("%d %b") if log.get("match_date") else "N/A", + "runs": log.get("runs_scored", 0), + "wickets": log.get("wickets_taken", 0), + "rating": log.get("performance_rating", 0), } for log in recent_logs ], @@ -143,9 +182,8 @@ async def get_dashboard_chart_data(db: Session = Depends(get_db)): @router.get("/team-ai-insights") -async def get_team_ai_insights(db: Session = Depends(get_db)): - """Generate AI-style team summary from recent performances.""" - recent_logs = db.query(PerformanceLog).order_by(PerformanceLog.match_date.desc()).limit(30).all() +async def get_team_ai_insights(): + recent_logs = list_docs(COLL.performance_logs, sort_key="match_date", reverse=True, limit=30) if not recent_logs: return { @@ -155,9 +193,9 @@ async def get_team_ai_insights(db: Session = Depends(get_db)): "insights": ["Log team matches to unlock AI projections."], } - avg_rating = sum(log.performance_rating for log in recent_logs) / len(recent_logs) - avg_runs = sum(log.runs_scored for log in recent_logs) / len(recent_logs) - avg_wickets = sum(log.wickets_taken for log in recent_logs) / len(recent_logs) + avg_rating = sum(float(log.get("performance_rating", 0)) for log in recent_logs) / len(recent_logs) + avg_runs = sum(float(log.get("runs_scored", 0)) for log in recent_logs) / len(recent_logs) + avg_wickets = sum(float(log.get("wickets_taken", 0)) for log in recent_logs) / len(recent_logs) if avg_rating >= 7.5: team_form = "excellent" @@ -188,25 +226,26 @@ async def get_team_ai_insights(db: Session = Depends(get_db)): @router.get("/funds-summary") -async def get_funds_summary(db: Session = Depends(get_db)): - """Get finance summary for dashboard cards.""" - total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter( - Payment.status == "completed" - ).scalar() or 0.0 - - manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "credit", - FinanceTransaction.category == "manual_credit", - ).scalar() or 0.0 - - guest_fund_spent = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "debit", - FinanceTransaction.category == "guest_fund", - ).scalar() or 0.0 - - all_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "debit", - ).scalar() or 0.0 +async def get_funds_summary(): + payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed") + transactions = list_docs(COLL.finance_transactions) + + total_collected = sum(float(row.get("amount", 0)) for row in payments) + manual_credits = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit" + ) + guest_fund_spent = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "debit" and row.get("category") == "guest_fund" + ) + all_debits = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "debit" + ) remaining_funds = round((total_collected + manual_credits) - all_debits, 2) diff --git a/backend/app/routes/finance.py b/backend/app/routes/finance.py index 9186a763fcf818ef56f3e070454e0544f0ef50bf..963d571fd98f17afe017c45a672eac36091de602 100644 --- a/backend/app/routes/finance.py +++ b/backend/app/routes/finance.py @@ -1,70 +1,52 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.orm import Session -from sqlalchemy import func + from app.config import settings -from app.database import get_db -from app.models import User, Payment, FinanceTransaction from app.middleware.auth import get_current_user from app.schemas import GuestFundRequest, ManualCreditRequest, FinanceTransactionResponse +from app.utils.firestore_data import COLL, as_obj, create_doc, list_docs, now_utc from app.utils.logger import log_action router = APIRouter(prefix="/finance", tags=["Finance"]) -def require_admin(user: User) -> None: +def require_admin(user) -> None: if user.role != "admin": - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Only admins can perform this action", - ) - + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only admins can perform this action") -def calculate_remaining_funds(db: Session) -> float: - total_payments = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter( - Payment.status == "completed" - ).scalar() or 0.0 - total_manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "credit", - FinanceTransaction.category == "manual_credit", - ).scalar() or 0.0 +def calculate_remaining_funds() -> float: + payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed") + transactions = list_docs(COLL.finance_transactions) - total_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "debit", - ).scalar() or 0.0 + total_payments = sum(float(row.get("amount", 0)) for row in payments) + total_manual_credits = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit" + ) + total_debits = sum(float(row.get("amount", 0)) for row in transactions if row.get("transaction_type") == "debit") return round((total_payments + total_manual_credits) - total_debits, 2) @router.get("/overview") -async def get_finance_overview( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Get total collected funds, pending funds, and remaining funds.""" - active_players = db.query(User).filter(User.is_active == True, User.role == "player").all() - - paid_user_ids = { - row[0] - for row in db.query(Payment.user_id) - .filter(Payment.status == "completed") - .distinct() - .all() - } - - unpaid_players = [player for player in active_players if player.id not in paid_user_ids] - - total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter( - Payment.status == "completed" - ).scalar() or 0.0 - - total_guest_fund_used = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter( - FinanceTransaction.transaction_type == "debit", - FinanceTransaction.category == "guest_fund", - ).scalar() or 0.0 +async def get_finance_overview(current_user=Depends(get_current_user)): + active_players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player") + payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed") + transactions = list_docs(COLL.finance_transactions) + + paid_user_ids = {row.get("user_id") for row in payments} + unpaid_players = [player for player in active_players if player.get("id") not in paid_user_ids] + + total_collected = sum(float(row.get("amount", 0)) for row in payments) + total_guest_fund_used = sum( + float(row.get("amount", 0)) + for row in transactions + if row.get("transaction_type") == "debit" and row.get("category") == "guest_fund" + ) pending_funds = len(unpaid_players) * settings.PREMIUM_COST - funds_remaining = calculate_remaining_funds(db) + funds_remaining = calculate_remaining_funds() return { "total_collected": round(total_collected, 2), @@ -78,29 +60,24 @@ async def get_finance_overview( @router.get("/player-payments") -async def get_player_payments( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Show who paid premium and current payment status per player.""" - players = db.query(User).filter(User.is_active == True, User.role == "player").all() +async def get_player_payments(current_user=Depends(get_current_user)): + players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player") + all_payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed") result = [] for player in players: - payments = db.query(Payment).filter( - Payment.user_id == player.id, - Payment.status == "completed", - ).order_by(Payment.created_at.desc()).all() + payments = [row for row in all_payments if row.get("user_id") == player.get("id")] + payments.sort(key=lambda row: row.get("created_at") or now_utc(), reverse=True) - amount_paid = round(sum(payment.amount for payment in payments), 2) - last_payment_date = payments[0].created_at if payments else None + amount_paid = round(sum(float(payment.get("amount", 0)) for payment in payments), 2) + last_payment_date = payments[0].get("created_at") if payments else None result.append( { - "user_id": player.id, - "name": player.name, - "email": player.email, - "is_premium": player.is_premium, + "user_id": player.get("id"), + "name": player.get("name"), + "email": player.get("email"), + "is_premium": player.get("is_premium", False), "amount_paid": amount_paid, "has_paid": amount_paid >= settings.PREMIUM_COST, "last_payment_date": last_payment_date, @@ -108,27 +85,18 @@ async def get_player_payments( } ) - result.sort(key=lambda row: (not row["has_paid"], row["name"].lower())) + result.sort(key=lambda row: (not row["has_paid"], (row["name"] or "").lower())) return result @router.get("/transactions", response_model=list[FinanceTransactionResponse]) -async def get_finance_transactions( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """List recent finance transactions.""" - transactions = db.query(FinanceTransaction).order_by(FinanceTransaction.created_at.desc()).limit(100).all() - return transactions +async def get_finance_transactions(current_user=Depends(get_current_user)): + transactions = list_docs(COLL.finance_transactions, sort_key="created_at", reverse=True, limit=100) + return [as_obj(row) for row in transactions] @router.post("/guest-fund") -async def record_guest_fund_expense( - payload: GuestFundRequest, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Record guest fund expense after a match and update remaining funds.""" +async def record_guest_fund_expense(payload: GuestFundRequest, current_user=Depends(get_current_user)): require_admin(current_user) if payload.guest_fund <= 0: @@ -138,19 +106,20 @@ async def record_guest_fund_expense( if payload.notes: description = f"{description} | {payload.notes}" - transaction = FinanceTransaction( - user_id=None, - transaction_type="debit", - amount=payload.guest_fund, - category="guest_fund", - description=description, - reference_id=None, + create_doc( + COLL.finance_transactions, + { + "user_id": None, + "transaction_type": "debit", + "amount": payload.guest_fund, + "category": "guest_fund", + "description": description, + "reference_id": None, + "created_at": now_utc(), + }, ) - db.add(transaction) - db.commit() - - funds_remaining = calculate_remaining_funds(db) + funds_remaining = calculate_remaining_funds() log_action("Guest fund expense recorded", user_id=current_user.id, details=description) return { @@ -161,30 +130,26 @@ async def record_guest_fund_expense( @router.post("/manual-credit") -async def record_manual_credit( - payload: ManualCreditRequest, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Add manual credit to club funds.""" +async def record_manual_credit(payload: ManualCreditRequest, current_user=Depends(get_current_user)): require_admin(current_user) if payload.amount <= 0: raise HTTPException(status_code=400, detail="Credit amount should be greater than zero") - transaction = FinanceTransaction( - user_id=payload.user_id, - transaction_type="credit", - amount=payload.amount, - category="manual_credit", - description=payload.notes or "Manual fund credit", - reference_id=None, + create_doc( + COLL.finance_transactions, + { + "user_id": payload.user_id, + "transaction_type": "credit", + "amount": payload.amount, + "category": "manual_credit", + "description": payload.notes or "Manual fund credit", + "reference_id": None, + "created_at": now_utc(), + }, ) - db.add(transaction) - db.commit() - - funds_remaining = calculate_remaining_funds(db) + funds_remaining = calculate_remaining_funds() log_action("Manual fund credit recorded", user_id=current_user.id, details=str(payload.amount)) return { diff --git a/backend/app/routes/matches.py b/backend/app/routes/matches.py index c8360008cf55b8bec4df3bafb5ae2326f0e34728..cc57c0d44d6aa3bacd03c78e5ef24b099a69c498 100644 --- a/backend/app/routes/matches.py +++ b/backend/app/routes/matches.py @@ -1,10 +1,6 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy import func -from sqlalchemy.orm import Session -from app.database import get_db from app.middleware.auth import get_current_user -from app.models import BallEvent, Match, MatchPlayer, User from app.schemas import ( BallEventCreate, MatchCreate, @@ -15,34 +11,41 @@ from app.schemas import ( MatchStartRequest, MatchTeamSetupRequest, ) +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime from app.utils.logger import log_action -from app.utils.premium import check_and_downgrade_premium router = APIRouter(prefix="/matches", tags=["Matches"]) -def ensure_match_editor(match_obj: Match, current_user: User): +def ensure_match_editor(match_obj: dict, current_user): if current_user.role == "admin": return - if match_obj.created_by_id != current_user.id: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Only match creator can update this match", - ) + if match_obj.get("created_by_id") != current_user.id: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only match creator can update this match") -def ensure_premium_creator(db: Session, user: User): - check_and_downgrade_premium(db, user) - db.refresh(user) - if not user.is_premium: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Only premium players can create matches", - ) +def ensure_premium_creator(user: dict): + from datetime import datetime, timezone + + expiry = user.get("premium_expiry") + if user.get("is_premium") and expiry: + # Parse expiry to timezone-aware datetime + expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry + + # Ensure expiry_dt is timezone-aware + if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None: + expiry_dt = expiry_dt.replace(tzinfo=timezone.utc) + + # Check if premium has expired + if expiry_dt and now_utc() >= expiry_dt: + user = update_doc(COLL.users, user["id"], {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}) or user + if not user.get("is_premium"): + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only premium players can create matches") -def get_team_totals(db: Session, match_id: int): - events = db.query(BallEvent).filter(BallEvent.match_id == match_id).all() + +def get_team_totals(match_id: int): + events = list_docs(COLL.ball_events, predicate=lambda row: row.get("match_id") == match_id) team_a_runs = 0 team_b_runs = 0 @@ -50,44 +53,56 @@ def get_team_totals(db: Session, match_id: int): team_b_wickets = 0 for event in events: - total = event.runs_off_bat + event.extras - if event.batting_team == "A": + total = int(event.get("runs_off_bat", 0)) + int(event.get("extras", 0)) + if event.get("batting_team") == "A": team_a_runs += total - if event.is_wicket: + if event.get("is_wicket"): team_a_wickets += 1 - elif event.batting_team == "B": + elif event.get("batting_team") == "B": team_b_runs += total - if event.is_wicket: + if event.get("is_wicket"): team_b_wickets += 1 return team_a_runs, team_b_runs, team_a_wickets, team_b_wickets -def get_innings_teams(db: Session, match_id: int, default_team: str): - first_innings_event = ( - db.query(BallEvent) - .filter(BallEvent.match_id == match_id, BallEvent.innings == 1) - .order_by(BallEvent.created_at.asc()) - .first() +def get_innings_teams(match_id: int, default_team: str): + first_innings_event = first_doc( + COLL.ball_events, + predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == 1, + sort_key="created_at", + reverse=False, ) - first_batting_team = first_innings_event.batting_team if first_innings_event else (default_team or "A") + first_batting_team = first_innings_event.get("batting_team") if first_innings_event else (default_team or "A") second_batting_team = "B" if first_batting_team == "A" else "A" return first_batting_team, second_batting_team -def build_scoreboard(db: Session, match_obj: Match, innings: int): - batting_team = match_obj.batting_team or "A" - events = ( - db.query(BallEvent) - .filter(BallEvent.match_id == match_obj.id, BallEvent.innings == innings) - .order_by(BallEvent.created_at.asc()) - .all() +def get_batting_side_player_count(match_id: int, team: str): + return len(list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id and row.get("team") == team)) + + +def build_scoreboard(match_obj: dict, innings: int): + batting_team = match_obj.get("batting_team") or "A" + events = list_docs( + COLL.ball_events, + predicate=lambda row: row.get("match_id") == match_obj.get("id") and row.get("innings") == innings, + sort_key="created_at", + reverse=False, ) - total_runs = sum(event.runs_off_bat + event.extras for event in events) - wickets = sum(1 for event in events if event.is_wicket) - legal_balls = sum(1 for event in events if event.extra_type not in {"wide", "no_ball"}) + # Get all balls from all innings for match history + all_events = list_docs( + COLL.ball_events, + predicate=lambda row: row.get("match_id") == match_obj.get("id"), + sort_key="created_at", + reverse=False, + ) + + total_runs = sum(int(event.get("runs_off_bat", 0)) + int(event.get("extras", 0)) for event in events) + wickets = sum(1 for event in events if event.get("is_wicket")) + legal_balls = sum(1 for event in events if event.get("extra_type") not in {"wide", "no_ball"}) completed_overs = legal_balls // 6 balls_in_current_over = legal_balls % 6 @@ -97,24 +112,25 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int): over_map = {} for event in events[-18:]: - ball_text = f"{event.over_number}.{event.ball_number} " - if event.is_wicket: + ball_text = f"{event.get('over_number')}.{event.get('ball_number')} " + if event.get("is_wicket"): ball_text += "W" - elif event.extra_type: - ball_text += f"{event.runs_off_bat + event.extras} ({event.extra_type})" + elif event.get("extra_type"): + ball_text += f"{int(event.get('runs_off_bat', 0)) + int(event.get('extras', 0))} ({event.get('extra_type')})" else: - ball_text += str(event.runs_off_bat) + ball_text += str(event.get("runs_off_bat", 0)) recent_balls.append(ball_text) for event in events: - if event.is_wicket: + if event.get("is_wicket"): result = "W" - elif event.extra_type: - result = f"{event.runs_off_bat + event.extras} ({event.extra_type})" + elif event.get("extra_type"): + result = f"{int(event.get('runs_off_bat', 0)) + int(event.get('extras', 0))} ({event.get('extra_type')})" else: - result = str(event.runs_off_bat) + result = str(event.get("runs_off_bat", 0)) - over_map.setdefault(event.over_number, []).append(f"{event.ball_number}:{result}") + over_no = int(event.get("over_number", 1)) + over_map.setdefault(over_no, []).append(f"{event.get('ball_number')}:{result}") if over_map: current_over_number = max(over_map.keys()) @@ -129,21 +145,21 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int): current_over_balls = [] past_overs = [] - team_a_runs, team_b_runs, team_a_wickets, team_b_wickets = get_team_totals(db, match_obj.id) - first_team, second_team = get_innings_teams(db, match_obj.id, match_obj.batting_team or "A") + team_a_runs, team_b_runs, team_a_wickets, team_b_wickets = get_team_totals(match_obj.get("id")) + first_team, second_team = get_innings_teams(match_obj.get("id"), match_obj.get("batting_team") or "A") winner_team = None result_text = None - if match_obj.status == "completed": + if match_obj.get("status") == "completed": if team_a_runs == team_b_runs: result_text = "Match tied" else: winner_code = "A" if team_a_runs > team_b_runs else "B" - winner_team = match_obj.team_a_name if winner_code == "A" else match_obj.team_b_name + winner_team = match_obj.get("team_a_name") if winner_code == "A" else match_obj.get("team_b_name") if winner_code == second_team: - winner_player_count = get_batting_side_player_count(db, match_obj.id, winner_code) + winner_player_count = get_batting_side_player_count(match_obj.get("id"), winner_code) winner_wickets = team_a_wickets if winner_code == "A" else team_b_wickets wickets_in_hand = max(0, (winner_player_count - 1) - winner_wickets) result_text = f"{winner_team} won by {wickets_in_hand} wicket{'s' if wickets_in_hand != 1 else ''}" @@ -152,10 +168,10 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int): result_text = f"{winner_team} won by {margin} run{'s' if margin != 1 else ''}" return MatchScoreboardResponse( - match_id=match_obj.id, + match_id=match_obj.get("id"), innings=innings, - match_status=match_obj.status, - current_innings=match_obj.current_innings, + match_status=match_obj.get("status"), + current_innings=match_obj.get("current_innings", 1), batting_team=batting_team, total_runs=total_runs, wickets=wickets, @@ -169,108 +185,102 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int): team_b_runs=team_b_runs, winner_team=winner_team, result_text=result_text, + all_balls=[ + { + "id": event.get("id"), + "innings": event.get("innings"), + "over_number": event.get("over_number"), + "ball_number": event.get("ball_number"), + "batting_team": event.get("batting_team"), + "runs_off_bat": event.get("runs_off_bat", 0), + "extras": event.get("extras", 0), + "extra_type": event.get("extra_type"), + "is_wicket": event.get("is_wicket", False), + "wicket_type": event.get("wicket_type"), + "commentary": event.get("commentary"), + "created_at": event.get("created_at"), + } + for event in all_events + ], ) -def get_next_delivery_position(db: Session, match_id: int, innings: int): - legal_balls = ( - db.query(BallEvent) - .filter(BallEvent.match_id == match_id, BallEvent.innings == innings) - .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"]))) - .count() +def get_next_delivery_position(match_id: int, innings: int): + events = list_docs( + COLL.ball_events, + predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == innings, + sort_key="created_at", ) - + legal_balls = len([e for e in events if e.get("extra_type") not in {"wide", "no_ball"}]) over_number = (legal_balls // 6) + 1 ball_number = (legal_balls % 6) + 1 return over_number, ball_number -def get_batting_side_player_count(db: Session, match_id: int, team: str): - return ( - db.query(MatchPlayer) - .filter(MatchPlayer.match_id == match_id, MatchPlayer.team == team) - .count() - ) - - @router.post("", response_model=MatchResponse) -async def create_match( - payload: MatchCreate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - ensure_premium_creator(db, current_user) +async def create_match(payload: MatchCreate, current_user=Depends(get_current_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + ensure_premium_creator(user) if payload.overs_per_innings <= 0: raise HTTPException(status_code=400, detail="Overs must be greater than zero") - match_obj = Match( - title=payload.title.strip(), - created_by_id=current_user.id, - team_a_name=payload.team_a_name.strip(), - team_b_name=payload.team_b_name.strip(), - overs_per_innings=payload.overs_per_innings, + match_obj = create_doc( + COLL.matches, + { + "title": payload.title.strip(), + "created_by_id": current_user.id, + "team_a_name": payload.team_a_name.strip(), + "team_b_name": payload.team_b_name.strip(), + "overs_per_innings": payload.overs_per_innings, + "status": "setup", + "current_innings": 1, + "batting_team": None, + "created_at": now_utc(), + "updated_at": now_utc(), + }, ) - db.add(match_obj) - db.commit() - db.refresh(match_obj) - log_action("Created live match", user_id=current_user.id, details=match_obj.title) - return match_obj + log_action("Created live match", user_id=current_user.id, details=match_obj.get("title")) + return as_obj(match_obj) @router.get("", response_model=list[MatchResponse]) -async def list_matches( - db: Session = Depends(get_db), - current_user: User = Depends(get_current_user), -): +async def list_matches(current_user=Depends(get_current_user)): _ = current_user - matches = db.query(Match).order_by(Match.created_at.desc()).limit(50).all() - return matches + matches = list_docs(COLL.matches, sort_key="created_at", reverse=True, limit=50) + return [as_obj(row) for row in matches] @router.get("/{match_id}", response_model=MatchDetailResponse) -async def get_match( - match_id: int, - db: Session = Depends(get_db), - current_user: User = Depends(get_current_user), -): +async def get_match(match_id: int, current_user=Depends(get_current_user)): _ = current_user - match_obj = db.query(Match).filter(Match.id == match_id).first() + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") - rows = ( - db.query(MatchPlayer.user_id, MatchPlayer.team, User.name) - .join(User, User.id == MatchPlayer.user_id) - .filter(MatchPlayer.match_id == match_id) - .all() - ) + rows = list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id) team_a = [] team_b = [] - for user_id, team, name in rows: - view = MatchPlayerView(user_id=user_id, team=team, name=name) - if team == "A": + for row in rows: + player = first_doc(COLL.users, predicate=lambda u: u.get("id") == row.get("user_id")) + name = (player or {}).get("name", "Unknown") + view = MatchPlayerView(user_id=row.get("user_id"), team=row.get("team"), name=name) + if row.get("team") == "A": team_a.append(view) else: team_b.append(view) - return MatchDetailResponse( - match=match_obj, - team_a_players=team_a, - team_b_players=team_b, - ) + return MatchDetailResponse(match=as_obj(match_obj), team_a_players=team_a, team_b_players=team_b) @router.post("/{match_id}/teams") -async def setup_match_teams( - match_id: int, - payload: MatchTeamSetupRequest, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - match_obj = db.query(Match).filter(Match.id == match_id).first() +async def setup_match_teams(match_id: int, payload: MatchTeamSetupRequest, current_user=Depends(get_current_user)): + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") @@ -283,36 +293,41 @@ async def setup_match_teams( if not all_player_ids: raise HTTPException(status_code=400, detail="Select players for both teams") - valid_count = ( - db.query(func.count(User.id)) - .filter(User.id.in_(all_player_ids), User.is_active == True) - .scalar() - ) - if valid_count != len(all_player_ids): - raise HTTPException(status_code=400, detail="One or more selected players are invalid") - - db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).delete() + # Check for valid players - must match either 'id', 'uid' field, or document ID and be active + def is_valid_player(row): + if not row.get("is_active", True): + return False + # Check document id (row.get("id") in Firestore context), id field, uid field + player_id = row.get("id") or row.get("uid") + return player_id in all_player_ids + + users = list_docs(COLL.users, predicate=is_valid_player) + if len(users) != len(all_player_ids): + # Debug: log which players were not found + found_ids = set((u.get("id") or u.get("uid")) for u in users) + missing_ids = set(all_player_ids) - found_ids + print(f"Missing players: {missing_ids}, Found: {found_ids}, All requested: {all_player_ids}") + raise HTTPException(status_code=400, detail=f"One or more selected players are invalid (not found: {missing_ids})") + + existing = list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id) + for row in existing: + from app.utils.firestore_data import delete_doc + + delete_doc(COLL.match_players, row.get("id")) for player_id in payload.team_a_player_ids: - db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="A")) + create_doc(COLL.match_players, {"match_id": match_id, "user_id": player_id, "team": "A", "is_captain": False}) for player_id in payload.team_b_player_ids: - db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="B")) + create_doc(COLL.match_players, {"match_id": match_id, "user_id": player_id, "team": "B", "is_captain": False}) - db.commit() log_action("Updated match teams", user_id=current_user.id, details=f"match_id={match_id}") - return {"message": "Teams updated"} @router.post("/{match_id}/start", response_model=MatchResponse) -async def start_match( - match_id: int, - payload: MatchStartRequest, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - match_obj = db.query(Match).filter(Match.id == match_id).first() +async def start_match(match_id: int, payload: MatchStartRequest, current_user=Depends(get_current_user)): + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") @@ -322,118 +337,119 @@ async def start_match( if batting_team not in {"A", "B"}: raise HTTPException(status_code=400, detail="batting_team must be A or B") - team_count = db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).count() + team_count = len(list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id)) if team_count == 0: raise HTTPException(status_code=400, detail="Please set teams first") - match_obj.status = "live" - match_obj.current_innings = 1 - match_obj.batting_team = batting_team - db.commit() - db.refresh(match_obj) + match_obj = update_doc( + COLL.matches, + match_id, + {"status": "live", "current_innings": 1, "batting_team": batting_team, "updated_at": now_utc()}, + ) log_action("Started match", user_id=current_user.id, details=f"match_id={match_id}") - return match_obj + return as_obj(match_obj) @router.post("/{match_id}/ball") -async def record_ball_event( - match_id: int, - payload: BallEventCreate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - match_obj = db.query(Match).filter(Match.id == match_id).first() +async def record_ball_event(match_id: int, payload: BallEventCreate, current_user=Depends(get_current_user)): + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") ensure_match_editor(match_obj, current_user) - if match_obj.status != "live": + if match_obj.get("status") != "live": raise HTTPException(status_code=400, detail="Match is not live") if payload.runs_off_bat < 0 or payload.extras < 0: raise HTTPException(status_code=400, detail="Runs and extras cannot be negative") - innings_in_use = match_obj.current_innings or payload.innings - batting_team_in_use = (match_obj.batting_team or payload.batting_team or "").upper().strip() + innings_in_use = match_obj.get("current_innings") or payload.innings + batting_team_in_use = (match_obj.get("batting_team") or payload.batting_team or "").upper().strip() if batting_team_in_use not in {"A", "B"}: raise HTTPException(status_code=400, detail="batting_team must be A or B") - auto_over_number, auto_ball_number = get_next_delivery_position(db, match_id, innings_in_use) + auto_over_number, auto_ball_number = get_next_delivery_position(match_id, innings_in_use) legal_ball = payload.extra_type not in {"wide", "no_ball"} - # Enforce innings over limit for legal balls only - current_legal = ( - db.query(BallEvent) - .filter(BallEvent.match_id == match_id, BallEvent.innings == innings_in_use) - .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"]))) - .count() + current_events = list_docs( + COLL.ball_events, + predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == innings_in_use, ) - if legal_ball and current_legal >= (match_obj.overs_per_innings * 6): + current_legal = len([e for e in current_events if e.get("extra_type") not in {"wide", "no_ball"}]) + + if legal_ball and current_legal >= (int(match_obj.get("overs_per_innings", 20)) * 6): raise HTTPException(status_code=400, detail="Innings overs limit reached") - event = BallEvent( - match_id=match_id, - innings=innings_in_use, - over_number=auto_over_number, - ball_number=auto_ball_number, - batting_team=batting_team_in_use, - striker_id=payload.striker_id, - bowler_id=payload.bowler_id, - runs_off_bat=payload.runs_off_bat, - extras=payload.extras, - extra_type=payload.extra_type, - is_wicket=payload.is_wicket, - wicket_type=payload.wicket_type, - commentary=payload.commentary, - created_by_id=current_user.id, + create_doc( + COLL.ball_events, + { + "match_id": match_id, + "innings": innings_in_use, + "over_number": auto_over_number, + "ball_number": auto_ball_number, + "batting_team": batting_team_in_use, + "striker_id": payload.striker_id, + "bowler_id": payload.bowler_id, + "runs_off_bat": payload.runs_off_bat, + "extras": payload.extras, + "extra_type": payload.extra_type, + "is_wicket": payload.is_wicket, + "wicket_type": payload.wicket_type, + "commentary": payload.commentary, + "created_by_id": current_user.id, + "created_at": now_utc(), + }, ) - db.add(event) - db.commit() - - scoreboard = build_scoreboard(db, match_obj, innings_in_use) + refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) + scoreboard = build_scoreboard(refreshed_match, innings_in_use) innings_over = False match_completed = False - team_player_count = get_batting_side_player_count(db, match_id, batting_team_in_use) - all_out_limit = max(1, team_player_count - 1) + team_player_count = get_batting_side_player_count(match_id, batting_team_in_use) + # All out when all players are dismissed (not team_player_count - 1) + all_out_limit = team_player_count if team_player_count > 0 and scoreboard.wickets >= all_out_limit: innings_over = True if innings_in_use == 1: - match_obj.current_innings = 2 - match_obj.batting_team = "B" if batting_team_in_use == "A" else "A" - db.commit() - db.refresh(match_obj) + update_doc( + COLL.matches, + match_id, + { + "current_innings": 2, + "batting_team": "B" if batting_team_in_use == "A" else "A", + "updated_at": now_utc(), + }, + ) else: - match_obj.status = "completed" - db.commit() - db.refresh(match_obj) + update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()}) match_completed = True + refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) + if not match_completed and innings_in_use == 2: - first_team, second_team = get_innings_teams(db, match_id, batting_team_in_use) - team_a_runs, team_b_runs, _, _ = get_team_totals(db, match_id) + first_team, second_team = get_innings_teams(match_id, batting_team_in_use) + team_a_runs, team_b_runs, _, _ = get_team_totals(match_id) first_score = team_a_runs if first_team == "A" else team_b_runs second_score = team_a_runs if second_team == "A" else team_b_runs if second_score > first_score: - match_obj.status = "completed" - db.commit() - db.refresh(match_obj) + update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()}) + refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) match_completed = True innings_over = True - next_innings = match_obj.current_innings or innings_in_use - next_over_number, next_ball_number = get_next_delivery_position(db, match_id, next_innings) + next_innings = refreshed_match.get("current_innings") or innings_in_use + next_over_number, next_ball_number = get_next_delivery_position(match_id, next_innings) return { "message": "Ball recorded", "innings_over": innings_over, "match_completed": match_completed, - "match_status": match_obj.status, + "match_status": refreshed_match.get("status"), "recorded_ball": { "innings": innings_in_use, "over_number": auto_over_number, @@ -443,42 +459,31 @@ async def record_ball_event( "innings": next_innings, "over_number": next_over_number, "ball_number": next_ball_number, - "batting_team": match_obj.batting_team, + "batting_team": refreshed_match.get("batting_team"), }, "scoreboard": scoreboard, } @router.get("/{match_id}/scoreboard", response_model=MatchScoreboardResponse) -async def get_match_scoreboard( - match_id: int, - innings: int = 1, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): +async def get_match_scoreboard(match_id: int, innings: int = 1, current_user=Depends(get_current_user)): _ = current_user - match_obj = db.query(Match).filter(Match.id == match_id).first() + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") - return build_scoreboard(db, match_obj, innings) + return build_scoreboard(match_obj, innings) @router.post("/{match_id}/complete", response_model=MatchResponse) -async def complete_match( - match_id: int, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - match_obj = db.query(Match).filter(Match.id == match_id).first() +async def complete_match(match_id: int, current_user=Depends(get_current_user)): + match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id) if not match_obj: raise HTTPException(status_code=404, detail="Match not found") ensure_match_editor(match_obj, current_user) - match_obj.status = "completed" - db.commit() - db.refresh(match_obj) + match_obj = update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()}) log_action("Completed match", user_id=current_user.id, details=f"match_id={match_id}") - return match_obj + return as_obj(match_obj) diff --git a/backend/app/routes/notifications.py b/backend/app/routes/notifications.py index 6c2e0557c2269414ed94b57b26a1533996aedf02..9d9b788468fb1710bfda8a8c50f8acc33772f70b 100644 --- a/backend/app/routes/notifications.py +++ b/backend/app/routes/notifications.py @@ -1,35 +1,61 @@ -from datetime import datetime +from datetime import datetime, timezone from fastapi import APIRouter, Depends, HTTPException -from sqlalchemy.orm import Session -from app.database import get_db -from app.models import Notification, User + from app.middleware.auth import get_current_user from app.schemas import NotificationResponse +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime from app.utils.logger import log_action -from app.utils.premium import check_and_downgrade_premium router = APIRouter(prefix="/notifications", tags=["Notifications"]) +def _downgrade_if_expired(user: dict) -> bool: + expiry = user.get("premium_expiry") + if user.get("is_premium") and expiry: + # Parse expiry to timezone-aware datetime + expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry + + # Ensure expiry_dt is timezone-aware + if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None: + expiry_dt = expiry_dt.replace(tzinfo=timezone.utc) + + # Check if premium has expired + if expiry_dt and now_utc() >= expiry_dt: + update_doc(COLL.users, user["id"], {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}) + create_doc( + COLL.notifications, + { + "user_id": user["id"], + "title": "Premium Membership Expired", + "message": "Your premium membership has expired. Upgrade again to get featured!", + "notification_type": "premium_expiry", + "is_read": False, + "created_at": now_utc(), + }, + ) + return True + return False + + @router.get("/me", response_model=list[NotificationResponse]) -async def get_my_notifications( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Get notifications for current user.""" - notifications = db.query(Notification).filter( - Notification.user_id == current_user.id - ).order_by(Notification.created_at.desc()).limit(100).all() - return notifications +async def get_my_notifications(current_user=Depends(get_current_user)): + notifications = list_docs( + COLL.notifications, + predicate=lambda row: row.get("user_id") == current_user.id, + sort_key="created_at", + reverse=True, + limit=100, + ) + return [as_obj(row) for row in notifications] @router.post("/check-expiry") -async def check_premium_expiry_notification( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Create expiry warning notification if premium is close to expiry.""" - expired = check_and_downgrade_premium(db, current_user) +async def check_premium_expiry_notification(current_user=Depends(get_current_user)): + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + expired = _downgrade_if_expired(user) if expired: return { @@ -38,14 +64,15 @@ async def check_premium_expiry_notification( "notification_created": True, } - if not current_user.is_premium or not current_user.premium_expiry: + if not user.get("is_premium") or not user.get("premium_expiry"): return { "message": "No active premium subscription.", "days_left": None, "notification_created": False, } - days_left = (current_user.premium_expiry - datetime.utcnow()).total_seconds() / 86400 + expiry_dt = _parse_datetime(user["premium_expiry"]) if isinstance(user["premium_expiry"], str) else user["premium_expiry"] + days_left = (expiry_dt - now_utc()).total_seconds() / 86400 if expiry_dt else None if days_left > 3: return { @@ -61,11 +88,12 @@ async def check_premium_expiry_notification( "notification_created": False, } - existing = db.query(Notification).filter( - Notification.user_id == current_user.id, - Notification.notification_type == "premium_expiry_warning", - Notification.is_read == False, - ).first() + existing = first_doc( + COLL.notifications, + predicate=lambda row: row.get("user_id") == current_user.id + and row.get("notification_type") == "premium_expiry_warning" + and not row.get("is_read", False), + ) if existing: return { @@ -74,14 +102,17 @@ async def check_premium_expiry_notification( "notification_created": False, } - notification = Notification( - user_id=current_user.id, - title="Premium Expiry Reminder", - message=f"Your premium membership expires in {int(round(days_left))} day(s). Renew to stay featured.", - notification_type="premium_expiry_warning", + create_doc( + COLL.notifications, + { + "user_id": current_user.id, + "title": "Premium Expiry Reminder", + "message": f"Your premium membership expires in {int(round(days_left))} day(s). Renew to stay featured.", + "notification_type": "premium_expiry_warning", + "is_read": False, + "created_at": now_utc(), + }, ) - db.add(notification) - db.commit() log_action("Premium expiry warning created", user_id=current_user.id) @@ -93,36 +124,27 @@ async def check_premium_expiry_notification( @router.put("/{notification_id}/read") -async def mark_notification_as_read( - notification_id: int, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Mark a notification as read.""" - notification = db.query(Notification).filter( - Notification.id == notification_id, - Notification.user_id == current_user.id, - ).first() +async def mark_notification_as_read(notification_id: int, current_user=Depends(get_current_user)): + notification = first_doc( + COLL.notifications, + predicate=lambda row: row.get("id") == notification_id and row.get("user_id") == current_user.id, + ) if not notification: raise HTTPException(status_code=404, detail="Notification not found") - notification.is_read = True - db.commit() + update_doc(COLL.notifications, notification_id, {"is_read": True}) return {"message": "Notification marked as read"} @router.put("/read-all") -async def mark_all_notifications_as_read( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), -): - """Mark all notifications as read.""" - db.query(Notification).filter( - Notification.user_id == current_user.id, - Notification.is_read == False, - ).update({"is_read": True}) - db.commit() +async def mark_all_notifications_as_read(current_user=Depends(get_current_user)): + rows = list_docs( + COLL.notifications, + predicate=lambda row: row.get("user_id") == current_user.id and not row.get("is_read", False), + ) + for row in rows: + update_doc(COLL.notifications, row["id"], {"is_read": True}) return {"message": "All notifications marked as read"} diff --git a/backend/app/routes/performance.py b/backend/app/routes/performance.py index 5f2c9678d8d748aefec206bb7f665d41ecdbac36..2bcf2946124972486cd6df6c2ce3ccee8a74f7a2 100644 --- a/backend/app/routes/performance.py +++ b/backend/app/routes/performance.py @@ -1,30 +1,42 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.orm import Session -from typing import List -from app.database import get_db -from app.models import PerformanceLog, User -from app.schemas import PerformanceLogCreate, PerformanceLogUpdate, PerformanceLogResponse +from typing import List, Union + from app.middleware.auth import get_current_user +from app.schemas import PerformanceLogCreate, PerformanceLogUpdate, PerformanceLogResponse +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, delete_doc from app.utils.logger import log_action router = APIRouter(prefix="/performance", tags=["Performance"]) -def recalculate_user_career_stats(db: Session, user: User) -> None: - """Recalculate user stats from performance logs to keep career data accurate.""" - logs = db.query(PerformanceLog).filter(PerformanceLog.user_id == user.id).all() - - user.matches = len(logs) - user.runs = sum(log.runs_scored for log in logs) - user.wickets = sum(log.wickets_taken for log in logs) - user.centuries = sum(1 for log in logs if log.runs_scored >= 100) - user.half_centuries = sum(1 for log in logs if 50 <= log.runs_scored < 100) - user.highest_score = max([log.runs_scored for log in logs], default=0) - user.average_runs = round(user.runs / user.matches, 2) if user.matches else 0.0 +def recalculate_user_career_stats(user_id: int) -> None: + logs = list_docs(COLL.performance_logs, predicate=lambda row: row.get("user_id") == user_id) + + matches = len(logs) + runs = sum(int(log.get("runs_scored", 0)) for log in logs) + wickets = sum(int(log.get("wickets_taken", 0)) for log in logs) + centuries = sum(1 for log in logs if int(log.get("runs_scored", 0)) >= 100) + half_centuries = sum(1 for log in logs if 50 <= int(log.get("runs_scored", 0)) < 100) + highest_score = max([int(log.get("runs_scored", 0)) for log in logs], default=0) + average_runs = round(runs / matches, 2) if matches else 0.0 + + update_doc( + COLL.users, + user_id, + { + "matches": matches, + "runs": runs, + "wickets": wickets, + "centuries": centuries, + "half_centuries": half_centuries, + "highest_score": highest_score, + "average_runs": average_runs, + "updated_at": now_utc(), + }, + ) -def build_ai_insights(logs: List[PerformanceLog]) -> dict: - """Generate lightweight AI-style insights using recent performance trends.""" +def build_ai_insights(logs: List[dict]) -> dict: if not logs: return { "headline": "No recent match data", @@ -39,12 +51,12 @@ def build_ai_insights(logs: List[PerformanceLog]) -> dict: } recent = logs[:5] - avg_runs = sum(item.runs_scored for item in recent) / len(recent) - avg_wickets = sum(item.wickets_taken for item in recent) / len(recent) - avg_rating = sum(item.performance_rating for item in recent) / len(recent) + avg_runs = sum(float(item.get("runs_scored", 0)) for item in recent) / len(recent) + avg_wickets = sum(float(item.get("wickets_taken", 0)) for item in recent) / len(recent) + avg_rating = sum(float(item.get("performance_rating", 0)) for item in recent) / len(recent) - first_runs = recent[-1].runs_scored - latest_runs = recent[0].runs_scored + first_runs = float(recent[-1].get("runs_scored", 0)) + latest_runs = float(recent[0].get("runs_scored", 0)) run_trend = latest_runs - first_runs if avg_rating >= 8: @@ -96,81 +108,79 @@ def build_ai_insights(logs: List[PerformanceLog]) -> dict: @router.post("", response_model=PerformanceLogResponse) async def log_performance( performance: PerformanceLogCreate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): - """Log a match performance""" - if performance.runs_scored < 0 or performance.wickets_taken < 0: raise HTTPException(status_code=400, detail="Runs and wickets cannot be negative") - perf_log = PerformanceLog( - user_id=current_user.id, - match_date=performance.match_date, - runs_scored=performance.runs_scored, - wickets_taken=performance.wickets_taken, - match_type=performance.match_type, - opponent=performance.opponent, - performance_rating=performance.performance_rating, - notes=performance.notes + perf_log = create_doc( + COLL.performance_logs, + { + "user_id": current_user.id, + "match_date": performance.match_date, + "runs_scored": performance.runs_scored, + "wickets_taken": performance.wickets_taken, + "match_type": performance.match_type, + "opponent": performance.opponent, + "performance_rating": performance.performance_rating, + "notes": performance.notes, + "created_at": now_utc(), + }, ) - db.add(perf_log) - db.flush() - recalculate_user_career_stats(db, current_user) - db.commit() - db.refresh(perf_log) - - log_action("Performance logged", user_id=current_user.id, - details=f"{performance.runs_scored} runs") - - return perf_log + recalculate_user_career_stats(current_user.id) + log_action("Performance logged", user_id=current_user.id, details=f"{performance.runs_scored} runs") + return as_obj(perf_log) @router.get("/my-logs", response_model=List[PerformanceLogResponse]) async def get_my_performance_logs( - current_user: User = Depends(get_current_user), + current_user=Depends(get_current_user), skip: int = 0, limit: int = 20, - db: Session = Depends(get_db) ): - """Get current player's performance logs""" - - logs = db.query(PerformanceLog).filter( - PerformanceLog.user_id == current_user.id - ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all() - - return logs + logs = list_docs( + COLL.performance_logs, + predicate=lambda row: row.get("user_id") == current_user.id, + sort_key="match_date", + reverse=True, + offset=skip, + limit=limit, + ) + return [as_obj(row) for row in logs] @router.get("/match-history") async def get_my_match_history( - current_user: User = Depends(get_current_user), + current_user=Depends(get_current_user), skip: int = 0, limit: int = 30, - db: Session = Depends(get_db), ): - """Get structured match history with summary for dashboard and profile views.""" - logs = db.query(PerformanceLog).filter( - PerformanceLog.user_id == current_user.id - ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all() + logs = list_docs( + COLL.performance_logs, + predicate=lambda row: row.get("user_id") == current_user.id, + sort_key="match_date", + reverse=True, + offset=skip, + limit=limit, + ) - total_runs = sum(log.runs_scored for log in logs) - total_wickets = sum(log.wickets_taken for log in logs) + total_runs = sum(int(log.get("runs_scored", 0)) for log in logs) + total_wickets = sum(int(log.get("wickets_taken", 0)) for log in logs) average_rating = round( - sum(log.performance_rating for log in logs) / len(logs), 2 + sum(float(log.get("performance_rating", 0)) for log in logs) / len(logs), 2 ) if logs else 0.0 best_match = None if logs: - top = max(logs, key=lambda item: (item.runs_scored + (item.wickets_taken * 20))) + top = max(logs, key=lambda item: (int(item.get("runs_scored", 0)) + (int(item.get("wickets_taken", 0)) * 20))) best_match = { - "id": top.id, - "match_date": top.match_date, - "opponent": top.opponent, - "runs_scored": top.runs_scored, - "wickets_taken": top.wickets_taken, - "performance_rating": top.performance_rating, + "id": top.get("id"), + "match_date": top.get("match_date"), + "opponent": top.get("opponent"), + "runs_scored": top.get("runs_scored"), + "wickets_taken": top.get("wickets_taken"), + "performance_rating": top.get("performance_rating"), } return { @@ -181,7 +191,7 @@ async def get_my_match_history( "average_rating": average_rating, "best_match": best_match, }, - "logs": logs, + "logs": [as_obj(row) for row in logs], } @@ -189,14 +199,12 @@ async def get_my_match_history( async def update_performance_log( log_id: int, payload: PerformanceLogUpdate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), + current_user=Depends(get_current_user), ): - """Edit an existing performance log for the current player.""" - perf_log = db.query(PerformanceLog).filter( - PerformanceLog.id == log_id, - PerformanceLog.user_id == current_user.id, - ).first() + perf_log = first_doc( + COLL.performance_logs, + predicate=lambda row: row.get("id") == log_id and row.get("user_id") == current_user.id, + ) if not perf_log: raise HTTPException(status_code=404, detail="Performance log not found") @@ -208,36 +216,28 @@ async def update_performance_log( if "wickets_taken" in updates and updates["wickets_taken"] < 0: raise HTTPException(status_code=400, detail="Wickets cannot be negative") - for key, value in updates.items(): - setattr(perf_log, key, value) - - recalculate_user_career_stats(db, current_user) - db.commit() - db.refresh(perf_log) + perf_log = update_doc(COLL.performance_logs, log_id, updates) + recalculate_user_career_stats(current_user.id) log_action("Performance log updated", user_id=current_user.id, details=f"log_id={log_id}") - return perf_log + return as_obj(perf_log) @router.delete("/{log_id}") async def delete_performance_log( log_id: int, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), + current_user=Depends(get_current_user), ): - """Delete a performance log and recalculate career stats.""" - perf_log = db.query(PerformanceLog).filter( - PerformanceLog.id == log_id, - PerformanceLog.user_id == current_user.id, - ).first() + perf_log = first_doc( + COLL.performance_logs, + predicate=lambda row: row.get("id") == log_id and row.get("user_id") == current_user.id, + ) if not perf_log: raise HTTPException(status_code=404, detail="Performance log not found") - db.delete(perf_log) - db.flush() - recalculate_user_career_stats(db, current_user) - db.commit() + delete_doc(COLL.performance_logs, log_id) + recalculate_user_career_stats(current_user.id) log_action("Performance log deleted", user_id=current_user.id, details=f"log_id={log_id}") return {"message": "Performance log deleted"} @@ -245,70 +245,63 @@ async def delete_performance_log( @router.get("/player/{player_id}", response_model=List[PerformanceLogResponse]) async def get_player_performance_logs( - player_id: int, + player_id: Union[int, str], skip: int = 0, limit: int = 20, - db: Session = Depends(get_db) ): - """Get a player's performance logs""" - - # Check if player exists - player = db.query(User).filter(User.id == player_id).first() + player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id) if not player: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Player not found" - ) - - logs = db.query(PerformanceLog).filter( - PerformanceLog.user_id == player_id - ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all() + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found") + + logs = list_docs( + COLL.performance_logs, + predicate=lambda row: row.get("user_id") == player_id, + sort_key="match_date", + reverse=True, + offset=skip, + limit=limit, + ) - return logs + return [as_obj(row) for row in logs] @router.get("/stats/{player_id}") -async def get_player_stats(player_id: int, db: Session = Depends(get_db)): - """Get player statistics summary""" - - player = db.query(User).filter(User.id == player_id).first() +async def get_player_stats(player_id: Union[int, str]): + player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id) if not player: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Player not found" - ) + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found") return { - "id": player.id, - "name": player.name, - "runs": player.runs, - "matches": player.matches, - "wickets": player.wickets, - "centuries": player.centuries, - "half_centuries": player.half_centuries, - "average_runs": player.average_runs, - "highest_score": player.highest_score + "id": player.get("id"), + "name": player.get("name"), + "runs": player.get("runs", 0), + "matches": player.get("matches", 0), + "wickets": player.get("wickets", 0), + "centuries": player.get("centuries", 0), + "half_centuries": player.get("half_centuries", 0), + "average_runs": player.get("average_runs", 0.0), + "highest_score": player.get("highest_score", 0), } @router.get("/ai-insights/{player_id}") -async def get_player_ai_insights(player_id: int, db: Session = Depends(get_db)): - """Generate AI-based performance insights from recent match logs.""" - player = db.query(User).filter(User.id == player_id).first() +async def get_player_ai_insights(player_id: Union[int, str]): + player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id) if not player: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Player not found", - ) - - logs = db.query(PerformanceLog).filter( - PerformanceLog.user_id == player_id - ).order_by(PerformanceLog.match_date.desc()).limit(10).all() + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found") + + logs = list_docs( + COLL.performance_logs, + predicate=lambda row: row.get("user_id") == player_id, + sort_key="match_date", + reverse=True, + limit=10, + ) return { - "player_id": player.id, - "player_name": player.name, + "player_id": player.get("id"), + "player_name": player.get("name"), "insights": build_ai_insights(logs), } diff --git a/backend/app/routes/players.py b/backend/app/routes/players.py index 2b4e6b53f84156b2ea4b134b86c7df97337b4495..d5611c0b25ea21db301b87e7f32ad033f1996772 100644 --- a/backend/app/routes/players.py +++ b/backend/app/routes/players.py @@ -1,151 +1,190 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.orm import Session -from typing import List -from app.database import get_db -from app.models import User +from typing import List, Union from app.schemas import UserResponse, UserUpdate, CareerStatsUpdate from app.middleware.auth import get_current_user -from app.utils.premium import check_and_downgrade_premium +from app.utils.firestore_data import COLL, as_obj, first_doc, list_docs, now_utc, update_doc, _parse_datetime, normalize_user from app.utils.logger import log_action router = APIRouter(prefix="/players", tags=["Players"]) +def _check_and_downgrade_premium(user: dict) -> dict: + from datetime import datetime, timezone + + expiry = user.get("premium_expiry") + if user.get("is_premium") and expiry: + # Parse expiry to timezone-aware datetime + expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry + + # Ensure expiry_dt is timezone-aware + if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None: + expiry_dt = expiry_dt.replace(tzinfo=timezone.utc) + + # Check if premium has expired + if expiry_dt and now_utc() >= expiry_dt: + # Use _doc_id (actual Firestore document ID) if available, otherwise use id + doc_id = user.get("_doc_id") or user.get("id") + user = update_doc( + COLL.users, + doc_id, + {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}, + ) or user + return user + + @router.get("/me", response_model=UserResponse) -async def get_current_player(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)): +async def get_current_player(current_user=Depends(get_current_user)): """Get current logged-in player's profile""" - check_and_downgrade_premium(db, current_user) - db.refresh(current_user) - log_action("Viewed own profile", user_id=current_user.id) - return current_user + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="Player not found") + user = _check_and_downgrade_premium(user) + log_action("Viewed own profile", user_id=user["id"]) + return normalize_user(user) @router.put("/me", response_model=UserResponse) async def update_current_player( user_update: UserUpdate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): """Update current player's profile""" + patch = {"updated_at": now_utc()} if user_update.name: - current_user.name = user_update.name + patch["name"] = user_update.name if user_update.bio is not None: - current_user.bio = user_update.bio + patch["bio"] = user_update.bio if user_update.jersey_number is not None: - current_user.jersey_number = user_update.jersey_number - - db.commit() - db.refresh(current_user) - - log_action("Updated profile", user_id=current_user.id) - return current_user + patch["jersey_number"] = user_update.jersey_number + + user = update_doc(COLL.users, current_user.id, patch) + if not user: + raise HTTPException(status_code=404, detail="Player not found") + + log_action("Updated profile", user_id=user["id"]) + return normalize_user(user) @router.put("/me/career-stats", response_model=UserResponse) async def update_career_stats( stats_update: CareerStatsUpdate, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db), + current_user=Depends(get_current_user), ): """Update current player's career statistics""" + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="Player not found") + + patch = {"updated_at": now_utc()} + if stats_update.runs is not None: if stats_update.runs < 0: raise HTTPException(status_code=400, detail="Runs cannot be negative") - current_user.runs = stats_update.runs + patch["runs"] = stats_update.runs if stats_update.matches is not None: if stats_update.matches < 0: raise HTTPException(status_code=400, detail="Matches cannot be negative") - current_user.matches = stats_update.matches + patch["matches"] = stats_update.matches if stats_update.wickets is not None: if stats_update.wickets < 0: raise HTTPException(status_code=400, detail="Wickets cannot be negative") - current_user.wickets = stats_update.wickets + patch["wickets"] = stats_update.wickets if stats_update.centuries is not None: if stats_update.centuries < 0: raise HTTPException(status_code=400, detail="Centuries cannot be negative") - current_user.centuries = stats_update.centuries + patch["centuries"] = stats_update.centuries if stats_update.half_centuries is not None: if stats_update.half_centuries < 0: raise HTTPException(status_code=400, detail="Half-centuries cannot be negative") - current_user.half_centuries = stats_update.half_centuries + patch["half_centuries"] = stats_update.half_centuries if stats_update.highest_score is not None: if stats_update.highest_score < 0: raise HTTPException(status_code=400, detail="Highest score cannot be negative") - current_user.highest_score = stats_update.highest_score + patch["highest_score"] = stats_update.highest_score - if current_user.matches > 0: - current_user.average_runs = round(current_user.runs / current_user.matches, 2) + runs = patch.get("runs", user.get("runs", 0)) + matches = patch.get("matches", user.get("matches", 0)) + if matches > 0: + patch["average_runs"] = round(runs / matches, 2) else: - current_user.average_runs = 0.0 + patch["average_runs"] = 0.0 - db.commit() - db.refresh(current_user) + user = update_doc(COLL.users, current_user.id, patch) + if not user: + raise HTTPException(status_code=404, detail="Player not found") - log_action("Updated career stats", user_id=current_user.id) - return current_user + log_action("Updated career stats", user_id=user["id"]) + return normalize_user(user) @router.get("", response_model=List[UserResponse]) -async def list_all_players(skip: int = 0, limit: int = 50, db: Session = Depends(get_db)): +async def list_all_players(skip: int = 0, limit: int = 50): """Get list of all active players""" - players = db.query(User).filter(User.is_active == True).offset(skip).limit(limit).all() - - for player in players: - check_and_downgrade_premium(db, player) - - return players + players = list_docs( + COLL.users, + predicate=lambda row: row.get("is_active", True), + sort_key="created_at", + reverse=True, + offset=skip, + limit=limit, + ) + return [normalize_user(_check_and_downgrade_premium(player)) for player in players] @router.get("/premium", response_model=List[UserResponse]) -async def get_premium_players(db: Session = Depends(get_db)): +async def get_premium_players(): """Get list of premium players""" - premium_players = db.query(User).filter( - User.is_premium == True, - User.is_active == True - ).order_by(User.runs.desc()).all() - - for player in premium_players: - check_and_downgrade_premium(db, player) - - return premium_players + premium_players = list_docs( + COLL.users, + predicate=lambda row: row.get("is_active", True) and row.get("is_premium", False), + sort_key="runs", + reverse=True, + ) + return [normalize_user(_check_and_downgrade_premium(player)) for player in premium_players] @router.get("/leaderboard/top-performers", response_model=List[UserResponse]) -async def get_top_performers(limit: int = 10, db: Session = Depends(get_db)): +async def get_top_performers(limit: int = 10): """Get top performers by runs""" - top_players = db.query(User).filter(User.is_active == True).order_by( - User.runs.desc() - ).limit(limit).all() - - return top_players + top_players = list_docs( + COLL.users, + predicate=lambda row: row.get("is_active", True), + sort_key="runs", + reverse=True, + limit=limit, + ) + return [normalize_user(row) for row in top_players] @router.get("/leaderboard/by-wickets", response_model=List[UserResponse]) -async def get_top_wicket_takers(limit: int = 10, db: Session = Depends(get_db)): +async def get_top_wicket_takers(limit: int = 10): """Get top wicket takers""" - top_wicket_takers = db.query(User).filter(User.is_active == True).order_by( - User.wickets.desc() - ).limit(limit).all() - - return top_wicket_takers + top_wicket_takers = list_docs( + COLL.users, + predicate=lambda row: row.get("is_active", True), + sort_key="wickets", + reverse=True, + limit=limit, + ) + return [normalize_user(row) for row in top_wicket_takers] @router.get("/{player_id}", response_model=UserResponse) -async def get_player(player_id: int, db: Session = Depends(get_db)): +async def get_player(player_id: Union[int, str]): """Get player profile by ID""" - player = db.query(User).filter(User.id == player_id).first() + player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id) if not player: raise HTTPException( @@ -153,7 +192,5 @@ async def get_player(player_id: int, db: Session = Depends(get_db)): detail="Player not found" ) - check_and_downgrade_premium(db, player) - db.refresh(player) - - return player + player = _check_and_downgrade_premium(player) + return normalize_user(player) diff --git a/backend/app/routes/premium.py b/backend/app/routes/premium.py index eeab0e9730d121caa6dd2edb2a601d8a44be60bb..2626f271a9e37ad391eb4f674b9527f392ff1277 100644 --- a/backend/app/routes/premium.py +++ b/backend/app/routes/premium.py @@ -1,11 +1,8 @@ from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.orm import Session from datetime import datetime, timedelta -from app.database import get_db -from app.models import User, Payment, FinanceTransaction from app.schemas import PremiumUpgradeRequest, PremiumResponse, PaymentResponse from app.middleware.auth import get_current_user -from app.utils.premium import upgrade_to_premium, check_and_downgrade_premium +from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime from app.utils.logger import log_action, log_error import uuid @@ -15,104 +12,160 @@ router = APIRouter(prefix="/premium", tags=["Premium"]) @router.post("/upgrade", response_model=PremiumResponse) async def upgrade_to_premium_plan( request_data: PremiumUpgradeRequest, - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): """Upgrade player to premium membership""" - if current_user.is_premium: + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + if user.get("is_premium"): # Extend premium period - new_expiry = current_user.premium_expiry + timedelta(days=request_data.plan_days) - current_user.premium_expiry = new_expiry + current_expiry = user.get("premium_expiry", now_utc()) + if isinstance(current_expiry, str): + current_expiry = _parse_datetime(current_expiry) or now_utc() + new_expiry = current_expiry + timedelta(days=request_data.plan_days) + user = update_doc( + COLL.users, + user["id"], + {"premium_expiry": new_expiry, "updated_at": now_utc()}, + ) or user else: # New premium membership - upgrade_to_premium(db, current_user, request_data.plan_days) + user = update_doc( + COLL.users, + user["id"], + { + "is_premium": True, + "premium_start_date": now_utc(), + "premium_expiry": now_utc() + timedelta(days=request_data.plan_days), + "updated_at": now_utc(), + }, + ) or user # Create payment record - payment = Payment( - user_id=current_user.id, - amount=1000, # ₹1000 - transaction_id=str(uuid.uuid4()), - status="completed", - plan_duration_days=request_data.plan_days + transaction_id = str(uuid.uuid4()) + create_doc( + COLL.payments, + { + "user_id": user["id"], + "amount": 1000.0, + "payment_method": "razorpay", + "transaction_id": transaction_id, + "status": "completed", + "plan_duration_days": request_data.plan_days, + "created_at": now_utc(), + "updated_at": now_utc(), + }, ) - finance_entry = FinanceTransaction( - user_id=current_user.id, - transaction_type="credit", - amount=1000, - category="premium_payment", - description=f"Premium payment by {current_user.email}", - reference_id=payment.transaction_id, + create_doc( + COLL.finance_transactions, + { + "user_id": user["id"], + "transaction_type": "credit", + "amount": 1000.0, + "category": "premium_payment", + "description": f"Premium payment by {user.get('email')}", + "reference_id": transaction_id, + "created_at": now_utc(), + }, ) - db.add(payment) - db.add(finance_entry) - db.commit() - db.refresh(current_user) - - log_action("Premium upgrade", user_id=current_user.id, details=f"{request_data.plan_days} days") + log_action("Premium upgrade", user_id=user["id"], details=f"{request_data.plan_days} days") return { - "is_premium": current_user.is_premium, - "premium_expiry": current_user.premium_expiry, + "is_premium": user.get("is_premium", False), + "premium_expiry": user.get("premium_expiry"), "message": f"Successfully upgraded to premium for {request_data.plan_days} days!" } @router.get("/status", response_model=PremiumResponse) async def get_premium_status( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): """Get current premium status""" - check_and_downgrade_premium(db, current_user) - db.refresh(current_user) + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + expiry = user.get("premium_expiry") + if user.get("is_premium") and expiry: + from datetime import timezone + # Parse expiry to timezone-aware datetime + expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry + + # Ensure expiry_dt is timezone-aware + if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None: + expiry_dt = expiry_dt.replace(tzinfo=timezone.utc) + + # Check if premium has expired + if expiry_dt and now_utc() >= expiry_dt: + user = update_doc( + COLL.users, + user["id"], + {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}, + ) or user - if current_user.is_premium: - message = f"Premium active until {current_user.premium_expiry.strftime('%Y-%m-%d')}" + if user.get("is_premium"): + expiry = user.get("premium_expiry") + from datetime import timezone + # Ensure timezone-aware datetime for formatting + if isinstance(expiry, str): + expiry = _parse_datetime(expiry) or now_utc() + elif isinstance(expiry, datetime) and expiry.tzinfo is None: + expiry = expiry.replace(tzinfo=timezone.utc) + message = f"Premium active until {expiry.strftime('%Y-%m-%d')}" if expiry else "Premium active" else: message = "Not a premium member. Upgrade to get featured!" return { - "is_premium": current_user.is_premium, - "premium_expiry": current_user.premium_expiry, + "is_premium": user.get("is_premium", False), + "premium_expiry": user.get("premium_expiry"), "message": message } @router.post("/cancel") async def cancel_premium( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): """Cancel premium membership""" - if not current_user.is_premium: + user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id) + if not user: + raise HTTPException(status_code=404, detail="User not found") + + if not user.get("is_premium"): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="User is not a premium member" ) - current_user.is_premium = False - current_user.premium_expiry = None - db.commit() + update_doc( + COLL.users, + user["id"], + {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}, + ) - log_action("Premium cancelled", user_id=current_user.id) + log_action("Premium cancelled", user_id=user["id"]) return {"message": "Premium membership cancelled"} @router.get("/payments", response_model=list) async def get_payment_history( - current_user: User = Depends(get_current_user), - db: Session = Depends(get_db) + current_user=Depends(get_current_user), ): """Get payment history""" - payments = db.query(Payment).filter(Payment.user_id == current_user.id).order_by( - Payment.created_at.desc() - ).all() - - return payments + payments = list_docs( + COLL.payments, + predicate=lambda row: row.get("user_id") == current_user.id, + sort_key="created_at", + reverse=True, + ) + return [as_obj(row) for row in payments] diff --git a/backend/app/schemas/chat.py b/backend/app/schemas/chat.py index 7c774d1b8096f84e9000ff3954f0c6f206846318..374caeb53c06b7eabd12106471a4c99aef6571a5 100644 --- a/backend/app/schemas/chat.py +++ b/backend/app/schemas/chat.py @@ -1,5 +1,6 @@ from pydantic import BaseModel from datetime import datetime +from typing import Union class AdminChatCreate(BaseModel): @@ -8,7 +9,7 @@ class AdminChatCreate(BaseModel): class AdminChatResponse(BaseModel): id: int - user_id: int + user_id: Union[int, str] sender_role: str message: str is_read: bool diff --git a/backend/app/schemas/finance.py b/backend/app/schemas/finance.py index ef37532f6701e61adad16ddcec21d4b996fb090b..bfbb62f953fc1ce99061b9efb5842513c8e6c077 100644 --- a/backend/app/schemas/finance.py +++ b/backend/app/schemas/finance.py @@ -1,6 +1,6 @@ from pydantic import BaseModel from datetime import datetime -from typing import Optional +from typing import Optional, Union class GuestFundRequest(BaseModel): @@ -11,13 +11,13 @@ class GuestFundRequest(BaseModel): class ManualCreditRequest(BaseModel): amount: float - user_id: Optional[int] = None + user_id: Optional[Union[int, str]] = None notes: Optional[str] = None class FinanceTransactionResponse(BaseModel): id: int - user_id: Optional[int] + user_id: Optional[Union[int, str]] transaction_type: str amount: float category: str diff --git a/backend/app/schemas/match.py b/backend/app/schemas/match.py index 61fa170d7a784a0ae9f2a6c389bb48acccabdeee..cc4ab5d32b05f00f74fb8aa9cc200b339c15f9fe 100644 --- a/backend/app/schemas/match.py +++ b/backend/app/schemas/match.py @@ -1,5 +1,5 @@ from datetime import datetime -from typing import List, Optional +from typing import List, Optional, Union from pydantic import BaseModel @@ -14,7 +14,7 @@ class MatchCreate(BaseModel): class MatchResponse(BaseModel): id: int title: str - created_by_id: int + created_by_id: Union[int, str] team_a_name: str team_b_name: str overs_per_innings: int @@ -28,12 +28,12 @@ class MatchResponse(BaseModel): class MatchTeamSetupRequest(BaseModel): - team_a_player_ids: List[int] - team_b_player_ids: List[int] + team_a_player_ids: List[Union[int, str]] + team_b_player_ids: List[Union[int, str]] class MatchPlayerView(BaseModel): - user_id: int + user_id: Union[int, str] name: str team: str @@ -53,8 +53,8 @@ class BallEventCreate(BaseModel): over_number: int ball_number: int batting_team: str # A or B - striker_id: Optional[int] = None - bowler_id: Optional[int] = None + striker_id: Optional[Union[int, str]] = None + bowler_id: Optional[Union[int, str]] = None runs_off_bat: int = 0 extras: int = 0 extra_type: Optional[str] = None @@ -99,3 +99,4 @@ class MatchScoreboardResponse(BaseModel): team_b_runs: int winner_team: Optional[str] = None result_text: Optional[str] = None + all_balls: List[BallEventResponse] = [] diff --git a/backend/app/schemas/notification.py b/backend/app/schemas/notification.py index 59c89eed34d9a8ed459158f6f1862868b2b43c66..613f577ca3c232d46a41171acdcd5ba399f70c7a 100644 --- a/backend/app/schemas/notification.py +++ b/backend/app/schemas/notification.py @@ -1,10 +1,11 @@ from pydantic import BaseModel from datetime import datetime +from typing import Union class NotificationResponse(BaseModel): id: int - user_id: int + user_id: Union[int, str] title: str message: str notification_type: str diff --git a/backend/app/schemas/payment.py b/backend/app/schemas/payment.py index 12a019ac9789c18e151f7a8cf4f4c534e1c5fa2b..cc871ea3165b03e723ad1efc3bb0abdf29bacd5d 100644 --- a/backend/app/schemas/payment.py +++ b/backend/app/schemas/payment.py @@ -1,6 +1,6 @@ from pydantic import BaseModel from datetime import datetime -from typing import Optional +from typing import Optional, Union class PaymentRequest(BaseModel): @@ -10,7 +10,7 @@ class PaymentRequest(BaseModel): class PaymentResponse(BaseModel): id: int - user_id: int + user_id: Union[int, str] amount: float status: str transaction_id: str diff --git a/backend/app/schemas/performance.py b/backend/app/schemas/performance.py index 9b27341da34f8297944cd76bdd706d3825a04f79..3badcdd4490dba0c048baac94b7a8e6ca0c67164 100644 --- a/backend/app/schemas/performance.py +++ b/backend/app/schemas/performance.py @@ -1,6 +1,6 @@ from pydantic import BaseModel from datetime import datetime -from typing import Optional +from typing import Optional, Union class PerformanceLogCreate(BaseModel): @@ -25,7 +25,7 @@ class PerformanceLogUpdate(BaseModel): class PerformanceLogResponse(BaseModel): id: int - user_id: int + user_id: Union[int, str] match_date: datetime runs_scored: int wickets_taken: int diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.py index 51e2a617d5c6a4a219483593965928353a190b3b..4b6fb989800db76d856ae6ebcf4b2dd9d73aaf2e 100644 --- a/backend/app/schemas/user.py +++ b/backend/app/schemas/user.py @@ -1,6 +1,6 @@ -from pydantic import BaseModel, EmailStr +from pydantic import BaseModel, EmailStr, Field from datetime import datetime -from typing import Optional +from typing import Optional, Union class UserRegister(BaseModel): @@ -15,7 +15,7 @@ class UserLogin(BaseModel): class UserResponse(BaseModel): - id: int + id: Union[int, str] = Field(..., description="User ID (can be integer or Firebase UID string)") name: str email: str role: str @@ -30,7 +30,7 @@ class UserResponse(BaseModel): highest_score: int is_premium: bool premium_expiry: Optional[datetime] = None - created_at: datetime + created_at: Optional[datetime] = None is_active: bool class Config: diff --git a/backend/app/utils/__init__.py b/backend/app/utils/__init__.py index 17e3ff880d331d08169844a74c74f3fce13374e3..6f35c924afdfa94baa8fe097730431a3de1391d8 100644 --- a/backend/app/utils/__init__.py +++ b/backend/app/utils/__init__.py @@ -6,9 +6,8 @@ from app.utils.auth import ( ) from app.utils.premium import ( check_and_downgrade_premium, - upgrade_to_premium, calculate_average_runs, - get_player_rank, + premium_patch, ) from app.utils.logger import log_action, log_error @@ -18,9 +17,8 @@ __all__ = [ "create_access_token", "decode_token", "check_and_downgrade_premium", - "upgrade_to_premium", "calculate_average_runs", - "get_player_rank", + "premium_patch", "log_action", "log_error", ] diff --git a/backend/app/utils/auth.py b/backend/app/utils/auth.py index c61ab6a87e242bfb2c9e40f31c1746eae1a3f4cb..6c16c380e36504e56a72eed7691291abc9ce2a6b 100644 --- a/backend/app/utils/auth.py +++ b/backend/app/utils/auth.py @@ -1,9 +1,18 @@ from passlib.context import CryptContext -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Optional from jose import JWTError, jwt from app.config import settings from fastapi import HTTPException, status +import logging +import json +import os + +import firebase_admin +from firebase_admin import auth as firebase_auth, credentials + +logger = logging.getLogger(__name__) +_firebase_initialized = False pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") @@ -23,28 +32,84 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) - to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt +def _init_firebase_if_needed() -> None: + global _firebase_initialized + + if _firebase_initialized: + return + + if firebase_admin._apps: + _firebase_initialized = True + return + + if settings.FIREBASE_SERVICE_ACCOUNT_JSON: + try: + account_info = json.loads(settings.FIREBASE_SERVICE_ACCOUNT_JSON) + cred = credentials.Certificate(account_info) + firebase_admin.initialize_app(cred) + _firebase_initialized = True + return + except Exception as e: + logger.warning("Firebase init from JSON failed: %s", str(e)) + + if settings.FIREBASE_SERVICE_ACCOUNT_PATH: + path = settings.FIREBASE_SERVICE_ACCOUNT_PATH + if os.path.exists(path): + try: + cred = credentials.Certificate(path) + firebase_admin.initialize_app(cred) + _firebase_initialized = True + return + except Exception as e: + logger.warning("Firebase init from service account path failed: %s", str(e)) + + logger.warning("Firebase Auth is enabled but service account credentials are not configured correctly") + + def decode_token(token: str): - """Decode and validate JWT token""" + """Decode and validate JWT token (legacy local JWT + Firebase ID token).""" + # 1) Legacy local JWT support try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) email: str = payload.get("sub") - if email is None: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - ) - return {"email": email} + if email: + return { + "email": email, + "sub": payload.get("sub"), + "name": payload.get("name"), + } except JWTError: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - ) + pass + + # 2) Firebase ID token support + if settings.FIREBASE_AUTH_ENABLED: + _init_firebase_if_needed() + if _firebase_initialized: + try: + decoded = firebase_auth.verify_id_token(token) + email = decoded.get("email") + name = decoded.get("name") + sub = decoded.get("uid") or decoded.get("sub") + + if email: + return { + "email": email, + "sub": sub, + "name": name, + } + except Exception as e: + logger.warning("Firebase token validation failed: %s", str(e)) + + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + ) diff --git a/backend/app/utils/cache.py b/backend/app/utils/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..a3648e72b7063dc784e6f6f49686acc1a2cae4ad --- /dev/null +++ b/backend/app/utils/cache.py @@ -0,0 +1,65 @@ +"""Simple in-memory caching with TTL for dashboard endpoints.""" +from datetime import datetime, timezone, timedelta +from typing import Any, Callable, Optional +import json + + +class CacheEntry: + def __init__(self, value: Any, ttl_seconds: int): + self.value = value + self.created_at = datetime.now(timezone.utc) + self.ttl_seconds = ttl_seconds + + def is_expired(self) -> bool: + elapsed = (datetime.now(timezone.utc) - self.created_at).total_seconds() + return elapsed >= self.ttl_seconds + + +class SimpleCache: + """Thread-safe cache with TTL expiration.""" + + def __init__(self): + self._cache: dict[str, CacheEntry] = {} + + def get(self, key: str) -> Optional[Any]: + """Get value from cache if it exists and hasn't expired.""" + if key in self._cache: + entry = self._cache[key] + if not entry.is_expired(): + return entry.value + else: + # Clean up expired entry + del self._cache[key] + return None + + def set(self, key: str, value: Any, ttl_seconds: int = 300): + """Store value in cache with TTL (default 5 minutes).""" + self._cache[key] = CacheEntry(value, ttl_seconds) + + def clear(self, key: str = None): + """Clear specific key or entire cache.""" + if key: + self._cache.pop(key, None) + else: + self._cache.clear() + + def get_or_fetch( + self, key: str, fetch_fn: Callable[[], Any], ttl_seconds: int = 300 + ) -> Any: + """Get from cache or fetch and cache the result.""" + cached = self.get(key) + if cached is not None: + return cached + + value = fetch_fn() + self.set(key, value, ttl_seconds) + return value + + +# Global cache instance +_cache = SimpleCache() + + +def get_cache() -> SimpleCache: + """Get the global cache instance.""" + return _cache diff --git a/backend/app/utils/firestore.py b/backend/app/utils/firestore.py new file mode 100644 index 0000000000000000000000000000000000000000..0527ef39fd5c93576e66a1adc788f2e5e96ccba6 --- /dev/null +++ b/backend/app/utils/firestore.py @@ -0,0 +1,63 @@ +from datetime import datetime +from typing import Any + +import firebase_admin +from firebase_admin import firestore + +from app.config import settings +from app.utils.auth import _init_firebase_if_needed + + +def _get_firestore_client(): + """Return Firestore client when Firebase is configured, else None.""" + if not settings.FIREBASE_AUTH_ENABLED: + return None + + _init_firebase_if_needed() + if not firebase_admin._apps: + return None + + return firestore.client() + + +def _serialize_datetime(value: datetime | None) -> str | None: + if value is None: + return None + return value.isoformat() + + +def sync_user_profile_to_firestore(user: Any) -> None: + """Upsert a SQL user profile into Firestore to support phased DB migration.""" + client = _get_firestore_client() + if client is None: + return + + doc_id = str(getattr(user, "id", "")) + if not doc_id: + return + + payload = { + "id": doc_id, + "name": getattr(user, "name", None), + "email": getattr(user, "email", None), + "role": getattr(user, "role", "player"), + "jersey_number": getattr(user, "jersey_number", None), + "bio": getattr(user, "bio", None), + "runs": getattr(user, "runs", 0), + "matches": getattr(user, "matches", 0), + "wickets": getattr(user, "wickets", 0), + "centuries": getattr(user, "centuries", 0), + "half_centuries": getattr(user, "half_centuries", 0), + "average_runs": getattr(user, "average_runs", 0.0), + "highest_score": getattr(user, "highest_score", 0), + "is_premium": getattr(user, "is_premium", False), + "premium_expiry": _serialize_datetime(getattr(user, "premium_expiry", None)), + "premium_start_date": _serialize_datetime(getattr(user, "premium_start_date", None)), + "is_active": getattr(user, "is_active", True), + "created_at": _serialize_datetime(getattr(user, "created_at", None)), + "updated_at": _serialize_datetime(getattr(user, "updated_at", None)), + "last_login": _serialize_datetime(getattr(user, "last_login", None)), + "source": "sql-mirror", + } + + client.collection("users").document(doc_id).set(payload, merge=True) diff --git a/backend/app/utils/firestore_data.py b/backend/app/utils/firestore_data.py new file mode 100644 index 0000000000000000000000000000000000000000..6c813c55155b9440861cec2d05380eba009e20b7 --- /dev/null +++ b/backend/app/utils/firestore_data.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone +from types import SimpleNamespace +from typing import Any, Callable + +import firebase_admin +from firebase_admin import firestore + +from app.config import settings +from app.utils.auth import _init_firebase_if_needed + + +@dataclass +class CollectionNames: + users: str = "users" + payments: str = "payments" + performance_logs: str = "performance_logs" + notifications: str = "notifications" + finance_transactions: str = "finance_transactions" + admin_chat_messages: str = "admin_chat_messages" + matches: str = "matches" + match_players: str = "match_players" + ball_events: str = "ball_events" + + +COLL = CollectionNames() + + +def _client(): + if not settings.FIREBASE_AUTH_ENABLED: + raise RuntimeError("FIREBASE_AUTH_ENABLED must be True for Firestore mode") + + _init_firebase_if_needed() + if not firebase_admin._apps: + raise RuntimeError("Firebase Admin is not initialized. Check service account config.") + + return firestore.client() + + +def _counter_doc(collection: str) -> str: + return f"counter::{collection}" + + +def next_int_id(collection: str) -> int: + client = _client() + ref = client.collection("_meta").document(_counter_doc(collection)) + snap = ref.get() + current = 0 + if snap.exists: + current = int((snap.to_dict() or {}).get("value", 0)) + new_value = current + 1 + ref.set({"value": new_value}, merge=True) + return new_value + + +def now_utc() -> datetime: + return datetime.now(timezone.utc) + + +def create_doc(collection: str, data: dict[str, Any], doc_id: str | None = None) -> dict[str, Any]: + client = _client() + payload = dict(data) + if doc_id is None: + doc_id = str(payload.get("id") or next_int_id(collection)) + payload.setdefault("id", int(doc_id) if doc_id.isdigit() else doc_id) + client.collection(collection).document(doc_id).set(payload, merge=True) + return payload + + +def get_doc(collection: str, doc_id: str | int) -> dict[str, Any] | None: + client = _client() + snap = client.collection(collection).document(str(doc_id)).get() + if not snap.exists: + return None + data = snap.to_dict() or {} + if "id" not in data: + data["id"] = int(str(doc_id)) if str(doc_id).isdigit() else str(doc_id) + return data + + +def update_doc(collection: str, doc_id: str | int, patch: dict[str, Any]) -> dict[str, Any] | None: + existing = get_doc(collection, doc_id) + if not existing: + return None + merged = dict(existing) + merged.update(patch) + create_doc(collection, merged, str(doc_id)) + return merged + + +def delete_doc(collection: str, doc_id: str | int) -> bool: + client = _client() + snap = client.collection(collection).document(str(doc_id)).get() + if not snap.exists: + return False + client.collection(collection).document(str(doc_id)).delete() + return True + +def _parse_datetime(value: Any) -> datetime | None: + """Parse a value to datetime if it's a datetime string. Always returns timezone-aware UTC.""" + if isinstance(value, datetime): + # If naive, make it aware as UTC + if value.tzinfo is None: + return value.replace(tzinfo=timezone.utc) + return value + if isinstance(value, str): + try: + # Only try parsing if it looks like ISO format (contains T or -) + if 'T' in value or (value.count('-') >= 2): + if value.endswith('Z'): + value = value.replace('Z', '+00:00') + dt = datetime.fromisoformat(value) + # If naive, make it aware as UTC + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt + except (ValueError, AttributeError): + pass + return None + + +def _normalize_sort_value(value: Any) -> Any: + """Normalize a value for sorting - handle datetime and string representations.""" + if value is None: + return (0, "") + + # Try to parse as datetime + if isinstance(value, datetime): + return (1, value) + if isinstance(value, str): + parsed_dt = _parse_datetime(value) + if parsed_dt: + return (1, parsed_dt) + return (2, value) + + # Numbers (int, float) + if isinstance(value, (int, float)): + return (3, value) + + return (4, str(value)) + + +def list_docs( + collection: str, + predicate: Callable[[dict[str, Any]], bool] | None = None, + sort_key: str | None = None, + reverse: bool = False, + limit: int | None = None, + offset: int = 0, +) -> list[dict[str, Any]]: + client = _client() + rows: list[dict[str, Any]] = [] + for snap in client.collection(collection).stream(): + row = snap.to_dict() or {} + doc_id = snap.id + + # Always track the actual Firestore document ID + row["_doc_id"] = doc_id + + # If no id field, use the Firestore document ID + if "id" not in row: + row["id"] = int(doc_id) if doc_id.isdigit() else doc_id + if predicate and not predicate(row): + continue + rows.append(row) + + if sort_key: + rows.sort(key=lambda item: _normalize_sort_value(item.get(sort_key)), reverse=reverse) + + if offset: + rows = rows[offset:] + if limit is not None: + rows = rows[:limit] + return rows + + +def first_doc( + collection: str, + predicate: Callable[[dict[str, Any]], bool] | None = None, + sort_key: str | None = None, + reverse: bool = False, +) -> dict[str, Any] | None: + rows = list_docs(collection, predicate=predicate, sort_key=sort_key, reverse=reverse, limit=1) + return rows[0] if rows else None + + +def as_obj(data: dict[str, Any]) -> Any: + return SimpleNamespace(**data) + + +def normalize_user(user: dict[str, Any]) -> dict[str, Any]: + """Ensure all required user fields exist with defaults.""" + created_at = user.get("created_at") or user.get("createdAt") or now_utc() + + # Prefer uid (Firebase UID) over id for consistency across Firestore + user_id = user.get("uid") or user.get("id", "") + + defaults = { + "id": user_id, + "uid": user.get("uid") or user.get("id", ""), + "name": user.get("name", ""), + "email": user.get("email", ""), + "role": user.get("role", "player"), + "jersey_number": user.get("jersey_number"), + "bio": user.get("bio"), + "runs": int(user.get("runs", 0)) if user.get("runs") else 0, + "matches": int(user.get("matches", 0)) if user.get("matches") else 0, + "wickets": int(user.get("wickets", 0)) if user.get("wickets") else 0, + "centuries": int(user.get("centuries", 0)) if user.get("centuries") else 0, + "half_centuries": int(user.get("half_centuries", 0)) if user.get("half_centuries") else 0, + "average_runs": float(user.get("average_runs", 0.0)) if user.get("average_runs") else 0.0, + "highest_score": int(user.get("highest_score", 0)) if user.get("highest_score") else 0, + "is_premium": bool(user.get("is_premium", False)), + "premium_expiry": user.get("premium_expiry"), + "is_active": bool(user.get("is_active", True)), + "created_at": created_at, + } + return defaults diff --git a/backend/app/utils/premium.py b/backend/app/utils/premium.py index 95bc0dcd1bec52e69cea780a83526153d8fcba04..09c824ae74737e749671a8548065be8d4e4d28bb 100644 --- a/backend/app/utils/premium.py +++ b/backend/app/utils/premium.py @@ -1,60 +1,31 @@ -from datetime import datetime, timedelta -from sqlalchemy.orm import Session -from app.models import User, Notification -from app.config import settings -import pytz - - -def check_and_downgrade_premium(db: Session, user: User): - """Check if premium membership has expired and downgrade if needed""" - if user.is_premium and user.premium_expiry: - if datetime.utcnow() >= user.premium_expiry: - user.is_premium = False - user.premium_expiry = None - db.commit() - - # Create notification - notification = Notification( - user_id=user.id, - title="Premium Membership Expired", - message="Your premium membership has expired. Upgrade again to get featured!", - notification_type="premium_expiry" - ) - db.add(notification) - db.commit() - return True - return False - - -def upgrade_to_premium(db: Session, user: User, days: int = 30): - """Upgrade user to premium membership""" - user.is_premium = True - user.premium_start_date = datetime.utcnow() - user.premium_expiry = datetime.utcnow() + timedelta(days=days) - db.commit() - - # Create notification - notification = Notification( - user_id=user.id, - title="🎉 Welcome to Premium!", - message=f"You are now a premium member for {days} days! Enjoy exclusive features.", - notification_type="achievement" - ) - db.add(notification) - db.commit() - - -def calculate_average_runs(db: Session, user: User) -> float: - """Calculate average runs for a player""" - if user.matches == 0: +from datetime import datetime, timedelta, timezone +from app.utils.firestore_data import now_utc + + +def check_and_downgrade_premium(user: dict) -> bool: + """Return True when the given premium user should be downgraded.""" + if not (user.get("is_premium") and user.get("premium_expiry")): + return False + expiry = user["premium_expiry"] + if isinstance(expiry, str): + from app.utils.firestore_data import _parse_datetime + expiry = _parse_datetime(expiry) + if not isinstance(expiry, datetime): + return False + return now_utc() >= expiry + + +def premium_patch(days: int = 30) -> dict: + """Generate patch payload to set premium membership fields.""" + return { + "is_premium": True, + "premium_start_date": now_utc(), + "premium_expiry": now_utc() + timedelta(days=days), + } + + +def calculate_average_runs(user: dict) -> float: + matches = int(user.get("matches", 0) or 0) + if matches == 0: return 0.0 - return round(user.runs / user.matches, 2) - - -def get_player_rank(db: Session, user_id: int) -> int: - """Get player's rank based on runs""" - users = db.query(User).order_by(User.runs.desc()).all() - for idx, user in enumerate(users, 1): - if user.id == user_id: - return idx - return 0 + return round(float(user.get("runs", 0)) / matches, 2) diff --git a/backend/creation_log.txt b/backend/creation_log.txt new file mode 100644 index 0000000000000000000000000000000000000000..f771d46fc4f38ad64af29f0a3d83603f505f8a7a Binary files /dev/null and b/backend/creation_log.txt differ diff --git a/backend/fix_user_ids.py b/backend/fix_user_ids.py new file mode 100644 index 0000000000000000000000000000000000000000..5d625a655a24562dceb6e89f419282b5dfe61970 --- /dev/null +++ b/backend/fix_user_ids.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +""" +Fix Firestore users with inconsistent IDs. +Ensures all users have both 'id' and 'uid' fields set to their Firebase UID. +""" + +import firebase_admin +from firebase_admin import credentials, firestore +import os + +# Initialize Firebase +cred_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS', 'firebase-service-account.json') +if not firebase_admin._apps: + if os.path.exists(cred_path): + cred = credentials.Certificate(cred_path) + firebase_admin.initialize_app(cred) + else: + raise FileNotFoundError(f"Service account file not found: {cred_path}") + +db = firestore.client() + +def fix_user_ids(): + """Fix all users to have consistent Firebase UID-based IDs""" + users_ref = db.collection('users') + docs = users_ref.stream() + + fixed_count = 0 + total_count = 0 + + print("[USER ID FIX] Starting user ID normalization...\n") + + for doc in docs: + total_count += 1 + user_id = doc.id # Document ID (Firebase UID) + user_data = doc.to_dict() + + current_id = user_data.get('id') + current_uid = user_data.get('uid') + + # Check if ID fields need fixing + needs_fix = False + + # If id field is missing or is an integer (not Firebase UID style), fix it + if not current_id or (isinstance(current_id, int) or (isinstance(current_id, str) and len(current_id) < 20)): + needs_fix = True + + # If uid field is missing, fix it + if not current_uid: + needs_fix = True + + # If either id or uid doesn't match the document ID (Firebase UID), fix it + if current_id != user_id or current_uid != user_id: + needs_fix = True + + if needs_fix: + user_name = user_data.get('name', 'Unknown') + email = user_data.get('email', 'No email') + + print(f"[FIX] {user_name} ({email})") + print(f" Document ID: {user_id}") + print(f" Old 'id' field: {current_id}") + print(f" Old 'uid' field: {current_uid}") + + # Update both id and uid to match the document ID (Firebase UID) + try: + users_ref.document(user_id).update({ + 'id': user_id, + 'uid': user_id, + }) + print(f" Status: [FIXED]") + fixed_count += 1 + except Exception as e: + print(f" Status: [ERROR] {str(e)}") + print() + + print("="*70) + print(f"[RESULT] Fixed {fixed_count} out of {total_count} users") + print("="*70) + print("\nAll users should now use Firebase UID as both 'id' and 'uid'") + +if __name__ == "__main__": + try: + fix_user_ids() + except Exception as e: + print(f"[ERROR] {str(e)}") diff --git a/backend/main.py b/backend/main.py index a0eaafa74dcff0a97ea3ced7eddb956d314e4351..aa9cc1e2e43f973fd2810fd4040065c14b11cd3e 100644 --- a/backend/main.py +++ b/backend/main.py @@ -2,7 +2,6 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.openapi.utils import get_openapi from app.config import settings -from app.database import init_db from app.middleware import LoggingMiddleware, RateLimitMiddleware from app.middleware.auth import security from app.routes import ( @@ -17,9 +16,6 @@ from app.routes import ( matches_router, ) -# Initialize database -init_db() - # Create FastAPI app app = FastAPI( title=settings.API_TITLE, diff --git a/backend/requirements.txt b/backend/requirements.txt index 0b5468f75c4757e433987616d808aebaa3ceee87..bf381d47ce97b9b5a7a16eb7a3e78a705aa419ff 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,7 +1,6 @@ fastapi==0.104.1 uvicorn==0.24.0 gunicorn==21.2.0 -sqlalchemy==2.0.23 pydantic==2.5.0 pydantic-settings==2.1.0 python-dotenv==1.0.0 @@ -11,5 +10,5 @@ python-jose[cryptography]==3.3.0 email-validator==2.1.0 python-multipart==0.0.6 slowapi==0.1.9 -aiosqlite==0.19.0 pytz==2023.3 +firebase-admin==6.8.0 diff --git a/backend/seed_dummy_users_firebase.py b/backend/seed_dummy_users_firebase.py new file mode 100644 index 0000000000000000000000000000000000000000..4242630095abb1e0acb1fe2ee9ea5e4c222b56c4 --- /dev/null +++ b/backend/seed_dummy_users_firebase.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +""" +Seed Firebase with dummy player users (10 premium + 5 non-premium) +Run from backend directory: python seed_dummy_users_firebase.py +""" + +import firebase_admin +from firebase_admin import credentials, auth, firestore +from datetime import datetime, timedelta +import os + +# Initialize Firebase +cred_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS', 'firebase-service-account.json') +if not firebase_admin._apps: + if os.path.exists(cred_path): + cred = credentials.Certificate(cred_path) + firebase_admin.initialize_app(cred) + else: + raise FileNotFoundError(f"Service account file not found: {cred_path}") + +db = firestore.client() +auth_client = auth + +# Dummy user data +DUMMY_USERS = [ + # Premium players + { + "name": "Virat Kohli", + "email": "virat.kohli@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 18, + "runs": 7000, + "matches": 150, + "wickets": 0, + "centuries": 50, + "half_centuries": 35, + "highest_score": 183, + "average_runs": 46.67, + }, + { + "name": "Rohit Sharma", + "email": "rohit.sharma@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 45, + "runs": 6500, + "matches": 145, + "wickets": 0, + "centuries": 48, + "half_centuries": 38, + "highest_score": 264, + "average_runs": 44.83, + }, + { + "name": "Jasprit Bumrah", + "email": "jasprit.bumrah@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 93, + "runs": 500, + "matches": 120, + "wickets": 280, + "centuries": 0, + "half_centuries": 0, + "highest_score": 34, + "average_runs": 4.17, + }, + { + "name": "Hardik Pandya", + "email": "hardik.pandya@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 31, + "runs": 3500, + "matches": 110, + "wickets": 145, + "centuries": 5, + "half_centuries": 18, + "highest_score": 123, + "average_runs": 31.82, + }, + { + "name": "MS Dhoni", + "email": "ms.dhoni@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 7, + "runs": 5000, + "matches": 130, + "wickets": 0, + "centuries": 12, + "half_centuries": 28, + "highest_score": 156, + "average_runs": 38.46, + }, + { + "name": "Shikhar Dhawan", + "email": "shikhar.dhawan@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 25, + "runs": 6800, + "matches": 160, + "wickets": 0, + "centuries": 52, + "half_centuries": 40, + "highest_score": 192, + "average_runs": 42.50, + }, + { + "name": "KL Rahul", + "email": "kl.rahul@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 1, + "runs": 4200, + "matches": 95, + "wickets": 0, + "centuries": 18, + "half_centuries": 22, + "highest_score": 180, + "average_runs": 44.21, + }, + { + "name": "Ravichandran Ashwin", + "email": "ravichandran.ashwin@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 37, + "runs": 3200, + "matches": 140, + "wickets": 420, + "centuries": 8, + "half_centuries": 15, + "highest_score": 113, + "average_runs": 22.86, + }, + { + "name": "Yuzvendra Chahal", + "email": "yuzvendra.chahal@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 72, + "runs": 600, + "matches": 95, + "wickets": 310, + "centuries": 0, + "half_centuries": 0, + "highest_score": 38, + "average_runs": 6.32, + }, + { + "name": "Bhuvneshwar Kumar", + "email": "bhuvneshwar.kumar@example.com", + "password": "Password@123", + "is_premium": True, + "jersey_number": 33, + "runs": 400, + "matches": 110, + "wickets": 290, + "centuries": 0, + "half_centuries": 0, + "highest_score": 28, + "average_runs": 3.64, + }, + # Non-premium players + { + "name": "Prithvi Shaw", + "email": "prithvi.shaw@example.com", + "password": "Password@123", + "is_premium": False, + "jersey_number": 10, + "runs": 1200, + "matches": 35, + "wickets": 0, + "centuries": 3, + "half_centuries": 8, + "highest_score": 146, + "average_runs": 34.29, + }, + { + "name": "Ruturaj Gaikwad", + "email": "ruturaj.gaikwad@example.com", + "password": "Password@123", + "is_premium": False, + "jersey_number": 5, + "runs": 900, + "matches": 28, + "wickets": 0, + "centuries": 2, + "half_centuries": 5, + "highest_score": 128, + "average_runs": 32.14, + }, + { + "name": "Devdutt Padikkal", + "email": "devdutt.padikkal@example.com", + "password": "Password@123", + "is_premium": False, + "jersey_number": 4, + "runs": 800, + "matches": 32, + "wickets": 0, + "centuries": 1, + "half_centuries": 6, + "highest_score": 102, + "average_runs": 25.00, + }, + { + "name": "Ishan Kishan", + "email": "ishan.kishan@example.com", + "password": "Password@123", + "is_premium": False, + "jersey_number": 23, + "runs": 1100, + "matches": 40, + "wickets": 0, + "centuries": 2, + "half_centuries": 7, + "highest_score": 131, + "average_runs": 27.50, + }, + { + "name": "Shreyas Iyer", + "email": "shreyas.iyer@example.com", + "password": "Password@123", + "is_premium": False, + "jersey_number": 27, + "runs": 1500, + "matches": 50, + "wickets": 0, + "centuries": 4, + "half_centuries": 10, + "highest_score": 144, + "average_runs": 30.00, + }, +] + + +def create_firebase_users(): + """Create users in Firebase Authentication and Firestore""" + created_count = 0 + failed_count = 0 + + print(f"\n[FIREBASE] Creating {len(DUMMY_USERS)} dummy users in Firebase...\n") + + for user_data in DUMMY_USERS: + try: + email = user_data["email"] + password = user_data["password"] + name = user_data["name"] + is_premium = user_data["is_premium"] + + # Create user in Firebase Authentication + user_record = auth_client.create_user( + email=email, + password=password, + display_name=name, + ) + + uid = user_record.uid + print(f"[OK] Created Firebase Auth user: {name} ({email}) - UID: {uid[:12]}...") + + # Prepare user document for Firestore + now = datetime.utcnow() + premium_expiry = None + if is_premium: + # Premium expires 30 days from now + premium_expiry = now + timedelta(days=30) + + firestore_user = { + "id": uid, # Store Firebase UID as id + "uid": uid, # Also store as uid + "email": email, + "name": name, + "role": "player", + "is_active": True, + "is_premium": is_premium, + "premium_expiry": premium_expiry, + "premium_start_date": now if is_premium else None, + "jersey_number": user_data.get("jersey_number"), + "bio": f"Professional cricketer - {name}", + "runs": user_data.get("runs", 0), + "matches": user_data.get("matches", 0), + "wickets": user_data.get("wickets", 0), + "centuries": user_data.get("centuries", 0), + "half_centuries": user_data.get("half_centuries", 0), + "highest_score": user_data.get("highest_score", 0), + "average_runs": user_data.get("average_runs", 0.0), + "created_at": now, + "updated_at": now, + } + + # Store in Firestore using UID as document ID + db.collection("users").document(uid).set(firestore_user) + + status = "[PREMIUM]" if is_premium else "[NON-PREMIUM]" + print(f" └─ Saved to Firestore: {status}\n") + + created_count += 1 + + except auth_client.EmailAlreadyExistsError: + print(f"[WARN] User already exists: {user_data['email']}\n") + failed_count += 1 + except Exception as e: + print(f"[ERROR] Failed to create {user_data['name']}: {str(e)}\n") + failed_count += 1 + + # Print summary + print("\n" + "="*60) + print(f"[SUCCESS] Successfully created: {created_count} users") + print(f"[ERROR] Failed/Skipped: {failed_count} users") + print(f"[TOTAL] {created_count + failed_count} attempts") + print("="*60) + + # Count premium vs non-premium + premium_count = sum(1 for u in DUMMY_USERS if u["is_premium"]) + non_premium_count = len(DUMMY_USERS) - premium_count + print(f"\n[SUMMARY] User Distribution:") + print(f" [PREMIUM]: {premium_count}") + print(f" [NON-PREMIUM]: {non_premium_count}") + print("="*60 + "\n") + + +if __name__ == "__main__": + try: + create_firebase_users() + except KeyboardInterrupt: + print("\n\n[WARN] Operation cancelled by user") + except Exception as e: + print(f"\n[ERROR] Error: {str(e)}") diff --git a/backend/verify_users_created.py b/backend/verify_users_created.py new file mode 100644 index 0000000000000000000000000000000000000000..bd11a8b3066375d1cccf5f3eec97307d355b070e --- /dev/null +++ b/backend/verify_users_created.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Verify all created Firebase users""" + +import firebase_admin +from firebase_admin import credentials, firestore +import os + +cred_path = 'firebase-service-account.json' +if not firebase_admin._apps and os.path.exists(cred_path): + cred = credentials.Certificate(cred_path) + firebase_admin.initialize_app(cred) + +db = firestore.client() +users_snap = list(db.collection('users').stream()) +users = sorted(users_snap, key=lambda u: u.get('name', '')) + +premium_users = [u for u in users if u.get('is_premium')] +non_premium_users = [u for u in users if not u.get('is_premium')] + +print('='*80) +print('FIREBASE USERS CREATED') +print('='*80) +print(f'\n[PREMIUM USERS] ({len(premium_users)})') +print('-'*80) +for i, user in enumerate(premium_users, 1): + data = user.to_dict() + name = data.get('name', 'N/A') + email = data.get('email', 'N/A') + jersey = data.get('jersey_number', 0) + runs = data.get('runs', 0) + matches = data.get('matches', 0) + wickets = data.get('wickets', 0) + print(f'{i:2}. {name:30} | {email}') + print(f' Jersey: {jersey:3} | Runs: {runs:5} | Matches: {matches:3} | Wickets: {wickets:3}') + +print(f'\n[NON-PREMIUM USERS] ({len(non_premium_users)})') +print('-'*80) +for i, user in enumerate(non_premium_users, 1): + data = user.to_dict() + name = data.get('name', 'N/A') + email = data.get('email', 'N/A') + jersey = data.get('jersey_number', 0) + runs = data.get('runs', 0) + matches = data.get('matches', 0) + wickets = data.get('wickets', 0) + print(f'{i:2}. {name:30} | {email}') + print(f' Jersey: {jersey:3} | Runs: {runs:5} | Matches: {matches:3} | Wickets: {wickets:3}') + +print('\n' + '='*80) +print(f'TOTAL USERS: {len(users)} (Premium: {len(premium_users)}, Non-Premium: {len(non_premium_users)})') +print('='*80) +print('\nLogin credentials:') +print(' Password: Password@123 (for all users)') +print('='*80) diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index f1c3487b9fc30564e831f32a91a7b417db4ef4f1..6c06eb0d98010096ed3a5c6db519e5f7c7b19ea2 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -19,6 +19,12 @@ services: dockerfile: Dockerfile.prod args: VITE_API_URL: /api + VITE_FIREBASE_API_KEY: ${VITE_FIREBASE_API_KEY-} + VITE_FIREBASE_AUTH_DOMAIN: ${VITE_FIREBASE_AUTH_DOMAIN-} + VITE_FIREBASE_PROJECT_ID: ${VITE_FIREBASE_PROJECT_ID-} + VITE_FIREBASE_STORAGE_BUCKET: ${VITE_FIREBASE_STORAGE_BUCKET-} + VITE_FIREBASE_MESSAGING_SENDER_ID: ${VITE_FIREBASE_MESSAGING_SENDER_ID-} + VITE_FIREBASE_APP_ID: ${VITE_FIREBASE_APP_ID-} ports: - "80:80" depends_on: diff --git a/frontend/.env.example b/frontend/.env.example index 551017ccac869f1636325c2caa09e7e7b311dba5..bafdd5cd7899fdbd517f5886b08a6650b3ef6082 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -2,4 +2,10 @@ # Local development backend VITE_API_URL=http://localhost:8000 +VITE_FIREBASE_API_KEY= +VITE_FIREBASE_AUTH_DOMAIN= +VITE_FIREBASE_PROJECT_ID= +VITE_FIREBASE_STORAGE_BUCKET= +VITE_FIREBASE_MESSAGING_SENDER_ID= +VITE_FIREBASE_APP_ID= VITE_APP_TITLE=SSC - Sculpt Soft Cricketers diff --git a/frontend/.env.production.example b/frontend/.env.production.example index cf4318be0637bef024b9b0e90b9bfb03a92ad54d..c4ec30c8a419082749cc9c0d96dab330f651b96a 100644 --- a/frontend/.env.production.example +++ b/frontend/.env.production.example @@ -1,4 +1,10 @@ # Frontend production build variables # For docker+nginx deployment keep this as /api VITE_API_URL=/api +VITE_FIREBASE_API_KEY= +VITE_FIREBASE_AUTH_DOMAIN= +VITE_FIREBASE_PROJECT_ID= +VITE_FIREBASE_STORAGE_BUCKET= +VITE_FIREBASE_MESSAGING_SENDER_ID= +VITE_FIREBASE_APP_ID= VITE_APP_TITLE=SSC - Sculpt Soft Cricketers diff --git a/frontend/Dockerfile.prod b/frontend/Dockerfile.prod index fd9f3a0f12a293894fef088ca650d2a34687e397..85198380ffbdb5bbc374979d6669408708745cf8 100644 --- a/frontend/Dockerfile.prod +++ b/frontend/Dockerfile.prod @@ -3,12 +3,24 @@ FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ -RUN npm ci +RUN npm install COPY . . ARG VITE_API_URL=/api ENV VITE_API_URL=${VITE_API_URL} +ARG VITE_FIREBASE_API_KEY= +ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY} +ARG VITE_FIREBASE_AUTH_DOMAIN= +ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN} +ARG VITE_FIREBASE_PROJECT_ID= +ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID} +ARG VITE_FIREBASE_STORAGE_BUCKET= +ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET} +ARG VITE_FIREBASE_MESSAGING_SENDER_ID= +ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID} +ARG VITE_FIREBASE_APP_ID= +ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID} RUN npm run build FROM nginx:1.27-alpine diff --git a/frontend/index.html b/frontend/index.html index 6aa8d58f7fcca144c41d1935a538bfb01cac8ebe..4b2405f638b96425e8b5f55af83d9038e02a614d 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,7 +2,18 @@
- + + + + + + + + + + + +