"""合同审核管理平台 - API服务器""" import os import shutil import tempfile from pathlib import Path from fastapi import FastAPI, UploadFile, File, HTTPException, Query, Body from fastapi.responses import HTMLResponse, JSONResponse, FileResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles import uvicorn import contract_service as cs BASE_DIR = Path(__file__).parent.resolve() REPORT_DIR = BASE_DIR / "报告" REPORT_DIR.mkdir(parents=True, exist_ok=True) app = FastAPI(title="合同审核管理平台") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.mount("/reports", StaticFiles(directory=str(REPORT_DIR)), name="reports") app.mount("/static", StaticFiles(directory=str(BASE_DIR)), name="static") _SAFE_STATIC_SUFFIXES = { ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp", ".css", ".js", ".woff", ".woff2", ".ttf", } @app.middleware("http") async def _block_unsafe_static(request, call_next): if request.url.path.startswith("/static/"): suffix = os.path.splitext(request.url.path)[1].lower() if suffix not in _SAFE_STATIC_SUFFIXES: return JSONResponse(status_code=404, content={"detail": "Not Found"}) return await call_next(request) @app.get("/api/health") async def health(): return {"status": "ok"} # ====== 登录会话(Cookie + HMAC 签名,四套系统共享) ====== import auth_guard as auth @app.middleware("http") async def _auth_middleware(request, call_next): resp = auth.guard(request) if resp is not None: return resp return await call_next(request) @app.get("/", response_class=HTMLResponse) async def index(): index_path = BASE_DIR / "index.html" return HTMLResponse(content=index_path.read_text(encoding="utf-8")) @app.get("/api/contracts") async def list_contracts( date_from: str = Query(None), date_to: str = Query(None) ): contracts = cs.list_contracts(date_from, date_to) return JSONResponse(content={"contracts": contracts}) @app.post("/api/contracts/upload") async def upload_contract(file: UploadFile = File(...)): if not file.filename: raise HTTPException(status_code=400, detail="文件名不能为空") ext = Path(file.filename).suffix.lower() if ext not in [".docx", ".pdf"]: raise HTTPException(status_code=400, detail="仅支持Word(.docx)和PDF(.pdf)文件") with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as tmp: shutil.copyfileobj(file.file, tmp) tmp_path = tmp.name try: result = cs.upload_only(file.filename, tmp_path) return JSONResponse(content={"contract": result}) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if os.path.exists(tmp_path): os.remove(tmp_path) @app.post("/api/contracts/{contract_id}/review") async def review_contract(contract_id: int): """调用大模型审核合同""" try: result = cs.review_and_save(contract_id) except Exception as e: raise HTTPException(status_code=500, detail="审核失败:" + str(e)) if not result: raise HTTPException(status_code=404, detail="合同不存在") return JSONResponse(content={"contract": result}) @app.put("/api/contracts/{contract_id}/review") async def update_review(contract_id: int, body: dict = Body(...)): """手动修改审核结果并重新生成报告""" result = cs.update_review(contract_id, body) if not result: raise HTTPException(status_code=404, detail="合同不存在") return JSONResponse(content={"contract": result}) @app.get("/api/contracts/{contract_id}/preview", response_class=HTMLResponse) async def preview_contract(contract_id: int): """在线预览:PDF 直接返回,Word 转成 HTML 返回""" contract = cs.get_contract(contract_id) if not contract: raise HTTPException(status_code=404, detail="合同不存在") path = contract.get("file_path") or "" if not path or not os.path.exists(path): alt = cs.CONTRACT_DIR / Path(path).name if alt.exists(): path = str(alt) if not path or not os.path.exists(path): raise HTTPException(status_code=404, detail="合同文件不存在") ext = Path(path).suffix.lower() if ext == ".pdf": from fastapi.responses import RedirectResponse return RedirectResponse(url=f"/api/contracts/{contract_id}/file") try: body = cs.docx_to_html(path) except Exception as e: raise HTTPException(status_code=500, detail="Word 预览转换失败:" + str(e)) html = """