Commit 4ec2c0f1 by zhouhaibao

fix(data-process): 修复数据处理中的计算错误和配置问题

- 更新数据库连接配置,修改用户名和密码以及服务器地址
- 修复营销费用计算错误,添加对Excel预算表百分比格式的正确处理
- 增强列匹配功能,支持处理重复列名的ordinal语法
- 在预算达成Excel解析中添加对"本月占比"等多个同名列的正确定位
- 优化BizSQL诊断查询的WHERE条件构造逻辑
1 parent 2f5cd0e2
......@@ -98,7 +98,7 @@ class Config:
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv(
'BIZ_SQL_DATABASE_URL',
'mysql+pymysql://wechat_user:b4WRTkl@192.168.1.228:3307/dj_smartcarlife?charset=utf8mb4'
'mysql+pymysql://read_dj_smartcarlife:X9RNTOLr@192.168.5.23:3306/dj_smartcarlife?charset=utf8mb4'
)
# ---------- 文件上传 ----------
......
......@@ -209,7 +209,8 @@ class WarrantyProcessor:
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = clamp_ratio(extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio'))
marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
# Excel 预算表的百分比是"带百分号"的原值(如 5.0 = 5%),算费用时需除以 100
marketing_fee = (store_output_value * marketing_fee_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee
......
......@@ -204,7 +204,8 @@ class EquityProcessor:
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = clamp_ratio(extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio'))
marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
# Excel 预算表的百分比是"带百分号"的原值(如 5.0 = 5%),算费用时需除以 100
marketing_fee = (store_output_value * marketing_fee_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee
......
......@@ -243,17 +243,48 @@ def download_all_files(task_id, tmp_dir):
def match_columns(columns, keywords_map):
"""
模糊匹配列名。
keywords_map = {标准名: [关键词列表]},返回 {标准名: 实际列名}。
keywords_map = {标准名: [关键词列表]},返回 {标准名: 列名str 或 列索引int}。
支持 ordinal 语法处理重复列名:
keywords_map 中某个 keyword 可为 ("本月占比", 4) → 取第 4 个匹配的列,返回其**整数索引**
普通字符串 keyword 保持原有精确→子串匹配逻辑,返回**列名字符串**。
返回值类型说明(调用方需兼容):
- 匹配到重复列名(ordinal)→ 返回 int(列索引)
- 匹配到唯一列名(普通) → 返回 str(列名字符串)
这样 pandas 取值时:df.iloc[:, col_idx](int)或 df[col_name](str)都能正确工作。
匹配优先级:先精确相等(列名 strip 后与关键词完全一致),再子串包含。
这样可避免如「门店」子串误命中「门店类型」之类的歧义(后者列序更靠前)。
"""
result = {}
# —— 先处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)——
for std, keywords in keywords_map.items():
for kw in keywords:
if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int):
target_name, ordinal = kw[0], kw[1]
# 收集所有匹配该列名的**位置索引**
matches_idx = [i for i, col in enumerate(columns)
if str(col).strip() == target_name or target_name in str(col).strip()]
if len(matches_idx) >= ordinal:
result[std] = matches_idx[ordinal - 1] # 返回 int 索引
elif matches_idx:
logger.warning(f"[match_columns] {std} 期望第 {ordinal} 个 '{target_name}' 列,实际只有 {len(matches_idx)} 个,取最后一个")
result[std] = matches_idx[-1]
else:
logger.warning(f"[match_columns] {std} 未找到 '{target_name}' 列")
break
# —— 再处理普通 keyword(返回 str 列名)——
# 第一遍:精确相等
for std, keywords in keywords_map.items():
for col in columns:
c = str(col).strip()
for kw in keywords:
if std in result:
continue
for kw in keywords:
if isinstance(kw, tuple):
continue
for col in columns:
c = str(col).strip()
if c == kw:
result[std] = col
break
......@@ -263,9 +294,11 @@ def match_columns(columns, keywords_map):
for std, keywords in keywords_map.items():
if std in result:
continue
for col in columns:
col_lower = str(col).lower()
for kw in keywords:
for kw in keywords:
if isinstance(kw, tuple):
continue
for col in columns:
col_lower = str(col).lower()
if kw.lower() in col_lower:
result[std] = col
break
......@@ -583,31 +616,45 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
col_map = match_columns(df.columns, {
'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'],
'biz_type': ['业务类型', '业务线'],
'labor_ratio': ['人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
# 人员工资占比 → 营销费用占比:Excel 有多个同名列 "本月占比",取第 4 个
'labor_ratio': [("本月占比", 4), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'],
'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'],
'store_consumables': ['门店耗材', '耗材'],
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率'],
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 5)],
})
if 'store_name' not in col_map:
logger.warning("[预算达成Excel] 未找到门店名列")
return {}
# 诊断:打印列映射,方便验证"第 N 个本月占比"是否正确命中
logger.info(f"[预算达成Excel] 列映射: {dict(col_map)}")
store_col = col_map['store_name']
biz_col = col_map.get('biz_type')
field_cols = {k: v for k, v in col_map.items() if k not in ('store_name', 'biz_type')}
# 兼容:col 值可能是 str(唯一列名)或 int(ordinal 重复列索引)
def _get(row, col_ref):
"""row 取值:col_ref=int → iloc;col_ref=str → []"""
if isinstance(col_ref, int):
try:
return row.iloc[col_ref]
except Exception:
return None
return row.get(col_ref, None)
# 先收集所有值,同门店同 biz_type 多行 → sum+count → 最后取平均
# 聚合 key = (store_name, biz_type_val)
agg = {} # (sn, bt_val) → {field: [sum, count]}
for _, row in df.iterrows():
sn = str(row.get(store_col, '')).strip()
sn = str(_get(row, store_col) or '').strip()
if not sn or sn in ('nan', 'None', ''):
continue
bt_val = str(row.get(biz_col, '')).strip() if biz_col else ''
bt_val = str(_get(row, biz_col) or '').strip() if biz_col else ''
# 如果没找到 biz_type 列或传入了过滤条件,按过滤条件匹配
if biz_type is not None and biz_col:
if bt_val != biz_type:
......@@ -618,7 +665,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
agg[key] = {}
for field, col in field_cols.items():
val = row.get(col, None)
val = _get(row, col)
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None', '-', '/'):
continue
try:
......@@ -1345,8 +1392,9 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
# === 诊断:带 store_names 过滤返回 0 时,自动再跑一次不带过滤的全量 ===
if store_names and len(out) == 0:
logger.warning(f"[BizSQL-延保权益财务] store_cnt={len(store_names)} 过滤后返回 0,诊断全量...")
# 构造不带 store_names 的 SQL
diag_sql = sql.split("WHERE")[0] + "WHERE {' AND '.join([w for w in where_parts if 'LIKE' not in w])} GROUP BY go.merchant_name"
# 构造不带 store_names LIKE 条件的全量 SQL
diag_where_parts = [w for w in where_parts if 'LIKE' not in w]
diag_sql = sql.split("WHERE")[0] + "WHERE " + " AND ".join(diag_where_parts) + " GROUP BY go.merchant_name"
try:
_diag_preview = diag_sql.strip().replace('\n', ' ')[:400]
logger.info(f"[BizSQL-诊断] 全量 SQL={_diag_preview}...")
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!