feat: remind duty students one hour before each shift
This commit is contained in:
+50
-23
@@ -29,6 +29,9 @@ def load_schedule(path):
|
||||
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]:
|
||||
@@ -41,6 +44,10 @@ def load_schedule(path):
|
||||
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
|
||||
|
||||
|
||||
@@ -105,30 +112,50 @@ def finish(state_path, day, email, status):
|
||||
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)
|
||||
def due_batches(schedule, now):
|
||||
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。"""
|
||||
batches = []
|
||||
anchor = date.fromisoformat(schedule["anchor_date"])
|
||||
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")
|
||||
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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user