build_store_effect_board.py
65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
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
# -*- coding: utf-8 -*-
"""
门店店效人效汇总表(总看板)构建器
==================================
按桌面模板「门店店效人效汇总表.xlsx」的 总看板 + 字段说明 两个 sheet 输出。
取数口径详见模板 sheet2「字段说明」。本脚本从"源数据"重算(用户确认:从源重算,
不依赖同事的 report_* 结果表):
- SAAS门店预算分解表 sheet1(biz 2.1/2.3) + sheet2(biz 1.1)
→ 门店数/豪华/非豪华/直营/存量新增/预算目标/纠偏预算
- 主机厂数据表(鸿蒙/广联) → 交车数
- 二手车收购与销售台账-汇总销售台账 → 6.1 系列
- config_brand_category(豪华品牌配置表) → 豪华/非豪华判定(模糊匹配)
暂未接入(置 0 并在说明里标注):
- 人力成本表("人力成本表-密码2026.xlsx" 加密/BadZipFile,无法读取)
→ 全国直营总人数/营销人数/店均人数/人均产值/豪华·非豪华员工数 等
- 指标系统 API 产值(A036)/成交(A075)/触客(A084)
→ 全国经营总产值/店均产值/1.1·2.1·2.3 产值 等
- 系统数据(闭店日期/商户创建日期/品牌归属)
→ 本月流失门店/新增门店 及其豪华·非豪华拆分
用法:
python build_store_effect_board.py --src "C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
--month 2026-08 [--period-start 2026-08-01 --period-end 2026-08-31]
"""
import os
import sys
import argparse
import logging
from datetime import datetime, date, timedelta
from decimal import Decimal, InvalidOperation
import pandas as pd
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger('board')
# ============================================================
# 通用工具
# ============================================================
def to_decimal(v):
"""金额解析:空/NaN/异常 → 0"""
if v is None or v == '':
return Decimal('0')
# NaN / NaT 必须先拦掉,否则 Decimal(str(nan)) 会得到 Decimal('NaN') 污染求和
try:
if pd.isna(v):
return Decimal('0')
except (TypeError, ValueError):
pass
if isinstance(v, (int, float, Decimal)):
try:
return Decimal(str(v))
except InvalidOperation:
return Decimal('0')
s = str(v).strip().replace(',', '').replace('¥', '').replace('%', '')
if s in ('', '-', 'nan', 'None'):
return Decimal('0')
try:
return Decimal(s)
except InvalidOperation:
return Decimal('0')
def excel_serial_to_date(v):
"""Excel 序列号日期 → date;已是 datetime/date 直接返回;无法解析返回 None"""
if v is None or v == '':
return None
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if isinstance(v, (int, float)):
# Excel 1900 日期系统
try:
return (datetime(1899, 12, 30) + pd.Timedelta(days=float(v))).date()
except Exception:
return None
s = str(v).strip()
if not s:
return None
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M:%S'):
try:
return datetime.strptime(s, fmt).date()
except ValueError:
continue
try:
return pd.to_datetime(s).date()
except Exception:
return None
def norm_col(c):
"""列名归一化:去换行/空格/全角括号"""
return str(c).replace('\n', '').replace('\r', '').replace(' ', '').replace('(', '(').replace(')', ')')
def find_col(columns, keywords):
"""按关键字找列名:先精确相等,再包含匹配"""
normed = [(c, norm_col(c)) for c in columns]
for kw in keywords:
for c, nc in normed:
if nc == kw:
return c
for kw in keywords:
for c, nc in normed:
if kw in nc:
return c
return None
def safe_div(a, b, digits=2):
"""安全除法,分母 0 → 0"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b).quantize(Decimal('1.' + '0' * digits))
except Exception:
return Decimal('0')
def pct(a, b, digits=2):
"""百分比:a/b*100,保留 digits 位(表内已 ×100,配 '0.00"%"' 格式)"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b * 100).quantize(Decimal('1.' + '0' * digits))
except Exception:
return Decimal('0')
def div2(a, b):
"""普通比值(如客单价):a/b,保留 2 位小数,不做 ×100"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b).quantize(Decimal('0.01'))
except Exception:
return Decimal('0')
# ============================================================
# 品牌 → 豪华/非豪华(config_brand_category,模糊匹配)
# ============================================================
def load_brand_category():
"""
读取 config_brand_category(brand → category)。
返回 (exact_map, fuzzy_list);无 DB 时返回空。
"""
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import app, db
from sqlalchemy import text
with app.app_context():
rows = db.session.execute(text('SELECT brand, category FROM config_brand_category')).fetchall()
exact = {str(b).strip(): str(c).strip() for b, c in rows}
logger.info(f"[品牌配置] 载入 {len(exact)} 条")
return exact, list(exact.keys())
except Exception as e:
logger.warning(f"[品牌配置] 读取失败,全部按非豪华: {e}")
return {}, []
def brand_category(brand, exact_map, keys):
"""
判定豪华/非豪华:先精确匹配,再双向包含匹配(取最长匹配避免误判)。
配置表里目前 18 条全是"豪华",未命中即非豪华。
"""
if not brand:
return '非豪华'
b = str(brand).strip()
if not b or b == 'nan':
return '非豪华'
if b in exact_map:
return exact_map[b]
nb = norm_col(b)
best_cat, best_len = None, 0
for k in keys:
nk = norm_col(k)
if not nk:
continue
if nk == nb or nk in nb or nb in nk:
if len(nk) > best_len:
best_len, best_cat = len(nk), exact_map[k]
return best_cat or '非豪华'
# ============================================================
# SAAS 门店预算分解表
# ============================================================
def parse_saas(src):
"""
解析 SAAS门店预算分解表。
返回 (sheet1_rows, sheet2_rows)
sheet1 (biz 2.1/2.3): store/brand/biz_type/resident_type/budget_target/budget_corrected
sheet2 (biz 1.1) : store/brand/nature(存量|新增)/resident_type/budget_target/budget_corrected
说明:文件里 sheet1 真实表头在第 2 行(第 1 行是标题),sheet2 表头在第 1 行。
"""
path = None
for fn in os.listdir(src):
if 'SAAS' in fn and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
break
if not path:
logger.warning("[SAAS] 未找到文件")
return [], []
def _read(sheet_idx, header_row):
raw = pd.read_excel(path, sheet_name=sheet_idx, header=None)
# 用"表头特征关键字打分"定位真实表头行,避免标题行误判
hints = ['门店', '品牌', '业务类型', '预估产值', '驻店类型', '性质', '序号']
best_i, best_score = header_row, 0
for i in range(min(6, len(raw))):
vals = [str(v) for v in raw.iloc[i].tolist() if v is not None]
score = sum(1 for v in vals if any(h in v for h in hints))
if score > best_score:
best_score, best_i = score, i
df = pd.read_excel(path, sheet_name=sheet_idx, header=best_i)
logger.info(f"[SAAS] sheet{sheet_idx} 表头行={best_i}")
return df
def _pick(df, kws):
return find_col(df.columns, kws)
out1, out2 = [], []
# ---- sheet1: 延保权益 (2.1 / 2.3) ----
try:
df1 = _read(0, 1)
c_store = _pick(df1, ['门店', '门店名称', '门店名'])
c_brand = _pick(df1, ['品牌'])
c_biz = _pick(df1, ['业务类型'])
c_nat = _pick(df1, ['存量/新店', '存量新店'])
c_res = _pick(df1, ['驻店类型', '驻店'])
c_tgt = _pick(df1, ['预估产值(预算目标)', '预估产值(预算)', '预算目标'])
c_cor = _pick(df1, ['预估产值(纠偏)', '预估产值(纠偏', '预估总产值', '纠偏'])
logger.info(f"[SAAS sheet1] 列: store={c_store} brand={c_brand} biz={c_biz} "
f"存量/新店={c_nat} resident={c_res} 预算目标={c_tgt} 纠偏={c_cor}")
if c_store:
for _, r in df1.iterrows():
sn = str(r.get(c_store, '')).strip()
if not sn or sn in ('nan', 'None'):
continue
bt = str(r.get(c_biz, '')).strip() if c_biz else ''
if bt not in ('2.1', '2.3'):
continue
out1.append({
'store': sn,
'brand': str(r.get(c_brand, '')).strip() if c_brand else '',
'biz_type': bt,
'resident_type': str(r.get(c_res, '')).strip() if c_res else '',
'budget_target': to_decimal(r.get(c_tgt)) if c_tgt else Decimal('0'),
'budget_corrected': to_decimal(r.get(c_cor)) if c_cor else Decimal('0'),
'nature': str(r.get(c_nat, '')).strip() if c_nat else '', # 存量/新店
})
except Exception as e:
logger.error(f"[SAAS sheet1] 解析失败: {e}")
# ---- sheet2: 轻改 (1.1) ----
try:
df2 = _read(1, 0)
c_store = _pick(df2, ['门店', '门店名称', '门店名'])
c_brand = _pick(df2, ['品牌'])
c_nat = _pick(df2, ['性质'])
c_res = _pick(df2, ['驻店类型', '驻店', '经营属性'])
c_tgt = _pick(df2, ['预估产值(预算目标)', '预算目标'])
c_cor = _pick(df2, ['预估产值(纠偏)', '预估总产值', '纠偏'])
logger.info(f"[SAAS sheet2] 列: store={c_store} brand={c_brand} 性质={c_nat} "
f"resident={c_res} 预算目标={c_tgt} 纠偏={c_cor}")
if c_store:
for _, r in df2.iterrows():
sn = str(r.get(c_store, '')).strip()
if not sn or sn in ('nan', 'None'):
continue
nat = str(r.get(c_nat, '')).strip() if c_nat else ''
out2.append({
'store': sn,
'brand': str(r.get(c_brand, '')).strip() if c_brand else '',
'biz_type': '1.1',
'resident_type': str(r.get(c_res, '')).strip() if c_res else '',
'budget_target': to_decimal(r.get(c_tgt)) if c_tgt else Decimal('0'),
'budget_corrected': to_decimal(r.get(c_cor)) if c_cor else Decimal('0'),
'nature': nat,
})
except Exception as e:
logger.error(f"[SAAS sheet2] 解析失败: {e}")
logger.info(f"[SAAS] sheet1={len(out1)} 条, sheet2={len(out2)} 条")
return out1, out2
# ============================================================
# 主机厂交车数
# ============================================================
def parse_delivery(src):
"""解析鸿蒙/广联主机厂数据表 → {门店: 交车数}"""
delivery = {}
for fn in os.listdir(src):
if ('主机厂' in fn or '广联' in fn) and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from report_utils import parse_delivery_table
part = parse_delivery_table(path)
for k, v in (part or {}).items():
delivery[k] = delivery.get(k, 0) + int(v or 0)
logger.info(f"[主机厂] {fn} → {len(part or {})} 条")
except Exception as e:
logger.warning(f"[主机厂] {fn} 解析失败: {e}")
return delivery
# ============================================================
# 二手车(6.1)
# ============================================================
def parse_used_car(src, period_start, period_end):
"""
解析二手车收购与销售台账 - 汇总销售台账。
口径(字段说明):
6.1产值 = 拍卖日期在周期内 的 拍卖价格 之和
6.1毛利率 = (拍卖价格-收购价格)之和 / 6.1产值
6.1单车均毛利= (拍卖价格-收购价格)之和 / 处置台次
6.1交付平均车价 = 收购日期在周期内 的 收购价格之和 / 收购台次
6.1处置车量 = 拍卖日期在周期内 的明细数量
6.1收车台次 = 收购日期在周期内 的明细数量
6.1处置周期(批售) = 拍卖平台≠个人:(拍卖日期-收车日期)天数之和/明细数
6.1处置周期(零售) = 拍卖平台=个人:同上
6.1库存数量 = 拍卖日期为空 且 处置类型≠寄售 的明细数量
"""
res = {'output': Decimal('0'), 'profit': Decimal('0'), 'dispose_cnt': 0,
'buy_amount': Decimal('0'), 'buy_cnt': 0, 'wholesale_days': 0,
'retail_days': 0, 'stock_cnt': 0, 'avg_price': Decimal('0'),
'gross_rate': Decimal('0'), 'unit_profit': Decimal('0'),
'wholesale_cycle': Decimal('0'), 'retail_cycle': Decimal('0')}
path = None
for fn in os.listdir(src):
if '二手车' in fn and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
break
if not path:
logger.warning("[二手车] 未找到文件")
return res
try:
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
if '汇总销售台账' not in wb.sheetnames:
logger.warning("[二手车] 无「汇总销售台账」sheet")
wb.close()
return res
ws = wb['汇总销售台账']
rows = list(ws.iter_rows(values_only=True))
wb.close()
if len(rows) < 2:
return res
header = [norm_col(c) if c is not None else '' for c in rows[0]]
idx = {name: i for i, name in enumerate(header)}
def col(*names):
for n in names:
for k, i in idx.items():
if n in k:
return i
return None
i_store = col('门店')
i_type = col('处置类型')
i_buy_d = col('收购日期')
i_buy_p = col('收购价格')
i_auc_d = col('拍卖日期')
i_auc_p = col('拍卖价格')
i_plat = col('拍卖平台')
i_profit = col('收拍利润')
def in_period(d):
if d is None:
return False
if period_start and d < period_start:
return False
if period_end and d > period_end:
return False
return True
for r in rows[1:]:
if not r:
continue
first = str(r[i_store]).strip() if (i_store is not None and i_store < len(r) and r[i_store]) else ''
if not first or first == '合计': # 跳过合计行
continue
def gv(i):
if i is None or i >= len(r):
return None
return r[i]
auc_d = excel_serial_to_date(gv(i_auc_d))
buy_d = excel_serial_to_date(gv(i_buy_d))
auc_p = to_decimal(gv(i_auc_p))
buy_p = to_decimal(gv(i_buy_p))
plat = str(gv(i_plat) or '').strip() if i_plat is not None else ''
dtype = str(gv(i_type) or '').strip() if i_type is not None else ''
if in_period(auc_d):
res['output'] += auc_p
pf = to_decimal(gv(i_profit)) if i_profit is not None else (auc_p - buy_p)
res['profit'] += pf
res['dispose_cnt'] += 1
if auc_d and buy_d:
days = (auc_d - buy_d).days
if plat and plat != '个人':
res['wholesale_days'] += days
else:
res['retail_days'] += days
if in_period(buy_d):
res['buy_amount'] += buy_p
res['buy_cnt'] += 1
# 库存:拍卖日期为空 且 处置类型≠寄售(处置类型为空也视为非寄售)
if auc_d is None and dtype != '寄售':
res['stock_cnt'] += 1
res['avg_price'] = safe_div(res['buy_amount'], res['buy_cnt'])
res['gross_rate'] = pct(res['profit'], res['output'])
res['unit_profit'] = safe_div(res['profit'], res['dispose_cnt'])
res['wholesale_cycle'] = safe_div(res['wholesale_days'], res['dispose_cnt'])
res['retail_cycle'] = safe_div(res['retail_days'], res['dispose_cnt'])
logger.info(f"[二手车] 6.1产值={res['output']} 处置={res['dispose_cnt']} 收车={res['buy_cnt']} 库存={res['stock_cnt']}")
except Exception as e:
logger.error(f"[二手车] 解析失败: {e}")
return res
# ============================================================
# 人力成本表(加密需先解密)
# ============================================================
def _resolve_hr_path(src, password='2026'):
"""
定位人力成本表。若为加密的 OLE2 容器(非 zip)则解密:
1) 优先复用 outputs/tmp/hr_decrypted.xlsx 缓存
2) 否则用 msoffcrypto 解密(需安装 msoffcrypto-tool)
"""
import zipfile
hr_file = None
for fn in os.listdir(src):
if '人力成本' in fn and fn.endswith(('.xlsx', '.xls')):
hr_file = os.path.join(src, fn)
break
if not hr_file:
return None
if zipfile.is_zipfile(hr_file):
return hr_file
cache_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'tmp')
os.makedirs(cache_dir, exist_ok=True)
cache = os.path.join(cache_dir, 'hr_decrypted.xlsx')
if os.path.exists(cache):
logger.info("[人力表] 复用已解密缓存")
return cache
try:
import msoffcrypto
with open(hr_file, 'rb') as f:
of = msoffcrypto.OfficeFile(f)
of.load_key(password=password)
with open(cache, 'wb') as g:
of.decrypt(g)
logger.info(f"[人力表] 已解密 → {cache}")
return cache
except Exception as e:
logger.warning(f"[人力表] 解密失败(需 msoffcrypto-tool): {e}")
return None
def parse_hr(src, password='2026'):
"""
解析人力成本表 sheet「人力成本」。
关键列:B=工号 / D=入驻门店 / F=岗位 / AF=检核(注意 AG 也叫"检核",取首次出现的 AF)
返回 list[dict]: emp_no / store / position / checked
"""
path = _resolve_hr_path(src, password)
if not path:
logger.warning("[人力表] 未找到文件")
return []
try:
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
ws = wb['人力成本'] if '人力成本' in wb.sheetnames else wb[wb.sheetnames[0]]
rows = list(ws.iter_rows(values_only=True))
wb.close()
except Exception as e:
logger.error(f"[人力表] 读取失败: {e}")
return []
if len(rows) < 2:
return []
header = [norm_col(c) if c is not None else '' for c in rows[0]]
idx = {}
for i, n in enumerate(header): # 首次出现优先 → '检核' 命中 AF 而非 AG
if n and n not in idx:
idx[n] = i
def col(*names):
for n in names:
if n in idx:
return idx[n]
for n in names:
for k, i in idx.items():
if n in k:
return i
return None
i_no, i_store = col('工号'), col('入驻门店')
i_pos, i_chk = col('岗位'), col('检核')
logger.info(f"[人力表] 列: 工号={i_no} 入驻门店={i_store} 岗位={i_pos} 检核={i_chk}")
out = []
for r in rows[1:]:
if not r:
continue
def gv(i):
return r[i] if (i is not None and i < len(r)) else None
no = str(gv(i_no) or '').strip()
if not no or no in ('nan', 'None'):
continue
out.append({
'emp_no': no,
'store': str(gv(i_store) or '').strip(),
'position': str(gv(i_pos) or '').strip(),
'checked': gv(i_chk),
})
logger.info(f"[人力表] 解析 {len(out)} 条")
return out
# ============================================================
# 指标计算
# ============================================================
def _lr_sum_one(which, col_attr, period_start, period_end):
"""单表某数值列之和;which='inshop'|'park'|'equity';条件:同 task_id, is_deleted=0。返回 Decimal。
task_id 解析:优先与汇总同周期(period_start>=/period_end<=),否则取最新(最大) task_id。
"""
from app import app, db
from models import (ReportLightReformInshop, ReportLightReformPark,
ReportEquityService, ReportExtendedWarranty)
from sqlalchemy import func
model_cls = (ReportLightReformInshop if which == 'inshop'
else ReportLightReformPark if which == 'park'
else ReportEquityService if which == 'equity'
else ReportExtendedWarranty)
tag = ('轻改' if which in ('inshop', 'park')
else '权益' if which == 'equity' else '延保')
with app.app_context():
q = db.session.query(model_cls.task_id).filter(model_cls.is_deleted == 0)
if period_start and period_end:
q = q.filter(model_cls.period_start >= period_start,
model_cls.period_end <= period_end)
tids = [t for (t,) in q.distinct().all()]
if not tids:
t = db.session.query(func.max(model_cls.task_id)).filter(
model_cls.is_deleted == 0).scalar()
tids = [t] if t else []
if not tids:
logger.info(f"[{tag}] 未找到结果 task_id,{which}.{col_attr}=0")
return Decimal('0')
task_id = max(tids)
col = getattr(model_cls, col_attr)
logger.info(f"[{tag}] 取 task_id={task_id}({which}){col_attr} 之和")
s = db.session.query(func.coalesce(func.sum(col), 0)).filter(
model_cls.task_id == task_id, model_cls.is_deleted == 0).scalar() or 0
return Decimal(str(float(s)))
def fetch_light_reform_11_sum(col_attr, period_start, period_end):
"""轻改结果表(inshop + park)某数值列之和;条件:同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('inshop', col_attr, period_start, period_end) \
+ _lr_sum_one('park', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[轻改] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_light_reform_11_sum_one(which, col_attr, period_start, period_end):
"""轻改单表某数值列之和(安全包装,失败置0);which='inshop'|'park'。"""
try:
return _lr_sum_one(which, col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[轻改] 读取失败,{which}.{col_attr} 置0: {e}")
return Decimal('0')
def fetch_equity_21_sum(col_attr, period_start, period_end):
"""权益服务结果表(report_equity_service)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('equity', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[权益] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_extended_warranty_23_sum(col_attr, period_start, period_end):
"""延保盈利测算结果表(report_extended_warranty)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('warranty', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[延保] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_closed_stores(month_start, month_end_excl):
"""
读取 dj_smartcarlife.sale_close_store_record 中闭店时间落在
[month_start, month_end_excl) 的门店闭店记录。
返回 [(close_time, main_brands), ...],每行一条闭店记录(一条记录=一个闭店门店)。
数据库不可达时返回空列表(指标置 0)。
"""
try:
from config import Config
from sqlalchemy import create_engine, text
engine = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
with engine.connect() as conn:
sql = text(
"SELECT close_time, main_brands "
"FROM sale_close_store_record "
"WHERE close_time >= :s AND close_time < :e"
)
rows = conn.execute(sql, {'s': month_start, 'e': month_end_excl}).fetchall()
logger.info(f"[流失门店] sale_close_store_record 命中 {len(rows)} 条 "
f"({month_start}~{month_end_excl})")
return rows
except Exception as e:
logger.warning(f"[流失门店] 读取 sale_close_store_record 失败,置0: {e}")
return []
def _in_params(ids, prefix):
"""把列表转成 SQLAlchemy text 的具名 IN 参数。空列表返回 (None, None)。"""
if not ids:
return None, None
params = {f'{prefix}{i}': v for i, v in enumerate(ids)}
placeholders = ', '.join(f':{prefix}{i}' for i in range(len(ids)))
return params, placeholders
def _engine(url_key):
from config import Config
from sqlalchemy import create_engine
return create_engine(getattr(Config, url_key), echo=False, pool_pre_ping=True)
def fetch_new_stores(month_start, month_end_excl, exact_map, keys):
"""
本月新增门店(dj_smartcarlife.dj_car_life_scene_merchant_ref_new)。
口径(已与用户确认):
- 按 main_merchant_id(门店商户号)去重;该门店所有 sub_merchant_id 行中
MIN(created_date) 作为「首建日期」。
- 首建日期落在 [month_start, month_end_excl) → 本月新增门店。
- 品牌判定:用 main_merchant_id 查 scrm_account.platform_merchant_brand
取 first_brand_id / sec_brand_id → 查 cyb_os.platform_carbrand 得品牌名
→ brand_category() 定豪华;first 或 sec 任一为豪华即「新增豪华门店」。
返回 (total, lux, nonlux)。容错:首建日期(dj_smartcarlife) 取总数;
若商户品牌关联(scrm_account)/品牌字典(cyb_os) 不可达,则豪华拆分降级为 0/总数
(总量仍保留)。
"""
from sqlalchemy import text
# ---- 1) 各门店首建日期(dj_smartcarlife)----
try:
eng_ref = _engine('BIZ_SQL_DATABASE_URL')
with eng_ref.connect() as conn:
sql = text(
"SELECT main_merchant_id, MIN(created_date) AS first_created "
"FROM dj_car_life_scene_merchant_ref_new "
"GROUP BY main_merchant_id "
"HAVING MIN(created_date) >= :s AND MIN(created_date) < :e"
)
rows = conn.execute(sql, {'s': month_start, 'e': month_end_excl}).fetchall()
new_ids = [r[0] for r in rows if r[0] is not None]
logger.info(f"[新增门店] 首建日期命中 {len(new_ids)} 个门店 ({month_start}~{month_end_excl})")
except Exception as e:
logger.warning(f"[新增门店] 读取首建日期失败,置0: {e}")
return 0, 0, 0
if not new_ids:
return 0, 0, 0
total = len(new_ids)
# ---- 2)+3)+4) 豪华归类(scrm_account + cyb_os,单独立容错)----
lux = 0
try:
# 商户→品牌ID(一个 merchant_id 可能多行,按商户 union 所有 first/sec 品牌 id)
brand_set_map = {} # main_merchant_id -> set([first_brand_id, sec_brand_id, ...])
eng_scrm = _engine('SCRM_DATABASE_URL')
with eng_scrm.connect() as conn:
p, ph = _in_params(new_ids, 'm')
if p is not None:
sql = text(
"SELECT merchant_id, first_brand_id, sec_brand_id "
"FROM platform_merchant_brand "
"WHERE del_flag = 0 AND merchant_id IN ({ph})".format(ph=ph)
)
for r in conn.execute(sql, p).fetchall():
mid = r[0]
bids = brand_set_map.setdefault(mid, set())
for b in (r[1], r[2]):
if b not in (None, '', 0):
bids.add(b)
logger.info(f"[新增门店] platform_merchant_brand 命中 {len(brand_set_map)} 个商户")
# 品牌ID→品牌名(cyb_os.platform_carbrand,bid=first/sec_brand_id,品牌名字段为 brand)
all_bids = set()
for bids in brand_set_map.values():
all_bids |= bids
bid_name = {} # bid -> 品牌名
if all_bids:
eng_cyb = _engine('CYB_OS_DATABASE_URL')
with eng_cyb.connect() as conn:
p, ph = _in_params(list(all_bids), 'b')
if p is not None:
sql = text(f"SELECT bid, brand FROM platform_carbrand WHERE bid IN ({ph})")
for r in conn.execute(sql, p).fetchall():
bid, nm = r[0], r[1]
if bid is not None and nm:
bid_name[bid] = str(nm).strip()
logger.info(f"[新增门店] platform_carbrand 命中 {len(bid_name)} 个品牌")
for mid in new_ids:
brand_names = [bid_name[b] for b in brand_set_map.get(mid, set()) if b in bid_name]
if any(brand_category(nm, exact_map, keys) == '豪华' for nm in brand_names):
lux += 1
except Exception as e:
logger.warning(f"[新增门店] 品牌归类失败,豪华拆分降级为 0/总数: {e}")
nonlux = total - lux
logger.info(f"[新增门店] 合计={total} 豪华={lux} 非豪华={nonlux}")
return total, lux, nonlux
def compute_metrics(src, period_start, period_end, month_start=None, month_end_excl=None):
exact_map, keys = load_brand_category()
s1, s2 = parse_saas(src)
allrows = s1 + s2
# 品牌归类
for r in allrows:
r['category'] = brand_category(r['brand'], exact_map, keys)
def uniq(rows, pred=None):
return {r['store'] for r in rows if r['store'] and (pred is None or pred(r))}
m = {}
# ---- 门店数 ----
m['全国经营门店总数'] = len(uniq(allrows))
m['豪华车门店数量'] = len(uniq(allrows, lambda r: r['category'] == '豪华'))
m['非豪华门店数量'] = len(uniq(allrows, lambda r: r['category'] != '豪华'))
# 存量/新增:sheet1 读"A列 存量/新店",sheet2 读"J列 性质"
# 用户口径:存量 = (sheet1 存量/新店=存量) ∪ (sheet2 性质=存量),门店名去重
# 新增 = (sheet1 存量/新店=新增) ∪ (sheet2 性质=新增),门店名去重
# 注:个别门店可能同时出现在"存量"和"新增"两处,union 后会同时计入两边(与源数据一致),
# 故不再强求 存量+新增=总数。
m['存量门店数量'] = len(uniq(allrows, lambda r: r['nature'] == '存量'))
m['新店数量'] = len(uniq(allrows, lambda r: r['nature'] == '新增'))
m['全国直营门店总数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营'))
m['豪华直营门店数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营' and r['category'] == '豪华'))
m['非豪华直营门店数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营' and r['category'] != '豪华'))
# ---- 预算 ----
def ssum(rows, key, pred=None):
t = Decimal('0')
for r in rows:
if pred is None or pred(r):
t += r.get(key, Decimal('0'))
return t
m['经管预算目标'] = ssum(allrows, 'budget_target')
m['全国经营总预算'] = ssum(allrows, 'budget_corrected')
m['存量门店总预算'] = ssum(allrows, 'budget_corrected', lambda r: r['nature'] == '存量')
m['新增门店总预算'] = ssum(allrows, 'budget_corrected', lambda r: r['nature'] == '新增')
m['1.1预算'] = ssum(s2, 'budget_corrected')
m['2.1预算'] = ssum(s1, 'budget_corrected', lambda r: r['biz_type'] == '2.1')
m['2.3预算'] = ssum(s1, 'budget_corrected', lambda r: r['biz_type'] == '2.3')
m['6.1预算'] = Decimal('0') # 字段说明:默认为空
# ---- 交车数(主机厂) ----
delivery = parse_delivery(src)
def dsum(stores):
return sum(int(delivery.get(s, 0)) for s in stores)
stores_11 = uniq(s2)
stores_21 = uniq(s1, lambda r: r['biz_type'] == '2.1')
stores_23 = uniq(s1, lambda r: r['biz_type'] == '2.3')
m['1.1交车数'] = fetch_light_reform_11_sum('delivery_cnt', period_start, period_end)
m['2.1交车数'] = fetch_equity_21_sum('delivery_cnt', period_start, period_end)
m['2.3交车数'] = fetch_extended_warranty_23_sum('delivery_cnt', period_start, period_end)
# ---- 6.1 二手车 ----
uc = parse_used_car(src, period_start, period_end)
m['6.1产值'] = uc['output']
m['6.1毛利率'] = uc['gross_rate']
m['6.1单车均毛利'] = uc['unit_profit']
m['6.1交付平均车价'] = uc['avg_price']
m['6.1处置车量'] = uc['dispose_cnt']
m['6.1收车台次'] = uc['buy_cnt']
m['6.1处置周期(批售)'] = uc['wholesale_cycle']
m['6.1处置周期(零售)'] = uc['retail_cycle']
m['6.1库存数量'] = uc['stock_cnt']
m['6.1达成率'] = pct(m['6.1产值'], m['6.1预算'])
# ---- 以下依赖 指标系统API / 人力表 / 系统数据,暂置 0(骨架待校准)----
for k in ['全国经营总产值', '豪华车店均产值(w)', '非豪华店均产值(w)',
'1.1产值', '2.1产值', '2.3产值',
'1.1毛利率', '2.1毛利率', '2.3毛利率',
'1.1毛利率(含人力)', '2.1毛利率(含人力)', '2.3毛利率(含人力)',
'1.1接待数', '2.1接待数', '2.3接待数',
'1.1成交单数', '2.1成交单数', '2.3成交单数',
'本月流失门店', '流失豪华门店', '流失非豪华门店',
'本月新增门店', '新增豪华门店', '新增非豪华门店']:
m[k] = Decimal('0')
# ---- 本月流失门店(dj_smartcarlife.sale_close_store_record,闭店时间在统计月份)----
# 一条闭店记录=一个门店;main_brands 多个逗号分隔,按各品牌归类(任一为豪华→豪华门店)
if month_start and month_end_excl:
try:
closed_rows = fetch_closed_stores(month_start, month_end_excl)
closed_total = closed_lux = closed_nonlux = 0
for _ct, mb in closed_rows:
closed_total += 1
brands = [b.strip() for b in (mb or '').split(',') if b and b.strip()]
if any(brand_category(b, exact_map, keys) == '豪华' for b in brands):
closed_lux += 1
else:
closed_nonlux += 1
m['本月流失门店'] = Decimal(str(closed_total))
m['流失豪华门店'] = Decimal(str(closed_lux))
m['流失非豪华门店'] = Decimal(str(closed_nonlux))
logger.info(f"[流失门店] 合计={closed_total} 豪华={closed_lux} 非豪华={closed_nonlux}")
except Exception as e:
logger.warning(f"[流失门店] 统计失败,置0: {e}")
# ---- 本月新增门店(dj_smartcarlife.dj_car_life_scene_merchant_ref_new 首建日期在统计月份)----
# 3 库关联:dj_smartcarlife(首建日期) → scrm_account(商户品牌ID) → cyb_os(品牌名) → config_brand_category(豪华)
if month_start and month_end_excl:
try:
nt, nlux, nnon = fetch_new_stores(month_start, month_end_excl, exact_map, keys)
m['本月新增门店'] = Decimal(str(nt))
m['新增豪华门店'] = Decimal(str(nlux))
m['新增非豪华门店'] = Decimal(str(nnon))
except Exception as e:
logger.warning(f"[新增门店] 统计失败,置0: {e}")
# ---- 指标系统:产值A036 / 成交A075 / 触客A084 ----
# biz: 1=延保(2.3) 2=轻改(1.1) 3=权益(2.1);多业务用 list → bizs="1,2,3"
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
ind_all = ind_23 = ind_21 = ind_11 = ind_total = {}
if start_str and end_str:
try:
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
bz_w = INDICATOR_BIZ_MAP.get('warranty') # 1
bz_e = INDICATOR_BIZ_MAP.get('equity') # 3
bz_l = INDICATOR_BIZ_MAP.get('light_reform') # 2
ind_all = fetch_indicator_data(start_str, end_str, [bz_w, bz_e, bz_l], ['A036']) or {}
# 注意:单值 biz 会被 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
# 全国经营总产值用 A0018(含二手车业务):不传 bizs 直接查全量总数,不做门店匹配
ind_total = fetch_indicator_data(start_str, end_str, None, ['A0018']) or {}
ind_23 = fetch_indicator_data(start_str, end_str, [bz_w], ['A036', 'A075', 'A084']) or {}
ind_21 = fetch_indicator_data(start_str, end_str, [bz_e], ['A036', 'A075', 'A084']) or {}
ind_11 = fetch_indicator_data(start_str, end_str, [bz_l], ['A036', 'A075', 'A084']) or {}
logger.info(f"[指标] 全业务={len(ind_all)} 延保={len(ind_23)} 权益={len(ind_21)} 轻改={len(ind_11)}")
except Exception as e:
logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}")
def match_any(name, stores):
"""指标系统商户名 ↔ SAAS 门店名 匹配(精确优先,再双向包含)"""
if not name:
return False
if name in stores:
return True
return any(s and (s in name or name in s) for s in stores)
def ind_sum(ind_map, stores, code):
t = Decimal('0')
for nm, vals in (ind_map or {}).items():
if match_any(nm, stores):
t += to_decimal((vals or {}).get(code))
return t
all_stores = uniq(allrows)
# 全国经营总产值 = A0018 全量(含二手车业务),不传 bizs、不做门店匹配,直接求和
m['全国经营总产值'] = sum((to_decimal((vals or {}).get('A0018'))
for vals in (ind_total or {}).values()), Decimal('0'))
# 1.1产值:来自轻改结果表(report_light_reform_inshop + report_light_reform_park 的
# total_output_value 合计总产值 之和,条件:同 task_id, is_deleted=0)
m['1.1产值'] = fetch_light_reform_11_sum('total_output_value', period_start, period_end)
# 1.1毛利率 =(所有"毛利测算"之和 / 1.1产值)*100%,四舍五入保留百分比后2位
# "毛利测算"之和 = 轻改结果表 gross_profit 之和(同 task_id, is_deleted=0)
m['1.1毛利率'] = pct(
fetch_light_reform_11_sum('gross_profit', period_start, period_end),
m['1.1产值'])
# 1.1毛利率(含人力)=(毛利测算之和 + 营销成本(inshop.marketing_personnel_cost)
# + 人力成本(park.personnel_cost))/ 1.1产值 * 100%,四舍五入保留百分比后2位
# 条件:同 task_id, is_deleted=0
gp_11 = fetch_light_reform_11_sum('gross_profit', period_start, period_end)
mkt_11 = fetch_light_reform_11_sum_one('inshop', 'marketing_personnel_cost', period_start, period_end)
hr_11 = fetch_light_reform_11_sum_one('park', 'personnel_cost', period_start, period_end)
m['1.1毛利率(含人力)'] = pct(gp_11 + mkt_11 + hr_11, m['1.1产值'])
# 2.1产值:report_equity_service.store_output_value(门店产值) 之和,同 task_id, is_deleted=0
m['2.1产值'] = fetch_equity_21_sum('store_output_value', period_start, period_end)
# 2.1毛利率 =(gross_profit 之和 / 2.1产值)*100%,四舍五入保留百分比后2位
gp_21 = fetch_equity_21_sum('gross_profit', period_start, period_end)
m['2.1毛利率'] = pct(gp_21, m['2.1产值'])
# 2.1毛利率(含人力)=(gross_profit 之和 + marketing_fee 之和)/ 2.1产值 *100%,四舍五入保留百分比后2位
mkt_21 = fetch_equity_21_sum('marketing_fee', period_start, period_end)
m['2.1毛利率(含人力)'] = pct(gp_21 + mkt_21, m['2.1产值'])
# 2.3产值:report_extended_warranty.store_output_value(门店产值) 之和,同 task_id, is_deleted=0
m['2.3产值'] = fetch_extended_warranty_23_sum('store_output_value', period_start, period_end)
# 1.1成交单数 = park.deal_cnt(成交数) 之和 + inshop.total_deal_cnt(总成交数) 之和
# 条件:同 task_id, is_deleted=0
m['1.1成交单数'] = (fetch_light_reform_11_sum_one('park', 'deal_cnt', period_start, period_end)
+ fetch_light_reform_11_sum_one('inshop', 'total_deal_cnt', period_start, period_end))
m['2.1成交单数'] = fetch_equity_21_sum('deal_cnt', period_start, period_end)
# 2.3毛利率 =(gross_profit 之和 / 2.3产值)*100%,四舍五入保留百分比后2位
gp_23 = fetch_extended_warranty_23_sum('gross_profit', period_start, period_end)
m['2.3毛利率'] = pct(gp_23, m['2.3产值'])
# 2.3毛利率(含人力)=(gross_profit 之和 + marketing_fee 之和)/ 2.3产值 *100%,四舍五入保留百分比后2位
mkt_23 = fetch_extended_warranty_23_sum('marketing_fee', period_start, period_end)
m['2.3毛利率(含人力)'] = pct(gp_23 + mkt_23, m['2.3产值'])
m['2.3成交单数'] = fetch_extended_warranty_23_sum('deal_cnt', period_start, period_end)
# 1.1接待数 = park.arrival_cnt(到店数) 之和 + inshop.delivery_touch_cnt(交付触客数) 之和
# 条件:同 task_id, is_deleted=0
m['1.1接待数'] = (fetch_light_reform_11_sum_one('park', 'arrival_cnt', period_start, period_end)
+ fetch_light_reform_11_sum_one('inshop', 'delivery_touch_cnt', period_start, period_end))
m['2.1接待数'] = fetch_equity_21_sum('touch_cnt', period_start, period_end)
m['2.3接待数'] = fetch_extended_warranty_23_sum('touch_cnt', period_start, period_end)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'}
lux_output = ind_sum(ind_total, lux_stores, 'A0018')
nonlux_output = ind_sum(ind_total, nonlux_stores, 'A0018')
m['豪华车店均产值(w)'] = safe_div(lux_output, m['豪华车门店数量'])
m['非豪华店均产值(w)'] = safe_div(nonlux_output, m['非豪华门店数量'])
# ---- 人力(人力成本表,AF列检核=TRUE)----
hr = parse_hr(src)
checked = [r for r in hr
if r['checked'] is True or str(r['checked']).strip().lower() == 'true']
not_left = [r for r in checked if '离职' not in r['position']]
sales = [r for r in checked if r['position'] == '门店销售']
logger.info(f"[人力] 检核通过={len(checked)} 非离职={len(not_left)} 门店销售={len(sales)}")
m['全国直营总人数'] = len({r['emp_no'] for r in not_left})
m['全国直营营销人数'] = len({r['emp_no'] for r in sales})
m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数'])
m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数'])
# 豪华/非豪华:按「入驻门店」映射门店集合(精确优先,再包含匹配)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'}
def in_stores(hs, stores):
if not hs:
return False
if hs in stores:
return True
return any(s and (s in hs or hs in s) for s in stores)
lux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], lux_stores)}
nonlux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], nonlux_stores)}
lux_sales = {r['emp_no'] for r in sales if in_stores(r['store'], lux_stores)}
nonlux_sales = {r['emp_no'] for r in sales if in_stores(r['store'], nonlux_stores)}
m['豪华车员工数量'] = len(lux_emp)
m['非豪华员工数量'] = len(nonlux_emp)
m['豪华车营销人数'] = len(lux_sales)
m['非豪华车营销人数'] = len(nonlux_sales)
m['豪华车店均人数'] = safe_div(len(lux_sales), m['豪华车门店数量'])
m['非豪华车店均人数'] = safe_div(len(nonlux_sales), m['非豪华门店数量'])
m['豪华车人均产值'] = safe_div(lux_output, len(lux_sales))
m['非豪华车人均产值(w)'] = safe_div(nonlux_output, len(nonlux_sales))
# ---- 派生指标 ----
m['1.1达成率'] = pct(m['1.1产值'], m['1.1预算'])
m['2.1达成率'] = pct(m['2.1产值'], m['2.1预算'])
m['2.3达成率'] = pct(m['2.3产值'], m['2.3预算'])
m['1.1触客率'] = pct(m['1.1接待数'], m['1.1交车数'])
m['2.1触客率'] = pct(m['2.1接待数'], m['2.1交车数'])
m['2.3触客率'] = pct(m['2.3接待数'], m['2.3交车数'])
m['1.1转化率'] = pct(m['1.1成交单数'], m['1.1接待数'])
m['2.1转化率'] = pct(m['2.1成交单数'], m['2.1接待数'])
m['2.3转化率'] = pct(m['2.3成交单数'], m['2.3接待数'])
m['1.1成交客单价'] = div2(m['1.1产值'], m['1.1交车数'])
m['2.1成交客单价'] = div2(m['2.1产值'], m['2.1成交单数'])
m['2.3成交客单价'] = div2(m['2.3产值'], m['2.3成交单数'])
# 人力/招聘类:默认为空
for k in ['原本月招聘需求', '新店拓展需求', '总计', '已入职', '待招聘',
'本月离职人员', '本月净增长人员']:
m[k] = ''
# ---- (w) 列统一换算成万元(用户确认:列名含 (w) 的需 ÷10000)----
for _k in list(m.keys()):
if '(w)' in _k or '(w)' in _k:
_v = m[_k]
try:
if _v not in ('', None) and isinstance(_v, (int, float, Decimal)):
m[_k] = (Decimal(str(_v)) / Decimal('10000')).quantize(Decimal('1.0000'))
except Exception:
pass
return m
# ============================================================
# 渲染「总看板」
# ============================================================
# (行号, [(标签列, 字段名, 值列), ...]) —— 与模板逐格对齐
BOARD = [
(3, [('A', '全国经营门店总数', 'B'), ('C', '豪华车门店数量', 'D'), ('E', '非豪华门店数量', 'F'),
('G', '原本月招聘需求', 'H'), ('I', '新店拓展需求', 'J'), ('K', '总计', 'L')]),
(4, [('A', '经管预算目标', 'B'), ('C', '存量门店数量', 'D'), ('E', '新店数量', 'F'), ('G', '已入职', 'H')]),
(5, [('A', '全国经营总预算', 'B'), ('C', '存量门店总预算', 'D'), ('E', '新增门店总预算', 'F'), ('G', '待招聘', 'H')]),
(6, [('A', '全国经营总产值', 'B'), ('C', '豪华车店均产值(w)', 'D'), ('E', '非豪华店均产值(w)', 'F'), ('G', '本月离职人员', 'H')]),
(7, [('A', '全国直营门店总数', 'B'), ('C', '豪华直营门店数', 'D'), ('E', '非豪华直营门店数', 'F'), ('G', '本月净增长人员', 'H')]),
(8, [('A', '全国直营总人数', 'B'), ('C', '豪华车员工数量', 'D'), ('E', '非豪华员工数量', 'F')]),
(9, [('A', '全国直营营销人数', 'B'), ('C', '豪华车营销人数', 'D'), ('E', '非豪华车营销人数', 'F')]),
(10, [('A', '全国直营店均人数', 'B'), ('C', '豪华车店均人数', 'D'), ('E', '非豪华车店均人数', 'F')]),
(11, [('A', '全国人均产值(w)', 'B'), ('C', '豪华车人均产值', 'D'), ('E', '非豪华车人均产值(w)', 'F')]),
(13, [('A', '1.1预算', 'B'), ('C', '2.1预算', 'D'), ('E', '2.3预算', 'F'), ('G', '6.1预算', 'H'), ('I', '本月流失门店', 'J')]),
(14, [('A', '1.1产值', 'B'), ('C', '2.1产值', 'D'), ('E', '2.3产值', 'F'), ('G', '6.1产值', 'H'), ('I', '流失豪华门店', 'J')]),
(15, [('A', '1.1达成率', 'B'), ('C', '2.1达成率', 'D'), ('E', '2.3达成率', 'F'), ('G', '6.1达成率', 'H'), ('I', '流失非豪华门店', 'J')]),
(16, [('A', '1.1毛利率', 'B'), ('C', '2.1毛利率', 'D'), ('E', '2.3毛利率', 'F'), ('G', '6.1毛利率', 'H'), ('I', '本月新增门店', 'J')]),
(17, [('A', '1.1毛利率(含人力)', 'B'), ('C', '2.1毛利率(含人力)', 'D'), ('E', '2.3毛利率(含人力)', 'F'),
('G', '6.1单车均毛利', 'H'), ('I', '新增豪华门店', 'J')]),
(18, [('A', '1.1交车数', 'B'), ('C', '2.1交车数', 'D'), ('E', '2.3交车数', 'F'), ('G', '6.1交付平均车价', 'H'), ('I', '新增非豪华门店', 'J')]),
(19, [('A', '1.1接待数', 'B'), ('C', '2.1接待数', 'D'), ('E', '2.3接待数', 'F'), ('G', '6.1处置车量', 'H')]),
(20, [('A', '1.1触客率', 'B'), ('C', '2.1触客率', 'D'), ('E', '2.3触客率', 'F'), ('G', '6.1收车台次', 'H')]),
(21, [('A', '1.1转化率', 'B'), ('C', '2.1转化率', 'D'), ('E', '2.3转化率', 'F'), ('G', '6.1处置周期(批售)', 'H')]),
(22, [('A', '1.1成交单数', 'B'), ('C', '2.1成交单数', 'D'), ('E', '2.3成交单数', 'F'), ('G', '6.1处置周期(零售)', 'H')]),
(23, [('A', '1.1成交客单价', 'B'), ('C', '2.1成交客单价', 'D'), ('E', '2.3成交客单价', 'F'), ('G', '6.1库存数量', 'H')]),
]
RATE_FIELDS = {'1.1达成率', '2.1达成率', '2.3达成率', '6.1达成率',
'1.1毛利率', '2.1毛利率', '2.3毛利率', '6.1毛利率',
'1.1毛利率(含人力)', '2.1毛利率(含人力)', '2.3毛利率(含人力)',
'1.1触客率', '2.1触客率', '2.3触客率',
'1.1转化率', '2.1转化率', '2.3转化率'}
# 目标表(存量/新增/总计目标,单位:万)——字段说明未定义取数,留空待填
TARGET_TABLE = [('2.1', 2), ('2.3', 4), ('1.1', 5), ('6.1', 6), ('合计', 7)]
def render_board(m, out_path, month_label, targets=None):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = '总看板'
title_font = Font(name='微软雅黑', size=14, bold=True)
label_font = Font(name='微软雅黑', size=10)
value_font = Font(name='微软雅黑', size=10, bold=True)
head_font = Font(name='微软雅黑', size=10, bold=True, color='FFFFFF')
head_fill = PatternFill('solid', start_color='4472C4', end_color='4472C4')
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
thin = Border(*[Side(style='thin')] * 4)
# 标题 + 期间
ws['A1'] = '业务运营数据看板'
ws['A1'].font = title_font
ws['A1'].alignment = center
ws['Q1'] = month_label
# 目标表
for c, h in zip(range(18, 22), ['业务类型', '存量目标\n(万)', '新增目标\n(万)', '总计目标\n(万)']):
cell = ws.cell(row=1, column=c, value=h)
cell.font = head_font
cell.fill = head_fill
cell.alignment = center
cell.border = thin
for biz, row in TARGET_TABLE:
ws.cell(row=row, column=18, value=biz).border = thin
vals = (targets or {}).get(biz, ('', '', ''))
for i, v in enumerate(vals):
c = ws.cell(row=row, column=19 + i, value=v)
c.border = thin
c.alignment = center
# 看板主体
for row, items in BOARD:
for label_col, field, val_col in items:
lc = ws[f'{label_col}{row}']
lc.value = field
lc.font = label_font
lc.alignment = center
lc.border = thin
v = m.get(field, 0)
vc = ws[f'{val_col}{row}']
if isinstance(v, Decimal):
vc.value = float(v)
vc.number_format = '0.00"%"' if field in RATE_FIELDS else '#,##0.00'
elif isinstance(v, int):
vc.value = v
vc.number_format = '#,##0'
else:
vc.value = v
vc.font = value_font
vc.alignment = center
vc.border = thin
# 标签列合并到值列左侧:模板为"标签|值"两列紧邻
ws.column_dimensions[label_col].width = 18
ws.column_dimensions[val_col].width = 14
# ---- sheet2 字段说明 ----
ws2 = wb.create_sheet('字段说明')
ws2['A1'], ws2['B1'] = '字段名', '取数说明'
for c in ('A1', 'B1'):
ws2[c].font = head_font
ws2[c].fill = head_fill
ws2[c].alignment = center
ws2[c].border = thin
ws2.column_dimensions['A'].width = 24
ws2.column_dimensions['B'].width = 90
notes = FIELD_NOTES
for i, (name, desc) in enumerate(notes, start=2):
ws2.cell(row=i, column=1, value=name).border = thin
c = ws2.cell(row=i, column=2, value=desc)
c.border = thin
c.alignment = Alignment(wrap_text=True, vertical='center')
wb.save(out_path)
logger.info(f"[输出] 已生成: {out_path}")
return out_path
# 字段说明(源自模板 sheet2,标注当前取数状态)
FIELD_NOTES = [
('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'),
('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'),
('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'),
('全国经营总产值', '指标系统 A0018(含二手车业务),不传bizs全量求和、不做门店匹配;2026-08=97,681,597.64'),
('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'),
('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'),
('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'),
('全国直营店均人数', '全国直营营销人数/全国直营门店总数【依赖人力表,当前0】'),
('全国人均产值(w)', '全国经营总产值/全国直营营销人数【依赖产值+人力表,当前0】'),
('豪华车门店数量', 'saa表sheet1+sheet2,"品牌"信息=豪华 的门店按门店名称去重;判定用 config_brand_category 模糊匹配'),
('存量门店数量', '门店预算分解表 sheet1 以"存量/新店"(A列)=存量、sheet2 以"性质"(J列)=存量,两表满足存量的门店按门店名称去重合计'),
('存量门店总预算', '存量明细的"预估产值(纠偏)"之和'),
('豪华车店均产值(w)', '豪华车门店对应系统产值/豪华车门店数量【待接入A036,当前0】'),
('豪华直营门店数', '品牌=豪华且驻店类型=直营的去重门店数'),
('豪华车员工数量', '豪华车门店映射人力成本表"入驻门店",检核=TRUE、过滤离职,按工号去重【人力表加密,当前0】'),
('豪华车营销人数', '同上条件,岗位=门店销售【人力表加密,当前0】'),
('豪华车店均人数', '豪华车营销人数/豪华门店数量【依赖人力表,当前0】'),
('豪华车人均产值', '豪华车门店产值/豪华车营销人数【待接入,当前0】'),
('非豪华门店数量', '品牌≠豪华的去重门店数'),
('新店数量', '门店预算分解表 sheet1 以"存量/新店"(A列)=新增、sheet2 以"性质"(J列)=新增,两表满足新增的门店按门店名称去重合计'),
('新增门店总预算', '新增明细的"预估产值(纠偏)"之和'),
('非豪华店均产值(w)', '非豪华门店对应产值/非豪华门店数量【待接入A036,当前0】'),
('非豪华直营门店数', '品牌≠豪华且驻店类型=直营的去重门店数'),
('非豪华员工数量', '非豪华门店映射人力表【人力表加密,当前0】'),
('非豪华车营销人数', '非豪华门店映射人力表,岗位=门店销售【人力表加密,当前0】'),
('非豪华车店均人数', '非豪华车营销人数/非豪华门店数量【依赖人力表,当前0】'),
('非豪华车人均产值(w)', '非豪华门店产值/非豪华车营销人数【待接入,当前0】'),
('1.1预算', 'sheet2所有明细的"预估产值(纠偏)"之和'),
('1.1产值', '轻改结果表:report_light_reform_inshop + report_light_reform_park 的 total_output_value(合计总产值) 之和,条件:同 task_id, is_deleted=0'),
('1.1达成率', '(1.1产值/1.1预算)*100%'),
('1.1毛利率', '(report_light_reform_inshop + report_light_reform_park 的 gross_profit(毛利测算) 之和 / 1.1产值)*100%,四舍五入保留百分比后2位;条件:同 task_id, is_deleted=0'),
('1.1毛利率(含人力)', '(report_light_reform_inshop + report_light_reform_park 的 gross_profit(毛利测算) 之和 + inshop.marketing_personnel_cost(营销成本) + park.personnel_cost(人力成本))/ 1.1产值 *100%,四舍五入保留百分比后2位;条件:同 task_id, is_deleted=0'),
('1.1交车数', 'report_light_reform_inshop + report_light_reform_park 的 delivery_cnt(交车数) 之和,条件:同 task_id, is_deleted=0'),
('1.1接待数', 'report_light_reform_park.arrival_cnt(到店数) 之和 + report_light_reform_inshop.delivery_touch_cnt(交付触客数) 之和,条件:同 task_id, is_deleted=0'),
('1.1触客率', '(1.1接待数/1.1交车数)*100%'),
('1.1转化率', '(1.1成交单数/1.1接待数)*100%'),
('1.1成交单数', 'report_light_reform_park.deal_cnt(成交数) 之和 + report_light_reform_inshop.total_deal_cnt(总成交数) 之和,条件:同 task_id, is_deleted=0'),
('1.1成交客单价', '1.1产值/1.1交车数,四舍五入保留2位小数'),
('2.1预算', 'sheet1业务类型=2.1明细的"预估产值(纠偏)"之和'),
('2.1产值', 'report_equity_service.store_output_value(门店产值) 之和,条件:同 task_id, is_deleted=0'),
('2.1达成率', '(2.1产值/2.1预算)*100%'),
('2.1毛利率', 'report_equity_service.gross_profit(毛利测算) 之和 / 2.1产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.1毛利率(含人力)', '(report_equity_service.gross_profit(毛利测算) 之和 + marketing_fee(营销费用) 之和)/ 2.1产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.1交车数', 'report_equity_service.delivery_cnt(交车) 之和,条件:同 task_id, is_deleted=0'),
('2.1接待数', 'report_equity_service.touch_cnt(触客) 之和,条件:同 task_id, is_deleted=0'),
('2.1触客率', '(2.1接待数/2.1交车数)*100%'),
('2.1转化率', '(2.1成交单数/2.1接待数)*100%'),
('2.1成交单数', 'report_equity_service.deal_cnt(成交数) 之和,条件:同 task_id, is_deleted=0'),
('2.1成交客单价', '2.1产值/2.1成交单数,四舍五入保留2位小数'),
('2.3预算', 'sheet1业务类型=2.3明细的"预估产值(纠偏)"之和'),
('2.3产值', 'report_extended_warranty.store_output_value(门店产值) 之和,条件:同 task_id, is_deleted=0'),
('2.3达成率', '(2.3产值/2.3预算)*100%'),
('2.3毛利率', 'report_extended_warranty.gross_profit(毛利测算) 之和 / 2.3产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.3毛利率(含人力)', '(report_extended_warranty.gross_profit(毛利测算) 之和 + marketing_fee(营销费用) 之和)/ 2.3产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.3交车数', 'report_extended_warranty.delivery_cnt(交车) 之和,条件:同 task_id, is_deleted=0'),
('2.3接待数', 'report_extended_warranty.touch_cnt(触客) 之和,条件:同 task_id, is_deleted=0'),
('2.3触客率', '(2.3接待数/2.3交车数)*100%'),
('2.3转化率', '(2.3成交单数/2.3接待数)*100%'),
('2.3成交单数', 'report_extended_warranty.deal_cnt(成交数) 之和,条件:同 task_id, is_deleted=0'),
('2.3成交客单价', '2.3产值/2.3成交单数,四舍五入保留2位小数'),
('6.1预算', '默认为空'),
('6.1产值', '二手车台账-汇总销售台账:拍卖日期在周期内 的拍卖价格之和'),
('6.1达成率', '(6.1产值/6.1预算)*100%'),
('6.1毛利率', '(拍卖价格-收购价格)之和/6.1产值'),
('6.1单车均毛利', '(拍卖价格-收购价格)之和/处置台次'),
('6.1交付平均车价', '收购日期在周期内 的收购价格之和/收购台次'),
('6.1处置车量', '拍卖日期在周期内 的明细数量'),
('6.1收车台次', '收购日期在周期内 的明细数量'),
('6.1处置周期(批售)', '拍卖平台≠个人:(拍卖日期-收车日期)天数之和/明细数'),
('6.1处置周期(零售)', '拍卖平台=个人:(拍卖日期-收车日期)天数之和/明细数'),
('6.1库存数量', '拍卖日期为空且处置类型≠寄售 的明细数量'),
('本月流失门店', 'dj_smartcarlife.sale_close_store_record:close_time 在统计月份内的闭店门店数(一条记录=一个门店)'),
('流失豪华门店', '本月流失门店中 main_brands 任一品牌归类=豪华 的门店数'),
('流失非豪华门店', '本月流失门店中 main_brands 无豪华品牌 的门店数'),
('本月新增门店', 'dj_smartcarlife.dj_car_life_scene_merchant_ref_new:按 main_merchant_id 去重取 MIN(created_date) 为首建日期,落在统计月份的门店数'),
('新增豪华门店', '本月新增门店中,main_merchant_id→scrm_account.platform_merchant_brand(first/sec_brand_id)→cyb_os.platform_carbrand(品牌名)→config_brand_category 任一品牌=豪华'),
('新增非豪华门店', '本月新增门店中,品牌未归类豪华(含无品牌记录)的门店数'),
]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--src', default=r'C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源')
ap.add_argument('--month', default='')
ap.add_argument('--period-start', default='')
ap.add_argument('--period-end', default='')
ap.add_argument('--out', default='')
args = ap.parse_args()
ps = excel_serial_to_date(args.period_start) if args.period_start else None
pe = excel_serial_to_date(args.period_end) if args.period_end else None
month_label = args.month or (ps.strftime('%Y%m') if ps else '')
logger.info(f"[构建] 数据源={args.src} 期间={ps}~{pe}")
# 统计月份区间(用于闭店记录查询):优先 --month,其次回退到 --period-start/end
month_start = month_end_excl = None
if args.month:
try:
y, mo = map(int, args.month.split('-'))
month_start = date(y, mo, 1)
if mo == 12:
month_end_excl = date(y + 1, 1, 1)
else:
month_end_excl = date(y, mo + 1, 1)
except Exception:
month_start = month_end_excl = None
elif ps:
month_start = ps
month_end_excl = (pe + timedelta(days=1)) if pe else None
m = compute_metrics(args.src, ps, pe, month_start, month_end_excl)
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
out = args.out or os.path.join(out_dir, f'门店店效人效汇总表_{month_label or "总看板"}.xlsx')
render_board(m, out, month_label)
# 控制台回显关键值,便于核对
print('=' * 60)
for k in ['全国经营门店总数', '豪华车门店数量', '非豪华门店数量', '存量门店数量', '新店数量',
'全国直营门店总数', '豪华直营门店数', '非豪华直营门店数',
'经管预算目标', '全国经营总预算', '存量门店总预算', '新增门店总预算',
'1.1预算', '2.1预算', '2.3预算',
'全国经营总产值', '豪华车店均产值(w)', '非豪华店均产值(w)',
'1.1产值', '2.1产值', '2.3产值',
'1.1成交单数', '2.1成交单数', '2.3成交单数',
'1.1接待数', '2.1接待数', '2.3接待数',
'1.1达成率', '2.1达成率', '2.3达成率',
'1.1触客率', '2.1触客率', '2.3触客率',
'1.1交车数', '2.1交车数', '2.3交车数',
'6.1产值', '6.1处置车量', '6.1收车台次', '6.1库存数量',
'全国直营总人数', '全国直营营销人数', '全国直营店均人数', '全国人均产值(w)',
'豪华车员工数量', '豪华车营销人数', '豪华车店均人数', '豪华车人均产值',
'非豪华员工数量', '非豪华车营销人数', '非豪华车店均人数', '非豪华车人均产值(w)',
'本月流失门店', '流失豪华门店', '流失非豪华门店',
'本月新增门店', '新增豪华门店', '新增非豪华门店']:
print(f'{k:16s} = {m.get(k)}')
print('=' * 60)
print('OUT:', out)
if __name__ == '__main__':
main()