Hkoradiya123 commited on
Commit
48eca97
·
1 Parent(s): 9ffce66

feat: Add Firebase user management scripts and PWA enhancements

Browse files

- Created `fix_user_ids.py` to ensure all Firestore users have consistent IDs.
- Developed `seed_dummy_users_firebase.py` to populate Firebase with dummy player users.
- Implemented `verify_users_created.py` to verify and display created Firebase users.
- Added `manifest.json` for PWA configuration with app details and icons.
- Introduced `service-worker.js` for caching and offline capabilities.
- Created `PWAInstallGuide.jsx` component to guide users on installing the PWA.
- Established `firebase.js` utility for Firebase app initialization and configuration.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +2 -0
  2. Dockerfile +17 -5
  3. Dockerfile.huggingface +13 -1
  4. PWA_INSTALLATION_GUIDE.md +128 -0
  5. PWA_SETUP_CHECK.sh +87 -0
  6. backend/.env.example +5 -1
  7. backend/app/config.py +16 -3
  8. backend/app/database.py +11 -19
  9. backend/app/middleware/auth.py +40 -10
  10. backend/app/routes/admin.py +119 -183
  11. backend/app/routes/auth.py +37 -25
  12. backend/app/routes/dashboard.py +159 -120
  13. backend/app/routes/finance.py +70 -105
  14. backend/app/routes/matches.py +231 -226
  15. backend/app/routes/notifications.py +78 -56
  16. backend/app/routes/performance.py +135 -142
  17. backend/app/routes/players.py +108 -71
  18. backend/app/routes/premium.py +106 -53
  19. backend/app/schemas/chat.py +2 -1
  20. backend/app/schemas/finance.py +3 -3
  21. backend/app/schemas/match.py +8 -7
  22. backend/app/schemas/notification.py +2 -1
  23. backend/app/schemas/payment.py +2 -2
  24. backend/app/schemas/performance.py +2 -2
  25. backend/app/schemas/user.py +4 -4
  26. backend/app/utils/__init__.py +2 -4
  27. backend/app/utils/auth.py +79 -14
  28. backend/app/utils/cache.py +65 -0
  29. backend/app/utils/firestore.py +63 -0
  30. backend/app/utils/firestore_data.py +220 -0
  31. backend/app/utils/premium.py +30 -59
  32. backend/creation_log.txt +0 -0
  33. backend/fix_user_ids.py +85 -0
  34. backend/main.py +0 -4
  35. backend/requirements.txt +1 -2
  36. backend/seed_dummy_users_firebase.py +332 -0
  37. backend/verify_users_created.py +54 -0
  38. docker-compose.prod.yml +6 -0
  39. frontend/.env.example +6 -0
  40. frontend/.env.production.example +6 -0
  41. frontend/Dockerfile.prod +13 -1
  42. frontend/index.html +12 -1
  43. frontend/package-lock.json +1012 -6
  44. frontend/package.json +7 -6
  45. frontend/public/manifest.json +63 -0
  46. frontend/public/service-worker.js +106 -0
  47. frontend/src/App.jsx +34 -30
  48. frontend/src/components/Navbar.jsx +3 -4
  49. frontend/src/components/PWAInstallGuide.jsx +164 -0
  50. frontend/src/main.jsx +94 -0
.gitignore CHANGED
@@ -29,3 +29,5 @@ logs/
29
  .vscode/
30
  .idea/
31
  venv/
 
 
 
29
  .vscode/
30
  .idea/
31
  venv/
