from fastapi import APIRouter, File, UploadFile, Depends from fastapi.responses import JSONResponse, FileResponse from fastapi.exceptions import HTTPException from sqlalchemy.orm import Session from starlette.websockets import WebSocket, WebSocketDisconnect from werkzeug.utils import secure_filename from app.api import get_current_user_websocket from app.models.agent_model import AgentModel, AgentType from app.models.base_model import get_db from app.models.user_model import UserModel from app.utils.excelmerge.conformity import run_conformity import shutil import os router = APIRouter() ALLOWED_EXTENSIONS = {'xlsx'} EXCEL_FILES_PATH = 'data/output' SOURCE_FILES_PATH = 'data/source' def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def create_dir_if_not_exists(path): if not os.path.exists(path): os.makedirs(path) # 清理函数 def clear_directory(path): for filename in os.listdir(path): file_path = os.path.join(path, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: return {"error": "清空出错"} return {"message": "目录已清空"} @router.post('/excel/upload') async def upload_file(files: list[UploadFile] = File(...)): if not any(file.filename for file in files): return JSONResponse(content={"error": "没有文件部分"}, status_code=400) create_dir_if_not_exists(SOURCE_FILES_PATH) create_dir_if_not_exists(EXCEL_FILES_PATH) clear_directory(SOURCE_FILES_PATH) clear_directory(EXCEL_FILES_PATH) save_path_list = [] for file in files: if file.filename == '': return JSONResponse(content={"error": "没有选择文件"}, status_code=400) if file and allowed_file(file.filename): filename = secure_filename(file.filename) save_path = os.path.join(SOURCE_FILES_PATH, filename) with open(save_path, 'wb') as buffer: shutil.copyfileobj(file.file, buffer) save_path_list.append(save_path) else: return JSONResponse(content={"error": "不允许的文件类型"}, status_code=400) return JSONResponse(content={"message": "文件上传成功", "paths": save_path_list}, status_code=201) # ws://localhost:9201/api/document/ws/excel @router.websocket("/ws/excel") async def ws_excel(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_json() action = data.get("action") try: if action == "process": clear_directory(EXCEL_FILES_PATH) output_file_path = run_conformity() await websocket.send_json({"step_message": "开始合并"}) elif action == "inquire": files = os.listdir(EXCEL_FILES_PATH) if not files: await websocket.send_json({"step_message": "正在合并中"}) else: await websocket.send_json({"step_message": "文档合并成功!"}) elif action == "download": files = os.listdir(EXCEL_FILES_PATH) if not files: await websocket.send_json({"error": "目录下没有生成的文件"}) else: first_file = files[0] await websocket.send_json({"step_message": "合并文件已生成", "download_url": f"/download/{first_file}"}) else: await websocket.send_json({"error": "未知指令"}) except Exception as e: await websocket.send_json({"error": str(e)}) @router.get("/download/{filename}") async def download_file(filename: str): try: return FileResponse(os.path.join(EXCEL_FILES_PATH, filename), filename=filename, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') except FileNotFoundError: raise HTTPException(status_code=404, detail="文件不存在") except Exception as e: raise HTTPException(status_code=500, detail="服务器错误")