Skip to content

API Reference

Activity summaries sub-module for aggregated metrics.

This module provides summary aggregations of activity data across different time periods (weekly, monthly, yearly, lifetime) with breakdowns by day, week, month, year, and activity type.

Exports
  • CRUD: get_weekly_summary, get_monthly_summary, get_yearly_summary, get_lifetime_summary
  • Schemas: SummaryMetrics, DaySummary, WeekSummary, MonthSummary, YearlyPeriodSummary, TypeBreakdownItem, WeeklySummaryResponse, MonthlySummaryResponse, YearlySummaryResponse, LifetimeSummaryResponse
  • Dependencies: validate_view_type

DaySummary

Bases: SummaryMetrics

Daily activity summary within a week.

Attributes:

Name Type Description
day_of_week StrictInt

Day of week (0=Mon, 6=Sun).

Source code in backend/app/activities/activity_summaries/schema.py
54
55
56
57
58
59
60
61
62
63
64
65
class DaySummary(SummaryMetrics):
    """
    Daily activity summary within a week.

    Attributes:
        day_of_week: Day of week (0=Mon, 6=Sun).
    """

    day_of_week: StrictInt = Field(
        ...,
        description=("Day of week (0=Monday, 6=Sunday)"),
    )

LifetimeSummaryResponse

Bases: SummaryMetrics

Lifetime summary with yearly breakdowns.

Attributes:

Name Type Description
breakdown list[YearlyPeriodSummary]

List of yearly summaries.

type_breakdown list[TypeBreakdownItem] | None

Optional breakdown by type.

Source code in backend/app/activities/activity_summaries/schema.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
class LifetimeSummaryResponse(SummaryMetrics):
    """
    Lifetime summary with yearly breakdowns.

    Attributes:
        breakdown: List of yearly summaries.
        type_breakdown: Optional breakdown by type.
    """

    breakdown: list[YearlyPeriodSummary] = Field(
        ...,
        description="List of yearly summaries",
    )
    type_breakdown: list[TypeBreakdownItem] | None = Field(
        default=None,
        description=("Optional breakdown by activity type"),
    )

MonthSummary

Bases: SummaryMetrics

Monthly activity summary within a year.

Attributes:

Name Type Description
month_number StrictInt

Month (1=Jan, 12=Dec).

Source code in backend/app/activities/activity_summaries/schema.py
82
83
84
85
86
87
88
89
90
91
92
93
class MonthSummary(SummaryMetrics):
    """
    Monthly activity summary within a year.

    Attributes:
        month_number: Month (1=Jan, 12=Dec).
    """

    month_number: StrictInt = Field(
        ...,
        description="Month (1=January, 12=December)",
    )

MonthlySummaryResponse

Bases: SummaryMetrics

Monthly summary with weekly breakdowns.

Attributes:

Name Type Description
breakdown list[WeekSummary]

List of weekly summaries.

type_breakdown list[TypeBreakdownItem] | None

Optional breakdown by type.

Source code in backend/app/activities/activity_summaries/schema.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
class MonthlySummaryResponse(SummaryMetrics):
    """
    Monthly summary with weekly breakdowns.

    Attributes:
        breakdown: List of weekly summaries.
        type_breakdown: Optional breakdown by type.
    """

    breakdown: list[WeekSummary] = Field(
        ...,
        description="List of weekly summaries",
    )
    type_breakdown: list[TypeBreakdownItem] | None = Field(
        default=None,
        description=("Optional breakdown by activity type"),
    )

SummaryMetrics

Bases: BaseModel

Base metrics shared by all summary responses.

Attributes:

Name Type Description
total_distance StrictFloat

Total distance in meters.

total_duration StrictFloat

Total duration in seconds.

total_elevation_gain StrictFloat

Total elevation gain in meters.

activity_count StrictInt

Number of activities.

total_calories StrictFloat

Total calories burned.

Source code in backend/app/activities/activity_summaries/schema.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class SummaryMetrics(BaseModel):
    """
    Base metrics shared by all summary responses.

    Attributes:
        total_distance: Total distance in meters.
        total_duration: Total duration in seconds.
        total_elevation_gain: Total elevation gain
            in meters.
        activity_count: Number of activities.
        total_calories: Total calories burned.
    """

    total_distance: StrictFloat = Field(
        default=0.0,
        description="Total distance in meters",
    )
    total_duration: StrictFloat = Field(
        default=0.0,
        description="Total duration in seconds",
    )
    total_elevation_gain: StrictFloat = Field(
        default=0.0,
        description="Total elevation gain in meters",
    )
    activity_count: StrictInt = Field(
        default=0,
        description="Number of activities",
    )
    total_calories: StrictFloat = Field(
        default=0.0,
        description="Total calories burned",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
    )