32
+ backend/firebase-service-account.json
33
+ backend/*firebase-adminsdk*.json
Dockerfile CHANGED
@@ -3,12 +3,24 @@ FROM node:18-alpine AS frontend-builder
3
  WORKDIR /app/frontend
4
 
5
  COPY frontend/package*.json ./
6
- RUN npm ci
7
 
8
  COPY frontend/ .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
 
 
 
 
 
 
 
 
 
 
 
 
12
  RUN npm run build
13
 
14
  # ============================================
@@ -22,13 +34,13 @@ WORKDIR /app
22
 
23
  # Install Nginx
24
  RUN apt-get update && apt-get install -y --no-install-recommends \
25
- nginx \
26
- && rm -rf /var/lib/apt/lists/*
27
 
28
  # Copy and install Python dependencies
29
  COPY backend/requirements.txt ./
30
  RUN pip install --no-cache-dir --upgrade pip && \
31
- pip install --no-cache-dir -r requirements.txt
32
 
33
  # Copy backend code
34
  COPY backend/ ./backend/
@@ -43,7 +55,7 @@ COPY nginx-huggingface.conf /etc/nginx/conf.d/default.conf
43
  COPY docker-entrypoint.sh /app/
44
  RUN chmod +x /app/docker-entrypoint.sh
45
 
46
- # Create data directory for SQLite
47
  RUN mkdir -p /app/data
48
 
49
  EXPOSE 7860
 
3
  WORKDIR /app/frontend
4
 
5
  COPY frontend/package*.json ./
6
+ RUN npm install
7
 
8
  COPY frontend/ .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
12
+ ARG VITE_FIREBASE_API_KEY=
13
+ ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY}
14
+ ARG VITE_FIREBASE_AUTH_DOMAIN=
15
+ ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN}
16
+ ARG VITE_FIREBASE_PROJECT_ID=
17
+ ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID}
18
+ ARG VITE_FIREBASE_STORAGE_BUCKET=
19
+ ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET}
20
+ ARG VITE_FIREBASE_MESSAGING_SENDER_ID=
21
+ ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID}
22
+ ARG VITE_FIREBASE_APP_ID=
23
+ ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID}
24
  RUN npm run build
25
 
26
  # ============================================
 
34
 
35
  # Install Nginx
36
  RUN apt-get update && apt-get install -y --no-install-recommends \
37
+ nginx \
38
+ && rm -rf /var/lib/apt/lists/*
39
 
40
  # Copy and install Python dependencies
41
  COPY backend/requirements.txt ./
42
  RUN pip install --no-cache-dir --upgrade pip && \
43
+ pip install --no-cache-dir -r requirements.txt
44
 
45
  # Copy backend code
46
  COPY backend/ ./backend/
 
55
  COPY docker-entrypoint.sh /app/
56
  RUN chmod +x /app/docker-entrypoint.sh
57
 
58
+ # Create data directory for SQLite fallback
59
  RUN mkdir -p /app/data
60
 
61
  EXPOSE 7860
Dockerfile.huggingface CHANGED
@@ -3,12 +3,24 @@ FROM node:18-alpine AS frontend-builder
3
  WORKDIR /app/frontend
4
 
5
  COPY frontend/package*.json ./
6
- RUN npm ci
7
 
8
  COPY frontend/ .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
 
 
 
 
 
 
 
 
 
 
 
 
12
  RUN npm run build
13
 
14
  # ============================================
 
3
  WORKDIR /app/frontend
4
 
5
  COPY frontend/package*.json ./
6
+ RUN npm install
7
 
8
  COPY frontend/ .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
12
+ ARG VITE_FIREBASE_API_KEY=
13
+ ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY}
14
+ ARG VITE_FIREBASE_AUTH_DOMAIN=
15
+ ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN}
16
+ ARG VITE_FIREBASE_PROJECT_ID=
17
+ ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID}
18
+ ARG VITE_FIREBASE_STORAGE_BUCKET=
19
+ ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET}
20
+ ARG VITE_FIREBASE_MESSAGING_SENDER_ID=
21
+ ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID}
22
+ ARG VITE_FIREBASE_APP_ID=
23
+ ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID}
24
  RUN npm run build
25
 
26
  # ============================================
PWA_INSTALLATION_GUIDE.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PWA Installation Guide - SSC (Sculpt Soft Cricketers)
2
+
3
+ ## What is a PWA?
4
+
5
+ A **Progressive Web App (PWA)** is a web application that can be installed on your device like a native app. It provides:
6
+ - ✅ Fast loading times
7
+ - ✅ Offline functionality
8
+ - ✅ Push notifications support
9
+ - ✅ Home screen icon
10
+ - ✅ Full-screen experience (no browser bar)
11
+
12
+ ---
13
+
14
+ ## How to Install SSC App
15
+
16
+ ### **On Android (Chrome, Edge, Opera)**
17
+ 1. **Look for the install banner** at the bottom of the screen
18
+ - Or tap the menu icon (⋮) in the top-right corner
19
+
20
+ 2. **Tap "Install" or "Install app"**
21
+ - Confirm any prompts
22
+
23
+ 3. **The app will be added to your home screen**
24
+ - You can now open it like any other app
25
+
26
+ ### **On iOS (Safari)**
27
+ 1. **Tap the Share button** (square with arrow ↗️)
28
+
29
+ 2. **Scroll down and tap "Add to Home Screen"**
30
+
31
+ 3. **Enter a name** (or keep "SSC")
32
+
33
+ 4. **Tap "Add"** to confirm
34
+
35
+ 5. **The app will appear on your home screen**
36
+ - Open it anytime like a regular app
37
+
38
+ ### **On Desktop/Windows (Chrome, Edge)**
39
+ 1. **Look for the install icon** in the address bar (usually on the right side)
40
+ - Or use the menu → "Install SSC"
41
+
42
+ 2. **Click the icon to install**
43
+
44
+ 3. **Confirm the installation**
45
+
46
+ 4. **The app will launch in a window** without the browser bar
47
+
48
+ ### **On macOS (Safari, Chrome)**
49
+ 1. **Same as Desktop Windows steps above**
50
+ - Or use Safari menu → File → "Add to Dock" (if available)
51
+
52
+ ---
53
+
54
+ ## Features After Installation
55
+
56
+ Once installed, you get:
57
+
58
+ ### **✨ Better Performance**
59
+ - Faster loading from cache
60
+ - Works instantly on return visits
61
+
62
+ ### **📱 App Experience**
63
+ - No browser address bar
64
+ - Full screen experience
65
+ - Feels like a native app
66
+
67
+ ### **🌐 Offline Support**
68
+ - View previously loaded matches
69
+ - Queue actions while offline
70
+ - Auto-sync when reconnected
71
+
72
+ ### **🔔 Quick Access**
73
+ - Home screen icon
74
+ - App switcher access
75
+ - Faster than bookmarks
76
+
77
+ ---
78
+
79
+ ## Troubleshooting
80
+
81
+ ### **"Install" option not showing?**
82
+ - **Android**: Make sure you're using Chrome, Edge, or Opera
83
+ - **iOS**: Must use Safari; Chrome doesn't support PWA installation on iOS
84
+ - **Desktop**: Try using Chrome or Edge instead of Firefox
85
+
86
+ ### **App not working offline?**
87
+ - Some features require internet (live scoring, sync)
88
+ - Basic match viewing should work offline
89
+ - Reload the app to force cache update
90
+
91
+ ### **Want to remove the app?**
92
+ - **Android**: Long-press the app icon → "Uninstall"
93
+ - **iOS**: Long-press the app icon → "Remove App" → "Remove from Home Screen"
94
+ - **Desktop**: Remove like any other application from your system
95
+
96
+ ---
97
+
98
+ ## How PWA Works
99
+
100
+ The app uses:
101
+ - **Service Worker**: Caches app files for faster loading
102
+ - **Manifest**: Defines app metadata (name, icons, colors)
103
+ - **HTTPS**: Secure connection for safe installation
104
+
105
+ All your data is stored locally in your browser and synced with our servers when online.
106
+
107
+ ---
108
+
109
+ ## Security & Privacy
110
+
111
+ - ✅ All data encrypted in transit (HTTPS)
112
+ - ✅ Local storage is separate per device
113
+ - ✅ No tracking or ads
114
+ - ✅ Same privacy policy as web version
115
+
116
+ ---
117
+
118
+ ## Questions?
119
+
120
+ For technical issues:
121
+ 1. **Clear app cache**: Settings → Apps → SSC → Storage → Clear Cache
122
+ 2. **Reinstall**: Uninstall and install again from the address bar
123
+ 3. **Update**: The app auto-updates in the background
124
+ 4. **Fallback**: Visit the web version at https://ssc.app
125
+
126
+ ---
127
+
128
+ **Enjoy SSC in app form!** 🏏
PWA_SETUP_CHECK.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # PWA Checklist - Verify Installation
3
+
4
+ echo "=========================================="
5
+ echo "SSC PWA Setup Verification"
6
+ echo "=========================================="
7
+ echo ""
8
+
9
+ # Check manifest.json
10
+ echo "✓ Checking manifest.json..."
11
+ if [ -f "frontend/public/manifest.json" ]; then
12
+ echo " ✅ manifest.json exists"
13
+ if grep -q '"display": "standalone"' frontend/public/manifest.json; then
14
+ echo " ✅ display mode set to 'standalone'"
15
+ fi
16
+ if grep -q '"icons"' frontend/public/manifest.json; then
17
+ echo " ✅ icons configured"
18
+ fi
19
+ else
20
+ echo " ❌ manifest.json not found"
21
+ fi
22
+ echo ""
23
+
24
+ # Check service-worker.js
25
+ echo "✓ Checking service-worker.js..."
26
+ if [ -f "frontend/public/service-worker.js" ]; then
27
+ echo " ✅ service-worker.js exists"
28
+ if grep -q "CACHE_NAME" frontend/public/service-worker.js; then
29
+ echo " ✅ caching strategy implemented"
30
+ fi
31
+ if grep -q "beforeinstallprompt" frontend/public/service-worker.js; then
32
+ echo " ✅ install prompt handler ready"
33
+ fi
34
+ else
35
+ echo " ❌ service-worker.js not found"
36
+ fi
37
+ echo ""
38
+
39
+ # Check index.html
40
+ echo "✓ Checking index.html..."
41
+ if [ -f "frontend/index.html" ]; then
42
+ echo " ✅ index.html exists"
43
+ if grep -q 'manifest.json' frontend/index.html; then
44
+ echo " ✅ manifest.json link present"
45
+ fi
46
+ if grep -q 'meta name="theme-color"' frontend/index.html; then
47
+ echo " ✅ theme-color meta tag set"
48
+ fi
49
+ if grep -q 'apple-mobile-web-app-capable' frontend/index.html; then
50
+ echo " ✅ iOS PWA support configured"
51
+ fi
52
+ else
53
+ echo " ❌ index.html not found"
54
+ fi
55
+ echo ""
56
+
57
+ # Check main.jsx service worker registration
58
+ echo "✓ Checking service worker registration..."
59
+ if grep -q "navigator.serviceWorker.register" frontend/src/main.jsx; then
60
+ echo " ✅ Service worker registration code present"
61
+ fi
62
+ if grep -q "beforeinstallprompt" frontend/src/main.jsx; then
63
+ echo " ✅ Install prompt handler in main.jsx"
64
+ fi
65
+ echo ""
66
+
67
+ # Check PWA Install Guide component
68
+ echo "✓ Checking PWA components..."
69
+ if [ -f "frontend/src/components/PWAInstallGuide.jsx" ]; then
70
+ echo " ✅ PWAInstallGuide.jsx component exists"
71
+ fi
72
+ if grep -q "PWAInstallGuide" frontend/src/App.jsx; then
73
+ echo " ✅ PWAInstallGuide imported in App.jsx"
74
+ fi
75
+ echo ""
76
+
77
+ echo "=========================================="
78
+ echo "PWA Setup Complete! ✅"
79
+ echo "=========================================="
80
+ echo ""
81
+ echo "Next steps:"
82
+ echo "1. Run: npm run dev"
83
+ echo "2. Visit: http://localhost:3000"
84
+ echo "3. Look for install prompt/button"
85
+ echo "4. On Android: Install from browser menu"
86
+ echo "5. On iOS: Use Share → Add to Home Screen"
87
+ echo ""
backend/.env.example CHANGED
@@ -1,4 +1,3 @@
1
- DATABASE_URL=sqlite:////app/data/ssc.db
2
  SECRET_KEY=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET
3
  ALGORITHM=HS256
4
  ACCESS_TOKEN_EXPIRE_MINUTES=30
@@ -14,3 +13,8 @@ API_TITLE=SSC API
14
  API_VERSION=1.0.0
15
  DEBUG=False
16
  CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
 
 
 
 
 
 
 
1
  SECRET_KEY=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET
2
  ALGORITHM=HS256
3
  ACCESS_TOKEN_EXPIRE_MINUTES=30
 
13
  API_VERSION=1.0.0
14
  DEBUG=False
15
  CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
16
+ FIREBASE_AUTH_ENABLED=True
17
+ FIREBASE_PROJECT_ID=
18
+ FIREBASE_WEB_API_KEY=
19
+ FIREBASE_SERVICE_ACCOUNT_PATH=./firebase-service-account.json
20
+ FIREBASE_SERVICE_ACCOUNT_JSON=
backend/app/config.py CHANGED
@@ -24,9 +24,6 @@ def env_first_bool(keys: list[str], default: bool) -> bool:
24
 
25
 
26
  class Settings(BaseSettings):
27
- # Database
28
- DATABASE_URL: str = env_first(["DATABASE_URL", "DATABASEURL"], "sqlite:///./ssc.db")
29
-
30
  # Security
31
  SECRET_KEY: str = env_first(["SECRET_KEY", "SECRETKEY"], "dev-secret-key-change-in-production")
32
  ALGORITHM: str = env_first(["ALGORITHM"], "HS256")
@@ -63,6 +60,22 @@ class Settings(BaseSettings):
63
  "http://localhost:3000,http://127.0.0.1:3000",
64
  )
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  @property
67
  def cors_origins_list(self) -> list[str]:
68
  return [origin.strip() for origin in self.CORS_ORIGINS.split(",") if origin.strip()]
 
24
 
25
 
26
  class Settings(BaseSettings):
 
 
 
27
  # Security
28
  SECRET_KEY: str = env_first(["SECRET_KEY", "SECRETKEY"], "dev-secret-key-change-in-production")
29
  ALGORITHM: str = env_first(["ALGORITHM"], "HS256")
 
60
  "http://localhost:3000,http://127.0.0.1:3000",
61
  )
62
 
63
+ # Firebase Auth integration
64
+ FIREBASE_AUTH_ENABLED: bool = env_first_bool(
65
+ ["FIREBASE_AUTH_ENABLED", "FIREBASEAUTHENABLED"],
66
+ False,
67
+ )
68
+ FIREBASE_PROJECT_ID: str = env_first(["FIREBASE_PROJECT_ID", "FIREBASEPROJECTID"], "")
69
+ FIREBASE_WEB_API_KEY: str = env_first(["FIREBASE_WEB_API_KEY", "FIREBASEWEBAPIKEY"], "")
70
+ FIREBASE_SERVICE_ACCOUNT_PATH: str = env_first(
71
+ ["FIREBASE_SERVICE_ACCOUNT_PATH", "FIREBASESERVICEACCOUNTPATH"],
72
+ "",
73
+ )
74
+ FIREBASE_SERVICE_ACCOUNT_JSON: str = env_first(
75
+ ["FIREBASE_SERVICE_ACCOUNT_JSON", "FIREBASESERVICEACCOUNTJSON"],
76
+ "",
77
+ )
78
+
79
  @property
80
  def cors_origins_list(self) -> list[str]:
81
  return [origin.strip() for origin in self.CORS_ORIGINS.split(",") if origin.strip()]
backend/app/database.py CHANGED
@@ -1,29 +1,21 @@
1
- from sqlalchemy import create_engine
2
- from sqlalchemy.orm import sessionmaker, declarative_base
3
- from app.config import settings
4
 
5
- # Create engine
6
- engine = create_engine(
7
- settings.DATABASE_URL,
8
- connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {}
9
- )
10
 
11
- # Create session factory
12
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
13
 
14
- # Base class for models
15
- Base = declarative_base()
 
 
16
 
17
 
18
  def get_db():
19
- """Dependency for database session"""
20
- db = SessionLocal()
21
- try:
22
  yield db
23
- finally:
24
- db.close()
25
 
26
 
27
  def init_db():
28
- """Initialize database with all tables"""
29
- Base.metadata.create_all(bind=engine)
 
1
+ from contextlib import contextmanager
 
 
2
 
 
 
 
 
 
3
 
4
+ class _NoDatabase:
5
+ """Compatibility object for legacy dependencies while moving to Firestore-only."""
6
 
7
+
8
+ @contextmanager
9
+ def _noop_db_context():
10
+ yield _NoDatabase()
11
 
12
 
13
  def get_db():
14
+ """Legacy dependency kept for backward compatibility with route signatures."""
15
+ with _noop_db_context() as db:
 
16
  yield db
 
 
17
 
18
 
19
  def init_db():
20
+ """No-op: Firestore does not require SQL table initialization."""
21
+ return None
backend/app/middleware/auth.py CHANGED
@@ -1,36 +1,66 @@
1
  from fastapi import Depends, HTTPException, status
2
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
- from sqlalchemy.orm import Session
4
  from app.utils.auth import decode_token
5
- from app.models import User
6
- from app.database import get_db
7
 
8
  security = HTTPBearer()
9
 
10
 
11
  async def get_current_user(
12
  credentials: HTTPAuthorizationCredentials = Depends(security),
13
- db: Session = Depends(get_db)
14
- ) -> User:
15
  """Get current authenticated user"""
16
  token = credentials.credentials
17
  token_data = decode_token(token)
18
  email = token_data.get("email")
 
19
 
20
- user = db.query(User).filter(User.email == email).first()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- if not user or not user.is_active:
23
  raise HTTPException(
24
  status_code=status.HTTP_401_UNAUTHORIZED,
25
  detail="Invalid authentication credentials",
26
  )
 
27
 
28
- return user
29
 
30
 
31
  async def get_admin_user(
32
- current_user: User = Depends(get_current_user),
33
- ) -> User:
34
  """Verify current user is admin"""
35
  if current_user.role != "admin":
36
  raise HTTPException(
 
1
  from fastapi import Depends, HTTPException, status
2
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
 
3
  from app.utils.auth import decode_token
4
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc
 
5
 
6
  security = HTTPBearer()
7
 
8
 
9
  async def get_current_user(
10
  credentials: HTTPAuthorizationCredentials = Depends(security),
11
+ ):
 
12
  """Get current authenticated user"""
13
  token = credentials.credentials
14
  token_data = decode_token(token)
15
  email = token_data.get("email")
16
+ display_name = token_data.get("name")
17
 
18
+ user = first_doc(COLL.users, predicate=lambda row: row.get("email") == email)
19
+
20
+ if user and user.get("updated_at") is None:
21
+ user["updated_at"] = now_utc()
22
+
23
+ if not user and email:
24
+ inferred_name = display_name or email.split("@")[0]
25
+ user = create_doc(
26
+ COLL.users,
27
+ {
28
+ "name": inferred_name,
29
+ "email": email,
30
+ "password": "",
31
+ "role": "player",
32
+ "jersey_number": None,
33
+ "bio": None,
34
+ "runs": 0,
35
+ "matches": 0,
36
+ "wickets": 0,
37
+ "centuries": 0,
38
+ "half_centuries": 0,
39
+ "average_runs": 0.0,
40
+ "highest_score": 0,
41
+ "is_premium": False,
42
+ "premium_expiry": None,
43
+ "premium_start_date": None,
44
+ "is_active": True,
45
+ "created_at": now_utc(),
46
+ "updated_at": now_utc(),
47
+ "last_login": None,
48
+ },
49
+ )
50
 
51
+ if not user or not user.get("is_active", True):
52
  raise HTTPException(
53
  status_code=status.HTTP_401_UNAUTHORIZED,
54
  detail="Invalid authentication credentials",
55
  )
56
+ update_doc(COLL.users, user["id"], {"updated_at": now_utc()})
57
 
58
+ return as_obj(user)
59
 
60
 
61
  async def get_admin_user(
62
+ current_user = Depends(get_current_user),
63
+ ):
64
  """Verify current user is admin"""
65
  if current_user.role != "admin":
66
  raise HTTPException(
backend/app/routes/admin.py CHANGED
@@ -1,144 +1,104 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy import func
3
- from sqlalchemy.orm import Session
4
- from datetime import datetime
5
  from typing import List
 
6
  from app.config import settings
7
- from app.database import get_db
8
- from app.models import User, Payment, FinanceTransaction, AdminChatMessage
9
  from app.schemas import AdminChatCreate, AdminChatResponse
10
  from app.middleware.auth import get_admin_user, get_current_user
11
- from app.utils.logger import log_action, log_error
 
12
 
13
  router = APIRouter(prefix="/admin", tags=["Admin"])
14
 
15
 
16
  @router.get("/users", response_model=List)
17
- async def list_all_users(
18
- skip: int = 0,
19
- limit: int = 100,
20
- admin: User = Depends(get_admin_user),
21
- db: Session = Depends(get_db)
22
- ):
23
- """Get all users (admin only)"""
24
-
25
- users = db.query(User).offset(skip).limit(limit).all()
26
  log_action("Admin viewed all users", user_id=admin.id)
27
  return [
28
  {
29
- "id": user.id,
30
- "name": user.name,
31
- "email": user.email,
32
- "role": user.role,
33
- "is_active": user.is_active,
34
- "is_premium": user.is_premium,
35
- "runs": user.runs,
36
- "matches": user.matches,
37
- "wickets": user.wickets,
38
- "created_at": user.created_at,
39
  }
40
  for user in users
41
  ]
42
 
43
 
44
  @router.put("/users/{user_id}/premium")
45
- async def toggle_user_premium(
46
- user_id: int,
47
- days: int = 30,
48
- admin: User = Depends(get_admin_user),
49
- db: Session = Depends(get_db)
50
- ):
51
- """Toggle user premium status (admin only)"""
52
-
53
- user = db.query(User).filter(User.id == user_id).first()
54
 
55
  if not user:
56
- raise HTTPException(
57
- status_code=status.HTTP_404_NOT_FOUND,
58
- detail="User not found"
59
- )
60
 
61
- user.is_premium = not user.is_premium
 
62
 
63
- if user.is_premium:
64
- from datetime import datetime, timedelta
65
- user.premium_expiry = datetime.utcnow() + timedelta(days=days)
66
- user.premium_start_date = datetime.utcnow()
67
  else:
68
- user.premium_expiry = None
69
 
70
- db.commit()
71
- log_action("Admin toggled user premium", user_id=admin.id,
72
- details=f"User {user_id}")
73
 
74
- return {"message": f"User premium status updated"}
75
 
76
 
77
  @router.delete("/users/{user_id}")
78
- async def deactivate_user(
79
- user_id: int,
80
- admin: User = Depends(get_admin_user),
81
- db: Session = Depends(get_db)
82
- ):
83
- """Deactivate user (admin only)"""
84
-
85
- user = db.query(User).filter(User.id == user_id).first()
86
 
87
  if not user:
88
- raise HTTPException(
89
- status_code=status.HTTP_404_NOT_FOUND,
90
- detail="User not found"
91
- )
92
 
93
- user.is_active = False
94
- db.commit()
95
 
96
- log_action("Admin deactivated user", user_id=admin.id,
97
- details=f"User {user_id}")
98
 
99
  return {"message": "User deactivated successfully"}
100
 
101
 
102
  @router.get("/stats")
103
- async def get_system_stats(
104
- admin: User = Depends(get_admin_user),
105
- db: Session = Depends(get_db)
106
- ):
107
- """Get system statistics (admin only)"""
108
-
109
- total_users = db.query(User).count()
110
- active_users = db.query(User).filter(User.is_active == True).count()
111
- premium_users = db.query(User).filter(User.is_premium == True).count()
112
- total_matches = sum([u.matches for u in db.query(User).all()])
113
-
114
- paid_user_ids = {
115
- row[0]
116
- for row in db.query(Payment.user_id)
117
- .filter(Payment.status == "completed")
118
- .distinct()
119
- .all()
120
- }
121
- active_players = db.query(User).filter(User.is_active == True, User.role == "player").all()
122
- unpaid_players = [player for player in active_players if player.id not in paid_user_ids]
123
 
124
  pending_funds = len(unpaid_players) * settings.PREMIUM_COST
125
 
126
- total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter(
127
- Payment.status == "completed"
128
- ).scalar() or 0.0
129
- manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
130
- FinanceTransaction.transaction_type == "credit",
131
- FinanceTransaction.category == "manual_credit",
132
- ).scalar() or 0.0
133
- total_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
134
- FinanceTransaction.transaction_type == "debit",
135
- ).scalar() or 0.0
136
  funds_remaining = round((total_collected + manual_credits) - total_debits, 2)
137
 
138
- unread_chat_messages = db.query(AdminChatMessage).filter(
139
- AdminChatMessage.sender_role == "player",
140
- AdminChatMessage.is_read == False,
141
- ).count()
142
 
143
  log_action("Admin viewed system stats", user_id=admin.id)
144
 
@@ -154,34 +114,26 @@ async def get_system_stats(
154
 
155
 
156
  @router.get("/chats")
157
- async def get_chat_threads(
158
- admin: User = Depends(get_admin_user),
159
- db: Session = Depends(get_db),
160
- ):
161
- """Get admin chat thread summary by player."""
162
- players = db.query(User).filter(User.role == "player", User.is_active == True).all()
163
 
164
  threads = []
165
  for player in players:
166
- messages = db.query(AdminChatMessage).filter(
167
- AdminChatMessage.user_id == player.id
168
- ).order_by(AdminChatMessage.created_at.desc()).limit(1).all()
169
-
170
- last_message = messages[0] if messages else None
171
- unread_count = db.query(AdminChatMessage).filter(
172
- AdminChatMessage.user_id == player.id,
173
- AdminChatMessage.sender_role == "player",
174
- AdminChatMessage.is_read == False,
175
- ).count()
176
 
177
  threads.append(
178
  {
179
- "user_id": player.id,
180
- "name": player.name,
181
- "email": player.email,
182
  "unread_count": unread_count,
183
- "last_message": last_message.message if last_message else None,
184
- "last_message_at": last_message.created_at if last_message else None,
185
  }
186
  )
187
 
@@ -190,39 +142,29 @@ async def get_chat_threads(
190
 
191
 
192
  @router.get("/chats/{user_id}", response_model=list[AdminChatResponse])
193
- async def get_chat_thread(
194
- user_id: int,
195
- admin: User = Depends(get_admin_user),
196
- db: Session = Depends(get_db),
197
- ):
198
- """Get full chat thread for a player."""
199
- user = db.query(User).filter(User.id == user_id, User.role == "player").first()
200
  if not user:
201
  raise HTTPException(status_code=404, detail="Player not found")
202
 
203
- messages = db.query(AdminChatMessage).filter(
204
- AdminChatMessage.user_id == user_id
205
- ).order_by(AdminChatMessage.created_at.asc()).all()
 
 
 
206
 
207
- db.query(AdminChatMessage).filter(
208
- AdminChatMessage.user_id == user_id,
209
- AdminChatMessage.sender_role == "player",
210
- AdminChatMessage.is_read == False,
211
- ).update({"is_read": True})
212
- db.commit()
213
 
214
- return messages
215
 
216
 
217
  @router.post("/chats/{user_id}", response_model=AdminChatResponse)
218
- async def send_admin_chat_message(
219
- user_id: int,
220
- payload: AdminChatCreate,
221
- admin: User = Depends(get_admin_user),
222
- db: Session = Depends(get_db),
223
- ):
224
- """Send a message from admin to a player."""
225
- user = db.query(User).filter(User.id == user_id, User.role == "player").first()
226
  if not user:
227
  raise HTTPException(status_code=404, detail="Player not found")
228
 
@@ -230,60 +172,54 @@ async def send_admin_chat_message(
230
  if not message:
231
  raise HTTPException(status_code=400, detail="Message cannot be empty")
232
 
233
- chat = AdminChatMessage(
234
- user_id=user_id,
235
- sender_role="admin",
236
- message=message,
237
- is_read=False,
 
 
 
 
238
  )
239
- db.add(chat)
240
- db.commit()
241
- db.refresh(chat)
242
 
243
  log_action("Admin chat message sent", user_id=admin.id, details=f"to={user_id}")
244
- return chat
245
 
246
 
247
  @router.get("/my-chat", response_model=list[AdminChatResponse])
248
- async def get_my_chat(
249
- current_user: User = Depends(get_current_user),
250
- db: Session = Depends(get_db),
251
- ):
252
- """Get current player's chat with admin."""
253
- messages = db.query(AdminChatMessage).filter(
254
- AdminChatMessage.user_id == current_user.id
255
- ).order_by(AdminChatMessage.created_at.asc()).all()
256
 
257
- db.query(AdminChatMessage).filter(
258
- AdminChatMessage.user_id == current_user.id,
259
- AdminChatMessage.sender_role == "admin",
260
- AdminChatMessage.is_read == False,
261
- ).update({"is_read": True})
262
- db.commit()
263
 
264
- return messages
265
 
266
 
267
  @router.post("/my-chat", response_model=AdminChatResponse)
268
- async def send_message_to_admin(
269
- payload: AdminChatCreate,
270
- current_user: User = Depends(get_current_user),
271
- db: Session = Depends(get_db),
272
- ):
273
- """Send message to admin from current player."""
274
  message = payload.message.strip()
275
  if not message:
276
  raise HTTPException(status_code=400, detail="Message cannot be empty")
277
 
278
- chat = AdminChatMessage(
279
- user_id=current_user.id,
280
- sender_role="player",
281
- message=message,
282
- is_read=False,
 
 
 
 
283
  )
284
- db.add(chat)
285
- db.commit()
286
- db.refresh(chat)
287
 
288
  log_action("Player chat message sent", user_id=current_user.id)
289
- return chat
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
+ from datetime import datetime, timedelta
 
 
3
  from typing import List
4
+
5
  from app.config import settings
 
 
6
  from app.schemas import AdminChatCreate, AdminChatResponse
7
  from app.middleware.auth import get_admin_user, get_current_user
8
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc
9
+ from app.utils.logger import log_action
10
 
11
  router = APIRouter(prefix="/admin", tags=["Admin"])
12
 
13
 
14
  @router.get("/users", response_model=List)
15
+ async def list_all_users(skip: int = 0, limit: int = 100, admin=Depends(get_admin_user)):
16
+ users = list_docs(COLL.users, sort_key="created_at", reverse=True, offset=skip, limit=limit)
 
 
 
 
 
 
 
17
  log_action("Admin viewed all users", user_id=admin.id)
18
  return [
19
  {
20
+ "id": user.get("id"),
21
+ "name": user.get("name"),
22
+ "email": user.get("email"),
23
+ "role": user.get("role"),
24
+ "is_active": user.get("is_active", True),
25
+ "is_premium": user.get("is_premium", False),
26
+ "runs": user.get("runs", 0),
27
+ "matches": user.get("matches", 0),
28
+ "wickets": user.get("wickets", 0),
29
+ "created_at": user.get("created_at"),
30
  }
31
  for user in users
32
  ]
33
 
34
 
35
  @router.put("/users/{user_id}/premium")
36
+ async def toggle_user_premium(user_id: int, days: int = 30, admin=Depends(get_admin_user)):
37
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id)
 
 
 
 
 
 
 
38
 
39
  if not user:
40
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
 
 
 
41
 
42
+ is_premium = not user.get("is_premium", False)
43
+ patch = {"is_premium": is_premium, "updated_at": now_utc()}
44
 
45
+ if is_premium:
46
+ from datetime import timedelta
47
+ patch["premium_expiry"] = now_utc() + timedelta(days=days)
48
+ patch["premium_start_date"] = now_utc()
49
  else:
50
+ patch["premium_expiry"] = None
51
 
52
+ update_doc(COLL.users, user_id, patch)
53
+ log_action("Admin toggled user premium", user_id=admin.id, details=f"User {user_id}")
 
54
 
55
+ return {"message": "User premium status updated"}
56
 
57
 
58
  @router.delete("/users/{user_id}")
59
+ async def deactivate_user(user_id: int, admin=Depends(get_admin_user)):
60
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id)
 
 
 
 
 
 
61
 
62
  if not user:
63
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
 
 
 
64
 
65
+ update_doc(COLL.users, user_id, {"is_active": False, "updated_at": now_utc()})
 
66
 
67
+ log_action("Admin deactivated user", user_id=admin.id, details=f"User {user_id}")
 
68
 
69
  return {"message": "User deactivated successfully"}
70
 
71
 
72
  @router.get("/stats")
73
+ async def get_system_stats(admin=Depends(get_admin_user)):
74
+ users = list_docs(COLL.users)
75
+ payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed")
76
+ transactions = list_docs(COLL.finance_transactions)
77
+ chats = list_docs(COLL.admin_chat_messages)
78
+
79
+ total_users = len(users)
80
+ active_users = len([u for u in users if u.get("is_active", True)])
81
+ premium_users = len([u for u in users if u.get("is_premium", False)])
82
+ total_matches = sum(int(u.get("matches", 0)) for u in users)
83
+
84
+ paid_user_ids = {row.get("user_id") for row in payments}
85
+ active_players = [u for u in users if u.get("is_active", True) and u.get("role") == "player"]
86
+ unpaid_players = [u for u in active_players if u.get("id") not in paid_user_ids]
 
 
 
 
 
 
87
 
88
  pending_funds = len(unpaid_players) * settings.PREMIUM_COST
89
 
90
+ total_collected = sum(float(row.get("amount", 0)) for row in payments)
91
+ manual_credits = sum(
92
+ float(row.get("amount", 0))
93
+ for row in transactions
94
+ if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit"
95
+ )
96
+ total_debits = sum(float(row.get("amount", 0)) for row in transactions if row.get("transaction_type") == "debit")
 
 
 
97
  funds_remaining = round((total_collected + manual_credits) - total_debits, 2)
98
 
99
+ unread_chat_messages = len(
100
+ [m for m in chats if m.get("sender_role") == "player" and not m.get("is_read", False)]
101
+ )
 
102
 
103
  log_action("Admin viewed system stats", user_id=admin.id)
104
 
 
114
 
115
 
116
  @router.get("/chats")
117
+ async def get_chat_threads(admin=Depends(get_admin_user)):
118
+ players = list_docs(COLL.users, predicate=lambda row: row.get("role") == "player" and row.get("is_active", True))
119
+ chats = list_docs(COLL.admin_chat_messages, sort_key="created_at", reverse=True)
 
 
 
120
 
121
  threads = []
122
  for player in players:
123
+ player_messages = [m for m in chats if m.get("user_id") == player.get("id")]
124
+ last_message = player_messages[0] if player_messages else None
125
+ unread_count = len(
126
+ [m for m in player_messages if m.get("sender_role") == "player" and not m.get("is_read", False)]
127
+ )
 
 
 
 
 
128
 
129
  threads.append(
130
  {
131
+ "user_id": player.get("id"),
132
+ "name": player.get("name"),
133
+ "email": player.get("email"),
134
  "unread_count": unread_count,
135
+ "last_message": last_message.get("message") if last_message else None,
136
+ "last_message_at": last_message.get("created_at") if last_message else None,
137
  }
138
  )
139
 
 
142
 
143
 
144
  @router.get("/chats/{user_id}", response_model=list[AdminChatResponse])
145
+ async def get_chat_thread(user_id: int, admin=Depends(get_admin_user)):
146
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id and row.get("role") == "player")
 
 
 
 
 
147
  if not user:
148
  raise HTTPException(status_code=404, detail="Player not found")
149
 
150
+ messages = list_docs(
151
+ COLL.admin_chat_messages,
152
+ predicate=lambda row: row.get("user_id") == user_id,
153
+ sort_key="created_at",
154
+ reverse=False,
155
+ )
156
 
157
+ for message in messages:
158
+ if message.get("sender_role") == "player" and not message.get("is_read", False):
159
+ update_doc(COLL.admin_chat_messages, message["id"], {"is_read": True})
160
+ message["is_read"] = True
 
 
161
 
162
+ return [as_obj(row) for row in messages]
163
 
164
 
165
  @router.post("/chats/{user_id}", response_model=AdminChatResponse)
166
+ async def send_admin_chat_message(user_id: int, payload: AdminChatCreate, admin=Depends(get_admin_user)):
167
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user_id and row.get("role") == "player")
 
 
 
 
 
 
168
  if not user:
169
  raise HTTPException(status_code=404, detail="Player not found")
170
 
 
172
  if not message:
173
  raise HTTPException(status_code=400, detail="Message cannot be empty")
174
 
175
+ chat = create_doc(
176
+ COLL.admin_chat_messages,
177
+ {
178
+ "user_id": user_id,
179
+ "sender_role": "admin",
180
+ "message": message,
181
+ "is_read": False,
182
+ "created_at": now_utc(),
183
+ },
184
  )
 
 
 
185
 
186
  log_action("Admin chat message sent", user_id=admin.id, details=f"to={user_id}")
187
+ return as_obj(chat)
188
 
189
 
190
  @router.get("/my-chat", response_model=list[AdminChatResponse])
191
+ async def get_my_chat(current_user=Depends(get_current_user)):
192
+ messages = list_docs(
193
+ COLL.admin_chat_messages,
194
+ predicate=lambda row: row.get("user_id") == current_user.id,
195
+ sort_key="created_at",
196
+ reverse=False,
197
+ )
 
198
 
199
+ for message in messages:
200
+ if message.get("sender_role") == "admin" and not message.get("is_read", False):
201
+ update_doc(COLL.admin_chat_messages, message["id"], {"is_read": True})
202
+ message["is_read"] = True
 
 
203
 
204
+ return [as_obj(row) for row in messages]
205
 
206
 
207
  @router.post("/my-chat", response_model=AdminChatResponse)
208
+ async def send_message_to_admin(payload: AdminChatCreate, current_user=Depends(get_current_user)):
 
 
 
 
 
209
  message = payload.message.strip()
210
  if not message:
211
  raise HTTPException(status_code=400, detail="Message cannot be empty")
212
 
213
+ chat = create_doc(
214
+ COLL.admin_chat_messages,
215
+ {
216
+ "user_id": current_user.id,
217
+ "sender_role": "player",
218
+ "message": message,
219
+ "is_read": False,
220
+ "created_at": now_utc(),
221
+ },
222
  )
 
 
 
223
 
224
  log_action("Player chat message sent", user_id=current_user.id)
225
+ return as_obj(chat)
backend/app/routes/auth.py CHANGED
@@ -1,10 +1,8 @@
1
  from fastapi import APIRouter, Depends, HTTPException, Request, status
2
- from sqlalchemy.orm import Session
3
  from datetime import timedelta
4
- from app.database import get_db
5
- from app.models import User
6
  from app.schemas import UserRegister, UserLogin, Token, UserResponse
7
  from app.utils.auth import hash_password, verify_password, create_access_token
 
8
  from app.utils.logger import log_action, log_error
9
  from slowapi import Limiter
10
  from slowapi.util import get_remote_address
@@ -15,11 +13,11 @@ limiter = Limiter(key_func=get_remote_address)
15
 
16
  @router.post("/register", response_model=Token)
17
  @limiter.limit("5/minute")
18
- async def register(request: Request, user_data: UserRegister, db: Session = Depends(get_db)):
19
  """Register a new player"""
20
 
21
  # Check if user already exists
22
- existing_user = db.query(User).filter(User.email == user_data.email).first()
23
  if existing_user:
24
  log_error(f"Registration failed: Email already exists", details=user_data.email)
25
  raise HTTPException(
@@ -28,56 +26,70 @@ async def register(request: Request, user_data: UserRegister, db: Session = Depe
28
  )
29
 
30
  # Create new user
31
- new_user = User(
32
- name=user_data.name,
33
- email=user_data.email,
34
- password=hash_password(user_data.password),
35
- role="player"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  )
37
 
38
- db.add(new_user)
39
- db.commit()
40
- db.refresh(new_user)
41
-
42
  # Create access token
43
  access_token = create_access_token(
44
  data={"sub": new_user.email},
45
  expires_delta=timedelta(minutes=30)
46
  )
47
 
48
- log_action("User registered", user_id=new_user.id)
49
 
50
  return {
51
  "access_token": access_token,
52
  "token_type": "bearer",
53
- "user": UserResponse.model_validate(new_user)
54
  }
55
 
56
 
57
  @router.post("/login", response_model=Token)
58
  @limiter.limit("10/minute")
59
- async def login(request: Request, credentials: UserLogin, db: Session = Depends(get_db)):
60
  """Login a player"""
61
 
62
- user = db.query(User).filter(User.email == credentials.email).first()
63
 
64
- if not user or not verify_password(credentials.password, user.password):
65
  log_error("Login failed: Invalid credentials", details=credentials.email)
66
  raise HTTPException(
67
  status_code=status.HTTP_401_UNAUTHORIZED,
68
  detail="Invalid email or password"
69
  )
70
 
71
- if not user.is_active:
72
  raise HTTPException(
73
  status_code=status.HTTP_403_FORBIDDEN,
74
  detail="Account is deactivated"
75
  )
76
 
77
  # Update last login
78
- from datetime import datetime
79
- user.last_login = datetime.utcnow()
80
- db.commit()
81
 
82
  # Create access token
83
  access_token = create_access_token(
@@ -85,10 +97,10 @@ async def login(request: Request, credentials: UserLogin, db: Session = Depends(
85
  expires_delta=timedelta(minutes=30)
86
  )
87
 
88
- log_action("User logged in", user_id=user.id)
89
 
90
  return {
91
  "access_token": access_token,
92
  "token_type": "bearer",
93
- "user": UserResponse.model_validate(user)
94
  }
 
1
  from fastapi import APIRouter, Depends, HTTPException, Request, status
 
2
  from datetime import timedelta
 
 
3
  from app.schemas import UserRegister, UserLogin, Token, UserResponse
4
  from app.utils.auth import hash_password, verify_password, create_access_token
5
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc
6
  from app.utils.logger import log_action, log_error
7
  from slowapi import Limiter
8
  from slowapi.util import get_remote_address
 
13
 
14
  @router.post("/register", response_model=Token)
15
  @limiter.limit("5/minute")
16
+ async def register(request: Request, user_data: UserRegister):
17
  """Register a new player"""
18
 
19
  # Check if user already exists
20
+ existing_user = first_doc(COLL.users, predicate=lambda row: row.get("email") == user_data.email)
21
  if existing_user:
22
  log_error(f"Registration failed: Email already exists", details=user_data.email)
23
  raise HTTPException(
 
26
  )
27
 
28
  # Create new user
29
+ new_user = create_doc(
30
+ COLL.users,
31
+ {
32
+ "name": user_data.name,
33
+ "email": user_data.email,
34
+ "password": hash_password(user_data.password),
35
+ "role": "player",
36
+ "jersey_number": None,
37
+ "bio": None,
38
+ "runs": 0,
39
+ "matches": 0,
40
+ "wickets": 0,
41
+ "centuries": 0,
42
+ "half_centuries": 0,
43
+ "average_runs": 0.0,
44
+ "highest_score": 0,
45
+ "is_premium": False,
46
+ "premium_expiry": None,
47
+ "premium_start_date": None,
48
+ "is_active": True,
49
+ "created_at": now_utc(),
50
+ "updated_at": now_utc(),
51
+ "last_login": None,
52
+ },
53
  )
54
 
 
 
 
 
55
  # Create access token
56
  access_token = create_access_token(
57
  data={"sub": new_user.email},
58
  expires_delta=timedelta(minutes=30)
59
  )
60
 
61
+ log_action("User registered", user_id=new_user["id"])
62
 
63
  return {
64
  "access_token": access_token,
65
  "token_type": "bearer",
66
+ "user": UserResponse.model_validate(as_obj(new_user))
67
  }
68
 
69
 
70
  @router.post("/login", response_model=Token)
71
  @limiter.limit("10/minute")
72
+ async def login(request: Request, credentials: UserLogin):
73
  """Login a player"""
74
 
75
+ user = first_doc(COLL.users, predicate=lambda row: row.get("email") == credentials.email)
76
 
77
+ if not user or not verify_password(credentials.password, user.get("password", "")):
78
  log_error("Login failed: Invalid credentials", details=credentials.email)
79
  raise HTTPException(
80
  status_code=status.HTTP_401_UNAUTHORIZED,
81
  detail="Invalid email or password"
82
  )
83
 
84
+ if not user.get("is_active", True):
85
  raise HTTPException(
86
  status_code=status.HTTP_403_FORBIDDEN,
87
  detail="Account is deactivated"
88
  )
89
 
90
  # Update last login
91
+ update_doc(COLL.users, user["id"], {"last_login": now_utc(), "updated_at": now_utc()})
92
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == user["id"])
 
93
 
94
  # Create access token
95
  access_token = create_access_token(
 
97
  expires_delta=timedelta(minutes=30)
98
  )
99
 
100
+ log_action("User logged in", user_id=user["id"])
101
 
102
  return {
103
  "access_token": access_token,
104
  "token_type": "bearer",
105
+ "user": UserResponse.model_validate(as_obj(user))
106
  }
backend/app/routes/dashboard.py CHANGED
@@ -1,48 +1,79 @@
1
- from fastapi import APIRouter, Depends
2
- from sqlalchemy import func
3
- from sqlalchemy.orm import Session
4
- from datetime import datetime
5
  from typing import List
6
- from app.database import get_db
7
- from app.models import User, PerformanceLog, Payment, FinanceTransaction
 
8
  from app.schemas import UserResponse
9
- from app.utils.premium import check_and_downgrade_premium
 
10
 
11
  router = APIRouter(prefix="/dashboard", tags=["Dashboard"])
12
 
13
 
14
- @router.get("/overview")
15
- async def get_dashboard_overview(db: Session = Depends(get_db)):
16
- """Get dashboard overview stats"""
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- total_players = db.query(User).filter(User.is_active == True).count()
19
- premium_players = db.query(User).filter(User.is_premium == True).count()
20
- total_matches = sum([p.matches for p in db.query(User).all()])
21
- total_runs = sum([p.runs for p in db.query(User).all()])
22
 
23
- return {
24
- "total_players": total_players,
25
- "premium_players": premium_players,
26
- "total_matches": total_matches,
27
- "total_runs": total_runs
28
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  @router.get("/extended-overview")
32
- async def get_extended_overview(db: Session = Depends(get_db)):
33
- """Get extended dashboard stats for real-world club overview."""
34
- players = db.query(User).filter(User.is_active == True, User.role == "player").all()
 
 
35
 
36
- total_players = len(players)
37
- premium_players = len([player for player in players if player.is_premium])
38
- total_matches = sum(player.matches for player in players)
39
- total_runs = sum(player.runs for player in players)
40
- total_wickets = sum(player.wickets for player in players)
41
 
42
- avg_runs_per_match = round(total_runs / total_matches, 2) if total_matches else 0.0
43
- premium_ratio = round((premium_players / total_players) * 100, 2) if total_players else 0.0
44
 
45
- top_performance = db.query(PerformanceLog).order_by(PerformanceLog.performance_rating.desc()).first()
 
46
 
47
  return {
48
  "total_players": total_players,
@@ -53,89 +84,97 @@ async def get_extended_overview(db: Session = Depends(get_db)):
53
  "avg_runs_per_match": avg_runs_per_match,
54
  "premium_ratio": premium_ratio,
55
  "top_performance": {
56
- "match_date": top_performance.match_date if top_performance else None,
57
- "performance_rating": top_performance.performance_rating if top_performance else 0,
58
- "runs_scored": top_performance.runs_scored if top_performance else 0,
59
- "wickets_taken": top_performance.wickets_taken if top_performance else 0,
60
  },
61
- }
62
-
63
-
64
- @router.get("/featured-players", response_model=List[UserResponse])
65
- async def get_featured_players(db: Session = Depends(get_db)):
66
- """Get featured premium players"""
67
 
68
- # Get premium players, check expiry
69
- premium_players = db.query(User).filter(
70
- User.is_premium == True,
71
- User.is_active == True
72
- ).all()
 
 
 
73
 
74
- for player in premium_players:
75
- check_and_downgrade_premium(db, player)
76
 
77
- # Get only confirmed premium players, sorted by runs
78
- featured = db.query(User).filter(
79
- User.is_premium == True,
80
- User.is_active == True
81
- ).order_by(User.runs.desc()).limit(5).all()
82
-
83
- return featured
 
 
 
84
 
85
 
86
  @router.get("/recent-players", response_model=List[UserResponse])
87
- async def get_recent_players(db: Session = Depends(get_db)):
88
- """Get recently registered players"""
89
-
90
- recent = db.query(User).filter(
91
- User.is_active == True
92
- ).order_by(User.created_at.desc()).limit(10).all()
93
-
94
- return recent
 
95
 
96
 
97
  @router.get("/top-stats")
98
- async def get_top_stats(db: Session = Depends(get_db)):
99
- """Get top statistics"""
100
-
101
- top_scorer = db.query(User).filter(User.is_active == True).order_by(
102
- User.runs.desc()
103
- ).first()
104
-
105
- top_wicket_taker = db.query(User).filter(User.is_active == True).order_by(
106
- User.wickets.desc()
107
- ).first()
 
 
 
 
108
 
109
- return {
110
- "top_scorer": {
111
- "name": top_scorer.name if top_scorer else None,
112
- "runs": top_scorer.runs if top_scorer else 0
113
- },
114
- "top_wicket_taker": {
115
- "name": top_wicket_taker.name if top_wicket_taker else None,
116
- "wickets": top_wicket_taker.wickets if top_wicket_taker else 0
 
117
  }
118
- }
 
 
 
 
 
 
 
 
119
 
120
 
121
  @router.get("/charts")
122
- async def get_dashboard_chart_data(db: Session = Depends(get_db)):
123
- """Get chart-friendly dataset for player stats and match trend."""
124
- top_players = db.query(User).filter(User.is_active == True).order_by(User.runs.desc()).limit(6).all()
125
-
126
- recent_logs = db.query(PerformanceLog).order_by(PerformanceLog.match_date.desc()).limit(12).all()
127
- recent_logs = list(reversed(recent_logs))
128
 
129
  return {
130
- "top_players_runs": [
131
- {"name": player.name, "runs": player.runs} for player in top_players
132
- ],
133
  "recent_match_trend": [
134
  {
135
- "label": log.match_date.strftime("%d %b"),
136
- "runs": log.runs_scored,
137
- "wickets": log.wickets_taken,
138
- "rating": log.performance_rating,
139
  }
140
  for log in recent_logs
141
  ],
@@ -143,9 +182,8 @@ async def get_dashboard_chart_data(db: Session = Depends(get_db)):
143
 
144
 
145
  @router.get("/team-ai-insights")
146
- async def get_team_ai_insights(db: Session = Depends(get_db)):
147
- """Generate AI-style team summary from recent performances."""
148
- recent_logs = db.query(PerformanceLog).order_by(PerformanceLog.match_date.desc()).limit(30).all()
149
 
150
  if not recent_logs:
151
  return {
@@ -155,9 +193,9 @@ async def get_team_ai_insights(db: Session = Depends(get_db)):
155
  "insights": ["Log team matches to unlock AI projections."],
156
  }
157
 
158
- avg_rating = sum(log.performance_rating for log in recent_logs) / len(recent_logs)
159
- avg_runs = sum(log.runs_scored for log in recent_logs) / len(recent_logs)
160
- avg_wickets = sum(log.wickets_taken for log in recent_logs) / len(recent_logs)
161
 
162
  if avg_rating >= 7.5:
163
  team_form = "excellent"
@@ -188,25 +226,26 @@ async def get_team_ai_insights(db: Session = Depends(get_db)):
188
 
189
 
190
  @router.get("/funds-summary")
191
- async def get_funds_summary(db: Session = Depends(get_db)):
192
- """Get finance summary for dashboard cards."""
193
- total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter(
194
- Payment.status == "completed"
195
- ).scalar() or 0.0
196
-
197
- manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
198
- FinanceTransaction.transaction_type == "credit",
199
- FinanceTransaction.category == "manual_credit",
200
- ).scalar() or 0.0
201
-
202
- guest_fund_spent = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
203
- FinanceTransaction.transaction_type == "debit",
204
- FinanceTransaction.category == "guest_fund",
205
- ).scalar() or 0.0
206
-
207
- all_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
208
- FinanceTransaction.transaction_type == "debit",
209
- ).scalar() or 0.0
 
210
 
211
  remaining_funds = round((total_collected + manual_credits) - all_debits, 2)
212
 
 
1
+ from fastapi import APIRouter
 
 
 
2
  from typing import List
3
+ from datetime import datetime, timezone
4
+ from google.api_core.exceptions import ResourceExhausted
5
+
6
  from app.schemas import UserResponse
7
+ from app.utils.firestore_data import COLL, as_obj, list_docs, now_utc, update_doc, _parse_datetime, normalize_user
8
+ from app.utils.cache import get_cache
9
 
10
  router = APIRouter(prefix="/dashboard", tags=["Dashboard"])
11
 
12
 
13
+ def _check_and_downgrade(player: dict) -> dict:
14
+ expiry = player.get("premium_expiry")
15
+ if player.get("is_premium") and expiry:
16
+ # Parse expiry to timezone-aware datetime
17
+ expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry
18
+
19
+ # Ensure expiry_dt is timezone-aware
20
+ if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None:
21
+ expiry_dt = expiry_dt.replace(tzinfo=timezone.utc)
22
+
23
+ # Check if premium has expired
24
+ if expiry_dt and now_utc() >= expiry_dt:
25
+ # Use _doc_id (actual Firestore document ID) if available, otherwise use id
26
+ doc_id = player.get("_doc_id") or player.get("id")
27
+ player = update_doc(COLL.users, doc_id, {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}) or player
28
+ return player
29
 
 
 
 
 
30
 
31
+ @router.get("/overview")
32
+ async def get_dashboard_overview():
33
+ cache = get_cache()
34
+
35
+ def fetch_overview():
36
+ players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True))
37
+ total_players = len(players)
38
+ premium_players = len([p for p in players if p.get("is_premium")])
39
+ total_matches = sum(int(p.get("matches", 0)) for p in players)
40
+ total_runs = sum(int(p.get("runs", 0)) for p in players)
41
+
42
+ return {
43
+ "total_players": total_players,
44
+ "premium_players": premium_players,
45
+ "total_matches": total_matches,
46
+ "total_runs": total_runs,
47
+ }
48
+
49
+ try:
50
+ return cache.get_or_fetch("dashboard_overview", fetch_overview, ttl_seconds=300)
51
+ except ResourceExhausted:
52
+ # Fall back to cached data if quota exceeded
53
+ cached = cache.get("dashboard_overview")
54
+ if cached:
55
+ return cached
56
+ raise
57
 
58
 
59
  @router.get("/extended-overview")
60
+ async def get_extended_overview():
61
+ cache = get_cache()
62
+
63
+ def fetch_extended_overview():
64
+ players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player")
65
 
66
+ total_players = len(players)
67
+ premium_players = len([player for player in players if player.get("is_premium")])
68
+ total_matches = sum(int(player.get("matches", 0)) for player in players)
69
+ total_runs = sum(int(player.get("runs", 0)) for player in players)
70
+ total_wickets = sum(int(player.get("wickets", 0)) for player in players)
71
 
72
+ avg_runs_per_match = round(total_runs / total_matches, 2) if total_matches else 0.0
73
+ premium_ratio = round((premium_players / total_players) * 100, 2) if total_players else 0.0
74
 
75
+ top_performance = list_docs(COLL.performance_logs, sort_key="performance_rating", reverse=True, limit=1)
76
+ top = top_performance[0] if top_performance else None
77
 
78
  return {
79
  "total_players": total_players,
 
84
  "avg_runs_per_match": avg_runs_per_match,
85
  "premium_ratio": premium_ratio,
86
  "top_performance": {
87
+ "match_date": top.get("match_date") if top else None,
88
+ "performance_rating": top.get("performance_rating", 0) if top else 0,
89
+ "runs_scored": top.get("runs_scored", 0) if top else 0,
90
+ "wickets_taken": top.get("wickets_taken", 0) if top else 0,
91
  },
92
+ }
 
 
 
 
 
93
 
94
+ try:
95
+ return cache.get_or_fetch("dashboard_extended_overview", fetch_extended_overview, ttl_seconds=300)
96
+ except ResourceExhausted:
97
+ # Fall back to cached data if quota exceeded
98
+ cached = cache.get("dashboard_extended_overview")
99
+ if cached:
100
+ return cached
101
+ raise
102
 
 
 
103
 
104
+ @router.get("/featured-players", response_model=List[UserResponse])
105
+ async def get_featured_players():
106
+ premium_players = list_docs(
107
+ COLL.users,
108
+ predicate=lambda row: row.get("is_premium") and row.get("is_active", True),
109
+ sort_key="runs",
110
+ reverse=True,
111
+ limit=5,
112
+ )
113
+ return [normalize_user(_check_and_downgrade(row)) for row in premium_players]
114
 
115
 
116
  @router.get("/recent-players", response_model=List[UserResponse])
117
+ async def get_recent_players():
118
+ recent = list_docs(
119
+ COLL.users,
120
+ predicate=lambda row: row.get("is_active", True),
121
+ sort_key="created_at",
122
+ reverse=True,
123
+ limit=10,
124
+ )
125
+ return [normalize_user(row) for row in recent]
126
 
127
 
128
  @router.get("/top-stats")
129
+ async def get_top_stats():
130
+ cache = get_cache()
131
+
132
+ def fetch_top_stats():
133
+ # Fetch active players once and compute top scorers and wicket takers from same list
134
+ players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True))
135
+
136
+ # Sort by runs and get top scorer
137
+ top_scorers = sorted(players, key=lambda x: int(x.get("runs", 0)), reverse=True)
138
+ top_scorer = top_scorers[0] if top_scorers else None
139
+
140
+ # Sort by wickets and get top wicket taker
141
+ top_wickets = sorted(players, key=lambda x: int(x.get("wickets", 0)), reverse=True)
142
+ top_wicket_taker = top_wickets[0] if top_wickets else None
143
 
144
+ return {
145
+ "top_scorer": {
146
+ "name": top_scorer.get("name") if top_scorer else None,
147
+ "runs": top_scorer.get("runs", 0) if top_scorer else 0,
148
+ },
149
+ "top_wicket_taker": {
150
+ "name": top_wicket_taker.get("name") if top_wicket_taker else None,
151
+ "wickets": top_wicket_taker.get("wickets", 0) if top_wicket_taker else 0,
152
+ },
153
  }
154
+
155
+ try:
156
+ return cache.get_or_fetch("dashboard_top_stats", fetch_top_stats, ttl_seconds=300)
157
+ except ResourceExhausted:
158
+ # Fall back to cached data if quota exceeded
159
+ cached = cache.get("dashboard_top_stats")
160
+ if cached:
161
+ return cached
162
+ raise
163
 
164
 
165
  @router.get("/charts")
166
+ async def get_dashboard_chart_data():
167
+ top_players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True), sort_key="runs", reverse=True, limit=6)
168
+ recent_logs = list_docs(COLL.performance_logs, sort_key="match_date", reverse=False, limit=12)
 
 
 
169
 
170
  return {
171
+ "top_players_runs": [{"name": player.get("name"), "runs": player.get("runs", 0)} for player in top_players],
 
 
172
  "recent_match_trend": [
173
  {
174
+ "label": log.get("match_date").strftime("%d %b") if log.get("match_date") else "N/A",
175
+ "runs": log.get("runs_scored", 0),
176
+ "wickets": log.get("wickets_taken", 0),
177
+ "rating": log.get("performance_rating", 0),
178
  }
179
  for log in recent_logs
180
  ],
 
182
 
183
 
184
  @router.get("/team-ai-insights")
185
+ async def get_team_ai_insights():
186
+ recent_logs = list_docs(COLL.performance_logs, sort_key="match_date", reverse=True, limit=30)
 
187
 
188
  if not recent_logs:
189
  return {
 
193
  "insights": ["Log team matches to unlock AI projections."],
194
  }
195
 
196
+ avg_rating = sum(float(log.get("performance_rating", 0)) for log in recent_logs) / len(recent_logs)
197
+ avg_runs = sum(float(log.get("runs_scored", 0)) for log in recent_logs) / len(recent_logs)
198
+ avg_wickets = sum(float(log.get("wickets_taken", 0)) for log in recent_logs) / len(recent_logs)
199
 
200
  if avg_rating >= 7.5:
201
  team_form = "excellent"
 
226
 
227
 
228
  @router.get("/funds-summary")
229
+ async def get_funds_summary():
230
+ payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed")
231
+ transactions = list_docs(COLL.finance_transactions)
232
+
233
+ total_collected = sum(float(row.get("amount", 0)) for row in payments)
234
+ manual_credits = sum(
235
+ float(row.get("amount", 0))
236
+ for row in transactions
237
+ if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit"
238
+ )
239
+ guest_fund_spent = sum(
240
+ float(row.get("amount", 0))
241
+ for row in transactions
242
+ if row.get("transaction_type") == "debit" and row.get("category") == "guest_fund"
243
+ )
244
+ all_debits = sum(
245
+ float(row.get("amount", 0))
246
+ for row in transactions
247
+ if row.get("transaction_type") == "debit"
248
+ )
249
 
250
  remaining_funds = round((total_collected + manual_credits) - all_debits, 2)
251
 
backend/app/routes/finance.py CHANGED
@@ -1,70 +1,52 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy.orm import Session
3
- from sqlalchemy import func
4
  from app.config import settings
5
- from app.database import get_db
6
- from app.models import User, Payment, FinanceTransaction
7
  from app.middleware.auth import get_current_user
8
  from app.schemas import GuestFundRequest, ManualCreditRequest, FinanceTransactionResponse
 
9
  from app.utils.logger import log_action
10
 
11
  router = APIRouter(prefix="/finance", tags=["Finance"])
12
 
13
 
14
- def require_admin(user: User) -> None:
15
  if user.role != "admin":
16
- raise HTTPException(
17
- status_code=status.HTTP_403_FORBIDDEN,
18
- detail="Only admins can perform this action",
19
- )
20
-
21
 
22
- def calculate_remaining_funds(db: Session) -> float:
23
- total_payments = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter(
24
- Payment.status == "completed"
25
- ).scalar() or 0.0
26
 
27
- total_manual_credits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
28
- FinanceTransaction.transaction_type == "credit",
29
- FinanceTransaction.category == "manual_credit",
30
- ).scalar() or 0.0
31
 
32
- total_debits = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
33
- FinanceTransaction.transaction_type == "debit",
34
- ).scalar() or 0.0
 
 
 
 
35
 
36
  return round((total_payments + total_manual_credits) - total_debits, 2)
37
 
38
 
39
  @router.get("/overview")
40
- async def get_finance_overview(
41
- current_user: User = Depends(get_current_user),
42
- db: Session = Depends(get_db),
43
- ):
44
- """Get total collected funds, pending funds, and remaining funds."""
45
- active_players = db.query(User).filter(User.is_active == True, User.role == "player").all()
46
-
47
- paid_user_ids = {
48
- row[0]
49
- for row in db.query(Payment.user_id)
50
- .filter(Payment.status == "completed")
51
- .distinct()
52
- .all()
53
- }
54
-
55
- unpaid_players = [player for player in active_players if player.id not in paid_user_ids]
56
-
57
- total_collected = db.query(func.coalesce(func.sum(Payment.amount), 0.0)).filter(
58
- Payment.status == "completed"
59
- ).scalar() or 0.0
60
-
61
- total_guest_fund_used = db.query(func.coalesce(func.sum(FinanceTransaction.amount), 0.0)).filter(
62
- FinanceTransaction.transaction_type == "debit",
63
- FinanceTransaction.category == "guest_fund",
64
- ).scalar() or 0.0
65
 
66
  pending_funds = len(unpaid_players) * settings.PREMIUM_COST
67
- funds_remaining = calculate_remaining_funds(db)
68
 
69
  return {
70
  "total_collected": round(total_collected, 2),
@@ -78,29 +60,24 @@ async def get_finance_overview(
78
 
79
 
80
  @router.get("/player-payments")
81
- async def get_player_payments(
82
- current_user: User = Depends(get_current_user),
83
- db: Session = Depends(get_db),
84
- ):
85
- """Show who paid premium and current payment status per player."""
86
- players = db.query(User).filter(User.is_active == True, User.role == "player").all()
87
 
88
  result = []
89
  for player in players:
90
- payments = db.query(Payment).filter(
91
- Payment.user_id == player.id,
92
- Payment.status == "completed",
93
- ).order_by(Payment.created_at.desc()).all()
94
 
95
- amount_paid = round(sum(payment.amount for payment in payments), 2)
96
- last_payment_date = payments[0].created_at if payments else None
97
 
98
  result.append(
99
  {
100
- "user_id": player.id,
101
- "name": player.name,
102
- "email": player.email,
103
- "is_premium": player.is_premium,
104
  "amount_paid": amount_paid,
105
  "has_paid": amount_paid >= settings.PREMIUM_COST,
106
  "last_payment_date": last_payment_date,
@@ -108,27 +85,18 @@ async def get_player_payments(
108
  }
109
  )
110
 
111
- result.sort(key=lambda row: (not row["has_paid"], row["name"].lower()))
112
  return result
113
 
114
 
115
  @router.get("/transactions", response_model=list[FinanceTransactionResponse])
116
- async def get_finance_transactions(
117
- current_user: User = Depends(get_current_user),
118
- db: Session = Depends(get_db),
119
- ):
120
- """List recent finance transactions."""
121
- transactions = db.query(FinanceTransaction).order_by(FinanceTransaction.created_at.desc()).limit(100).all()
122
- return transactions
123
 
124
 
125
  @router.post("/guest-fund")
126
- async def record_guest_fund_expense(
127
- payload: GuestFundRequest,
128
- current_user: User = Depends(get_current_user),
129
- db: Session = Depends(get_db),
130
- ):
131
- """Record guest fund expense after a match and update remaining funds."""
132
  require_admin(current_user)
133
 
134
  if payload.guest_fund <= 0:
@@ -138,19 +106,20 @@ async def record_guest_fund_expense(
138
  if payload.notes:
139
  description = f"{description} | {payload.notes}"
140
 
141
- transaction = FinanceTransaction(
142
- user_id=None,
143
- transaction_type="debit",
144
- amount=payload.guest_fund,
145
- category="guest_fund",
146
- description=description,
147
- reference_id=None,
 
 
 
 
148
  )
149
 
150
- db.add(transaction)
151
- db.commit()
152
-
153
- funds_remaining = calculate_remaining_funds(db)
154
  log_action("Guest fund expense recorded", user_id=current_user.id, details=description)
155
 
156
  return {
@@ -161,30 +130,26 @@ async def record_guest_fund_expense(
161
 
162
 
163
  @router.post("/manual-credit")
164
- async def record_manual_credit(
165
- payload: ManualCreditRequest,
166
- current_user: User = Depends(get_current_user),
167
- db: Session = Depends(get_db),
168
- ):
169
- """Add manual credit to club funds."""
170
  require_admin(current_user)
171
 
172
  if payload.amount <= 0:
173
  raise HTTPException(status_code=400, detail="Credit amount should be greater than zero")
174
 
175
- transaction = FinanceTransaction(
176
- user_id=payload.user_id,
177
- transaction_type="credit",
178
- amount=payload.amount,
179
- category="manual_credit",
180
- description=payload.notes or "Manual fund credit",
181
- reference_id=None,
 
 
 
 
182
  )
183
 
184
- db.add(transaction)
185
- db.commit()
186
-
187
- funds_remaining = calculate_remaining_funds(db)
188
  log_action("Manual fund credit recorded", user_id=current_user.id, details=str(payload.amount))
189
 
190
  return {
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
+
 
3
  from app.config import settings
 
 
4
  from app.middleware.auth import get_current_user
5
  from app.schemas import GuestFundRequest, ManualCreditRequest, FinanceTransactionResponse
6
+ from app.utils.firestore_data import COLL, as_obj, create_doc, list_docs, now_utc
7
  from app.utils.logger import log_action
8
 
9
  router = APIRouter(prefix="/finance", tags=["Finance"])
10
 
11
 
12
+ def require_admin(user) -> None:
13
  if user.role != "admin":
14
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only admins can perform this action")
 
 
 
 
15
 
 
 
 
 
16
 
17
+ def calculate_remaining_funds() -> float:
18
+ payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed")
19
+ transactions = list_docs(COLL.finance_transactions)
 
20
 
21
+ total_payments = sum(float(row.get("amount", 0)) for row in payments)
22
+ total_manual_credits = sum(
23
+ float(row.get("amount", 0))
24
+ for row in transactions
25
+ if row.get("transaction_type") == "credit" and row.get("category") == "manual_credit"
26
+ )
27
+ total_debits = sum(float(row.get("amount", 0)) for row in transactions if row.get("transaction_type") == "debit")
28
 
29
  return round((total_payments + total_manual_credits) - total_debits, 2)
30
 
31
 
32
  @router.get("/overview")
33
+ async def get_finance_overview(current_user=Depends(get_current_user)):
34
+ active_players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player")
35
+ payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed")
36
+ transactions = list_docs(COLL.finance_transactions)
37
+
38
+ paid_user_ids = {row.get("user_id") for row in payments}
39
+ unpaid_players = [player for player in active_players if player.get("id") not in paid_user_ids]
40
+
41
+ total_collected = sum(float(row.get("amount", 0)) for row in payments)
42
+ total_guest_fund_used = sum(
43
+ float(row.get("amount", 0))
44
+ for row in transactions
45
+ if row.get("transaction_type") == "debit" and row.get("category") == "guest_fund"
46
+ )
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  pending_funds = len(unpaid_players) * settings.PREMIUM_COST
49
+ funds_remaining = calculate_remaining_funds()
50
 
51
  return {
52
  "total_collected": round(total_collected, 2),
 
60
 
61
 
62
  @router.get("/player-payments")
63
+ async def get_player_payments(current_user=Depends(get_current_user)):
64
+ players = list_docs(COLL.users, predicate=lambda row: row.get("is_active", True) and row.get("role") == "player")
65
+ all_payments = list_docs(COLL.payments, predicate=lambda row: row.get("status") == "completed")
 
 
 
66
 
67
  result = []
68
  for player in players:
69
+ payments = [row for row in all_payments if row.get("user_id") == player.get("id")]
70
+ payments.sort(key=lambda row: row.get("created_at") or now_utc(), reverse=True)
 
 
71
 
72
+ amount_paid = round(sum(float(payment.get("amount", 0)) for payment in payments), 2)
73
+ last_payment_date = payments[0].get("created_at") if payments else None
74
 
75
  result.append(
76
  {
77
+ "user_id": player.get("id"),
78
+ "name": player.get("name"),
79
+ "email": player.get("email"),
80
+ "is_premium": player.get("is_premium", False),
81
  "amount_paid": amount_paid,
82
  "has_paid": amount_paid >= settings.PREMIUM_COST,
83
  "last_payment_date": last_payment_date,
 
85
  }
86
  )
87
 
88
+ result.sort(key=lambda row: (not row["has_paid"], (row["name"] or "").lower()))
89
  return result
90
 
91
 
92
  @router.get("/transactions", response_model=list[FinanceTransactionResponse])
93
+ async def get_finance_transactions(current_user=Depends(get_current_user)):
94
+ transactions = list_docs(COLL.finance_transactions, sort_key="created_at", reverse=True, limit=100)
95
+ return [as_obj(row) for row in transactions]
 
 
 
 
96
 
97
 
98
  @router.post("/guest-fund")
99
+ async def record_guest_fund_expense(payload: GuestFundRequest, current_user=Depends(get_current_user)):
 
 
 
 
 
100
  require_admin(current_user)
101
 
102
  if payload.guest_fund <= 0:
 
106
  if payload.notes:
107
  description = f"{description} | {payload.notes}"
108
 
109
+ create_doc(
110
+ COLL.finance_transactions,
111
+ {
112
+ "user_id": None,
113
+ "transaction_type": "debit",
114
+ "amount": payload.guest_fund,
115
+ "category": "guest_fund",
116
+ "description": description,
117
+ "reference_id": None,
118
+ "created_at": now_utc(),
119
+ },
120
  )
121
 
122
+ funds_remaining = calculate_remaining_funds()
 
 
 
123
  log_action("Guest fund expense recorded", user_id=current_user.id, details=description)
124
 
125
  return {
 
130
 
131
 
132
  @router.post("/manual-credit")
133
+ async def record_manual_credit(payload: ManualCreditRequest, current_user=Depends(get_current_user)):
 
 
 
 
 
134
  require_admin(current_user)
135
 
136
  if payload.amount <= 0:
137
  raise HTTPException(status_code=400, detail="Credit amount should be greater than zero")
138
 
139
+ create_doc(
140
+ COLL.finance_transactions,
141
+ {
142
+ "user_id": payload.user_id,
143
+ "transaction_type": "credit",
144
+ "amount": payload.amount,
145
+ "category": "manual_credit",
146
+ "description": payload.notes or "Manual fund credit",
147
+ "reference_id": None,
148
+ "created_at": now_utc(),
149
+ },
150
  )
151
 
152
+ funds_remaining = calculate_remaining_funds()
 
 
 
153
  log_action("Manual fund credit recorded", user_id=current_user.id, details=str(payload.amount))
154
 
155
  return {
backend/app/routes/matches.py CHANGED
@@ -1,10 +1,6 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy import func
3
- from sqlalchemy.orm import Session
4
 
5
- from app.database import get_db
6
  from app.middleware.auth import get_current_user
7
- from app.models import BallEvent, Match, MatchPlayer, User
8
  from app.schemas import (
9
  BallEventCreate,
10
  MatchCreate,
@@ -15,34 +11,41 @@ from app.schemas import (
15
  MatchStartRequest,
16
  MatchTeamSetupRequest,
17
  )
 
18
  from app.utils.logger import log_action
19
- from app.utils.premium import check_and_downgrade_premium
20
 
21
  router = APIRouter(prefix="/matches", tags=["Matches"])
22
 
23
 
24
- def ensure_match_editor(match_obj: Match, current_user: User):
25
  if current_user.role == "admin":
26
  return
27
- if match_obj.created_by_id != current_user.id:
28
- raise HTTPException(
29
- status_code=status.HTTP_403_FORBIDDEN,
30
- detail="Only match creator can update this match",
31
- )
32
 
33
 
34
- def ensure_premium_creator(db: Session, user: User):
35
- check_and_downgrade_premium(db, user)
36
- db.refresh(user)
37
- if not user.is_premium:
38
- raise HTTPException(
39
- status_code=status.HTTP_403_FORBIDDEN,
40
- detail="Only premium players can create matches",
41
- )
 
 
 
 
 
 
 
42
 
 
 
43
 
44
- def get_team_totals(db: Session, match_id: int):
45
- events = db.query(BallEvent).filter(BallEvent.match_id == match_id).all()
 
46
 
47
  team_a_runs = 0
48
  team_b_runs = 0
@@ -50,44 +53,56 @@ def get_team_totals(db: Session, match_id: int):
50
  team_b_wickets = 0
51
 
52
  for event in events:
53
- total = event.runs_off_bat + event.extras
54
- if event.batting_team == "A":
55
  team_a_runs += total
56
- if event.is_wicket:
57
  team_a_wickets += 1
58
- elif event.batting_team == "B":
59
  team_b_runs += total
60
- if event.is_wicket:
61
  team_b_wickets += 1
62
 
63
  return team_a_runs, team_b_runs, team_a_wickets, team_b_wickets
64
 
65
 
66
- def get_innings_teams(db: Session, match_id: int, default_team: str):
67
- first_innings_event = (
68
- db.query(BallEvent)
69
- .filter(BallEvent.match_id == match_id, BallEvent.innings == 1)
70
- .order_by(BallEvent.created_at.asc())
71
- .first()
72
  )
73
 
74
- first_batting_team = first_innings_event.batting_team if first_innings_event else (default_team or "A")
75
  second_batting_team = "B" if first_batting_team == "A" else "A"
76
  return first_batting_team, second_batting_team
77
 
78
 
79
- def build_scoreboard(db: Session, match_obj: Match, innings: int):
80
- batting_team = match_obj.batting_team or "A"
81
- events = (
82
- db.query(BallEvent)
83
- .filter(BallEvent.match_id == match_obj.id, BallEvent.innings == innings)
84
- .order_by(BallEvent.created_at.asc())
85
- .all()
 
 
 
 
86
  )
87
 
88
- total_runs = sum(event.runs_off_bat + event.extras for event in events)
89
- wickets = sum(1 for event in events if event.is_wicket)
90
- legal_balls = sum(1 for event in events if event.extra_type not in {"wide", "no_ball"})
 
 
 
 
 
 
 
 
91
 
92
  completed_overs = legal_balls // 6
93
  balls_in_current_over = legal_balls % 6
@@ -97,24 +112,25 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int):
97
  over_map = {}
98
 
99
  for event in events[-18:]:
100
- ball_text = f"{event.over_number}.{event.ball_number} "
101
- if event.is_wicket:
102
  ball_text += "W"
103
- elif event.extra_type:
104
- ball_text += f"{event.runs_off_bat + event.extras} ({event.extra_type})"
105
  else:
106
- ball_text += str(event.runs_off_bat)
107
  recent_balls.append(ball_text)
108
 
109
  for event in events:
110
- if event.is_wicket:
111
  result = "W"
112
- elif event.extra_type:
113
- result = f"{event.runs_off_bat + event.extras} ({event.extra_type})"
114
  else:
115
- result = str(event.runs_off_bat)
116
 
117
- over_map.setdefault(event.over_number, []).append(f"{event.ball_number}:{result}")
 
118
 
119
  if over_map:
120
  current_over_number = max(over_map.keys())
@@ -129,21 +145,21 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int):
129
  current_over_balls = []
130
  past_overs = []
131
 
132
- team_a_runs, team_b_runs, team_a_wickets, team_b_wickets = get_team_totals(db, match_obj.id)
133
- first_team, second_team = get_innings_teams(db, match_obj.id, match_obj.batting_team or "A")
134
 
135
  winner_team = None
136
  result_text = None
137
 
138
- if match_obj.status == "completed":
139
  if team_a_runs == team_b_runs:
140
  result_text = "Match tied"
141
  else:
142
  winner_code = "A" if team_a_runs > team_b_runs else "B"
143
- winner_team = match_obj.team_a_name if winner_code == "A" else match_obj.team_b_name
144
 
145
  if winner_code == second_team:
146
- winner_player_count = get_batting_side_player_count(db, match_obj.id, winner_code)
147
  winner_wickets = team_a_wickets if winner_code == "A" else team_b_wickets
148
  wickets_in_hand = max(0, (winner_player_count - 1) - winner_wickets)
149
  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):
152
  result_text = f"{winner_team} won by {margin} run{'s' if margin != 1 else ''}"
153
 
154
  return MatchScoreboardResponse(
155
- match_id=match_obj.id,
156
  innings=innings,
157
- match_status=match_obj.status,
158
- current_innings=match_obj.current_innings,
159
  batting_team=batting_team,
160
  total_runs=total_runs,
161
  wickets=wickets,
@@ -169,108 +185,102 @@ def build_scoreboard(db: Session, match_obj: Match, innings: int):
169
  team_b_runs=team_b_runs,
170
  winner_team=winner_team,
171
  result_text=result_text,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  )
173
 
174
 
175
- def get_next_delivery_position(db: Session, match_id: int, innings: int):
176
- legal_balls = (
177
- db.query(BallEvent)
178
- .filter(BallEvent.match_id == match_id, BallEvent.innings == innings)
179
- .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"])))
180
- .count()
181
  )
182
-
183
  over_number = (legal_balls // 6) + 1
184
  ball_number = (legal_balls % 6) + 1
185
  return over_number, ball_number
186
 
187
 
188
- def get_batting_side_player_count(db: Session, match_id: int, team: str):
189
- return (
190
- db.query(MatchPlayer)
191
- .filter(MatchPlayer.match_id == match_id, MatchPlayer.team == team)
192
- .count()
193
- )
194
-
195
-
196
  @router.post("", response_model=MatchResponse)
197
- async def create_match(
198
- payload: MatchCreate,
199
- current_user: User = Depends(get_current_user),
200
- db: Session = Depends(get_db),
201
- ):
202
- ensure_premium_creator(db, current_user)
203
 
204
  if payload.overs_per_innings <= 0:
205
  raise HTTPException(status_code=400, detail="Overs must be greater than zero")
206
 
207
- match_obj = Match(
208
- title=payload.title.strip(),
209
- created_by_id=current_user.id,
210
- team_a_name=payload.team_a_name.strip(),
211
- team_b_name=payload.team_b_name.strip(),
212
- overs_per_innings=payload.overs_per_innings,
 
 
 
 
 
 
 
 
213
  )
214
- db.add(match_obj)
215
- db.commit()
216
- db.refresh(match_obj)
217
 
218
- log_action("Created live match", user_id=current_user.id, details=match_obj.title)
219
- return match_obj
220
 
221
 
222
  @router.get("", response_model=list[MatchResponse])
223
- async def list_matches(
224
- db: Session = Depends(get_db),
225
- current_user: User = Depends(get_current_user),
226
- ):
227
  _ = current_user
228
- matches = db.query(Match).order_by(Match.created_at.desc()).limit(50).all()
229
- return matches
230
 
231
 
232
  @router.get("/{match_id}", response_model=MatchDetailResponse)
233
- async def get_match(
234
- match_id: int,
235
- db: Session = Depends(get_db),
236
- current_user: User = Depends(get_current_user),
237
- ):
238
  _ = current_user
239
- match_obj = db.query(Match).filter(Match.id == match_id).first()
240
  if not match_obj:
241
  raise HTTPException(status_code=404, detail="Match not found")
242
 
243
- rows = (
244
- db.query(MatchPlayer.user_id, MatchPlayer.team, User.name)
245
- .join(User, User.id == MatchPlayer.user_id)
246
- .filter(MatchPlayer.match_id == match_id)
247
- .all()
248
- )
249
 
250
  team_a = []
251
  team_b = []
252
- for user_id, team, name in rows:
253
- view = MatchPlayerView(user_id=user_id, team=team, name=name)
254
- if team == "A":
 
 
255
  team_a.append(view)
256
  else:
257
  team_b.append(view)
258
 
259
- return MatchDetailResponse(
260
- match=match_obj,
261
- team_a_players=team_a,
262
- team_b_players=team_b,
263
- )
264
 
265
 
266
  @router.post("/{match_id}/teams")
267
- async def setup_match_teams(
268
- match_id: int,
269
- payload: MatchTeamSetupRequest,
270
- current_user: User = Depends(get_current_user),
271
- db: Session = Depends(get_db),
272
- ):
273
- match_obj = db.query(Match).filter(Match.id == match_id).first()
274
  if not match_obj:
275
  raise HTTPException(status_code=404, detail="Match not found")
276
 
@@ -283,36 +293,41 @@ async def setup_match_teams(
283
  if not all_player_ids:
284
  raise HTTPException(status_code=400, detail="Select players for both teams")
285
 
286
- valid_count = (
287
- db.query(func.count(User.id))
288
- .filter(User.id.in_(all_player_ids), User.is_active == True)
289
- .scalar()
290
- )
291
- if valid_count != len(all_player_ids):
292
- raise HTTPException(status_code=400, detail="One or more selected players are invalid")
293
-
294
- db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).delete()
 
 
 
 
 
 
 
 
 
 
 
 
295
 
296
  for player_id in payload.team_a_player_ids:
297
- db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="A"))
298
 
299
  for player_id in payload.team_b_player_ids:
300
- db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="B"))
301
 
302
- db.commit()
303
  log_action("Updated match teams", user_id=current_user.id, details=f"match_id={match_id}")
304
-
305
  return {"message": "Teams updated"}
306
 
307
 
308
  @router.post("/{match_id}/start", response_model=MatchResponse)
309
- async def start_match(
310
- match_id: int,
311
- payload: MatchStartRequest,
312
- current_user: User = Depends(get_current_user),
313
- db: Session = Depends(get_db),
314
- ):
315
- match_obj = db.query(Match).filter(Match.id == match_id).first()
316
  if not match_obj:
317
  raise HTTPException(status_code=404, detail="Match not found")
318
 
@@ -322,118 +337,119 @@ async def start_match(
322
  if batting_team not in {"A", "B"}:
323
  raise HTTPException(status_code=400, detail="batting_team must be A or B")
324
 
325
- team_count = db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).count()
326
  if team_count == 0:
327
  raise HTTPException(status_code=400, detail="Please set teams first")
328
 
329
- match_obj.status = "live"
330
- match_obj.current_innings = 1
331
- match_obj.batting_team = batting_team
332
- db.commit()
333
- db.refresh(match_obj)
334
 
335
  log_action("Started match", user_id=current_user.id, details=f"match_id={match_id}")
336
- return match_obj
337
 
338
 
339
  @router.post("/{match_id}/ball")
340
- async def record_ball_event(
341
- match_id: int,
342
- payload: BallEventCreate,
343
- current_user: User = Depends(get_current_user),
344
- db: Session = Depends(get_db),
345
- ):
346
- match_obj = db.query(Match).filter(Match.id == match_id).first()
347
  if not match_obj:
348
  raise HTTPException(status_code=404, detail="Match not found")
349
 
350
  ensure_match_editor(match_obj, current_user)
351
 
352
- if match_obj.status != "live":
353
  raise HTTPException(status_code=400, detail="Match is not live")
354
 
355
  if payload.runs_off_bat < 0 or payload.extras < 0:
356
  raise HTTPException(status_code=400, detail="Runs and extras cannot be negative")
357
 
358
- innings_in_use = match_obj.current_innings or payload.innings
359
- batting_team_in_use = (match_obj.batting_team or payload.batting_team or "").upper().strip()
360
  if batting_team_in_use not in {"A", "B"}:
361
  raise HTTPException(status_code=400, detail="batting_team must be A or B")
362
 
363
- auto_over_number, auto_ball_number = get_next_delivery_position(db, match_id, innings_in_use)
364
  legal_ball = payload.extra_type not in {"wide", "no_ball"}
365
 
366
- # Enforce innings over limit for legal balls only
367
- current_legal = (
368
- db.query(BallEvent)
369
- .filter(BallEvent.match_id == match_id, BallEvent.innings == innings_in_use)
370
- .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"])))
371
- .count()
372
  )
373
- if legal_ball and current_legal >= (match_obj.overs_per_innings * 6):
 
 
374
  raise HTTPException(status_code=400, detail="Innings overs limit reached")
375
 
376
- event = BallEvent(
377
- match_id=match_id,
378
- innings=innings_in_use,
379
- over_number=auto_over_number,
380
- ball_number=auto_ball_number,
381
- batting_team=batting_team_in_use,
382
- striker_id=payload.striker_id,
383
- bowler_id=payload.bowler_id,
384
- runs_off_bat=payload.runs_off_bat,
385
- extras=payload.extras,
386
- extra_type=payload.extra_type,
387
- is_wicket=payload.is_wicket,
388
- wicket_type=payload.wicket_type,
389
- commentary=payload.commentary,
390
- created_by_id=current_user.id,
 
 
 
 
391
  )
392
 
393
- db.add(event)
394
- db.commit()
395
-
396
- scoreboard = build_scoreboard(db, match_obj, innings_in_use)
397
 
398
  innings_over = False
399
  match_completed = False
400
 
401
- team_player_count = get_batting_side_player_count(db, match_id, batting_team_in_use)
402
- all_out_limit = max(1, team_player_count - 1)
 
403
  if team_player_count > 0 and scoreboard.wickets >= all_out_limit:
404
  innings_over = True
405
  if innings_in_use == 1:
406
- match_obj.current_innings = 2
407
- match_obj.batting_team = "B" if batting_team_in_use == "A" else "A"
408
- db.commit()
409
- db.refresh(match_obj)
 
 
 
 
 
410
  else:
411
- match_obj.status = "completed"
412
- db.commit()
413
- db.refresh(match_obj)
414
  match_completed = True
415
 
 
 
416
  if not match_completed and innings_in_use == 2:
417
- first_team, second_team = get_innings_teams(db, match_id, batting_team_in_use)
418
- team_a_runs, team_b_runs, _, _ = get_team_totals(db, match_id)
419
  first_score = team_a_runs if first_team == "A" else team_b_runs
420
  second_score = team_a_runs if second_team == "A" else team_b_runs
421
 
422
  if second_score > first_score:
423
- match_obj.status = "completed"
424
- db.commit()
425
- db.refresh(match_obj)
426
  match_completed = True
427
  innings_over = True
428
 
429
- next_innings = match_obj.current_innings or innings_in_use
430
- next_over_number, next_ball_number = get_next_delivery_position(db, match_id, next_innings)
431
 
432
  return {
433
  "message": "Ball recorded",
434
  "innings_over": innings_over,
435
  "match_completed": match_completed,
436
- "match_status": match_obj.status,
437
  "recorded_ball": {
438
  "innings": innings_in_use,
439
  "over_number": auto_over_number,
@@ -443,42 +459,31 @@ async def record_ball_event(
443
  "innings": next_innings,
444
  "over_number": next_over_number,
445
  "ball_number": next_ball_number,
446
- "batting_team": match_obj.batting_team,
447
  },
448
  "scoreboard": scoreboard,
449
  }
450
 
451
 
452
  @router.get("/{match_id}/scoreboard", response_model=MatchScoreboardResponse)
453
- async def get_match_scoreboard(
454
- match_id: int,
455
- innings: int = 1,
456
- current_user: User = Depends(get_current_user),
457
- db: Session = Depends(get_db),
458
- ):
459
  _ = current_user
460
- match_obj = db.query(Match).filter(Match.id == match_id).first()
461
  if not match_obj:
462
  raise HTTPException(status_code=404, detail="Match not found")
463
 
464
- return build_scoreboard(db, match_obj, innings)
465
 
466
 
467
  @router.post("/{match_id}/complete", response_model=MatchResponse)
468
- async def complete_match(
469
- match_id: int,
470
- current_user: User = Depends(get_current_user),
471
- db: Session = Depends(get_db),
472
- ):
473
- match_obj = db.query(Match).filter(Match.id == match_id).first()
474
  if not match_obj:
475
  raise HTTPException(status_code=404, detail="Match not found")
476
 
477
  ensure_match_editor(match_obj, current_user)
478
 
479
- match_obj.status = "completed"
480
- db.commit()
481
- db.refresh(match_obj)
482
 
483
  log_action("Completed match", user_id=current_user.id, details=f"match_id={match_id}")
484
- return match_obj
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
 
 
2
 
 
3
  from app.middleware.auth import get_current_user
 
4
  from app.schemas import (
5
  BallEventCreate,
6
  MatchCreate,
 
11
  MatchStartRequest,
12
  MatchTeamSetupRequest,
13
  )
14
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime
15
  from app.utils.logger import log_action
 
16
 
17
  router = APIRouter(prefix="/matches", tags=["Matches"])
18
 
19
 
20
+ def ensure_match_editor(match_obj: dict, current_user):
21
  if current_user.role == "admin":
22
  return
23
+ if match_obj.get("created_by_id") != current_user.id:
24
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only match creator can update this match")
 
 
 
25
 
26
 
27
+ def ensure_premium_creator(user: dict):
28
+ from datetime import datetime, timezone
29
+
30
+ expiry = user.get("premium_expiry")
31
+ if user.get("is_premium") and expiry:
32
+ # Parse expiry to timezone-aware datetime
33
+ expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry
34
+
35
+ # Ensure expiry_dt is timezone-aware
36
+ if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None:
37
+ expiry_dt = expiry_dt.replace(tzinfo=timezone.utc)
38
+
39
+ # Check if premium has expired
40
+ if expiry_dt and now_utc() >= expiry_dt:
41
+ user = update_doc(COLL.users, user["id"], {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()}) or user
42
 
43
+ if not user.get("is_premium"):
44
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Only premium players can create matches")
45
 
46
+
47
+ def get_team_totals(match_id: int):
48
+ events = list_docs(COLL.ball_events, predicate=lambda row: row.get("match_id") == match_id)
49
 
50
  team_a_runs = 0
51
  team_b_runs = 0
 
53
  team_b_wickets = 0
54
 
55
  for event in events:
56
+ total = int(event.get("runs_off_bat", 0)) + int(event.get("extras", 0))
57
+ if event.get("batting_team") == "A":
58
  team_a_runs += total
59
+ if event.get("is_wicket"):
60
  team_a_wickets += 1
61
+ elif event.get("batting_team") == "B":
62
  team_b_runs += total
63
+ if event.get("is_wicket"):
64
  team_b_wickets += 1
65
 
66
  return team_a_runs, team_b_runs, team_a_wickets, team_b_wickets
67
 
68
 
69
+ def get_innings_teams(match_id: int, default_team: str):
70
+ first_innings_event = first_doc(
71
+ COLL.ball_events,
72
+ predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == 1,
73
+ sort_key="created_at",
74
+ reverse=False,
75
  )
76
 
77
+ first_batting_team = first_innings_event.get("batting_team") if first_innings_event else (default_team or "A")
78
  second_batting_team = "B" if first_batting_team == "A" else "A"
79
  return first_batting_team, second_batting_team
80
 
81
 
82
+ def get_batting_side_player_count(match_id: int, team: str):
83
+ return len(list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id and row.get("team") == team))
84
+
85
+
86
+ def build_scoreboard(match_obj: dict, innings: int):
87
+ batting_team = match_obj.get("batting_team") or "A"
88
+ events = list_docs(
89
+ COLL.ball_events,
90
+ predicate=lambda row: row.get("match_id") == match_obj.get("id") and row.get("innings") == innings,
91
+ sort_key="created_at",
92
+ reverse=False,
93
  )
94
 
95
+ # Get all balls from all innings for match history
96
+ all_events = list_docs(
97
+ COLL.ball_events,
98
+ predicate=lambda row: row.get("match_id") == match_obj.get("id"),
99
+ sort_key="created_at",
100
+ reverse=False,
101
+ )
102
+
103
+ total_runs = sum(int(event.get("runs_off_bat", 0)) + int(event.get("extras", 0)) for event in events)
104
+ wickets = sum(1 for event in events if event.get("is_wicket"))
105
+ legal_balls = sum(1 for event in events if event.get("extra_type") not in {"wide", "no_ball"})
106
 
107
  completed_overs = legal_balls // 6
108
  balls_in_current_over = legal_balls % 6
 
112
  over_map = {}
113
 
114
  for event in events[-18:]:
115
+ ball_text = f"{event.get('over_number')}.{event.get('ball_number')} "
116
+ if event.get("is_wicket"):
117
  ball_text += "W"
118
+ elif event.get("extra_type"):
119
+ ball_text += f"{int(event.get('runs_off_bat', 0)) + int(event.get('extras', 0))} ({event.get('extra_type')})"
120
  else:
121
+ ball_text += str(event.get("runs_off_bat", 0))
122
  recent_balls.append(ball_text)
123
 
124
  for event in events:
125
+ if event.get("is_wicket"):
126
  result = "W"
127
+ elif event.get("extra_type"):
128
+ result = f"{int(event.get('runs_off_bat', 0)) + int(event.get('extras', 0))} ({event.get('extra_type')})"
129
  else:
130
+ result = str(event.get("runs_off_bat", 0))
131
 
132
+ over_no = int(event.get("over_number", 1))
133
+ over_map.setdefault(over_no, []).append(f"{event.get('ball_number')}:{result}")
134
 
135
  if over_map:
136
  current_over_number = max(over_map.keys())
 
145
  current_over_balls = []
146
  past_overs = []
147
 
148
+ team_a_runs, team_b_runs, team_a_wickets, team_b_wickets = get_team_totals(match_obj.get("id"))
149
+ first_team, second_team = get_innings_teams(match_obj.get("id"), match_obj.get("batting_team") or "A")
150
 
151
  winner_team = None
152
  result_text = None
153
 
154
+ if match_obj.get("status") == "completed":
155
  if team_a_runs == team_b_runs:
156
  result_text = "Match tied"
157
  else:
158
  winner_code = "A" if team_a_runs > team_b_runs else "B"
159
+ winner_team = match_obj.get("team_a_name") if winner_code == "A" else match_obj.get("team_b_name")
160
 
161
  if winner_code == second_team:
162
+ winner_player_count = get_batting_side_player_count(match_obj.get("id"), winner_code)
163
  winner_wickets = team_a_wickets if winner_code == "A" else team_b_wickets
164
  wickets_in_hand = max(0, (winner_player_count - 1) - winner_wickets)
165
  result_text = f"{winner_team} won by {wickets_in_hand} wicket{'s' if wickets_in_hand != 1 else ''}"
 
168
  result_text = f"{winner_team} won by {margin} run{'s' if margin != 1 else ''}"
169
 
170
  return MatchScoreboardResponse(
171
+ match_id=match_obj.get("id"),
172
  innings=innings,
173
+ match_status=match_obj.get("status"),
174
+ current_innings=match_obj.get("current_innings", 1),
175
  batting_team=batting_team,
176
  total_runs=total_runs,
177
  wickets=wickets,
 
185
  team_b_runs=team_b_runs,
186
  winner_team=winner_team,
187
  result_text=result_text,
188
+ all_balls=[
189
+ {
190
+ "id": event.get("id"),
191
+ "innings": event.get("innings"),
192
+ "over_number": event.get("over_number"),
193
+ "ball_number": event.get("ball_number"),
194
+ "batting_team": event.get("batting_team"),
195
+ "runs_off_bat": event.get("runs_off_bat", 0),
196
+ "extras": event.get("extras", 0),
197
+ "extra_type": event.get("extra_type"),
198
+ "is_wicket": event.get("is_wicket", False),
199
+ "wicket_type": event.get("wicket_type"),
200
+ "commentary": event.get("commentary"),
201
+ "created_at": event.get("created_at"),
202
+ }
203
+ for event in all_events
204
+ ],
205
  )
206
 
207
 
208
+ def get_next_delivery_position(match_id: int, innings: int):
209
+ events = list_docs(
210
+ COLL.ball_events,
211
+ predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == innings,
212
+ sort_key="created_at",
 
213
  )
214
+ legal_balls = len([e for e in events if e.get("extra_type") not in {"wide", "no_ball"}])
215
  over_number = (legal_balls // 6) + 1
216
  ball_number = (legal_balls % 6) + 1
217
  return over_number, ball_number
218
 
219
 
 
 
 
 
 
 
 
 
220
  @router.post("", response_model=MatchResponse)
221
+ async def create_match(payload: MatchCreate, current_user=Depends(get_current_user)):
222
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
223
+ if not user:
224
+ raise HTTPException(status_code=404, detail="User not found")
225
+
226
+ ensure_premium_creator(user)
227
 
228
  if payload.overs_per_innings <= 0:
229
  raise HTTPException(status_code=400, detail="Overs must be greater than zero")
230
 
231
+ match_obj = create_doc(
232
+ COLL.matches,
233
+ {
234
+ "title": payload.title.strip(),
235
+ "created_by_id": current_user.id,
236
+ "team_a_name": payload.team_a_name.strip(),
237
+ "team_b_name": payload.team_b_name.strip(),
238
+ "overs_per_innings": payload.overs_per_innings,
239
+ "status": "setup",
240
+ "current_innings": 1,
241
+ "batting_team": None,
242
+ "created_at": now_utc(),
243
+ "updated_at": now_utc(),
244
+ },
245
  )
 
 
 
246
 
247
+ log_action("Created live match", user_id=current_user.id, details=match_obj.get("title"))
248
+ return as_obj(match_obj)
249
 
250
 
251
  @router.get("", response_model=list[MatchResponse])
252
+ async def list_matches(current_user=Depends(get_current_user)):
 
 
 
253
  _ = current_user
254
+ matches = list_docs(COLL.matches, sort_key="created_at", reverse=True, limit=50)
255
+ return [as_obj(row) for row in matches]
256
 
257
 
258
  @router.get("/{match_id}", response_model=MatchDetailResponse)
259
+ async def get_match(match_id: int, current_user=Depends(get_current_user)):
 
 
 
 
260
  _ = current_user
261
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
262
  if not match_obj:
263
  raise HTTPException(status_code=404, detail="Match not found")
264
 
265
+ rows = list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id)
 
 
 
 
 
266
 
267
  team_a = []
268
  team_b = []
269
+ for row in rows:
270
+ player = first_doc(COLL.users, predicate=lambda u: u.get("id") == row.get("user_id"))
271
+ name = (player or {}).get("name", "Unknown")
272
+ view = MatchPlayerView(user_id=row.get("user_id"), team=row.get("team"), name=name)
273
+ if row.get("team") == "A":
274
  team_a.append(view)
275
  else:
276
  team_b.append(view)
277
 
278
+ return MatchDetailResponse(match=as_obj(match_obj), team_a_players=team_a, team_b_players=team_b)
 
 
 
 
279
 
280
 
281
  @router.post("/{match_id}/teams")
282
+ async def setup_match_teams(match_id: int, payload: MatchTeamSetupRequest, current_user=Depends(get_current_user)):
283
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
 
 
 
 
 
284
  if not match_obj:
285
  raise HTTPException(status_code=404, detail="Match not found")
286
 
 
293
  if not all_player_ids:
294
  raise HTTPException(status_code=400, detail="Select players for both teams")
295
 
296
+ # Check for valid players - must match either 'id', 'uid' field, or document ID and be active
297
+ def is_valid_player(row):
298
+ if not row.get("is_active", True):
299
+ return False
300
+ # Check document id (row.get("id") in Firestore context), id field, uid field
301
+ player_id = row.get("id") or row.get("uid")
302
+ return player_id in all_player_ids
303
+
304
+ users = list_docs(COLL.users, predicate=is_valid_player)
305
+ if len(users) != len(all_player_ids):
306
+ # Debug: log which players were not found
307
+ found_ids = set((u.get("id") or u.get("uid")) for u in users)
308
+ missing_ids = set(all_player_ids) - found_ids
309
+ print(f"Missing players: {missing_ids}, Found: {found_ids}, All requested: {all_player_ids}")
310
+ raise HTTPException(status_code=400, detail=f"One or more selected players are invalid (not found: {missing_ids})")
311
+
312
+ existing = list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id)
313
+ for row in existing:
314
+ from app.utils.firestore_data import delete_doc
315
+
316
+ delete_doc(COLL.match_players, row.get("id"))
317
 
318
  for player_id in payload.team_a_player_ids:
319
+ create_doc(COLL.match_players, {"match_id": match_id, "user_id": player_id, "team": "A", "is_captain": False})
320
 
321
  for player_id in payload.team_b_player_ids:
322
+ create_doc(COLL.match_players, {"match_id": match_id, "user_id": player_id, "team": "B", "is_captain": False})
323
 
 
324
  log_action("Updated match teams", user_id=current_user.id, details=f"match_id={match_id}")
 
325
  return {"message": "Teams updated"}
326
 
327
 
328
  @router.post("/{match_id}/start", response_model=MatchResponse)
329
+ async def start_match(match_id: int, payload: MatchStartRequest, current_user=Depends(get_current_user)):
330
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
 
 
 
 
 
331
  if not match_obj:
332
  raise HTTPException(status_code=404, detail="Match not found")
333
 
 
337
  if batting_team not in {"A", "B"}:
338
  raise HTTPException(status_code=400, detail="batting_team must be A or B")
339
 
340
+ team_count = len(list_docs(COLL.match_players, predicate=lambda row: row.get("match_id") == match_id))
341
  if team_count == 0:
342
  raise HTTPException(status_code=400, detail="Please set teams first")
343
 
344
+ match_obj = update_doc(
345
+ COLL.matches,
346
+ match_id,
347
+ {"status": "live", "current_innings": 1, "batting_team": batting_team, "updated_at": now_utc()},
348
+ )
349
 
350
  log_action("Started match", user_id=current_user.id, details=f"match_id={match_id}")
351
+ return as_obj(match_obj)
352
 
353
 
354
  @router.post("/{match_id}/ball")
355
+ async def record_ball_event(match_id: int, payload: BallEventCreate, current_user=Depends(get_current_user)):
356
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
 
 
 
 
 
357
  if not match_obj:
358
  raise HTTPException(status_code=404, detail="Match not found")
359
 
360
  ensure_match_editor(match_obj, current_user)
361
 
362
+ if match_obj.get("status") != "live":
363
  raise HTTPException(status_code=400, detail="Match is not live")
364
 
365
  if payload.runs_off_bat < 0 or payload.extras < 0:
366
  raise HTTPException(status_code=400, detail="Runs and extras cannot be negative")
367
 
368
+ innings_in_use = match_obj.get("current_innings") or payload.innings
369
+ batting_team_in_use = (match_obj.get("batting_team") or payload.batting_team or "").upper().strip()
370
  if batting_team_in_use not in {"A", "B"}:
371
  raise HTTPException(status_code=400, detail="batting_team must be A or B")
372
 
373
+ auto_over_number, auto_ball_number = get_next_delivery_position(match_id, innings_in_use)
374
  legal_ball = payload.extra_type not in {"wide", "no_ball"}
375
 
376
+ current_events = list_docs(
377
+ COLL.ball_events,
378
+ predicate=lambda row: row.get("match_id") == match_id and row.get("innings") == innings_in_use,
 
 
 
379
  )
380
+ current_legal = len([e for e in current_events if e.get("extra_type") not in {"wide", "no_ball"}])
381
+
382
+ if legal_ball and current_legal >= (int(match_obj.get("overs_per_innings", 20)) * 6):
383
  raise HTTPException(status_code=400, detail="Innings overs limit reached")
384
 
385
+ create_doc(
386
+ COLL.ball_events,
387
+ {
388
+ "match_id": match_id,
389
+ "innings": innings_in_use,
390
+ "over_number": auto_over_number,
391
+ "ball_number": auto_ball_number,
392
+ "batting_team": batting_team_in_use,
393
+ "striker_id": payload.striker_id,
394
+ "bowler_id": payload.bowler_id,
395
+ "runs_off_bat": payload.runs_off_bat,
396
+ "extras": payload.extras,
397
+ "extra_type": payload.extra_type,
398
+ "is_wicket": payload.is_wicket,
399
+ "wicket_type": payload.wicket_type,
400
+ "commentary": payload.commentary,
401
+ "created_by_id": current_user.id,
402
+ "created_at": now_utc(),
403
+ },
404
  )
405
 
406
+ refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
407
+ scoreboard = build_scoreboard(refreshed_match, innings_in_use)
 
 
408
 
409
  innings_over = False
410
  match_completed = False
411
 
412
+ team_player_count = get_batting_side_player_count(match_id, batting_team_in_use)
413
+ # All out when all players are dismissed (not team_player_count - 1)
414
+ all_out_limit = team_player_count
415
  if team_player_count > 0 and scoreboard.wickets >= all_out_limit:
416
  innings_over = True
417
  if innings_in_use == 1:
418
+ update_doc(
419
+ COLL.matches,
420
+ match_id,
421
+ {
422
+ "current_innings": 2,
423
+ "batting_team": "B" if batting_team_in_use == "A" else "A",
424
+ "updated_at": now_utc(),
425
+ },
426
+ )
427
  else:
428
+ update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()})
 
 
429
  match_completed = True
430
 
431
+ refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
432
+
433
  if not match_completed and innings_in_use == 2:
434
+ first_team, second_team = get_innings_teams(match_id, batting_team_in_use)
435
+ team_a_runs, team_b_runs, _, _ = get_team_totals(match_id)
436
  first_score = team_a_runs if first_team == "A" else team_b_runs
437
  second_score = team_a_runs if second_team == "A" else team_b_runs
438
 
439
  if second_score > first_score:
440
+ update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()})
441
+ refreshed_match = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
 
442
  match_completed = True
443
  innings_over = True
444
 
445
+ next_innings = refreshed_match.get("current_innings") or innings_in_use
446
+ next_over_number, next_ball_number = get_next_delivery_position(match_id, next_innings)
447
 
448
  return {
449
  "message": "Ball recorded",
450
  "innings_over": innings_over,
451
  "match_completed": match_completed,
452
+ "match_status": refreshed_match.get("status"),
453
  "recorded_ball": {
454
  "innings": innings_in_use,
455
  "over_number": auto_over_number,
 
459
  "innings": next_innings,
460
  "over_number": next_over_number,
461
  "ball_number": next_ball_number,
462
+ "batting_team": refreshed_match.get("batting_team"),
463
  },
464
  "scoreboard": scoreboard,
465
  }
466
 
467
 
468
  @router.get("/{match_id}/scoreboard", response_model=MatchScoreboardResponse)
469
+ async def get_match_scoreboard(match_id: int, innings: int = 1, current_user=Depends(get_current_user)):
 
 
 
 
 
470
  _ = current_user
471
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
472
  if not match_obj:
473
  raise HTTPException(status_code=404, detail="Match not found")
474
 
475
+ return build_scoreboard(match_obj, innings)
476
 
477
 
478
  @router.post("/{match_id}/complete", response_model=MatchResponse)
479
+ async def complete_match(match_id: int, current_user=Depends(get_current_user)):
480
+ match_obj = first_doc(COLL.matches, predicate=lambda row: row.get("id") == match_id)
 
 
 
 
481
  if not match_obj:
482
  raise HTTPException(status_code=404, detail="Match not found")
483
 
484
  ensure_match_editor(match_obj, current_user)
485
 
486
+ match_obj = update_doc(COLL.matches, match_id, {"status": "completed", "updated_at": now_utc()})
 
 
487
 
488
  log_action("Completed match", user_id=current_user.id, details=f"match_id={match_id}")
489
+ return as_obj(match_obj)
backend/app/routes/notifications.py CHANGED
@@ -1,35 +1,61 @@
1
- from datetime import datetime
2
  from fastapi import APIRouter, Depends, HTTPException
3
- from sqlalchemy.orm import Session
4
- from app.database import get_db
5
- from app.models import Notification, User
6
  from app.middleware.auth import get_current_user
7
  from app.schemas import NotificationResponse
 
8
  from app.utils.logger import log_action
9
- from app.utils.premium import check_and_downgrade_premium
10
 
11
  router = APIRouter(prefix="/notifications", tags=["Notifications"])
12
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @router.get("/me", response_model=list[NotificationResponse])
15
- async def get_my_notifications(
16
- current_user: User = Depends(get_current_user),
17
- db: Session = Depends(get_db),
18
- ):
19
- """Get notifications for current user."""
20
- notifications = db.query(Notification).filter(
21
- Notification.user_id == current_user.id
22
- ).order_by(Notification.created_at.desc()).limit(100).all()
23
- return notifications
24
 
25
 
26
  @router.post("/check-expiry")
27
- async def check_premium_expiry_notification(
28
- current_user: User = Depends(get_current_user),
29
- db: Session = Depends(get_db),
30
- ):
31
- """Create expiry warning notification if premium is close to expiry."""
32
- expired = check_and_downgrade_premium(db, current_user)
33
 
34
  if expired:
35
  return {
@@ -38,14 +64,15 @@ async def check_premium_expiry_notification(
38
  "notification_created": True,
39
  }
40
 
41
- if not current_user.is_premium or not current_user.premium_expiry:
42
  return {
43
  "message": "No active premium subscription.",
44
  "days_left": None,
45
  "notification_created": False,
46
  }
47
 
48
- days_left = (current_user.premium_expiry - datetime.utcnow()).total_seconds() / 86400
 
49
 
50
  if days_left > 3:
51
  return {
@@ -61,11 +88,12 @@ async def check_premium_expiry_notification(
61
  "notification_created": False,
62
  }
63
 
64
- existing = db.query(Notification).filter(
65
- Notification.user_id == current_user.id,
66
- Notification.notification_type == "premium_expiry_warning",
67
- Notification.is_read == False,
68
- ).first()
 
69
 
70
  if existing:
71
  return {
@@ -74,14 +102,17 @@ async def check_premium_expiry_notification(
74
  "notification_created": False,
75
  }
76
 
77
- notification = Notification(
78
- user_id=current_user.id,
79
- title="Premium Expiry Reminder",
80
- message=f"Your premium membership expires in {int(round(days_left))} day(s). Renew to stay featured.",
81
- notification_type="premium_expiry_warning",
 
 
 
 
 
82
  )
83
- db.add(notification)
84
- db.commit()
85
 
86
  log_action("Premium expiry warning created", user_id=current_user.id)
87
 
@@ -93,36 +124,27 @@ async def check_premium_expiry_notification(
93
 
94
 
95
  @router.put("/{notification_id}/read")
96
- async def mark_notification_as_read(
97
- notification_id: int,
98
- current_user: User = Depends(get_current_user),
99
- db: Session = Depends(get_db),
100
- ):
101
- """Mark a notification as read."""
102
- notification = db.query(Notification).filter(
103
- Notification.id == notification_id,
104
- Notification.user_id == current_user.id,
105
- ).first()
106
 
107
  if not notification:
108
  raise HTTPException(status_code=404, detail="Notification not found")
109
 
110
- notification.is_read = True
111
- db.commit()
112
 
113
  return {"message": "Notification marked as read"}
114
 
115
 
116
  @router.put("/read-all")
117
- async def mark_all_notifications_as_read(
118
- current_user: User = Depends(get_current_user),
119
- db: Session = Depends(get_db),
120
- ):
121
- """Mark all notifications as read."""
122
- db.query(Notification).filter(
123
- Notification.user_id == current_user.id,
124
- Notification.is_read == False,
125
- ).update({"is_read": True})
126
- db.commit()
127
 
128
  return {"message": "All notifications marked as read"}
 
1
+ from datetime import datetime, timezone
2
  from fastapi import APIRouter, Depends, HTTPException
3
+
 
 
4
  from app.middleware.auth import get_current_user
5
  from app.schemas import NotificationResponse
6
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime
7
  from app.utils.logger import log_action
 
8
 
9
  router = APIRouter(prefix="/notifications", tags=["Notifications"])
10
 
11
 
12
+ def _downgrade_if_expired(user: dict) -> bool:
13
+ expiry = user.get("premium_expiry")
14
+ if user.get("is_premium") and expiry:
15
+ # Parse expiry to timezone-aware datetime
16
+ expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry
17
+
18
+ # Ensure expiry_dt is timezone-aware
19
+ if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None:
20
+ expiry_dt = expiry_dt.replace(tzinfo=timezone.utc)
21
+
22
+ # Check if premium has expired
23
+ if expiry_dt and now_utc() >= expiry_dt:
24
+ update_doc(COLL.users, user["id"], {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()})
25
+ create_doc(
26
+ COLL.notifications,
27
+ {
28
+ "user_id": user["id"],
29
+ "title": "Premium Membership Expired",
30
+ "message": "Your premium membership has expired. Upgrade again to get featured!",
31
+ "notification_type": "premium_expiry",
32
+ "is_read": False,
33
+ "created_at": now_utc(),
34
+ },
35
+ )
36
+ return True
37
+ return False
38
+
39
+
40
  @router.get("/me", response_model=list[NotificationResponse])
41
+ async def get_my_notifications(current_user=Depends(get_current_user)):
42
+ notifications = list_docs(
43
+ COLL.notifications,
44
+ predicate=lambda row: row.get("user_id") == current_user.id,
45
+ sort_key="created_at",
46
+ reverse=True,
47
+ limit=100,
48
+ )
49
+ return [as_obj(row) for row in notifications]
50
 
51
 
52
  @router.post("/check-expiry")
53
+ async def check_premium_expiry_notification(current_user=Depends(get_current_user)):
54
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
55
+ if not user:
56
+ raise HTTPException(status_code=404, detail="User not found")
57
+
58
+ expired = _downgrade_if_expired(user)
59
 
60
  if expired:
61
  return {
 
64
  "notification_created": True,
65
  }
66
 
67
+ if not user.get("is_premium") or not user.get("premium_expiry"):
68
  return {
69
  "message": "No active premium subscription.",
70
  "days_left": None,
71
  "notification_created": False,
72
  }
73
 
74
+ expiry_dt = _parse_datetime(user["premium_expiry"]) if isinstance(user["premium_expiry"], str) else user["premium_expiry"]
75
+ days_left = (expiry_dt - now_utc()).total_seconds() / 86400 if expiry_dt else None
76
 
77
  if days_left > 3:
78
  return {
 
88
  "notification_created": False,
89
  }
90
 
91
+ existing = first_doc(
92
+ COLL.notifications,
93
+ predicate=lambda row: row.get("user_id") == current_user.id
94
+ and row.get("notification_type") == "premium_expiry_warning"
95
+ and not row.get("is_read", False),
96
+ )
97
 
98
  if existing:
99
  return {
 
102
  "notification_created": False,
103
  }
104
 
105
+ create_doc(
106
+ COLL.notifications,
107
+ {
108
+ "user_id": current_user.id,
109
+ "title": "Premium Expiry Reminder",
110
+ "message": f"Your premium membership expires in {int(round(days_left))} day(s). Renew to stay featured.",
111
+ "notification_type": "premium_expiry_warning",
112
+ "is_read": False,
113
+ "created_at": now_utc(),
114
+ },
115
  )
 
 
116
 
117
  log_action("Premium expiry warning created", user_id=current_user.id)
118
 
 
124
 
125
 
126
  @router.put("/{notification_id}/read")
127
+ async def mark_notification_as_read(notification_id: int, current_user=Depends(get_current_user)):
128
+ notification = first_doc(
129
+ COLL.notifications,
130
+ predicate=lambda row: row.get("id") == notification_id and row.get("user_id") == current_user.id,
131
+ )
 
 
 
 
 
132
 
133
  if not notification:
134
  raise HTTPException(status_code=404, detail="Notification not found")
135
 
136
+ update_doc(COLL.notifications, notification_id, {"is_read": True})
 
137
 
138
  return {"message": "Notification marked as read"}
139
 
140
 
141
  @router.put("/read-all")
142
+ async def mark_all_notifications_as_read(current_user=Depends(get_current_user)):
143
+ rows = list_docs(
144
+ COLL.notifications,
145
+ predicate=lambda row: row.get("user_id") == current_user.id and not row.get("is_read", False),
146
+ )
147
+ for row in rows:
148
+ update_doc(COLL.notifications, row["id"], {"is_read": True})
 
 
 
149
 
150
  return {"message": "All notifications marked as read"}
backend/app/routes/performance.py CHANGED
@@ -1,30 +1,42 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy.orm import Session
3
- from typing import List
4
- from app.database import get_db
5
- from app.models import PerformanceLog, User
6
- from app.schemas import PerformanceLogCreate, PerformanceLogUpdate, PerformanceLogResponse
7
  from app.middleware.auth import get_current_user
 
 
8
  from app.utils.logger import log_action
9
 
10
  router = APIRouter(prefix="/performance", tags=["Performance"])
11
 
12
 
13
- def recalculate_user_career_stats(db: Session, user: User) -> None:
14
- """Recalculate user stats from performance logs to keep career data accurate."""
15
- logs = db.query(PerformanceLog).filter(PerformanceLog.user_id == user.id).all()
16
-
17
- user.matches = len(logs)
18
- user.runs = sum(log.runs_scored for log in logs)
19
- user.wickets = sum(log.wickets_taken for log in logs)
20
- user.centuries = sum(1 for log in logs if log.runs_scored >= 100)
21
- user.half_centuries = sum(1 for log in logs if 50 <= log.runs_scored < 100)
22
- user.highest_score = max([log.runs_scored for log in logs], default=0)
23
- user.average_runs = round(user.runs / user.matches, 2) if user.matches else 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
 
26
- def build_ai_insights(logs: List[PerformanceLog]) -> dict:
27
- """Generate lightweight AI-style insights using recent performance trends."""
28
  if not logs:
29
  return {
30
  "headline": "No recent match data",
@@ -39,12 +51,12 @@ def build_ai_insights(logs: List[PerformanceLog]) -> dict:
39
  }
40
 
41
  recent = logs[:5]
42
- avg_runs = sum(item.runs_scored for item in recent) / len(recent)
43
- avg_wickets = sum(item.wickets_taken for item in recent) / len(recent)
44
- avg_rating = sum(item.performance_rating for item in recent) / len(recent)
45
 
46
- first_runs = recent[-1].runs_scored
47
- latest_runs = recent[0].runs_scored
48
  run_trend = latest_runs - first_runs
49
 
50
  if avg_rating >= 8:
@@ -96,81 +108,79 @@ def build_ai_insights(logs: List[PerformanceLog]) -> dict:
96
  @router.post("", response_model=PerformanceLogResponse)
97
  async def log_performance(
98
  performance: PerformanceLogCreate,
99
- current_user: User = Depends(get_current_user),
100
- db: Session = Depends(get_db)
101
  ):
102
- """Log a match performance"""
103
-
104
  if performance.runs_scored < 0 or performance.wickets_taken < 0:
105
  raise HTTPException(status_code=400, detail="Runs and wickets cannot be negative")
106
 
107
- perf_log = PerformanceLog(
108
- user_id=current_user.id,
109
- match_date=performance.match_date,
110
- runs_scored=performance.runs_scored,
111
- wickets_taken=performance.wickets_taken,
112
- match_type=performance.match_type,
113
- opponent=performance.opponent,
114
- performance_rating=performance.performance_rating,
115
- notes=performance.notes
 
 
 
 
116
  )
117
 
118
- db.add(perf_log)
119
- db.flush()
120
- recalculate_user_career_stats(db, current_user)
121
- db.commit()
122
- db.refresh(perf_log)
123
-
124
- log_action("Performance logged", user_id=current_user.id,
125
- details=f"{performance.runs_scored} runs")
126
-
127
- return perf_log
128
 
129
 
130
  @router.get("/my-logs", response_model=List[PerformanceLogResponse])
131
  async def get_my_performance_logs(
132
- current_user: User = Depends(get_current_user),
133
  skip: int = 0,
134
  limit: int = 20,
135
- db: Session = Depends(get_db)
136
  ):
137
- """Get current player's performance logs"""
138
-
139
- logs = db.query(PerformanceLog).filter(
140
- PerformanceLog.user_id == current_user.id
141
- ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all()
142
-
143
- return logs
 
 
144
 
145
 
146
  @router.get("/match-history")
147
  async def get_my_match_history(
148
- current_user: User = Depends(get_current_user),
149
  skip: int = 0,
150
  limit: int = 30,
151
- db: Session = Depends(get_db),
152
  ):
153
- """Get structured match history with summary for dashboard and profile views."""
154
- logs = db.query(PerformanceLog).filter(
155
- PerformanceLog.user_id == current_user.id
156
- ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all()
 
 
 
 
157
 
158
- total_runs = sum(log.runs_scored for log in logs)
159
- total_wickets = sum(log.wickets_taken for log in logs)
160
  average_rating = round(
161
- sum(log.performance_rating for log in logs) / len(logs), 2
162
  ) if logs else 0.0
163
 
164
  best_match = None
165
  if logs:
166
- top = max(logs, key=lambda item: (item.runs_scored + (item.wickets_taken * 20)))
167
  best_match = {
168
- "id": top.id,
169
- "match_date": top.match_date,
170
- "opponent": top.opponent,
171
- "runs_scored": top.runs_scored,
172
- "wickets_taken": top.wickets_taken,
173
- "performance_rating": top.performance_rating,
174
  }
175
 
176
  return {
@@ -181,7 +191,7 @@ async def get_my_match_history(
181
  "average_rating": average_rating,
182
  "best_match": best_match,
183
  },
184
- "logs": logs,
185
  }
186
 
187
 
@@ -189,14 +199,12 @@ async def get_my_match_history(
189
  async def update_performance_log(
190
  log_id: int,
191
  payload: PerformanceLogUpdate,
192
- current_user: User = Depends(get_current_user),
193
- db: Session = Depends(get_db),
194
  ):
195
- """Edit an existing performance log for the current player."""
196
- perf_log = db.query(PerformanceLog).filter(
197
- PerformanceLog.id == log_id,
198
- PerformanceLog.user_id == current_user.id,
199
- ).first()
200
 
201
  if not perf_log:
202
  raise HTTPException(status_code=404, detail="Performance log not found")
@@ -208,36 +216,28 @@ async def update_performance_log(
208
  if "wickets_taken" in updates and updates["wickets_taken"] < 0:
209
  raise HTTPException(status_code=400, detail="Wickets cannot be negative")
210
 
211
- for key, value in updates.items():
212
- setattr(perf_log, key, value)
213
-
214
- recalculate_user_career_stats(db, current_user)
215
- db.commit()
216
- db.refresh(perf_log)
217
 
218
  log_action("Performance log updated", user_id=current_user.id, details=f"log_id={log_id}")
219
- return perf_log
220
 
221
 
222
  @router.delete("/{log_id}")
223
  async def delete_performance_log(
224
  log_id: int,
225
- current_user: User = Depends(get_current_user),
226
- db: Session = Depends(get_db),
227
  ):
228
- """Delete a performance log and recalculate career stats."""
229
- perf_log = db.query(PerformanceLog).filter(
230
- PerformanceLog.id == log_id,
231
- PerformanceLog.user_id == current_user.id,
232
- ).first()
233
 
234
  if not perf_log:
235
  raise HTTPException(status_code=404, detail="Performance log not found")
236
 
237
- db.delete(perf_log)
238
- db.flush()
239
- recalculate_user_career_stats(db, current_user)
240
- db.commit()
241
 
242
  log_action("Performance log deleted", user_id=current_user.id, details=f"log_id={log_id}")
243
  return {"message": "Performance log deleted"}
@@ -245,70 +245,63 @@ async def delete_performance_log(
245
 
246
  @router.get("/player/{player_id}", response_model=List[PerformanceLogResponse])
247
  async def get_player_performance_logs(
248
- player_id: int,
249
  skip: int = 0,
250
  limit: int = 20,
251
- db: Session = Depends(get_db)
252
  ):
253
- """Get a player's performance logs"""
254
-
255
- # Check if player exists
256
- player = db.query(User).filter(User.id == player_id).first()
257
  if not player:
258
- raise HTTPException(
259
- status_code=status.HTTP_404_NOT_FOUND,
260
- detail="Player not found"
261
- )
262
-
263
- logs = db.query(PerformanceLog).filter(
264
- PerformanceLog.user_id == player_id
265
- ).order_by(PerformanceLog.match_date.desc()).offset(skip).limit(limit).all()
 
 
266
 
267
- return logs
268
 
269
 
270
  @router.get("/stats/{player_id}")
271
- async def get_player_stats(player_id: int, db: Session = Depends(get_db)):
272
- """Get player statistics summary"""
273
-
274
- player = db.query(User).filter(User.id == player_id).first()
275
 
276
  if not player:
277
- raise HTTPException(
278
- status_code=status.HTTP_404_NOT_FOUND,
279
- detail="Player not found"
280
- )
281
 
282
  return {
283
- "id": player.id,
284
- "name": player.name,
285
- "runs": player.runs,
286
- "matches": player.matches,
287
- "wickets": player.wickets,
288
- "centuries": player.centuries,
289
- "half_centuries": player.half_centuries,
290
- "average_runs": player.average_runs,
291
- "highest_score": player.highest_score
292
  }
293
 
294
 
295
  @router.get("/ai-insights/{player_id}")
296
- async def get_player_ai_insights(player_id: int, db: Session = Depends(get_db)):
297
- """Generate AI-based performance insights from recent match logs."""
298
- player = db.query(User).filter(User.id == player_id).first()
299
 
300
  if not player:
301
- raise HTTPException(
302
- status_code=status.HTTP_404_NOT_FOUND,
303
- detail="Player not found",
304
- )
305
-
306
- logs = db.query(PerformanceLog).filter(
307
- PerformanceLog.user_id == player_id
308
- ).order_by(PerformanceLog.match_date.desc()).limit(10).all()
 
309
 
310
  return {
311
- "player_id": player.id,
312
- "player_name": player.name,
313
  "insights": build_ai_insights(logs),
314
  }
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
+ from typing import List, Union
3
+
 
 
 
4
  from app.middleware.auth import get_current_user
5
+ from app.schemas import PerformanceLogCreate, PerformanceLogUpdate, PerformanceLogResponse
6
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, delete_doc
7
  from app.utils.logger import log_action
8
 
9
  router = APIRouter(prefix="/performance", tags=["Performance"])
10
 
11
 
12
+ def recalculate_user_career_stats(user_id: int) -> None:
13
+ logs = list_docs(COLL.performance_logs, predicate=lambda row: row.get("user_id") == user_id)
14
+
15
+ matches = len(logs)
16
+ runs = sum(int(log.get("runs_scored", 0)) for log in logs)
17
+ wickets = sum(int(log.get("wickets_taken", 0)) for log in logs)
18
+ centuries = sum(1 for log in logs if int(log.get("runs_scored", 0)) >= 100)
19
+ half_centuries = sum(1 for log in logs if 50 <= int(log.get("runs_scored", 0)) < 100)
20
+ highest_score = max([int(log.get("runs_scored", 0)) for log in logs], default=0)
21
+ average_runs = round(runs / matches, 2) if matches else 0.0
22
+
23
+ update_doc(
24
+ COLL.users,
25
+ user_id,
26
+ {
27
+ "matches": matches,
28
+ "runs": runs,
29
+ "wickets": wickets,
30
+ "centuries": centuries,
31
+ "half_centuries": half_centuries,
32
+ "highest_score": highest_score,
33
+ "average_runs": average_runs,
34
+ "updated_at": now_utc(),
35
+ },
36
+ )
37
 
38
 
39
+ def build_ai_insights(logs: List[dict]) -> dict:
 
40
  if not logs:
41
  return {
42
  "headline": "No recent match data",
 
51
  }
52
 
53
  recent = logs[:5]
54
+ avg_runs = sum(float(item.get("runs_scored", 0)) for item in recent) / len(recent)
55
+ avg_wickets = sum(float(item.get("wickets_taken", 0)) for item in recent) / len(recent)
56
+ avg_rating = sum(float(item.get("performance_rating", 0)) for item in recent) / len(recent)
57
 
58
+ first_runs = float(recent[-1].get("runs_scored", 0))
59
+ latest_runs = float(recent[0].get("runs_scored", 0))
60
  run_trend = latest_runs - first_runs
61
 
62
  if avg_rating >= 8:
 
108
  @router.post("", response_model=PerformanceLogResponse)
109
  async def log_performance(
110
  performance: PerformanceLogCreate,
111
+ current_user=Depends(get_current_user),
 
112
  ):
 
 
113
  if performance.runs_scored < 0 or performance.wickets_taken < 0:
114
  raise HTTPException(status_code=400, detail="Runs and wickets cannot be negative")
115
 
116
+ perf_log = create_doc(
117
+ COLL.performance_logs,
118
+ {
119
+ "user_id": current_user.id,
120
+ "match_date": performance.match_date,
121
+ "runs_scored": performance.runs_scored,
122
+ "wickets_taken": performance.wickets_taken,
123
+ "match_type": performance.match_type,
124
+ "opponent": performance.opponent,
125
+ "performance_rating": performance.performance_rating,
126
+ "notes": performance.notes,
127
+ "created_at": now_utc(),
128
+ },
129
  )
130
 
131
+ recalculate_user_career_stats(current_user.id)
132
+ log_action("Performance logged", user_id=current_user.id, details=f"{performance.runs_scored} runs")
133
+ return as_obj(perf_log)
 
 
 
 
 
 
 
134
 
135
 
136
  @router.get("/my-logs", response_model=List[PerformanceLogResponse])
137
  async def get_my_performance_logs(
138
+ current_user=Depends(get_current_user),
139
  skip: int = 0,
140
  limit: int = 20,
 
141
  ):
142
+ logs = list_docs(
143
+ COLL.performance_logs,
144
+ predicate=lambda row: row.get("user_id") == current_user.id,
145
+ sort_key="match_date",
146
+ reverse=True,
147
+ offset=skip,
148
+ limit=limit,
149
+ )
150
+ return [as_obj(row) for row in logs]
151
 
152
 
153
  @router.get("/match-history")
154
  async def get_my_match_history(
155
+ current_user=Depends(get_current_user),
156
  skip: int = 0,
157
  limit: int = 30,
 
158
  ):
159
+ logs = list_docs(
160
+ COLL.performance_logs,
161
+ predicate=lambda row: row.get("user_id") == current_user.id,
162
+ sort_key="match_date",
163
+ reverse=True,
164
+ offset=skip,
165
+ limit=limit,
166
+ )
167
 
168
+ total_runs = sum(int(log.get("runs_scored", 0)) for log in logs)
169
+ total_wickets = sum(int(log.get("wickets_taken", 0)) for log in logs)
170
  average_rating = round(
171
+ sum(float(log.get("performance_rating", 0)) for log in logs) / len(logs), 2
172
  ) if logs else 0.0
173
 
174
  best_match = None
175
  if logs:
176
+ top = max(logs, key=lambda item: (int(item.get("runs_scored", 0)) + (int(item.get("wickets_taken", 0)) * 20)))
177
  best_match = {
178
+ "id": top.get("id"),
179
+ "match_date": top.get("match_date"),
180
+ "opponent": top.get("opponent"),
181
+ "runs_scored": top.get("runs_scored"),
182
+ "wickets_taken": top.get("wickets_taken"),
183
+ "performance_rating": top.get("performance_rating"),
184
  }
185
 
186
  return {
 
191
  "average_rating": average_rating,
192
  "best_match": best_match,
193
  },
194
+ "logs": [as_obj(row) for row in logs],
195
  }
196
 
197
 
 
199
  async def update_performance_log(
200
  log_id: int,
201
  payload: PerformanceLogUpdate,
202
+ current_user=Depends(get_current_user),
 
203
  ):
204
+ perf_log = first_doc(
205
+ COLL.performance_logs,
206
+ predicate=lambda row: row.get("id") == log_id and row.get("user_id") == current_user.id,
207
+ )
 
208
 
209
  if not perf_log:
210
  raise HTTPException(status_code=404, detail="Performance log not found")
 
216
  if "wickets_taken" in updates and updates["wickets_taken"] < 0:
217
  raise HTTPException(status_code=400, detail="Wickets cannot be negative")
218
 
219
+ perf_log = update_doc(COLL.performance_logs, log_id, updates)
220
+ recalculate_user_career_stats(current_user.id)
 
 
 
 
221
 
222
  log_action("Performance log updated", user_id=current_user.id, details=f"log_id={log_id}")
223
+ return as_obj(perf_log)
224
 
225
 
226
  @router.delete("/{log_id}")
227
  async def delete_performance_log(
228
  log_id: int,
229
+ current_user=Depends(get_current_user),
 
230
  ):
231
+ perf_log = first_doc(
232
+ COLL.performance_logs,
233
+ predicate=lambda row: row.get("id") == log_id and row.get("user_id") == current_user.id,
234
+ )
 
235
 
236
  if not perf_log:
237
  raise HTTPException(status_code=404, detail="Performance log not found")
238
 
239
+ delete_doc(COLL.performance_logs, log_id)
240
+ recalculate_user_career_stats(current_user.id)
 
 
241
 
242
  log_action("Performance log deleted", user_id=current_user.id, details=f"log_id={log_id}")
243
  return {"message": "Performance log deleted"}
 
245
 
246
  @router.get("/player/{player_id}", response_model=List[PerformanceLogResponse])
247
  async def get_player_performance_logs(
248
+ player_id: Union[int, str],
249
  skip: int = 0,
250
  limit: int = 20,
 
251
  ):
252
+ player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id)
 
 
 
253
  if not player:
254
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
255
+
256
+ logs = list_docs(
257
+ COLL.performance_logs,
258
+ predicate=lambda row: row.get("user_id") == player_id,
259
+ sort_key="match_date",
260
+ reverse=True,
261
+ offset=skip,
262
+ limit=limit,
263
+ )
264
 
265
+ return [as_obj(row) for row in logs]
266
 
267
 
268
  @router.get("/stats/{player_id}")
269
+ async def get_player_stats(player_id: Union[int, str]):
270
+ player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id)
 
 
271
 
272
  if not player:
273
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
 
 
 
274
 
275
  return {
276
+ "id": player.get("id"),
277
+ "name": player.get("name"),
278
+ "runs": player.get("runs", 0),
279
+ "matches": player.get("matches", 0),
280
+ "wickets": player.get("wickets", 0),
281
+ "centuries": player.get("centuries", 0),
282
+ "half_centuries": player.get("half_centuries", 0),
283
+ "average_runs": player.get("average_runs", 0.0),
284
+ "highest_score": player.get("highest_score", 0),
285
  }
286
 
287
 
288
  @router.get("/ai-insights/{player_id}")
289
+ async def get_player_ai_insights(player_id: Union[int, str]):
290
+ player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id)
 
291
 
292
  if not player:
293
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
294
+
295
+ logs = list_docs(
296
+ COLL.performance_logs,
297
+ predicate=lambda row: row.get("user_id") == player_id,
298
+ sort_key="match_date",
299
+ reverse=True,
300
+ limit=10,
301
+ )
302
 
303
  return {
304
+ "player_id": player.get("id"),
305
+ "player_name": player.get("name"),
306
  "insights": build_ai_insights(logs),
307
  }
backend/app/routes/players.py CHANGED
@@ -1,151 +1,190 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy.orm import Session
3
- from typing import List
4
- from app.database import get_db
5
- from app.models import User
6
  from app.schemas import UserResponse, UserUpdate, CareerStatsUpdate
7
  from app.middleware.auth import get_current_user
8
- from app.utils.premium import check_and_downgrade_premium
9
  from app.utils.logger import log_action
10
 
11
  router = APIRouter(prefix="/players", tags=["Players"])
12
 
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @router.get("/me", response_model=UserResponse)
15
- async def get_current_player(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
16
  """Get current logged-in player's profile"""
17
- check_and_downgrade_premium(db, current_user)
18
- db.refresh(current_user)
19
- log_action("Viewed own profile", user_id=current_user.id)
20
- return current_user
 
 
21
 
22
 
23
  @router.put("/me", response_model=UserResponse)
24
  async def update_current_player(
25
  user_update: UserUpdate,
26
- current_user: User = Depends(get_current_user),
27
- db: Session = Depends(get_db)
28
  ):
29
  """Update current player's profile"""
30
 
 
31
  if user_update.name:
32
- current_user.name = user_update.name
33
  if user_update.bio is not None:
34
- current_user.bio = user_update.bio
35
  if user_update.jersey_number is not None:
36
- current_user.jersey_number = user_update.jersey_number
37
-
38
- db.commit()
39
- db.refresh(current_user)
40
-
41
- log_action("Updated profile", user_id=current_user.id)
42
- return current_user
 
43
 
44
 
45
  @router.put("/me/career-stats", response_model=UserResponse)
46
  async def update_career_stats(
47
  stats_update: CareerStatsUpdate,
48
- current_user: User = Depends(get_current_user),
49
- db: Session = Depends(get_db),
50
  ):
51
  """Update current player's career statistics"""
52
 
 
 
 
 
 
 
53
  if stats_update.runs is not None:
54
  if stats_update.runs < 0:
55
  raise HTTPException(status_code=400, detail="Runs cannot be negative")
56
- current_user.runs = stats_update.runs
57
 
58
  if stats_update.matches is not None:
59
  if stats_update.matches < 0:
60
  raise HTTPException(status_code=400, detail="Matches cannot be negative")
61
- current_user.matches = stats_update.matches
62
 
63
  if stats_update.wickets is not None:
64
  if stats_update.wickets < 0:
65
  raise HTTPException(status_code=400, detail="Wickets cannot be negative")
66
- current_user.wickets = stats_update.wickets
67
 
68
  if stats_update.centuries is not None:
69
  if stats_update.centuries < 0:
70
  raise HTTPException(status_code=400, detail="Centuries cannot be negative")
71
- current_user.centuries = stats_update.centuries
72
 
73
  if stats_update.half_centuries is not None:
74
  if stats_update.half_centuries < 0:
75
  raise HTTPException(status_code=400, detail="Half-centuries cannot be negative")
76
- current_user.half_centuries = stats_update.half_centuries
77
 
78
  if stats_update.highest_score is not None:
79
  if stats_update.highest_score < 0:
80
  raise HTTPException(status_code=400, detail="Highest score cannot be negative")
81
- current_user.highest_score = stats_update.highest_score
82
 
83
- if current_user.matches > 0:
84
- current_user.average_runs = round(current_user.runs / current_user.matches, 2)
 
 
85
  else:
86
- current_user.average_runs = 0.0
87
 
88
- db.commit()
89
- db.refresh(current_user)
 
90
 
91
- log_action("Updated career stats", user_id=current_user.id)
92
- return current_user
93
 
94
 
95
  @router.get("", response_model=List[UserResponse])
96
- async def list_all_players(skip: int = 0, limit: int = 50, db: Session = Depends(get_db)):
97
  """Get list of all active players"""
98
 
99
- players = db.query(User).filter(User.is_active == True).offset(skip).limit(limit).all()
100
-
101
- for player in players:
102
- check_and_downgrade_premium(db, player)
103
-
104
- return players
 
 
 
105
 
106
 
107
  @router.get("/premium", response_model=List[UserResponse])
108
- async def get_premium_players(db: Session = Depends(get_db)):
109
  """Get list of premium players"""
110
 
111
- premium_players = db.query(User).filter(
112
- User.is_premium == True,
113
- User.is_active == True
114
- ).order_by(User.runs.desc()).all()
115
-
116
- for player in premium_players:
117
- check_and_downgrade_premium(db, player)
118
-
119
- return premium_players
120
 
121
 
122
  @router.get("/leaderboard/top-performers", response_model=List[UserResponse])
123
- async def get_top_performers(limit: int = 10, db: Session = Depends(get_db)):
124
  """Get top performers by runs"""
125
 
126
- top_players = db.query(User).filter(User.is_active == True).order_by(
127
- User.runs.desc()
128
- ).limit(limit).all()
129
-
130
- return top_players
 
 
 
131
 
132
 
133
  @router.get("/leaderboard/by-wickets", response_model=List[UserResponse])
134
- async def get_top_wicket_takers(limit: int = 10, db: Session = Depends(get_db)):
135
  """Get top wicket takers"""
136
 
137
- top_wicket_takers = db.query(User).filter(User.is_active == True).order_by(
138
- User.wickets.desc()
139
- ).limit(limit).all()
140
-
141
- return top_wicket_takers
 
 
 
142
 
143
 
144
  @router.get("/{player_id}", response_model=UserResponse)
145
- async def get_player(player_id: int, db: Session = Depends(get_db)):
146
  """Get player profile by ID"""
147
 
148
- player = db.query(User).filter(User.id == player_id).first()
149
 
150
  if not player:
151
  raise HTTPException(
@@ -153,7 +192,5 @@ async def get_player(player_id: int, db: Session = Depends(get_db)):
153
  detail="Player not found"
154
  )
155
 
156
- check_and_downgrade_premium(db, player)
157
- db.refresh(player)
158
-
159
- return player
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
+ from typing import List, Union
 
 
 
3
  from app.schemas import UserResponse, UserUpdate, CareerStatsUpdate
4
  from app.middleware.auth import get_current_user
5
+ from app.utils.firestore_data import COLL, as_obj, first_doc, list_docs, now_utc, update_doc, _parse_datetime, normalize_user
6
  from app.utils.logger import log_action
7
 
8
  router = APIRouter(prefix="/players", tags=["Players"])
9
 
10
 
11
+ def _check_and_downgrade_premium(user: dict) -> dict:
12
+ from datetime import datetime, timezone
13
+
14
+ expiry = user.get("premium_expiry")
15
+ if user.get("is_premium") and expiry:
16
+ # Parse expiry to timezone-aware datetime
17
+ expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry
18
+
19
+ # Ensure expiry_dt is timezone-aware
20
+ if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None:
21
+ expiry_dt = expiry_dt.replace(tzinfo=timezone.utc)
22
+
23
+ # Check if premium has expired
24
+ if expiry_dt and now_utc() >= expiry_dt:
25
+ # Use _doc_id (actual Firestore document ID) if available, otherwise use id
26
+ doc_id = user.get("_doc_id") or user.get("id")
27
+ user = update_doc(
28
+ COLL.users,
29
+ doc_id,
30
+ {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()},
31
+ ) or user
32
+ return user
33
+
34
+
35
  @router.get("/me", response_model=UserResponse)
36
+ async def get_current_player(current_user=Depends(get_current_user)):
37
  """Get current logged-in player's profile"""
38
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
39
+ if not user:
40
+ raise HTTPException(status_code=404, detail="Player not found")
41
+ user = _check_and_downgrade_premium(user)
42
+ log_action("Viewed own profile", user_id=user["id"])
43
+ return normalize_user(user)
44
 
45
 
46
  @router.put("/me", response_model=UserResponse)
47
  async def update_current_player(
48
  user_update: UserUpdate,
49
+ current_user=Depends(get_current_user),
 
50
  ):
51
  """Update current player's profile"""
52
 
53
+ patch = {"updated_at": now_utc()}
54
  if user_update.name:
55
+ patch["name"] = user_update.name
56
  if user_update.bio is not None:
57
+ patch["bio"] = user_update.bio
58
  if user_update.jersey_number is not None:
59
+ patch["jersey_number"] = user_update.jersey_number
60
+
61
+ user = update_doc(COLL.users, current_user.id, patch)
62
+ if not user:
63
+ raise HTTPException(status_code=404, detail="Player not found")
64
+
65
+ log_action("Updated profile", user_id=user["id"])
66
+ return normalize_user(user)
67
 
68
 
69
  @router.put("/me/career-stats", response_model=UserResponse)
70
  async def update_career_stats(
71
  stats_update: CareerStatsUpdate,
72
+ current_user=Depends(get_current_user),
 
73
  ):
74
  """Update current player's career statistics"""
75
 
76
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
77
+ if not user:
78
+ raise HTTPException(status_code=404, detail="Player not found")
79
+
80
+ patch = {"updated_at": now_utc()}
81
+
82
  if stats_update.runs is not None:
83
  if stats_update.runs < 0:
84
  raise HTTPException(status_code=400, detail="Runs cannot be negative")
85
+ patch["runs"] = stats_update.runs
86
 
87
  if stats_update.matches is not None:
88
  if stats_update.matches < 0:
89
  raise HTTPException(status_code=400, detail="Matches cannot be negative")
90
+ patch["matches"] = stats_update.matches
91
 
92
  if stats_update.wickets is not None:
93
  if stats_update.wickets < 0:
94
  raise HTTPException(status_code=400, detail="Wickets cannot be negative")
95
+ patch["wickets"] = stats_update.wickets
96
 
97
  if stats_update.centuries is not None:
98
  if stats_update.centuries < 0:
99
  raise HTTPException(status_code=400, detail="Centuries cannot be negative")
100
+ patch["centuries"] = stats_update.centuries
101
 
102
  if stats_update.half_centuries is not None:
103
  if stats_update.half_centuries < 0:
104
  raise HTTPException(status_code=400, detail="Half-centuries cannot be negative")
105
+ patch["half_centuries"] = stats_update.half_centuries
106
 
107
  if stats_update.highest_score is not None:
108
  if stats_update.highest_score < 0:
109
  raise HTTPException(status_code=400, detail="Highest score cannot be negative")
110
+ patch["highest_score"] = stats_update.highest_score
111
 
112
+ runs = patch.get("runs", user.get("runs", 0))
113
+ matches = patch.get("matches", user.get("matches", 0))
114
+ if matches > 0:
115
+ patch["average_runs"] = round(runs / matches, 2)
116
  else:
117
+ patch["average_runs"] = 0.0
118
 
119
+ user = update_doc(COLL.users, current_user.id, patch)
120
+ if not user:
121
+ raise HTTPException(status_code=404, detail="Player not found")
122
 
123
+ log_action("Updated career stats", user_id=user["id"])
124
+ return normalize_user(user)
125
 
126
 
127
  @router.get("", response_model=List[UserResponse])
128
+ async def list_all_players(skip: int = 0, limit: int = 50):
129
  """Get list of all active players"""
130
 
131
+ players = list_docs(
132
+ COLL.users,
133
+ predicate=lambda row: row.get("is_active", True),
134
+ sort_key="created_at",
135
+ reverse=True,
136
+ offset=skip,
137
+ limit=limit,
138
+ )
139
+ return [normalize_user(_check_and_downgrade_premium(player)) for player in players]
140
 
141
 
142
  @router.get("/premium", response_model=List[UserResponse])
143
+ async def get_premium_players():
144
  """Get list of premium players"""
145
 
146
+ premium_players = list_docs(
147
+ COLL.users,
148
+ predicate=lambda row: row.get("is_active", True) and row.get("is_premium", False),
149
+ sort_key="runs",
150
+ reverse=True,
151
+ )
152
+ return [normalize_user(_check_and_downgrade_premium(player)) for player in premium_players]
 
 
153
 
154
 
155
  @router.get("/leaderboard/top-performers", response_model=List[UserResponse])
156
+ async def get_top_performers(limit: int = 10):
157
  """Get top performers by runs"""
158
 
159
+ top_players = list_docs(
160
+ COLL.users,
161
+ predicate=lambda row: row.get("is_active", True),
162
+ sort_key="runs",
163
+ reverse=True,
164
+ limit=limit,
165
+ )
166
+ return [normalize_user(row) for row in top_players]
167
 
168
 
169
  @router.get("/leaderboard/by-wickets", response_model=List[UserResponse])
170
+ async def get_top_wicket_takers(limit: int = 10):
171
  """Get top wicket takers"""
172
 
173
+ top_wicket_takers = list_docs(
174
+ COLL.users,
175
+ predicate=lambda row: row.get("is_active", True),
176
+ sort_key="wickets",
177
+ reverse=True,
178
+ limit=limit,
179
+ )
180
+ return [normalize_user(row) for row in top_wicket_takers]
181
 
182
 
183
  @router.get("/{player_id}", response_model=UserResponse)
184
+ async def get_player(player_id: Union[int, str]):
185
  """Get player profile by ID"""
186
 
187
+ player = first_doc(COLL.users, predicate=lambda row: row.get("id") == player_id)
188
 
189
  if not player:
190
  raise HTTPException(
 
192
  detail="Player not found"
193
  )
194
 
195
+ player = _check_and_downgrade_premium(player)
196
+ return normalize_user(player)
 
 
backend/app/routes/premium.py CHANGED
@@ -1,11 +1,8 @@
1
  from fastapi import APIRouter, Depends, HTTPException, status
2
- from sqlalchemy.orm import Session
3
  from datetime import datetime, timedelta
4
- from app.database import get_db
5
- from app.models import User, Payment, FinanceTransaction
6
  from app.schemas import PremiumUpgradeRequest, PremiumResponse, PaymentResponse
7
  from app.middleware.auth import get_current_user
8
- from app.utils.premium import upgrade_to_premium, check_and_downgrade_premium
9
  from app.utils.logger import log_action, log_error
10
  import uuid
11
 
@@ -15,104 +12,160 @@ router = APIRouter(prefix="/premium", tags=["Premium"])
15
  @router.post("/upgrade", response_model=PremiumResponse)
16
  async def upgrade_to_premium_plan(
17
  request_data: PremiumUpgradeRequest,
18
- current_user: User = Depends(get_current_user),
19
- db: Session = Depends(get_db)
20
  ):
21
  """Upgrade player to premium membership"""
22
 
23
- if current_user.is_premium:
 
 
 
 
24
  # Extend premium period
25
- new_expiry = current_user.premium_expiry + timedelta(days=request_data.plan_days)
26
- current_user.premium_expiry = new_expiry
 
 
 
 
 
 
 
27
  else:
28
  # New premium membership
29
- upgrade_to_premium(db, current_user, request_data.plan_days)
 
 
 
 
 
 
 
 
 
30
 
31
  # Create payment record
32
- payment = Payment(
33
- user_id=current_user.id,
34
- amount=1000, # ₹1000
35
- transaction_id=str(uuid.uuid4()),
36
- status="completed",
37
- plan_duration_days=request_data.plan_days
 
 
 
 
 
 
 
38
  )
39
 
40
- finance_entry = FinanceTransaction(
41
- user_id=current_user.id,
42
- transaction_type="credit",
43
- amount=1000,
44
- category="premium_payment",
45
- description=f"Premium payment by {current_user.email}",
46
- reference_id=payment.transaction_id,
 
 
 
 
47
  )
48
 
49
- db.add(payment)
50
- db.add(finance_entry)
51
- db.commit()
52
- db.refresh(current_user)
53
-
54
- log_action("Premium upgrade", user_id=current_user.id, details=f"{request_data.plan_days} days")
55
 
56
  return {
57
- "is_premium": current_user.is_premium,
58
- "premium_expiry": current_user.premium_expiry,
59
  "message": f"Successfully upgraded to premium for {request_data.plan_days} days!"
60
  }
61
 
62
 
63
  @router.get("/status", response_model=PremiumResponse)
64
  async def get_premium_status(
65
- current_user: User = Depends(get_current_user),
66
- db: Session = Depends(get_db)
67
  ):
68
  """Get current premium status"""
69
 
70
- check_and_downgrade_premium(db, current_user)
71
- db.refresh(current_user)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- if current_user.is_premium:
74
- message = f"Premium active until {current_user.premium_expiry.strftime('%Y-%m-%d')}"
 
 
 
 
 
 
 
75
  else:
76
  message = "Not a premium member. Upgrade to get featured!"
77
 
78
  return {
79
- "is_premium": current_user.is_premium,
80
- "premium_expiry": current_user.premium_expiry,
81
  "message": message
82
  }
83
 
84
 
85
  @router.post("/cancel")
86
  async def cancel_premium(
87
- current_user: User = Depends(get_current_user),
88
- db: Session = Depends(get_db)
89
  ):
90
  """Cancel premium membership"""
91
 
92
- if not current_user.is_premium:
 
 
 
 
93
  raise HTTPException(
94
  status_code=status.HTTP_400_BAD_REQUEST,
95
  detail="User is not a premium member"
96
  )
97
 
98
- current_user.is_premium = False
99
- current_user.premium_expiry = None
100
- db.commit()
 
 
101
 
102
- log_action("Premium cancelled", user_id=current_user.id)
103
 
104
  return {"message": "Premium membership cancelled"}
105
 
106
 
107
  @router.get("/payments", response_model=list)
108
  async def get_payment_history(
109
- current_user: User = Depends(get_current_user),
110
- db: Session = Depends(get_db)
111
  ):
112
  """Get payment history"""
113
 
114
- payments = db.query(Payment).filter(Payment.user_id == current_user.id).order_by(
115
- Payment.created_at.desc()
116
- ).all()
117
-
118
- return payments
 
 
 
1
  from fastapi import APIRouter, Depends, HTTPException, status
 
2
  from datetime import datetime, timedelta
 
 
3
  from app.schemas import PremiumUpgradeRequest, PremiumResponse, PaymentResponse
4
  from app.middleware.auth import get_current_user
5
+ from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, list_docs, now_utc, update_doc, _parse_datetime
6
  from app.utils.logger import log_action, log_error
7
  import uuid
8
 
 
12
  @router.post("/upgrade", response_model=PremiumResponse)
13
  async def upgrade_to_premium_plan(
14
  request_data: PremiumUpgradeRequest,
15
+ current_user=Depends(get_current_user),
 
16
  ):
17
  """Upgrade player to premium membership"""
18
 
19
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
20
+ if not user:
21
+ raise HTTPException(status_code=404, detail="User not found")
22
+
23
+ if user.get("is_premium"):
24
  # Extend premium period
25
+ current_expiry = user.get("premium_expiry", now_utc())
26
+ if isinstance(current_expiry, str):
27
+ current_expiry = _parse_datetime(current_expiry) or now_utc()
28
+ new_expiry = current_expiry + timedelta(days=request_data.plan_days)
29
+ user = update_doc(
30
+ COLL.users,
31
+ user["id"],
32
+ {"premium_expiry": new_expiry, "updated_at": now_utc()},
33
+ ) or user
34
  else:
35
  # New premium membership
36
+ user = update_doc(
37
+ COLL.users,
38
+ user["id"],
39
+ {
40
+ "is_premium": True,
41
+ "premium_start_date": now_utc(),
42
+ "premium_expiry": now_utc() + timedelta(days=request_data.plan_days),
43
+ "updated_at": now_utc(),
44
+ },
45
+ ) or user
46
 
47
  # Create payment record
48
+ transaction_id = str(uuid.uuid4())
49
+ create_doc(
50
+ COLL.payments,
51
+ {
52
+ "user_id": user["id"],
53
+ "amount": 1000.0,
54
+ "payment_method": "razorpay",
55
+ "transaction_id": transaction_id,
56
+ "status": "completed",
57
+ "plan_duration_days": request_data.plan_days,
58
+ "created_at": now_utc(),
59
+ "updated_at": now_utc(),
60
+ },
61
  )
62
 
63
+ create_doc(
64
+ COLL.finance_transactions,
65
+ {
66
+ "user_id": user["id"],
67
+ "transaction_type": "credit",
68
+ "amount": 1000.0,
69
+ "category": "premium_payment",
70
+ "description": f"Premium payment by {user.get('email')}",
71
+ "reference_id": transaction_id,
72
+ "created_at": now_utc(),
73
+ },
74
  )
75
 
76
+ log_action("Premium upgrade", user_id=user["id"], details=f"{request_data.plan_days} days")
 
 
 
 
 
77
 
78
  return {
79
+ "is_premium": user.get("is_premium", False),
80
+ "premium_expiry": user.get("premium_expiry"),
81
  "message": f"Successfully upgraded to premium for {request_data.plan_days} days!"
82
  }
83
 
84
 
85
  @router.get("/status", response_model=PremiumResponse)
86
  async def get_premium_status(
87
+ current_user=Depends(get_current_user),
 
88
  ):
89
  """Get current premium status"""
90
 
91
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
92
+ if not user:
93
+ raise HTTPException(status_code=404, detail="User not found")
94
+
95
+ expiry = user.get("premium_expiry")
96
+ if user.get("is_premium") and expiry:
97
+ from datetime import timezone
98
+ # Parse expiry to timezone-aware datetime
99
+ expiry_dt = _parse_datetime(expiry) if isinstance(expiry, str) else expiry
100
+
101
+ # Ensure expiry_dt is timezone-aware
102
+ if isinstance(expiry_dt, datetime) and expiry_dt.tzinfo is None:
103
+ expiry_dt = expiry_dt.replace(tzinfo=timezone.utc)
104
+
105
+ # Check if premium has expired
106
+ if expiry_dt and now_utc() >= expiry_dt:
107
+ user = update_doc(
108
+ COLL.users,
109
+ user["id"],
110
+ {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()},
111
+ ) or user
112
 
113
+ if user.get("is_premium"):
114
+ expiry = user.get("premium_expiry")
115
+ from datetime import timezone
116
+ # Ensure timezone-aware datetime for formatting
117
+ if isinstance(expiry, str):
118
+ expiry = _parse_datetime(expiry) or now_utc()
119
+ elif isinstance(expiry, datetime) and expiry.tzinfo is None:
120
+ expiry = expiry.replace(tzinfo=timezone.utc)
121
+ message = f"Premium active until {expiry.strftime('%Y-%m-%d')}" if expiry else "Premium active"
122
  else:
123
  message = "Not a premium member. Upgrade to get featured!"
124
 
125
  return {
126
+ "is_premium": user.get("is_premium", False),
127
+ "premium_expiry": user.get("premium_expiry"),
128
  "message": message
129
  }
130
 
131
 
132
  @router.post("/cancel")
133
  async def cancel_premium(
134
+ current_user=Depends(get_current_user),
 
135
  ):
136
  """Cancel premium membership"""
137
 
138
+ user = first_doc(COLL.users, predicate=lambda row: row.get("id") == current_user.id)
139
+ if not user:
140
+ raise HTTPException(status_code=404, detail="User not found")
141
+
142
+ if not user.get("is_premium"):
143
  raise HTTPException(
144
  status_code=status.HTTP_400_BAD_REQUEST,
145
  detail="User is not a premium member"
146
  )
147
 
148
+ update_doc(
149
+ COLL.users,
150
+ user["id"],
151
+ {"is_premium": False, "premium_expiry": None, "updated_at": now_utc()},
152
+ )
153
 
154
+ log_action("Premium cancelled", user_id=user["id"])
155
 
156
  return {"message": "Premium membership cancelled"}
157
 
158
 
159
  @router.get("/payments", response_model=list)
160
  async def get_payment_history(
161
+ current_user=Depends(get_current_user),
 
162
  ):
163
  """Get payment history"""
164
 
165
+ payments = list_docs(
166
+ COLL.payments,
167
+ predicate=lambda row: row.get("user_id") == current_user.id,
168
+ sort_key="created_at",
169
+ reverse=True,
170
+ )
171
+ return [as_obj(row) for row in payments]
backend/app/schemas/chat.py CHANGED
@@ -1,5 +1,6 @@
1
  from pydantic import BaseModel
2
  from datetime import datetime
 
3
 
4
 
5
  class AdminChatCreate(BaseModel):
@@ -8,7 +9,7 @@ class AdminChatCreate(BaseModel):
8
 
9
  class AdminChatResponse(BaseModel):
10
  id: int
11
- user_id: int
12
  sender_role: str
13
  message: str
14
  is_read: bool
 
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
+ from typing import Union
4
 
5
 
6
  class AdminChatCreate(BaseModel):
 
9
 
10
  class AdminChatResponse(BaseModel):
11
  id: int
12
+ user_id: Union[int, str]
13
  sender_role: str
14
  message: str
15
  is_read: bool
backend/app/schemas/finance.py CHANGED
@@ -1,6 +1,6 @@
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
- from typing import Optional
4
 
5
 
6
  class GuestFundRequest(BaseModel):
@@ -11,13 +11,13 @@ class GuestFundRequest(BaseModel):
11
 
12
  class ManualCreditRequest(BaseModel):
13
  amount: float
14
- user_id: Optional[int] = None
15
  notes: Optional[str] = None
16
 
17
 
18
  class FinanceTransactionResponse(BaseModel):
19
  id: int
20
- user_id: Optional[int]
21
  transaction_type: str
22
  amount: float
23
  category: str
 
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
+ from typing import Optional, Union
4
 
5
 
6
  class GuestFundRequest(BaseModel):
 
11
 
12
  class ManualCreditRequest(BaseModel):
13
  amount: float
14
+ user_id: Optional[Union[int, str]] = None
15
  notes: Optional[str] = None
16
 
17
 
18
  class FinanceTransactionResponse(BaseModel):
19
  id: int
20
+ user_id: Optional[Union[int, str]]
21
  transaction_type: str
22
  amount: float
23
  category: str
backend/app/schemas/match.py CHANGED
@@ -1,5 +1,5 @@
1
  from datetime import datetime
2
- from typing import List, Optional
3
 
4
  from pydantic import BaseModel
5
 
@@ -14,7 +14,7 @@ class MatchCreate(BaseModel):
14
  class MatchResponse(BaseModel):
15
  id: int
16
  title: str
17
- created_by_id: int
18
  team_a_name: str
19
  team_b_name: str
20
  overs_per_innings: int
@@ -28,12 +28,12 @@ class MatchResponse(BaseModel):
28
 
29
 
30
  class MatchTeamSetupRequest(BaseModel):
31
- team_a_player_ids: List[int]
32
- team_b_player_ids: List[int]
33
 
34
 
35
  class MatchPlayerView(BaseModel):
36
- user_id: int
37
  name: str
38
  team: str
39
 
@@ -53,8 +53,8 @@ class BallEventCreate(BaseModel):
53
  over_number: int
54
  ball_number: int
55
  batting_team: str # A or B
56
- striker_id: Optional[int] = None
57
- bowler_id: Optional[int] = None
58
  runs_off_bat: int = 0
59
  extras: int = 0
60
  extra_type: Optional[str] = None
@@ -99,3 +99,4 @@ class MatchScoreboardResponse(BaseModel):
99
  team_b_runs: int
100
  winner_team: Optional[str] = None
101
  result_text: Optional[str] = None
 
 
1
  from datetime import datetime
2
+ from typing import List, Optional, Union
3
 
4
  from pydantic import BaseModel
5
 
 
14
  class MatchResponse(BaseModel):
15
  id: int
16
  title: str
17
+ created_by_id: Union[int, str]
18
  team_a_name: str
19
  team_b_name: str
20
  overs_per_innings: int
 
28
 
29
 
30
  class MatchTeamSetupRequest(BaseModel):
31
+ team_a_player_ids: List[Union[int, str]]
32
+ team_b_player_ids: List[Union[int, str]]
33
 
34
 
35
  class MatchPlayerView(BaseModel):
36
+ user_id: Union[int, str]
37
  name: str
38
  team: str
39
 
 
53
  over_number: int
54
  ball_number: int
55
  batting_team: str # A or B
56
+ striker_id: Optional[Union[int, str]] = None
57
+ bowler_id: Optional[Union[int, str]] = None
58
  runs_off_bat: int = 0
59
  extras: int = 0
60
  extra_type: Optional[str] = None
 
99
  team_b_runs: int
100
  winner_team: Optional[str] = None
101
  result_text: Optional[str] = None
102
+ all_balls: List[BallEventResponse] = []
backend/app/schemas/notification.py CHANGED
@@ -1,10 +1,11 @@
1
  from pydantic import BaseModel
2
  from datetime import datetime
 
3
 
4
 
5
  class NotificationResponse(BaseModel):
6
  id: int
7
- user_id: int
8
  title: str
9
  message: str
10
  notification_type: str
 
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
+ from typing import Union
4
 
5
 
6
  class NotificationResponse(BaseModel):
7
  id: int
8
+ user_id: Union[int, str]
9
  title: str
10
  message: str
11
  notification_type: str
backend/app/schemas/payment.py CHANGED
@@ -1,6 +1,6 @@
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
- from typing import Optional
4
 
5
 
6
  class PaymentRequest(BaseModel):
@@ -10,7 +10,7 @@ class PaymentRequest(BaseModel):
10
 
11
  class PaymentResponse(BaseModel):
12
  id: int
13
- user_id: int
14
  amount: float
15
  status: str
16
  transaction_id: str
 
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
+ from typing import Optional, Union
4
 
5
 
6
  class PaymentRequest(BaseModel):
 
10
 
11
  class PaymentResponse(BaseModel):
12
  id: int
13
+ user_id: Union[int, str]
14
  amount: float
15
  status: str
16
  transaction_id: str
backend/app/schemas/performance.py CHANGED
@@ -1,6 +1,6 @@
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
- from typing import Optional
4
 
5
 
6
  class PerformanceLogCreate(BaseModel):
@@ -25,7 +25,7 @@ class PerformanceLogUpdate(BaseModel):
25
 
26
  class PerformanceLogResponse(BaseModel):
27
  id: int
28
- user_id: int
29
  match_date: datetime
30
  runs_scored: int
31
  wickets_taken: int
 
1
  from pydantic import BaseModel
2
  from datetime import datetime
3
+ from typing import Optional, Union
4
 
5
 
6
  class PerformanceLogCreate(BaseModel):
 
25
 
26
  class PerformanceLogResponse(BaseModel):
27
  id: int
28
+ user_id: Union[int, str]
29
  match_date: datetime
30
  runs_scored: int
31
  wickets_taken: int
backend/app/schemas/user.py CHANGED
@@ -1,6 +1,6 @@
1
- from pydantic import BaseModel, EmailStr
2
  from datetime import datetime
3
- from typing import Optional
4
 
5
 
6
  class UserRegister(BaseModel):
@@ -15,7 +15,7 @@ class UserLogin(BaseModel):
15
 
16
 
17
  class UserResponse(BaseModel):
18
- id: int
19
  name: str
20
  email: str
21
  role: str
@@ -30,7 +30,7 @@ class UserResponse(BaseModel):
30
  highest_score: int
31
  is_premium: bool
32
  premium_expiry: Optional[datetime] = None
33
- created_at: datetime
34
  is_active: bool
35
 
36
  class Config:
 
1
+ from pydantic import BaseModel, EmailStr, Field
2
  from datetime import datetime
3
+ from typing import Optional, Union
4
 
5
 
6
  class UserRegister(BaseModel):
 
15
 
16
 
17
  class UserResponse(BaseModel):
18
+ id: Union[int, str] = Field(..., description="User ID (can be integer or Firebase UID string)")
19
  name: str
20
  email: str
21
  role: str
 
30
  highest_score: int
31
  is_premium: bool
32
  premium_expiry: Optional[datetime] = None
33
+ created_at: Optional[datetime] = None
34
  is_active: bool
35
 
36
  class Config:
backend/app/utils/__init__.py CHANGED
@@ -6,9 +6,8 @@ from app.utils.auth import (
6
  )
7
  from app.utils.premium import (
8
  check_and_downgrade_premium,
9
- upgrade_to_premium,
10
  calculate_average_runs,
11
- get_player_rank,
12
  )
13
  from app.utils.logger import log_action, log_error
14
 
@@ -18,9 +17,8 @@ __all__ = [
18
  "create_access_token",
19
  "decode_token",
20
  "check_and_downgrade_premium",
21
- "upgrade_to_premium",
22
  "calculate_average_runs",
23
- "get_player_rank",
24
  "log_action",
25
  "log_error",
26
  ]
 
6
  )
7
  from app.utils.premium import (
8
  check_and_downgrade_premium,
 
9
  calculate_average_runs,
10
+ premium_patch,
11
  )
12
  from app.utils.logger import log_action, log_error
13
 
 
17
  "create_access_token",
18
  "decode_token",
19
  "check_and_downgrade_premium",
 
20
  "calculate_average_runs",
21
+ "premium_patch",
22
  "log_action",
23
  "log_error",
24
  ]
backend/app/utils/auth.py CHANGED
@@ -1,9 +1,18 @@
1
  from passlib.context import CryptContext
2
- from datetime import datetime, timedelta
3
  from typing import Optional
4
  from jose import JWTError, jwt
5
  from app.config import settings
6
  from fastapi import HTTPException, status
 
 
 
 
 
 
 
 
 
7
 
8
  pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
9
 
@@ -23,28 +32,84 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
23
  to_encode = data.copy()
24
 
25
  if expires_delta:
26
- expire = datetime.utcnow() + expires_delta
27
  else:
28
- expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
29
 
30
  to_encode.update({"exp": expire})
31
  encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
32
  return encoded_jwt
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def decode_token(token: str):
36
- """Decode and validate JWT token"""
 
37
  try:
38
  payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
39
  email: str = payload.get("sub")
40
- if email is None:
41
- raise HTTPException(
42
- status_code=status.HTTP_401_UNAUTHORIZED,
43
- detail="Could not validate credentials",
44
- )
45
- return {"email": email}
46
  except JWTError:
47
- raise HTTPException(
48
- status_code=status.HTTP_401_UNAUTHORIZED,
49
- detail="Could not validate credentials",
50
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from passlib.context import CryptContext
2
+ from datetime import datetime, timedelta, timezone
3
  from typing import Optional
4
  from jose import JWTError, jwt
5
  from app.config import settings
6
  from fastapi import HTTPException, status
7
+ import logging
8
+ import json
9
+ import os
10
+
11
+ import firebase_admin
12
+ from firebase_admin import auth as firebase_auth, credentials
13
+
14
+ logger = logging.getLogger(__name__)
15
+ _firebase_initialized = False
16
 
17
  pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
18
 
 
32
  to_encode = data.copy()
33
 
34
  if expires_delta:
35
+ expire = datetime.now(timezone.utc) + expires_delta
36
  else:
37
+ expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
38
 
39
  to_encode.update({"exp": expire})
40
  encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
41
  return encoded_jwt
42
 
43
 
44
+ def _init_firebase_if_needed() -> None:
45
+ global _firebase_initialized
46
+
47
+ if _firebase_initialized:
48
+ return
49
+
50
+ if firebase_admin._apps:
51
+ _firebase_initialized = True
52
+ return
53
+
54
+ if settings.FIREBASE_SERVICE_ACCOUNT_JSON:
55
+ try:
56
+ account_info = json.loads(settings.FIREBASE_SERVICE_ACCOUNT_JSON)
57
+ cred = credentials.Certificate(account_info)
58
+ firebase_admin.initialize_app(cred)
59
+ _firebase_initialized = True
60
+ return
61
+ except Exception as e:
62
+ logger.warning("Firebase init from JSON failed: %s", str(e))
63
+
64
+ if settings.FIREBASE_SERVICE_ACCOUNT_PATH:
65
+ path = settings.FIREBASE_SERVICE_ACCOUNT_PATH
66
+ if os.path.exists(path):
67
+ try:
68
+ cred = credentials.Certificate(path)
69
+ firebase_admin.initialize_app(cred)
70
+ _firebase_initialized = True
71
+ return
72
+ except Exception as e:
73
+ logger.warning("Firebase init from service account path failed: %s", str(e))
74
+
75
+ logger.warning("Firebase Auth is enabled but service account credentials are not configured correctly")
76
+
77
+
78
  def decode_token(token: str):
79
+ """Decode and validate JWT token (legacy local JWT + Firebase ID token)."""
80
+ # 1) Legacy local JWT support
81
  try:
82
  payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
83
  email: str = payload.get("sub")
84
+ if email:
85
+ return {
86
+ "email": email,
87
+ "sub": payload.get("sub"),
88
+ "name": payload.get("name"),
89
+ }
90
  except JWTError:
91
+ pass
92
+
93
+ # 2) Firebase ID token support
94
+ if settings.FIREBASE_AUTH_ENABLED:
95
+ _init_firebase_if_needed()
96
+ if _firebase_initialized:
97
+ try:
98
+ decoded = firebase_auth.verify_id_token(token)
99
+ email = decoded.get("email")
100
+ name = decoded.get("name")
101
+ sub = decoded.get("uid") or decoded.get("sub")
102
+
103
+ if email:
104
+ return {
105
+ "email": email,
106
+ "sub": sub,
107
+ "name": name,
108
+ }
109
+ except Exception as e:
110
+ logger.warning("Firebase token validation failed: %s", str(e))
111
+
112
+ raise HTTPException(
113
+ status_code=status.HTTP_401_UNAUTHORIZED,
114
+ detail="Could not validate credentials",
115
+ )
backend/app/utils/cache.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple in-memory caching with TTL for dashboard endpoints."""
2
+ from datetime import datetime, timezone, timedelta
3
+ from typing import Any, Callable, Optional
4
+ import json
5
+
6
+
7
+ class CacheEntry:
8
+ def __init__(self, value: Any, ttl_seconds: int):
9
+ self.value = value
10
+ self.created_at = datetime.now(timezone.utc)
11
+ self.ttl_seconds = ttl_seconds
12
+
13
+ def is_expired(self) -> bool:
14
+ elapsed = (datetime.now(timezone.utc) - self.created_at).total_seconds()
15
+ return elapsed >= self.ttl_seconds
16
+
17
+
18
+ class SimpleCache:
19
+ """Thread-safe cache with TTL expiration."""
20
+
21
+ def __init__(self):
22
+ self._cache: dict[str, CacheEntry] = {}
23
+
24
+ def get(self, key: str) -> Optional[Any]:
25
+ """Get value from cache if it exists and hasn't expired."""
26
+ if key in self._cache:
27
+ entry = self._cache[key]
28
+ if not entry.is_expired():
29
+ return entry.value
30
+ else:
31
+ # Clean up expired entry
32
+ del self._cache[key]
33
+ return None
34
+
35
+ def set(self, key: str, value: Any, ttl_seconds: int = 300):
36
+ """Store value in cache with TTL (default 5 minutes)."""
37
+ self._cache[key] = CacheEntry(value, ttl_seconds)
38
+
39
+ def clear(self, key: str = None):
40
+ """Clear specific key or entire cache."""
41
+ if key:
42
+ self._cache.pop(key, None)
43
+ else:
44
+ self._cache.clear()
45
+
46
+ def get_or_fetch(
47
+ self, key: str, fetch_fn: Callable[[], Any], ttl_seconds: int = 300
48
+ ) -> Any:
49
+ """Get from cache or fetch and cache the result."""
50
+ cached = self.get(key)
51
+ if cached is not None:
52
+ return cached
53
+
54
+ value = fetch_fn()
55
+ self.set(key, value, ttl_seconds)
56
+ return value
57
+
58
+
59
+ # Global cache instance
60
+ _cache = SimpleCache()
61
+
62
+
63
+ def get_cache() -> SimpleCache:
64
+ """Get the global cache instance."""
65
+ return _cache
backend/app/utils/firestore.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Any
3
+
4
+ import firebase_admin
5
+ from firebase_admin import firestore
6
+
7
+ from app.config import settings
8
+ from app.utils.auth import _init_firebase_if_needed
9
+
10
+
11
+ def _get_firestore_client():
12
+ """Return Firestore client when Firebase is configured, else None."""
13
+ if not settings.FIREBASE_AUTH_ENABLED:
14
+ return None
15
+
16
+ _init_firebase_if_needed()
17
+ if not firebase_admin._apps:
18
+ return None
19
+
20
+ return firestore.client()
21
+
22
+
23
+ def _serialize_datetime(value: datetime | None) -> str | None:
24
+ if value is None:
25
+ return None
26
+ return value.isoformat()
27
+
28
+
29
+ def sync_user_profile_to_firestore(user: Any) -> None:
30
+ """Upsert a SQL user profile into Firestore to support phased DB migration."""
31
+ client = _get_firestore_client()
32
+ if client is None:
33
+ return
34
+
35
+ doc_id = str(getattr(user, "id", ""))
36
+ if not doc_id:
37
+ return
38
+
39
+ payload = {
40
+ "id": doc_id,
41
+ "name": getattr(user, "name", None),
42
+ "email": getattr(user, "email", None),
43
+ "role": getattr(user, "role", "player"),
44
+ "jersey_number": getattr(user, "jersey_number", None),
45
+ "bio": getattr(user, "bio", None),
46
+ "runs": getattr(user, "runs", 0),
47
+ "matches": getattr(user, "matches", 0),
48
+ "wickets": getattr(user, "wickets", 0),
49
+ "centuries": getattr(user, "centuries", 0),
50
+ "half_centuries": getattr(user, "half_centuries", 0),
51
+ "average_runs": getattr(user, "average_runs", 0.0),
52
+ "highest_score": getattr(user, "highest_score", 0),
53
+ "is_premium": getattr(user, "is_premium", False),
54
+ "premium_expiry": _serialize_datetime(getattr(user, "premium_expiry", None)),
55
+ "premium_start_date": _serialize_datetime(getattr(user, "premium_start_date", None)),
56
+ "is_active": getattr(user, "is_active", True),
57
+ "created_at": _serialize_datetime(getattr(user, "created_at", None)),
58
+ "updated_at": _serialize_datetime(getattr(user, "updated_at", None)),
59
+ "last_login": _serialize_datetime(getattr(user, "last_login", None)),
60
+ "source": "sql-mirror",
61
+ }
62
+
63
+ client.collection("users").document(doc_id).set(payload, merge=True)
backend/app/utils/firestore_data.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import datetime, timezone
5
+ from types import SimpleNamespace
6
+ from typing import Any, Callable
7
+
8
+ import firebase_admin
9
+ from firebase_admin import firestore
10
+
11
+ from app.config import settings
12
+ from app.utils.auth import _init_firebase_if_needed
13
+
14
+
15
+ @dataclass
16
+ class CollectionNames:
17
+ users: str = "users"
18
+ payments: str = "payments"
19
+ performance_logs: str = "performance_logs"
20
+ notifications: str = "notifications"
21
+ finance_transactions: str = "finance_transactions"
22
+ admin_chat_messages: str = "admin_chat_messages"
23
+ matches: str = "matches"
24
+ match_players: str = "match_players"
25
+ ball_events: str = "ball_events"
26
+
27
+
28
+ COLL = CollectionNames()
29
+
30
+
31
+ def _client():
32
+ if not settings.FIREBASE_AUTH_ENABLED:
33
+ raise RuntimeError("FIREBASE_AUTH_ENABLED must be True for Firestore mode")
34
+
35
+ _init_firebase_if_needed()
36
+ if not firebase_admin._apps:
37
+ raise RuntimeError("Firebase Admin is not initialized. Check service account config.")
38
+
39
+ return firestore.client()
40
+
41
+
42
+ def _counter_doc(collection: str) -> str:
43
+ return f"counter::{collection}"
44
+
45
+
46
+ def next_int_id(collection: str) -> int:
47
+ client = _client()
48
+ ref = client.collection("_meta").document(_counter_doc(collection))
49
+ snap = ref.get()
50
+ current = 0
51
+ if snap.exists:
52
+ current = int((snap.to_dict() or {}).get("value", 0))
53
+ new_value = current + 1
54
+ ref.set({"value": new_value}, merge=True)
55
+ return new_value
56
+
57
+
58
+ def now_utc() -> datetime:
59
+ return datetime.now(timezone.utc)
60
+
61
+
62
+ def create_doc(collection: str, data: dict[str, Any], doc_id: str | None = None) -> dict[str, Any]:
63
+ client = _client()
64
+ payload = dict(data)
65
+ if doc_id is None:
66
+ doc_id = str(payload.get("id") or next_int_id(collection))
67
+ payload.setdefault("id", int(doc_id) if doc_id.isdigit() else doc_id)
68
+ client.collection(collection).document(doc_id).set(payload, merge=True)
69
+ return payload
70
+
71
+
72
+ def get_doc(collection: str, doc_id: str | int) -> dict[str, Any] | None:
73
+ client = _client()
74
+ snap = client.collection(collection).document(str(doc_id)).get()
75
+ if not snap.exists:
76
+ return None
77
+ data = snap.to_dict() or {}
78
+ if "id" not in data:
79
+ data["id"] = int(str(doc_id)) if str(doc_id).isdigit() else str(doc_id)
80
+ return data
81
+
82
+
83
+ def update_doc(collection: str, doc_id: str | int, patch: dict[str, Any]) -> dict[str, Any] | None:
84
+ existing = get_doc(collection, doc_id)
85
+ if not existing:
86
+ return None
87
+ merged = dict(existing)
88
+ merged.update(patch)
89
+ create_doc(collection, merged, str(doc_id))
90
+ return merged
91
+
92
+
93
+ def delete_doc(collection: str, doc_id: str | int) -> bool:
94
+ client = _client()
95
+ snap = client.collection(collection).document(str(doc_id)).get()
96
+ if not snap.exists:
97
+ return False
98
+ client.collection(collection).document(str(doc_id)).delete()
99
+ return True
100
+
101
+ def _parse_datetime(value: Any) -> datetime | None:
102
+ """Parse a value to datetime if it's a datetime string. Always returns timezone-aware UTC."""
103
+ if isinstance(value, datetime):
104
+ # If naive, make it aware as UTC
105
+ if value.tzinfo is None:
106
+ return value.replace(tzinfo=timezone.utc)
107
+ return value
108
+ if isinstance(value, str):
109
+ try:
110
+ # Only try parsing if it looks like ISO format (contains T or -)
111
+ if 'T' in value or (value.count('-') >= 2):
112
+ if value.endswith('Z'):
113
+ value = value.replace('Z', '+00:00')
114
+ dt = datetime.fromisoformat(value)
115
+ # If naive, make it aware as UTC
116
+ if dt.tzinfo is None:
117
+ dt = dt.replace(tzinfo=timezone.utc)
118
+ return dt
119
+ except (ValueError, AttributeError):
120
+ pass
121
+ return None
122
+
123
+
124
+ def _normalize_sort_value(value: Any) -> Any:
125
+ """Normalize a value for sorting - handle datetime and string representations."""
126
+ if value is None:
127
+ return (0, "")
128
+
129
+ # Try to parse as datetime
130
+ if isinstance(value, datetime):
131
+ return (1, value)
132
+ if isinstance(value, str):
133
+ parsed_dt = _parse_datetime(value)
134
+ if parsed_dt:
135
+ return (1, parsed_dt)
136
+ return (2, value)
137
+
138
+ # Numbers (int, float)
139
+ if isinstance(value, (int, float)):
140
+ return (3, value)
141
+
142
+ return (4, str(value))
143
+
144
+
145
+ def list_docs(
146
+ collection: str,
147
+ predicate: Callable[[dict[str, Any]], bool] | None = None,
148
+ sort_key: str | None = None,
149
+ reverse: bool = False,
150
+ limit: int | None = None,
151
+ offset: int = 0,
152
+ ) -> list[dict[str, Any]]:
153
+ client = _client()
154
+ rows: list[dict[str, Any]] = []
155
+ for snap in client.collection(collection).stream():
156
+ row = snap.to_dict() or {}
157
+ doc_id = snap.id
158
+
159
+ # Always track the actual Firestore document ID
160
+ row["_doc_id"] = doc_id
161
+
162
+ # If no id field, use the Firestore document ID
163
+ if "id" not in row:
164
+ row["id"] = int(doc_id) if doc_id.isdigit() else doc_id
165
+ if predicate and not predicate(row):
166
+ continue
167
+ rows.append(row)
168
+
169
+ if sort_key:
170
+ rows.sort(key=lambda item: _normalize_sort_value(item.get(sort_key)), reverse=reverse)
171
+
172
+ if offset:
173
+ rows = rows[offset:]
174
+ if limit is not None:
175
+ rows = rows[:limit]
176
+ return rows
177
+
178
+
179
+ def first_doc(
180
+ collection: str,
181
+ predicate: Callable[[dict[str, Any]], bool] | None = None,
182
+ sort_key: str | None = None,
183
+ reverse: bool = False,
184
+ ) -> dict[str, Any] | None:
185
+ rows = list_docs(collection, predicate=predicate, sort_key=sort_key, reverse=reverse, limit=1)
186
+ return rows[0] if rows else None
187
+
188
+
189
+ def as_obj(data: dict[str, Any]) -> Any:
190
+ return SimpleNamespace(**data)
191
+
192
+
193
+ def normalize_user(user: dict[str, Any]) -> dict[str, Any]:
194
+ """Ensure all required user fields exist with defaults."""
195
+ created_at = user.get("created_at") or user.get("createdAt") or now_utc()
196
+
197
+ # Prefer uid (Firebase UID) over id for consistency across Firestore
198
+ user_id = user.get("uid") or user.get("id", "")
199
+
200
+ defaults = {
201
+ "id": user_id,
202
+ "uid": user.get("uid") or user.get("id", ""),
203
+ "name": user.get("name", ""),
204
+ "email": user.get("email", ""),
205
+ "role": user.get("role", "player"),
206
+ "jersey_number": user.get("jersey_number"),
207
+ "bio": user.get("bio"),
208
+ "runs": int(user.get("runs", 0)) if user.get("runs") else 0,
209
+ "matches": int(user.get("matches", 0)) if user.get("matches") else 0,
210
+ "wickets": int(user.get("wickets", 0)) if user.get("wickets") else 0,
211
+ "centuries": int(user.get("centuries", 0)) if user.get("centuries") else 0,
212
+ "half_centuries": int(user.get("half_centuries", 0)) if user.get("half_centuries") else 0,
213
+ "average_runs": float(user.get("average_runs", 0.0)) if user.get("average_runs") else 0.0,
214
+ "highest_score": int(user.get("highest_score", 0)) if user.get("highest_score") else 0,
215
+ "is_premium": bool(user.get("is_premium", False)),
216
+ "premium_expiry": user.get("premium_expiry"),
217
+ "is_active": bool(user.get("is_active", True)),
218
+ "created_at": created_at,
219
+ }
220
+ return defaults
backend/app/utils/premium.py CHANGED
@@ -1,60 +1,31 @@
1
- from datetime import datetime, timedelta
2
- from sqlalchemy.orm import Session
3
- from app.models import User, Notification
4
- from app.config import settings
5
- import pytz
6
-
7
-
8
- def check_and_downgrade_premium(db: Session, user: User):
9
- """Check if premium membership has expired and downgrade if needed"""
10
- if user.is_premium and user.premium_expiry:
11
- if datetime.utcnow() >= user.premium_expiry:
12
- user.is_premium = False
13
- user.premium_expiry = None
14
- db.commit()
15
-
16
- # Create notification
17
- notification = Notification(
18
- user_id=user.id,
19
- title="Premium Membership Expired",
20
- message="Your premium membership has expired. Upgrade again to get featured!",
21
- notification_type="premium_expiry"
22
- )
23
- db.add(notification)
24
- db.commit()
25
- return True
26
- return False
27
-
28
-
29
- def upgrade_to_premium(db: Session, user: User, days: int = 30):
30
- """Upgrade user to premium membership"""
31
- user.is_premium = True
32
- user.premium_start_date = datetime.utcnow()
33
- user.premium_expiry = datetime.utcnow() + timedelta(days=days)
34
- db.commit()
35
-
36
- # Create notification
37
- notification = Notification(
38
- user_id=user.id,
39
- title="🎉 Welcome to Premium!",
40
- message=f"You are now a premium member for {days} days! Enjoy exclusive features.",
41
- notification_type="achievement"
42
- )
43
- db.add(notification)
44
- db.commit()
45
-
46
-
47
- def calculate_average_runs(db: Session, user: User) -> float:
48
- """Calculate average runs for a player"""
49
- if user.matches == 0:
50
  return 0.0
51
- return round(user.runs / user.matches, 2)
52
-
53
-
54
- def get_player_rank(db: Session, user_id: int) -> int:
55
- """Get player's rank based on runs"""
56
- users = db.query(User).order_by(User.runs.desc()).all()
57
- for idx, user in enumerate(users, 1):
58
- if user.id == user_id:
59
- return idx
60
- return 0
 
1
+ from datetime import datetime, timedelta, timezone
2
+ from app.utils.firestore_data import now_utc
3
+
4
+
5
+ def check_and_downgrade_premium(user: dict) -> bool:
6
+ """Return True when the given premium user should be downgraded."""
7
+ if not (user.get("is_premium") and user.get("premium_expiry")):
8
+ return False
9
+ expiry = user["premium_expiry"]
10
+ if isinstance(expiry, str):
11
+ from app.utils.firestore_data import _parse_datetime
12
+ expiry = _parse_datetime(expiry)
13
+ if not isinstance(expiry, datetime):
14
+ return False
15
+ return now_utc() >= expiry
16
+
17
+
18
+ def premium_patch(days: int = 30) -> dict:
19
+ """Generate patch payload to set premium membership fields."""
20
+ return {
21
+ "is_premium": True,
22
+ "premium_start_date": now_utc(),
23
+ "premium_expiry": now_utc() + timedelta(days=days),
24
+ }
25
+
26
+
27
+ def calculate_average_runs(user: dict) -> float:
28
+ matches = int(user.get("matches", 0) or 0)
29
+ if matches == 0:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  return 0.0
31
+ return round(float(user.get("runs", 0)) / matches, 2)
 
 
 
 
 
 
 
 
 
backend/creation_log.txt ADDED
Binary file (3.17 kB). View file
 
backend/fix_user_ids.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Fix Firestore users with inconsistent IDs.
4
+ Ensures all users have both 'id' and 'uid' fields set to their Firebase UID.
5
+ """
6
+
7
+ import firebase_admin
8
+ from firebase_admin import credentials, firestore
9
+ import os
10
+
11
+ # Initialize Firebase
12
+ cred_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS', 'firebase-service-account.json')
13
+ if not firebase_admin._apps:
14
+ if os.path.exists(cred_path):
15
+ cred = credentials.Certificate(cred_path)
16
+ firebase_admin.initialize_app(cred)
17
+ else:
18
+ raise FileNotFoundError(f"Service account file not found: {cred_path}")
19
+
20
+ db = firestore.client()
21
+
22
+ def fix_user_ids():
23
+ """Fix all users to have consistent Firebase UID-based IDs"""
24
+ users_ref = db.collection('users')
25
+ docs = users_ref.stream()
26
+
27
+ fixed_count = 0
28
+ total_count = 0
29
+
30
+ print("[USER ID FIX] Starting user ID normalization...\n")
31
+
32
+ for doc in docs:
33
+ total_count += 1
34
+ user_id = doc.id # Document ID (Firebase UID)
35
+ user_data = doc.to_dict()
36
+
37
+ current_id = user_data.get('id')
38
+ current_uid = user_data.get('uid')
39
+
40
+ # Check if ID fields need fixing
41
+ needs_fix = False
42
+
43
+ # If id field is missing or is an integer (not Firebase UID style), fix it
44
+ if not current_id or (isinstance(current_id, int) or (isinstance(current_id, str) and len(current_id) < 20)):
45
+ needs_fix = True
46
+
47
+ # If uid field is missing, fix it
48
+ if not current_uid:
49
+ needs_fix = True
50
+
51
+ # If either id or uid doesn't match the document ID (Firebase UID), fix it
52
+ if current_id != user_id or current_uid != user_id:
53
+ needs_fix = True
54
+
55
+ if needs_fix:
56
+ user_name = user_data.get('name', 'Unknown')
57
+ email = user_data.get('email', 'No email')
58
+
59
+ print(f"[FIX] {user_name} ({email})")
60
+ print(f" Document ID: {user_id}")
61
+ print(f" Old 'id' field: {current_id}")
62
+ print(f" Old 'uid' field: {current_uid}")
63
+
64
+ # Update both id and uid to match the document ID (Firebase UID)
65
+ try:
66
+ users_ref.document(user_id).update({
67
+ 'id': user_id,
68
+ 'uid': user_id,
69
+ })
70
+ print(f" Status: [FIXED]")
71
+ fixed_count += 1
72
+ except Exception as e:
73
+ print(f" Status: [ERROR] {str(e)}")
74
+ print()
75
+
76
+ print("="*70)
77
+ print(f"[RESULT] Fixed {fixed_count} out of {total_count} users")
78
+ print("="*70)
79
+ print("\nAll users should now use Firebase UID as both 'id' and 'uid'")
80
+
81
+ if __name__ == "__main__":
82
+ try:
83
+ fix_user_ids()
84
+ except Exception as e:
85
+ print(f"[ERROR] {str(e)}")
backend/main.py CHANGED
@@ -2,7 +2,6 @@ from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.openapi.utils import get_openapi
4
  from app.config import settings
5
- from app.database import init_db
6
  from app.middleware import LoggingMiddleware, RateLimitMiddleware
7
  from app.middleware.auth import security
8
  from app.routes import (
@@ -17,9 +16,6 @@ from app.routes import (
17
  matches_router,
18
  )
19
 
20
- # Initialize database
21
- init_db()
22
-
23
  # Create FastAPI app
24
  app = FastAPI(
25
  title=settings.API_TITLE,
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.openapi.utils import get_openapi
4
  from app.config import settings
 
5
  from app.middleware import LoggingMiddleware, RateLimitMiddleware
6
  from app.middleware.auth import security
7
  from app.routes import (
 
16
  matches_router,
17
  )
18
 
 
 
 
19
  # Create FastAPI app
20
  app = FastAPI(
21
  title=settings.API_TITLE,
backend/requirements.txt CHANGED
@@ -1,7 +1,6 @@
1
  fastapi==0.104.1
2
  uvicorn==0.24.0
3
  gunicorn==21.2.0
4
- sqlalchemy==2.0.23
5
  pydantic==2.5.0
6
  pydantic-settings==2.1.0
7
  python-dotenv==1.0.0
@@ -11,5 +10,5 @@ python-jose[cryptography]==3.3.0
11
  email-validator==2.1.0
12
  python-multipart==0.0.6
13
  slowapi==0.1.9
14
- aiosqlite==0.19.0
15
  pytz==2023.3
 
 
1
  fastapi==0.104.1
2
  uvicorn==0.24.0
3
  gunicorn==21.2.0
 
4
  pydantic==2.5.0
5
  pydantic-settings==2.1.0
6
  python-dotenv==1.0.0
 
10
  email-validator==2.1.0
11
  python-multipart==0.0.6
12
  slowapi==0.1.9
 
13
  pytz==2023.3
14
+ firebase-admin==6.8.0
backend/seed_dummy_users_firebase.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Seed Firebase with dummy player users (10 premium + 5 non-premium)
4
+ Run from backend directory: python seed_dummy_users_firebase.py
5
+ """
6
+
7
+ import firebase_admin
8
+ from firebase_admin import credentials, auth, firestore
9
+ from datetime import datetime, timedelta
10
+ import os
11
+
12
+ # Initialize Firebase
13
+ cred_path = os.getenv('GOOGLE_APPLICATION_CREDENTIALS', 'firebase-service-account.json')
14
+ if not firebase_admin._apps:
15
+ if os.path.exists(cred_path):
16
+ cred = credentials.Certificate(cred_path)
17
+ firebase_admin.initialize_app(cred)
18
+ else:
19
+ raise FileNotFoundError(f"Service account file not found: {cred_path}")
20
+
21
+ db = firestore.client()
22
+ auth_client = auth
23
+
24
+ # Dummy user data
25
+ DUMMY_USERS = [
26
+ # Premium players
27
+ {
28
+ "name": "Virat Kohli",
29
+ "email": "virat.kohli@example.com",
30
+ "password": "Password@123",
31
+ "is_premium": True,
32
+ "jersey_number": 18,
33
+ "runs": 7000,
34
+ "matches": 150,
35
+ "wickets": 0,
36
+ "centuries": 50,
37
+ "half_centuries": 35,
38
+ "highest_score": 183,
39
+ "average_runs": 46.67,
40
+ },
41
+ {
42
+ "name": "Rohit Sharma",
43
+ "email": "rohit.sharma@example.com",
44
+ "password": "Password@123",
45
+ "is_premium": True,
46
+ "jersey_number": 45,
47
+ "runs": 6500,
48
+ "matches": 145,
49
+ "wickets": 0,
50
+ "centuries": 48,
51
+ "half_centuries": 38,
52
+ "highest_score": 264,
53
+ "average_runs": 44.83,
54
+ },
55
+ {
56
+ "name": "Jasprit Bumrah",
57
+ "email": "jasprit.bumrah@example.com",
58
+ "password": "Password@123",
59
+ "is_premium": True,
60
+ "jersey_number": 93,
61
+ "runs": 500,
62
+ "matches": 120,
63
+ "wickets": 280,
64
+ "centuries": 0,
65
+ "half_centuries": 0,
66
+ "highest_score": 34,
67
+ "average_runs": 4.17,
68
+ },
69
+ {
70
+ "name": "Hardik Pandya",
71
+ "email": "hardik.pandya@example.com",
72
+ "password": "Password@123",
73
+ "is_premium": True,
74
+ "jersey_number": 31,
75
+ "runs": 3500,
76
+ "matches": 110,
77
+ "wickets": 145,
78
+ "centuries": 5,
79
+ "half_centuries": 18,
80
+ "highest_score": 123,
81
+ "average_runs": 31.82,
82
+ },
83
+ {
84
+ "name": "MS Dhoni",
85
+ "email": "ms.dhoni@example.com",
86
+ "password": "Password@123",
87
+ "is_premium": True,
88
+ "jersey_number": 7,
89
+ "runs": 5000,
90
+ "matches": 130,
91
+ "wickets": 0,
92
+ "centuries": 12,
93
+ "half_centuries": 28,
94
+ "highest_score": 156,
95
+ "average_runs": 38.46,
96
+ },
97
+ {
98
+ "name": "Shikhar Dhawan",
99
+ "email": "shikhar.dhawan@example.com",
100
+ "password": "Password@123",
101
+ "is_premium": True,
102
+ "jersey_number": 25,
103
+ "runs": 6800,
104
+ "matches": 160,
105
+ "wickets": 0,
106
+ "centuries": 52,
107
+ "half_centuries": 40,
108
+ "highest_score": 192,
109
+ "average_runs": 42.50,
110
+ },
111
+ {
112
+ "name": "KL Rahul",
113
+ "email": "kl.rahul@example.com",
114
+ "password": "Password@123",
115
+ "is_premium": True,
116
+ "jersey_number": 1,
117
+ "runs": 4200,
118
+ "matches": 95,
119
+ "wickets": 0,
120
+ "centuries": 18,
121
+ "half_centuries": 22,
122
+ "highest_score": 180,
123
+ "average_runs": 44.21,
124
+ },
125
+ {
126
+ "name": "Ravichandran Ashwin",
127
+ "email": "ravichandran.ashwin@example.com",
128
+ "password": "Password@123",
129
+ "is_premium": True,
130
+ "jersey_number": 37,
131
+ "runs": 3200,
132
+ "matches": 140,
133
+ "wickets": 420,
134
+ "centuries": 8,
135
+ "half_centuries": 15,
136
+ "highest_score": 113,
137
+ "average_runs": 22.86,
138
+ },
139
+ {
140
+ "name": "Yuzvendra Chahal",
141
+ "email": "yuzvendra.chahal@example.com",
142
+ "password": "Password@123",
143
+ "is_premium": True,
144
+ "jersey_number": 72,
145
+ "runs": 600,
146
+ "matches": 95,
147
+ "wickets": 310,
148
+ "centuries": 0,
149
+ "half_centuries": 0,
150
+ "highest_score": 38,
151
+ "average_runs": 6.32,
152
+ },
153
+ {
154
+ "name": "Bhuvneshwar Kumar",
155
+ "email": "bhuvneshwar.kumar@example.com",
156
+ "password": "Password@123",
157
+ "is_premium": True,
158
+ "jersey_number": 33,
159
+ "runs": 400,
160
+ "matches": 110,
161
+ "wickets": 290,
162
+ "centuries": 0,
163
+ "half_centuries": 0,
164
+ "highest_score": 28,
165
+ "average_runs": 3.64,
166
+ },
167
+ # Non-premium players
168
+ {
169
+ "name": "Prithvi Shaw",
170
+ "email": "prithvi.shaw@example.com",
171
+ "password": "Password@123",
172
+ "is_premium": False,
173
+ "jersey_number": 10,
174
+ "runs": 1200,
175
+ "matches": 35,
176
+ "wickets": 0,
177
+ "centuries": 3,
178
+ "half_centuries": 8,
179
+ "highest_score": 146,
180
+ "average_runs": 34.29,
181
+ },
182
+ {
183
+ "name": "Ruturaj Gaikwad",
184
+ "email": "ruturaj.gaikwad@example.com",
185
+ "password": "Password@123",
186
+ "is_premium": False,
187
+ "jersey_number": 5,
188
+ "runs": 900,
189
+ "matches": 28,
190
+ "wickets": 0,
191
+ "centuries": 2,
192
+ "half_centuries": 5,
193
+ "highest_score": 128,
194
+ "average_runs": 32.14,
195
+ },
196
+ {
197
+ "name": "Devdutt Padikkal",
198
+ "email": "devdutt.padikkal@example.com",
199
+ "password": "Password@123",
200
+ "is_premium": False,
201
+ "jersey_number": 4,
202
+ "runs": 800,
203
+ "matches": 32,
204
+ "wickets": 0,
205
+ "centuries": 1,
206
+ "half_centuries": 6,
207
+ "highest_score": 102,
208
+ "average_runs": 25.00,
209
+ },
210
+ {
211
+ "name": "Ishan Kishan",
212
+ "email": "ishan.kishan@example.com",
213
+ "password": "Password@123",
214
+ "is_premium": False,
215
+ "jersey_number": 23,
216
+ "runs": 1100,
217
+ "matches": 40,
218
+ "wickets": 0,
219
+ "centuries": 2,
220
+ "half_centuries": 7,
221
+ "highest_score": 131,
222
+ "average_runs": 27.50,
223
+ },
224
+ {
225
+ "name": "Shreyas Iyer",
226
+ "email": "shreyas.iyer@example.com",
227
+ "password": "Password@123",
228
+ "is_premium": False,
229
+ "jersey_number": 27,
230
+ "runs": 1500,
231
+ "matches": 50,
232
+ "wickets": 0,
233
+ "centuries": 4,
234
+ "half_centuries": 10,
235
+ "highest_score": 144,
236
+ "average_runs": 30.00,
237
+ },
238
+ ]
239
+
240
+
241
+ def create_firebase_users():
242
+ """Create users in Firebase Authentication and Firestore"""
243
+ created_count = 0
244
+ failed_count = 0
245
+
246
+ print(f"\n[FIREBASE] Creating {len(DUMMY_USERS)} dummy users in Firebase...\n")
247
+
248
+ for user_data in DUMMY_USERS:
249
+ try:
250
+ email = user_data["email"]
251
+ password = user_data["password"]
252
+ name = user_data["name"]
253
+ is_premium = user_data["is_premium"]
254
+
255
+ # Create user in Firebase Authentication
256
+ user_record = auth_client.create_user(
257
+ email=email,
258
+ password=password,
259
+ display_name=name,
260
+ )
261
+
262
+ uid = user_record.uid
263
+ print(f"[OK] Created Firebase Auth user: {name} ({email}) - UID: {uid[:12]}...")
264
+
265
+ # Prepare user document for Firestore
266
+ now = datetime.utcnow()
267
+ premium_expiry = None
268
+ if is_premium:
269
+ # Premium expires 30 days from now
270
+ premium_expiry = now + timedelta(days=30)
271
+
272
+ firestore_user = {
273
+ "id": uid, # Store Firebase UID as id
274
+ "uid": uid, # Also store as uid
275
+ "email": email,
276
+ "name": name,
277
+ "role": "player",
278
+ "is_active": True,
279
+ "is_premium": is_premium,
280
+ "premium_expiry": premium_expiry,
281
+ "premium_start_date": now if is_premium else None,
282
+ "jersey_number": user_data.get("jersey_number"),
283
+ "bio": f"Professional cricketer - {name}",
284
+ "runs": user_data.get("runs", 0),
285
+ "matches": user_data.get("matches", 0),
286
+ "wickets": user_data.get("wickets", 0),
287
+ "centuries": user_data.get("centuries", 0),
288
+ "half_centuries": user_data.get("half_centuries", 0),
289
+ "highest_score": user_data.get("highest_score", 0),
290
+ "average_runs": user_data.get("average_runs", 0.0),
291
+ "created_at": now,
292
+ "updated_at": now,
293
+ }
294
+
295
+ # Store in Firestore using UID as document ID
296
+ db.collection("users").document(uid).set(firestore_user)
297
+
298
+ status = "[PREMIUM]" if is_premium else "[NON-PREMIUM]"
299
+ print(f" └─ Saved to Firestore: {status}\n")
300
+
301
+ created_count += 1
302
+
303
+ except auth_client.EmailAlreadyExistsError:
304
+ print(f"[WARN] User already exists: {user_data['email']}\n")
305
+ failed_count += 1
306
+ except Exception as e:
307
+ print(f"[ERROR] Failed to create {user_data['name']}: {str(e)}\n")
308
+ failed_count += 1
309
+
310
+ # Print summary
311
+ print("\n" + "="*60)
312
+ print(f"[SUCCESS] Successfully created: {created_count} users")
313
+ print(f"[ERROR] Failed/Skipped: {failed_count} users")
314
+ print(f"[TOTAL] {created_count + failed_count} attempts")
315
+ print("="*60)
316
+
317
+ # Count premium vs non-premium
318
+ premium_count = sum(1 for u in DUMMY_USERS if u["is_premium"])
319
+ non_premium_count = len(DUMMY_USERS) - premium_count
320
+ print(f"\n[SUMMARY] User Distribution:")
321
+ print(f" [PREMIUM]: {premium_count}")
322
+ print(f" [NON-PREMIUM]: {non_premium_count}")
323
+ print("="*60 + "\n")
324
+
325
+
326
+ if __name__ == "__main__":
327
+ try:
328
+ create_firebase_users()
329
+ except KeyboardInterrupt:
330
+ print("\n\n[WARN] Operation cancelled by user")
331
+ except Exception as e:
332
+ print(f"\n[ERROR] Error: {str(e)}")
backend/verify_users_created.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Verify all created Firebase users"""
3
+
4
+ import firebase_admin
5
+ from firebase_admin import credentials, firestore
6
+ import os
7
+
8
+ cred_path = 'firebase-service-account.json'
9
+ if not firebase_admin._apps and os.path.exists(cred_path):
10
+ cred = credentials.Certificate(cred_path)
11
+ firebase_admin.initialize_app(cred)
12
+
13
+ db = firestore.client()
14
+ users_snap = list(db.collection('users').stream())
15
+ users = sorted(users_snap, key=lambda u: u.get('name', ''))
16
+
17
+ premium_users = [u for u in users if u.get('is_premium')]
18
+ non_premium_users = [u for u in users if not u.get('is_premium')]
19
+
20
+ print('='*80)
21
+ print('FIREBASE USERS CREATED')
22
+ print('='*80)
23
+ print(f'\n[PREMIUM USERS] ({len(premium_users)})')
24
+ print('-'*80)
25
+ for i, user in enumerate(premium_users, 1):
26
+ data = user.to_dict()
27
+ name = data.get('name', 'N/A')
28
+ email = data.get('email', 'N/A')
29
+ jersey = data.get('jersey_number', 0)
30
+ runs = data.get('runs', 0)
31
+ matches = data.get('matches', 0)
32
+ wickets = data.get('wickets', 0)
33
+ print(f'{i:2}. {name:30} | {email}')
34
+ print(f' Jersey: {jersey:3} | Runs: {runs:5} | Matches: {matches:3} | Wickets: {wickets:3}')
35
+
36
+ print(f'\n[NON-PREMIUM USERS] ({len(non_premium_users)})')
37
+ print('-'*80)
38
+ for i, user in enumerate(non_premium_users, 1):
39
+ data = user.to_dict()
40
+ name = data.get('name', 'N/A')
41
+ email = data.get('email', 'N/A')
42
+ jersey = data.get('jersey_number', 0)
43
+ runs = data.get('runs', 0)
44
+ matches = data.get('matches', 0)
45
+ wickets = data.get('wickets', 0)
46
+ print(f'{i:2}. {name:30} | {email}')
47
+ print(f' Jersey: {jersey:3} | Runs: {runs:5} | Matches: {matches:3} | Wickets: {wickets:3}')
48
+
49
+ print('\n' + '='*80)
50
+ print(f'TOTAL USERS: {len(users)} (Premium: {len(premium_users)}, Non-Premium: {len(non_premium_users)})')
51
+ print('='*80)
52
+ print('\nLogin credentials:')
53
+ print(' Password: Password@123 (for all users)')
54
+ print('='*80)
docker-compose.prod.yml CHANGED
@@ -19,6 +19,12 @@ services:
19
  dockerfile: Dockerfile.prod
20
  args:
21
  VITE_API_URL: /api
 
 
 
 
 
 
22
  ports:
23
  - "80:80"
24
  depends_on:
 
19
  dockerfile: Dockerfile.prod
20
  args:
21
  VITE_API_URL: /api
22
+ VITE_FIREBASE_API_KEY: ${VITE_FIREBASE_API_KEY-}
23
+ VITE_FIREBASE_AUTH_DOMAIN: ${VITE_FIREBASE_AUTH_DOMAIN-}
24
+ VITE_FIREBASE_PROJECT_ID: ${VITE_FIREBASE_PROJECT_ID-}
25
+ VITE_FIREBASE_STORAGE_BUCKET: ${VITE_FIREBASE_STORAGE_BUCKET-}
26
+ VITE_FIREBASE_MESSAGING_SENDER_ID: ${VITE_FIREBASE_MESSAGING_SENDER_ID-}
27
+ VITE_FIREBASE_APP_ID: ${VITE_FIREBASE_APP_ID-}
28
  ports:
29
  - "80:80"
30
  depends_on:
frontend/.env.example CHANGED
@@ -2,4 +2,10 @@
2
 
3
  # Local development backend
4
  VITE_API_URL=http://localhost:8000
 
 
 
 
 
 
5
  VITE_APP_TITLE=SSC - Sculpt Soft Cricketers
 
2
 
3
  # Local development backend
4
  VITE_API_URL=http://localhost:8000
5
+ VITE_FIREBASE_API_KEY=
6
+ VITE_FIREBASE_AUTH_DOMAIN=
7
+ VITE_FIREBASE_PROJECT_ID=
8
+ VITE_FIREBASE_STORAGE_BUCKET=
9
+ VITE_FIREBASE_MESSAGING_SENDER_ID=
10
+ VITE_FIREBASE_APP_ID=
11
  VITE_APP_TITLE=SSC - Sculpt Soft Cricketers
frontend/.env.production.example CHANGED
@@ -1,4 +1,10 @@
1
  # Frontend production build variables
2
  # For docker+nginx deployment keep this as /api
3
  VITE_API_URL=/api
 
 
 
 
 
 
4
  VITE_APP_TITLE=SSC - Sculpt Soft Cricketers
 
1
  # Frontend production build variables
2
  # For docker+nginx deployment keep this as /api
3
  VITE_API_URL=/api
4
+ VITE_FIREBASE_API_KEY=
5
+ VITE_FIREBASE_AUTH_DOMAIN=
6
+ VITE_FIREBASE_PROJECT_ID=
7
+ VITE_FIREBASE_STORAGE_BUCKET=
8
+ VITE_FIREBASE_MESSAGING_SENDER_ID=
9
+ VITE_FIREBASE_APP_ID=
10
  VITE_APP_TITLE=SSC - Sculpt Soft Cricketers
frontend/Dockerfile.prod CHANGED
@@ -3,12 +3,24 @@ FROM node:18-alpine AS builder
3
  WORKDIR /app
4
 
5
  COPY package*.json ./
6
- RUN npm ci
7
 
8
  COPY . .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
 
 
 
 
 
 
 
 
 
 
 
 
12
  RUN npm run build
13
 
14
  FROM nginx:1.27-alpine
 
3
  WORKDIR /app
4
 
5
  COPY package*.json ./
6
+ RUN npm install
7
 
8
  COPY . .
9
 
10
  ARG VITE_API_URL=/api
11
  ENV VITE_API_URL=${VITE_API_URL}
12
+ ARG VITE_FIREBASE_API_KEY=
13
+ ENV VITE_FIREBASE_API_KEY=${VITE_FIREBASE_API_KEY}
14
+ ARG VITE_FIREBASE_AUTH_DOMAIN=
15
+ ENV VITE_FIREBASE_AUTH_DOMAIN=${VITE_FIREBASE_AUTH_DOMAIN}
16
+ ARG VITE_FIREBASE_PROJECT_ID=
17
+ ENV VITE_FIREBASE_PROJECT_ID=${VITE_FIREBASE_PROJECT_ID}
18
+ ARG VITE_FIREBASE_STORAGE_BUCKET=
19
+ ENV VITE_FIREBASE_STORAGE_BUCKET=${VITE_FIREBASE_STORAGE_BUCKET}
20
+ ARG VITE_FIREBASE_MESSAGING_SENDER_ID=
21
+ ENV VITE_FIREBASE_MESSAGING_SENDER_ID=${VITE_FIREBASE_MESSAGING_SENDER_ID}
22
+ ARG VITE_FIREBASE_APP_ID=
23
+ ENV VITE_FIREBASE_APP_ID=${VITE_FIREBASE_APP_ID}
24
  RUN npm run build
25
 
26
  FROM nginx:1.27-alpine
frontend/index.html CHANGED
@@ -2,7 +2,18 @@
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
 
 
 
 
 
 
 
 
 
 
6
  <title>SSC - Sculpt Soft Cricketers</title>
7
  <style>
8
  * {
 
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
6
+ <meta name="description" content="Cricket scoring app for match management, team setup, and live scoring">
7
+ <meta name="theme-color" content="#0f6f62">
8
+ <meta name="color-scheme" content="light">
9
+ <meta name="format-detection" content="telephone=no">
10
+ <meta name="apple-mobile-web-app-capable" content="yes">
11
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
12
+ <meta name="apple-mobile-web-app-title" content="SSC">
13
+ <meta name="apple-mobile-web-app-icons-precomposed" content="yes">
14
+ <link rel="apple-touch-icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'><rect fill='%230f6f62' width='192' height='192'/><text x='50%' y='50%' font-size='120' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>SSC</text></svg>">
15
+ <link rel="manifest" href="/manifest.json">
16
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect fill='%230f6f62' width='100' height='100'/><text x='50' y='50' font-size='60' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>S</text></svg>">
17
  <title>SSC - Sculpt Soft Cricketers</title>
18
  <style>
19
  * {
frontend/package-lock.json CHANGED
@@ -10,6 +10,7 @@
10
  "dependencies": {
11
  "axios": "^1.6.0",
12
  "chart.js": "^4.4.0",
 
13
  "react": "^18.2.0",
14
  "react-chartjs-2": "^5.2.0",
15
  "react-dom": "^18.2.0",
@@ -759,6 +760,649 @@
759
  "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
760
  }
761
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
762
  "node_modules/@humanwhocodes/config-array": {
763
  "version": "0.13.0",
764
  "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
@@ -891,6 +1535,70 @@
891
  "node": ">= 8"
892
  }
893
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
894
  "node_modules/@remix-run/router": {
895
  "version": "1.23.2",
896
  "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
@@ -1309,6 +2017,15 @@
1309
  "dev": true,
1310
  "license": "MIT"
1311
  },
 
 
 
 
 
 
 
 
 
1312
  "node_modules/@ungap/structured-clone": {
1313
  "version": "1.3.0",
1314
  "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -1382,7 +2099,6 @@
1382
  "version": "5.0.1",
1383
  "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
1384
  "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
1385
- "dev": true,
1386
  "license": "MIT",
1387
  "engines": {
1388
  "node": ">=8"
@@ -1392,7 +2108,6 @@
1392
  "version": "4.3.0",
1393
  "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
1394
  "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
1395
- "dev": true,
1396
  "license": "MIT",
1397
  "dependencies": {
1398
  "color-convert": "^2.0.1"
@@ -1768,11 +2483,24 @@
1768
  "pnpm": ">=8"
1769
  }
1770
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1771
  "node_modules/color-convert": {
1772
  "version": "2.0.1",
1773
  "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
1774
  "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
1775
- "dev": true,
1776
  "license": "MIT",
1777
  "dependencies": {
1778
  "color-name": "~1.1.4"
@@ -1785,7 +2513,6 @@
1785
  "version": "1.1.4",
1786
  "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
1787
  "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
1788
- "dev": true,
1789
  "license": "MIT"
1790
  },
1791
  "node_modules/combined-stream": {
@@ -1987,6 +2714,12 @@
1987
  "dev": true,
1988
  "license": "ISC"
1989
  },
 
 
 
 
 
 
1990
  "node_modules/es-abstract": {
1991
  "version": "1.24.1",
1992
  "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz",
@@ -2204,7 +2937,6 @@
2204
  "version": "3.2.0",
2205
  "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
2206
  "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
2207
- "dev": true,
2208
  "license": "MIT",
2209
  "engines": {
2210
  "node": ">=6"
@@ -2452,6 +3184,18 @@
2452
  "reusify": "^1.0.4"
2453
  }
2454
  },
 
 
 
 
 
 
 
 
 
 
 
 
2455
  "node_modules/file-entry-cache": {
2456
  "version": "6.0.1",
2457
  "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
@@ -2482,6 +3226,66 @@
2482
  "url": "https://github.com/sponsors/sindresorhus"
2483
  }
2484
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2485
  "node_modules/flat-cache": {
2486
  "version": "3.2.0",
2487
  "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz",
@@ -2638,6 +3442,15 @@
2638
  "node": ">=6.9.0"
2639
  }
2640
  },
 
 
 
 
 
 
 
 
 
2641
  "node_modules/get-intrinsic": {
2642
  "version": "1.3.0",
2643
  "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@@ -2871,6 +3684,18 @@
2871
  "node": ">= 0.4"
2872
  }
2873
  },
 
 
 
 
 
 
 
 
 
 
 
 
2874
  "node_modules/ignore": {
2875
  "version": "5.3.2",
2876
  "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -3103,6 +3928,15 @@
3103
  "url": "https://github.com/sponsors/ljharb"
3104
  }
3105
  },
 
 
 
 
 
 
 
 
 
3106
  "node_modules/is-generator-function": {
3107
  "version": "1.1.2",
3108
  "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz",
@@ -3488,6 +4322,12 @@
3488
  "url": "https://github.com/sponsors/sindresorhus"
3489
  }
3490
  },
 
 
 
 
 
 
3491
  "node_modules/lodash.merge": {
3492
  "version": "4.6.2",
3493
  "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -3495,6 +4335,12 @@
3495
  "dev": true,
3496
  "license": "MIT"
3497
  },
 
 
 
 
 
 
3498
  "node_modules/loose-envify": {
3499
  "version": "1.4.0",
3500
  "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -3923,6 +4769,30 @@
3923
  "react-is": "^16.13.1"
3924
  }
3925
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3926
  "node_modules/proxy-from-env": {
3927
  "version": "1.1.0",
3928
  "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
@@ -4090,6 +4960,15 @@
4090
  "url": "https://github.com/sponsors/ljharb"
4091
  }
4092
  },
 
 
 
 
 
 
 
 
 
4093
  "node_modules/resolve": {
4094
  "version": "2.0.0-next.6",
4095
  "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz",
@@ -4241,6 +5120,26 @@
4241
  "url": "https://github.com/sponsors/ljharb"
4242
  }
4243
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4244
  "node_modules/safe-push-apply": {
4245
  "version": "1.0.0",
4246
  "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
@@ -4467,6 +5366,20 @@
4467
  "node": ">= 0.4"
4468
  }
4469
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4470
  "node_modules/string.prototype.matchall": {
4471
  "version": "4.0.12",
4472
  "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
@@ -4569,7 +5482,6 @@
4569
  "version": "6.0.1",
4570
  "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
4571
  "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
4572
- "dev": true,
4573
  "license": "MIT",
4574
  "dependencies": {
4575
  "ansi-regex": "^5.0.1"
@@ -4624,6 +5536,12 @@
4624
  "dev": true,
4625
  "license": "MIT"
4626
  },
 
 
 
 
 
 
4627
  "node_modules/type-check": {
4628
  "version": "0.4.0",
4629
  "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -4747,6 +5665,12 @@
4747
  "url": "https://github.com/sponsors/ljharb"
4748
  }
4749
  },
 
 
 
 
 
 
4750
  "node_modules/update-browserslist-db": {
4751
  "version": "1.2.3",
4752
  "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -4849,6 +5773,35 @@
4849
  }
4850
  }
4851
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4852
  "node_modules/which": {
4853
  "version": "2.0.2",
4854
  "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -4964,6 +5917,23 @@
4964
  "node": ">=0.10.0"
4965
  }
4966
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4967
  "node_modules/wrappy": {
4968
  "version": "1.0.2",
4969
  "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
@@ -4971,6 +5941,15 @@
4971
  "dev": true,
4972
  "license": "ISC"
4973
  },
 
 
 
 
 
 
 
 
 
4974
  "node_modules/yallist": {
4975
  "version": "3.1.1",
4976
  "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
@@ -4978,6 +5957,33 @@
4978
  "dev": true,
4979
  "license": "ISC"
4980
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4981
  "node_modules/yocto-queue": {
4982
  "version": "0.1.0",
4983
  "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
 
10
  "dependencies": {
11
  "axios": "^1.6.0",
12
  "chart.js": "^4.4.0",
13
+ "firebase": "^11.2.0",
14
  "react": "^18.2.0",
15
  "react-chartjs-2": "^5.2.0",
16
  "react-dom": "^18.2.0",
 
760
  "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
761
  }
762
  },
763
+ "node_modules/@firebase/ai": {
764
+ "version": "1.4.1",
765
+ "resolved": "https://registry.npmjs.org/@firebase/ai/-/ai-1.4.1.tgz",
766
+ "integrity": "sha512-bcusQfA/tHjUjBTnMx6jdoPMpDl3r8K15Z+snHz9wq0Foox0F/V+kNLXucEOHoTL2hTc9l+onZCyBJs2QoIC3g==",
767
+ "license": "Apache-2.0",
768
+ "dependencies": {
769
+ "@firebase/app-check-interop-types": "0.3.3",
770
+ "@firebase/component": "0.6.18",
771
+ "@firebase/logger": "0.4.4",
772
+ "@firebase/util": "1.12.1",
773
+ "tslib": "^2.1.0"
774
+ },
775
+ "engines": {
776
+ "node": ">=18.0.0"
777
+ },
778
+ "peerDependencies": {
779
+ "@firebase/app": "0.x",
780
+ "@firebase/app-types": "0.x"
781
+ }
782
+ },
783
+ "node_modules/@firebase/analytics": {
784
+ "version": "0.10.17",
785
+ "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.10.17.tgz",
786
+ "integrity": "sha512-n5vfBbvzduMou/2cqsnKrIes4auaBjdhg8QNA2ZQZ59QgtO2QiwBaXQZQE4O4sgB0Ds1tvLgUUkY+pwzu6/xEg==",
787
+ "license": "Apache-2.0",
788
+ "dependencies": {
789
+ "@firebase/component": "0.6.18",
790
+ "@firebase/installations": "0.6.18",
791
+ "@firebase/logger": "0.4.4",
792
+ "@firebase/util": "1.12.1",
793
+ "tslib": "^2.1.0"
794
+ },
795
+ "peerDependencies": {
796
+ "@firebase/app": "0.x"
797
+ }
798
+ },
799
+ "node_modules/@firebase/analytics-compat": {
800
+ "version": "0.2.23",
801
+ "resolved": "https://registry.npmjs.org/@firebase/analytics-compat/-/analytics-compat-0.2.23.tgz",
802
+ "integrity": "sha512-3AdO10RN18G5AzREPoFgYhW6vWXr3u+OYQv6pl3CX6Fky8QRk0AHurZlY3Q1xkXO0TDxIsdhO3y65HF7PBOJDw==",
803
+ "license": "Apache-2.0",
804
+ "dependencies": {
805
+ "@firebase/analytics": "0.10.17",
806
+ "@firebase/analytics-types": "0.8.3",
807
+ "@firebase/component": "0.6.18",
808
+ "@firebase/util": "1.12.1",
809
+ "tslib": "^2.1.0"
810
+ },
811
+ "peerDependencies": {
812
+ "@firebase/app-compat": "0.x"
813
+ }
814
+ },
815
+ "node_modules/@firebase/analytics-types": {
816
+ "version": "0.8.3",
817
+ "resolved": "https://registry.npmjs.org/@firebase/analytics-types/-/analytics-types-0.8.3.tgz",
818
+ "integrity": "sha512-VrIp/d8iq2g501qO46uGz3hjbDb8xzYMrbu8Tp0ovzIzrvJZ2fvmj649gTjge/b7cCCcjT0H37g1gVtlNhnkbg==",
819
+ "license": "Apache-2.0"
820
+ },
821
+ "node_modules/@firebase/app": {
822
+ "version": "0.13.2",
823
+ "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.13.2.tgz",
824
+ "integrity": "sha512-jwtMmJa1BXXDCiDx1vC6SFN/+HfYG53UkfJa6qeN5ogvOunzbFDO3wISZy5n9xgYFUrEP6M7e8EG++riHNTv9w==",
825
+ "license": "Apache-2.0",
826
+ "peer": true,
827
+ "dependencies": {
828
+ "@firebase/component": "0.6.18",
829
+ "@firebase/logger": "0.4.4",
830
+ "@firebase/util": "1.12.1",
831
+ "idb": "7.1.1",
832
+ "tslib": "^2.1.0"
833
+ },
834
+ "engines": {
835
+ "node": ">=18.0.0"
836
+ }
837
+ },
838
+ "node_modules/@firebase/app-check": {
839
+ "version": "0.10.1",
840
+ "resolved": "https://registry.npmjs.org/@firebase/app-check/-/app-check-0.10.1.tgz",
841
+ "integrity": "sha512-MgNdlms9Qb0oSny87pwpjKush9qUwCJhfmTJHDfrcKo4neLGiSeVE4qJkzP7EQTIUFKp84pbTxobSAXkiuQVYQ==",
842
+ "license": "Apache-2.0",
843
+ "dependencies": {
844
+ "@firebase/component": "0.6.18",
845
+ "@firebase/logger": "0.4.4",
846
+ "@firebase/util": "1.12.1",
847
+ "tslib": "^2.1.0"
848
+ },
849
+ "engines": {
850
+ "node": ">=18.0.0"
851
+ },
852
+ "peerDependencies": {
853
+ "@firebase/app": "0.x"
854
+ }
855
+ },
856
+ "node_modules/@firebase/app-check-compat": {
857
+ "version": "0.3.26",
858
+ "resolved": "https://registry.npmjs.org/@firebase/app-check-compat/-/app-check-compat-0.3.26.tgz",
859
+ "integrity": "sha512-PkX+XJMLDea6nmnopzFKlr+s2LMQGqdyT2DHdbx1v1dPSqOol2YzgpgymmhC67vitXVpNvS3m/AiWQWWhhRRPQ==",
860
+ "license": "Apache-2.0",
861
+ "dependencies": {
862
+ "@firebase/app-check": "0.10.1",
863
+ "@firebase/app-check-types": "0.5.3",
864
+ "@firebase/component": "0.6.18",
865
+ "@firebase/logger": "0.4.4",
866
+ "@firebase/util": "1.12.1",
867
+ "tslib": "^2.1.0"
868
+ },
869
+ "engines": {
870
+ "node": ">=18.0.0"
871
+ },
872
+ "peerDependencies": {
873
+ "@firebase/app-compat": "0.x"
874
+ }
875
+ },
876
+ "node_modules/@firebase/app-check-interop-types": {
877
+ "version": "0.3.3",
878
+ "resolved": "https://registry.npmjs.org/@firebase/app-check-interop-types/-/app-check-interop-types-0.3.3.tgz",
879
+ "integrity": "sha512-gAlxfPLT2j8bTI/qfe3ahl2I2YcBQ8cFIBdhAQA4I2f3TndcO+22YizyGYuttLHPQEpWkhmpFW60VCFEPg4g5A==",
880
+ "license": "Apache-2.0"
881
+ },
882
+ "node_modules/@firebase/app-check-types": {
883
+ "version": "0.5.3",
884
+ "resolved": "https://registry.npmjs.org/@firebase/app-check-types/-/app-check-types-0.5.3.tgz",
885
+ "integrity": "sha512-hyl5rKSj0QmwPdsAxrI5x1otDlByQ7bvNvVt8G/XPO2CSwE++rmSVf3VEhaeOR4J8ZFaF0Z0NDSmLejPweZ3ng==",
886
+ "license": "Apache-2.0"
887
+ },
888
+ "node_modules/@firebase/app-compat": {
889
+ "version": "0.4.2",
890
+ "resolved": "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.4.2.tgz",
891
+ "integrity": "sha512-LssbyKHlwLeiV8GBATyOyjmHcMpX/tFjzRUCS1jnwGAew1VsBB4fJowyS5Ud5LdFbYpJeS+IQoC+RQxpK7eH3Q==",
892
+ "license": "Apache-2.0",
893
+ "peer": true,
894
+ "dependencies": {
895
+ "@firebase/app": "0.13.2",
896
+ "@firebase/component": "0.6.18",
897
+ "@firebase/logger": "0.4.4",
898
+ "@firebase/util": "1.12.1",
899
+ "tslib": "^2.1.0"
900
+ },
901
+ "engines": {
902
+ "node": ">=18.0.0"
903
+ }
904
+ },
905
+ "node_modules/@firebase/app-types": {
906
+ "version": "0.9.3",
907
+ "resolved": "https://registry.npmjs.org/@firebase/app-types/-/app-types-0.9.3.tgz",
908
+ "integrity": "sha512-kRVpIl4vVGJ4baogMDINbyrIOtOxqhkZQg4jTq3l8Lw6WSk0xfpEYzezFu+Kl4ve4fbPl79dvwRtaFqAC/ucCw==",
909
+ "license": "Apache-2.0",
910
+ "peer": true
911
+ },
912
+ "node_modules/@firebase/auth-compat": {
913
+ "version": "0.5.28",
914
+ "resolved": "https://registry.npmjs.org/@firebase/auth-compat/-/auth-compat-0.5.28.tgz",
915
+ "integrity": "sha512-HpMSo/cc6Y8IX7bkRIaPPqT//Jt83iWy5rmDWeThXQCAImstkdNo3giFLORJwrZw2ptiGkOij64EH1ztNJzc7Q==",
916
+ "license": "Apache-2.0",
917
+ "dependencies": {
918
+ "@firebase/auth": "1.10.8",
919
+ "@firebase/auth-types": "0.13.0",
920
+ "@firebase/component": "0.6.18",
921
+ "@firebase/util": "1.12.1",
922
+ "tslib": "^2.1.0"
923
+ },
924
+ "engines": {
925
+ "node": ">=18.0.0"
926
+ },
927
+ "peerDependencies": {
928
+ "@firebase/app-compat": "0.x"
929
+ }
930
+ },
931
+ "node_modules/@firebase/auth-compat/node_modules/@firebase/auth": {
932
+ "version": "1.10.8",
933
+ "resolved": "https://registry.npmjs.org/@firebase/auth/-/auth-1.10.8.tgz",
934
+ "integrity": "sha512-GpuTz5ap8zumr/ocnPY57ZanX02COsXloY6Y/2LYPAuXYiaJRf6BAGDEdRq1BMjP93kqQnKNuKZUTMZbQ8MNYA==",
935
+ "license": "Apache-2.0",
936
+ "dependencies": {
937
+ "@firebase/component": "0.6.18",
938
+ "@firebase/logger": "0.4.4",
939
+ "@firebase/util": "1.12.1",
940
+ "tslib": "^2.1.0"
941
+ },
942
+ "engines": {
943
+ "node": ">=18.0.0"
944
+ },
945
+ "peerDependencies": {
946
+ "@firebase/app": "0.x",
947
+ "@react-native-async-storage/async-storage": "^1.18.1"
948
+ },
949
+ "peerDependenciesMeta": {
950
+ "@react-native-async-storage/async-storage": {
951
+ "optional": true
952
+ }
953
+ }
954
+ },
955
+ "node_modules/@firebase/auth-interop-types": {
956
+ "version": "0.2.4",
957
+ "resolved": "https://registry.npmjs.org/@firebase/auth-interop-types/-/auth-interop-types-0.2.4.tgz",
958
+ "integrity": "sha512-JPgcXKCuO+CWqGDnigBtvo09HeBs5u/Ktc2GaFj2m01hLarbxthLNm7Fk8iOP1aqAtXV+fnnGj7U28xmk7IwVA==",
959
+ "license": "Apache-2.0"
960
+ },
961
+ "node_modules/@firebase/auth-types": {
962
+ "version": "0.13.0",
963
+ "resolved": "https://registry.npmjs.org/@firebase/auth-types/-/auth-types-0.13.0.tgz",
964
+ "integrity": "sha512-S/PuIjni0AQRLF+l9ck0YpsMOdE8GO2KU6ubmBB7P+7TJUCQDa3R1dlgYm9UzGbbePMZsp0xzB93f2b/CgxMOg==",
965
+ "license": "Apache-2.0",
966
+ "peerDependencies": {
967
+ "@firebase/app-types": "0.x",
968
+ "@firebase/util": "1.x"
969
+ }
970
+ },
971
+ "node_modules/@firebase/component": {
972
+ "version": "0.6.18",
973
+ "resolved": "https://registry.npmjs.org/@firebase/component/-/component-0.6.18.tgz",
974
+ "integrity": "sha512-n28kPCkE2dL2U28fSxZJjzPPVpKsQminJ6NrzcKXAI0E/lYC8YhfwpyllScqVEvAI3J2QgJZWYgrX+1qGI+SQQ==",
975
+ "license": "Apache-2.0",
976
+ "dependencies": {
977
+ "@firebase/util": "1.12.1",
978
+ "tslib": "^2.1.0"
979
+ },
980
+ "engines": {
981
+ "node": ">=18.0.0"
982
+ }
983
+ },
984
+ "node_modules/@firebase/data-connect": {
985
+ "version": "0.3.10",
986
+ "resolved": "https://registry.npmjs.org/@firebase/data-connect/-/data-connect-0.3.10.tgz",
987
+ "integrity": "sha512-VMVk7zxIkgwlVQIWHOKFahmleIjiVFwFOjmakXPd/LDgaB/5vzwsB5DWIYo+3KhGxWpidQlR8geCIn39YflJIQ==",
988
+ "license": "Apache-2.0",
989
+ "dependencies": {
990
+ "@firebase/auth-interop-types": "0.2.4",
991
+ "@firebase/component": "0.6.18",
992
+ "@firebase/logger": "0.4.4",
993
+ "@firebase/util": "1.12.1",
994
+ "tslib": "^2.1.0"
995
+ },
996
+ "peerDependencies": {
997
+ "@firebase/app": "0.x"
998
+ }
999
+ },
1000
+ "node_modules/@firebase/database": {
1001
+ "version": "1.0.20",
1002
+ "resolved": "https://registry.npmjs.org/@firebase/database/-/database-1.0.20.tgz",
1003
+ "integrity": "sha512-H9Rpj1pQ1yc9+4HQOotFGLxqAXwOzCHsRSRjcQFNOr8lhUt6LeYjf0NSRL04sc4X0dWe8DsCvYKxMYvFG/iOJw==",
1004
+ "license": "Apache-2.0",
1005
+ "dependencies": {
1006
+ "@firebase/app-check-interop-types": "0.3.3",
1007
+ "@firebase/auth-interop-types": "0.2.4",
1008
+ "@firebase/component": "0.6.18",
1009
+ "@firebase/logger": "0.4.4",
1010
+ "@firebase/util": "1.12.1",
1011
+ "faye-websocket": "0.11.4",
1012
+ "tslib": "^2.1.0"
1013
+ },
1014
+ "engines": {
1015
+ "node": ">=18.0.0"
1016
+ }
1017
+ },
1018
+ "node_modules/@firebase/database-compat": {
1019
+ "version": "2.0.11",
1020
+ "resolved": "https://registry.npmjs.org/@firebase/database-compat/-/database-compat-2.0.11.tgz",
1021
+ "integrity": "sha512-itEsHARSsYS95+udF/TtIzNeQ0Uhx4uIna0sk4E0wQJBUnLc/G1X6D7oRljoOuwwCezRLGvWBRyNrugv/esOEw==",
1022
+ "license": "Apache-2.0",
1023
+ "dependencies": {
1024
+ "@firebase/component": "0.6.18",
1025
+ "@firebase/database": "1.0.20",
1026
+ "@firebase/database-types": "1.0.15",
1027
+ "@firebase/logger": "0.4.4",
1028
+ "@firebase/util": "1.12.1",
1029
+ "tslib": "^2.1.0"
1030
+ },
1031
+ "engines": {
1032
+ "node": ">=18.0.0"
1033
+ }
1034
+ },
1035
+ "node_modules/@firebase/database-types": {
1036
+ "version": "1.0.15",
1037
+ "resolved": "https://registry.npmjs.org/@firebase/database-types/-/database-types-1.0.15.tgz",
1038
+ "integrity": "sha512-XWHJ0VUJ0k2E9HDMlKxlgy/ZuTa9EvHCGLjaKSUvrQnwhgZuRU5N3yX6SZ+ftf2hTzZmfRkv+b3QRvGg40bKNw==",
1039
+ "license": "Apache-2.0",
1040
+ "dependencies": {
1041
+ "@firebase/app-types": "0.9.3",
1042
+ "@firebase/util": "1.12.1"
1043
+ }
1044
+ },
1045
+ "node_modules/@firebase/firestore": {
1046
+ "version": "4.8.0",
1047
+ "resolved": "https://registry.npmjs.org/@firebase/firestore/-/firestore-4.8.0.tgz",
1048
+ "integrity": "sha512-QSRk+Q1/CaabKyqn3C32KSFiOdZpSqI9rpLK5BHPcooElumOBooPFa6YkDdiT+/KhJtel36LdAacha9BptMj2A==",
1049
+ "license": "Apache-2.0",
1050
+ "dependencies": {
1051
+ "@firebase/component": "0.6.18",
1052
+ "@firebase/logger": "0.4.4",
1053
+ "@firebase/util": "1.12.1",
1054
+ "@firebase/webchannel-wrapper": "1.0.3",
1055
+ "@grpc/grpc-js": "~1.9.0",
1056
+ "@grpc/proto-loader": "^0.7.8",
1057
+ "tslib": "^2.1.0"
1058
+ },
1059
+ "engines": {
1060
+ "node": ">=18.0.0"
1061
+ },
1062
+ "peerDependencies": {
1063
+ "@firebase/app": "0.x"
1064
+ }
1065
+ },
1066
+ "node_modules/@firebase/firestore-compat": {
1067
+ "version": "0.3.53",
1068
+ "resolved": "https://registry.npmjs.org/@firebase/firestore-compat/-/firestore-compat-0.3.53.tgz",
1069
+ "integrity": "sha512-qI3yZL8ljwAYWrTousWYbemay2YZa+udLWugjdjju2KODWtLG94DfO4NALJgPLv8CVGcDHNFXoyQexdRA0Cz8Q==",
1070
+ "license": "Apache-2.0",
1071
+ "dependencies": {
1072
+ "@firebase/component": "0.6.18",
1073
+ "@firebase/firestore": "4.8.0",
1074
+ "@firebase/firestore-types": "3.0.3",
1075
+ "@firebase/util": "1.12.1",
1076
+ "tslib": "^2.1.0"
1077
+ },
1078
+ "engines": {
1079
+ "node": ">=18.0.0"
1080
+ },
1081
+ "peerDependencies": {
1082
+ "@firebase/app-compat": "0.x"
1083
+ }
1084
+ },
1085
+ "node_modules/@firebase/firestore-types": {
1086
+ "version": "3.0.3",
1087
+ "resolved": "https://registry.npmjs.org/@firebase/firestore-types/-/firestore-types-3.0.3.tgz",
1088
+ "integrity": "sha512-hD2jGdiWRxB/eZWF89xcK9gF8wvENDJkzpVFb4aGkzfEaKxVRD1kjz1t1Wj8VZEp2LCB53Yx1zD8mrhQu87R6Q==",
1089
+ "license": "Apache-2.0",
1090
+ "peerDependencies": {
1091
+ "@firebase/app-types": "0.x",
1092
+ "@firebase/util": "1.x"
1093
+ }
1094
+ },
1095
+ "node_modules/@firebase/functions": {
1096
+ "version": "0.12.9",
1097
+ "resolved": "https://registry.npmjs.org/@firebase/functions/-/functions-0.12.9.tgz",
1098
+ "integrity": "sha512-FG95w6vjbUXN84Ehezc2SDjGmGq225UYbHrb/ptkRT7OTuCiQRErOQuyt1jI1tvcDekdNog+anIObihNFz79Lg==",
1099
+ "license": "Apache-2.0",
1100
+ "dependencies": {
1101
+ "@firebase/app-check-interop-types": "0.3.3",
1102
+ "@firebase/auth-interop-types": "0.2.4",
1103
+ "@firebase/component": "0.6.18",
1104
+ "@firebase/messaging-interop-types": "0.2.3",
1105
+ "@firebase/util": "1.12.1",
1106
+ "tslib": "^2.1.0"
1107
+ },
1108
+ "engines": {
1109
+ "node": ">=18.0.0"
1110
+ },
1111
+ "peerDependencies": {
1112
+ "@firebase/app": "0.x"
1113
+ }
1114
+ },
1115
+ "node_modules/@firebase/functions-compat": {
1116
+ "version": "0.3.26",
1117
+ "resolved": "https://registry.npmjs.org/@firebase/functions-compat/-/functions-compat-0.3.26.tgz",
1118
+ "integrity": "sha512-A798/6ff5LcG2LTWqaGazbFYnjBW8zc65YfID/en83ALmkhu2b0G8ykvQnLtakbV9ajrMYPn7Yc/XcYsZIUsjA==",
1119
+ "license": "Apache-2.0",
1120
+ "dependencies": {
1121
+ "@firebase/component": "0.6.18",
1122
+ "@firebase/functions": "0.12.9",
1123
+ "@firebase/functions-types": "0.6.3",
1124
+ "@firebase/util": "1.12.1",
1125
+ "tslib": "^2.1.0"
1126
+ },
1127
+ "engines": {
1128
+ "node": ">=18.0.0"
1129
+ },
1130
+ "peerDependencies": {
1131
+ "@firebase/app-compat": "0.x"
1132
+ }
1133
+ },
1134
+ "node_modules/@firebase/functions-types": {
1135
+ "version": "0.6.3",
1136
+ "resolved": "https://registry.npmjs.org/@firebase/functions-types/-/functions-types-0.6.3.tgz",
1137
+ "integrity": "sha512-EZoDKQLUHFKNx6VLipQwrSMh01A1SaL3Wg6Hpi//x6/fJ6Ee4hrAeswK99I5Ht8roiniKHw4iO0B1Oxj5I4plg==",
1138
+ "license": "Apache-2.0"
1139
+ },
1140
+ "node_modules/@firebase/installations": {
1141
+ "version": "0.6.18",
1142
+ "resolved": "https://registry.npmjs.org/@firebase/installations/-/installations-0.6.18.tgz",
1143
+ "integrity": "sha512-NQ86uGAcvO8nBRwVltRL9QQ4Reidc/3whdAasgeWCPIcrhOKDuNpAALa6eCVryLnK14ua2DqekCOX5uC9XbU/A==",
1144
+ "license": "Apache-2.0",
1145
+ "dependencies": {
1146
+ "@firebase/component": "0.6.18",
1147
+ "@firebase/util": "1.12.1",
1148
+ "idb": "7.1.1",
1149
+ "tslib": "^2.1.0"
1150
+ },
1151
+ "peerDependencies": {
1152
+ "@firebase/app": "0.x"
1153
+ }
1154
+ },
1155
+ "node_modules/@firebase/installations-compat": {
1156
+ "version": "0.2.18",
1157
+ "resolved": "https://registry.npmjs.org/@firebase/installations-compat/-/installations-compat-0.2.18.tgz",
1158
+ "integrity": "sha512-aLFohRpJO5kKBL/XYL4tN+GdwEB/Q6Vo9eZOM/6Kic7asSUgmSfGPpGUZO1OAaSRGwF4Lqnvi1f/f9VZnKzChw==",
1159
+ "license": "Apache-2.0",
1160
+ "dependencies": {
1161
+ "@firebase/component": "0.6.18",
1162
+ "@firebase/installations": "0.6.18",
1163
+ "@firebase/installations-types": "0.5.3",
1164
+ "@firebase/util": "1.12.1",
1165
+ "tslib": "^2.1.0"
1166
+ },
1167
+ "peerDependencies": {
1168
+ "@firebase/app-compat": "0.x"
1169
+ }
1170
+ },
1171
+ "node_modules/@firebase/installations-types": {
1172
+ "version": "0.5.3",
1173
+ "resolved": "https://registry.npmjs.org/@firebase/installations-types/-/installations-types-0.5.3.tgz",
1174
+ "integrity": "sha512-2FJI7gkLqIE0iYsNQ1P751lO3hER+Umykel+TkLwHj6plzWVxqvfclPUZhcKFVQObqloEBTmpi2Ozn7EkCABAA==",
1175
+ "license": "Apache-2.0",
1176
+ "peerDependencies": {
1177
+ "@firebase/app-types": "0.x"
1178
+ }
1179
+ },
1180
+ "node_modules/@firebase/logger": {
1181
+ "version": "0.4.4",
1182
+ "resolved": "https://registry.npmjs.org/@firebase/logger/-/logger-0.4.4.tgz",
1183
+ "integrity": "sha512-mH0PEh1zoXGnaR8gD1DeGeNZtWFKbnz9hDO91dIml3iou1gpOnLqXQ2dJfB71dj6dpmUjcQ6phY3ZZJbjErr9g==",
1184
+ "license": "Apache-2.0",
1185
+ "dependencies": {
1186
+ "tslib": "^2.1.0"
1187
+ },
1188
+ "engines": {
1189
+ "node": ">=18.0.0"
1190
+ }
1191
+ },
1192
+ "node_modules/@firebase/messaging": {
1193
+ "version": "0.12.22",
1194
+ "resolved": "https://registry.npmjs.org/@firebase/messaging/-/messaging-0.12.22.tgz",
1195
+ "integrity": "sha512-GJcrPLc+Hu7nk+XQ70Okt3M1u1eRr2ZvpMbzbc54oTPJZySHcX9ccZGVFcsZbSZ6o1uqumm8Oc7OFkD3Rn1/og==",
1196
+ "license": "Apache-2.0",
1197
+ "dependencies": {
1198
+ "@firebase/component": "0.6.18",
1199
+ "@firebase/installations": "0.6.18",
1200
+ "@firebase/messaging-interop-types": "0.2.3",
1201
+ "@firebase/util": "1.12.1",
1202
+ "idb": "7.1.1",
1203
+ "tslib": "^2.1.0"
1204
+ },
1205
+ "peerDependencies": {
1206
+ "@firebase/app": "0.x"
1207
+ }
1208
+ },
1209
+ "node_modules/@firebase/messaging-compat": {
1210
+ "version": "0.2.22",
1211
+ "resolved": "https://registry.npmjs.org/@firebase/messaging-compat/-/messaging-compat-0.2.22.tgz",
1212
+ "integrity": "sha512-5ZHtRnj6YO6f/QPa/KU6gryjmX4Kg33Kn4gRpNU6M1K47Gm8kcQwPkX7erRUYEH1mIWptfvjvXMHWoZaWjkU7A==",
1213
+ "license": "Apache-2.0",
1214
+ "dependencies": {
1215
+ "@firebase/component": "0.6.18",
1216
+ "@firebase/messaging": "0.12.22",
1217
+ "@firebase/util": "1.12.1",
1218
+ "tslib": "^2.1.0"
1219
+ },
1220
+ "peerDependencies": {
1221
+ "@firebase/app-compat": "0.x"
1222
+ }
1223
+ },
1224
+ "node_modules/@firebase/messaging-interop-types": {
1225
+ "version": "0.2.3",
1226
+ "resolved": "https://registry.npmjs.org/@firebase/messaging-interop-types/-/messaging-interop-types-0.2.3.tgz",
1227
+ "integrity": "sha512-xfzFaJpzcmtDjycpDeCUj0Ge10ATFi/VHVIvEEjDNc3hodVBQADZ7BWQU7CuFpjSHE+eLuBI13z5F/9xOoGX8Q==",
1228
+ "license": "Apache-2.0"
1229
+ },
1230
+ "node_modules/@firebase/performance": {
1231
+ "version": "0.7.7",
1232
+ "resolved": "https://registry.npmjs.org/@firebase/performance/-/performance-0.7.7.tgz",
1233
+ "integrity": "sha512-JTlTQNZKAd4+Q5sodpw6CN+6NmwbY72av3Lb6wUKTsL7rb3cuBIhQSrslWbVz0SwK3x0ZNcqX24qtRbwKiv+6w==",
1234
+ "license": "Apache-2.0",
1235
+ "dependencies": {
1236
+ "@firebase/component": "0.6.18",
1237
+ "@firebase/installations": "0.6.18",
1238
+ "@firebase/logger": "0.4.4",
1239
+ "@firebase/util": "1.12.1",
1240
+ "tslib": "^2.1.0",
1241
+ "web-vitals": "^4.2.4"
1242
+ },
1243
+ "peerDependencies": {
1244
+ "@firebase/app": "0.x"
1245
+ }
1246
+ },
1247
+ "node_modules/@firebase/performance-compat": {
1248
+ "version": "0.2.20",
1249
+ "resolved": "https://registry.npmjs.org/@firebase/performance-compat/-/performance-compat-0.2.20.tgz",
1250
+ "integrity": "sha512-XkFK5NmOKCBuqOKWeRgBUFZZGz9SzdTZp4OqeUg+5nyjapTiZ4XoiiUL8z7mB2q+63rPmBl7msv682J3rcDXIQ==",
1251
+ "license": "Apache-2.0",
1252
+ "dependencies": {
1253
+ "@firebase/component": "0.6.18",
1254
+ "@firebase/logger": "0.4.4",
1255
+ "@firebase/performance": "0.7.7",
1256
+ "@firebase/performance-types": "0.2.3",
1257
+ "@firebase/util": "1.12.1",
1258
+ "tslib": "^2.1.0"
1259
+ },
1260
+ "peerDependencies": {
1261
+ "@firebase/app-compat": "0.x"
1262
+ }
1263
+ },
1264
+ "node_modules/@firebase/performance-types": {
1265
+ "version": "0.2.3",
1266
+ "resolved": "https://registry.npmjs.org/@firebase/performance-types/-/performance-types-0.2.3.tgz",
1267
+ "integrity": "sha512-IgkyTz6QZVPAq8GSkLYJvwSLr3LS9+V6vNPQr0x4YozZJiLF5jYixj0amDtATf1X0EtYHqoPO48a9ija8GocxQ==",
1268
+ "license": "Apache-2.0"
1269
+ },
1270
+ "node_modules/@firebase/remote-config": {
1271
+ "version": "0.6.5",
1272
+ "resolved": "https://registry.npmjs.org/@firebase/remote-config/-/remote-config-0.6.5.tgz",
1273
+ "integrity": "sha512-fU0c8HY0vrVHwC+zQ/fpXSqHyDMuuuglV94VF6Yonhz8Fg2J+KOowPGANM0SZkLvVOYpTeWp3ZmM+F6NjwWLnw==",
1274
+ "license": "Apache-2.0",
1275
+ "dependencies": {
1276
+ "@firebase/component": "0.6.18",
1277
+ "@firebase/installations": "0.6.18",
1278
+ "@firebase/logger": "0.4.4",
1279
+ "@firebase/util": "1.12.1",
1280
+ "tslib": "^2.1.0"
1281
+ },
1282
+ "peerDependencies": {
1283
+ "@firebase/app": "0.x"
1284
+ }
1285
+ },
1286
+ "node_modules/@firebase/remote-config-compat": {
1287
+ "version": "0.2.18",
1288
+ "resolved": "https://registry.npmjs.org/@firebase/remote-config-compat/-/remote-config-compat-0.2.18.tgz",
1289
+ "integrity": "sha512-YiETpldhDy7zUrnS8e+3l7cNs0sL7+tVAxvVYU0lu7O+qLHbmdtAxmgY+wJqWdW2c9nDvBFec7QiF58pEUu0qQ==",
1290
+ "license": "Apache-2.0",
1291
+ "dependencies": {
1292
+ "@firebase/component": "0.6.18",
1293
+ "@firebase/logger": "0.4.4",
1294
+ "@firebase/remote-config": "0.6.5",
1295
+ "@firebase/remote-config-types": "0.4.0",
1296
+ "@firebase/util": "1.12.1",
1297
+ "tslib": "^2.1.0"
1298
+ },
1299
+ "peerDependencies": {
1300
+ "@firebase/app-compat": "0.x"
1301
+ }
1302
+ },
1303
+ "node_modules/@firebase/remote-config-types": {
1304
+ "version": "0.4.0",
1305
+ "resolved": "https://registry.npmjs.org/@firebase/remote-config-types/-/remote-config-types-0.4.0.tgz",
1306
+ "integrity": "sha512-7p3mRE/ldCNYt8fmWMQ/MSGRmXYlJ15Rvs9Rk17t8p0WwZDbeK7eRmoI1tvCPaDzn9Oqh+yD6Lw+sGLsLg4kKg==",
1307
+ "license": "Apache-2.0"
1308
+ },
1309
+ "node_modules/@firebase/storage": {
1310
+ "version": "0.13.14",
1311
+ "resolved": "https://registry.npmjs.org/@firebase/storage/-/storage-0.13.14.tgz",
1312
+ "integrity": "sha512-xTq5ixxORzx+bfqCpsh+o3fxOsGoDjC1nO0Mq2+KsOcny3l7beyBhP/y1u5T6mgsFQwI1j6oAkbT5cWdDBx87g==",
1313
+ "license": "Apache-2.0",
1314
+ "dependencies": {
1315
+ "@firebase/component": "0.6.18",
1316
+ "@firebase/util": "1.12.1",
1317
+ "tslib": "^2.1.0"
1318
+ },
1319
+ "engines": {
1320
+ "node": ">=18.0.0"
1321
+ },
1322
+ "peerDependencies": {
1323
+ "@firebase/app": "0.x"
1324
+ }
1325
+ },
1326
+ "node_modules/@firebase/storage-compat": {
1327
+ "version": "0.3.24",
1328
+ "resolved": "https://registry.npmjs.org/@firebase/storage-compat/-/storage-compat-0.3.24.tgz",
1329
+ "integrity": "sha512-XHn2tLniiP7BFKJaPZ0P8YQXKiVJX+bMyE2j2YWjYfaddqiJnROJYqSomwW6L3Y+gZAga35ONXUJQju6MB6SOQ==",
1330
+ "license": "Apache-2.0",
1331
+ "dependencies": {
1332
+ "@firebase/component": "0.6.18",
1333
+ "@firebase/storage": "0.13.14",
1334
+ "@firebase/storage-types": "0.8.3",
1335
+ "@firebase/util": "1.12.1",
1336
+ "tslib": "^2.1.0"
1337
+ },
1338
+ "engines": {
1339
+ "node": ">=18.0.0"
1340
+ },
1341
+ "peerDependencies": {
1342
+ "@firebase/app-compat": "0.x"
1343
+ }
1344
+ },
1345
+ "node_modules/@firebase/storage-types": {
1346
+ "version": "0.8.3",
1347
+ "resolved": "https://registry.npmjs.org/@firebase/storage-types/-/storage-types-0.8.3.tgz",
1348
+ "integrity": "sha512-+Muk7g9uwngTpd8xn9OdF/D48uiQ7I1Fae7ULsWPuKoCH3HU7bfFPhxtJYzyhjdniowhuDpQcfPmuNRAqZEfvg==",
1349
+ "license": "Apache-2.0",
1350
+ "peerDependencies": {
1351
+ "@firebase/app-types": "0.x",
1352
+ "@firebase/util": "1.x"
1353
+ }
1354
+ },
1355
+ "node_modules/@firebase/util": {
1356
+ "version": "1.12.1",
1357
+ "resolved": "https://registry.npmjs.org/@firebase/util/-/util-1.12.1.tgz",
1358
+ "integrity": "sha512-zGlBn/9Dnya5ta9bX/fgEoNC3Cp8s6h+uYPYaDieZsFOAdHP/ExzQ/eaDgxD3GOROdPkLKpvKY0iIzr9adle0w==",
1359
+ "hasInstallScript": true,
1360
+ "license": "Apache-2.0",
1361
+ "peer": true,
1362
+ "dependencies": {
1363
+ "tslib": "^2.1.0"
1364
+ },
1365
+ "engines": {
1366
+ "node": ">=18.0.0"
1367
+ }
1368
+ },
1369
+ "node_modules/@firebase/webchannel-wrapper": {
1370
+ "version": "1.0.3",
1371
+ "resolved": "https://registry.npmjs.org/@firebase/webchannel-wrapper/-/webchannel-wrapper-1.0.3.tgz",
1372
+ "integrity": "sha512-2xCRM9q9FlzGZCdgDMJwc0gyUkWFtkosy7Xxr6sFgQwn+wMNIWd7xIvYNauU1r64B5L5rsGKy/n9TKJ0aAFeqQ==",
1373
+ "license": "Apache-2.0"
1374
+ },
1375
+ "node_modules/@grpc/grpc-js": {
1376
+ "version": "1.9.15",
1377
+ "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.9.15.tgz",
1378
+ "integrity": "sha512-nqE7Hc0AzI+euzUwDAy0aY5hCp10r734gMGRdU+qOPX0XSceI2ULrcXB5U2xSc5VkWwalCj4M7GzCAygZl2KoQ==",
1379
+ "license": "Apache-2.0",
1380
+ "dependencies": {
1381
+ "@grpc/proto-loader": "^0.7.8",
1382
+ "@types/node": ">=12.12.47"
1383
+ },
1384
+ "engines": {
1385
+ "node": "^8.13.0 || >=10.10.0"
1386
+ }
1387
+ },
1388
+ "node_modules/@grpc/proto-loader": {
1389
+ "version": "0.7.15",
1390
+ "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.15.tgz",
1391
+ "integrity": "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==",
1392
+ "license": "Apache-2.0",
1393
+ "dependencies": {
1394
+ "lodash.camelcase": "^4.3.0",
1395
+ "long": "^5.0.0",
1396
+ "protobufjs": "^7.2.5",
1397
+ "yargs": "^17.7.2"
1398
+ },
1399
+ "bin": {
1400
+ "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js"
1401
+ },
1402
+ "engines": {
1403
+ "node": ">=6"
1404
+ }
1405
+ },
1406
  "node_modules/@humanwhocodes/config-array": {
1407
  "version": "0.13.0",
1408
  "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
 
1535
  "node": ">= 8"
1536
  }
1537
  },
1538
+ "node_modules/@protobufjs/aspromise": {
1539
+ "version": "1.1.2",
1540
+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
1541
+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
1542
+ "license": "BSD-3-Clause"
1543
+ },
1544
+ "node_modules/@protobufjs/base64": {
1545
+ "version": "1.1.2",
1546
+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
1547
+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
1548
+ "license": "BSD-3-Clause"
1549
+ },
1550
+ "node_modules/@protobufjs/codegen": {
1551
+ "version": "2.0.4",
1552
+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz",
1553
+ "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==",
1554
+ "license": "BSD-3-Clause"
1555
+ },
1556
+ "node_modules/@protobufjs/eventemitter": {
1557
+ "version": "1.1.0",
1558
+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz",
1559
+ "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==",
1560
+ "license": "BSD-3-Clause"
1561
+ },
1562
+ "node_modules/@protobufjs/fetch": {
1563
+ "version": "1.1.0",
1564
+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz",
1565
+ "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==",
1566
+ "license": "BSD-3-Clause",
1567
+ "dependencies": {
1568
+ "@protobufjs/aspromise": "^1.1.1",
1569
+ "@protobufjs/inquire": "^1.1.0"
1570
+ }
1571
+ },
1572
+ "node_modules/@protobufjs/float": {
1573
+ "version": "1.0.2",
1574
+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
1575
+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
1576
+ "license": "BSD-3-Clause"
1577
+ },
1578
+ "node_modules/@protobufjs/inquire": {
1579
+ "version": "1.1.0",
1580
+ "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz",
1581
+ "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==",
1582
+ "license": "BSD-3-Clause"
1583
+ },
1584
+ "node_modules/@protobufjs/path": {
1585
+ "version": "1.1.2",
1586
+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
1587
+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
1588
+ "license": "BSD-3-Clause"
1589
+ },
1590
+ "node_modules/@protobufjs/pool": {
1591
+ "version": "1.1.0",
1592
+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
1593
+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
1594
+ "license": "BSD-3-Clause"
1595
+ },
1596
+ "node_modules/@protobufjs/utf8": {
1597
+ "version": "1.1.0",
1598
+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz",
1599
+ "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==",
1600
+ "license": "BSD-3-Clause"
1601
+ },
1602
  "node_modules/@remix-run/router": {
1603
  "version": "1.23.2",
1604
  "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
 
2017
  "dev": true,
2018
  "license": "MIT"
2019
  },
2020
+ "node_modules/@types/node": {
2021
+ "version": "25.5.0",
2022
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.5.0.tgz",
2023
+ "integrity": "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw==",
2024
+ "license": "MIT",
2025
+ "dependencies": {
2026
+ "undici-types": "~7.18.0"
2027
+ }
2028
+ },
2029
  "node_modules/@ungap/structured-clone": {
2030
  "version": "1.3.0",
2031
  "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
 
2099
  "version": "5.0.1",
2100
  "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
2101
  "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
 
2102
  "license": "MIT",
2103
  "engines": {
2104
  "node": ">=8"
 
2108
  "version": "4.3.0",
2109
  "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
2110
  "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
 
2111
  "license": "MIT",
2112
  "dependencies": {
2113
  "color-convert": "^2.0.1"
 
2483
  "pnpm": ">=8"
2484
  }
2485
  },
2486
+ "node_modules/cliui": {
2487
+ "version": "8.0.1",
2488
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
2489
+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
2490
+ "license": "ISC",
2491
+ "dependencies": {
2492
+ "string-width": "^4.2.0",
2493
+ "strip-ansi": "^6.0.1",
2494
+ "wrap-ansi": "^7.0.0"
2495
+ },
2496
+ "engines": {
2497
+ "node": ">=12"
2498
+ }
2499
+ },
2500
  "node_modules/color-convert": {
2501
  "version": "2.0.1",
2502
  "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
2503
  "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
 
2504
  "license": "MIT",
2505
  "dependencies": {
2506
  "color-name": "~1.1.4"
 
2513
  "version": "1.1.4",
2514
  "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
2515
  "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
 
2516
  "license": "MIT"
2517
  },
2518
  "node_modules/combined-stream": {
 
2714
  "dev": true,
2715
  "license": "ISC"
2716
  },
2717
+ "node_modules/emoji-regex": {
2718
+ "version": "8.0.0",
2719
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
2720
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
2721
+ "license": "MIT"
2722
+ },
2723
  "node_modules/es-abstract": {
2724
  "version": "1.24.1",
2725
  "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz",
 
2937
  "version": "3.2.0",
2938
  "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
2939
  "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
 
2940
  "license": "MIT",
2941
  "engines": {
2942
  "node": ">=6"
 
3184
  "reusify": "^1.0.4"
3185
  }
3186
  },
3187
+ "node_modules/faye-websocket": {
3188
+ "version": "0.11.4",
3189
+ "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz",
3190
+ "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==",
3191
+ "license": "Apache-2.0",
3192
+ "dependencies": {
3193
+ "websocket-driver": ">=0.5.1"
3194
+ },
3195
+ "engines": {
3196
+ "node": ">=0.8.0"
3197
+ }
3198
+ },
3199
  "node_modules/file-entry-cache": {
3200
  "version": "6.0.1",
3201
  "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz",
 
3226
  "url": "https://github.com/sponsors/sindresorhus"
3227
  }
3228
  },
3229
+ "node_modules/firebase": {
3230
+ "version": "11.10.0",
3231
+ "resolved": "https://registry.npmjs.org/firebase/-/firebase-11.10.0.tgz",
3232
+ "integrity": "sha512-nKBXoDzF0DrXTBQJlZa+sbC5By99ysYU1D6PkMRYknm0nCW7rJly47q492Ht7Ndz5MeYSBuboKuhS1e6mFC03w==",
3233
+ "license": "Apache-2.0",
3234
+ "dependencies": {
3235
+ "@firebase/ai": "1.4.1",
3236
+ "@firebase/analytics": "0.10.17",
3237
+ "@firebase/analytics-compat": "0.2.23",
3238
+ "@firebase/app": "0.13.2",
3239
+ "@firebase/app-check": "0.10.1",
3240
+ "@firebase/app-check-compat": "0.3.26",
3241
+ "@firebase/app-compat": "0.4.2",
3242
+ "@firebase/app-types": "0.9.3",
3243
+ "@firebase/auth": "1.10.8",
3244
+ "@firebase/auth-compat": "0.5.28",
3245
+ "@firebase/data-connect": "0.3.10",
3246
+ "@firebase/database": "1.0.20",
3247
+ "@firebase/database-compat": "2.0.11",
3248
+ "@firebase/firestore": "4.8.0",
3249
+ "@firebase/firestore-compat": "0.3.53",
3250
+ "@firebase/functions": "0.12.9",
3251
+ "@firebase/functions-compat": "0.3.26",
3252
+ "@firebase/installations": "0.6.18",
3253
+ "@firebase/installations-compat": "0.2.18",
3254
+ "@firebase/messaging": "0.12.22",
3255
+ "@firebase/messaging-compat": "0.2.22",
3256
+ "@firebase/performance": "0.7.7",
3257
+ "@firebase/performance-compat": "0.2.20",
3258
+ "@firebase/remote-config": "0.6.5",
3259
+ "@firebase/remote-config-compat": "0.2.18",
3260
+ "@firebase/storage": "0.13.14",
3261
+ "@firebase/storage-compat": "0.3.24",
3262
+ "@firebase/util": "1.12.1"
3263
+ }
3264
+ },
3265
+ "node_modules/firebase/node_modules/@firebase/auth": {
3266
+ "version": "1.10.8",
3267
+ "resolved": "https://registry.npmjs.org/@firebase/auth/-/auth-1.10.8.tgz",
3268
+ "integrity": "sha512-GpuTz5ap8zumr/ocnPY57ZanX02COsXloY6Y/2LYPAuXYiaJRf6BAGDEdRq1BMjP93kqQnKNuKZUTMZbQ8MNYA==",
3269
+ "license": "Apache-2.0",
3270
+ "dependencies": {
3271
+ "@firebase/component": "0.6.18",
3272
+ "@firebase/logger": "0.4.4",
3273
+ "@firebase/util": "1.12.1",
3274
+ "tslib": "^2.1.0"
3275
+ },
3276
+ "engines": {
3277
+ "node": ">=18.0.0"
3278
+ },
3279
+ "peerDependencies": {
3280
+ "@firebase/app": "0.x",
3281
+ "@react-native-async-storage/async-storage": "^1.18.1"
3282
+ },
3283
+ "peerDependenciesMeta": {
3284
+ "@react-native-async-storage/async-storage": {
3285
+ "optional": true
3286
+ }
3287
+ }
3288
+ },
3289
  "node_modules/flat-cache": {
3290
  "version": "3.2.0",
3291
  "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz",
 
3442
  "node": ">=6.9.0"
3443
  }
3444
  },
3445
+ "node_modules/get-caller-file": {
3446
+ "version": "2.0.5",
3447
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
3448
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
3449
+ "license": "ISC",
3450
+ "engines": {
3451
+ "node": "6.* || 8.* || >= 10.*"
3452
+ }
3453
+ },
3454
  "node_modules/get-intrinsic": {
3455
  "version": "1.3.0",
3456
  "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
 
3684
  "node": ">= 0.4"
3685
  }
3686
  },
3687
+ "node_modules/http-parser-js": {
3688
+ "version": "0.5.10",
3689
+ "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz",
3690
+ "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==",
3691
+ "license": "MIT"
3692
+ },
3693
+ "node_modules/idb": {
3694
+ "version": "7.1.1",
3695
+ "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz",
3696
+ "integrity": "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ==",
3697
+ "license": "ISC"
3698
+ },
3699
  "node_modules/ignore": {
3700
  "version": "5.3.2",
3701
  "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
 
3928
  "url": "https://github.com/sponsors/ljharb"
3929
  }
3930
  },
3931
+ "node_modules/is-fullwidth-code-point": {
3932
+ "version": "3.0.0",
3933
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
3934
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
3935
+ "license": "MIT",
3936
+ "engines": {
3937
+ "node": ">=8"
3938
+ }
3939
+ },
3940
  "node_modules/is-generator-function": {
3941
  "version": "1.1.2",
3942
  "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz",
 
4322
  "url": "https://github.com/sponsors/sindresorhus"
4323
  }
4324
  },
4325
+ "node_modules/lodash.camelcase": {
4326
+ "version": "4.3.0",
4327
+ "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",
4328
+ "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==",
4329
+ "license": "MIT"
4330
+ },
4331
  "node_modules/lodash.merge": {
4332
  "version": "4.6.2",
4333
  "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
 
4335
  "dev": true,
4336
  "license": "MIT"
4337
  },
4338
+ "node_modules/long": {
4339
+ "version": "5.3.2",
4340
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
4341
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
4342
+ "license": "Apache-2.0"
4343
+ },
4344
  "node_modules/loose-envify": {
4345
  "version": "1.4.0",
4346
  "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
 
4769
  "react-is": "^16.13.1"
4770
  }
4771
  },
4772
+ "node_modules/protobufjs": {
4773
+ "version": "7.5.4",
4774
+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz",
4775
+ "integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==",
4776
+ "hasInstallScript": true,
4777
+ "license": "BSD-3-Clause",
4778
+ "dependencies": {
4779
+ "@protobufjs/aspromise": "^1.1.2",
4780
+ "@protobufjs/base64": "^1.1.2",
4781
+ "@protobufjs/codegen": "^2.0.4",
4782
+ "@protobufjs/eventemitter": "^1.1.0",
4783
+ "@protobufjs/fetch": "^1.1.0",
4784
+ "@protobufjs/float": "^1.0.2",
4785
+ "@protobufjs/inquire": "^1.1.0",
4786
+ "@protobufjs/path": "^1.1.2",
4787
+ "@protobufjs/pool": "^1.1.0",
4788
+ "@protobufjs/utf8": "^1.1.0",
4789
+ "@types/node": ">=13.7.0",
4790
+ "long": "^5.0.0"
4791
+ },
4792
+ "engines": {
4793
+ "node": ">=12.0.0"
4794
+ }
4795
+ },
4796
  "node_modules/proxy-from-env": {
4797
  "version": "1.1.0",
4798
  "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
 
4960
  "url": "https://github.com/sponsors/ljharb"
4961
  }
4962
  },
4963
+ "node_modules/require-directory": {
4964
+ "version": "2.1.1",
4965
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
4966
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
4967
+ "license": "MIT",
4968
+ "engines": {
4969
+ "node": ">=0.10.0"
4970
+ }
4971
+ },
4972
  "node_modules/resolve": {
4973
  "version": "2.0.0-next.6",
4974
  "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz",
 
5120
  "url": "https://github.com/sponsors/ljharb"
5121
  }
5122
  },
5123
+ "node_modules/safe-buffer": {
5124
+ "version": "5.2.1",
5125
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
5126
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
5127
+ "funding": [
5128
+ {
5129
+ "type": "github",
5130
+ "url": "https://github.com/sponsors/feross"
5131
+ },
5132
+ {
5133
+ "type": "patreon",
5134
+ "url": "https://www.patreon.com/feross"
5135
+ },
5136
+ {
5137
+ "type": "consulting",
5138
+ "url": "https://feross.org/support"
5139
+ }
5140
+ ],
5141
+ "license": "MIT"
5142
+ },
5143
  "node_modules/safe-push-apply": {
5144
  "version": "1.0.0",
5145
  "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
 
5366
  "node": ">= 0.4"
5367
  }
5368
  },
5369
+ "node_modules/string-width": {
5370
+ "version": "4.2.3",
5371
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
5372
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
5373
+ "license": "MIT",
5374
+ "dependencies": {
5375
+ "emoji-regex": "^8.0.0",
5376
+ "is-fullwidth-code-point": "^3.0.0",
5377
+ "strip-ansi": "^6.0.1"
5378
+ },
5379
+ "engines": {
5380
+ "node": ">=8"
5381
+ }
5382
+ },
5383
  "node_modules/string.prototype.matchall": {
5384
  "version": "4.0.12",
5385
  "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
 
5482
  "version": "6.0.1",
5483
  "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
5484
  "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
 
5485
  "license": "MIT",
5486
  "dependencies": {
5487
  "ansi-regex": "^5.0.1"
 
5536
  "dev": true,
5537
  "license": "MIT"
5538
  },
5539
+ "node_modules/tslib": {
5540
+ "version": "2.8.1",
5541
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
5542
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
5543
+ "license": "0BSD"
5544
+ },
5545
  "node_modules/type-check": {
5546
  "version": "0.4.0",
5547
  "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
 
5665
  "url": "https://github.com/sponsors/ljharb"
5666
  }
5667
  },
5668
+ "node_modules/undici-types": {
5669
+ "version": "7.18.2",
5670
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
5671
+ "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
5672
+ "license": "MIT"
5673
+ },
5674
  "node_modules/update-browserslist-db": {
5675
  "version": "1.2.3",
5676
  "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
 
5773
  }
5774
  }
5775
  },
5776
+ "node_modules/web-vitals": {
5777
+ "version": "4.2.4",
5778
+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-4.2.4.tgz",
5779
+ "integrity": "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==",
5780
+ "license": "Apache-2.0"
5781
+ },
5782
+ "node_modules/websocket-driver": {
5783
+ "version": "0.7.4",
5784
+ "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz",
5785
+ "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==",
5786
+ "license": "Apache-2.0",
5787
+ "dependencies": {
5788
+ "http-parser-js": ">=0.5.1",
5789
+ "safe-buffer": ">=5.1.0",
5790
+ "websocket-extensions": ">=0.1.1"
5791
+ },
5792
+ "engines": {
5793
+ "node": ">=0.8.0"
5794
+ }
5795
+ },
5796
+ "node_modules/websocket-extensions": {
5797
+ "version": "0.1.4",
5798
+ "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz",
5799
+ "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==",
5800
+ "license": "Apache-2.0",
5801
+ "engines": {
5802
+ "node": ">=0.8.0"
5803
+ }
5804
+ },
5805
  "node_modules/which": {
5806
  "version": "2.0.2",
5807
  "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
 
5917
  "node": ">=0.10.0"
5918
  }
5919
  },
5920
+ "node_modules/wrap-ansi": {
5921
+ "version": "7.0.0",
5922
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
5923
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
5924
+ "license": "MIT",
5925
+ "dependencies": {
5926
+ "ansi-styles": "^4.0.0",
5927
+ "string-width": "^4.1.0",
5928
+ "strip-ansi": "^6.0.0"
5929
+ },
5930
+ "engines": {
5931
+ "node": ">=10"
5932
+ },
5933
+ "funding": {
5934
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
5935
+ }
5936
+ },
5937
  "node_modules/wrappy": {
5938
  "version": "1.0.2",
5939
  "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
 
5941
  "dev": true,
5942
  "license": "ISC"
5943
  },
5944
+ "node_modules/y18n": {
5945
+ "version": "5.0.8",
5946
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
5947
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
5948
+ "license": "ISC",
5949
+ "engines": {
5950
+ "node": ">=10"
5951
+ }
5952
+ },
5953
  "node_modules/yallist": {
5954
  "version": "3.1.1",
5955
  "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
 
5957
  "dev": true,
5958
  "license": "ISC"
5959
  },
5960
+ "node_modules/yargs": {
5961
+ "version": "17.7.2",
5962
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
5963
+ "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
5964
+ "license": "MIT",
5965
+ "dependencies": {
5966
+ "cliui": "^8.0.1",
5967
+ "escalade": "^3.1.1",
5968
+ "get-caller-file": "^2.0.5",
5969
+ "require-directory": "^2.1.1",
5970
+ "string-width": "^4.2.3",
5971
+ "y18n": "^5.0.5",
5972
+ "yargs-parser": "^21.1.1"
5973
+ },
5974
+ "engines": {
5975
+ "node": ">=12"
5976
+ }
5977
+ },
5978
+ "node_modules/yargs-parser": {
5979
+ "version": "21.1.1",
5980
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
5981
+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
5982
+ "license": "ISC",
5983
+ "engines": {
5984
+ "node": ">=12"
5985
+ }
5986
+ },
5987
  "node_modules/yocto-queue": {
5988
  "version": "0.1.0",
5989
  "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
frontend/package.json CHANGED
@@ -10,17 +10,18 @@
10
  "lint": "eslint src --ext js,jsx"
11
  },
12
  "dependencies": {
13
- "react": "^18.2.0",
14
- "react-dom": "^18.2.0",
15
- "react-router-dom": "^6.20.0",
16
  "axios": "^1.6.0",
17
  "chart.js": "^4.4.0",
18
- "react-chartjs-2": "^5.2.0"
 
 
 
 
19
  },
20
  "devDependencies": {
21
  "@vitejs/plugin-react": "^4.2.0",
22
- "vite": "^5.0.0",
23
  "eslint": "^8.55.0",
24
- "eslint-plugin-react": "^7.33.0"
 
25
  }
26
  }
 
10
  "lint": "eslint src --ext js,jsx"
11
  },
12
  "dependencies": {
 
 
 
13
  "axios": "^1.6.0",
14
  "chart.js": "^4.4.0",
15
+ "firebase": "^11.2.0",
16
+ "react": "^18.2.0",
17
+ "react-chartjs-2": "^5.2.0",
18
+ "react-dom": "^18.2.0",
19
+ "react-router-dom": "^6.20.0"
20
  },
21
  "devDependencies": {
22
  "@vitejs/plugin-react": "^4.2.0",
 
23
  "eslint": "^8.55.0",
24
+ "eslint-plugin-react": "^7.33.0",
25
+ "vite": "^5.0.0"
26
  }
27
  }
frontend/public/manifest.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "SSC - Sculpt Soft Cricketers",
3
+ "short_name": "SSC",
4
+ "description": "Cricket scoring app for match management, team setup, and live scoring",
5
+ "start_url": "/",
6
+ "scope": "/",
7
+ "display": "standalone",
8
+ "orientation": "portrait-primary",
9
+ "theme_color": "#0f6f62",
10
+ "background_color": "#ffffff",
11
+ "icons": [
12
+ {
13
+ "src": "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 192 192'><rect fill='%230f6f62' width='192' height='192'/><text x='50%' y='50%' font-size='120' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>SSC</text></svg>",
14
+ "sizes": "192x192",
15
+ "type": "image/svg+xml",
16
+ "purpose": "any"
17
+ },
18
+ {
19
+ "src": "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><rect fill='%230f6f62' width='512' height='512'/><text x='50%' y='50%' font-size='320' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>SSC</text></svg>",
20
+ "sizes": "512x512",
21
+ "type": "image/svg+xml",
22
+ "purpose": "any maskable"
23
+ }
24
+ ],
25
+ "screenshots": [
26
+ {
27
+ "src": "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 540 720'><rect fill='%23eef4f3' width='540' height='720'/><text x='270' y='360' font-size='80' font-weight='bold' fill='%230f6f62' text-anchor='middle' dy='0.3em'>SSC Cricket Scores</text></svg>",
28
+ "sizes": "540x720",
29
+ "type": "image/svg+xml",
30
+ "form_factor": "narrow"
31
+ }
32
+ ],
33
+ "categories": ["sports"],
34
+ "shortcuts": [
35
+ {
36
+ "name": "Create Match",
37
+ "short_name": "Create Match",
38
+ "description": "Create a new cricket match",
39
+ "url": "/?step=create-match",
40
+ "icons": [
41
+ {
42
+ "src": "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 96'><rect fill='%230f6f62' width='96' height='96' rx='20'/><text x='48' y='48' font-size='60' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>+</text></svg>",
43
+ "sizes": "96x96",
44
+ "type": "image/svg+xml"
45
+ }
46
+ ]
47
+ },
48
+ {
49
+ "name": "Live Scores",
50
+ "short_name": "Scores",
51
+ "description": "View live match scores",
52
+ "url": "/?tab=scores",
53
+ "icons": [
54
+ {
55
+ "src": "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 96'><rect fill='%230f6f62' width='96' height='96' rx='20'/><text x='48' y='48' font-size='60' font-weight='bold' fill='white' text-anchor='middle' dy='0.3em'>🏏</text></svg>",
56
+ "sizes": "96x96",
57
+ "type": "image/svg+xml"
58
+ }
59
+ ]
60
+ }
61
+ ],
62
+ "prefer_related_applications": false
63
+ }
frontend/public/service-worker.js ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const CACHE_NAME = 'ssc-app-v1';
2
+ const urlsToCache = [
3
+ '/',
4
+ '/index.html',
5
+ '/manifest.json',
6
+ '/src/main.jsx',
7
+ '/src/App.jsx',
8
+ '/src/styles/global.css',
9
+ ];
10
+
11
+ // Install event - cache assets
12
+ self.addEventListener('install', (event) => {
13
+ event.waitUntil(
14
+ caches.open(CACHE_NAME).then((cache) => {
15
+ console.log('[Service Worker] Caching app shell');
16
+ return cache.addAll(urlsToCache).catch(() => {
17
+ // Some files might fail, but that's ok - continue anyway
18
+ console.log('[Service Worker] Some cache files failed to load');
19
+ });
20
+ })
21
+ );
22
+ self.skipWaiting();
23
+ });
24
+
25
+ // Activate event - clean up old caches
26
+ self.addEventListener('activate', (event) => {
27
+ event.waitUntil(
28
+ caches.keys().then((cacheNames) => {
29
+ return Promise.all(
30
+ cacheNames.map((cacheName) => {
31
+ if (cacheName !== CACHE_NAME) {
32
+ console.log('[Service Worker] Deleting old cache:', cacheName);
33
+ return caches.delete(cacheName);
34
+ }
35
+ })
36
+ );
37
+ })
38
+ );
39
+ self.clients.claim();
40
+ });
41
+
42
+ // Fetch event - serve from cache, fallback to network
43
+ self.addEventListener('fetch', (event) => {
44
+ const { request } = event;
45
+ const url = new URL(request.url);
46
+
47
+ // Skip cross-origin requests and non-GET requests
48
+ if (url.origin !== location.origin || request.method !== 'GET') {
49
+ return;
50
+ }
51
+
52
+ event.respondWith(
53
+ caches.match(request).then((response) => {
54
+ if (response) {
55
+ return response;
56
+ }
57
+
58
+ return fetch(request).then((response) => {
59
+ // Don't cache non-successful responses
60
+ if (!response || response.status !== 200 || response.type === 'error') {
61
+ return response;
62
+ }
63
+
64
+ // Clone the response
65
+ const responseToCache = response.clone();
66
+
67
+ // Cache successful GET requests for API endpoints and assets
68
+ if (
69
+ request.url.includes('/api/') ||
70
+ request.url.match(/\.(js|css|png|jpg|jpeg|svg|gif|woff|woff2)$/)
71
+ ) {
72
+ caches.open(CACHE_NAME).then((cache) => {
73
+ cache.put(request, responseToCache);
74
+ });
75
+ }
76
+
77
+ return response;
78
+ });
79
+ }).catch(() => {
80
+ // Return a custom offline message if needed
81
+ console.log('[Service Worker] Fetch failed for:', request.url);
82
+
83
+ // For API requests, return offline status
84
+ if (request.url.includes('/api/')) {
85
+ return new Response(
86
+ JSON.stringify({
87
+ detail: 'You are offline. Changes will sync when you reconnect.',
88
+ offline: true
89
+ }),
90
+ {
91
+ status: 503,
92
+ statusText: 'Service Unavailable',
93
+ headers: { 'Content-Type': 'application/json' }
94
+ }
95
+ );
96
+ }
97
+ })
98
+ );
99
+ });
100
+
101
+ // Handle messages from the client
102
+ self.addEventListener('message', (event) => {
103
+ if (event.data && event.data.type === 'SKIP_WAITING') {
104
+ self.skipWaiting();
105
+ }
106
+ });
frontend/src/App.jsx CHANGED
@@ -1,6 +1,7 @@
1
  import React, { useState, useEffect } from 'react';
2
  import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
3
  import { Navbar } from './components/Navbar';
 
4
  import { HomePage } from './pages/Home';
5
  import { LoginPage, RegisterPage } from './pages/Auth';
6
  import { DashboardPage } from './pages/Dashboard';
@@ -54,37 +55,40 @@ function App() {
54
  }
55
 
56
  return (
57
- <BrowserRouter>
58
- <Navbar isAuthenticated={isAuthenticated} user={user} />
59
- <Routes>
60
- {/* Public Routes */}
61
- <Route path="/" element={<HomePage />} />
62
- <Route path="/login" element={isAuthenticated ? <Navigate to="/dashboard" /> : <LoginPage />} />
63
- <Route path="/register" element={isAuthenticated ? <Navigate to="/dashboard" /> : <RegisterPage />} />
 
