earnings_report_processor.py
15.2 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
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 延保表独立处理器
====================================
对应 ORM 表:report_extended_warranty
业务类型过滤:biz_type=2.3 (对比权益表的 2.1)
指标系统 biz 编码:1 (延保)
流程:
Step1 Excel(SAAS预算分解表 biz_type=2.3 + 关系表 + 主机厂交车)
Step2 指标系统 API(biz=1 延保)
Step3 业务系统 SQL(TODO 占位)
Step4 系统公式计算 + 上月预算达成占比
Step5 排名 + 批量入库
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
from models import ReportExtendedWarranty, db
logger = logging.getLogger('WarrantyProcessor')
class WarrantyProcessor:
"""延保盈利测算独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='warranty'):
"""扫描 store_effect_earnings 任务并处理延保表"""
from models import DataProcessTask
logger.info(f"[warranty] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[warranty] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[warranty] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[warranty] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[warranty] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[warranty] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的延保表输出"""
task_id = task.id
category = 'warranty'
# 子任务已完成 → 跳过(幂等)
if is_subtask_completed(task_id, category):
logger.info(f"[warranty] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
# 子任务状态 → PROCESSING
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_extended_warranty(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[warranty] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
def _process_extended_warranty(self, task):
"""
延保盈利测算完整处理流程。
与权益表的差异:
- biz_type 过滤值 2.3(权益是 2.1)
- 指标系统 biz=1(权益是 3)
- 指标编码多 A066/A070/A086(整车延保/电池/安心包)
- 输出表多延保专属字段(vehicle_warranty_cnt / battery_warranty_cnt / easy_bag_cnt 及各自渗透率)
"""
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[延保] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"warranty_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
base_records = parse_saas_base(saas_path, BIZ_TYPE_WARRANTY)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 鸿蒙 + 广联主机厂交车 → 跨表模糊匹配合并
hm_part = parse_delivery_table(file_map.get('鸿蒙主机厂数据表')) if file_map.get('鸿蒙主机厂数据表') else {}
gl_part = parse_delivery_table(file_map.get('广联主机厂数据表')) if file_map.get('广联主机厂数据表') else {}
delivery_map = merge_delivery_maps(hm_part, gl_part)
# 预算达成数据(商务)→ 人员工资占比 = 营销费用占比
# form_type 兼容中英文括号
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
prev_labor_ratio_map = {}
if budget_path:
prev_labor_ratio_map = parse_budget_achieve_excel(budget_path, biz_type='2.3')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step1.5: 主机厂交车数未匹配门店 → 系统日报 scene_type=0 兜底 ==========
all_store_names = [r.get('store_name', '') for r in base_records if r.get('store_name')]
unfitted_names = [sn for sn in all_store_names if not fuzzy_match_store(sn, delivery_map)]
system_delivery_map = {}
if unfitted_names:
logger.info(f"[延保] Excel交车未匹配 {len(unfitted_names)} 家门店,查系统日报 scene_type=0 兜底")
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
try:
system_delivery_map = fetch_park_daily_report(start_str, end_str, scene_type=0)
logger.info(f"[延保] 系统日报 scene_type=0 → {len(system_delivery_map)} 个门店")
except Exception as e:
logger.warning(f"[延保] 系统日报兜底查询失败: {e}")
system_delivery_map = {}
# ========== Step2: 指标系统(延保 2.3)→ 产值/成交/触客/延保各项 ==========
# 注意:单值 biz 会被指标 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
try:
indicator_data = fetch_indicator_data(
start_str, end_str, [INDICATOR_BIZ_MAP.get('warranty')],
['A036', 'A075', 'A084', 'A066', 'A070', 'A086']) or {}
except Exception as e:
logger.warning(f"[延保] 指标系统拉取失败,指标类字段置 0: {e}")
indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
# 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
# ========== Step5: 逐行公式计算 ==========
rows_to_insert = []
for rec in base_records:
store_name = rec.get('store_name', '')
brand = rec.get('brand', '')
province = rec.get('province', '')
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
# 业务系统 SQL — 精确匹配,避免模糊误匹配(如"广西河池中达"误匹配到其他"中达"门店)
biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(两边都是 Excel,命名可能不同 → 模糊保留)
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map:
_sys_entry = exact_match_store(store_name, system_delivery_map) or {}
delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值
touch_cnt = int(Decimal(str(ind.get('A084', 0))))
deal_cnt = int(Decimal(str(ind.get('A075', 0))))
vehicle_warranty_cnt = int(Decimal(str(ind.get('A066', 0))))
battery_warranty_cnt = int(Decimal(str(ind.get('A070', 0))))
easy_bag_cnt = int(Decimal(str(ind.get('A086', 0))))
store_output_value = Decimal(str(ind.get('A036', 0)))
# ======= 公式 =======
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
vehicle_warranty_penetration = safe_div_pct(vehicle_warranty_cnt, delivery_cnt)
vehicle_warranty_touch_convert = safe_div_pct(vehicle_warranty_cnt, touch_cnt)
battery_warranty_penetration = safe_div_pct(battery_warranty_cnt, delivery_cnt)
easy_bag_penetration = safe_div_pct(easy_bag_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
# —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)——
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0'))
# —— 门店分成:普通品牌取系统流量费 shop_traffic_money;岚图按渗透率区间算比例 * 门店产值 ——
# penetration_rate 范围 0-100(safe_div_pct 已 ×100)
is_lantu = '岚图' in (brand or '')
if is_lantu:
pr = float(penetration_rate)
if pr < 30:
lantu_ratio = Decimal('0.88')
elif pr < 50:
lantu_ratio = Decimal('0.85')
else:
lantu_ratio = Decimal('0.80')
store_share = (store_output_value * lantu_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
else:
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = clamp_ratio(extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio'))
# Excel 预算表的百分比是"带百分号"的原值(如 5.0 = 5%),算费用时需除以 100
marketing_fee = (store_output_value * marketing_fee_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
gross_profit = gl_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
region_area = region_map.get((BIZ_TYPE_WARRANTY, province), '') or region_map.get(('', province), '')
row = ReportExtendedWarranty(
task_id=task_id,
period_start=period_start,
period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
region_manager=rec.get('region_manager', ''),
training_supervisor=rec.get('training_supervisor', ''),
biz_manager=rec.get('biz_manager', ''),
resident_type=resident_type, store_name=store_name, brand=brand,
# 触客/成交
delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt,
penetration_rate=penetration_rate,
# 延保特有指标
vehicle_warranty_cnt=vehicle_warranty_cnt,
vehicle_warranty_penetration=vehicle_warranty_penetration,
vehicle_warranty_touch_convert=vehicle_warranty_touch_convert,
battery_warranty_cnt=battery_warranty_cnt,
battery_warranty_penetration=battery_warranty_penetration,
easy_bag_cnt=easy_bag_cnt,
easy_bag_penetration=easy_bag_penetration,
# 产值/成本/费用/毛利
store_output_value=store_output_value,
upgrade_unit_price=upgrade_unit_price,
product_cost=product_cost, store_share=store_share,
guarantee_amount=guarantee_amount, gl_share=gl_share,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
marketing_fee=marketing_fee, marketing_fee_ratio=marketing_fee_ratio,
service_fee=service_fee, service_fee_ratio=service_fee_ratio,
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step6: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step7: 批量入库 ==========
ReportExtendedWarranty.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
batch = rows_to_insert[i:i + 500]
db.session.add_all(batch)
db.session.flush()
logger.info(f"[延保] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)