TypeBreakdownItem

Bases: SummaryMetrics

Summary metrics broken down by activity type.

Attributes:

Name Type Description
activity_type_id StrictInt

Numeric activity type ID.

activity_type StrictStr

Human-readable type name.

Source code in backend/app/activities/activity_summaries/schema.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class TypeBreakdownItem(SummaryMetrics):
    """
    Summary metrics broken down by activity type.

    Attributes:
        activity_type_id: Numeric activity type ID.
        activity_type: Human-readable type name.
    """

    activity_type_id: StrictInt = Field(
        ...,
        description="Numeric activity type ID",
    )
    activity_type: StrictStr = Field(
        ...,
        description=("Human-readable activity type name"),
    )

WeekSummary

Bases: SummaryMetrics

Weekly activity summary within a month.

Attributes:

Name Type Description
week_number StrictInt

ISO week number.

Source code in backend/app/activities/activity_summaries/schema.py
68
69
70
71
72
73
74
75
76
77
78
79
class WeekSummary(SummaryMetrics):
    """
    Weekly activity summary within a month.

    Attributes:
        week_number: ISO week number.
    """

    week_number: StrictInt = Field(
        ...,
        description="ISO week number",
    )

WeeklySummaryResponse

Bases: SummaryMetrics

Weekly summary with daily breakdowns.

Attributes:

Name Type Description
breakdown list[DaySummary]

List of daily summaries.

type_breakdown list[TypeBreakdownItem] | None

Optional breakdown by type.

Source code in backend/app/activities/activity_summaries/schema.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class WeeklySummaryResponse(SummaryMetrics):
    """
    Weekly summary with daily breakdowns.

    Attributes:
        breakdown: List of daily summaries.
        type_breakdown: Optional breakdown by type.
    """

    breakdown: list[DaySummary] = Field(
        ...,
        description="List of daily summaries",
    )
    type_breakdown: list[TypeBreakdownItem] | None = Field(
        default=None,
        description=("Optional breakdown by activity type"),
    )

YearlyPeriodSummary

Bases: SummaryMetrics

Yearly activity summary within lifetime view.

Attributes:

Name Type Description
year_number StrictInt

Calendar year.

Source code in backend/app/activities/activity_summaries/schema.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class YearlyPeriodSummary(SummaryMetrics):
    """
    Yearly activity summary within lifetime view.

    Attributes:
        year_number: Calendar year.
    """

    year_number: StrictInt = Field(
        ...,
        description="Calendar year",
    )

YearlySummaryResponse

Bases: SummaryMetrics

Yearly summary with monthly breakdowns.

Attributes:

Name Type Description
breakdown list[MonthSummary]

List of monthly summaries.

type_breakdown list[TypeBreakdownItem] | None

Optional breakdown by type.

Source code in backend/app/activities/activity_summaries/schema.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class YearlySummaryResponse(SummaryMetrics):
    """
    Yearly summary with monthly breakdowns.

    Attributes:
        breakdown: List of monthly summaries.
        type_breakdown: Optional breakdown by type.
    """

    breakdown: list[MonthSummary] = Field(
        ...,
        description="List of monthly summaries",
    )
    type_breakdown: list[TypeBreakdownItem] | None = Field(
        default=None,
        description=("Optional breakdown by activity type"),
    )

get_lifetime_summary

get_lifetime_summary(db, user_id, activity_type=None)

Get lifetime activity summary for a user.

Parameters:

Name Type Description Default
db Session

Database session.

required
user_id int

Target user ID.

required
activity_type str | None

Optional activity type filter name.

None

Returns:

Type Description
LifetimeSummaryResponse

Lifetime summary with yearly breakdowns.

