示例#1
0
def sendAssignmentEmail(assignmentID):
    import mailer
    setExits()
    resultString = ""
    assignmentID = cleanRecordID(assignmentID)
    assignment = Assignment.query.get(cleanRecordID(assignmentID))
    if not assignment:
        resultString = "Invitaton Could not be sent. The Assignment Record could not be found"
        return resultString

    user = User.query.get(assignment.user_ID)
    if not user:
        resultString = "Invitaton Could not be sent. The User Record could not be found"
        return resultString

    countEvent = CountEvent.query.get(assignment.countEvent_ID)
    if not countEvent:
        resultString = "Invitaton Could not be sent. The Count Event record could not be found"
        return resultString

    countEventDict = getTimeDictionary(countEvent.startDate,countEvent.endDate)

    sendResult, resultString = mailer.sendInvite(assignment,user,countEventDict)
    
    # Record the fact that the email was sent
    if sendResult == True:
        sql = "UPDATE assignment set invitationSent = '%s' WHERE ID = %d;" % (datetime.strftime(datetime.now(), '%Y-%m-%d'), assignmentID)
        try:
            ass = db.engine.execute(sql)
        except Exception as e:
            printException('Error attempting to update invitationSent for '+g.title+' record.',"error",e)
            
    return resultString
示例#2
0
def before_request():
    # layout.html looks for g.user so declare it early
    g.user = session.get('user')
    g.orgID = None
    g.role = None
    
    if not db:
        # really can't do anything with out a database, so just bail
        printException("Database not Available", "error")
        return render_template('errors/500.html'), 500
        
    freeDirectories = ("login","logout","count","static","ping","_auth","map",
            "report",) #first directory of request URL
    superUserDirectories = ("org","feature","trip","traveler","super",) #first directory of request URL
    
    rootURL = request.path.split("/")
    rootURL = rootURL[1]
    
    superRequired = rootURL in superUserDirectories
    noLoginRequired = rootURL in freeDirectories
    ### Otherwise, user must be an Org. admin
    
    if noLoginRequired:
        #No login required
        pass
    else:
        # Require a secure connection?
        if app.config['REQUIRE_SSL'] and not app.config['DEBUG'] and not request.is_secure :
            return redirect(request.url.replace("http://", "https://"))
            
        # login required
        if g.user is None and rootURL !="":
            # no email in session, can only see the home page
            return redirect(url_for('login.login'))
        
        ## email must be linked to a user
        if views.user.setUserStatus(g.user):
            # Session timeout is set in app.config["PERMANENT_SESSION_LIFETIME"]
            # g.email, g.role, & g.orgID will be set
            if g.role == "counter":
                ## Nothing for these users here...
                session.clear()
                g.user = None
                flash("You don't have access to the Administration web site.")
                return redirect(url_for("login.login"))
                
            g.organizationName = views.org.getName(g.orgID)
            if superRequired and g.role != "super":
                flash("Sorry, you don't have access for that feature.")
                return redirect(url_for("home"))
        else:
            # Not a valid email or session timed out, go to Home page...
            return views.index.home()
示例#3
0
def createEventRecord():
    """ Create a stub record """
    n = datetime.now()
    # Round time to even hour
    startingDate = datetime(n.year, n.month, n.day, n.hour)
    endingDate = startingDate + timedelta(hours=2)
    cur = CountEvent("Untitled",startingDate.isoformat()[:19],endingDate.isoformat()[:19],getDefaultTimeZone(),0,g.orgID)
    db.session.add(cur)
    try:
        db.session.commit()
    except Exception as e:
        printException("Unable to create event record", "error", e)
        db.session.rollback()
        
    return cur
示例#4
0
def display():
    setExits()
    if db:
        recs = None
        cl = Assignment.query.filter(
            Assignment.organization_ID == g.orgID).order_by(
                Assignment.eventStartDate.desc())
        # collect additional data for each record
        if cl:
            recs = dict()
            for row in cl:
                base = str(row)
                recs[base] = dict()
                recs[base]["ID"] = row.ID
                recs[base]['UID'] = row.assignmentUID
                recs[base]['startDate'] = getDatetimeFromString(
                    row.eventStartDate).strftime('%x @ %I:%M %p')
                recs[base]["location"] = row.locationName
                recs[base]["userName"] = row.userName

        return render_template('assignment/assignment_list.html', recs=recs)

    else:
        flash(printException('Could not open Database', "info"))
        return redirect(url_for('home'))
示例#5
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
 
    rec = Traveler.query.get(id)
    if rec:
        ## Can't delete Traveler that has been used in a trip
        trip = Trip.query.filter_by(traveler_ID = str(id)).all()
        if trip:
            #can't delete
            flash("You can't delete this Traveler because there are Trip records that use it")
            return redirect(g.listURL)
        
        # Delete the related records
        et = EventTraveler.query.filter_by(traveler_ID = str(id)).delete(synchronize_session='fetch')
        tf = TravelerFeature.query.filter_by(traveler_ID = str(id)).delete(synchronize_session='fetch')
        ## delete the traveler
    try:
        db.session.delete(rec)
        db.session.commit()
    except Exception as e:
        flash(printException('Error attempting to delete '+g.title+' record.',"error",e))
        db.session.rollback()

    return redirect(g.listURL)
示例#6
0
def edit(id=0):
    setExits()
    defaultLoc = {'lat': app.config['LOCATION_DEFAULT_LAT'], 'lng': app.config['LOCATION_DEFAULT_LNG']}
    #LOCATION_DEFAULT_LNG
    #LOCATION_DEFAULT_LAT
    
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
            
    g.tripTotalCount = getLocationTripTotal(id)
    rec = None
    if id > 0:
        rec = Location.query.get(id)
        if not rec:
            flash(printException("Could not edit that "+g.title + " record. ID="+str(id)+")",'error'))
            return redirect(g.listURL)
    
    form = LocationForm(request.form, rec)

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Location(form.locationName.data,g.orgID)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)
        
    return render_template('location/location_edit.html', rec=rec, form=form, defaultLoc=defaultLoc)
示例#7
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
        
    if getCountEventTripTotal(id) > 0 and g.role != "super":
        flash("You must be the super user to delete an event with trips.")
        return redirect(g.listURL)

    if id > 0:
        rec = CountEvent.query.filter(CountEvent.ID == id, CountEvent.organization_ID == g.orgID)
        if rec:
            try:
                #delete related records
                assigned = Assignment.query.filter(Assignment.countEvent_ID == id).delete()
                trav = EventTraveler.query.filter(EventTraveler.countEvent_ID == id).delete()
                rec.delete()
                db.session.commit()
                app.logger.info(g.title+' record (id='+str(id)+') Deleted by: ' + g.user + " on "+ datetime.now().isoformat())
            except Exception as e:
                flash(printException('Error attempting to delete '+g.title+' record.',"error",e))
                db.session.rollback()
        else:
            flash("Record could not be found.")
            
    return redirect(g.listURL)
示例#8
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
            
    rec = None
    if id > 0:
        rec = Trip.query.get(id)
        if not rec:
            flash(printException("Could not edit that "+g.title + " record. ID="+str(id)+")",'error'))
            return redirect(g.listURL)
    
    form = TripForm(request.form, rec)
    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.countEvent_ID.choices = getCountEventChoices()
    form.location_ID.choices = getLocationChoices()
    form.traveler_ID.choices = getTravelerChoices()
    form.turnDirection.choices = getTurnDirectionChoices()
    
    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Trip(form.tripCount.data,form.tripDate.data,form.turnDirection.data,form.seqNo.data,form.location_ID.data,form.traveler_ID.data,form.countEvent_ID.data)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)
        
    return render_template('genericEditForm.html', rec=rec, form=form)
