Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add demo entities to demo account #723

Merged
merged 1 commit into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions backend/bracket/logic/subscriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@
from typing import TYPE_CHECKING, Any

from fastapi import HTTPException
from heliclockter import datetime_utc
from pydantic import BaseModel

from bracket.models.db.account import UserAccountType
from bracket.models.db.club import ClubCreateBody
from bracket.models.db.tournament import TournamentBody
from bracket.sql.clubs import create_club
from bracket.sql.tournaments import sql_create_tournament
from bracket.utils.id_types import UserId
from bracket.utils.types import assert_some

if TYPE_CHECKING:
from bracket.models.db.user import UserBase
Expand Down Expand Up @@ -60,3 +67,20 @@ def check_requirement(array: list[Any], user: UserBase, attribute: str, addition
f'Your `{user.account_type.value}` subscription allows a maximum of '
f'{constraint} {attribute.replace("max_", "")}.',
)


async def setup_demo_account(user_id: UserId) -> None:
club = ClubCreateBody(name="Demo Club")
club_inserted = await create_club(club, user_id)

tournament = TournamentBody(
name="Demo Tournament",
club_id=assert_some(club_inserted.id),
start_time=datetime_utc.future(hours=1),
dashboard_public=False,
players_can_be_in_multiple_teams=False,
auto_assign_courts=True,
duration_minutes=10,
margin_minutes=5,
)
await sql_create_tournament(tournament)
4 changes: 0 additions & 4 deletions backend/bracket/models/db/tournament.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,3 @@ class TournamentUpdateBody(BaseModelORM):

class TournamentBody(TournamentUpdateBody):
club_id: ClubId


class TournamentToInsert(TournamentBody):
created: datetime_utc
11 changes: 2 additions & 9 deletions backend/bracket/routes/tournaments.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import aiofiles.os
import asyncpg # type: ignore[import-untyped]
from fastapi import APIRouter, Depends, HTTPException, UploadFile
from heliclockter import datetime_utc
from starlette import status

from bracket.database import database
Expand All @@ -13,7 +12,6 @@
from bracket.logic.tournaments import get_tournament_logo_path
from bracket.models.db.tournament import (
TournamentBody,
TournamentToInsert,
TournamentUpdateBody,
)
from bracket.models.db.user import UserPublic
Expand All @@ -26,6 +24,7 @@
from bracket.routes.models import SuccessResponse, TournamentResponse, TournamentsResponse
from bracket.schema import tournaments
from bracket.sql.tournaments import (
sql_create_tournament,
sql_delete_tournament,
sql_get_tournament,
sql_get_tournament_by_endpoint_name,
Expand Down Expand Up @@ -134,13 +133,7 @@ async def create_tournament(
)

try:
await database.execute(
query=tournaments.insert(),
values=TournamentToInsert(
**tournament_to_insert.model_dump(),
created=datetime_utc.now(),
).model_dump(),
)
await sql_create_tournament(tournament_to_insert)
except asyncpg.exceptions.UniqueViolationError as exc:
check_unique_constraint_violation(exc, {UniqueIndex.ix_tournaments_dashboard_endpoint})

Expand Down
2 changes: 2 additions & 0 deletions backend/bracket/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from starlette import status

from bracket.config import config
from bracket.logic.subscriptions import setup_demo_account
from bracket.models.db.account import UserAccountType
from bracket.models.db.user import (
DemoUserToRegister,
Expand Down Expand Up @@ -131,6 +132,7 @@ async def register_demo_user(user_to_register: DemoUserToRegister) -> TokenRespo
access_token = create_access_token(
data={"user": user_created.email}, expires_delta=access_token_expires
)
await setup_demo_account(assert_some(user_created.id))
return TokenResponse(
data=Token(
access_token=access_token, token_type="bearer", user_id=assert_some(user_created.id)
Expand Down
22 changes: 13 additions & 9 deletions backend/bracket/sql/clubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,31 @@
from bracket.utils.types import assert_some


async def sql_give_user_access_to_club(user_id: UserId, club_id: ClubId) -> None:
query_many_to_many = """
INSERT INTO users_x_clubs (club_id, user_id, relation)
VALUES (:club_id, :user_id, 'OWNER')
"""
await database.execute(
query=query_many_to_many,
values={"club_id": assert_some(club_id), "user_id": user_id},
)


async def create_club(club: ClubCreateBody, user_id: UserId) -> Club:
async with database.transaction():
query = """
INSERT INTO clubs (name, created)
VALUES (:name, NOW())
RETURNING *
"""
"""
result = await database.fetch_one(query=query, values={"name": club.name})
if result is None:
raise ValueError("Could not create club")

club_created = Club.model_validate(dict(result._mapping))

query_many_to_many = """
INSERT INTO users_x_clubs (club_id, user_id, relation)
VALUES (:club_id, :user_id, 'OWNER')
"""
await database.execute(
query=query_many_to_many,
values={"club_id": assert_some(club_created.id), "user_id": user_id},
)
await sql_give_user_access_to_club(user_id, assert_some(club_created.id))

return club_created

Expand Down
35 changes: 34 additions & 1 deletion backend/bracket/sql/tournaments.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Any

from bracket.database import database
from bracket.models.db.tournament import Tournament, TournamentUpdateBody
from bracket.models.db.tournament import Tournament, TournamentBody, TournamentUpdateBody
from bracket.utils.id_types import TournamentId


Expand Down Expand Up @@ -74,3 +74,36 @@ async def sql_update_tournament(
query=query,
values={"tournament_id": tournament_id, **tournament.model_dump()},
)


async def sql_create_tournament(tournament: TournamentBody) -> None:
query = """
INSERT INTO tournaments (
name,
start_time,
club_id,
dashboard_public,
dashboard_endpoint,
logo_path,
players_can_be_in_multiple_teams,
auto_assign_courts,
duration_minutes,
margin_minutes
)
VALUES (
:name,
:start_time,
:club_id,
:dashboard_public,
:dashboard_endpoint,
:logo_path,
:players_can_be_in_multiple_teams,
:auto_assign_courts,
:duration_minutes,
:margin_minutes
)
"""
await database.execute(
query=query,
values=tournament.model_dump(),
)
Loading