Source code in backend/app/activities/activity_summaries/crud.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
def get_lifetime_summary(
    db: Session,
    user_id: int,
    activity_type: str | None = None,
) -> LifetimeSummaryResponse:
    """
    Get lifetime activity summary for a user.

    Args:
        db: Database session.
        user_id: Target user ID.
        activity_type: Optional activity type
            filter name.

    Returns:
        Lifetime summary with yearly breakdowns.
    """
    # Overall metrics
    metrics_stmt = select(
        func.coalesce(func.sum(Activity.distance), 0.0).label("total_distance"),
        func.coalesce(
            func.sum(Activity.total_timer_time),
            0.0,
        ).label("total_duration"),
        func.coalesce(
            func.sum(Activity.elevation_gain),
            0.0,
        ).label("total_elevation_gain"),
        func.coalesce(func.sum(Activity.calories), 0.0).label("total_calories"),
        func.count(Activity.id).label("activity_count"),
    ).where(Activity.user_id == user_id)

    metrics_stmt, _ = _apply_activity_type_filter(metrics_stmt, activity_type)

    totals = db.execute(metrics_stmt).one_or_none()

    # Yearly breakdown
    year_expr = extract("year", Activity.start_time)
    yearly_stmt = select(
        year_expr.label("year_number"),
        func.coalesce(func.sum(Activity.distance), 0.0).label("total_distance"),
        func.coalesce(
            func.sum(Activity.total_timer_time),
            0.0,
        ).label("total_duration"),
        func.coalesce(
            func.sum(Activity.elevation_gain),
            0.0,
        ).label("total_elevation_gain"),
        func.coalesce(func.sum(Activity.calories), 0.0).label("total_calories"),
        func.count(Activity.id).label("activity_count"),
    ).where(Activity.user_id == user_id)

    yearly_stmt, _ = _apply_activity_type_filter(yearly_stmt, activity_type)

    yearly_stmt = yearly_stmt.group_by(year_expr).order_by(year_expr.desc())

    yearly_rows = db.execute(yearly_stmt).all()
    breakdown: list[YearlyPeriodSummary] = []
    for row in yearly_rows:
        breakdown.append(
            YearlyPeriodSummary(
                year_number=int(row.year_number),
                total_distance=float(row.total_distance),
                total_duration=float(row.total_duration),
                total_elevation_gain=float(row.total_elevation_gain),
                total_calories=float(row.total_calories),
                activity_count=int(row.activity_count),
            )
        )

    if totals:
        return LifetimeSummaryResponse(
            total_distance=float(totals.total_distance),
            total_duration=float(totals.total_duration),
            total_elevation_gain=float(totals.total_elevation_gain),
            total_calories=float(totals.total_calories),
            activity_count=int(totals.activity_count),
            breakdown=breakdown,
            type_breakdown=(
                _get_type_breakdown(
                    db,
                    user_id,
                    date.min,
                    date.max,
                    activity_type,
                )
                or []
            ),
        )

    return LifetimeSummaryResponse(
        total_distance=0.0,
        total_duration=0.0,
        total_elevation_gain=0.0,
        total_calories=0.0,
        activity_count=0,
        breakdown=[],
        type_breakdown=[],
    )

get_monthly_summary

get_monthly_summary(db, user_id, target_date, activity_type=None)

Get monthly activity summary for a user.

Parameters:

Name Type Description Default
db Session

Database session.

required
user_id int

Target user ID.

required
target_date date

Any date within the target month.

required
activity_type str | None

Optional activity type filter name.

None

Returns:

Type Description
MonthlySummaryResponse

Monthly summary with weekly breakdowns.

