停止记录和补记值班缺勤,移除缺勤入口并保留历史数据

This commit is contained in:
2026-11-08 11:41:29 +08:00
parent 6377a42a8f
commit 0663b44cdc
10 changed files with 50 additions and 115 deletions
-2
View File
@@ -201,8 +201,6 @@ async def reminder_loop(schedule_path, state_path, get_accounts, send_email, ove
while True:
try:
schedule = load_schedule(schedule_path)
from .duty_receipts import sync_absences
await asyncio.to_thread(sync_absences, state_path, schedule, datetime.now(BEIJING))
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, base_url)
+7 -32
View File
@@ -6,7 +6,6 @@ import sqlite3
import time
from contextlib import closing
from html import escape
from datetime import date, datetime, timedelta
def connect(path):
@@ -16,8 +15,6 @@ def connect(path):
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)")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmation_forms (digest TEXT PRIMARY KEY, nonce_hash TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS duty_absences (day TEXT, slot TEXT, name TEXT, end_at REAL NOT NULL, recorded_at REAL NOT NULL, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_audit_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS mail_button_tests (digest TEXT PRIMARY KEY, kind TEXT NOT NULL, expires REAL NOT NULL, confirmed REAL NOT NULL DEFAULT 0)")
return con
@@ -162,36 +159,14 @@ def button_test(path, token, now, consume=False):
return row['kind']
def sync_absences(path, schedule, now):
from .duty import BEIJING, duties_on
now = now.astimezone(BEIJING)
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
cursor = con.execute("SELECT value FROM duty_audit_state WHERE key='day'").fetchone()
first = max(date.fromisoformat(schedule["anchor_date"]), date.fromisoformat(cursor[0]) if cursor else now.date())
if schedule["enabled"]:
day = first
while day <= now.date():
_, assignments = duties_on(schedule, day)
for name, slots in assignments.items():
for slot in slots:
clock = schedule.get("slot_times", {}).get(slot)
if not clock:
continue
end = datetime.combine(day, datetime.strptime(clock, '%H:%M').time(), BEIJING) + timedelta(minutes=schedule.get('duration_minutes', 105))
if end > now:
continue
ensure(con, day.isoformat(), slot, name, None)
row = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day.isoformat(), slot, name)).fetchone()
if not row[0] or row[0] > end.timestamp():
con.execute("INSERT OR IGNORE INTO duty_absences VALUES (?,?,?,?,?)", (day.isoformat(), slot, name, end.timestamp(), now.timestamp()))
day += timedelta(days=1)
con.execute("INSERT OR REPLACE INTO duty_audit_state VALUES ('day',?)", (now.date().isoformat(),))
con.commit()
def absence_records(path, limit=50, offset=0):
with closing(connect(path)) as con:
"""只读兼容历史缺勤记录,不再创建、生成或补记缺勤。"""
if not path.exists():
return []
with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as con:
con.row_factory = sqlite3.Row
if not con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='duty_absences'").fetchone():
return []
rows = con.execute("SELECT * FROM duty_absences ORDER BY day DESC,end_at DESC,name LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return [{"day": r['day'], "slot": r['slot'], "name": r['name'], "end_at": int(r['end_at'] * 1000), "recorded_at": int(r['recorded_at'] * 1000), "reason": "未确认缺勤"} for r in rows]
+4 -10
View File
@@ -1249,7 +1249,6 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
return duty_status({"enabled": False}, datetime.now(BEIJING))
try:
schedule = load_schedule(path)
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), schedule, datetime.now(BEIJING))
data = duty_status(schedule, datetime.now(BEIJING))
accounts = [dict(r) for r in (await db.execute(select(users.c.id, users.c.display_name, users.c.email))).mappings()]
overrides = _duty_overrides()
@@ -1275,13 +1274,8 @@ def _duty_state():
@app.get("/api/duty/absences")
async def list_duty_absences(_viewer: dict = Depends(current_user), limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)):
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
if path.exists():
try:
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), load_schedule(path), datetime.now(BEIJING))
except (ValueError, KeyError, TypeError, OSError) as exc:
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset)}
# 兼容旧客户端读取历史数据,不再创建或补记任何缺勤记录。
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset), "recording_enabled": False}
@app.post("/api/auth/test-email")
@@ -1320,7 +1314,7 @@ async def test_button_email(payload: ButtonTestIn, viewer: dict = Depends(curren
token = await asyncio.to_thread(duty_receipts.create_button_test, _duty_state(), payload.kind, time.time())
label = '值班确认' if payload.kind == 'duty' else '活动参加'
url = _site_base_url() + '/mail-test/' + token
text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动、值班或缺勤记录。链接24小时内有效。\n{url}'
text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动和值班记录。链接24小时内有效。\n{url}'
html = f'<div style="font-family:sans-serif;line-height:1.8"><h2>{label}按钮测试</h2><p>仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;border-radius:8px;text-decoration:none">{label}(测试)</a></div>'
await _send_email(email, f'【WorkLog测试】{label}按钮', text, html)
return {'ok': True, 'retry_after': 120}
@@ -1342,7 +1336,7 @@ async def confirm_button_test(token: str, request: Request):
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce, 'mail-test'):
return HTMLResponse(_confirmation_page('请重新打开测试邮件,再点击确认。', title='邮件按钮测试'), status_code=403)
await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time(), True)
return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动、值班和缺勤记录未发生变化。', title=label + '测试'))
return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动和值班记录未发生变化。', title=label + '测试'))
class DutySiteConfirmIn(BaseModel):