diff --git a/app/controllers/admin_routes/adminManagement.py b/app/controllers/admin_routes/adminManagement.py index 68590cd70..4ce25af81 100644 --- a/app/controllers/admin_routes/adminManagement.py +++ b/app/controllers/admin_routes/adminManagement.py @@ -6,8 +6,6 @@ from flask import Flask, redirect, url_for, flash, jsonify from app.models.supervisor import Supervisor from app.models.student import Student -from app.logic.tracy import Tracy -from app.logic.userInsertFunctions import createStudentFromTracy, createSupervisorFromTracy, createUser from app.logic.adminManagement import searchForAdmin, getUser from app.logic.utils import adminFlashMessage diff --git a/app/controllers/admin_routes/allPendingForms.py b/app/controllers/admin_routes/allPendingForms.py index ef3499db2..bba1c9d3c 100644 --- a/app/controllers/admin_routes/allPendingForms.py +++ b/app/controllers/admin_routes/allPendingForms.py @@ -18,8 +18,6 @@ from app.models.formHistory import FormHistory from app.models.term import Term from app.logic.banner import Banner -from app.logic.tracy import Tracy -from app.models.Tracy.stuposn import STUPOSN from app.models.supervisor import Supervisor from app.models.student import Student from app.models.historyType import HistoryType diff --git a/app/controllers/admin_routes/manage_departments.py b/app/controllers/admin_routes/manage_departments.py index 6b16877cb..e4058b4e2 100644 --- a/app/controllers/admin_routes/manage_departments.py +++ b/app/controllers/admin_routes/manage_departments.py @@ -12,7 +12,6 @@ from flask import request, redirect from flask import jsonify from playhouse.shortcuts import model_to_dict -from app.logic.tracy import Tracy @admin.route('/admin/manageDepartments', methods=['GET']) # @login_required diff --git a/app/controllers/main_routes/alterLSF.py b/app/controllers/main_routes/alterLSF.py index c6edd850a..5a0ae07c0 100644 --- a/app/controllers/main_routes/alterLSF.py +++ b/app/controllers/main_routes/alterLSF.py @@ -6,7 +6,6 @@ from app.models.formHistory import FormHistory from app.models.user import User from app.models.supervisor import Supervisor -from app.logic.userInsertFunctions import createSupervisorFromTracy from app.logic.emailHandler import * from app.login_manager import require_login from app.logic.tracy import Tracy, InvalidQueryException @@ -27,7 +26,6 @@ def alterLSF(laborStatusKey): if not currentUser.isLaborAdmin: # Not an admin if currentUser.student and not currentUser.supervisor: # If a student is logged in and trying to get to this URL then send them back to their own page. return redirect("/laborHistory/" + currentUser.student.ID) - currentDate = date.today() #If logged in.... #Step 1: get form attached to the student (via labor history modal) @@ -37,7 +35,6 @@ def alterLSF(laborStatusKey): # Query the status of the form to determine if correction or adjust LSF formStatus = (FormHistory.get(FormHistory.formID == laborStatusKey).status_id) - if currentDate > form.termCode.adjustmentCutOff and formStatus == "Approved" and not currentUser.isLaborAdmin: return render_template("errors/403.html") #Step 2: get prefill data from said form, then the data that populates dropdowns for supervisors and position @@ -60,12 +57,21 @@ def alterLSF(laborStatusKey): totalHours += i.weeklyHours else: prefillhours = form.contractHours - #These are the data fields to populate our dropdowns(Supervisor. Position) - supervisors = Tracy().getSupervisors() - positions = Tracy().getPositionsFromDepartment(form.department.ORG, form.department.ACCOUNT) - departments = Tracy().getDepartments() - + supervisors = Supervisor.select() #.where(Supervisor.isActive) if we want supervisors to be active one + positions = ( + LaborStatusForm + .select(FormHistory, LaborStatusForm, Department) + .join(FormHistory, on=(FormHistory.formID == LaborStatusForm.laborStatusFormID)) + .switch(LaborStatusForm) + .join(Department, on=(LaborStatusForm.department == Department.departmentID)) + .where( + (Department.ACCOUNT == form.department.ACCOUNT) & + (Department.ORG == form.department.ORG) + ) + ) + positions = {position for position in positions} + departments = Department.select() # supervisors from the old system WILL have a Supervisor record, but might not have a Tracy record oldSupervisor = Supervisor.get_or_none(ID = form.supervisor.ID) if not oldSupervisor: @@ -119,7 +125,17 @@ def getDate(termcode): @main_bp.route("/alterLSF/fetchPositions//", methods=['GET']) def fetchPositions(departmentOrg, departmentAccount): currentUser = require_login() - positions = Tracy().getPositionsFromDepartment(departmentOrg, departmentAccount) + positions = ( + LaborStatusForm + .select(LaborStatusForm, FormHistory, Department) + .join(FormHistory, on=(FormHistory.formID == LaborStatusForm.laborStatusFormID)) + .switch(LaborStatusForm) + .join(Department, on=(LaborStatusForm.department == Department.departmentID)) + .where( + (Department.ACCOUNT == departmentAccount) & + (Department.ORG == departmentOrg) + ) + ) positionDict = {} for position in positions: if position.POSN_CODE != "S12345" or currentUser.isLaborAdmin: diff --git a/app/controllers/main_routes/laborHistory.py b/app/controllers/main_routes/laborHistory.py index bc916665d..73e22b50c 100755 --- a/app/controllers/main_routes/laborHistory.py +++ b/app/controllers/main_routes/laborHistory.py @@ -154,9 +154,16 @@ def populateModal(statusKey): form.adjustedForm.newValue = newSupervisor.FIRST_NAME +" "+ newSupervisor.LAST_NAME if form.adjustedForm.fieldAdjusted == "position": # if position field has been changed in adjust form then retriev position name. - newPosition = Tracy().getPositionFromCode(newValue) + newPosition = ( + LaborStatusForm + .select() + .where(LaborStatusForm.POSN_CODE == newValue) + .first() + ) try: - oldPosition = Tracy().getPositionFromCode(oldValue) + oldPosition = LaborStatusForm.get_or_none( + LaborStatusForm.POSN_CODE == oldValue + ) except: oldPosition = types.SimpleNamespace(POSN_TITLE="Unknown - " + oldValue, WLS="?") diff --git a/app/controllers/main_routes/laborStatusForm.py b/app/controllers/main_routes/laborStatusForm.py index dc794952d..529af12af 100755 --- a/app/controllers/main_routes/laborStatusForm.py +++ b/app/controllers/main_routes/laborStatusForm.py @@ -18,7 +18,6 @@ from app.logic.emailHandler import* from app.logic.userInsertFunctions import* from app.models.supervisor import Supervisor -from app.logic.tracy import Tracy from app.controllers.main_routes.laborReleaseForm import createLaborReleaseForm from app.logic.allPendingForms import saveStatus from app.logic.statusFormFunctions import * @@ -37,10 +36,10 @@ def laborStatusForm(laborStatusKey = None): return redirect('/laborHistory/' + currentUser.student.ID) # Logged in - students = Tracy().getStudents() + students = Student.select() terms = Term.select().where(Term.termState == "open") # changed to term state, open, closed, inactive - staffs = Tracy().getSupervisors() - departments = Tracy().getDepartments() + staffs = Supervisor.select() + departments = Department.select() # Only prepopulate form if current user is the supervisor or creator of the form. if laborStatusKey != None: @@ -77,7 +76,7 @@ def userInsert(): # Get a student record for the given bnumber try: student = getOrCreateStudentRecord(bnumber=rspFunctional[i]['stuBNumber']) - supervisor = createSupervisorFromTracy(bnumber=rspFunctional[i]['stuSupervisorID']) + supervisor = Supervisor.get(Supervisor.ID ==rspFunctional[i]['stuSupervisorID']) except InvalidUserException as e: print(e) return "", 500 @@ -119,7 +118,17 @@ def getDates(termcode): def getPositions(departmentOrg, departmentAcct): """ Get all of the positions that are in the selected department """ currentUser = require_login() - positions = Tracy().getPositionsFromDepartment(departmentOrg,departmentAcct) + positions = set( + LaborStatusForm + .select(FormHistory, LaborStatusForm, Department) + .join(FormHistory, on=(FormHistory.formID == LaborStatusForm.laborStatusFormID)) + .switch(LaborStatusForm) + .join(Department, on=(LaborStatusForm.department == Department.departmentID)) + .where( + (Department.ACCOUNT == departmentAcct) & + (Department.ORG == departmentOrg) + ) + ) positionDict = {} for position in positions: if position.POSN_CODE != "S12345" or currentUser.isLaborAdmin: @@ -187,8 +196,8 @@ def releaseAndRehire(): createLaborReleaseForm(currentUser, previousPrimaryPosition.formID, tomorrowDate, "Satisfactory", "Released by labor admin.", "Approved", todayDate, currentUser) # Create new labor status form - student = getOrCreateStudentRecord(bnumber=studentDict['stuBNumber']) - supervisor = createSupervisorFromTracy(bnumber=studentDict['stuSupervisorID']) + 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']) diff --git a/app/controllers/main_routes/search.py b/app/controllers/main_routes/search.py index e448affda..4fd312e24 100644 --- a/app/controllers/main_routes/search.py +++ b/app/controllers/main_routes/search.py @@ -1,6 +1,5 @@ from app.controllers.main_routes import main_bp from app.login_manager import require_login -from app.logic.tracy import Tracy, InvalidQueryException from app.logic.search import limitSearchByUserDepartment, studentDbToDict, usernameFromEmail from app.models.student import Student from app.models.laborStatusForm import LaborStatusForm @@ -33,7 +32,8 @@ def search(query=None): # bnumber search if re.match('[Bb]\d+', query): our_students = list(map(studentDbToDict, Student.select().where(Student.ID % "{}%".format(query.upper())))) - current_students = list(map(studentDbToDict, Tracy().getStudentsFromBNumberSearch(query))) + current_students = list(map(studentDbToDict, Student.select().where(Student.ID.contains(query)))) + # name search else: @@ -47,7 +47,7 @@ def search(query=None): results = Student.select().where((Student.preferred_name ** first_query | Student.legal_name ** first_query) & Student.LAST_NAME ** last_query) our_students = list(map(studentDbToDict, results)) - current_students = list(map(studentDbToDict, Tracy().getStudentsFromUserInput(query))) + current_students = list(map(studentDbToDict, Student.select().where((Student.LAST_NAME.contains(query)) | (Student.preferred_name.contains(query)) | (Student.legal_name.contains(query))))) # combine lists, remove duplicates, and then sort students = list({v['bnumber']:v for v in (current_students + our_students)}.values()) diff --git a/app/logic/adminManagement.py b/app/logic/adminManagement.py index 643fd7903..273e125ce 100644 --- a/app/logic/adminManagement.py +++ b/app/logic/adminManagement.py @@ -1,18 +1,19 @@ from peewee import DoesNotExist from app.models.user import User -from app.logic.tracy import Tracy from flask import request, flash from app.logic.userInsertFunctions import createStudentFromTracy, createSupervisorFromTracy, createUser - +from app.models.supervisor import Supervisor +from app.models.student import Student +from app.logic.tracy import Tracy def searchForAdmin(rsp): userInput = rsp[1] adminType = rsp[0] userList = [] if adminType == "addlaborAdmin": - tracyStudents = Tracy().getStudentsFromUserInput(userInput) + databaseStudents = Student.select().where(Student.legal_name.contains(userInput) | Student.preferred_name.contains(userInput)| Student.LAST_NAME.contains(userInput)) students = [] - for student in tracyStudents: + for student in databaseStudents: try: existingUser = User.get(User.student == student.ID) if existingUser.isLaborAdmin: @@ -28,9 +29,9 @@ def searchForAdmin(rsp): 'lastName': student.LAST_NAME, 'type': 'Student' }) - tracySupervisors = Tracy().getSupervisorsFromUserInput(userInput) + databaseSupervisors = Supervisor.select().where(Supervisor.legal_name.contains(userInput) | Supervisor.preferred_name.contains(userInput)| Supervisor.LAST_NAME.contains(userInput)) supervisors = [] - for supervisor in tracySupervisors: + for supervisor in databaseSupervisors: try: existingUser = User.get(User.supervisor == supervisor.ID) if ((existingUser.isLaborAdmin and adminType == "addlaborAdmin") diff --git a/app/logic/allPendingForms.py b/app/logic/allPendingForms.py index 60110d5ef..6175cd696 100644 --- a/app/logic/allPendingForms.py +++ b/app/logic/allPendingForms.py @@ -72,6 +72,7 @@ def saveStatus(new_status, formHistoryIds, currentUser): LSF = LaborStatusForm.get_by_id(formHistory.formID) overrideOriginalStatusFormOnAdjustmentFormApproval(formHistory, LSF) + else: print("Unable to update form status for formHistoryID {}.".format(id)) return jsonify({"success": False}), 500 @@ -105,7 +106,9 @@ def overrideOriginalStatusFormOnAdjustmentFormApproval(form, LSF): if form.adjustedForm.fieldAdjusted == "position": LSF.POSN_CODE = form.adjustedForm.newValue - position = Tracy().getPositionFromCode(form.adjustedForm.newValue) + position = LaborStatusForm.get_or_none( + LaborStatusForm.POSN_CODE == fieldsChanged[fieldName]["newValue"] + ) LSF.POSN_TITLE = position.POSN_TITLE LSF.WLS = position.WLS LSF.save() @@ -213,7 +216,12 @@ def modal_approval_and_denial_data(formHistoryIdList): if formHistory.adjustedForm: match formHistory.adjustedForm.fieldAdjusted: case "position": - position = Tracy().getPositionFromCode(formHistory.adjustedForm.newValue) + position = ( + LaborStatusForm + .select() + .where(LaborStatusForm.POSN_CODE == formHistory.adjustedForm.newValue) + .first() + ) position = position.POSN_TITLE case "supervisor": supervisor = Supervisor.get(Supervisor.ID == formHistory.adjustedForm.newValue) @@ -276,7 +284,12 @@ def checkAdjustment(allForms): if allForms.adjustedForm.fieldAdjusted == "position": newPositionCode = allForms.adjustedForm.newValue - newPosition = Tracy().getPositionFromCode(newPositionCode) + newPosition = ( + LaborStatusForm + .select() + .where(LaborStatusForm.POSN_CODE == newPositionCode) + .first() + ) # temporarily storing the position code and wls in new value, and position name in old value # because we want to show these information in the hmtl template. allForms.adjustedForm.newValue = newPosition.POSN_CODE +" (" + newPosition.WLS+")" diff --git a/app/logic/alterLSF.py b/app/logic/alterLSF.py index d77071624..6fbd4c5f8 100644 --- a/app/logic/alterLSF.py +++ b/app/logic/alterLSF.py @@ -21,7 +21,7 @@ def modifyLSF(fieldsChanged, fieldName, lsf, currentUser, host=None): lsf.supervisorNotes = noteEntry.notesContents lsf.save() if fieldName == "supervisor": - supervisor = createSupervisorFromTracy(bnumber=fieldsChanged[fieldName]["newValue"]) + supervisor = Supervisor.get(Supervisor.ID == fieldsChanged[fieldName]["newValue"]) lsf.supervisor = supervisor.ID lsf.save() @@ -31,7 +31,9 @@ def modifyLSF(fieldsChanged, fieldName, lsf, currentUser, host=None): lsf.save() if fieldName == "position": - position = Tracy().getPositionFromCode(fieldsChanged[fieldName]["newValue"]) + position = LaborStatusForm.get_or_none( + LaborStatusForm.POSN_CODE == fieldsChanged[fieldName]["newValue"] + ) lsf.POSN_CODE = position.POSN_CODE lsf.POSN_TITLE = position.POSN_TITLE lsf.WLS = position.WLS diff --git a/app/logic/departmentPositions.py b/app/logic/departmentPositions.py deleted file mode 100644 index cd6ca53b6..000000000 --- a/app/logic/departmentPositions.py +++ /dev/null @@ -1,43 +0,0 @@ -from app.logic.tracy import Tracy, InvalidQueryException -from app.models.department import Department -from app.logic.userInsertFunctions import updateDepartmentRecord -from app.models.Tracy.stuposn import STUPOSN - - -def updatePositionRecords(): - remoteDepartments = Tracy().getDepartments() # Create local copies of new departments in Tracy - departmentsPulledFromTracy = 0 - for dept in remoteDepartments: - d = Department.get_or_none(ACCOUNT=dept.ACCOUNT, ORG=dept.ORG) - if d: - d.DEPT_NAME = dept.DEPT_NAME - d.save() - else: - Department.create(DEPT_NAME=dept.DEPT_NAME, ACCOUNT=dept.ACCOUNT, ORG=dept.ORG) - departmentsPulledFromTracy += 1 - - departmentsInDB = list(Department.select()) - departmentsUpdated = 0 - departmentsNotFound = 0 - departmentsFailed = 0 - for department in departmentsInDB: - try: - updateDepartmentRecord(department) - departmentsUpdated += 1 - except InvalidQueryException as e: - departmentsNotFound += 1 - except Exception as e: - departmentsFailed += 1 - - return departmentsPulledFromTracy, departmentsUpdated, departmentsNotFound, departmentsFailed - -def updateDepartmentRecord(department): - tracyDepartment = STUPOSN.query.filter((STUPOSN.ORG == department.ORG) & (STUPOSN.ACCOUNT == department.ACCOUNT)).first() - - department.isActive = bool(tracyDepartment) - if tracyDepartment is None: - raise InvalidQueryException("Department ({department.ORG}, {department.ACCOUNT}) not found") - - - department.DEPT_NAME = tracyDepartment.DEPT_NAME - department.save() diff --git a/app/logic/emailHandler.py b/app/logic/emailHandler.py index 1de8ef492..d4edbf19f 100644 --- a/app/logic/emailHandler.py +++ b/app/logic/emailHandler.py @@ -11,7 +11,6 @@ from app.models.student import* from datetime import datetime from app.models.emailTracker import * -from app.logic.tracy import Tracy import string from app import app import os @@ -69,13 +68,22 @@ def __init__(self, formHistoryKey): if self.formHistory.adjustedForm: if self.formHistory.adjustedForm.fieldAdjusted == "supervisor": - from app.logic.userInsertFunctions import createSupervisorFromTracy - newSupervisor = createSupervisorFromTracy(bnumber=self.formHistory.adjustedForm.newValue) + newSupervisor = Supervisor.select().where(Supervisor.ID == self.formHistory.adjustedForm.newValue) self.newAdjustmentField = "Pending new Supervisor: {0} {1}".format(newSupervisor.FIRST_NAME, newSupervisor.LAST_NAME) self.oldAdjustmentField = "Current Supervisor: {0} {1}".format(self.formHistory.formID.supervisor.FIRST_NAME, self.formHistory.formID.supervisor.LAST_NAME) elif self.formHistory.adjustedForm.fieldAdjusted == "position": - currentPosition = Tracy().getPositionFromCode(self.formHistory.adjustedForm.oldValue) - newPosition = Tracy().getPositionFromCode(self.formHistory.adjustedForm.newValue) + currentPosition = ( + LaborStatusForm + .select() + .where(LaborStatusForm.POSN_CODE == self.formHistory.adjustedForm.oldValue) + .first() + ) + newPosition = ( + LaborStatusForm + .select() + .where(LaborStatusForm.POSN_CODE == self.formHistory.adjustedForm.newValue) + .first() + ) self.oldAdjustmentField = "Current Position: {0} ({1})".format(currentPosition.POSN_TITLE, currentPosition.WLS) self.newAdjustmentField = "Pending new Position: {0} ({1})".format(newPosition.POSN_TITLE, newPosition.WLS) else: diff --git a/app/logic/statusFormFunctions.py b/app/logic/statusFormFunctions.py index 4694bad63..832f3fe94 100644 --- a/app/logic/statusFormFunctions.py +++ b/app/logic/statusFormFunctions.py @@ -5,7 +5,6 @@ from app.models.formHistory import* from app.logic.emailHandler import emailHandler from app.logic.utils import makeThirdPartyLink, calculateExpirationDate -from app.logic.tracy import Tracy, InvalidQueryException from flask import request, json, jsonify from functools import reduce import operator diff --git a/app/logic/userInsertFunctions.py b/app/logic/userInsertFunctions.py index 5e77212d3..ad07988b2 100644 --- a/app/logic/userInsertFunctions.py +++ b/app/logic/userInsertFunctions.py @@ -13,7 +13,7 @@ from app.models.supervisor import Supervisor from app.models.department import * from app.logic.tracy import Tracy, InvalidQueryException, InvalidUserException - +from app.models.Tracy.stuposn import STUPOSN def updatePersonRecords(): """ @@ -226,3 +226,41 @@ def createSupervisorFromTracy(username=None, bnumber=None): except Exception as e: print(e) raise InvalidUserException("Error: Could not get or create {0} {1}".format(tracyUser.FIRST_NAME, tracyUser.LAST_NAME)) + +def updatePositionRecords(): + remoteDepartments = Tracy().getDepartments() # Create local copies of new departments in Tracy + departmentsPulledFromTracy = 0 + for dept in remoteDepartments: + d = Department.get_or_none(ACCOUNT=dept.ACCOUNT, ORG=dept.ORG) + if d: + d.DEPT_NAME = dept.DEPT_NAME + d.save() + else: + Department.create(DEPT_NAME=dept.DEPT_NAME, ACCOUNT=dept.ACCOUNT, ORG=dept.ORG) + departmentsPulledFromTracy += 1 + + departmentsInDB = list(Department.select()) + departmentsUpdated = 0 + departmentsNotFound = 0 + departmentsFailed = 0 + for department in departmentsInDB: + try: + updateDepartmentRecord(department) + departmentsUpdated += 1 + except InvalidQueryException as e: + departmentsNotFound += 1 + except Exception as e: + departmentsFailed += 1 + + return departmentsPulledFromTracy, departmentsUpdated, departmentsNotFound, departmentsFailed + +def updateDepartmentRecord(department): + tracyDepartment = STUPOSN.query.filter((STUPOSN.ORG == department.ORG) & (STUPOSN.ACCOUNT == department.ACCOUNT)).first() + + department.isActive = bool(tracyDepartment) + if tracyDepartment is None: + raise InvalidQueryException("Department ({department.ORG}, {department.ACCOUNT}) not found") + + + department.DEPT_NAME = tracyDepartment.DEPT_NAME + department.save() diff --git a/app/login_manager.py b/app/login_manager.py index 49f67016d..c1c68b4c6 100755 --- a/app/login_manager.py +++ b/app/login_manager.py @@ -3,7 +3,7 @@ from app.controllers.errors_routes.handlers import * from app.models.user import User, DoesNotExist from app.models.term import Term -from app.logic.userInsertFunctions import createSupervisorFromTracy, createStudentFromTracy, updateUserFromTracy, createUser +from app.logic.userInsertFunctions import createSupervisorFromTracy, createStudentFromTracy, createUser from app.logic.tracy import InvalidUserException def getUsernameFromEnv(env): @@ -38,10 +38,9 @@ def require_login(): return False # Update the user's name - user = updateUserFromTracy(user) + user = User.get(User.userID == user.userID) if 'username' not in session: - print("Logging in as", user.username) session['username'] = user.username return user @@ -63,13 +62,9 @@ def auth_user(env, username): description = env['description'].lower() supervisor = student = None if description == 'student': - print("Adding {} to student table".format(username)) student = createStudentFromTracy(username) else: - print("Adding {} to supervisor table".format(username)) supervisor = createSupervisorFromTracy(username) - - print("Creating record for {} in user table".format(username)) return createUser(username, student=student, supervisor=supervisor) def getOpenTerm(): diff --git a/db_test.py b/db_test.py deleted file mode 100644 index 2afe0f525..000000000 --- a/db_test.py +++ /dev/null @@ -1,70 +0,0 @@ -import pyodbc - -details = { - "user": "ute_limited", - "password": "REPLACE", - "server": "timemachine1sql.berea.edu", - "db": "UTE" -} - -########################### -# Test pyodbc connection -########################### - -pyodbc_uri = 'DRIVER=FreeTDS;SERVER={};PORT=1433;DATABASE={};UID={};PWD={};TDS_Version=8.0;'.format(details['server'],details['db'],details['user'],details['password']) -pyconn = pyodbc.connect(pyodbc_uri) -c = pyconn.cursor() -for row in c.execute('select * from STUPOSN'): - print("PYODBC:",row) - break - -########################### -# Test SQL Alchemy with pyodbc -########################### - -from urllib.parse import quote -import sqlalchemy - -# SAWarning: No driver name specified; this is expected by PyODBC when using DSN-less connections -#uri = "mssql+pyodbc://{}:{}@{}/{}".format(details['user'], details['password'], details['server'], details['db']) - -# No driver name specified -#uri = "mssql+pyodbc://{}:{}@{}/{}?DRIVER=FreeTDS".format(details['user'], details['password'], details['server'], details['db']) -uri = "mssql+pyodbc:///?odbc_connect=" + quote('DRIVER=FreeTDS;SERVER={};PORT=1433;DATABASE={};UID={};PWD={};TDS_Version=8.0;'.format(details['server'], details['db'], details['user'], details['password'])) - -engine = sqlalchemy.create_engine(uri) -for row in engine.execute('select * from STUPOSN'): - print("SQLALCHEMY:",row) - break - -########################### -# Test SQL Alchemy with app configuration -########################### - -from flask_sqlalchemy import SQLAlchemy -from app import load_config, app -from app.logic.tracy import Tracy - -cfg = load_config('app/config/secret_config.yaml') -app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - -uri = "mssql+pyodbc:///?odbc_connect=" + quote('DRIVER=FreeTDS;SERVER={};PORT=1433;DATABASE={};UID={};PWD={};TDS_Version=8.0;'.format(details['server'], details['db'], details['user'], details['password'])) - -app.config['SQLALCHEMY_DATABASE_URI'] = uri -db = SQLAlchemy(app) - -print("FLASK:",Tracy().getPositionFromCode("S01015")) - -########################### -# Test Banner connection -########################### - -from app.logic.banner import Banner -from app.models.formHistory import FormHistory -b = Banner() -cursor = b.conn.cursor() -print(cursor) - -# NOT FOR PROD -# b.insert(FormHistory.get_by_id(39061)) - diff --git a/tests/code/test_alterLSF.py b/tests/code/test_alterLSF.py index 24400e865..14cb41ddf 100644 --- a/tests/code/test_alterLSF.py +++ b/tests/code/test_alterLSF.py @@ -1,6 +1,6 @@ import pytest from app import app -from app.controllers.main_routes.alterLSF import modifyLSF, adjustLSF +from app.controllers.main_routes.alterLSF import modifyLSF, adjustLSF, fetchPositions, alterLSF from app.logic.statusFormFunctions import createOverloadForm from app.models.user import User from app.models.laborStatusForm import LaborStatusForm @@ -9,7 +9,16 @@ from app.models.formHistory import FormHistory from datetime import date, datetime from app.logic.statusFormFunctions import createOverloadForm - +from app.models import mainDB +from app.models.supervisor import Supervisor +from app.models.department import Department +from app.models.laborStatusForm import LaborStatusForm +from app.models.term import Term +from app.models.student import Student +from app.models.historyType import HistoryType +from app.models.status import Status +from flask import json, template_rendered +from contextlib import contextmanager @pytest.fixture def setup(): @@ -67,6 +76,67 @@ def resetLSF(): @pytest.mark.integration def test_adjustLSF(setup): with app.test_request_context(): + term = Term.create( + termCode=999999, + termName="Test Term", + termStart=date(2020, 7, 1), + termEnd=date(2020, 12, 31), + termState=True + ) + student = Student.create( + ID="B12345678", + preferred_name="Nyan", + legal_name="Nyan", + LAST_NAME="Zaw", + STU_EMAIL="imran@berea.edu" + ) + dept = Department.create( + DEPT_NAME="SSDT", + ACCOUNT="SSDTACC", + ORG="SSDTORG" + ) + supervisor = Supervisor.create(ID="B12361006") + supervisorOld = Supervisor.create(ID="B12365892") + + lsf = LaborStatusForm.create( + laborStatusFormID=2, + termCode=term, + studentSupervisee=student, + supervisor=supervisor, + department=dept, + jobType="Primary", + WLS="OLDWLS", + POSN_TITLE="Old Position", + POSN_CODE="S61419", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes." + ) + LaborStatusForm.create( + laborStatusFormID=2001, + termCode=term, + studentSupervisee=student, + supervisor=supervisorOld, + department=dept, + jobType="Primary", + WLS="OLDWLS", + POSN_TITLE="Old Position Title", + POSN_CODE="S61419" + ) + + # New position code row + LaborStatusForm.create( + laborStatusFormID=2002, + termCode=term, + studentSupervisee=student, + supervisor=supervisorOld, + department=dept, + jobType="Primary", + WLS="NEWWLS", + POSN_TITLE="New Position Title", + POSN_CODE="S61407" + ) + fieldName = 'supervisorNotes' adjustLSF(fieldsChanged, fieldName, lsf, currentUser) assert Notes.get(Notes.notesContents == 'new notes.') @@ -106,35 +176,95 @@ def test_adjustLSF(setup): @pytest.mark.integration def test_modifyLSF(setup): + with mainDB.transaction() as transaction: - with app.test_request_context(): - fieldName = 'supervisorNotes' - modifyLSF(fieldsChanged, fieldName, lsf, currentUser) - assert lsf.supervisorNotes == 'new notes.' + term = Term.create( + termCode=22332, + termName="Test Term", + termStart=date(2020, 7, 1), + termEnd=date(2020, 12, 31), + termState=True + ) + student = Student.create( + ID="B12332123", + preferred_name="Nyan", + legal_name="Nyan", + LAST_NAME="Zaw", + STU_EMAIL="imran@berea.edu" + ) + dept = Department.create( + DEPT_NAME="SSDT", + ACCOUNT="SSDTACC", + ORG="SSDTORG" + ) + oldSupervisor = Supervisor.get_or_none(Supervisor.ID == "B12361006") + if oldSupervisor is None: + oldSupervisor = Supervisor.create(ID="B12361006") + newSupervisor = Supervisor.get_or_none(Supervisor.ID == "B12365892") + if newSupervisor is None: + newSupervisor = Supervisor.create(ID="B12365892") + lsf = LaborStatusForm.create( + laborStatusFormID=98765, + termCode=term, + studentSupervisee=student, + supervisor=oldSupervisor, + department=dept, + jobType="Primary", + WLS="OLDWLS", + POSN_TITLE="Old Position", + POSN_CODE="S61419", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes." + ) + LaborStatusForm.create( + laborStatusFormID=98766, + termCode=term, + studentSupervisee=student, + supervisor=oldSupervisor, + department=dept, + jobType="Primary", + WLS="OLDWLS", + POSN_TITLE="Old Position Title", + POSN_CODE="S61419" + ) + LaborStatusForm.create( + laborStatusFormID=98767, + termCode=term, + studentSupervisee=student, + supervisor=oldSupervisor, + department=dept, + jobType="Primary", + WLS="NEWWLS", + POSN_TITLE="New Position Title", + POSN_CODE="S61407" + ) - fieldName = 'supervisor' - modifyLSF(fieldsChanged, fieldName, lsf, currentUser) - assert lsf.supervisor.ID == 'B12365892' + with app.test_request_context(): + fieldName = 'supervisorNotes' + modifyLSF(fieldsChanged, fieldName, lsf, currentUser) + assert lsf.supervisorNotes == 'new notes.' - fieldName = 'position' - modifyLSF(fieldsChanged, fieldName, lsf, currentUser) - assert lsf.POSN_CODE == 'S61407' + fieldName = 'supervisor' + modifyLSF(fieldsChanged, fieldName, lsf, currentUser) + assert lsf.supervisor.ID == 'B12365892' - fieldName = 'weeklyHours' - modifyLSF(fieldsChanged, fieldName, lsf, currentUser) - assert lsf.weeklyHours == 12 + fieldName = 'position' + modifyLSF(fieldsChanged, fieldName, lsf, currentUser) + assert lsf.POSN_CODE == 'S61407' - # Modified verload - modifyLSF(fieldsChangedOverload, fieldName, lsf, currentUser) - assert lsf.weeklyHours == 20 - formHistory = FormHistory.get((FormHistory.formID == lsf.laborStatusFormID) & - (FormHistory.historyType == 'Labor Overload Form')) - assert formHistory.historyType.historyTypeName == 'Labor Overload Form' + fieldName = 'weeklyHours' + modifyLSF(fieldsChanged, fieldName, lsf, currentUser) + assert lsf.weeklyHours == 12 - fieldName = 'contractHours' - modifyLSF(fieldsChangedContractHours, fieldName, lsf, currentUser) - assert lsf.contractHours == 60 - resetLSF() + modifyLSF(fieldsChangedOverload, fieldName, lsf, currentUser) + assert lsf.weeklyHours == 20 + + fieldName = 'contractHours' + modifyLSF(fieldsChangedContractHours, fieldName, lsf, currentUser) + assert lsf.contractHours == 60 + resetLSF() + transaction.rollback() @pytest.mark.integration def test_createOverloadForm(setup): @@ -165,3 +295,216 @@ def test_createOverloadForm(setup): assert adjustedForm.newValue == '20' formHistory = FormHistory.get((FormHistory.formID == lsf.laborStatusFormID) & (FormHistory.historyType == 'Labor Overload Form')) assert formHistory.historyType.historyTypeName == 'Labor Overload Form' + +@pytest.mark.integration +def test_fetchPositions(setup): + with mainDB.transaction() as transaction: + deptOk = Department.create(DEPT_NAME="SSDT", ACCOUNT="SSDTACC", ORG="SSDTORG") + deptOther = Department.create(DEPT_NAME="OTHER", ACCOUNT="OTHERACC", ORG="OTHERORG") + term = Term.create(termCode=22332, termName="T", termStart="2020-07-01", termEnd="2020-12-31", termState=True) + student = Student.create(ID="B1", preferred_name="N", legal_name="N", LAST_NAME="Z", STU_EMAIL="x@x.com") + supervisor = Supervisor.create(ID="S1") + lsfGood = LaborStatusForm.create( + laborStatusFormID=98765, + termCode=term, + studentSupervisee=student, + supervisor=supervisor, + department=deptOk, + jobType="Primary", + WLS="W1", + POSN_TITLE="Good Position", + POSN_CODE="S61407", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes." + ) + lsfDummy = LaborStatusForm.create( + laborStatusFormID=98766, + termCode=term, + studentSupervisee=student, + supervisor=supervisor, + department=deptOk, + jobType="Primary", + WLS="WD", + POSN_TITLE="Dummy Position", + POSN_CODE="S12345", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes." + ) + lsfOther = LaborStatusForm.create( + laborStatusFormID=98767, + termCode=term, + studentSupervisee=student, + supervisor=supervisor, + department=deptOther, + jobType="Primary", + WLS="Wo", + POSN_TITLE="Other Dept Position", + POSN_CODE="S99999", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes." + ) + status_obj, _ = Status.get_or_create(statusName="Approved") + history_type_obj, _ = HistoryType.get_or_create(historyTypeName="Labor Status Form") + currentUser = User.get(User.userID == 3) + FormHistory.create( + formID=lsfGood, + historyType=history_type_obj, + createdBy=currentUser, + createdDate=date.today(), + status=status_obj + ) + FormHistory.create( + formID=lsfDummy, + historyType=history_type_obj, + createdBy=currentUser, + createdDate=date.today(), + status=status_obj + ) + FormHistory.create( + formID=lsfOther, + historyType=history_type_obj, + createdBy=currentUser, + createdDate=date.today(), + status=status_obj + ) + + with app.test_request_context(): + positions = json.loads(fetchPositions("SSDTORG", "SSDTACC")) + assert "S61407" in positions + assert positions["S61407"]["POSN_TITLE"] == "Good Position" + assert positions["S61407"]["WLS"] == "W1" + assert positions["S61407"]["POSN_CODE"] == "S61407" + assert "S12347" not in positions + assert "S99999" not in positions + + resetLSF() + transaction.rollback() + +@pytest.mark.integration +def test_alterLSF(setup): + with mainDB.transaction() as transaction: + deptOk = Department.create(DEPT_NAME="SSDT", ACCOUNT="SSDTACC", ORG="SSDTORG") + deptOther = Department.create(DEPT_NAME="OTHER", ACCOUNT="OTHERACC", ORG="OTHERORG") + term = Term.create( + termCode=22332, + termName="T", + termStart=date(2020, 7, 1), + termEnd=date(2020, 12, 31), + termState=True, + adjustmentCutOff=date(2099, 1, 1), + ) + student = Student.create( + ID="B12332123", + preferred_name="Nyan", + legal_name="Nyan", + LAST_NAME="Zaw", + STU_EMAIL="imran@berea.edu" + ) + supervisor1 = Supervisor.get_or_none(Supervisor.ID == "B12361007") + if supervisor1 is None: + supervisor1 = Supervisor.create(ID="B12361007", PIDM = 14578, LAST_NAME = "Bledsoe", legal_name = "Finn", preferred_name = "Finn", EMAIL="bledsoef@berea.edu", CPO="5467", DEPT_Name="SSDT") + supervisor2 = Supervisor.get_or_none(Supervisor.ID == "B12365892") + if supervisor2 is None: + supervisor2 = Supervisor.create(ID="B12365892", PIDM = 14579, LAST_NAME = "Bledsoe", legal_name = "Jason", preferred_name = "Jason", EMAIL="bledsoej@berea.edu", CPO="5468", DEPT_Name="SSDT") + currentUser = User.get(User.userID == 3) + status, _ = Status.get_or_create(statusName="Approved") + historyType, _ = HistoryType.get_or_create(historyTypeName="Labor Status Form") + lsfGood = LaborStatusForm.create( + laborStatusFormID=98765, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOk, + jobType="Primary", + WLS="W1", + POSN_TITLE="Good Position", + POSN_CODE="S61407", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + lsfDummy = LaborStatusForm.create( + laborStatusFormID=98766, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOk, + jobType="Primary", + WLS="WD", + POSN_TITLE="Dummy Position", + POSN_CODE="S12345", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + lsfOther = LaborStatusForm.create( + laborStatusFormID=98767, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOther, + jobType="Primary", + WLS="WO", + POSN_TITLE="Other Dept Position", + POSN_CODE="S99999", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + FormHistory.create( + formID=lsfGood, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + FormHistory.create( + formID=lsfDummy, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + FormHistory.create( + formID=lsfOther, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + with app.test_request_context(): + with renderedTemplate(app) as templates: + alterLSF(lsfGood.laborStatusFormID) + template, ctx = templates[0] + supervisors = [s.ID for s in ctx["supervisors"]] + assert "B12361006" in supervisors + assert "B12365892" in supervisors + departments = {d.departmentID for d in ctx["departments"]} + assert deptOk.departmentID in departments + assert deptOther.departmentID in departments + positions = ctx["positions"] + positionIDs = { + p.formID.laborStatusFormID if hasattr(p, "formID") + else p.laborStatusFormID + for p in positions + } + assert lsfGood.laborStatusFormID in positionIDs + assert lsfDummy.laborStatusFormID in positionIDs + assert lsfOther.laborStatusFormID not in positionIDs + resetLSF() + transaction.rollback() + +@contextmanager +def renderedTemplate(app): + recorded = [] + def record(sender, template, context, **extra): + recorded.append((template, context)) + + template_rendered.connect(record, app) + try: + yield recorded + finally: + template_rendered.disconnect(record, app) \ No newline at end of file diff --git a/tests/code/test_laborStatusForm.py b/tests/code/test_laborStatusForm.py new file mode 100644 index 000000000..f5cd2d350 --- /dev/null +++ b/tests/code/test_laborStatusForm.py @@ -0,0 +1,176 @@ +import pytest +from app import app +from app.controllers.main_routes.laborStatusForm import getPositions +from app.logic.statusFormFunctions import createOverloadForm +from app.models.user import User +from app.models.laborStatusForm import LaborStatusForm +from app.models.notes import Notes +from app.models.adjustedForm import AdjustedForm +from app.models.formHistory import FormHistory +from datetime import date, datetime +from app.logic.statusFormFunctions import createOverloadForm +from app.models import mainDB +from app.models.supervisor import Supervisor +from app.models.department import Department +from app.models.laborStatusForm import LaborStatusForm +from app.models.term import Term +from app.models.student import Student +from app.models.historyType import HistoryType +from app.models.status import Status +from flask import json, template_rendered +from contextlib import contextmanager + +@pytest.fixture +def setup(): + delete_forms() + + yield + +@pytest.fixture +def cleanup(): + yield + delete_forms() + + +def delete_forms(): + formHistories = FormHistory.select().where((FormHistory.formID == 2) & (FormHistory.historyType == "Labor Adjustment Form")) + FormHistory.delete().where((FormHistory.formID == 2) & (FormHistory.historyType == "Labor Overload Form")).execute() + for form in formHistories: + # form.delete().execute() + AdjustedForm.delete().where(AdjustedForm.adjustedFormID == form.adjustedForm.adjustedFormID).execute() + Notes.delete().where(Notes.formID.cast('char').contains("2")).execute() + +def resetLSF(): + lsfInfo = { + "supervisorNotes":"", + "supervisor" : "B12361006", + "position":"S61419", + "weeklyHours":10, + "contractHours": None + } + + lsf.supervisorNotes = lsfInfo["supervisorNotes"] + lsf.save() + lsf.supervisor = lsfInfo["supervisor"] + lsf.save() + lsf.position = lsfInfo["position"] + lsf.save() + lsf.weeklyHours = lsfInfo["weeklyHours"] + lsf.save() + lsf.contractHours = lsfInfo["contractHours"] + lsf.save() + + +currentUser = User.get(User.userID == 1) # Scott Heggen's entry in User table +lsf = LaborStatusForm.get(LaborStatusForm.laborStatusFormID == 2) +fieldsChanged = {'supervisor':{'oldValue':'B12361006', 'newValue':'B12365892','date':'07/21/2020'}, + 'weeklyHours':{'oldValue': '10', 'newValue': '12', 'date': '07/21/2020'}, + 'position':{'oldValue': 'S61419', 'newValue': 'S61407', 'date': '07/21/2020'}, + 'supervisorNotes':{'oldValue':'old notes.', 'newValue':'new notes.'} + } + +fieldsChangedOverload = {'weeklyHours': {'oldValue':'10', 'newValue':'20', 'date': '07/21/2020'}} + +fieldsChangedContractHours = {'contractHours':{'oldValue': '40', 'newValue': '60', 'date': '07/21/2020'}} + +@pytest.mark.integration +def test_getPositions(setup): + with mainDB.transaction() as transaction: + deptOk = Department.create(DEPT_NAME="SSDT", ACCOUNT="SSDTACC", ORG="SSDTORG") + deptOther = Department.create(DEPT_NAME="OTHER", ACCOUNT="OTHERACC", ORG="OTHERORG") + term = Term.create( + termCode=22332, + termName="Fall 2020", + termStart=date(2020, 7, 1), + termEnd=date(2020, 12, 31), + termState=True, + adjustmentCutOff=date(2099, 1, 1), + ) + student = Student.create( + ID="B12332123", + preferred_name="Nyan", + legal_name="Nyan", + LAST_NAME="Zaw", + STU_EMAIL="imran@berea.edu" + ) + supervisor1 = Supervisor.get_or_none(Supervisor.ID == "B12361007") + if supervisor1 is None: + supervisor1 = Supervisor.create(ID="B12361007", PIDM = 14578, LAST_NAME = "Bledsoe", legal_name = "Finn", preferred_name = "Finn", EMAIL="bledsoef@berea.edu", CPO="5467", DEPT_Name="SSDT") + supervisor2 = Supervisor.get_or_none(Supervisor.ID == "B12365892") + if supervisor2 is None: + supervisor2 = Supervisor.create(ID="B12365892", PIDM = 14579, LAST_NAME = "Bledsoe", legal_name = "Jason", preferred_name = "Jason", EMAIL="bledsoej@berea.edu", CPO="5468", DEPT_Name="SSDT") + currentUser = User.get(User.userID == 3) + status, _ = Status.get_or_create(statusName="Approved") + historyType, _ = HistoryType.get_or_create(historyTypeName="Labor Status Form") + lsfGood = LaborStatusForm.create( + laborStatusFormID=98765, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOk, + jobType="Primary", + WLS="W1", + POSN_TITLE="Good Position", + POSN_CODE="S61407", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + lsfDummy = LaborStatusForm.create( + laborStatusFormID=98766, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOk, + jobType="Primary", + WLS="WD", + POSN_TITLE="Dummy Position", + POSN_CODE="S12345", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + lsfOther = LaborStatusForm.create( + laborStatusFormID=98767, + termCode=term, + studentSupervisee=student, + supervisor=supervisor1, + department=deptOther, + jobType="Primary", + WLS="WO", + POSN_TITLE="Other Dept Position", + POSN_CODE="S99999", + contractHours=40, + weeklyHours=10, + supervisorNotes="old notes.", + ) + FormHistory.create( + formID=lsfGood, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + FormHistory.create( + formID=lsfDummy, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + FormHistory.create( + formID=lsfOther, + historyType=historyType, + createdBy=currentUser, + createdDate=date.today(), + status=status, + ) + with app.test_request_context(): + positions = json.loads(getPositions("SSDTORG", "SSDTACC")) + assert "S12345" in positions + assert "S61407" in positions + + assert positions["S12345"]["position"] == "Dummy Position" + assert positions["S61407"]["position"] == "Good Position" + resetLSF() + transaction.rollback()