Commit 9abd5db8 by zhouhaibao

refactor(data-process): 重构数据处理模块以支持业务类型过滤和预算比例提取

- 在 parse_budget_achieve_excel 函数中添加 biz_type 参数以支持业务类型过滤
- 新增 extract_budget_ratio 函数用于安全提取预算比例数据
- 新增 prorate_by_period 函数用于按周期摊销月度固定费用
- 为多个解析函数添加 biz_type 参数和业务类型过滤功能
- 统一多个 Excel 解析函数的聚合逻辑,支持同门店同业务类型多行数据处理
- 重构轻改店中店和园区店处理器中的预算数据处理逻辑
- 替换原有的 fetch_prev_month_budget_detail 调用为 Excel 解析方式
- 优化人力成本表解析逻辑,支持动态业务类型过滤
1 parent 45b68eba
...@@ -24,7 +24,7 @@ from report_utils import ( ...@@ -24,7 +24,7 @@ from report_utils import (
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED, SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, parse_saas_base, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, parse_budget_achieve_excel, extract_budget_ratio,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
...@@ -146,7 +146,7 @@ class WarrantyProcessor: ...@@ -146,7 +146,7 @@ class WarrantyProcessor:
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)') budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
prev_labor_ratio_map = {} prev_labor_ratio_map = {}
if budget_path: if budget_path:
prev_labor_ratio_map = parse_budget_achieve_excel(budget_path) prev_labor_ratio_map = parse_budget_achieve_excel(budget_path, biz_type='2.3')
finally: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
...@@ -198,7 +198,7 @@ class WarrantyProcessor: ...@@ -198,7 +198,7 @@ class WarrantyProcessor:
gl_share = store_output_value - product_cost - store_share - guarantee_amount gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value) 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_ratio = extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio')
marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) 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) service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
......
...@@ -24,7 +24,7 @@ from report_utils import ( ...@@ -24,7 +24,7 @@ from report_utils import (
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED, SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, parse_saas_base, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, parse_budget_achieve_excel, extract_budget_ratio,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
...@@ -148,7 +148,7 @@ class EquityProcessor: ...@@ -148,7 +148,7 @@ class EquityProcessor:
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)') budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
prev_labor_ratio_map = {} prev_labor_ratio_map = {}
if budget_path: if budget_path:
prev_labor_ratio_map = parse_budget_achieve_excel(budget_path) prev_labor_ratio_map = parse_budget_achieve_excel(budget_path, biz_type='2.1')
finally: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
...@@ -193,7 +193,7 @@ class EquityProcessor: ...@@ -193,7 +193,7 @@ class EquityProcessor:
gl_share = store_output_value - product_cost - store_share - guarantee_amount gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value) 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_ratio = extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio')
marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) 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) service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
......
...@@ -22,7 +22,7 @@ from report_utils import ( ...@@ -22,7 +22,7 @@ from report_utils import (
parse_saas_base_sheet2, parse_region_map, parse_saas_base_sheet2, parse_region_map,
parse_inshop_delivery_touch, parse_commerce_policy_inshop, parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
fetch_prev_month_budget_detail, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformInshop, db from models import ReportLightReformInshop, db
...@@ -127,32 +127,35 @@ class LightReformInshopProcessor: ...@@ -127,32 +127,35 @@ class LightReformInshopProcessor:
delivery_touch_map = {} delivery_touch_map = {}
dt_path = file_map.get('店中店交车触客表') dt_path = file_map.get('店中店交车触客表')
if dt_path: if dt_path:
delivery_touch_map = parse_inshop_delivery_touch(dt_path) delivery_touch_map = parse_inshop_delivery_touch(dt_path, biz_type='1.1')
# 商务政策表(店中店处理版) # 商务政策表(店中店处理版)
commerce_map = {} commerce_map = {}
cp_path = file_map.get('商务政策表(店中店)') or file_map.get('商务政策表(店中店)') cp_path = file_map.get('商务政策表(店中店)') or file_map.get('商务政策表(店中店)')
if cp_path: if cp_path:
commerce_map = parse_commerce_policy_inshop(cp_path) commerce_map = parse_commerce_policy_inshop(cp_path, biz_type='1.1')
# 人力成本表 # 人力成本表
labor_map = {} labor_map = {}
lc_path = file_map.get('人力成本表') lc_path = file_map.get('人力成本表')
if lc_path: if lc_path:
labor_map = parse_labor_cost(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: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
# ========== Step2: 业务系统 SQL(TODO 占位) ========== # ========== Step2: 业务系统 SQL(TODO 占位) ==========
# 轻改店中店完全不调指标系统,所有 SQL 来源字段统一走 biz_sql_data
# 包含:成交数/产值、品类成交数、各类产值/成本、门店分成、市场费、施工收入等
biz_sql_data = {} biz_sql_data = {}
logger.warning("[轻改店中店] Step2 业务系统 SQL 暂未实现,相关字段默认 0") logger.warning("[轻改店中店] Step2 业务系统 SQL 暂未实现")
# ========== Step4: 上月预算明细 ========== # ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')}) prev_budget_map = budget_achieve_map
prev_budget_map = fetch_prev_month_budget_detail(task, store_names)
# ========== Step5: 逐行计算 ========== # ========== Step5: 逐行计算 ==========
rows_to_insert = [] rows_to_insert = []
...@@ -226,12 +229,19 @@ class LightReformInshopProcessor: ...@@ -226,12 +229,19 @@ class LightReformInshopProcessor:
construction_cost_post = Decimal(str(cp.get('construction_cost_post', 0))) construction_cost_post = Decimal(str(cp.get('construction_cost_post', 0)))
frontline_ratio_cp = Decimal(str(cp.get('frontline_incentive_ratio', 0))) frontline_ratio_cp = Decimal(str(cp.get('frontline_incentive_ratio', 0)))
# —— 上月预算明细 —— # —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
pb = prev_budget_map.get(sn, {}) # 装修分摊 / 房租水电 / 门店耗材:按"周期天数/月份总天数"摊销
renovation_amortization = pb.get('renovation_amortization', Decimal('0')) renovation_amortization = prorate_by_period(
rent_utilities = pb.get('rent_utilities', Decimal('0')) extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
store_consumables = pb.get('store_consumables', Decimal('0')) period_start, period_end)
sp_ratio = pb.get('service_provider_share_ratio', Decimal('0')) 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)
# 服务费占比:直接取(比例值不摊销)
sp_ratio = extract_budget_ratio(prev_budget_map, sn, 'service_provider_share_ratio')
# —— 人力成本 —— # —— 人力成本 ——
headcount = labor_map.get(sn, 0) headcount = labor_map.get(sn, 0)
......
...@@ -25,7 +25,8 @@ from report_utils import ( ...@@ -25,7 +25,8 @@ from report_utils import (
parse_saas_base_sheet2_exclude, parse_region_map, parse_saas_base_sheet2_exclude, parse_region_map,
parse_park_delivery_touch, parse_commerce_policy_park, parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
fetch_prev_month_budget_detail, fetch_indicator_data, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformPark, db from models import ReportLightReformPark, db
...@@ -124,36 +125,40 @@ class LightReformParkProcessor: ...@@ -124,36 +125,40 @@ class LightReformParkProcessor:
delivery_touch_map = {} delivery_touch_map = {}
dt_path = file_map.get('园区店交车触客表') dt_path = file_map.get('园区店交车触客表')
if dt_path: if dt_path:
delivery_touch_map = parse_park_delivery_touch(dt_path) delivery_touch_map = parse_park_delivery_touch(dt_path, biz_type='1.1')
# 商务政策表(园区店处理版) # 商务政策表(园区店处理版)
commerce_map = {} commerce_map = {}
cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)') cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)')
if cp_path: if cp_path:
commerce_map = parse_commerce_policy_park(cp_path) commerce_map = parse_commerce_policy_park(cp_path, biz_type='1.1')
# 人力成本表 # 人力成本表
labor_map = {} labor_map = {}
lc_path = file_map.get('人力成本表') lc_path = file_map.get('人力成本表')
if lc_path: if lc_path:
labor_map = parse_labor_cost(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: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统 biz=2 轻改 ========== # ========== Step2: 指标系统 biz=2 轻改 ==========
park_codes = ['A075'] # A075=成交数(园区店唯一指标) park_codes = ['A075'] # A075=成交数
indicator_data = fetch_indicator_data( indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP.get('light_reform', 2), park_codes) start_str, end_str, INDICATOR_BIZ_MAP.get('light_reform', 2), park_codes)
# ========== Step3: 业务系统 SQL(TODO 占位) ========== # ========== Step3: 业务系统 SQL(TODO 占位) ==========
# 窗膜/车衣/精品成交数、产值、产品成本、流量费、市场费、预估流量等
biz_sql_data = {} biz_sql_data = {}
logger.warning("[轻改园区店] Step3 业务系统 SQL 暂未实现,相关字段默认 0") logger.warning("[轻改园区店] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月预算明细 ========== # ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')}) prev_budget_map = budget_achieve_map
prev_budget_map = fetch_prev_month_budget_detail(task, store_names)
# ========== Step5: 合作门店数量(按 park_name 聚合) ========== # ========== Step5: 合作门店数量(按 park_name 聚合) ==========
from collections import Counter from collections import Counter
...@@ -213,12 +218,19 @@ class LightReformParkProcessor: ...@@ -213,12 +218,19 @@ class LightReformParkProcessor:
est_delivery_cnt = rec.get('est_delivery_cnt', 0) est_delivery_cnt = rec.get('est_delivery_cnt', 0)
est_output_value_raw = rec.get('est_output_value', Decimal('0')) est_output_value_raw = rec.get('est_output_value', Decimal('0'))
# —— 上月预算明细 —— # —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
pb = prev_budget_map.get(sn, {}) renovation_amortization = prorate_by_period(
renovation_amortization = pb.get('renovation_amortization', Decimal('0')) extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
rent_utilities = pb.get('rent_utilities', Decimal('0')) period_start, period_end)
store_consumables = pb.get('store_consumables', Decimal('0')) rent_utilities = prorate_by_period(
sp_ratio = pb.get('service_provider_share_ratio', Decimal('0')) 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')
# ======= 公式 ======= # ======= 公式 =======
......
...@@ -511,15 +511,20 @@ def fetch_prev_month_labor_ratio(task, base_records): ...@@ -511,15 +511,20 @@ def fetch_prev_month_labor_ratio(task, base_records):
return results return results
def parse_budget_achieve_excel(file_path): def parse_budget_achieve_excel(file_path, biz_type=None):
""" """
解析上传的"预算达成数据(商务)"Excel 文件,取"人员工资占比" → 营销费用占比。 解析上传的"预算达成数据(商务)"Excel 文件。
门店名映射列:流量费名称(target_name / 流量方名称 / 门店名)。 一个文件同时服务多个场景:
返回 dict[store_name] = Decimal(营销费用占比)。 - 延保 (biz_type='2.3') / 权益 (biz_type='2.1'):人员工资占比 → 营销费用占比
- 轻改店中店/园区店 (biz_type='1.1'):装修分摊 / 房租水电 / 门店耗材 / 服务费占比
注:这是延保/权益营销费用占比的**主要来源**(form_type=预算达成数据(商务))。
:param file_path: Excel 文件路径
:param biz_type: 业务类型过滤值('1.1'/'2.1'/'2.3'),None 则不按业务类型过滤
匹配到同门店同业务类型多行时,数值字段取**平均**,文本字段取第一条
门店名映射列:流量费名称 / 流量方名称 / 门店名。
返回 dict[store_name] = {5 个字段 Decimal}
""" """
logger.info(f"[预算达成Excel] 解析 {file_path}") logger.info(f"[预算达成Excel] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -528,38 +533,112 @@ def parse_budget_achieve_excel(file_path): ...@@ -528,38 +533,112 @@ def parse_budget_achieve_excel(file_path):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
# 门店名映射列(流量费名称 / 流量方名称)
'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'], 'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'],
# 人员工资占比 → 营销费用占比 'biz_type': ['业务类型', '业务线'],
'labor_ratio': ['人员工资占比', '人员工资', '人员成本占比', '营销费用占比'], 'labor_ratio': ['人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'],
'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'],
'store_consumables': ['门店耗材', '耗材'],
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率'],
}) })
if 'store_name' not in col_map: if 'store_name' not in col_map:
logger.warning("[预算达成Excel] 未找到门店名列(流量费名称)") logger.warning("[预算达成Excel] 未找到门店名列")
return {}
if 'labor_ratio' not in col_map:
logger.warning("[预算达成Excel] 未找到人员工资占比列")
return {} return {}
store_col = col_map['store_name'] store_col = col_map['store_name']
ratio_col = col_map['labor_ratio'] biz_col = col_map.get('biz_type')
result = {} field_cols = {k: v for k, v in col_map.items() if k not in ('store_name', 'biz_type')}
# 先收集所有值,同门店同 biz_type 多行 → sum+count → 最后取平均
# 聚合 key = (store_name, biz_type_val)
agg = {} # (sn, bt_val) → {field: [sum, count]}
for _, row in df.iterrows(): for _, row in df.iterrows():
sn = str(row.get(store_col, '')).strip() sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''): if not sn or sn in ('nan', 'None', ''):
continue continue
val = row.get(ratio_col, None)
bt_val = str(row.get(biz_col, '')).strip() if biz_col else ''
# 如果没找到 biz_type 列或传入了过滤条件,按过滤条件匹配
if biz_type is not None and biz_col:
if bt_val != biz_type:
continue
key = (sn, bt_val) if biz_col else (sn, '')
if key not in agg:
agg[key] = {}
for field, col in field_cols.items():
val = row.get(col, None)
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'): if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'):
continue continue
try: try:
result[sn] = Decimal(str(val)) d = Decimal(str(val))
except Exception: except Exception:
continue continue
if field not in agg[key]:
agg[key][field] = [Decimal('0'), 0]
agg[key][field][0] += d
agg[key][field][1] += 1
logger.info(f"[预算达成Excel] {len(result)} 个门店匹配到人员工资占比") # 取平均
result = {}
for (sn, _bt), fields in agg.items():
if sn not in result:
result[sn] = {
'labor_ratio': Decimal('0'),
'renovation_amortization': Decimal('0'),
'rent_utilities': Decimal('0'),
'store_consumables': Decimal('0'),
'service_provider_share_ratio': Decimal('0'),
}
for field, (total, cnt) in fields.items():
if cnt > 0:
result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)
logger.info(f"[预算达成Excel] {len(result)} 个门店匹配")
return result return result
def extract_budget_ratio(budget_map, store_name, field='labor_ratio'):
"""从 parse_budget_achieve_excel 返回值中安全取单个字段(向后兼容)"""
entry = budget_map.get(store_name, {})
val = entry.get(field, Decimal('0'))
return val or Decimal('0')
def prorate_by_period(total_amount, period_start, period_end):
"""
按"当前统计周期天数 / 月份总天数"摊销费用。
装修分摊/房租水电/门店耗材 等月度固定费用需要按周期天数折算。
period_start/period_end: date 对象。
返回 Decimal。
"""
if not total_amount or total_amount == 0:
return Decimal('0')
try:
# 周期天数
if period_start and period_end:
period_days = (period_end - period_start).days + 1
else:
period_days = 30 # fallback
# 月份总天数(按 period_start 所在月算)
if period_start:
import calendar
month_total = calendar.monthrange(period_start.year, period_start.month)[1]
else:
month_total = 30
if month_total <= 0:
return Decimal(str(total_amount))
return (Decimal(str(total_amount)) * Decimal(str(period_days)) / Decimal(str(month_total))
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal(str(total_amount))
# ============================================================ # ============================================================
# 轻改店中店 - 专属解析函数 # 轻改店中店 - 专属解析函数
# ============================================================ # ============================================================
...@@ -713,7 +792,75 @@ def parse_inshop_delivery_touch(file_path): ...@@ -713,7 +792,75 @@ def parse_inshop_delivery_touch(file_path):
返回 dict[store_name] = {sales_order_cnt, sales_touch_cnt, delivery_cnt, delivery_touch_cnt, 返回 dict[store_name] = {sales_order_cnt, sales_touch_cnt, delivery_cnt, delivery_touch_cnt,
aftersales_baohui_cnt, aftersales_shigu_cnt, aftersales_touch_cnt, purchase_indicator} aftersales_baohui_cnt, aftersales_shigu_cnt, aftersales_touch_cnt, purchase_indicator}
""" """
logger.info(f"[店中店交车触客表] 解析 {file_path}") def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fields, biz_type=None):
"""
通用聚合器:按 (store_name, biz_type) 过滤后,同门店多行 → 数值字段求和取平均,文本字段取第一条。
返回 dict[store_name] = {field: value}。
"""
biz_col = col_map.get('biz_type')
agg = {} # (sn, bt) → {field: [sum, count]} for numeric, 'text'→first_val for text
for _, row in df.iterrows():
sn = str(row.get(store_name_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
bt_val = str(row.get(biz_col, '')).strip() if biz_col else ''
if biz_type is not None and biz_col and bt_val != biz_type:
continue
key = (sn, bt_val) if biz_col else (sn, '')
if key not in agg:
agg[key] = {}
for f in numeric_fields:
col = col_map.get(f)
if not col:
continue
val = row.get(col, None)
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'):
continue
try:
d = Decimal(str(val))
except Exception:
continue
if f not in agg[key]:
agg[key][f] = [Decimal('0'), 0]
agg[key][f][0] += d
agg[key][f][1] += 1
for f in text_fields:
col = col_map.get(f)
if not col:
continue
val = str(row.get(col, '')).strip()
if val in ('', 'nan', 'None'):
continue
# 文本字段:第一条非空值覆盖
if f not in agg[key] or not agg[key][f]:
agg[key][f] = val
result = {}
for (sn, _bt), fields in agg.items():
if sn not in result:
result[sn] = {}
for f, v in fields.items():
if isinstance(v, list):
# 数值 [sum, count] → 取平均
total, cnt = v
result[sn][f] = (total / Decimal(str(cnt))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0')
else:
result[sn][f] = v
return result
def parse_inshop_delivery_touch(file_path, biz_type='1.1'):
"""
解析店中店交车触客表(区域运营填写)。
同门店同业务类型多行时,数值字段取**平均**。
返回 dict[store_name] = {...}
"""
logger.info(f"[店中店交车触客表] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -723,6 +870,7 @@ def parse_inshop_delivery_touch(file_path): ...@@ -723,6 +870,7 @@ def parse_inshop_delivery_touch(file_path):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'], 'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'sales_order_cnt': ['销售大定数', '销售大定'], 'sales_order_cnt': ['销售大定数', '销售大定'],
'sales_touch_cnt': ['销售触客数', '销售触客'], 'sales_touch_cnt': ['销售触客数', '销售触客'],
'delivery_cnt': ['交车数', '交车'], 'delivery_cnt': ['交车数', '交车'],
...@@ -737,21 +885,16 @@ def parse_inshop_delivery_touch(file_path): ...@@ -737,21 +885,16 @@ def parse_inshop_delivery_touch(file_path):
logger.warning("[店中店交车触客表] 未找到门店名列") logger.warning("[店中店交车触客表] 未找到门店名列")
return {} return {}
numeric = ['sales_order_cnt', 'sales_touch_cnt', 'delivery_cnt', 'delivery_touch_cnt',
'aftersales_baohui_cnt', 'aftersales_shigu_cnt', 'aftersales_touch_cnt']
text = ['purchase_indicator']
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, text, biz_type)
# int 字段转回 int
result = {} result = {}
for _, row in df.iterrows(): for sn, v in raw.items():
sn = str(row.get(col_map['store_name'], '')).strip() result[sn] = {k: int(v[k]) if k in numeric and v.get(k) else int(Decimal('0')) for k in numeric}
if not sn or sn in ('nan', 'None', ''): result[sn]['purchase_indicator'] = v.get('purchase_indicator', '')
continue
result[sn] = {
'sales_order_cnt': _to_int(row.get(col_map.get('sales_order_cnt', ''), 0)),
'sales_touch_cnt': _to_int(row.get(col_map.get('sales_touch_cnt', ''), 0)),
'delivery_cnt': _to_int(row.get(col_map.get('delivery_cnt', ''), 0)),
'delivery_touch_cnt': _to_int(row.get(col_map.get('delivery_touch_cnt', ''), 0)),
'aftersales_baohui_cnt': _to_int(row.get(col_map.get('aftersales_baohui_cnt', ''), 0)),
'aftersales_shigu_cnt': _to_int(row.get(col_map.get('aftersales_shigu_cnt', ''), 0)),
'aftersales_touch_cnt': _to_int(row.get(col_map.get('aftersales_touch_cnt', ''), 0)),
'purchase_indicator': str(row.get(col_map.get('purchase_indicator', ''), '')).strip() if col_map.get('purchase_indicator') else '',
}
logger.info(f"[店中店交车触客表] {len(result)} 个门店") logger.info(f"[店中店交车触客表] {len(result)} 个门店")
return result return result
...@@ -765,18 +908,12 @@ def _to_int(val): ...@@ -765,18 +908,12 @@ def _to_int(val):
return 0 return 0
def parse_commerce_policy_inshop(file_path): def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
""" """
解析商务政策表(店中店处理版)。 解析商务政策表(店中店处理版)。
返回 dict[store_name] = { 同门店同业务类型多行时,数值字段取**平均**。
oe_window_film_cost, nonoe_window_film_cost,
oe_car_wrap_cost, nonoe_car_wrap_cost,
oe_premium_cost, nonoe_premium_cost,
pedal_cost, construction_cost_post,
frontline_incentive_ratio,
}
""" """
logger.info(f"[商务政策-店中店] 解析 {file_path}") logger.info(f"[商务政策-店中店] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -786,14 +923,13 @@ def parse_commerce_policy_inshop(file_path): ...@@ -786,14 +923,13 @@ def parse_commerce_policy_inshop(file_path):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'], 'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'frontline_incentive_ratio': ['一线激励', '一线激励占比', '一线激励前置'], 'frontline_incentive_ratio': ['一线激励', '一线激励占比', '一线激励前置'],
'construction_cost_post': ['施工费后置', '施工成本后置'], 'construction_cost_post': ['施工费后置', '施工成本后置'],
# 原厂各品类前置施工成本
'oe_window_film_cost': ['原厂窗膜前置', '窗膜原厂前置', '原厂膜前置'], 'oe_window_film_cost': ['原厂窗膜前置', '窗膜原厂前置', '原厂膜前置'],
'oe_car_wrap_cost': ['原厂车衣前置', '车衣原厂前置'], 'oe_car_wrap_cost': ['原厂车衣前置', '车衣原厂前置'],
'oe_premium_cost': ['原厂精品前置', '精品原厂前置'], 'oe_premium_cost': ['原厂精品前置', '精品原厂前置'],
'pedal_cost': ['踏板前置', '踏板施工'], 'pedal_cost': ['踏板前置', '踏板施工'],
# 副厂
'nonoe_window_film_cost': ['副厂窗膜前置', '窗膜副厂前置'], 'nonoe_window_film_cost': ['副厂窗膜前置', '窗膜副厂前置'],
'nonoe_car_wrap_cost': ['副厂车衣前置', '车衣副厂前置'], 'nonoe_car_wrap_cost': ['副厂车衣前置', '车衣副厂前置'],
'nonoe_premium_cost': ['副厂精品前置', '精品副厂前置'], 'nonoe_premium_cost': ['副厂精品前置', '精品副厂前置'],
...@@ -803,22 +939,26 @@ def parse_commerce_policy_inshop(file_path): ...@@ -803,22 +939,26 @@ def parse_commerce_policy_inshop(file_path):
logger.warning("[商务政策-店中店] 未找到门店名列") logger.warning("[商务政策-店中店] 未找到门店名列")
return {} return {}
numeric_fields = [k for k in col_map if k not in ('store_name', 'biz_type')]
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric_fields, [], biz_type)
# 所有数值字段默认 Decimal('0')
result = {} result = {}
for _, row in df.iterrows(): default = {f: Decimal('0') for f in numeric_fields}
sn = str(row.get(col_map['store_name'], '')).strip() for sn, v in raw.items():
if not sn or sn in ('nan', 'None', ''): merged = dict(default)
continue merged.update({k: v[k] for k in numeric_fields if k in v})
result[sn] = {k: _to_decimal(row.get(v, 0)) for k, v in col_map.items() if k != 'store_name'} result[sn] = merged
logger.info(f"[商务政策-店中店] {len(result)} 个门店") logger.info(f"[商务政策-店中店] {len(result)} 个门店")
return result return result
def parse_labor_cost(file_path): def parse_labor_cost(file_path, biz_type='1.1'):
""" """
解析人力成本表。 解析人力成本表。
返回 dict[store_name] = headcount (int) — AF列核验=TUER, 业务类型=1.1, 岗位=门店销售/精品内勤/前台/调度质检员 返回 dict[store_name] = headcount (int)
过滤条件:AF列核验=TUER, 业务类型=biz_type, 岗位=门店销售/精品内勤/前台/调度质检员
""" """
logger.info(f"[人力成本表] 解析 {file_path}") logger.info(f"[人力成本表] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -836,22 +976,30 @@ def parse_labor_cost(file_path): ...@@ -836,22 +976,30 @@ def parse_labor_cost(file_path):
return {} return {}
target_positions = ['门店销售', '精品内勤', '前台', '调度质检员'] target_positions = ['门店销售', '精品内勤', '前台', '调度质检员']
verify_col = col_map.get('verify')
biz_col = col_map.get('biz_type')
pos_col = col_map.get('position')
# 同门店同业务类型可能多行(多人),count 后直接累加(人数相加)
result = {} result = {}
for _, row in df.iterrows(): for _, row in df.iterrows():
verify_val = str(row.get(col_map.get('verify', ''), '')).strip() if col_map.get('verify') else '' if verify_col:
verify_val = str(row.get(verify_col, '')).strip()
if verify_val != 'TUER': if verify_val != 'TUER':
continue continue
bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else '' if biz_col:
if bt != '1.1': bt = str(row.get(biz_col, '')).strip()
if bt != biz_type:
continue continue
pos = str(row.get(col_map.get('position', ''), '')).strip() if col_map.get('position') else '' if pos_col:
pos = str(row.get(pos_col, '')).strip()
if pos and not any(t in pos for t in target_positions): if pos and not any(t in pos for t in target_positions):
continue continue
sn = str(row.get(col_map['store_name'], '')).strip() sn = str(row.get(col_map['store_name'], '')).strip()
if not sn or sn in ('nan', 'None', ''): if not sn or sn in ('nan', 'None', ''):
continue continue
result[sn] = result.get(sn, 0) + 1 result[sn] = result.get(sn, 0) + 1
logger.info(f"[人力成本表] {len(result)} 个门店匹配到人数") logger.info(f"[人力成本表] {len(result)} 个门店, biz_type={biz_type}")
return result return result
...@@ -919,12 +1067,12 @@ def is_luxury_brand(brand_name): ...@@ -919,12 +1067,12 @@ def is_luxury_brand(brand_name):
return '非豪华' return '非豪华'
def parse_park_delivery_touch(file_path): def parse_park_delivery_touch(file_path, biz_type='1.1'):
""" """
解析园区店交车触客表(区域运营填写)。 解析园区店交车触客表(区域运营填写)。
返回 dict[store_name] = {delivery_cnt, arrival_cnt, arrival_invalid_cnt, purchase_indicator} 同门店同业务类型多行时,数值字段取**平均**。
""" """
logger.info(f"[园区店交车触客表] 解析 {file_path}") logger.info(f"[园区店交车触客表] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -934,6 +1082,7 @@ def parse_park_delivery_touch(file_path): ...@@ -934,6 +1082,7 @@ def parse_park_delivery_touch(file_path):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'], 'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'delivery_cnt': ['交车数', '交车', '新车交付'], 'delivery_cnt': ['交车数', '交车', '新车交付'],
'arrival_cnt': ['到店数', '到店'], 'arrival_cnt': ['到店数', '到店'],
'arrival_invalid_cnt': ['到店无效', '无效客户数', '到店无效客户'], 'arrival_invalid_cnt': ['到店无效', '无效客户数', '到店无效客户'],
...@@ -943,27 +1092,23 @@ def parse_park_delivery_touch(file_path): ...@@ -943,27 +1092,23 @@ def parse_park_delivery_touch(file_path):
logger.warning("[园区店交车触客表] 未找到门店名列") logger.warning("[园区店交车触客表] 未找到门店名列")
return {} return {}
numeric = ['delivery_cnt', 'arrival_cnt', 'arrival_invalid_cnt']
text = ['purchase_indicator']
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, text, biz_type)
result = {} result = {}
for _, row in df.iterrows(): for sn, v in raw.items():
sn = str(row.get(col_map['store_name'], '')).strip() result[sn] = {k: int(v[k]) if k in numeric and v.get(k) else 0 for k in numeric}
if not sn or sn in ('nan', 'None', ''): result[sn]['purchase_indicator'] = v.get('purchase_indicator', '')
continue
result[sn] = {
'delivery_cnt': _to_int(row.get(col_map.get('delivery_cnt', ''), 0)),
'arrival_cnt': _to_int(row.get(col_map.get('arrival_cnt', ''), 0)),
'arrival_invalid_cnt': _to_int(row.get(col_map.get('arrival_invalid_cnt', ''), 0)),
'purchase_indicator': str(row.get(col_map.get('purchase_indicator', ''), '')).strip() if col_map.get('purchase_indicator') else '',
}
logger.info(f"[园区店交车触客表] {len(result)} 个门店") logger.info(f"[园区店交车触客表] {len(result)} 个门店")
return result return result
def parse_commerce_policy_park(file_path): def parse_commerce_policy_park(file_path, biz_type='1.1'):
""" """
解析商务政策表(园区店处理版)。 解析商务政策表(园区店处理版)。
返回 dict[store_name] = {traffic_fee_per_car, ...} —— 门店分成参考(按单台计算流量/台) 同门店同业务类型多行时,数值字段取**平均**。
""" """
logger.info(f"[商务政策-园区店] 解析 {file_path}") logger.info(f"[商务政策-园区店] 解析 {file_path}, biz_type={biz_type}")
try: try:
df = pd.read_excel(file_path) df = pd.read_excel(file_path)
except Exception: except Exception:
...@@ -973,19 +1118,17 @@ def parse_commerce_policy_park(file_path): ...@@ -973,19 +1118,17 @@ def parse_commerce_policy_park(file_path):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'], 'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'traffic_fee_per_car': ['门店分成参考', '按单台计算流量', '流量费/台', '单台流量费'], 'traffic_fee_per_car': ['门店分成参考', '按单台计算流量', '流量费/台', '单台流量费'],
}) })
if 'store_name' not in col_map: if 'store_name' not in col_map:
logger.warning("[商务政策-园区店] 未找到门店名列") logger.warning("[商务政策-园区店] 未找到门店名列")
return {} return {}
numeric = [k for k in col_map if k not in ('store_name', 'biz_type')]
raw = _aggregate_by_biz_type(df, col_map, col_map['store_name'], numeric, [], biz_type)
result = {} result = {}
for _, row in df.iterrows(): for sn, v in raw.items():
sn = str(row.get(col_map['store_name'], '')).strip() result[sn] = {f: v.get(f, Decimal('0')) for f in numeric}
if not sn or sn in ('nan', 'None', ''):
continue
result[sn] = {
'traffic_fee_per_car': _to_decimal(row.get(col_map.get('traffic_fee_per_car', ''), 0)),
}
logger.info(f"[商务政策-园区店] {len(result)} 个门店") logger.info(f"[商务政策-园区店] {len(result)} 个门店")
return result return result
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!