diff --git a/config.toml b/config.toml index 1466249..433d572 100644 --- a/config.toml +++ b/config.toml @@ -7,7 +7,7 @@ port = 37777 frontend_dir = "./dist" # 对外访问地址(用于邮件里的链接)。留空时使用本机地址; # 通过固定域名/IP 访问时建议写全,如 "http://你的服务器IP:37777" -base_url = "" +base_url = "https://worklog.bansonic.top" [notify] # 有人发起活动(参与不算)时,给其他所有已注册用户发邮件通知,邮件里带"一键我也参加过"按钮 diff --git a/dist/assets/styles.css b/dist/assets/styles.css index 15dbee6..1fc6ae4 100644 --- a/dist/assets/styles.css +++ b/dist/assets/styles.css @@ -548,7 +548,7 @@ 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-banner { display: flex; flex-wrap: wrap; 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); } @@ -565,3 +565,10 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } } + +.duty-reminders { flex-basis: 100%; min-width: 0; } +.duty-reminders:empty { display: none; } +.duty-reminder-row { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding-top: 12px; margin-top: 4px; border-top: 1px solid #cbded1; } +.duty-reminder-row > div { min-width: 0; overflow-wrap: anywhere; } +.duty-reminder-row .muted { display: block; margin-top: 5px; } +.duty-reminder-row .btn { flex: none; min-height: 40px; } diff --git a/dist/index.html b/dist/index.html index 7ee2c38..30fa158 100644 --- a/dist/index.html +++ b/dist/index.html @@ -5,7 +5,7 @@ WorkLog · 活动记录 - +
@@ -129,6 +129,7 @@
值班安排正在加载…
+
@@ -222,6 +223,12 @@
+
+

测试邮件连通性

+

向当前账号绑定的邮箱发送测试邮件,同一邮箱每 2 分钟可测试一次。

+ +

+

登录方式

支持邮箱密码或邮箱验证码登录。忘记密码时可通过邮箱验证码重设;修改密码后,其他设备上的登录状态会退出。