示例#9
0
def display():
    setExits()
    if db :
        recs = None
        queryData = {}
        queryData['searchType'] = 'tripList'
        queryData['selectType'] = 'single'
        queryData['includeAllOption'] = False
        
        searchOrgs = []
        searchEvents = []
        searchForm.getSelectValues(request.form,searchOrgs,searchEvents)
        queryData['searchOrgs'] = searchOrgs
        queryData['searchEvents'] = searchEvents
        
        #Get all orgs
        searchForm.orgsToDict(queryData)

        #get the Events
        searchForm.eventsToDict(queryData)
        
        recs = queryTripData(searchOrgs, searchEvents, searchType='listing')
        
        return render_template('trip/trip_list.html', recs=recs, queryData=queryData )
        
    else:
        flash(printException('Could not open Database',"info"))
        return redirect(url_for('home'))
示例#10
0
def display():
    setExits()
    if db:
        recs = None
        queryData = {}
        queryData['searchType'] = 'tripList'
        queryData['selectType'] = 'single'
        queryData['includeAllOption'] = False

        searchOrgs = []
        searchEvents = []
        searchForm.getSelectValues(request.form, searchOrgs, searchEvents)
        queryData['searchOrgs'] = searchOrgs
        queryData['searchEvents'] = searchEvents

        #Get all orgs
        searchForm.orgsToDict(queryData)

        #get the Events
        searchForm.eventsToDict(queryData)

        recs = queryTripData(searchOrgs, searchEvents, searchType='listing')

        return render_template('trip/trip_list.html',
                               recs=recs,
                               queryData=queryData)

    else:
        flash(printException('Could not open Database', "info"))
        return redirect(url_for('home'))
示例#11
0
def sendInvite(assignment, user, countEventDict):
    """ Send a single counting Assignment email """
    hostName = app.config["HOST_NAME"]
    organization = Organization.query.get(cleanRecordID(g.orgID))

    with mail.record_messages() as outbox:
        if user and assignment and organization:
            subject = "Your assignment from %s" % (organization.name)
            msg = Message(subject,
                          sender=(organization.name, organization.email),
                          recipients=[(user.name, user.email)])

            msg.body = render_template(
                "email/standardInvite.txt",
                assignment=assignment,
                countEventDict=countEventDict,
                user=user,
                hostName=hostName,
                organization=organization,
            )
            msg.html = render_template(
                "email/standardInvite.html",
                assignment=assignment,
                countEventDict=countEventDict,
                user=user,
                hostName=hostName,
                organization=organization,
            )
        else:
            mes = "Email is missing parameters"
            printException(mes, "error", e)
            return (False, mes)

        try:
            mail.send(msg)
        except Exception as e:
            mes = "Error Sending email"
            printException(mes, "error", e)
            return (False, mes)

    if mail.suppress:
        mes = '%d email(s) would have been sent if we were not testing' % (
            len(outbox))
        return (True, mes)

    return (True, "Email Sent Successfully")
示例#12
0
def display():
    if db :
        recs = Feature.query.all()
        setExits()
        return render_template('feature/feature_list.html', recs=recs)

    flash(printException('Could not open Database',"info"))
    return redirect(url_for('home'))
示例#13
0
def createEventRecord():
    """ Create a stub record """
    n = datetime.now()
    # Round time to even hour
    startingDate = datetime(n.year, n.month, n.day, n.hour)
    endingDate = startingDate + timedelta(hours=2)
    cur = CountEvent("Untitled",
                     startingDate.isoformat()[:19],
                     endingDate.isoformat()[:19], getDefaultTimeZone(), 0,
                     g.orgID)
    db.session.add(cur)
    try:
        db.session.commit()
    except Exception as e:
        printException("Unable to create event record", "error", e)
        db.session.rollback()

    return cur
示例#14
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
            
    if db:
        if id > 0:
            rec = Feature.query.get(id)
            if rec:
                db.session.delete(rec)
                db.session.commit()
            else:
                flash(printException(g.title + " Record ID "+str(id)+" could not be found.","info"))
    else:
        flash(printException("Could not open database","info"))
        
    return redirect(url_for('.display'))
示例#15
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
        
    if db:
        if not request.form:
            """ if no form object, send the form page """
            # get the Org record if you can
            rec = None
            if id > 0:
                rec = Feature.query.filter_by(ID=id).first_or_404()
                
            return render_template('feature/feature_edit.html', rec=rec)

        #have the request form
        if validForm():
            try:
                if int(id) > 0:
                    rec = Feature.query.get(id)
                else:
                    ## create a new record stub
                    rec = Feature(request.form['featureClass'],request.form['featureValue'])
                    db.session.add(rec)
                #update the record
                rec.featureClass = request.form['featureClass']
                rec.featureValue = request.form['featureValue']
                db.session.commit()
                
                return redirect(url_for('.display'))

            except Exception as e:
                flash(printException('Could not save record. Unknown Error',"error",e))

        # form not valid - redisplay
        return render_template('feature/feature_edit.html', rec=request.form)

    else:
        flash(printException('Could not open database'),"info")

    return redirect(url_for('.display'))
示例#16
0
def display():
    # Display the Trips map
    setExits()
    if db :
        searchOrgs = []
        searchEvents = []
        searchForm.getSelectValues(request.form,searchOrgs,searchEvents) 
        
        queryData = {}
        queryData["searchOrgs"] = searchOrgs
        queryData["searchEvents"] = searchEvents
        queryData['searchType'] = 'map'
        queryData['selectType'] = 'multiple'
        queryData['includeAllOption'] = True
        
        #Get all orgs
        searchForm.orgsToDict(queryData)

        #get the Events
        searchForm.eventsToDict(queryData)
        
        # Jun 10, 2016 modified query to speed up map display
        # The order of the selected fields is critical to creating a proper namedtuple below
        
        recs = queryTripData(searchOrgs, searchEvents, queryData['searchType'])
        
        markerData = {"markers":[]}
        markerData["cluster"] = True
        markerData["zoomToFit"] = False # can/t zoom if there are no markers.
        if recs:
            markerData["zoomToFit"] = True
            for rec in recs:
                #db.engine.execute returns a list of sets without column names
                #namedtuple creates an object that getMarkerDict can access with dot notation
                Fields = namedtuple('record', 'locationName ID latitude longitude tripCount')
                record = Fields(rec[0], rec[1], rec[2], rec[3], rec[4])

                marker = getMarkerDict(record, searchEvents) # returns a dict or None
                if marker:
                    popup = render_template('map/tripCountMapPopup.html', rec=record)
                    popup = escapeTemplateForJson(popup)
                    marker['popup'] = popup
                    
                    marker["divIcon"] = getDivIcon(record.tripCount)
                    
                    markerData["markers"].append(marker)
                    
        return render_template('map/JSONmap.html', markerData=markerData, queryData=queryData)

    else:
        flash(printException('Could not open Database',"info"))
        return redirect(url_for('home'))
示例#17
0
def sendAssignmentEmail(assignmentID):
    import mailer
    setExits()
    resultString = ""
    assignmentID = cleanRecordID(assignmentID)
    assignment = Assignment.query.get(cleanRecordID(assignmentID))
    if not assignment:
        resultString = "Invitaton Could not be sent. The Assignment Record could not be found"
        return resultString

    user = User.query.get(assignment.user_ID)
    if not user:
        resultString = "Invitaton Could not be sent. The User Record could not be found"
        return resultString

    countEvent = CountEvent.query.get(assignment.countEvent_ID)
    if not countEvent:
        resultString = "Invitaton Could not be sent. The Count Event record could not be found"
        return resultString

    countEventDict = getTimeDictionary(countEvent.startDate,
                                       countEvent.endDate)

    sendResult, resultString = mailer.sendInvite(assignment, user,
                                                 countEventDict)

    # Record the fact that the email was sent
    if sendResult == True:
        sql = "UPDATE assignment set invitationSent = '%s' WHERE ID = %d;" % (
            datetime.strftime(datetime.now(), '%Y-%m-%d'), assignmentID)
        try:
            ass = db.engine.execute(sql)
        except Exception as e:
            printException(
                'Error attempting to update invitationSent for ' + g.title +
                ' record.', "error", e)

    return resultString
