Commit 52c3ee3a by zhouhaibao

refactor(data-process): 优化预算达成数据处理逻辑

- 修改 strip_if_dplus 函数保留 D+ 前缀
- 更新 _fetch_gmv_from_db 方法返回 settlement_map 和 park_ratio_map
- 添加园区店比例数据查询和处理功能
- 修改任务状态筛选条件从 PROCESSING 到 AA
- 调整外包施工费、人力成本、房租水电费用解析方法增加比例分摊逻辑
- 重构人力成本解析逻辑实现园区店回退匹配和精确分摊
- 优化成本汇总表构建过程添加数据聚合和比例分摊功能
- 增强日志输出和数据验证机制确保金额守恒
1 parent ae6a13ea
...@@ -466,9 +466,7 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -466,9 +466,7 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
def strip_if_dplus(name): def strip_if_dplus(name):
"""去 'D+' 前缀的归一化(避免重复 import)。""" """返回字符串(保留 D+ 前缀)。"""
if name and name.startswith('D+'):
return name[2:]
return name or '' return name or ''
......
...@@ -101,9 +101,7 @@ KNOWN_PASSWORDS = { ...@@ -101,9 +101,7 @@ KNOWN_PASSWORDS = {
_ALIAS_MAPS = {} # kind('4s'|'yq') -> {alias_name: standard_name} _ALIAS_MAPS = {} # kind('4s'|'yq') -> {alias_name: standard_name}
def strip_if_dplus(name): def strip_if_dplus(name):
"""去 'D+' 前缀的归一化""" """返回字符串(保留 D+ 前缀)。"""
if name and str(name).startswith('D+'):
return str(name)[2:]
return str(name or '') return str(name or '')
def load_alias_maps(): def load_alias_maps():
...@@ -405,8 +403,11 @@ class DataProcessor: ...@@ -405,8 +403,11 @@ class DataProcessor:
def _fetch_gmv_from_db(self, task_id, stat_month): def _fetch_gmv_from_db(self, task_id, stat_month):
""" """
从 biz_budget_achieve 表查询已有的 GMV 和产值数据。 从 biz_budget_achieve 表查询已有的 GMV 和产值数据。
返回:settlement_map 字典 {(流量方名称, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal, 返回:(settlement_map, park_ratio_map)
"服务费": Decimal, "嘀加分润": Decimal, "服务商": str, "装修摊销": Decimal, "门店耗材": Decimal}} settlement_map: {(流量方名称, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal,
"服务费": Decimal, "嘀加分润": Decimal, "服务商": str, "装修摊销": Decimal, "门店耗材": Decimal,
"gmv_ratio": float|None, "gmv_ratio_park": float|None}}
park_ratio_map: {(业务类型, 园区店): gmv_ratio_park}
""" """
logger.info(f"[GMV数据] 从数据库获取 task_id={task_id}, stat_month={stat_month} 的 GMV 数据") logger.info(f"[GMV数据] 从数据库获取 task_id={task_id}, stat_month={stat_month} 的 GMV 数据")
settlement_map = {} settlement_map = {}
...@@ -418,7 +419,7 @@ class DataProcessor: ...@@ -418,7 +419,7 @@ class DataProcessor:
if not records: if not records:
logger.warning(f"[GMV数据] 数据库中无 task_id={task_id}, stat_month={stat_month} 的记录") logger.warning(f"[GMV数据] 数据库中无 task_id={task_id}, stat_month={stat_month} 的记录")
return settlement_map return settlement_map, {}
for r in records: for r in records:
flow_name = (r.traffic_name or "").strip() flow_name = (r.traffic_name or "").strip()
...@@ -431,13 +432,16 @@ class DataProcessor: ...@@ -431,13 +432,16 @@ class DataProcessor:
service_provider = (r.service_provider or "").strip() service_provider = (r.service_provider or "").strip()
renovation = Decimal(str(r.renovation_amortization or 0)) renovation = Decimal(str(r.renovation_amortization or 0))
consumables = Decimal(str(r.store_consumables or 0)) consumables = Decimal(str(r.store_consumables or 0))
park_store_val = to_standard((r.park_store or "").strip(), 'yq')
key = (flow_name, biz_type, brand) key = (flow_name, biz_type, brand)
if key not in settlement_map: if key not in settlement_map:
settlement_map[key] = { settlement_map[key] = {
"GMV": Decimal("0"), "产值": Decimal("0"), "GMV": Decimal("0"), "产值": Decimal("0"),
"服务费": Decimal("0"), "嘀加分润": Decimal("0"), "服务费": Decimal("0"), "嘀加分润": Decimal("0"),
"服务商": "", "装修摊销": Decimal("0"), "门店耗材": Decimal("0") "服务商": "", "装修摊销": Decimal("0"), "门店耗材": Decimal("0"),
"gmv_ratio": None, "gmv_ratio_park": None,
"park_store": ""
} }
settlement_map[key]["GMV"] += gmv_val settlement_map[key]["GMV"] += gmv_val
settlement_map[key]["产值"] += revenue_val settlement_map[key]["产值"] += revenue_val
...@@ -446,12 +450,45 @@ class DataProcessor: ...@@ -446,12 +450,45 @@ class DataProcessor:
settlement_map[key]["服务商"] = service_provider # 服务商不累积,直接覆盖 settlement_map[key]["服务商"] = service_provider # 服务商不累积,直接覆盖
settlement_map[key]["装修摊销"] += renovation settlement_map[key]["装修摊销"] += renovation
settlement_map[key]["门店耗材"] += consumables settlement_map[key]["门店耗材"] += consumables
settlement_map[key]["park_store"] = park_store_val # 园区店直接覆盖
logger.info(f"[GMV数据] 获取到 {len(settlement_map)} 条 GMV 记录") # 直接查询比例数据(不用ORM对象属性名冲突)
try:
ratio_records = db.session.execute(
text("SELECT traffic_name, business_type, brand, gmv_ratio, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm")
).params(tid=task_id, sm=stat_month).fetchall()
for rr in ratio_records:
flow_n = (rr[0] or "").strip()
bt = (rr[1] or "").strip()
br = (rr[2] or "").strip()
key = (flow_n, bt, br)
if key in settlement_map:
settlement_map[key]["gmv_ratio"] = float(rr[3]) if rr[3] is not None else None
settlement_map[key]["gmv_ratio_park"] = float(rr[4]) if rr[4] is not None else None
except Exception as e2:
logger.warning(f"[GMV数据] 比例数据查询失败: {str(e2)}")
# 构建 park_ratio_map: (业务类型, 园区店) -> gmv_ratio_park
park_ratio_map = {}
try:
park_ratio_records = db.session.execute(
text("SELECT business_type, park_store, gmv_ratio_park FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm AND gmv_ratio_park IS NOT NULL")
).params(tid=task_id, sm=stat_month).fetchall()
for pr in park_ratio_records:
bt = (pr[0] or "").strip()
ps = to_standard((pr[1] or "").strip(), 'yq')
if bt and ps:
park_ratio_map[(bt, ps)] = float(pr[2])
except Exception as e3:
logger.warning(f"[GMV数据] 园区店比例查询失败: {str(e3)}")
park_store_count = len([v for v in settlement_map.values() if v.get('park_store')])
logger.info(f"[GMV数据] 获取到 {len(settlement_map)} 条 GMV 记录,已装配 {park_store_count} 条 park_store")
logger.info(f"[GMV数据] 比例数据: {len([v for v in settlement_map.values() if v.get('gmv_ratio') is not None])} 条有gmv_ratio, {len(park_ratio_map)} 条park_ratio_map")
except Exception as e: except Exception as e:
logger.error(f"[GMV数据] 查询失败: {str(e)}") logger.error(f"[GMV数据] 查询失败: {str(e)}")
return settlement_map return settlement_map, park_ratio_map
def _fetch_previous_month_data(self, task_id, stat_month): def _fetch_previous_month_data(self, task_id, stat_month):
""" """
...@@ -511,7 +548,7 @@ class DataProcessor: ...@@ -511,7 +548,7 @@ class DataProcessor:
""" """
logger.info("[扫描] 开始扫描待处理任务...") logger.info("[扫描] 开始扫描待处理任务...")
tasks = DataProcessTask.query.filter( tasks = DataProcessTask.query.filter(
DataProcessTask.status == 'PROCESSING', DataProcessTask.status == 'AA',
DataProcessTask.is_deleted == 0 DataProcessTask.is_deleted == 0
).order_by(DataProcessTask.created_at.asc()).all() ).order_by(DataProcessTask.created_at.asc()).all()
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务") logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务")
...@@ -674,7 +711,7 @@ class DataProcessor: ...@@ -674,7 +711,7 @@ class DataProcessor:
# 从数据库获取 GMV 和产值数据(替代解析结算数据汇总表 Excel) # 从数据库获取 GMV 和产值数据(替代解析结算数据汇总表 Excel)
settlement_data = None settlement_data = None
settlement_map = self._fetch_gmv_from_db(task.id, task.month) settlement_map, park_ratio_map = self._fetch_gmv_from_db(task.id, task.month)
if settlement_map: if settlement_map:
# 构建兼容格式的 settlement_data(供 _build_cost_summary 使用) # 构建兼容格式的 settlement_data(供 _build_cost_summary 使用)
settlement_data = [] settlement_data = []
...@@ -690,6 +727,9 @@ class DataProcessor: ...@@ -690,6 +727,9 @@ class DataProcessor:
"服务商": data.get("服务商", ""), "服务商": data.get("服务商", ""),
"装修摊销": data.get("装修摊销", Decimal("0")), "装修摊销": data.get("装修摊销", Decimal("0")),
"门店耗材": data.get("门店耗材", Decimal("0")), "门店耗材": data.get("门店耗材", Decimal("0")),
"gmv_ratio": data.get("gmv_ratio"),
"gmv_ratio_park": data.get("gmv_ratio_park"),
"park_store": data.get("park_store", ""),
}) })
logger.info(f"[处理任务] 从数据库获取 GMV 数据 {len(settlement_data)} 条记录") logger.info(f"[处理任务] 从数据库获取 GMV 数据 {len(settlement_data)} 条记录")
else: else:
...@@ -704,19 +744,19 @@ class DataProcessor: ...@@ -704,19 +744,19 @@ class DataProcessor:
# 解析外援施工费 # 解析外援施工费
wage_results = [] wage_results = []
if '外施施工费用表' in downloaded_files: if '外施施工费用表' in downloaded_files:
wage_results = self._parse_external_worker_fee(downloaded_files['外施施工费用表']) wage_results = self._parse_external_worker_fee(downloaded_files['外施施工费用表'], settlement_map=settlement_map)
logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录") logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录")
# 解析人力成本 # 解析人力成本
labor_results = [] labor_results = []
if '人力成本统计表' in downloaded_files: if '人力成本统计表' in downloaded_files:
labor_results = self._parse_labor_cost(downloaded_files['人力成本统计表']) labor_results = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map)
logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 条记录") logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 条记录")
# 解析房租水电施工费 # 解析房租水电施工费
utility_results = [] utility_results = []
if '房租水电费用表' in downloaded_files: if '房租水电费用表' in downloaded_files:
utility_results = self._parse_utility_fee(downloaded_files['房租水电费用表']) utility_results = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map)
logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录") logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录")
logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s") logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")
...@@ -739,7 +779,8 @@ class DataProcessor: ...@@ -739,7 +779,8 @@ class DataProcessor:
prev_month_data = self._fetch_previous_month_data(task.id, task.month) prev_month_data = self._fetch_previous_month_data(task.id, task.month)
summary_data = self._build_cost_summary( summary_data = self._build_cost_summary(
settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data,
settlement_map=settlement_map, park_ratio_map=park_ratio_map
) )
logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录") logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录")
logger.info(f"[处理任务] 步骤 d 完成, 耗时: {time.time() - step_d_start:.2f}s") logger.info(f"[处理任务] 步骤 d 完成, 耗时: {time.time() - step_d_start:.2f}s")
...@@ -1180,7 +1221,7 @@ class DataProcessor: ...@@ -1180,7 +1221,7 @@ class DataProcessor:
# 解析外援施工费表 # 解析外援施工费表
# ======================================================== # ========================================================
def _parse_external_worker_fee(self, file_path): def _parse_external_worker_fee(self, file_path, settlement_map=None):
""" """
解析外援施工费表。 解析外援施工费表。
规则: 规则:
...@@ -1280,11 +1321,29 @@ class DataProcessor: ...@@ -1280,11 +1321,29 @@ class DataProcessor:
result = [] result = []
for (flow, biz), records in grouped.items(): for (flow, biz), records in grouped.items():
total_fee = sum(r["外援施工费"] for r in records) total_fee = sum(r["外援施工费"] for r in records)
result.append({
"流量方名称": flow, # 优先从 settlement_map 查找 gmv_ratio 进行分摊
"业务类型": biz, db_ratio = None
"外援施工费": round_2(total_fee), if settlement_map:
}) for (fn, bt, br), sv in settlement_map.items():
if fn == flow and bt == biz and sv.get("gmv_ratio") is not None:
db_ratio = sv["gmv_ratio"]
break
if db_ratio is not None:
logger.info(f"[外援施工费分摊] 流量方匹配成功,使用 gmv_ratio={db_ratio}")
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(total_fee * Decimal(str(db_ratio))),
})
else:
logger.warning(f"[外援施工费分摊] 流量方匹配失败,使用原始金额")
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(total_fee),
})
logger.info(f"[外援施工费] 汇总后 {len(result)} 条记录") logger.info(f"[外援施工费] 汇总后 {len(result)} 条记录")
if result: if result:
...@@ -1295,17 +1354,16 @@ class DataProcessor: ...@@ -1295,17 +1354,16 @@ class DataProcessor:
# 解析人力成本表 # 解析人力成本表
# ======================================================== # ========================================================
def _parse_labor_cost(self, file_path): def _parse_labor_cost(self, file_path, settlement_map=None, park_ratio_map=None):
""" """
解析人力成本表。 解析人力成本表。
规则: 规则:
- 仅检核=TRUE的行参与计算 - 仅检核=TRUE的行参与计算
- 1.1业务:岗位=贴膜技师→技师工资;其他→营销团队工资 - 1.1业务:岗位=贴膜技师→技师工资;其他→营销团队工资
- 2.1/2.3业务:全部→营销团队工资 - 2.1/2.3业务:全部→营销团队工资
- 匹配策略:先"流量方名称+业务类型"→"入驻门店+人员业务归属" - 匹配策略:先用"入驻门店"直接匹配settlement_map的流量方名称
- 回退策略:匹配失败时用"园区店+业务类型"匹配 - 回退策略:匹配失败时用"入驻门店"标准化为园区店名,查找关联流量方,按比例分摊
- 多条记录按GMV分摊 返回:List[dict],每行 {流量方名称, 业务类型, 技师工资, 营销团队工资}
返回:List[dict],每行 {流量方名称, 业务类型, 技师工资, 营销团队工资, __park_store__}
""" """
logger.info(f"[人力成本] 解析文件: {file_path}") logger.info(f"[人力成本] 解析文件: {file_path}")
...@@ -1313,9 +1371,50 @@ class DataProcessor: ...@@ -1313,9 +1371,50 @@ class DataProcessor:
logger.warning(f"[人力成本] 文件不存在: {file_path}") logger.warning(f"[人力成本] 文件不存在: {file_path}")
return [] return []
# 尝试解密文件 if settlement_map is None:
actual_path, is_decrypted = decrypt_excel_if_needed(file_path) settlement_map = {}
# 构建 settlement_map 的索引
flow_names_set = set() # 所有流量方名称
park_to_flows = defaultdict(list) # park_store -> [(flow_name, biz_type)]
# 每个 (流量方, 业务类型) 在园区店内的 GMV 占比(已入库 gmv_ratio_park)
# 按 (park_store, flow_name, biz_type) 聚合求和,兼容多品牌行
_park_ratio_raw = defaultdict(lambda: defaultdict(Decimal))
for (flow_name, biz_type, brand), data in settlement_map.items():
flow_names_set.add(flow_name)
ps = data.get("park_store", "")
if ps:
park_to_flows[ps].append((flow_name, biz_type))
ratio = data.get("gmv_ratio_park")
if ratio is not None:
_park_ratio_raw[ps][(flow_name, biz_type)] += Decimal(str(ratio))
# park_to_ratio: key=ps or (bt,ps) or (ps, flow, bt) -> ratio
park_to_ratio = {}
# (park_store, flow, biz_type) 级最精细
for ps, inner in _park_ratio_raw.items():
for (fn, bt), total in inner.items():
park_to_ratio[(ps, fn, bt)] = float(total)
park_to_ratio[(bt, ps)] = float(total) # 便于回退
# park_store 级取任意一个(通常 park 下所有 flow 的 ratio 语义一致,
# 这里仅作兜底,真正分摊按 (ps, flow, bt) 精确匹配)
if inner:
first_ratio = next(iter(inner.values()))
park_to_ratio[ps] = float(first_ratio)
# 如果有 park_ratio_map,合并进去(兜底补充)
if park_ratio_map:
for (bt, ps), ratio in park_ratio_map.items():
key = (bt, ps)
if key not in park_to_ratio:
park_to_ratio[key] = ratio
if ps not in park_to_ratio:
park_to_ratio[ps] = ratio
logger.info(f"[人力成本] settlement_map 索引: {len(flow_names_set)} 个流量方, {len(park_to_flows)} 个园区店")
# 解密并读取 Excel
actual_path, is_decrypted = decrypt_excel_if_needed(file_path)
try: try:
xls = pd.ExcelFile(actual_path) xls = pd.ExcelFile(actual_path)
except Exception as e: except Exception as e:
...@@ -1325,13 +1424,14 @@ class DataProcessor: ...@@ -1325,13 +1424,14 @@ class DataProcessor:
return [] return []
raw_records = [] raw_records = []
direct_match_count = 0
park_match_count = 0
park_fail_count = 0
park_allocated_total = Decimal("0")
failed_count = 0
failed_stores = []
try: try:
# 人力成本只读取第一个 Sheet(通常命名为"人力成本")
if not xls.sheet_names:
logger.warning("[人力成本] Excel 文件没有 Sheet")
return []
sheet_name = xls.sheet_names[0] sheet_name = xls.sheet_names[0]
logger.info(f"[人力成本] 读取第一个 Sheet: {sheet_name}") logger.info(f"[人力成本] 读取第一个 Sheet: {sheet_name}")
df_raw = pd.read_excel(actual_path, sheet_name=sheet_name, header=None) df_raw = pd.read_excel(actual_path, sheet_name=sheet_name, header=None)
...@@ -1339,52 +1439,55 @@ class DataProcessor: ...@@ -1339,52 +1439,55 @@ class DataProcessor:
df = pd.read_excel(actual_path, sheet_name=sheet_name, header=header_row) df = pd.read_excel(actual_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns] df.columns = [str(col).strip() for col in df.columns]
# 调试日志:显示识别到的列名
logger.info(f"[人力成本] 识别到列名({len(df.columns)}列): {list(df.columns)[:15]}...")
logger.info(f"[人力成本] 数据行数: {len(df)}")
logger.info(f"[人力成本] 前2行数据预览:")
for i in range(min(2, len(df))):
row_vals = {k: str(v)[:30] for k, v in df.iloc[i].items() if pd.notna(v) and str(v).strip()}
logger.info(f"[人力成本] 行{i}: {row_vals}")
# 查找关键列 # 查找关键列
col_store = find_column(df, "入驻门店", "门店", "流量方名称") col_store = find_column(df, "入驻门店")
col_park_store = find_column(df, "园区店", "园区") col_biz = find_column(df, "业务线")
col_biz = find_column(df, "人员业务归属", "业务归属", "业务类型") col_position = find_column(df, "岗位")
col_position = find_column(df, "岗位", "职位", "工种") col_salary = find_column(df, "个人本店分摊薪资")
col_salary = find_column(df, "个人本店分摊薪资", "薪资", "工资", "应发工资", "合计")
col_gmv = find_column(df, "GMV", "产值") col_gmv = find_column(df, "GMV", "产值")
# 检核列:优先使用 AF 列(index 31),即"检核业务线"列 # 检核列 —— 优先使用 AF 列(索引 31)
# 原始需求:仅考虑 AF 列:检核=TRUE
col_check = None col_check = None
# 先尝试找"检核业务线"列 if len(df.columns) > 31:
col_check_af = find_column(df, "检核业务线") col_check = df.columns[31]
if col_check_af: logger.info(f"[人力成本] 检核列: 使用 AF 列 (索引 31), 列名='{col_check}'")
col_check = col_check_af else:
logger.info(f"[人力成本] 使用检核业务线列: {col_check}") logger.warning(f"[人力成本] 列数不足 32 列 ({len(df.columns)}), 回退到列名查找")
# 如果找不到,尝试 AF 列(index 31) col_check_af = find_column(df, "检核业务线")
if col_check is None and len(df.columns) > 31: if col_check_af:
col_check = df.columns[31] # AF 列(索引31) col_check = col_check_af
logger.info(f"[人力成本] 使用 AF 列作为检核列: {col_check}") if col_check is None:
# 最后回退到找"检核"列 col_check = find_column(df, "检核", "审核")
if col_check is None:
col_check = find_column(df, "检核", "审核") logger.info(f"[人力成本] 列匹配: 门店={col_store}, "
logger.info(f"[人力成本] 列匹配结果: 门店={col_store}, 园区店={col_park_store}, "
f"业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, " f"业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, "
f"检核={col_check}, GMV={col_gmv}") f"检核={col_check}")
# 用于直接匹配的流量方名称集合(已标准化)
std_flow_names_set = {to_standard(name, '4s') for name in flow_names_set}
# 建立 标准名 -> 原名 的映射
std_to_original_flow = {}
for name in flow_names_set:
std_name = to_standard(name, '4s')
if std_name not in std_to_original_flow:
std_to_original_flow[std_name] = name
total_rows = len(df)
check_passed = 0
check_skipped = 0
for _, row in df.iterrows(): for _, row in df.iterrows():
# 检核列必须为 True(兼容多种格式:True/TRUE/1/1.0/Y/YES) # 检核列筛选
if col_check: if col_check:
check_val = row[col_check] check_val = row[col_check]
if pd.isna(check_val): if pd.isna(check_val):
check_skipped += 1
continue continue
# 统一转为字符串判断
check_str = str(check_val).strip().upper() check_str = str(check_val).strip().upper()
if check_str not in ["TRUE", "1", "1.0", "Y", "YES"]: if check_str not in ["TRUE", "1", "1.0", "Y", "YES"]:
check_skipped += 1
continue continue
check_passed += 1
store_name = None store_name = None
if col_store: if col_store:
...@@ -1393,19 +1496,8 @@ class DataProcessor: ...@@ -1393,19 +1496,8 @@ class DataProcessor:
continue continue
store_name = str(store_name).strip() store_name = str(store_name).strip()
# 使用标准名映射
std_store_name = to_standard(store_name, '4s') std_store_name = to_standard(store_name, '4s')
# 获取园区店
park_store = ""
if col_park_store:
park_store_val = row[col_park_store]
if pd.notna(park_store_val) and str(park_store_val).strip() not in ["", "nan"]:
park_store = str(park_store_val).strip()
# 园区店也应用标准名映射
park_store = to_standard(park_store, 'yq')
# 获取业务类型 # 获取业务类型
biz_type = None biz_type = None
if col_biz: if col_biz:
...@@ -1426,141 +1518,186 @@ class DataProcessor: ...@@ -1426,141 +1518,186 @@ class DataProcessor:
salary = Decimal("0") salary = Decimal("0")
if col_salary: if col_salary:
salary = safe_decimal(row[col_salary]) salary = safe_decimal(row[col_salary])
if salary == 0: if salary == 0:
continue continue
# 获取 GMV(用于分摊) # 岗位分类
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 按业务类型和岗位分类
technician_salary = Decimal("0") technician_salary = Decimal("0")
marketing_salary = Decimal("0") marketing_salary = Decimal("0")
if biz_type == BIZ_TYPE_1_1: if biz_type == BIZ_TYPE_1_1:
# 1.1 业务:贴膜技师 → 技师工资;其他 → 营销团队工资
if position and "贴膜技师" in position: if position and "贴膜技师" in position:
technician_salary = salary technician_salary = salary
else: else:
marketing_salary = salary marketing_salary = salary
elif biz_type in [BIZ_TYPE_2_1, BIZ_TYPE_2_3]: elif biz_type in [BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
# 2.1/2.3 业务:全部 → 营销团队工资
marketing_salary = salary marketing_salary = salary
else: else:
marketing_salary = salary marketing_salary = salary
is_park_store = "园区" in store_name or "园区店" in store_name # ---------- 一级匹配:直接匹配 ----------
if std_store_name in std_flow_names_set:
raw_records.append({ # 直接匹配成功
"流量方名称": std_store_name, original_flow = std_to_original_flow.get(std_store_name, std_store_name)
"原始名称": store_name, raw_records.append({
"园区店": park_store, "流量方名称": original_flow,
"业务类型": biz_type or "未知", "业务类型": biz_type or "未知",
"技师工资": technician_salary, "技师工资": technician_salary,
"营销团队工资": marketing_salary, "营销团队工资": marketing_salary,
"gmv": gmv, "匹配方式": "direct",
"is_park_store": is_park_store, })
}) direct_match_count += 1
else:
if not raw_records: # ---------- 二级回退:园区店匹配 ----------
logger.info("[人力成本] 无有效数据") ps = to_standard(store_name, 'yq')
return [] if ps in park_to_flows:
related_flows = park_to_flows[ps]
# 按 (流量方名称, 业务类型) 汇总 logger.info(f"[园区店回退] 入驻门店='{store_name}' → park_store='{ps}', 命中{len(related_flows)}个流量方")
# 先汇总非园区店数据
direct_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0"), "gmv_sum": Decimal("0")}) matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
for r in raw_records: if matching_flows:
if r["is_park_store"]: # 先按 (ps, flow, biz) 精确取已入库 gmv_ratio_park,
continue # 对每个命中流量方使用其自身在园区店内的 GMV 占比分摊;
key = (r["流量方名称"], r["业务类型"]) # 未命中比例的流量方参与"剩余金额"均分,保证金额守恒。
direct_grouped[key]["技师工资"] += r["技师工资"] any_ratio_found = False
direct_grouped[key]["营销团队工资"] += r["营销团队工资"] allocated_tech = Decimal("0")
direct_grouped[key]["gmv_sum"] += r["gmv"] allocated_mkt = Decimal("0")
ratio_hit_flows = []
# 汇总园区店数据 for flow_name, flow_biz in matching_flows:
park_store_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")}) key_fine = (ps, flow_name, flow_biz)
for r in raw_records: r_val = park_to_ratio.get(key_fine)
if not r["is_park_store"]: if r_val is None:
continue r_val = park_to_ratio.get((flow_biz, ps))
# 园区店以 park_store 字段为主键 if r_val is None:
park_key = r["园区店"] or r["流量方名称"] r_val = park_to_ratio.get(ps)
key = (park_key, r["业务类型"]) if r_val is None:
park_store_grouped[key]["技师工资"] += r["技师工资"] continue
park_store_grouped[key]["营销团队工资"] += r["营销团队工资"] any_ratio_found = True
r = Decimal(str(r_val))
# 构建结果 - 一级匹配:直接匹配到门店 tech_share = round_2(technician_salary * r)
result = [] mkt_share = round_2(marketing_salary * r)
for (flow, biz), salaries in direct_grouped.items(): allocated_tech += tech_share
result.append({ allocated_mkt += mkt_share
"流量方名称": flow, ratio_hit_flows.append((flow_name, flow_biz, tech_share, mkt_share))
"业务类型": biz, logger.debug(f"[园区店回退] 流量方={flow_name}, 业务={flow_biz}, "
"技师工资": round_2(salaries["技师工资"]), f"gmv_ratio_park={r}, 技师工资={tech_share}, 营销团队={mkt_share}")
"营销团队工资": round_2(salaries["营销团队工资"]), # 先写入命中比例的流量方
}) for flow_name, flow_biz, tech_share, mkt_share in ratio_hit_flows:
raw_records.append({
# 二级匹配:园区店回退匹配 "流量方名称": flow_name,
# 检查 direct_grouped 中没有的流量方,尝试从 park_store_grouped 中按园区店匹配 "业务类型": flow_biz,
matched_park_stores = set() "技师工资": tech_share,
for (flow, biz), salaries in direct_grouped.items(): "营销团队工资": mkt_share,
# 查找该流量方是否关联某个园区店 "匹配方式": "park_ratio_db",
for (park_store_key, park_biz), park_salaries in park_store_grouped.items(): })
if park_biz == biz and park_store_key in flow: if any_ratio_found:
matched_park_stores.add((park_store_key, park_biz)) # 剩余流量方按剩余金额均分,保证总额守恒
missing_flows = [(fn, fb) for (fn, fb) in matching_flows
# 未直接匹配的流量方,使用园区店数据(按GMV分摊) if (fn, fb) not in {(x[0], x[1]) for x in ratio_hit_flows}]
for (park_store_key, biz), salaries in park_store_grouped.items(): if missing_flows:
if (park_store_key, biz) not in matched_park_stores: remain_tech = technician_salary - allocated_tech
# 查找使用该园区店的流量方 remain_mkt = marketing_salary - allocated_mkt
related_flows = [] n = len(missing_flows)
for (flow, flow_biz) in direct_grouped.keys(): for flow_name, flow_biz in missing_flows:
if flow_biz == biz and park_store_key in flow: tech_share = round_2(remain_tech / n)
related_flows.append(flow) mkt_share = round_2(remain_mkt / n)
raw_records.append({
if related_flows: "流量方名称": flow_name,
# 按流量方的GMV占比分摊园区店费用 "业务类型": flow_biz,
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped) "技师工资": tech_share,
for flow in related_flows: "营销团队工资": mkt_share,
if (flow, biz) in direct_grouped: "匹配方式": "park_ratio_db",
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"] })
if total_gmv > 0 and flow_gmv > 0: park_match_count += 1
ratio = flow_gmv / total_gmv park_allocated_total += allocated_tech + allocated_mkt
tech_share = salaries["技师工资"] * ratio logger.info(f"[园区店回退] park_ratio_db分摊成功: park_store='{ps}', "
mkt_share = salaries["营销团队工资"] * ratio f"命中{len(ratio_hit_flows)}个流量方, 技师工资分摊={allocated_tech}, "
else: f"营销团队分摊={allocated_mkt}")
# 无GMV信息,平均分摊 else:
n = len(related_flows) # 无比例信息,全部平均分摊
tech_share = salaries["技师工资"] / n n = len(matching_flows)
mkt_share = salaries["营销团队工资"] / n tech_share_each = technician_salary / n
mkt_share_each = marketing_salary / n
# 累加 avg_allocated_tech = Decimal("0")
for r in result: avg_allocated_mkt = Decimal("0")
if r["流量方名称"] == flow and r["业务类型"] == biz: for flow_name, flow_biz in matching_flows:
r["技师工资"] = round_2(r["技师工资"] + tech_share) t_share = round_2(tech_share_each)
r["营销团队工资"] = round_2(r["营销团队工资"] + mkt_share) m_share = round_2(mkt_share_each)
break avg_allocated_tech += t_share
else: avg_allocated_mkt += m_share
result.append({ raw_records.append({
"流量方名称": flow, "流量方名称": flow_name,
"业务类型": biz, "业务类型": flow_biz,
"技师工资": round_2(tech_share), "技师工资": t_share,
"营销团队工资": round_2(mkt_share), "营销团队工资": m_share,
"匹配方式": "park_avg",
}) })
park_match_count += 1
park_allocated_total += avg_allocated_tech + avg_allocated_mkt
logger.info(f"[园区店回退] park_avg平均分摊: park_store='{ps}', "
f"共{n}个流量方, 技师工资={avg_allocated_tech}, 营销团队={avg_allocated_mkt}")
else:
park_fail_count += 1
failed_count += 1
logger.warning(f"[园区店回退] park_store='{ps}' 无匹配业务类型={biz_type}的流量方, "
f"入驻门店='{store_name}'")
if len(failed_stores) < 10:
failed_stores.append(store_name)
else: else:
# 无关联流量方,直接输出园区店数据 # 匹配失败
result.append({ park_fail_count += 1
"流量方名称": park_store_key, failed_count += 1
"业务类型": biz, logger.warning(f"[园区店回退] 入驻门店='{store_name}' 归一化后 park_store='{ps}' "
"技师工资": round_2(salaries["技师工资"]), f"未命中任何园区店, 无法分摊")
"营销团队工资": round_2(salaries["营销团队工资"]), if len(failed_stores) < 10:
"__park_store__": True, failed_stores.append(store_name)
})
finally: finally:
# 清理临时解密文件
if is_decrypted and actual_path != file_path and os.path.exists(actual_path): if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
os.unlink(actual_path) os.unlink(actual_path)
logger.info("[人力成本] 已清理临时解密文件")
# 检核过滤统计日志
logger.info(f"[人力成本] 检核过滤: 总行数={total_rows}, 通过={check_passed}, 过滤掉={check_skipped}")
# 日志汇总
logger.info(f"[人力成本] 匹配统计: 直接匹配={direct_match_count}, "
f"园区店回退成功={park_match_count}, 园区店回退失败={park_fail_count}, "
f"总失败={failed_count}")
logger.info(f"[人力成本] 园区店回退分摊金额合计: {park_allocated_total}")
if failed_stores:
logger.warning(f"[人力成本] 匹配失败的门店(最多显示10个): {failed_stores}")
if not raw_records:
logger.info("[人力成本] 无有效数据")
return []
# 按 (流量方名称, 业务类型) 汇总
aggregated = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
for r in raw_records:
key = (r["流量方名称"], r["业务类型"])
aggregated[key]["技师工资"] += r["技师工资"]
aggregated[key]["营销团队工资"] += r["营销团队工资"]
result = []
for (flow, biz), salaries in aggregated.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
})
# 计算总量守恒
total_input = sum(
technician_salary + marketing_salary
for r in raw_records
for technician_salary, marketing_salary in [(r["技师工资"], r["营销团队工资"])]
)
total_output = sum(
r["技师工资"] + r["营销团队工资"]
for r in result
)
logger.info(f"[人力成本] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}")
logger.info(f"[人力成本] 解析完成,共 {len(result)} 条记录") logger.info(f"[人力成本] 解析完成,共 {len(result)} 条记录")
return result return result
...@@ -1569,7 +1706,7 @@ class DataProcessor: ...@@ -1569,7 +1706,7 @@ class DataProcessor:
# 解析房租水电施工费表 # 解析房租水电施工费表
# ======================================================== # ========================================================
def _parse_utility_fee(self, file_path): def _parse_utility_fee(self, file_path, settlement_map=None, park_ratio_map=None):
""" """
解析房租水电施工费表。 解析房租水电施工费表。
规则: 规则:
...@@ -1696,32 +1833,74 @@ class DataProcessor: ...@@ -1696,32 +1833,74 @@ class DataProcessor:
related_flows.append(flow) related_flows.append(flow)
if related_flows: if related_flows:
# 按流量方的GMV占比分摊园区店费用 # 尝试使用数据库比例
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped) db_ratio = None
for flow in related_flows: ratio_source = None
if (flow, biz) in direct_grouped: if settlement_map:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"] for flow in related_flows:
if total_gmv > 0 and flow_gmv > 0: for (fn, bt, br), sv in settlement_map.items():
ratio = flow_gmv / total_gmv if fn == flow and bt == biz and sv.get("gmv_ratio") is not None:
share = fee * ratio db_ratio = sv["gmv_ratio"]
else: ratio_source = "settlement"
# 无GMV信息,平均分摊
n = len(related_flows)
share = fee / n
# 累加
found = False
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["房租及水电费"] = round_2(r["房租及水电费"] + share)
found = True
break break
if not found: if db_ratio is not None:
result.append({ break
"流量方名称": flow,
"业务类型": biz, if db_ratio is None and park_ratio_map:
"房租及水电费": round_2(share), pr_key = (biz, park_flow)
}) if pr_key in park_ratio_map:
db_ratio = park_ratio_map[pr_key]
ratio_source = "park"
if db_ratio is not None:
if ratio_source == "settlement":
logger.info(f"[房租水电分摊] 流量方匹配成功,使用 gmv_ratio={db_ratio}")
else:
logger.info(f"[房租水电分摊] 流量方匹配失败,尝试园区店匹配,使用 gmv_ratio_park={db_ratio}")
for flow in related_flows:
if (flow, biz) in direct_grouped:
share = fee * db_ratio
found = False
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["房租及水电费"] = round_2(r["房租及水电费"] + share)
found = True
break
if not found:
result.append({
"流量方名称": flow,
"业务类型": biz,
"房租及水电费": round_2(share),
})
else:
logger.warning("[房租水电分摊] 比例缺失,降级为Excel计算")
# 按流量方的GMV占比分摊园区店费用
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
for flow in related_flows:
if (flow, biz) in direct_grouped:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
if total_gmv > 0 and flow_gmv > 0:
ratio = flow_gmv / total_gmv
share = fee * ratio
else:
# 无GMV信息,平均分摊
n = len(related_flows)
share = fee / n
# 累加
found = False
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["房租及水电费"] = round_2(r["房租及水电费"] + share)
found = True
break
if not found:
result.append({
"流量方名称": flow,
"业务类型": biz,
"房租及水电费": round_2(share),
})
else: else:
# 无关联流量方,直接输出园区店数据 # 无关联流量方,直接输出园区店数据
result.append({ result.append({
...@@ -1738,7 +1917,7 @@ class DataProcessor: ...@@ -1738,7 +1917,7 @@ class DataProcessor:
# 构建成本汇总表 # 构建成本汇总表
# ======================================================== # ========================================================
def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data=None): def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data=None, settlement_map=None, park_ratio_map=None):
""" """
生成成本汇总表。 生成成本汇总表。
综合结算数据、市场费、外援施工费、人力成本、房租水电施工费, 综合结算数据、市场费、外援施工费、人力成本、房租水电施工费,
...@@ -1750,11 +1929,11 @@ class DataProcessor: ...@@ -1750,11 +1929,11 @@ class DataProcessor:
# ---------- 收集 GMV 和产值数据 ---------- # ---------- 收集 GMV 和产值数据 ----------
# 从结算数据构建 GMV 和产值映射 # 从结算数据构建 GMV 和产值映射
settlement_map = {} # (流量方, 业务类型, 品牌) -> {GMV, 产值, 服务费, 嘀加分润, 服务商, 装修摊销, 门店耗材} gmv_lookup = {} # (流量方, 业务类型, 品牌) -> {GMV, 产值, 服务费, 嘀加分润, 服务商, 装修摊销, 门店耗材}
if settlement_data: if settlement_data:
for s in settlement_data: for s in settlement_data:
key = (s["流量方名称"], s["业务类型"], s["品牌"] or "") key = (s["流量方名称"], s["业务类型"], s["品牌"] or "")
settlement_map[key] = { gmv_lookup[key] = {
"GMV": s["GMV"], "GMV": s["GMV"],
"产值": s["产值"], "产值": s["产值"],
"服务费": s.get("服务费", Decimal("0")), "服务费": s.get("服务费", Decimal("0")),
...@@ -1762,6 +1941,9 @@ class DataProcessor: ...@@ -1762,6 +1941,9 @@ class DataProcessor:
"服务商": s.get("服务商", ""), "服务商": s.get("服务商", ""),
"装修摊销": s.get("装修摊销", Decimal("0")), "装修摊销": s.get("装修摊销", Decimal("0")),
"门店耗材": s.get("门店耗材", Decimal("0")), "门店耗材": s.get("门店耗材", Decimal("0")),
"gmv_ratio": s.get("gmv_ratio"),
"gmv_ratio_park": s.get("gmv_ratio_park"),
"park_store": s.get("park_store", ""),
} }
# 如果没有结算数据,从市场费结果中收集流量方信息用于占位 # 如果没有结算数据,从市场费结果中收集流量方信息用于占位
...@@ -1769,8 +1951,8 @@ class DataProcessor: ...@@ -1769,8 +1951,8 @@ class DataProcessor:
logger.warning("[成本汇总] 无结算数据,使用占位值") logger.warning("[成本汇总] 无结算数据,使用占位值")
for m in market_results: for m in market_results:
key = (m["流量方名称"], m["业务类型"], m["品牌"] or "") key = (m["流量方名称"], m["业务类型"], m["品牌"] or "")
if key not in settlement_map: if key not in gmv_lookup:
settlement_map[key] = { gmv_lookup[key] = {
"GMV": Decimal("0"), "GMV": Decimal("0"),
"产值": Decimal("0"), "产值": Decimal("0"),
} }
...@@ -1787,10 +1969,8 @@ class DataProcessor: ...@@ -1787,10 +1969,8 @@ class DataProcessor:
for r in wage_results: for r in wage_results:
all_keys.add((r["流量方名称"], r["业务类型"], "")) all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 人力成本(非园区店) # 人力成本
for r in labor_results: for r in labor_results:
if r.get("__park_store__"):
continue
all_keys.add((r["流量方名称"], r["业务类型"], "")) all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 房租水电(非园区店) # 房租水电(非园区店)
...@@ -1800,9 +1980,35 @@ class DataProcessor: ...@@ -1800,9 +1980,35 @@ class DataProcessor:
all_keys.add((r["流量方名称"], r["业务类型"], "")) all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 结算数据中的所有键 # 结算数据中的所有键
for key in settlement_map.keys(): for key in gmv_lookup.keys():
all_keys.add(key) all_keys.add(key)
# ---------- 预先按 (流量方, 业务类型) 聚合无品牌的费用 ----------
labor_agg = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
for l in labor_results:
key = (l["流量方名称"].strip(), l["业务类型"].strip())
labor_agg[key]["技师工资"] += l["技师工资"]
labor_agg[key]["营销团队工资"] += l["营销团队工资"]
# 人力成本聚合日志
if labor_agg:
labor_total_tech = sum(v["技师工资"] for v in labor_agg.values())
labor_total_mkt = sum(v["营销团队工资"] for v in labor_agg.values())
logger.info(f"[成本汇总] 人力成本聚合: {len(labor_agg)} 个(流量方,业务类型)键, "
f"技师工资合计={labor_total_tech}, 营销团队工资合计={labor_total_mkt}")
wage_agg = defaultdict(lambda: Decimal("0"))
for w in wage_results:
key = (w["流量方名称"].strip(), w["业务类型"].strip())
wage_agg[key] += w["外援施工费"]
utility_agg = defaultdict(lambda: Decimal("0"))
for u in utility_results:
if u.get("__park_store__"):
continue
key = (u["流量方名称"].strip(), u["业务类型"].strip())
utility_agg[key] += u["房租及水电费"]
# ---------- 按键汇总各项费用 ---------- # ---------- 按键汇总各项费用 ----------
summary = [] summary = []
...@@ -1814,25 +2020,25 @@ class DataProcessor: ...@@ -1814,25 +2020,25 @@ class DataProcessor:
# 获取 GMV 和产值 # 获取 GMV 和产值
settle_key = (flow_name, biz_type, brand) settle_key = (flow_name, biz_type, brand)
if settle_key in settlement_map: if settle_key in gmv_lookup:
gmv = settlement_map[settle_key]["GMV"] gmv = gmv_lookup[settle_key]["GMV"]
revenue = settlement_map[settle_key]["产值"] revenue = gmv_lookup[settle_key]["产值"]
service_fee = settlement_map[settle_key].get("服务费", Decimal("0")) service_fee = gmv_lookup[settle_key].get("服务费", Decimal("0"))
dijia_profit = settlement_map[settle_key].get("嘀加分润", Decimal("0")) dijia_profit = gmv_lookup[settle_key].get("嘀加分润", Decimal("0"))
service_provider = (settlement_map[settle_key].get("服务商", "") or "").strip() service_provider = (gmv_lookup[settle_key].get("服务商", "") or "").strip()
renovation = settlement_map[settle_key].get("装修摊销", Decimal("0")) renovation = gmv_lookup[settle_key].get("装修摊销", Decimal("0"))
consumables = settlement_map[settle_key].get("门店耗材", Decimal("0")) consumables = gmv_lookup[settle_key].get("门店耗材", Decimal("0"))
else: else:
# 尝试无品牌匹配 # 尝试无品牌匹配
settle_key_no_brand = (flow_name, biz_type, "") settle_key_no_brand = (flow_name, biz_type, "")
if settle_key_no_brand in settlement_map: if settle_key_no_brand in gmv_lookup:
gmv = settlement_map[settle_key_no_brand]["GMV"] gmv = gmv_lookup[settle_key_no_brand]["GMV"]
revenue = settlement_map[settle_key_no_brand]["产值"] revenue = gmv_lookup[settle_key_no_brand]["产值"]
service_fee = settlement_map[settle_key_no_brand].get("服务费", Decimal("0")) service_fee = gmv_lookup[settle_key_no_brand].get("服务费", Decimal("0"))
dijia_profit = settlement_map[settle_key_no_brand].get("嘀加分润", Decimal("0")) dijia_profit = gmv_lookup[settle_key_no_brand].get("嘀加分润", Decimal("0"))
service_provider = (settlement_map[settle_key_no_brand].get("服务商", "") or "").strip() service_provider = (gmv_lookup[settle_key_no_brand].get("服务商", "") or "").strip()
renovation = settlement_map[settle_key_no_brand].get("装修摊销", Decimal("0")) renovation = gmv_lookup[settle_key_no_brand].get("装修摊销", Decimal("0"))
consumables = settlement_map[settle_key_no_brand].get("门店耗材", Decimal("0")) consumables = gmv_lookup[settle_key_no_brand].get("门店耗材", Decimal("0"))
else: else:
gmv = Decimal("0") gmv = Decimal("0")
revenue = Decimal("0") revenue = Decimal("0")
...@@ -1869,25 +2075,64 @@ class DataProcessor: ...@@ -1869,25 +2075,64 @@ class DataProcessor:
and (m_brand == brand or not brand or not m_brand)): and (m_brand == brand or not brand or not m_brand)):
row["市场费"] += m["市场费"] row["市场费"] += m["市场费"]
# --- 匹配外援施工费 --- # 同一 (流量方, 业务类型) 下所有品牌的 GMV 合计
for w in wage_results: same_flow_biz_gmv = Decimal("0")
if w["流量方名称"] == flow_name and w["业务类型"] == biz_type: brand_count = 0
row["外援施工"] += w["外援施工费"] for s_key in gmv_lookup:
if s_key[0] == flow_name and s_key[1] == biz_type:
# --- 匹配人力成本 --- same_flow_biz_gmv += gmv_lookup[s_key]["GMV"]
for l in labor_results: brand_count += 1
if l.get("__park_store__"):
continue if brand_count > 1:
if l["流量方名称"] == flow_name and l["业务类型"] == biz_type: logger.info(f"[成本汇总] 多品牌分摊: 流量方={flow_name}, 业务类型={biz_type}, 品牌数={brand_count}, GMV合计={same_flow_biz_gmv}, 本品牌GMV={gmv}")
row["技师工资"] += l["技师工资"]
row["营销团队工资"] += l["营销团队工资"] # 计算本品牌的分摊比例 —— 优先使用已入库 gmv_ratio
flow_biz_ratio = Decimal("1")
# --- 匹配房租水电 --- ratio_source = "gmv_calc" # 记录比例来源
for u in utility_results: db_ratio = gmv_lookup[settle_key].get("gmv_ratio") if settle_key in gmv_lookup else None
if u.get("__park_store__"): if db_ratio is None:
continue # 尝试无品牌版本
if u["流量方名称"] == flow_name and u["业务类型"] == biz_type: nk = (flow_name, biz_type, "")
row["房租及水电费"] += u["房租及水电费"] if nk in gmv_lookup:
db_ratio = gmv_lookup[nk].get("gmv_ratio")
if db_ratio is not None:
flow_biz_ratio = Decimal(str(float(db_ratio)))
ratio_source = "db_gmv_ratio"
logger.debug(f"[比例来源] 使用数据库 gmv_ratio={flow_biz_ratio} (流量方={flow_name}, 业务={biz_type}, 品牌={brand})")
elif same_flow_biz_gmv > 0 and gmv > 0:
flow_biz_ratio = gmv / same_flow_biz_gmv
ratio_source = "gmv_calc"
logger.debug(f"[比例来源] 回退 GMV 计算分摊 ratio={flow_biz_ratio} (流量方={flow_name}, 业务={biz_type}, 品牌={brand})")
# --- 外援施工费(按 GMV 占比分摊)---
wage_key = (flow_name, biz_type)
if wage_key in wage_agg:
row["外援施工"] += round_2(wage_agg[wage_key] * flow_biz_ratio)
# --- 人力成本(单品牌全额,多品牌按 GMV 占比分摊)---
labor_key = (flow_name, biz_type)
if labor_key in labor_agg:
if brand_count <= 1:
# 单品牌:全额分配,不分摊
row["技师工资"] += labor_agg[labor_key]["技师工资"]
row["营销团队工资"] += labor_agg[labor_key]["营销团队工资"]
logger.debug(f"[人力成本分配] 单品牌全额: 流量方={flow_name}, 业务={biz_type}, "
f"品牌={brand}, 技师工资={labor_agg[labor_key]['技师工资']}, "
f"营销团队={labor_agg[labor_key]['营销团队工资']}")
else:
# 多品牌:按 GMV 占比分摊
tech_share = round_2(labor_agg[labor_key]["技师工资"] * flow_biz_ratio)
mkt_share = round_2(labor_agg[labor_key]["营销团队工资"] * flow_biz_ratio)
row["技师工资"] += tech_share
row["营销团队工资"] += mkt_share
logger.debug(f"[人力成本分配] 多品牌分摊: 流量方={flow_name}, 业务={biz_type}, "
f"品牌={brand}, 分摊比例={flow_biz_ratio}, "
f"技师工资分摊={tech_share}, 营销团队分摊={mkt_share}")
# --- 房租水电(按 GMV 占比分摊)---
utility_key = (flow_name, biz_type)
if utility_key in utility_agg:
row["房租及水电费"] += round_2(utility_agg[utility_key] * flow_biz_ratio)
# 计算人员工资小计 # 计算人员工资小计
row["人员工资"] = row["技师工资"] + row["营销团队工资"] row["人员工资"] = row["技师工资"] + row["营销团队工资"]
...@@ -1966,56 +2211,53 @@ class DataProcessor: ...@@ -1966,56 +2211,53 @@ class DataProcessor:
logger.info(f"[毛利计算] 服务商类型汇总: {_seen_sp}") logger.info(f"[毛利计算] 服务商类型汇总: {_seen_sp}")
# ---------- 处理园区店 GMV 分摊 ---------- # ---------- 处理园区店 GMV 分摊 ----------
park_labor = [r for r in labor_results if r.get("__park_store__")]
park_utility = [r for r in utility_results if r.get("__park_store__")] park_utility = [r for r in utility_results if r.get("__park_store__")]
if park_labor or park_utility: if park_utility:
logger.info(f"[成本汇总] 处理园区店分摊:人力成本 {len(park_labor)} 条,房租水电 {len(park_utility)} 条") logger.info(f"[成本汇总] 处理园区店分摊:房租水电 {len(park_utility)} 条")
# 收集各流量方 GMV(用于分摊) # 按业务类型聚合园区店费用
flow_gmv = {} park_utility_agg = defaultdict(lambda: Decimal("0"))
for s in summary: for p in park_utility:
key = (s["流量方名称"], s["业务类型"]) key = p["业务类型"].strip()
flow_gmv[key] = s["GMV"] park_utility_agg[key] += p["房租及水电费"]
# 分摊人力成本中的园区店费用 # 计算每个业务类型的总 GMV(跨所有流量方和品牌)
for park_item in park_labor: biz_total_gmv = defaultdict(lambda: Decimal("0"))
biz = park_item["业务类型"] biz_brand_count = defaultdict(int)
tech_fee = park_item["技师工资"] for s in summary:
marketing_fee = park_item["营销团队工资"] biz_total_gmv[s["业务类型"]] += s["GMV"]
if s["品牌"]:
candidates = [s for s in summary if s["业务类型"] == biz] biz_brand_count[s["业务类型"]] += 1
if not candidates:
continue
cand_gmv = {c["流量方名称"]: c["GMV"] for c in candidates}
total_cand_gmv = sum(cand_gmv.values())
if total_cand_gmv == 0:
continue
for c in candidates: for biz, count in biz_brand_count.items():
ratio = c["GMV"] / total_cand_gmv if total_cand_gmv > 0 else Decimal("0") if count > 1:
c["技师工资"] += round_2(tech_fee * ratio) logger.info(f"[成本汇总] 园区店多品牌分摊: 业务类型={biz}, 品牌数={count}, GMV合计={biz_total_gmv[biz]}")
c["营销团队工资"] += round_2(marketing_fee * ratio)
c["人员工资"] = c["技师工资"] + c["营销团队工资"]
# 分摊房租水电中的园区店费用 # 分摊到各品牌行(按 GMV 占比,跨流量方)
for park_item in park_utility: for s in summary:
biz = park_item["业务类型"] biz = s["业务类型"]
util_fee = park_item["房租及水电费"] gmv = s["GMV"]
candidates = [s for s in summary if s["业务类型"] == biz] # 优先使用数据库中的 gmv_ratio
if not candidates: db_ratio = None
continue if settlement_map:
for (fn, bt, br), sv in settlement_map.items():
if fn == s["流量方名称"] and bt == biz and sv.get("gmv_ratio") is not None:
db_ratio = sv["gmv_ratio"]
break
cand_gmv = {c["流量方名称"]: c["GMV"] for c in candidates} brand_ratio = Decimal("0")
total_cand_gmv = sum(cand_gmv.values()) if db_ratio is not None:
if total_cand_gmv == 0: brand_ratio = Decimal(str(db_ratio))
continue logger.info(f"[成本汇总分摊] 使用数据库比例 流量方={s['流量方名称']} gmv_ratio={db_ratio}")
elif biz_total_gmv[biz] > 0 and gmv > 0:
brand_ratio = gmv / biz_total_gmv[biz]
else:
logger.warning(f"[成本汇总分摊] 比例缺失且无GMV数据,流量方={s['流量方名称']}")
for c in candidates: if biz in park_utility_agg:
ratio = c["GMV"] / total_cand_gmv if total_cand_gmv > 0 else Decimal("0") s["房租及水电费"] += round_2(park_utility_agg[biz] * brand_ratio)
c["房租及水电费"] += round_2(util_fee * ratio)
# 重新计算占比和毛利(使用与主循环一致的公式) # 重新计算占比和毛利(使用与主循环一致的公式)
for s in summary: for s in summary:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!