Hkoradiya123 commited on
Commit
815d7a1
·
1 Parent(s): b996603

Add match schemas, seed script, and match page with live scoring functionality

Browse files

- Created match schemas in `match.py` for match creation, response, team setup, ball events, and scoreboard.
- Implemented a seed script `seed_dummy_users_sqlite.py` to populate the database with dummy users for testing.
- Developed the `MatchesPage` component in React for creating matches, setting up teams, and recording ball events.
- Added CSS styles for the matches page to enhance UI/UX.

backend/app/models/__init__.py CHANGED
@@ -4,6 +4,7 @@ from app.models.performance_log import PerformanceLog
4
  from app.models.notification import Notification
5
  from app.models.finance_transaction import FinanceTransaction
6
  from app.models.admin_chat_message import AdminChatMessage
 
7
 
8
  __all__ = [
9
  "User",
@@ -12,4 +13,7 @@ __all__ = [
12
  "Notification",
13
  "FinanceTransaction",
14
  "AdminChatMessage",
 
 
 
15
  ]
 
4
  from app.models.notification import Notification
5
  from app.models.finance_transaction import FinanceTransaction
6
  from app.models.admin_chat_message import AdminChatMessage
7
+ from app.models.match import Match, MatchPlayer, BallEvent
8
 
9
  __all__ = [
10
  "User",
 
13
  "Notification",
14
  "FinanceTransaction",
15
  "AdminChatMessage",
16
+ "Match",
17
+ "MatchPlayer",
18
+ "BallEvent",
19
  ]
backend/app/models/match.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, UniqueConstraint
3
+
4
+ from app.database import Base
5
+
6
+
7
+ class Match(Base):
8
+ __tablename__ = "matches"
9
+
10
+ id = Column(Integer, primary_key=True, index=True)
11
+ title = Column(String(150), nullable=False)
12
+ created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
13
+
14
+ team_a_name = Column(String(80), nullable=False)
15
+ team_b_name = Column(String(80), nullable=False)
16
+
17
+ overs_per_innings = Column(Integer, default=20)
18
+ status = Column(String(30), default="setup") # setup, live, completed
19
+ current_innings = Column(Integer, default=1)
20
+ batting_team = Column(String(1), nullable=True) # A or B
21
+
22
+ created_at = Column(DateTime, default=datetime.utcnow)
23
+ updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
24
+
25
+
26
+ class MatchPlayer(Base):
27
+ __tablename__ = "match_players"
28
+ __table_args__ = (UniqueConstraint("match_id", "user_id", name="uq_match_player"),)
29
+
30
+ id = Column(Integer, primary_key=True, index=True)
31
+ match_id = Column(Integer, ForeignKey("matches.id"), nullable=False, index=True)
32
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
33
+ team = Column(String(1), nullable=False) # A or B
34
+ is_captain = Column(Boolean, default=False)
35
+
36
+
37
+ class BallEvent(Base):
38
+ __tablename__ = "ball_events"
39
+
40
+ id = Column(Integer, primary_key=True, index=True)
41
+ match_id = Column(Integer, ForeignKey("matches.id"), nullable=False, index=True)
42
+
43
+ innings = Column(Integer, default=1)
44
+ over_number = Column(Integer, nullable=False)
45
+ ball_number = Column(Integer, nullable=False)
46
+
47
+ batting_team = Column(String(1), nullable=False) # A or B
48
+ striker_id = Column(Integer, ForeignKey("users.id"), nullable=True)
49
+ bowler_id = Column(Integer, ForeignKey("users.id"), nullable=True)
50
+
51
+ runs_off_bat = Column(Integer, default=0)
52
+ extras = Column(Integer, default=0)
53
+ extra_type = Column(String(30), nullable=True) # wide, no_ball, bye, leg_bye
54
+
55
+ is_wicket = Column(Boolean, default=False)
56
+ wicket_type = Column(String(50), nullable=True)
57
+
58
+ commentary = Column(String(300), nullable=True)
59
+
60
+ created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
61
+ created_at = Column(DateTime, default=datetime.utcnow)
backend/app/routes/__init__.py CHANGED
@@ -6,6 +6,7 @@ from app.routes.dashboard import router as dashboard_router
6
  from app.routes.admin import router as admin_router
7
  from app.routes.finance import router as finance_router
8
  from app.routes.notifications import router as notifications_router
 
9
 
10
  __all__ = [
11
  "auth_router",
@@ -16,4 +17,5 @@ __all__ = [
16
  "admin_router",
17
  "finance_router",
18
  "notifications_router",
 
19
  ]
 
6
  from app.routes.admin import router as admin_router
7
  from app.routes.finance import router as finance_router
8
  from app.routes.notifications import router as notifications_router
9
+ from app.routes.matches import router as matches_router
10
 
11
  __all__ = [
12
  "auth_router",
 
17
  "admin_router",
18
  "finance_router",
19
  "notifications_router",
20
+ "matches_router",
21
  ]
backend/app/routes/matches.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
11
+ MatchDetailResponse,
12
+ MatchPlayerView,
13
+ MatchResponse,
14
+ MatchScoreboardResponse,
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 build_scoreboard(db: Session, match_obj: Match, innings: int):
45
+ batting_team = match_obj.batting_team or "A"
46
+ events = (
47
+ db.query(BallEvent)
48
+ .filter(BallEvent.match_id == match_obj.id, BallEvent.innings == innings)
49
+ .order_by(BallEvent.created_at.asc())
50
+ .all()
51
+ )
52
+
53
+ total_runs = sum(event.runs_off_bat + event.extras for event in events)
54
+ wickets = sum(1 for event in events if event.is_wicket)
55
+ legal_balls = sum(1 for event in events if event.extra_type not in {"wide", "no_ball"})
56
+
57
+ completed_overs = legal_balls // 6
58
+ balls_in_current_over = legal_balls % 6
59
+ overs_display = f"{completed_overs}.{balls_in_current_over}"
60
+
61
+ recent_balls = []
62
+ for event in events[-18:]:
63
+ ball_text = f"{event.over_number}.{event.ball_number} "
64
+ if event.is_wicket:
65
+ ball_text += "W"
66
+ elif event.extra_type:
67
+ ball_text += f"{event.runs_off_bat + event.extras} ({event.extra_type})"
68
+ else:
69
+ ball_text += str(event.runs_off_bat)
70
+ recent_balls.append(ball_text)
71
+
72
+ return MatchScoreboardResponse(
73
+ match_id=match_obj.id,
74
+ innings=innings,
75
+ batting_team=batting_team,
76
+ total_runs=total_runs,
77
+ wickets=wickets,
78
+ legal_balls=legal_balls,
79
+ overs_display=overs_display,
80
+ recent_balls=recent_balls,
81
+ )
82
+
83
+
84
+ def get_next_delivery_position(db: Session, match_id: int, innings: int):
85
+ legal_balls = (
86
+ db.query(BallEvent)
87
+ .filter(BallEvent.match_id == match_id, BallEvent.innings == innings)
88
+ .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"])))
89
+ .count()
90
+ )
91
+
92
+ over_number = (legal_balls // 6) + 1
93
+ ball_number = (legal_balls % 6) + 1
94
+ return over_number, ball_number
95
+
96
+
97
+ @router.post("", response_model=MatchResponse)
98
+ async def create_match(
99
+ payload: MatchCreate,
100
+ current_user: User = Depends(get_current_user),
101
+ db: Session = Depends(get_db),
102
+ ):
103
+ ensure_premium_creator(db, current_user)
104
+
105
+ if payload.overs_per_innings <= 0:
106
+ raise HTTPException(status_code=400, detail="Overs must be greater than zero")
107
+
108
+ match_obj = Match(
109
+ title=payload.title.strip(),
110
+ created_by_id=current_user.id,
111
+ team_a_name=payload.team_a_name.strip(),
112
+ team_b_name=payload.team_b_name.strip(),
113
+ overs_per_innings=payload.overs_per_innings,
114
+ )
115
+ db.add(match_obj)
116
+ db.commit()
117
+ db.refresh(match_obj)
118
+
119
+ log_action("Created live match", user_id=current_user.id, details=match_obj.title)
120
+ return match_obj
121
+
122
+
123
+ @router.get("", response_model=list[MatchResponse])
124
+ async def list_matches(
125
+ db: Session = Depends(get_db),
126
+ current_user: User = Depends(get_current_user),
127
+ ):
128
+ _ = current_user
129
+ matches = db.query(Match).order_by(Match.created_at.desc()).limit(50).all()
130
+ return matches
131
+
132
+
133
+ @router.get("/{match_id}", response_model=MatchDetailResponse)
134
+ async def get_match(
135
+ match_id: int,
136
+ db: Session = Depends(get_db),
137
+ current_user: User = Depends(get_current_user),
138
+ ):
139
+ _ = current_user
140
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
141
+ if not match_obj:
142
+ raise HTTPException(status_code=404, detail="Match not found")
143
+
144
+ rows = (
145
+ db.query(MatchPlayer.user_id, MatchPlayer.team, User.name)
146
+ .join(User, User.id == MatchPlayer.user_id)
147
+ .filter(MatchPlayer.match_id == match_id)
148
+ .all()
149
+ )
150
+
151
+ team_a = []
152
+ team_b = []
153
+ for user_id, team, name in rows:
154
+ view = MatchPlayerView(user_id=user_id, team=team, name=name)
155
+ if team == "A":
156
+ team_a.append(view)
157
+ else:
158
+ team_b.append(view)
159
+
160
+ return MatchDetailResponse(
161
+ match=match_obj,
162
+ team_a_players=team_a,
163
+ team_b_players=team_b,
164
+ )
165
+
166
+
167
+ @router.post("/{match_id}/teams")
168
+ async def setup_match_teams(
169
+ match_id: int,
170
+ payload: MatchTeamSetupRequest,
171
+ current_user: User = Depends(get_current_user),
172
+ db: Session = Depends(get_db),
173
+ ):
174
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
175
+ if not match_obj:
176
+ raise HTTPException(status_code=404, detail="Match not found")
177
+
178
+ ensure_match_editor(match_obj, current_user)
179
+
180
+ if set(payload.team_a_player_ids).intersection(set(payload.team_b_player_ids)):
181
+ raise HTTPException(status_code=400, detail="Same player cannot exist in both teams")
182
+
183
+ all_player_ids = list(set(payload.team_a_player_ids + payload.team_b_player_ids))
184
+ if not all_player_ids:
185
+ raise HTTPException(status_code=400, detail="Select players for both teams")
186
+
187
+ valid_count = (
188
+ db.query(func.count(User.id))
189
+ .filter(User.id.in_(all_player_ids), User.is_active == True)
190
+ .scalar()
191
+ )
192
+ if valid_count != len(all_player_ids):
193
+ raise HTTPException(status_code=400, detail="One or more selected players are invalid")
194
+
195
+ db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).delete()
196
+
197
+ for player_id in payload.team_a_player_ids:
198
+ db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="A"))
199
+
200
+ for player_id in payload.team_b_player_ids:
201
+ db.add(MatchPlayer(match_id=match_id, user_id=player_id, team="B"))
202
+
203
+ db.commit()
204
+ log_action("Updated match teams", user_id=current_user.id, details=f"match_id={match_id}")
205
+
206
+ return {"message": "Teams updated"}
207
+
208
+
209
+ @router.post("/{match_id}/start", response_model=MatchResponse)
210
+ async def start_match(
211
+ match_id: int,
212
+ payload: MatchStartRequest,
213
+ current_user: User = Depends(get_current_user),
214
+ db: Session = Depends(get_db),
215
+ ):
216
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
217
+ if not match_obj:
218
+ raise HTTPException(status_code=404, detail="Match not found")
219
+
220
+ ensure_match_editor(match_obj, current_user)
221
+
222
+ batting_team = payload.batting_team.upper().strip()
223
+ if batting_team not in {"A", "B"}:
224
+ raise HTTPException(status_code=400, detail="batting_team must be A or B")
225
+
226
+ team_count = db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).count()
227
+ if team_count == 0:
228
+ raise HTTPException(status_code=400, detail="Please set teams first")
229
+
230
+ match_obj.status = "live"
231
+ match_obj.current_innings = 1
232
+ match_obj.batting_team = batting_team
233
+ db.commit()
234
+ db.refresh(match_obj)
235
+
236
+ log_action("Started match", user_id=current_user.id, details=f"match_id={match_id}")
237
+ return match_obj
238
+
239
+
240
+ @router.post("/{match_id}/ball")
241
+ async def record_ball_event(
242
+ match_id: int,
243
+ payload: BallEventCreate,
244
+ current_user: User = Depends(get_current_user),
245
+ db: Session = Depends(get_db),
246
+ ):
247
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
248
+ if not match_obj:
249
+ raise HTTPException(status_code=404, detail="Match not found")
250
+
251
+ ensure_match_editor(match_obj, current_user)
252
+
253
+ if match_obj.status != "live":
254
+ raise HTTPException(status_code=400, detail="Match is not live")
255
+
256
+ if payload.runs_off_bat < 0 or payload.extras < 0:
257
+ raise HTTPException(status_code=400, detail="Runs and extras cannot be negative")
258
+
259
+ if payload.batting_team not in {"A", "B"}:
260
+ raise HTTPException(status_code=400, detail="batting_team must be A or B")
261
+
262
+ auto_over_number, auto_ball_number = get_next_delivery_position(db, match_id, payload.innings)
263
+ legal_ball = payload.extra_type not in {"wide", "no_ball"}
264
+
265
+ # Enforce innings over limit for legal balls only
266
+ current_legal = (
267
+ db.query(BallEvent)
268
+ .filter(BallEvent.match_id == match_id, BallEvent.innings == payload.innings)
269
+ .filter(BallEvent.extra_type.is_(None) | (~BallEvent.extra_type.in_(["wide", "no_ball"])))
270
+ .count()
271
+ )
272
+ if legal_ball and current_legal >= (match_obj.overs_per_innings * 6):
273
+ raise HTTPException(status_code=400, detail="Innings overs limit reached")
274
+
275
+ event = BallEvent(
276
+ match_id=match_id,
277
+ innings=payload.innings,
278
+ over_number=auto_over_number,
279
+ ball_number=auto_ball_number,
280
+ batting_team=payload.batting_team,
281
+ striker_id=payload.striker_id,
282
+ bowler_id=payload.bowler_id,
283
+ runs_off_bat=payload.runs_off_bat,
284
+ extras=payload.extras,
285
+ extra_type=payload.extra_type,
286
+ is_wicket=payload.is_wicket,
287
+ wicket_type=payload.wicket_type,
288
+ commentary=payload.commentary,
289
+ created_by_id=current_user.id,
290
+ )
291
+
292
+ db.add(event)
293
+ db.commit()
294
+
295
+ scoreboard = build_scoreboard(db, match_obj, payload.innings)
296
+ next_over_number, next_ball_number = get_next_delivery_position(db, match_id, payload.innings)
297
+
298
+ return {
299
+ "message": "Ball recorded",
300
+ "recorded_ball": {
301
+ "over_number": auto_over_number,
302
+ "ball_number": auto_ball_number,
303
+ },
304
+ "next_ball": {
305
+ "over_number": next_over_number,
306
+ "ball_number": next_ball_number,
307
+ },
308
+ "scoreboard": scoreboard,
309
+ }
310
+
311
+
312
+ @router.get("/{match_id}/scoreboard", response_model=MatchScoreboardResponse)
313
+ async def get_match_scoreboard(
314
+ match_id: int,
315
+ innings: int = 1,
316
+ current_user: User = Depends(get_current_user),
317
+ db: Session = Depends(get_db),
318
+ ):
319
+ _ = current_user
320
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
321
+ if not match_obj:
322
+ raise HTTPException(status_code=404, detail="Match not found")
323
+
324
+ return build_scoreboard(db, match_obj, innings)
325
+
326
+
327
+ @router.post("/{match_id}/complete", response_model=MatchResponse)
328
+ async def complete_match(
329
+ match_id: int,
330
+ current_user: User = Depends(get_current_user),
331
+ db: Session = Depends(get_db),
332
+ ):
333
+ match_obj = db.query(Match).filter(Match.id == match_id).first()
334
+ if not match_obj:
335
+ raise HTTPException(status_code=404, detail="Match not found")
336
+
337
+ ensure_match_editor(match_obj, current_user)
338
+
339
+ match_obj.status = "completed"
340
+ db.commit()
341
+ db.refresh(match_obj)
342
+
343
+ log_action("Completed match", user_id=current_user.id, details=f"match_id={match_id}")
344
+ return match_obj
backend/app/schemas/__init__.py CHANGED
@@ -13,6 +13,17 @@ from app.schemas.performance import PerformanceLogCreate, PerformanceLogUpdate,
13
  from app.schemas.notification import NotificationResponse
