def AddWaste(): #function is what is run to render the right page, if GET, it shows the create container view which allows form entry for container #if Post, it creates a row entry to the database for waste containers with a relevant message for success. auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": if request.method == "GET": return render_template("views/AddWasteContainerView.html", authLevel=userLevel, config=config, chemConfig=chemConfig, wasteConfig=wasteConfig) status, flashMessage, flashFormat, wCont = createWaste( request.form) # Function located in wasteContainersModel.py flash(flashMessage, flashFormat) print wCont.wID #if status: # Chemical created successfully # return redirect(url_for('ViewChemical', chemId = newChem.chemId)) #Redirect to the new chemical page #else: return redirect(url_for('AddWasteItem', wID=wCont.wID)) else: abort(403)
def AddChemical(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": if request.method == "GET": return render_template("views/AddChemicalView.html", authLevel=userLevel, config=config, chemConfig=chemConfig) status, flashMessage, flashFormat, newChem = createChemical( request.form) # Function located in chemicalsModel.py flash(flashMessage, flashFormat) if status: # Chemical created successfully return redirect(url_for( 'ViewChemical', chemId=newChem.chemId)) #Redirect to the new chemical page else: return render_template("views/AddChemicalView.html", authLevel=userLevel, config=config, chemConfig=chemConfig) else: abort(403)
def AddWasteChemical(wID): #function is what is run to render the right page, if GET, it shows the create chemical view which allows form entry for chemicals #if Post, it creates a row entry to the database for waste chemicals as well as a row entry for contents to #show which container the chemical is in with a relevant message for success. auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": if request.method == "GET": return render_template("views/AddWasteChemicalView.html", authLevel = userLevel, config = config, wasteConfig = wasteConfig) status, flashMessage, flashFormat, wChem = createWasteChemical(request.form) # Function located in wasteChemicalsModel.py flash(flashMessage, flashFormat) print(wID) contentData= {'wCHEMID':unicode(str(wChem.wCHEMID), "utf-8"),'wID':unicode(str(wID), "utf-8")} status, flashMessage, flashFormat, wCont = createWasteItem(contentData) # Function located in wasteContentsModel.py flash(flashMessage, flashFormat) return redirect(url_for('AddWasteItem', wID = wID)) else: abort(403)
def report(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == 'admin' or userLevel == 'superUser' or userLevel == 'systemAdmin': if request.method == "GET": allBuild = getBuildings() inputs = [None] * len(reportConfig.ReportTypes.Inputs) for key in reportConfig.ReportTypes.Inputs: index = reportConfig.ReportTypes.Inputs[key] inputs[index] = key return render_template("views/ReportView.html", authLevel=userLevel, config=config, reportConfig=reportConfig, inputs=inputs, allBuild=allBuild) else: data = request.form locData = genLocationReport(data) path = os.path.join(current_app.root_path, 'reports') #make the directory if it doesn't exist try: os.makedirs(path) except: pass reportName = exportExcel( "Report", reportConfig["ReportTypes"]["LocationBased"] ["LocationQuantity"]["row_title"], reportConfig["ReportTypes"] ["LocationBased"]["LocationQuantity"]["queries"], locData, path) return redirect("/download/" + reportName)
def CheckOut(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": storageList = getStorages() buildingList = getBuildings() if request.method == "POST": data = request.form cont = getContainer(data['barcodeId']) updateHistory(cont, "Checked Out", data['storageId'], user.username) changeLocation(cont, True, data, user.username) flash('Container Checked Out','list-group-item list-group-item-success') return render_template("views/CheckOutView.html", config = config, contConfig = contConfig, container = None, #container = None is needed as a placeholder for the page before the barcode is entered. buildingList = buildingList, storageList = storageList, pageConfig = checkOutConfig, authLevel = userLevel, user = user) else: # This will later have a slightly different render_template. To allow for all other users to access a specific checkout page. abort(403)
def CheckIn(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": storageList = getStorages() buildingList = getBuildings() if request.method == "POST": data = request.form cont = getContainer(data['barcodeId']) updateHistory(cont, "Checked In", data['storageId'], user.username) # updateHistory located in historiesModel.py changeLocation(cont, False, data, user.username) # changeLocation located in containersModel.py flash('Container Checked In','list-group-item list-group-item-success') # Move Try and Except to containersModel.py changeLocation() """try: data = request.form cont = Containers.get(Containers.barcodeId == data['barcodeId']) Histories.create(movedFrom = cont.storageId, movedTo = data['storageId'], containerId = cont.conId, modUser = user.username, action = "Checked In", pastQuantity = "%s %s" %(cont.currentQuantity, cont.currentQuantityUnit)) cont.storageId = data['storageId'] cont.currentQuantity = data['currentQuantity'] cont.currentQuantityUnit = data['currentQuantityUnit'] cont.checkedOut = False cont.checkOutReason ='' cont.forProf = '' cont.checkedOutBy = '' cont.save() flash(data['barcodeId']+" Successfully Checked-In") except: flash("Failed to Check-In "+ data['barcodeId'])""" return render_template("views/CheckInView.html", config = config, contConfig = contConfig, container = None, #container = None is needed as a placeholder for the page before the barcode is entered. buildingList = buildingList, storageList = storageList, pageConfig = checkInConfig, authLevel = userLevel) else: # This will also be replaced for a specific checkin control for all other users abort(403)
def ChemTable(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel chemicals = getChemicals() #Get all chemicals from the database contDict = contCount(chemicals) return render_template("views/ChemTableView.html", config=config, chemicals=chemicals, contDict=contDict, quote=quote, authLevel=userLevel)
def maDelete(location, lId): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel if userLevel == "admin": state = 0 if request.method == "GET": #Calls delete queries based on what type of location is being deleted. if location == "Building": floors = getFloors(lId) #All floors of the current building for floor in floors: rooms = getRooms(floor) #All rooms of current floor for room in rooms: storages = getStorages(room) #All storage locations of current room for storage in storages: if getContainers(storage) != False:# Try to get any containers related to this storage, they do not need to be saved as their mere existence prohibits this building from being deleted. state = 1 if state != 1: status, flashMessage, flashStatus = deleteBuilding(lId) flash(flashMessage, flashStatus) else: flash("This building could not be deleted, as there are 1 or more containers still assigned to it.", "list-group-item list-group-item-danger") elif location == "Room": storages = getStorages(lId) for storage in storages: if getContainers(storage) != False:# Try to get any containers related to this storage, they do not need to be saved as their mere existence prohibits this building from being deleted. state = 1 if state != 1: status, flashMessage, flashStatus = deleteRoom(lId) flash(flashMessage, flashStatus) else: flash("This room could not be deleted, as there are 1 or more containers still assigned to it.", "list-group-item list-group-item-danger") elif location == "Storage": if getContainers(lId) != False:# Try to get any containers related to this storage, they do not need to be saved as their mere existence prohibits this building from being deleted. state = 1 if state != 1: status, flashMessage, flashStatus = deleteStorage(lId) flash(flashMessage, flashStatus) else: flash("This storage location could not be deleted, as there are 1 or more containers still assigned to it.", "list-group-item list-group-item-danger") return redirect(url_for("adminHome")) #need some js to handle this and edit in order to reload the page on the location tab else: abort(403)
def UserApproval(): # User authorization auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel if userLevel == "admin": if request.method == "POST": data = request.form usersList = request.form.getlist("users") # print usersList # print data if 'approveButton' in data: # print data['approveButton'] for user in usersList: flashMessage, flashFormat = approveUsers(user) flash(flashMessage, flashFormat) elif 'denyButton' in data: #TODO: delete users that were denied print data['denyButton'] for user in usersList: try: query = Users.delete().where(Users.userId == user) query.execute() flash("Success: User has been denied.", 'list-group-item list-group-item-success') except: flash("Error: User could not be removed.", 'list-group-item list-group-item-danger') pass else: #User was neither approved or denied? This should never happen... pass pendingUsers = Users.select().where(Users.approve == False) return render_template("views/UserApprovalView.html", config=config, userConfig=userConfig, authLevel=userLevel, pendingUsers=pendingUsers) else: abort(403)
def AddUser(): # User authorization auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel if userLevel == "admin": if request.method == "POST": status, flashMessage, flashFormat = createUser( request.form, user.username, True) # createUser function located in usersModel.py flash(flashMessage, flashFormat) return redirect(url_for("AddUser")) date = time.strftime("%d/%m/%Y") return render_template("views/AddUserView.html", config=config, authLevel=userLevel, date=date)
def RequestUserAccess(): # User authorization auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel if request.method == "POST": status, flashMessage, flashFormat = createUser(request.form, user.username, False) if status: flash( "Success: Access for " + user.first_name + " " + user.last_name + " was Requested", flashFormat) else: flash(flashMessage, flashFormat) return render_template("views/RequestUserAccessView.html", config=config, userConfig=userConfig, authLevel=userLevel)
def AddWasteItem(wID): #function is what is run to render the right page, if GET, it shows the add waste contents view which allows a place to click to add chemicals #if Post, it redirects to waste chemicals page with a specific url conatining the waste container number. auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": if request.method == "GET": return render_template("views/AddWasteContentsView.html", wID = wID, authLevel = userLevel, config = config, wasteConfig = wasteConfig) return redirect(url_for('AddWasteChemical', wID = wID)) else: abort(403)
def maContainerInfo(chemId, barcodeId): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": chemical = getChemical(chemId) if chemical.remove == True: return redirect('/ChemTable') container = getContainer(barcodeId) if container.disposalDate is not None: return redirect('/ChemTable') storageList = getStorages() buildingList = getBuildings() histories = getContainerHistory(container.conId) if request.method =="POST": data = request.form cont = getContainer(barcodeId) if data['formName'] == 'checkOutForm': updateHistory(cont, "Checked Out", data['storageId'], user) changeLocation(cont, True, data, user.username) else: updateHistory(cont, "Checked In", data['storageId'], user) changeLocation(cont, False, data, user.username) return redirect('/ViewChemical/%s/' %(chemId)) else: #It is a GET return render_template("views/ContainerInfoView.html", config = config, contConfig = contConfig, pageConfig = checkInConfig, container = container, chemical = chemical, storageList = storageList, buildingList = buildingList, histories = histories, authLevel = userLevel) else: abort(403)
def ViewUser(): # User authorization auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel usersList = Users.select().where(Users.approve == True) if request.method == "POST": data = request.form if 'auth_level' in data: #Updating selected user to a new selected auth_level flashMessage, flashFormat = updateUserAuth(data['username'], data['auth_level']) else: flashMessage, flashFormat = denyUsers(data['username']) flash(flashMessage, flashFormat) return render_template("views/ViewUserView.html", config=config, authLevel=userLevel, usersList=usersList)
def migrateChem(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() print user.username, userLevel #locdict = Batch.select().dicts().get() This was used for datamodel testing if userLevel == 'admin' or userLevel == "systemAdmin": if request.method == "GET": return render_template("views/MigrateChem.html", authLevel = userLevel, config = config ) elif request.method == "POST": data = request.form if request.form['formName'] == "searchBcode": return renderCorrectTemplate(request.form['barcodeID']) elif request.form['formName'] == 'addCont': ### ##Process the form of adding a Container ### status, flashMessage, flashFormat, newChem = addContainer(data, user.username) flash(flashMessage, flashFormat) return redirect(url_for("migrateChem")) elif request.form['formName'] == 'addChem': data = request.form status, flashMessage, flashFormat, newChem = createChemical(request.form) flash(flashMessage, flashFormat) if status: return renderCorrectTemplate(data['barcode']) return render_template('views/MigrateChem.html', config = config, authLevel = userLevel)
def renderCorrectTemplate(barcode): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() ######## INIT = -1 #Inial start state(Not really needed but looks nice) MIGRATED = 0 #Both Chemical and Container already Migrated ONLYCHEM = 1 #Only Chemical has been Migrated. Container needs to be migrated NIETHER = 2 #Both Chemical and Container need to be migrated UNKNOWN = 3 #This container does not exist anywhere ######## inputBar = barcode.upper() state = INIT containerObj = None chemObj = None ####### if getContainer(inputBar): flash("Container " + inputBar + " Already Migrated Into System", "list-group-item list-group-item-success") state = MIGRATED #Try and Retrieve Container and Chemical Informatoin from CISPro if state != MIGRATED: containerObj = getCisProContainer(inputBar) print containerObj if containerObj == False: flash("Container " + inputBar + " Is Not In CISPro Database", "list-group-item list-group-item-danger") state = UNKNOWN if state != UNKNOWN: ######## #If Continer in CISPro check if parent Chemical is Migrated chemObj = getChemicalOldPK(containerObj.NameRaw_id) if chemObj: storageList = getStorages() buildingList = getBuildings() chemObj.remove = False #Make sure that the chemical will show in the UI chemObj.save() state = ONLYCHEM return render_template("views/MigrateChem.html", state = state, container = containerObj, chemInfo = chemObj, inputBar = inputBar, config = config, contConfig = contConfig, storageList = storageList, buildingList = buildingList, barcode = inputBar, authLevel = userLevel, migrated = 1) else: #Chemical is not yet in BCCIS state = NIETHER return render_template("views/MigrateChem.html", state = state, container = containerObj, chemInfo = chemObj, inputBar = inputBar, config = config, chemConfig = chemConfig, authLevel = userLevel) return redirect(url_for("migrateChem"))
def ViewChemical(chemId): # User authorization auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if userLevel == -1 or user == -1: abort(403) print user.username, userLevel hazardList = getChemicalHazards(chemId) try: chemInfo = getChemical(chemId) #Get chemical by correct chemId except: return redirect('ChemTable') if chemInfo.remove == True: #If the chemical attribute, 'remove', was set to True, go back to the chemical table. return redirect('ChemTable') if userLevel == "admin" or userLevel == "systemAdmin": chemDict = Chemicals.select().where(Chemicals.chemId == chemId).dicts( ).get() #Get chemical by correct chemId as a dictionary storageList = Storages.select().order_by(Storages.roomId) buildingList = Buildings.select() if request.method == "POST": #If there was a form posted to this page data = request.form if data['formName'] == 'addChem': for i in data: #Loop through the keys in the form dictionary setattr( chemInfo, i, data[i] ) #Set the attribute, 'i' (the current key in the form), of 'chemInfo' (the chemical) to the value of the current key in the form chemInfo.save() elif data["formName"] == "addCont": status, flashMessage, flashFormat, newChem = addContainer( data, user.username) flash(flashMessage, flashFormat) try: lastCont = Containers.select().where(Containers.migrated >> 0)\ .order_by(-Containers.barcodeId).get().barcodeId # Gets the last entered container that was not migrated. Used for creating the next barcode barcode = genBarcode(lastCont) while getContainer(barcode) != False: barcode = genBarcode(barcode) except Exception as e: barcode = genBarcode("00000000") #lastCont needs to be assigned after any potential updates to the last barcode, and before render_template containers = (((Containers.select()).join(Chemicals) ).where((Containers.chemId == chemId) & (Containers.disposalDate == None))) #(Above) Get all containers of this chemical that haven't been disposed of return render_template("views/ViewChemicalView.html", config=config, chemInfo=chemInfo, containers=containers, contConfig=contConfig, chemConfig=chemConfig, storageList=storageList, buildingList=buildingList, hazardList=hazardList, barcode=barcode, authLevel=userLevel, migrated=0, date=datetime.date.today().strftime("%m-%d-%Y")) else: containers = (((Containers.select()).join(Chemicals) ).where((Containers.chemId == chemId) & (Containers.disposalDate == None))) #(Above) Get all containers of this chemical that haven't been disposed of return render_template("views/ViewChemicalView.html", config=config, chemInfo=chemInfo, containers=containers, contConfig=contConfig, chemConfig=chemConfig, hazardList=hazardList, quote=quote, authLevel=userLevel, migrated=0, date=datetime.date.today().strftime("%m-%d-%Y"))
def adminHome(): auth = AuthorizedUser() user = auth.getUser() userLevel = auth.userLevel() if user == -1: render_template("views/UnathorizedView.html") print user.username, userLevel if userLevel == "admin" or userLevel == "systemAdmin": buildings = getBuildings() floors = {} rooms = {} storages = {} if request.method == "POST": data = request.form #If a form is posted to the page if data['location'] == "Building": #If the form is editing a building if data['action'] == 'edit': status, flashMessage, flashFormat, editBuild = editBuilding( data) elif data['action'] == 'add': status, flashMessage, flashFormat, newBuild = createBuilding( data) if status: for value in range(int(data['numFloors'])): createFloor({ 'buildId': str(newBuild.bId), 'name': "Level " + str(value), 'level': str(value) }) flash(flashMessage, flashFormat) elif data['location'] == "Floor": #If the form is editing a floor status, flashMessage, flashFormat, editedFloor = editFloor( data) flash(flashMessage, flashFormat) elif data['location'] == "Room": #If the form is editing a room if data['action'] == 'edit': status, flashMessage, flashFormat, editedRoom = editRoom( data) flash(flashMessage, flashFormat) elif data['action'] == 'add': status, flashMessage, flashFormat, editedRoom = createRoom( data) flash(flashMessage, flashFormat) elif data[ 'location'] == "Storage": #If the form is editing a storage if data['action'] == 'edit': print data storage = Storages.get( Storages.sId == data['id'] ) #Get storage location to be edited and change all information to what was in form for i in data: setattr(storage, i, data[i]) storage.save() elif data['action'] == 'add': modelData, extraData = sortPost(data, Storages) Storages.create(**modelData) return redirect(url_for("adminHome")) for building in buildings: #Set floor dictionary with key of current building, and value of all floors that reference that building floors[building.bId] = getFloors(building.bId) for floor in floors[ building. bId]: #Set room dictionary with key of current floor, and value of all rooms that reference that floor rooms[floor.fId] = Rooms.select().where( Rooms.floorId == floor.fId).order_by(+Rooms.name) for room in rooms[ floor. fId]: #Set storage dictionary with key of current room, and value of all storages that reference that room storages[room.rId] = Storages.select().where( Storages.roomId == room.rId) return render_template("views/HomeView.html", config=config, locationConfig=locationConfig, buildings=buildings, floors=floors, rooms=rooms, storages=storages, authLevel=userLevel) else: return redirect("/ChemTable")