Commit 97b9da6f by zhouhaibao

feat(data-process): 优化店中店数据处理逻辑

- 实现商务政策精确匹配失败后的 fuzzy 包含匹配机制
- 添加门店商务政策未匹配时的日志警告功能
- 将施工成本拆分为前置(原厂/副厂)和后置成本分别计算
- 新增后置施工成本字段(窗膜、车衣、精品)的独立计算
- 修改进销差计算逻辑,仅使用前置施工成本合计
- 更新数据库模型,新增 construction_cost_oe、construction_cost_nonoe、
  construction_cost_post 等字段
- 添加 SQL 表结构变更脚本,支持后置施工成本字段存储
- 优化商务政策 Excel 解析逻辑,支持分类表头和序号行跳过
- 实现人力成本表加密文件解密功能(默认密码 2026)
- 修正人力成本表过滤条件,使用"人员业务归属"替代"业务类型"
- 统一百分比字段处理逻辑,将 Excel 中的小数转换为百分比存储
1 parent 335323c3
......@@ -365,3 +365,18 @@ ALTER TABLE report_light_reform_inshop
ADD COLUMN `store_share_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '门店分成占比(门店分成/门店总产值)'
AFTER `store_share`;
-- ============================================================================
-- 增量 ALTER: 店中店新增后置施工成本 2 字段
-- DB 已有: construction_cost(总计), construction_cost_oe(前置原厂),
-- construction_cost_nonoe(前置副厂), construction_cost_ratio(总计占比)
-- 新增: construction_cost_post, construction_cost_post_ratio
-- construction_cost = oe + nonoe + post
-- ============================================================================
ALTER TABLE report_light_reform_inshop
ADD COLUMN `construction_cost_post` DECIMAL(15, 2) DEFAULT 0
COMMENT '后置施工成本(直营按商务政策, 服务商=0)'
AFTER `construction_cost_nonoe`,
ADD COLUMN `construction_cost_post_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '后置施工成本占比(post/门店总产值)'
AFTER `construction_cost_post`;
......@@ -270,7 +270,12 @@ class LightReformInshopProcessor:
market_fee_raw = sql_data.get('market_fee', Decimal('0'))
# —— 商务政策(店中店)——
cp = commerce_map.get(sn, {})
# 先精确匹配,失败则 fuzzy 包含匹配
cp = commerce_map.get(sn)
if cp is None:
cp = fuzzy_match_store(sn, commerce_map) or {}
if not cp and commerce_map:
logger.warning(f"[店中店] 商务政策未匹配到门店: {sn} (cp_map_keys 样本={list(commerce_map.keys())[:3]})")
oe_film_unit = Decimal(str(cp.get('oe_window_film_cost', 0)))
oe_wrap_unit = Decimal(str(cp.get('oe_car_wrap_cost', 0)))
oe_premium_unit = Decimal(str(cp.get('oe_premium_cost', 0)))
......@@ -278,7 +283,9 @@ class LightReformInshopProcessor:
nonoe_film_unit = Decimal(str(cp.get('nonoe_window_film_cost', 0)))
nonoe_wrap_unit = Decimal(str(cp.get('nonoe_car_wrap_cost', 0)))
nonoe_premium_unit = Decimal(str(cp.get('nonoe_premium_cost', 0)))
construction_cost_post = Decimal(str(cp.get('construction_cost_post', 0)))
post_film_unit = Decimal(str(cp.get('construction_cost_post_film', 0)))
post_wrap_unit = Decimal(str(cp.get('construction_cost_post_wrap', 0)))
post_premium_unit = Decimal(str(cp.get('construction_cost_post_premium', 0)))
frontline_ratio_cp = Decimal(str(cp.get('frontline_incentive_ratio', 0)))
# —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
......@@ -311,7 +318,7 @@ class LightReformInshopProcessor:
# 产值/合计
total_output_value = store_output_value + internal_settle_value
# 施工成本(前置 = 数量 * 单价)
# 施工成本拆分(进销差只用前置合计,后置单独列展示)
construction_cost_oe = (
window_film_oe_cnt * oe_film_unit +
car_wrap_oe_cnt * oe_wrap_unit +
......@@ -323,20 +330,23 @@ class LightReformInshopProcessor:
car_wrap_nonoe_cnt * nonoe_wrap_unit +
premium_nonoe_cnt * nonoe_premium_unit
)
# 直营才加后置施工费(按主订单台次 = delivery_cnt)
construction_cost_post_total = Decimal('0')
if operate_type != '服务商':
construction_cost_post_total = construction_cost_post * Decimal(str(delivery_cnt))
construction_cost = construction_cost_oe + construction_cost_nonoe + construction_cost_post_total
construction_cost_ratio = safe_div_pct_decimal(construction_cost, store_output_value)
# 一线激励
frontline_incentive = (store_output_value * frontline_ratio_cp).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
construction_cost_post = Decimal('0') if (operate_type == '服务商') else (
(window_film_oe_cnt + window_film_nonoe_cnt) * post_film_unit +
(car_wrap_oe_cnt + car_wrap_nonoe_cnt) * post_wrap_unit +
(premium_oe_cnt + premium_nonoe_cnt) * post_premium_unit
)
construction_cost_post_ratio = safe_div_pct_decimal(construction_cost_post, store_output_value)
construction_cost_pre = construction_cost_oe + construction_cost_nonoe # 前置合计,进销差用
construction_cost_ratio = safe_div_pct_decimal(construction_cost_pre, store_output_value) # 复用 DB 字段存前置合计占比
# construction_cost 总计暂不更新(保持默认 0)
# 一线激励(cp_map 已存 1-100 的百分比值,计算金额需 /100)
frontline_incentive = (store_output_value * frontline_ratio_cp / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
frontline_incentive_ratio = frontline_ratio_cp
# 进销差(未分成)
# 进销差(未分成):只用前置施工成本合计
gross_profit_pre_share = (
store_output_value - product_cost_finance - construction_cost - frontline_incentive
store_output_value - product_cost_finance - construction_cost_pre - frontline_incentive
)
gross_profit_pre_share_ratio = safe_div_pct_decimal(gross_profit_pre_share, store_output_value)
......@@ -385,9 +395,9 @@ class LightReformInshopProcessor:
service_provider_share = (store_output_value * sp_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_provider_share_ratio = sp_ratio
# 成本总计
# 成本总计(前置施工成本 + 人力 + 市场费 + 固定费用 + 服务商分成)
total_cost = (
marketing_personnel_cost + construction_cost + market_fee +
marketing_personnel_cost + construction_cost_pre + market_fee +
renovation_amortization + rent_utilities + store_consumables +
service_provider_share
)
......@@ -456,9 +466,12 @@ class LightReformInshopProcessor:
car_wrap_cost=car_wrap_cost,
premium_cost=premium_cost,
product_cost_ratio=product_cost_ratio,
# 施工/激励/进销差/门店分成/兜底/广联
construction_cost=construction_cost,
# 施工成本:oe/nonoe 写入拆分值,ratio 复用存前置合计占比,post/post_ratio 新增写入
construction_cost_oe=construction_cost_oe,
construction_cost_nonoe=construction_cost_nonoe,
construction_cost_ratio=construction_cost_ratio,
construction_cost_post=construction_cost_post,
construction_cost_post_ratio=construction_cost_post_ratio,
frontline_incentive=frontline_incentive,
frontline_incentive_ratio=frontline_incentive_ratio,
gross_profit_pre_share=gross_profit_pre_share,
......
......@@ -482,9 +482,13 @@ class ReportLightReformInshop(db.Model):
premium_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='精品成本')
product_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='产品总成本占比')
# --- 施工/激励/进销差/门店分成/兜底/广联(11 列) ---
construction_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='施工成本')
construction_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='施工成本占比')
# --- 施工成本 ---
construction_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='施工成本合计(当前暂不用)')
construction_cost_oe = db.Column(db.DECIMAL(15, 2), default=0, comment='前置原厂施工成本')
construction_cost_nonoe = db.Column(db.DECIMAL(15, 2), default=0, comment='前置副厂施工成本')
construction_cost_post = db.Column(db.DECIMAL(15, 2), default=0, comment='后置施工成本(直营按商务政策, 服务商=0)')
construction_cost_post_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='后置施工成本占比(post/门店总产值)')
construction_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='前置施工成本占比((oe+nonoe)/门店总产值)')
frontline_incentive = db.Column(db.DECIMAL(15, 2), default=0, comment='一线激励')
frontline_incentive_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='一线激励占比')
gross_profit_pre_share = db.Column(db.DECIMAL(15, 2), default=0, comment='进销差(未分成)')
......
......@@ -1100,32 +1100,43 @@ def _to_int(val):
def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
"""
解析商务政策表(店中店处理版)。
同门店同业务类型多行时,数值字段取**平均**。
Excel 结构:
row0: 分类表头(施工成本前置/后置/一线激励)
row1: 真实列名(门店名称, 窗膜(原厂), ..., 窗膜, 车衣, 精品(后置), 一线激励(前置)...)
row2: 序号行 ('1', '2', '3'...) ← 必须 skip!
row3+: 真实数据
"""
logger.info(f"[商务政策-店中店] 解析 {file_path}, biz_type={biz_type}")
try:
df = pd.read_excel(file_path)
# header=1(row2),skiprows=[2] 跳过序号行
df = pd.read_excel(file_path, header=1, skiprows=[2])
except Exception:
logger.warning(f"[商务政策-店中店] 读取失败 {file_path}")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
df.columns = [re.sub(r'\s+', '', str(c)) if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '门店名'],
'biz_type': ['业务类型', '业务线'],
'frontline_incentive_ratio': ['一线激励', '一线激励占比', '一线激励前置'],
'construction_cost_post': ['施工费后置', '施工成本后置'],
'oe_window_film_cost': ['原厂窗膜前置', '窗膜原厂前置', '原厂膜前置'],
'oe_car_wrap_cost': ['原厂车衣前置', '车衣原厂前置'],
'oe_premium_cost': ['原厂精品前置', '精品原厂前置'],
'pedal_cost': ['踏板前置', '踏板施工'],
'nonoe_window_film_cost': ['副厂窗膜前置', '窗膜副厂前置'],
'nonoe_car_wrap_cost': ['副厂车衣前置', '车衣副厂前置'],
'nonoe_premium_cost': ['副厂精品前置', '精品副厂前置'],
# 施工成本(前置)台/元 → row0 分类表头下的 row1 列名
'oe_window_film_cost': ['窗膜(原厂)', '窗膜(原厂)'],
'oe_car_wrap_cost': ['车衣(原厂)', '车衣(原厂)'],
'oe_premium_cost': ['精品(原厂)', '精品(原厂)'],
'pedal_cost': ['踏板'],
'nonoe_window_film_cost': ['窗膜(副厂)', '窗膜(副厂)'],
'nonoe_car_wrap_cost': ['车衣(副厂)', '车衣(副厂)'],
'nonoe_premium_cost': ['精品(副厂)', '精品(副厂)'],
# 施工成本(后置)台/元 → Excel 列名就是 "窗膜" "车衣" "精品"
'construction_cost_post_film': ['窗膜'],
'construction_cost_post_wrap': ['车衣'],
'construction_cost_post_premium': ['精品'],
# 一线激励
'frontline_incentive_ratio': ['一线激励(前置)', '一线激励(前置)', '一线激励前置', '一线激励'],
})
if 'store_name' not in col_map:
logger.warning("[商务政策-店中店] 未找到门店名列")
logger.warning(f"[商务政策-店中店] 未找到门店名列 (实际列={list(df.columns)[:15]})")
return {}
numeric_fields = [k for k in col_map if k not in ('store_name', 'biz_type')]
......@@ -1133,35 +1144,79 @@ def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
# 所有数值字段默认 Decimal('0')
result = {}
default = {f: Decimal('0') for f in numeric_fields}
# 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100
pct_fields = {'frontline_incentive_ratio'}
for sn, v in raw.items():
merged = dict(default)
merged.update({k: v[k] for k in numeric_fields if k in v})
# 比例字段 ×100(pandas 自动把 Excel 百分比转成小数)
for pf in pct_fields:
if pf in merged and merged[pf] != 0:
merged[pf] = (merged[pf] * Decimal('100')).quantize(Decimal('0.01'))
# 合并后置施工成本 3 列为合计
merged['construction_cost_post'] = (
merged.get('construction_cost_post_film', Decimal('0')) +
merged.get('construction_cost_post_wrap', Decimal('0')) +
merged.get('construction_cost_post_premium', Decimal('0'))
)
result[sn] = merged
logger.info(f"[商务政策-店中店] {len(result)} 个门店")
return result
def parse_labor_cost(file_path, biz_type='1.1'):
def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
"""
解析人力成本表。
解析人力成本表(加密文件密码默认 2026)。
返回 dict[store_name] = headcount (int)
过滤条件:AF列核验=TUER, 业务类型=biz_type, 岗位=门店销售/精品内勤/前台/调度质检员
过滤条件:AF列核验=TUER, 人员业务归属=biz_type, 岗位=门店销售/精品内勤/前台/调度质检员
"""
import tempfile, os, io
logger.info(f"[人力成本表] 解析 {file_path}, biz_type={biz_type}")
# 解密加密的 Excel(密码通常是 2026)
actual_path = file_path
is_tmp = False
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning(f"[人力成本表] 读取失败 {file_path}")
import msoffcrypto
with open(file_path, 'rb') as f:
of = msoffcrypto.OfficeFile(f)
if of.is_encrypted():
of.load_key(password=password)
decrypted = of.decrypt()
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_labor_')
with os.fdopen(tmp_fd, 'wb') as tmp_f:
tmp_f.write(decrypted)
actual_path = tmp_path
is_tmp = True
logger.info(f"[人力成本表] 解密成功(密码={password})")
except ImportError:
logger.warning("[人力成本表] msoffcrypto 未安装,尝试直接读取")
except Exception as e:
logger.warning(f"[人力成本表] 解密失败({e}),尝试直接读取")
try:
df = pd.read_excel(actual_path)
except Exception as e:
logger.warning(f"[人力成本表] 读取失败 {file_path}: {e}")
if is_tmp:
os.unlink(actual_path)
return {}
finally:
if is_tmp:
try:
os.unlink(actual_path)
except Exception:
pass
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['入驻门店', '门店名称', '门店名'],
'verify': ['核验', 'AF', 'AF列'],
'biz_type': ['业务类型'],
'verify': ['核验', 'AF', 'AF列', 'AF列核验', '检核'],
'biz_type': ['人员业务归属', '业务类型', '业务线'],
'position': ['岗位', '职位'],
})
if 'store_name' not in col_map:
logger.warning(f"[人力成本表] 未找到门店名列 (实际列={list(df.columns)[:15]})")
return {}
target_positions = ['门店销售', '精品内勤', '前台', '调度质检员']
......@@ -1169,17 +1224,19 @@ def parse_labor_cost(file_path, biz_type='1.1'):
biz_col = col_map.get('biz_type')
pos_col = col_map.get('position')
# 同门店同业务类型可能多行(多人),count 后直接累加(人数相加)
result = {}
for _, row in df.iterrows():
# AF列核验=TUER
if verify_col:
verify_val = str(row.get(verify_col, '')).strip()
if verify_val != 'TUER':
if verify_val.upper() != 'TUER':
continue
# 人员业务归属=1.1
if biz_col:
bt = str(row.get(biz_col, '')).strip()
if bt != biz_type:
continue
# 岗位筛选
if pos_col:
pos = str(row.get(pos_col, '')).strip()
if pos and not any(t in pos for t in target_positions):
......@@ -1188,7 +1245,7 @@ def parse_labor_cost(file_path, biz_type='1.1'):
if not sn or sn in ('nan', 'None', ''):
continue
result[sn] = result.get(sn, 0) + 1
logger.info(f"[人力成本表] {len(result)} 个门店, biz_type={biz_type}")
logger.info(f"[人力成本表] {len(result)} 个门店, biz_type={biz_type}, headcount样本={list(result.items())[:5]}")
return result
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!