light_reform_park_processor.py
25.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
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
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 轻改园区店汇总独立处理器
============================================
对应 ORM 表:report_light_reform_park
输出类别:park
指标系统:✅ 有(成交数 A075 — 用户明确指定)
关键差异(对比店中店):
- sheet2 反过滤(不包含鸿蒙/AITO/问界/智界/享界/尚界/尊界)
- 用"园区店交车触客表"和"商务政策表(园区店)"
- 施工成本是固定公式(窗膜×95 + 车衣×900 + 精品×60 + 无效×50)
- 园区名称从 Excel park_name 列直接取
SQL 数据源:dj_smartcarlife 库
- fetch_park_daily_report → 日报数据(交车数/到店数)
- fetch_light_reform_goods_stats → 品类成交数(原厂+副厂聚合)+ 产值(与店中店共用 SQL)
- fetch_est_delivery_count → 预估交车数(dj_car_life_merchant_store_info 静态配置表)
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, 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_sheet2_exclude, parse_region_map,
parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats,
fetch_est_delivery_count, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformPark, db
logger = logging.getLogger('LightReformParkProcessor')
class LightReformParkProcessor:
"""轻改园区店汇总独立处理器"""
def __init__(self, app=None):
self.app = app
def scan_store_effect_earnings(self, output_category='park'):
from models import DataProcessTask
logger.info(f"[park] 开始扫描 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"[park] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[park] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[park] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
task_id = task.id
category = 'park'
if is_subtask_completed(task_id, category):
logger.info(f"[park] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_light_reform_park(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
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_light_reform_park(self, task):
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"park_{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_sheet2_exclude(saas_path)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 园区店交车触客表
delivery_touch_map = {}
dt_path = file_map.get('园区店交车触客表')
if dt_path:
delivery_touch_map = parse_park_delivery_touch(dt_path, biz_type='1.1')
# 商务政策表(园区店处理版)
commerce_map = {}
cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)')
if cp_path:
commerce_map = parse_commerce_policy_park(cp_path, biz_type='1.1')
# 人力成本表
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path, biz_type='1.1')
# 预算达成数据(商务)→ 装修分摊/房租水电/门店耗材/服务费占比
budget_achieve_map = {}
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
if budget_path:
budget_achieve_map = parse_budget_achieve_excel(budget_path, biz_type='1.1')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统 biz=2 轻改 ==========
park_codes = ['A075'] # A075=成交数
indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP.get('light_reform', 2), park_codes)
# ========== Step3: 业务系统 SQL ==========
# 3a. 日报数据(scene_type=1 轻改,一次连接两次 GROUP BY,3 字段全返回)
daily_report_map = fetch_park_daily_report(period_start, period_end, scene_type=1)
# 3b. 品类成交数 + 产值(店中店+园区店共用 SQL,park 侧聚合 oe+nonoe)
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 3c. 预估交车数(静态配置表,无日期参数,traffic_party_name 即门店名)
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 3e. 园区店名称(系统表 dj_car_life_merchant_store_info → parking_store_name)
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
# 3e. 精确匹配系统数据 → 组装 sql_data dict
biz_sql_data = {}
for rec in base_records:
sn = rec.get('store_name', '')
dr = exact_match_store(sn, daily_report_map) or {}
gs = exact_match_store(sn, goods_stats_map) or {}
fs = exact_match_store(sn, finance_map) or {}
eq = dr.get('equity_to_shop_count', 0)
af = dr.get('after_sale_equity_to_shop_count', 0)
biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0),
'arrival_cnt': eq + af,
'arrival_invalid_cnt': 0, # 无 SQL
# —— 品类成交数(原厂+副厂聚合,来自 fetch_light_reform_goods_stats)——
'deal_cnt': gs.get('total_deal_cnt', 0),
'window_film_cnt': gs.get('window_film_oe_cnt', 0) + gs.get('window_film_nonoe_cnt', 0),
'car_wrap_cnt': gs.get('car_wrap_oe_cnt', 0) + gs.get('car_wrap_nonoe_cnt', 0),
'premium_cnt': gs.get('premium_oe_cnt', 0) + gs.get('premium_nonoe_cnt', 0),
# —— 产值(来自 fetch_light_reform_goods_stats)——
'store_sales_output': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
# —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': exact_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
'traffic_fee_finance': fs.get('store_share', Decimal('0')), # 流量费 = gopa.shop_traffic_money (dj_order_type!=6)
'market_fee_weighted': fs.get('market_fee', Decimal('0')), # 市场费加权测算 = fee 四项费用累计
}
# 3f. 其他字段(service_fee / construction_cost 等) park 从 Excel 或公式取,保持 0
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
park_est_delivery_total = {}
for rec in base_records:
sn = rec.get('store_name', '')
pn = store_to_park.get(sn, '')
est = int(get_with_fallback(
rec.get('est_delivery_cnt', 0),
get_with_fallback(
exact_match_store(sn, est_delivery_map) or 0,
biz_sql_data.get(sn, {}).get('est_delivery_cnt', 0),
),
) or 0)
park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est
# ========== Step5.5: 识别合并组(Excel 合并单元格) ==========
# 按物理行顺序:est_output_value > 0 的行是"头行",后面连续 est=0 的行属于同一合并组
from decimal import Decimal as _D
merge_groups = []
cur_group = None
for rec in base_records:
sn = rec.get('store_name', '')
est_val = rec.get('est_output_value', _D('0')) or _D('0')
est_del = int(rec.get('est_delivery_cnt', 0) or 0)
if est_val > 0:
if cur_group is not None:
merge_groups.append(cur_group)
cur_group = {
'head_est': est_val,
'stores': [sn],
'deliveries': {sn: est_del},
}
else:
if cur_group is None:
cur_group = {'head_est': _D('0'), 'stores': [sn], 'deliveries': {sn: est_del}}
else:
cur_group['stores'].append(sn)
cur_group['deliveries'][sn] = est_del
if cur_group is not None:
merge_groups.append(cur_group)
store_to_group = {}
for g in merge_groups:
for sn in g['stores']:
store_to_group[sn] = g
multi_groups = [g for g in merge_groups if len(g['stores']) > 1]
logger.info(f"[合并行] 共 {len(merge_groups)} 个合并组, 其中 {len(multi_groups)} 个是多门店组:")
for g in multi_groups:
logger.info(f" head_est={g['head_est']}, stores={g['stores']}")
# ========== Step6: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
park_name = store_to_park.get(sn, '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 ——
pt_excel = delivery_touch_map.get(sn, {})
sql_data = biz_sql_data.get(sn, {})
delivery_cnt = get_with_fallback(
pt_excel.get('delivery_cnt'), sql_data.get('delivery_cnt', 0))
arrival_cnt = get_with_fallback(
pt_excel.get('arrival_cnt'), sql_data.get('arrival_cnt', 0))
arrival_invalid_cnt = get_with_fallback(
pt_excel.get('arrival_invalid_cnt'), sql_data.get('arrival_invalid_cnt', 0))
purchase_indicator = pt_excel.get('purchase_indicator', '')
# —— 指标系统 A075 ——
ind = indicator_data.get(sn, {})
deal_cnt = int(Decimal(str(ind.get('A075', sql_data.get('deal_cnt', 0)))))
# —— SQL 取值(来自 fetch_inshop_goods_stats,品类=原厂+副厂聚合)——
store_sales_output = Decimal(str(sql_data.get('store_sales_output', Decimal('0'))))
internal_settle_value = Decimal(str(sql_data.get('internal_settle_value', Decimal('0'))))
window_film_cnt = sql_data.get('window_film_cnt', 0)
car_wrap_cnt = sql_data.get('car_wrap_cnt', 0)
premium_cnt = sql_data.get('premium_cnt', 0)
est_traffic = sql_data.get('est_traffic', 0)
product_cost_finance = Decimal(str(sql_data.get('product_cost_finance', Decimal('0'))))
internal_settle_cost = Decimal(str(sql_data.get('internal_settle_cost', Decimal('0'))))
traffic_fee_finance = Decimal(str(sql_data.get('traffic_fee_finance', Decimal('0'))))
market_fee_weighted = Decimal(str(sql_data.get('market_fee_weighted', Decimal('0'))))
# —— 商务政策(园区店)——
cp = commerce_map.get(sn, {})
traffic_fee_per_car = Decimal(str(cp.get('traffic_fee_per_car', 0)))
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
# —— 预算目标(预估交车数:Excel 第一优先,SQL 回退)——
avg_price_target = rec.get('avg_price_target', Decimal('0'))
est_delivery_cnt = get_with_fallback(
rec.get('est_delivery_cnt', 0), sql_data.get('est_delivery_cnt', 0))
est_output_value_raw = rec.get('est_output_value', Decimal('0'))
# —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
renovation_amortization = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
period_start, period_end)
rent_utilities = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'rent_utilities'),
period_start, period_end)
store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end)
# 服务费占比:直营店强制 0,服务商直接取
sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
prev_budget_map, sn, 'service_provider_share_ratio')
# ======= 公式 =======
total_output_value = store_sales_output + internal_settle_value
# 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
group = store_to_group.get(sn)
group_head_est = group['head_est'] if group else (rec.get('est_output_value', Decimal('0')) or Decimal('0'))
est_output_value = group_head_est
if group and len(group['stores']) > 1 and group_head_est > 0:
# 多门店合并组 → 按预估交车数占比分摊
group_total_del = sum(group['deliveries'].values())
store_del = group['deliveries'].get(sn, 0)
if group_total_del > 0:
est_output_value = (group_head_est
* Decimal(store_del) / Decimal(group_total_del)
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
# 转化率链路
valid_arrival = arrival_cnt - arrival_invalid_cnt # 有效到店
invalid_arrival_rate = safe_div_pct(arrival_invalid_cnt, arrival_cnt)
arrival_rate = safe_div_pct(arrival_cnt, delivery_cnt)
conversion_rate = safe_div_pct(deal_cnt, arrival_cnt)
avg_unit_price_arrival = safe_div(store_sales_output, valid_arrival, 2)
avg_price_diff = avg_unit_price_arrival - avg_price_target
upgrade_unit_price = safe_div(store_sales_output, deal_cnt, 2)
# 品类转化率
window_film_convert = safe_div_pct(window_film_cnt, arrival_cnt)
car_wrap_convert = safe_div_pct(car_wrap_cnt, arrival_cnt)
premium_convert = safe_div_pct(premium_cnt, arrival_cnt)
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_sales_output)
# 流量费:优先商务政策按台次算,否则用财务列表流量费
traffic_fee_order = (traffic_fee_per_car * Decimal(str(valid_arrival))
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
store_traffic_fee = traffic_fee_order if traffic_fee_order and traffic_fee_order > 0 else traffic_fee_finance
traffic_fee_ratio = safe_div_pct_decimal(store_traffic_fee, store_sales_output)
# 广联分成
gl_share = store_sales_output - product_cost_finance - store_traffic_fee
gl_share_ratio = safe_div_pct_decimal(gl_share, store_sales_output)
internal_settle_profit = internal_settle_value - internal_settle_cost
gl_total_share = gl_share + internal_settle_profit
# 人员成本(直营才算)
personnel_cost = Decimal('0')
if operate_type == '直营':
personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') +
store_sales_output * Decimal('0.04')
)
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
# 施工成本(直营固定公式)
construction_cost = Decimal('0')
if operate_type != '服务商':
construction_cost = (
Decimal(str(window_film_cnt)) * Decimal('95') +
Decimal(str(car_wrap_cnt)) * Decimal('900') +
Decimal(str(premium_cnt)) * Decimal('60') +
Decimal(str(arrival_invalid_cnt)) * Decimal('50')
)
construction_cost_ratio = safe_div_pct_decimal(construction_cost, store_sales_output)
market_fee_weighted_ratio = safe_div_pct_decimal(market_fee_weighted, store_sales_output)
# 服务费(商务报表)= 服务商分成占比 * 门店总产值 / 100(占比为百分比值)
service_fee = (store_sales_output * sp_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = sp_ratio if operate_type != '直营' else Decimal('0')
renovation_ratio = safe_div_pct_decimal(renovation_amortization, store_sales_output)
rent_utilities_ratio = safe_div_pct_decimal(rent_utilities, store_sales_output)
store_consumables_ratio = safe_div_pct_decimal(store_consumables, store_sales_output)
# 成本总计
total_cost = (
personnel_cost + construction_cost + market_fee_weighted +
service_fee + renovation_amortization + rent_utilities + store_consumables
)
cost_ratio = safe_div_pct_decimal(total_cost, store_sales_output)
# 毛利
gross_profit = gl_total_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_sales_output)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
row = ReportLightReformPark(
task_id=task_id, period_start=period_start, period_end=period_end,
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', '园区店'),
operate_type=operate_type, partner_store_cnt=partner_store_cnt,
region_manager=rec.get('region_manager', ''),
park_name=park_name, store_name=sn, brand=brand,
biz_type=biz_type, purchase_indicator=purchase_indicator,
# 触客/交车/转化
delivery_cnt=delivery_cnt, arrival_cnt=arrival_cnt,
arrival_invalid_cnt=arrival_invalid_cnt,
invalid_arrival_rate=invalid_arrival_rate,
arrival_rate=arrival_rate,
deal_cnt=deal_cnt, conversion_rate=conversion_rate,
# 产值/客单
store_sales_output=store_sales_output,
internal_settle_value=internal_settle_value,
total_output_value=total_output_value,
output_progress=output_progress,
avg_unit_price_arrival=avg_unit_price_arrival,
avg_price_target=avg_price_target,
avg_price_diff=avg_price_diff,
upgrade_unit_price=upgrade_unit_price,
# 品类成交+转化
window_film_cnt=window_film_cnt, window_film_convert=window_film_convert,
car_wrap_cnt=car_wrap_cnt, car_wrap_convert=car_wrap_convert,
premium_cnt=premium_cnt, premium_convert=premium_convert,
# 预算
est_traffic=est_traffic,
est_delivery_cnt=est_delivery_cnt,
est_output_value=est_output_value,
# 成本/流量费/广联
product_cost_finance=product_cost_finance,
product_cost_ratio=product_cost_ratio,
internal_settle_cost=internal_settle_cost,
traffic_fee_finance=traffic_fee_finance,
traffic_fee_per_car=traffic_fee_per_car,
traffic_fee_order=traffic_fee_order,
store_traffic_fee=store_traffic_fee,
traffic_fee_ratio=traffic_fee_ratio,
gl_share=gl_share, gl_share_ratio=gl_share_ratio,
internal_settle_profit=internal_settle_profit,
gl_total_share=gl_total_share,
# 人/施/市/服/装/租/耗
personnel_cost=personnel_cost,
personnel_cost_ratio=personnel_cost_ratio,
construction_cost=construction_cost,
construction_cost_ratio=construction_cost_ratio,
market_fee_weighted=market_fee_weighted,
market_fee_weighted_ratio=market_fee_weighted_ratio,
service_fee=service_fee,
service_fee_ratio=service_fee_ratio,
renovation_amortization=renovation_amortization,
renovation_ratio=renovation_ratio,
rent_utilities=rent_utilities,
rent_utilities_ratio=rent_utilities_ratio,
store_consumables=store_consumables,
store_consumables_ratio=store_consumables_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)
# ========== Step7: 排名 ==========
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
# ========== Step8: 批量入库 ==========
ReportLightReformPark.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
db.session.add_all(rows_to_insert[i:i + 500])
db.session.flush()
logger.info(f"[轻改园区店] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)