Commit 91b3d594 by zhouhaibao

fix(data-process): 修复数据处理中的逻辑判断和服务费计算

- 修正服务费计算逻辑,将直营判断改为服务商判断
- 优化岚图品牌识别逻辑,使用精确匹配替代模糊匹配
- 移除门店到园区映射的冗余步骤和诊断日志
- 添加合并组识别逻辑用于处理Excel合并单元格场景
- 修正产值达成进度计算,按预估交车数占比分摊
- 更新文件命名规则,使用任务类型名称和当前日期
- 移除预算解析中的模糊匹配,改用精确匹配避免串店问题
- 修正子订单级产品成本计算,增加数量乘积逻辑
1 parent 25e20091
......@@ -218,11 +218,11 @@ class WarrantyProcessor:
# —— 业务系统 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'))
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 '')
is_lantu = (brand or '') == '岚图'
if is_lantu:
pr = float(penetration_rate)
if pr < 30:
......
......@@ -214,7 +214,7 @@ class EquityProcessor:
# —— 业务系统 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'))
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')
......
......@@ -205,27 +205,22 @@ class LightReformParkProcessor:
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step5/Step6 聚合) ==========
# 一次性算好,后面 park_counter / park_est_delivery_total / 主循环都复用
from collections import Counter
# ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
# 精确 → 模糊 → Excel fallback
store_to_park[sn] = (
park_name_sys_map.get(sn)
or fuzzy_match_store(sn, park_name_sys_map)
or rec.get('park_name', '')
)
# 诊断日志:让用户确认 park_name 映射是否生效
_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_name 聚合) ==========
# ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
# ========== Step5.5: 预计算每个 park 的预估交车数合计(用于同 park 多门店分摊预估产值纠偏)==========
park_est_delivery_total = {}
for rec in base_records:
sn = rec.get('store_name', '')
......@@ -239,6 +234,44 @@ class LightReformParkProcessor:
) 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:
......@@ -247,9 +280,8 @@ class LightReformParkProcessor:
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) # 类型=豪华/非豪华
biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 ——
......@@ -312,22 +344,18 @@ class LightReformParkProcessor:
total_output_value = store_sales_output + internal_settle_value
# 产值达成进度(预估总产值 = 预估产值纠偏按同 park 多门店的预估交车数占比分摊)
est_output_value_raw = rec.get('est_output_value', Decimal('0'))
est_output_value = est_output_value_raw
if est_output_value_raw and est_output_value_raw > 0:
# 同 park 多门店共用一个纠偏值 → 按预估交车数占比分摊
park_total_est = park_est_delivery_total.get(park_name, 0)
if partner_store_cnt > 1 and park_total_est > 0:
store_est_delivery = int(get_with_fallback(
rec.get('est_delivery_cnt', 0),
get_with_fallback(
exact_match_store(sn, est_delivery_map) or 0,
sql_data.get('est_delivery_cnt', 0),
),
) or 0)
est_output_value = (est_output_value_raw
* Decimal(store_est_delivery) / Decimal(park_total_est)
# 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
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)
......
......@@ -456,6 +456,8 @@ class OutputValueProcessor:
"""
task_id = task.id
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
# 统计周期起止(页面参数「所属周期」的起止时间)
period_start = getattr(task, 'period_start', None)
......@@ -627,10 +629,10 @@ class OutputValueProcessor:
# ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
try:
excel_path = os.path.join(tmp_dir, f'产值达成表_{stat_month}.xlsx')
excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/output_value_{stat_month}_{task_id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
return file_url
......
......@@ -759,18 +759,14 @@ def extract_budget_ratio(budget_map, store_name, field='labor_ratio'):
"""
从 parse_budget_achieve_excel 返回值中安全取单个字段。
匹配逻辑:先精确匹配 store_name → budget_map key,失败则用 fuzzy_match_store 模糊包含匹配。
模糊匹配兼容"门店名"(SAAS表) vs "流量费名称"(预算表) 命名差异。
返回 Decimal,取不到返回 Decimal('0')。
匹配逻辑:只做门店名**精确匹配**,取不到返回 Decimal('0')。
营销费用/服务费等占比必须精准对应门店,避免模糊匹配串店。
"""
if not budget_map or not store_name:
return Decimal('0')
# 1. 精确匹配
entry = budget_map.get(store_name)
if entry is None:
# 2. 模糊包含匹配
entry = fuzzy_match_store(store_name, budget_map) or {}
return Decimal('0')
val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0')
return val or Decimal('0')
......@@ -2218,35 +2214,35 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
-- gpa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE}
THEN gso.upgrade_shop_price - gso.base_shop_price
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
ELSE 0 END) AS premium_cost,
SUM(CASE WHEN gso.dj_order_type != 6
......
......@@ -428,6 +428,8 @@ class StoreEffectSummaryProcessor:
def generate_result_excel(self, task, row, board_metrics=None, local_only=False):
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
period_end = getattr(task, 'period_end', None)
period_start = getattr(task, 'period_start', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
......@@ -447,14 +449,14 @@ class StoreEffectSummaryProcessor:
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f'红黄门店盈利测算_{stat_month}.xlsx')
final_path = os.path.join(out_dir, f'{type_name}_{today_str}.xlsx')
import shutil
shutil.copy2(local_path, final_path)
logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}")
return final_path
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/red_yellow_report_{stat_month}_{task.id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(local_path, object_key)
logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}")
return file_url
......@@ -529,10 +531,10 @@ class StoreEffectSummaryProcessor:
tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_')
try:
excel_path = os.path.join(tmp_dir, f'门店店效人效汇总表_{stat_month}.xlsx')
excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/store_effect_summary_{stat_month}_{task.id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}")
return file_url
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!