feat: show current duty students and shift countdown on activity wall
This commit is contained in:
@@ -32,6 +32,8 @@ def load_schedule(path):
|
||||
before = data.get("before_minutes", 0)
|
||||
if type(before) is not int or not 0 <= before <= 480:
|
||||
raise ValueError("值班前提醒分钟数必须为 0–480")
|
||||
if type(data.get("duration_minutes", 105)) is not int or not 1 <= data.get("duration_minutes", 105) <= 1440:
|
||||
raise ValueError("每轮值班时长必须为 1–1440 分钟")
|
||||
for week in ("odd", "even"):
|
||||
seen = set()
|
||||
for entry in data["weeks"][week]:
|
||||
@@ -89,6 +91,39 @@ def resolve_recipients(assignments, accounts, overrides=None):
|
||||
return recipients, missing
|
||||
|
||||
|
||||
def duty_status(schedule, now):
|
||||
"""活动墙只返回排班姓名和时间,不暴露邮箱等联系方式。"""
|
||||
now = now.astimezone(BEIJING)
|
||||
result = {"server_now": int(now.timestamp() * 1000), "enabled": schedule["enabled"], "current": None, "next": None}
|
||||
if not schedule["enabled"]:
|
||||
return result
|
||||
anchor = date.fromisoformat(schedule["anchor_date"])
|
||||
first = max(now.date(), anchor)
|
||||
for offset in range(15):
|
||||
day = first + timedelta(days=offset)
|
||||
week, assignments = duties_on(schedule, day)
|
||||
grouped = defaultdict(list)
|
||||
for name, slots in assignments.items():
|
||||
for slot in slots:
|
||||
grouped[slot].append(name)
|
||||
shifts = []
|
||||
for slot, names in grouped.items():
|
||||
clock = schedule.get("slot_times", {}).get(slot)
|
||||
if not clock:
|
||||
continue
|
||||
start = datetime.combine(day, datetime.strptime(clock, "%H:%M").time(), BEIJING)
|
||||
end = start + timedelta(minutes=schedule.get("duration_minutes", 105))
|
||||
shifts.append((start, end, slot, names))
|
||||
for start, end, slot, names in sorted(shifts):
|
||||
shift = {"slot": slot, "names": names, "week": week, "start_at": int(start.timestamp() * 1000), "end_at": int(end.timestamp() * 1000)}
|
||||
if start <= now < end:
|
||||
result["current"] = shift
|
||||
elif start > now:
|
||||
result["next"] = shift
|
||||
return result
|
||||
return result
|
||||
|
||||
|
||||
def claim(state_path, day, email, now):
|
||||
Path(state_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
with closing(sqlite3.connect(state_path, timeout=10)) as con:
|
||||
|
||||
+12
-1
@@ -19,6 +19,7 @@ import uuid
|
||||
from html import escape
|
||||
from ipaddress import ip_address
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
@@ -36,7 +37,7 @@ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from .models import activities, auth_limits, email_verifications, join_links, metadata, participations, sessions, users
|
||||
from .security import hash_password, new_token, token_digest, verify_password
|
||||
from .backup import backup_loop, parse_time
|
||||
from .duty import reminder_loop
|
||||
from .duty import BEIJING, duty_status, load_schedule, reminder_loop
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_DIR = BASE_DIR.parent
|
||||
@@ -1145,6 +1146,16 @@ async def update_me(payload: ProfileIn, user: dict = Depends(current_user), db:
|
||||
|
||||
# ---------------------------------------------------------------- 成员
|
||||
|
||||
@app.get("/api/duty/current")
|
||||
async def current_duty(_viewer: dict = Depends(current_user)) -> dict:
|
||||
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
|
||||
if not path.exists():
|
||||
return duty_status({"enabled": False}, datetime.now(BEIJING))
|
||||
try:
|
||||
return duty_status(load_schedule(path), datetime.now(BEIJING))
|
||||
except (ValueError, KeyError, TypeError, OSError) as exc:
|
||||
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
|
||||
|
||||
@app.get("/api/stats/overview")
|
||||
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
|
||||
members = int((await db.execute(select(func.count()).select_from(users))).scalar() or 0)
|
||||
|
||||
Reference in New Issue
Block a user