Commit 95156a0c by zhouhaibao

refactor(data-process): 优化市场费分摊逻辑并支持多层级降级策略

- 预构建 2-tuple 索引支持双向查找,提升查询效率
- 实现品牌去重机制避免 to_standard 引入的重复数据
- 移除不必要的品牌记录列表存储结构
- 重构 GMV 匹配逻辑支持原始和标准化流量方双向兼容
- 新增 2-tuple 降级分摊机制当 GMV 数据不可用时按 gmv_ratio 分摊
- 完善未知品牌处理逻辑,支持全未知品牌场景的合理分摊
- 添加分摊比例计算的多级降级策略:gmv_ratio → GMV 值 → 平均分摊
- 实现尾差归并机制确保费用分配精度
- 增强诊断日志输出便于问题排查和验证
1 parent 42cd7484
...@@ -1745,6 +1745,18 @@ class DataProcessor: ...@@ -1745,6 +1745,18 @@ class DataProcessor:
if not records: if not records:
return [] return []
# 预构建 2-tuple 索引:(flow_key, biz) → [(brand, gmv_ratio, GMV)]
# flow_key 同时存原始名和 to_standard 后的值,双向可查
flat_index = defaultdict(list)
for (sf, sb, sbr), data in settlement_map.items():
if not (sf and sb and sbr):
continue
entry = (sbr, data.get("gmv_ratio"), data["GMV"])
flat_index[(sf, sb)].append(entry)
std_f = to_standard(sf, '4s')
if std_f and std_f != sf:
flat_index[(std_f, sb)].append(entry)
# 按 (流量方, 业务类型) 分组 # 按 (流量方, 业务类型) 分组
groups = defaultdict(list) groups = defaultdict(list)
for r in records: for r in records:
...@@ -1753,9 +1765,17 @@ class DataProcessor: ...@@ -1753,9 +1765,17 @@ class DataProcessor:
result = [] result = []
for (flow, biz), group_records in groups.items(): for (flow, biz), group_records in groups.items():
# 取预构建的 flat_entries,并按品牌去重(to_standard 可能引入重复 brand)
raw_entries = flat_index.get((flow, biz), [])
seen_brands = set()
flat_entries = []
for e in raw_entries:
if e[0] not in seen_brands:
seen_brands.add(e[0])
flat_entries.append(e)
# 按品牌汇总费用 # 按品牌汇总费用
brand_fees = defaultdict(Decimal) # {品牌: 费用合计} brand_fees = defaultdict(Decimal) # {品牌: 费用合计}
brand_records = defaultdict(list) # {品牌: [原始记录列表]}
unknown_brand_fee = Decimal("0") # 未知品牌的费用总和 unknown_brand_fee = Decimal("0") # 未知品牌的费用总和
for r in group_records: for r in group_records:
...@@ -1765,7 +1785,6 @@ class DataProcessor: ...@@ -1765,7 +1785,6 @@ class DataProcessor:
unknown_brand_fee += fee unknown_brand_fee += fee
else: else:
brand_fees[brand] += fee brand_fees[brand] += fee
brand_records[brand].append(r)
# 诊断日志:分摊前的品牌费用(仅针对特定流量方) # 诊断日志:分摊前的品牌费用(仅针对特定流量方)
if "广西恒为" in flow or "恒为" in flow: if "广西恒为" in flow or "恒为" in flow:
...@@ -1776,14 +1795,17 @@ class DataProcessor: ...@@ -1776,14 +1795,17 @@ class DataProcessor:
# 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊 # 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
if unknown_brand_fee > 0 and brand_fees: if unknown_brand_fee > 0 and brand_fees:
# 获取各品牌的 GMV # 获取各品牌的 GMV —— 只统计真能 3-tuple 匹配上的品牌
# 匹配不上的品牌(如 identify_brand 输出"赛力斯"但数据库没有)不纳入分母
brand_gmv = {} brand_gmv = {}
for brand in brand_fees.keys(): for brand in brand_fees.keys():
key = (flow, biz, brand) # 先试原始 flow,再试 to_standard 后的值(双向兼容)
if key in settlement_map: data = settlement_map.get((flow, biz, brand))
brand_gmv[brand] = settlement_map[key]["GMV"] if not data:
else: std_f = to_standard(flow, '4s')
brand_gmv[brand] = Decimal("0") if std_f and std_f != flow:
data = settlement_map.get((std_f, biz, brand))
brand_gmv[brand] = data["GMV"] if data else Decimal("0")
total_gmv = sum(brand_gmv.values()) total_gmv = sum(brand_gmv.values())
...@@ -1817,12 +1839,19 @@ class DataProcessor: ...@@ -1817,12 +1839,19 @@ class DataProcessor:
if "广西恒为" in flow or "恒为" in flow: if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}") logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}")
else: else:
# GMV 都为 0,平均分摊 # total_gmv=0 说明 brand_fees 里没有任何品牌能 3-tuple 匹配上
# 降级:用 2-tuple 查 settlement_map 全量,按 gmv_ratio 分摊
if flat_entries:
self._append_split_result(result, flow, biz, None, unknown_brand_fee, flat_entries)
if "广西恒为" in flow or "恒为" in flow:
db_brands = [e[0] for e in flat_entries]
logger.info(f"[市场费诊断] 2-tuple降级分摊: flat_entries={db_brands}, fee={unknown_brand_fee}")
else:
# settlement_map 也没数据,真的只能平均分摊到 brand_fees
n = len(brand_fees) n = len(brand_fees)
avg_fee = (unknown_brand_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) avg_fee = (unknown_brand_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for brand in brand_fees.keys(): for brand in brand_fees.keys():
brand_fees[brand] += avg_fee brand_fees[brand] += avg_fee
# 尾差归并
allocated_sum = avg_fee * n allocated_sum = avg_fee * n
diff = unknown_brand_fee - allocated_sum diff = unknown_brand_fee - allocated_sum
if diff != 0: if diff != 0:
...@@ -1844,8 +1873,15 @@ class DataProcessor: ...@@ -1844,8 +1873,15 @@ class DataProcessor:
"市场费": round_2(fee), "市场费": round_2(fee),
}) })
# 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留 # 处理:如果所有记录都是未知品牌(无已知品牌),用 2-tuple 查全量按 gmv_ratio 分摊
if not brand_fees and unknown_brand_fee > 0: if not brand_fees and unknown_brand_fee > 0:
if flat_entries:
self._append_split_result(result, flow, biz, None, unknown_brand_fee, flat_entries)
if "广西恒为" in flow or "恒为" in flow:
db_brands = [e[0] for e in flat_entries]
logger.info(f"[市场费诊断] 全未知品牌, 2-tuple分摊: flat_entries={db_brands}, fee={unknown_brand_fee}")
else:
# settlement_map 也没数据,原样保留
result.append({ result.append({
"流量方名称": flow, "流量方名称": flow,
"业务类型": biz, "业务类型": biz,
...@@ -1856,6 +1892,74 @@ class DataProcessor: ...@@ -1856,6 +1892,74 @@ class DataProcessor:
logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录") logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录")
return result return result
@staticmethod
def _append_split_result(result, flow, biz, fixed_brand, total_fee, entries):
"""
将 total_fee 按比例分摊到 entries 的各品牌,追加到 result。
比例优先级:gmv_ratio 归一化 → GMV 值归一化 → 平均分摊
Args:
result: 待追加的结果列表
flow: 流量方
biz: 业务类型
fixed_brand: 若不为 None,所有输出用这个品牌;若为 None 用 entries 里的品牌
total_fee: 待分摊的总费用
entries: [(brand, gmv_ratio_float_or_None, GMV_Decimal), ...]
"""
n = len(entries)
if n == 0:
return
# 判断是否有可用的 gmv_ratio(全部 None 就降级)
ratios = []
has_ratio = False
for (br, rt, gmv) in entries:
if rt is not None:
ratios.append(Decimal(str(rt)))
has_ratio = True
else:
ratios.append(Decimal("0"))
if has_ratio:
total_ratio = sum(ratios)
if total_ratio > 0:
for i, (br, rt, gmv) in enumerate(entries):
allocated = (total_fee * ratios[i] / total_ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
# 尾差归并到最后一条
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 降级:用 GMV 值
gmv_total = sum(gmv for (_, _, gmv) in entries)
if gmv_total > 0:
for (br, rt, gmv) in entries:
allocated = (total_fee * gmv / gmv_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 最终降级:平均分摊
avg = (total_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for (br, rt, gmv) in entries:
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": avg})
allocated_sum = avg * n
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
# ======================================================== # ========================================================
# 解析市场费表 # 解析市场费表
# ======================================================== # ========================================================
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!