diff --git a/dist/assets/styles.css b/dist/assets/styles.css index a2aa521..15dbee6 100644 --- a/dist/assets/styles.css +++ b/dist/assets/styles.css @@ -548,6 +548,20 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s .code-row { gap: 6px; } .code-row .btn { padding-inline: 10px; } } +.duty-banner { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 20px 24px; margin-bottom: 24px; background: var(--primary-soft); border: 1px solid #d5e5da; border-radius: var(--radius); } +.duty-info { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; min-width: 0; } +.duty-label { display: inline-flex; align-items: center; gap: 7px; color: var(--primary); font-size: 13px; } +.on-duty .duty-label::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--primary); } +#duty-names { font-weight: 600; font-size: 17px; overflow-wrap: anywhere; } +.duty-time { width: 100%; color: var(--muted); font-size: 12px; } +.duty-clock { text-align: right; flex: none; border-left: 1px solid #cbded1; padding-left: 24px; } +.duty-clock > span { display: block; color: var(--muted); font-size: 12px; } +.duty-clock strong { display: block; font-size: 25px; font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: .5px; } +@media (max-width: 520px) { + .duty-banner { align-items: stretch; padding: 18px; gap: 16px; flex-direction: column; } + .duty-clock { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; text-align: left; padding: 12px 0 0; border-left: 0; border-top: 1px solid #cbded1; } + .duty-clock strong { font-size: 26px; } +} @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } } diff --git a/dist/index.html b/dist/index.html index ce3586e..7ee2c38 100644 --- a/dist/index.html +++ b/dist/index.html @@ -5,7 +5,7 @@ WorkLog · 活动记录 - +
@@ -126,6 +126,10 @@
+
+
值班安排正在加载…
+ +
@@ -242,7 +246,7 @@ - + diff --git a/dist/js/app.js b/dist/js/app.js index 279a628..b0ad550 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -134,7 +134,7 @@ if (a.dataset.view === view) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current"); }); - if (view === "feed") loadFeed(); + if (view === "feed") { loadFeed(); loadDutyStatus(); } if (view === "mine") loadMine(); if (view === "members") loadMembers(); if (view === "profile") fillProfile(); @@ -519,7 +519,76 @@ $("#feed-q").addEventListener("input", debounce(() => { state.feed.q = $("#feed-q").value.trim(); loadFeed(); }, 350)); $("#feed-dept").addEventListener("change", () => { state.feed.department = $("#feed-dept").value; loadFeed(); }); $("#feed-scope").addEventListener("change", () => { state.feed.scope = $("#feed-scope").value; loadFeed(); }); - $("#feed-refresh").addEventListener("click", loadFeed); + $("#feed-refresh").addEventListener("click", () => { loadFeed(); loadDutyStatus(); }); + + // 倒计时以服务端时间和浏览器单调时钟计算,不依赖用户电脑校时。 + let dutySnapshot = null; + let dutySyncedAt = 0; + let dutyRetryAt = 0; + let dutyLoading = false; + const dutyDate = (ms, includeDate = false) => new Intl.DateTimeFormat("zh-CN", { + timeZone: "Asia/Shanghai", ...(includeDate ? { month: "numeric", day: "numeric", weekday: "short" } : {}), + hour: "2-digit", minute: "2-digit", hourCycle: "h23", + }).format(ms); + + function renderDutyStatus() { + if (!dutySnapshot) return; + const now = dutySnapshot.server_now + performance.now() - dutySyncedAt; + const current = dutySnapshot.current; + const next = dutySnapshot.next; + const active = current && now < current.end_at; + const shift = active ? current : next; + const boundary = current ? current.end_at : next?.start_at; + const expired = boundary && now >= boundary; + $("#duty-banner").classList.toggle("on-duty", !!active); + $("#duty-clock").classList.toggle("hidden", !shift || !!expired); + if (expired) { + $("#duty-label").textContent = "值班安排"; + $("#duty-names").textContent = "正在更新…"; + $("#duty-time").textContent = ""; + } else if (shift) { + $("#duty-label").textContent = active ? "当前值班" : "下一轮值班"; + $("#duty-names").textContent = shift.names.join("、"); + $("#duty-time").textContent = `${active ? shift.slot : dutyDate(shift.start_at, true)} · ${active ? dutyDate(shift.start_at) + "–" + dutyDate(shift.end_at) : "开始"}(北京时间)`; + $("#duty-countdown-label").textContent = active ? "本轮剩余" : "距离开始"; + const seconds = Math.max(0, Math.ceil(((active ? shift.end_at : shift.start_at) - now) / 1000)); + const days = Math.floor(seconds / 86400); + const clock = [Math.floor(seconds / 3600) % 24, Math.floor(seconds / 60) % 60, seconds % 60].map((n) => String(n).padStart(2, "0")).join(":"); + $("#duty-countdown").textContent = (days ? `${days}天 ` : "") + clock; + } else { + $("#duty-label").textContent = "值班安排"; + $("#duty-names").textContent = dutySnapshot.enabled ? "暂无值班安排" : "值班安排已暂停"; + $("#duty-time").textContent = ""; + } + if ((expired || performance.now() - dutySyncedAt >= 60000) && performance.now() >= dutyRetryAt) loadDutyStatus(); + } + + async function loadDutyStatus() { + if (dutyLoading || !state.me || state.view !== "feed") return; + dutyLoading = true; + dutyRetryAt = performance.now() + 10000; + try { + const data = await api("/duty/current"); + dutySnapshot = data; + dutySyncedAt = performance.now(); + renderDutyStatus(); + } catch { + dutySnapshot = null; + $("#duty-banner").classList.remove("on-duty"); + $("#duty-label").textContent = "值班安排"; + $("#duty-names").textContent = "暂时无法加载"; + $("#duty-time").textContent = "稍后自动重试"; + $("#duty-clock").classList.add("hidden"); + } finally { + dutyLoading = false; + } + } + setInterval(() => { + if (state.view !== "feed" || document.hidden) return; + if (!dutySnapshot && performance.now() >= dutyRetryAt) loadDutyStatus(); + else renderDutyStatus(); + }, 1000); + document.addEventListener("visibilitychange", () => { if (!document.hidden) loadDutyStatus(); }); // ------------------------------------------------------------- 我的记录 async function loadMine() { diff --git a/duty/README.md b/duty/README.md index 8adc9cd..3f272de 100644 --- a/duty/README.md +++ b/duty/README.md @@ -12,6 +12,7 @@ - 默认持续按单双周循环;假期和调休如需停发,将 `enabled` 改为 false。不会自动读取学校校历。 - 不追发已错过日期的提醒;当天 18:00 后启动可补发当晚应发提醒。值班前提醒在预定提醒时间至值班开始前可补发,值班开始后跳过。每分钟检查一次,正常发送可能有一分钟以内的延迟。 - 值班提醒由 WorkLog 服务自动运行,不需要另设定时任务;服务必须持续在线。现有 SMTP 配置继续使用。 +- 活动墙顶部显示当前值班姓名、节次和本轮剩余倒计时,每轮 105 分钟:08:30–10:15、10:25–12:10、14:00–15:45、16:00–17:45。课间、午休及周末显示下一轮人员和开始倒计时。倒计时以服务端北京时间为准,到点自动刷新排班。 ## 邮箱匹配 diff --git a/duty/schedule.json b/duty/schedule.json index 68b3894..ab7102b 100644 --- a/duty/schedule.json +++ b/duty/schedule.json @@ -315,5 +315,6 @@ "三四节": "10:25", "五六节": "14:00", "七八节": "16:00" - } + }, + "duration_minutes": 105 } diff --git a/server/duty.py b/server/duty.py index 4a06c21..077df16 100644 --- a/server/duty.py +++ b/server/duty.py @@ -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: diff --git a/server/main.py b/server/main.py index e82b02b..9459f4c 100644 --- a/server/main.py +++ b/server/main.py @@ -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) diff --git a/tests/test_api.py b/tests/test_api.py index 5d68e73..b91ace5 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -89,6 +89,21 @@ class ApiTestCase(unittest.IsolatedAsyncioTestCase): class WorkLogApiTests(ApiTestCase): + async def test_wall_duty_requires_login_and_only_exposes_schedule(self): + from datetime import datetime + from server.duty import BEIJING + c = self.client + self.assertEqual((await c.get("/api/duty/current")).status_code, 401) + u = await register(c, "dutyviewer") + with patch.object(self.m, "datetime") as clock: + clock.now.return_value = datetime(2026, 11, 6, 8, 30, tzinfo=BEIJING) + r = await c.get("/api/duty/current", headers=auth(u["token"])) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.json()["current"]["names"], ["华秋豪"]) + self.assertEqual(r.json()["current"]["end_at"] - r.json()["current"]["start_at"], 105 * 60000) + self.assertNotIn("email", r.text) + self.assertNotIn("phone", r.text) + # ------------------------------------------------------------- 账号 async def test_register_login_profile(self): c = self.client diff --git a/tests/test_duty.py b/tests/test_duty.py index fc4cc60..a901f8a 100644 --- a/tests/test_duty.py +++ b/tests/test_duty.py @@ -6,7 +6,7 @@ from datetime import date, datetime from pathlib import Path from unittest.mock import AsyncMock -from server.duty import BEIJING, ROOT, duties_on, load_schedule, resolve_recipients, send_due +from server.duty import BEIJING, ROOT, duties_on, duty_status, load_schedule, resolve_recipients, send_due class DutyTests(unittest.IsolatedAsyncioTestCase): @@ -33,6 +33,24 @@ class DutyTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(self.names, {"华秋豪": ["一二节"], "孙鹏": ["三四节"], "武鑫": ["三四节"], "仲雅玉": ["五六节"], "马涵雪": ["五六节"], "马驰骋": ["七八节"]}) self.assertEqual(sum(len(e["names"]) for entries in self.schedule["weeks"].values() for e in entries), 58) + def test_wall_current_shift_boundaries_and_duration(self): + for hour, minute, expected_slot in [(8, 30, "一二节"), (10, 14, "一二节"), (10, 15, None), (10, 25, "三四节"), (12, 10, None), (14, 0, "五六节"), (15, 45, None), (16, 0, "七八节"), (17, 45, None)]: + data = duty_status(self.schedule, self.now.replace(hour=hour, minute=minute)) + self.assertEqual(data["current"]["slot"] if data["current"] else None, expected_slot, (hour, minute)) + if data["current"]: + self.assertEqual(data["current"]["end_at"] - data["current"]["start_at"], 105 * 60000) + current = duty_status(self.schedule, self.now.replace(hour=8, minute=30))["current"] + self.assertEqual(current["names"], ["华秋豪"]) + + def test_wall_weekend_next_week_and_disabled(self): + weekend = duty_status(self.schedule, datetime(2026, 11, 7, 12, tzinfo=BEIJING)) + self.assertIsNone(weekend["current"]) + self.assertEqual(weekend["next"]["names"], ["刘旭洋"]) + self.assertEqual(weekend["next"]["week"], "even") + self.assertEqual(datetime.fromtimestamp(weekend["next"]["start_at"] / 1000, BEIJING).isoformat(), "2026-11-09T08:30:00+08:00") + self.schedule["enabled"] = False + self.assertIsNone(duty_status(self.schedule, self.now)["next"]) + def test_matching_never_guesses_missing_or_duplicate_names(self): accounts = [{"display_name": "同名", "email": "a@example.test"}, {"display_name": "同名", "email": "b@example.test"}] found, missing = resolve_recipients({"同名": ["一二节"], "未注册": ["三四节"]}, accounts)