Skip to content

Commit

Permalink
Improve user and group assignment upload (#162)
Browse files Browse the repository at this point in the history
<!--- Please write your PR name in the present imperative tense.
Examples of that tense are: "Fix issue in the dispatcher where…",
"Improve our handling of…", etc." -->
<!-- For more information on Pull Requests, you can reference here:
https://success.vanillaforums.com/kb/articles/228-using-pull-requests-to-contribute
-->
## Describe Your Changes
closes #122 
- checks for qualtrics_id and skips row in upload
- creates upload for group assignments (user_id, group_id) 
- adds nav bar for super-admin to get to add_students and analysis
dashboard

## Non-Obvious Technical Information
- group assignment upload fails in an ugly way.  Will add issue.

## Checklist Before Requesting a Review
- [X] The code runs successfully.

```commandline
2024-03-11 16:14:20 INFO:     172.21.0.1:42138 - "POST /admin/add_group_assignments HTTP/1.1" 302 Found
2024-03-11 16:14:20 INFO:     172.21.0.1:42138 - "GET /admin/dashboard?success=12+group+assignments+added+to+the+database. HTTP/1.1" 200 OK
```
  • Loading branch information
anisfeld authored Mar 11, 2024
1 parent 3972f2d commit 020f9fb
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 16 deletions.
4 changes: 2 additions & 2 deletions prijateli_tree/app/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class User(Base):
nullable=True,
)
high_school = relationship("HighSchool", back_populates="users")
random_group = relationship("RandomGroups", back_populates="users")
random_group = relationship("RandomGroup", back_populates="users")

@property
def name_str(self):
Expand All @@ -95,7 +95,7 @@ def name_str(self):
)


class RandomGroups(Base):
class RandomGroup(Base):
__tablename__ = "random_groups"
id = Column(Integer, Identity(start=1, cycle=True), primary_key=True)
created_at = Column(
Expand Down
80 changes: 73 additions & 7 deletions prijateli_tree/app/routers/administration.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
GameSession,
GameSessionPlayer,
GameType,
RandomGroup,
SessionLocal,
User,
)
Expand All @@ -50,7 +51,10 @@
WINNING_SCORES,
WINNING_WEIGHTS,
)
from prijateli_tree.app.utils.games import raise_exception_if_not
from prijateli_tree.app.utils.games import (
raise_exception_if_none,
raise_exception_if_not,
)


base_dir = Path(__file__).resolve().parent
Expand Down Expand Up @@ -456,6 +460,7 @@ def dashboard_add_students(
"administration/admin_bulk_add.html",
{
"request": request,
"user": user,
},
)

Expand Down Expand Up @@ -486,13 +491,19 @@ def add_students(
)

for _, student in student_df.iterrows():
student_in = User(
created_by=user.id,
**student,
role="student",
student_exists = (
db.query(User)
.filter_by(qualtrics_id=student.qualtrics_id)
.one_or_none()
)
db.add(student_in)
students_added += 1
if student_exists is None and student.qualtrics_id is not None:
student_in = User(
created_by=user.id,
**student,
role="student",
)
db.add(student_in)
students_added += 1
db.commit()

except Exception as e:
Expand All @@ -514,6 +525,61 @@ def add_students(
)


@router.post("/add_group_assignments", response_class=HTMLResponse)
def add_group_assignments(
file: UploadFile = File(...),
user=Depends(login_manager.optional),
db: Session = Depends(get_db),
) -> RedirectResponse:
if user is None:
return RedirectResponse("login", status_code=HTTPStatus.FOUND)

try:
group_df = pd.read_csv(file.file)
expected_fields = ["user_id", "group_id"]
raise_exception_if_not(
all([x in group_df.columns for x in expected_fields]),
detail="Upload file is missing expected fields",
)
groups_added = 0
for _, assignment in group_df.iterrows():
student_exists = (
db.query(User).filter_by(id=assignment.user_id).one_or_none()
)
raise_exception_if_none(
student_exists,
detail=f"student {assignment.user_id} not found in db.",
)

group_assignment_in = RandomGroup(
# created_by=user.id,
user_id=assignment.user_id,
group_id=assignment.group_id.lower(),
)
db.add(group_assignment_in)
groups_added += 1

db.commit()

except Exception as e:
# Rollback the transaction if an error occurs
raise HTTPException(
status_code=500, detail=f"Internal Server Error: {str(e)}"
)

finally:
file.file.close()

redirect_url = URL("/admin/dashboard").include_query_params(
success=f"{groups_added} group assignments added to the database."
)

return RedirectResponse(
redirect_url,
status_code=HTTPStatus.FOUND,
)


@router.get("/dashboard_analysis", response_class=HTMLResponse)
def analysis_dashboard(
request: Request,
Expand Down
17 changes: 14 additions & 3 deletions prijateli_tree/app/templates/administration/admin_bulk_add.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
<div class="container-sm">
<div class="row">
<div class="form-container bg-light-subtle col-xs-12 offset-md-1 col-md-10 offset-lg-1 col col-lg-10 offset-xl-3 col col-xl-6">
<h1>Upload Students</h1>
<p>Expects first_name, last_name, qualtrics_id, high_school_id, grade_level and langauge_id</p>
<form method="post"
action='{{ url_for("add_students") }}'
enctype="multipart/form-data">
Expand All @@ -33,9 +35,18 @@
<button type="submit" class="btn btn-primary float-end">Upload Data</button>
</form>
</div>
<div class="form-container bg-light-subtle col-xs-12 offset-md-1 col-md-10 offset-lg-1 col col-lg-10 offset-xl-3 col col-xl-6">
<h1>Upload Group Assignments</h1>
<p>Expects a valid user id and group id</p>
<form method="post"
action='{{ url_for("add_group_assignments") }}'
enctype="multipart/form-data">
<label for="file">Choose a CSV file:</label>
<input type="file" name="file" accept=".csv" required>
<br>
<button type="submit" class="btn btn-primary float-end">Upload Data</button>
</form>
</div>
</div>
</div>
{% endblock content %}
<form class="d-flex" action='{{ url_for("logout") }}'>
<button class="float-end btn btn-primary" type="submit">Logout</button>
</form>
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ <h2>List of Students</h2>
{% for s in students %}
<tr>
<td>
{% for g in s.random_group %}{{ g.group_id }}{% endfor %}
{% for g in s.random_group %}{{ g.group_id }}&nbsp;{% endfor %}
</td>
<td>{{ s.first_name }}</td>
<td>{{ s.last_name }}</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,3 @@ <h2>Students</h2>
</div>
</div>
{% endblock content %}
<form class="d-flex" action='{{ url_for("logout") }}'>
<button class="float-end btn btn-primary" type="submit">Logout</button>
</form>
8 changes: 8 additions & 0 deletions prijateli_tree/app/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@
height="35">
<span>Admin Panel</span>
</a>
{% if user.role == "super-admin" %}
<form class="d-flex" action='{{ url_for("add_students") }}'>
<button class="btn float-end" type="submit">Add Users</button>
</form>
<form class="d-flex" action='{{ url_for("analysis_dashboard") }}'>
<button class="btn float-end" type="submit">Analysis Dashboard</button>
</form>
{% endif %}
<form class="d-flex" action='{{ url_for("logout") }}'>
<button class="btn btn-primary float-end" type="submit">Logout</button>
</form>
Expand Down

0 comments on commit 020f9fb

Please sign in to comment.