示例#18
0
def createNewRecord(eventID=None):
    """ return a reference to a newly created record or elss None"""
    eventID=cleanRecordID(eventID)
    rec = None
    if eventID > 0:
        #test that countEvent record exits
        cnt = CountEvent.query.filter(CountEvent.ID == eventID).count()
        if cnt > 0:
            rec = Assignment(eventID,getUID())
            db.session.add(rec)
        else:
            flash(printException("Invalid countEvent ID during Count Event creation.","error"))
            
    return rec
示例#19
0
def delete(id="0"):
    setExits()
    id = cleanRecordID(id)
    
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
                        
    if deleteRecordID(id):
        pass
    else:
        flash(printException("Could not delete that "+g.title + " record ID="+str(id)+" could not be found.","error"))
        
    return redirect(g.listURL)
示例#20
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
        
    if id > 0:
        rec = Trip.query.get(id)
        if rec:
            db.session.delete(rec)
            db.session.commit()
        else:
            flash(printException("Could not delete that "+g.title + " record ID="+str(id)+" could not be found.","error"))
        
    return redirect(g.listURL)
示例#21
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid record ID")
        return redirect(g.listURL)

    if id > 0:
        rec = Location.query.filter(Location.ID == id, Location.organization_ID == g.orgID).first()
        if rec:
            db.session.delete(rec)
            db.session.commit()
        else:
            flash(printException("Could not delete that "+g.title + " record ID="+str(id)+" could not be found or was wrong org.","error"))

    return redirect(g.listURL)
示例#22
0
def createNewRecord(eventID=None):
    """ return a reference to a newly created record or elss None"""
    eventID = cleanRecordID(eventID)
    rec = None
    if eventID > 0:
        #test that countEvent record exits
        cnt = CountEvent.query.filter(CountEvent.ID == eventID).count()
        if cnt > 0:
            rec = Assignment(eventID, getUID())
            db.session.add(rec)
        else:
            flash(
                printException(
                    "Invalid countEvent ID during Count Event creation.",
                    "error"))

    return rec
示例#23
0
def delete(id="0"):
    setExits()
    id = cleanRecordID(id)

    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    if deleteRecordID(id):
        pass
    else:
        flash(
            printException(
                "Could not delete that " + g.title + " record ID=" + str(id) +
                " could not be found.", "error"))

    return redirect(g.listURL)
示例#24
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
    
    if id > 0:
        rec = User.query.get(id)
        if rec:
            try:
                db.session.delete(rec)
                db.session.commit()
            except Exception as e:
                flash(printException('Error attempting to delete '+g.title+' record.',"error",e))
        else:
            flash("Record could not be deleted.")
            
    return redirect(g.listURL)
示例#25
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    if id > 0:
        rec = Trip.query.get(id)
        if rec:
            db.session.delete(rec)
            db.session.commit()
        else:
            flash(
                printException(
                    "Could not delete that " + g.title + " record ID=" +
                    str(id) + " could not be found.", "error"))

    return redirect(g.listURL)
示例#26
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid record ID")
        return redirect(g.listURL)

    if id > 0:
        rec = Location.query.filter(
            Location.ID == id, Location.organization_ID == g.orgID).first()
        if rec:
            db.session.delete(rec)
            db.session.commit()
        else:
            flash(
                printException(
                    "Could not delete that " + g.title + " record ID=" +
                    str(id) + " could not be found or was wrong org.",
                    "error"))

    return redirect(g.listURL)
示例#27
0
def org_edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
     
    timeZones = getTimeZones()
    if not request.form:
        """ if no form object, send the form page """
        # get the Org record if you can
        rec = None
        if int(id) > 0:
            rec = Organization.query.get(id)
            
        return render_template('org/org_edit.html', rec=rec, timeZones=timeZones)
            
            
    #have the request form
    if validForm():
        if id > 0:
            rec = Organization.query.get(id)
        else:
            ## create a new record stub
            rec = Organization(request.form['name'],request.form['email'],request.form["defaultTimeZone"])
            db.session.add(rec)
        #update the record
        rec.name = request.form['name']
        rec.email = request.form['email']
        rec.defaultTimeZone = request.form["defaultTimeZone"]
        try:
            db.session.commit()
        except Exception as e:
            flash(printException('Error attempting to create '+g.title+' record.',"error",e))
            db.session.rollback()
            
        return redirect(url_for('.org_list'))
        
    # form not valid - redisplay
    return render_template('org/org_edit.html', rec=request.form, timeZones=timeZones)
示例#28
0
def edit(id=0):
    setExits()
    defaultLoc = {
        'lat': app.config['LOCATION_DEFAULT_LAT'],
        'lng': app.config['LOCATION_DEFAULT_LNG']
    }
    #LOCATION_DEFAULT_LNG
    #LOCATION_DEFAULT_LAT

    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    g.tripTotalCount = getLocationTripTotal(id)
    rec = None
    if id > 0:
        rec = Location.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = LocationForm(request.form, rec)

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Location(form.locationName.data, g.orgID)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)

    return render_template('location/location_edit.html',
                           rec=rec,
                           form=form,
                           defaultLoc=defaultLoc)
示例#29
0
def edit(id="0"):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    rec = None
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = AssignmentForm(request.form, rec)

    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.user_ID.choices = getUserChoices()
    form.countEvent_ID.choices = getCountEventChoices()
    form.location_ID.choices = getLocationChoices()
    g.AssignedUserIDs = ()
    if rec:
        g.AssignedUserIDs = getAssignedUsers(int(rec.countEvent_ID))

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = createNewRecord(form.countEvent_ID.data)
            if not rec:
                return redirect(g.listURL)

        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)

    return render_template('genericEditForm.html', rec=rec, form=form)
示例#30
0
def display():
    setExits()
    if db :
        recs = None
        cl = Assignment.query.filter(Assignment.organization_ID == g.orgID).order_by(Assignment.eventStartDate.desc())
        # collect additional data for each record
        if cl:
            recs = dict()
            for row in cl:
                base = str(row)
                recs[base] = dict()
                recs[base]["ID"] = row.ID
                recs[base]['UID'] = row.assignmentUID
                recs[base]['startDate'] = getDatetimeFromString(row.eventStartDate).strftime('%x @ %I:%M %p')
                recs[base]["location"] = row.locationName
                recs[base]["userName"] = row.userName
                    
        return render_template('assignment/assignment_list.html', recs=recs)
        
    else:
        flash(printException('Could not open Database',"info"))
        return redirect(url_for('home'))
示例#31
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    rec = None
    if id > 0:
        rec = Trip.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = TripForm(request.form, rec)
    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.countEvent_ID.choices = getCountEventChoices()
    form.location_ID.choices = getLocationChoices()
    form.traveler_ID.choices = getTravelerChoices()
    form.turnDirection.choices = getTurnDirectionChoices()

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = Trip(form.tripCount.data, form.tripDate.data,
                       form.turnDirection.data, form.seqNo.data,
                       form.location_ID.data, form.traveler_ID.data,
                       form.countEvent_ID.data)
            db.session.add(rec)
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)

    return render_template('genericEditForm.html', rec=rec, form=form)
