支持清点修正和人数上限调整,优化邮件发送及上传文件清理
This commit is contained in:
+30
-18
@@ -605,6 +605,9 @@ async def lifespan(_app: FastAPI):
|
||||
hour, minute = parse_time(BACKUP_TIME)
|
||||
backup_task = asyncio.create_task(backup_loop(_db_path, hour, minute, BACKUP_KEEP))
|
||||
duty_task: asyncio.Task | None = None
|
||||
upload_cleanup_task = asyncio.create_task(
|
||||
center.orphan_upload_cleanup_loop(SessionLocal, lambda: _db_path.parent / 'uploads')
|
||||
)
|
||||
duty_path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json")))
|
||||
if duty_path.exists() and os.getenv("WORKLOG_DUTY_REMINDERS", "1").lower() not in ("0", "false", "no"):
|
||||
async def duty_accounts():
|
||||
@@ -623,6 +626,8 @@ async def lifespan(_app: FastAPI):
|
||||
if duty_task is not None:
|
||||
duty_task.cancel()
|
||||
await asyncio.gather(duty_task, return_exceptions=True)
|
||||
upload_cleanup_task.cancel()
|
||||
await asyncio.gather(upload_cleanup_task, return_exceptions=True)
|
||||
if backup_task is not None:
|
||||
backup_task.cancel()
|
||||
await engine.dispose()
|
||||
@@ -881,8 +886,7 @@ def _site_base_url(request: Request | None = None) -> str:
|
||||
|
||||
|
||||
async def _notify_new_activity(activity_id: str, organizer_name: str, base_url: str) -> None:
|
||||
"""给除发起人外的所有已注册用户发新活动通知。发信在后台任务里逐个进行,
|
||||
单个失败只打日志,不影响活动创建,也不阻塞 API 响应。"""
|
||||
"""给其他已注册用户通知新活动;最多同时发送3封,单封失败不影响其他收件人。"""
|
||||
from .models import join_links # noqa: F401 (保证模块已被导入)
|
||||
|
||||
async with SessionLocal() as db:
|
||||
@@ -902,26 +906,33 @@ async def _notify_new_activity(activity_id: str, organizer_name: str, base_url:
|
||||
).all()
|
||||
|
||||
portal = f"{base_url}/"
|
||||
ok = failed = 0
|
||||
messages = []
|
||||
for user_id, email, _name in recipients:
|
||||
token = new_token()
|
||||
await db.execute(
|
||||
insert(join_links).values(
|
||||
messages.append((email, token, f"【WorkLog】{organizer_name} 发起了新活动:{row['title']}"))
|
||||
await db.execute(insert(join_links).values(
|
||||
id=new_id(), token=token_digest(token), activity_id=activity_id, user_id=user_id,
|
||||
expires_at=now_ms() + JOIN_LINK_DAYS * 86_400_000,
|
||||
used=0, created_at=now_ms(),
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
join_url = f"{base_url}/join/{token}"
|
||||
html = _notify_mail_html(organizer_name, row, join_url, portal)
|
||||
plain = _notify_mail_text(organizer_name, row, join_url, portal)
|
||||
try:
|
||||
await _send_email(email, f"【WorkLog】{organizer_name} 发起了新活动:{row['title']}", plain, html)
|
||||
ok += 1
|
||||
except Exception as exc: # 通知失败不影响活动本身,细节已由 maillog 记录
|
||||
failed += 1
|
||||
print(f"[notify] 发送失败 to={email}: {exc}", flush=True)
|
||||
))
|
||||
await db.commit()
|
||||
|
||||
semaphore = asyncio.Semaphore(3)
|
||||
async def send_one(email: str, token: str, subject: str) -> bool:
|
||||
async with semaphore:
|
||||
join_url = f"{base_url}/join/{token}"
|
||||
html = _notify_mail_html(organizer_name, row, join_url, portal)
|
||||
plain = _notify_mail_text(organizer_name, row, join_url, portal)
|
||||
try:
|
||||
await _send_email(email, subject, plain, html)
|
||||
return True
|
||||
except Exception as exc:
|
||||
print(f"[notify] 发送失败 to={email}: {exc}", flush=True)
|
||||
return False
|
||||
|
||||
results = await asyncio.gather(*(send_one(*message) for message in messages))
|
||||
ok = sum(results)
|
||||
failed = len(results) - ok
|
||||
# 顺手清掉过期的旧链接
|
||||
await db.execute(delete(join_links).where(join_links.c.expires_at < now_ms()))
|
||||
await db.commit()
|
||||
@@ -1747,7 +1758,8 @@ async def update_activity(
|
||||
row = await fetch_activity(db, activity_id)
|
||||
if row["organizer_id"] != viewer["id"]:
|
||||
raise HTTPException(status_code=403, detail="只有发起人可以修改该活动")
|
||||
changes = {k: v for k, v in payload.model_dump(exclude_unset=True).items() if v is not None}
|
||||
provided = payload.model_dump(exclude_unset=True)
|
||||
changes = {k: v for k, v in provided.items() if v is not None or k == 'capacity'}
|
||||
old_meta = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))).mappings().first()
|
||||
kind = changes.pop('record_type', 'center' if old_meta else 'normal')
|
||||
material_id = changes.pop('material_id', old_meta['material_id'] if old_meta else None)
|
||||
|
||||
Reference in New Issue
Block a user