From 9be4808a8d7038e9af6de826f573c66ca38194db Mon Sep 17 00:00:00 2001
From: xuyonghao <898441624@qq.com>
Date: 星期三, 22 一月 2025 11:31:16 +0800
Subject: [PATCH] 报表合并webSocket信息格式修改

---
 app/api/excel.py |  186 +++++++++++++++++++++++++++-------------------
 1 files changed, 109 insertions(+), 77 deletions(-)

diff --git a/app/api/excel.py b/app/api/excel.py
index ac2c6ef..e8cc6ec 100644
--- a/app/api/excel.py
+++ b/app/api/excel.py
@@ -1,13 +1,15 @@
-from fastapi import APIRouter, File, UploadFile, Depends
+import random
+import string
+
+from fastapi import APIRouter, File, UploadFile, Form, BackgroundTasks, Depends, Request
 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 starlette.websockets import WebSocket
+
+from app.api import get_current_user, get_current_user_websocket, Response
+from app.models import UserModel, AgentType
 from app.models.base_model import get_db
-from app.models.user_model import UserModel
+from app.service.session import SessionService
 from app.utils.excelmerge.conformity import run_conformity
 import shutil
 import os
@@ -18,17 +20,17 @@
 EXCEL_FILES_PATH = 'data/output'
 SOURCE_FILES_PATH = 'data/source'
 
-def allowed_file(filename):
+
+def allowed_file(filename: str) -> bool:
     return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
 
-def create_dir_if_not_exists(path):
+def create_dir_if_not_exists(path: str):
     if not os.path.exists(path):
         os.makedirs(path)
 
 
-# 娓呯悊鍑芥暟
-def clear_directory(path):
+def clear_directory(path: str) -> dict:
     for filename in os.listdir(path):
         file_path = os.path.join(path, filename)
         try:
@@ -41,104 +43,134 @@
     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)
+def user_file_path(userid: str, path: str) -> str:
+    return os.path.join(path, userid)
 
-    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)
+
+def generate_db_id(prefix: str = "me") -> str:
+    random_part = ''.join(random.choices(string.ascii_letters + string.digits, k=13))
+    return prefix + random_part
+
+
+def db_create_session(db: Session, user_id: str):
+    db_id = generate_db_id()
+    session = SessionService(db).create_session(
+        db_id,
+        "鍚堝苟Excel",
+        "basic_excel_merge",
+        AgentType.BASIC,
+        int(user_id)
+    )
+    return session
+
+
+@router.post('/excel/upload', response_model=Response)
+async def upload_file(files: list[UploadFile] = File(...), current_user: UserModel = Depends(get_current_user)):
+    user_id = str(current_user.id)
+    if not any(file.filename for file in files):
+        return Response(code=400, msg="娌℃湁鏂囦欢閮ㄥ垎", data={})
+    if not user_id:
+        return Response(code=400, msg="缂哄皯鍙傛暟user_id", data={})
+    user_source = user_file_path(user_id, SOURCE_FILES_PATH)
+    user_excel = EXCEL_FILES_PATH
+
+    create_dir_if_not_exists(user_source)
+    create_dir_if_not_exists(user_excel)
+    clear_directory(user_source)
 
     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)
+            save_path = os.path.join(user_source, file.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={"code": 200, "msg": "", "data": {}}, status_code=200)
+            return Response(code=400, msg="涓嶅厑璁哥殑鏂囦欢绫诲瀷", data={})
+    return Response(code=200, msg="涓婁紶鎴愬姛", data={})
 
 
 # ws://localhost:9201/api/document/ws/excel
 @router.websocket("/ws/excel")
-async def ws_excel(websocket: WebSocket):
+async def ws_excel(websocket: WebSocket,
+                   current_user: UserModel = Depends(get_current_user_websocket),
+                   db: Session = Depends(get_db)):
     await websocket.accept()
+    user_id = str(current_user.id)
 
-    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)
+    user_source = user_file_path(user_id, SOURCE_FILES_PATH)
+    user_excel = EXCEL_FILES_PATH
+    create_dir_if_not_exists(user_source)
+    create_dir_if_not_exists(user_excel)
 
     while True:
         data = await websocket.receive_text()
         try:
             if data == "\"鍚堝苟Excel\"":
