Пример #1
0
    def call_resource(self, request):
        readings = TrainingDataManager().reading_types_unused_for_date(
            request.POST['date'])

        response = TrainingDiaryResponse()
        response.add_data('readings', readings)

        return JsonResponse(data=response.as_dict())
Пример #2
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        last_date = TrainingDataManager().latest_date()
        d = parser.parse(last_date).date()
        next_date = d + timedelta(1)
        response.add_data('next_date', next_date)

        return JsonResponse(data=response.as_dict())
Пример #3
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        try:
            tdm = TrainingDataManager()
            tdm.delete_reading_for_primary_key(request.POST['primary_key'])
            response.set_status(response.SUCCESS)
            response.add_data('primary_key', request.POST['primary_key'])
            response.add_message(
                response.MSG_INFO,
                f"Reading Deleted: {request.POST['primary_key']}")
        except Exception as e:
            response.set_status(response.ERROR)
            response.add_message(response.MSG_ERROR,
                                 f"Delete failed: {str(e)}")

        return JsonResponse(data=response.as_dict())
Пример #4
0
    def post(self, request, *args, **kwargs):
        r = super().post(request, args, kwargs)
        user = authenticate(request, username=request.POST['username'], password=request.POST['password'])

        if user is None:
            return JsonResponse(data=TrainingDiaryResponse.error_response_dict('Invalid username and password. Please try again'))

        if r.status_code == 302:
            login(self.request, user)
            response = TrainingDiaryResponse()
            response.set_status(response.SUCCESS)
            response.add_data('user', str(user))
            response.add_data('logged_in', True)
            return JsonResponse(data=response.as_dict())
        else:
            return JsonResponse(data=TrainingDiaryResponse.error_response_dict('Unable to login. No idea why'))
Пример #5
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        tdm = TrainingDataManager()
        instances = []
        if request.POST['data_type'] == 'Day':
            instances = tdm.days_between(request.POST['from_date'],
                                         request.POST['to_date'])
        elif request.POST['data_type'] == 'Reading':
            instances = tdm.readings_between(request.POST['from_date'],
                                             request.POST['to_date'])
        elif request.POST['data_type'] == 'Workout':
            instances = tdm.workouts_between(request.POST['from_date'],
                                             request.POST['to_date'])

        response.add_data('instances',
                          [i.data_dictionary() for i in instances])

        return JsonResponse(data=response.as_dict())
Пример #6
0
    def call_resource(self, request):
        date = request.POST['date']
        readings = list()
        tdm = TrainingDataManager()
        for reading in json.loads(request.POST['json']):
            tdm.save_reading(date, reading['reading'], reading['value'])
            readings.append(reading['reading'])

        readings_saved = list()
        for r in readings:
            readings_saved.append(
                tdm.reading_for_date_and_type(date, r)[0].data_dictionary())

        response = TrainingDiaryResponse()
        response.add_message(response.MSG_INFO,
                             f"{len(readings)} saved: {', '.join(readings)}")
        response.add_data('readings', readings_saved)
        return JsonResponse(data=response.as_dict())
Пример #7
0
 def call_resource(self, request):
     response = TrainingDiaryResponse()
     tdm = TrainingDataManager()
     summary = tdm.training_annual_summary()
     totals = {"name": 'Total'}
     years = list()
     for yr, v in summary.items():
         for activity, dd in v.items():
             a_dd = totals.get(activity, {'km': 0, 'seconds': 0, 'tss': 0})
             a_dd['km'] += dd['km']
             a_dd['seconds'] += dd['seconds']
             a_dd['tss'] += dd['tss']
             totals[activity] = a_dd
         v['name'] = yr
         years.append(v)
     years.append(totals)
     # response.add_data('summary', summary)
     response.add_data('years', years)
     return JsonResponse(data=response.as_dict())
