test_build_template_merchant.py
10 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
# -*- coding: utf-8 -*-
"""
从已有分析报表中提取门店模板数据
数据源: 问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx
从 主表 提取: 门店、兜底指标、兜底类型、特殊情况1、特殊情况2
从 赔付方案 提取: 需达标转化率、赔付金额(非阶梯赔付)、兜底截止日期
从 阶梯赔付明细子表 解析: 阶梯赔付门店的赔付系数公式 → "阈值%,金额"格式
输出: app/templates/问界门店数据模板{序号}.xlsx
"""
import sys, io, re, math
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
from copy import copy
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
SRC = r'C:\Users\jiata\Desktop\问界生态系数生态(生态6.26-7.6&7.1-7.6).xlsx'
# 自动递增三位序号: 问界门店数据模板001.xlsx, 002.xlsx, ...
import os, glob
max_no = 0
for f in glob.glob('app/templates/xlsx/问界门店数据模板[0-9][0-9][0-9].xlsx'):
try:
no = int(os.path.splitext(os.path.basename(f))[0][-3:])
max_no = max(max_no, no)
except ValueError:
pass
OUT = f'app/templates/xlsx/问界门店数据模板{max_no + 1:03d}.xlsx'
# ── 1. 读取主表门店信息 ──
wb = load_workbook(SRC, data_only=True)
main_ws = wb['问界生态系数(6.26-7.5)&(7.1-7.5)']
stores = [] # [(store_name, baodi, baodi_type, special1, special2), ...]
for r in range(5, main_ws.max_row + 1):
sn = main_ws.cell(row=r, column=1).value
if not sn:
break
stores.append({
'门店': str(sn).strip(),
'兜底指标': str(main_ws.cell(row=r, column=2).value or '').strip(),
'兜底类型': str(main_ws.cell(row=r, column=3).value or '').strip(),
'特殊情况1': str(main_ws.cell(row=r, column=4).value or ''),
'特殊情况2': str(main_ws.cell(row=r, column=5).value or ''),
'兜底月份': str(main_ws.cell(row=r, column=49).value or '').strip(), # Col 49 (AW): 兜底月份
# 需达标转化率: 主表 AK/AL/AM (Col 37-39)
'需达标_整车': str(main_ws.cell(row=r, column=37).value or ''),
'需达标_安心包': str(main_ws.cell(row=r, column=38).value or ''),
'需达标_电池': str(main_ws.cell(row=r, column=39).value or ''),
# 赔付金额: 主表 AR/AS/AT (Col 44-46)
'赔付_整车': str(main_ws.cell(row=r, column=44).value or ''),
'赔付_安心包': str(main_ws.cell(row=r, column=45).value or ''),
'赔付_电池': str(main_ws.cell(row=r, column=46).value or ''),
})
print(f'主表门店数: {len(stores)}')
# ── 3. 解析阶梯赔付明细子表 (读取公式) ──
wb_formula = load_workbook(SRC, data_only=False)
step_ws = wb_formula['阶梯赔付明细子表']
step_store_group = {} # {store_name: group_id}
step_formulas = {} # {group_id: {row: {品: formula}}}
group_cols = {'整车延保': 12, '安心包': 13, '电池': 14} # L, M, N
group_id_map = {} # row -> group_id
current_group = 0
for r in range(2, step_ws.max_row + 1):
sn = step_ws.cell(row=r, column=1).value
if sn and str(sn).strip():
step_store_group[str(sn).strip()] = current_group
step_formulas.setdefault(current_group, {})
formulas = {}
for cat, col in group_cols.items():
f = step_ws.cell(row=r, column=col).value
formulas[cat] = str(f).strip() if f else ''
step_formulas[current_group][r] = formulas
else:
# 空行 → 新分组
has_content = any(step_ws.cell(row=r, column=c).value for c in range(1, 15))
if not has_content:
current_group += 1
print(f'阶梯赔付门店: {step_store_group}')
def parse_ladder_coefficient(formula_text, group_id):
"""解析阶梯赔付公式为 "阈值%,金额;阈值%,金额" 格式"""
if not formula_text or not formula_text.startswith('='):
return formula_text
try:
parts = re.findall(r'<(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)\*', formula_text)
if parts:
return ';'.join(f'{t}%,{a}' for t, a in parts)
return ''
except Exception:
return formula_text
# 阶梯分组 → 赔付系数映射
LADDER_COEFF = {
# Group 0: 骏业/骏智系列 (Row 3-6)
0: {'整车延保': '60%,1500;65%,1000', '安心包': '15%,800;20%,600', '电池': '11%,800;15%,600'},
# Group 1: 山西聚驰 (Row 10)
1: {'整车延保': '45%,3420;50%,1500', '安心包': '40%,1154;50%,1000', '电池': '15%,500'},
# Group 2: 山西聚锦驰/长治聚鑫驰 (Row 13-14)
2: {'整车延保': '50%,2000;60%,1000', '安心包': '20%,800', '电池': '15%,500'},
}
for sn, gid in step_store_group.items():
print(f' 阶梯赔付: {sn} → 组{gid}: {LADDER_COEFF.get(gid)}')
# ── 4. 合并数据,输出模板 ──
# 9列: A=门店, B=兜底指标, C=兜底类型, D=特殊情况1, E=特殊情况2,
# F=整车延保, G=安心包, H=电池电池(赔付系数 F1:H1), I=兜底截止日期
header_fill = PatternFill('solid', fgColor='4472C4')
header_font = Font(name='微软雅黑', bold=True, color='FFFFFF', size=10)
sub_fill = PatternFill('solid', fgColor='D6E4F0')
sub_font = Font(name='微软雅黑', bold=True, size=10)
data_font = Font(name='微软雅黑', size=10)
thin_border = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin')
)
center_align = Alignment(horizontal='center', vertical='center', wrap_text=True)
def write_header_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = header_font
c.fill = header_fill
c.alignment = center_align
c.border = thin_border
return c
def write_sub_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = sub_font
c.fill = sub_fill
c.alignment = center_align
c.border = thin_border
return c
def write_data_cell(ws, row, col, value):
c = ws.cell(row=row, column=col, value=value)
c.font = data_font
c.alignment = center_align
c.border = thin_border
return c
# 创建输出工作簿
from openpyxl import Workbook
owb = Workbook()
ows = owb.active
ows.title = '门店信息-赔付信息'
# Row1 表头: A-E 合并 A1:A2 .. E1:E2, F1:H1 合并为"赔付系数", I1:I2 合并
write_header_cell(ows, 1, 1, '门店')
write_header_cell(ows, 1, 2, '兜底指标')
write_header_cell(ows, 1, 3, '兜底类型')
write_header_cell(ows, 1, 4, '特殊情况1')
write_header_cell(ows, 1, 5, '特殊情况2')
write_header_cell(ows, 1, 6, '赔付系数')
ows.merge_cells('F1:H1')
write_header_cell(ows, 1, 9, '兜底截止日期')
for col_letter in ['A', 'B', 'C', 'D', 'E', 'I']:
ows.merge_cells(f'{col_letter}1:{col_letter}2')
# Row2 子表头
write_sub_cell(ows, 2, 6, '整车延保')
write_sub_cell(ows, 2, 7, '安心包')
write_sub_cell(ows, 2, 8, '电池')
# 列宽
ows.column_dimensions['A'].width = 35
ows.column_dimensions['B'].width = 30
ows.column_dimensions['C'].width = 10
ows.column_dimensions['D'].width = 14
ows.column_dimensions['E'].width = 14
ows.column_dimensions['F'].width = 18
ows.column_dimensions['G'].width = 18
ows.column_dimensions['H'].width = 18
ows.column_dimensions['I'].width = 14
# Row3+: 写入数据
missing = 0
step_count = 0
row_num = 3
for s in stores:
sn = s['门店']
write_data_cell(ows, row_num, 1, sn)
write_data_cell(ows, row_num, 2, s['兜底指标'])
write_data_cell(ows, row_num, 3, s['兜底类型'])
write_data_cell(ows, row_num, 4, s['特殊情况1'] if s['特殊情况1'] and s['特殊情况1'] != 'None' else '')
write_data_cell(ows, row_num, 5, s['特殊情况2'] if s['特殊情况2'] and s['特殊情况2'] != 'None' else '')
# 赔付系数
is_ladder = s['特殊情况1'] and '阶梯' in s['特殊情况1']
if is_ladder and sn in step_store_group:
gid = step_store_group[sn]
coeff = LADDER_COEFF.get(gid, {})
write_data_cell(ows, row_num, 6, coeff.get('整车延保', ''))
write_data_cell(ows, row_num, 7, coeff.get('安心包', ''))
write_data_cell(ows, row_num, 8, coeff.get('电池', ''))
step_count += 1
else:
# 从主表取 需达标转化率 (AK/AL/AM) 和 赔付金额 (AR/AS/AT)
target_yb = s.get('需达标_整车', '').replace('None', '')
target_axb = s.get('需达标_安心包', '').replace('None', '')
target_bat = s.get('需达标_电池', '').replace('None', '')
pf_yb = s.get('赔付_整车', '').replace('None', '')
pf_axb = s.get('赔付_安心包', '').replace('None', '')
pf_bat = s.get('赔付_电池', '').replace('None', '')
# 构造 "阈值%,金额" 格式 (target 是小数如0.5, 需转为50%)
def fmt_coeff(target, amount):
if not amount or amount in ('', '0', '0.0'):
return '0%,0'
if '阶段赔付' in amount:
return '阶段赔付'
try:
t_pct = str(round(float(target) * 100, 1)).rstrip('0').rstrip('.')
except (ValueError, TypeError):
t_pct = ''
if not t_pct:
return ''
return f'{t_pct}%,{amount}'.rstrip('.,')
write_data_cell(ows, row_num, 6, fmt_coeff(target_yb, pf_yb))
write_data_cell(ows, row_num, 7, fmt_coeff(target_axb, pf_axb))
write_data_cell(ows, row_num, 8, fmt_coeff(target_bat, pf_bat))
write_data_cell(ows, row_num, 9, s.get('兜底月份', ''))
row_num += 1
# 设置行高 (默认字体大小10, 1.2倍行高 ≈ 15)
default_row_height = 15
for r in range(1, row_num):
ows.row_dimensions[r].height = default_row_height
# 冻结前两行表头
ows.freeze_panes = 'A3'
owb.save(OUT)
print(f'\n输出: {OUT}')
print(f'总行数: {row_num - 3}, 缺失门店: {missing}, 阶梯赔付: {step_count}')
wb.close()
wb_formula.close()