endpoints.py
45.7 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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
# -*- coding: utf-8 -*-
"""
文件名: app/api/endpoints.py
职责: 定义 FastAPI 路由接口,处理前端请求并调用 Service 层逻辑。
注意: 不要删除这个注释。
"""
import glob, os, re
from datetime import datetime
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.services.upload_service import (
import_store_guarantee, import_oem_delivery, get_upload_history,
)
from app.services.file_naming import (
build_filename,
build_store_filename,
build_factory_filename,
build_analysis_output_filename,
ensure_unique_filename
)
from app.core.scheduler import SchedulerManager
import os
import shutil
import logging
logger = logging.getLogger("app.api")
router = APIRouter()
# 统一上传基础目录,所有文件按日期目录分级存放
UPLOAD_BASE = "temp_uploads"
os.makedirs(UPLOAD_BASE, exist_ok=True)
def _date_path(filename: str, category: str = "") -> str:
"""生成按日期分级的文件路径: temp_uploads/YYYYMMDD/filename"""
today = datetime.now().strftime("%Y%m%d")
target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today)
os.makedirs(target_dir, exist_ok=True)
return os.path.join(target_dir, filename)
def _find_file(filename: str) -> Optional[str]:
"""在 temp_uploads 下递归查找指定文件名,返回完整路径或 None"""
for root, _dirs, files in os.walk(UPLOAD_BASE):
if filename in files:
return os.path.join(root, filename)
return None
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 = _date_path(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),
task_pattern: str = Query(None)
):
"""获取执行历史
- task_id: 精确匹配
- task_pattern: LIKE 模糊匹配,如 '%_ods_sync' 匹配所有 ODS 同步任务
"""
try:
return await ETLService.get_etl_history(task_id=task_id, limit=limit, task_pattern=task_pattern)
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
def _load_store_df_from_batch(batch_no: str) -> "pd.DataFrame":
"""从DB加载门店兜底配置批次,返回可直接用于build_report的DataFrame"""
from app.services.upload_service import _get_conn
import pandas as pd
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute("SELECT id FROM upload_batch WHERE batch_no=%s AND data_type='store_guarantee'", (batch_no,))
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")
cur.execute(
"""SELECT store_name, guarantee_target, guarantee_type,
special_case_1, special_case_2,
ew_conversion_rate, ax_conversion_rate, battery_conversion_rate,
ew_compensation, ax_compensation, battery_compensation,
guarantee_end_date
FROM store_guarantee_config WHERE batch_id=%s""",
(batch["id"],))
rows = cur.fetchall()
if not rows:
raise HTTPException(status_code=400, detail="批次中无数据")
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['兜底指标'] = df['guarantee_target']
df['兜底类型'] = df['guarantee_type']
df['特殊情况1'] = df['special_case_1']
df['特殊情况2'] = df['special_case_2']
df['达标转化率_整车延保'] = df['ew_conversion_rate']
df['达标转化率_安心包'] = df['ax_conversion_rate']
df['达标转化率_电池'] = df['battery_conversion_rate']
df['每单赔付金额_整车'] = df['ew_compensation']
df['每单赔付金额_安心包'] = df['ax_compensation']
df['每单赔付金额_电池'] = df['battery_compensation']
df['兜底截止日期'] = df['guarantee_end_date']
return df
finally:
conn.close()
def _load_oem_factory_from_batch(batch_no: str) -> dict:
"""从DB加载OEM交付批次,返回 {sheet_name: DataFrame} 格式(兼容read_factory_data输出)"""
from app.services.upload_service import _get_conn
import pandas as pd
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute("SELECT id FROM upload_batch WHERE batch_no=%s AND data_type='oem_delivery'", (batch_no,))
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail=f"批次 {batch_no} 不存在")
cur.execute(
"""SELECT store_code, store_name, province,
delivery_count, ew_purchase_count, ax_purchase_count,
battery_purchase_count, tire_purchase_count
FROM oem_delivery_data WHERE batch_id=%s""",
(batch["id"],))
rows = cur.fetchall()
if not rows:
return {}
df = pd.DataFrame(rows)
df['门店名'] = df['store_name']
df['厅店代码'] = df['store_code']
df['区域(省)'] = df['province']
df['交付数'] = pd.to_numeric(df['delivery_count'], errors='coerce').fillna(0)
df['整车延保采购数'] = pd.to_numeric(df['ew_purchase_count'], errors='coerce').fillna(0)
df['安心包采购数'] = pd.to_numeric(df['ax_purchase_count'], errors='coerce').fillna(0)
df['电池延保采购数'] = pd.to_numeric(df['battery_purchase_count'], errors='coerce').fillna(0)
df['轮胎险采购数'] = pd.to_numeric(df['tire_purchase_count'], errors='coerce').fillna(0)
# 去重
df = df.drop_duplicates(subset=["门店名"], keep="first")
return {"Sheet1": df}
finally:
conn.close()
@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 # 缓存自然月主机厂文件路径
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
"""构建带日期范围的文件名: 使用新的命名规范
支持的 prefix:
- analysis_store: 问界门店数据
- analysis_ecology: 问界主机厂数据(生态月)
- analysis_nature: 问界主机厂数据(自然月)
- harmony_store: 鸿蒙门店数据
- harmony_factory: 鸿蒙主机厂数据
"""
# 使用统一的命名规范
if "store" in prefix and "harmony" not in prefix:
return build_store_filename("问界", start_date, end_date)
elif "ecology" in prefix:
return build_factory_filename("问界", "生态月", start_date, end_date)
elif "nature" in prefix:
return build_factory_filename("问界", "自然月", start_date, end_date)
elif "harmony_store" in prefix:
return build_store_filename("鸿蒙", start_date, end_date)
elif "harmony_factory" in prefix:
return build_factory_filename("鸿蒙", "", start_date, end_date)
# 回退到旧的命名方式
stem, ext = os.path.splitext(original_name)
parts = [prefix, stem]
if start_date and end_date:
s = start_date[5:].replace("-", "") if len(start_date) >= 10 else start_date
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(f"{s}~{e}")
elif end_date:
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(e)
return "_".join(parts) + ext
@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),
ecology_start_date: str = Form(None),
ecology_end_date: str = Form(None),
nature_start_date: str = Form(None),
nature_end_date: str = Form(None),
):
"""上传门店数据、生态主机厂数据(26日周期)、自然月主机厂数据(1日周期)"""
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
fname = _build_dated_filename(store_file.filename, "analysis_store")
file_path = _date_path(fname, category="analysis")
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, start_date=None, end_date=None):
if not upload_file or not upload_file.filename:
return None
fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date)
file_path = _date_path(fname, category="analysis")
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", ecology_start_date, ecology_end_date)
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", nature_start_date, nature_end_date)
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/save-batch")
async def analysis_save_batch(
file_type: str = Form(...), # "store", "ecology", "nature", "factory"
file: UploadFile = File(...),
period_start: str = Form(""),
period_end: str = Form(""),
period_type: str = Form(""), # ecology / nature,仅 oem 使用
brand: str = Form("问界"),
):
"""将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "ecology", "nature", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/ecology/nature/factory")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
file_path = _date_path(f"_save_batch_{file.filename}", category="batch")
try:
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
file_size = os.path.getsize(file_path)
if file_type == "store":
from app.services.upload_service import import_store_guarantee
today = datetime.now().strftime("%Y-%m-%d")
result = import_store_guarantee(
file_path=file_path,
original_filename=file.filename,
brand=brand,
data_period_start=today,
data_period_end=today,
file_size=file_size,
)
else:
from app.services.upload_service import import_oem_delivery
pt = period_type or ("ecology" if file_type == "ecology" else "nature")
result = import_oem_delivery(
file_path=file_path,
original_filename=file.filename,
brand=brand,
data_period_start=period_start or "",
data_period_end=period_end or "",
period_type=pt,
file_size=file_size,
)
return {"status": "success", "data": result}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Save batch failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"保存批次失败: {str(e)}")
finally:
if os.path.exists(file_path):
os.remove(file_path)
@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),
store_batch_no: str = Form(None),
ecology_batch_no: str = Form(None),
nature_batch_no: str = Form(None),
):
"""根据已上传的数据或历史批次生成生态系数分析报表(双sheet:生态数据+自然月)"""
global _analysis_store_file, _analysis_ecology_factory_file, _analysis_nature_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
store_df = _load_store_df_from_batch(store_batch_no)
elif _analysis_store_file and os.path.exists(_analysis_store_file):
store_df = AnalysisService.read_store_list(_analysis_store_file)
else:
default_store = _find_latest_wenjie_template()
if os.path.exists(default_store):
_analysis_store_file = default_store
store_df = AnalysisService.read_store_list(_analysis_store_file)
else:
raise HTTPException(status_code=400, detail="请先上传门店列表文件")
ecology_factory = {}
nature_factory = {}
if ecology_batch_no:
ecology_factory = _load_oem_factory_from_batch(ecology_batch_no)
elif _analysis_ecology_factory_file and os.path.exists(_analysis_ecology_factory_file):
ecology_factory = AnalysisService.read_factory_data(_analysis_ecology_factory_file)
if nature_batch_no:
nature_factory = _load_oem_factory_from_batch(nature_batch_no)
elif _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:
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)):
"""下载生成的分析报表,支持指定文件名"""
if file:
file_path = _find_file(file)
if not 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(
[os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
for f in fs if f.startswith("问界生态系数分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到分析报表,请先生成")
file_path = output_files[0]
return FileResponse(
file_path,
filename=output_files[0],
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# ==================== 分析预览接口 ====================
@router.post("/analysis/preview-file")
async def analysis_preview_file(
file_type: str = Form(...), # "store" or "factory"
file: UploadFile = File(...),
):
"""上传分析文件并返回解析后的预览数据"""
file_path = _date_path(f"_preview_{file.filename}")
try:
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
if file_type == "store":
df = AnalysisService.read_store_list(file_path)
else:
data = AnalysisService.read_factory_data(file_path)
sheet_names = list(data.keys())
if sheet_names:
df = data[sheet_names[0]]
else:
df = pd.DataFrame()
import pandas as pd
rows = df.head(100).fillna("").to_dict(orient="records")
columns = list(df.columns)
return {"status": "success", "data": {"columns": columns, "rows": rows, "total": len(df)}}
except Exception as e:
logger.error(f"Analysis preview file failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"文件解析失败: {str(e)}")
finally:
if os.path.exists(file_path):
os.remove(file_path)
@router.get("/analysis/batch-data")
async def analysis_batch_data(batch_no: str = Query(...)):
"""获取历史批次数据用于右侧预览"""
import decimal
import datetime as dt
from app.services.upload_service import _get_conn
conn = _get_conn()
try:
with conn.cursor() as cur:
cur.execute(
"""SELECT id, batch_no, data_type FROM upload_batch
WHERE batch_no = %s AND status != 3""",
(batch_no,),
)
batch = cur.fetchone()
if not batch:
raise HTTPException(status_code=404, detail="批次不存在")
batch_id = batch["id"]
data_type = batch["data_type"]
if data_type == "store_guarantee":
cur.execute(
"""SELECT store_name, brand, guarantee_target, province, city,
direct_sale, area_supervision, flight_supervision, online_supervision,
guarantee_type, special_case_1, special_case_2,
ew_conversion_rate, ax_conversion_rate, battery_conversion_rate,
ew_compensation, ax_compensation, battery_compensation,
guarantee_end_date
FROM store_guarantee_config WHERE batch_id = %s""",
(batch_id,),
)
else:
cur.execute(
"""SELECT store_code, store_name, brand, province, city,
delivery_count, ew_purchase_count, ax_purchase_count,
battery_purchase_count, tire_purchase_count
FROM oem_delivery_data WHERE batch_id = %s""",
(batch_id,),
)
rows = cur.fetchall()
columns = list(rows[0].keys()) if rows else []
clean_rows = []
for r in rows:
clean = {}
for k, v in r.items():
if isinstance(v, decimal.Decimal):
clean[k] = float(v)
elif isinstance(v, (dt.date, dt.datetime)):
clean[k] = str(v)
elif v is None:
clean[k] = ""
else:
clean[k] = v
clean_rows.append(clean)
return {
"status": "success",
"data": {"columns": columns, "rows": clean_rows, "total": len(rows)},
}
finally:
conn.close()
# ==================== 鸿蒙生态分析接口 ====================
@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),
start_date: str = Form(None),
end_date: str = Form(None),
):
"""上传鸿蒙门店兜底配置、主机厂数据(产值表数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file
result = {"status": "success", "messages": []}
if store_file and store_file.filename:
fname = _build_dated_filename(store_file.filename, "harmony_store")
file_path = _date_path(fname, category="harmony")
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:
fname = _build_dated_filename(factory_file.filename, "harmony_factory", start_date, end_date)
file_path = _date_path(fname, category="harmony")
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),
store_batch_no: str = Form(None),
factory_batch_no: str = Form(None),
):
"""根据已上传的数据或历史批次生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file
# 加载store_df:优先批次DB数据,其次文件,最后默认模板
if store_batch_no:
store_df = _load_store_df_from_batch(store_batch_no)
elif _harmony_store_file and os.path.exists(_harmony_store_file):
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
else:
try:
_harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板")
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
except FileNotFoundError:
raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")
# 加载factory_df:优先批次DB数据,其次文件
factory_df = None
if factory_batch_no:
factory_df = _load_oem_factory_from_batch(factory_batch_no)
elif _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
try:
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)):
"""下载鸿蒙分析报表"""
if file:
file_path = _find_file(file)
if not 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(
[os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
for f in fs if f.startswith("鸿蒙分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到鸿蒙分析报表,请先生成")
file_path = 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.get("/strategy/{strategy_id}/penetration")
async def strategy_penetration_analysis(strategy_id: int):
"""获取策略渗透率分析数据(按天/阶段、员工、品牌、产品维度拆解 + LLM总结)"""
try:
data = StrategyService.get_penetration_analysis(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"Penetration analysis 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)}")
# ==================== 门店数据 & 主机厂数据 上传接口 ====================
# 数据导入临时上传(使用 _date_path + data 类别实现日期分级)
DATA_UPLOAD_CATEGORY = "data"
def _save_upload(file: UploadFile, brand: str, data_type: str) -> tuple:
"""保存上传文件到按日期分级的目录,返回 (文件路径, 原始文件名)"""
ts = datetime.now().strftime("%H%M%S")
base, ext = os.path.splitext(file.filename)
safe_name = f"{data_type}_{brand}_{ts}{ext}"
file_path = _date_path(safe_name, category=DATA_UPLOAD_CATEGORY)
with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f)
return file_path, file.filename
@router.post("/data-import/upload-store")
async def upload_store_guarantee(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
brand: str = Form(...),
period_start: str = Form(...),
period_end: str = Form(...),
):
"""上传门店兜底配置 Excel,导入 store_guarantee_config 表"""
logger.info(f"upload-store: filename={file.filename}, brand={brand}, period={period_start}~{period_end}")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
if brand not in ("问界", "鸿蒙"):
raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙")
file_path, original_name = _save_upload(file, brand, "store")
try:
file_size = os.path.getsize(file_path)
result = import_store_guarantee(
file_path=file_path,
original_filename=original_name,
brand=brand,
data_period_start=period_start,
data_period_end=period_end,
file_size=file_size,
)
return {"status": "success", "data": result}
except ValueError as e:
logger.warning(f"Store guarantee upload validation: {e}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Store guarantee upload failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")
@router.post("/data-import/upload-oem")
async def upload_oem_delivery(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
brand: str = Form(...),
period_start: str = Form(...),
period_end: str = Form(...),
period_type: str = Form(""),
):
"""上传主机厂交付数据 Excel,导入 oem_delivery_data 表"""
logger.info(f"upload-oem: filename={file.filename}, brand={brand}, period={period_start}~{period_end}, period_type={period_type}")
if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件")
if brand not in ("问界", "鸿蒙"):
raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙")
if period_type not in ("", "ecology", "nature"):
raise HTTPException(status_code=400, detail="周期类型仅支持 ecology 或 nature")
file_path, original_name = _save_upload(file, brand, "oem")
try:
file_size = os.path.getsize(file_path)
result = import_oem_delivery(
file_path=file_path,
original_filename=original_name,
brand=brand,
data_period_start=period_start,
data_period_end=period_end,
period_type=period_type,
file_size=file_size,
)
return {"status": "success", "data": result}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"OEM delivery upload failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")
@router.get("/data-import/history")
async def get_import_history(
brand: Optional[str] = Query(None),
data_type: Optional[str] = Query(None),
period_type: Optional[str] = Query(None),
):
"""获取上传批次历史列表"""
try:
rows = get_upload_history(brand=brand, data_type=data_type, period_type=period_type)
return {"status": "success", "data": rows}
except Exception as e:
logger.error(f"Get upload history failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")