Source code in backend/app/activities/activity_summaries/crud.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def get_monthly_summary(
    db: Session,
    user_id: int,
    target_date: date,
    activity_type: str | None = None,
) -> MonthlySummaryResponse:
    """
    Get monthly activity summary for a user.

    Args:
        db: Database session.
        user_id: Target user ID.
        target_date: Any date within the target
            month.
        activity_type: Optional activity type
            filter name.

    Returns:
        Monthly summary with weekly breakdowns.
    """
    start_of_month = target_date.replace(day=1)
    end_of_month = (start_of_month + timedelta(days=32)).replace(day=1)

    week_expr = extract("week", Activity.start_time)

    stmt = select(
        week_expr.label("week_number"),
        func.coalesce(func.sum(Activity.distance), 0).label("total_distance"),
        func.coalesce(
            func.sum(Activity.total_timer_time),
            0.0,
        ).label("total_duration"),
        func.coalesce(func.sum(Activity.elevation_gain), 0).label("total_elevation_gain"),
        func.coalesce(func.sum(Activity.calories), 0).label("total_calories"),
        func.count(Activity.id).label("activity_count"),
    ).where(
        Activity.user_id == user_id,
        Activity.start_time >= start_of_month,
        Activity.start_time < end_of_month,
    )

    stmt, _ = _apply_activity_type_filter(stmt, activity_type)

    stmt = stmt.group_by(week_expr).order_by(week_expr)

    weekly_results = db.execute(stmt).all()
    breakdown: list[WeekSummary] = []
    overall = SummaryMetrics()

    for week_data in weekly_results:
        ws = WeekSummary(
            week_number=int(week_data.week_number),
            total_distance=float(week_data.total_distance),
            total_duration=float(week_data.total_duration),
            total_elevation_gain=float(week_data.total_elevation_gain),
            total_calories=float(week_data.total_calories),
            activity_count=int(week_data.activity_count),
        )
        breakdown.append(ws)
        overall.total_distance += ws.total_distance
        overall.total_duration += ws.total_duration
        overall.total_elevation_gain += ws.total_elevation_gain
        overall.total_calories += ws.total_calories
        overall.activity_count += ws.activity_count

    return MonthlySummaryResponse(
        total_distance=overall.total_distance,
        total_duration=overall.total_duration,
        total_elevation_gain=(overall.total_elevation_gain),
        total_calories=overall.total_calories,
        activity_count=overall.activity_count,
        breakdown=breakdown,
        type_breakdown=_get_type_breakdown(
            db,
            user_id,
            start_of_month,
            end_of_month,
            activity_type,
        ),
    )

get_weekly_summary

get_weekly_summary(db, user_id, target_date, activity_type=None)

Get weekly activity summary for a user.

Parameters:

Name Type Description Default
db Session

Database session.

required
user_id int

Target user ID.

required
target_date date

Any date within the target week.

required
activity_type str | None

Optional activity type filter name.

None

Returns:

Type Description
WeeklySummaryResponse

Weekly summary with daily breakdowns.

Source code in backend/app/activities/activity_summaries/crud.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def get_weekly_summary(
    db: Session,
    user_id: int,
    target_date: date,
    activity_type: str | None = None,
) -> WeeklySummaryResponse:
    """
    Get weekly activity summary for a user.

    Args:
        db: Database session.
        user_id: Target user ID.
        target_date: Any date within the target
            week.
        activity_type: Optional activity type
            filter name.

    Returns:
        Weekly summary with daily breakdowns.
    """
    start_of_week = target_date - timedelta(days=target_date.weekday())
    end_of_week = start_of_week + timedelta(days=7)

    # Database-agnostic ISO day of week
    # PostgreSQL: extract('isodow') -> 1-7 Mon-Sun
    # MySQL: DAYOFWEEK (1=Sun, 7=Sat) -> ISO
    engine_name = db.get_bind().dialect.name
    if engine_name == "postgresql":
        iso_dow: ColumnElement[Any] = extract("isodow", Activity.start_time)
    else:
        iso_dow = case(
            (
                func.dayofweek(Activity.start_time) == 1,
                7,
            ),
            else_=(func.dayofweek(Activity.start_time) - 1),
        )

    stmt = select(
        iso_dow.label("day_of_week"),
        func.coalesce(func.sum(Activity.distance), 0).label("total_distance"),
        func.coalesce(
            func.sum(Activity.total_timer_time),
            0.0,
        ).label("total_duration"),
        func.coalesce(func.sum(Activity.elevation_gain), 0).label("total_elevation_gain"),
        func.coalesce(func.sum(Activity.calories), 0).label("total_calories"),
        func.count(Activity.id).label("activity_count"),
    ).where(
        Activity.user_id == user_id,
        Activity.start_time >= start_of_week,
        Activity.start_time < end_of_week,
    )

    stmt, _ = _apply_activity_type_filter(stmt, activity_type)

    stmt = stmt.group_by(iso_dow).order_by(iso_dow)

    daily_results = db.execute(stmt).all()
    breakdown: list[DaySummary] = []
    overall = SummaryMetrics()

    day_map = {d.day_of_week: d for d in daily_results}

    for i in range(1, 8):
        day_data = day_map.get(i)
        if day_data:
            ds = DaySummary(
                day_of_week=i - 1,
                total_distance=float(day_data.total_distance),
                total_duration=float(day_data.total_duration),
                total_elevation_gain=float(day_data.total_elevation_gain),
                total_calories=float(day_data.total_calories),
                activity_count=int(day_data.activity_count),
            )
            breakdown.append(ds)
            overall.total_distance += ds.total_distance
            overall.total_duration += ds.total_duration
            overall.total_elevation_gain += ds.total_elevation_gain
            overall.total_calories += ds.total_calories
            overall.activity_count += ds.activity_count
        else:
            breakdown.append(DaySummary(day_of_week=i - 1))

    return WeeklySummaryResponse(
        total_distance=overall.total_distance,
        total_duration=overall.total_duration,
        total_elevation_gain=(overall.total_elevation_gain),
        total_calories=overall.total_calories,
        activity_count=overall.activity_count,
        breakdown=breakdown,
        type_breakdown=_get_type_breakdown(
            db,
            user_id,
            start_of_week,
            end_of_week,
            activity_type,
        ),
    )