-                clear_directory(EXCEL_FILES_PATH)
-                output_file_path = run_conformity()
-                clear_directory(EXCEL_FILES_PATH)
-                output_file_path = run_conformity()
-                files = os.listdir(EXCEL_FILES_PATH)
-                if files:
-                    first_file = files[0]
-                    file_name = os.path.basename(first_file)
-                    file_url = f"./api/document/download/{first_file}"
+                merge_file = run_conformity(user_source, user_excel)
+                if merge_file is not None:
+
                     await websocket.send_json({
-                        "message": "鏂囨。鍚堝苟鎴愬姛锛�",
                         "type": "stream",
-                        "files": [{
-                            "file_name": file_name,
-                            "file_url": file_url
-                        }]
+                        "files": [
+                            {
+                                "file_name": "Excel",
+                                "file_url": f"./api/document/download/{merge_file}.xlsx?file_type=excel",
+                            }
+                        ]
                     })
                     await websocket.send_json({
-                        "message": "鏂囨。鍚堝苟鎴愬姛锛�",
+                        "message": "鍚堝苟鎴愬姛",
                         "type": "close",
                     })
+                    # 鍒涘缓浼氳瘽璁板綍
+                    session = db_create_session(db, user_id)
+                    # 鏇存柊浼氳瘽璁板綍
+                    if session:
+                        session_id = session.id
+                        new_message = {
+                            "role": "assistant",
+                            "content": {
+                                "message": "\u5408\u5e76\u6210\u529f",
+                                "type": "message",
+                                "file_name": "Excel",
+                                "file_url": f"/api/document/download/{merge_file}.xlsx?file_type=excel"
+                            }
+                        }
+                        session_service = SessionService(db)
+                        session_service.update_session(session_id, message=new_message)
                 else:
-                    await websocket.send_json({"error": "鍚堝苟鎿嶄綔鏈敓鎴愭枃浠�", "type": "stream", "files": []})
-            elif data == "\"鏌ヨ鍚堝苟杩涘害\"":
-                files = os.listdir(EXCEL_FILES_PATH)
-                if not files:
-                    await websocket.send_json({"step_message": "姝e湪鍚堝苟涓�", "type": "stream", "files": []})
-                else:
-                    await websocket.send_json({"step_message": "鏂囨。鍚堝苟鎴愬姛锛�", "type": "stream", "files": []})
-            elif data == "\"鑾峰彇鏂囦欢\"":
-                files = os.listdir(EXCEL_FILES_PATH)
-                if not files:
-                    await websocket.send_json({"error": "鐩綍涓嬫病鏈夌敓鎴愮殑鏂囦欢", "type": "stream", "files": []})
-                else:
-                    first_file = files[0]
-                    file_name = os.path.basename(first_file)
-                    file_url = f"./api/document/download/{first_file}"
-                    await websocket.send_json({
-                        "step_message": "鏂囨。鍚堝苟鎴愬姛锛�",
-                        "type": "stream",
-                        "files": [{
-                            "file_name": file_name,
-                            "file_url": file_url
-                        }]
-                    })
+                    await websocket.send_json({"error": "鍚堝苟澶辫触", "type": "stream", "files": []})
+                    await websocket.close()
             else:
                 print(f"Received data: {data}")
                 await websocket.send_json({"error": "鏈煡鎸囦护", "data": str(data)})
+                await websocket.close()
         except Exception as e:
             await websocket.send_json({"error": str(e)})
             await websocket.close()
 
 
-@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="鏈嶅姟鍣ㄩ敊璇�")
\ No newline at end of file
+@router.get("/download/{file_full_name}")
+async def download_file(file_full_name: str):
+    file_name = os.path.basename(file_full_name)
+    user_excel = EXCEL_FILES_PATH
+    file_path = os.path.join(user_excel, file_full_name)
+
+    if not os.path.exists(file_path):
+        return JSONResponse(content={"error": "鏂囦欢涓嶅瓨鍦�"}, status_code=404)
+    return FileResponse(
+        path=file_path,
+        filename="Excel.xlsx",
+        media_type='application/octet-stream',
+    )
+    # def delete_file():
+    #     try:
+    #         os.unlink(file_path)
+    #     except OSError as e:
+    #         print(f"Deleting file error")
+
+    # 寰呬笅杞藉畬鎴愬悗鍒犻櫎鐢熸垚鐨勬枃浠�
+    # background_tasks.add_task(delete_file)
+    # return FileResponse(path=file_path, filename=file_name,
+    #                    media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

--
Gitblit v1.8.0