-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpause_utils.py
More file actions
158 lines (129 loc) · 4.74 KB
/
Copy pathpause_utils.py
File metadata and controls
158 lines (129 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
"""
Normalize pause records from manual timer sessions and the process watcher.
Manual timer pauses (integrated):
paused_at, resumed_at, pause_duration, incomplete
Process watcher pauses:
start, end, reason, resume_reason
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
PauseInterval = Tuple[datetime, datetime]
def _parse_iso(value: str) -> Optional[datetime]:
if not value:
return None
try:
return datetime.fromisoformat(value)
except (ValueError, TypeError):
return None
def _parse_hms_duration(value: str) -> Optional[timedelta]:
if not value:
return None
try:
parts = value.strip().split(":")
if len(parts) != 3:
return None
hours, minutes, seconds = (int(p) for p in parts)
return timedelta(hours=hours, minutes=minutes, seconds=seconds)
except (ValueError, TypeError):
return None
def pause_interval(
pause: Dict,
*,
session_end: Optional[datetime] = None,
) -> Optional[PauseInterval]:
"""Return (start, end) for a single pause dict, or None if not drawable.
Incomplete pauses (session ended while still paused) have no resume time.
When ``session_end`` is provided, use it as the pause end so charts can
show the break through session stop. Watcher sessions often set ``end`` on
finalize already; manual timer pauses typically only have ``paused_at``.
"""
if not isinstance(pause, dict):
return None
start = _parse_iso(pause.get("paused_at") or pause.get("start"))
if start is None:
return None
end = _parse_iso(pause.get("resumed_at") or pause.get("end"))
if end is None and pause.get("pause_duration"):
duration = _parse_hms_duration(pause["pause_duration"])
if duration is not None:
end = start + duration
if end is None and pause.get("incomplete") and session_end is not None:
end = session_end
if end is None or end <= start:
return None
return start, end
def pause_duration_timedelta(
pause: Dict,
*,
session_end: Optional[datetime] = None,
) -> timedelta:
interval = pause_interval(pause, session_end=session_end)
if interval is None:
return timedelta()
return interval[1] - interval[0]
def session_pause_periods(session: Dict) -> List[Dict]:
"""Pause intervals as {start, end, duration} with duration in minutes (heatmap)."""
session_end = _parse_iso(session.get("end"))
periods: List[Dict] = []
for pause in session.get("pauses") or []:
interval = pause_interval(pause, session_end=session_end)
if interval is None:
continue
start, end = interval
periods.append({
"start": start,
"end": end,
"duration": (end - start).total_seconds() / 60,
"incomplete": bool(pause.get("incomplete")),
})
return periods
def total_session_pause_timedelta(session: Dict) -> timedelta:
session_end = _parse_iso(session.get("end"))
total = timedelta()
for pause in session.get("pauses") or []:
total += pause_duration_timedelta(pause, session_end=session_end)
return total
def normalize_pause_to_integrated(pause: Dict) -> Dict:
"""Convert a watcher-style pause to manual integrated fields (for migration)."""
if not isinstance(pause, dict):
return pause
if "paused_at" in pause and "resumed_at" in pause:
return pause
interval = pause_interval(pause)
if interval is None:
return pause
start, end = interval
delta = end - start
hours, remainder = divmod(int(delta.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
out = {
"paused_at": start.isoformat(),
"resumed_at": end.isoformat(),
"pause_duration": f"{hours:02d}:{minutes:02d}:{seconds:02d}",
}
if pause.get("reason"):
out["reason"] = pause["reason"]
if pause.get("resume_reason"):
out["resume_reason"] = pause["resume_reason"]
if pause.get("incomplete"):
out["incomplete"] = True
return out
def normalize_session_pauses(session: Dict) -> Dict:
"""Return session with pauses converted to integrated manual shape when needed."""
pauses = session.get("pauses")
if not pauses:
return session
normalized: List[Dict] = []
changed = False
for pause in pauses:
if isinstance(pause, dict) and "start" in pause and "paused_at" not in pause:
normalized.append(normalize_pause_to_integrated(pause))
changed = True
else:
normalized.append(pause)
if not changed:
return session
out = dict(session)
out["pauses"] = normalized
return out