Files

261 lines
13 KiB
Python
Raw Permalink 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
from .security import valid_email
BEIJING = timezone(timedelta(hours=8))
log = logging.getLogger("worklog.duty")
ROOT = Path(__file__).resolve().parent.parent
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 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("值班表版本或开关无效")
for key in ("title", "organization"):
if key in data and (not isinstance(data[key], str) or not data[key].strip()):
raise ValueError(f"{key} 不能为空")
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")
if type(data.get("duration_minutes", 105)) is not int or not 1 <= data.get("duration_minutes", 105) <= 1440:
raise ValueError("每轮值班时长必须为 1–1440 分钟")
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 week_type_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"
return week
def duties_on(schedule, day):
week = week_type_on(schedule, day)
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 valid_email(email):
missing[name] = "邮箱无效或为空"
continue
email = email.strip().lower()
recipient = recipients.setdefault(email, {})
recipient[name] = slots
return recipients, missing
def duty_status(schedule, now):
"""活动墙只返回排班姓名和时间,不暴露邮箱等联系方式。"""
now = now.astimezone(BEIJING)
result = {
"server_now": int(now.timestamp() * 1000),
"enabled": schedule["enabled"],
"title": schedule.get("title", "值班安排"),
"organization": schedule.get("organization", ""),
"current": None,
"next": None,
}
if not schedule["enabled"]:
return result
anchor = date.fromisoformat(schedule["anchor_date"])
first = max(now.date(), anchor)
for offset in range(15):
day = first + timedelta(days=offset)
week, assignments = duties_on(schedule, day)
grouped = defaultdict(list)
for name, slots in assignments.items():
for slot in slots:
grouped[slot].append(name)
shifts = []
for slot, names in grouped.items():
clock = schedule.get("slot_times", {}).get(slot)
if not clock:
continue
start = datetime.combine(day, datetime.strptime(clock, "%H:%M").time(), BEIJING)
end = start + timedelta(minutes=schedule.get("duration_minutes", 105))
shifts.append((start, end, slot, names))
for start, end, slot, names in sorted(shifts):
shift = {"slot": slot, "names": names, "week": week, "start_at": int(start.timestamp() * 1000), "end_at": int(end.timestamp() * 1000)}
if start <= now < end:
result["current"] = shift
elif start > now:
result["next"] = shift
return result
return result
def due_batches(schedule, now):
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。
第三项 key 是发给回执层的日期键:晚间汇总沿用旧版纯日期,
值班前提醒使用 ``日期#before:节次``,因此同一天的多个节次可以
各自去重,而不会互相吞掉。
"""
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, 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
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", {})
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]
organization = schedule.get("organization", "招生就业服务队")
body = f"机构:{organization}\n日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "、".join(f"{slot} {clocks[slot]} 开始" for slot in sorted(slots)) + "\n以上时间均为北京时间。请准时值班。"
subject = f"{schedule.get('title', organization + '值班')}|{label}|{target.isoformat()}"
try:
sent = await send_notice(state_path, key, names, email, max(ends).timestamp(), send_email, subject, 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"] += 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, 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, base_url)
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()