|
| 1 | +from models.challenges import UserChallengeStatus |
| 2 | +from sqlalchemy import func |
1 | 3 | from sqlalchemy.orm import Session |
2 | 4 | from models.teams import Team |
3 | 5 | from schemas.team_schema import TeamCreateRequest, TeamResponse |
|
6 | 8 | def create_team(db: Session, req: TeamCreateRequest) -> TeamResponse: |
7 | 9 | all_ids = [req.my_id] + req.member_ids |
8 | 10 |
|
9 | | - existing = db.query(Team).filter(Team.user_id.in_(all_ids)).all() |
10 | | - if existing: |
11 | | - raise HTTPException(status_code=400, detail="Some users are already in a team.") |
12 | | - |
13 | | - last_team = ( |
14 | | - db.query(Team) |
15 | | - .order_by(Team.team_id.desc()) |
16 | | - .with_for_update() |
17 | | - .first() |
| 11 | + records = ( |
| 12 | + db.query(Team.user_id, Team.is_active, UserChallengeStatus.is_correct) |
| 13 | + .outerjoin(UserChallengeStatus, Team.user_id == UserChallengeStatus.user_id) |
| 14 | + .filter(Team.user_id.in_(all_ids)) |
| 15 | + .all() |
18 | 16 | ) |
| 17 | + |
| 18 | + active_ids = [r.user_id for r in records if r.is_active] |
| 19 | + corrected_ids = [r.user_id for r in records if r.is_correct] |
| 20 | + |
| 21 | + if active_ids: |
| 22 | + raise HTTPException( |
| 23 | + status_code=400, |
| 24 | + detail=f"Users already in active team: {active_ids}", |
| 25 | + ) |
| 26 | + |
| 27 | + if corrected_ids: |
| 28 | + raise HTTPException( |
| 29 | + status_code=400, |
| 30 | + detail=f"Users already corrected: {corrected_ids}", |
| 31 | + ) |
19 | 32 |
|
20 | | - new_team_id = (last_team.team_id + 1) if last_team else 1 |
| 33 | + last_team_id = db.query(func.max(Team.team_id)).scalar() |
| 34 | + new_team_id = (last_team_id or 0) + 1 |
21 | 35 |
|
22 | | - for uid in all_ids: |
23 | | - db.add(Team(team_id=new_team_id, user_id=uid)) |
| 36 | + teams_to_add = [ |
| 37 | + {"team_id": new_team_id, "user_id": uid, "is_active": True} |
| 38 | + for uid in all_ids |
| 39 | + ] |
24 | 40 |
|
| 41 | + db.bulk_insert_mappings(Team, teams_to_add) |
25 | 42 | db.commit() |
26 | 43 |
|
27 | 44 | return TeamResponse(team_id=new_team_id, members_ids=all_ids) |
| 45 | + |
| 46 | +def dissolve_team_by_user(db: Session, user_id: int): |
| 47 | + team_entry = db.query(Team).filter(Team.user_id == user_id, Team.is_active == True).first() |
| 48 | + if not team_entry: |
| 49 | + raise HTTPException(status_code=400, detail="User not in active team") |
| 50 | + |
| 51 | + team_id = team_entry.team_id |
| 52 | + team_members = db.query(Team).filter(Team.team_id == team_id, Team.is_active == True).all() |
| 53 | + |
| 54 | + for member in team_members: |
| 55 | + member.is_active = False |
| 56 | + |
| 57 | + db.commit() |
| 58 | + return {"message": f"Team {team_id} dissolved", "team_id": team_id} |
0 commit comments