示例#32
0
def delete(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    if getCountEventTripTotal(id) > 0 and g.role != "super":
        flash("You must be the super user to delete an event with trips.")
        return redirect(g.listURL)

    if id > 0:
        rec = CountEvent.query.filter(CountEvent.ID == id,
                                      CountEvent.organization_ID == g.orgID)
        if rec:
            try:
                #delete related records
                assigned = Assignment.query.filter(
                    Assignment.countEvent_ID == id).delete()
                trav = EventTraveler.query.filter(
                    EventTraveler.countEvent_ID == id).delete()
                rec.delete()
                db.session.commit()
                app.logger.info(g.title + ' record (id=' + str(id) +
                                ') Deleted by: ' + g.user + " on " +
                                datetime.now().isoformat())
            except Exception as e:
                flash(
                    printException(
                        'Error attempting to delete ' + g.title + ' record.',
                        "error", e))
                db.session.rollback()
        else:
            flash("Record could not be found.")

    return redirect(g.listURL)
示例#33
0
def edit(id="0"):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
        
    rec = None
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            flash(printException("Could not edit that "+g.title + " record. ID="+str(id)+")",'error'))
            return redirect(g.listURL)
    
    form = AssignmentForm(request.form, rec)
        
    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.user_ID.choices = getUserChoices()
    form.countEvent_ID.choices = getCountEventChoices()
    form.location_ID.choices = getLocationChoices()
    g.AssignedUserIDs = ()
    if rec: 
        g.AssignedUserIDs = getAssignedUsers(int(rec.countEvent_ID))

    if request.method == 'POST' and form.validate():
        if not rec:
            rec = createNewRecord(form.countEvent_ID.data)
            if not rec:
                return redirect(g.listURL)
                    
        form.populate_obj(rec)
        db.session.commit()
        return redirect(g.listURL)
        
    return render_template('genericEditForm.html', rec=rec, form=form)
示例#34
0
def editFromList(id="0"):
    """
        handle the editing from the count event form.
        Intended for use with AJAX request
        There should always be POST data
    """
    ## when creating a new record, g.countEventID will contain the ID of the countEvent record
    setExits()

    data = None
    if not data:
        data = request.form

    if "ID" in data:
        id = data["ID"]

    id = cleanRecordID(id)
    if id < 0:
        flash("Invalid Record ID")
        return redirect(g.listURL)

    locations = None
    if id == 0:
        if "countEvent_ID" in data:
            g.countEventID = data["countEvent_ID"]

        ceID = cleanRecordID(g.countEventID)
        g.orgID = cleanRecordID(g.orgID)

        ## It's important to call fetchAll() or fetchOne() after executing sql this way or the
        ##  database will be left in a locked state.

        sql = 'select ID,locationName from location where organization_ID = %d \
               and ID not in \
               (select location_ID from assignment where countEvent_ID  = %d) \
               order by locationName;' \
            % (g.orgID, ceID)

        locations = db.engine.execute(sql).fetchall()
        if len(locations) == 0:
            return "failure: There are no more Locations to use."

    rec = None
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            flash(
                printException(
                    "Could not edit that " + g.title + " record. (ID=" +
                    str(id) + ")", 'error'))
            return redirect(g.listURL)

    form = AssignmentEditFromListForm(data, rec)

    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.user_ID.choices = getUserChoices()

    if request.method == "POST" and form.validate():
        if not rec:
            rec = createNewRecord(form.countEvent_ID.data)
            if not rec:
                return "failure: Unable to create a new Assignment record"

        rec.location_ID = form.location_ID.data
        rec.countEvent_ID = form.countEvent_ID.data
        rec.user_ID = form.user_ID.data
        try:
            db.session.commit()
        except Exception as e:
            printException("Unable to save Assignment from list", "error", e)
            return "failure: Sorry. Unable to save your changes."

        return "success"  # the success function looks for this...

    assignedUserIDs = ()
    if rec:
        g.countEventID = int(rec.countEvent_ID)

    assignedUserIDs = getAssignedUsers(g.countEventID)
    return render_template(
        'assignment/popupEditForm.html',
        form=form,
        locations=locations,
        assigned=assignedUserIDs,
    )
示例#35
0

def startLogging():
        logging.basicConfig(filename='bikeandwalk.log', level=logging.DEBUG)
        logging.info('Logging Started : ' + datetime.now().isoformat())
        
   
if __name__ == '__main__':
    """ Test to see if database file exists.
        if not, create it with init_db()
    """
    ## Turn on logging:
    startLogging()
    try:
        f=open(app.config["DATABASE"],'r')
        f.close()
    except IOError as e:
        try:
            init_db()
        except Exception as e:
            printException("Not able to create database file.","error",e)
            sys.exit(0)
            
    if not db:
        printException("Database did not startup","error")
        sys.exit(0)
        
    print "Web Server Running"
    app.run()
    ##app.run('10.0.1.9',5000)
示例#36
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)

    assignmentList = getAssignmentList(id)  #fully rendered HTML
    travelerList = getTravelerList(id)
    timeZones = getTimeZones()
    g.tripTotalCount = getCountEventTripTotal(id)

    if not request.form:
        """ if no form object, send the form page """
        #Set up a default time for the event
        # Today with time set to something reasonable
        start = datetime.now().replace(hour=16, minute=0, second=0)
        end = start + timedelta(hours=2)

        theTime = getTimeDictionary(start.isoformat(), end.isoformat())
        cur = None
        #Get the default timeZone for this Organization
        g.timeZone = getDefaultTimeZone()

        if id > 0:
            cur = CountEvent.query.filter_by(ID=id).first()
            if not cur:
                mes = g.title + " Record could not be found." + " ID:" + str(
                    id)
                flash(printException(mes, "error"))
                return redirect(g.listURL)

            theTime = getTimeDictionary(cur.startDate, cur.endDate)
            g.timeZone = None

        return render_template(
            'count_event/count_event_edit.html',
            rec=cur,
            theTime=theTime,
            timeZones=timeZones,
            assignmentList=assignmentList,
            travelerList=travelerList,
        )

    #have the request form
    # handle the checkbox for Daylite savings time
    isDST = 0
    if request.form["isDST"]:
        isDST = request.form["isDST"]

    if validForm():
        startingDate = startDateFromForm()
        endingDate = endDateFromForm()
        if id > 0:
            cur = CountEvent.query.get(id)
            #update the record
            cur.title = request.form["title"]
            cur.startDate = startingDate.isoformat()[:19]
            cur.endDate = endingDate.isoformat()[:19]
            cur.isDST = isDST
            cur.timeZone = request.form["timeZone"]
            cur.weather = request.form["weather"]
            cur.organization_ID = request.form['organization_ID']
        else:
            ## create a new record
            cur = CountEvent(request.form["title"],
                             startingDate.isoformat()[:19],
                             endingDate.isoformat()[:19],
                             request.form["timeZone"], isDST,
                             request.form['organization_ID'])
            db.session.add(cur)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(
                printException(
                    'Error attempting to save ' + g.title + ' record.',
                    "error", e))

        return redirect(g.listURL)

    # form not valid - redisplay
    #restore theTime to the values as entered
    theTime = dict()
    theTime["hour"] = int(request.form["hour"])
    theTime["minute"] = int(request.form["minute"])
    theTime["duration"] = int(request.form["duration"])
    theTime["AMPM"] = request.form["AMPM"]
    theTime["eventDate"] = request.form["eventDate"]

    return render_template('count_event/count_event_edit.html',
                           rec=request.form,
                           theTime=theTime,
                           timeZones=timeZones,
                           assignmentList=assignmentList)
示例#37
0

def startLogging():
    logging.basicConfig(filename='bikeandwalk.log', level=logging.DEBUG)
    logging.info('Logging Started : ' + datetime.now().isoformat())


if __name__ == '__main__':
    """ Test to see if database file exists.
        if not, create it with init_db()
    """
    ## Turn on logging:
    startLogging()
    try:
        f = open(app.config["DATABASE"], 'r')
        f.close()
    except IOError as e:
        try:
            init_db()
        except Exception as e:
            printException("Not able to create database file.", "error", e)
            sys.exit(0)

    if not db:
        printException("Database did not startup", "error")
        sys.exit(0)

    print "Web Server Running"
    app.run()
    ##app.run('10.0.1.9',5000)
