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

Dashboards #19

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
576 changes: 298 additions & 278 deletions scripts/main_constants.py

Large diffs are not rendered by default.

51 changes: 26 additions & 25 deletions scripts/seeder/seed_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from requests.sessions import Session

from config.logger import logger
from scripts.main_constants import clusters, events, points
from scripts.main_constants import clusters, events, points, departments
from scripts.test_constants import test_departments, test_user
from server.schemas.cluster import Cluster
from server.schemas.department import Department
Expand All @@ -22,26 +22,27 @@ async def seed_maindb(database: Session):
logger.info("Seeding main database")
if database.query(Department).count() == 0:
logger.info("Seeding database with test departments")
for department in test_departments:
for department in departments:
database.add(
Department(
key=department["id"],
name=department["name"],
description=department["description"],
)
)
database.commit()
if database.query(Users).count() == 0:
database.add(
Users(
name=test_user["name"],
email=test_user["email"],
mobile_number=test_user["mobile_number"],
gender=test_user["gender"],
department_id=None,
fcm_token=None,
)
)
database.commit()
# if database.query(Users).count() == 0:
# database.add(
# Users(
# name=test_user["name"],
# email=test_user["email"],
# mobile_number=test_user["mobile_number"],
# gender=test_user["gender"],
# department_id=test_user["department_id"],
# fcm_token=None,
# )
# )
# database.commit()
if database.query(Cluster).count() == 0:
for cluster in clusters:
database.add(
Expand Down Expand Up @@ -71,17 +72,17 @@ async def seed_maindb(database: Session):
)
)
database.commit()
if database.query(Point).count() == 0:
for point in points:
database.add(
Point(
point=point["point"],
position=point["position"],
event_id=point["event_id"],
department_id=None,
)
)
database.commit()
# if database.query(Point).count() == 0:
# for point in points:
# database.add(
# Point(
# point=point["point"],
# position=point["position"],
# event_id=point["event_id"],
# department_id=point["department_id"],
# )
# )
# database.commit()
logger.info("Successfully seeded database")
database.commit()
database.close()
Expand Down
1 change: 1 addition & 0 deletions scripts/seeder/seed_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def seed_testdb(database: Session):
for department in test_departments:
database.add(
Department(
key=department["id"],
name=department["name"],
description=department["description"],
)
Expand Down
9 changes: 8 additions & 1 deletion server/controllers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,14 @@ def get_department_id(email: str) -> int:
"""
get the department id of the current User
"""
return int(email[1:3])
if int(email[0] == 1):
return int(email[1:3])
if int(email[0] == 2):
return 15
if int(email[0] == 3 or email[0] == 4):
return 16

return 1


class JWTBearer(HTTPBearer):
Expand Down
65 changes: 65 additions & 0 deletions server/controllers/dashboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
Dashboard controller
"""

from datetime import datetime

from server.models.event import EventModel
from server.schemas.event import Event


def get_upcoming_events(events: tuple[Event]) -> list[EventModel]:
"""
Util function to get upcoming events
"""
upcoming_events: list[EventModel] = []
current_time = datetime.now()
for event in events:
if event.start_time > current_time:
upcoming_events.append(
EventModel(
image_link=event.image_link,
rules=event.rules,
description=event.description,
start_time=event.start_time,
end_time=event.end_time,
is_reg_completed=event.is_reg_completed,
name=event.name,
points=[],
form_link=event.form_link,
is_event_completed=event.is_event_completed,
event_link=event.event_link,
)
)
return upcoming_events


def get_points(points: list[tuple], department: int) -> int:
"""
Util function to get points of the department
"""
point_list: dict = {}
for point in points:
point_list.update({point[0]: point[1]})
print(point_list)
return point_list.get(department, 0)


def get_position(points: list[tuple], department: int) -> int:
"""
Util function to get position of the department
"""
point_list: dict = {}
for point in points:
point_list.update({point[0]: point[1]})
sorted_list = sorted(point_list.items(), key=lambda item: item[1])
sorted_list.reverse()
pos = 0
current_value = -1
for point in sorted_list:
if current_value != point[1]:
current_value = point[1]
pos += 1
if point[0] == department:
break
return pos
3 changes: 2 additions & 1 deletion server/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from config.database import Base, engine
from config.settings import settings
from server.routers import department, event
from server.routers import dashboard, department, event

if "pytest" in sys.modules:
from server.routers import auth, preferences, questions, scores, tshirt
Expand All @@ -33,6 +33,7 @@
app.include_router(event.router)
app.include_router(tshirt.router)
app.include_router(scores.router)
app.include_router(dashboard.router)
origins = []

if "pytest" not in sys.modules:
Expand Down
38 changes: 38 additions & 0 deletions server/models/dashboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Dasnboard Model
"""

from pydantic import BaseModel
from pydantic.fields import Field

from server.models.event import EventModel


class DashboardResponseModel(BaseModel):
"""
model for dashboard
"""

department: str = Field(
...,
title="department",
description="department of the current User",
)

point: float = Field(
...,
title="point",
description="Total score of department in the event",
)

position: int = Field(
...,
title="description",
description="current positon of the department in the event",
)

upcoming_events: list[EventModel] = Field(
...,
title="Upcomind Events",
description="List of all upcoming Events",
)
79 changes: 79 additions & 0 deletions server/routers/dashboard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""
Dashboard route
"""

from fastapi import APIRouter, HTTPException
from fastapi.param_functions import Depends
from sqlalchemy import func
from sqlalchemy.orm import Session

from config.database import get_database
from config.logger import logger
from server.controllers.auth import JWTBearer, decode_jwt
from server.controllers.dashboard import (
get_points,
get_position,
get_upcoming_events,
)
from server.models.dashboard import DashboardResponseModel
from server.models.errors import GenericError
from server.schemas.department import Department
from server.schemas.event import Event
from server.schemas.point import Point
from server.schemas.users import Users

router = APIRouter(
prefix="/dashboard",
)


@router.get(
"/",
response_model=DashboardResponseModel,
dependencies=[Depends(get_database)],
)
async def get_dashboard(
token: str = Depends(JWTBearer()),
database: Session = Depends(get_database),
) -> DashboardResponseModel:
"""
GET route for Dashboard
"""
try:
user_email = decode_jwt(token)["user_email"]
user = database.query(Users).filter_by(email=user_email).first()
if not user:
raise GenericError("User not found")

department = (
database.query(Department)
.filter_by(id=user.department_id)
.first()
)
if not department:
raise GenericError("Department not found for the current user")

points = (
database.query(Point.department_id, func.sum(Point.point))
.group_by(Point.department_id)
.all()
)
print(points)
events = tuple(database.query(Event).all())

return DashboardResponseModel(
department=department.name,
point=get_points(points=points, department=1),
upcoming_events=get_upcoming_events(events=events),
position=get_position(points=points, department=1),
)

except GenericError as exception:
logger.error(f"<Dashboard retrieval failed due to {exception}>")
raise HTTPException(
status_code=500,
detail="An unexpected error occurred while retrieving dashboard details ",
headers={
"X-Error": "An unexpected error occurred while retrieving dashboard"
},
) from exception
1 change: 0 additions & 1 deletion server/routers/seeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from scripts.seeder.seed_details import seed_maindb
from config.database import SessionLocal


router = APIRouter()


Expand Down
3 changes: 2 additions & 1 deletion server/schemas/department.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class Department(Base):
name = Column(String(100))
description = Column(String(3000))

def __init__(self, name, description):
def __init__(self, key, name, description):
self.id = key
self.name = name
self.description = description

Expand Down
26 changes: 26 additions & 0 deletions tests/dashboard_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
Test for dashboard route
"""

from fastapi.testclient import TestClient

from config.settings import settings

jwt_test = settings.test_jwt
header = {"Authorization": f"Bearer {jwt_test}"}
ROUTE = "/dashboard/"
res = {
"department": "EEE",
"point": 34.0,
"position": 2,
"upcoming_events": [],
}


def get_dashboard(client: TestClient):
"""
get list of dashboard
"""
get_response = client.get(url=ROUTE, headers=header)
assert get_response.status_code == 200
assert get_response.json() == res
9 changes: 9 additions & 0 deletions tests/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from scripts.seeder.seed_tests import seed_testdb
from server.main import app
from tests.answers_test import post_answers
from tests.dashboard_test import get_dashboard
from tests.department_test import get_departments
from tests.event_test import get_events
from tests.preferences_test import (
Expand Down Expand Up @@ -76,6 +77,13 @@ def scores_test():
get_scores(client)


def dashboard_test():
"""
method to execute tests on dashboard route
"""
get_dashboard(client)


app.dependency_overrides[get_database] = get_test_database

client = test()
Expand All @@ -86,3 +94,4 @@ def scores_test():
departments_test()
events_test()
scores_test()
dashboard_test()