endpoints.py
27.1 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# -*- 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, _find_latest_template
from app.services.strategy_service import StrategyService, get_task_state
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)
XLSX_DIR = os.path.join("app", "templates", "xlsx")
@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, "门店数据-问界-模板001.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": "主机厂数据-问界-模板001.xlsx",
"output": "输出模板-问界-模板001.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):
"""下载鸿蒙分析模板文件(自动使用最新版本)"""
prefix_map = {
"store": "门店数据-鸿蒙-模板",
"factory": "主机厂数据-鸿蒙-模板",
"output": "输出模板-鸿蒙-模板",
}
prefix = prefix_map.get(template_type)
if not prefix:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: store, factory, output")
try:
file_path = _find_latest_template(prefix)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")
filename = os.path.basename(file_path)
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):
try:
_harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板")
except FileNotFoundError:
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"
)
# ==================== 策略效果盯防接口 ====================
@router.get("/strategy/options")
async def strategy_options():
"""获取策略盯防筛选选项"""
try:
return {"status": "success", "data": StrategyService.get_filter_options()}
except Exception as e:
logger.error(f"Strategy options failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@router.get("/strategy/list")
async def strategy_list(
keyword: Optional[str] = Query(None),
province: Optional[str] = Query(None),
baodi_type: Optional[str] = Query(None),
monitor_type: Optional[str] = Query(None),
status: Optional[str] = Query(None),
operation_mode: Optional[str] = Query(None),
effect: Optional[str] = Query(None),
start_date: Optional[str] = Query(None),
end_date: Optional[str] = Query(None),
strategy_type: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(8, ge=1, le=100),
):
"""策略盯防列表:查询策略并计算执行前后效果"""
try:
data = StrategyService.get_strategy_list(
keyword=keyword,
province=province,
baodi_type=baodi_type,
monitor_type=monitor_type,
status=status,
operation_mode=operation_mode,
effect=effect,
start_date=start_date,
end_date=end_date,
strategy_type=strategy_type,
page=page,
page_size=page_size,
)
return {"status": "success", "data": data}
except Exception as e:
logger.error(f"Strategy list failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询策略列表失败: {str(e)}")
@router.get("/strategy/{strategy_id}")
async def strategy_detail(strategy_id: int):
"""获取单条策略详情及效果分析"""
try:
data = StrategyService.get_strategy_detail(strategy_id)
if not data:
raise HTTPException(status_code=404, detail="策略不存在")
return {"status": "success", "data": data}
except HTTPException:
raise
except Exception as e:
logger.error(f"Strategy detail failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询策略详情失败: {str(e)}")
# ==================== 策略分析任务控制接口 ====================
@router.post("/strategy/analyze")
async def strategy_trigger_analyze():
"""触发策略效果批量分析任务(异步后台执行)"""
try:
state = get_task_state()
if state.get("running"):
return {
"status": "warning",
"message": "分析任务已在运行中",
"data": state,
}
result = StrategyService.trigger_analysis_async()
return {"status": "success", "message": "分析任务已触发", "data": result}
except Exception as e:
logger.error(f"Strategy analyze trigger failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"触发分析任务失败: {str(e)}")
@router.post("/strategy/analyze/{strategy_id}")
async def strategy_analyze_single(strategy_id: int):
"""对单条策略执行分析并保存结果(同步实时执行,分析+写入完成后返回)"""
try:
logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} START ====")
result = StrategyService.analyze_and_save_single(strategy_id)
if result is None:
logger.warning(f"[API] POST /strategy/analyze/{strategy_id} returned None")
raise HTTPException(status_code=404, detail=f"策略 #{strategy_id} 未找到或分析失败")
logger.info(f"[API] ==== POST /strategy/analyze/{strategy_id} DONE, effect={result.get('effect_label')} ====")
return {"status": "success", "message": f"策略 #{strategy_id} 分析完成", "data": result}
except HTTPException:
raise
except Exception as e:
logger.error(f"Single strategy analyze failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"单条策略分析失败: {str(e)}")
@router.get("/strategy/analyze/status")
async def strategy_analyze_status():
"""获取策略分析任务进度状态"""
try:
state = get_task_state()
return {"status": "success", "data": state}
except Exception as e:
logger.error(f"Strategy analyze status failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}")
@router.post("/strategy/refresh-stale")
async def strategy_refresh_stale(stale_hours: int = Query(4, ge=1, le=48)):
"""手动触发超时盯防数据刷新,扫描超过指定小时未更新的盯防策略并自动刷新"""
try:
result = StrategyService.auto_refresh_stale_monitoring(stale_hours)
return {"status": "success", "message": f"刷新完成", "data": result}
except Exception as e:
logger.error(f"Strategy refresh stale failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"刷新盯防数据失败: {str(e)}")
@router.get("/strategy/refresh-status")
async def strategy_refresh_status():
"""查询盯防数据刷新状态(活跃/超时/从未刷新)"""
try:
status = StrategyService.get_monitoring_refresh_status()
return {"status": "success", "data": status}
except Exception as e:
logger.error(f"Strategy refresh status failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询刷新状态失败: {str(e)}")
@router.get("/strategy/stale-list")
async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)):
"""查询超时未刷新的盯防策略列表"""
try:
strategies = StrategyService.get_stale_monitoring_strategies(stale_hours)
items = []
for s in strategies:
items.append({
"id": s["id"],
"title": s.get("title") or "",
"merchant_name": s.get("merchant_name") or "",
"start_date": StrategyService._date_str(s.get("start_date")),
"end_date": StrategyService._date_str(s.get("end_date")),
})
return {"status": "success", "data": {"count": len(items), "items": items}}
except Exception as e:
logger.error(f"Strategy stale list failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询超时策略失败: {str(e)}")