Add Done button, tablet controls, super admin management, midnight strike reset, and activity log improvements
- Done button snaps block to full duration, marks complete, logs "Marked Done by User"; Reset after Done fully un-completes the block - Session action buttons stretch full-width and double height for tablet tapping - Super admin: reset password, disable/enable accounts, delete user (with cascade), last active date per user's timezone - Disabled account login returns specific error message instead of generic invalid credentials - Users can change own password from Admin → Settings - Strikes reset automatically at midnight in user's configured timezone (lazy reset on page load) - Break timer state fully restored when navigating away and back to dashboard - Timer no longer auto-starts on navigation if it wasn't running before - Implicit pause guard: no duplicate pause events when switching already-paused blocks or starting a break - Block selection events removed from activity log; all event types have human-readable labels - House emoji favicon via inline SVG data URI - README updated to reflect all changes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import select, delete
|
||||
|
||||
from app.auth.jwt import create_admin_token, create_access_token
|
||||
from app.auth.jwt import create_admin_token, create_access_token, hash_password
|
||||
from app.config import get_settings
|
||||
from app.dependencies import get_db, get_admin_user
|
||||
from app.models.user import User
|
||||
@@ -35,11 +35,62 @@ async def list_users(
|
||||
"full_name": u.full_name,
|
||||
"is_active": u.is_active,
|
||||
"created_at": u.created_at,
|
||||
"last_active_at": u.last_active_at,
|
||||
"timezone": u.timezone,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
|
||||
|
||||
@router.post("/toggle-active/{user_id}")
|
||||
async def toggle_user_active(
|
||||
user_id: int,
|
||||
_: dict = Depends(get_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
user.is_active = not user.is_active
|
||||
await db.commit()
|
||||
return {"id": user.id, "is_active": user.is_active}
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
_: dict = Depends(get_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
await db.execute(delete(User).where(User.id == user_id))
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/reset-password/{user_id}")
|
||||
async def reset_user_password(
|
||||
user_id: int,
|
||||
body: dict,
|
||||
_: dict = Depends(get_admin_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
new_password = body.get("new_password", "").strip()
|
||||
if not new_password:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="new_password is required")
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
user.hashed_password = hash_password(new_password)
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/impersonate/{user_id}")
|
||||
async def impersonate_user(
|
||||
user_id: int,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, Request, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
@@ -9,7 +10,7 @@ from app.auth.jwt import (
|
||||
hash_password,
|
||||
verify_password,
|
||||
)
|
||||
from app.dependencies import get_db
|
||||
from app.dependencies import get_db, get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.subject import Subject
|
||||
from app.schemas.auth import LoginRequest, RegisterRequest, TokenResponse
|
||||
@@ -58,10 +59,15 @@ async def register(body: RegisterRequest, response: Response, db: AsyncSession =
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(body: LoginRequest, response: Response, db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(select(User).where(User.email == body.email, User.is_active == True))
|
||||
result = await db.execute(select(User).where(User.email == body.email))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user or not verify_password(body.password, user.hashed_password):
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="This account has been disabled. Please contact your administrator.")
|
||||
|
||||
user.last_active_at = datetime.utcnow()
|
||||
await db.commit()
|
||||
|
||||
access = create_access_token({"sub": str(user.id)})
|
||||
refresh = create_refresh_token({"sub": str(user.id)})
|
||||
@@ -89,6 +95,9 @@ async def refresh_token(request: Request, response: Response, db: AsyncSession =
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
|
||||
user.last_active_at = datetime.utcnow()
|
||||
await db.commit()
|
||||
|
||||
access = create_access_token({"sub": str(user.id)})
|
||||
new_refresh = create_refresh_token({"sub": str(user.id)})
|
||||
response.set_cookie(REFRESH_COOKIE, new_refresh, **COOKIE_OPTS)
|
||||
@@ -99,3 +108,20 @@ async def refresh_token(request: Request, response: Response, db: AsyncSession =
|
||||
async def logout(response: Response):
|
||||
response.delete_cookie(REFRESH_COOKIE)
|
||||
return {"detail": "Logged out"}
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
async def change_password(
|
||||
body: dict,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
current = body.get("current_password", "")
|
||||
new = body.get("new_password", "").strip()
|
||||
if not current or not new:
|
||||
raise HTTPException(status_code=400, detail="current_password and new_password are required")
|
||||
if not verify_password(current, current_user.hashed_password):
|
||||
raise HTTPException(status_code=400, detail="Current password is incorrect")
|
||||
current_user.hashed_password = hash_password(new)
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -13,6 +16,15 @@ from app.websocket.manager import manager
|
||||
router = APIRouter(prefix="/api/children", tags=["children"])
|
||||
|
||||
|
||||
def _today_in_tz(tz_name: str):
|
||||
"""Return today's date in the given IANA timezone, falling back to UTC."""
|
||||
try:
|
||||
tz = ZoneInfo(tz_name)
|
||||
except (ZoneInfoNotFoundError, Exception):
|
||||
tz = timezone.utc
|
||||
return datetime.now(tz).date()
|
||||
|
||||
|
||||
@router.get("", response_model=list[ChildOut])
|
||||
async def list_children(
|
||||
current_user: User = Depends(get_current_user),
|
||||
@@ -21,7 +33,20 @@ async def list_children(
|
||||
result = await db.execute(
|
||||
select(Child).where(Child.user_id == current_user.id).order_by(Child.name)
|
||||
)
|
||||
return result.scalars().all()
|
||||
children = result.scalars().all()
|
||||
|
||||
today = _today_in_tz(current_user.timezone)
|
||||
needs_commit = False
|
||||
for child in children:
|
||||
if child.strikes != 0 and child.strikes_last_reset != today:
|
||||
child.strikes = 0
|
||||
child.strikes_last_reset = today
|
||||
needs_commit = True
|
||||
await manager.broadcast(child.id, {"event": "strikes_update", "strikes": 0})
|
||||
if needs_commit:
|
||||
await db.commit()
|
||||
|
||||
return children
|
||||
|
||||
|
||||
@router.post("", response_model=ChildOut, status_code=status.HTTP_201_CREATED)
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.models.schedule import ScheduleBlock
|
||||
from app.models.subject import Subject # noqa: F401 — needed for selectinload chain
|
||||
from app.models.session import DailySession, TimerEvent
|
||||
from app.schemas.session import DashboardSnapshot
|
||||
from app.utils.timer import compute_block_elapsed
|
||||
from app.utils.timer import compute_block_elapsed, compute_break_elapsed
|
||||
|
||||
router = APIRouter(prefix="/api/dashboard", tags=["dashboard"])
|
||||
|
||||
@@ -65,10 +65,34 @@ async def get_dashboard(child_id: int, db: AsyncSession = Depends(get_db)):
|
||||
|
||||
# Compute elapsed seconds and paused state for the current block from timer_events
|
||||
is_paused = False
|
||||
is_break_active = False
|
||||
break_elapsed_seconds = 0
|
||||
is_break_paused = False
|
||||
if session and session.current_block_id:
|
||||
block_elapsed_seconds, is_paused = await compute_block_elapsed(
|
||||
db, session.id, session.current_block_id
|
||||
)
|
||||
# Determine if break mode is active: check whether the most recent
|
||||
# timer event for this block (main or break) is a break event.
|
||||
last_event_result = await db.execute(
|
||||
select(TimerEvent)
|
||||
.where(
|
||||
TimerEvent.session_id == session.id,
|
||||
TimerEvent.block_id == session.current_block_id,
|
||||
TimerEvent.event_type.in_([
|
||||
"start", "resume",
|
||||
"break_start", "break_resume", "break_pause", "break_reset",
|
||||
]),
|
||||
)
|
||||
.order_by(TimerEvent.occurred_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
last_event = last_event_result.scalar_one_or_none()
|
||||
if last_event and last_event.event_type.startswith("break_"):
|
||||
is_break_active = True
|
||||
break_elapsed_seconds, is_break_paused = await compute_break_elapsed(
|
||||
db, session.id, session.current_block_id
|
||||
)
|
||||
|
||||
routine_result = await db.execute(
|
||||
select(MorningRoutineItem)
|
||||
@@ -93,4 +117,7 @@ async def get_dashboard(child_id: int, db: AsyncSession = Depends(get_db)):
|
||||
is_paused=is_paused,
|
||||
morning_routine=morning_routine,
|
||||
break_activities=break_activities,
|
||||
is_break_active=is_break_active,
|
||||
break_elapsed_seconds=break_elapsed_seconds,
|
||||
is_break_paused=is_break_paused,
|
||||
)
|
||||
|
||||
@@ -37,6 +37,7 @@ async def get_timeline(
|
||||
selectinload(DailySession.template),
|
||||
),
|
||||
)
|
||||
.where(TimerEvent.event_type != "select")
|
||||
.order_by(TimerEvent.occurred_at.desc())
|
||||
)
|
||||
if child_id:
|
||||
|
||||
@@ -14,6 +14,7 @@ from app.models.subject import Subject # noqa: F401 — needed for selectinload
|
||||
from app.models.session import DailySession, TimerEvent
|
||||
from app.models.user import User
|
||||
from app.schemas.session import DailySessionOut, SessionStart, TimerAction
|
||||
from sqlalchemy import delete as sql_delete
|
||||
from app.utils.timer import compute_block_elapsed, compute_break_elapsed
|
||||
from app.websocket.manager import manager
|
||||
|
||||
@@ -194,12 +195,15 @@ async def timer_action(
|
||||
|
||||
# When break starts, implicitly pause the main block timer so elapsed
|
||||
# time is captured accurately in the activity log and on page reload.
|
||||
# Only write the pause if the block is actually running.
|
||||
if body.event_type == "break_start" and block_id:
|
||||
db.add(TimerEvent(
|
||||
session_id=session.id,
|
||||
block_id=block_id,
|
||||
event_type="pause",
|
||||
))
|
||||
_, already_paused = await compute_block_elapsed(db, session.id, block_id)
|
||||
if not already_paused:
|
||||
db.add(TimerEvent(
|
||||
session_id=session.id,
|
||||
block_id=block_id,
|
||||
event_type="pause",
|
||||
))
|
||||
|
||||
db.add(TimerEvent(
|
||||
session_id=session.id,
|
||||
@@ -235,32 +239,48 @@ async def timer_action(
|
||||
if body.event_type in ("start", "select", "reset") and body.block_id is not None:
|
||||
prev_block_id = session.current_block_id
|
||||
if prev_block_id and prev_block_id != body.block_id:
|
||||
db.add(TimerEvent(
|
||||
session_id=session.id,
|
||||
block_id=prev_block_id,
|
||||
event_type="pause",
|
||||
))
|
||||
# Autoflush means the implicit pause above is visible to the helper.
|
||||
prev_block_elapsed_seconds, _ = await compute_block_elapsed(
|
||||
prev_block_elapsed_seconds, prev_already_paused = await compute_block_elapsed(
|
||||
db, session.id, prev_block_id
|
||||
)
|
||||
# Only write an implicit pause if the previous block was actually running.
|
||||
if not prev_already_paused:
|
||||
db.add(TimerEvent(
|
||||
session_id=session.id,
|
||||
block_id=prev_block_id,
|
||||
event_type="pause",
|
||||
))
|
||||
# Recompute elapsed now that the pause event is included.
|
||||
prev_block_elapsed_seconds, _ = await compute_block_elapsed(
|
||||
db, session.id, prev_block_id
|
||||
)
|
||||
|
||||
# Update current block if provided
|
||||
if body.block_id is not None:
|
||||
session.current_block_id = body.block_id
|
||||
|
||||
# Record the timer event
|
||||
# Record the timer event (select events are not persisted — they only drive WS broadcasts)
|
||||
event = TimerEvent(
|
||||
session_id=session.id,
|
||||
block_id=body.block_id or session.current_block_id,
|
||||
event_type=body.event_type,
|
||||
)
|
||||
db.add(event)
|
||||
if body.event_type != "select":
|
||||
db.add(event)
|
||||
|
||||
# Mark session complete if event is session-level complete
|
||||
if body.event_type == "complete" and body.block_id is None:
|
||||
session.is_active = False
|
||||
|
||||
# Reset removes completed status — delete any complete events for this block
|
||||
if body.event_type == "reset" and event.block_id:
|
||||
await db.execute(
|
||||
sql_delete(TimerEvent).where(
|
||||
TimerEvent.session_id == session.id,
|
||||
TimerEvent.block_id == event.block_id,
|
||||
TimerEvent.event_type == "complete",
|
||||
)
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(session)
|
||||
|
||||
@@ -283,6 +303,7 @@ async def timer_action(
|
||||
"block_elapsed_seconds": block_elapsed_seconds,
|
||||
"prev_block_id": prev_block_id,
|
||||
"prev_block_elapsed_seconds": prev_block_elapsed_seconds,
|
||||
"uncomplete_block_id": event.block_id if body.event_type == "reset" else None,
|
||||
}
|
||||
await manager.broadcast(session.child_id, ws_payload)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user