"""值班提醒回执;独立 SQLite 保存每人每轮的发送次数和确认状态。""" import hashlib import json import secrets import sqlite3 import time from contextlib import closing from html import escape from datetime import date, datetime, timedelta 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)") 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 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 confirm_on_site(path, day, slot, name, email, now, end_at): if now >= end_at: return None with closing(connect(path)) as con: con.execute("BEGIN IMMEDIATE") ensure(con, day, slot, name, email) 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)) confirmed = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()[0] con.commit() return int(confirmed * 1000) def issue_confirmation_form(path, token, now): with closing(connect(path)) as con: digest = hashlib.sha256(token.encode()).hexdigest() row = con.execute("SELECT expires FROM duty_confirmations WHERE digest=?", (digest,)).fetchone() if row is None or row[0] <= now: return None nonce = secrets.token_urlsafe(32) con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest())) con.commit() return nonce def issue_activity_form(path, token, namespace='activity'): digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest() nonce = secrets.token_urlsafe(32) with closing(connect(path)) as con: con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest())) con.commit() return nonce def validate_activity_form(path, token, nonce, namespace='activity'): if not nonce: return False digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest() with closing(connect(path)) as con: row = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (digest,)).fetchone() return bool(row and secrets.compare_digest(row[0], hashlib.sha256(nonce.encode()).hexdigest())) def confirmation(path, token, now, consume=False, form_token=None, require_form=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 if consume and require_form: form = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone() if form is None or not form_token or not secrets.compare_digest(form[0], hashlib.sha256(form_token.encode()).hexdigest()): 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 def create_button_test(path, kind, now): token = secrets.token_urlsafe(32) with closing(connect(path)) as con: con.execute("INSERT INTO mail_button_tests(digest,kind,expires) VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), kind, now + 86400)) con.commit() return token def button_test(path, token, now, consume=False): digest = hashlib.sha256(token.encode()).hexdigest() with closing(connect(path)) as con: row = con.execute("SELECT * FROM mail_button_tests WHERE digest=? AND expires>?", (digest, now)).fetchone() if not row: return None if consume: con.execute("UPDATE mail_button_tests SET confirmed=CASE WHEN confirmed=0 THEN ? ELSE confirmed END WHERE digest=?", (now, digest)) con.commit() 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: 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] 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(body).replace(chr(10), "
")}
{escape(details).replace(chr(10), "
")}
打开后请在页面中确认。WorkLog