endpoints.py
13.6 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
# -*- 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": "门店数据-模板0625.xlsx",
"factory": "主机厂数据-模板.xlsx",
"output": "输出-问界生态系数-模板0625.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 # 缓存门店文件路径
_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):
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": "api/analysis/download",
"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():
"""下载生成的分析报表"""
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"
)