Files
homeschool-dashboard/backend/app/utils/timer.py
T
derekcandClaude Sonnet 4.6 1420d57e7e Add Reset button and move End Day to right side of actions bar
Reset clears the current block's elapsed time to zero and immediately
starts the timer. A shared compute_block_elapsed() utility (utils/timer.py)
handles the elapsed calculation in both the sessions and dashboard routers,
and correctly treats "reset" events as zero-elapsed restart markers so
page reloads after a reset show accurate times.

Layout: Start/Pause/Resume/Reset are grouped on the left; End Day sits
on the right via justify-content: space-between.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-03-03 00:17:02 -08:00

45 lines
1.5 KiB
Python

"""Shared timer-elapsed computation used by sessions and dashboard routers."""
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models.session import TimerEvent
async def compute_block_elapsed(
db: AsyncSession, session_id: int, block_id: int
) -> tuple[int, bool]:
"""Return (elapsed_seconds, is_paused) for a block.
'reset' events are treated as zero-elapsed restart markers: any elapsed
time accumulated before a reset is discarded.
"""
tick_result = await db.execute(
select(TimerEvent)
.where(
TimerEvent.session_id == session_id,
TimerEvent.block_id == block_id,
TimerEvent.event_type.in_(["start", "resume", "pause", "reset"]),
)
.order_by(TimerEvent.occurred_at)
)
tick_events = tick_result.scalars().all()
elapsed = 0.0
last_start = None
for e in tick_events:
if e.event_type == "reset":
elapsed = 0.0
last_start = e.occurred_at
elif e.event_type in ("start", "resume"):
last_start = e.occurred_at
elif e.event_type == "pause" and last_start:
elapsed += (e.occurred_at - last_start).total_seconds()
last_start = None
if last_start:
elapsed += (datetime.utcnow() - last_start).total_seconds()
is_paused = bool(tick_events) and tick_events[-1].event_type == "pause"
return int(elapsed), is_paused