equity_processor.py
11.9 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
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 权益表独立处理器
====================================
对应 ORM 表:report_equity_service
业务类型过滤:biz_type=2.1 (对比延保表的 2.3)
指标系统 biz 编码:3 (权益)
流程:
Step1 Excel(SAAS预算分解表 biz_type=2.1 + 关系表 + 主机厂交车)
Step2 指标系统 API(biz=3 权益)
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_EQUITY, 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,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fuzzy_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
from models import ReportEquityService, db
logger = logging.getLogger('EquityProcessor')
class EquityProcessor:
"""权益盈利测算独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='equity'):
"""扫描 store_effect_earnings 任务并处理权益表"""
from models import DataProcessTask
logger.info(f"[equity] 开始扫描 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"[equity] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[equity] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[equity] 任务 {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"[equity] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[equity] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的权益表输出"""
task_id = task.id
category = 'equity'
if is_subtask_completed(task_id, category):
logger.info(f"[equity] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_equity_service(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[equity] 任务 {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_equity_service(self, task):
"""
权益盈利测算完整处理流程。
与延保表的差异:
- biz_type 过滤值 2.1(延保是 2.3)
- 指标系统 biz=3(延保是 1)
- 指标编码仅 A084/A075/A036(延保还有 A066/A070/A086 延保专属字段)
- 输出表列更简洁(无延保/电池/安心包特有字段)
"""
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"equity_{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门店预算分解表")
# 权益表用 biz_type=2.1
base_records = parse_saas_base(saas_path, BIZ_TYPE_EQUITY)
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
# 预算达成数据(商务)→ 人员工资占比 = 营销费用占比
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.1')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(权益 2.1)→ 产值/成交/触客 ==========
# 注意:单值 biz 会被指标 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
try:
indicator_data = fetch_indicator_data(
start_str, end_str, [INDICATOR_BIZ_MAP.get('equity')],
['A036', 'A075', 'A084']) or {}
except Exception as e:
logger.warning(f"[权益] 指标系统拉取失败,指标类字段置 0: {e}")
indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')]
# BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY, store_names_for_sql)
# ========== 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, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {}
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))))
store_output_value = Decimal(str(ind.get('A036', 0)))
# ======= 公式 =======
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
# —— 业务系统 SQL 取值 ——
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(来自主汇总记录)
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_EQUITY, province), '') or region_map.get(('', province), '')
row = ReportEquityService(
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,
# 产值/成本/费用/毛利
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: 批量入库 ==========
ReportEquityService.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)