Coverage for app / services / stats / periods.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1""" 

2Periods — *over what window* a breakdown is computed. 

3 

4A small registry rather than a pair of free-form timestamps, because a widget 

5stores its period and has to mean the same thing next month. ``this_month`` 

6stored as an explicit ``since`` would quietly become "since the first of 

7whichever month the tile was created in" — the classic dashboard bug where a 

8board built in January is still reporting January in March. 

9 

10Custom ranges remain available on the API for callers that want one; the 

11widget picker offers these. 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Callable 

17from dataclasses import dataclass 

18from datetime import datetime, timedelta 

19from typing import Any 

20 

21from app.util.time import aware_utcnow 

22 

23 

24@dataclass(frozen=True) 

25class Period: 

26 """One selectable window.""" 

27 

28 key: str 

29 label: str 

30 #: Start of the window relative to now, or None for "everything". 

31 start: Callable[[datetime], datetime | None] 

32 #: End of the window relative to now, for one already over (last 

33 #: month); None runs up to now. 

34 end: Callable[[datetime], datetime | None] | None = None 

35 

36 def since(self, now: datetime | None = None) -> datetime | None: 

37 return self.start(now or aware_utcnow()) 

38 

39 def until(self, now: datetime | None = None) -> datetime | None: 

40 """Where the window ends: None for one running up to now.""" 

41 return self.end(now or aware_utcnow()) if self.end is not None else None 

42 

43 def spec(self) -> dict[str, Any]: 

44 return {"key": self.key, "label": self.label} 

45 

46 

47def _month_start(now: datetime) -> datetime: 

48 return now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) 

49 

50 

51def _last_month_start(now: datetime) -> datetime: 

52 return _month_start(_month_start(now) - timedelta(days=1)) 

53 

54 

55PERIODS: dict[str, Period] = { 

56 period.key: period 

57 for period in ( 

58 Period("last_24_hours", "Last 24 hours", lambda now: now - timedelta(days=1)), 

59 Period("last_7_days", "Last 7 days", lambda now: now - timedelta(days=7)), 

60 Period("last_30_days", "Last 30 days", lambda now: now - timedelta(days=30)), 

61 Period("this_month", "This month", _month_start), 

62 # A whole month that is over, so a figure can be set beside its 

63 # predecessor (Governance → Spend). 

64 Period("last_month", "Last month", _last_month_start, _month_start), 

65 Period("all_time", "All time", lambda now: None), 

66 ) 

67} 

68 

69#: What a request that names no period, or an unrecognised one, gets. A window 

70#: rather than everything: a tile whose period was mistyped should show a 

71#: figure the user can sanity-check against the rest of the board, not the 

72#: account's lifetime total under a label claiming otherwise. 

73DEFAULT_PERIOD = "this_month" 

74 

75 

76def get_period(key: str | None) -> Period: 

77 """The period registered under ``key``, falling back to the default.""" 

78 return PERIODS.get(str(key or ""), PERIODS[DEFAULT_PERIOD]) 

79 

80 

81def catalogue() -> list[dict[str, Any]]: 

82 """Registered periods, in picker order.""" 

83 return [period.spec() for period in PERIODS.values()]