Skip to content

Commit

Permalink
Merge pull request #1176 from BCStudentSoftwareDevTeam/serviceTEntry658
Browse files Browse the repository at this point in the history
Selectively remove service transcript entry for banned programs
  • Loading branch information
BrianRamsay authored Dec 11, 2024
2 parents eda40bb + 3dafa2f commit 05f7477
Show file tree
Hide file tree
Showing 10 changed files with 180 additions and 56 deletions.
61 changes: 50 additions & 11 deletions app/controllers/main/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def landingPage():
# Limit returned list to events in the future
futureEvents = [p for p in programsWithEventsList if not p.event.isPastEnd]

return render_template("/main/landingPage.html",
return render_template("/main/landingPage.html",
managerProgramDict=managerProgramDict,
term=g.current_term,
programsWithEventsList = futureEvents)
Expand All @@ -77,20 +77,20 @@ def events(selectedTerm, activeTab, programID):
if selectedTerm:
currentTerm = selectedTerm
currentTime = datetime.datetime.now()

listOfTerms = Term.select()
participantRSVP = EventRsvp.select(EventRsvp, Event).join(Event).where(EventRsvp.user == g.current_user)
rsvpedEventsID = [event.event.id for event in participantRSVP]

term: Term = Term.get_by_id(currentTerm)
term: Term = Term.get_by_id(currentTerm)

currentEventRsvpAmount = getEventRsvpCountsForTerm(term)
studentLedEvents = getStudentLedEvents(term)
countUpcomingStudentLedEvents = getUpcomingStudentLedCount(term, currentTime)
trainingEvents = getTrainingEvents(term, g.current_user)
bonnerEvents = getBonnerEvents(term)
otherEvents = getOtherEvents(term)

managersProgramDict = getManagerProgramDict(g.current_user)

# Fetch toggle state from session
Expand Down Expand Up @@ -179,6 +179,8 @@ def viewUsersProfile(username):

allBackgroundHistory = getUserBGCheckHistory(volunteer)
backgroundTypes = list(BackgroundCheckType.select())



eligibilityTable = []

Expand All @@ -188,8 +190,15 @@ def viewUsersProfile(username):
.where(ProgramBan.user == volunteer,
ProgramBan.program == program,
ProgramBan.endDate > datetime.datetime.now()).execute())
onTranscriptQuery = list(ProgramBan.select(ProgramBan)
.where(ProgramBan.user == volunteer,
ProgramBan.program == program,
ProgramBan.unbanNote.is_null(),
ProgramBan.removeFromTranscript == 0))

onTranscript = True if len(onTranscriptQuery) > 0 else False
userParticipatedTrainingEvents = getParticipationStatusForTrainings(program, [volunteer], g.current_term)
try:
try:
allTrainingsComplete = False not in [attended for event, attended in userParticipatedTrainingEvents[username]] # Did volunteer attend all events
except KeyError:
allTrainingsComplete = False
Expand All @@ -198,7 +207,9 @@ def viewUsersProfile(username):
"completedTraining": allTrainingsComplete,
"trainingList": userParticipatedTrainingEvents,
"isNotBanned": (not banNotes),
"banNote": noteForDict})
"banNote": noteForDict,
"onTranscript": onTranscript}),

profileNotes = ProfileNote.select().where(ProfileNote.user == volunteer)

bonnerRequirements = getCertRequirementsWithCompletion(certification=Certification.BONNER, username=volunteer)
Expand Down Expand Up @@ -245,14 +256,15 @@ def emergencyContactInfo(username):
contactInfo=contactInfo,
readOnly=readOnly
)

elif request.method == 'POST':
if g.current_user.username != username:
abort(403)

rowsUpdated = EmergencyContact.update(**request.form).where(EmergencyContact.user == username).execute()
if not rowsUpdated:
EmergencyContact.create(user = username, **request.form)

createActivityLog(f"{g.current_user.fullName} updated {user.fullName}'s emergency contact information.")
flash('Emergency contact information saved successfully!', 'success')

Expand Down Expand Up @@ -288,6 +300,7 @@ def insuranceInfo(username):
rowsUpdated = InsuranceInfo.update(**request.form).where(InsuranceInfo.user == username).execute()
if not rowsUpdated:
InsuranceInfo.create(user = username, **request.form)

createActivityLog(f"{g.current_user.fullName} updated {user.fullName}'s insurance information.")
flash('Insurance information saved successfully!', 'success')

Expand All @@ -300,7 +313,7 @@ def insuranceInfo(username):
def travelForm(username):
if not (g.current_user.username == username or g.current_user.isCeltsAdmin):
abort(403)

user = (User.select(User, EmergencyContact, InsuranceInfo)
.join(EmergencyContact, JOIN.LEFT_OUTER).switch()
.join(InsuranceInfo, JOIN.LEFT_OUTER)
Expand Down Expand Up @@ -354,6 +367,7 @@ def ban(program_id, username):
postData = request.form
banNote = postData["note"] # This contains the note left about the change
banEndDate = postData["endDate"] # Contains the date the ban will no longer be effective

try:
banUser(program_id, username, banNote, banEndDate, g.current_user)
programInfo = Program.get(int(program_id))
Expand Down Expand Up @@ -495,6 +509,31 @@ def serviceTranscript(username):
startDate = startDate,
userData = user)

@main_bp.route('/profile/<username>/updateTranscript/<program_id>', methods=['POST'])
def updateTranscript(username, program_id):
# Check user permissions
user = User.get_or_none(User.username == username)
if user is None:
abort(404)
if user != g.current_user and not g.current_user.isAdmin:
abort(403)

# Get the data sent from the client-side JavaScript
data = request.json

# Retrieve removeFromTranscript value from the request data
removeFromTranscript = data.get('removeFromTranscript')

