endpoints.py 11.8 KB
# -*- coding: utf-8 -*-
"""
文件名: app/api/endpoints.py
职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。
"""

from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Form, BackgroundTasks
from fastapi.responses import FileResponse
from typing import Optional
from app.services.etl_service import ETLService
from app.services.excel_service import ExcelService
from app.services.analysis_service import AnalysisService
from app.core.scheduler import SchedulerManager
import os
import shutil
import logging

logger = logging.getLogger("app.api")
router = APIRouter()

# 临时文件存放目录
UPLOAD_DIR = "temp_uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

@router.post("/data/upload")
async def upload_data(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(...),
    table_name: Optional[str] = Form(None),
    upload_type: Optional[str] = Form(None),
    version_tag: Optional[str] = Form(None)
):
    """上传 Excel 并导入。支持 ODS 固定表或动态分析表。"""
    # 记录接收到的参数,方便调试 422 错误
    logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}")
    
    file_path = os.path.join(UPLOAD_DIR, file.filename)
    try:
        # 1. 保存临时文件
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 2. 判断同步模式
        if table_name and table_name.strip() != "" and table_name.startswith("ods_"):
            # ODS 固定表模式
            rows = await ExcelService.upload_to_ods(file_path, table_name)
            # 处理完后删除文件
            if os.path.exists(file_path): os.remove(file_path)
            return {
                "status": "success",
                "message": f"成功导入 {rows} 行数据到 {table_name}",
                "rows": rows
            }
        else:
            # 动态分析模式
            if not upload_type:
                if os.path.exists(file_path): os.remove(file_path)
                raise HTTPException(status_code=400, detail="智能分析模式下必须选择'分析数据类型'")

            # 使用后台任务处理 LLM 分析和导入
            background_tasks.add_task(
                ExcelService.process_dynamic_upload, 
                file_path, file.filename, upload_type, version_tag
            )
            return {
                "status": "success",
                "message": f"文件 {file.filename} 已上传,正在使用 LLM 进行结构分析并导入后台,请稍后在数据目录查看结果。",
                "upload_type": upload_type
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Upload processing failed: {e}", exc_info=True)
        if os.path.exists(file_path): os.remove(file_path)
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/status")
async def get_etl_status():
    """获取数据同步状态"""
    try:
        return await ETLService.get_sync_status()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/history")
async def get_etl_history(
    task_id: str = Query(None), 
    limit: int = Query(10)
):
    """获取执行历史"""
    try:
        return await ETLService.get_etl_history(task_id=task_id, limit=limit)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/etl/scheduler-config")
async def get_scheduler_config(task_id: str = "sync_ods_data"):
    """获取定时任务配置"""
    try:
        # 从 SchedulerManager 获取作业信息
        job = SchedulerManager._scheduler.get_job(task_id)
        if not job:
            return {"task_id": task_id, "status": "not_found"}
        
        return {
            "task_id": job.id,
            "next_run_time": str(job.next_run_time),
            "trigger": str(job.trigger),
            "status": "active"
        }
    except Exception as e:
        return {"task_id": task_id, "status": "error", "detail": str(e)}

@router.post("/etl/run-ods")
async def run_ods_sync(background_tasks: BackgroundTasks, source_table: str = None):
    """手动触发 ODS 同步 (后台异步执行)"""
    try:
        # 使用 BackgroundTasks 异步运行同步任务,防止阻塞主线程
        background_tasks.add_task(ETLService.run_ods_sync, source_table, "manual_ods_sync")
        return {
            "status": "success", 
            "message": "ODS 同步任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background ODS sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/etl/run-dw")
async def run_dw_sync(
    background_tasks: BackgroundTasks, 
    layer: str = Form(None),
    start_date: str = Form(None),
    end_date: str = Form(None),
    full_sync: str = Form(None)
):
    """手动触发 DWS/DWM/DWA 加工 (后台异步执行)
    - 默认增量同步(最近一天)
    - full_sync=true 时全量覆盖
    - 指定 start_date/end_date 时按日期范围处理
    - 参数支持 Form 或 Query 方式传递
    """
    try:
        if not layer:
            raise HTTPException(status_code=400, detail="缺少必要参数: layer")
        task_id = f"manual_{layer.lower()}_sync"
        background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
        return {
            "status": "success", 
            "message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background {layer} sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/etl/run-dw")
async def run_dw_sync_get(
    background_tasks: BackgroundTasks,
    layer: str = Query(...),
    start_date: str = Query(None),
    end_date: str = Query(None),
    full_sync: str = Query(None)
):
    """GET 方式触发 DWS/DWM/DWA 加工 (支持 Query 参数)
    - 用法: GET /api/etl/run-dw?layer=DWS&full_sync=true
    """
    try:
        task_id = f"manual_{layer.lower()}_sync"
        background_tasks.add_task(ETLService.run_dw_sync, layer, start_date, end_date, task_id, full_sync)
        return {
            "status": "success",
            "message": f"{layer} 加工任务已在后台启动,请查看执行历史获取进度。"
        }
    except Exception as e:
        logger.error(f"Failed to start background {layer} sync: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# ==================== 数据分析接口 ====================

@router.get("/analysis/template/{template_type}")
async def download_analysis_template(template_type: str):
    """下载分析模板文件"""
    template_map = {
        "store": "门店数据-模板.xlsx",
        "factory": "主机厂数据-模板.xlsx",
        "output": "输出-问界生态系数生态(5.25-6.14).xlsx",
    }
    filename = template_map.get(template_type)
    if not filename:
        raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")

    # 查找模板文件
    search_paths = [
        os.path.join("app", "templates", filename),
        os.path.join("docs", "test-demos", filename),
    ]
    file_path = None
    for p in search_paths:
        if os.path.exists(p):
            file_path = p
            break

    if not file_path:
        raise HTTPException(status_code=404, detail=f"模板文件不存在: {filename}")

    return FileResponse(file_path, filename=filename,
                        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")


_analysis_store_file = None  # 缓存门店文件路径


@router.post("/analysis/upload")
async def analysis_upload(
    store_file: Optional[UploadFile] = File(None),
    factory_file: Optional[UploadFile] = File(None),
):
    """上传门店数据和主机厂数据"""
    result = {"status": "success", "messages": []}

    if store_file and store_file.filename:
        file_path = os.path.join(UPLOAD_DIR, f"analysis_store_{store_file.filename}")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(store_file.file, f)
        global _analysis_store_file
        _analysis_store_file = file_path
        result["messages"].append(f"门店列表已上传: {store_file.filename}")

    factory_paths = {}
    if factory_file and factory_file.filename:
        file_path = os.path.join(UPLOAD_DIR, f"analysis_factory_{factory_file.filename}")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(factory_file.file, f)
        # 读取sheet信息
        try:
            import pandas as pd
            sheets = pd.read_excel(file_path, sheet_name=None)
            factory_paths["path"] = file_path
            factory_paths["sheets"] = list(sheets.keys())
            factory_paths["sheet_count"] = len(sheets)
        except Exception as e:
            factory_paths["error"] = str(e)
        result["factory_info"] = factory_paths
        result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")

    if not result["messages"]:
        raise HTTPException(status_code=400, detail="请至少上传一个文件")

    return result


@router.post("/analysis/generate")
async def analysis_generate(
    background_tasks: BackgroundTasks,
    start_date: str = Form(None),
    end_date: str = Form(None)
):
    """根据已上传的数据生成生态系数分析报表"""
    global _analysis_store_file

    if not _analysis_store_file or not os.path.exists(_analysis_store_file):
        raise HTTPException(status_code=400, detail="请先上传门店列表文件")

    # 查找最近上传的主机厂数据文件
    factory_files = sorted(
        [f for f in os.listdir(UPLOAD_DIR) if f.startswith("analysis_factory_") and f.endswith(".xlsx")],
        key=lambda f: os.path.getmtime(os.path.join(UPLOAD_DIR, f)),
        reverse=True
    )
    if not factory_files:
        raise HTTPException(status_code=400, detail="请先上传主机厂数据文件")

    factory_path = os.path.join(UPLOAD_DIR, factory_files[0])

    try:
        store_df = AnalysisService.read_store_list(_analysis_store_file)
        factory_sheets = AnalysisService.read_factory_data(factory_path)
        output_path = AnalysisService.build_report(
            store_df, factory_sheets,
            start_date=start_date or None,
            end_date=end_date or None
        )

        return {
            "status": "success",
            "message": "分析报表已生成",
            "file_path": output_path,
            "download_url": "/api/analysis/download",
            "store_count": len(store_df),
            "factory_sheets": list(factory_sheets.keys()),
            "factory_rows": sum(len(v) for v in factory_sheets.values()),
        }
    except Exception as e:
        logger.error(f"Analysis generate failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")


@router.get("/analysis/download")
async def analysis_download():
    """下载生成的分析报表"""
    output_dir = "temp_uploads"
    output_files = sorted(
        [f for f in os.listdir(output_dir) if f.startswith("问界生态系数分析") and f.endswith(".xlsx")],
        key=lambda f: os.path.getmtime(os.path.join(output_dir, f)),
        reverse=True
    )
    if not output_files:
        raise HTTPException(status_code=404, detail="未找到分析报表,请先生成")

    file_path = os.path.join(output_dir, output_files[0])
    return FileResponse(
        file_path,
        filename=output_files[0],
        media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    )