earnings_report_processor.py
11.6 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
# -*- 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,
fetch_indicator_data, fetch_prev_month_labor_ratio,
safe_div, safe_div_pct, safe_div_pct_decimal,
)
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 {}
delivery_map = {}
for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'):
fpath = file_map.get(ftype)
if fpath:
part = parse_delivery_table(fpath)
for k, v in part.items():
delivery_map[k] = delivery_map.get(k, 0) + v
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(biz=1 延保) ==========
warranty_codes = ['A084', 'A075', 'A066', 'A070', 'A086', 'A036']
indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP['warranty'], warranty_codes)
# ========== Step3: 业务系统 SQL(TODO 占位) ==========
biz_sql_data = {}
logger.warning("[延保] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月营销费用占比 ==========
prev_labor_ratio_map = fetch_prev_month_labor_ratio(task, base_records)
# ========== 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, {})
delivery_cnt = delivery_map.get(store_name, 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)
biz_data = biz_sql_data.get(store_name, {})
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'))
store_share = biz_data.get('store_share', 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 = prev_labor_ratio_map.get(store_name, Decimal('0'))
marketing_fee = (store_output_value * marketing_fee_ratio).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)