chore: initial open-source baseline v1.0.0
CI / check (push) Failing after 15m48s

Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
This commit is contained in:
guwangtu committed 2026-12-05 15:44:53 +00:00
commit b91954df4a
106 files changed
+43359

No files matched your search

+227
View File
@@ -0,0 +1,227 @@
"""合同审核管理平台 - 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 = """<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>%s - 合同预览</title>
<style>
body{margin:0;background:#eef2f6;color:#1f2d3d;font-family:"Microsoft YaHei","PingFang SC",sans-serif}
.bar{position:sticky;top:0;background:#16323c;color:#9fe8ff;padding:12px 24px;font-size:14px;display:flex;justify-content:space-between}
.bar a{color:#9fe8ff;text-decoration:none}
.paper{max-width:900px;margin:24px auto;background:#fff;padding:48px 56px;box-shadow:0 8px 30px rgba(0,0,0,.12);line-height:1.9;font-size:15px;border-radius:6px}
.paper img{max-width:100%%;height:auto}
.paper table{border-collapse:collapse;width:100%%}
.paper td,.paper th{border:1px solid #d8dee8;padding:8px 10px}
.paper h1,.paper h2,.paper h3{margin:1.2em 0 .5em}
</style></head><body>
<div class="bar"><span>%s - 合同预览(Word 自动转换)</span><a href="javascript:history.back()">← 返回</a></div>
<div class="paper">%s</div>
</body></html>""" % (contract.get("name", "合同"), contract.get("name", "合同"), body)
return HTMLResponse(content=html, headers={"Cache-Control": "no-store"})
@app.get("/api/contracts/{contract_id}/file")
async def get_contract_file(contract_id: int):
"""预览/下载合同原文件:PDF 浏览器内预览,Word 下载"""
import urllib.parse
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()
name = Path(path).name
if ext == ".pdf":
return FileResponse(path, media_type="application/pdf",
headers={"Content-Disposition": "inline; filename*=UTF-8''" + urllib.parse.quote(name)})
return FileResponse(path, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
headers={"Content-Disposition": "attachment; filename*=UTF-8''" + urllib.parse.quote(name)})
@app.get("/api/contracts/{contract_id}")
async def get_contract(contract_id: int):
contract = cs.get_contract(contract_id)
if not contract:
raise HTTPException(status_code=404, detail="合同不存在")
return JSONResponse(content={"contract": contract})
@app.delete("/api/contracts/{contract_id}")
async def delete_contract(contract_id: int):
cs.delete_contract(contract_id)
return JSONResponse(content={"success": True})
@app.put("/api/contracts/{contract_id}/rectification")
async def update_rectification(contract_id: int, body: dict = Body(...)):
rectifications = body.get("rectifications", [])
result = cs.update_rectification(contract_id, rectifications)
return JSONResponse(content={"contract": result})
@app.get("/api/statistics")
async def get_statistics(
date_from: str = Query(None),
date_to: str = Query(None)
):
stats = cs.get_statistics(date_from, date_to)
return JSONResponse(content=stats)
@app.get("/api/reports/{filename}")
async def get_report(filename: str):
report_path = REPORT_DIR / filename
if not report_path.exists():
raise HTTPException(status_code=404, detail="报告不存在")
return HTMLResponse(content=report_path.read_text(encoding="utf-8"))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8090)