get_yearly_summary

get_yearly_summary(db, user_id, year, activity_type=None)

Get yearly activity summary for a user.

Parameters:

Name Type Description Default
db Session

Database session.

required
user_id int

Target user ID.

required
year int

Target calendar year.

required
activity_type str | None

Optional activity type filter name.

None

Returns:

Type Description
YearlySummaryResponse

Yearly summary with monthly breakdowns.

Source code in backend/app/activities/activity_summaries/crud.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def get_yearly_summary(
    db: Session,
    user_id: int,
    year: int,
    activity_type: str | None = None,
) -> YearlySummaryResponse:
    """
    Get yearly activity summary for a user.

    Args:
        db: Database session.
        user_id: Target user ID.
        year: Target calendar year.
        activity_type: Optional activity type
            filter name.

    Returns:
        Yearly summary with monthly breakdowns.
    """
    start_of_year = date(year, 1, 1)
    end_of_year = date(year + 1, 1, 1)

    month_expr = extract("month", Activity.start_time)

    stmt = select(
        month_expr.label("month_number"),
        func.coalesce(func.sum(Activity.distance), 0).label("total_distance"),
        func.coalesce(
            func.sum(Activity.total_timer_time),
            0.0,
        ).label("total_duration"),
        func.coalesce(func.sum(Activity.elevation_gain), 0).label("total_elevation_gain"),
        func.coalesce(func.sum(Activity.calories), 0).label("total_calories"),
        func.count(Activity.id).label("activity_count"),
    ).where(
        Activity.user_id == user_id,
        Activity.start_time >= start_of_year,
        Activity.start_time < end_of_year,
    )

    stmt, _ = _apply_activity_type_filter(stmt, activity_type)

    stmt = stmt.group_by(month_expr).order_by(month_expr)

    monthly_results = db.execute(stmt).all()
    breakdown: list[MonthSummary] = []
    overall = SummaryMetrics()

    month_map = {m.month_number: m for m in monthly_results}

    for i in range(1, 13):
        month_data = month_map.get(i)
        if month_data:
            ms = MonthSummary(
                month_number=i,
                total_distance=float(month_data.total_distance),
                total_duration=float(month_data.total_duration),
                total_elevation_gain=float(month_data.total_elevation_gain),
                total_calories=float(month_data.total_calories),
                activity_count=int(month_data.activity_count),
            )
            breakdown.append(ms)
            overall.total_distance += ms.total_distance
            overall.total_duration += ms.total_duration
            overall.total_elevation_gain += ms.total_elevation_gain
            overall.total_calories += ms.total_calories
            overall.activity_count += ms.activity_count
        else:
            breakdown.append(MonthSummary(month_number=i))

    return YearlySummaryResponse(
        total_distance=overall.total_distance,
        total_duration=overall.total_duration,
        total_elevation_gain=(overall.total_elevation_gain),
        total_calories=overall.total_calories,
        activity_count=overall.activity_count,
        breakdown=breakdown,
        type_breakdown=_get_type_breakdown(
            db,
            user_id,
            start_of_year,
            end_of_year,
            activity_type,
        ),
    )

validate_view_type

validate_view_type(view_type)

Validate the view type path parameter.

Parameters:

Name Type Description Default
view_type str

The view type to validate.

required

Raises:

Type Description
HTTPException

If the view type is not a valid option.

Source code in backend/app/activities/activity_summaries/dependencies.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def validate_view_type(view_type: str) -> None:
    """
    Validate the view type path parameter.

    Args:
        view_type: The view type to validate.

    Raises:
        HTTPException: If the view type is not
            a valid option.
    """
    if view_type not in _VALID_VIEW_TYPES:
        raise HTTPException(
            status_code=(status.HTTP_422_UNPROCESSABLE_CONTENT),
            detail="Invalid view type field",
        )