示例#38
0
def before_request():
    # layout.html looks for g.user so declare it early
    g.user = session.get('user')
    g.orgID = None
    g.role = None

    if not db:
        # really can't do anything with out a database, so just bail
        printException("Database not Available", "error")
        return render_template('errors/500.html'), 500

    freeDirectories = (
        "login",
        "logout",
        "count",
        "static",
        "ping",
        "_auth",
        "map",
        "report",
    )  #first directory of request URL
    superUserDirectories = (
        "org",
        "feature",
        "trip",
        "traveler",
        "super",
    )  #first directory of request URL

    rootURL = request.path.split("/")
    rootURL = rootURL[1]

    superRequired = rootURL in superUserDirectories
    noLoginRequired = rootURL in freeDirectories
    ### Otherwise, user must be an Org. admin

    if noLoginRequired:
        #No login required
        pass
    else:
        # Require a secure connection?
        if app.config['REQUIRE_SSL'] and not app.config[
                'DEBUG'] and not request.is_secure:
            return redirect(request.url.replace("http://", "https://"))

        # login required
        if g.user is None and rootURL != "":
            # no email in session, can only see the home page
            return redirect(url_for('login.login'))

        ## email must be linked to a user
        if views.user.setUserStatus(g.user):
            # Session timeout is set in app.config["PERMANENT_SESSION_LIFETIME"]
            # g.email, g.role, & g.orgID will be set
            if g.role == "counter":
                ## Nothing for these users here...
                session.clear()
                g.user = None
                flash("You don't have access to the Administration web site.")
                return redirect(url_for("login.login"))

            g.organizationName = views.org.getName(g.orgID)
            if superRequired and g.role != "super":
                flash("Sorry, you don't have access for that feature.")
                return redirect(url_for("home"))
        else:
            # Not a valid email or session timed out, go to Home page...
            return views.index.home()
示例#39
0
def editFromList(id="0"):
    """
        handle the editing from the count event form.
        Intended for use with AJAX request
        There should always be POST data
    """
    ## when creating a new record, g.countEventID will contain the ID of the countEvent record
    setExits()
    
    data = None
    if not data:
        data = request.form
        
    if "ID" in data:
        id = data["ID"]
    
    id = cleanRecordID(id)
    if id < 0:
        flash("Invalid Record ID")
        return redirect(g.listURL)
        
    locations = None
    if id == 0:
        if "countEvent_ID" in data:
            g.countEventID = data["countEvent_ID"]
            
        ceID = cleanRecordID(g.countEventID)
        g.orgID = cleanRecordID(g.orgID)
        
        ## It's important to call fetchAll() or fetchOne() after executing sql this way or the
        ##  database will be left in a locked state.
        
        sql = 'select ID,locationName from location where organization_ID = %d \
               and ID not in \
               (select location_ID from assignment where countEvent_ID  = %d) \
               order by locationName;' \
            % (g.orgID, ceID)
        
        locations = db.engine.execute(sql).fetchall()
        if len(locations) == 0:
            return "failure: There are no more Locations to use."
        
        
    rec = None
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            flash(printException("Could not edit that "+g.title + " record. (ID="+str(id)+")",'error'))
            return redirect(g.listURL)
    
    form = AssignmentEditFromListForm(data, rec)
        
    ## choices need to be assigned before rendering the form
    # AND before attempting to validate it
    form.user_ID.choices = getUserChoices()        

    if request.method == "POST" and form.validate():
        if not rec:
            rec = createNewRecord(form.countEvent_ID.data)
            if  not rec:
                return "failure: Unable to create a new Assignment record"
                
        rec.location_ID = form.location_ID.data
        rec.countEvent_ID = form.countEvent_ID.data
        rec.user_ID = form.user_ID.data
        try:
            db.session.commit()
        except Exception as e:
            printException("Unable to save Assignment from list", "error", e)
            return "failure: Sorry. Unable to save your changes."
            
        return "success" # the success function looks for this...
        
            
    assignedUserIDs = ()
    if rec: 
        g.countEventID = int(rec.countEvent_ID)
        
    assignedUserIDs = getAssignedUsers(g.countEventID)
    return render_template('assignment/popupEditForm.html', 
        form=form, 
        locations=locations, 
        assigned=assignedUserIDs, 
        )
示例#40
0
def editTripsFromList(id):
    setExits()
    tripData = {} #empty dictionary
    id=cleanRecordID(id)
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            return "failure: Assignment record not found"
            
        tripCount = getAssignmentTripTotal(id)
        if tripCount > 0:
            return "failure: There are already trips recorded."
        
        # Get travelers
        travelers = getTravelersForEvent(rec.countEvent_ID)        
        
        #populate tripData with info on manually enterd counts
        tripData = getTurnData(rec)
        countEvent = CountEvent.query.get(rec.countEvent_ID)
        
        timeFrames = getTripTimeFrames(getDatetimeFromString(countEvent.startDate),getDatetimeFromString(countEvent.endDate))
        
        if request.method == "POST":
            # Validate form?
            result = True
            # record trips
            for countInputName in tripData.keys():
                if not request.form[countInputName]:
                    tripCount = 0
                else:
                    tripCount = request.form[countInputName]

                turnLeg = tripData[countInputName][1]
                travelerID = tripData[countInputName][2]
                try:
                    tripCount = int(tripCount) #this may throw a ValueError
                    if tripCount < 0:
                        result = False
                        raise ValueError("Negative values are not allowed.")
                        
                    if tripCount != tripData[countInputName][0]:
                         #delete the previous manual trips, if any
                         # gin up the possible start and end times
                         startTime, endTime = getTimeStampFromTimeFrame(tripData[countInputName][3].split("-")[0],countEvent.startDate)
                        
                         try:
                             trips = Trip.query.filter(Trip.countEvent_ID == rec.countEvent_ID, 
                                                       Trip.location_ID == rec.location_ID, 
                                                       Trip.traveler_ID == travelerID, 
                                                       Trip.tripDate >= startTime,
                                                       Trip.tripDate <= endTime,
                                                       Trip.turnDirection == turnLeg, 
                                                       Trip.seqNo == "000"
                                                       ).delete()
                         except:
                             pass #the trip records may not exist
                             
                             
                         if tripCount > 0:
                             # genterate the trip time stamp
                             startTime, endTime = getTimeStampFromTimeFrame(tripData[countInputName][3].split("-")[0],countEvent.startDate)
                             try:
                                 cur = Trip(tripCount,endTime,turnLeg,"000",rec.location_ID,travelerID,rec.countEvent_ID)
                                 db.session.add(cur)
                             except Exception as e:
                                 result = False
                                 flash(printException('Could not record Trip for ' + turnLeg,"error",e))
                                
                except ValueError as e:
                    result = False
                    #remove the 'standard' errpr message
                    mes = "%s" % (e)
                    if mes[0:7] == 'invalid':
                        mes = ''
                        
                    trav = Traveler.query.get(travelerID)
                    errTrav = "a traveler"
                    if trav:
                        errTrav = trav.name

                    flash("The value '%s' in turn %s of %s is invalid. %s" % (tripCount,turnLeg,errTrav,mes))
                            
            if result:
                db.session.commit()
                return "success" # this is an ajax request
            else:
                db.session.rollback()
                tripData = getTurnData(rec,request.form)
                flash("No changes were saved.")
                
        # render form
        return render_template('assignment/editTrips.html',
            rec=rec, 
            travelers=travelers,
            tripData=tripData,
            timeFrames=timeFrames
            )
        
    return "failure: Unable to edit trips for Assignment"