14
  from app.schemas.finance import GuestFundRequest, ManualCreditRequest, FinanceTransactionResponse
15
  from app.schemas.chat import AdminChatCreate, AdminChatResponse
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  __all__ = [
18
  "UserRegister",
@@ -34,4 +45,13 @@ __all__ = [
34
  "FinanceTransactionResponse",
35
  "AdminChatCreate",
36
  "AdminChatResponse",
 
 
 
 
 
 
 
 
 
37
  ]
 
13
  from app.schemas.notification import NotificationResponse
14
  from app.schemas.finance import GuestFundRequest, ManualCreditRequest, FinanceTransactionResponse
15
  from app.schemas.chat import AdminChatCreate, AdminChatResponse
16
+ from app.schemas.match import (
17
+ MatchCreate,
18
+ MatchResponse,
19
+ MatchTeamSetupRequest,
20
+ MatchPlayerView,
21
+ MatchDetailResponse,
22
+ MatchStartRequest,
23
+ BallEventCreate,
24
+ BallEventResponse,
25
+ MatchScoreboardResponse,
26
+ )
27
 
28
  __all__ = [
29
  "UserRegister",
 
45
  "FinanceTransactionResponse",
46
  "AdminChatCreate",
47
  "AdminChatResponse",
48
+ "MatchCreate",
49
+ "MatchResponse",
50
+ "MatchTeamSetupRequest",
51
+ "MatchPlayerView",
52
+ "MatchDetailResponse",
53
+ "MatchStartRequest",
54
+ "BallEventCreate",
55
+ "BallEventResponse",
56
+ "MatchScoreboardResponse",
57
  ]
backend/app/schemas/match.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import List, Optional
3
+
4
+ from pydantic import BaseModel
5
+
6
+
7
+ class MatchCreate(BaseModel):
8
+ title: str
9
+ team_a_name: str
10
+ team_b_name: str
11
+ overs_per_innings: int = 20
12
+
13
+
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
21
+ status: str
22
+ current_innings: int
23
+ batting_team: Optional[str]
24
+ created_at: datetime
25
+
26
+ class Config:
27
+ from_attributes = True
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
+
40
+
41
+ class MatchDetailResponse(BaseModel):
42
+ match: MatchResponse
43
+ team_a_players: List[MatchPlayerView]
44
+ team_b_players: List[MatchPlayerView]
45
+
46
+
47
+ class MatchStartRequest(BaseModel):
48
+ batting_team: str # A or B
49
+
50
+
51
+ class BallEventCreate(BaseModel):
52
+ innings: int = 1
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
61
+ is_wicket: bool = False
62
+ wicket_type: Optional[str] = None
63
+ commentary: Optional[str] = None
64
+
65
+
66
+ class BallEventResponse(BaseModel):
67
+ id: int
68
+ innings: int
69
+ over_number: int
70
+ ball_number: int
71
+ batting_team: str
72
+ runs_off_bat: int
73
+ extras: int
74
+ extra_type: Optional[str]
75
+ is_wicket: bool
76
+ wicket_type: Optional[str]
77
+ commentary: Optional[str]
78
+ created_at: datetime
79
+
80
+ class Config:
81
+ from_attributes = True
82
+
83
+
84
+ class MatchScoreboardResponse(BaseModel):
85
+ match_id: int
86
+ innings: int
87
+ batting_team: str
88
+ total_runs: int
89
+ wickets: int
90
+ legal_balls: int
91
+ overs_display: str
92
+ recent_balls: List[str]
backend/load_test_data.py CHANGED
@@ -23,12 +23,6 @@ def load_test_data():
23
  db = SessionLocal()
24
 
25
  try:
26
- # Check if data already exists
27
- existing_users = db.query(User).count()
28
- if existing_users > 0:
29
- print("✓ Database already has data. Skipping test data load.")
30
- return
31
-
32
  print("📊 Loading test data...")
33
 
34
  # Create sample players
@@ -99,13 +93,63 @@ def load_test_data():
99
  "matches": 0,
100
  }