64
 
65
- {/* Protected Routes */}
66
- {isAuthenticated ? (
67
- <>
68
- <Route path="/dashboard" element={<DashboardPage />} />
69
- <Route path="/players" element={<PlayersPage />} />
70
- <Route path="/profile" element={<ProfilePage />} />
71
- <Route path="/player/:playerId" element={<ProfilePage />} />
72
- <Route path="/finance" element={<FinancePage />} />
73
- <Route path="/matches" element={<MatchesPage />} />
74
- <Route path="/admin" element={isAdmin ? <AdminPage /> : <Navigate to="/dashboard" />} />
75
- </>
76
- ) : (
77
- <>
78
- <Route path="/dashboard" element={<Navigate to="/login" />} />
79
- <Route path="/players" element={<Navigate to="/login" />} />
80
- <Route path="/profile" element={<Navigate to="/login" />} />
81
- <Route path="/finance" element={<Navigate to="/login" />} />
82
- <Route path="/matches" element={<Navigate to="/login" />} />
83
- <Route path="/admin" element={<Navigate to="/login" />} />
84
- </>
85
- )}
86
- </Routes>
87
- </BrowserRouter>
 
 
88
  );
89
  }
90
 
 
1
  import React, { useState, useEffect } from 'react';
2
  import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
3
  import { Navbar } from './components/Navbar';
