def validForm(rec): # Validate the form goodForm = True if rec.title and rec.title.strip(): pass else: flash("You must give the event a title") goodForm = False if not isinstance(getDatetimeFromString(rec.start), ( date, datetime, )): flash("That is not a valid Starting Date") goodForm = False if not isinstance(getDatetimeFromString(rec.end), ( date, datetime, )): flash("That is not a valid Ending Date") goodForm = False if goodForm: if rec.end <= rec.start: flash("The Starting date must be before the Ending date") goodForm = False return goodForm
def stock_report(): """Ask user for report date range then create report on post""" setExits() g.title = "Inventory Stock Report" start_date = None end_date = None warehouses = Warehouse(g.db).select() if request.form: start_date = getDatetimeFromString(request.form.get( "start_date", None)) end_date = getDatetimeFromString(request.form.get("end_date", None)) warehouse_id = request.form.get('warehouse_id', '-1') if start_date and end_date and start_date < end_date: return stock_on_hand_report(start_date, end_date, warehouse_id) else: start_date = request.form['start_date'] end_date = request.form['end_date'] flash("Those don't look like valid dates... Try 'YYYY-MM-DD'") ## else send form page if not start_date: start_date = local_datetime_now().replace(month=1, day=1) if not end_date: end_date = local_datetime_now().replace(month=12, day=31) return render_template('reports/item_report_input.html', start_date=start_date, end_date=end_date, warehouses=warehouses)
def test_getDatetimeFromString(): site_config = get_site_config() assert dates.getDatetimeFromString("12/14/12") == dates.make_tz_aware( datetime(2012, 12, 14), site_config["TIME_ZONE"]) assert dates.getDatetimeFromString("2012-12-14") == dates.make_tz_aware( datetime(2012, 12, 14), site_config["TIME_ZONE"]) assert dates.getDatetimeFromString("12/14/2012") == dates.make_tz_aware( datetime(2012, 12, 14), site_config["TIME_ZONE"]) assert dates.getDatetimeFromString("2/8/19") == dates.make_tz_aware( datetime(2019, 2, 8), site_config["TIME_ZONE"]) assert dates.getDatetimeFromString("2/8/51") == dates.make_tz_aware( datetime(1951, 2, 8), site_config["TIME_ZONE"]) #test what happens when you pass in a date time assert dates.getDatetimeFromString(datetime(2019, 2, 8)) == dates.make_tz_aware( datetime(2019, 2, 8), site_config["TIME_ZONE"]) assert dates.getDatetimeFromString( datetime(2019, 2, 8, 6, 33, 00)) == dates.make_tz_aware(datetime(2019, 2, 8, 6, 33, 00), site_config["TIME_ZONE"]) # Pass in a date assert dates.getDatetimeFromString(date(2019, 2, 8)) == dates.make_tz_aware( datetime(2019, 2, 8), site_config["TIME_ZONE"])
def update(self,rec,form,save=False): """Update the rec, with the matching elements in form Args: rec: dictionary like object, represents an existing or new reocrd or a dict of values to be applied to the current current record. form is a dictionary like object with the new data. Usually request.form The id element is never updated. Before calling this method be sure that any elements in form that have names matching names in rec contain the values you want. Optionally can save the rec (but not committed) after update """ # import pdb;pdb.set_trace() if rec and form: for key,value in rec.items(): if key != 'id' and key in form: val = form[key] try: # if key is an adhoc column name that was defined in a query, no update required # Dates need special formatting col_type = self.get_column_type(key).upper() if col_type == 'DATETIME' or col_type == 'DATE': if not isinstance(val,datetime): val = getDatetimeFromString(val) setattr(rec, key, val) except KeyError: pass if save: self.save(rec)
def validate_form(rec): valid_form = True datestring = request.form.get('created', '').strip() if datestring == '': valid_form = False flash('Date may not be empty') else: createdDate = getDatetimeFromString(datestring) if createdDate is None: flash('Date is not in a known format ("mm/dd/yy")') valid_form = False elif createdDate > local_datetime_now(): flash("The date may not be in the future") valid_form = False if valid_form: rec.created = createdDate # Value must be a number try: rec.value = float(request.form.get('value', 0)) except ValueError as e: flash('Could not convert Value {} to a number'.format( request.form.get('value', ""))) valid_form = False # Must be attached to an item itemID = cleanRecordID(request.form.get('item_id', 0)) if not itemID or itemID < 0: flash("You must select an item to use with this transaction") valid_form = False #Try to coerse qty to a number rec.qty = request.form.get('qty', '').strip() if rec.qty == '': flash('Quantity is required') valid_form = False if not Warehouse(g.db).get(request.form.get('warehouse_id', -1)): flash("You must select a warehouse") valid_form = False try: rec.qty = float(rec.qty) if rec.qty == 0: flash('Quantity may not be 0') valid_form = False #truncate qty if int if rec.qty - int(rec.qty) == 0: rec.qty = int(rec.qty) except ValueError as e: flash('Could not convert Qty {} to a number'.format(rec.qty)) valid_form = False return valid_form
def add_event(self, uid, start, end, summary, **kwargs): """Ad an event to the calendar""" if isinstance(start, str): start = getDatetimeFromString(start) if isinstance(end, str): end = getDatetimeFromString(end) ev = Event() ev.add('uid', uid) ev.add('dtstart', start) ev.add('dtend', end) ev.add('summary', summary) datestamp = kwargs.pop('dtstamp', datetime.utcnow()) ev.add('DTSTAMP', datestamp) for key, value in kwargs.items(): if value: ev.add(key, value) self.add_component(ev)
def abbr_date_string(value): """Mon. Mar. 4, 2019""" format='%a. %b. %-d, %Y' if type(value) is str: # convert the string to a date first then back. value = getDatetimeFromString(value) #No period after May if value.month == 5: format='%a. %b %-d, %Y' return date_to_string(value,format)
def validate_form(rec): valid_form = True #Try to coerse qty to a number if request.form['qty'].strip() == '': flash('Quantity is required') valid_form = False else: try: rec.qty = float(rec.qty) if rec.qty <= 0: flash('Quantity must be greater than 0') valid_form = False #truncate qty if int elif rec.qty - int(rec.qty) == 0: rec.qty = int(rec.qty) except ValueError as e: flash('Quantity must be a number') valid_form = False # Must be attached to an item itemID = cleanRecordID(request.form.get('item_id', 0)) if itemID <= 0: flash("You must select an item to use with this transfer") valid_form = False #Must not be more than stock on hand elif rec.qty and type(rec.qty) != str: QOH = Item(g.db).stock_on_hand( itemID, warehouse_id=request.form.get("warehouse_out_id")) if rec.qty > QOH: flash("You may not transfer more than the quantity on hand ({})". format(QOH)) valid_form = False if not Warehouse(g.db).get( cleanRecordID(request.form.get('warehouse_out_id'))): flash("You must select a transfer out warehouse") valid_form = False if not Warehouse(g.db).get( cleanRecordID(request.form.get('warehouse_in_id'))): flash("You must select a transfer in warehouse") valid_form = False # test for valid date test_date = rec.transfer_date if isinstance(test_date, str): test_date = getDatetimeFromString(rec.transfer_date) if not test_date: flash("There must be transfer date") valid_form = False else: rec.transfer_date = test_date if test_date > local_datetime_now(): flash("Transfer date may not be in the future") valid_form = False return valid_form
def test_prefs(): from shotglass2.users.models import Pref #db = get_test_db() assert Pref(db).get(0) == None assert Pref(db).get("this") == None rec = Pref(db).new() rec.name = "Testing" rec.value = "A test value" recID = Pref(db).save(rec) rec = Pref(db).get(recID) assert rec.id == recID assert rec.name == 'Testing' assert rec.value == "A test value" rec = Pref(db).get('Testing') assert rec.name == 'Testing' assert rec.value == "A test value" # get is now case in-sensitive rec = Pref(db).get('testing') assert rec.name == 'Testing' assert rec.value == "A test value" #Modify the record rec.name = "New Test" Pref(db).save(rec) rec = Pref(db).get(rec.id) assert rec.name == "New Test" db.rollback() # test the default setting pref_name = "A new pref" default_value = "A Default value" rec = Pref(db).get(pref_name) assert rec == None # create a new record with default values rec = Pref(db).get(pref_name, default=default_value) assert rec != None assert rec.name == pref_name assert rec.value == default_value assert rec.user_name == None # create another except has a user name rec = Pref(db).get(pref_name, user_name='test', default="new value") assert rec != None assert rec.name == pref_name assert rec.value == 'new value' assert rec.user_name == 'test' # get the generic record rec = Pref(db).get(pref_name) assert rec != None assert rec.name == pref_name assert rec.value == default_value # get the user specific record. Providing a default should not change the record rec = Pref(db).get(pref_name, user_name='test', default="someother value") assert rec != None assert rec.name == pref_name assert rec.value == 'new value' assert rec.user_name == 'test' # this should have no effect because get with default does a commit db.rollback() rec = Pref(db).get(pref_name) assert rec != None assert rec.name == pref_name assert rec.value == default_value #new pref was committed, so delete it assert Pref(db).delete(rec.id) == True db.commit() #Test that it's really gone rec = Pref(db).get(pref_name) assert rec == None # make with all values temp_date = local_datetime_now() pref = Pref(db) rec = pref.get("sample1", default="me", description="test me", user_name='willie', expires=temp_date) assert rec != None assert rec.name == "sample1" assert rec.value == "me" assert rec.description == "test me" assert rec.user_name == "willie" assert getDatetimeFromString(rec.expires).date() == temp_date.date()
def time_lapse_map(): """ Display an automated map of bike sightings over time @@@ This is left over from the JumpStat maps but it might be a place to start in the future... """ setExits() days = 1 start_date = local_datetime_now() + timedelta( days=-1) # Always starts at midnight, yesterday start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0) end_date = start_date + timedelta(days=days, seconds=-1) frame_duration = 10 * 60 # this many seconds of real time elapse between each frame seconds_per_frame = 1 # display each frame for this many seconds sql = """select id, lng, lat, sighted, retrieved from sighting where retrieved >= '{start_date}' and sighted <= '{end_date}' order by sighted """.format(start_date=start_date.isoformat(sep=' '), end_date=end_date.isoformat(sep=' ')) recs = g.db.execute(sql).fetchall() marker_data = {"markers": []} marker_data["zoomToFit"] = False # can/t zoom if there are no markers. if recs: """ The Marker is a list of lists containing: lng, lat, display start seconds, display end seconds At play time in javascript, every frame_duration seconds loop through Markers: if display start seconds <= frame start time and display end seconds >= frame end time, set the marker opacity to 1 else set opacity to 0 """ total_seconds = int(round((end_date - start_date).total_seconds(), 0)) marker_data["zoomToFit"] = True marker_data['total_seconds'] = total_seconds marker_data['frame_duration'] = frame_duration marker_data['seconds_per_frame'] = seconds_per_frame #import pdb;pdb.set_trace() for rec in recs: sighted_dt = getDatetimeFromString(rec['sighted']) if sighted_dt.day == 17: #import pdb;pdb.set_trace() pass #print('sighted_dt: {}'.format(sighted_dt)) retrieved_dt = getDatetimeFromString(rec['retrieved']) #print('retrieved_dt: {}'.format(retrieved_dt)) marker_data["markers"].append([ round(rec['lng'], 5), round(rec['lat'], 5), int(round((sighted_dt - start_date).total_seconds(), 0)), int(round((retrieved_dt - start_date).total_seconds(), 0)), ]) return render_template('JSONmap.html', marker_data=marker_data, start_date=start_date)