report_utils.py
106 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
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 共用工具模块
================================
被 warranty_processor / equity_processor / inshop_processor / park_processor 共同引用。
统一封装 Excel 下载解析、安全除法、指标系统调用、幂等检查、临时目录清理等。
"""
import os
import re
import logging
import tempfile
import shutil
import time as _time
from decimal import Decimal, ROUND_HALF_UP
import pandas as pd
from models import (
DataProcessTask, DataProcessFile, BizBudgetAchieve,
ReportExtendedWarranty, ReportEquityService,
ReportLightReformInshop, ReportLightReformPark,
db,
)
from oss_utils import download_file
from indicator_client import IndicatorClient
from config import Config
logger = logging.getLogger('report_utils')
# ============================================================
# 调度器常量
# ============================================================
STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings'
# biz_type 过滤值(各表不同)
BIZ_TYPE_WARRANTY = '2.3' # 延保
BIZ_TYPE_EQUITY = '2.1' # 权益
# 指标系统 biz 编码
INDICATOR_BIZ_MAP = {
'warranty': Config.INDICATOR_BIZ_WARRANTY, # 1
'equity': Config.INDICATOR_BIZ_EQUITY, # 3
'light_reform': Config.INDICATOR_BIZ_LIGHT_REFORM, # 2
}
# ============================================================
# 任务状态管理
# ============================================================
def mark_task_failed(task_id, error_msg):
"""标记任务为失败状态(独立函数,无类依赖)。"""
try:
task = DataProcessTask.query.filter_by(id=task_id).first()
if task:
task.status = 'FAILED'
task.error_msg = (error_msg or '')[:500]
db.session.commit()
logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
except Exception as e:
logger.error(f"[标记失败] 更新失败: {e}")
db.session.rollback()
raise
def cleanup_tmp_dir(tmp_dir):
"""清理临时目录(Windows 文件占用重试 3 次)。"""
try:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir, ignore_errors=True)
for _ in range(3):
if not os.path.exists(tmp_dir):
break
_time.sleep(0.5)
shutil.rmtree(tmp_dir, ignore_errors=True)
if not os.path.exists(tmp_dir):
logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
else:
logger.warning(f"[清理] 临时目录仍被占用,跳过: {tmp_dir}")
except Exception as e:
logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")
# ============================================================
# 子任务管理(DataProcessSubtask)
# ============================================================
# 4 张输出表的类别常量 + 门店店效人效汇总表(整体合计,第5个sheet)
ALL_OUTPUT_CATEGORIES = ['warranty', 'equity', 'inshop', 'park', 'store_effect_summary']
# 子任务状态常量
SUBTASK_PENDING = 'PENDING'
SUBTASK_PROCESSING = 'PROCESSING'
SUBTASK_COMPLETED = 'COMPLETED'
SUBTASK_FAILED = 'FAILED'
def create_subtasks_for_task(task_id, output_categories=None, reset=False):
"""
为一条主任务创建子任务记录(状态 PENDING)。
幂等:已存在的 category 默认跳过(status 保持不变)。
reset=True 时,已存在的子任务状态重置为 PENDING(用于重新生成场景)。
"""
from models import DataProcessSubtask
if output_categories is None:
output_categories = ALL_OUTPUT_CATEGORIES
created = 0
reset_cnt = 0
for cat in output_categories:
existing = DataProcessSubtask.query.filter_by(
task_id=task_id, output_category=cat, is_deleted=0).first()
if existing:
if reset:
existing.status = SUBTASK_PENDING
existing.error_msg = ''
existing.row_count = None
db.session.flush()
reset_cnt += 1
continue
sub = DataProcessSubtask(
task_id=task_id,
output_category=cat,
status=SUBTASK_PENDING,
)
db.session.add(sub)
created += 1
if created or reset_cnt:
db.session.commit()
logger.info(f"[子任务] task_id={task_id} 新建 {created} 条, 重置 {reset_cnt} 条 (reset={reset})")
return created
def get_subtask(task_id, output_category):
"""查子任务,返回 DataProcessSubtask 对象或 None"""
from models import DataProcessSubtask
return DataProcessSubtask.query.filter_by(
task_id=task_id, output_category=output_category, is_deleted=0).first()
def get_subtask_status(task_id, output_category):
"""查子任务状态,返回字符串或 None(不存在)"""
sub = get_subtask(task_id, output_category)
return sub.status if sub else None
def update_subtask(task_id, output_category, status, error_msg='', row_count=None):
"""更新子任务状态/错误信息/写入行数"""
from models import DataProcessSubtask
sub = DataProcessSubtask.query.filter_by(
task_id=task_id, output_category=output_category, is_deleted=0).first()
if not sub:
# 不存在则创建一条
sub = DataProcessSubtask(task_id=task_id, output_category=output_category, status=status)
db.session.add(sub)
sub.status = status
if error_msg:
sub.error_msg = error_msg[:500]
if row_count is not None:
sub.row_count = row_count
db.session.flush()
logger.info(f"[子任务] task_id={task_id} category={output_category} → {status}"
+ (f" ({row_count} 行)" if row_count is not None else ''))
def is_subtask_completed(task_id, output_category):
"""判断该类别子任务是否已 COMPLETED(调度器跳过用)"""
return get_subtask_status(task_id, output_category) == SUBTASK_COMPLETED
def check_all_subtasks_done(task_id):
"""
判断 4 条 output_category 是否都到达终态(COMPLETED 或 FAILED)。
用于调度器最后把主任务置为 COMPLETED。
返回 (all_done: bool, completed_count: int, failed_count: int, pending_count: int)
"""
from models import DataProcessSubtask
subs = DataProcessSubtask.query.filter_by(task_id=task_id, is_deleted=0).all()
if not subs:
return False, 0, 0, len(ALL_OUTPUT_CATEGORIES)
completed = sum(1 for s in subs if s.status == SUBTASK_COMPLETED)
failed = sum(1 for s in subs if s.status == SUBTASK_FAILED)
processing = sum(1 for s in subs if s.status == SUBTASK_PROCESSING)
pending = sum(1 for s in subs if s.status == SUBTASK_PENDING)
all_done = (completed + failed) == len(ALL_OUTPUT_CATEGORIES) and processing == 0
return all_done, completed, failed, pending
# 主任务状态规则:
# - 有子任务 FAILED → 主任务置为 FAILED(自动推)
# - 全部 COMPLETED → 主任务保持 PROCESSING(等总表逻辑来推)
# 总表逻辑后续统一接入 finalize_all_subtasks_done() 时再启用
def promote_subtask_failure_to_main_task(task_id):
"""
子任务处理失败时调用:
查该 task_id 下是否有 FAILED 的子任务 → 有则把主任务置为 FAILED。
error_msg 汇总所有 FAILED 子任务的错误。
"""
from models import DataProcessTask, DataProcessSubtask
subs = DataProcessSubtask.query.filter_by(task_id=task_id, is_deleted=0).all()
if not subs:
return
failed = [s for s in subs if s.status == SUBTASK_FAILED]
if not failed:
return
task = DataProcessTask.query.filter_by(id=task_id).first()
if task and task.status == 'PROCESSING':
err_parts = [f"{s.output_category}: {s.error_msg or 'unknown'}" for s in failed]
task.status = 'FAILED'
task.error_msg = (f"子任务失败 {len(failed)}/{len(subs)}: " + '; '.join(err_parts))[:500]
db.session.commit()
logger.info(f"[主任务] task_id={task_id} → FAILED (失败 {len(failed)} 条子任务)")
# 保留旧函数名做兼容,内部改为查子任务表
def is_output_already_done(task_id, output_category):
"""幂等检查(兼容旧调用):判断子任务是否已 COMPLETED"""
return is_subtask_completed(task_id, output_category)
# ============================================================
# Excel 下载 & 解析
# ============================================================
def download_all_files(task_id, tmp_dir):
"""
下载 task_id 关联的所有 Excel 文件到 tmp_dir。
返回 {form_type: local_path} (下载失败则值为 None)。
"""
files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
result = {}
for f in files:
if not f.file_url:
logger.warning(f"[文件下载] form_type={f.form_type} 无 file_url,跳过")
continue
local_path = os.path.join(tmp_dir, f.file_name or f"{f.form_type}.xlsx")
try:
download_file(f.file_url, local_path)
result[f.form_type] = local_path
logger.info(f"[文件下载] {f.form_type} OK → {local_path}")
except Exception as e:
logger.error(f"[文件下载] {f.form_type} 失败: {e}")
result[f.form_type] = None
return result
def match_columns(columns, keywords_map):
"""
模糊匹配列名。
keywords_map = {标准名: [关键词列表]},返回 {标准名: 列名str 或 列索引int}。
支持 ordinal 语法处理重复列名:
keywords_map 中某个 keyword 可为 ("本月占比", 4) → 取第 4 个匹配的列,返回其**整数索引**
普通字符串 keyword 保持原有精确→子串匹配逻辑,返回**列名字符串**。
返回值类型说明(调用方需兼容):
- 匹配到重复列名(ordinal)→ 返回 int(列索引)
- 匹配到唯一列名(普通) → 返回 str(列名字符串)
这样 pandas 取值时:df.iloc[:, col_idx](int)或 df[col_name](str)都能正确工作。
匹配优先级:先精确相等(列名 strip 后与关键词完全一致),再子串包含。
"""
result = {}
# —— 先处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)——
for std, keywords in keywords_map.items():
for kw in keywords:
if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int):
target_name, ordinal = kw[0], kw[1]
# 收集所有匹配该列名的**位置索引**
matches_idx = [i for i, col in enumerate(columns)
if str(col).strip() == target_name or target_name in str(col).strip()]
if len(matches_idx) >= ordinal:
result[std] = matches_idx[ordinal - 1] # 返回 int 索引
elif matches_idx:
logger.warning(f"[match_columns] {std} 期望第 {ordinal} 个 '{target_name}' 列,实际只有 {len(matches_idx)} 个,取最后一个")
result[std] = matches_idx[-1]
else:
logger.warning(f"[match_columns] {std} 未找到 '{target_name}' 列")
break
# —— 再处理普通 keyword(返回 str 列名)——
# 第一遍:精确相等
for std, keywords in keywords_map.items():
if std in result:
continue
for kw in keywords:
if isinstance(kw, tuple):
continue
for col in columns:
c = str(col).strip()
if c == kw:
result[std] = col
break
if std in result:
break
# 第二遍:子串包含(仅补充未命中的标准名)
for std, keywords in keywords_map.items():
if std in result:
continue
for kw in keywords:
if isinstance(kw, tuple):
continue
for col in columns:
col_lower = str(col).lower()
if kw.lower() in col_lower:
result[std] = col
break
if std in result:
break
return result
# 表头行常见关键字(用于打分挑选真实表头行,避免误把含「门店」的标题行当表头)
HEADER_HINT_KEYWORDS = [
'门店', '品牌', '省份', '城市', '区域运营', '业务类型', '预估产值',
'驻店类型', '大区经理', '业务负责人', '培训督导', '门店类型', '业务经理',
'园区', '片区', '序号',
]
def find_header_row(df, max_scan=8):
"""
在 DataFrame 前 max_scan 行中,挑选「表头特征关键字命中最多」的一行作为表头行。
解决标题行(如「8月SAAS+延保权益门店预算分解」)也含「门店」导致误判为表头的问题。
找不到任何命中的返回 0。
"""
best_i, best_score = 0, 0
for i in range(min(max_scan, len(df))):
row_vals = [str(v) if v is not None else '' for v in df.iloc[i].tolist()]
score = sum(1 for v in row_vals if any(k in v for k in HEADER_HINT_KEYWORDS))
if score > best_score:
best_score, best_i = score, i
return best_i
def parse_saas_base(file_path, biz_type_filter):
"""
解析 SAAS门店预算分解表 sheet1,按 biz_type_filter 过滤。
返回 list[dict]:store_name / brand / province / city / region_manager /
training_supervisor / biz_manager / resident_type
"""
logger.info(f"[SAAS预算分解] 解析 {file_path}, 过滤 biz_type={biz_type_filter}")
df_raw = pd.read_excel(file_path, sheet_name=0, header=None)
header_row = find_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=0, header=header_row)
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类', 'biz_type'],
'store_name': ['门店名称', '门店名', '门店', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省', 'province'],
'city': ['城市', '市', 'city'],
'region_manager': ['区域运营', '区域经理', '大区经理'],
'training_supervisor': ['培训督导', '督导'],
'biz_manager': ['业务经理','业务负责人'],
'resident_type': ['驻店类型', '驻店'],
})
logger.info(f"[SAAS预算分解] 匹配列: {col_map}")
biz_col = col_map.get('biz_type')
store_col = col_map.get('store_name')
if not store_col:
logger.error("[SAAS预算分解] 未找到门店名列")
return []
result = []
def _safe_str(val):
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('nan', 'None'):
return ''
return str(val).strip()
for _, row in df.iterrows():
if biz_col:
bt = _safe_str(row.get(biz_col))
if bt and bt != biz_type_filter:
continue
sn = _safe_str(row.get(store_col))
if not sn:
continue
result.append({
'store_name': sn,
'brand': _safe_str(row.get(col_map.get('brand'))) if col_map.get('brand') else '',
'province': _safe_str(row.get(col_map.get('province'))) if col_map.get('province') else '',
'city': _safe_str(row.get(col_map.get('city'))) if col_map.get('city') else '',
'region_manager': _safe_str(row.get(col_map.get('region_manager'))) if col_map.get('region_manager') else '',
'training_supervisor': _safe_str(row.get(col_map.get('training_supervisor'))) if col_map.get('training_supervisor') else '',
'biz_manager': _safe_str(row.get(col_map.get('biz_manager'))) if col_map.get('biz_manager') else '',
'resident_type': _safe_str(row.get(col_map.get('resident_type'))) if col_map.get('resident_type') else '',
})
logger.info(f"[SAAS预算分解] biz_type={biz_type_filter} 共 {len(result)} 条")
return result
def parse_region_map(file_path):
"""
解析关系表,按 (业务类型, 省份) → 片区。
返回 dict[(biz_type, province)] = region_area (额外包含 ('', province) fallback)。
"""
logger.info(f"[关系表] 解析 {file_path}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning("[关系表] 读取失败,跳过")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类'],
'province': ['省份', '省'],
'region_area': ['片区', '大区'],
})
if 'region_area' not in col_map or 'province' not in col_map:
logger.warning("[关系表] 缺少 片区/省份 关键列")
return {}
result = {}
for _, row in df.iterrows():
prov = str(row.get(col_map['province'], '')).strip()
area = str(row.get(col_map['region_area'], '')).strip()
if not prov or not area:
continue
bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
result[(bt, prov)] = area
result[('', prov)] = area
logger.info(f"[关系表] 片区映射 {len(result)} 条")
return result
def parse_delivery_table(file_path):
"""
解析主机厂交车数据表(鸿蒙/广联共用结构)。
自动探测 header 行:先试 header=0,找不到 store_name 再试 header=1。
鸿蒙表有两层表头(row0=合并表头/row1=真实列名),广联表 header=0 就是真实列名。
返回 dict[store_name] = delivery_cnt (int)。
"""
logger.info(f"[主机厂交车] 解析 {file_path}")
KEYWORDS = {
# 鸿蒙 header=1 列名: 门店名称 / 总交付
# 广联 header=0 列名: 厅店名称 / 交付量
'store_name': ['基础信息-门店名称', '厅店名称', '门店名称', '基础信息-门店', '门店', '用户中心门店名称'],
'delivery': ['主机厂数据-总交付', '总交付', '交付量', '交车数', '主机厂数据'],
}
df = None
col_map = {}
used_header = 0
for hdr in (0, 1):
try:
_df = pd.read_excel(file_path, header=hdr)
except Exception:
continue
_df.columns = [str(c).strip() if c else '' for c in _df.columns]
_col_map = match_columns(_df.columns, KEYWORDS)
if 'store_name' in _col_map:
df = _df
col_map = _col_map
used_header = hdr
break
logger.info(f"[主机厂交车] header={hdr} 未找到 store_name,重试 header={hdr+1}")
if df is None:
logger.warning(f"[主机厂交车] 所有 header 都未匹配到门店名列,跳过 {file_path}")
return {}
logger.info(f"[主机厂交车] {file_path} header={used_header} 列映射: {dict(col_map)}")
store_col = col_map['store_name']
delivery_col = col_map.get('delivery')
result = {}
for _, row in df.iterrows():
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
cnt = 0
if delivery_col:
try:
v = row.get(delivery_col, 0)
if v is not None and not pd.isna(v):
cnt = int(float(v))
except (ValueError, TypeError):
cnt = 0
result[sn] = result.get(sn, 0) + cnt
logger.info(f"[主机厂交车] {file_path} → {len(result)} 个门店")
return result
def merge_delivery_maps(*maps):
"""
合并多个主机厂交车 map(鸿蒙 + 广联)。
跨表门店名可能不一致(如鸿蒙叫"AITO深圳华为中心",广联叫"深圳华为中心"),
用 fuzzy_match_store 模糊包含匹配合并到同一条。
返回 dict[统一后门店名] = 总交车数。
"""
merged = {}
for m in maps:
if not m:
continue
for store_name, cnt in m.items():
# 在 merged 里模糊找已有门店
hit_key = fuzzy_match_store(store_name, merged, return_key=True)
if hit_key:
merged[hit_key] = merged[hit_key] + cnt
else:
merged[store_name] = cnt
logger.info(f"[主机厂交车合并] {len(maps)} 张表合并后 → {len(merged)} 个门店")
return merged
# ============================================================
# 指标系统 API
# ============================================================
def fetch_indicator_data(start_str, end_str, biz_code, item_codes):
"""
调指标系统 API,返回 {merchantName: {itemCode: itemValue}}。
start_str / end_str: 'YYYY-MM-DD' 字符串,空则返回 {}。
biz_code: int 单值 或 list/tuple 多业务线(如 [1,3],序列化为 bizs="1,3")。
"""
if not start_str or not end_str or not item_codes:
return {}
logger.info(f"[IndicatorAPI-fetch] dates={start_str}~{end_str} biz_code={biz_code} item_codes={item_codes}")
client = IndicatorClient()
return client.fetch(start_str, end_str, biz_code, item_codes)
# ============================================================
# 安全除法 / 百分比
# ============================================================
def safe_div(numerator, denominator, scale=2):
"""Decimal 安全除法,分母为 0 返回 Decimal('0')。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) / Decimal(str(denominator))).quantize(
Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def safe_div_pct(numerator, denominator):
"""整数/整数 → 百分比(*100),保留百分比后 2 位小数 → Decimal(10,6)。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def safe_div_pct_decimal(numerator, denominator):
"""Decimal/Decimal → 百分比(*100)。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
result = (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
# 防 DECIMAL(10,6) 列溢出:脏数据(分母极小)会让比值远超 ±9999.999999,
# 直接写入会整行 INSERT 失败、进而污染整个任务。超界截断并告警以便核对。
_MAX = Decimal('9999.999999')
if result > _MAX or result < -_MAX:
logger.warning(f"[比率clamp] 超出 DECIMAL(10,6) 已截断: num={numerator} den={denominator} -> {result}")
result = min(max(result, -_MAX), _MAX)
return result
except Exception:
return Decimal('0')
def clamp_ratio(value, max_abs=Decimal('9999.999999')):
"""比率列(DECIMAL(10,6))写入前的安全截断,防脏数据超界导致整行 INSERT 失败。"""
try:
v = Decimal(str(value))
except Exception:
return Decimal('0')
if v > max_abs or v < -max_abs:
logger.warning(f"[比率clamp] 超出 DECIMAL(10,6) 已截断: value={value} -> {max_abs if v > 0 else -max_abs}")
return max_abs if v > 0 else -max_abs
return v
def prev_month(month_str):
"""'2026-09' → '2026-08'"""
if not month_str or '-' not in month_str:
return ''
try:
parts = month_str.split('-')
y = int(parts[0])
m = int(parts[1])
if m == 1:
y -= 1
m = 12
else:
m -= 1
return f"{y}-{m:02d}"
except Exception:
return ''
def fetch_prev_month_labor_ratio(task, base_records):
"""
从上月 BizBudgetAchieve 表取人员工资占比 → 营销费用占比。
store_name 模糊匹配 target_name。
返回 dict[store_name] = Decimal
"""
current_month = getattr(task, 'month', '')
pm = prev_month(current_month)
if not pm:
return {}
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
if not store_names:
return {}
results = {}
try:
rows = BizBudgetAchieve.query.filter(
BizBudgetAchieve.month == pm,
BizBudgetAchieve.is_deleted == 0,
).all()
for row in rows:
target = getattr(row, 'target_name', '') or ''
ratio = getattr(row, 'personnel_salary_ratio_current', None)
if ratio is None:
continue
for sn in store_names:
if sn in target or target in sn:
results[sn] = Decimal(str(ratio))
break
logger.info(f"[上月占比] month={pm} 匹配 {len(results)}/{len(store_names)}")
except Exception as e:
logger.warning(f"[上月占比] 查询失败: {e}")
return results
def parse_budget_achieve_excel(file_path, biz_type=None):
"""
解析上传的"预算达成数据(商务)"Excel 文件。
一个文件同时服务多个场景:
- 延保 (biz_type='2.3') / 权益 (biz_type='2.1'):人员工资占比 → 营销费用占比
- 轻改店中店/园区店 (biz_type='1.1'):装修分摊 / 房租水电 / 门店耗材 / 服务费占比
:param file_path: Excel 文件路径
:param biz_type: 业务类型过滤值('1.1'/'2.1'/'2.3'),None 则不按业务类型过滤
匹配到同门店同业务类型多行时,数值字段取**平均**,文本字段取第一条
门店名映射列:流量费名称 / 流量方名称 / 门店名。
返回 dict[store_name] = {5 个字段 Decimal}
"""
logger.info(f"[预算达成Excel] 解析 {file_path}, biz_type={biz_type}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning(f"[预算达成Excel] 读取失败 {file_path}")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'],
'biz_type': ['业务类型', '业务线'],
# 人员工资占比 → 营销费用占比:Excel header=None row0 有 5 个同名"本月占比"
# header=0 下 pandas 自动加后缀 .1~.4,ordinal 子串匹配能命中全部 5 个
# 第 1 个=成本占比(col11) / 第 2 个=流量费占比(col14) / 第 3 个=服务费占比(col17)
# 第 4 个=市场费占比(col23) / 第 5 个=营销团队工资占比(col31) ← 延保/权益要这个
'labor_ratio': [("本月占比", 5), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'],
'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'],
'store_consumables': ['门店耗材', '耗材'],
# 服务费占比 = 第 3 个本月占比(col17),与 labor_ratio(第5个) 不冲突
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 3)],
})
if 'store_name' not in col_map:
logger.warning("[预算达成Excel] 未找到门店名列")
return {}
# 诊断:打印列映射,方便验证"第 N 个本月占比"是否正确命中
logger.info(f"[预算达成Excel] 列映射: {dict(col_map)}")
store_col = col_map['store_name']
biz_col = col_map.get('biz_type')
field_cols = {k: v for k, v in col_map.items() if k not in ('store_name', 'biz_type')}
# 兼容:col 值可能是 str(唯一列名)或 int(ordinal 重复列索引)
def _get(row, col_ref):
"""row 取值:col_ref=int → iloc;col_ref=str → []"""
if isinstance(col_ref, int):
try:
return row.iloc[col_ref]
except Exception:
return None
return row.get(col_ref, None)
# 先收集所有值,同门店同 biz_type 多行 → sum+count → 最后取平均
# 聚合 key = (store_name, biz_type_val)
agg = {} # (sn, bt_val) → {field: [sum, count]}
for _, row in df.iterrows():
sn = str(_get(row, store_col) or '').strip()
if not sn or sn in ('nan', 'None', ''):
continue
bt_val = str(_get(row, biz_col) or '').strip() if biz_col else ''
# 如果没找到 biz_type 列或传入了过滤条件,按过滤条件匹配
if biz_type is not None and biz_col:
if bt_val != biz_type:
continue
key = (sn, bt_val) if biz_col else (sn, '')
if key not in agg:
agg[key] = {}
for field, col in field_cols.items():
val = _get(row, col)
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'):
continue
try:
d = Decimal(str(val))
except Exception:
continue
if field not in agg[key]:
agg[key][field] = [Decimal('0'), 0]
agg[key][field][0] += d
agg[key][field][1] += 1
# 取平均
result = {}
for (sn, _bt), fields in agg.items():
if sn not in result:
result[sn] = {
'labor_ratio': Decimal('0'),
'renovation_amortization': Decimal('0'),
'rent_utilities': Decimal('0'),
'store_consumables': Decimal('0'),
'service_provider_share_ratio': Decimal('0'),
}
for field, (total, cnt) in fields.items():
if cnt > 0:
result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)
logger.info(f"[预算达成Excel] {len(result)} 个门店匹配")
return result
def extract_budget_ratio(budget_map, store_name, field='labor_ratio'):
"""
从 parse_budget_achieve_excel 返回值中安全取单个字段。
匹配逻辑:只做门店名**精确匹配**,取不到返回 Decimal('0')。
营销费用/服务费等占比必须精准对应门店,避免模糊匹配串店。
"""
if not budget_map or not store_name:
return Decimal('0')
entry = budget_map.get(store_name)
if entry is None:
return Decimal('0')
val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0')
return val or Decimal('0')
def prorate_by_period(total_amount, period_start, period_end):
"""
按"当前统计周期天数 / 月份总天数"摊销费用。
装修分摊/房租水电/门店耗材 等月度固定费用需要按周期天数折算。
period_start/period_end: date 对象。
返回 Decimal。
"""
if not total_amount or total_amount == 0:
return Decimal('0')
try:
# 周期天数
if period_start and period_end:
period_days = (period_end - period_start).days + 1
else:
period_days = 30 # fallback
# 月份总天数(按 period_start 所在月算)
if period_start:
import calendar
month_total = calendar.monthrange(period_start.year, period_start.month)[1]
else:
month_total = 30
if month_total <= 0:
return Decimal(str(total_amount))
return (Decimal(str(total_amount)) * Decimal(str(period_days)) / Decimal(str(month_total))
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal(str(total_amount))
# ============================================================
# 轻改店中店 - 专属解析函数
# ============================================================
# 轻改品牌关键字(sheet2 过滤用)
LIGHT_REFORM_BRAND_KEYWORDS = ['鸿蒙', 'AITO', '问界', '智界', '享界', '尚界', '尊界']
# 经营属性映射(驻店类型 → 直营/服务商)
RESIDENT_TYPE_MAP = {
'直营': '直营',
'服务商': '服务商',
}
def parse_saas_base_sheet2(file_path):
"""
解析 SAAS门店预算分解表 sheet2,按品牌关键字过滤。
返回 list[dict]:基础门店维度(园区/品牌/业务线/经营属性等)。
"""
logger.info(f"[SAAS预算分解-sheet2] 解析 {file_path}")
df_raw = pd.read_excel(file_path, sheet_name=1, header=None)
header_row = find_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=1, header=header_row)
# 归一化表头:去掉所有空白(含 \n \r \t),避免 Excel 换行表头导致匹配失败
df.columns = [re.sub(r'\s+', '', str(c)) if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'park_name': ['园区名称', '园区'],
'store_name': ['门店名称', '门店名', '门店', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省'],
'city': ['城市', '市'],
'park_type': ['园区类型'],
'biz_line': ['业务线', '业务类型'],
# 同时返回 operate_type 和 resident_type(兼容不同 processor 叫法)
'operate_type': ['驻店类型', '经营属性', '驻店'],
'resident_type': ['驻店类型', '经营属性', '驻店'],
'training_supervisor': ['培训督导'],
'region_manager': ['区域经理', '区域运营'],
'avg_price_target': ['预估平均客单价', '平客目标值', '预估平均客单价'],
})
logger.info(f"[SAAS预算分解-sheet2] 匹配列: {col_map}")
if 'store_name' not in col_map:
logger.error("[SAAS预算分解-sheet2] 未找到门店名列")
return []
brand_col = col_map.get('brand')
store_col = col_map['store_name']
park_col = col_map.get('park_name')
result = []
def _safe_str(val):
"""pandas NaN / None → 空字符串,否则 strip"""
import pandas as _pd
if val is None or (isinstance(val, float) and _pd.isna(val)) or str(val).strip() in ('nan', 'None'):
return ''
return str(val).strip()
for _, row in df.iterrows():
# 品牌关键字过滤
brand_val = _safe_str(row.get(brand_col)) if brand_col else ''
brand_text = (brand_val + ' ' + _safe_str(row.get(store_col))).strip()
if brand_val and not any(kw in brand_text for kw in LIGHT_REFORM_BRAND_KEYWORDS):
continue
sn = _safe_str(row.get(store_col))
if not sn:
continue
result.append({
'park_name': _safe_str(row.get(col_map.get('park_name'))) if col_map.get('park_name') else '',
'store_name': sn,
'brand': brand_val,
'province': _safe_str(row.get(col_map.get('province'))) if col_map.get('province') else '',
'city': _safe_str(row.get(col_map.get('city'))) if col_map.get('city') else '',
'park_type': _safe_str(row.get(col_map.get('park_type'))) if col_map.get('park_type') else '',
'biz_line': _safe_str(row.get(col_map.get('biz_line'))) or '1.1',
'operate_type': _safe_str(row.get(col_map.get('operate_type'))) if col_map.get('operate_type') else '',
'resident_type': _safe_str(row.get(col_map.get('resident_type'))) if col_map.get('resident_type') else '',
'training_supervisor': _safe_str(row.get(col_map.get('training_supervisor'))) if col_map.get('training_supervisor') else '',
'region_manager': _safe_str(row.get(col_map.get('region_manager'))) if col_map.get('region_manager') else '',
'avg_price_target': _to_decimal(row.get(col_map.get('avg_price_target', ''), '')) if col_map.get('avg_price_target') else Decimal('0'),
})
logger.info(f"[SAAS预算分解-sheet2] 品牌过滤后共 {len(result)} 条")
return result
def parse_saas_base_sheet2_exclude(file_path):
"""
解析 SAAS门店预算分解表 sheet2,按品牌关键字**反过滤**(不包含关键字的保留)。
用于轻改园区店。
返回 list[dict]:同 parse_saas_base_sheet2,额外带 est_delivery_cnt / est_output_value / est_output_value_original
"""
logger.info(f"[SAAS预算分解-sheet2-exclude] 解析 {file_path}")
df_raw = pd.read_excel(file_path, sheet_name=1, header=None)
header_row = find_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=1, header=header_row)
# 关键:去掉所有空白(含 \n \r \t),否则 Excel 带换行的表头(如"预估产值\n(预算目标)")
# 无法被 match_columns 的子串匹配命中 → est_output_value 永远取不到值
df.columns = [re.sub(r'\s+', '', str(c)) if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'park_name': ['园区名称', '园区'],
'store_name': ['门店名称', '门店名', '门店', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省'],
'city': ['城市', '市'],
'park_type': ['园区类型'],
'operate_type': ['驻店类型', '经营属性', '驻店'],
'region_manager': ['区域经理', '区域运营'],
'avg_price_target': ['预估平均客单价', '平客目标值'],
'est_delivery_cnt': ['预估交车数'],
# 关键词按业务实际优先级排序:先纠偏(用户明确要求取纠偏列),再预算目标,最后兜底
# 业务 Excel sheet2 表头有 \n 换行 + 英文半角括号,已在上方做了全空白归一化
'est_output_value': [
# —— 纠偏优先(ORM 注释虽写"预算目标",但用户确认实际取纠偏列)——
'预估产值(纠偏)', '预估产值(纠偏)', '预估产值纠偏',
# —— 预算目标备选(有些旧表可能只有这一列)——
'预估产值(预算目标)', '预估产值(预算目标)', '预估产值预算目标',
# —— 无括号近似词兜底 ——
'预估总产值',
# —— 最短兜底(任何含"预估产值"的列都能命中)——
'预估产值',
],
})
if 'store_name' not in col_map:
logger.error("[SAAS预算分解-sheet2-exclude] 未找到门店名列")
return []
brand_col = col_map.get('brand')
store_col = col_map['store_name']
result = []
def _safe_str(val):
"""pandas NaN / None → 空字符串,否则 strip"""
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('nan', 'None'):
return ''
return str(val).strip()
for _, row in df.iterrows():
brand_val = _safe_str(row.get(brand_col)) if brand_col else ''
brand_text = (brand_val + ' ' + _safe_str(row.get(store_col))).strip()
# 反过滤:包含关键字 → 跳过
if brand_val and any(kw in brand_text for kw in LIGHT_REFORM_BRAND_KEYWORDS):
continue
sn = _safe_str(row.get(store_col))
if not sn:
continue
result.append({
'park_name': _safe_str(row.get(col_map.get('park_name'))) if col_map.get('park_name') else '',
'store_name': sn,
'brand': brand_val,
'province': _safe_str(row.get(col_map.get('province'))) if col_map.get('province') else '',
'city': _safe_str(row.get(col_map.get('city'))) if col_map.get('city') else '',
'park_type': _safe_str(row.get(col_map.get('park_type'))) or '园区店',
'operate_type': _safe_str(row.get(col_map.get('operate_type'))) if col_map.get('operate_type') else '',
'region_manager': _safe_str(row.get(col_map.get('region_manager'))) if col_map.get('region_manager') else '',
'avg_price_target': _to_decimal(row.get(col_map.get('avg_price_target', ''), '')) if col_map.get('avg_price_target') else Decimal('0'),
'est_delivery_cnt': _to_int(row.get(col_map.get('est_delivery_cnt', ''), 0)) if col_map.get('est_delivery_cnt') else 0,
'est_output_value': _to_decimal(row.get(col_map.get('est_output_value', ''), '')) if col_map.get('est_output_value') else Decimal('0'),
})
logger.info(f"[SAAS预算分解-sheet2-exclude] 反过滤后共 {len(result)} 条")
return result
def _to_decimal(val):
"""安全转 Decimal"""
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'):
return Decimal('0')
try:
return Decimal(str(val))
except Exception:
return Decimal('0')
def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fields, biz_type=None):
"""
通用聚合器:按 (store_name, biz_type) 过滤后,同门店多行 → 数值字段求和取平均,文本字段取第一条。
返回 dict[store_name] = {field: value}。
"""
biz_col = col_map.get('biz_type')
logger.info(f"[_aggregate_by_biz_type] biz_col={biz_col}, 目标biz_type={biz_type}, 总行数={len(df)}")
# 诊断:如果有 biz_col,打印实际有哪些值
if biz_col and biz_type is not None:
actual_vals = df.iloc[:, df.columns.get_loc(biz_col)].astype(str).str.strip().unique().tolist()
logger.info(f"[_aggregate_by_biz_type] 业务类型列实际值={actual_vals}, 目标值={biz_type}")
skipped_by_biz = 0
agg = {} # (sn, bt) → {field: [sum, count]} for numeric, 'text'→first_val for text
for _, row in df.iterrows():
sn = str(row.get(store_name_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
bt_val = str(row.get(biz_col, '')).strip() if biz_col else ''
if biz_type is not None and biz_col and bt_val != biz_type:
skipped_by_biz += 1
continue
key = (sn, bt_val) if biz_col else (sn, '')
if key not in agg:
agg[key] = {}
for f in numeric_fields:
col = col_map.get(f)
if not col:
continue
val = row.get(col, None)
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'):
continue
try:
d = Decimal(str(val))
except Exception:
continue
if f not in agg[key]:
agg[key][f] = [Decimal('0'), 0]
agg[key][f][0] += d
agg[key][f][1] += 1
for f in text_fields:
col = col_map.get(f)
if not col:
continue
val = str(row.get(col, '')).strip()
if val in ('', 'nan', 'None'):
continue
# 文本字段:第一条非空值覆盖
if f not in agg[key] or not agg[key][f]:
agg[key][f] = val
if skipped_by_biz > 0:
logger.warning(f"[_aggregate_by_biz_type] 因biz_type过滤跳过 {skipped_by_biz} 行")
result = {}
for (sn, _bt), fields in agg.items():
if sn not in result:
result[sn] = {}
for f, v in fields.items():
if isinstance(v, list):
# 数值 [sum, count] → 取平均
total, cnt = v
result[sn][f] = (total / Decimal(str(cnt))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0')
else:
result[sn][f] = v
return result
def _read_excel_with_auto_header(file_path, primary_col_keywords):
"""
读取 Excel,自动扫描前 5 行找到正确的表头行。
判断依据:该行包含 primary_col_keywords 中的任意一个关键词(作为子串)。
返回 (df, header_row_idx);找不到则 header_row_idx=None 返回 (None, None)。
"""
try:
raw = pd.read_excel(file_path, header=None)
except Exception as e:
logger.warning(f"[_read_excel_auto_header] 读取失败 {file_path}: {e}")
return None, None
for i in range(min(5, len(raw))):
row_vals = [str(c).strip() if c is not None else '' for c in raw.iloc[i].tolist()]
hit = any(any(kw in v for v in row_vals if v) for kw in primary_col_keywords)
if hit:
df = pd.read_excel(file_path, header=i)
logger.info(f"[_read_excel_auto_header] 自动选定 header={i}, 列={[str(c).strip() for c in df.columns.tolist()]}")
return df, i
logger.warning(f"[_read_excel_auto_header] 前 5 行均未命中关键词 {primary_col_keywords}")
return None, None
def parse_inshop_delivery_touch(file_path):
"""
解析店中店交车触客表(区域运营填写)。
只按门店名称聚合,不按业务类型过滤(Excel 无业务类型列)。
同门店多行时,数值字段取**平均**。
返回 dict[store_name] = {...}
"""
logger.info(f"[店中店交车触客表] 解析 {file_path}")
df, header_idx = _read_excel_with_auto_header(file_path, ['门店名称', '门店名'])
if df is None:
logger.warning("[店中店交车触客表] 未找到有效表头行")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'],
'sales_order_cnt': ['销售大定数', '销售大定'],
'sales_touch_cnt': ['销售触客数', '销售触客'],
'delivery_cnt': ['交车数', '交车'],
'delivery_touch_cnt': ['交付触客数', '交付触客'],
'aftersales_baohui_cnt': ['售后首保回厂', '首保回厂'],
'aftersales_shigu_cnt': ['售后事故回厂', '事故回厂'],
'aftersales_touch_cnt': ['售后触客数', '售后触客'],
'purchase_indicator': ['采买', '兜底指标', '采买兜底'],
})
logger.info(f"[店中店交车触客表] header={header_idx}, 列映射={col_map}")
if 'store_name' not in col_map:
logger.warning("[店中店交车触客表] 未找到门店名列")
return {}
numeric = ['sales_order_cnt', 'sales_touch_cnt', 'delivery_cnt', 'delivery_touch_cnt',
'aftersales_baohui_cnt', 'aftersales_shigu_cnt', 'aftersales_touch_cnt']
text = ['purchase_indicator']
# 不传 biz_type → _aggregate_by_biz_type 内部 biz_col=None,不做业务类型过滤
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, text, biz_type=None)
# int 字段转回 int
result = {}
for sn, v in raw.items():
result[sn] = {k: int(v[k]) if k in numeric and v.get(k) else int(Decimal('0')) for k in numeric}
result[sn]['purchase_indicator'] = v.get('purchase_indicator', '')
logger.info(f"[店中店交车触客表] {len(result)} 个门店")
return result
def _to_int(val):
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'):
return 0
try:
return int(float(val))
except Exception:
return 0
def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
"""
解析商务政策表(店中店处理版)。
Excel 结构:
row0: 分类表头(施工成本前置/后置/一线激励)
row1: 真实列名(门店名称, 窗膜(原厂), ..., 窗膜, 车衣, 精品(后置), 一线激励(前置)...)
row2: 序号行 ('1', '2', '3'...) ← 必须 skip!
row3+: 真实数据
"""
logger.info(f"[商务政策-店中店] 解析 {file_path}, biz_type={biz_type}")
try:
# header=1(row2),skiprows=[2] 跳过序号行
df = pd.read_excel(file_path, header=1, skiprows=[2])
except Exception:
logger.warning(f"[商务政策-店中店] 读取失败 {file_path}")
return {}
df.columns = [re.sub(r'\s+', '', str(c)) if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
# 施工成本(前置)台/元 → row0 分类表头下的 row1 列名
'oe_window_film_cost': ['窗膜(原厂)', '窗膜(原厂)'],
'oe_car_wrap_cost': ['车衣(原厂)', '车衣(原厂)'],
'oe_premium_cost': ['精品(原厂)', '精品(原厂)'],
'pedal_cost': ['踏板'],
'nonoe_window_film_cost': ['窗膜(副厂)', '窗膜(副厂)'],
'nonoe_car_wrap_cost': ['车衣(副厂)', '车衣(副厂)'],
'nonoe_premium_cost': ['精品(副厂)', '精品(副厂)'],
# 施工成本(后置)台/元 → Excel 列名就是 "窗膜" "车衣" "精品"
'construction_cost_post_film': ['窗膜'],
'construction_cost_post_wrap': ['车衣'],
'construction_cost_post_premium': ['精品'],
# 一线激励
'frontline_incentive_ratio': ['一线激励(前置)', '一线激励(前置)', '一线激励前置', '一线激励'],
})
if 'store_name' not in col_map:
logger.warning(f"[商务政策-店中店] 未找到门店名列 (实际列={list(df.columns)[:15]})")
return {}
numeric_fields = [k for k in col_map if k not in ('store_name', 'biz_type')]
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric_fields, [], biz_type)
# 所有数值字段默认 Decimal('0')
result = {}
default = {f: Decimal('0') for f in numeric_fields}
# 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100
pct_fields = {'frontline_incentive_ratio'}
for sn, v in raw.items():
merged = dict(default)
merged.update({k: v[k] for k in numeric_fields if k in v})
# 比例字段 ×100(pandas 自动把 Excel 百分比转成小数)
for pf in pct_fields:
if pf in merged and merged[pf] != 0:
merged[pf] = (merged[pf] * Decimal('100')).quantize(Decimal('0.01'))
# 合并后置施工成本 3 列为合计
merged['construction_cost_post'] = (
merged.get('construction_cost_post_film', Decimal('0')) +
merged.get('construction_cost_post_wrap', Decimal('0')) +
merged.get('construction_cost_post_premium', Decimal('0'))
)
result[sn] = merged
logger.info(f"[商务政策-店中店] {len(result)} 个门店")
return result
def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
"""
解析人力成本表(加密文件密码默认 2026)。
返回 dict[store_name] = headcount (int)
过滤条件:检核列值为 truthy(1.0/True/'TUER'), 人员业务归属=biz_type,
岗位=门店销售/精品内勤/前台/调度质检员, 排除已离职
"""
import tempfile, os, io
logger.info(f"[人力成本表] 解析 {file_path}, biz_type={biz_type}")
# 解密加密的 Excel(密码通常是 2026)
actual_path = file_path
is_tmp = False
try:
import msoffcrypto
with open(file_path, 'rb') as f:
of = msoffcrypto.OfficeFile(f)
if of.is_encrypted():
of.load_key(password=password)
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_labor_')
with os.fdopen(tmp_fd, 'wb') as tmp_f:
of.decrypt(outfile=tmp_f) # 新版 API:outfile 需是文件对象
actual_path = tmp_path
is_tmp = True
logger.info(f"[人力成本表] 解密成功(密码={password})")
except ImportError:
logger.warning("[人力成本表] msoffcrypto 未安装,尝试直接读取")
except Exception as e:
logger.warning(f"[人力成本表] 解密失败({e}),尝试直接读取")
try:
df = pd.read_excel(actual_path)
except Exception as e:
logger.warning(f"[人力成本表] 读取失败 {file_path}: {e}")
if is_tmp:
os.unlink(actual_path)
return {}
finally:
if is_tmp:
try:
os.unlink(actual_path)
except Exception:
pass
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['入驻门店', '门店名称', '门店名'],
'verify': ['检核业务线'],
'biz_type': ['人员业务归属', '业务类型', '业务线'],
'position': ['岗位', '职位'],
})
logger.info(f"[人力成本表] 列映射: {col_map}")
if 'store_name' not in col_map:
logger.warning(f"[人力成本表] 未找到门店名列 (实际列={list(df.columns)[:15]})")
return {}
target_positions = ['门店销售', '精品内勤', '前台', '调度质检员']
verify_col = col_map.get('verify')
biz_col = col_map.get('biz_type')
pos_col = col_map.get('position')
result = {}
skip_verify = skip_biz = skip_pos = 0
for _, row in df.iterrows():
# 检核业务线 = True
if verify_col:
v = row.get(verify_col)
if v is not True:
skip_verify += 1
continue
# 人员业务归属 = biz_type
if biz_col:
bt_raw = row.get(biz_col)
bt = str(bt_raw).strip() if bt_raw is not None else ''
# pandas 可能把 '1.1' 读成 float 1.1
try:
fbt = float(bt)
bt = str(fbt) if fbt == int(fbt) else str(fbt)
except (ValueError, TypeError):
pass
if bt != biz_type:
skip_biz += 1
continue
# 岗位筛选
if pos_col:
pos = str(row.get(pos_col, '')).strip()
if pos and not any(t in pos for t in target_positions):
skip_pos += 1
continue
sn = str(row.get(col_map['store_name'], '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result[sn] = result.get(sn, 0) + 1
logger.info(f"[人力成本表] {len(result)} 个门店, biz_type={biz_type}, "
f"skip_verify={skip_verify}, skip_biz={skip_biz}, skip_pos={skip_pos}, "
f"headcount样本={list(result.items())[:10]}")
return result
def get_with_fallback(primary, secondary):
"""
第一优先取值(Excel),为空/0 时回退到第二优先(SQL/指标系统)。
用于轻改店中店的"双优先"取值模式。
"""
if primary is not None and primary != 0 and str(primary).strip() not in ('', 'nan', 'None'):
return primary
return secondary
def fetch_prev_month_budget_detail(task, store_names):
"""
从上月 BizBudgetAchieve 表取轻改店中店需要的多字段:
renovation_amortization / rent_utilities / store_consumables / service_provider_share_ratio
返回 dict[store_name] = dict{字段: Decimal}
"""
from models import BizBudgetAchieve
current_month = getattr(task, 'month', '')
pm = prev_month(current_month)
if not pm or not store_names:
return {}
results = {}
try:
rows = BizBudgetAchieve.query.filter(
BizBudgetAchieve.month == pm,
BizBudgetAchieve.is_deleted == 0,
).all()
fields = [
('renovation_amortization', '装修分摊'),
('rent_utilities', '房租水电'),
('store_consumables', '门店耗材'),
('service_provider_share_ratio', '服务费占比'),
]
for row in rows:
target = getattr(row, 'target_name', '') or ''
for sn in store_names:
if sn in target or target in sn:
if sn not in results:
results[sn] = {}
for attr, _label in fields:
val = getattr(row, attr, None)
if val is not None:
results[sn][attr] = Decimal(str(val))
break
logger.info(f"[上月预算明细] month={pm} 匹配 {len(results)}/{len(store_names)}")
except Exception as e:
logger.warning(f"[上月预算明细] 查询失败: {e}")
return results
def is_luxury_brand(brand_name):
"""查豪华品牌表,判断是否豪华品牌。找不到默认非豪华。"""
from models import LuxuryBrandConfig
if not brand_name:
return '非豪华'
row = LuxuryBrandConfig.query.filter_by(
brand_name=brand_name, is_deleted=0).first()
if row and row.is_luxury == 1:
return '豪华'
return '非豪华'
def parse_park_delivery_touch(file_path, biz_type='1.1'):
"""
解析园区店交车触客表(区域运营填写)。
同门店同业务类型多行时,数值字段取**平均**。
"""
logger.info(f"[园区店交车触客表] 解析 {file_path}, biz_type={biz_type}")
df, header_idx = _read_excel_with_auto_header(file_path, ['门店名称', '门店名'])
if df is None:
logger.warning("[园区店交车触客表] 未找到有效表头行")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'delivery_cnt': ['交车数', '交车', '新车交付'],
'arrival_cnt': ['到店数', '到店'],
'arrival_invalid_cnt': ['到店无效', '无效客户数', '到店无效客户'],
'purchase_indicator': ['采买', '兜底指标', '采买兜底'],
})
logger.info(f"[园区店交车触客表] header={header_idx}, 列映射={col_map}")
numeric = ['delivery_cnt', 'arrival_cnt', 'arrival_invalid_cnt']
text = ['purchase_indicator']
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, text, biz_type)
result = {}
for sn, v in raw.items():
result[sn] = {k: int(v[k]) if k in numeric and v.get(k) else 0 for k in numeric}
result[sn]['purchase_indicator'] = v.get('purchase_indicator', '')
logger.info(f"[园区店交车触客表] {len(result)} 个门店")
return result
def parse_commerce_policy_park(file_path, biz_type='1.1'):
"""
解析商务政策表(园区店处理版)。
结构:row0=分类表头, row1=第一层列名, row2=第二层列名(含市场费参考/门店分成参考), row3+=数据
header=2 取真实列名。
同门店同业务类型多行时,数值字段取**平均**。
"""
logger.info(f"[商务政策-园区店] 解析 {file_path}, biz_type={biz_type}")
try:
df = pd.read_excel(file_path, header=2)
except Exception:
logger.warning(f"[商务政策-园区店] 读取失败 {file_path}")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
# 用户命名:按单台计算流量/台 = Excel "门店分成参考"
'traffic_fee_per_car': ['门店分成参考', '按单台计算流量', '流量费/台', '单台流量费'],
'market_fee_ref': ['市场费参考'],
})
logger.info(f"[商务政策-园区店] 列映射: {col_map}")
if 'store_name' not in col_map:
logger.warning(f"[商务政策-园区店] 未找到门店名列 (实际列={list(df.columns)[:15]})")
return {}
# 去掉 Unnamed 列(空列)
df = df.loc[:, ~df.columns.str.startswith('Unnamed')]
numeric = [k for k in col_map if k not in ('store_name', 'biz_type')]
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, [], biz_type)
result = {}
for sn, v in raw.items():
row = {}
for f in numeric:
val = v.get(f, Decimal('0'))
# 百分比列处理:如果是 0.05 这种小数(Excel % 格式),×100 转成 1-100
if val and f in ('market_fee_ref',):
try:
fval = float(val)
if 0 < fval <= 1: # 典型百分比小数
val = Decimal(str(round(fval * 100, 2)))
except (ValueError, TypeError):
pass
row[f] = val
result[sn] = row
logger.info(f"[商务政策-园区店] {len(result)} 个门店, 样本keys={list(result.keys())[:3]}")
return result
# ============================================================
# 嘀加 dj_smartcarlife 业务系统 SQL 批量聚合查询
# ============================================================
# biz_type → 嘀加 scene_type / business_type 映射
# 1.1 → scene_type=1(轻改,无 business_type)
# 2.1 → scene_type=0, business_type=1(权益)
# 2.3 → scene_type=0, business_type=2(延保)
BIZ_TYPE_TO_SMARTCARLIFE = {
'1.1': {'scene_type': 1},
'2.1': {'scene_type': 0, 'business_type': 1},
'2.3': {'scene_type': 0, 'business_type': 2},
}
def _get_biz_sql_conn():
"""从 config.BIZ_SQL_DATABASE_URL 创建 SQLAlchemy engine + pymysql 连接。"""
from config import Config
try:
from sqlalchemy import create_engine, text
engine = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
return engine.connect()
except Exception as e:
logger.error(f"[BizSQL] 连接 dj_smartcarlife 失败: {e}")
return None
def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
"""
延保/权益 轻改共用的财务类聚合 SQL(scene_type/business_type 由 biz_type 自动映射)。
一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。
字段口径(与 Java 财务测算保持一致):
- product_cost = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
即第三方成本仅在按 GMV 口径算流量费时才计入商品成本
- market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行)
- service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2)
- shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2)
- store_output_value = total_price(门店产值分账金额,主汇总记录 gopa2)
- other_cost = custom_common_cost(其他费用,主汇总记录 gopa2)
调用方:warranty_processor(延保 biz_type=2.3)、equity_processor(权益 biz_type=2.1)
注:两个处理器的 store_output_value 都从指标系统 A036 取,这里 SQL 取的作为备用。
:param start_date: date 对象
:param end_date: date 对象
:param biz_type: '2.1' / '2.3'(延保权益才有财务 SQL;'1.1' 轻改已由 fetch_light_reform_goods_stats 接管)
:param store_names: list[str] 门店名列表(可选,不传则全量查该 biz_type 的所有门店)
:return: dict[merchant_name] = {
product_cost, market_fee, service_fee, store_output_value,
shop_traffic_money, other_cost
}
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-延保权益财务] BIZ_SQL_ENABLED=false,跳过查询")
return {}
mapping = BIZ_TYPE_TO_SMARTCARLIFE.get(biz_type)
if not mapping:
logger.warning(f"[BizSQL-延保权益财务] 未知 biz_type={biz_type}")
return {}
scene_type = mapping['scene_type']
business_type = mapping.get('business_type') # 1=权益, 2=延保; None=轻改
conn = _get_biz_sql_conn()
if conn is None:
return {}
start_str = start_date.strftime('%Y-%m-%d 00:00:00') if start_date else ''
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# —— SQL 构造 ——
# 子查询 fee:四项费用累计,INNER JOIN go+po 下推过滤避免笛卡尔乘积
# 外层:主表 gopa(子订单级) JOIN go+po+gso(子订单) + LEFT JOIN gopa2(主汇总 order_flag='Y') + LEFT JOIN fee
where_parts = [
"gopa.deleted_flag = 'N'",
"gopa.order_flag = 'N'",
f"go.scene_type = {scene_type}",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
]
if business_type is not None:
where_parts.append(f"go.business_type = {business_type}")
if store_names:
name_conds = []
for n in store_names[:200]:
safe_n = n.replace("'", "''")
name_conds.append("go.merchant_name LIKE '%" + safe_n + "%'")
where_parts.append(f"({' OR '.join(name_conds)})")
# 子查询 fee 的条件(日期/scene_type/business_type 必须与外层同步!)
fee_where = [
"ecc.deleted_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
"ecc.expense_category_id IN (706, 808, 809, 901)",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
f"go.scene_type = {scene_type}",
]
if business_type is not None:
fee_where.append(f"go.business_type = {business_type}")
# 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
# 内层: 按 merchant_name + order_code GROUP BY
# - gopa/gso 级字段(product_cost, shop_traffic_money) → SUM(同订单多 sub_order 要累加)
# - order 级字段(fee.total, gopa2 各字段) → MAX(LEFT JOIN 被 gopa 多行放大,取单次值)
# 外层: 按 merchant_name GROUP BY → 全部 SUM(跨订单聚合)
sql = f"""
SELECT
t.merchant_name AS merchant_name,
SUM(t.product_cost) AS product_cost,
SUM(t.market_fee) AS market_fee,
SUM(t.service_fee) AS service_fee,
SUM(t.store_output_value) AS store_output_value,
SUM(t.shop_traffic_money) AS shop_traffic_money,
SUM(t.other_cost) AS other_cost
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级:同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级:LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE {' AND '.join(where_parts)}
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
"""
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_biz_sql_aggregated] biz_type={biz_type} dates={start_str}~{end_str} scene_type={scene_type} business_type={business_type} store_cnt={len(store_names) if store_names else 'all'} SQL={_sql_preview}...")
result = conn.execute(sa_text(sql))
rows = result.mappings().all()
out = {}
for r in rows:
mn = r['merchant_name']
if not mn:
continue
out[mn] = {
'product_cost': Decimal(str(r['product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'service_fee': Decimal(str(r['service_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'store_output_value': Decimal(str(r['store_output_value'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'other_cost': Decimal(str(r['other_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
}
logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 聚合完成, {len(out)} 个门店")
# === 诊断:带 store_names 过滤返回 0 时,自动再跑一次不带过滤的全量 ===
if store_names and len(out) == 0:
logger.warning(f"[BizSQL-延保权益财务] store_cnt={len(store_names)} 过滤后返回 0,诊断全量...")
# 构造不带 store_names LIKE 条件的全量 SQL
diag_where_parts = [w for w in where_parts if 'LIKE' not in w]
diag_sql = sql.split("WHERE")[0] + "WHERE " + " AND ".join(diag_where_parts) + " GROUP BY go.merchant_name"
try:
_diag_preview = diag_sql.strip().replace('\n', ' ')[:400]
logger.info(f"[BizSQL-诊断] 全量 SQL={_diag_preview}...")
diag_rows = conn.execute(sa_text(diag_sql)).mappings().all()
logger.info(f"[BizSQL-诊断] 全量返回 {len(diag_rows)} 个门店")
if diag_rows:
diag_names = [r['merchant_name'] for r in diag_rows[:15]]
logger.info(f"[BizSQL-诊断] merchant_name 样本: {diag_names}")
# 比较 store_names 和 merchant_name 的交集
store_set = set(store_names)
name_set = {r['merchant_name'] for r in diag_rows}
exact_match = store_set & name_set
logger.info(f"[BizSQL-诊断] Excel store_names={len(store_set)}, DB merchant_name={len(name_set)}, 精确匹配={len(exact_match)}")
if exact_match:
logger.info(f"[BizSQL-诊断] 精确匹配样本: {list(exact_match)[:5]}")
# 模糊包含检查
fuzzy_hits = []
for sn in store_set:
for mn in name_set:
if sn and mn and (sn in mn or mn in sn):
fuzzy_hits.append((sn, mn))
break
logger.info(f"[BizSQL-诊断] 模糊包含匹配={len(fuzzy_hits)}")
if fuzzy_hits:
logger.info(f"[BizSQL-诊断] 模糊匹配样本: {fuzzy_hits[:5]}")
except Exception as de:
logger.error(f"[BizSQL-诊断] 全量查询也失败: {de}")
return out
except Exception as e:
logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def exact_match_store(store_name, store_map):
"""
系统数据源精确匹配 — 门店名必须完全一致才返回。
用于 biz_sql_map / system_delivery_map / indicator_data 等系统数据源,
避免模糊匹配导致"广西河池中达"误匹配到其他含"中达"的门店。
"""
if not store_name or not store_map:
return None
return store_map.get(store_name)
def fuzzy_match_store(store_name, biz_sql_map, return_key=False):
"""
Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。
规则:store_name in merchant_name 或 merchant_name in store_name。
精确匹配优先,否则取第一个包含关系匹配。
return_key=False(默认):返回匹配到的 value,没匹配到返回 None
return_key=True: 返回匹配到的 key(门店名字符串),没匹配到返回 None
"""
if not store_name or not biz_sql_map:
return None
# 精确
if store_name in biz_sql_map:
return store_name if return_key else biz_sql_map[store_name]
# 模糊
for mn, val in biz_sql_map.items():
if store_name in mn or mn in store_name:
return mn if return_key else val
return None
# 产值达成表(output_value)解析辅助
# =====================================================
def find_header_row_by_keyword(df_raw, keyword='区域运营', max_scan=6):
"""在前 max_scan 行中查找包含 keyword 的表头行索引,找不到返回 0。
比 find_header_row 更精准:产值表的标题行也含「门店」,用「区域运营」定位表头更可靠。
"""
for i in range(min(max_scan, len(df_raw))):
row_vals = [str(v) for v in df_raw.iloc[i].tolist() if v is not None]
if any(keyword in v for v in row_vals):
return i
return 0
def pick_sheet_by_keywords(file_path, keywords, fallback_index=0):
"""按 sheet 名关键字挑选工作表;未命中则按索引回退(兼容月份变化的表名)。"""
try:
xls = pd.ExcelFile(file_path)
except Exception as e:
logger.warning(f"[产值达成] 打开 Excel 失败 {file_path}: {e}")
return fallback_index
for name in xls.sheet_names:
if all(kw in str(name) for kw in keywords):
logger.info(f"[产值达成] 命中 sheet: {name}")
return name
names = xls.sheet_names
if len(names) > fallback_index:
logger.warning(f"[产值达成] 未按关键字 {keywords} 命中 sheet,回退索引 {fallback_index} → {names[fallback_index]}")
return names[fallback_index]
return names[0]
def _locate_store_column(columns):
"""定位「门店」列:优先精确同名,其次含「门店」但排除「门店类型/门店数量」。"""
for c in columns:
if str(c).strip() == '门店':
return c
for c in columns:
s = str(c)
if '门店' in s and '类型' not in s and '数量' not in s:
return c
return None
def fetch_park_daily_report(start_date, end_date, scene_type=1):
"""
轻改店中店/园区店**共用**的日报数据批量查询(scene_type=1 轻改)。
一次 DB 连接内两次 GROUP BY,返回 3 个字段供不同处理器按需组合。
返回 dict[merchant_name] = {
delivery_cnt, # int 新车交付数(merchant_daily_report_huawei.delivery_count)
equity_to_shop_count, # int 权益到店数(staff_daily_report_huawei.equity_to_shop_count)
after_sale_equity_to_shop_count, # int 售后权益到店数(同表 after_sale_equity_to_shop_count)
}
调用方按需组合:
- 园区店 delivery_cnt → 交车数
equity_to_shop_count + after_sale_equity_to_shop_count → 到店数
到店无效客户数 → 无 SQL,默认 0
- 店中店 delivery_cnt → 交车数
equity_to_shop_count → 交付触客数
after_sale_equity_to_shop_count → 售后触客数
售后首保/事故回厂数 → 无 SQL,默认 0
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
# SQL 1:新车交付数(merchant 日报表)
sql_delivery = f"""
SELECT merchant_name, SUM(IFNULL(delivery_count, 0)) AS delivery_cnt
FROM dj_car_life_merchant_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{start_date}'
AND report_date <= '{end_date}'
AND scene_type = {scene_type}
GROUP BY merchant_name
"""
# SQL 2:权益到店 + 售后权益到店(staff 日报表,一次 GROUP BY 分开返回两列)
sql_arrival = f"""
SELECT merchant_name,
SUM(IFNULL(equity_to_shop_count, 0)) AS equity_to_shop_count,
SUM(IFNULL(after_sale_equity_to_shop_count, 0)) AS after_sale_equity_to_shop_count
FROM dj_car_life_staff_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{start_date}'
AND report_date <= '{end_date}'
AND scene_type = {scene_type}
GROUP BY merchant_name
"""
out = {}
try:
from sqlalchemy import text as sa_text
_sql_preview = sql_delivery.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_park_daily_report] start_date={start_date}, end_date={end_date}, scene_type={scene_type} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql_delivery)).mappings().all():
mn = r['merchant_name']
if mn:
out[mn] = out.get(mn, {})
out[mn]['delivery_cnt'] = int(r['delivery_cnt'] or 0)
_sql_preview = sql_arrival.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_park_daily_report] start_date={start_date}, end_date={end_date}, scene_type={scene_type} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql_arrival)).mappings().all():
mn = r['merchant_name']
if mn:
out[mn] = out.get(mn, {})
out[mn]['equity_to_shop_count'] = int(r['equity_to_shop_count'] or 0)
out[mn]['after_sale_equity_to_shop_count'] = int(r['after_sale_equity_to_shop_count'] or 0)
# 默认值补全
for mn in out:
out[mn].setdefault('delivery_cnt', 0)
out[mn].setdefault('equity_to_shop_count', 0)
out[mn].setdefault('after_sale_equity_to_shop_count', 0)
logger.info(f"[BizSQL-日报] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-日报] 查询异常: {e}")
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_light_reform_goods_stats(start_date, end_date):
"""
轻改店中店 + 园区店 共用:品类成交数 + 产值批量查询(scene_type=1)。
**一条条件聚合 SQL** 一次性查出所有门店的:
- 品类成交数:窗膜/车衣/精品(各原厂+副厂)、踏板(带礼品排除 NOT LIKE '%(赠)%')
- 总产值:门店总产值 / 内部结算产值 / 原厂总产值 / 副厂总产值(不带礼品排除,按 dj_order_type + AITO/HIMA 关键字区分)
- 总成交数:COUNT(DISTINCT order_code) 排除内部结算订单(dj_order_type != 6)
数据源表:dj_car_life_goods_sub_order (t1) + dj_car_life_goods_order (t2) + dj_car_life_pay_order (t3)
过滤条件:t1.status=1, t2.status IN (4,6,12), t2.scene_type=1, t3.success_date BETWEEN start AND end
:param start_date: date 对象
:param end_date: date 对象
:return: dict[merchant_name] = {
'total_deal_cnt': int, # 总成交数(dj_order_type != 6 的门店有效订单数)
'window_film_oe_cnt': int, # 窗膜原厂成交数
'window_film_nonoe_cnt': int, # 窗膜副厂成交数
'car_wrap_oe_cnt': int, # 车衣原厂成交数
'car_wrap_nonoe_cnt': int, # 车衣副厂成交数
'premium_oe_cnt': int, # 精品原厂成交数
'premium_nonoe_cnt': int, # 精品副厂成交数
'pedal_cnt': int, # 踏板成交数
'store_output_value': Decimal, # 门店总产值(dj_order_type != 6)
'internal_settle_value': Decimal, # 内部结算产值(dj_order_type = 6)
'oe_output_value': Decimal, # 原厂总产值(dj_order_type != 6 AND 名称含 AITO/HIMA)
'nonoe_output_value': Decimal, # 副厂总产值(dj_order_type != 6 AND 名称不含 AITO/HIMA)
}
调用方说明:
- 店中店(inshop):直接用原厂+副厂拆分字段,以及全部产值字段
- 园区店(park):品类 = 原厂+副厂求和,产值映射 store_sales_output ← store_output_value
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-店中店商品] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
start_str = start_date.strftime('%Y-%m-%d 00:00:00') if start_date else ''
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
sql = f"""
SELECT
t2.merchant_name AS merchant_name,
-- 总成交数(门店有效订单数,dj_order_type != 6 排除内部结算,与 SQL #2 一致)
COUNT(DISTINCT CASE
WHEN t1.dj_order_type != 6
THEN t2.order_code END) AS total_deal_cnt,
-- 窗膜成交数(带礼品排除)
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS window_film_oe_cnt,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS window_film_nonoe_cnt,
-- 车衣成交数(带礼品排除)
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS car_wrap_oe_cnt,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS car_wrap_nonoe_cnt,
-- 踏板成交数(带礼品排除)
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name = '踏板'
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
THEN t2.order_code END) AS pedal_cnt,
-- 精品成交数(带礼品排除,排除已归类的品类)
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS premium_oe_cnt,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS premium_nonoe_cnt,
-- 门店总产值(dj_order_type != 6,不含礼品排除,与原 SQL 一致)
SUM(CASE WHEN t1.dj_order_type != 6
THEN IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0)
ELSE 0 END) AS store_output_value,
-- 内部结算产值(dj_order_type = 6)
SUM(CASE WHEN t1.dj_order_type = 6
THEN IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0)
ELSE 0 END) AS internal_settle_value,
-- 原厂总产值(dj_order_type != 6 AND 名称含 AITO/HIMA)
SUM(CASE WHEN t1.dj_order_type != 6
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0)
ELSE 0 END) AS oe_output_value,
-- 副厂总产值(dj_order_type != 6 AND 名称不含 AITO/HIMA)
SUM(CASE WHEN t1.dj_order_type != 6
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0)
ELSE 0 END) AS nonoe_output_value
FROM dj_car_life_goods_sub_order t1
LEFT JOIN dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
AND t2.deleted_flag = 'N'
LEFT JOIN dj_car_life_pay_order t3
ON t3.order_code = t1.order_code
AND t3.deleted_flag = 'N'
WHERE t1.status = 1
AND t1.deleted_flag = 'N'
AND t2.scene_type = 1
AND t3.success_date BETWEEN '{start_str}' AND '{end_str}'
GROUP BY t2.merchant_name
"""
out = {}
try:
from sqlalchemy import text as sa_text
from decimal import Decimal
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_light_reform_goods_stats] start_date={start_date}, end_date={end_date} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql)).mappings().all():
mn = r['merchant_name']
if not mn:
continue
out[mn] = {
'total_deal_cnt': int(r['total_deal_cnt'] or 0),
'window_film_oe_cnt': int(r['window_film_oe_cnt'] or 0),
'window_film_nonoe_cnt': int(r['window_film_nonoe_cnt'] or 0),
'car_wrap_oe_cnt': int(r['car_wrap_oe_cnt'] or 0),
'car_wrap_nonoe_cnt': int(r['car_wrap_nonoe_cnt'] or 0),
'premium_oe_cnt': int(r['premium_oe_cnt'] or 0),
'premium_nonoe_cnt': int(r['premium_nonoe_cnt'] or 0),
'pedal_cnt': int(r['pedal_cnt'] or 0),
'store_output_value': Decimal(str(r['store_output_value'] or 0)),
'internal_settle_value': Decimal(str(r['internal_settle_value'] or 0)),
'oe_output_value': Decimal(str(r['oe_output_value'] or 0)),
'nonoe_output_value': Decimal(str(r['nonoe_output_value'] or 0)),
}
logger.info(f"[BizSQL-店中店商品] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-店中店商品] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_est_delivery_count(base_scene_code='100101'):
"""
预估交车数批量查询(静态配置表,无日期参数)。
数据源:dj_car_life_merchant_store_info(门店流量方配置表)
取值逻辑:estimated_delivery_count_per_month 为空时回退 delivery_count(IF 表达式)。
过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N'
:param base_scene_code: 业务场景编码,默认 '100101' 轻改
:return: dict[traffic_party_name] = final_delivery_count (int)
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-预估交车数] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
sql = f"""
SELECT traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL,
delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info
WHERE base_scene_code = '{base_scene_code}'
AND deleted_flag = 'N'
ORDER BY created_date DESC
"""
out = {}
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_est_delivery_count] base_scene_code={base_scene_code} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql)).mappings().all():
tn = r['traffic_party_name']
# ORDER BY created_date DESC → 同门店多条时只取最新一条(先遍历到的就是最新)
if tn and tn not in out:
out[tn] = int(r['final_delivery_count'] or 0)
logger.info(f"[BizSQL-预估交车数] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-预估交车数] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_park_name_map(base_scene_code='100101'):
"""
园区店名称批量查询(静态配置表,无日期参数)。
数据源:dj_car_life_merchant_store_info(门店流量方配置表)
取值逻辑:traffic_party_name(流量方门店名)→ parking_store_name(园区店名称)
过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N'
:param base_scene_code: 业务场景编码,默认 '100101' 轻改
:return: dict[traffic_party_name] = parking_store_name (str)
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-园区名称] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
sql = f"""
SELECT traffic_party_name, parking_store_name
FROM dj_car_life_merchant_store_info
WHERE base_scene_code = '{base_scene_code}'
AND deleted_flag = 'N'
AND traffic_party_name IS NOT NULL
AND parking_store_name IS NOT NULL
ORDER BY created_date DESC
"""
out = {}
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_park_name_map] base_scene_code={base_scene_code} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql)).mappings().all():
tp = r['traffic_party_name']
ps = r['parking_store_name']
# ORDER BY created_date DESC → 同 traffic_party 多条时只取最新一条
if tp and tp not in out:
out[tp] = ps
logger.info(f"[BizSQL-园区名称] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-园区名称] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
"""
轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。
一条条件聚合 SQL 一次性查出所有门店的全部成本分项,供两个处理器按需消费。
核心公式(**注意与延保/权益不同!**):
商品成本 = SUM(upgrade_shop_price - base_shop_price)
(延保/权益用的是 upgrade_dj_cost + upgrade_third_party_cost,别搞混)
分项口径(全部用 CASE WHEN 按 dj_order_type + 品类 + 原厂/副厂 关键字切分):
- product_cost_finance 产品成本(dj_order_type != 6 非内部结算)
- internal_settle_cost 内部结算成本(dj_order_type = 6)
- oe_product_cost / nonoe_product_cost 原厂/副厂产品成本(dj_order_type != 6 + AITO/HIMA 关键字)
- window_film_cost / car_wrap_cost / premium_cost 品类产品成本(upgrade_goods_type_name 分类)
- store_share 门店分成/流量费(dj_order_type != 6 的 shop_traffic_money)
- construction_income 施工收入(custom_common_cost)
- market_fee 市场费(fee 子查询的四项费用累计:706/808/809/901)
数据源表:dj_car_life_goods_order_profit_allocation(gopa) + gopa2 + sub_order(gso) + order(go) + pay_order(po)
过滤条件:gopa.deleted_flag='N', gopa.order_flag='N', go.scene_type=scene_type, po.success_date BETWEEN ...
business_type **不限制**(1 或 2 都算轻改业务)
调用方说明:
- 店中店 inshop:消费全部 10 个字段
- 园区店 park:仅消费 product_cost_finance / internal_settle_cost / store_share(=traffic_fee_finance) / market_fee(=market_fee_weighted)
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-轻改财务] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
start_str = start_date.strftime('%Y-%m-%d 00:00:00') if start_date else ''
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# 轻改品类常量(与 goods_stats 里的分类逻辑保持一致)
FILM_TYPES = "('自建商品-太阳膜','天窗冰甲','太阳膜')"
CAR_WRAP_TYPES = "('车衣','改色膜')"
PREMIUM_EXCLUDE = "('自建商品-太阳膜','天窗冰甲','车衣','改色膜','踏板','充电桩','验收一级类目','太阳膜')"
# 子查询 fee(四项费用累计)— 日期 + scene_type 与外层同步
fee_where = [
"ecc.deleted_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
"ecc.expense_category_id IN (706, 808, 809, 901)",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
f"go.scene_type = {scene_type}",
]
sql = f"""
SELECT
t.merchant_name AS merchant_name,
-- 内层已按 merchant_name + order_code 聚合好, 外层全部 SUM 跨订单
SUM(t.product_cost_finance) AS product_cost_finance,
SUM(t.internal_settle_cost) AS internal_settle_cost,
SUM(t.oe_product_cost) AS oe_product_cost,
SUM(t.nonoe_product_cost) AS nonoe_product_cost,
SUM(t.window_film_cost) AS window_film_cost,
SUM(t.car_wrap_cost) AS car_wrap_cost,
SUM(t.premium_cost) AS premium_cost,
SUM(t.store_share) AS store_share,
SUM(t.construction_income) AS construction_income,
SUM(t.market_fee) AS market_fee
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gpa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES}
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES}
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE}
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS premium_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'Y' and gopa.grain_size_type = 1
AND go.scene_type = {scene_type}
AND po.success_date >= '{start_str}'
AND po.success_date <= '{end_str}'
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
"""
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_light_reform_finance_stats] start_date={start_date}, end_date={end_date}, scene_type={scene_type} SQL={_sql_preview}...")
result = conn.execute(sa_text(sql))
rows = result.mappings().all()
out = {}
for r in rows:
mn = r['merchant_name']
if not mn:
continue
out[mn] = {
'product_cost_finance': Decimal(str(r['product_cost_finance'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'internal_settle_cost': Decimal(str(r['internal_settle_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'oe_product_cost': Decimal(str(r['oe_product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'nonoe_product_cost': Decimal(str(r['nonoe_product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'window_film_cost': Decimal(str(r['window_film_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'car_wrap_cost': Decimal(str(r['car_wrap_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'premium_cost': Decimal(str(r['premium_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'store_share': Decimal(str(r['store_share'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'construction_income': Decimal(str(r['construction_income'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
}
logger.info(f"[BizSQL-轻改财务] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-轻改财务] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def parse_saas_achieve_details(file_path, sheet_keywords, fallback_index=0):
"""
解析 SAAS门店预算分解表 的指定 sheet,返回门店明细列表。
参数:
sheet_keywords: sheet 名需同时包含的关键字,如 ['权益延保', '门店'] / ['轻改', '门店']
fallback_index: 关键字未命中时的 sheet 索引回退
返回 list[dict],每条字段:
region_operator 区域运营(结果表 C 列取值来源)
store_name 门店(E/F 列按此列去重计数)
resident_type 驻店类型(直营 / 服务商 …)
store_kind 存量 / 新增(sheet1「存量/新店」列、sheet2「性质」列)
budget_corrected 预估产值(纠偏)—— H/K 列预算求和口径
biz_type 业务类型明细值(2.1 / 2.3 / 1.1)
"""
sheet = pick_sheet_by_keywords(file_path, sheet_keywords, fallback_index)
try:
df_raw = pd.read_excel(file_path, sheet_name=sheet, header=None)
header_row = find_header_row_by_keyword(df_raw, '区域运营')
df = pd.read_excel(file_path, sheet_name=sheet, header=header_row)
except Exception as e:
logger.warning(f"[产值达成] 读取 sheet[{sheet}] 失败: {e}")
return []
df.columns = [str(c).replace('\n', '').strip() for c in df.columns]
cols = list(df.columns)
col_region = next((c for c in cols if '区域运营' in c), None)
col_resident = next((c for c in cols if '驻店类型' in c), None)
col_store = _locate_store_column(cols)
col_kind = next((c for c in cols if ('存量/新店' in c) or ('性质' in c)), None)
col_budget = next((c for c in cols if '纠偏' in c), None)
col_biz = next((c for c in cols if c.strip() == '业务类型'), None)
if not col_region:
logger.warning(f"[产值达成] sheet[{sheet}] 未找到「区域运营」列,跳过")
return []
if not col_budget:
logger.warning(f"[产值达成] sheet[{sheet}] 未找到「预估产值(纠偏)」列,预算将按 0 计")
records = []
for _, row in df.iterrows():
ro = str(row.get(col_region, '') or '').strip()
if not ro or ro in ('nan', 'None'):
continue
store = str(row.get(col_store, '') or '').strip() if col_store else ''
kind_raw = str(row.get(col_kind, '') or '').strip() if col_kind else ''
if '新增' in kind_raw or '新店' in kind_raw:
kind = '新增'
elif '存量' in kind_raw:
kind = '存量'
else:
kind = kind_raw
records.append({
'region_operator': ro,
'store_name': store,
'resident_type': str(row.get(col_resident, '') or '').strip() if col_resident else '',
'store_kind': kind,
'budget_corrected': _to_decimal(row.get(col_budget, 0)) if col_budget else Decimal('0'),
'biz_type': str(row.get(col_biz, '') or '').strip() if col_biz else '',
})
logger.info(f"[产值达成] sheet[{sheet}] 解析 {len(records)} 行明细,"
f"区域运营 {len(set(r['region_operator'] for r in records))} 个")
return records
def parse_operator_relation(file_path):
"""
解析关系表,返回 {业务线: {区域经理(E列): 大区经理(D列)}}。
仅用于产值达成表:按 C 列区域运营 → 关系表 E 列(区域经理) 匹配 → 取 D 列(大区经理) 作为结果表 B 列。
"""
try:
df = pd.read_excel(file_path)
except Exception as e:
logger.warning(f"[产值达成-关系表] 读取失败 {file_path}: {e}")
return {}
df.columns = [str(c).replace('\n', '').strip() for c in df.columns]
cols = list(df.columns)
col_line = next((c for c in cols if '业务线' in c), None)
col_manager = next((c for c in cols if '大区经理' in c), None)
col_operator = next((c for c in cols if '区域经理' in c), None)
if not (col_manager and col_operator):
logger.warning("[产值达成-关系表] 未找到「大区经理」或「区域经理」列")
return {}
result = {}
for _, row in df.iterrows():
operator = str(row.get(col_operator, '') or '').strip()
if not operator or operator in ('nan', 'None'):
continue
manager = str(row.get(col_manager, '') or '').strip()
line = str(row.get(col_line, '') or '').strip() if col_line else ''
result.setdefault(line, {})
# 同一区域经理可能对应多省份多行,保留首个非空大区经理
if operator not in result[line] or not result[line][operator] or result[line][operator] in ('/', 'nan'):
result[line][operator] = manager
total = sum(len(v) for v in result.values())
logger.info(f"[产值达成-关系表] 解析 {total} 个区域经理,业务线: {list(result.keys())}")
return result