Пример #8
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        dd, errors = self._process_data(request.POST['json'])
        [response.add_message(response.MSG_ERROR, e) for e in errors]

        tdm = TrainingDataManager()
        primary_key = tdm.workout_primary_key(dd['date'], dd['workout_number'])
        try:
            if 'primary_key' not in dd or dd['primary_key'] == "":
                # new workout
                lastrowid = tdm.save_workout(
                    **self._filtered_dict(dd, self.NEW_FIELDS))
                response.add_message(response.MSG_INFO, f"New workout saved")
                response.add_data(
                    'workout',
                    tdm.workout_for_rowid(lastrowid)[0].data_dictionary())
            elif primary_key == dd['primary_key']:
                # update workout
                tdm.update_workout(
                    **self._filtered_dict(dd, self.UPDATE_FIELDS))
                response.add_message(response.MSG_INFO, f"Workout updated")
                response.add_data(
                    'workout',
                    tdm.workout_for_primary_key(primary_key)
                    [0].data_dictionary())
            else:
                # changed the date. Need a new workout to get primary_keys right
                old_key = dd['primary_key']
                tdm.delete_workout_for_primary_key(old_key)
                response.add_data('removed_primary_key', old_key)
                lastrowid = tdm.save_workout(
                    **self._filtered_dict(dd, self.NEW_FIELDS))
                workout = tdm.workout_for_rowid(lastrowid)[0]
                response.add_message(
                    response.MSG_INFO,
                    f"Workout date changed so old workout deleted and new one added. Remove {old_key} and added {workout.primary_key}"
                )
                response.add_data('workout', workout.data_dictionary())
        except TypeError as e:
            response.set_status(response.ERROR)
            response.add_message(response.MSG_ERROR, str(e))

        return JsonResponse(data=response.as_dict())
Пример #9
0
    def call_resource(self, request):
        target_date = request.POST['date']
        response = TrainingDiaryResponse()
        tdm = TrainingDataManager()

        if tdm.day_exists(target_date):
            tdm.update_day(target_date, request.POST['day_type'],
                           request.POST['comments'])
            response.add_message(response.MSG_INFO,
                                 f"Day updated for {target_date}")
        else:
            tdm.save_day(target_date, request.POST['day_type'],
                         request.POST['comments'])
            response.add_message(response.MSG_INFO,
                                 f"New day added for {target_date}")

        response.add_data('day',
                          tdm.day_for_date(target_date).data_dictionary())

        return JsonResponse(data=response.as_dict())
Пример #10
0
    def call_resource(self, request):

        period_year = Period(pandas_period=PandasPeriod.Y_DEC,
                             aggregation=Aggregation.MEAN,
                             to_date=False,
                             incl_zeroes=False)

        series_definition = SeriesDefinition(period=period_year, rolling_definition=NoOpRoller())

        time_series_sets = list()

        for reading in ReadingEnum:
            dd = DataDefinition(measure=reading.value, day_aggregation_method=DayAggregation.MEAN)
            time_series_sets.append(TimeSeriesManager.TimeSeriesSet(data_definition=dd,
                                                                    series_definition=series_definition,
                                                                    processor=TimeSeriesProcessor.get_processor("No-op")))

        diary_time_period = TrainingDataManager().diary_time_period()
        # year summaries do need time period to be to year end
        diary_time_period.end = date(diary_time_period.end.year, 12, 31)
        tsl, errors = TimeSeriesManager().time_series_list(requested_time_period=diary_time_period, time_series_list=time_series_sets)

        if len(tsl) > 0:
            total_series = {'date': "Total"}
            for k in tsl[0].keys():
                if k != 'date':
                    entries = [d[k] for d in tsl]
                    year_count = sum([1 for e in entries if e > 0])
                    total_series[k] = 0 if year_count == 0 else sum(entries) / year_count
            tsl.append(total_series)

        for dd in tsl:
            dd['name'] = dd['date']

        response = TrainingDiaryResponse()
        [response.add_message(response.MSG_ERROR, e) for e in errors]
        response.add_data('time_series', tsl)

        return JsonResponse(data=response.as_dict())
Пример #11
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        tdm = TrainingDataManager()
        summary = tdm.bike_summary()
        bikes = list()
        totals = {'name': 'Total'}
        for bike, years in summary.items():
            for year, value in years.items():
                y = totals.get(year, 0)
                y += value
                totals[year] = y
            years['name'] = bike
            bikes.append(years)
        bikes.append(totals)
        response.add_data('bikes', bikes)
        years = list()
        for k, v in summary.items():
            years = [y for y in sorted(v.keys(), reverse=True)]
            break
        response.add_data('years', years)

        return JsonResponse(data=response.as_dict())