# Update the ProgramBan object matching the program_id and username
try:
bannedProgramForUser = ProgramBan.get((ProgramBan.program == program_id) & (ProgramBan.user == user) & (ProgramBan.unbanNote.is_null()))
bannedProgramForUser.removeFromTranscript = removeFromTranscript
bannedProgramForUser.save()
return jsonify({'status': 'success'})
except ProgramBan.DoesNotExist:
return jsonify({'status': 'error', 'message': 'ProgramBan not found'})


@main_bp.route('/searchUser/<query>', methods = ['GET'])
def searchUser(query):

Expand All @@ -520,10 +559,10 @@ def getDietInfo():
dietaryInfo = request.form
user = dietaryInfo["user"]
dietInfo = dietaryInfo["dietInfo"]

if (g.current_user.username == user) or g.current_user.isAdmin:
updateDietInfo(user, dietInfo)
userInfo = User.get(User.username == user)
userInfo = User.get(User.username == user)
if len(dietInfo) > 0:
createActivityLog(f"Updated {userInfo.fullName}'s dietary restrictions to {dietInfo}.") if dietInfo.strip() else None
else:
Expand Down
34 changes: 25 additions & 9 deletions app/logic/transcript.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from peewee import fn
from collections import defaultdict

from app.models.course import Course
from app.models.courseParticipant import CourseParticipant
from app.models.program import Program
from app.models.programBan import ProgramBan
from app.models.courseInstructor import CourseInstructor
from app.models.user import User
from app.models.term import Term
Expand All @@ -11,24 +13,31 @@

def getProgramTranscript(username):
"""
Returns a Program query object containing all the programs for
current user.
Returns a Program query object containing all the programs for ,
the current user.
"""
# Add up hours earned in a term for each program they've participated in

EventData = (Event.select(Event, fn.SUM(EventParticipant.hoursEarned).alias("hoursEarned"))
.join(EventParticipant)
.where(EventParticipant.user == username)
.group_by(Event.program, Event.term)
.order_by(Event.term)
.having(fn.SUM(EventParticipant.hoursEarned > 0)))
transcriptData = {}

# Fetch all ProgramBan objects for the user
bannedProgramsForParticipant = ProgramBan.select().where(ProgramBan.user == username)

# Create a set of program IDs to remove from transcript
programsToRemoveFromTranscript = {bannedProgram.program_id for bannedProgram in bannedProgramsForParticipant if bannedProgram.removeFromTranscript}
transcriptData = defaultdict(list)

# Iterate through EventData and populate transcriptData
for event in EventData:
if event.program in transcriptData:
if event.program.id not in programsToRemoveFromTranscript: # Check if program is not in programs to be removed from transcript
transcriptData[event.program].append([event.term.description, event.hoursEarned])
else:
transcriptData[event.program] = [[event.term.description, event.hoursEarned]]
return transcriptData

return dict(transcriptData)

def getSlCourseTranscript(username):
"""
Expand All @@ -47,8 +56,15 @@ def getTotalHours(username):
"""
Get the toal hours from events and courses combined.
"""
bannedAndTranscriptsRemoved = ProgramBan.select().where((ProgramBan.user == username) and (ProgramBan.unbanNote.is_null(True)) and (ProgramBan.removeFromTranscript == 1))
transcriptsRemovedIdList = [program.program_id for program in bannedAndTranscriptsRemoved]

eventHours = (EventParticipant.select(fn.SUM(EventParticipant.hoursEarned))
.where(EventParticipant.user == username)).scalar()
.join(Event, on=(EventParticipant.event == Event.id))
.where((EventParticipant.user == username) & (Event.program_id.not_in(transcriptsRemovedIdList)))).scalar()



courseHours = (CourseParticipant.select(fn.SUM(CourseParticipant.hoursEarned))
.where(CourseParticipant.user == username)).scalar()

Expand Down
5 changes: 4 additions & 1 deletion app/logic/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from app.models.note import Note
from app.models.user import User
from app.models.profileNote import ProfileNote
from app.models.programBan import ProgramBan
from app.models.backgroundCheck import BackgroundCheck
from app.models.backgroundCheckType import BackgroundCheckType
from app.logic.volunteers import addUserBackgroundCheck
Expand Down Expand Up @@ -76,6 +77,7 @@ def banUser(program_id, username, note, banEndDate, creator):
banEndDate: date when the ban will end
creator: the admin or person with authority who created the ban
"""

noteForDb = Note.create(createdBy = creator,
createdOn = datetime.datetime.now(),
noteContent = note,
Expand Down Expand Up @@ -103,7 +105,8 @@ def unbanUser(program_id, username, note, creator):
isPrivate = 0,
noteType = "unban")
(ProgramBan.update(endDate = datetime.datetime.now(),
unbanNote = noteForDb)
unbanNote = noteForDb,
removeFromTranscript = 0)
.where(ProgramBan.program == program_id,
ProgramBan.user == username,
ProgramBan.endDate > datetime.datetime.now())).execute()
Expand Down
3 changes: 3 additions & 0 deletions app/models/programBan.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ class ProgramBan(baseModel):
endDate = DateField(null=True)
banNote = ForeignKeyField(Note, null=False)
unbanNote = ForeignKeyField(Note, null=True)
removeFromTranscript = BooleanField(default=False)


17 changes: 16 additions & 1 deletion app/static/css/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,19 @@ form {

.saveBtnDiv {
text-align: center;
}
}

.transcriptStatus {
font-size: 13px;
margin-left: 5px;
display: inline-block;
}

.onTranscript {
width: 147px;
}

.editIcon {
position: relative;
top: -4px;
}
Loading

0 comments on commit 05f7477

Please sign in to comment.