Skip to content

Commit

Permalink
Added rough sketch for Member report backend. A little slow because o…
Browse files Browse the repository at this point in the history
…f User queries. Only thing left to do is maybe better formatting of columns, especially roles
  • Loading branch information
IrishBumfuzzle committed Dec 20, 2024
1 parent 2669560 commit 31cd022
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 2 deletions.
15 changes: 14 additions & 1 deletion otypes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
from functools import cached_property
from typing import Dict, Optional, Union
from typing import Dict, Optional, Union, List

import strawberry
from strawberry.fastapi import BaseContext
Expand Down Expand Up @@ -85,3 +85,16 @@ class SimpleMemberInput:
@strawberry.input
class SimpleClubInput:
cid: str


@strawberry.input
class MemberInputDataReportDetails:
clubid: str | None
fields: List[str]


@strawberry.type
class MemberCSVResponse:
csvFile: str
successMessage: str
errorMessage: str
71 changes: 70 additions & 1 deletion queries.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import csv
import io
from typing import List

import strawberry
from fastapi.encoders import jsonable_encoder

from db import membersdb
from models import Member
from utils import getClubDetails, getUser

# import all models and types
from otypes import Info, MemberType, SimpleClubInput, SimpleMemberInput
from otypes import Info, MemberType, SimpleClubInput, SimpleMemberInput, MemberInputDataReportDetails, MemberCSVResponse

"""
Member Queries
Expand Down Expand Up @@ -234,6 +237,71 @@ def pendingMembers(info: Info) -> List[MemberType]:
else:
raise Exception("No Member Result/s Found")

@strawberry.field
def downloadMembersData(details: MemberInputDataReportDetails, info: Info) -> MemberCSVResponse:
user = info.context.user
if user is None:
raise Exception("You do not have permission to access this resource.")

results = membersdb.find({"cid": details.clubid}, {"_id": 0})

allMembers = []
for result in results:
roles = result["roles"]
roles_result = []

for i in roles:
if i["deleted"] is True:
continue
roles_result.append(i)

if len(roles_result) > 0:
result["roles"] = roles_result
allMembers.append(
result
)

headerMapping = {"clubid": "Club Name", "uid": "Name", "poc": "Is POC", "roles": "Roles"}

# Prepare CSV content
csvOutput = io.StringIO()
fieldnames = [
headerMapping.get(field.lower(), field)
for field in details.fields
]
csv_writer = csv.DictWriter(csvOutput, fieldnames=fieldnames)
csv_writer.writeheader()
clubName = getClubDetails(details.clubid, info.context.cookies)["name"]

for member in allMembers:
memberData = {}
for field in details.fields:
value = ""
mappedField = headerMapping.get(field.lower())
if field == "clubid":
value = clubName
elif field == "uid":
userDetails = getUser(member[field], info.context.cookies)
value = userDetails["firstName"] + " " +userDetails["lastName"]
elif field == "roles":
listOfRoles = []
for i in member[field]:
roleFormatting = [i["name"], i["start_year"], i["end_year"]]
listOfRoles.append(roleFormatting)
value = str(listOfRoles)
else:
value = member[field]
memberData[mappedField] = value
csv_writer.writerow(memberData)

csv_content = csvOutput.getvalue()
csvOutput.close()

return MemberCSVResponse(
csvFile=csv_content,
successMessage="CSV file generated successfully",
errorMessage="",
)

# register all queries
queries = [
Expand All @@ -242,4 +310,5 @@ def pendingMembers(info: Info) -> List[MemberType]:
members,
currentMembers,
pendingMembers,
downloadMembersData,
]
27 changes: 27 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,30 @@ def getUser(uid, cookies=None):
return request.json()["data"]["userProfile"]
except Exception:
return None

# get club name from club id
def getClubDetails(
clubid: str,
cookies,
) -> dict:
try:
query = """
query Club($clubInput: SimpleClubInput!) {
club(clubInput: $clubInput) {
cid
name
email
studentBody
category
}
}
"""
variable = {"clubInput": {"cid": clubid}}
request = requests.post(
"http://gateway/graphql",
json={"query": query, "variables": variable},
cookies=cookies,
)
return request.json()["data"]["club"]
except Exception:
return {}

0 comments on commit 31cd022

Please sign in to comment.