-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlaborStatusForm.py
More file actions
executable file
·208 lines (188 loc) · 10.8 KB
/
laborStatusForm.py
File metadata and controls
executable file
·208 lines (188 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
from flask_login import login_required
from flask_mail import Mail, Message
from app.controllers.main_routes import *
from app.login_manager import require_login
from app.models.user import *
from app.models.status import *
from app.models.laborStatusForm import *
from app.models.overloadForm import *
from app.models.formHistory import *
from app.models.historyType import *
from app.models.term import *
from app.models.student import Student
from app.models.department import *
from app.models.activePosition import ActivePosition
from flask import json, jsonify
from flask import request
from datetime import datetime, date, timedelta
from flask import Flask, redirect, url_for, flash
from app.logic.emailHandler import*
from app.logic.userInsertFunctions import*
from app.models.supervisor import Supervisor
from app.controllers.main_routes.laborReleaseForm import createLaborReleaseForm
from app.logic.allPendingForms import saveStatus
from app.logic.statusFormFunctions import *
@main_bp.route('/laborstatusform', methods=['GET'])
@main_bp.route('/laborstatusform/<laborStatusKey>', methods=['GET'])
def laborStatusForm(laborStatusKey = None):
""" Render labor Status Form, and pre-populate LaborStatusForm page with the correct information when redirected from Labor History."""
currentUser = require_login()
if not currentUser: # Not logged in
return render_template('errors/403.html'), 403
if not currentUser.isLaborAdmin:
if currentUser.student and not currentUser.supervisor:
return redirect('/laborHistory/' + currentUser.student.ID)
# Logged in
students = Student.select()
terms = Term.select().where(Term.termState == "open") # changed to term state, open, closed, inactive
staffs = Supervisor.select()
departments = Department.select()
# Only prepopulate form if current user is the supervisor or creator of the form.
if laborStatusKey != None:
selectedLSForm = LaborStatusForm.get(LaborStatusForm.laborStatusFormID == laborStatusKey)
selectedFormHistory = FormHistory.get(FormHistory.formID == laborStatusKey)
creator = selectedFormHistory.createdBy.supervisor.ID
supervisor = selectedLSForm.supervisor.ID
if currentUser.supervisor.ID == supervisor or currentUser.supervisor.ID == creator or currentUser.isLaborAdmin:
forms = LaborStatusForm.get(LaborStatusForm.laborStatusFormID == laborStatusKey) # getting labor status form id, to prepopulate laborStatusForm.
else:
forms = None
else:
forms = None
return render_template( 'main/laborStatusForm.html',
title=('Labor Status Form'),
UserID = currentUser,
forms = forms,
students = students,
terms = terms,
staffs = staffs,
departments = departments)
@main_bp.route('/laborstatusform/userInsert', methods=['POST'])
def userInsert():
""" Create labor status form. Create labor history form. Most of the functions called here are in userInsertFunctions.py"""
currentUser = require_login()
if not currentUser: # Not logged in
return render_template('errors/403.html'), 403
rsp = (request.data).decode("utf-8") # This turns byte data into a string
rspFunctional = json.loads(rsp)
all_forms = []
for i in range(len(rspFunctional)):
# Get a student record for the given bnumber
try:
student = getOrCreateStudentRecord(bnumber=rspFunctional[i]['stuBNumber'])
supervisor = Supervisor.get(Supervisor.ID ==rspFunctional[i]['stuSupervisorID'])
except InvalidUserException as e:
print(e)
return "", 500
department, created = Department.get_or_create(DEPT_NAME = rspFunctional[i]['stuDepartment'])
term, created = Term.get_or_create(termCode = rspFunctional[i]['stuTermCode'])
try:
lsf = createLaborStatusForm(student, supervisor.ID, department.departmentID, term, rspFunctional[i])
createOverloadFormAndFormHistory(rspFunctional[i], lsf, currentUser, host=request.host)
try:
emailDuringBreak(checkForSecondLSFBreak(term.termCode, student.ID), term)
except Exception as e:
print("Error when sending emails during break: " + str(e))
all_forms.append(True)
except Exception as e:
all_forms.append(False)
print("ERROR on creating Labor Status Form/Overload Form" + str(e))
flash("Form(s) submitted successfully! They will be eligible for approval in one business day.", "success")
return jsonify(all_forms)
@main_bp.route("/laborstatusform/getDate/<termcode>", methods=['GET'])
def getDates(termcode):
""" Get the start and end dates of the selected term. """
dates = Term.select().where(Term.termCode == termcode)
datesDict = {}
for date in dates:
start = date.termStart
end = date.termEnd
primaryCutOff = date.primaryCutOff
if primaryCutOff is None:
datesDict[date.termCode] = {"Start Date":datetime.strftime(start, "%m/%d/%Y") , "End Date": datetime.strftime(end, "%m/%d/%Y")}
else:
datesDict[date.termCode] = {"Start Date":datetime.strftime(start, "%m/%d/%Y") , "End Date": datetime.strftime(end, "%m/%d/%Y"), "Primary Cut Off": datetime.strftime(primaryCutOff, "%m/%d/%Y"), "isBreak": date.isBreak, "isSummer": date.isSummer}
return json.dumps(datesDict)
@main_bp.route("/laborstatusform/getPositions/<departmentOrg>/<departmentAcct>", methods=['GET'])
def getPositions(departmentOrg, departmentAcct):
""" Get all of the positions that are in the selected department """
currentUser = require_login()
positions = (ActivePosition.select(ActivePosition, Department)
.join(Department, on=(ActivePosition.department == Department.departmentID))
.where((Department.ACCOUNT == departmentAcct) & (Department.ORG == departmentOrg))
)
positionDict = {}
for position in positions:
if position.POSN_CODE != "S12345" or currentUser.isLaborAdmin:
positionDict[position.POSN_CODE] = {"position": position.POSN_TITLE, "WLS":position.WLS, "positionCode":position.POSN_CODE}
return json.dumps(positionDict)
@main_bp.route("/laborstatusform/getstudents/<termCode>/<student>", methods=["POST"])
@main_bp.route("/laborstatusform/getstudents/<termCode>/<student>/<isOneLSF>", methods=["GET"])
def checkForPrimaryOrSecondLSFBreak(termCode, student, isOneLSF=None):
currentUser = require_login()
if isOneLSF:
return checkForSecondLSFBreak(termCode, student)
else:
return checkForPrimaryPosition(termCode, student, currentUser)
@main_bp.route("/laborstatusform/getcompliance/<department>", methods=["GET"])
def checkCompliance(department):
""" Gets the compliance status of a department. """
depts = Department.select().where(Department.ORG == department, Department.isActive == True)
deptDict = {}
for dept in depts:
deptDict['Department'] = {'Department Compliance': dept.departmentCompliance}
return json.dumps(deptDict)
@main_bp.route("/laborstatusform/checktotalhours/<termCode>/<student>/<hours>", methods=["GET"])
def checkTotalHours(termCode, student, hours):
""" Counts the total number of hours for the student after the new lsf is filled. """
shortCode, spring, fall, ayTermCode = termCode[-2:], '12', '11', None
if shortCode == spring or shortCode == fall: # Count the AY hours only for Fall and Spring, not break terms.
ayTermCode = termCode[:-2] + '00'
positions = FormHistory.select()\
.join_from(FormHistory, LaborStatusForm)\
.where(((FormHistory.formID.termCode == termCode) | (FormHistory.formID.termCode == ayTermCode)),
FormHistory.formID.studentSupervisee == student,
FormHistory.historyType == "Labor Status Form",
((FormHistory.status == "Approved") | (FormHistory.status == "Pending"))
)
term = Term.get(Term.termCode == termCode)
totalHours = 0
for item in positions:
formID = item.formID
releasedForm = FormHistory.select().where(FormHistory.formID == formID, FormHistory.historyType == "Labor Release Form", FormHistory.status == "Approved")
if not releasedForm:
if term.isBreak:
totalHours = totalHours + item.formID.contractHours
else:
totalHours = totalHours + item.formID.weeklyHours
totalHours = totalHours + int(hours)
return json.dumps(totalHours)
@main_bp.route("/laborStatusForm/modal/releaseAndRehire", methods=['POST'])
def releaseAndRehire():
try:
currentUser = require_login()
null=None; true = True; false= False
studentDict = eval(request.data.decode("utf-8"))
previousPrimaryPosition = FormHistory.select()\
.join_from(FormHistory, LaborStatusForm)\
.where(FormHistory.formID.termCode == studentDict["stuTermCode"], FormHistory.formID.studentSupervisee == studentDict["stuBNumber"], FormHistory.historyType == "Labor Status Form", FormHistory.formID.jobType == "Primary")\
.order_by(FormHistory.formHistoryID.desc())\
.get()
# Release previous labor status form
todayDate = date.today()
tomorrowDate = datetime.now()+timedelta(1)
createLaborReleaseForm(currentUser, previousPrimaryPosition.formID, tomorrowDate, "Satisfactory", "Released by labor admin.", "Approved", todayDate, currentUser)
# Create new labor status form
student = Student.get(Student.ID == studentDict['stuBNumber'])
supervisor = Supervisor.get(Supervisor.ID == studentDict['stuSupervisorID'])
department, created = Department.get_or_create(DEPT_NAME = studentDict['stuDepartment'])
term, created = Term.get_or_create(termCode = studentDict['stuTermCode'])
newLaborStatusForm = createLaborStatusForm(student, supervisor.ID, department.departmentID, term, studentDict)
formHistory = createOverloadFormAndFormHistory(studentDict, newLaborStatusForm, currentUser, host=request.host)
# Mark the newly created labor status form as approved in both our system and Banner
saveStatus("Approved", [str(formHistory.formHistoryID)], currentUser)
flash("Form has been successfully released and submitted.", "success")
return jsonify({"Success":True})
except Exception as e:
print("Error on release and rehire: ", e)
return jsonify({"Success": False})