endpoints.py 20.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
# -*- coding: utf-8 -*-
"""
文件名: app/api/endpoints.py
职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。
"""

import glob, os, re
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.services.harmony_analysis_service import HarmonyAnalysisService
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))


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

XLSX_DIR = os.path.join("app", "templates", "xlsx")

def _find_latest_wenjie_template():
    """返回最新的问界门店数据模板(最大序号),无带序号文件时回退到旧版"""
    max_no = 0
    for f in glob.glob(os.path.join(XLSX_DIR, "问界门店数据模板[0-9][0-9][0-9].xlsx")):
        m = re.search(r"问界门店数据模板(\d{3})\.xlsx", os.path.basename(f))
        if m:
            max_no = max(max_no, int(m.group(1)))
    if max_no > 0:
        return os.path.join(XLSX_DIR, f"问界门店数据模板{max_no:03d}.xlsx")
    # 回退到旧版模板
    fallback = os.path.join(XLSX_DIR, "门店数据-模板0625.xlsx")
    if os.path.exists(fallback):
        return fallback
    return None

@router.get("/analysis/template/{template_type}")
async def download_analysis_template(template_type: str):
    """下载分析模板文件"""
    template_map = {
        # store 使用动态查找最新带序号的模板
        "factory": "主机厂数据-模板.xlsx",
        "output": "输出-问界生态系数-模板0625.xlsx",
    }

    if template_type == "store":
        file_path = _find_latest_wenjie_template()
        if not file_path:
            raise HTTPException(status_code=404, detail="门店数据模板文件不存在")
        filename = os.path.basename(file_path)
    else:
        filename = template_map.get(template_type)
        if not filename:
            raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
        # 查找模板文件
        search_paths = [
            os.path.join(XLSX_DIR, 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  # 缓存门店文件路径
_analysis_ecology_factory_file = None  # 缓存生态主机厂文件路径
_analysis_nature_factory_file = None  # 缓存自然月主机厂文件路径


@router.post("/analysis/upload")
async def analysis_upload(
    store_file: Optional[UploadFile] = File(None),
    ecology_factory_file: Optional[UploadFile] = File(None),
    nature_factory_file: Optional[UploadFile] = File(None),
):
    """上传门店数据、生态主机厂数据(26日周期)、自然月主机厂数据(1日周期)"""
    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}")

    def _save_factory(upload_file, prefix, global_var_name):
        if not upload_file or not upload_file.filename:
            return None
        file_path = os.path.join(UPLOAD_DIR, f"analysis_{prefix}_{upload_file.filename}")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(upload_file.file, f)
        try:
            import pandas as pd
            sheets = pd.read_excel(file_path, sheet_name=None)
            return {
                "path": file_path,
                "sheets": list(sheets.keys()),
                "sheet_count": len(sheets),
            }
        except Exception as e:
            return {"path": file_path, "error": str(e)}

    ecology_info = _save_factory(ecology_factory_file, "ecology", "_analysis_ecology_factory_file")
    if ecology_info:
        global _analysis_ecology_factory_file
        _analysis_ecology_factory_file = ecology_info.get("path") if not ecology_info.get("error") else None
        result["ecology_factory_info"] = ecology_info
        result["messages"].append(f"生态主机厂数据已上传: {ecology_factory_file.filename}")

    nature_info = _save_factory(nature_factory_file, "nature", "_analysis_nature_factory_file")
    if nature_info:
        global _analysis_nature_factory_file
        _analysis_nature_factory_file = nature_info.get("path") if not nature_info.get("error") else None
        result["nature_factory_info"] = nature_info
        result["messages"].append(f"自然月主机厂数据已上传: {nature_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,
    ecology_start_date: str = Form(None),
    ecology_end_date: str = Form(None),
    nature_start_date: str = Form(None),
    nature_end_date: str = Form(None)
):
    """根据已上传的数据生成生态系数分析报表(双sheet:生态数据+自然月)"""
    global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file

    if not _analysis_store_file or not os.path.exists(_analysis_store_file):
        # 未上传时使用模板库中最新的默认门店数据
        default_store = _find_latest_wenjie_template()
        if os.path.exists(default_store):
            _analysis_store_file = default_store
        else:
            raise HTTPException(status_code=400, detail="请先上传门店列表文件")

    ecology_factory = None
    nature_factory = None

    if _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
        ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)

    if _analysis_nature_factory_file and os.path.exists(_analysis_nature_factory_file):
        nature_factory = AnalysisService.read_factory_data(_analysis_nature_factory_file)

    if not ecology_factory and not nature_factory:
        raise HTTPException(status_code=400, detail="请至少上传一个主机厂数据文件(生态或自然月)")

    try:
        store_df = AnalysisService.read_store_list(_analysis_store_file)
        output_path = AnalysisService.build_report(
            store_df,
            ecology_factory=ecology_factory or {},
            nature_factory=nature_factory or {},
            ecology_start=ecology_start_date or None,
            ecology_end=ecology_end_date or None,
            nature_start=nature_start_date or None,
            nature_end=nature_end_date or None
        )

        # 统计信息
        ecology_stores = store_df[store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]
        nature_stores = store_df[~store_df["兜底截止日期"].apply(AnalysisService._is_ecology_deadline)]

        return {
            "status": "success",
            "message": "分析报表已生成",
            "file_path": output_path,
            "download_url": f"api/analysis/download?file={os.path.basename(output_path)}",
            "ecology_store_count": len(ecology_stores),
            "nature_store_count": len(nature_stores),
            "ecology_factory_sheets": list(ecology_factory.keys()) if ecology_factory else [],
            "nature_factory_sheets": list(nature_factory.keys()) if nature_factory else [],
        }
    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(file: str = Query(None)):
    """下载生成的分析报表,支持指定文件名"""
    output_dir = "temp_uploads"
    if file:
        file_path = os.path.join(output_dir, file)
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="指定的报表文件不存在")
        return FileResponse(
            file_path, filename=file,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )

    # 无指定时返回最新文件
    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"
    )


