Commit 9aaa43b4 by zhouhaibao

feat(data-process): 新增房租水电费用按GMV分摊功能

- 添加parse_allocation_targets函数解析分账目标字符串
- 实现query_gmv_by_targets函数按流量方和园区店查询GMV数据
- 新增allocate_by_gmv_ratio函数按GMV占比分配费用
- 添加update_rent_utilities函数更新房租水电费用到数据库
- 实现detect_merged_cells函数检测合并单元格处理多对象分摊
- 在_parse_utility_fee方法中集成GMV分摊逻辑和合并行处理
- 支持多对象同时分摊和独立费用行分别处理
- 添加详细的日志记录和调试信息便于问题排查
- 优化数据库更新逻辑确保分摊结果准确写入
1 parent a78bb9a6
...@@ -312,6 +312,340 @@ def pct(numerator, denominator): ...@@ -312,6 +312,340 @@ def pct(numerator, denominator):
return result return result
def parse_allocation_targets(target_str, flow_names_set, park_to_flows):
if not target_str or not str(target_str).strip():
return []
separators = [',', ',', '、', ';', ';', '\n', '\r']
normalized = str(target_str).strip()
for sep in separators[1:]:
normalized = normalized.replace(sep, separators[0])
parts = [p.strip() for p in normalized.split(separators[0]) if p.strip()]
targets = []
for part in parts:
std_part = to_standard(part, '4s')
if std_part in flow_names_set or part in flow_names_set:
targets.append({
'name': part,
'type': 'flow',
'std_name': std_part
})
elif part in park_to_flows or to_standard(part, 'yq') in park_to_flows:
targets.append({
'name': part,
'type': 'park',
'std_name': to_standard(part, 'yq')
})
else:
targets.append({
'name': part,
'type': 'flow',
'std_name': std_part
})
return targets
def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names=None):
from sqlalchemy import text, bindparam
result = {}
if flow_names:
# 使用 bindparam expanding=True 支持 IN 子句的列表参数(SQLAlchemy 2.0 兼容)
sql = text("""
SELECT traffic_name, SUM(gmv) as total_gmv
FROM biz_budget_achieve
WHERE traffic_name IN :names
AND task_id = :task_id
AND business_type = :biz_type
GROUP BY traffic_name
""").bindparams(bindparam("names", expanding=True))
params = {"names": flow_names, "task_id": task_id, "biz_type": business_type}
try:
rows = db.session.execute(sql, params).fetchall()
for row in rows:
result[row[0]] = float(row[1]) if row[1] else 0
except Exception as e:
logger.error(f"[GMV查询] 流量方GMV查询失败: {e}")
if park_names:
# 使用 bindparam expanding=True 支持 IN 子句的列表参数(SQLAlchemy 2.0 兼容)
sql = text("""
SELECT park_store, SUM(gmv) as total_gmv
FROM biz_budget_achieve
WHERE park_store IN :names
AND task_id = :task_id
AND business_type = :biz_type
GROUP BY park_store
""").bindparams(bindparam("names", expanding=True))
params = {"names": park_names, "task_id": task_id, "biz_type": business_type}
try:
rows = db.session.execute(sql, params).fetchall()
for row in rows:
result[row[0]] = float(row[1]) if row[1] else 0
except Exception as e:
logger.error(f"[GMV查询] 园区店GMV查询失败: {e}")
for name in (flow_names or []):
if name not in result:
result[name] = 0
for name in (park_names or []):
if name not in result:
result[name] = 0
return result
def allocate_by_gmv_ratio(total_fee, targets, gmv_data):
"""
按 GMV 占比分摊费用
用户需求示例:
假设A+B分账总和20000,Agmv占比40%,B占比60%
A ---8000 B ----12000
"""
if not targets or total_fee == 0:
return []
if len(targets) == 1:
logger.info(f"[GMV分摊计算] 单对象: name={targets[0]['name']}, type={targets[0]['type']}, share={total_fee}, ratio=1.0")
return [{
'name': targets[0]['name'],
'type': targets[0]['type'],
'share': total_fee,
'ratio': 1.0
}]
total_gmv = 0
gmv_details = []
for t in targets:
gmv = gmv_data.get(t['name'], gmv_data.get(t.get('std_name', ''), 0))
total_gmv += gmv
gmv_details.append(f"{t['name']}={gmv}")
logger.info(f"[GMV分摊计算] total_fee={total_fee}, targets={len(targets)}, total_gmv={total_gmv}, gmv_details=[{', '.join(gmv_details)}]")
results = []
if total_gmv > 0:
allocated = Decimal("0")
for i, t in enumerate(targets):
gmv = gmv_data.get(t['name'], gmv_data.get(t.get('std_name', ''), 0))
ratio = gmv / total_gmv if total_gmv > 0 else 0
if i == len(targets) - 1:
share = total_fee - allocated
else:
share = round_2(total_fee * Decimal(str(ratio)))
allocated += share
results.append({
'name': t['name'],
'type': t['type'],
'share': share,
'ratio': ratio
})
logger.info(f"[GMV分摊计算] target[{i}]: name={t['name']}, gmv={gmv}, ratio={ratio:.4f}, share={share}")
else:
flow_count = len(targets)
logger.warning(f"[GMV分摊计算] total_gmv=0, 平均分配给{flow_count}个对象")
for i, t in enumerate(targets):
if i == flow_count - 1:
share = total_fee - sum(r['share'] for r in results)
else:
share = round_2(total_fee / flow_count)
results.append({
'name': t['name'],
'type': t['type'],
'share': share,
'ratio': 1.0 / flow_count
})
logger.info(f"[GMV分摊计算] target[{i}]: name={t['name']}, share={share}")
total_share = sum(r['share'] for r in results)
logger.info(f"[GMV分摊计算] 分摊汇总: total_fee={total_fee}, total_share={total_share}, diff={total_fee - total_share}")
return results
def update_rent_utilities(db, task_id, business_type, target_name, target_type, allocation_result):
from sqlalchemy import text
share = allocation_result.get('share', Decimal('0'))
if target_type == 'flow':
query_sql = text("""
SELECT id, gmv_ratio
FROM biz_budget_achieve
WHERE traffic_name = :traffic_name
AND business_type = :biz_type
AND task_id = :task_id
AND gmv_ratio IS NOT NULL
""")
params = {"traffic_name": target_name, "biz_type": business_type, "task_id": task_id}
else:
query_sql = text("""
SELECT id, gmv_ratio
FROM biz_budget_achieve
WHERE park_store = :park_store
AND business_type = :biz_type
AND task_id = :task_id
AND gmv_ratio IS NOT NULL
""")
params = {"park_store": target_name, "biz_type": business_type, "task_id": task_id}
try:
rows = db.session.execute(query_sql, params).fetchall()
updated_count = 0
for row in rows:
row_id, gmv_ratio = row
if gmv_ratio is not None:
rent_utilities = share * Decimal(str(gmv_ratio))
update_sql = text("""
UPDATE biz_budget_achieve
SET rent_utilities = :rent_utilities
WHERE id = :row_id
""")
db.session.execute(update_sql, {"rent_utilities": rent_utilities, "row_id": row_id})
updated_count += 1
logger.info(f"[房租水电更新] id={row_id}, target={target_name}, share={share}, gmv_ratio={gmv_ratio}, rent_utilities={rent_utilities}")
return updated_count
except Exception as e:
logger.error(f"[房租水电更新] 更新失败: {e}")
return 0
def detect_merged_cells(df, row_idx, rent_col, water_col, construction_col, target_col=None):
"""
检测指定行是否为合并行(房租、水电、施工费用任意一列是合并单元格)。
合并行检测逻辑(修复版):
1. 检查当前行的费用列是否有值
2. 向下扫描,检查「费用列是否为空」作为合并判断依据
3. 若后续行「所有费用列都为空」,则是合并行延续
4. 若后续行「任何费用列有值」,则是独立费用行,停止扫描
5. 合并行延续的分账对象列通常有值(每个分账对象对应一行)
Args:
df: DataFrame
row_idx: 当前行索引
rent_col: 房租费用列名
water_col: 水电费列名
construction_col: 施工费用列名
target_col: 分账对象列名(可选)
Returns:
dict: {
'is_merged': bool, # 是否为合并行
'merged_cols': list, # 合并的列名列表
'merged_row_count': int, # 合并了多少行
'independent_row_indices': list # 独立费用行的索引列表
}
"""
# 收集所有费用列
fee_cols = []
for col, col_name in [(rent_col, '房租费用'), (water_col, '水电费'), (construction_col, '施工费用')]:
if col:
fee_cols.append((col, col_name))
if not fee_cols or row_idx >= len(df) - 1:
return {
'is_merged': False,
'merged_cols': [],
'merged_row_count': 1,
'independent_row_indices': []
}
# 检查当前行是否有费用
current_has_fee = False
for col, col_name in fee_cols:
val = df.iloc[row_idx][col]
if pd.notna(val) and str(val).strip() not in ('', 'nan', 'None'):
current_has_fee = True
break
if not current_has_fee:
return {
'is_merged': False,
'merged_cols': [],
'merged_row_count': 1,
'independent_row_indices': []
}
# 核心逻辑:基于「费用列是否为空」判断合并行
# 向下扫描,找出合并行范围和独立费用行
merged_count = 1 # 当前行算1行
independent_row_indices = [] # 独立费用行索引
# 安全限制:最多扫描 5 行
max_scan = 5
scan_limit = min(row_idx + max_scan + 1, len(df))
for check_idx in range(row_idx + 1, scan_limit):
# 检查该行的费用列是否有值
row_has_any_fee = any(
pd.notna(df.iloc[check_idx][col]) and str(df.iloc[check_idx][col]).strip() not in ('', 'nan', 'None')
for col, _ in fee_cols
)
if row_has_any_fee:
# 该行有费用,是独立费用行,停止扫描
independent_row_indices.append(check_idx)
break
else:
# 该行所有费用列为空,是合并行延续
merged_count += 1
# 安全限制:最多合并5行
MAX_MERGED_ROWS = 5
if merged_count > MAX_MERGED_ROWS:
merged_count = MAX_MERGED_ROWS
# 如果独立行索引超出限制,移除超出部分
independent_row_indices = [idx for idx in independent_row_indices if idx <= row_idx + MAX_MERGED_ROWS]
# 只有检测到合并延续行(merged_count > 1)才认为是合并行
is_merged = merged_count > 1
merged_row_count = merged_count if is_merged else 1
# 构建合并列信息(仅当是合并行时)
merged_cols = []
if is_merged:
for col, col_name in fee_cols:
current_val = df.iloc[row_idx][col]
if pd.notna(current_val) and str(current_val).strip() not in ('', 'nan', 'None'):
merged_cols.append({
'col': col,
'name': col_name,
'merged_count': merged_count
})
# 诊断日志:合并行检测结果
if is_merged:
logger.debug(f"[房租水电][合并行检测] 行{row_idx}: is_merged=True, merged_count={merged_count}, "
f"independent_indices={independent_row_indices}, "
f"fee_cols_with_values={[m['name'] for m in merged_cols]}")
return {
'is_merged': is_merged,
'merged_cols': merged_cols,
'merged_row_count': merged_row_count,
'independent_row_indices': independent_row_indices
}
def detect_header_row(df_raw, max_scan=15): def detect_header_row(df_raw, max_scan=15):
""" """
自动检测 Excel 表头行位置。 自动检测 Excel 表头行位置。
...@@ -1187,9 +1521,10 @@ class DataProcessor: ...@@ -1187,9 +1521,10 @@ class DataProcessor:
# 解析房租水电施工费 # 解析房租水电施工费
utility_results = [] utility_results = []
gmv_allocated_utility = []
if '房租水电费用表' in downloaded_files: if '房租水电费用表' in downloaded_files:
utility_results = 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) utility_results, gmv_allocated_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)} 条记录") logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条")
logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s") logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")
# ========== 步骤 d: 执行成本计算 ========== # ========== 步骤 d: 执行成本计算 ==========
...@@ -1222,15 +1557,18 @@ class DataProcessor: ...@@ -1222,15 +1557,18 @@ class DataProcessor:
# 市场费直接使用 market_results,不通过 summary_data 提取(避免重复计算) # 市场费直接使用 market_results,不通过 summary_data 提取(避免重复计算)
market_fee_data = [r for r in market_results if r.get("市场费", Decimal("0")) > 0] market_fee_data = [r for r in market_results if r.get("市场费", Decimal("0")) > 0]
utility_fee_data = [r for r in summary_data if r.get("房租及水电费", Decimal("0")) > 0] utility_fee_data = [r for r in summary_data if r.get("房租及水电费", Decimal("0")) > 0]
# 合并GMV分摊的记录,这些记录绕过了_build_cost_summary
all_utility_data = utility_fee_data + gmv_allocated_utility
logger.info(f"[处理任务] 各费用类型数据量: 市场费={len(market_fee_data)}, " logger.info(f"[处理任务] 各费用类型数据量: 市场费={len(market_fee_data)}, "
f"房租水电费={len(utility_fee_data)}") f"房租水电费={len(utility_fee_data)}+GMV分摊={len(gmv_allocated_utility)}")
# 依次执行各独立更新 # 依次执行各独立更新
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 utility_fee_data: if all_utility_data:
self._update_utility_fee_to_db(task.id, task.month, utility_fee_data) self._update_utility_fee_to_db(task.id, task.month, all_utility_data)
# 人员工资汇总值和占比更新(按主键ID直接更新,在所有金额数据落库后执行) # 人员工资汇总值和占比更新(按主键ID直接更新,在所有金额数据落库后执行)
self._update_labor_ratios_by_id(task.id, task.month) self._update_labor_ratios_by_id(task.id, task.month)
...@@ -2279,7 +2617,7 @@ class DataProcessor: ...@@ -2279,7 +2617,7 @@ class DataProcessor:
# 解析房租水电施工费表 # 解析房租水电施工费表
# ======================================================== # ========================================================
def _parse_utility_fee(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None): def _parse_utility_fee(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None, task_id=None):
""" """
解析房租水电施工费表。 解析房租水电施工费表。
规则: 规则:
...@@ -2288,6 +2626,7 @@ class DataProcessor: ...@@ -2288,6 +2626,7 @@ class DataProcessor:
- 取"房租费用+水电费+施工费用"合计 - 取"房租费用+水电费+施工费用"合计
- 回退策略:匹配失败时按"分账对象"匹配"园区店" - 回退策略:匹配失败时按"分账对象"匹配"园区店"
- 多条记录按GMV分摊 - 多条记录按GMV分摊
- 支持多对象GMV分摊(task_id提供时启用)
返回:List[dict],每行 {流量方名称, 业务类型, 房租及水电费} 返回:List[dict],每行 {流量方名称, 业务类型, 房租及水电费}
""" """
logger.info(f"[房租水电] 解析文件: {file_path}") logger.info(f"[房租水电] 解析文件: {file_path}")
...@@ -2302,9 +2641,6 @@ class DataProcessor: ...@@ -2302,9 +2641,6 @@ class DataProcessor:
if flow_ratio_entries is None: if flow_ratio_entries is None:
flow_ratio_entries = {} flow_ratio_entries = {}
# 诊断日志:检查 park_rows_data
logger.info(f"[房租水电][DEBUG] park_rows_data: type={type(park_rows_data)}, value={park_rows_data[:2] if park_rows_data else 'None'}")
# 构建索引 # 构建索引
flow_names_set = set() flow_names_set = set()
flow_ratios = defaultdict(list) flow_ratios = defaultdict(list)
...@@ -2366,15 +2702,6 @@ class DataProcessor: ...@@ -2366,15 +2702,6 @@ class DataProcessor:
gmv_ratio_park = data.get("gmv_ratio_park") gmv_ratio_park = data.get("gmv_ratio_park")
flow_ratios[(std_flow, biz_type)].append((brand, gmv_ratio, gmv_ratio_park, data.get("park_store_raw", ""))) flow_ratios[(std_flow, biz_type)].append((brand, gmv_ratio, gmv_ratio_park, data.get("park_store_raw", "")))
# 诊断日志:检查 flow_ratios 中的数据
target_flow = '龙联汽车科技(深圳)有限公司'
std_target_flow = to_standard(target_flow, '4s')
target_key = (std_target_flow, '1.1')
if target_key in flow_ratios:
logger.info(f"[房租水电] flow_ratios[{target_key}]: {len(flow_ratios[target_key])} 条记录")
for brand, gmv_ratio, gmv_ratio_park, ps in flow_ratios[target_key]:
logger.info(f"[房租水电] brand={brand}, park_store={ps}, gmv_ratio={gmv_ratio}, gmv_ratio_park={gmv_ratio_park}")
logger.info(f"[房租水电] settlement_map 索引: {len(flow_names_set)} 个流量方, {len(park_to_flows)} 个园区店, " logger.info(f"[房租水电] settlement_map 索引: {len(flow_names_set)} 个流量方, {len(park_to_flows)} 个园区店, "
f"flow_ratios={len(flow_ratios)}, park_rows={len(park_rows)}") f"flow_ratios={len(flow_ratios)}, park_rows={len(park_rows)}")
if flow_ratios: if flow_ratios:
...@@ -2383,20 +2710,6 @@ class DataProcessor: ...@@ -2383,20 +2710,6 @@ class DataProcessor:
gmv_ratio_count = sum(1 for rows in flow_ratios.values() for _, gmv_ratio, _, _ in rows if gmv_ratio is not None) gmv_ratio_count = sum(1 for rows in flow_ratios.values() for _, gmv_ratio, _, _ in rows if gmv_ratio is not None)
logger.info(f"[房租水电] flow_ratios 中有gmv_ratio的行数: {gmv_ratio_count}") logger.info(f"[房租水电] flow_ratios 中有gmv_ratio的行数: {gmv_ratio_count}")
# 诊断日志:检查龙联汽车科技的比例数据
target_flow = '龙联汽车科技(深圳)有限公司'
std_target_flow = to_standard(target_flow, '4s')
logger.info(f"[房租水电] 诊断: 检查'{target_flow}'在flow_ratios中的数据")
logger.info(f"[房租水电] 标准化名称: '{std_target_flow}'")
# 查找所有匹配的 key
matching_keys = [(k, v) for k, v in flow_ratios.items() if std_target_flow in str(k[0]) or target_flow in str(k[0])]
logger.info(f"[房租水电] 匹配的key数量: {len(matching_keys)}")
for key, rows in matching_keys:
logger.info(f"[房租水电] key={key}, 行数={len(rows)}")
for brand, gmv_ratio, gmv_ratio_park, park_store_raw in rows:
logger.info(f"[房租水电] brand={brand}, gmv_ratio={gmv_ratio}, gmv_ratio_park={gmv_ratio_park}, park_store={park_store_raw}")
# 解密并读取 Excel # 解密并读取 Excel
actual_path, is_decrypted = decrypt_excel_if_needed(file_path) actual_path, is_decrypted = decrypt_excel_if_needed(file_path)
try: try:
...@@ -2408,6 +2721,7 @@ class DataProcessor: ...@@ -2408,6 +2721,7 @@ class DataProcessor:
return [] return []
raw_records = [] raw_records = []
gmv_allocated_records = [] # GMV分摊的记录,直接传递给数据库更新
direct_match_count = 0 direct_match_count = 0
park_match_count = 0 park_match_count = 0
park_fail_count = 0 park_fail_count = 0
...@@ -2436,9 +2750,9 @@ class DataProcessor: ...@@ -2436,9 +2750,9 @@ class DataProcessor:
col_biz = find_column(df, "业务类型", "业务分类") col_biz = find_column(df, "业务类型", "业务分类")
col_gmv = find_column(df, "GMV", "产值") col_gmv = find_column(df, "GMV", "产值")
logger.info(f"[房租水电] Sheet '{sheet_name}' 列匹配: 分账对象={col_target}, " logger.debug(f"[房租水电] Sheet '{sheet_name}' 列匹配: 分账对象={col_target}, "
f"房租={col_rent}, 水电={col_water}, 施工={col_construction}, " f"房租={col_rent}, 水电={col_water}, 施工={col_construction}, "
f"业务={col_biz}, GMV={col_gmv}") f"业务={col_biz}, GMV={col_gmv}")
# 用于直接匹配的流量方名称集合(已标准化) # 用于直接匹配的流量方名称集合(已标准化)
std_flow_names_set = {to_standard(name, '4s') for name in flow_names_set} std_flow_names_set = {to_standard(name, '4s') for name in flow_names_set}
...@@ -2448,7 +2762,12 @@ class DataProcessor: ...@@ -2448,7 +2762,12 @@ class DataProcessor:
if std_name not in std_to_original_flow: if std_name not in std_to_original_flow:
std_to_original_flow[std_name] = name std_to_original_flow[std_name] = name
for _, row in df.iterrows(): skip_processed_rows = set()
for idx, row in df.iterrows():
if idx in skip_processed_rows:
continue
target = None target = None
if col_target: if col_target:
target = row[col_target] target = row[col_target]
...@@ -2458,6 +2777,11 @@ class DataProcessor: ...@@ -2458,6 +2777,11 @@ class DataProcessor:
target = str(target).strip() target = str(target).strip()
std_target = to_standard(target, '4s') std_target = to_standard(target, '4s')
# 检测是否为合并行(房租、水电、施工费用列存在合并单元格)
# 传入 col_target 用于判定真实合并(后续行分账对象为空才算合并)
merged_info = detect_merged_cells(df, idx, col_rent, col_water, col_construction, col_target)
is_merged_row = merged_info['is_merged']
# 仅统计 1.1 业务 # 仅统计 1.1 业务
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 ""
...@@ -2473,6 +2797,214 @@ class DataProcessor: ...@@ -2473,6 +2797,214 @@ class DataProcessor:
if total_fee == 0: if total_fee == 0:
continue continue
# 诊断日志:打印每一行原始数据
logger.info(f"[房租水电][原始行] 行{idx}: target='{target}', rent={rent}, water={water}, construction={construction}, total={total_fee}, is_merged={is_merged_row}")
logger.info(f"[房租水电][原始行] 原始Excel数据: {row.to_dict()}")
# 合并行处理:如果当前行是合并行,向下扫描收集所有分账对象
if is_merged_row and merged_info['merged_row_count'] > 1:
collected_targets = []
merged_total_fee = Decimal("0")
skip_rows = set()
independent_rows = [] # 存储有独立费用的行
# 收集当前行的分账对象和费用
if pd.notna(target) and target.strip():
collected_targets.append(target.strip())
merged_total_fee += total_fee
# 从 detect_merged_cells 获取独立费用行索引
independent_indices = merged_info.get('independent_row_indices', [])
# 向下扫描合并行,只收集分账对象
scan_count = merged_info['merged_row_count']
for scan_idx in range(idx + 1, min(idx + scan_count, len(df))):
# 如果是独立费用行,跳过合并处理
if scan_idx in independent_indices:
next_target = df.iloc[scan_idx][col_target] if col_target else None
next_rent = safe_decimal(df.iloc[scan_idx][col_rent]) if col_rent else Decimal("0")
next_water = safe_decimal(df.iloc[scan_idx][col_water]) if col_water else Decimal("0")
next_construction = safe_decimal(df.iloc[scan_idx][col_construction]) if col_construction else Decimal("0")
next_total = next_rent + next_water + next_construction
if next_total > 0:
independent_rows.append({
'idx': scan_idx,
'target': str(next_target).strip() if next_target is not None else '',
'rent': next_rent,
'water': next_water,
'construction': next_construction,
'total': next_total
})
continue
# 合并行延续:收集分账对象
next_target = df.iloc[scan_idx][col_target] if col_target else None
if next_target is not None and pd.notna(next_target) and str(next_target).strip():
next_target_str = str(next_target).strip()
if next_target_str not in collected_targets:
collected_targets.append(next_target_str)
skip_rows.add(scan_idx)
logger.info(f"[房租水电][合并行] 行{idx}: 收集{len(collected_targets)}个分账对象, 总费用={merged_total_fee}, 跳过行={skip_rows}, 独立费用行={len(independent_rows)}")
logger.info(f"[房租水电][合并行] targets详情: {collected_targets}")
# 先处理合并行的分摊
if merged_total_fee > 0 and len(collected_targets) > 1:
# 解析所有收集到的分账对象(用逗号拼接后解析)
combined_target_str = ','.join(collected_targets)
alloc_targets = parse_allocation_targets(combined_target_str, flow_names_set, park_to_flows)
logger.info(f"[房租水电][合并行] 解析后alloc_targets: {alloc_targets}")
if len(alloc_targets) > 1 and task_id:
# 多个分账对象:按 GMV 占比分摊
flow_names_list = [t['name'] for t in alloc_targets if t['type'] == 'flow']
park_names_list = [t['name'] for t in alloc_targets if t['type'] == 'park']
gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1,
flow_names=flow_names_list,
park_names=park_names_list)
logger.info(f"[房租水电][合并行] GMV数据: {gmv_data}")
allocation_results = allocate_by_gmv_ratio(merged_total_fee, alloc_targets, gmv_data)
logger.info(f"[房租水电][合并行] 分摊结果: {allocation_results}")
if allocation_results:
for alloc in allocation_results:
gmv_allocated_records.append({
"流量方名称": alloc['name'],
"业务类型": BIZ_TYPE_1_1,
"品牌": "",
"房租及水电费": alloc['share'],
"匹配方式": "gmv_ratio_merged",
"__gmv_allocated__": True,
"target_type": alloc['type'],
})
total_input_fee += merged_total_fee
row_count += 1
logger.info(f"[房租水电][合并行分摊] targets={len(alloc_targets)}, total_fee={merged_total_fee}, results={len(allocation_results)}")
# 处理独立费用行(每个行独立分摊)
for ind_row in independent_rows:
ind_target = ind_row['target']
ind_total = ind_row['total']
if ind_target and ind_total > 0 and task_id:
ind_alloc_targets = parse_allocation_targets(ind_target, flow_names_set, park_to_flows)
if ind_alloc_targets:
ind_flow_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'flow']
ind_park_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'park']
ind_gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1,
flow_names=ind_flow_names,
park_names=ind_park_names)
ind_results = allocate_by_gmv_ratio(ind_total, ind_alloc_targets, ind_gmv_data)
if ind_results:
for ind_alloc in ind_results:
gmv_allocated_records.append({
"流量方名称": ind_alloc['name'],
"业务类型": BIZ_TYPE_1_1,
"品牌": "",
"房租及水电费": ind_alloc['share'],
"匹配方式": "gmv_ratio_independent",
"__gmv_allocated__": True,
"target_type": ind_alloc['type'],
})
total_input_fee += ind_total
row_count += 1
logger.info(f"[房租水电][独立行分摊] target='{ind_target}', fee={ind_total}, results={len(ind_results)}")
continue
elif merged_total_fee > 0 and len(collected_targets) == 1:
# 单个分账对象:直接分配
target_info = alloc_targets[0]
gmv_allocated_records.append({
"流量方名称": target_info['name'],
"业务类型": BIZ_TYPE_1_1,
"品牌": "",
"房租及水电费": merged_total_fee,
"匹配方式": "single_merged",
"__gmv_allocated__": True,
"target_type": target_info['type'],
})
total_input_fee += merged_total_fee
row_count += 1
logger.info(f"[房租水电][合并行单对象] target='{target_info['name']}', fee={merged_total_fee}")
# 处理独立费用行
for ind_row in independent_rows:
ind_target = ind_row['target']
ind_total = ind_row['total']
if ind_target and ind_total > 0 and task_id:
ind_alloc_targets = parse_allocation_targets(ind_target, flow_names_set, park_to_flows)
if ind_alloc_targets:
ind_flow_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'flow']
ind_park_names = [t['name'] for t in ind_alloc_targets if t['type'] == 'park']
ind_gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1,
flow_names=ind_flow_names,
park_names=ind_park_names)
ind_results = allocate_by_gmv_ratio(ind_total, ind_alloc_targets, ind_gmv_data)
if ind_results:
for ind_alloc in ind_results:
gmv_allocated_records.append({
"流量方名称": ind_alloc['name'],
"业务类型": BIZ_TYPE_1_1,
"品牌": "",
"房租及水电费": ind_alloc['share'],
"匹配方式": "gmv_ratio_independent",
"__gmv_allocated__": True,
"target_type": ind_alloc['type'],
})
total_input_fee += ind_total
row_count += 1
logger.info(f"[房租水电][独立行分摊] target='{ind_target}', fee={ind_total}, results={len(ind_results)}")
continue
# GMV分摊路径:当 task_id 提供时,尝试使用 GMV 分摊(非合并行或合并行回退)
gmv_allocated = False
if task_id:
try:
alloc_targets = parse_allocation_targets(target, flow_names_set, park_to_flows)
logger.info(f"[房租水电][GMV分摊路径] 行{idx}: target='{target}', alloc_targets={alloc_targets}")
if alloc_targets:
flow_names = [t['name'] for t in alloc_targets if t['type'] == 'flow']
park_names = [t['name'] for t in alloc_targets if t['type'] == 'park']
gmv_data = query_gmv_by_targets(db, task_id, BIZ_TYPE_1_1, flow_names=flow_names, park_names=park_names)
logger.info(f"[房租水电][GMV分摊路径] GMV数据: {gmv_data}")
allocation_results = allocate_by_gmv_ratio(total_fee, alloc_targets, gmv_data)
logger.info(f"[房租水电][GMV分摊路径] 分摊结果: {allocation_results}")
if allocation_results:
for alloc in allocation_results:
gmv_allocated_records.append({
"流量方名称": alloc['name'],
"业务类型": BIZ_TYPE_1_1,
"品牌": "",
"房租及水电费": alloc['share'],
"匹配方式": "gmv_ratio_allocation",
"__gmv_allocated__": True,
"target_type": alloc['type'],
})
gmv_allocated = True
total_input_fee += total_fee
row_count += 1
merged_flag = " [合并行]" if is_merged_row else ""
logger.info(f"[房租水电][GMV分摊完成]{merged_flag} target='{target}', fee={total_fee}, targets={len(alloc_targets)}, allocated={len(allocation_results)}")
except Exception as e:
logger.warning(f"[房租水电][GMV分摊] 分摊失败,回退原有逻辑: {e}")
if gmv_allocated:
continue
# 获取 GMV # 获取 GMV
gmv = Decimal("0") gmv = Decimal("0")
if col_gmv: if col_gmv:
...@@ -2489,7 +3021,7 @@ class DataProcessor: ...@@ -2489,7 +3021,7 @@ class DataProcessor:
# 诊断日志:前10条记录显示匹配检查结果 # 诊断日志:前10条记录显示匹配检查结果
if row_count <= 10: if row_count <= 10:
logger.info(f"[房租水电] 门店检查: store='{target}', in_park_to_flows={in_park_to_flows}, std_in_park_to_flows={std_in_park_to_flows}, in_flow_names={std_target in std_flow_names_set}") logger.debug(f"[房租水电] 门店检查: store='{target}', in_park_to_flows={in_park_to_flows}, std_in_park_to_flows={std_in_park_to_flows}, in_flow_names={std_target in std_flow_names_set}")
if in_park_to_flows or std_in_park_to_flows: if in_park_to_flows or std_in_park_to_flows:
# 园区店回退桶 - 使用原始值或标准化值匹配 # 园区店回退桶 - 使用原始值或标准化值匹配
...@@ -2510,7 +3042,7 @@ class DataProcessor: ...@@ -2510,7 +3042,7 @@ class DataProcessor:
park_buckets[key] = Decimal("0") park_buckets[key] = Decimal("0")
park_buckets[key] += total_fee park_buckets[key] += total_fee
if park_match_count < 5: if park_match_count < 5:
logger.info(f"[房租水电] 园区店回退匹配成功: store='{target}', ps='{ps}', 方式={match_method}") logger.debug(f"[房租水电] 园区店回退匹配成功: store='{target}', ps='{ps}', 方式={match_method}")
park_match_count += 1 park_match_count += 1
continue # 跳过直接匹配逻辑 continue # 跳过直接匹配逻辑
...@@ -2549,9 +3081,9 @@ class DataProcessor: ...@@ -2549,9 +3081,9 @@ class DataProcessor:
logger.info(f"[房租水电] 聚合完成: {row_count} 行有效, 总输入金额={total_input_fee}") logger.info(f"[房租水电] 聚合完成: {row_count} 行有效, 总输入金额={total_input_fee}")
logger.info(f"[房租水电] 桶统计: direct_buckets={len(direct_buckets)}, park_buckets={len(park_buckets)}") logger.info(f"[房租水电] 桶统计: direct_buckets={len(direct_buckets)}, park_buckets={len(park_buckets)}")
for (k, v) in list(direct_buckets.items())[:3]: for (k, v) in list(direct_buckets.items())[:3]:
logger.info(f"[房租水电] direct_bucket key={k}, fee={v}") logger.debug(f"[房租水电] direct_bucket key={k}, fee={v}")
for (k, v) in list(park_buckets.items())[:3]: for (k, v) in list(park_buckets.items())[:3]:
logger.info(f"[房租水电] park_bucket key={k}, fee={v}") logger.debug(f"[房租水电] park_bucket key={k}, fee={v}")
# 第二阶段:分配 # 第二阶段:分配
...@@ -2729,9 +3261,9 @@ class DataProcessor: ...@@ -2729,9 +3261,9 @@ class DataProcessor:
if failed_stores: if failed_stores:
logger.warning(f"[房租水电] 匹配失败的门店(最多显示10个): {failed_stores}") logger.warning(f"[房租水电] 匹配失败的门店(最多显示10个): {failed_stores}")
if not raw_records: if not raw_records and not gmv_allocated_records:
logger.info("[房租水电] 无有效数据") logger.info("[房租水电] 无有效数据")
return [] return [], []
# 按 (流量方名称, 业务类型, 品牌) 汇总 # 按 (流量方名称, 业务类型, 品牌) 汇总
aggregated = defaultdict(lambda: Decimal("0")) aggregated = defaultdict(lambda: Decimal("0"))
...@@ -2757,8 +3289,14 @@ class DataProcessor: ...@@ -2757,8 +3289,14 @@ class DataProcessor:
) )
logger.info(f"[房租水电] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}") logger.info(f"[房租水电] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}")
logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录") # 打印 GMV 分摊记录详情
return result if gmv_allocated_records:
logger.info(f"[房租水电] GMV分摊记录详情({len(gmv_allocated_records)}条):")
for i, rec in enumerate(gmv_allocated_records):
logger.info(f"[房租水电] GMV记录[{i}]: name={rec['流量方名称']}, fee={rec['房租及水电费']}, type={rec.get('target_type', 'unknown')}, method={rec.get('匹配方式', 'unknown')}")
logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录,GMV分摊 {len(gmv_allocated_records)} 条")
return result, gmv_allocated_records
# ======================================================== # ========================================================
# 构建成本汇总表 # 构建成本汇总表
...@@ -2897,12 +3435,15 @@ class DataProcessor: ...@@ -2897,12 +3435,15 @@ class DataProcessor:
logger.info(f"[成本汇总] 外援施工费聚合: {len(wage_agg)} 个键, 总金额={sum(wage_agg.values())}") logger.info(f"[成本汇总] 外援施工费聚合: {len(wage_agg)} 个键, 总金额={sum(wage_agg.values())}")
utility_agg = defaultdict(lambda: Decimal("0")) utility_agg = defaultdict(lambda: Decimal("0"))
utility_gmv_allocated = set() # 记录已GMV分摊的键,避免重复分摊
for u in utility_results: for u in utility_results:
if u.get("__park_store__"): if u.get("__park_store__"):
continue continue
brand = u.get("品牌", "") or "" brand = u.get("品牌", "") or ""
key = (u["流量方名称"].strip(), u["业务类型"].strip(), brand.strip() if brand else "") key = (u["流量方名称"].strip(), u["业务类型"].strip(), brand.strip() if brand else "")
utility_agg[key] += u["房租及水电费"] utility_agg[key] += u["房租及水电费"]
if u.get("__gmv_allocated__"):
utility_gmv_allocated.add(key)
# ---------- 过滤无效品牌 ---------- # ---------- 过滤无效品牌 ----------
original_key_count = len(all_keys) original_key_count = len(all_keys)
...@@ -3116,6 +3657,9 @@ class DataProcessor: ...@@ -3116,6 +3657,9 @@ class DataProcessor:
utility_key = (flow_name, biz_type, brand) utility_key = (flow_name, biz_type, brand)
if utility_key in utility_agg: if utility_key in utility_agg:
utility_fee = utility_agg[utility_key] utility_fee = utility_agg[utility_key]
# 标记已GMV分摊的记录,避免在_update_utility_fee_to_db中重复分摊
if utility_key in utility_gmv_allocated:
row["__gmv_allocated__"] = True
# 多园区店二次分摊 # 多园区店二次分摊
park_count = brand_park_counts.get((flow_name, biz_type, brand), 1) park_count = brand_park_counts.get((flow_name, biz_type, brand), 1)
if park_count > 1 and park_store: if park_count > 1 and park_store:
...@@ -3127,7 +3671,7 @@ class DataProcessor: ...@@ -3127,7 +3671,7 @@ class DataProcessor:
utility_fee = utility_fee / park_count utility_fee = utility_fee / park_count
row["房租及水电费"] += round_2(utility_fee) row["房租及水电费"] += round_2(utility_fee)
if is_target_flow: if is_target_flow:
logger.info(f"[房租水电分摊] flow={flow_name}, brand={brand}, ps={park_store}, utility_fee={utility_fee}") logger.info(f"[房租水电分摊] flow={flow_name}, brand={brand}, ps={park_store}, utility_fee={utility_fee}, gmv_allocated={utility_key in utility_gmv_allocated}")
# 计算人员工资小计 # 计算人员工资小计
# 人员工资 = 外援施工 + 技师工资 + 营销团队工资 # 人员工资 = 外援施工 + 技师工资 + 营销团队工资
...@@ -3886,6 +4430,68 @@ class DataProcessor: ...@@ -3886,6 +4430,68 @@ class DataProcessor:
return updated_count return updated_count
def _update_rent_utilities_by_target(self, conn, table, task_id, month, target_name, business_type, fee, target_type):
"""
按目标类型(流量方/园区店)查询匹配行,并用 分账结果 * gmv_ratio 更新数据库
符合用户需求:
1. 根据目标类型查询 biz_budget_achieve 表(不关联品牌)
2. 获取 id, gmv_ratio
3. 更新 rent_utilities = 分账结果 * gmv_ratio
用户SQL示例:
SELECT id, gmv_ratio FROM biz_budget_achieve
WHERE traffic_name IN (?) AND business_type = ? AND task_id = ?
UPDATE biz_budget_achieve SET rent_utilities = 分账结果 * gmv_ratio WHERE id = ?
"""
from sqlalchemy import text
updated_count = 0
if target_type == 'flow':
# 流量方查询(不关联品牌)
query_sql = text("""
SELECT id, gmv_ratio
FROM biz_budget_achieve
WHERE traffic_name = :target_name
AND business_type = :biz_type
AND task_id = :task_id
""")
params = {"target_name": target_name, "biz_type": business_type, "task_id": task_id}
else:
# 园区店查询
query_sql = text("""
SELECT id, gmv_ratio
FROM biz_budget_achieve
WHERE park_store = :target_name
AND business_type = :biz_type
AND task_id = :task_id
""")
params = {"target_name": target_name, "biz_type": business_type, "task_id": task_id}
try:
rows = conn.execute(query_sql, params).fetchall()
logger.info(f"[房租水电GMV写入] 查询到 {len(rows)} 条记录: target={target_name}, type={target_type}")
for row in rows:
row_id, gmv_ratio = row
# 分账结果 * gmv_ratio
ratio = Decimal(str(gmv_ratio)) if gmv_ratio is not None else Decimal("1")
rent_utilities = Decimal(str(fee)) * ratio
update_sql = text(f"""
UPDATE {table}
SET rent_utilities = :rent_utilities, updated_at = CURRENT_TIMESTAMP
WHERE id = :row_id
""")
conn.execute(update_sql, {"rent_utilities": float(rent_utilities), "row_id": row_id})
updated_count += 1
logger.info(f"[房租水电GMV写入] id={row_id}, gmv_ratio={gmv_ratio}, fee={fee}, rent_utilities={rent_utilities}")
except Exception as e:
logger.error(f"[房租水电GMV写入] 查询失败: target={target_name}, type={target_type}, error={e}")
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 分摊写入"""
update_columns = ['rent_utilities'] update_columns = ['rent_utilities']
...@@ -3906,8 +4512,26 @@ class DataProcessor: ...@@ -3906,8 +4512,26 @@ class DataProcessor:
business_type = (row.get("业务类型", "") or "").strip() business_type = (row.get("业务类型", "") or "").strip()
brand = (row.get("品牌", "") or "").strip() brand = (row.get("品牌", "") or "").strip()
brand_level_fee = self._safe_float(row.get("房租及水电费", Decimal("0"))) brand_level_fee = self._safe_float(row.get("房租及水电费", Decimal("0")))
is_gmv_allocated = row.get("__gmv_allocated__", False)
key = (traffic_name, business_type, brand) key = (traffic_name, business_type, brand)
if not traffic_name or not business_type or brand_level_fee <= 0:
continue
if is_gmv_allocated:
# 已GMV分摊的记录,按分账结果 * gmv_ratio 更新
target_type = row.get("target_type", "flow")
updated_rows = self._update_rent_utilities_by_target(
conn, table, task_id, month, traffic_name, business_type,
brand_level_fee, target_type
)
updated_count += updated_rows
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}")
else:
logger.warning(f"[房租水电GMV写入] 未找到匹配行: flow={traffic_name}, biz={business_type}, target_type={target_type}")
continue
if key in ratio_index and len(ratio_index[key]) > 1: if key in ratio_index and len(ratio_index[key]) > 1:
rows_info = ratio_index[key] rows_info = ratio_index[key]
total_ratio = sum(r for _, _, r in rows_info) total_ratio = sum(r for _, _, r in rows_info)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!