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

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')