示例#41
0
def export():
    """ Export some data"""
    K = []
    F = {}
    if request.form:
        F = request.form
        K = F.keys()
        
    # convert queryData from json
    data = None
    if 'queryData' in K:
        data = request.form['queryData']
        try:
            data = json.loads(request.form['queryData'])
        except Exception as e:
            printException('Bad JSON data in post',"error",e)
            printException("json = " + request.data,"info")
            abort(500)
            
    exportStyle = 'summary'
    if 'exportStyle' in K:
        exportStyle = F['exportStyle']
        
        
    if exportStyle == 'nbpd':
        # this export is completely different...
        return NBPD_Export(data)
        
    # perform query
    recs = None
    if 'searchOrgs' in data.keys() and 'searchEvents' in data.keys():
        recs = queryTripData(data['searchOrgs'], data['searchEvents'], exportStyle)
        
    #print recs
    csv = "Error occured while creating Export\n"
    if app.debug:
        if 'queryData' in K:
            csv += "queryData: %s" % F['queryData']
        else:
            csv += "No queryData in form"
    
    if recs:
    # the columns output are:
    #   Location, Location ID, Latitude, Longitude, Trip Count, 
    #       Trip Date, Turn direction, Traveler name, Organization Name, Event Title, Event Start, Event End
        csv = ""
        for rec in recs:
            headers = "%s is an unknown export style." % (exportStyle)
            row = ""
            if exportStyle == "map":
                headers = "Location Name,Latitude,Longitude,Trip Count\n"
                row = "\"%s\",\"%s\",\"%s\",%d\n" % (rec[0], rec[2], rec[3], rec[4])
            if exportStyle == "summary":
                headers = "Location Name,Latitude,Longitude,Trip Count,Organization Name,Event Title,Event Start,Event End\n"
                row = "\"%s\",\"%s\",\"%s\",%d,\"%s\",\"%s\",\"%s\",\"%s\"\n" % (rec[0], rec[2], rec[3], rec[4], rec[8], rec[9], rec[10], rec[11])
            if exportStyle == "detail":
                headers = "Location Name,Latitude,Longitude,Trip Count,Trip Date,Turn,Traveler,Organization Name,Event Title,Event Start,Event End\n"
                row = "\"%s\",\"%s\",\"%s\",%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n" % (rec[0], rec[2], rec[3], rec[4], rec[5], rec[6], rec[7], rec[8], rec[9], rec[10], rec[11])
                
            csv += row
            
        csv = headers + csv
   
    response = make_response(csv)
    now = datetime.now()
    now = now.strftime('%H%M%S')
    cd = "attachment; filename=BAW_%s_export_%s.csv" % (exportStyle, now)
    
    response.headers['Content-Disposition'] = cd 
    response.mimetype='text/csv'
    
    return response
示例#42
0
def count_trip():
    #theResult = "Unknown"
    try:
        # receive a json object containing the trips and other data
        data = request.get_json(force=True)
        
    except Exception as e:
        printException('Bad JSON data in post',"error",e)
        printException("json = " + request.data,"info")
        return '{"result":"success"}'
        
    # get the countEvent record because we need the timezone offset
    rec = CountEvent.query.get(int(data['countEvent']))
    try:
        if rec:
            startDate = getDatetimeFromString(rec.startDate)
            endDate = getDatetimeFromString(rec.endDate)
            localTime = getLocalTimeAtEvent(rec.timeZone,rec.isDST) # Get the current local time at the event location
        else:
            raise ValueError("CountEvent Record No Found")
            
    except Exception as e:
        printException("CountEvent Record No Found","error")
        #theResult = "CountEventError"
        return '{"result":"success"}'
        
    trip = dict()
    trip['action'] = data.get('action')
    trip['location_ID'] = cleanRecordID(data.get('location'))
    trip['countEvent_ID'] = cleanRecordID(data.get('countEvent'))
    
    ## There is an 'action' called as 'total' with no trips data.
    ##  This loop will not execute and only the current total will be returned
    
    for i in range(len(data['trips'])):
        #d = datetime.utcnow() + timedelta(hours=-7)
        temp = data['trips'][i] # get the dict for the trip
        trip['seqNo'] = cleanRecordID(temp.get('seqNo'))
        trip['tripCount'] = cleanRecordID(temp.get("count"))
        trip['tripDate'] = temp.get('tripDate', "").strip()
        trip['turnDirection'] = temp.get('direction', "").strip()
        trip['traveler_ID'] = cleanRecordID(temp.get('traveler'))
        
        tripDate = getDatetimeFromString(trip['tripDate'])
        if not tripDate:
            # bad date string, log it and go to the next record
            printException("Bad trip date: " + temp, "error")
            continue # do next loop
           
        if trip['action'] == "undo":
            ## don't allow old trips to be undone
            ### If the trip is more than 1 minute in the past, it can't be deleted
            if tripDate + timedelta(minutes= 1) > localTime:
                
                try:
                    rec = Trip.query.filter(Trip.location_ID == trip['location_ID'], \
                        Trip.countEvent_ID == trip['countEvent_ID'], \
                        Trip.seqNo == trip['seqNo'], \
                        Trip.tripDate == trip["tripDate"]).first()
                    
                    if rec:
                        db.session.delete(rec)
                        db.session.commit()
                
                except Exception as e:
                    printException('Could not undo Trip '+str(i),"error",e)
            

        if trip["action"] == "add":
            
            validTrip, errorMess = isValidTrip(trip,startDate,endDate,localTime)
            
            if validTrip or True: #### Always Valid for Now #####
                try:
                    cur = Trip(trip['tripCount'],trip['tripDate'],trip['turnDirection'],trip['seqNo'],trip['location_ID'],trip['traveler_ID'],trip['countEvent_ID'])
                    db.session.add(cur)
                    db.session.commit()            
                except Exception as e:
                    printException('Could not record Trip '+str(i),"error",e)
                    printException("trip data: " + str(data), "info" )
                    
            else:
                #not a valid trip, so save in provisionalTrip table
                try:
                    cur = ProvisionalTrip(trip['tripCount'],trip['tripDate'],trip['turnDirection'],trip['seqNo'],trip['location_ID'],trip['traveler_ID'],trip['countEvent_ID'])
                    db.session.add(cur)
                    cur.issue = errorMess
                    
                    # inform the responsible parties
                    #sendProvisionalTripEmail() #Sends an email no more than once a day
                    
                except Exception as e:
                    printException('Could not record provisional Trip',"error",e)
                    printException("trip data: " + str(data), "info" )
                    
        else:
            #Bad action request
            pass
            
    try:
        db.session.commit()
    except Exception as e:
        printException("Unable to commit to trip or provisionalTrip", "error", e)
        printException("trip data: " + str(data), "info" )
        
    #Get the total so far:
    totalCnt = getAssignmentTripTotal(trip["countEvent_ID"], trip["location_ID"])
    
    return '{"result":"success", "total": %d}' % (totalCnt)
示例#43
0
def location(orgID="0"):
    setExits()
    g.title = 'Count Locations'
    g.mapURL = url_for('.location')
    
    searchOrgs = []
    searchEvents = []
    
    # User specified a particular organization to list
    orgID = cleanRecordID(orgID)
    if orgID > 0:
        g.orgID = orgID
        searchOrgs.append(str(orgID))
        
    if db :
        queryData = {}
        queryData['searchType'] = 'locations'
        queryData['selectType'] = 'multiple'
        queryData['includeAllOption'] = True
        
        #Get all orgs
        searchForm.orgsToDict(queryData)
        
        if not request.form and g.orgID:
            queryData['searchOrgs'] = [str(g.orgID)]
        else:
            searchForm.getSelectValues(request.form, searchOrgs,searchEvents) # all parameters must be empty lists
            queryData['searchOrgs'] = searchOrgs #We don't need searchEvents for this map

        sql = "select locationName, ID, latitude, longitude from location "
        if '0' not in searchOrgs:
            orgIDs = ""
            for i in searchOrgs:
                orgIDs += i + ","
            sql += " where organization_ID in (%s) " % (orgIDs[0:-1])
        
        recs = db.engine.execute(sql).fetchall()
        
        markerData = {}
        markerData["cluster"] = True
        markerData["zoomToFit"] = False # can't zoom if there are no markers
        if recs:
            markerData["markers"] = []

            for rec in recs:
                #db.engine.execute returns a list of sets without column names
                #namedtuple creates an object that getMarkerDict can access with dot notation
                Fields = namedtuple('record', 'locationName ID latitude longitude')
                record = Fields(rec[0], rec[1], rec[2], rec[3])

                marker = getMarkerDict(record) # returns a dict or None
                
                if marker:
                    popup = render_template('map/locationListPopup.html', rec=record)
                    popup = escapeTemplateForJson(popup)
                    marker['popup'] = popup
                    
                    markerData["markers"].append(marker)
                    
                markerData["zoomToFit"] = True
            
        return render_template('map/JSONmap.html', markerData=markerData, queryData=queryData)
        
    else:
        flash(printException('Could not open Database',"info"))
        return redirect(url_for('home'))