101
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
 
 
 
 
 
103
  for player_data in players:
 
 
104
  player = User(**player_data)
105
  db.add(player)
 
106
 
107
  db.commit()
108
- print(f"✓ Created {len(players)} sample players")
109
 
110
  # Add sample performance logs
111
  players = db.query(User).filter(User.role == "player").all()
 
23
  db = SessionLocal()
24
 
25
  try:
 
 
 
 
 
 
26
  print("📊 Loading test data...")
27
 
28
  # Create sample players
 
93
  "matches": 0,
94
  }
95
  ]
96
+
97
+ # Add 20 premium dummy players (mix of batsman and bowler)
98
+ premium_now = datetime.utcnow()
99
+ for i in range(1, 21):
100
+ is_batsman = i <= 10
101
+ players.append(
102
+ {
103
+ "name": f"Premium Player {i:02d}",
104
+ "email": f"premium{i:02d}@ssc.com",
105
+ "password": hash_password("password123"),
106
+ "jersey_number": 100 + i,
107
+ "bio": "Premium Batsman" if is_batsman else "Premium Bowler",
108
+ "runs": 1200 + (i * 45) if is_batsman else 320 + (i * 15),
109
+ "matches": 30 + i,
110
+ "wickets": 8 + (i % 6) if is_batsman else 55 + (i * 3),
111
+ "centuries": 2 + (i % 4) if is_batsman else 0,
112
+ "half_centuries": 6 + (i % 8) if is_batsman else 1 + (i % 3),
113
+ "highest_score": 95 + (i * 4) if is_batsman else 42 + (i % 10),
114
+ "is_premium": True,
115
+ "premium_start_date": premium_now,
116
+ "premium_expiry": premium_now + timedelta(days=30),
117
+ }
118
+ )
119
+
120
+ # Add 10 regular guest dummy players
121
+ for i in range(1, 11):
122
+ players.append(
123
+ {
124
+ "name": f"Guest Player {i:02d}",
125
+ "email": f"guest{i:02d}@ssc.com",
126
+ "password": hash_password("password123"),
127
+ "jersey_number": 200 + i,
128
+ "bio": "Guest Regular Player",
129
+ "runs": 140 + (i * 25),
130
+ "matches": 8 + i,
131
+ "wickets": 1 + (i % 4),
132
+ "centuries": 0,
133
+ "half_centuries": 0,
134
+ "highest_score": 28 + (i * 3),
135
+ "is_premium": False,
136
+ }
137
+ )
138
 
139
+ existing_emails = {
140
+ row[0] for row in db.query(User.email).all()
141
+ }
142
+ inserted_count = 0
143
+
144
  for player_data in players:
145
+ if player_data["email"] in existing_emails:
146
+ continue
147
  player = User(**player_data)
148
  db.add(player)
149
+ inserted_count += 1
150
 
151
  db.commit()
152
+ print(f"✓ Added {inserted_count} users (skipped existing emails)")
153
 
154
  # Add sample performance logs
155
  players = db.query(User).filter(User.role == "player").all()
backend/main.py CHANGED
@@ -14,6 +14,7 @@ from app.routes import (
14
  admin_router,
15
  finance_router,
16
  notifications_router,
 
17
  )
18
 
19
  # Initialize database
@@ -48,6 +49,7 @@ app.include_router(dashboard_router)
48
  app.include_router(admin_router)
49
  app.include_router(finance_router)
50
  app.include_router(notifications_router)
 
51
 
52
 
53
  @app.get("/")
 
14
  admin_router,
15
  finance_router,
16
  notifications_router,
17
+ matches_router,
18
  )
19
 
20
  # Initialize database
 
49
  app.include_router(admin_router)
50
  app.include_router(finance_router)
51
  app.include_router(notifications_router)
52
+ app.include_router(matches_router)
53
 
54
 
55
  @app.get("/")