4
+ import { PWAInstallGuide } from './components/PWAInstallGuide';
5
  import { HomePage } from './pages/Home';
6
  import { LoginPage, RegisterPage } from './pages/Auth';
7
  import { DashboardPage } from './pages/Dashboard';
 
55
  }
56
 
57
  return (
58
+ <>
59
+ <BrowserRouter>
60
+ <Navbar isAuthenticated={isAuthenticated} user={user} />
61
+ <Routes>
62
+ {/* Public Routes */}
63
+ <Route path="/" element={<HomePage />} />
64
+ <Route path="/login" element={isAuthenticated ? <Navigate to="/dashboard" /> : <LoginPage />} />
65
+ <Route path="/register" element={isAuthenticated ? <Navigate to="/dashboard" /> : <RegisterPage />} />
66
 
67
+ {/* Protected Routes */}
68
+ {isAuthenticated ? (
69
+ <>
70
+ <Route path="/dashboard" element={<DashboardPage />} />
71
+ <Route path="/players" element={<PlayersPage />} />
72
+ <Route path="/profile" element={<ProfilePage />} />
73
+ <Route path="/player/:playerId" element={<ProfilePage />} />
74
+ <Route path="/finance" element={<FinancePage />} />
75
+ <Route path="/matches" element={<MatchesPage />} />
76
+ <Route path="/admin" element={isAdmin ? <AdminPage /> : <Navigate to="/dashboard" />} />
77
+ </>
78
+ ) : (
79
+ <>
80
+ <Route path="/dashboard" element={<Navigate to="/login" />} />
81
+ <Route path="/players" element={<Navigate to="/login" />} />
82
+ <Route path="/profile" element={<Navigate to="/login" />} />
83
+ <Route path="/finance" element={<Navigate to="/login" />} />
84
+ <Route path="/matches" element={<Navigate to="/login" />} />
85
+ <Route path="/admin" element={<Navigate to="/login" />} />
86
+ </>
87
+ )}
88
+ </Routes>
89
+ </BrowserRouter>
90
+ <PWAInstallGuide />
91
+ </>
92
  );
