Files
worklog/server/duty.py
T

201 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""单双周值班排程、邮箱解析与持久化提醒。时间统一为北京时间。"""
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")
before = data.get("before_minutes", 0)
if type(before) is not int or not 0 <= before <= 480:
raise ValueError("值班前提醒分钟数必须为 0–480")
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("值班姓名不能为空")
if before:
start = data["slot_times"][entry["slot"]]
if datetime.strptime(start, "%H:%M").strftime("%H:%M") != start:
raise ValueError("值班开始时间必须为 HH:MM")
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()
def due_batches(schedule, now):
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。"""
batches = []
anchor = date.fromisoformat(schedule["anchor_date"])
target = now.date() + timedelta(days=schedule["reminder_days_before"])
if target >= anchor and now.strftime("%H:%M") >= schedule["reminder_time"]:
week, assignments = duties_on(schedule, target)
# 沿用旧版日期键,保留已发晚间邮件的去重记录。
batches.append((target, week, assignments, target.isoformat(), "值班汇总提醒"))
before = schedule.get("before_minutes", 0)
if before and now.date() >= anchor:
week, assignments = duties_on(schedule, now.date())
for slot, clock in schedule["slot_times"].items():
start = datetime.combine(now.date(), datetime.strptime(clock, "%H:%M").time(), BEIJING)
if start - timedelta(minutes=before) <= now < start:
people = {name: [slot] for name, slots in assignments.items() if slot in slots}
key = f"{now.date().isoformat()}#before:{slot}"
batches.append((now.date(), week, people, key, f"值班前提醒({clock} 开始)"))
return batches
async def send_due(schedule, now, accounts, send_email, state_path, overrides=None):
result = {"sent": 0, "failed": 0, "missing": {}}
if not schedule["enabled"]:
return result
now = now.astimezone(BEIJING)
for target, week, assignments, key, label in due_batches(schedule, now):
recipients, missing = resolve_recipients(assignments, accounts, overrides)
result["missing"].update(missing)
for email, names in recipients.items():
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"
try:
await send_email(email, f"{label}|{target.isoformat()}", body)
except Exception:
result["failed"] += 1
await asyncio.to_thread(finish, state_path, key, email, "failed")
log.exception("值班邮件发送失败")
else:
result["sent"] += 1
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):
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()