backend/seed_dummy_users_sqlite.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ from datetime import UTC, datetime, timedelta
3
+
4
+ DB_PATH = "ssc.db"
5
+
6
+
7
+ def get_password_hash(cursor):
8
+ cursor.execute("SELECT password FROM users WHERE email = ? LIMIT 1", ("virat@ssc.com",))
9
+ row = cursor.fetchone()
10
+ if row and row[0]:
11
+ return row[0]
12
+
13
+ cursor.execute("SELECT password FROM users LIMIT 1")
14
+ row = cursor.fetchone()
15
+ if row and row[0]:
16
+ return row[0]
17
+
18
+ # Fallback only if table has no users yet
19
+ return "password123"
20
+
21
+
22
+ def user_exists(cursor, email):
23
+ cursor.execute("SELECT 1 FROM users WHERE email = ? LIMIT 1", (email,))
24
+ return cursor.fetchone() is not None
25
+
26
+
27
+ def insert_user(cursor, payload):
28
+ cursor.execute(
29
+ """
30
+ INSERT INTO users (
31
+ name, email, password, jersey_number, role, bio,
32
+ runs, matches, wickets, centuries, half_centuries,
33
+ average_runs, highest_score, is_premium,
34
+ premium_expiry, premium_start_date,
35
+ is_active, created_at, updated_at, last_login
36
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
37
+ """,
38
+ (
39
+ payload["name"],
40
+ payload["email"],
41
+ payload["password"],
42
+ payload["jersey_number"],
43
+ payload["role"],
44
+ payload["bio"],
45
+ payload["runs"],
46
+ payload["matches"],
47
+ payload["wickets"],
48
+ payload["centuries"],
49
+ payload["half_centuries"],
50
+ payload["average_runs"],
51
+ payload["highest_score"],
52
+ 1 if payload["is_premium"] else 0,
53
+ payload["premium_expiry"],
54
+ payload["premium_start_date"],
55
+ 1,
56
+ payload["created_at"],
57
+ payload["updated_at"],
58
+ None,
59
+ ),
60
+ )
61
+
62
+
63
+ def main():
64
+ conn = sqlite3.connect(DB_PATH)
65
+ cur = conn.cursor()
66
+
67
+ now = datetime.now(UTC).replace(microsecond=0)
68
+ now_text = now.isoformat(sep=" ")
69
+ premium_expiry_text = (now + timedelta(days=30)).isoformat(sep=" ")
70
+ shared_password_hash = get_password_hash(cur)
71
+
72
+ inserted_premium = 0
73
+ inserted_guest = 0
74
+
75
+ # 20 premium dummy players (10 batsmen + 10 bowlers)
76
+ for i in range(1, 21):
77
+ is_batsman = i <= 10
78
+ email = f"premium{i:02d}@ssc.com"
79
+ if user_exists(cur, email):
80
+ continue
81
+
82
+ runs = 1200 + (i * 45) if is_batsman else 320 + (i * 15)
83
+ matches = 30 + i
84
+ wickets = 8 + (i % 6) if is_batsman else 55 + (i * 3)
85
+ avg_runs = round(runs / matches, 2) if matches else 0.0
86
+
87
+ insert_user(
88
+ cur,
89
+ {
90
+ "name": f"Premium Player {i:02d}",
91
+ "email": email,
92
+ "password": shared_password_hash,
93
+ "jersey_number": 100 + i,
94
+ "role": "player",
95
+ "bio": "Premium Batsman" if is_batsman else "Premium Bowler",
96
+ "runs": runs,
97
+ "matches": matches,
98
+ "wickets": wickets,
99
+ "centuries": 2 + (i % 4) if is_batsman else 0,
100
+ "half_centuries": 6 + (i % 8) if is_batsman else 1 + (i % 3),
101
+ "average_runs": avg_runs,
102
+ "highest_score": 95 + (i * 4) if is_batsman else 42 + (i % 10),
103
+ "is_premium": True,
104
+ "premium_expiry": premium_expiry_text,
105
+ "premium_start_date": now_text,
106
+ "created_at": now_text,
107
+ "updated_at": now_text,
108
+ },
109
+ )
110
+ inserted_premium += 1
111
+
112
+ # 10 regular guest players
113
+ for i in range(1, 11):
114
+ email = f"guest{i:02d}@ssc.com"
115
+ if user_exists(cur, email):
116
+ continue
117
+
118
+ runs = 140 + (i * 25)
119
+ matches = 8 + i
120
+ avg_runs = round(runs / matches, 2)
121
+
122
+ insert_user(
123
+ cur,
124
+ {
125
+ "name": f"Guest Player {i:02d}",
126
+ "email": email,
127
+ "password": shared_password_hash,
128
+ "jersey_number": 200 + i,
129
+ "role": "player",
130
+ "bio": "Guest Regular Player",
131
+ "runs": runs,
132
+ "matches": matches,
133
+ "wickets": 1 + (i % 4),
134
+ "centuries": 0,
135
+ "half_centuries": 0,
136
+ "average_runs": avg_runs,
137
+ "highest_score": 28 + (i * 3),
138
+ "is_premium": False,
139
+ "premium_expiry": None,
140
+ "premium_start_date": None,
141
+ "created_at": now_text,
142
+ "updated_at": now_text,
143
+ },
144
+ )
145
+ inserted_guest += 1
146
+
147
+ conn.commit()
148
+
149
+ cur.execute("SELECT COUNT(*) FROM users WHERE email LIKE 'premium%@ssc.com' AND is_premium = 1")
150
+ total_premium = cur.fetchone()[0]
151
+ cur.execute("SELECT COUNT(*) FROM users WHERE email LIKE 'guest%@ssc.com' AND is_premium = 0")
152
+ total_guest = cur.fetchone()[0]
153
+
154
+ conn.close()
155
+
156
+ print(f"Inserted premium users: {inserted_premium}")
157
+ print(f"Inserted guest users: {inserted_guest}")
158
+ print(f"Total premium dummy users in DB: {total_premium}")
159
+ print(f"Total guest dummy users in DB: {total_guest}")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
frontend/package-lock.json CHANGED
@@ -53,6 +53,7 @@
53
  "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
54
  "dev": true,
55
  "license": "MIT",
 
56
  "dependencies": {
57
  "@babel/code-frame": "^7.29.0",
58
  "@babel/generator": "^7.29.0",
@@ -1342,6 +1343,7 @@
1342
  "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
1343
  "dev": true,
1344
  "license": "MIT",
 
1345
  "bin": {
1346
  "acorn": "bin/acorn"
1347
  },
@@ -1641,6 +1643,7 @@
1641
  }
1642
  ],
1643
  "license": "MIT",
 