Пример #12
0
    def call_resource(self, request):
        type = request.POST['type']
        tdm = TrainingDataManager()

        choices = list()
        if type == 'activity':
            choices = tdm.activities()
        elif type == 'activityType':
            choices = tdm.activity_types()
        elif type == 'equipment':
            choices = tdm.equipment_types()
        elif type == 'tssMethod':
            choices = tdm.tss_methods()
        elif type == 'dayType':
            choices = tdm.day_types()
        elif type == 'measure':
            choices = [m.value for m in WorkoutFloatMeasureEnum] + [m.value for m in ReadingEnum]
        elif type == 'generated_measure':
            choices = [m for m in TimeSeriesProcessor.generated_measures()]
        elif type == 'period':
            choices = [p.value for p in PandasPeriod]
        elif type == 'aggregation':
            choices = [a.value for a in Aggregation]
        elif type == 'day_aggregation':
            choices = [a.value for a in DayAggregation]
        elif type == 'years':
            choices = range(dateutil.parser.parse(tdm.earliest_date()).year, dateutil.parser.parse(tdm.latest_date()).year + 1)
        elif type == 'processor':
            choices = TimeSeriesProcessor.TYPES
        elif type == 'interpolation':
            choices = [i.value for i in PandasInterpolation]

        if request.POST['include_all'] == 'true':
            choices.append('All')

        response = TrainingDiaryResponse()
        response.add_data('choices', sorted([{'text': c, 'id': c} for c in choices], key=lambda c: c["text"]))

        return JsonResponse(data=response.as_dict())
Пример #13
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        year = int(request.POST['year'])
        tp = TimePeriod(date(year,1,1), date(year, 12,31))

        swim_km = DataDefinition(activity='Swim', activity_type='All', equipment='All', measure='km', day_aggregation_method=DayAggregation.SUM)
        bike_km = DataDefinition(activity='Bike', activity_type='All', equipment='All', measure='km', day_aggregation_method=DayAggregation.SUM)
        run_km = DataDefinition(activity='Run', activity_type='All', equipment='All', measure='km', day_aggregation_method=DayAggregation.SUM)
        hours = DataDefinition(activity='All', activity_type='All', equipment='All', measure='hours', day_aggregation_method=DayAggregation.SUM)
        reps = DataDefinition(activity='Gym', activity_type='PressUp', equipment='All', measure='reps', day_aggregation_method=DayAggregation.SUM)
        series_defn = SeriesDefinition(period=Period(PandasPeriod(request.POST['period'])))

        summary = list()
        summary.append(TimeSeriesManager.TimeSeriesSet(data_definition=swim_km, series_definition=series_defn))
        summary.append(TimeSeriesManager.TimeSeriesSet(data_definition=bike_km, series_definition=series_defn))
        summary.append(TimeSeriesManager.TimeSeriesSet(data_definition=run_km, series_definition=series_defn))
        summary.append(TimeSeriesManager.TimeSeriesSet(data_definition=hours, series_definition=series_defn))
        summary.append(TimeSeriesManager.TimeSeriesSet(data_definition=reps, series_definition=series_defn))

        dd, errors = TimeSeriesManager().time_series_list(tp, summary)
        response.add_data('time_series', sorted(dd, key=lambda x: x['date']))
        [response.add_message(response.MSG_ERROR, error) for error in errors]

        return JsonResponse(data=response.as_dict())
Пример #14
0
    def call_resource(self, request):
        response = TrainingDiaryResponse()
        tms = TimeSeriesManager()
        graph = request.POST['graph']
        activity = request.POST['activity']
        year_str = self._normalise_year_str(request.POST['year'])
        yr_title = year_str if year_str != 'Total' else "All Time"

        if year_str == 'Total':
            tdm = TrainingDataManager()
            tp = tdm.diary_time_period()
        else:
            year = int(year_str)
            tp = TimePeriod(date(year,1,1), date(year,12,31))

        tss_list = list()
        if graph == 'tss':
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=DataDefinition(activity='All' if activity == "Total" else activity,
                                                                                           activity_type='All',
                                                                                           equipment='All',
                                                                                           measure='tss',
                                                                                           day_aggregation_method=DayAggregation.SUM),
                                                            processor=TSBProcessor(7, 7, 42, 42)))
        elif graph == 'duration':
            duration_defn = DataDefinition(activity='All' if activity == "Total" else activity,
                                           activity_type='All',
                                           equipment='All',
                                           measure='hours',
                                           day_aggregation_method=DayAggregation.SUM)
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=duration_defn))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=duration_defn, series_definition=SeriesDefinition(Period(), RollingDefinition(7, Aggregation.SUM))))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=duration_defn, series_definition=SeriesDefinition(Period(PandasPeriod.Y_DEC, to_date=True))))
        elif graph == 'km':
            km_defn = DataDefinition(activity='All' if activity == "Total" else activity,
                                     activity_type='All',
                                     equipment='All',
                                     measure='km',
                                     day_aggregation_method=DayAggregation.SUM)
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=km_defn))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=km_defn, series_definition=SeriesDefinition(Period(), RollingDefinition(7, Aggregation.SUM))))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=km_defn, series_definition=SeriesDefinition(Period(PandasPeriod.Y_DEC, to_date=True))))
        elif graph == 'reading':
            reading_defn = DataDefinition(activity='All',
                                          activity_type='All',
                                          equipment='All',
                                          measure=activity,
                                          day_aggregation_method=DayAggregation.MEAN)
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=reading_defn))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=reading_defn, series_definition=SeriesDefinition(Period(), RollingDefinition(7, Aggregation.MEAN))))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=reading_defn, series_definition=SeriesDefinition(Period(), RollingDefinition(31, Aggregation.MEAN))))
        elif graph == 'bike':
            bike_defn = DataDefinition(activity='Bike',
                                       activity_type='All',
                                       equipment='All' if activity == 'Total' else activity,
                                       measure='km',
                                       day_aggregation_method=DayAggregation.SUM)
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=bike_defn))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=bike_defn,
                                                            series_definition=SeriesDefinition(Period(), RollingDefinition(7, Aggregation.SUM))))
            tss_list.append(TimeSeriesManager.TimeSeriesSet(data_definition=bike_defn,
                                                            series_definition=SeriesDefinition(Period(PandasPeriod.Y_DEC, Aggregation.SUM, to_date=True))))

        if len(tss_list) > 0:
            values = tms.time_series_graph(requested_time_period=tp, time_series_list=tss_list)
        else:
            values = {'title': "No Data"}

        response.add_data('chart_title', f"{yr_title} {values['title']}")
        response.add_data('time_series', values)
        return JsonResponse(data=response.as_dict())