@@ -246,7 +253,7 @@ - +
diff --git a/dist/js/app.js b/dist/js/app.js index b0ad550..e83660a 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -526,6 +526,7 @@ let dutySyncedAt = 0; let dutyRetryAt = 0; let dutyLoading = false; + let dutyRemindersKey = ""; 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", @@ -540,6 +541,14 @@ const shift = active ? current : next; const boundary = current ? current.end_at : next?.start_at; const expired = boundary && now >= boundary; + const reminderKey = JSON.stringify(expired ? null : [shift?.start_at, shift?.reminders]); + if (reminderKey !== dutyRemindersKey) { + dutyRemindersKey = reminderKey; + $("#duty-reminders").innerHTML = !shift || expired ? "" : (shift.reminders || []).map((r) => ` +
${esc(r.name)} ${r.confirmed_at ? '已确认' : '未确认'} + ${r.last_sent_at ? `已提醒 ${dutyDate(r.last_sent_at, true)}` : '尚未成功发送'} · ${r.attempts}/3 次${r.confirmed_at ? ` · 确认于 ${dutyDate(r.confirmed_at, true)}` : ''}${r.matched ? '' : ' · 未匹配邮箱'}
+ ${!r.confirmed_at ? `` : ''}
`).join(""); + } $("#duty-banner").classList.toggle("on-duty", !!active); $("#duty-clock").classList.toggle("hidden", !shift || !!expired); if (expired) { @@ -574,6 +583,8 @@ renderDutyStatus(); } catch { dutySnapshot = null; + dutyRemindersKey = ""; + $("#duty-reminders").innerHTML = ""; $("#duty-banner").classList.remove("on-duty"); $("#duty-label").textContent = "值班安排"; $("#duty-names").textContent = "暂时无法加载"; @@ -589,6 +600,34 @@ else renderDutyStatus(); }, 1000); document.addEventListener("visibilitychange", () => { if (!document.hidden) loadDutyStatus(); }); + $("#duty-reminders").addEventListener("click", async (event) => { + const button = event.target.closest("[data-duty-remind]"); + if (!button || button.disabled) return; + button.disabled = true; + try { + await api("/duty/remind", { method: "POST", body: { name: button.dataset.dutyRemind, start_at: Number(button.dataset.start) } }); + toast("值班提醒已发送"); + } catch (error) { toast(error.message, true); } + finally { await loadDutyStatus(); } + }); + + const testEmailCooldowns = new Map(); + function updateTestEmailButton() { + const until = testEmailCooldowns.get(state.me?.email?.toLowerCase()) || 0; + const left = Math.max(0, Math.ceil((until - Date.now()) / 1000)); + $("#pf-test-email").disabled = left > 0; + $("#pf-test-email").textContent = left ? `${left} 秒后可再次测试` : "发送测试邮件"; + } + $("#pf-test-email").addEventListener("click", async () => { + testEmailCooldowns.set(state.me.email.toLowerCase(), Date.now() + 120000); + updateTestEmailButton(); + $("#pf-test-email-status").textContent = "正在发送…"; + try { + await api("/auth/test-email", { method: "POST" }); + $("#pf-test-email-status").textContent = "测试邮件已发送,请查看绑定邮箱及垃圾邮件文件夹。"; + } catch (error) { $("#pf-test-email-status").textContent = error.message; } + }); + setInterval(updateTestEmailButton, 1000); // ------------------------------------------------------------- 我的记录 async function loadMine() { diff --git a/duty/README.md b/duty/README.md index 3f272de..02d8cc6 100644 --- a/duty/README.md +++ b/duty/README.md @@ -33,6 +33,16 @@ python -m server.duty --date 2026-11-09 --db /app/data/worklog.db --emails /app/ 可用环境变量覆盖路径:`WORKLOG_DUTY_SCHEDULE`(排班 JSON)、`WORKLOG_DUTY_EMAILS`(本机邮箱映射)。`WORKLOG_DUTY_REMINDERS=0` 可关闭提醒。排班和邮箱映射每分钟重读,修改后无需重启。 -发送记录写入业务数据库同目录下的 `duty-reminders.db`,不会修改原业务表。每个收件邮箱、每个值班日期的晚间汇总和每个节次提醒分别最多记录一次成功发送;同一批次中同一邮箱对应多位同学会合并。沿用旧版晚间提醒记录,更新后不会重发已成功的晚间汇总。多进程通过 SQLite 事务抢占任务。失败后间隔 15 分钟重试,每封最多尝试 3 次;发信过程中进程崩溃或 SMTP 接收后连接中断,重试仍有重复投递的可能。 +发送记录写入业务数据库同目录下的 `duty-reminders.db`,不会修改原业务表。每个收件邮箱、每个值班日期的晚间汇总和每个节次提醒分别最多记录一次成功发送;同一批次中同一邮箱对应多位同学会合并。沿用旧版晚间提醒记录,更新后不会重发已成功的晚间汇总。多进程通过 SQLite 事务抢占任务。失败后间隔 15 分钟重试,并受下述每人每轮 3 次总尝试上限约束;发信过程中进程崩溃或 SMTP 接收后连接中断,重试仍有重复投递的可能。 更新部署时保留整个 data 目录(包括提醒发送记录),勿覆盖业务数据库。Docker 镜像已包含 duty 目录。 + +## 提醒回执与补发 + +活动墙按每位同学显示发送成功时间、尝试次数和确认时间。邮件内的按钮打开确认页,GET 不记为确认,点击页面确认按钮后 POST 才保存回执;链接有效至该邮件所含最后一轮值班结束。令牌仅以摘要保存在数据库。 + +每人每轮自动和手动提醒合计最多尝试 3 次,失败尝试也计入上限。手动补发仅限活动墙正在展示的本轮或下一轮,距上次尝试至少 1 分钟。已确认后该轮不再发送。状态保存在 duty-reminders.db 中,刷新、重启和并发点击均不会重置限额。 + +账号设置中可发送连通性测试邮件,仅发送到本人当前绑定邮箱。同一邮箱(忽略大小写)每 120 秒最多尝试一次,服务端持久化限流;发送失败也需等待冷却结束。此测试独立于值班提醒次数。 + +线上确认按钮使用配置的 `server.base_url`(当前为 https://worklog.bansonic.top),`WORKLOG_BASE_URL` 可覆盖。本地预览请覆盖为 http://127.0.0.1:37777,以便确认本机保存的回执。 diff --git a/server/duty.py b/server/duty.py index 077df16..afbf37e 100644 --- a/server/duty.py +++ b/server/duty.py @@ -168,7 +168,8 @@ def due_batches(schedule, now): return batches -async def send_due(schedule, now, accounts, send_email, state_path, overrides=None): +async def send_due(schedule, now, accounts, send_email, state_path, overrides=None, base_url="http://127.0.0.1:37777"): + from .duty_receipts import send_notice result = {"sent": 0, "failed": 0, "missing": {}} if not schedule["enabled"]: return result @@ -180,28 +181,29 @@ async def send_due(schedule, now, accounts, send_email, state_path, overrides=No if not await asyncio.to_thread(claim, state_path, key, email, now.timestamp()): continue clocks = schedule.get("slot_times", {}) - lines = [f"{name}:" + "、".join(f"{slot}({clocks[slot]} 开始)" if slot in clocks else slot for slot in slots) for name, slots in names.items()] - body = f"{label}\n\n日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "\n".join(lines) + "\n\n以上时间均为北京时间。请准时值班;如需调班,请提前联系值班负责人。\nWorkLog" + slots = {slot for items in names.values() for slot in items} + ends = [datetime.combine(target, datetime.strptime(clocks[slot], "%H:%M").time(), BEIJING) + timedelta(minutes=schedule.get("duration_minutes", 105)) for slot in slots] + body = f"日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "、".join(f"{slot} {clocks[slot]} 开始" for slot in sorted(slots)) + "\n以上时间均为北京时间。请准时值班。" try: - await send_email(email, f"{label}|{target.isoformat()}", body) + sent = await send_notice(state_path, target.isoformat(), names, email, max(ends).timestamp(), send_email, f"{label}|{target.isoformat()}", body, base_url, now.timestamp()) except Exception: result["failed"] += 1 await asyncio.to_thread(finish, state_path, key, email, "failed") log.exception("值班邮件发送失败") else: - result["sent"] += 1 + result["sent"] += int(sent) await asyncio.to_thread(finish, state_path, key, email, "sent") return result -async def reminder_loop(schedule_path, state_path, get_accounts, send_email, overrides_path=None): +async def reminder_loop(schedule_path, state_path, get_accounts, send_email, overrides_path=None, base_url="http://127.0.0.1:37777"): previous_missing = None while True: try: schedule = load_schedule(schedule_path) if schedule["enabled"]: overrides = json.loads(Path(overrides_path).read_text(encoding="utf-8-sig")) if overrides_path and Path(overrides_path).exists() else {} - result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides) + result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides, base_url) if result["missing"] and result["missing"] != previous_missing: log.warning("值班名单无法匹配邮箱:%s", result["missing"]) previous_missing = result["missing"] diff --git a/server/duty_receipts.py b/server/duty_receipts.py new file mode 100644 index 0000000..66072b0 --- /dev/null +++ b/server/duty_receipts.py @@ -0,0 +1,107 @@ +"""值班提醒回执;独立 SQLite 保存每人每轮的发送次数和确认状态。""" +import hashlib +import json +import secrets +import sqlite3 +import time +from contextlib import closing +from html import escape + + +def connect(path): + path.parent.mkdir(parents=True, exist_ok=True) + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + con.execute("CREATE TABLE IF NOT EXISTS duty_receipts (day TEXT, slot TEXT, name TEXT, attempts INTEGER DEFAULT 0, sent_count INTEGER DEFAULT 0, last_attempt REAL DEFAULT 0, last_sent REAL DEFAULT 0, confirmed REAL DEFAULT 0, PRIMARY KEY(day,slot,name))") + con.execute("CREATE TABLE IF NOT EXISTS duty_confirmations (digest TEXT PRIMARY KEY, targets TEXT NOT NULL, expires REAL NOT NULL)") + return con + + +def ensure(con, day, slot, name, email): + # 导入旧版成功发送记录;新版已有回执后不重复导入。 + count, last = 0, 0 + if email and con.execute("SELECT 1 FROM sqlite_master WHERE name='deliveries'").fetchone(): + rows = con.execute("SELECT updated FROM deliveries WHERE email=? AND status='sent' AND day IN (?,?)", (email, day, f"{day}#before:{slot}")).fetchall() + count = len(rows) + last = max((r[0] for r in rows), default=0) + con.execute("INSERT OR IGNORE INTO duty_receipts(day,slot,name,attempts,sent_count,last_attempt,last_sent) VALUES (?,?,?,?,?,?,?)", (day, slot, name, count, count, last, last)) + + +def status(path, day, slot, name, email, now): + with closing(connect(path)) as con: + ensure(con, day, slot, name, email) + row = dict(con.execute("SELECT * FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()) + con.commit() + return {"name": name, "attempts": row["attempts"], "sent_count": row["sent_count"], "last_sent_at": int(row["last_sent"] * 1000) or None, "confirmed_at": int(row["confirmed"] * 1000) or None, "can_remind": bool(email and not row["confirmed"] and row["attempts"] < 3 and now - row["last_attempt"] >= 60), "matched": bool(email)} + + +def reserve(path, day, names, email, expires, now): + selected = {} + with closing(connect(path)) as con: + con.execute("BEGIN IMMEDIATE") + for name, slots in names.items(): + for slot in slots: + ensure(con, day, slot, name, email) + row = con.execute("SELECT * FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone() + if row["confirmed"] or row["attempts"] >= 3 or now - row["last_attempt"] < 60: + continue + con.execute("UPDATE duty_receipts SET attempts=attempts+1,last_attempt=? WHERE day=? AND slot=? AND name=?", (now, day, slot, name)) + selected.setdefault(name, []).append(slot) + if not selected: + con.commit() + return None, {} + token = secrets.token_urlsafe(32) + targets = [(day, slot, name) for name, slots in selected.items() for slot in slots] + con.execute("INSERT INTO duty_confirmations VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), json.dumps(targets), expires)) + con.commit() + return token, selected + + +def mark_sent(path, day, names, now): + with closing(connect(path)) as con: + for name, slots in names.items(): + for slot in slots: + con.execute("UPDATE duty_receipts SET sent_count=sent_count+1,last_sent=? WHERE day=? AND slot=? AND name=?", (now, day, slot, name)) + con.commit() + + +def confirmation(path, token, now, consume=False): + with closing(connect(path)) as con: + con.execute("BEGIN IMMEDIATE") + row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone() + if row is None or row["expires"] <= now: + return None + targets = json.loads(row["targets"]) + if consume: + for day, slot, name in targets: + con.execute("UPDATE duty_receipts SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE day=? AND slot=? AND name=?", (now, day, slot, name)) + con.commit() + return targets + + +def reserve_test(path, email, now): + with closing(connect(path)) as con: + con.execute("CREATE TABLE IF NOT EXISTS mail_test_limits (email TEXT PRIMARY KEY, last_attempt REAL NOT NULL)") + con.execute("BEGIN IMMEDIATE") + row = con.execute("SELECT last_attempt FROM mail_test_limits WHERE email=?", (email.strip().lower(),)).fetchone() + if row and now - row[0] < 120: + return False + con.execute("INSERT OR REPLACE INTO mail_test_limits VALUES (?,?)", (email.strip().lower(), now)) + con.commit() + return True + + +async def send_notice(path, day, names, email, expires, send_email, subject, body, base_url, now=None): + import asyncio + now = time.time() if now is None else now + token, selected = await asyncio.to_thread(reserve, path, day, names, email, expires, now) + if not selected: + return False + url = base_url.rstrip('/') + '/duty-confirm/' + token + # 仅写入本次获得发送名额的同学和时段,避免再次提醒已确认的记录。 + details = '\n'.join(f"{name}:{'、'.join(slots)}" for name, slots in selected.items()) + plain = f"{subject}\n\n{body}\n{details}\n\n请点击以下链接确认已知晓本次值班安排:\n{url}\n\nWorkLog" + html = f'

{escape(subject)}

{escape(body).replace(chr(10), "
")}

{escape(details).replace(chr(10), "
")}

确认已知晓值班安排

打开后请在页面中确认。WorkLog

' + await send_email(email, subject, plain, html) + await asyncio.to_thread(mark_sent, path, day, selected, now) + return True diff --git a/server/main.py b/server/main.py index 9459f4c..8a6515e 100644 --- a/server/main.py +++ b/server/main.py @@ -38,6 +38,8 @@ from .models import activities, auth_limits, email_verifications, join_links, me from .security import hash_password, new_token, token_digest, verify_password from .backup import backup_loop, parse_time from .duty import BEIJING, duty_status, load_schedule, reminder_loop +from .duty import resolve_recipients +from . import duty_receipts BASE_DIR = Path(__file__).resolve().parent PROJECT_DIR = BASE_DIR.parent @@ -547,6 +549,7 @@ async def lifespan(_app: FastAPI): duty_task = asyncio.create_task(reminder_loop( duty_path, _db_path.with_name("duty-reminders.db"), duty_accounts, _send_email, os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json")), + _site_base_url(), )) try: yield @@ -639,7 +642,7 @@ async def security_headers(request: Request, call_next): "img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; " "frame-ancestors 'none'; form-action 'self'" ) - if request.url.path.startswith(("/api/", "/join/")): + if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/")): response.headers["Cache-Control"] = "no-store" return response @@ -1147,15 +1150,84 @@ 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: +async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> 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)) + data = duty_status(load_schedule(path), datetime.now(BEIJING)) + accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()] + overrides = _duty_overrides() + for shift in (data["current"], data["next"]): + if not shift: + continue + recipients, _ = resolve_recipients({name: [shift["slot"]] for name in shift["names"]}, accounts, overrides) + emails = {name: email for email, names in recipients.items() for name in names} + day = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING).date().isoformat() + shift["reminders"] = [await asyncio.to_thread(duty_receipts.status, _duty_state(), day, shift["slot"], name, emails.get(name), time.time()) for name in shift["names"]] + return data except (ValueError, KeyError, TypeError, OSError) as exc: raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc + +def _duty_state(): + return _db_path.with_name("duty-reminders.db") + + +@app.post("/api/auth/test-email") +async def test_account_email(viewer: dict = Depends(current_user)): + email = viewer.get("email", "").strip() + if not email: + raise HTTPException(status_code=409, detail="当前账号尚未绑定邮箱") + if not await asyncio.to_thread(duty_receipts.reserve_test, _duty_state(), email, time.time()): + raise HTTPException(status_code=429, detail="同一邮箱2分钟内只能测试一次,请稍后重试", headers={"Retry-After": "120"}) + await _send_email(email, "【WorkLog】邮箱连通性测试", "这是一封由你在账号设置中主动发送的测试邮件。收到本邮件表示当前邮件发送服务可以向你的绑定邮箱投递邮件。\n\nWorkLog") + return {"ok": True, "retry_after": 120} + + +def _duty_overrides(): + import json + path = Path(os.getenv("WORKLOG_DUTY_EMAILS", str(_db_path.parent / "duty-emails.json"))) + return json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {} + + +class DutyRemindIn(BaseModel): + name: str = Field(min_length=1, max_length=64) + start_at: int + + +@app.post("/api/duty/remind") +async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user), db: AsyncSession = Depends(get_db)): + data = await current_duty(viewer, db) + shift = next((s for s in (data["current"], data["next"]) if s and s["start_at"] == payload.start_at and payload.name in s["names"]), None) + if not shift: + raise HTTPException(status_code=409, detail="值班安排已变化,请刷新页面") + accounts = [dict(r) for r in (await db.execute(select(users.c.display_name, users.c.email))).mappings()] + recipients, _ = resolve_recipients({payload.name: [shift["slot"]]}, accounts, _duty_overrides()) + if not recipients: + raise HTTPException(status_code=409, detail="未找到唯一的绑定邮箱,请核对姓名和账号") + email = next(iter(recipients)) + start = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING) + try: + sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, "值班提醒", f"日期:{start:%Y-%m-%d},{start:%H:%M} 开始(北京时间)", _site_base_url()) + except HTTPException: + raise + if not sent: + raise HTTPException(status_code=429, detail="已确认、已达3次上限或距上次发送不足1分钟") + return {"ok": True} + + +@app.get("/duty-confirm/{token}", include_in_schema=False) +@app.post("/duty-confirm/{token}", include_in_schema=False) +async def confirm_duty(token: str, request: Request): + targets = await asyncio.to_thread(duty_receipts.confirmation, _duty_state(), token, time.time(), request.method == "POST") + if targets is None: + return HTMLResponse(_join_page("确认链接无效或本轮值班已结束。", "err"), status_code=410) + text = ";".join(f"{day} {slot} {name}" for day, slot, name in targets) + if request.method == "GET": + return HTMLResponse(_join_page("请确认已知晓:" + text, "confirm", extra='
')) + return HTMLResponse(_join_page("已确认值班安排,谢谢。", "ok")) + @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 b91ace5..484712b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -89,13 +89,53 @@ class ApiTestCase(unittest.IsolatedAsyncioTestCase): class WorkLogApiTests(ApiTestCase): + async def test_duty_reminder_and_confirmation_flow(self): + from datetime import datetime + from unittest.mock import AsyncMock + from server.duty import BEIJING, duty_status, load_schedule, ROOT + status = duty_status(load_schedule(ROOT / 'duty/schedule.json'), datetime.now(BEIJING)) + shift = status['current'] or status['next'] + name = shift['names'][0] + u = await register(self.client, name) + with tempfile.TemporaryDirectory() as directory: + with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send: + request = {'name': name, 'start_at': shift['start_at']} + response = await self.client.post('/api/duty/remind', json=request, headers=auth(u['token'])) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(send.await_args.args[0], u['user']['email']) + self.assertIn('确认已知晓', send.await_args.args[3]) + token = send.await_args.args[2].split('/duty-confirm/')[1].split()[0] + url = '/duty-confirm/' + token + self.assertEqual((await self.client.get(url)).status_code, 200) + state = (await self.client.get('/api/duty/current', headers=auth(u['token']))).json() + selected = next(s for s in (state['current'], state['next']) if s and s['start_at'] == shift['start_at']) + row = next(r for r in selected['reminders'] if r['name'] == name) + self.assertIsNone(row['confirmed_at']) + self.assertEqual(row['sent_count'], 1) + self.assertEqual((await self.client.post(url)).status_code, 200) + self.assertEqual((await self.client.post('/api/duty/remind', json=request, headers=auth(u['token']))).status_code, 429) + self.assertEqual(send.await_count, 1) + + async def test_test_email_only_uses_current_account_and_limits_two_minutes(self): + from unittest.mock import AsyncMock + c = self.client + self.assertEqual((await c.post('/api/auth/test-email')).status_code, 401) + u = await register(c, 'mailtester') + with tempfile.TemporaryDirectory() as directory: + with patch.object(self.m, '_duty_state', return_value=Path(directory) / 'state.db'), patch.object(self.m, '_send_email', new_callable=AsyncMock) as send: + response = await c.post('/api/auth/test-email', headers=auth(u['token']), json={'email': 'other@example.test'}) + self.assertEqual(response.status_code, 200) + self.assertEqual(send.await_args.args[0], u['user']['email']) + self.assertEqual((await c.post('/api/auth/test-email', headers=auth(u['token']))).status_code, 429) + self.assertEqual(send.await_count, 1) + 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: + with patch.object(self.m, "datetime", wraps=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) diff --git a/tests/test_duty.py b/tests/test_duty.py index a901f8a..0524149 100644 --- a/tests/test_duty.py +++ b/tests/test_duty.py @@ -81,6 +81,7 @@ class DutyTests(unittest.IsolatedAsyncioTestCase): import sqlite3 with closing(sqlite3.connect(self.state)) as db: db.execute("UPDATE deliveries SET updated=0") + db.execute("UPDATE duty_receipts SET last_attempt=0") db.commit() result = await send_due(self.schedule, self.now, self.accounts[:1], send, self.state) self.assertEqual(result["sent"], 1) diff --git a/tests/test_duty_receipts.py b/tests/test_duty_receipts.py new file mode 100644 index 0000000..42206c1 --- /dev/null +++ b/tests/test_duty_receipts.py @@ -0,0 +1,51 @@ +import asyncio +import tempfile +import unittest +from pathlib import Path +from unittest.mock import AsyncMock +from server import duty_receipts as r + + +class ReceiptsTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.path = Path(self.tmp.name) / 'state.db' + + def tearDown(self): + self.tmp.cleanup() + + async def test_three_attempts_and_confirmation_suppresses_reminders(self): + names = {'同学': ['一二节']} + send = AsyncMock() + tokens = [] + for now in [1000, 1061, 1122]: + self.assertTrue(await r.send_notice(self.path, '2026-11-06', names, 'a@example.test', 9999, send, '提醒', '正文', 'https://example.test', now)) + tokens.append(send.await_args.args[2].split('/duty-confirm/')[1].split()[0]) + self.assertFalse(await r.send_notice(self.path, '2026-11-06', names, 'a@example.test', 9999, send, '提醒', '正文', 'https://example.test', 1200)) + state = r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1200) + self.assertEqual(state['sent_count'], 3) + self.assertEqual(state['last_sent_at'], 1122000) + # 邮件扫描 GET 不确认,POST 确认可重复调用且不改变首次确认时间。 + self.assertIsNotNone(r.confirmation(self.path, tokens[0], 1200)) + self.assertIsNone(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1200)['confirmed_at']) + r.confirmation(self.path, tokens[0], 1200, True) + r.confirmation(self.path, tokens[0], 1250, True) + self.assertEqual(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1250)['confirmed_at'], 1200000) + self.assertIsNone(r.confirmation(self.path, tokens[0], 10000, True)) + self.assertIsNone(r.confirmation(self.path, 'invalid', 1200, True)) + + async def test_confirmed_person_stops_early_and_concurrent_sends_cannot_bypass_limit(self): + names = {'同学': ['一二节']} + async def attempt(): + return await asyncio.to_thread(r.reserve, self.path, '2026-11-06', names, 'a@example.test', 9999, 1000) + results = await asyncio.gather(*(attempt() for _ in range(5))) + self.assertEqual(sum(bool(token) for token, _ in results), 1) + token = next(token for token, _ in results if token) + r.confirmation(self.path, token, 1010, True) + self.assertEqual(r.reserve(self.path, '2026-11-06', names, 'a@example.test', 9999, 1100), (None, {})) + self.assertIsNotNone(r.reserve(self.path, '2026-11-06', {'同学': ['三四节']}, 'a@example.test', 9999, 1100)[0]) + + async def test_test_mail_limit_is_persistent_and_case_insensitive(self): + self.assertTrue(r.reserve_test(self.path, 'Student@example.test', 1000)) + self.assertFalse(r.reserve_test(self.path, 'student@example.test', 1119)) + self.assertTrue(r.reserve_test(self.path, 'student@example.test', 1120))