"""单双周值班排程、邮箱解析与持久化提醒。时间统一为北京时间。""" from __future__ import annotations import argparse import asyncio import json import logging import sqlite3 import time from collections import defaultdict from contextlib import closing from datetime import date, datetime, timedelta, timezone from pathlib import Path BEIJING = timezone(timedelta(hours=8)) log = logging.getLogger("worklog.duty") ROOT = Path(__file__).resolve().parent.parent def load_schedule(path): data = json.loads(Path(path).read_text(encoding="utf-8-sig")) if data.get("version") != 1 or type(data.get("enabled")) is not bool: raise ValueError("值班表版本或开关无效") date.fromisoformat(data["anchor_date"]) if data["anchor_week"] not in ("odd", "even"): raise ValueError("anchor_week 必须为 odd 或 even") parsed_time = datetime.strptime(data["reminder_time"], "%H:%M") if parsed_time.strftime("%H:%M") != data["reminder_time"]: raise ValueError("提醒时间必须为 HH:MM") if type(data["reminder_days_before"]) is not int or not 0 <= data["reminder_days_before"] <= 7: raise ValueError("提前提醒天数必须为 0–7") for week in ("odd", "even"): seen = set() for entry in data["weeks"][week]: if type(entry["weekday"]) is not int or entry["weekday"] not in range(1, 6): raise ValueError("星期必须为 1–5") if not isinstance(entry["slot"], str) or not entry["slot"].strip(): raise ValueError("节次不能为空") if (entry["weekday"], entry["slot"]) in seen: raise ValueError("同一周存在重复时段") seen.add((entry["weekday"], entry["slot"])) if not isinstance(entry["names"], list) or not entry["names"] or any(not isinstance(n, str) or not n.strip() for n in entry["names"]): raise ValueError("值班姓名不能为空") return data def duties_on(schedule, day): anchor = date.fromisoformat(schedule["anchor_date"]) monday = anchor - timedelta(days=anchor.weekday()) offset = (day - monday).days // 7 week = schedule["anchor_week"] if offset % 2: week = "even" if week == "odd" else "odd" assignments = defaultdict(list) for entry in schedule["weeks"][week]: if entry["weekday"] == day.isoweekday(): for name in entry["names"]: if entry["slot"] not in assignments[name.strip()]: assignments[name.strip()].append(entry["slot"]) return week, dict(assignments) def resolve_recipients(assignments, accounts, overrides=None): """姓名须唯一匹配;额外邮箱映射只从本机文件读取,不模糊匹配。""" overrides = overrides or {} recipients, missing = {}, {} for name, slots in assignments.items(): matches = [a for a in accounts if a["display_name"].strip() == name] if overrides.get(name): email = overrides[name] elif len(matches) != 1: missing[name] = "未找到账号" if not matches else "同名账号不唯一" continue else: email = matches[0]["email"] if not isinstance(email, str) or "@" not in email or any(c.isspace() for c in email): missing[name] = "邮箱无效或为空" continue email = email.strip().lower() recipient = recipients.setdefault(email, {}) recipient[name] = slots return recipients, missing 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: con.execute("CREATE TABLE IF NOT EXISTS deliveries (day TEXT, email TEXT, status TEXT, attempts INTEGER, updated REAL, PRIMARY KEY(day,email))") con.execute("BEGIN IMMEDIATE") row = con.execute("SELECT status,attempts,updated FROM deliveries WHERE day=? AND email=?", (day, email)).fetchone() if row and (row[0] == "sent" or row[1] >= 3 or now - row[2] < 900): con.rollback() return False if row: con.execute("UPDATE deliveries SET status='sending', attempts=attempts+1, updated=? WHERE day=? AND email=?", (now, day, email)) else: con.execute("INSERT INTO deliveries VALUES (?,?,'sending',1,?)", (day, email, now)) con.commit() return True def finish(state_path, day, email, status): with closing(sqlite3.connect(state_path, timeout=10)) as con: con.execute("UPDATE deliveries SET status=?,updated=? WHERE day=? AND email=?", (status, time.time(), day, email)) con.commit() async def send_due(schedule, now, accounts, send_email, state_path, overrides=None): if not schedule["enabled"]: return {"sent": 0, "failed": 0, "missing": {}} now = now.astimezone(BEIJING) target = now.date() + timedelta(days=schedule["reminder_days_before"]) if target < date.fromisoformat(schedule["anchor_date"]) or now.strftime("%H:%M") < schedule["reminder_time"]: return {"sent": 0, "failed": 0, "missing": {}} week, assignments = duties_on(schedule, target) recipients, missing = resolve_recipients(assignments, accounts, overrides) result = {"sent": 0, "failed": 0, "missing": missing} for email, names in recipients.items(): if not await asyncio.to_thread(claim, state_path, target.isoformat(), email, now.timestamp()): continue lines = [f"{name}:{'、'.join(slots)}" for name, slots in names.items()] body = f"值班提醒\n\n日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "\n".join(lines) + "\n\n请按节次准时值班;如需调班,请提前联系值班负责人。\nWorkLog" try: await send_email(email, f"值班提醒|{target.isoformat()}", body) except Exception: result["failed"] += 1 await asyncio.to_thread(finish, state_path, target.isoformat(), email, "failed") log.exception("值班邮件发送失败") else: result["sent"] += 1 await asyncio.to_thread(finish, state_path, target.isoformat(), email, "sent") return result async def reminder_loop(schedule_path, state_path, get_accounts, send_email, overrides_path=None): 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) if result["missing"] and result["missing"] != previous_missing: log.warning("值班名单无法匹配邮箱:%s", result["missing"]) previous_missing = result["missing"] if result["sent"] or result["failed"]: log.info("值班提醒:成功 %s,失败 %s", result["sent"], result["failed"]) except asyncio.CancelledError: raise except Exception: log.exception("值班提醒检查失败,将于一分钟后重试") await asyncio.sleep(60) def main(): parser = argparse.ArgumentParser(description="预览值班名单及邮箱匹配,不发送邮件") parser.add_argument("--date", default=datetime.now(BEIJING).date().isoformat()) parser.add_argument("--schedule", default=str(ROOT / "duty/schedule.json")) parser.add_argument("--db", default=str(ROOT / "data/worklog.db")) parser.add_argument("--emails", help="本机姓名到邮箱的 JSON 映射") args = parser.parse_args() schedule = load_schedule(args.schedule) week, assignments = duties_on(schedule, date.fromisoformat(args.date)) with closing(sqlite3.connect(Path(args.db).resolve().as_uri() + "?mode=ro", uri=True)) as con: con.row_factory = sqlite3.Row accounts = [dict(r) for r in con.execute("SELECT display_name,email FROM users")] overrides = json.loads(Path(args.emails).read_text(encoding="utf-8-sig")) if args.emails else {} recipients, missing = resolve_recipients(assignments, accounts, overrides) print(json.dumps({"date": args.date, "week": week, "enabled": schedule["enabled"], "assignments": assignments, "matched_people": sum(map(len, recipients.values())), "missing": missing}, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()