1644
  "dependencies": {
1645
  "baseline-browser-mapping": "^2.9.0",
1646
  "caniuse-lite": "^1.0.30001759",
@@ -1757,6 +1760,7 @@
1757
  "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
1758
  "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
1759
  "license": "MIT",
 
1760
  "dependencies": {
1761
  "@kurkle/color": "^0.3.0"
1762
  },
@@ -2226,6 +2230,7 @@
2226
  "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
2227
  "dev": true,
2228
  "license": "MIT",
 
2229
  "dependencies": {
2230
  "@eslint-community/eslint-utils": "^4.2.0",
2231
  "@eslint-community/regexpp": "^4.6.1",
@@ -3960,6 +3965,7 @@
3960
  "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
3961
  "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
3962
  "license": "MIT",
 
3963
  "dependencies": {
3964
  "loose-envify": "^1.1.0"
3965
  },
@@ -3982,6 +3988,7 @@
3982
  "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
3983
  "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
3984
  "license": "MIT",
 
3985
  "dependencies": {
3986
  "loose-envify": "^1.1.0",
3987
  "scheduler": "^0.23.2"
@@ -4787,6 +4794,7 @@
4787
  "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
4788
  "dev": true,
4789
  "license": "MIT",
 
4790
  "dependencies": {
4791
  "esbuild": "^0.21.3",
4792
  "postcss": "^8.4.43",
 
53
  "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
54
  "dev": true,
55
  "license": "MIT",
56
+ "peer": true,
57
  "dependencies": {
58
  "@babel/code-frame": "^7.29.0",
59
  "@babel/generator": "^7.29.0",
 
1343
  "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
1344
  "dev": true,
1345
  "license": "MIT",
1346
+ "peer": true,
1347
  "bin": {
1348
  "acorn": "bin/acorn"
1349
  },
 
1643
  }
1644
  ],
1645
  "license": "MIT",
1646
+ "peer": true,
1647
  "dependencies": {
1648
  "baseline-browser-mapping": "^2.9.0",
1649
  "caniuse-lite": "^1.0.30001759",
 
1760
  "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
1761
  "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
1762
  "license": "MIT",
1763
+ "peer": true,
1764
  "dependencies": {
1765
  "@kurkle/color": "^0.3.0"
1766
  },
 
2230
  "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
2231
  "dev": true,
2232
  "license": "MIT",
2233
+ "peer": true,
2234
  "dependencies": {
2235
  "@eslint-community/eslint-utils": "^4.2.0",
2236
  "@eslint-community/regexpp": "^4.6.1",
 
3965
  "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
3966
  "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
3967
  "license": "MIT",
3968
+ "peer": true,
3969
  "dependencies": {
3970
  "loose-envify": "^1.1.0"
3971
  },
 
3988
  "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
3989
  "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
3990
  "license": "MIT",
3991
+ "peer": true,
3992
  "dependencies": {
3993
  "loose-envify": "^1.1.0",
3994
  "scheduler": "^0.23.2"
 
4794
  "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
4795
  "dev": true,
4796
  "license": "MIT",
4797
+ "peer": true,
4798
  "dependencies": {
4799
  "esbuild": "^0.21.3",
4800
  "postcss": "^8.4.43",
frontend/src/App.jsx CHANGED
@@ -8,10 +8,12 @@ import { PlayersPage } from './pages/Players';
8
  import { ProfilePage } from './pages/Profile';
9
  import { FinancePage } from './pages/Finance';
10
  import { AdminPage } from './pages/Admin';
 
11
 
12
  function App() {
13
  const [isAuthenticated, setIsAuthenticated] = useState(false);
14
  const [user, setUser] = useState(null);
 
15
  const isAdmin = user?.role === 'admin';
16
 
17
  const updateAuthState = () => {
@@ -29,7 +31,9 @@ function App() {
29
  };
30
 
31
  useEffect(() => {
 
32
  updateAuthState();
 
33
 
34
  // Listen for auth changes (login, logout)
35
  const handleAuthChange = () => {
@@ -45,14 +49,18 @@ function App() {
45
  };
46
  }, []);
47
 
 
 
 
 
48
  return (
49
  <BrowserRouter>
50
  <Navbar isAuthenticated={isAuthenticated} user={user} />
51
  <Routes>
52
  {/* Public Routes */}
53
  <Route path="/" element={<HomePage />} />
54
- <Route path="/login" element={<LoginPage />} />
55
- <Route path="/register" element={<RegisterPage />} />
56
 
57
  {/* Protected Routes */}
58
  {isAuthenticated ? (
@@ -62,6 +70,7 @@ function App() {
62
  <Route path="/profile" element={<ProfilePage />} />
63
  <Route path="/player/:playerId" element={<ProfilePage />} />
64
  <Route path="/finance" element={<FinancePage />} />
 
65
  <Route path="/admin" element={isAdmin ? <AdminPage /> : <Navigate to="/dashboard" />} />
66
  </>
67
  ) : (
@@ -70,6 +79,7 @@ function App() {
70
  <Route path="/players" element={<Navigate to="/login" />} />
71
  <Route path="/profile" element={<Navigate to="/login" />} />
72
  <Route path="/finance" element={<Navigate to="/login" />} />
 
73
  <Route path="/admin" element={<Navigate to="/login" />} />
74
  </>
75
  )}
 
8
  import { ProfilePage } from './pages/Profile';
9
  import { FinancePage } from './pages/Finance';
10
  import { AdminPage } from './pages/Admin';
11
+ import { MatchesPage } from './pages/Matches';
12
 
13
  function App() {
14
  const [isAuthenticated, setIsAuthenticated] = useState(false);
15
  const [user, setUser] = useState(null);
16
+ const [isLoading, setIsLoading] = useState(true);
17
  const isAdmin = user?.role === 'admin';
18
 
19
  const updateAuthState = () => {
 
31
  };
32
 
33
  useEffect(() => {
34
+ // Initial auth check from localStorage
35
  updateAuthState();
36
+ setIsLoading(false);
37
 
38
  // Listen for auth changes (login, logout)
39
  const handleAuthChange = () => {
 
49
  };
50
  }, []);
51
 
52
+ if (isLoading) {
53
+ return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>Loading...</div>;
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 ? (
 
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
  ) : (
 
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
  )}
frontend/src/components/Navbar.jsx CHANGED
@@ -24,6 +24,7 @@ export function Navbar({ isAuthenticated, user }) {
24
  <>
25
  <Link to="/dashboard">Dashboard</Link>
26
  <Link to="/players">Players</Link>
 
27
  <Link to="/profile">Profile</Link>
28
  <Link to="/finance">Finance</Link>
29
  {user?.role === 'admin' && (
 
24
  <>
25
  <Link to="/dashboard">Dashboard</Link>
26
  <Link to="/players">Players</Link>
27
+ <Link to="/matches">Matches</Link>
28
  <Link to="/profile">Profile</Link>
29
  <Link to="/finance">Finance</Link>
30
  {user?.role === 'admin' && (
frontend/src/components/navbar.module.css CHANGED
@@ -49,12 +49,25 @@
49
  }
50
 
51
  .register {
52
- background-color: #ffb63a;
53
- color: #173f39;
54
- padding: 6px 16px;
55
- border-radius: 999px;
56
  text-decoration: none !important;
57
- font-weight: 700;
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  }
59
 
60
  .logout {
 
49
  }
50
 
51
  .register {
52
+ background-color: #ffa500 !important;
53
+ color: white !important;
54
+ padding: 8px 18px !important;
55
+ border-radius: 999px !important;
56
  text-decoration: none !important;
57
+ font-weight: 700 !important;
58
+ border: none !important;
59
+ cursor: pointer !important;
60
+ transition: all 0.3s ease !important;
61
+ box-shadow: 0 2px 8px rgba(255, 165, 0, 0.3) !important;
62
+ display: inline-block !important;
63
+ line-height: 1.2 !important;
64
+ vertical-align: middle !important;
65
+ }
66
+
67
+ .register:hover {
68
+ background-color: #ff8c00;
69
+ transform: translateY(-2px);
70
+ box-shadow: 0 4px 12px rgba(255, 165, 0, 0.4);
71
  }
72
 
73
  .logout {
frontend/src/pages/Home.jsx CHANGED
@@ -11,7 +11,7 @@ export function HomePage() {
11
  <p>Sculpt Soft Cricketers platform for performance, finances, match history, and smart club operations.</p>
12
  <div className={styles.buttons}>
13
  <Link to="/register" className={styles.primaryBtn}>
14
- Get Started
15
  </Link>
16
  <Link to="/login" className={styles.secondaryBtn}>
17
  Login
 
11
  <p>Sculpt Soft Cricketers platform for performance, finances, match history, and smart club operations.</p>
12
  <div className={styles.buttons}>
13
  <Link to="/register" className={styles.primaryBtn}>
14
+ Register
15
  </Link>
16
  <Link to="/login" className={styles.secondaryBtn}>
17
  Login
frontend/src/pages/Matches.jsx ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import { matchesService, playerService } from '../utils/api';
3
+ import styles from './matches.module.css';
4
+
5
+ export function MatchesPage() {
6
+ const inningsOptions = [1, 2];
7
+ const runOptions = [0, 1, 2, 3, 4, 5, 6];
8
+ const wicketTypeOptions = ['bowled', 'caught', 'lbw', 'run out', 'stumped', 'hit wicket', 'retired out'];
9
+
10
+ const [currentStep, setCurrentStep] = useState(1);
11
+ const [matches, setMatches] = useState([]);
12
+ const [players, setPlayers] = useState([]);
13
+ const [selectedMatchId, setSelectedMatchId] = useState(null);
14
+ const [selectedMatch, setSelectedMatch] = useState(null);
15
+ const [scoreboard, setScoreboard] = useState(null);
16
+ const [message, setMessage] = useState('');
17
+ const [error, setError] = useState('');
18
+
19
+ const [createForm, setCreateForm] = useState({
20
+ title: '',
21
+ team_a_name: 'Team A',
22
+ team_b_name: 'Team B',
23
+ overs_per_innings: 20,
24
+ });
25
+
26
+ const [teamAIds, setTeamAIds] = useState([]);
27
+ const [teamBIds, setTeamBIds] = useState([]);
28
+ const [teamSource, setTeamSource] = useState('new');
29
+ const [previousMatchId, setPreviousMatchId] = useState('');
30
+
31
+ const [ballForm, setBallForm] = useState({
32
+ innings: 1,
33
+ over_number: 1,
34
+ ball_number: 1,
35
+ batting_team: 'A',
36
+ striker_id: '',
37
+ bowler_id: '',
38
+ runs_off_bat: 0,
39
+ extras: 0,
40
+ extra_type: '',
41
+ is_wicket: false,
42
+ wicket_type: '',
43
+ commentary: '',
44
+ });
45
+
46
+ const user = useMemo(() => {
47
+ try {
48
+ return JSON.parse(localStorage.getItem('user') || '{}');
49
+ } catch (_err) {
50
+ return {};
51
+ }
52
+ }, []);
53
+
54
+ const canCreateMatch = !!user?.is_premium || user?.role === 'admin';
55
+
56
+ const fetchBase = async () => {
57
+ try {
58
+ const [matchRes, playerRes] = await Promise.all([
59
+ matchesService.listMatches(),
60
+ playerService.getAllPlayers(0, 200),
61
+ ]);
62
+ setMatches(matchRes.data || []);
63
+ setPlayers((playerRes.data || []).filter((p) => p.role === 'player'));
64
+ } catch (err) {
65
+ setError(err.response?.data?.detail || 'Failed to load match data');
66
+ }
67
+ };
68
+
69
+ const fetchMatchDetail = async (matchId) => {
70
+ if (!matchId) {
71
+ setSelectedMatch(null);
72
+ setScoreboard(null);
73
+ return;
74
+ }
75
+
76
+ try {
77
+ const [detailRes, scoreRes] = await Promise.all([
78
+ matchesService.getMatch(matchId),
79
+ matchesService.getScoreboard(matchId, 1),
80
+ ]);
81
+ setSelectedMatch(detailRes.data);
82
+ setScoreboard(scoreRes.data);
83
+
84
+ setTeamAIds((detailRes.data?.team_a_players || []).map((p) => String(p.user_id)));
85
+ setTeamBIds((detailRes.data?.team_b_players || []).map((p) => String(p.user_id)));
86
+
87
+ setError('');
88
+ } catch (err) {
89
+ setError(err.response?.data?.detail || 'Failed to load selected match');
90
+ }
91
+ };
92
+
93
+ useEffect(() => {
94
+ fetchBase();
95
+ }, []);
96
+
97
+ useEffect(() => {
98
+ fetchMatchDetail(selectedMatchId);
99
+ }, [selectedMatchId]);
100
+
101
+ useEffect(() => {
102
+ if (!selectedMatchId || currentStep !== 3) {
103
+ return;
104
+ }
105
+
106
+ const timer = setInterval(() => {
107
+ matchesService
108
+ .getScoreboard(selectedMatchId, 1)
109
+ .then((res) => setScoreboard(res.data))
110
+ .catch(() => null);
111
+ }, 2000);
112
+
113
+ return () => clearInterval(timer);
114
+ }, [selectedMatchId, currentStep]);
115
+
116
+ const handleSelectMatch = (match) => {
117
+ setSelectedMatchId(match.id);
118
+ setCurrentStep(match.status === 'setup' ? 2 : 3);
119
+ };
120
+
121
+ const handleCreateMatch = async (e) => {
122
+ e.preventDefault();
123
+ setError('');
124
+ setMessage('');
125
+
126
+ try {
127
+ const payload = {
128
+ ...createForm,
129
+ overs_per_innings: Number(createForm.overs_per_innings),
130
+ };
131
+ const res = await matchesService.createMatch(payload);
132
+ setMessage('Match created successfully');
133
+ setCreateForm({ title: '', team_a_name: 'Team A', team_b_name: 'Team B', overs_per_innings: 20 });
134
+ await fetchBase();
135
+ setSelectedMatchId(res.data.id);
136
+ setCurrentStep(2);
137
+ } catch (err) {
138
+ setError(err.response?.data?.detail || 'Could not create match');
139
+ }
140
+ };
141
+
142
+ const handleApplyPreviousTeams = async () => {
143
+ if (!previousMatchId) {
144
+ setError('Select a previous match first');
145
+ return;
146
+ }
147
+
148
+ try {
149
+ const detailRes = await matchesService.getMatch(Number(previousMatchId));
150
+ const prevTeamA = (detailRes.data?.team_a_players || []).map((p) => String(p.user_id));
151
+ const prevTeamB = (detailRes.data?.team_b_players || []).map((p) => String(p.user_id));
152
+
153
+ if (prevTeamA.length === 0 && prevTeamB.length === 0) {
154
+ setError('Selected match has no teams configured');
155
+ return;
156
+ }
157
+
158
+ setTeamAIds(prevTeamA);
159
+ setTeamBIds(prevTeamB);
160
+ setMessage('Previous teams loaded. Save teams to apply to this match.');
161
+ setError('');
162
+ } catch (err) {
163
+ setError(err.response?.data?.detail || 'Could not load previous match teams');
164
+ }
165
+ };
166
+
167
+ const handleTeamSetup = async () => {
168
+ if (!selectedMatchId) {
169
+ return;
170
+ }
171
+
172
+ setError('');
173
+ setMessage('');
174
+
175
+ try {
176
+ await matchesService.setupTeams(selectedMatchId, {
177
+ team_a_player_ids: teamAIds.map(Number),
178
+ team_b_player_ids: teamBIds.map(Number),
179
+ });
180
+ setMessage('Teams saved');
181
+ await fetchMatchDetail(selectedMatchId);
182
+ } catch (err) {
183
+ setError(err.response?.data?.detail || 'Failed to save teams');
184
+ }
185
+ };
186
+
187
+ const handleStartMatch = async () => {
188
+ if (!selectedMatchId) {
189
+ return;
190
+ }
191
+
192
+ setError('');
193
+ setMessage('');
194
+
195
+ try {
196
+ await matchesService.startMatch(selectedMatchId, { batting_team: ballForm.batting_team });
197
+ setMessage('Match started');
198
+ await fetchMatchDetail(selectedMatchId);
199
+ setCurrentStep(3);
200
+ } catch (err) {
201
+ setError(err.response?.data?.detail || 'Failed to start match');
202
+ }
203
+ };
204
+
205
+ const handleBallSubmit = async (e) => {
206
+ e.preventDefault();
207
+ if (!selectedMatchId) {
208
+ return;
209
+ }
210
+
211
+ setError('');
212
+ setMessage('');
213
+
214
+ try {
215
+ const res = await matchesService.recordBall(selectedMatchId, {
216
+ ...ballForm,
217
+ innings: Number(ballForm.innings),
218
+ over_number: Number(ballForm.over_number),
219
+ ball_number: Number(ballForm.ball_number),
220
+ striker_id: ballForm.striker_id ? Number(ballForm.striker_id) : null,
221
+ bowler_id: ballForm.bowler_id ? Number(ballForm.bowler_id) : null,
222
+ runs_off_bat: Number(ballForm.runs_off_bat),
223
+ extras: Number(ballForm.extras),
224
+ extra_type: ballForm.extra_type || null,
225
+ wicket_type: ballForm.wicket_type || null,
226
+ commentary: ballForm.commentary || null,
227
+ });
228
+
229
+ setMessage('Ball updated');
230
+ await fetchMatchDetail(selectedMatchId);
231
+
232
+ const nextOver = res.data?.next_ball?.over_number;
233
+ const nextBall = res.data?.next_ball?.ball_number;
234
+
235
+ setBallForm((prev) => ({
236
+ ...prev,
237
+ over_number: nextOver || prev.over_number,
238
+ ball_number: nextBall || prev.ball_number,
239
+ commentary: '',
240
+ is_wicket: false,
241
+ wicket_type: '',
242
+ runs_off_bat: 0,
243
+ extras: 0,
244
+ }));
245
+ } catch (err) {
246
+ setError(err.response?.data?.detail || 'Could not record ball');
247
+ }
248
+ };
249
+
250
+ const teamAOptions = players.filter((p) => !teamBIds.includes(String(p.id)));
251
+ const teamBOptions = players.filter((p) => !teamAIds.includes(String(p.id)));
252
+ const reusableMatches = matches.filter((m) => m.id !== selectedMatchId);
253
+
254
+ return (
255
+ <div className={styles.page}>
256
+ <div className={styles.container}>
257
+ <h1>Live Match Center</h1>
258
+ <p className={styles.subtitle}>Premium creators can set teams and track ball-by-ball scoring in real time.</p>
259
+
260
+ <div className={styles.steps}>
261
+ <button
262
+ type="button"
263
+ className={`${styles.stepBtn} ${currentStep === 1 ? styles.stepActive : ''}`}
264
+ onClick={() => setCurrentStep(1)}
265
+ >
266
+ 1. Match
267
+ </button>
268
+ <button
269
+ type="button"
270
+ className={`${styles.stepBtn} ${currentStep === 2 ? styles.stepActive : ''}`}
271
+ onClick={() => selectedMatchId && setCurrentStep(2)}
272
+ disabled={!selectedMatchId}
273
+ >
274
+ 2. Teams
275
+ </button>
276
+ <button
277
+ type="button"
278
+ className={`${styles.stepBtn} ${currentStep === 3 ? styles.stepActive : ''}`}
279
+ onClick={() => selectedMatchId && setCurrentStep(3)}
280
+ disabled={!selectedMatchId}
281
+ >
282
+ 3. Live Scoring
283
+ </button>
284
+ </div>
285
+
286
+ {error && <div className={styles.error}>{error}</div>}
287
+ {message && <div className={styles.message}>{message}</div>}
288
+
289
+ {currentStep === 1 && (
290
+ <section className={styles.card}>
291
+ <h2>Create Match</h2>
292
+ {!canCreateMatch && <p className={styles.note}>Only premium players can create matches.</p>}
293
+ <form onSubmit={handleCreateMatch}>
294
+ <input
295
+ placeholder="Match title"
296
+ value={createForm.title}
297
+ onChange={(e) => setCreateForm((p) => ({ ...p, title: e.target.value }))}
298
+ disabled={!canCreateMatch}
299
+ required
300
+ />
301
+ <input
302
+ placeholder="Team A name"
303
+ value={createForm.team_a_name}
304
+ onChange={(e) => setCreateForm((p) => ({ ...p, team_a_name: e.target.value }))}
305
+ disabled={!canCreateMatch}
306
+ required
307
+ />
308
+ <input
309
+ placeholder="Team B name"
310
+ value={createForm.team_b_name}
311
+ onChange={(e) => setCreateForm((p) => ({ ...p, team_b_name: e.target.value }))}
312
+ disabled={!canCreateMatch}
313
+ required
314
+ />
315
+ <input
316
+ type="number"
317
+ min="1"
318
+ max="50"
319
+ value={createForm.overs_per_innings}
320
+ onChange={(e) => setCreateForm((p) => ({ ...p, overs_per_innings: e.target.value }))}
321
+ disabled={!canCreateMatch}
322
+ required
323
+ />
324
+ <button type="submit" disabled={!canCreateMatch}>Create Match</button>
325
+ </form>
326
+
327
+ <h3 className={styles.sectionTitle}>All Matches</h3>
328
+ <div className={styles.matchList}>
329
+ {matches.map((match) => (
330
+ <button
331
+ key={match.id}
332
+ className={`${styles.matchItem} ${selectedMatchId === match.id ? styles.active : ''}`}
333
+ onClick={() => handleSelectMatch(match)}
334
+ >
335
+ <strong>{match.title}</strong>
336
+ <span>{match.team_a_name} vs {match.team_b_name}</span>
337
+ <small>{match.status}</small>
338
+ </button>
339
+ ))}
340
+ {matches.length === 0 && <p>No matches yet.</p>}
341
+ </div>
342
+
343
+ {selectedMatchId && (
344
+ <div className={styles.rowButtons}>
345
+ <button type="button" onClick={() => setCurrentStep(2)}>Continue to Team Setup</button>
346
+ </div>
347
+ )}
348
+ </section>
349
+ )}
350
+
351
+ {currentStep === 2 && (
352
+ <section className={styles.card}>
353
+ <h2>Match Setup</h2>
354
+ {!selectedMatch && <p>Select a match to setup teams and scoring.</p>}
355
+ {selectedMatch && (
356
+ <>
357
+ <p className={styles.note}>{selectedMatch.match.team_a_name} vs {selectedMatch.match.team_b_name}</p>
358
+
359
+ <div className={styles.teamSourceRow}>
360
+ <label>
361
+ <input
362
+ type="radio"
363
+ name="teamSource"
364
+ value="new"
365
+ checked={teamSource === 'new'}
366
+ onChange={() => setTeamSource('new')}
367
+ />
368
+ Create new teams
369
+ </label>
370
+ <label>
371
+ <input
372
+ type="radio"
373
+ name="teamSource"
374
+ value="previous"
375
+ checked={teamSource === 'previous'}
376
+ onChange={() => setTeamSource('previous')}
377
+ />
378
+ Use previous match teams
379
+ </label>
380
+ </div>
381
+
382
+ {teamSource === 'previous' && (
383
+ <div className={styles.previousBox}>
384
+ <select
385
+ value={previousMatchId}
386
+ onChange={(e) => setPreviousMatchId(e.target.value)}
387
+ >
388
+ <option value="">Select previous match</option>
389
+ {reusableMatches.map((m) => (
390
+ <option key={m.id} value={m.id}>
391
+ {m.title} ({m.team_a_name} vs {m.team_b_name})
392
+ </option>
393
+ ))}
394
+ </select>
395
+ <button type="button" onClick={handleApplyPreviousTeams}>Load Previous Teams</button>
396
+ </div>
397
+ )}
398
+
399
+ <div className={styles.teamSetup}>
400
+ <div>
401
+ <label>Team A Players</label>
402
+ <select
403
+ multiple
404
+ value={teamAIds}
405
+ onChange={(e) => setTeamAIds(Array.from(e.target.selectedOptions).map((o) => o.value))}
406
+ >
407
+ {teamAOptions.map((p) => (
408
+ <option key={p.id} value={p.id}>{p.name}</option>
409
+ ))}
410
+ </select>
411
+ </div>
412
+ <div>
413
+ <label>Team B Players</label>
414
+ <select
415
+ multiple
416
+ value={teamBIds}
417
+ onChange={(e) => setTeamBIds(Array.from(e.target.selectedOptions).map((o) => o.value))}
418
+ >
419
+ {teamBOptions.map((p) => (
420
+ <option key={p.id} value={p.id}>{p.name}</option>
421
+ ))}
422
+ </select>
423
+ </div>
424
+ </div>
425
+
426
+ <div className={styles.rowButtons}>
427
+ <button type="button" onClick={() => setCurrentStep(1)}>Back</button>
428
+ <button type="button" onClick={handleTeamSetup}>Save Teams</button>
429
+ <button type="button" onClick={handleStartMatch}>Start Match</button>
430
+ </div>
431
+ </>
432
+ )}
433
+ </section>
434
+ )}
435
+
436
+ {currentStep === 3 && (
437
+ <section className={styles.card}>
438
+ <h2>Ball by Ball (Umpire Panel)</h2>
439
+ {!selectedMatch && <p>Select a match from step 1 first.</p>}
440
+ {selectedMatch && (
441
+ <>
442
+ <div className={styles.umpireGuide}>
443
+ <h3>Quick Guide</h3>
444
+ <div className={styles.guideGrid}>
445
+ <p><strong>Innings:</strong> 1 for first innings, 2 for second innings.</p>
446
+ <p><strong>Over/Ball:</strong> Auto-generated by system after each ball.</p>
447
+ <p><strong>Runs:</strong> Runs scored from bat on that ball.</p>
448
+ <p><strong>Extras:</strong> Extra runs (wide/no-ball/bye/leg bye).</p>
449
+ <p><strong>Wicket:</strong> Tick if wicket fell on this ball.</p>
450
+ <p><strong>Commentary:</strong> Short note like "Cover drive for four".</p>
451
+ </div>
452
+ </div>
453
+
454
+ <form onSubmit={handleBallSubmit}>
455
+ <div className={styles.formRow}>
456
+ <div className={styles.fieldGroup}>
457
+ <label className={styles.fieldLabel}>Innings</label>
458
+ <select
459
+ value={ballForm.innings}
460
+ onChange={(e) => setBallForm((p) => ({ ...p, innings: e.target.value }))}
461
+ >
462
+ {inningsOptions.map((opt) => (
463
+ <option key={opt} value={opt}>{opt}</option>
464
+ ))}
465
+ </select>
466
+ </div>
467
+ <div className={styles.fieldGroup}>
468
+ <label className={styles.fieldLabel}>Over Number</label>
469
+ <input
470
+ type="number"
471
+ min="1"
472
+ value={ballForm.over_number}
473
+ readOnly
474
+ />
475
+ </div>
476
+ <div className={styles.fieldGroup}>
477
+ <label className={styles.fieldLabel}>Ball Number (1-6)</label>
478
+ <input
479
+ type="number"
480
+ min="1"
481
+ max="6"
482
+ value={ballForm.ball_number}
483
+ readOnly
484
+ />
485
+ </div>
486
+ <div className={styles.fieldGroup}>
487
+ <label className={styles.fieldLabel}>Batting Team</label>
488
+ <select
489
+ value={ballForm.batting_team}
490
+ onChange={(e) => setBallForm((p) => ({ ...p, batting_team: e.target.value }))}
491
+ >
492
+ <option value="A">Batting Team A</option>
493
+ <option value="B">Batting Team B</option>
494
+ </select>
495
+ </div>
496
+ </div>
497
+
498
+ <div className={styles.formRow}>
499
+ <div className={styles.fieldGroup}>
500
+ <label className={styles.fieldLabel}>Runs Off Bat</label>
501
+ <select
502
+ value={ballForm.runs_off_bat}
503
+ onChange={(e) => setBallForm((p) => ({ ...p, runs_off_bat: e.target.value }))}
504
+ >
505
+ {runOptions.map((opt) => (
506
+ <option key={opt} value={opt}>{opt}</option>
507
+ ))}
508
+ </select>
509
+ </div>
510
+ <div className={styles.fieldGroup}>
511
+ <label className={styles.fieldLabel}>Extras</label>
512
+ <select
513
+ value={ballForm.extras}
514
+ onChange={(e) => setBallForm((p) => ({ ...p, extras: e.target.value }))}
515
+ >
516
+ {runOptions.map((opt) => (
517
+ <option key={opt} value={opt}>{opt}</option>
518
+ ))}
519
+ </select>
520
+ </div>
521
+ <div className={styles.fieldGroup}>
522
+ <label className={styles.fieldLabel}>Extra Type</label>
523
+ <select
524
+ value={ballForm.extra_type}
525
+ onChange={(e) => setBallForm((p) => ({ ...p, extra_type: e.target.value }))}
526
+ >
527
+ <option value="">No Extra Type</option>
528
+ <option value="wide">Wide</option>
529
+ <option value="no_ball">No Ball</option>
530
+ <option value="bye">Bye</option>
531
+ <option value="leg_bye">Leg Bye</option>
532
+ </select>
533
+ </div>
534
+ <div className={styles.fieldGroup}>
535
+ <label className={styles.fieldLabel}>Wicket On This Ball?</label>
536
+ <label className={styles.wicketCheck}>
537
+ <input
538
+ type="checkbox"
539
+ checked={ballForm.is_wicket}
540
+ onChange={(e) => setBallForm((p) => ({ ...p, is_wicket: e.target.checked }))}
541
+ />
542
+ Yes, wicket fell
543
+ </label>
544
+ </div>
545
+ </div>
546
+
547
+ {ballForm.is_wicket && (
548
+ <div className={styles.fieldGroup}>
549
+ <label className={styles.fieldLabel}>Wicket Type</label>
550
+ <select
551
+ value={ballForm.wicket_type}
552
+ onChange={(e) => setBallForm((p) => ({ ...p, wicket_type: e.target.value }))}
553
+ >
554
+ <option value="">Select Wicket Type</option>
555
+ {wicketTypeOptions.map((opt) => (
556
+ <option key={opt} value={opt}>{opt}</option>
557
+ ))}
558
+ </select>
559
+ </div>
560
+ )}
561
+
562
+ <div className={styles.fieldGroup}>
563
+ <label className={styles.fieldLabel}>Ball Commentary</label>
564
+ <input
565
+ placeholder="Short comment for this ball"
566
+ value={ballForm.commentary}
567
+ onChange={(e) => setBallForm((p) => ({ ...p, commentary: e.target.value }))}
568
+ />
569
+ </div>
570
+
571
+ <div className={styles.rowButtons}>
572
+ <button type="button" onClick={() => setCurrentStep(2)}>Back</button>
573
+ <button type="submit">Record Ball</button>
574
+ </div>
575
+ </form>
576
+
577
+ <h3 className={styles.sectionTitle}>Live Scoreboard</h3>
578
+ {!scoreboard && <p>Select a match to view live score.</p>}
579
+ {scoreboard && (
580
+ <div className={styles.scoreboard}>
581
+ <h3>{selectedMatch?.match?.title}</h3>
582
+ <p className={styles.bigScore}>
583
+ {scoreboard.total_runs}/{scoreboard.wickets}
584
+ </p>
585
+ <p>Overs: {scoreboard.overs_display}</p>
586
+ <p>
587
+ Batting Team: {scoreboard.batting_team === 'A' ? selectedMatch?.match?.team_a_name : selectedMatch?.match?.team_b_name}
588
+ </p>
589
+
590
+ <h4>Recent Balls</h4>
591
+ <div className={styles.ballStrip}>
592
+ {scoreboard.recent_balls.map((ball, idx) => (
593
+ <span key={`${ball}-${idx}`}>{ball}</span>
594
+ ))}
595
+ {scoreboard.recent_balls.length === 0 && <span>No balls recorded yet</span>}
596
+ </div>
597
+ </div>
598
+ )}
599
+ </>
600
+ )}
601
+ </section>
602
+ )}
603
+ </div>
604
+ </div>
605
+ );
606
+ }
frontend/src/pages/matches.module.css ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .page {
2
+ min-height: calc(100vh - 74px);
3
+ background: #eef4f3;
4
+ color: #173a36;
5
+ padding: 24px 16px 40px;
6
+ }
7
+
8
+ .container {
9
+ max-width: 1260px;
10
+ margin: 0 auto;
11
+ }
12
+
13
+ .subtitle {
14
+ margin-top: 4px;
15
+ color: #476b67;
16
+ }
17
+
18
+ .steps {
19
+ margin-top: 16px;
20
+ display: flex;
21
+ gap: 8px;
22
+ flex-wrap: wrap;
23
+ }
24
+
25
+ .stepBtn {
26
+ border: 1px solid #bcd7d2;
27
+ background: #f4faf8;
28
+ color: #24554e;
29
+ border-radius: 999px;
30
+ padding: 8px 14px;
31
+ cursor: pointer;
32
+ font-weight: 700;
33
+ }
34
+
35
+ .stepBtn:disabled {
36
+ opacity: 0.55;
37
+ cursor: not-allowed;
38
+ }
39
+
40
+ .stepActive {
41
+ background: #0f6f62;
42
+ color: #ffffff;
43
+ border-color: #0f6f62;
44
+ }
45
+
46
+ .card {
47
+ margin-top: 16px;
48
+ background: #ffffff;
49
+ border-radius: 16px;
50
+ border: 1px solid #d8e7e4;
51
+ padding: 16px;
52
+ box-shadow: 0 8px 20px rgba(11, 46, 41, 0.08);
53
+ }
54
+
55
+ .card h2 {
56
+ margin: 0 0 10px;
57
+ }
58
+
59
+ .card h3 {
60
+ margin: 10px 0;
61
+ }
62
+
63
+ .card form {
64
+ display: flex;
65
+ flex-direction: column;
66
+ gap: 10px;
67
+ }
68
+
69
+ .card input,
70
+ .card select,
71
+ .card button {
72
+ padding: 10px 12px;
73
+ border-radius: 10px;
74
+ border: 1px solid #bdd8d3;
75
+ font-size: 14px;
76
+ }
77
+
78
+ .card button {
79
+ background: #0f6f62;
80
+ color: white;
81
+ font-weight: 700;
82
+ border: none;
83
+ cursor: pointer;
84
+ }
85
+
86
+ .card button:disabled {
87
+ opacity: 0.5;
88
+ cursor: not-allowed;
89
+ }
90
+
91
+ .note {
92
+ font-size: 13px;
93
+ color: #567a74;
94
+ }
95
+
96
+ .matchList {
97
+ display: flex;
98
+ flex-direction: column;
99
+ gap: 8px;
100
+ max-height: 280px;
101
+ overflow: auto;
102
+ }
103
+
104
+ .matchItem {
105
+ background: #f4f9f8;
106
+ border: 1px solid #cfe2de;
107
+ text-align: left;
108
+ display: flex;
109
+ flex-direction: column;
110
+ gap: 3px;
111
+ }
112
+
113
+ .matchItem.active {
114
+ border-color: #0f6f62;
115
+ background: #e4f4f1;
116
+ }
117
+
118
+ .sectionTitle {
119
+ margin-top: 16px;
120
+ }
121
+
122
+ .teamSourceRow {
123
+ display: flex;
124
+ gap: 16px;
125
+ margin: 12px 0;
126
+ color: #2d5b54;
127
+ flex-wrap: wrap;
128
+ }
129
+
130
+ .teamSourceRow label {
131
+ display: flex;
132
+ align-items: center;
133
+ gap: 6px;
134
+ }
135
+
136
+ .previousBox {
137
+ display: flex;
138
+ gap: 8px;
139
+ margin-bottom: 10px;
140
+ }
141
+
142
+ .previousBox select {
143
+ min-width: 280px;
144
+ }
145
+
146
+ .teamSetup {
147
+ display: grid;
148
+ grid-template-columns: 1fr 1fr;
149
+ gap: 10px;
150
+ }
151
+
152
+ .teamSetup select {
153
+ min-height: 170px;
154
+ }
155
+
156
+ .rowButtons {
157
+ display: flex;
158
+ gap: 8px;
159
+ margin-top: 10px;
160
+ margin-bottom: 10px;
161
+ }
162
+
163
+ .umpireGuide {
164
+ margin-bottom: 12px;
165
+ background: #f4faf8;
166
+ border: 1px solid #cae2dc;
167
+ border-radius: 12px;
168
+ padding: 12px;
169
+ }
170
+
171
+ .umpireGuide h3 {
172
+ margin: 0 0 6px;
173
+ }
174
+
175
+ .guideGrid {
176
+ display: grid;
177
+ grid-template-columns: 1fr 1fr;
178
+ gap: 6px 14px;
179
+ }
180
+
181
+ .guideGrid p {
182
+ margin: 0;
183
+ font-size: 13px;
184
+ color: #305d57;
185
+ }
186
+
187
+ .fieldGroup {
188
+ display: flex;
189
+ flex-direction: column;
190
+ gap: 6px;
191
+ }
192
+
193
+ .fieldLabel {
194
+ font-size: 12px;
195
+ color: #355e59;
196
+ font-weight: 700;
197
+ }
198
+
199
+ .formRow {
200
+ display: grid;
201
+ grid-template-columns: repeat(4, minmax(0, 1fr));
202
+ gap: 8px;
203
+ }
204
+
205
+ .wicketCheck {
206
+ display: flex;
207
+ align-items: center;
208
+ gap: 6px;
209
+ font-size: 14px;
210
+ color: #2f5a54;
211
+ }
212
+
213
+ .scoreboard {
214
+ background: #0f332f;
215
+ color: #e7fffb;
216
+ border-radius: 14px;
217
+ padding: 14px;
218
+ }
219
+
220
+ .bigScore {
221
+ font-size: 36px;
222
+ margin: 4px 0;
223
+ font-weight: 800;
224
+ }
225
+
226
+ .ballStrip {
227
+ display: flex;
228
+ flex-wrap: wrap;
229
+ gap: 6px;
230
+ }
231
+
232
+ .ballStrip span {
233
+ background: #1c4d48;
234
+ padding: 5px 8px;
235
+ border-radius: 8px;
236
+ font-size: 12px;
237
+ }
238
+
239
+ .error {
240
+ margin: 10px 0;
241
+ background: #fde7ea;
242
+ border: 1px solid #f6c2cb;
243
+ color: #8b1f32;
244
+ border-radius: 10px;
245
+ padding: 10px;
246
+ }
247
+
248
+ .message {
249
+ margin: 10px 0;
250
+ background: #e7f8f3;
251
+ border: 1px solid #bfe8d8;
252
+ color: #14513d;
253
+ border-radius: 10px;
254
+ padding: 10px;
255
+ }
256
+
257
+ @media (max-width: 1080px) {
258
+ .teamSetup {
259
+ grid-template-columns: 1fr;
260
+ }
261
+
262
+ .guideGrid {
263
+ grid-template-columns: 1fr;
264
+ }
265
+
266
+ .formRow {
267
+ grid-template-columns: 1fr 1fr;
268
+ }
269
+
270
+ .previousBox {
271
+ flex-direction: column;
272
+ }
273
+
274
+ .previousBox select {
275
+ min-width: 0;
276
+ }
277
+ }
frontend/src/utils/api.js CHANGED
@@ -1,6 +1,6 @@
1
  import axios from 'axios';
2
 
3
- const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8001';
4
 
5
  // Set up axios instance
6
  const api = axios.create({
@@ -103,4 +103,15 @@ export const financeService = {
103
  addManualCredit: (payload) => api.post('/finance/manual-credit', payload),
104
  };
105
 
 
 
 
 
 
 
 
 
 
 
 
106
  export default api;
 
1
  import axios from 'axios';
2
 
3
+ const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
4
 
5
  // Set up axios instance
6
  const api = axios.create({
 
103
  addManualCredit: (payload) => api.post('/finance/manual-credit', payload),
104
  };
105
 
106
+ export const matchesService = {
107
+ createMatch: (payload) => api.post('/matches', payload),
108
+ listMatches: () => api.get('/matches'),
109
+ getMatch: (matchId) => api.get(`/matches/${matchId}`),
110
+ setupTeams: (matchId, payload) => api.post(`/matches/${matchId}/teams`, payload),
111
+ startMatch: (matchId, payload) => api.post(`/matches/${matchId}/start`, payload),
112
+ recordBall: (matchId, payload) => api.post(`/matches/${matchId}/ball`, payload),
113
+ getScoreboard: (matchId, innings = 1) => api.get(`/matches/${matchId}/scoreboard?innings=${innings}`),
114
+ completeMatch: (matchId) => api.post(`/matches/${matchId}/complete`),
115
+ };
116
+
117
  export default api;