示例#44
0
def editTripsFromList(id):
    setExits()
    tripData = {}  #empty dictionary
    id = cleanRecordID(id)
    if id > 0:
        rec = Assignment.query.get(id)
        if not rec:
            return "failure: Assignment record not found"

        tripCount = getAssignmentTripTotal(id)
        if tripCount > 0:
            return "failure: There are already trips recorded."

        # Get travelers
        travelers = getTravelersForEvent(rec.countEvent_ID)

        #populate tripData with info on manually enterd counts
        tripData = getTurnData(rec)
        countEvent = CountEvent.query.get(rec.countEvent_ID)

        timeFrames = getTripTimeFrames(
            getDatetimeFromString(countEvent.startDate),
            getDatetimeFromString(countEvent.endDate))

        if request.method == "POST":
            # Validate form?
            result = True
            # record trips
            for countInputName in tripData.keys():
                if not request.form[countInputName]:
                    tripCount = 0
                else:
                    tripCount = request.form[countInputName]

                turnLeg = tripData[countInputName][1]
                travelerID = tripData[countInputName][2]
                try:
                    tripCount = int(tripCount)  #this may throw a ValueError
                    if tripCount < 0:
                        result = False
                        raise ValueError("Negative values are not allowed.")

                    if tripCount != tripData[countInputName][0]:
                        #delete the previous manual trips, if any
                        # gin up the possible start and end times
                        startTime, endTime = getTimeStampFromTimeFrame(
                            tripData[countInputName][3].split("-")[0],
                            countEvent.startDate)

                        try:
                            trips = Trip.query.filter(
                                Trip.countEvent_ID == rec.countEvent_ID,
                                Trip.location_ID == rec.location_ID,
                                Trip.traveler_ID == travelerID,
                                Trip.tripDate >= startTime,
                                Trip.tripDate <= endTime,
                                Trip.turnDirection == turnLeg,
                                Trip.seqNo == "000").delete()
                        except:
                            pass  #the trip records may not exist

                        if tripCount > 0:
                            # genterate the trip time stamp
                            startTime, endTime = getTimeStampFromTimeFrame(
                                tripData[countInputName][3].split("-")[0],
                                countEvent.startDate)
                            try:
                                cur = Trip(tripCount, endTime, turnLeg, "000",
                                           rec.location_ID, travelerID,
                                           rec.countEvent_ID)
                                db.session.add(cur)
                            except Exception as e:
                                result = False
                                flash(
                                    printException(
                                        'Could not record Trip for ' + turnLeg,
                                        "error", e))

                except ValueError as e:
                    result = False
                    #remove the 'standard' errpr message
                    mes = "%s" % (e)
                    if mes[0:7] == 'invalid':
                        mes = ''

                    trav = Traveler.query.get(travelerID)
                    errTrav = "a traveler"
                    if trav:
                        errTrav = trav.name

                    flash("The value '%s' in turn %s of %s is invalid. %s" %
                          (tripCount, turnLeg, errTrav, mes))

            if result:
                db.session.commit()
                return "success"  # this is an ajax request
            else:
                db.session.rollback()
                tripData = getTurnData(rec, request.form)
                flash("No changes were saved.")

        # render form
        return render_template('assignment/editTrips.html',
                               rec=rec,
                               travelers=travelers,
                               tripData=tripData,
                               timeFrames=timeFrames)

    return "failure: Unable to edit trips for Assignment"
示例#45
0
def editEventTraveler(eventTravelerID=0):
    setExits()
    data = None
    rec = None
    traveler = None

    if request.form:
        eventTravelerID = cleanRecordID(request.form["ID"])
        g.countEventID = cleanRecordID(request.form["countEvent_ID"])
    else:
        eventTravelerID = cleanRecordID(eventTravelerID)
        
    travelerName = ""
    if eventTravelerID > 0:
        rec = EventTraveler.query.get(eventTravelerID)
        if rec:
            g.countEventID = rec.countEvent_ID
            traveler = Traveler.query.get(rec.traveler_ID)
            travelerName = traveler.name
            
#    print eventTravelerID
#    print g.countEventID
        
    if g.countEventID <= 0:
        return "failure: No Count Event ID was found."

    availableTravelers = None 
    if eventTravelerID == 0:
        #If creating a new record, get a list of unused travelers

        sql = 'select ID,name from traveler \
            where  \
            ID not in \
               (select traveler_ID from event_traveler where countEvent_ID  = %d);' \
            % (g.countEventID)

        ## It's important to call fetchcll() or fetchone() after executing sql this way or the
        ##  database will be left in a locked state.
        availableTravelers = db.engine.execute(sql).fetchall()
        if len(availableTravelers) == 0:
            return "failure: There are no more Travelers to use."
    
    travelerOrder = None
    #get a list of all the sort orders for the current set of travelers for this event
    et = getEventTravelers(g.countEventID)
    travelerOrder = []
    elem = {"travelerName" : "1st in list", "sortOrder": 0}
    lastSortOrder = 0
    travelerOrder.append(elem)
    for t in et:
        elem = {"travelerName": ("Before " + t.travelerName),"sortOrder": int((lastSortOrder + t.sortOrder) / 2)}
        lastSortOrder = t.sortOrder
        if traveler:
            currentID = traveler.ID
        else:
            currentID = 0
            
        if t.traveler_ID != currentID:
            travelerOrder.append(elem)
            
    elem = {"travelerName": "End of List","sortOrder": lastSortOrder + 100}
    travelerOrder.append(elem)
    
    form = EventTravelerForm(request.form, rec)
     
     
    if request.method == "POST" :
        #There is only one select element on the form so it always validates
        if not rec:
            rec = EventTraveler(form.countEvent_ID.data, form.traveler_ID.data)
            if  not rec:
                return "failure: Unable to create a new EventTraveler record"
                
            db.session.add(rec)
            
        rec.sortOrder = form.sortOrder.data
        try:
            db.session.commit()
            
        except Exception as e:
            printException("Unable to save Assignment from list", "error", e)
            return "failure: Sorry. Unable to save your changes."
        
        # "Normalize the sortOrders"
        recs = EventTraveler.query.filter(EventTraveler.countEvent_ID == g.countEventID).order_by(EventTraveler.sortOrder)
        if recs:
            next = 100
            for rec in recs:
                rec.sortOrder = next
                next += 100
            try:
                db.session.commit()
            except Exception as e:
                # this is not critical to the current operation, advise only
                db.session.rollback()
                printException("Unable to Normalize EventTraveler recs", "error", e)
                
        return "success" # the success function looks for this...
    
    return render_template('traveler/eventTravelerPopupEditForm.html', 
        form=form, 
        availableTravelers=availableTravelers,
        travelerOrder=travelerOrder, 
        travelerName=travelerName,
        )
