重构共享逻辑并修复值班提醒回执去重

This commit is contained in:
2026-11-22 14:32:13 +08:00
parent 2fb2c5e1ad
commit 982f0df41c
35 changed files with 2345 additions and 571 deletions
+53 -30
View File
@@ -12,15 +12,43 @@ 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")
@@ -53,13 +81,18 @@ def load_schedule(path):
return data
def duties_on(schedule, day):
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():
@@ -82,7 +115,7 @@ def resolve_recipients(assignments, accounts, overrides=None):
continue
else:
email = matches[0]["email"]
if not isinstance(email, str) or "@" not in email or any(c.isspace() for c in email):
if not valid_email(email):
missing[name] = "邮箱无效或为空"
continue
email = email.strip().lower()
@@ -94,7 +127,14 @@ def resolve_recipients(assignments, accounts, overrides=None):
def duty_status(schedule, now):
"""活动墙只返回排班姓名和时间,不暴露邮箱等联系方式。"""
now = now.astimezone(BEIJING)
result = {"server_now": int(now.timestamp() * 1000), "enabled": schedule["enabled"], "current": None, "next": None}
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"])
@@ -124,37 +164,18 @@ def duty_status(schedule, now):
return result
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):
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。"""
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。
第三项 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:
@@ -183,9 +204,11 @@ async def send_due(schedule, now, accounts, send_email, state_path, overrides=No
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]
body = f"日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "、".join(f"{slot} {clocks[slot]} 开始" for slot in sorted(slots)) + "\n以上时间均为北京时间。请准时值班。"
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, target.isoformat(), names, email, max(ends).timestamp(), send_email, f"{label}|{target.isoformat()}", body, base_url, now.timestamp())
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")