Commit 31f35605 by zhouhaibao

fix(data-process): 更新装修摊销逻辑中的服务商过滤条件

- 在查询结果中新增 service_provider 字段用于服务商筛选
- 将服务商过滤条件从"深圳嘀加"改为"嘀加"以匹配实际数据库值
- 更新日志输出中的服务商名称显示
- 修正装修摊销和耗材分摊中的服务商过滤逻辑
- 添加服务商过滤说明注释(嘀加自营/嘀加直营)
1 parent ce59bee5
...@@ -324,10 +324,10 @@ def query_task_biz_rows(conn, task_id, stat_month, business_type): ...@@ -324,10 +324,10 @@ def query_task_biz_rows(conn, task_id, stat_month, business_type):
"""查询本任务下指定业务类型的预算达成结果行(用于装修摊销的 GMV 占比分摊)。 """查询本任务下指定业务类型的预算达成结果行(用于装修摊销的 GMV 占比分摊)。
Returns: Returns:
list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park} list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, service_provider}
""" """
sql = ( sql = (
'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park ' 'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, service_provider '
'FROM biz_budget_achieve ' 'FROM biz_budget_achieve '
'WHERE task_id = %s AND stat_month = %s AND business_type = %s' 'WHERE task_id = %s AND stat_month = %s AND business_type = %s'
) )
...@@ -436,14 +436,14 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -436,14 +436,14 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
if total == 0: if total == 0:
continue continue
rows = row_map[key] rows = row_map[key]
# --- 服务商过滤:只保留 service_provider 含"深圳嘀加"的行 --- # --- 服务商过滤:只保留 service_provider 含"嘀加"的行(嘀加自营/嘀加直营) ---
dijia_rows = [r for r in rows if _is_dijia_row(r)] dijia_rows = [r for r in rows if _is_dijia_row(r)]
if not dijia_rows: if not dijia_rows:
# 全是非嘀加 → 不分摊(费用=0),跳过 # 全是非嘀加 → 不分摊(费用=0),跳过
continue continue
if len(dijia_rows) < len(rows): if len(dijia_rows) < len(rows):
logger.info(f"[装修分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行" logger.info(f"[装修摊销] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
f" 服务商=深圳嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行") f" 服务商=嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
rows = dijia_rows rows = dijia_rows
if field == 'mgv_ratio_park': if field == 'mgv_ratio_park':
...@@ -662,15 +662,13 @@ def query_all_biz_rows(conn, task_id, stat_month): ...@@ -662,15 +662,13 @@ def query_all_biz_rows(conn, task_id, stat_month):
return cur.fetchall() return cur.fetchall()
_DIJIA_SPIDER = '%深圳嘀加%' # 匹配服务商含"深圳嘀加"的行 _DIJIA_SPIDER = '%嘀加%' # 匹配服务商含"嘀加"的行(DB 实际值:嘀加自营/嘀加直营)
def _is_dijia_row(row): def _is_dijia_row(row):
"""判断 biz_budget_achieve 行的 service_provider 是否含"深圳嘀加"。 """判断 biz_budget_achieve 行的 service_provider 是否含"嘀加"(嘀加自营/嘀加直营)。"""
row 可以是 dict(query_all_biz_rows 返回)或 sqlalchemy Row / pymysql dict。
"""
sp = (row.get('service_provider') or row.get('serviceProvider') or '').strip() sp = (row.get('service_provider') or row.get('serviceProvider') or '').strip()
return '深圳嘀加' in sp return '嘀加' in sp
def compute_consumables_amounts(detail_rows, biz_rows, stat_month): def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
...@@ -772,14 +770,14 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month): ...@@ -772,14 +770,14 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
if total == 0: if total == 0:
continue # 净额为 0 才跳过;净负池同样分配成负摊消(冲减) continue # 净额为 0 才跳过;净负池同样分配成负摊消(冲减)
rows = row_map[key] rows = row_map[key]
# --- 服务商过滤:只保留 service_provider 含"深圳嘀加"的行 --- # --- 服务商过滤:只保留 service_provider 含"嘀加"的行(嘀加自营/嘀加直营) ---
dijia_rows = [r for r in rows if _is_dijia_row(r)] dijia_rows = [r for r in rows if _is_dijia_row(r)]
if not dijia_rows: if not dijia_rows:
# 全是非嘀加 → 不分摊(费用=0),跳过 # 全是非嘀加 → 不分摊(费用=0),跳过
continue continue
if len(dijia_rows) < len(rows): if len(dijia_rows) < len(rows):
logger.info(f"[耗材分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行" logger.info(f"[耗材分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
f" 服务商=深圳嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行") f" 服务商=嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
rows = dijia_rows rows = dijia_rows
if field == 'mgv_ratio_park': if field == 'mgv_ratio_park':
......
...@@ -371,14 +371,14 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names ...@@ -371,14 +371,14 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names
business_type: 业务类型(如 "1.1" / "2.1" / "2.3") business_type: 业务类型(如 "1.1" / "2.1" / "2.3")
flow_names: 流量方标准名列表(可选) flow_names: 流量方标准名列表(可选)
park_names: 园区店标准名列表(可选) park_names: 园区店标准名列表(可选)
only_dijia: True=只累计服务商含"深圳嘀加"的行(默认 True,GMV 分摊口径) only_dijia: True=只累计服务商含"嘀加"的行(默认 True,GMV 分摊口径)
Returns: Returns:
dict: {name(str): gmv(float)},键为流量方或园区店名称 dict: {name(str): gmv(float)},键为流量方或园区店名称
""" """
from sqlalchemy import text, bindparam from sqlalchemy import text, bindparam
result = {} result = {}
sp_clause = "AND service_provider LIKE '%深圳嘀加%'" if only_dijia else "" sp_clause = "AND service_provider LIKE '%嘀加%'" if only_dijia else ""
if flow_names: if flow_names:
sql = text(f""" sql = text(f"""
...@@ -439,7 +439,7 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data, only_dijia=True): ...@@ -439,7 +439,7 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data, only_dijia=True):
total_fee: 总金额(Decimal) total_fee: 总金额(Decimal)
targets: 分摊对象列表 [{'name': str, 'type': 'flow'|'park', ...}, ...] targets: 分摊对象列表 [{'name': str, 'type': 'flow'|'park', ...}, ...]
gmv_data: {name(str): gmv(float)},来自 query_gmv_by_targets 的结果 gmv_data: {name(str): gmv(float)},来自 query_gmv_by_targets 的结果
only_dijia: True=gmv_data 已过滤非深圳嘀加;若 total_gmv=0 则直接返回 [](费用=0) only_dijia: True=gmv_data 已过滤非嘀加;若 total_gmv=0 则直接返回 [](费用=0)
False=gmv_data 可能含非嘀加;total_gmv=0 时回退平均分配(原行为) False=gmv_data 可能含非嘀加;total_gmv=0 时回退平均分配(原行为)
Returns: Returns:
...@@ -1503,6 +1503,46 @@ class DataProcessor: ...@@ -1503,6 +1503,46 @@ class DataProcessor:
logger.info(f"[处理任务] 已更新 {len(files)} 个文件状态为清洗中") logger.info(f"[处理任务] 已更新 {len(files)} 个文件状态为清洗中")
logger.info(f"[处理任务] 步骤 a 完成, 耗时: {time.time() - step_a_start:.2f}s") logger.info(f"[处理任务] 步骤 a 完成, 耗时: {time.time() - step_a_start:.2f}s")
# ========== 步骤 a-2: 重置所有待分配费用字段为 0 ==========
reset_start = time.time()
logger.info("[处理任务] 步骤 a-2: 重置费用字段...")
try:
import pymysql as _pymysql
_uri = Config.SQLALCHEMY_DATABASE_URI or ''
logger.info(f"[诊断] processor DB URI = {_uri}")
_host = Config.MYSQL_HOST
_port = int(Config.MYSQL_PORT or 3306)
_user = Config.MYSQL_USER
_pwd = Config.MYSQL_PASSWORD
_db = Config.MYSQL_DB
logger.info(f"[诊断] 连接 {_user}@{_host}:{_port}/{_db}")
_conn = _pymysql.connect(host=_host, port=_port, user=_user,
password=_pwd, db=_db, charset='utf8mb4', autocommit=True)
_cur = _conn.cursor()
# reset 前诊断
_cur.execute("SELECT SUM(marketing_team_salary), SUM(technician_salary) FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task.id, task.month))
_before = _cur.fetchone()
logger.info(f"[诊断] reset 参数: task.id={task.id!r}, task.month={task.month!r}")
logger.info(f"[诊断] reset 前: mkt={float(_before[0] or 0):.2f}, tech={float(_before[1] or 0):.2f}")
# 执行 reset
_cur.execute("""
UPDATE biz_budget_achieve
SET market_fee = 0, external_construction = 0,
technician_salary = 0, marketing_team_salary = 0,
rent_utilities = 0, renovation_amortization = 0, store_consumables = 0,
updated_at = CURRENT_TIMESTAMP
WHERE task_id = %s AND stat_month = %s
""", (task.id, task.month))
logger.info(f"[处理任务] 步骤 a-2 reset 影响行数: {_cur.rowcount}")
# reset 后诊断
_cur.execute("SELECT SUM(marketing_team_salary), SUM(technician_salary) FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task.id, task.month))
_after = _cur.fetchone()
logger.info(f"[诊断] reset 后: mkt={float(_after[0] or 0):.2f}, tech={float(_after[1] or 0):.2f}")
_conn.close()
logger.info(f"[处理任务] 步骤 a-2 完成, 耗时 {time.time() - reset_start:.2f}s")
except Exception as reset_err:
logger.error(f"[处理任务] 步骤 a-2 重置失败: {reset_err}")
try: try:
# ========== 步骤 b: 下载所有关联文件到本地临时目录 ========== # ========== 步骤 b: 下载所有关联文件到本地临时目录 ==========
logger.info("[处理任务] 步骤 b: 下载文件到本地临时目录...") logger.info("[处理任务] 步骤 b: 下载文件到本地临时目录...")
...@@ -1604,9 +1644,11 @@ class DataProcessor: ...@@ -1604,9 +1644,11 @@ class DataProcessor:
labor_results, unmatched_labor = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id, stat_month=task.month, db=db) labor_results, unmatched_labor = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id, stat_month=task.month, db=db)
logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 个key") logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 个key")
# 按主键id更新 # 按主键id更新
labor_total_input, labor_total_output, labor_updated = self._update_labor_cost_by_id( labor_total_input, labor_total_output, labor_updated, labor_skipped = self._update_labor_cost_by_id(
task.id, task.month, labor_results task.id, task.month, labor_results
) )
# 写库 skip 的钱暂存(稍后合并进 unmatched_collector)
logger.info(f"[处理任务] 人力成本写库 skip: {labor_skipped}")
logger.info(f"[处理任务] 人力成本更新完成: 输入={labor_total_input}, 输出={labor_total_output}, 更新{labor_updated}行") logger.info(f"[处理任务] 人力成本更新完成: 输入={labor_total_input}, 输出={labor_total_output}, 更新{labor_updated}行")
# 解析房租水电施工费 # 解析房租水电施工费
...@@ -1616,46 +1658,23 @@ class DataProcessor: ...@@ -1616,46 +1658,23 @@ class DataProcessor:
if '房租水电费用表' in downloaded_files: if '房租水电费用表' in downloaded_files:
utility_results, gmv_allocated_utility, unmatched_utility = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id) utility_results, gmv_allocated_utility, unmatched_utility = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id)
logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条") logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条")
logger.info(f"[处理任务] 房租水电 unmatched_utility={unmatched_utility}")
else:
logger.warning(f"[处理任务] downloaded_files 里无 '房租水电费用表',available={list(downloaded_files.keys())}")
# 收集所有未匹配金额 + 写入 biz_unmatched_fee(幂等:先删后插) # 收集所有未匹配金额(先不写库,等所有 update 完后统一写 —— 因为 _update_utility_fee_to_db 可能返回 failed_amount 需补进 unmatched)
unmatched_collector = {**unmatched_market, **unmatched_external, **unmatched_labor, **unmatched_utility} unmatched_collector = {**unmatched_market, **unmatched_external, **unmatched_labor, **unmatched_utility}
logger.info(f"[未匹配收集] processor 侧: {unmatched_collector}") # 合并 labor_cost 写库 skip 金额(因无 DB 行丢失的钱 → 归入 unmatched)
# --- 写库 biz_unmatched_fee ---
# 注意:clean_budget_achievement(装修摊销+门店耗材)已在前置步骤写了自己的 fee_type,
# 这里只 DELETE + INSERT 本侧 5 个 fee_type,避免互相覆盖
PROCESSOR_FEE_TYPES = ['market_fee', 'external_construction',
'technician_salary', 'marketing_team_salary', 'rent_utilities']
try: try:
# 先删本侧 5 个 fee_type 的旧记录(保留 clean 侧的 renovation/consumables) if labor_skipped:
BizUnmatchedFee.query.filter( for col, amt in labor_skipped.items():
BizUnmatchedFee.task_id == task.id, if amt > 0:
BizUnmatchedFee.stat_month == task.month, unmatched_collector[col] = unmatched_collector.get(col, Decimal("0")) + amt
BizUnmatchedFee.fee_type.in_(PROCESSOR_FEE_TYPES), logger.info(f"[未匹配收集] 合并 labor_skipped 后: {unmatched_collector}")
).delete(synchronize_session='fetch') except NameError:
db.session.flush() pass # 没有人力成本统计表 → labor_skipped 未定义,跳过
# 只写有未匹配金额的 fee_type(unmatched_amount != 0) logger.info(f"[未匹配收集] processor 侧(初步): {unmatched_collector}")
inserted = 0 # 【写库延后到所有 update 之后统一执行 —— 见 L1725+】
for fee_type, amount in unmatched_collector.items():
if fee_type not in PROCESSOR_FEE_TYPES:
continue # 保护:跳过 clean 侧的 fee_type
amt = Decimal(str(amount)) if amount is not None else Decimal('0')
if amt == 0:
continue
db.session.add(BizUnmatchedFee(
task_id=task.id, stat_month=task.month,
fee_type=fee_type, unmatched_amount=amt,
))
inserted += 1
if inserted > 0:
db.session.commit()
logger.info(f"[未匹配写库] processor 侧: task={task.id} month={task.month} 写入 {inserted} 条(market/wage/labor/utility)")
else:
db.session.commit() # 即使没 INSERT 也要提交 DELETE
logger.info(f"[未匹配写库] processor 侧: 全部 matched, 仅清理旧记录 (task={task.id})")
except Exception as e_unm:
logger.error(f"[未匹配写库] 失败: {e_unm}", e_unm)
db.session.rollback()
logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s") logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")
# ========== 步骤 d: 执行成本计算 ========== # ========== 步骤 d: 执行成本计算 ==========
...@@ -1665,7 +1684,7 @@ class DataProcessor: ...@@ -1665,7 +1684,7 @@ class DataProcessor:
# 外援施工费:直接按 gmv_ratio 分摊 + 按主键id更新 # 外援施工费:直接按 gmv_ratio 分摊 + 按主键id更新
if wage_results: if wage_results:
logger.info(f"[处理任务] 外援施工费解析结果: {len(wage_results)} 个key, 开始按主键id分摊更新") logger.info(f"[处理任务] 外援施工费解析结果: {len(wage_results)} 个key, 开始按主键id分摊更新")
wage_total_input, wage_total_output, wage_updated = self._update_wage_fee_by_id( wage_total_input, wage_total_output, wage_updated, _ = self._update_wage_fee_by_id(
task.id, task.month, wage_results task.id, task.month, wage_results
) )
logger.info(f"[处理任务] 外援施工费更新完成: 输入={wage_total_input}, 输出={wage_total_output}, 更新{wage_updated}行") logger.info(f"[处理任务] 外援施工费更新完成: 输入={wage_total_input}, 输出={wage_total_output}, 更新{wage_updated}行")
...@@ -1699,7 +1718,12 @@ class DataProcessor: ...@@ -1699,7 +1718,12 @@ class DataProcessor:
if market_fee_data: if market_fee_data:
self._update_market_fee_by_id(task.id, task.month, market_fee_data) self._update_market_fee_by_id(task.id, task.month, market_fee_data)
if all_utility_data: if all_utility_data:
self._update_utility_fee_to_db(task.id, task.month, all_utility_data) _, failed_amount = self._update_utility_fee_to_db(task.id, task.month, all_utility_data)
# 写库失败的金额 → 合并进 unmatched_collector(稍后统一写库)
if failed_amount > 0:
cur_rent = Decimal(str(unmatched_collector.get('rent_utilities', 0) or 0))
unmatched_collector['rent_utilities'] = cur_rent + failed_amount
logger.info(f"[未匹配补录] 房租水电写库失败合并到 unmatched_collector: failed_amount={failed_amount}, rent_utilities now={unmatched_collector['rent_utilities']}")
# 人员工资汇总值和占比更新(按主键ID直接更新,在所有金额数据落库后执行) # 人员工资汇总值和占比更新(按主键ID直接更新,在所有金额数据落库后执行)
self._update_labor_ratios_by_id(task.id, task.month) self._update_labor_ratios_by_id(task.id, task.month)
...@@ -1709,6 +1733,36 @@ class DataProcessor: ...@@ -1709,6 +1733,36 @@ class DataProcessor:
logger.info(f"[处理任务] 步骤 e 完成, 耗时: {time.time() - step_e_start:.2f}s") logger.info(f"[处理任务] 步骤 e 完成, 耗时: {time.time() - step_e_start:.2f}s")
# ========== 步骤 e-2: 统一写库 biz_unmatched_fee(先删后插) ==========
# 所有 update 执行完毕后,把 unmatched_collector 一次性写入,避免顺序问题
PROCESSOR_FEE_TYPES = ['market_fee', 'external_construction',
'technician_salary', 'marketing_team_salary', 'rent_utilities']
try:
logger.info(f"[未匹配写库] 最终 unmatched_collector={unmatched_collector}")
BizUnmatchedFee.query.filter(
BizUnmatchedFee.task_id == task.id,
BizUnmatchedFee.stat_month == task.month,
BizUnmatchedFee.fee_type.in_(PROCESSOR_FEE_TYPES),
).delete(synchronize_session='fetch')
db.session.flush()
inserted = 0
for fee_type, amount in unmatched_collector.items():
if fee_type not in PROCESSOR_FEE_TYPES:
continue
amt = Decimal(str(amount)) if amount is not None else Decimal('0')
if amt == 0:
continue
db.session.add(BizUnmatchedFee(
task_id=task.id, stat_month=task.month,
fee_type=fee_type, unmatched_amount=amt,
))
inserted += 1
db.session.commit()
logger.info(f"[未匹配写库] 完成: task={task.id} month={task.month} 写入 {inserted} 条")
except Exception as e_unm:
db.session.rollback()
logger.error(f"[未匹配写库] 失败: {e_unm}", e_unm)
# ========== 步骤 f: 生成汇总 Excel 并上传到 OSS ========== # ========== 步骤 f: 生成汇总 Excel 并上传到 OSS ==========
step_f_start = time.time() step_f_start = time.time()
logger.info("[处理任务] 步骤 f: 生成汇总 Excel 并上传到 OSS...") logger.info("[处理任务] 步骤 f: 生成汇总 Excel 并上传到 OSS...")
...@@ -1895,8 +1949,7 @@ class DataProcessor: ...@@ -1895,8 +1949,7 @@ class DataProcessor:
r = group_records[0] r = group_records[0]
brand = r.get("品牌") or "未知品牌" brand = r.get("品牌") or "未知品牌"
fee = r.get("市场费", Decimal("0")) fee = r.get("市场费", Decimal("0"))
logger.info(f"[市场费分摊] 单条记录,跳过品牌匹配与 GMV 分摊: " logger.info(f"[市场费·规则1命中] flow={flow}, biz={biz}, brand={brand}, fee={fee}")
f"flow={flow}, biz={biz}, brand={brand}, fee={fee}")
result.append({ result.append({
"流量方名称": flow, "流量方名称": flow,
"业务类型": biz, "业务类型": biz,
...@@ -1916,21 +1969,41 @@ class DataProcessor: ...@@ -1916,21 +1969,41 @@ class DataProcessor:
# ---------- 场景B: 同时有 问界 + 鸿蒙 ---------- # ---------- 场景B: 同时有 问界 + 鸿蒙 ----------
if has_wj and has_hm: if has_wj and has_hm:
logger.info(f"[市场费分摊] 双品牌场景(问界+鸿蒙),逐行按车型匹配,无车型行跳过: " # 收集问界和鸿蒙在 settlement_map 里的 GMV,用于无车型行分摊
f"flow={flow}, biz={biz}, 总行数={len(group_records)}") wj_gmv_data = settlement_map.get((flow, biz, "问界"), {})
hm_gmv_data = settlement_map.get((flow, biz, "鸿蒙"), {})
wj_gmv = Decimal(str(wj_gmv_data.get("GMV", 0) or 0))
hm_gmv = Decimal(str(hm_gmv_data.get("GMV", 0) or 0))
total_gmv = wj_gmv + hm_gmv
logger.info(f"[市场费·规则2命中·双品牌] flow={flow}, biz={biz}, 总行数={len(group_records)}, "
f"问界GMV={wj_gmv}, 鸿蒙GMV={hm_gmv}")
output_by_brand = defaultdict(Decimal) output_by_brand = defaultdict(Decimal)
skipped_fee = Decimal("0") unknown_fee = Decimal("0")
for r in group_records: for r in group_records:
# 注: 上游 _parse_market_fee 已把 None 统一转成 "未知品牌",
# 这里只需判断 "未知品牌" 即可;brand 不可能为 None。
brand = r.get("品牌") brand = r.get("品牌")
fee = r.get("市场费", Decimal("0")) fee = r.get("市场费", Decimal("0"))
if brand == "未知品牌": if brand == "未知品牌":
skipped_fee += fee unknown_fee += fee
continue else:
output_by_brand[brand] += fee output_by_brand[brand] += fee
if skipped_fee > 0:
logger.info(f"[市场费分摊] 双品牌场景跳过无车型行,金额={skipped_fee}") # 无车型行费用按 GMV 比例分摊到问界和鸿蒙
if unknown_fee > 0:
if total_gmv > 0:
wj_share = unknown_fee * (wj_gmv / total_gmv)
hm_share = unknown_fee - wj_share # 吃掉尾差
else:
# GMV 为 0 → 回退平均分摊
wj_share = unknown_fee / 2
hm_share = unknown_fee - wj_share
output_by_brand["问界"] += wj_share
output_by_brand["鸿蒙"] += hm_share
logger.info(f"[市场费·规则2命中·无车型分摊] flow={flow}, biz={biz}, "
f"unknown_fee={round_2(unknown_fee)}, "
f"wj_share={round_2(wj_share)}, hm_share={round_2(hm_share)}")
for brand, fee in output_by_brand.items(): for brand, fee in output_by_brand.items():
result.append({ result.append({
"流量方名称": flow, "流量方名称": flow,
...@@ -1941,6 +2014,10 @@ class DataProcessor: ...@@ -1941,6 +2014,10 @@ class DataProcessor:
continue continue
# ---------- 默认: 单品牌 / 全未知 → 走原有 GMV 分摊 ---------- # ---------- 默认: 单品牌 / 全未知 → 走原有 GMV 分摊 ----------
default_total_fee = sum(r.get("市场费", Decimal("0")) for r in group_records)
default_brands = {r.get("品牌", "未知品牌") for r in group_records}
logger.info(f"[市场费·规则3命中·GMV分摊] flow={flow}, biz={biz}, "
f"品牌={default_brands}, 行数={len(group_records)}, 费用={default_total_fee}")
result.extend(self._apply_gmv_allocation(group_records, flow, biz, settlement_map)) result.extend(self._apply_gmv_allocation(group_records, flow, biz, settlement_map))
logger.info(f"[市场费分摊] 完成,共 {len(result)} 条记录") logger.info(f"[市场费分摊] 完成,共 {len(result)} 条记录")
...@@ -2546,12 +2623,32 @@ class DataProcessor: ...@@ -2546,12 +2623,32 @@ class DataProcessor:
logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...") logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...")
result = self._allocate_market_fee_by_gmv(all_results, settlement_map) result = self._allocate_market_fee_by_gmv(all_results, settlement_map)
# 总量校验:matched_sum 来自 result 聚合(已 GMV 分摊后的品牌维度金额) # 总量校验
matched_sum = sum(r["市场费"] for r in result) matched_sum = sum(r["市场费"] for r in result)
# 用总量守恒计算未匹配(精确到 continue 跳过的 + 分摊差值)
unmatched_amount = total_input_fee - matched_sum unmatched_amount = total_input_fee - matched_sum
unmatched['market_fee'] += unmatched_amount
logger.info(f"[市场费][未匹配汇总] market_fee: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['market_fee']}") # 按 biz_type 分别统计未匹配
biz_input = defaultdict(Decimal)
for r in all_results:
biz_input[r["业务类型"]] += r["市场费"]
biz_matched = defaultdict(Decimal)
for r in result:
biz_matched[r["业务类型"]] += r["市场费"]
# 按 biz_type 分别存 unmatched
for biz in [BIZ_TYPE_1_1, BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
z = biz_input.get(biz, Decimal("0")) - biz_matched.get(biz, Decimal("0"))
unmatched[f'market_fee_{biz}'] = unmatched.get(f'market_fee_{biz}', Decimal("0")) + z
# 未匹配合计
unmatched['market_fee'] = unmatched.get('market_fee', Decimal("0")) + unmatched_amount
logger.info(f"[市场费][未匹配汇总] 总额={total_input_fee} 已匹配={matched_sum} 未匹配合计={unmatched_amount}")
for biz in [BIZ_TYPE_1_1, BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
z = unmatched.get(f'market_fee_{biz}', Decimal("0"))
if biz_input.get(biz, Decimal("0")) > 0 or z != 0:
logger.info(f" biz={biz}: 输入={biz_input.get(biz, Decimal('0'))}, "
f"已匹配={biz_matched.get(biz, Decimal('0'))}, 未匹配={z}")
logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录") logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录")
return result, unmatched return result, unmatched
...@@ -2714,16 +2811,16 @@ class DataProcessor: ...@@ -2714,16 +2811,16 @@ class DataProcessor:
park_to_flows[ps_std].append((flow_name, biz_type)) park_to_flows[ps_std].append((flow_name, biz_type))
# 构建 park_rows 索引(用于 gmv_ratio_park 分摊) # 构建 park_rows 索引(用于 gmv_ratio_park 分摊)
# 只保留 service_provider 含"深圳嘀加"的 entries(分摊分母口径) # 只保留 service_provider 含"嘀加"的 entries(分摊分母口径)
# settlement_map 里每个 (flow_name, biz_type, brand) 存了服务商字段(L1068) # settlement_map 里每个 (flow_name, biz_type, brand) 存了服务商字段
def _is_dijia_flow(flow_name, biz_type, brand=None): def _is_dijia_flow(flow_name, biz_type, brand=None):
"""判断 settlement_map 中该 key 的服务商是否含"深圳嘀加"。""" """判断 settlement_map 中该 key 的服务商是否含"嘀加"(嘀加自营/嘀加直营)。"""
if brand is not None: if brand is not None:
sp = (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "").strip() sp = (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "").strip()
return "深圳嘀加" in sp return "嘀加" in sp
# brand=None → 查该 (flow, biz) 任意 brand 有嘀加就算 # brand=None → 查该 (flow, biz) 任意 brand 有嘀加就算
for (fn, bt, br), data in settlement_map.items(): for (fn, bt, br), data in settlement_map.items():
if fn == flow_name and bt == biz_type and "深圳嘀加" in (data.get("服务商") or ""): if fn == flow_name and bt == biz_type and "嘀加" in (data.get("服务商") or ""):
return True return True
return False return False
...@@ -2739,7 +2836,7 @@ class DataProcessor: ...@@ -2739,7 +2836,7 @@ class DataProcessor:
if not park_rows and settlement_map: if not park_rows and settlement_map:
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
sp = (data.get("服务商") or "").strip() sp = (data.get("服务商") or "").strip()
if "深圳嘀加" not in sp: if "嘀加" not in sp:
continue continue
ps_raw = data.get("park_store_raw", "") ps_raw = data.get("park_store_raw", "")
gmv_ratio = data.get("gmv_ratio") gmv_ratio = data.get("gmv_ratio")
...@@ -2750,7 +2847,7 @@ class DataProcessor: ...@@ -2750,7 +2847,7 @@ class DataProcessor:
if ps_std != ps_raw: if ps_std != ps_raw:
park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
logger.info(f"[人力成本] park_rows 构建(仅深圳嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合") logger.info(f"[人力成本] park_rows 构建(仅嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")
if not park_to_flows and settlement_map: if not park_to_flows and settlement_map:
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
...@@ -2775,6 +2872,8 @@ class DataProcessor: ...@@ -2775,6 +2872,8 @@ class DataProcessor:
check_passed = 0 check_passed = 0
check_skipped = 0 check_skipped = 0
failed_match_count = 0 failed_match_count = 0
# 诊断:收集完全未匹配的门店
_unmatched_stores = defaultdict(lambda: {"tech": Decimal("0"), "mkt": Decimal("0"), "rows": 0})
try: try:
sheet_name = xls.sheet_names[0] sheet_name = xls.sheet_names[0]
...@@ -2852,7 +2951,7 @@ class DataProcessor: ...@@ -2852,7 +2951,7 @@ class DataProcessor:
return cur_biz return cur_biz
only_bt = next(iter(real)) only_bt = next(iter(real))
if only_bt != cur_biz: if only_bt != cur_biz:
logger.info(f"[人力成本归属] 门店='{sn}': Excel归属={cur_biz}, DB只有={only_bt} → 纠正为={only_bt}") logger.info(f"[规则1命中] 门店='{sn}', Excel biz={cur_biz}, DB 只有={only_bt} → 纠正为={only_bt}")
return only_bt return only_bt
return cur_biz return cur_biz
...@@ -2889,6 +2988,19 @@ class DataProcessor: ...@@ -2889,6 +2988,19 @@ class DataProcessor:
elif "2.3" in biz_val: elif "2.3" in biz_val:
biz_type = BIZ_TYPE_2_3 biz_type = BIZ_TYPE_2_3
# --- biz_type 兜底:空值时从 park_to_flows 推导或默认 1.1 ---
if not biz_type:
ps_candidates = [store_name, to_standard(store_name, 'yq')]
for ps in ps_candidates:
if ps in park_to_flows:
biz_set = set(fb for _, fb in park_to_flows[ps])
if len(biz_set) == 1:
biz_type = list(biz_set)[0]
break
if not biz_type:
biz_type = BIZ_TYPE_1_1 # 最后兜底:贴膜技师通常归 1.1
logger.warning(f"[人力成本] biz_type 未知, 兜底为 1.1: store='{store_name}'")
# --- 归属纠正(2.1/2.3 规则) --- # --- 归属纠正(2.1/2.3 规则) ---
if biz_type: if biz_type:
biz_type = _resolve_biz_by_store(store_name, biz_type) biz_type = _resolve_biz_by_store(store_name, biz_type)
...@@ -2932,19 +3044,37 @@ class DataProcessor: ...@@ -2932,19 +3044,37 @@ class DataProcessor:
std_in_park_to_flows = to_standard(store_name, 'yq') in park_to_flows std_in_park_to_flows = to_standard(store_name, 'yq') in park_to_flows
if in_park_to_flows or std_in_park_to_flows: if in_park_to_flows or std_in_park_to_flows:
# 园区店回退:找到关联的流量方 # 园区店回退:找到关联的流量方(全部 flow,不做服务商过滤)
ps = store_name if in_park_to_flows else to_standard(store_name, 'yq') ps = store_name if in_park_to_flows else to_standard(store_name, 'yq')
related_flows = park_to_flows.get(ps, []) related_flows = park_to_flows.get(ps, [])
# 优先用 Excel 的 biz_type 匹配;匹配不到就用所有关联 flow(各自带自己的真实 biz_type)
matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type] matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
use_flow_own_biz = False
if not matching_flows: if not matching_flows:
matching_flows = related_flows # 回退:使用所有关联流量方 matching_flows = related_flows # 回退:使用所有关联流量方
use_flow_own_biz = True # 每个 flow 用自己的 DB biz_type
if matching_flows: if matching_flows:
# 优先使用 gmv_ratio_park 分摊 # 优先使用 gmv_ratio_park 分摊
park_ratio_rows = park_rows.get((ps, biz_type), []) # park_ratio_rows 也需要根据是否用 flow 自身 biz_type 来取
pr_key_biz = None if use_flow_own_biz else biz_type
park_ratio_rows = park_rows.get((ps, pr_key_biz), []) if pr_key_biz else []
if not park_ratio_rows and related_flows:
# 收集该园区店所有 biz_type 的 park_ratio_rows
all_biz = set(fb for _, fb in related_flows)
for ab in all_biz:
park_ratio_rows.extend(park_rows.get((ps, ab), []))
if park_ratio_rows: if park_ratio_rows:
raw_ratios = []
for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows: for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
# 从 matching_flows 里找该 flow 的真实 biz_type
real_biz = None
for fn, fb in matching_flows:
if fn == flow_name:
real_biz = fb
break
if not real_biz:
continue
if gmv_ratio_park is not None: if gmv_ratio_park is not None:
r = Decimal(str(gmv_ratio_park)) r = Decimal(str(gmv_ratio_park))
ratio_type = "gmv_ratio_park" ratio_type = "gmv_ratio_park"
...@@ -2953,26 +3083,40 @@ class DataProcessor: ...@@ -2953,26 +3083,40 @@ class DataProcessor:
ratio_type = "gmv_ratio(回退)" ratio_type = "gmv_ratio(回退)"
else: else:
continue continue
result[(flow_name, biz_type)]["技师工资"] += technician_salary * r raw_ratios.append((flow_name, brand, r, ratio_type, real_biz))
result[(flow_name, biz_type)]["营销团队工资"] += marketing_salary * r total_r = sum(r for _, _, r, _, _ in raw_ratios)
logger.info(f"[人力成本] 园区店分摊({ratio_type}): ps='{ps}', {len(park_ratio_rows)}行, tech={technician_salary}, mkt={marketing_salary}") if total_r > 0:
for flow_name, brand, r, ratio_type, real_biz in raw_ratios:
normalized_r = r / total_r
result[(flow_name, real_biz)]["技师工资"] += technician_salary * normalized_r
result[(flow_name, real_biz)]["营销团队工资"] += marketing_salary * normalized_r
logger.info(f"[规则3命中·园区店分摊] ps='{ps}', matching_flows={len(matching_flows)}, "
f"有效比例行={len(raw_ratios)}, 分母sum_r={total_r:.4f}, "
f"tech={technician_salary}, mkt={marketing_salary}, ratio_type={ratio_type}")
else:
flow_count = len(matching_flows)
for flow_name, real_biz in matching_flows:
key = (flow_name, real_biz)
result[key]["技师工资"] += technician_salary / flow_count
result[key]["营销团队工资"] += marketing_salary / flow_count
logger.info(f"[规则3命中·园区店平均回退] ps='{ps}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
else: else:
# 回退:平均分配
flow_count = len(matching_flows) flow_count = len(matching_flows)
for flow_name, _ in matching_flows: for flow_name, real_biz in matching_flows:
key = (flow_name, biz_type) key = (flow_name, real_biz)
result[key]["技师工资"] += technician_salary / flow_count result[key]["技师工资"] += technician_salary / flow_count
result[key]["营销团队工资"] += marketing_salary / flow_count result[key]["营销团队工资"] += marketing_salary / flow_count
logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps}', flows={flow_count}") logger.info(f"[规则3命中·无park_ratio平均回退] ps='{ps}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary _us = _unmatched_stores[store_name]
unmatched['marketing_team_salary'] += marketing_salary _us["tech"] += technician_salary
_us["mkt"] += marketing_salary
_us["rows"] += 1
continue continue
# 直接匹配:检查是否为流量方 # 直接匹配:检查是否为流量方(不做服务商过滤,非嘀加 flow 也正常拿工资)
if std_store_name in flow_names_set: if std_store_name in flow_names_set:
# 使用原名
original_flow = std_to_original_flow.get(std_store_name, std_store_name) original_flow = std_to_original_flow.get(std_store_name, std_store_name)
key = (original_flow, biz_type) key = (original_flow, biz_type)
result[key]["技师工资"] += technician_salary result[key]["技师工资"] += technician_salary
...@@ -2983,13 +3127,27 @@ class DataProcessor: ...@@ -2983,13 +3127,27 @@ class DataProcessor:
if ps_std in park_to_flows: if ps_std in park_to_flows:
related_flows = park_to_flows[ps_std] related_flows = park_to_flows[ps_std]
matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type] matching_flows = [(fn, fb) for fn, fb in related_flows if fb == biz_type]
use_flow_own_biz = False
if not matching_flows: if not matching_flows:
matching_flows = related_flows matching_flows = related_flows
use_flow_own_biz = True
if matching_flows: if matching_flows:
# 优先使用 gmv_ratio_park 分摊 pr_key_biz = None if use_flow_own_biz else biz_type
park_ratio_rows = park_rows.get((ps_std, biz_type), []) park_ratio_rows = park_rows.get((ps_std, pr_key_biz), []) if pr_key_biz else []
if not park_ratio_rows and related_flows:
all_biz = set(fb for _, fb in related_flows)
for ab in all_biz:
park_ratio_rows.extend(park_rows.get((ps_std, ab), []))
if park_ratio_rows: if park_ratio_rows:
raw_ratios = []
for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows: for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
real_biz = None
for fn, fb in matching_flows:
if fn == flow_name:
real_biz = fb
break
if not real_biz:
continue
if gmv_ratio_park is not None: if gmv_ratio_park is not None:
r = Decimal(str(gmv_ratio_park)) r = Decimal(str(gmv_ratio_park))
ratio_type = "gmv_ratio_park" ratio_type = "gmv_ratio_park"
...@@ -2998,25 +3156,39 @@ class DataProcessor: ...@@ -2998,25 +3156,39 @@ class DataProcessor:
ratio_type = "gmv_ratio(回退)" ratio_type = "gmv_ratio(回退)"
else: else:
continue continue
result[(flow_name, biz_type)]["技师工资"] += technician_salary * r raw_ratios.append((flow_name, brand, r, ratio_type, real_biz))
result[(flow_name, biz_type)]["营销团队工资"] += marketing_salary * r total_r = sum(r for _, _, r, _, _ in raw_ratios)
logger.info(f"[人力成本] 园区店分摊({ratio_type}): ps='{ps_std}', {len(park_ratio_rows)}行, tech={technician_salary}, mkt={marketing_salary}") if total_r > 0:
for flow_name, brand, r, ratio_type, real_biz in raw_ratios:
normalized_r = r / total_r
result[(flow_name, real_biz)]["技师工资"] += technician_salary * normalized_r
result[(flow_name, real_biz)]["营销团队工资"] += marketing_salary * normalized_r
logger.info(f"[人力成本] 园区店模糊分摊({ratio_type}·归一化): ps='{ps_std}', {len(raw_ratios)}行, sum_r={total_r:.4f}")
else:
flow_count = len(matching_flows)
for flow_name, real_biz in matching_flows:
key = (flow_name, real_biz)
result[key]["技师工资"] += technician_salary / flow_count
result[key]["营销团队工资"] += marketing_salary / flow_count
else: else:
# 回退:平均分配
flow_count = len(matching_flows) flow_count = len(matching_flows)
for flow_name, _ in matching_flows: for flow_name, real_biz in matching_flows:
key = (flow_name, biz_type) key = (flow_name, real_biz)
result[key]["技师工资"] += technician_salary / flow_count result[key]["技师工资"] += technician_salary / flow_count
result[key]["营销团队工资"] += marketing_salary / flow_count result[key]["营销团队工资"] += marketing_salary / flow_count
logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps_std}', flows={flow_count}") logger.info(f"[人力成本] 园区店模糊分摊(平均回退): ps='{ps_std}', flows={flow_count}, use_flow_own_biz={use_flow_own_biz}")
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary _us = _unmatched_stores[store_name + "(park有关联但没匹配到biz_type)"]
unmatched['marketing_team_salary'] += marketing_salary _us["tech"] += technician_salary
_us["mkt"] += marketing_salary
_us["rows"] += 1
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary _us = _unmatched_stores[store_name + "(flow和park_store都不匹配)"]
unmatched['marketing_team_salary'] += marketing_salary _us["tech"] += technician_salary
_us["mkt"] += marketing_salary
_us["rows"] += 1
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):
...@@ -3026,9 +3198,20 @@ class DataProcessor: ...@@ -3026,9 +3198,20 @@ class DataProcessor:
logger.info(f"[人力成本] 检核过滤: 总行数={len(df)}, 通过={check_passed}, 过滤掉={check_skipped}") logger.info(f"[人力成本] 检核过滤: 总行数={len(df)}, 通过={check_passed}, 过滤掉={check_skipped}")
logger.info(f"[人力成本] 解析完成: {row_count} 行有效, 总输入薪资={total_input_salary}") logger.info(f"[人力成本] 解析完成: {row_count} 行有效, 总输入薪资={total_input_salary}")
logger.info(f"[人力成本] 聚合结果: {len(result)} 个key, 匹配失败={failed_match_count}") logger.info(f"[人力成本] 聚合结果: {len(result)} 个key, 匹配失败={failed_match_count}")
# ===== 诊断:打印所有未匹配门店明细 =====
if _unmatched_stores:
total_um_tech = sum(v["tech"] for v in _unmatched_stores.values())
total_um_mkt = sum(v["mkt"] for v in _unmatched_stores.values())
logger.warning(f"[人力成本-诊断] 未匹配门店共 {len(_unmatched_stores)} 个, 合计 tech={total_um_tech}, mkt={total_um_mkt}")
for store, info in sorted(_unmatched_stores.items(), key=lambda x: float(x[1]["tech"] + x[1]["mkt"]), reverse=True)[:30]:
logger.warning(f" 未匹配: 门店='{store}', tech={info['tech']}, mkt={info['mkt']}, 行数={info['rows']}")
if not result: if not result:
logger.info("[人力成本] 无有效数据") logger.info("[人力成本] 无有效数据(无嘀加流量方匹配成功)")
# 全部进 unmatched
unmatched['technician_salary'] += total_input_tech
unmatched['marketing_team_salary'] += total_input_mkt
return {}, unmatched return {}, unmatched
# 总量校验 # 总量校验
...@@ -3082,6 +3265,7 @@ class DataProcessor: ...@@ -3082,6 +3265,7 @@ class DataProcessor:
flow_ratio_entries = {} flow_ratio_entries = {}
unmatched = {'rent_utilities': Decimal('0')} unmatched = {'rent_utilities': Decimal('0')}
skip_reasons = defaultdict(lambda: Decimal('0')) # 追踪每条 continue 跳过路径的金额(用于诊断漏记)
# 构建索引 # 构建索引
flow_names_set = set() flow_names_set = set()
...@@ -3090,18 +3274,37 @@ class DataProcessor: ...@@ -3090,18 +3274,37 @@ class DataProcessor:
park_to_flows = defaultdict(list) # 从 park_rows_data 直接构建 park_to_flows = defaultdict(list) # 从 park_rows_data 直接构建
# 优先使用独立查询的 park_rows_data(使用原始 park_store 值) # 优先使用独立查询的 park_rows_data(使用原始 park_store 值)
# 只保留 service_provider 含"深圳嘀加"的记录(分摊口径统一) # 只保留 service_provider 含"嘀加"的记录(分摊口径统一)
def _is_dijia_flow(flow_name, biz_type, brand=None): def _is_dijia_flow(flow_name, biz_type, brand=None):
"""从 settlement_map 查服务商是否含"深圳嘀加"。""" """从 settlement_map 查服务商是否含"嘀加"(嘀加自营/嘀加直营)。"""
if brand is not None: if brand is not None:
return "深圳嘀加" in (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "") return "嘀加" in (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "")
# brand=None → 任意 brand 有嘀加就算 # brand=None → 任意 brand 有嘀加就算
for (fn, bt, br), data in settlement_map.items(): for (fn, bt, br), data in settlement_map.items():
if fn == flow_name and bt == biz_type and "深圳嘀加" in (data.get("服务商") or ""): if fn == flow_name and bt == biz_type and "嘀加" in (data.get("服务商") or ""):
return True return True
return False return False
if park_rows_data: if park_rows_data:
# ========== 第 1 步:先构建完整的 park_to_flows 查找索引(不过滤服务商) ==========
# park_to_flows 是 Excel 门店名 → DB 流量方列表的查找表,
# 必须包含所有门店(不管服务商是什么),否则 Excel 里非嘀加/无品牌门店找不到匹配目标 → 费用丢失
for record in park_rows_data:
try:
if len(record) >= 4:
flow_name, bt, brand, ps_raw = record[0], record[1], record[2], record[3]
else:
continue
if ps_raw and bt:
park_to_flows[ps_raw].append((flow_name, bt))
ps_std = to_standard(ps_raw, 'yq')
if ps_std != ps_raw:
park_to_flows[ps_std].append((flow_name, bt))
except Exception as e:
logger.error(f"[房租水电][诊断] park_to_flows 构建失败: {e}")
# ========== 第 2 步:再构建过滤后的 park_rows(GMV 分母池) ==========
# park_rows 用于 gmv_ratio_park 分摊的分母池计算 —— 这里只保留嘀加服务商
for i, record in enumerate(park_rows_data): for i, record in enumerate(park_rows_data):
try: try:
# 支持5/6/7元素三种格式 # 支持5/6/7元素三种格式
...@@ -3115,33 +3318,35 @@ class DataProcessor: ...@@ -3115,33 +3318,35 @@ class DataProcessor:
gmv_ratio = None gmv_ratio = None
ps_std = to_standard(ps_raw, 'yq') if ps_raw else "" ps_std = to_standard(ps_raw, 'yq') if ps_raw else ""
else: else:
logger.warning(f"[房租水电][诊断] park_rows_data[{i}] 格式错误: len={len(record)}")
continue continue
# --- 服务商过滤 ---
if not _is_dijia_flow(flow_name, bt, brand): if not _is_dijia_flow(flow_name, bt, brand):
continue continue
if ps_raw and bt: if ps_raw and bt:
park_rows[(ps_raw, bt)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_raw, bt)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
park_to_flows[ps_raw].append((flow_name, bt))
except Exception as e: except Exception as e:
logger.error(f"[房租水电][诊断] park_rows_data[{i}] 处理失败: {e}") logger.error(f"[房租水电][诊断] park_rows_data[{i}] 处理失败: {e}")
else: else:
# 回退:从 settlement_map 聚合(兼容旧数据),同样过滤服务商 # 回退:从 settlement_map 聚合 —— 同时构建完整 park_to_flows + 过滤后 park_rows
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
sp = (data.get("服务商") or "").strip()
if "深圳嘀加" not in sp:
continue
ps_raw = data.get("park_store_raw", "") ps_raw = data.get("park_store_raw", "")
gmv_ratio_park = data.get("gmv_ratio_park") if not ps_raw:
gmv_ratio = data.get("gmv_ratio") continue
if (gmv_ratio_park is not None or gmv_ratio is not None) and ps_raw: # park_to_flows 查找索引:不加过滤
park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_to_flows[ps_raw].append((flow_name, biz_type))
park_to_flows[ps_raw].append((flow_name, biz_type)) ps_std = to_standard(ps_raw, 'yq')
if ps_std != ps_raw:
park_to_flows[ps_std].append((flow_name, biz_type))
# park_rows 分母池:只保留嘀加
if "嘀加" in (data.get("服务商") or ""):
gmv_ratio_park = data.get("gmv_ratio_park")
gmv_ratio = data.get("gmv_ratio")
if gmv_ratio_park is not None or gmv_ratio is not None:
park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
logger.info(f"[房租水电] park_rows 构建(仅深圳嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合") logger.info(f"[房租水电] park_rows 构建(仅嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")
logger.info(f"[房租水电] park_to_flows 从 park_rows_data 构建(仅深圳嘀加服务商): {len(park_to_flows)} 个园区店") logger.info(f"[房租水电] park_to_flows 完整索引(所有服务商): {len(park_to_flows)} 个园区店")
# 优先使用 flow_ratio_entries 构建流量方索引(保留所有 park_store 的比例值) # 优先使用 flow_ratio_entries 构建流量方索引(保留所有 park_store 的比例值)
# 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖 # 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖
...@@ -3232,6 +3437,7 @@ class DataProcessor: ...@@ -3232,6 +3437,7 @@ class DataProcessor:
if col_target: if col_target:
target = row[col_target] target = row[col_target]
if target is None or str(target).strip() == "" or str(target).strip() == "nan": if target is None or str(target).strip() == "" or str(target).strip() == "nan":
skip_reasons['SKIP-target为空'] += Decimal('1')
continue continue
target = str(target).strip() target = str(target).strip()
...@@ -3246,6 +3452,13 @@ class DataProcessor: ...@@ -3246,6 +3452,13 @@ class DataProcessor:
if col_biz: if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else "" biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if biz_val and "1.1" not in biz_val and "贴膜" not in biz_val: if biz_val and "1.1" not in biz_val and "贴膜" not in biz_val:
rent = safe_decimal(row[col_rent]) if col_rent else Decimal("0")
water = safe_decimal(row[col_water]) if col_water else Decimal("0")
construction = safe_decimal(row[col_construction]) if col_construction else Decimal("0")
total_fee = rent + water + construction
skip_reasons['SKIP-业务类型非1.1'] += total_fee
if total_fee > 0:
unmatched['rent_utilities'] += total_fee # 差额完整性:即使非1.1业务,有金额也要计入未匹配
continue continue
# 合计 = 房租 + 水电 + 施工 # 合计 = 房租 + 水电 + 施工
...@@ -3255,6 +3468,7 @@ class DataProcessor: ...@@ -3255,6 +3468,7 @@ class DataProcessor:
total_fee = rent + water + construction total_fee = rent + water + construction
if total_fee == 0: if total_fee == 0:
skip_reasons['SKIP-金额为0'] += Decimal('1')
continue continue
# 诊断日志:打印每一行原始数据 # 诊断日志:打印每一行原始数据
...@@ -3572,47 +3786,37 @@ class DataProcessor: ...@@ -3572,47 +3786,37 @@ class DataProcessor:
ratio_applied = False ratio_applied = False
if ratio_rows: if ratio_rows:
# 诊断日志:检查 ratio_rows 内容 # 过滤非嘀加 brand,只保留嘀加自营行
if is_target: dijia_entries = []
logger.info(f"[直接匹配-诊断] ratio_rows 详情: {ratio_rows}")
for idx, row in enumerate(ratio_rows):
logger.info(f"[直接匹配-诊断] ratio_rows[{idx}]: type={type(row)}, len={len(row) if hasattr(row, '__len__') else 'N/A'}")
if hasattr(row, '__len__') and len(row) >= 3:
logger.info(f"[直接匹配-诊断] brand={row[0]}, gmv_ratio={row[1]}, type(gmv_ratio)={type(row[1])}, gmv_ratio_park={row[2]}")
for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_rows: for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_rows:
# 诊断日志:显示原始数据和计算过程 if gmv_ratio is None:
if is_target: continue
logger.info(f"[直接匹配-诊断] 处理品牌: brand={brand}, gmv_ratio原始={gmv_ratio}, type={type(gmv_ratio)}, gmv_ratio_park={gmv_ratio_park}") # 判断该 brand 是否嘀加
logger.info(f"[直接匹配-诊断] fee={fee}, type={type(fee)}") sp = ""
logger.info(f"[直接匹配-诊断] gmv_ratio is not None: {gmv_ratio is not None}") if settlement_map:
sp = (settlement_map.get((original_flow, biz_type, brand), {}).get("服务商") or "").strip()
# 关键修复:检查 gmv_ratio 是否有值 if "嘀加" in sp or not sp: # 没 settlement_map 信息时保守保留
if gmv_ratio is not None: dijia_entries.append((brand, Decimal(str(gmv_ratio))))
r = Decimal(str(gmv_ratio))
if is_target: if dijia_entries:
logger.info(f"[直接匹配-诊断] Decimal转换: r={r}, type={type(r)}") # 过滤后重新归一化比例到 sum=1
logger.info(f"[直接匹配-诊断] 乘法计算: fee * r = {fee * r}") sum_r = sum(r for _, r in dijia_entries)
fee_share = round_2(fee * r) if sum_r > 0:
if is_target: for brand, r in dijia_entries:
logger.info(f"[直接匹配-诊断] round_2结果: fee_share={fee_share}") normalized_r = r / sum_r
raw_records.append({ fee_share = round_2(fee * normalized_r)
"流量方名称": original_flow, raw_records.append({
"业务类型": biz_type or BIZ_TYPE_1_1, "流量方名称": original_flow,
"品牌": brand or "", "业务类型": biz_type or BIZ_TYPE_1_1,
"房租及水电费": fee_share, "品牌": brand or "",
"匹配方式": "direct_ratio", "房租及水电费": fee_share,
}) "匹配方式": "direct_ratio",
ratio_applied = True })
logger.info(f"[直接匹配] flow={original_flow}, brand={brand}, gmv_ratio={r}, fee_share={fee_share}") ratio_applied = True
elif is_target: logger.info(f"[直接匹配](嘀加归一化) flow={original_flow}, brand={brand}, raw_r={r}, norm_r={normalized_r:.4f}, fee_share={fee_share}")
logger.warning(f"[直接匹配-诊断] gmv_ratio 为 None,跳过此品牌: brand={brand}")
if not ratio_applied: if not ratio_applied:
if is_target: logger.warning(f"[直接匹配] flow={original_flow}, biz_type={biz_type} 无gmv_ratio, 回退100%分配")
logger.warning(f"[直接匹配] 目标流量方无gmv_ratio, ratio_rows={ratio_rows}, 回退100%分配")
else:
logger.warning(f"[直接匹配] flow={original_flow}, biz_type={biz_type} 无gmv_ratio, 回退100%分配")
raw_records.append({ raw_records.append({
"流量方名称": original_flow, "流量方名称": original_flow,
"业务类型": biz_type or BIZ_TYPE_1_1, "业务类型": biz_type or BIZ_TYPE_1_1,
...@@ -3642,31 +3846,39 @@ class DataProcessor: ...@@ -3642,31 +3846,39 @@ class DataProcessor:
# 优先查找 gmv_ratio_park # 优先查找 gmv_ratio_park
park_ratio_rows = park_rows.get((ps, biz_type), []) park_ratio_rows = park_rows.get((ps, biz_type), [])
if park_ratio_rows: if park_ratio_rows:
allocated_fee = Decimal("0") # 归一化:过滤非嘀加后比例和 < 1,需重新归一化到 100%
raw_ratios = []
for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows: for flow_name, brand, gmv_ratio_park, gmv_ratio in park_ratio_rows:
# 优先使用 gmv_ratio_park
if gmv_ratio_park is not None: if gmv_ratio_park is not None:
r = Decimal(str(gmv_ratio_park)) r = Decimal(str(gmv_ratio_park))
ratio_type = "gmv_ratio_park" ratio_type = "gmv_ratio_park"
elif gmv_ratio is not None: elif gmv_ratio is not None:
# 回退使用 gmv_ratio
r = Decimal(str(gmv_ratio)) r = Decimal(str(gmv_ratio))
ratio_type = "gmv_ratio(回退)" ratio_type = "gmv_ratio(回退)"
else: else:
continue continue
fee_share = round_2(fee * r) raw_ratios.append((flow_name, brand, r, ratio_type))
allocated_fee += fee_share total_r = sum(r for _, _, r, _ in raw_ratios)
raw_records.append({ if total_r > 0:
"流量方名称": flow_name, allocated_fee = Decimal("0")
"业务类型": biz_type or BIZ_TYPE_1_1, for flow_name, brand, r, ratio_type in raw_ratios:
"品牌": brand or "", normalized_r = r / total_r
"房租及水电费": fee_share, fee_share = round_2(fee * normalized_r)
"匹配方式": "park_ratio_db", allocated_fee += fee_share
}) raw_records.append({
logger.info(f"[园区店回退] 使用{ratio_type}: flow={flow_name}, brand={brand}, r={r}, fee={fee_share}") "流量方名称": flow_name,
park_match_count += 1 "业务类型": biz_type or BIZ_TYPE_1_1,
park_allocated_total += allocated_fee "品牌": brand or "",
logger.info(f"[园区店回退] gmv_ratio_park分配成功: ps='{ps}', {len(park_ratio_rows)}行, fee={allocated_fee}") "房租及水电费": fee_share,
"匹配方式": "park_ratio_db",
})
park_match_count += 1
park_allocated_total += allocated_fee
logger.info(f"[园区店回退] {ratio_type}(归一化): ps='{ps}', {len(raw_ratios)}行, sum_r={total_r:.4f}, fee={allocated_fee}")
else:
# 比例和为0 → 直接进 unmatched
unmatched['rent_utilities'] += fee
continue
else: else:
# 回退:使用 gmv_ratio 按流量方分配 # 回退:使用 gmv_ratio 按流量方分配
logger.info(f"[园区店回退] gmv_ratio_park不存在, 回退使用gmv_ratio: ps='{ps}', bt={biz_type}") logger.info(f"[园区店回退] gmv_ratio_park不存在, 回退使用gmv_ratio: ps='{ps}', bt={biz_type}")
...@@ -3676,10 +3888,17 @@ class DataProcessor: ...@@ -3676,10 +3888,17 @@ class DataProcessor:
std_fn = to_standard(fn, '4s') std_fn = to_standard(fn, '4s')
ratio_entries = flow_ratios.get((std_fn, biz_type), []) ratio_entries = flow_ratios.get((std_fn, biz_type), [])
for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_entries: for brand, gmv_ratio, gmv_ratio_park, park_store_val in ratio_entries:
if gmv_ratio is not None: if gmv_ratio is None:
r = Decimal(str(gmv_ratio)) continue
flow_ratio_list.append((fn, brand, r)) # 过滤非嘀加 brand
total_ratio += r sp = ""
if settlement_map:
sp = (settlement_map.get((fn, biz_type, brand), {}).get("服务商") or "").strip()
if sp and "嘀加" not in sp:
continue
r = Decimal(str(gmv_ratio))
flow_ratio_list.append((fn, brand, r))
total_ratio += r
if flow_ratio_list and total_ratio > 0: if flow_ratio_list and total_ratio > 0:
for fn, brand, r in flow_ratio_list: for fn, brand, r in flow_ratio_list:
...@@ -3758,6 +3977,8 @@ class DataProcessor: ...@@ -3758,6 +3977,8 @@ class DataProcessor:
conservation_unmatched = total_input_fee - matched_sum conservation_unmatched = total_input_fee - matched_sum
unmatched['rent_utilities'] += conservation_unmatched unmatched['rent_utilities'] += conservation_unmatched
logger.info(f"[房租水电][未匹配汇总] rent_utilities: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['rent_utilities']}") logger.info(f"[房租水电][未匹配汇总] rent_utilities: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['rent_utilities']}")
if skip_reasons:
logger.warning(f"[房租水电][跳过追踪] 各路径跳过金额/行数: {dict(skip_reasons)}")
# 打印 GMV 分摊记录详情 # 打印 GMV 分摊记录详情
if gmv_allocated_records: if gmv_allocated_records:
...@@ -4606,6 +4827,22 @@ class DataProcessor: ...@@ -4606,6 +4827,22 @@ class DataProcessor:
if flow_rows: if flow_rows:
logger.info(f"[市场费分摊] 使用模糊匹配名称: '{fuzzy_flow}', 品牌='{brand}', 匹配{len(flow_rows)}行") logger.info(f"[市场费分摊] 使用模糊匹配名称: '{fuzzy_flow}', 品牌='{brand}', 匹配{len(flow_rows)}行")
if not matching_rows and brand == "未知品牌":
# brand="未知品牌" fallback: 匹配同 (flow, biz) 下的所有 DB 行,按 gmv_ratio 分摊
for try_flow in all_possible_flows:
flow_rows = [r for r in rows if r.traffic_name == try_flow and r.business_type == bt]
if flow_rows:
matching_rows.extend(flow_rows)
if not matching_rows:
# 再试模糊匹配
db_flow_names = set(r.traffic_name for r in rows)
fuzzy_matches = [fn for fn in db_flow_names if flow in str(fn) or str(fn) in flow]
for fuzzy_flow in fuzzy_matches:
flow_rows = [r for r in rows if r.traffic_name == fuzzy_flow and r.business_type == bt]
matching_rows.extend(flow_rows)
if matching_rows:
logger.info(f"[市场费分摊·fallback] brand='未知品牌' → 匹配同 (flow={flow}, biz={bt}) 下所有 DB 行={len(matching_rows)}, 按gmv_ratio分摊")
if not matching_rows: if not matching_rows:
logger.warning(f"[市场费分摊] 流量方='{flow}', 业务类型='{bt}', 品牌='{brand}' 无匹配数据库行,跳过该品牌") logger.warning(f"[市场费分摊] 流量方='{flow}', 业务类型='{bt}', 品牌='{brand}' 无匹配数据库行,跳过该品牌")
continue continue
...@@ -4963,18 +5200,25 @@ class DataProcessor: ...@@ -4963,18 +5200,25 @@ class DataProcessor:
return updated_count return updated_count
def _update_utility_fee_to_db(self, task_id, month, data_list): def _update_utility_fee_to_db(self, task_id, month, data_list):
"""只更新房租水电费相关字段;对多 park_store 场景按 gmv_ratio 分摊写入""" """只更新房租水电费相关字段;对多 park_store 场景按 gmv_ratio 分摊写入
Returns:
tuple: (updated_count, failed_amount)
- updated_count: 实际更新的行数
- failed_amount: 写库时 DB 查不到对应 traffic_name/park_store 的金额(=应进 unmatched 的部分)
"""
update_columns = ['rent_utilities'] update_columns = ['rent_utilities']
if not data_list: if not data_list:
logger.info("[房租水电费] 无数据需要更新") logger.info("[房租水电费] 无数据需要更新")
return 0 return 0, Decimal('0')
ratio_index = self._load_db_ratio_index(task_id, month) ratio_index = self._load_db_ratio_index(task_id, month)
table = BizBudgetAchieve.__tablename__ table = BizBudgetAchieve.__tablename__
conn = db.engine.connect() conn = db.engine.connect()
updated_count = 0 updated_count = 0
failed_amount = Decimal('0') # 写库失败的金额(DB 查不到行的)
try: try:
trans = conn.begin() trans = conn.begin()
for row in data_list: for row in data_list:
...@@ -4999,7 +5243,8 @@ class DataProcessor: ...@@ -4999,7 +5243,8 @@ class DataProcessor:
if updated_rows > 0: if updated_rows > 0:
logger.info(f"[房租水电GMV写入] flow={traffic_name}, biz={business_type}, fee={brand_level_fee}, target_type={target_type}, updated_rows={updated_rows}") logger.info(f"[房租水电GMV写入] flow={traffic_name}, biz={business_type}, fee={brand_level_fee}, target_type={target_type}, updated_rows={updated_rows}")
else: else:
logger.warning(f"[房租水电GMV写入] 未找到匹配行: flow={traffic_name}, biz={business_type}, target_type={target_type}") logger.warning(f"[房租水电GMV写入] 未找到匹配行: flow={traffic_name}, biz={business_type}, target_type={target_type}, fee={brand_level_fee}")
failed_amount += Decimal(str(brand_level_fee)) # ← 新增:写库失败 → 计入差额
continue continue
if key in ratio_index and len(ratio_index[key]) > 1: if key in ratio_index and len(ratio_index[key]) > 1:
...@@ -5045,6 +5290,8 @@ class DataProcessor: ...@@ -5045,6 +5290,8 @@ class DataProcessor:
total = len(data_list) total = len(data_list)
rate = updated_count / total * 100 if total > 0 else 0 rate = updated_count / total * 100 if total > 0 else 0
logger.info(f"[房租水电费] Update 成功,共处理 {total} 条,实际更新 {updated_count} 条,成功率 {rate:.1f}%") logger.info(f"[房租水电费] Update 成功,共处理 {total} 条,实际更新 {updated_count} 条,成功率 {rate:.1f}%")
if failed_amount > 0:
logger.warning(f"[房租水电费] 写库失败需补入差额: failed_amount={failed_amount}")
except Exception as e: except Exception as e:
trans.rollback() trans.rollback()
logger.error(f"[房租水电费] Update 失败: {str(e)}") logger.error(f"[房租水电费] Update 失败: {str(e)}")
...@@ -5052,7 +5299,7 @@ class DataProcessor: ...@@ -5052,7 +5299,7 @@ class DataProcessor:
finally: finally:
conn.close() conn.close()
return updated_count return updated_count, failed_amount
# ======================================================== # ========================================================
# 通用分摊更新方法:按 gmv_ratio 分摊 + 按主键id直接更新 # 通用分摊更新方法:按 gmv_ratio 分摊 + 按主键id直接更新
...@@ -5076,34 +5323,51 @@ class DataProcessor: ...@@ -5076,34 +5323,51 @@ class DataProcessor:
返回: 返回:
(分摊前总金额, 分摊后总金额, 更新行数) (分摊前总金额, 分摊后总金额, 更新行数)
""" """
# 诊断:写库前查 DB 当前值(用 pymysql 直连,绕过 SQLAlchemy)
try:
import pymysql as _pym
_diag = _pym.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
db=Config.MYSQL_DB, charset='utf8mb4', autocommit=True)
_dc = _diag.cursor()
_cols = [c['column'] for c in field_configs]
_dc.execute(f"SELECT {', '.join(f'SUM({c})' for c in _cols)} FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task_id, month))
_dv = _dc.fetchone()
logger.info(f"[分摊更新-诊断] 写库前 DB sum: {dict(zip(_cols, _dv))}")
_diag.close()
except Exception as _de:
logger.warning(f"[分摊更新-诊断] 写库前查询失败: {_de}")
if not parsed_data: if not parsed_data:
logger.info(f"[分摊更新] 无数据需要处理") logger.info(f"[分摊更新] 无数据需要处理")
return Decimal("0"), Decimal("0"), 0 return Decimal("0"), Decimal("0"), 0, {}
# 1. 加载 biz_budget_achieve 所有行 # 1. 加载 biz_budget_achieve 所有行
table = BizBudgetAchieve.__tablename__ table = BizBudgetAchieve.__tablename__
try: try:
rows = db.session.execute( rows = db.session.execute(
text("SELECT id, traffic_name, business_type, brand, park_store, gmv_ratio FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"), text("SELECT id, traffic_name, business_type, brand, park_store, gmv_ratio, service_provider FROM biz_budget_achieve WHERE task_id=:tid AND stat_month=:sm"),
{"tid": task_id, "sm": month} {"tid": task_id, "sm": month}
).fetchall() ).fetchall()
# 构建索引: (traffic_name, business_type) → [(id, brand, park_store, gmv_ratio), ...] # 构建索引: (traffic_name, business_type) → [(id, brand, park_store, gmv_ratio, is_dijia), ...]
flow_biz_index = {} flow_biz_index = {}
for r in rows: for r in rows:
row_id, traffic_name, business_type, brand, park_store, gmv_ratio = r row_id, traffic_name, business_type, brand, park_store, gmv_ratio, service_provider = r
key = ( _flow = (traffic_name or "").strip()
(traffic_name or "").strip(), _biz = (business_type or "").strip()
(business_type or "").strip() key = (_flow, _biz)
)
if key not in flow_biz_index: if key not in flow_biz_index:
flow_biz_index[key] = [] flow_biz_index[key] = []
flow_biz_index[key].append({ sp = (service_provider or "").strip()
row_info = {
'id': row_id, 'id': row_id,
'brand': (brand or "").strip(), 'brand': (brand or "").strip(),
'park_store': (park_store or "").strip(), 'park_store': (park_store or "").strip(),
'gmv_ratio': Decimal(str(gmv_ratio)) if gmv_ratio is not None else None, 'gmv_ratio': Decimal(str(gmv_ratio)) if gmv_ratio is not None else None,
}) 'is_dijia': "嘀加" in sp,
}
flow_biz_index[key].append(row_info)
logger.info(f"[分摊更新] 加载数据库行: {len(rows)} 条, 索引键: {len(flow_biz_index)} 个") logger.info(f"[分摊更新] 加载数据库行: {len(rows)} 条, 索引键: {len(flow_biz_index)} 个")
except Exception as e: except Exception as e:
...@@ -5114,11 +5378,16 @@ class DataProcessor: ...@@ -5114,11 +5378,16 @@ class DataProcessor:
total_input = Decimal("0") total_input = Decimal("0")
total_output = Decimal("0") total_output = Decimal("0")
updated_count = 0 updated_count = 0
conn = db.engine.connect() # 分字段统计 skip 金额(无匹配 DB 行导致钱丢失 → 需合并进 unmatched)
skipped_by_col = {cfg['column']: Decimal("0") for cfg in field_configs}
# 用 pymysql 直连(绕过 SQLAlchemy 在 Flask app context 下的事务管理问题)
import pymysql as _pym
_write_conn = _pym.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
db=Config.MYSQL_DB, charset='utf8mb4', autocommit=False)
_write_cur = _write_conn.cursor()
try: try:
trans = conn.begin()
for data_key, value in parsed_data.items(): for data_key, value in parsed_data.items():
# 解析 key # 解析 key
if isinstance(data_key, tuple) and len(data_key) >= 2: if isinstance(data_key, tuple) and len(data_key) >= 2:
...@@ -5146,73 +5415,105 @@ class DataProcessor: ...@@ -5146,73 +5415,105 @@ class DataProcessor:
db_rows = flow_biz_index.get((flow_name, biz_type), []) db_rows = flow_biz_index.get((flow_name, biz_type), [])
if not db_rows: if not db_rows:
logger.warning(f"[{label}] 未找到匹配的数据库行: flow={flow_name}, biz={biz_type}") logger.warning(f"[{label}] 未找到匹配的数据库行: flow={flow_name}, biz={biz_type}, 跳过金额={field_value}")
skipped_by_col[column] += field_value
continue continue
# 按 gmv_ratio 分摊(支持混合场景) # === 规则2验证 + 服务商过滤层 ===
valid_rows = [(i, r) for i, r in enumerate(db_rows) if r['gmv_ratio'] is not None and r['gmv_ratio'] > 0] # 优先使用嘀加 brand 行;只有全是非嘀加时才回退全量
none_ratio_rows = [(i, r) for i, r in enumerate(db_rows) if r['gmv_ratio'] is None or r['gmv_ratio'] <= 0] dijia_rows = [r for r in db_rows if r.get('is_dijia')]
if dijia_rows:
target_rows = dijia_rows
else:
target_rows = db_rows
# 规则2验证日志:多条记录 + 嘀加过滤
if len(db_rows) > 1:
logger.info(f"[规则2命中] flow={flow_name}, biz={biz_type}, DB 原始行={len(db_rows)}, "
f"嘀加行={len(dijia_rows)}, 最终 target={len(target_rows)}, 金额={field_value}")
# === 规则4外援施工专属验证日志 ===
if label == "外援施工费":
excluded = len(db_rows) - len(dijia_rows)
logger.info(f"[外援施工费·规则4命中] flow={flow_name}, biz={biz_type}, "
f"DB原始行={len(db_rows)}, 嘀加行={len(dijia_rows)}, "
f"非嘀加行排除={excluded}, 最终target={len(target_rows)}, 金额={field_value}")
# 在 target_rows 内按 gmv_ratio 分摊(比例需重新归一化到 sum=1)
valid_rows = [(i, r) for i, r in enumerate(target_rows) if r['gmv_ratio'] is not None and r['gmv_ratio'] > 0]
none_ratio_rows = [(i, r) for i, r in enumerate(target_rows) if r['gmv_ratio'] is None or r['gmv_ratio'] <= 0]
if valid_rows and none_ratio_rows: if valid_rows and none_ratio_rows:
# 混合场景:有比例行 + 无比例行 # 混合场景:有比例行 + 无比例行
total_valid_ratio = sum((r['gmv_ratio'] for _, r in valid_rows), Decimal("0")) # 先归一化 valid_rows 的 gmv_ratio 到 sum=1
remaining_ratio = Decimal("1") - total_valid_ratio raw_total = sum((r['gmv_ratio'] for _, r in valid_rows), Decimal("0"))
remaining_amount = field_value * remaining_ratio if raw_total > 0:
allocated = Decimal("0")
allocated = Decimal("0") for idx, (i, row_info) in enumerate(valid_rows):
for idx, (i, row_info) in enumerate(valid_rows): normalized_r = row_info['gmv_ratio'] / raw_total
gmv_ratio = row_info['gmv_ratio'] if idx == len(valid_rows) - 1:
if idx == len(valid_rows) - 1: share = round_2(field_value - allocated)
share = round_2(field_value - allocated)
else:
share = round_2(field_value * gmv_ratio)
allocated += share
row_info['_share'] = share
if none_ratio_rows:
per_row = remaining_amount / len(none_ratio_rows)
for idx, (i, row_info) in enumerate(none_ratio_rows):
if idx == len(none_ratio_rows) - 1:
row_info['_share'] = round_2(remaining_amount - per_row * (len(none_ratio_rows) - 1))
else: else:
row_info['_share'] = round_2(per_row) share = round_2(field_value * normalized_r)
allocated += share
row_info['_share'] = share
# none_ratio_rows 平均分配剩余
remaining_amount = field_value - allocated
if remaining_amount > 0 and none_ratio_rows:
per_row = remaining_amount / len(none_ratio_rows)
for idx, (i, row_info) in enumerate(none_ratio_rows):
if idx == len(none_ratio_rows) - 1:
row_info['_share'] = round_2(remaining_amount - per_row * (len(none_ratio_rows) - 1))
else:
row_info['_share'] = round_2(per_row)
elif valid_rows: elif valid_rows:
# 所有行都有 gmv_ratio # 所有行都有 gmv_ratio → 归一化后分配
allocated = Decimal("0") raw_total = sum((r['gmv_ratio'] for _, r in valid_rows), Decimal("0"))
for i, row_info in enumerate(db_rows): if raw_total > 0:
gmv_ratio = row_info['gmv_ratio'] allocated = Decimal("0")
if i == len(db_rows) - 1: for idx, (_, row_info) in enumerate(valid_rows):
share = round_2(field_value - allocated) normalized_r = row_info['gmv_ratio'] / raw_total
else: if idx == len(valid_rows) - 1:
share = round_2(field_value * gmv_ratio) share = round_2(field_value - allocated)
allocated += share else:
row_info['_share'] = share share = round_2(field_value * normalized_r)
allocated += share
row_info['_share'] = share
else:
# raw_total=0 回退均分
per_row = field_value / len(target_rows)
for idx, row_info in enumerate(target_rows):
if idx == len(target_rows) - 1:
row_info['_share'] = round_2(field_value - per_row * (len(target_rows) - 1))
else:
row_info['_share'] = round_2(per_row)
else: else:
# 无 gmv_ratio,回退均分 # 无 gmv_ratio,回退均分
allocated = Decimal("0") allocated = Decimal("0")
for i, row_info in enumerate(db_rows): for i, row_info in enumerate(target_rows):
if i == len(db_rows) - 1: if i == len(target_rows) - 1:
share = round_2(field_value - allocated) share = round_2(field_value - allocated)
else: else:
share = round_2(field_value / len(db_rows)) share = round_2(field_value / len(target_rows))
allocated += share allocated += share
row_info['_share'] = share row_info['_share'] = share
# 执行更新 # 执行更新(只更新有 _share 的 target_rows)
for row_info in db_rows: for row_info in target_rows:
row_id = row_info['id'] row_id = row_info['id']
share = row_info['_share'] share = row_info.get('_share', Decimal("0"))
gmv_ratio = row_info['gmv_ratio']
if share < 0: if share < 0:
share = Decimal("0") share = Decimal("0")
total_output += share total_output += share
conn.execute( # pymysql 方式执行 UPDATE
text(f"UPDATE {table} SET {column}=:val, updated_at=CURRENT_TIMESTAMP WHERE id=:id"), _write_cur.execute(
{'val': float(share), 'id': row_id} f"UPDATE {table} SET {column}=%s, updated_at=CURRENT_TIMESTAMP WHERE id=%s",
(float(share), row_id)
) )
updated_count += 1 updated_count += 1
...@@ -5221,7 +5522,22 @@ class DataProcessor: ...@@ -5221,7 +5522,22 @@ class DataProcessor:
f"brand={row_info['brand']}, ps={row_info['park_store']}, " f"brand={row_info['brand']}, ps={row_info['park_store']}, "
f"gmv_ratio={gmv_ratio}, share={float(share)}") f"gmv_ratio={gmv_ratio}, share={float(share)}")
trans.commit() _write_conn.commit()
_write_conn.close()
# 诊断:写库后查 DB 实际值
try:
import pymysql as _pym2
_diag2 = _pym2.connect(host=Config.MYSQL_HOST, port=int(Config.MYSQL_PORT or 3306),
user=Config.MYSQL_USER, password=Config.MYSQL_PASSWORD,
db=Config.MYSQL_DB, charset='utf8mb4', autocommit=True)
_dc2 = _diag2.cursor()
_dc2.execute(f"SELECT {', '.join(f'SUM({c})' for c in _cols)} FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (task_id, month))
_dv2 = _dc2.fetchone()
logger.info(f"[分摊更新-诊断] 写库后 DB sum: {dict(zip(_cols, _dv2))}")
_diag2.close()
except Exception as _de2:
logger.warning(f"[分摊更新-诊断] 写库后查询失败: {_de2}")
# 3. 验证总量守恒 # 3. 验证总量守恒
diff = total_input - total_output diff = total_input - total_output
...@@ -5230,16 +5546,22 @@ class DataProcessor: ...@@ -5230,16 +5546,22 @@ class DataProcessor:
else: else:
logger.info(f"[{field_configs[0]['label']}] 总量校验通过: 输入={total_input}, 输出={total_output}") logger.info(f"[{field_configs[0]['label']}] 总量校验通过: 输入={total_input}, 输出={total_output}")
logger.info(f"[分摊更新] 完成: 共更新 {updated_count} 行") total_skip = sum(skipped_by_col.values())
logger.info(f"[分摊更新] 完成: 共更新 {updated_count} 行, 跳过(无DB行)={dict(skipped_by_col)}, 合计={total_skip}")
except Exception as e: except Exception as e:
trans.rollback() try:
_write_conn.rollback()
except:
pass
try:
_write_conn.close()
except:
pass
logger.error(f"[分摊更新] 失败: {e}") logger.error(f"[分摊更新] 失败: {e}")
raise raise
finally:
conn.close()
return total_input, total_output, updated_count return total_input, total_output, updated_count, skipped_by_col
def _update_wage_fee_by_id(self, task_id, month, parsed_data): def _update_wage_fee_by_id(self, task_id, month, parsed_data):
"""按 gmv_ratio 分摊外援施工费并按主键id更新""" """按 gmv_ratio 分摊外援施工费并按主键id更新"""
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!