# ==================== 鸿蒙生态分析接口 ====================

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

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

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


_harmony_store_file = None
_harmony_factory_file = None


@router.post("/harmony/upload")
async def harmony_upload(
    store_file: Optional[UploadFile] = File(None),
    factory_file: Optional[UploadFile] = File(None),
):
    """上传鸿蒙门店兜底配置、主机厂数据(产值表数据从数据库自动查询)"""
    global _harmony_store_file, _harmony_factory_file
    result = {"status": "success", "messages": []}

    if store_file and store_file.filename:
        file_path = os.path.join(UPLOAD_DIR, f"harmony_store_{store_file.filename}")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(store_file.file, f)
        _harmony_store_file = file_path
        result["messages"].append(f"门店兜底配置已上传: {store_file.filename}")

    if factory_file and factory_file.filename:
        file_path = os.path.join(UPLOAD_DIR, f"harmony_factory_{factory_file.filename}")
        with open(file_path, "wb") as f:
            shutil.copyfileobj(factory_file.file, f)
        _harmony_factory_file = file_path
        result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")

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

    return result


@router.post("/harmony/generate")
async def harmony_generate(
    start_date: str = Form(None),
    end_date: str = Form(None),
):
    """根据已上传的数据生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
    global _harmony_store_file, _harmony_factory_file

    # 门店兜底配置:未上传时使用默认模板
    if not _harmony_store_file or not os.path.exists(_harmony_store_file):
        default_store = os.path.join(XLSX_DIR, "鸿蒙门店数据-模板.xlsx")
        if os.path.exists(default_store):
            _harmony_store_file = default_store
        else:
            raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")

    factory_df = None

    if _harmony_factory_file and os.path.exists(_harmony_factory_file):
        factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)

    try:
        store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
        output_path = HarmonyAnalysisService.build_report(
            store_df,
            factory_df=factory_df,
            start_date=start_date,
            end_date=end_date,
        )

        return {
            "status": "success",
            "message": "鸿蒙分析报表已生成",
            "file_path": output_path,
            "download_url": f"api/harmony/download?file={os.path.basename(output_path)}",
            "store_count": len(store_df),
            "factory_count": len(factory_df) if factory_df is not None else 0,
            "db_store_count": len(store_df),
        }
    except Exception as e:
        logger.error(f"Harmony analysis generate failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")


@router.get("/harmony/download")
async def harmony_download(file: str = Query(None)):
    """下载鸿蒙分析报表"""
    output_dir = "temp_uploads"
    if file:
        file_path = os.path.join(output_dir, file)
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="指定的报表文件不存在")
        return FileResponse(
            file_path, filename=file,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )

    # 无指定时返回最新的鸿蒙分析文件
    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"
    )