示例#46
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
    
    if not request.form:
        """ if no form object, send the form page """
        # get the Org record if you can
        rec = None
        if id > 0:
            rec = Traveler.query.get(id)
        #get a cursor of all features
        features = getFeatureSet(id)

        return render_template('traveler/traveler_edit.html', rec=rec, features=features, lastFeature=len(features))

    #have the request form
    if validForm():
        if id > 0:
            rec = Traveler.query.get(id)
        else:
            ## create a new record stub
            rec = Traveler(request.form['name'],request.form['travelerCode'])
            db.session.add(rec)
        try:
            db.session.commit() ## ID now has a value
        except Exception as e:
            db.session.rollback()
            flash(printException('Could not '+g.title+' record.',"error",e))
            return redirect(g.listURL)
            
        #update the record
        rec.name = request.form['name']
        rec.travelerCode = request.form['travelerCode']
        rec.description = request.form['description']
        rec.iconURL = request.form['iconURL']
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(printException('Could not Update '+g.title+' record (ID ='+str(id)+').',"error",e))
            return redirect(g.listURL)
            
        id = rec.ID
        
        # now update the features
        #delete the old ones first
        tf = TravelerFeature.query.filter_by(traveler_ID = str(id)).delete(synchronize_session='fetch')
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(printException('Could not Delete Feature records for '+g.title+' record (ID ='+str(id)+').',"error",e))
            return redirect(g.listURL)
           
        #create new ones
        featureSet = request.form.getlist('featureSet')
        for feat in featureSet:
            tf = TravelerFeature(id,int(feat))
            db.session.add(tf)
            
        try:
            db.session.commit()    
        except Exception as e:
            db.session.rollback()
            flash(printException('Could not Create Feature records for '+g.title+' record (ID ='+str(id)+').',"error",e))
            return redirect(g.listURL)
                 
        return redirect(g.listURL)

    # form not valid - redisplay
    features = getFeatureSet(id)
    app.logger.info("Feature set len = " +str(features))
    return render_template('traveler/traveler_edit.html', rec=request.form, features=features, lastFeature=len(features))
示例#47
0
def edit(id=0):
    setExits()
    id = cleanRecordID(id)
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
        
    assignmentList = getAssignmentList(id) #fully rendered HTML
    travelerList = getTravelerList(id)
    timeZones = getTimeZones()
    g.tripTotalCount = getCountEventTripTotal(id)
    
    if not request.form:
        """ if no form object, send the form page """
        #Set up a default time for the event
        # Today with time set to something reasonable
        start = datetime.now().replace(hour=16, minute=0, second=0)
        end = start + timedelta(hours=2)
        
        theTime = getTimeDictionary(start.isoformat(),end.isoformat())
        cur = None
        #Get the default timeZone for this Organization
        g.timeZone = getDefaultTimeZone()
            
        if id > 0:
            cur = CountEvent.query.filter_by(ID=id).first()
            if not cur:
                mes = g.title +" Record could not be found." + " ID:" + str(id)
                flash(printException(mes,"error"))
                return redirect(g.listURL)
            
            theTime = getTimeDictionary(cur.startDate,cur.endDate)
            g.timeZone = None
            
        
        return render_template('count_event/count_event_edit.html', 
            rec=cur ,theTime=theTime, 
            timeZones=timeZones, 
            assignmentList=assignmentList, 
            travelerList=travelerList,
            )

    #have the request form
    # handle the checkbox for Daylite savings time
    isDST = 0
    if request.form["isDST"]:
        isDST = request.form["isDST"]
        
    if validForm():
        startingDate = startDateFromForm()
        endingDate = endDateFromForm()
        if id > 0:
            cur = CountEvent.query.get(id)
            #update the record
            cur.title = request.form["title"]
            cur.startDate = startingDate.isoformat()[:19]
            cur.endDate = endingDate.isoformat()[:19]
            cur.isDST = isDST
            cur.timeZone = request.form["timeZone"]
            cur.weather = request.form["weather"]
            cur.organization_ID = request.form['organization_ID']
        else:
            ## create a new record
            cur = CountEvent(request.form["title"],startingDate.isoformat()[:19],endingDate.isoformat()[:19],request.form["timeZone"],isDST,request.form['organization_ID'])
            db.session.add(cur)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(printException('Error attempting to save '+g.title+' record.',"error",e))
            
        return redirect(g.listURL)


    # form not valid - redisplay
    #restore theTime to the values as entered
    theTime = dict()
    theTime["hour"] = int(request.form["hour"])
    theTime["minute"] = int(request.form["minute"])
    theTime["duration"] = int(request.form["duration"])
    theTime["AMPM"] = request.form["AMPM"]
    theTime["eventDate"] = request.form["eventDate"]
    
    return render_template('count_event/count_event_edit.html', rec=request.form, theTime=theTime, timeZones=timeZones, assignmentList=assignmentList)
示例#48
0
def edit(id=0):
    #printException(str(request.form)) 
    
    setExits()
    id = cleanRecordID(id)
    orgs = Organization.query.order_by(Organization.name)
    u = getUserOrgs(id)
    selectedOrgs = []
    for s in u:
        selectedOrgs.append(s.ID)
    
    if id < 0:
        flash("That is not a valid ID")
        return redirect(g.listURL)
            
    rec = None
    
    if not request.form:
        """ if no form object, send the form page """
        # get the user record if you can
        currentPassword = ""
        if id > 0:
            rec = User.query.get(id)
            currentPassword = rec.password
                
        
    else:
        #have the request form
        #ensure a value for the check box
        inactive = request.form.get('inactive')
        if not inactive: 
            inactive = "0"
        

        if validForm():
            if id > 0:
                rec = User.query.get(id)
            else:
                ## create a new record stub
                rec = User(request.form['name'],request.form['email'])
                db.session.add(rec)
                #db.session.commit() # this loads the new ID into rec
                
                rec.userName = db.null()
                rec.password = db.null()
        
            #Are we editing the current user's record?
            editingCurrentUser = ''
            if(g.user == rec.userName):
                editingCurrentUser = request.form['userName'].strip()
            else: 
                if(g.user == rec.email):
                    editingCurrentUser = request.form['email'].strip()
            
            #update the record
            rec.name = request.form['name'].strip()
            rec.email = request.form['email'].strip()
            rec.role = request.form['role'].strip()
            rec.inactive = str(inactive)
            
            user_name = ''
            if request.form['userName']:
                user_name = request.form['userName'].strip()
            
            if user_name != '':
                rec.userName = user_name
            else:
                rec.userName = db.null()
        
            # Null values in db are returned as None
            if str(rec.password) != 'NULL' and request.form['password'].strip() == '':
                # Don't change the password
                pass
            else:
                user_password = ''
                if request.form['password'].strip() != '':
                    user_password = getPasswordHash(request.form['password'].strip())

                if user_password != '':
                    rec.password = user_password
                else:
                    rec.password = db.null()
    
            try:
                db.session.commit()
                # create user_organization records
                # in the case of a new user, rec.ID is now available
                orgIDs = request.form.getlist("orgs")
                if not orgIDs:
                    orgIDs = [request.form.get('org')]
                makeUserOrgRecords(rec.ID,orgIDs)
                db.session.commit()
                
                # if the username or email address are the same as g.user
                # update g.user if it changes
                if(editingCurrentUser != ''):
                    setUserStatus(editingCurrentUser)
                    views.login.setUserSession(editingCurrentUser)
                
            
           
                
            except Exception as e:
                db.session.rollback()
                flash(printException('Error attempting to save '+g.title+' record.',"error",e))
            
            return redirect(g.listURL)
        
        else:
            # form did not validate, giv user the option to keep their old password if there was one
            currentPassword = ""
            if request.form["password"] != "" and id > 0:
                rec = User.query.get(id)
                currentPassword = rec.password
            rec=request.form

    # so the checkbox will be set on new record form
    if len(selectedOrgs) == 0:
        selectedOrgs.append(g.orgID)
            
    # display form
    return render_template('user/user_edit.html', rec=rec, currentPassword=currentPassword, orgs=orgs, selectedOrgs=selectedOrgs)