Пример #15
0
 def call_resource(self, request):
     logout(request)
     response = TrainingDiaryResponse()
     response.set_status(response.SUCCESS)
     response.add_data('logged_in', False)
     return JsonResponse(data=response.as_dict())
Пример #16
0
    def call_resource(self, request):
        dd, errors = self._process_data(request.POST['json'])

        dd_keys = set([d for d in dd.keys()])

        data_definition = DataDefinition(activity=dd['activity'],
                                         activity_type=dd['activity_type'],
                                         equipment=dd['equipment'],
                                         measure=dd['measure'],
                                         day_aggregation_method=DayAggregation(dd['day_aggregation']),
                                         day_type=dd['day_type'],
                                         day_of_week=dd['day_of_week'],
                                         month=dd['month'],
                                         interpolation=dd['interpolation'])

        dd_keys.remove('activity')
        dd_keys.remove('activity_type')
        dd_keys.remove('equipment')
        dd_keys.remove('measure')
        dd_keys.remove('day_aggregation')
        dd_keys.remove('day_type')
        dd_keys.remove('day_of_week')
        dd_keys.remove('month')
        dd_keys.remove('interpolation')

        period = Period(pandas_period=PandasPeriod(dd['period']), aggregation=Aggregation(dd['period_aggregation']),
                        to_date=dd['to_date'] == 'yes',
                        incl_zeroes=dd['period_include_zeroes'] == 'yes')
        dd_keys.remove('period')
        dd_keys.remove('period_aggregation')
        dd_keys.remove('to_date')
        dd_keys.remove('period_include_zeroes')

        if dd['rolling'] == 'yes':
            rolling_definition = RollingDefinition(periods=int(dd['number_of_rolling_periods']), aggregation=Aggregation(dd['rolling_aggregation']),
                                                   incl_zeros=dd['rolling_include_zeroes'] == 'yes')
        else:
            rolling_definition = NoOpRoller()
        dd_keys.remove('number_of_rolling_periods')
        dd_keys.remove('rolling_aggregation')
        dd_keys.remove('rolling_include_zeroes')
        dd_keys.remove('rolling')

        series_definition = SeriesDefinition(period=period, rolling_definition=rolling_definition)

        processor = self.get_processor(dd)
        dd_keys.remove('processor_type')

        response = TrainingDiaryResponse()
        [response.add_message(response.MSG_ERROR, e) for e in errors]

        diary_time_period = TrainingDataManager().diary_time_period()
        data_tp = TimePeriod(diary_time_period.start if dd['series_start'] is None else dd['series_start'],
                             diary_time_period.end if dd['series_end'] is None else dd['series_end'])
        dd_keys.remove('series_start')
        dd_keys.remove('series_end')

        x_axis_number = 1
        if 'x_axis_number' in dd:
            x_axis_number = dd['x_axis_number']
            dd_keys.remove('x_axis_number')
        tss = TimeSeriesManager.TimeSeriesSet(data_definition, series_definition=series_definition, processor=processor, x_axis_number=x_axis_number)

        ts = TimeSeriesManager().time_series_graph(data_tp, [tss])
        response.add_data('time_series', ts)

        if len(dd_keys) > 0:
            response.add_message(response.MSG_WARNING, f"The following data was not used: {' ,'.join(dd_keys)}")

        return JsonResponse(data=response.as_dict())