支持清点修正和人数上限调整,优化邮件发送及上传文件清理

This commit is contained in:
2026-11-12 15:08:23 +08:00
parent ddf3ba32c6
commit 0dbb5063ec
6 changed files with 120 additions and 28 deletions
+78 -3
View File
@@ -2,6 +2,7 @@
import asyncio
import io
import json
import re
import time
import uuid
import warnings
@@ -14,7 +15,7 @@ from typing import Literal
from fastapi import Depends, HTTPException, Query, Request
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, func, text, or_
from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, activities, users
from .duty import BEIJING
@@ -59,11 +60,78 @@ class MaterialIn(BaseModel):
MAX_PHOTOS_PER_UPLOAD = 20
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
def now_ms(): return int(time.time() * 1000)
async def cleanup_orphan_uploads(db, root: Path, before_ms: int) -> tuple[int, int]:
"""Remove unlinked uploads after a grace period, preserving every referenced photo/package."""
materials = (await db.execute(select(center_materials))).mappings().all()
linked_ids = set((await db.execute(select(center_activity_materials.c.material_id))).scalars())
meta_materials = await db.execute(select(center_activity_meta.c.material_id))
linked_ids.update(row[0] for row in meta_materials.all() if row[0])
stale_materials = [row for row in materials if row['created_at'] < before_ms and row['id'] not in linked_ids]
stale_ids = {row['id'] for row in stale_materials}
if stale_ids:
await db.execute(delete(center_materials).where(center_materials.c.id.in_(stale_ids)))
# A photo is retained while any activity or any remaining material references it.
photo_refs = set()
for raw in (await db.execute(select(center_activity_meta.c.photo_ids))).scalars():
try:
photo_refs.update(json.loads(raw))
except (TypeError, ValueError):
continue
for raw in (await db.execute(select(center_materials.c.photo_ids))).scalars():
try:
photo_refs.update(json.loads(raw))
except (TypeError, ValueError):
continue
photo_rows = (await db.execute(select(center_photos).where(center_photos.c.created_at < before_ms))).mappings().all()
stale_photos = [row['id'] for row in photo_rows if row['id'] not in photo_refs]
if stale_photos:
await db.execute(delete(center_photos).where(center_photos.c.id.in_(stale_photos)))
known_materials = set((await db.execute(select(center_materials.c.id))).scalars())
known_photos = set((await db.execute(select(center_photos.c.id))).scalars())
await db.commit()
root.mkdir(parents=True, exist_ok=True)
for material_id in stale_ids:
(root / f'{material_id}.zip').unlink(missing_ok=True)
for photo_id in stale_photos:
if re.fullmatch(r'[0-9a-f]{32}', photo_id):
(root / f'{photo_id}.jpg').unlink(missing_ok=True)
# Also remove old files left behind if an earlier cleanup deleted database rows but
# could not unlink the files (for example, a temporary filesystem error).
for path in root.iterdir():
match = re.fullmatch(r'([0-9a-f]{32})\.(zip|jpg)', path.name)
if not match or match.group(1) in (known_materials if match.group(2) == 'zip' else known_photos):
continue
try:
if path.stat().st_mtime * 1000 < before_ms:
path.unlink(missing_ok=True)
except OSError:
continue
return len(stale_ids), len(stale_photos)
async def orphan_upload_cleanup_loop(session_factory, root_provider):
while True:
try:
async with session_factory() as db:
materials, photos = await cleanup_orphan_uploads(db, root_provider(), now_ms() - UPLOAD_ORPHAN_TTL_MS)
if materials or photos:
print(f'[uploads] 清理未关联文件包 {materials} 个、照片 {photos} 张', flush=True)
except asyncio.CancelledError:
raise
except Exception as exc:
print(f'[uploads] 清理未关联文件失败: {exc}', flush=True)
await asyncio.sleep(6 * 60 * 60)
def validate_photo_batch(ids, existing=()):
"""限制本次新增照片,历史照片不占本次额度。"""
if len(set(ids) - set(existing)) > MAX_PHOTOS_PER_UPLOAD:
@@ -218,6 +286,7 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
@app.get('/api/center/photos/{photo_id}')
async def photo(photo_id: str, db=Depends(get_db), viewer=Depends(current_user)):
if not re.fullmatch(r'[0-9a-f]{32}', photo_id): raise HTTPException(404, '照片不存在')
row = (await db.execute(select(center_photos).where(center_photos.c.id == photo_id))).mappings().first()
if not row: raise HTTPException(404, '照片不存在')
if row['owner_id'] != viewer['id']:
@@ -290,7 +359,9 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
async def stocktake(payload: CheckIn, db=Depends(get_db), viewer=Depends(current_user)):
await db.execute(text('BEGIN IMMEDIATE'))
day=datetime.now(BEIJING).date().isoformat()
if (await db.execute(select(center_checks.c.day).where(center_checks.c.day==day))).first():raise HTTPException(409,'今天已经完成清点,无需重复提交')
existing=(await db.execute(select(center_checks).where(center_checks.c.day==day))).mappings().first()
if existing and existing['user_id'] != viewer['id']:
raise HTTPException(409,'今天的清点已由其他成员提交,只有提交人可以修正')
rows=(await db.execute(select(center_items))).mappings().all()
if not rows or set(payload.quantities)!={r['id'] for r in rows}:raise HTTPException(422,'请逐项清点全部物品,物品列表如有变化请刷新')
used=dict((await db.execute(select(center_loans.c.item_id,func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved',center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
@@ -302,7 +373,11 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
if count!=expected and not payload.note.strip():raise HTTPException(422,'清点有差异,请填写说明')
details.append({'id':row['id'],'name':row['name'],'expected':expected,'actual':count,'borrowed':used.get(row['id'],0)})
await db.execute(update(center_items).where(center_items.c.id==row['id']).values(quantity=count+used.get(row['id'],0)))
await db.execute(insert(center_checks).values(day=day,user_id=viewer['id'],details=json.dumps(details,ensure_ascii=False),note=payload.note.strip(),created_at=now_ms()))
check_values = {'details':json.dumps(details,ensure_ascii=False),'note':payload.note.strip()}
if existing:
await db.execute(update(center_checks).where(center_checks.c.day==day,center_checks.c.user_id==viewer['id']).values(**check_values))
else:
await db.execute(insert(center_checks).values(day=day,user_id=viewer['id'],**check_values,created_at=now_ms()))
await db.commit();return {'ok':True,'day':day}
@app.get('/api/center/checks')
+30 -18
View File
@@ -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)