93
  }
94
 
frontend/src/components/Navbar.jsx CHANGED
@@ -1,14 +1,13 @@
1
  import React from 'react';
2
  import styles from './navbar.module.css';
3
  import { Link, useNavigate } from 'react-router-dom';
 
4
 
5
  export function Navbar({ isAuthenticated, user }) {
6
  const navigate = useNavigate();
7
 
8
- const handleLogout = () => {
9
- localStorage.removeItem('token');
10
- localStorage.removeItem('user');
11
- window.dispatchEvent(new Event('authchange'));
12
  navigate('/');
13
  };
14
 
 
1
  import React from 'react';
2
  import styles from './navbar.module.css';
3
  import { Link, useNavigate } from 'react-router-dom';
4
+ import { authService } from '../utils/api';
5
 
6
  export function Navbar({ isAuthenticated, user }) {
7
  const navigate = useNavigate();
8
 
9
+ const handleLogout = async () => {
10
+ await authService.logout();
 
 
11
  navigate('/');
12
  };
13
 
frontend/src/components/PWAInstallGuide.jsx ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+
3
+ export function PWAInstallGuide() {
4
+ const [showGuide, setShowGuide] = useState(false);
5
+
6
+ const getInstallInstructions = () => {
7
+ const userAgent = navigator.userAgent;
8
+
9
+ if (/android/i.test(userAgent)) {
10
+ return {
11
+ os: 'Android',
12
+ steps: [
13
+ 'Look for the "Install" popup at the bottom of the screen',
14
+ 'Tap "Install" to add SSC to your home screen',
15
+ 'Or, tap the menu icon (three dots) → "Install app"',
16
+ 'The app will appear as a standalone app on your home screen'
17
+ ]
18
+ };
19
+ } else if (/iphone|ipad|ipod/.test(userAgent)) {
20
+ return {
21
+ os: 'iOS',
22
+ steps: [
23
+ 'Tap the Share button (square with arrow)',
24
+ 'Scroll down and tap "Add to Home Screen"',
25
+ 'Enter the app name (or leave as "SSC")',
26
+ 'Tap "Add" to confirm',
27
+ 'The app will appear on your home screen'
28
+ ]
29
+ };
30
+ } else {
31
+ return {
32
+ os: 'Desktop/Web',
33
+ steps: [
34
+ 'Look for the install icon in the address bar (usually on the right)',
35
+ 'Click the icon to install the app',
36
+ 'Or, use the browser menu → "Install SSC"',
37
+ 'The app can be launched from your applications menu'
38
+ ]
39
+ };
40
+ }
41
+ };
42
+
43
+ const instructions = getInstallInstructions();
44
+
45
+ return (
46
+ <>
47
+ <button
48
+ onClick={() => setShowGuide(!showGuide)}
49
+ style={{
50
+ position: 'fixed',
51
+ bottom: '20px',
52
+ right: '20px',
53
+ width: '50px',
54
+ height: '50px',
55
+ borderRadius: '50%',
56
+ background: '#0f6f62',
57
+ color: 'white',
58
+ border: 'none',
59
+ fontSize: '24px',
60
+ cursor: 'pointer',
61
+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
62
+ zIndex: 100,
63
+ display: 'flex',
64
+ alignItems: 'center',
65
+ justifyContent: 'center',
66
+ fontWeight: 'bold'
67
+ }}
68
+ title="PWA Install Guide"
69
+ >
70
+ ?
71
+ </button>
72
+
73
+ {showGuide && (
74
+ <div style={{
75
+ position: 'fixed',
76
+ top: 0,
77
+ left: 0,
78
+ right: 0,
79
+ bottom: 0,
80
+ background: 'rgba(0, 0, 0, 0.5)',
81
+ display: 'flex',
82
+ alignItems: 'center',
83
+ justifyContent: 'center',
84
+ zIndex: 1001,
85
+ }}>
86
+ <div style={{
87
+ background: 'white',
88
+ borderRadius: '16px',
89
+ padding: '24px',
90
+ maxWidth: '500px',
91
+ width: '90%',
92
+ maxHeight: '80vh',
93
+ overflow: 'auto',
94
+ boxShadow: '0 10px 40px rgba(0, 0, 0, 0.2)',
95
+ }}>
96
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
97
+ <h2 style={{ margin: 0, color: '#173a36' }}>Install SSC App</h2>
98
+ <button
99
+ onClick={() => setShowGuide(false)}
100
+ style={{
101
+ background: 'none',
102
+ border: 'none',
103
+ fontSize: '24px',
104
+ cursor: 'pointer',
105
+ color: '#305d57',
106
+ }}
107
+ >
108
+ ✕
109
+ </button>
110
+ </div>
111
+
112
+ <p style={{ color: '#476b67', marginBottom: '16px' }}>
113
+ <strong>Platform:</strong> {instructions.os}
114
+ </p>
115
+
116
+ <h3 style={{ color: '#0f6f62', marginTop: '0', marginBottom: '12px' }}>How to Install:</h3>
117
+ <ol style={{ color: '#1d4b45', margin: 0, paddingLeft: '20px', lineHeight: '1.8' }}>
118
+ {instructions.steps.map((step, idx) => (
119
+ <li key={idx} style={{ marginBottom: '8px' }}>
120
+ {step}
121
+ </li>
122
+ ))}
123
+ </ol>
124
+
125
+ <div style={{
126
+ background: '#f4faf8',
127
+ border: '1px solid #d0e8e3',
128
+ borderRadius: '8px',
129
+ padding: '12px',
130
+ marginTop: '16px',
131
+ color: '#305d57',
132
+ fontSize: '13px',
133
+ }}>
134
+ <strong>Benefits of installing:</strong>
135
+ <ul style={{ margin: '8px 0 0 0', paddingLeft: '18px' }}>
136
+ <li>Access app from home screen</li>
137
+ <li>Faster loading times</li>
138
+ <li>Works offline for basic features</li>
139
+ <li>No browser address bar</li>
140
+ </ul>
141
+ </div>
142
+
143
+ <button
144
+ onClick={() => setShowGuide(false)}
145
+ style={{
146
+ width: '100%',
147
+ marginTop: '20px',
148
+ background: '#0f6f62',
149
+ color: 'white',
150
+ border: 'none',
151
+ padding: '10px 20px',
152
+ borderRadius: '8px',
153
+ cursor: 'pointer',
154
+ fontWeight: '600',
155
+ }}
156
+ >
157
+ Close
158
+ </button>
159
+ </div>
160
+ </div>
161
+ )}
162
+ </>
163
+ );
164
+ }
frontend/src/main.jsx CHANGED
@@ -8,3 +8,97 @@ ReactDOM.createRoot(document.getElementById('root')).render(
8
  <App />
9
  </React.StrictMode>,
10
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  <App />
9
  </React.StrictMode>,
10
  )
11
+
12
+ // Register Service Worker for PWA
13
+ if ('serviceWorker' in navigator) {
14
+ window.addEventListener('load', () => {
15
+ navigator.serviceWorker.register('/service-worker.js')
16
+ .then((registration) => {
17
+ console.log('[PWA] Service Worker registered:', registration);
18
+ })
19
+ .catch((error) => {
20
+ console.log('[PWA] Service Worker registration failed:', error);
21
+ });
22
+ });
23
+ }
24
+
25
+ // Handle install prompt
26
+ let deferredPrompt;
27
+ const installPromptDiv = document.createElement('div');
28
+ installPromptDiv.id = 'pwa-install-prompt';
29
+ installPromptDiv.style.cssText = `
30
+ position: fixed;
31
+ bottom: 20px;
32
+ left: 20px;
33
+ right: 20px;
34
+ background: linear-gradient(135deg, #0f6f62 0%, #12927f 100%);
35
+ color: white;
36
+ padding: 16px;
37
+ border-radius: 12px;
38
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
39
+ display: none;
40
+ z-index: 9999;
41
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
42
+ `;
43
+
44
+ installPromptDiv.innerHTML = `
45
+ <div style="display: flex; justify-content: space-between; align-items: center; gap: 12px;">
46
+ <div style="flex: 1;">
47
+ <strong style="font-size: 16px; display: block; margin-bottom: 4px;">Install SSC App</strong>
48
+ <span style="font-size: 14px; opacity: 0.9;">Get instant access to cricket scoring</span>
49
+ </div>
50
+ <div style="display: flex; gap: 8px; white-space: nowrap;">
51
+ <button id="pwa-install-btn" style="
52
+ background: white;
53
+ color: #0f6f62;
54
+ border: none;
55
+ padding: 8px 16px;
56
+ border-radius: 6px;
57
+ font-weight: 600;
58
+ cursor: pointer;
59
+ font-size: 14px;
60
+ ">Install</button>
61
+ <button id="pwa-dismiss-btn" style="
62
+ background: transparent;
63
+ color: white;
64
+ border: 1px solid rgba(255, 255, 255, 0.3);
65
+ padding: 8px 16px;
66
+ border-radius: 6px;
67
+ font-weight: 600;
68
+ cursor: pointer;
69
+ font-size: 14px;
70
+ ">Later</button>
71
+ </div>
72
+ </div>
73
+ `;
74
+
75
+ document.body.appendChild(installPromptDiv);
76
+
77
+ window.addEventListener('beforeinstallprompt', (e) => {
78
+ e.preventDefault();
79
+ deferredPrompt = e;
80
+ installPromptDiv.style.display = 'block';
81
+ console.log('[PWA] Install prompt is available');
82
+ });
83
+
84
+ document.getElementById('pwa-install-btn').addEventListener('click', async () => {
85
+ if (deferredPrompt) {
86
+ deferredPrompt.prompt();
87
+ const { outcome } = await deferredPrompt.userChoice;
88
+ console.log(`[PWA] User response to install prompt: ${outcome}`);
89
+ deferredPrompt = null;
90
+ installPromptDiv.style.display = 'none';
91
+ }
92
+ });
93
+
94
+ document.getElementById('pwa-dismiss-btn').addEventListener('click', () => {
95
+ deferredPrompt = null;
96
+ installPromptDiv.style.display = 'none';
97
+ });
98
+
99
+ // Hide install prompt if app is already installed
100
+ window.addEventListener('appinstalled', () => {
101
+ console.log('[PWA] App installed successfully');
102
+ installPromptDiv.style.display = 'none';
103
+ deferredPrompt = null;
104
+ });