def safeProxy(self, id): from models.shift import Shift t = Template(filename=os.path.join(WEB_ROOT, "html/proxy.mako"), lookup=lookup) theShift = Shift.read(id, proxy=True) if theShift == None or theShift['type'] != 'shift': return self.statusPage(status="err", details="proxyperm") ctxt = { "src": "/unsafe-proxy/%s" % id, } return t.render(**ctxt)
def get(self): user = None if self.request.cookies.get( 'our_token' ): #the cookie that should contain the access token! user = User.checkToken(self.request.cookies.get('our_token')) if not user: self.redirect("/") return reqID = int(self.request.get('req_id')) req = Switch.get_by_id(reqID) if req.from_shift_id: from_shift = Shift.get_by_id(int(req.from_shift_id)) print from_shift print from_shift.employee_number print req.from_empno if from_shift and from_shift.employee_number == req.from_empno: from_shift.employee_number = req.to_empno from_shift.put() if req.to_shift_id: to_shift = Shift.get_by_id(int(req.to_shift_id)) print to_shift print to_shift.employee_number print req.to_empno if to_shift and to_shift.employee_number == req.to_empno: to_shift.employee_number = req.from_empno to_shift.put() req.status = 'approved' req.put() self.response.set_cookie('our_token', str(user.key.id())) self.response.write(json.dumps({'status': 'OK'}))
def load(): with open('smaller_schedule.json') as data: data = json.load(data) shifts = [ Shift(day=s['day'], start=datetime.strptime(s['startTime'], "%H:%M:%S"), end=datetime.strptime(s['endTime'], "%H:%M:%S"), location=s['location']) for s in data['shifts'] ] employees = [ Employee(cpr=e['cpr'], name=e['name'], min_hours=timedelta(hours=int(e['min_hours'])), max_hours=timedelta(hours=int(e['max_hours'])), locations=e['locations'], time_constraint=e['time_constraint']) for e in data['employees'] ] return shifts, employees
from google.appengine.ext.webapp import template
def automatic_shift_creation(latitude, longitude): # create the new shift new_shift = Shift(location_lat=latitude, location_long=longitude) db.session.add(new_shift) # instantiate the new shift. We need to get the ID to stamp our vehicles db.session.commit() # query for 20 nearest not in use/not fully charged vehicles target_data = db.session.execute( """SELECT *, SQRT( POW(69.1 * (location_lat - :lat), 2) + POW(69.1 * (location_long - :long) * COS(location_lat / 57.3), 2) ) AS distance FROM vehicle WHERE battery_level != 100.0 AND shift_id IS NULL AND in_use = 'False' ORDER BY distance LIMIT 20""", { 'lat': latitude, 'long': longitude }) vehicles = [] for v in target_data: vehicles.append( Vehicle( id=v.id, license_plate=v.license_plate, battery_level=v.battery_level, in_use=v.in_use, model=v.model, location_lat=v.location_lat, location_long=v.location_long, shift_id=new_shift.id, created_at=v.created_at, )) path = PathFinder(vehicles, new_shift).initial_route[1:len(vehicles) + 1] # pathing logic for vehicles goes HERE # currently employing nearest neighbor heuristic, need to hook up the Two_opt solution for further accuracy # then iterate through the newly sorted/pathed vehicles # not enough time to implement two_opt confidently. Will do further research and go over during onsite, currently just using Nearest Neighbor if len(path) > 0: for i in range(0, len(path)): # set the Vehicle.next_id to be the next vehicle current_vehicle_index = path[i] - 1 if i < len(path) - 1: db.session.query(Vehicle).filter( Vehicle.id == vehicles[current_vehicle_index].id).update({ 'next_id': vehicles[path[i + 1] - 1].id, 'shift_id': new_shift.id }) else: db.session.query(Vehicle).filter( Vehicle.id == vehicles[current_vehicle_index].id).update( {'shift_id': new_shift.id}) # create the shift_index row new_link = ShiftIndex(shift_id=new_shift.id, next_vehicle_id=vehicles[path[0]].id) db.session.add(new_link) # # commit all changes db.session.commit() return ShiftSchema().dump(new_shift)
def create_shift(): new_shift = Shift() db.session.add(new_shift) db.session.commit() return ShiftSchema().dump(new_shift)
def unsafeProxy(self, id): """ Serves the proxy. Takes a shift id and returns the original page where the shift was created, injects the required Javascript and CSS and recreates the shift. All scripts and onload handlers are removed from the original page to prevent interference with shift loading. """ try: from models.shift import Shift from urllib import FancyURLopener, urlcleanup from lxml.html import fromstring, tostring from linkprocessor import LinkProcessor except: return self.statusPage(status="err", details="proxy") class FancyOpener(FancyURLopener): version = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1" pageopener = FancyOpener() theShift = Shift.read(id, proxy=True) if theShift['type'] != 'shift': return self.statusPage(status="err", details="proxyperm") shiftId = theShift["_id"] space = theShift["space"]["name"] url = theShift["href"] created = theShift["created"] userName = theShift["userName"] # clear the urllib cache urlcleanup() page = pageopener.open(url) source = page.read() linkprocessor = LinkProcessor(); linkprocessor.parse(source); linkprocessor.set_url(url) dom = linkprocessor.get_dom() [node.drop_tree() for node in dom.cssselect("script")] for node in dom.cssselect("*[onload]"): del node.attrib['onload'] # load the space attributes fh = open(os.path.join(WEB_ROOT, "spaces", space, "attrs.json")) attrs = fh.read() fh.close() attrs = self.absolutify(json.loads(attrs)) # load the scripts source = tostring(dom) server = "http://localhost:%s" % serverport ctxt = { "server": server, "spacesPath": "/".join([server, "spaces"]), "shiftId": shiftId, "space": space, "shift": json.dumps(theShift.toDict()), "attrs": json.dumps(attrs), } t = Template(filename=os.path.join(WEB_ROOT, "server/bootstrap.mako"), lookup=lookup) source = source.replace("</head>", "%s</head>" % t.render(**ctxt)) # load proxy message t = Template(filename=os.path.join(WEB_ROOT, "server/proxymessage.mako"), lookup=lookup) ctxt = { "space": space, "href": url, "created": created, "userName": userName, } source = source.replace("</body>", "%s</body>" % t.render(**ctxt)) return source
def get(self): user = None if self.request.cookies.get( 'our_token' ): #the cookie that should contain the access token! user = User.checkToken(self.request.cookies.get('our_token')) template_variables = {} if user: template_variables['user'] = user.email template_variables['userempno'] = user.employee_number if user.isAdmin: template_variables['useradmin'] = True else: self.redirect('/Login') return if self.request.get('cms'): #chosen my shift cms = self.request.get('cms') template_variables['cms'] = cms print cms if self.request.get('ce'): #chosen employee ce = self.request.get('ce') template_variables['ce'] = ce usersList = User.getAllActiveUsers() #QUERY template_variables['userlist'] = [] for tmpuser in usersList: template_variables['userlist'].append({ "empno": tmpuser.employee_number, "name": tmpuser.first_name + " " + tmpuser.last_name, }) allshifts = Shift.qryGetWeekShiftsByDate(date.today()) template_variables['allshifts'] = [] for sft in allshifts: template_variables['allshifts'].append({ "id": sft.key.id(), "empno": sft.employee_number, "shift": Shift.shiftToString(sft) }) allshifts2 = Shift.qryGetWeekShiftsByDate(date.today() + timedelta(days=7)) template_variables['allshifts2'] = [] for sft in allshifts2: template_variables['allshifts2'].append({ "id": sft.key.id(), "empno": sft.employee_number, "shift": Shift.shiftToString(sft) }) allReq = Switch.allRequests() template_variables['requests'] = [] for req in allReq: #check======= if req.status == 'pending': if req.from_shift_id: from_shift = Shift.get_by_id(int(req.from_shift_id)) if from_shift == None or from_shift.employee_number != req.from_empno: req.key.delete() continue if req.to_shift_id: to_shift = Shift.get_by_id(int(req.to_shift_id)) if to_shift == None or to_shift.employee_number != req.to_empno: req.key.delete() continue try: from_shift_str = Shift.shiftToString( Shift.get_by_id(int(req.from_shift_id))) except: from_shift_str = "" try: to_shift_str = Shift.shiftToString( Shift.get_by_id(int(req.to_shift_id))) except: to_shift_str = "" template_variables['requests'].append({ "id": req.key.id(), "to_empno": req.to_empno, "from_empno": req.from_empno, "from_shift": from_shift_str, "to_shift": to_shift_str, "date": req.date, "status": req.status }) html = template.render('web/templates/Switch_shifts.html', template_variables) self.response.write(html)