"""赋能中心一楼:照片、物品、每日清点与借还。""" import asyncio import io import json import time import uuid import warnings import zipfile from pathlib import PurePosixPath from datetime import datetime from pathlib import Path 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 from .models import center_photos, center_materials, center_activity_meta, center_items, center_loans, center_checks, activities, users from .duty import BEIJING class ItemIn(BaseModel): name: str = Field(min_length=1, max_length=100) quantity: int = Field(ge=0, le=100000) @field_validator('name') @classmethod def clean_name(cls, value): if not value.strip(): raise ValueError('物品名称不能为空') return value.strip() class LoanIn(BaseModel): quantity: int = Field(ge=1, le=100000) reason: str = Field(min_length=1, max_length=500) contact: str = Field(min_length=1, max_length=200) @field_validator('reason', 'contact') @classmethod def required_text(cls, value): if not value.strip(): raise ValueError('申请理由和联系方式不能为空') return value.strip() class CheckIn(BaseModel): quantities: dict[str, int] note: str = Field(default='', max_length=1000) class ReviewIn(BaseModel): action: Literal['approve', 'reject'] note: str = Field(default='', max_length=500) def now_ms(): return int(time.time() * 1000) async def validate_photos(db, ids, owner_id, existing=()): if not 1 <= len(ids) <= 5 or len(set(ids)) != len(ids): raise HTTPException(422, '一楼活动须上传1至5张照片,照片不能重复') rows = (await db.execute(select(center_photos).where(center_photos.c.id.in_(ids)))).mappings().all() if len(rows) != len(ids) or any(r['owner_id'] != owner_id and r['id'] not in existing for r in rows): raise HTTPException(403, '照片不存在或不属于当前账号') async def save_meta(db, activity_id, kind, photo_ids, owner_id, material_id=None): if kind != 'center': return await validate_photos(db, photo_ids, owner_id) await db.execute(insert(center_activity_meta).values(activity_id=activity_id, photo_ids=json.dumps(photo_ids),material_id=material_id)) async def material_photos(db, material_id, owner_id): row = (await db.execute(select(center_materials).where(center_materials.c.id==material_id))).mappings().first() if not row or row['owner_id']!=owner_id:raise HTTPException(403,'材料包不存在或不属于当前账号') return json.loads(row['photo_ids']) def convert_photo(raw): from PIL import Image, ImageOps with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) with Image.open(io.BytesIO(raw)) as image: if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 24000000: raise ValueError('仅支持24百万像素以内的JPG、PNG、WebP照片') image = ImageOps.exif_transpose(image).convert('RGB') image.thumbnail((2400, 2400)) output = io.BytesIO(); image.save(output, 'JPEG', quality=85) return output.getvalue() def convert_package(raw): photos=[];names=set() 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 len(entries)>100 or sum(e.file_size for e in entries)>100*1024*1024:raise ValueError('ZIP最多100项,展开后不超过100MB') 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包含不安全路径或链接') if entry.flag_bits&1:raise ValueError('不支持加密ZIP') if name in names:raise ValueError('ZIP中存在重复文件名') names.add(name) if entry.is_dir():continue if name.startswith('__MACOSX/') or path.name=='.DS_Store':continue if path.suffix.lower() not in allowed:raise ValueError('ZIP只支持图片、PDF、Office文档和文本材料') if entry.file_size>20*1024*1024:raise ValueError('包内单个文档不超过20MB') if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}: if entry.file_size>8*1024*1024:raise ValueError('包内单张照片不超过8MB') photos.append(convert_photo(archive.read(entry))) if len(photos)>5:raise ValueError('ZIP内最多5张活动照片') if not photos:raise ValueError('ZIP内至少需要1张JPG、PNG或WebP活动照片') 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() @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') 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>=100:raise HTTPException(429,'今日照片上传已达上限') 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 if count+len(photos)>100:raise HTTPException(429,'材料包中的照片超过今日上传上限') key=uuid.uuid4().hex;folder=photo_root();folder.mkdir(parents=True,exist_ok=True);paths=[];ids=[] try: package=folder/(key+'.zip');paths.append(package);await asyncio.to_thread(package.write_bytes,bytes(raw)) for photo in photos: photo_id=uuid.uuid4().hex;path=folder/(photo_id+'.jpg');paths.append(path);ids.append(photo_id) await asyncio.to_thread(path.write_bytes,photo) await db.execute(insert(center_photos).values(id=photo_id,owner_id=viewer['id'],created_at=now_ms())) await db.execute(insert(center_materials).values(id=key,owner_id=viewer['id'],photo_ids=json.dumps(ids),created_at=now_ms())) await db.commit() except Exception: await db.rollback() for path in paths:path.unlink(missing_ok=True) raise return {'id':key,'photo_ids':ids} @app.get('/api/center/materials/{material_id}') async def material(material_id:str,db=Depends(get_db),viewer=Depends(current_user)): row=(await db.execute(select(center_materials).where(center_materials.c.id==material_id))).mappings().first() if not row:raise HTTPException(404,'材料包不存在') if row['owner_id']!=viewer['id']: allowed=(await db.execute(select(activities.c.id).join(center_activity_meta).where(visible_clause(viewer['id']),center_activity_meta.c.material_id==material_id))).first() if not allowed:raise HTTPException(403,'无权下载此材料包') path=photo_root()/(row['id']+'.zip') if not path.is_file():raise HTTPException(404,'材料包文件不存在') return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip') @app.post('/api/center/photos') async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)): raw = bytearray() async for chunk in request.stream(): raw.extend(chunk) if len(raw) > 8 * 1024 * 1024: raise HTTPException(413, '每张照片最大8MB') 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 >= 100: raise HTTPException(429, '今日照片上传已达100张') 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 folder = photo_root(); folder.mkdir(parents=True, exist_ok=True) path = folder / (key + '.jpg') await asyncio.to_thread(path.write_bytes, data) try: await db.execute(insert(center_photos).values(id=key, owner_id=viewer['id'], created_at=now_ms())) await db.commit() except Exception: path.unlink(missing_ok=True); raise return {'id': key} @app.get('/api/center/photos/{photo_id}') async def photo(photo_id: str, db=Depends(get_db), viewer=Depends(current_user)): 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']: allowed = (await db.execute(select(activities.c.id).join(center_activity_meta).where(visible_clause(viewer['id']), center_activity_meta.c.photo_ids.like('%"' + photo_id + '"%')))).first() if not allowed: raise HTTPException(403, '无权查看此照片') path = photo_root() / (row['id'] + '.jpg') if not path.is_file(): raise HTTPException(404, '照片文件不存在') return FileResponse(path, media_type='image/jpeg') @app.get('/api/center/items') async def items(q: str = '', db=Depends(get_db), viewer=Depends(current_user)): rows = (await db.execute(select(center_items).where(center_items.c.name.like('%'+q.strip()+'%')).order_by(center_items.c.name))).mappings().all() 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())} @app.post('/api/center/items') async def add_item(payload: ItemIn, db=Depends(get_db), viewer=Depends(current_user)): key=uuid.uuid4().hex await db.execute(insert(center_items).values(id=key, **payload.model_dump(), created_at=now_ms())); await db.commit() return {'id': key} @app.post('/api/center/items/{item_id}/loans') async def borrow(item_id: str, payload: LoanIn, db=Depends(get_db), viewer=Depends(current_user)): await db.execute(text('BEGIN IMMEDIATE')) item=(await db.execute(select(center_items).where(center_items.c.id==item_id))).mappings().first() if not item: raise HTTPException(404,'物品不存在') 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} @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!='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} @app.post('/api/center/loans/{loan_id}/return') async def return_item(loan_id: str, db=Depends(get_db), viewer=Depends(current_user)): row=(await db.execute(select(center_loans).where(center_loans.c.id==loan_id))).mappings().first() if not row:raise HTTPException(404,'借用记录不存在') if row['user_id']!=viewer['id']:raise HTTPException(403,'仅借用人可以登记归还') if row['status']=='returned':return {'ok':True} if row['status']!='approved':raise HTTPException(409,'仅已批准的借用可归还') await db.execute(update(center_loans).where(center_loans.c.id==loan_id,center_loans.c.returned_at.is_(None)).values(returned_at=now_ms(),status='returned')) await db.commit(); return {'ok':True} @app.post('/api/center/checks') 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,'今天已经完成清点,无需重复提交') 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()) details=[] for row in rows: count=payload.quantities[row['id']] if type(count) is not int or not 0<=count<=100000:raise HTTPException(422,'实点在库数量必须为非负整数') expected=row['quantity']-used.get(row['id'],0) 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())) await db.commit();return {'ok':True,'day':day} @app.get('/api/center/checks') async def checks(db=Depends(get_db), viewer=Depends(current_user)): rows=(await db.execute(select(center_checks,users.c.display_name).join(users).order_by(center_checks.c.day.desc()).limit(100))).mappings().all() return {'items':[{**r,'details':json.loads(r['details'])} for r in rows]}