物品借出免审批并扩大上传限制
This commit is contained in:
+23
-37
@@ -49,17 +49,17 @@ class CheckIn(BaseModel):
|
||||
note: str = Field(default='', max_length=1000)
|
||||
|
||||
|
||||
class ReviewIn(BaseModel):
|
||||
action: Literal['approve', 'reject']
|
||||
note: str = Field(default='', max_length=500)
|
||||
|
||||
|
||||
class MaterialIn(BaseModel):
|
||||
material_id: str | None = Field(default=None, min_length=32, max_length=32)
|
||||
photo_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
MAX_PHOTOS_PER_UPLOAD = 20
|
||||
MAX_PHOTOS_PER_UPLOAD = 50
|
||||
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||
MAX_ZIP_BYTES = 100 * 1024 * 1024
|
||||
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
|
||||
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
|
||||
DAILY_PHOTO_LIMIT = 1000
|
||||
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ async def orphan_upload_cleanup_loop(session_factory, root_provider):
|
||||
def validate_photo_batch(ids, existing=()):
|
||||
"""限制本次新增照片,历史照片不占本次额度。"""
|
||||
if len(set(ids) - set(existing)) > MAX_PHOTOS_PER_UPLOAD:
|
||||
raise HTTPException(422, '每次最多上传20张照片(含ZIP内照片)')
|
||||
raise HTTPException(422, f'每次最多上传{MAX_PHOTOS_PER_UPLOAD}张照片(含ZIP内照片)')
|
||||
|
||||
|
||||
async def validate_photos(db, ids, owner_id, existing=(), allow_empty=False):
|
||||
@@ -205,7 +205,7 @@ def convert_package(raw):
|
||||
allowed={'.jpg','.jpeg','.png','.webp','.pdf','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.txt','.csv','.md'}
|
||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||
entries=archive.infolist()
|
||||
if sum(e.file_size for e in entries)>100*1024*1024:raise ValueError('ZIP展开后不超过100MB')
|
||||
if sum(e.file_size for e in entries)>MAX_ZIP_EXPANDED_BYTES:raise ValueError(f'ZIP展开后不超过{MAX_ZIP_EXPANDED_BYTES // 1024 // 1024}MB')
|
||||
for entry in entries:
|
||||
name=entry.filename.replace('\\','/');path=PurePosixPath(name)
|
||||
if path.is_absolute() or '..' in path.parts or ':' in name or '\x00' in name or ((entry.external_attr>>16)&0o170000)==0o120000:raise ValueError('ZIP包含不安全路径或链接')
|
||||
@@ -216,25 +216,22 @@ def convert_package(raw):
|
||||
if name.startswith('__MACOSX/') or path.name=='.DS_Store':continue
|
||||
if path.suffix.lower() not in allowed:raise ValueError('ZIP只支持图片、PDF、Office文档和文本材料')
|
||||
file_count += 1
|
||||
if entry.file_size>20*1024*1024:raise ValueError('包内单个文档不超过20MB')
|
||||
if entry.file_size>MAX_ZIP_ENTRY_BYTES:raise ValueError(f'包内单个文档不超过{MAX_ZIP_ENTRY_BYTES // 1024 // 1024}MB')
|
||||
if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}:
|
||||
if len(photos) >= MAX_PHOTOS_PER_UPLOAD:raise ValueError('每次最多上传20张照片(含ZIP内照片)')
|
||||
if entry.file_size>8*1024*1024:raise ValueError('包内单张照片不超过8MB')
|
||||
if len(photos) >= MAX_PHOTOS_PER_UPLOAD:raise ValueError(f'每次最多上传{MAX_PHOTOS_PER_UPLOAD}张照片(含ZIP内照片)')
|
||||
if entry.file_size>MAX_PHOTO_BYTES:raise ValueError(f'包内单张照片不超过{MAX_PHOTO_BYTES // 1024 // 1024}MB')
|
||||
photos.append(convert_photo(archive.read(entry)))
|
||||
if not file_count:raise ValueError('ZIP附件不能为空')
|
||||
return photos
|
||||
|
||||
|
||||
def install(app, get_db, current_user, photo_root, visible_clause, approver_emails):
|
||||
def can_review(viewer):
|
||||
return viewer.get('email', '').strip().lower() in approver_emails()
|
||||
|
||||
def install(app, get_db, current_user, photo_root, visible_clause):
|
||||
@app.post('/api/center/materials')
|
||||
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
|
||||
raw=bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw.extend(chunk)
|
||||
if len(raw)>30*1024*1024:raise HTTPException(413,'ZIP材料包最大30MB')
|
||||
if len(raw)>MAX_ZIP_BYTES:raise HTTPException(413,f'ZIP材料包最大{MAX_ZIP_BYTES // 1024 // 1024}MB')
|
||||
try:photos=await asyncio.to_thread(convert_package,bytes(raw))
|
||||
except Exception as exc:raise HTTPException(422,str(exc) if isinstance(exc,ValueError) else 'ZIP材料包无效或损坏') from exc
|
||||
key=uuid.uuid4().hex;folder=photo_root();folder.mkdir(parents=True,exist_ok=True);paths=[];ids=[]
|
||||
@@ -268,9 +265,9 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw.extend(chunk)
|
||||
if len(raw) > 8 * 1024 * 1024: raise HTTPException(413, '每张照片最大8MB')
|
||||
if len(raw) > MAX_PHOTO_BYTES: raise HTTPException(413, f'每张照片最大{MAX_PHOTO_BYTES // 1024 // 1024}MB')
|
||||
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
|
||||
if count >= 1000: raise HTTPException(429, '今日照片上传已达1000张')
|
||||
if count >= DAILY_PHOTO_LIMIT: raise HTTPException(429, f'今日照片上传已达{DAILY_PHOTO_LIMIT}张')
|
||||
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
|
||||
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP,最大24百万像素') from exc
|
||||
key = uuid.uuid4().hex
|
||||
@@ -303,7 +300,7 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
|
||||
borrowed = 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())
|
||||
day = datetime.now(BEIJING).date().isoformat()
|
||||
check = (await db.execute(select(center_checks).where(center_checks.c.day == day))).mappings().first()
|
||||
return {'items': [{**r, 'borrowed': borrowed.get(r['id'], 0), 'available': r['quantity']-borrowed.get(r['id'],0)} for r in rows], 'day': day, 'checked_today': bool(check), 'check': dict(check) if check else None, 'can_review': can_review(viewer), 'approval_configured': bool(approver_emails())}
|
||||
return {'items': [{**r, 'borrowed': borrowed.get(r['id'], 0), 'available': r['quantity']-borrowed.get(r['id'],0)} for r in rows], 'day': day, 'checked_today': bool(check), 'check': dict(check) if check else None}
|
||||
|
||||
@app.post('/api/center/items')
|
||||
async def add_item(payload: ItemIn, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
@@ -319,31 +316,20 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
|
||||
used=(await db.execute(select(func.coalesce(func.sum(center_loans.c.quantity),0)).where(center_loans.c.item_id==item_id, center_loans.c.status=='approved', center_loans.c.returned_at.is_(None)))).scalar()
|
||||
if payload.quantity > item['quantity']-used: raise HTTPException(409,'可借数量不足,请刷新')
|
||||
key=uuid.uuid4().hex
|
||||
await db.execute(insert(center_loans).values(id=key,item_id=item_id,user_id=viewer['id'],**payload.model_dump(),created_at=now_ms()))
|
||||
await db.commit(); return {'id':key}
|
||||
await db.execute(insert(center_loans).values(
|
||||
id=key,item_id=item_id,user_id=viewer['id'],**payload.model_dump(),
|
||||
status='approved',created_at=now_ms()
|
||||
))
|
||||
await db.commit(); return {'id':key,'status':'approved'}
|
||||
|
||||
@app.get('/api/center/loans')
|
||||
async def loans(status: str='all', db=Depends(get_db), viewer=Depends(current_user)):
|
||||
stmt=select(center_loans,center_items.c.name.label('item_name'),users.c.display_name).select_from(center_loans).join(center_items,center_items.c.id==center_loans.c.item_id).join(users,users.c.id==center_loans.c.user_id)
|
||||
if status=='borrowed':stmt=stmt.where(center_loans.c.status=='approved')
|
||||
elif status in ('pending','returned','rejected'):stmt=stmt.where(center_loans.c.status==status)
|
||||
elif status=='returned':stmt=stmt.where(center_loans.c.status==status)
|
||||
elif status!='all':raise HTTPException(422,'无效借用状态')
|
||||
rows=(await db.execute(stmt.order_by(center_loans.c.created_at.desc()).limit(200))).mappings().all()
|
||||
return {'items':[{**r,'contact':r['contact'] if can_review(viewer) or r['user_id']==viewer['id'] else None} for r in rows]}
|
||||
|
||||
@app.post('/api/center/loans/{loan_id}/review')
|
||||
async def review(loan_id: str, payload: ReviewIn, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
if not can_review(viewer):raise HTTPException(403,'仅负责人可审批借出申请')
|
||||
await db.execute(text('BEGIN IMMEDIATE'))
|
||||
row=(await db.execute(select(center_loans).where(center_loans.c.id==loan_id))).mappings().first()
|
||||
if not row:raise HTTPException(404,'借用申请不存在')
|
||||
if row['status']!='pending':raise HTTPException(409,'申请已处理,请刷新')
|
||||
if payload.action=='approve':
|
||||
total=(await db.execute(select(center_items.c.quantity).where(center_items.c.id==row['item_id']))).scalar()
|
||||
used=(await db.execute(select(func.coalesce(func.sum(center_loans.c.quantity),0)).where(center_loans.c.item_id==row['item_id'],center_loans.c.status=='approved'))).scalar()
|
||||
if row['quantity']>total-used:raise HTTPException(409,'可借数量不足,无法批准')
|
||||
await db.execute(update(center_loans).where(center_loans.c.id==loan_id).values(status='approved' if payload.action=='approve' else 'rejected',reviewer_id=viewer['id'],reviewed_at=now_ms(),review_note=payload.note.strip()))
|
||||
await db.commit();return {'ok':True}
|
||||
return {'items':[{**r,'contact':r['contact'] if r['user_id']==viewer['id'] else None} for r in rows]}
|
||||
|
||||
@app.post('/api/center/loans/{loan_id}/return')
|
||||
async def return_item(loan_id: str, db=Depends(get_db), viewer=Depends(current_user)):
|
||||
|
||||
Reference in New Issue
Block a user