Commit 8e40284e by 周立明
2 parents e864dae8 41343504
......@@ -9,7 +9,9 @@ import base64
import hashlib
import hmac
import json
import logging
import os
import threading
import time
import uuid
from datetime import datetime, timedelta, timezone
......@@ -18,6 +20,8 @@ import oss2
from config import Config
logger = logging.getLogger('oss_utils')
_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 直传签名有效期(秒)
......@@ -110,14 +114,20 @@ def get_object_key_from_url(file_url):
return file_url
def download_file(file_url, local_path):
"""从 OSS 下载文件到本地路径。
def download_file(file_url, local_path, timeout_seconds=60):
"""从 OSS 下载文件到本地路径,带超时保护。
- 解析 file_url 获取 OSS object key
- 使用 oss2.Bucket.get_object_to_file() 下载
- 本地回退模式:如果 file_url 以 /uploads/ 开头,直接从本地 uploads 目录复制
- 目录不存在时自动创建
- 下载失败时抛出 Exception
- 超时后抛出 TimeoutError
"""
import threading
import time as time_module
download_start = time_module.time()
# 本地回退模式:从本地 uploads 目录复制
if file_url.startswith('/uploads/'):
source_path = os.path.join(Config.UPLOAD_FOLDER, file_url[len('/uploads/'):])
......@@ -126,24 +136,45 @@ def download_file(file_url, local_path):
raise Exception(f"本地文件不存在: {source_path}")
import shutil
shutil.copy2(source_path, local_path)
elapsed = time_module.time() - download_start
logger.info(f"[OSS下载] 本地复制完成: {file_url}, 耗时: {elapsed:.2f}s")
return
if not Config.OSS_ENABLED:
raise Exception("OSS 未启用,无法下载远程文件")
# 从 URL 中解析 object key
object_key = get_object_key_from_url(file_url)
# 确保本地目录存在
os.makedirs(os.path.dirname(local_path), exist_ok=True)
# 从 OSS 下载
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
try:
bucket.get_object_to_file(object_key, local_path)
except Exception as e:
raise Exception(f"OSS 下载失败: {str(e)}")
logger.info(f"[OSS下载] 开始下载: url={file_url[:80]}..., timeout={timeout_seconds}s")
# 使用线程实现超时控制
result = {'error': None}
def _do_download():
try:
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
bucket.get_object_to_file(object_key, local_path)
except Exception as e:
result['error'] = str(e)
download_thread = threading.Thread(target=_do_download, daemon=True)
download_thread.start()
download_thread.join(timeout=timeout_seconds)
if download_thread.is_alive():
elapsed = time_module.time() - download_start
raise TimeoutError(f"下载超时: {file_url[:80]}, 超过 {timeout_seconds}s (实际耗时 {elapsed:.2f}s)")
if result['error']:
raise Exception(f"OSS 下载失败: {result['error']}")
elapsed = time_module.time() - download_start
logger.info(f"[OSS下载] 下载完成: url={file_url[:80]}..., 耗时: {elapsed:.2f}s")
def upload_file(local_path, object_key=None):
......
......@@ -21,13 +21,16 @@ import logging
import math
import re
import shutil
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from collections import defaultdict
from datetime import datetime
import time
import pandas as pd
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from sqlalchemy import text
from models import DataProcessTask, DataProcessFile, BizBudgetAchieve, db
from oss_utils import download_file, upload_file
......@@ -49,6 +52,9 @@ BIZ_TYPE_1_1 = "1.1" # 贴膜等1.1业务
BIZ_TYPE_2_1 = "2.1" # 2.1业务
BIZ_TYPE_2_3 = "2.3" # 2.3业务
# 必需的表单类型(仅下载这些文件)
REQUIRED_FORM_TYPES = ['市场费总表', '人力成本统计表', '外施施工费用表', '房租水电费用表']
# 市场费 Title 与业务类型的映射关系
TITLE_TO_BIZ = {
"Title2": BIZ_TYPE_1_1,
......@@ -61,10 +67,93 @@ TITLE_TO_BIZ = {
"Title10": BIZ_TYPE_2_3,
}
# 市场费 Sheet 名称模式与业务类型、取费字段的映射
# 根据 Sheet 名称中的关键词匹配业务类型和取费列
# fee_col: 'market_fee' 表示取"市场费"列,'market_fee_total' 表示取"市场费总额"列
SHEET_BIZ_MAP = [
# 1.1 业务:太阳膜、龙南(无后缀)
{'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
# 2.1 业务:权益、续保
{'pattern': '权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
{'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
# 2.3 业务:延保
{'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
]
# 跳过的 Sheet 名称关键词
SHEET_SKIP_PATTERNS = ['6月预算', '汇总', '合计']
# 品牌关键词映射
WENJIE_KEYWORDS = ["问界"]
HARMONY_KEYWORDS = ["享界", "智界", "尊界", "尚界"]
# 已知密码映射(文件名 → 密码)
KNOWN_PASSWORDS = {
"人力成本表-密码2026": "2026",
}
def decrypt_excel_if_needed(file_path):
"""
检查 Excel 文件是否有密码保护,如有则解密到临时文件。
返回:(file_path, is_decrypted) 元组
- file_path: 可读取的文件路径(可能是解密后的临时文件)
- is_decrypted: 是否进行了解密操作(调用方负责清理临时文件)
"""
basename = os.path.basename(file_path)
name_without_ext = os.path.splitext(basename)[0]
# 检查是否有已知密码
password = None
for key, pwd in KNOWN_PASSWORDS.items():
if key in name_without_ext:
password = pwd
break
if not password:
# 尝试直接读取,如果能读取则返回原路径
try:
pd.ExcelFile(file_path)
return file_path, False
except Exception:
# 可能有密码,尝试用默认密码
logger.warning(f"[解密] 文件可能有密码保护: {file_path}")
return file_path, False
# 使用密码解密
try:
import io
import msoffcrypto
with open(file_path, 'rb') as f:
office_file = msoffcrypto.OfficeFile(f)
if office_file.is_encrypted():
office_file.load_key(password=password)
decrypted = office_file.decrypt()
# 写入临时文件
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_')
with os.fdopen(tmp_fd, 'wb') as tmp_f:
tmp_f.write(decrypted)
logger.info(f"[解密] 成功解密文件,密码: {password}")
return tmp_path, True
except ImportError:
logger.warning("[解密] msoffcrypto 未安装,尝试使用 pandas 直接读取")
except Exception as e:
logger.error(f"[解密] 解密失败: {e}")
# 回退:尝试用 openpyxl 的 password 参数
try:
wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)
wb.close()
return file_path, False
except Exception:
pass
return file_path, False
# ============================================================
# 通用工具函数
......@@ -121,6 +210,7 @@ def pct(numerator, denominator):
"""
计算百分比(分子/分母*100),四舍五入保留2位小数。
分母为0时返回 0.00。
返回值上限 999.99(对应数据库 decimal(5,2) 字段)。
"""
if denominator is None or denominator == 0:
return Decimal("0.00")
......@@ -128,7 +218,14 @@ def pct(numerator, denominator):
den = safe_decimal(denominator)
if den == 0:
return Decimal("0.00")
return round_2(num / den * Decimal("100"))
result = round_2(num / den * Decimal("100"))
# 限制上限为 999.99,防止超出 decimal(5,2) 范围
if result > Decimal("999.99"):
result = Decimal("999.99")
# 限制下限为 0
if result < Decimal("0"):
result = Decimal("0.00")
return result
def detect_header_row(df_raw, max_scan=15):
......@@ -249,6 +346,92 @@ class DataProcessor:
self.app = app
self._task_files = {} # 缓存任务下载的文件路径
def _fetch_gmv_from_db(self, task_id, stat_month):
"""
从 biz_budget_achieve 表查询已有的 GMV 和产值数据。
返回:settlement_map 字典 {(流量方名称, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}}
"""
logger.info(f"[GMV数据] 从数据库获取 task_id={task_id}, stat_month={stat_month} 的 GMV 数据")
settlement_map = {}
try:
records = db.session.query(BizBudgetAchieve).filter(
BizBudgetAchieve.task_id == task_id,
BizBudgetAchieve.stat_month == stat_month
).all()
if not records:
logger.warning(f"[GMV数据] 数据库中无 task_id={task_id}, stat_month={stat_month} 的记录")
return settlement_map
for r in records:
flow_name = (r.traffic_name or "").strip()
biz_type = (r.business_type or "").strip()
brand = (r.brand or "").strip()
gmv_val = Decimal(str(r.gmv or 0))
revenue_val = Decimal(str(r.revenue or 0))
key = (flow_name, biz_type, brand)
if key not in settlement_map:
settlement_map[key] = {"GMV": Decimal("0"), "产值": Decimal("0")}
settlement_map[key]["GMV"] += gmv_val
settlement_map[key]["产值"] += revenue_val
logger.info(f"[GMV数据] 获取到 {len(settlement_map)} 条 GMV 记录")
except Exception as e:
logger.error(f"[GMV数据] 查询失败: {str(e)}")
return settlement_map
def _fetch_previous_month_data(self, task_id, stat_month):
"""
从上月 biz_budget_achieve 表查询历史数据,用于计算上月占比。
返回:prev_month_data 字典 {(流量方名称, 业务类型, 品牌): {market_fee_ratio, personnel_salary_ratio, gmv}}
"""
from datetime import datetime, timedelta
try:
year, month = stat_month.split("-")
year = int(year)
month = int(month)
if month == 1:
prev_year = year - 1
prev_month = 12
else:
prev_year = year
prev_month = month - 1
prev_month_str = f"{prev_year}-{prev_month:02d}"
except Exception:
logger.warning(f"[上月数据] 无法解析月份: {stat_month}")
return {}
logger.info(f"[上月数据] 查询 {prev_month_str} 的历史数据 (task_id={task_id})")
prev_month_data = {}
try:
records = db.session.query(BizBudgetAchieve).filter(
BizBudgetAchieve.stat_month == prev_month_str
).all()
if not records:
logger.warning(f"[上月数据] {prev_month_str} 无历史数据")
return prev_month_data
for r in records:
flow_name = r.traffic_name or ""
biz_type = r.business_type or ""
brand = r.brand or ""
key = (flow_name, biz_type, brand)
prev_month_data[key] = {
"market_fee_ratio": Decimal(str(r.market_fee_ratio_current or 0)),
"personnel_salary_ratio": Decimal(str(r.personnel_salary_ratio_current or 0)),
"gmv": Decimal(str(r.gmv or 0)),
}
logger.info(f"[上月数据] 获取到 {len(prev_month_data)} 条 {prev_month_str} 历史记录")
except Exception as e:
logger.error(f"[上月数据] 查询失败: {str(e)}")
return prev_month_data
def scan_processing_tasks(self):
"""
查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。
......@@ -280,8 +463,10 @@ class DataProcessor:
success_count += 1
logger.info(f"[批量处理] 任务 {task.id} ({task.month}) 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[批量处理] 任务 {task.id} ({task.month}) 处理失败: {str(e)}")
logger.error(traceback.format_exc())
# 标记任务为失败
try:
self._mark_task_failed(task.id, str(e))
......@@ -300,6 +485,8 @@ class DataProcessor:
- task_id: 任务ID
"""
logger.info(f"[处理任务] 开始处理任务 ID: {task_id}")
task_start_time = time.time()
logger.info(f"[处理任务] 任务 {task_id} 开始处理, 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# 获取任务
task = DataProcessTask.query.filter_by(id=task_id, is_deleted=0).first()
......@@ -309,12 +496,14 @@ class DataProcessor:
logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})")
# ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ==========
step_a_start = time.time()
logger.info("[处理任务] 步骤 a: 更新文件状态为清洗中...")
files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
for f in files:
f.clean_status = 2
db.session.commit()
logger.info(f"[处理任务] 已更新 {len(files)} 个文件状态为清洗中")
logger.info(f"[处理任务] 步骤 a 完成, 耗时: {time.time() - step_a_start:.2f}s")
try:
# ========== 步骤 b: 下载所有关联文件到本地临时目录 ==========
......@@ -323,34 +512,71 @@ class DataProcessor:
os.makedirs(tmp_dir, exist_ok=True)
downloaded_files = {}
for f in files:
# 过滤出必需的文件类型
files_to_download = [f for f in files if f.form_type in REQUIRED_FORM_TYPES]
skipped_files = [f for f in files if f.form_type not in REQUIRED_FORM_TYPES]
for f in skipped_files:
logger.warning(f"[处理任务] 跳过非必需文件: {f.form_type}")
logger.info(f"[处理任务] 待下载文件列表 ({len(files_to_download)} 个):")
for i, f in enumerate(files_to_download):
logger.info(f"[处理任务] [{i+1}] form_type={f.form_type}, file_url={f.file_url[:80] if f.file_url else 'None'}...")
download_start_time = time.time()
for i, f in enumerate(files_to_download):
local_path = os.path.join(tmp_dir, f.file_name)
logger.info(f"[处理任务] 下载文件: {f.form_type} -> {local_path}")
file_download_start = time.time()
logger.info(f"[处理任务] 开始下载 [{i+1}/{len(files_to_download)}]: {f.form_type}")
# 检查 file_url 是否有效
if not f.file_url or not str(f.file_url).strip():
logger.warning(f"[处理任务] 文件 {f.form_type} 无 file_url,跳过")
continue
try:
download_file(f.file_url, local_path)
downloaded_files[f.form_type] = local_path
file_elapsed = time.time() - file_download_start
logger.info(f"[处理任务] 下载完成 [{i+1}/{len(files_to_download)}]: {f.form_type}, 耗时: {file_elapsed:.2f}s")
except Exception as dl_err:
logger.warning(f"[处理任务] 下载文件失败: {f.form_type}, 错误: {str(dl_err)}")
logger.error(f"[处理任务] 下载文件失败 [{i+1}/{len(files_to_download)}]: {f.form_type}, 错误: {str(dl_err)}")
# 对于必需的文件,下载失败时抛出异常
if f.form_type in ['结算数据汇总表', '市场费总表', '人力成本统计表',
'外施施工费用表', '房租水电费用表']:
if f.form_type in REQUIRED_FORM_TYPES:
raise Exception(f"必需文件下载失败: {f.form_type} - {str(dl_err)}")
else:
logger.warning(f"[处理任务] 非必需文件下载失败,跳过: {f.form_type}")
continue
logger.info(f"[处理任务] 共下载 {len(downloaded_files)} 个文件")
total_download_elapsed = time.time() - download_start_time
logger.info(f"[处理任务] 文件下载完成,共下载 {len(downloaded_files)} 个文件,总耗时: {total_download_elapsed:.2f}s")
logger.info(f"[处理任务] 已下载文件类型: {list(downloaded_files.keys())}")
# ========== 步骤 c: 根据 form_type 分发解析逻辑 ==========
step_c_start = time.time()
logger.info("[处理任务] 步骤 c: 解析上传的文件...")
# 解析结算数据汇总表(获取 GMV 和产值数据)
# 从数据库获取 GMV 和产值数据(替代解析结算数据汇总表 Excel)
settlement_data = None
if '结算数据汇总表' in downloaded_files:
settlement_data = self._parse_settlement(downloaded_files['结算数据汇总表'])
logger.info(f"[处理任务] 结算数据汇总表解析完成,获取 {len(settlement_data)} 条记录")
settlement_map = self._fetch_gmv_from_db(task.id, task.month)
if settlement_map:
# 构建兼容格式的 settlement_data(供 _build_cost_summary 使用)
settlement_data = []
for (flow, biz, brand), data in settlement_map.items():
settlement_data.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"GMV": data["GMV"],
"产值": data["产值"],
})
logger.info(f"[处理任务] 从数据库获取 GMV 数据 {len(settlement_data)} 条记录")
else:
logger.warning("[处理任务] 数据库中无 GMV 数据,市场费分摊将降级为直接汇总")
# 解析市场费
# 解析市场费(传入 settlement_map 用于 GMV 分摊)
market_results = []
if '市场费总表' in downloaded_files:
market_results = self._parse_market_fee(downloaded_files['市场费总表'])
market_results = self._parse_market_fee(downloaded_files['市场费总表'], settlement_map)
logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录")
# 解析外援施工费
......@@ -370,49 +596,92 @@ class DataProcessor:
if '房租水电费用表' in downloaded_files:
utility_results = self._parse_utility_fee(downloaded_files['房租水电费用表'])
logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录")
logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")
# ========== 步骤 d: 执行成本计算 ==========
step_d_start = time.time()
logger.info("[处理任务] 步骤 d: 执行成本计算...")
# 调试日志:显示解析结果的样本数据
if market_results:
sample = market_results[0]
logger.info(f"[调试] 市场费样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 市场费={sample.get('市场费')}")
if wage_results:
sample = wage_results[0]
logger.info(f"[调试] 外援施工费样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 外援施工费={sample.get('外援施工费')}")
if labor_results:
sample = labor_results[0]
logger.info(f"[调试] 人力成本样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, 技师工资={sample.get('技师工资')}, 营销团队={sample.get('营销团队工资')}")
# 查询上月历史数据用于计算上月占比
prev_month_data = self._fetch_previous_month_data(task.id, task.month)
summary_data = self._build_cost_summary(
settlement_data, market_results, wage_results, labor_results, utility_results
settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data
)
logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录")
logger.info(f"[处理任务] 步骤 d 完成, 耗时: {time.time() - step_d_start:.2f}s")
# 调试日志:显示汇总结果的样本数据
if summary_data:
sample = summary_data[0]
logger.info(f"[调试] 汇总样本: 流量方={sample.get('流量方名称')}, 业务={sample.get('业务类型')}, "
f"市场费={sample.get('市场费')}, 外援施工={sample.get('外援施工')}, "
f"技师工资={sample.get('技师工资')}, 营销团队={sample.get('营销团队工资')}, "
f"人员工资={sample.get('人员工资')}")
# ========== 步骤 e: 将结果写入 biz_budget_achieve 表 ==========
step_e_start = time.time()
logger.info("[处理任务] 步骤 e: 写入预算达成表...")
self._write_budget_achieve(task.id, task.month, summary_data)
logger.info(f"[处理任务] 已写入 {len(summary_data)} 条预算达成记录")
logger.info(f"[处理任务] 步骤 e 完成, 耗时: {time.time() - step_e_start:.2f}s")
# ========== 步骤 f: 生成汇总 Excel 并上传到 OSS ==========
step_f_start = time.time()
logger.info("[处理任务] 步骤 f: 生成汇总 Excel 并上传到 OSS...")
result_file_url = self._generate_and_upload_excel(task.month, summary_data, tmp_dir)
logger.info(f"[处理任务] 结果文件已上传: {result_file_url}")
logger.info(f"[处理任务] 步骤 f 完成, 耗时: {time.time() - step_f_start:.2f}s")
# ========== 步骤 g: 更新文件 clean_status 为 3(清洗完成) ==========
step_g_start = time.time()
logger.info("[处理任务] 步骤 g: 更新文件状态为清洗完成...")
for f in files:
f.clean_status = 3
db.session.commit()
logger.info(f"[处理任务] 步骤 g 完成, 耗时: {time.time() - step_g_start:.2f}s")
# ========== 步骤 h: 更新任务 status 为 COMPLETED,回填 result_file_url ==========
step_h_start = time.time()
logger.info("[处理任务] 步骤 h: 更新任务状态为已完成...")
task.status = 'COMPLETED'
task.result_file_url = result_file_url
task.error_msg = ''
task.updater = task.updater or task.creator
db.session.commit()
logger.info(f"[处理任务] 任务 {task_id} 处理完成!")
logger.info(f"[处理任务] 步骤 h 完成, 耗时: {time.time() - step_h_start:.2f}s")
total_elapsed = time.time() - task_start_time
logger.info(f"[处理任务] 任务 {task_id} 处理完成!总耗时: {total_elapsed:.2f}s")
# 清理临时文件
self._cleanup_tmp_dir(tmp_dir)
except Exception as e:
# ========== 步骤 i: 异常时标记任务 status=FAILED,记录 error_msg ==========
logger.error(f"[处理任务] 处理任务 {task_id} 失败: {str(e)}")
import traceback
error_detail = f"处理任务 {task_id} 失败: {str(e)}\n{traceback.format_exc()}"
logger.error(error_detail)
db.session.rollback()
self._mark_task_failed(task_id, str(e))
try:
self._mark_task_failed(task_id, str(e))
except Exception as mark_err:
logger.error(f"[处理任务] 标记失败状态时出错: {str(mark_err)}")
# 清理临时文件
self._cleanup_tmp_dir(tmp_dir)
try:
self._cleanup_tmp_dir(tmp_dir)
except Exception as cleanup_err:
logger.warning(f"[处理任务] 清理临时文件时出错: {str(cleanup_err)}")
raise
# ========================================================
......@@ -515,11 +784,115 @@ class DataProcessor:
logger.info(f"[结算数据] 解析完成,共 {len(result)} 条汇总记录")
return result
def _allocate_market_fee_by_gmv(self, records, settlement_map):
"""
根据 GMV 数据对市场费进行品牌分摊。
规则:
1. 同一流量方+业务类型下,未知品牌的费用按已知品牌的 GMV 占比分摊
2. 同一流量方+业务类型+品牌有多条记录时,先汇总再按 GMV 比例分摊
参数:
- records: List[dict],原始记录列表,每条包含 {流量方名称, 业务类型, 品牌, 市场费}
- settlement_map: {(流量方, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}}
返回:List[dict],分摊后的记录列表
"""
if not records:
return []
# 按 (流量方, 业务类型) 分组
groups = defaultdict(list)
for r in records:
key = (r["流量方名称"], r["业务类型"])
groups[key].append(r)
result = []
for (flow, biz), group_records in groups.items():
# 按品牌汇总费用
brand_fees = defaultdict(Decimal) # {品牌: 费用合计}
brand_records = defaultdict(list) # {品牌: [原始记录列表]}
unknown_brand_fee = Decimal("0") # 未知品牌的费用总和
for r in group_records:
brand = r.get("品牌", "未知品牌")
fee = r.get("市场费", Decimal("0"))
if brand == "未知品牌":
unknown_brand_fee += fee
else:
brand_fees[brand] += fee
brand_records[brand].append(r)
# 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
if unknown_brand_fee > 0 and brand_fees:
# 获取各品牌的 GMV
brand_gmv = {}
for brand in brand_fees.keys():
key = (flow, biz, brand)
if key in settlement_map:
brand_gmv[brand] = settlement_map[key]["GMV"]
else:
brand_gmv[brand] = Decimal("0")
total_gmv = sum(brand_gmv.values())
if total_gmv > 0:
# 按 GMV 占比分摊未知品牌费用
for brand in brand_fees.keys():
ratio = brand_gmv[brand] / total_gmv
allocated_fee = (unknown_brand_fee * ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
brand_fees[brand] += allocated_fee
# 尾差归并到第一个品牌
allocated_total = sum(brand_fees.values()) - sum(
Decimal(str(r.get("市场费", 0))) for r in group_records if r.get("品牌") == "未知品牌"
)
diff = unknown_brand_fee - (brand_fees[list(brand_fees.keys())[0]] - (brand_fees[list(brand_fees.keys())[0]] - allocated_total))
# 简化处理:计算分摊后的实际总和与未知品牌费用的差额,加到第一个品牌
first_brand = list(brand_fees.keys())[0]
allocated_sum = sum(
(unknown_brand_fee * (brand_gmv[b] / total_gmv)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for b in brand_fees.keys()
)
diff = unknown_brand_fee - allocated_sum
if diff != 0:
brand_fees[first_brand] += diff
else:
# GMV 都为 0,平均分摊
n = len(brand_fees)
avg_fee = (unknown_brand_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for brand in brand_fees.keys():
brand_fees[brand] += avg_fee
# 尾差归并
allocated_sum = avg_fee * n
diff = unknown_brand_fee - allocated_sum
if diff != 0:
first_brand = list(brand_fees.keys())[0]
brand_fees[first_brand] += diff
# 输出结果
for brand, fee in brand_fees.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"市场费": round_2(fee),
})
# 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留
if not brand_fees and unknown_brand_fee > 0:
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": "未知品牌",
"市场费": round_2(unknown_brand_fee),
})
logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录")
return result
# ========================================================
# 解析市场费表
# ========================================================
def _parse_market_fee(self, file_path):
def _parse_market_fee(self, file_path, settlement_map=None):
"""
解析市场费表。
规则:
......@@ -527,7 +900,11 @@ class DataProcessor:
- 1.1业务:取"市场费"(Title2/3/5) 或 "市场费总额"(Title4)
- 2.1业务:取"市场费"(Title7) 或 "市场费总额"(Title6)
- 2.3业务:取"市场费";商品类别=权益服务/延保-原厂权益归属2.1
- 品牌归属:含"问界"→问界,含"享界/智界/尊界/尚界"→鸿蒙,无车型按GMV分摊
- 品牌归属:含"问界"→问界,含"享界/智界/尊界/尚界"→鸿蒙,无车型→未知品牌
- GMV 分摊:同组内未知品牌费用按已知品牌 GMV 占比分摊
参数:
- file_path: 市场费 Excel 文件路径
- settlement_map: GMV 数据映射(可选),用于品牌分摊
返回:List[dict],每行 {流量方名称, 业务类型, 品牌, 市场费}
"""
logger.info(f"[市场费] 解析文件: {file_path}")
......@@ -536,36 +913,91 @@ class DataProcessor:
logger.warning(f"[市场费] 文件不存在: {file_path}")
return []
if settlement_map is None:
settlement_map = {}
xls = pd.ExcelFile(file_path)
all_results = []
for sheet_name in xls.sheet_names:
# 检查是否需要跳过此 Sheet
should_skip = False
for skip_pattern in SHEET_SKIP_PATTERNS:
if skip_pattern in sheet_name:
logger.info(f"[市场费] Sheet '{sheet_name}' 匹配跳过规则 '{skip_pattern}',跳过")
should_skip = True
break
if should_skip:
continue
# 根据 Sheet 名称匹配业务类型和取费列
sheet_config = None
for config in SHEET_BIZ_MAP:
pattern = config['pattern']
if pattern.startswith('^'):
# 精确匹配(正则)
if re.match(pattern, sheet_name):
sheet_config = config
break
else:
# 包含匹配
if pattern in sheet_name:
sheet_config = config
break
if not sheet_config:
logger.info(f"[市场费] Sheet '{sheet_name}' 未匹配到业务类型规则,跳过")
continue
sheet_biz_type = sheet_config['biz_type']
fee_col_type = sheet_config['fee_col']
logger.info(f"[市场费] Sheet '{sheet_name}' -> 业务类型={sheet_biz_type}, 取费列={fee_col_type}")
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 从 title_rows 中提取 Title 信息
title_map = {} # {Title号: 业务类型}
for idx, title_text in title_rows:
biz_type = identify_biz_type_by_title(title_text)
if biz_type:
title_map[idx] = biz_type
# 查找关键列
col_flow = find_column(df, "流量方-流量方", "流量方名称", "流量方")
# 调试日志:显示所有列名
logger.info(f"[市场费] Sheet '{sheet_name}' 共 {len(df.columns)} 列: {list(df.columns)}")
logger.info(f"[市场费] 数据行数: {len(df)}")
if len(df) > 0:
logger.info(f"[市场费] 第1行数据预览:")
first_row = {k: str(v)[:40] for k, v in df.iloc[0].items() if pd.notna(v) and str(v).strip()}
logger.info(f"[市场费] {first_row}")
# 查找关键列 - 支持多种列名模式
col_flow = find_column(df, "流量方-流量方", "流量方名称", "流量方", "门店", "服务商")
col_fee_market = find_column(df, "市场费")
col_fee_total = find_column(df, "市场费总额")
col_fee_total = find_column(df, "市场费总额", "市场费合计")
col_model = find_column(df, "车型", "商品名称", "产品名称")
col_category = find_column(df, "商品类别", "类别")
# 确定当前 sheet 的业务类型(根据 title_rows 中的 Title)
sheet_biz_type = None
for idx, title_text in title_rows:
biz_type = identify_biz_type_by_title(title_text)
if biz_type:
sheet_biz_type = biz_type
break
col_category = find_column(df, "商品类别", "类别", "业务类别")
# 根据配置选择取费列
if fee_col_type == 'market_fee':
col_fee = col_fee_market
# 如果没找到"市场费"列,尝试找包含"市场费"的列
if not col_fee:
for col in df.columns:
if '市场费' in str(col) and '总额' not in str(col) and '合计' not in str(col):
col_fee = col
break
else: # 'market_fee_total'
col_fee = col_fee_total
# 如果没找到"市场费总额"列,尝试找包含"总额"或"合计"的列
if not col_fee:
for col in df.columns:
if '总额' in str(col) or '合计' in str(col):
col_fee = col
break
logger.info(f"[市场费] 列匹配: 流量方={col_flow}, 市场费={col_fee_market}, "
f"市场费总额={col_fee_total}, 车型={col_model}, 商品类别={col_category}, "
f"取费列(col_fee)={col_fee}")
if not col_fee:
logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列 (fee_col_type={fee_col_type})")
continue
for _, row in df.iterrows():
flow_name = None
......@@ -578,58 +1010,11 @@ class DataProcessor:
if flow_name == "":
continue
# 确定业务类型
# 从配置获取业务类型
biz_type = sheet_biz_type
# 根据业务类型选择取费字段
fee = Decimal("0")
if biz_type == BIZ_TYPE_1_1:
# 1.1业务:Title2/3/5 取"市场费",Title4 取"市场费总额"
# 从 title_text 中判断是 Title4 还是其他
title_num = None
for idx, title_text in title_rows:
if identify_biz_type_by_title(title_text) == BIZ_TYPE_1_1:
match = re.search(r'Title\s*(\d+)', title_text, re.IGNORECASE)
if match:
title_num = int(match.group(1))
break
if title_num == 4:
# Title4 取"市场费总额"
if col_fee_total:
fee = safe_decimal(row[col_fee_total])
else:
# Title2/3/5 取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
elif biz_type == BIZ_TYPE_2_1:
# 2.1业务:Title7 取"市场费",Title6 取"市场费总额"
title_num = None
for idx, title_text in title_rows:
if identify_biz_type_by_title(title_text) == BIZ_TYPE_2_1:
match = re.search(r'Title\s*(\d+)', title_text, re.IGNORECASE)
if match:
title_num = int(match.group(1))
break
if title_num == 6:
# Title6 取"市场费总额"
if col_fee_total:
fee = safe_decimal(row[col_fee_total])
else:
# Title7 取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
elif biz_type == BIZ_TYPE_2_3:
# 2.3业务:取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
else:
# 未知业务类型,尝试取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
# 取费
fee = safe_decimal(row[col_fee])
if fee == 0:
continue
......@@ -640,16 +1025,17 @@ class DataProcessor:
brand = identify_brand(row[col_model])
# 2.3→2.1 归属规则:商品类别=权益服务/延保-原厂权益 归属2.1
if col_category:
if biz_type == BIZ_TYPE_2_3 and col_category:
category = str(row[col_category]).strip() if pd.notna(row[col_category]) else ""
if category in ["权益服务", "延保-原厂权益"]:
biz_type = BIZ_TYPE_2_1
logger.debug(f"[市场费] 2.3→2.1 归属: flow={flow_name}, category={category}")
result_row = {
"流量方名称": flow_name,
"业务类型": biz_type or "未知",
"业务类型": biz_type,
"品牌": brand or "未知品牌",
"市场费": round_2(fee),
"市场费": fee,
}
all_results.append(result_row)
......@@ -657,22 +1043,9 @@ class DataProcessor:
logger.info("[市场费] 无有效数据")
return []
# 按 (流量方, 业务类型, 品牌) 汇总
aggregated = defaultdict(lambda: Decimal("0"))
for r in all_results:
key = (r["流量方名称"], r["业务类型"], r["品牌"])
aggregated[key] += r["市场费"]
# 处理无车型信息的 GMV 分摊(同一流量方+业务类型下,品牌=None 的按 GMV 分摊)
# 这里简化处理:如果同一流量方+业务类型存在多条品牌记录,且有"未知品牌",则按比例分摊
result = []
for (flow, biz, brand), fee in aggregated.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"市场费": round_2(fee),
})
# 使用 GMV 分摊进行品牌费用分配
logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...")
result = self._allocate_market_fee_by_gmv(all_results, settlement_map)
logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录")
return result
......@@ -686,9 +1059,9 @@ class DataProcessor:
解析外援施工费表。
规则:
- 仅1.1业务统计,其他业务类型默认=0
- 按"流量来源"匹配
- 取"总计"列累加
- 多条记录按GMV分摊
- 读取 Sheet "按门店名称汇总"
- 按"流量来源"匹配流量方名称
- 取"总计"列作为外援施工费金额
返回:List[dict],每行 {流量方名称, 业务类型, 外援施工费}
"""
logger.info(f"[外援施工费] 解析文件: {file_path}")
......@@ -698,61 +1071,77 @@ class DataProcessor:
return []
xls = pd.ExcelFile(file_path)
raw_records = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 查找关键列
col_source = find_column(df, "流量来源", "流量方名称", "流量来源门店")
col_total = find_column(df, "总计", "合计", "总金额")
col_biz = find_column(df, "业务类型", "业务分类")
col_gmv = find_column(df, "GMV", "产值", "订单金额")
for _, row in df.iterrows():
flow_source = None
if col_source:
flow_source = row[col_source]
if flow_source is None or str(flow_source).strip() == "" or str(flow_source).strip() == "nan":
continue
flow_source = str(flow_source).strip()
logger.info(f"[外援施工费] 所有 Sheet: {xls.sheet_names}")
# 查找 "按门店名称汇总" Sheet
target_sheet = None
for name in xls.sheet_names:
if "按门店" in name or "门店名称汇总" in name:
target_sheet = name
break
if not target_sheet:
# 回退:尝试找第一个 Sheet
target_sheet = xls.sheet_names[0]
logger.warning(f"[外援施工费] 未找到'按门店名称汇总'Sheet,使用第一个: {target_sheet}")
else:
logger.info(f"[外援施工费] 读取 Sheet: {target_sheet}")
# 扫描前 5 行,查找包含"流量来源"的行作为表头行
df_raw = pd.read_excel(file_path, sheet_name=target_sheet, header=None)
header_row = 0
for i in range(min(5, len(df_raw))):
row_text = " ".join(str(v) for v in df_raw.iloc[i].tolist() if pd.notna(v))
logger.info(f"[外援施工费] 第{i}行: {row_text[:120]}")
if "流量来源" in row_text:
header_row = i
logger.info(f"[外援施工费] 表头行: 第{i}行")
break
# 用检测到的表头行读取
df = pd.read_excel(file_path, sheet_name=target_sheet, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
logger.info(f"[外援施工费] 列名: {list(df.columns)}")
logger.info(f"[外援施工费] 数据行数: {len(df)}")
# 匹配列
col_source = find_column(df, "流量来源")
col_total = find_column(df, "总计")
logger.info(f"[外援施工费] 列匹配: 流量来源={col_source}, 总计={col_total}")
if not col_source or not col_total:
logger.warning(f"[外援施工费] 列匹配失败,所有列: {list(df.columns)}")
return []
# 获取"总计"金额
fee = Decimal("0")
if col_total:
fee = safe_decimal(row[col_total])
raw_records = []
for _, row in df.iterrows():
flow_source = row[col_source]
if flow_source is None or pd.isna(flow_source) or str(flow_source).strip() == "":
continue
if fee == 0:
continue
flow_source = str(flow_source).strip()
# 获取 GMV(用于分摊)
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 跳过汇总行
if any(k in flow_source for k in ["合计", "汇总", "总计", "月外"]):
continue
# 外援施工费仅归属 1.1 业务
biz_type = BIZ_TYPE_1_1
if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if biz_val and biz_val not in ["1.1", "贴膜", ""]:
continue
fee = safe_decimal(row[col_total])
if fee == 0:
continue
raw_records.append({
"流量方名称": flow_source,
"业务类型": biz_type,
"外援施工费": fee,
"gmv": gmv,
})
raw_records.append({
"流量方名称": flow_source,
"业务类型": BIZ_TYPE_1_1,
"外援施工费": fee,
})
if not raw_records:
logger.info("[外援施工费] 无有效数据")
return []
# 按 (流量方, 业务类型) 分组,同一组内按 GMV 分摊
logger.info(f"[外援施工费] 解析到 {len(raw_records)} 条记录")
# 按 (流量方, 业务类型) 分组汇总
grouped = defaultdict(list)
for r in raw_records:
key = (r["流量方名称"], r["业务类型"])
......@@ -761,35 +1150,15 @@ class DataProcessor:
result = []
for (flow, biz), records in grouped.items():
total_fee = sum(r["外援施工费"] for r in records)
total_gmv = sum(r["gmv"] for r in records)
# 如果有多条记录且有 GMV 信息,按 GMV 分摊
if len(records) > 1 and total_gmv > 0:
for r in records:
if r["gmv"] > 0:
share = (r["gmv"] / total_gmv) * total_fee
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(share),
})
else:
# 无 GMV 的记录平均分摊
share = total_fee / len(records)
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(share),
})
else:
# 单条记录或无 GMV,直接汇总
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(total_fee),
})
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(total_fee),
})
logger.info(f"[外援施工费] 解析完成,共 {len(result)} 条记录")
logger.info(f"[外援施工费] 汇总后 {len(result)} 条记录")
if result:
logger.info(f"[外援施工费] 预览前3条: {result[:3]}")
return result
# ========================================================
......@@ -814,38 +1183,77 @@ class DataProcessor:
logger.warning(f"[人力成本] 文件不存在: {file_path}")
return []
# 尝试解密文件
actual_path, is_decrypted = decrypt_excel_if_needed(file_path)
try:
xls = pd.ExcelFile(file_path)
xls = pd.ExcelFile(actual_path)
except Exception as e:
logger.error(f"[人力成本] 读取失败(可能有密码保护): {e}")
logger.error(f"[人力成本] 读取失败: {e}")
if is_decrypted and actual_path != file_path:
os.unlink(actual_path)
return []
raw_records = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
try:
# 人力成本只读取第一个 Sheet(通常命名为"人力成本")
if not xls.sheet_names:
logger.warning("[人力成本] Excel 文件没有 Sheet")
return []
sheet_name = xls.sheet_names[0]
logger.info(f"[人力成本] 读取第一个 Sheet: {sheet_name}")
df_raw = pd.read_excel(actual_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df = pd.read_excel(actual_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 调试日志:显示识别到的列名
logger.info(f"[人力成本] 识别到列名({len(df.columns)}列): {list(df.columns)[:15]}...")
logger.info(f"[人力成本] 数据行数: {len(df)}")
logger.info(f"[人力成本] 前2行数据预览:")
for i in range(min(2, len(df))):
row_vals = {k: str(v)[:30] for k, v in df.iloc[i].items() if pd.notna(v) and str(v).strip()}
logger.info(f"[人力成本] 行{i}: {row_vals}")
# 查找关键列
col_store = find_column(df, "入驻门店", "门店", "流量方名称")
col_park_store = find_column(df, "园区店", "园区")
col_biz = find_column(df, "人员业务归属", "业务归属", "业务类型")
col_position = find_column(df, "岗位", "职位", "工种")
col_salary = find_column(df, "个人本店分摊薪资", "薪资", "工资", "应发工资", "合计")
col_check = find_column(df, "检核", "审核")
col_gmv = find_column(df, "GMV", "产值")
# 如果找不到检核列,尝试定位 AF 列
# 检核列:优先使用 AF 列(index 31),即"检核业务线"列
# 原始需求:仅考虑 AF 列:检核=TRUE
col_check = None
# 先尝试找"检核业务线"列
col_check_af = find_column(df, "检核业务线")
if col_check_af:
col_check = col_check_af
logger.info(f"[人力成本] 使用检核业务线列: {col_check}")
# 如果找不到,尝试 AF 列(index 31)
if col_check is None and len(df.columns) > 31:
col_check = df.columns[31] # AF 列(索引31)
logger.info(f"[人力成本] 使用 AF 列作为检核列: {col_check}")
# 最后回退到找"检核"列
if col_check is None:
col_check = find_column(df, "检核", "审核")
logger.info(f"[人力成本] 列匹配结果: 门店={col_store}, 园区店={col_park_store}, "
f"业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, "
f"检核={col_check}, GMV={col_gmv}")
for _, row in df.iterrows():
# 检核列必须为 True
# 检核列必须为 True(兼容多种格式:True/TRUE/1/1.0/Y/YES)
if col_check:
check_val = row[col_check]
if pd.isna(check_val) or str(check_val).strip().upper() not in ["TRUE", "True", "true", "1", "Y", "YES"]:
if pd.isna(check_val):
continue
# 统一转为字符串判断
check_str = str(check_val).strip().upper()
if check_str not in ["TRUE", "1", "1.0", "Y", "YES"]:
continue
store_name = None
......@@ -920,98 +1328,103 @@ class DataProcessor:
"is_park_store": is_park_store,
})
if not raw_records:
logger.info("[人力成本] 无有效数据")
return []
# 按 (流量方名称, 业务类型) 汇总
# 先汇总非园区店数据
direct_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0"), "gmv_sum": Decimal("0")})
for r in raw_records:
if r["is_park_store"]:
continue
key = (r["流量方名称"], r["业务类型"])
direct_grouped[key]["技师工资"] += r["技师工资"]
direct_grouped[key]["营销团队工资"] += r["营销团队工资"]
direct_grouped[key]["gmv_sum"] += r["gmv"]
# 汇总园区店数据
park_store_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
for r in raw_records:
if not r["is_park_store"]:
continue
# 园区店以 park_store 字段为主键
park_key = r["园区店"] or r["流量方名称"]
key = (park_key, r["业务类型"])
park_store_grouped[key]["技师工资"] += r["技师工资"]
park_store_grouped[key]["营销团队工资"] += r["营销团队工资"]
# 构建结果 - 一级匹配:直接匹配到门店
result = []
for (flow, biz), salaries in direct_grouped.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
})
# 二级匹配:园区店回退匹配
# 检查 direct_grouped 中没有的流量方,尝试从 park_store_grouped 中按园区店匹配
matched_park_stores = set()
for (flow, biz), salaries in direct_grouped.items():
# 查找该流量方是否关联某个园区店
for (park_store_key, park_biz), park_salaries in park_store_grouped.items():
if park_biz == biz and park_store_key in flow:
matched_park_stores.add((park_store_key, park_biz))
if not raw_records:
logger.info("[人力成本] 无有效数据")
return []
# 未直接匹配的流量方,使用园区店数据(按GMV分摊)
for (park_store_key, biz), salaries in park_store_grouped.items():
if (park_store_key, biz) not in matched_park_stores:
# 查找使用该园区店的流量方
related_flows = []
for (flow, flow_biz) in direct_grouped.keys():
if flow_biz == biz and park_store_key in flow:
related_flows.append(flow)
if related_flows:
# 按流量方的GMV占比分摊园区店费用
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
for flow in related_flows:
if (flow, biz) in direct_grouped:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
if total_gmv > 0 and flow_gmv > 0:
ratio = flow_gmv / total_gmv
tech_share = salaries["技师工资"] * ratio
mkt_share = salaries["营销团队工资"] * ratio
else:
# 无GMV信息,平均分摊
n = len(related_flows)
tech_share = salaries["技师工资"] / n
mkt_share = salaries["营销团队工资"] / n
# 按 (流量方名称, 业务类型) 汇总
# 先汇总非园区店数据
direct_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0"), "gmv_sum": Decimal("0")})
for r in raw_records:
if r["is_park_store"]:
continue
key = (r["流量方名称"], r["业务类型"])
direct_grouped[key]["技师工资"] += r["技师工资"]
direct_grouped[key]["营销团队工资"] += r["营销团队工资"]
direct_grouped[key]["gmv_sum"] += r["gmv"]
# 汇总园区店数据
park_store_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
for r in raw_records:
if not r["is_park_store"]:
continue
# 园区店以 park_store 字段为主键
park_key = r["园区店"] or r["流量方名称"]
key = (park_key, r["业务类型"])
park_store_grouped[key]["技师工资"] += r["技师工资"]
park_store_grouped[key]["营销团队工资"] += r["营销团队工资"]
# 构建结果 - 一级匹配:直接匹配到门店
result = []
for (flow, biz), salaries in direct_grouped.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
})
# 累加
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["技师工资"] = round_2(r["技师工资"] + tech_share)
r["营销团队工资"] = round_2(r["营销团队工资"] + mkt_share)
break
else:
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(tech_share),
"营销团队工资": round_2(mkt_share),
})
else:
# 无关联流量方,直接输出园区店数据
result.append({
"流量方名称": park_store_key,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
"__park_store__": True,
})
# 二级匹配:园区店回退匹配
# 检查 direct_grouped 中没有的流量方,尝试从 park_store_grouped 中按园区店匹配
matched_park_stores = set()
for (flow, biz), salaries in direct_grouped.items():
# 查找该流量方是否关联某个园区店
for (park_store_key, park_biz), park_salaries in park_store_grouped.items():
if park_biz == biz and park_store_key in flow:
matched_park_stores.add((park_store_key, park_biz))
# 未直接匹配的流量方,使用园区店数据(按GMV分摊)
for (park_store_key, biz), salaries in park_store_grouped.items():
if (park_store_key, biz) not in matched_park_stores:
# 查找使用该园区店的流量方
related_flows = []
for (flow, flow_biz) in direct_grouped.keys():
if flow_biz == biz and park_store_key in flow:
related_flows.append(flow)
if related_flows:
# 按流量方的GMV占比分摊园区店费用
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
for flow in related_flows:
if (flow, biz) in direct_grouped:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
if total_gmv > 0 and flow_gmv > 0:
ratio = flow_gmv / total_gmv
tech_share = salaries["技师工资"] * ratio
mkt_share = salaries["营销团队工资"] * ratio
else:
# 无GMV信息,平均分摊
n = len(related_flows)
tech_share = salaries["技师工资"] / n
mkt_share = salaries["营销团队工资"] / n
# 累加
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["技师工资"] = round_2(r["技师工资"] + tech_share)
r["营销团队工资"] = round_2(r["营销团队工资"] + mkt_share)
break
else:
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(tech_share),
"营销团队工资": round_2(mkt_share),
})
else:
# 无关联流量方,直接输出园区店数据
result.append({
"流量方名称": park_store_key,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
"__park_store__": True,
})
finally:
# 清理临时解密文件
if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
os.unlink(actual_path)
logger.info("[人力成本] 已清理临时解密文件")
logger.info(f"[人力成本] 解析完成,共 {len(result)} 条记录")
return result
......@@ -1185,7 +1598,7 @@ class DataProcessor:
# 构建成本汇总表
# ========================================================
def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results):
def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results, prev_month_data=None):
"""
生成成本汇总表。
综合结算数据、市场费、外援施工费、人力成本、房租水电施工费,
......@@ -1248,6 +1661,11 @@ class DataProcessor:
summary = []
for flow_name, biz_type, brand in sorted(all_keys):
# 清理空格
flow_name = flow_name.strip() if flow_name else ""
biz_type = biz_type.strip() if biz_type else ""
brand = brand.strip() if brand else ""
# 获取 GMV 和产值
settle_key = (flow_name, biz_type, brand)
if settle_key in settlement_map:
......@@ -1311,8 +1729,17 @@ class DataProcessor:
# ---------- 计算占比 ----------
# 市场费本月占比 = 市场费/GMV*100%
row["市场费本月占比"] = pct(row["市场费"], gmv)
# 市场费上月占比(暂用占位,需要上月数据)
row["市场费上月占比"] = pct(row["市场费"], gmv)
# 市场费上月占比 - 从历史数据查询
row["市场费上月占比"] = Decimal("0")
if prev_month_data:
prev_key = (flow_name, biz_type, brand)
if prev_key in prev_month_data:
row["市场费上月占比"] = prev_month_data[prev_key]["market_fee_ratio"]
else:
prev_key_no_brand = (flow_name, biz_type, "")
if prev_key_no_brand in prev_month_data:
row["市场费上月占比"] = prev_month_data[prev_key_no_brand]["market_fee_ratio"]
# 技师工资占比 = 技师工资/产值*100%
row["技师工资占比"] = pct(row["技师工资"], revenue)
......@@ -1320,8 +1747,14 @@ class DataProcessor:
row["营销团队工资占比"] = pct(row["营销团队工资"], revenue)
# 人员工资本月占比 = 人员工资/产值*100%
row["人员工资本月占比"] = pct(row["人员工资"], revenue)
# 人员工资上月占比(占位)
row["人员工资上月占比"] = pct(row["人员工资"], revenue)
# 人员工资上月占比 - 从历史数据查询
row["人员工资上月占比"] = Decimal("0")
if prev_month_data:
if prev_key in prev_month_data:
row["人员工资上月占比"] = prev_month_data[prev_key]["personnel_salary_ratio"]
elif prev_key_no_brand in prev_month_data:
row["人员工资上月占比"] = prev_month_data[prev_key_no_brand]["personnel_salary_ratio"]
# 计算毛利 = GMV - 市场费 - 人员工资 - 房租及水电费
# 注意:这里的成本计算简化处理
......@@ -1414,58 +1847,66 @@ class DataProcessor:
"""
将汇总数据写入 biz_budget_achieve 表。
使用业务唯一键 (task_id, stat_month, traffic_name, business_type, brand) 进行 Upsert:
- 存在则更新所有业务字段
- 不存在则新增记录
- 存在则仅更新成本相关字段(市场费、人力成本、房租水电等)
- 不存在则新增完整记录
"""
# 业务字段列表(不包含 id, created_at)
# 业务字段列表(仅成本相关字段在 ON DUPLICATE KEY UPDATE 时更新)
update_columns = [
'is_multi_category', 'entity', 'park_store', 'service_provider',
'order_count', 'gmv', 'revenue',
'cost_gmv', 'cost_gmv_ratio_current', 'cost_gmv_ratio_previous',
'traffic_fee_gmv', 'traffic_fee_gmv_ratio_current', 'traffic_fee_gmv_ratio_previous',
'service_fee', 'service_fee_ratio_current', 'service_fee_ratio_previous',
'cost_revenue', 'traffic_fee_revenue', 'dijia_profit_sharing',
'market_fee', 'market_fee_ratio_current', 'market_fee_ratio_previous',
'personnel_salary', 'external_construction',
'technician_salary', 'technician_salary_ratio',
'marketing_team_salary', 'marketing_team_salary_ratio',
'personnel_salary_ratio_current', 'personnel_salary_ratio_previous',
'rent_utilities', 'renovation_amortization', 'store_consumables',
'f_company_gross_profit', 'gross_profit',
'gross_profit_ratio_current', 'gross_profit_ratio_previous',
'rent_utilities',
]
def safe_float(val):
"""安全转换为 float,处理 Decimal、None、空字符串等"""
if val is None or val == '' or val == 'nan':
return 0.0
if isinstance(val, Decimal):
return float(val)
try:
return float(val)
except (ValueError, TypeError):
return 0.0
# 构建批量参数
params_list = []
for row in summary_data:
for idx, row in enumerate(summary_data):
# 清理字符串字段的前后空格
traffic_name = (row["流量方名称"] or "").strip()
business_type = (row["业务类型"] or "").strip()
brand = (row.get("品牌", "") or "").strip()
params = {
'task_id': task_id,
'stat_month': month,
'traffic_name': row["流量方名称"],
'business_type': row["业务类型"],
'brand': row.get("品牌", "") or "",
'traffic_name': traffic_name,
'business_type': business_type,
'brand': brand,
'is_multi_category': row.get("is_multi_category", ""),
'entity': row.get("entity", ""),
'park_store': row.get("park_store", ""),
'service_provider': row.get("service_provider", ""),
'order_count': row.get("order_count", 0),
'gmv': float(row.get("GMV", Decimal("0"))),
'revenue': float(row.get("产值", Decimal("0"))),
'market_fee': float(row.get("市场费", Decimal("0"))),
'market_fee_ratio_current': float(row.get("市场费本月占比", Decimal("0"))),
'market_fee_ratio_previous': float(row.get("市场费上月占比", Decimal("0"))),
'personnel_salary': float(row.get("人员工资", Decimal("0"))),
'external_construction': float(row.get("外援施工", Decimal("0"))),
'technician_salary': float(row.get("技师工资", Decimal("0"))),
'technician_salary_ratio': float(row.get("技师工资占比", Decimal("0"))),
'marketing_team_salary': float(row.get("营销团队工资", Decimal("0"))),
'marketing_team_salary_ratio': float(row.get("营销团队工资占比", Decimal("0"))),
'personnel_salary_ratio_current': float(row.get("人员工资本月占比", Decimal("0"))),
'personnel_salary_ratio_previous': float(row.get("人员工资上月占比", Decimal("0"))),
'rent_utilities': float(row.get("房租及水电费", Decimal("0"))),
'gross_profit': float(row.get("毛利", Decimal("0"))),
'gross_profit_ratio_current': float(row.get("毛利率本月", Decimal("0"))),
'gross_profit_ratio_previous': float(row.get("毛利率上月", Decimal("0"))),
'gmv': safe_float(row.get("GMV", Decimal("0"))),
'revenue': safe_float(row.get("产值", Decimal("0"))),
'market_fee': safe_float(row.get("市场费", Decimal("0"))),
'market_fee_ratio_current': safe_float(row.get("市场费本月占比", Decimal("0"))),
'market_fee_ratio_previous': safe_float(row.get("市场费上月占比", Decimal("0"))),
'personnel_salary': safe_float(row.get("人员工资", Decimal("0"))),
'external_construction': safe_float(row.get("外援施工", Decimal("0"))),
'technician_salary': safe_float(row.get("技师工资", Decimal("0"))),
'technician_salary_ratio': safe_float(row.get("技师工资占比", Decimal("0"))),
'marketing_team_salary': safe_float(row.get("营销团队工资", Decimal("0"))),
'marketing_team_salary_ratio': safe_float(row.get("营销团队工资占比", Decimal("0"))),
'personnel_salary_ratio_current': safe_float(row.get("人员工资本月占比", Decimal("0"))),
'personnel_salary_ratio_previous': safe_float(row.get("人员工资上月占比", Decimal("0"))),
'rent_utilities': safe_float(row.get("房租及水电费", Decimal("0"))),
'gross_profit': safe_float(row.get("毛利", Decimal("0"))),
'gross_profit_ratio_current': safe_float(row.get("毛利率本月", Decimal("0"))),
'gross_profit_ratio_previous': safe_float(row.get("毛利率上月", Decimal("0"))),
# 预留字段默认0
'cost_gmv': 0,
'cost_gmv_ratio_current': 0,
......@@ -1485,29 +1926,51 @@ class DataProcessor:
}
params_list.append(params)
# 构建 INSERT ... ON DUPLICATE KEY UPDATE SQL
table = BizBudgetAchieve.__tablename__
all_columns = ['task_id', 'stat_month', 'traffic_name', 'business_type', 'brand'] + update_columns
placeholders = ', '.join(['%s'] * len(all_columns))
update_clause = ', '.join([f'{col}=VALUES({col})' for col in update_columns])
# 记录前几条数据的调试日志
if idx < 3:
logger.info(f"[写入调试] 第{idx}条: 流量方={params['traffic_name']}, "
f"业务类型={params['business_type']}, 品牌={params['brand']}, "
f"市场费={params['market_fee']}, 人员工资={params['personnel_salary']}, "
f"外援施工={params['external_construction']}, 技师工资={params['technician_salary']}, "
f"营销团队工资={params['marketing_team_salary']}")
sql = (
f"INSERT INTO {table} ({', '.join(all_columns)}) VALUES ({placeholders}) "
f"ON DUPLICATE KEY UPDATE {update_clause}"
# 构建 UPDATE SQL(只更新已存在的记录,不插入新记录)
table = BizBudgetAchieve.__tablename__
# 更新子句:仅更新成本相关字段
set_clause = ', '.join([f'{col}=:{col}' for col in update_columns])
set_clause += ', updated_at = CURRENT_TIMESTAMP'
# WHERE 条件:按业务唯一键匹配
where_columns = ['task_id', 'stat_month', 'traffic_name', 'business_type', 'brand']
where_clause = ' AND '.join([f'{col}=:{col}' for col in where_columns])
sql_text = text(
f"UPDATE {table} SET {set_clause} "
f"WHERE {where_clause}"
)
# 执行批量 Upsert
# 执行批量 Update(只更新已存在的记录)
conn = db.engine.connect()
updated_count = 0
try:
trans = conn.begin()
for params in params_list:
values = [params[col] for col in all_columns]
conn.execute(sql, values)
# 构建命名字典参数(包含 WHERE 和 SET 所需的所有字段)
bind_params = {}
for col in where_columns + update_columns:
bind_params[col] = params.get(col, 0)
# brand 为空字符串时需要特殊处理
if not bind_params.get('brand'):
bind_params['brand'] = ''
result = conn.execute(sql_text, bind_params)
if result.rowcount > 0:
updated_count += 1
trans.commit()
logger.info(f"[写入] Upsert 成功,共处理 {len(params_list)} 条预算达成记录")
logger.info(f"[写入] Update 成功,共处理 {len(params_list)} 条记录,实际更新 {updated_count} 条")
except Exception as e:
trans.rollback()
logger.error(f"[写入] Upsert 失败: {str(e)}")
logger.error(f"[写入] Update 失败: {str(e)}")
raise
finally:
conn.close()
......@@ -1650,11 +2113,26 @@ class DataProcessor:
def _cleanup_tmp_dir(self, tmp_dir):
"""
清理临时目录。
处理 Windows 文件占用问题,添加重试机制。
"""
import time
try:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
# 先尝试忽略错误删除
shutil.rmtree(tmp_dir, ignore_errors=True)
# 检查是否还存在,若存在则重试
if os.path.exists(tmp_dir):
time.sleep(0.5)
shutil.rmtree(tmp_dir, ignore_errors=True)
if os.path.exists(tmp_dir):
# 第三次尝试
time.sleep(1)
shutil.rmtree(tmp_dir, ignore_errors=True)
if not os.path.exists(tmp_dir):
logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
else:
logger.warning(f"[清理] 临时目录仍被占用,跳过: {tmp_dir}")
except Exception as e:
logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")
......
......@@ -6,3 +6,6 @@ cryptography>=42.0
python-dotenv>=1.0
openpyxl>=3.1
requests>=2.31
pandas>=2.0
xlrd>=2.0.1
msoffcrypto-tool>=5.3
......@@ -15,12 +15,25 @@
import threading
import logging
import sys
import traceback
from datetime import datetime
from config import Config
logger = logging.getLogger('TaskScheduler')
# 注册线程异常钩子,捕获 daemon 线程中的未处理异常
def _threading_excepthook(args):
"""捕获线程中未处理的异常并记录完整堆栈。"""
error_msg = f"线程异常: {args.exc_type.__name__}: {args.exc_value}\n"
error_msg += ''.join(traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback))
logger.error(error_msg)
sys.stderr.write(error_msg)
sys.stderr.flush()
threading.excepthook = _threading_excepthook
class TaskScheduler:
"""
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!