Commit d78d5ea5 by zhouhaibao

refactor(data-process): 将盈利测算处理器拆分为独立模块

- 提取延保表处理器到单独的 warranty_processor.py 文件
- 新增权益表处理器到 equity_processor.py 文件
- 创建 report_utils.py 公用工具模块
- 统一 Excel 解析、指标系统调用、安全除法等公共功能
- 移除原 earnings_report_processor.py 中的权益和轻改表处理逻辑
- 优化代码结构,提高模块化和可维护性
1 parent 1cb049cc
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
红黄门店盈利测算 - 独立处理引擎 红黄门店盈利测算 - 延保表独立处理器
================================ ====================================
覆盖 4 张输出表:延保 / 权益 / 轻改店中店汇总 / 轻改园区店汇总。 对应 ORM 表:report_extended_warranty
统一扫描 data_table_type='store_effect_earnings' 类型的 PROCESSING 任务, 业务类型过滤:biz_type=2.3 (对比权益表的 2.1)
但根据 output_category 参数只处理对应的输出表(4 个独立调度器各自调各自的 category)。 指标系统 biz 编码:1 (延保)
流程(每张表通用): 流程:
Step1 Excel 解析(SAAS预算分解表 + 关系表 + 主机厂交车) Step1 Excel(SAAS预算分解表 biz_type=2.3 + 关系表 + 主机厂交车)
Step2 指标系统 API(IndicatorClient) Step2 指标系统 API(biz=1 延保)
Step3 业务系统 SQL(TODO 占位,后续完善) Step3 业务系统 SQL(TODO 占位)
Step4 系统公式计算 + 上月预算达成关联 Step4 系统公式计算 + 上月预算达成占比
Step5 排名 + 批量入库 Step5 排名 + 批量入库
""" """
import os
import logging import logging
import tempfile import tempfile
from decimal import Decimal, ROUND_HALF_UP from decimal import Decimal, ROUND_HALF_UP
import pandas as pd from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP,
from models import ( mark_task_failed, cleanup_tmp_dir, is_output_already_done,
DataProcessTask, DataProcessFile, BizBudgetAchieve, download_all_files,
ReportExtendedWarranty, ReportEquityService, parse_saas_base, parse_region_map, parse_delivery_table,
ReportLightReformInshop, ReportLightReformPark, fetch_indicator_data, fetch_prev_month_labor_ratio,
db, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from oss_utils import download_file from models import ReportExtendedWarranty, db
from indicator_client import IndicatorClient
from config import Config
logger = logging.getLogger('EarningsReportProcessor')
logger = logging.getLogger('WarrantyProcessor')
class EarningsReportProcessor:
"""红黄门店盈利测算 - 独立处理引擎"""
# store_effect_earnings 任务类型:4 张输出表共享同一批上传文件 class WarrantyProcessor:
STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings' """延保盈利测算独立处理器"""
def __init__(self, app=None): def __init__(self, app=None):
self.app = app self.app = app
# ============================================================ # ============================================================
# 调度器入口 / 任务分发 # 调度器入口
# ============================================================ # ============================================================
def scan_store_effect_earnings(self, output_category): def scan_store_effect_earnings(self, output_category='warranty'):
""" """扫描 store_effect_earnings 任务并处理延保表"""
独立调度器入口:统一扫描 store_effect_earnings 类型的 PROCESSING 任务, from models import DataProcessTask
但根据 output_category 只处理对应的输出表。 logger.info(f"[warranty] 开始扫描 store_effect_earnings 待处理任务")
参数:
- output_category: 输出类别 'warranty' / 'equity' / 'inshop' / 'park'
"""
logger.info(f"[{output_category}] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by( tasks = DataProcessTask.query.filter_by(
data_table_type=self.STORE_EFFECT_EARNINGS_TYPE, data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING', status='PROCESSING',
is_deleted=0 is_deleted=0
).order_by(DataProcessTask.id.asc()).all() ).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[{output_category}] 扫描到 {len(tasks)} 个待处理任务") logger.info(f"[warranty] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0 success_count = 0
fail_count = 0 fail_count = 0
for task in tasks: for task in tasks:
try: try:
self.process_store_effect_earnings_category(task, output_category) self.process(task)
success_count += 1 success_count += 1
logger.info(f"[{output_category}] 任务 {task.id} 处理成功") logger.info(f"[warranty] 任务 {task.id} 处理成功")
except Exception as e: except Exception as e:
import traceback import traceback
fail_count += 1 fail_count += 1
logger.error(f"[{output_category}] 任务 {task.id} 处理失败: {str(e)}") logger.error(f"[warranty] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
try: try:
self._mark_task_failed(task.id, str(e)) mark_task_failed(task.id, str(e))
except Exception as mark_err: except Exception as mark_err:
logger.error(f"[{output_category}] 标记任务失败时出错: {str(mark_err)}") logger.error(f"[warranty] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[{output_category}] 完成, 成功 {success_count}, 失败 {fail_count}") logger.info(f"[warranty] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count} return {'success': success_count, 'failed': fail_count}
def process_store_effect_earnings_category(self, task, output_category): def process(self, task):
""" """处理单个 task 的延保表输出"""
store_effect_earnings 单任务-单输出类别处理入口。
同一份上传文件,4 个调度器各自只写自己的输出表。
"""
task_id = task.id task_id = task.id
month = getattr(task, 'month', '')
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
logger.info(f"[{output_category}] 处理任务 id={task_id}, month={month}, period={period_start}~{period_end}") if is_output_already_done(task_id, 'warranty'):
logger.info(f"[warranty] 任务 {task_id} 已处理过,跳过")
# 幂等:输出表已有该 task_id 数据则跳过
if self._is_output_already_done(task_id, output_category):
logger.info(f"[{output_category}] 任务 {task_id} 已处理过该类别,跳过(输出表已有数据)")
return return
try: try:
if output_category == 'warranty': self._process_extended_warranty(task)
self._process_extended_warranty(task)
elif output_category == 'equity':
self._process_equity_service(task)
elif output_category == 'inshop':
self._process_light_reform_inshop(task)
elif output_category == 'park':
self._process_light_reform_park(task)
else:
raise ValueError(f"未知的输出类别: {output_category}")
db.session.commit() db.session.commit()
logger.info(f"[{output_category}] 任务 {task_id} 处理完成") logger.info(f"[warranty] 任务 {task_id} 处理完成")
except Exception as e:
db.session.rollback()
raise
def _is_output_already_done(self, task_id, output_category):
"""幂等检查:判断输出表里是否已有该 task_id 的有效数据"""
model_map = {
'warranty': ReportExtendedWarranty,
'equity': ReportEquityService,
'inshop': ReportLightReformInshop,
'park': ReportLightReformPark,
}
model = model_map.get(output_category)
if not model:
return True
cnt = model.query.filter_by(task_id=task_id, is_deleted=0).count()
return cnt > 0
# ============================================================
# 公共辅助方法(从 DataProcessor 复制)
# ============================================================
def _mark_task_failed(self, task_id, error_msg):
"""标记任务为失败状态,记录错误信息。"""
try:
task = DataProcessTask.query.filter_by(id=task_id).first()
if task:
task.status = 'FAILED'
task.error_msg = error_msg[:500]
db.session.commit()
logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
except Exception as e: except Exception as e:
logger.error(f"[标记失败] 更新任务失败状态时出错: {str(e)}")
db.session.rollback() db.session.rollback()
raise raise
def _cleanup_tmp_dir(self, tmp_dir):
"""清理临时目录(Windows 文件占用重试)。"""
import shutil
import time as _time
try:
if os.path.exists(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)}")
def _download_and_decrypt(self, task_id, tmp_dir):
"""下载 task_id 关联的所有 Excel 文件到 tmp_dir,返回 {form_type: local_path}"""
files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
result = {}
for f in files:
if not f.file_url:
logger.warning(f"[文件下载] form_type={f.form_type} 无 file_url,跳过")
continue
local_path = os.path.join(tmp_dir, f.file_name or f"{f.form_type}.xlsx")
try:
download_file(f.file_url, local_path)
result[f.form_type] = local_path
logger.info(f"[文件下载] {f.form_type} OK → {local_path}")
except Exception as e:
logger.error(f"[文件下载] {f.form_type} 失败: {e}")
result[f.form_type] = None
return result
# ============================================================ # ============================================================
# 通用 Excel 解析工具 # 核心处理逻辑
# ============================================================ # ============================================================
def _match_columns(self, columns, keywords_map):
"""模糊匹配列名。keywords_map = {标准名: [关键词列表]},返回 {标准名: 实际列名}"""
result = {}
std_names = list(columns)
for std, keywords in keywords_map.items():
for col in std_names:
col_lower = str(col).lower()
for kw in keywords:
if kw.lower() in col_lower:
result[std] = col
break
if std in result:
break
return result
def _safe_div(self, numerator, denominator, scale=2):
"""Decimal 安全除法,分母为 0 返回 0"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) / Decimal(str(denominator))).quantize(
Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def _safe_div_pct(self, numerator, denominator):
"""整数/整数 百分比(*100),返回 Decimal(10,6),四舍五入保留百分比后 2 位小数"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def _safe_div_pct_decimal(self, numerator, denominator):
"""Decimal/Decimal 百分比(*100)"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def _get_prev_month(self, month_str):
"""'2026-09' → '2026-08'"""
if not month_str or '-' not in month_str:
return ''
try:
parts = month_str.split('-')
y = int(parts[0])
m = int(parts[1])
if m == 1:
y -= 1
m = 12
else:
m -= 1
return f"{y}-{m:02d}"
except Exception:
return ''
def _fetch_prev_month_labor_ratio(self, task, base_records):
"""
从上月 BizBudgetAchieve 表取营销费用占比(人员工资占比)。
store_name 匹配 biz_budget_achieve.target_name 作为流量费名称。
返回 dict[store_name] = Decimal
"""
current_month = getattr(task, 'month', '')
prev_month = self._get_prev_month(current_month)
if not prev_month:
return {}
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
if not store_names:
return {}
results = {}
try:
rows = BizBudgetAchieve.query.filter(
BizBudgetAchieve.month == prev_month,
BizBudgetAchieve.is_deleted == 0,
).all()
for row in rows:
target = getattr(row, 'target_name', '') or ''
ratio = getattr(row, 'personnel_salary_ratio_current', None)
if ratio is None:
continue
for sn in store_names:
if sn in target or target in sn:
results[sn] = Decimal(str(ratio))
break
logger.info(f"[上月占比] month={prev_month} 匹配 {len(results)}/{len(store_names)}")
except Exception as e:
logger.warning(f"[上月占比] 查询失败: {e}")
return results
# ============================================================
# Excel 解析(多个共用)
# ============================================================
def _parse_region_map(self, file_path):
"""解析关系表,按 (业务类型, 省份) → 片区"""
logger.info(f"[关系表] 解析 {file_path}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning("[关系表] 读取失败,跳过")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = self._match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类'],
'province': ['省份', '省'],
'region_area': ['片区', '大区'],
})
if 'region_area' not in col_map or 'province' not in col_map:
logger.warning("[关系表] 缺少 片区/省份 关键列")
return {}
result = {}
for _, row in df.iterrows():
prov = str(row.get(col_map['province'], '')).strip()
area = str(row.get(col_map['region_area'], '')).strip()
if not prov or not area:
continue
bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
result[(bt, prov)] = area
result[('', prov)] = area
logger.info(f"[关系表] 片区映射 {len(result)} 条")
return result
def _parse_delivery_table(self, file_path):
"""
解析主机厂交车数据表(鸿蒙/广联共用结构)。
返回 dict[store_name] = delivery_cnt (int)
"""
logger.info(f"[主机厂交车] 解析 {file_path}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning(f"[主机厂交车] 读取失败 {file_path}")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = self._match_columns(df.columns, {
'store_name': ['门店名称', '厅店名称', '基础信息-门店'],
'delivery': ['总交付', '交车数', '交付量', '主机厂数据'],
})
if 'store_name' not in col_map:
logger.warning("[主机厂交车] 未找到门店名列")
return {}
store_col = col_map['store_name']
delivery_col = col_map.get('delivery')
result = {}
for _, row in df.iterrows():
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
cnt = 0
if delivery_col:
try:
v = row.get(delivery_col, 0)
if v is not None and not pd.isna(v):
cnt = int(float(v))
except (ValueError, TypeError):
cnt = 0
result[sn] = result.get(sn, 0) + cnt
logger.info(f"[主机厂交车] {file_path} → {len(result)} 个门店")
return result
# ============================================================
# 表 1:延保盈利测算
# ============================================================
def _parse_warranty_base(self, file_path):
"""
解析 SAAS门店预算分解表 sheet1,取 biz_type=2.3 的明细。
返回 list[dict]:store_name / brand / province / city / region_manager / ...
"""
logger.info(f"[SAAS预算分解-延保] 解析 {file_path}")
df = pd.read_excel(file_path, sheet_name=0, header=None)
header_row = 0
for i in range(min(5, len(df))):
row_vals = [str(v) if v is not None else '' for v in df.iloc[i].tolist()]
if any('门店' in v for v in row_vals):
header_row = i
break
df = pd.read_excel(file_path, sheet_name=0, header=header_row)
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = self._match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类', 'biz_type'],
'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省', 'province'],
'city': ['城市', '市', 'city'],
'region_manager': ['区域运营', '区域经理', '大区经理'],
'training_supervisor': ['培训督导', '督导'],
'biz_manager': ['业务经理'],
'resident_type': ['驻店类型', '驻店'],
})
logger.info(f"[SAAS预算分解-延保] 匹配列: {col_map}")
biz_col = col_map.get('biz_type')
store_col = col_map.get('store_name')
if not store_col:
logger.error("[SAAS预算分解-延保] 未找到门店名列")
return []
result = []
for _, row in df.iterrows():
if biz_col:
bt = str(row.get(biz_col, '')).strip()
if bt != '2.3':
continue
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result.append({
'store_name': sn,
'brand': str(row.get(col_map.get('brand', ''), '')).strip() if col_map.get('brand') else '',
'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
'training_supervisor': str(row.get(col_map.get('training_supervisor', ''), '')).strip() if col_map.get('training_supervisor') else '',
'biz_manager': str(row.get(col_map.get('biz_manager', ''), '')).strip() if col_map.get('biz_manager') else '',
'resident_type': str(row.get(col_map.get('resident_type', ''), '')).strip() if col_map.get('resident_type') else '',
})
logger.info(f"[SAAS预算分解-延保] biz_type=2.3 共 {len(result)} 条")
return result
def _process_extended_warranty(self, task): def _process_extended_warranty(self, task):
""" """
延保盈利测算完整处理流程: 延保盈利测算完整处理流程。
Step1 Excel(SAAS预算分解表 biz_type=2.3 + 关系表 + 主机厂交车) 与权益表的差异:
Step2 指标系统 API(biz=1 延保) - biz_type 过滤值 2.3(权益是 2.1)
Step3 业务系统 SQL(TODO 占位) - 指标系统 biz=1(权益是 3)
Step4 系统公式计算 + 上月预算达成占比 - 指标编码多 A066/A070/A086(整车延保/电池/安心包)
Step5 排名 + 批量入库 report_extended_warranty - 输出表多延保专属字段(vehicle_warranty_cnt / battery_warranty_cnt / easy_bag_cnt 及各自渗透率)
""" """
task_id = task.id task_id = task.id
period_start = getattr(task, 'period_start', None) period_start = getattr(task, 'period_start', None)
...@@ -452,42 +113,40 @@ class EarningsReportProcessor: ...@@ -452,42 +113,40 @@ class EarningsReportProcessor:
# ========== Step1: Excel ========== # ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"warranty_{task_id}_") tmp_dir = tempfile.mkdtemp(prefix=f"warranty_{task_id}_")
try: try:
file_map = self._download_and_decrypt(task.id, tmp_dir) file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表') saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path: if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表") raise Exception("缺少必需文件: SAAS门店预算分解表")
base_records = self._parse_warranty_base(saas_path) base_records = parse_saas_base(saas_path, BIZ_TYPE_WARRANTY)
rel_path = file_map.get('关系表') rel_path = file_map.get('关系表')
region_map = self._parse_region_map(rel_path) if rel_path else {} region_map = parse_region_map(rel_path) if rel_path else {}
delivery_map = {} delivery_map = {}
for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'): for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'):
fpath = file_map.get(ftype) fpath = file_map.get(ftype)
if fpath: if fpath:
part = self._parse_delivery_table(fpath) part = parse_delivery_table(fpath)
for k, v in part.items(): for k, v in part.items():
delivery_map[k] = delivery_map.get(k, 0) + v delivery_map[k] = delivery_map.get(k, 0) + v
finally: finally:
self._cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统 ========== # ========== Step2: 指标系统(biz=1 延保) ==========
indicator = IndicatorClient()
warranty_codes = ['A084', 'A075', 'A066', 'A070', 'A086', 'A036'] warranty_codes = ['A084', 'A075', 'A066', 'A070', 'A086', 'A036']
indicator_data = {} indicator_data = fetch_indicator_data(
if start_str and end_str: start_str, end_str, INDICATOR_BIZ_MAP['warranty'], warranty_codes)
indicator_data = indicator.fetch(start_str, end_str, Config.INDICATOR_BIZ_WARRANTY, warranty_codes)
# ========== Step3: 业务系统 SQL(TODO 占位) ========== # ========== Step3: 业务系统 SQL(TODO 占位) ==========
biz_sql_data = {} biz_sql_data = {}
logger.warning("[延保] Step3 业务系统 SQL 暂未实现") logger.warning("[延保] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月营销费用占比 ========== # ========== Step4: 上月营销费用占比 ==========
prev_labor_ratio_map = self._fetch_prev_month_labor_ratio(task, base_records) prev_labor_ratio_map = fetch_prev_month_labor_ratio(task, base_records)
# ========== Step5: 逐行计算 ========== # ========== Step5: 逐行公式计算 ==========
rows_to_insert = [] rows_to_insert = []
for rec in base_records: for rec in base_records:
store_name = rec.get('store_name', '') store_name = rec.get('store_name', '')
...@@ -497,6 +156,8 @@ class EarningsReportProcessor: ...@@ -497,6 +156,8 @@ class EarningsReportProcessor:
ind = indicator_data.get(store_name, {}) ind = indicator_data.get(store_name, {})
delivery_cnt = delivery_map.get(store_name, 0) delivery_cnt = delivery_map.get(store_name, 0)
# 指标系统取值
touch_cnt = int(Decimal(str(ind.get('A084', 0)))) touch_cnt = int(Decimal(str(ind.get('A084', 0))))
deal_cnt = int(Decimal(str(ind.get('A075', 0)))) deal_cnt = int(Decimal(str(ind.get('A075', 0))))
vehicle_warranty_cnt = int(Decimal(str(ind.get('A066', 0)))) vehicle_warranty_cnt = int(Decimal(str(ind.get('A066', 0))))
...@@ -504,13 +165,13 @@ class EarningsReportProcessor: ...@@ -504,13 +165,13 @@ class EarningsReportProcessor:
easy_bag_cnt = int(Decimal(str(ind.get('A086', 0)))) easy_bag_cnt = int(Decimal(str(ind.get('A086', 0))))
store_output_value = Decimal(str(ind.get('A036', 0))) store_output_value = Decimal(str(ind.get('A036', 0)))
# 公式 # ======= 公式 =======
penetration_rate = self._safe_div_pct(deal_cnt, delivery_cnt) penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
vehicle_warranty_penetration = self._safe_div_pct(vehicle_warranty_cnt, delivery_cnt) vehicle_warranty_penetration = safe_div_pct(vehicle_warranty_cnt, delivery_cnt)
vehicle_warranty_touch_convert = self._safe_div_pct(vehicle_warranty_cnt, touch_cnt) vehicle_warranty_touch_convert = safe_div_pct(vehicle_warranty_cnt, touch_cnt)
battery_warranty_penetration = self._safe_div_pct(battery_warranty_cnt, delivery_cnt) battery_warranty_penetration = safe_div_pct(battery_warranty_cnt, delivery_cnt)
easy_bag_penetration = self._safe_div_pct(easy_bag_cnt, delivery_cnt) easy_bag_penetration = safe_div_pct(easy_bag_cnt, delivery_cnt)
upgrade_unit_price = self._safe_div(store_output_value, deal_cnt, 2) upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
biz_data = biz_sql_data.get(store_name, {}) biz_data = biz_sql_data.get(store_name, {})
product_cost = biz_data.get('product_cost', Decimal('0')) product_cost = biz_data.get('product_cost', Decimal('0'))
...@@ -520,15 +181,15 @@ class EarningsReportProcessor: ...@@ -520,15 +181,15 @@ class EarningsReportProcessor:
guarantee_amount = Decimal('0') guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = self._safe_div_pct_decimal(market_fee, store_output_value) market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = prev_labor_ratio_map.get(store_name, Decimal('0')) marketing_fee_ratio = prev_labor_ratio_map.get(store_name, Decimal('0'))
marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) marketing_fee = (store_output_value * marketing_fee_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = self._safe_div_pct_decimal(service_fee, store_output_value) service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee total_cost = market_fee + marketing_fee + service_fee
cost_ratio = self._safe_div_pct_decimal(total_cost, store_output_value) cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
gross_profit = gl_share - total_cost gross_profit = gl_share - total_cost
gross_profit_rate = self._safe_div_pct_decimal(gross_profit, store_output_value) gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0: if gross_profit_rate > 0:
gross_profit_status = '盈利' gross_profit_status = '盈利'
...@@ -537,19 +198,22 @@ class EarningsReportProcessor: ...@@ -537,19 +198,22 @@ class EarningsReportProcessor:
else: else:
gross_profit_status = '亏损' gross_profit_status = '亏损'
region_area = region_map.get(('2.3', province), '') or region_map.get(('', province), '') region_area = region_map.get((BIZ_TYPE_WARRANTY, province), '') or region_map.get(('', province), '')
row = ReportExtendedWarranty( row = ReportExtendedWarranty(
task_id=task_id, task_id=task_id,
period_start=period_start, period_start=period_start,
period_end=period_end, period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''), region_area=region_area, province=province, city=rec.get('city', ''),
region_manager=rec.get('region_manager', ''), region_manager=rec.get('region_manager', ''),
training_supervisor=rec.get('training_supervisor', ''), training_supervisor=rec.get('training_supervisor', ''),
biz_manager=rec.get('biz_manager', ''), biz_manager=rec.get('biz_manager', ''),
resident_type=resident_type, store_name=store_name, brand=brand, resident_type=resident_type, store_name=store_name, brand=brand,
# 触客/成交
delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt, delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt,
penetration_rate=penetration_rate, penetration_rate=penetration_rate,
# 延保特有指标
vehicle_warranty_cnt=vehicle_warranty_cnt, vehicle_warranty_cnt=vehicle_warranty_cnt,
vehicle_warranty_penetration=vehicle_warranty_penetration, vehicle_warranty_penetration=vehicle_warranty_penetration,
vehicle_warranty_touch_convert=vehicle_warranty_touch_convert, vehicle_warranty_touch_convert=vehicle_warranty_touch_convert,
...@@ -557,6 +221,7 @@ class EarningsReportProcessor: ...@@ -557,6 +221,7 @@ class EarningsReportProcessor:
battery_warranty_penetration=battery_warranty_penetration, battery_warranty_penetration=battery_warranty_penetration,
easy_bag_cnt=easy_bag_cnt, easy_bag_cnt=easy_bag_cnt,
easy_bag_penetration=easy_bag_penetration, easy_bag_penetration=easy_bag_penetration,
# 产值/成本/费用/毛利
store_output_value=store_output_value, store_output_value=store_output_value,
upgrade_unit_price=upgrade_unit_price, upgrade_unit_price=upgrade_unit_price,
product_cost=product_cost, store_share=store_share, product_cost=product_cost, store_share=store_share,
...@@ -584,22 +249,3 @@ class EarningsReportProcessor: ...@@ -584,22 +249,3 @@ class EarningsReportProcessor:
db.session.flush() db.session.flush()
logger.info(f"[延保] 完成入库 {len(rows_to_insert)} 条") logger.info(f"[延保] 完成入库 {len(rows_to_insert)} 条")
# ============================================================
# 表 2-4:权益 / 轻改店中店 / 轻改园区店(骨架,后续填业务逻辑)
# ============================================================
def _process_equity_service(self, task):
"""【骨架】权益盈利测算 - biz=3 指标系统 + 同 SAAS 预算分解表,后续完善"""
logger.warning("[权益] 业务逻辑待实现,当前空跑占位")
pass
def _process_light_reform_inshop(self, task):
"""【骨架】轻改-店中店汇总 - biz=2 指标系统 + 二级表头解析,后续完善"""
logger.warning("[轻改店中店] 业务逻辑待实现,当前空跑占位")
pass
def _process_light_reform_park(self, task):
"""【骨架】轻改-园区店汇总 - biz=2 指标系统,后续完善"""
logger.warning("[轻改园区店] 业务逻辑待实现,当前空跑占位")
pass
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 权益表独立处理器
====================================
对应 ORM 表:report_equity_service
业务类型过滤:biz_type=2.1 (对比延保表的 2.3)
指标系统 biz 编码:3 (权益)
流程:
Step1 Excel(SAAS预算分解表 biz_type=2.1 + 关系表 + 主机厂交车)
Step2 指标系统 API(biz=3 权益)
Step3 业务系统 SQL(TODO 占位)
Step4 系统公式计算 + 上月预算达成占比
Step5 排名 + 批量入库
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir, is_output_already_done,
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table,
fetch_indicator_data, fetch_prev_month_labor_ratio,
safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportEquityService, db
logger = logging.getLogger('EquityProcessor')
class EquityProcessor:
"""权益盈利测算独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='equity'):
"""扫描 store_effect_earnings 任务并处理权益表"""
from models import DataProcessTask
logger.info(f"[equity] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[equity] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[equity] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[equity] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[equity] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[equity] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的权益表输出"""
task_id = task.id
if is_output_already_done(task_id, 'equity'):
logger.info(f"[equity] 任务 {task_id} 已处理过,跳过")
return
try:
self._process_equity_service(task)
db.session.commit()
logger.info(f"[equity] 任务 {task_id} 处理完成")
except Exception as e:
db.session.rollback()
raise
# ============================================================
# 核心处理逻辑
# ============================================================
def _process_equity_service(self, task):
"""
权益盈利测算完整处理流程。
与延保表的差异:
- biz_type 过滤值 2.1(延保是 2.3)
- 指标系统 biz=3(延保是 1)
- 指标编码仅 A084/A075/A036(延保还有 A066/A070/A086 延保专属字段)
- 输出表列更简洁(无延保/电池/安心包特有字段)
"""
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[权益] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"equity_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
# 权益表用 biz_type=2.1
base_records = parse_saas_base(saas_path, BIZ_TYPE_EQUITY)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
delivery_map = {}
for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'):
fpath = file_map.get(ftype)
if fpath:
part = parse_delivery_table(fpath)
for k, v in part.items():
delivery_map[k] = delivery_map.get(k, 0) + v
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(biz=3 权益) ==========
equity_codes = ['A084', 'A075', 'A036'] # 触客 / 成交 / 产值
indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP['equity'], equity_codes)
# ========== Step3: 业务系统 SQL(TODO 占位) ==========
biz_sql_data = {}
logger.warning("[权益] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月营销费用占比 ==========
prev_labor_ratio_map = fetch_prev_month_labor_ratio(task, base_records)
# ========== Step5: 逐行公式计算 ==========
rows_to_insert = []
for rec in base_records:
store_name = rec.get('store_name', '')
brand = rec.get('brand', '')
province = rec.get('province', '')
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
delivery_cnt = delivery_map.get(store_name, 0)
# 指标系统取值
touch_cnt = int(Decimal(str(ind.get('A084', 0))))
deal_cnt = int(Decimal(str(ind.get('A075', 0))))
store_output_value = Decimal(str(ind.get('A036', 0)))
# ======= 公式 =======
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
biz_data = biz_sql_data.get(store_name, {})
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0'))
store_share = biz_data.get('store_share', Decimal('0'))
guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = prev_labor_ratio_map.get(store_name, Decimal('0'))
marketing_fee = (store_output_value * marketing_fee_ratio).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
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
gross_profit = gl_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
region_area = region_map.get((BIZ_TYPE_EQUITY, province), '') or region_map.get(('', province), '')
row = ReportEquityService(
task_id=task_id,
period_start=period_start,
period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
region_manager=rec.get('region_manager', ''),
training_supervisor=rec.get('training_supervisor', ''),
biz_manager=rec.get('biz_manager', ''),
resident_type=resident_type, store_name=store_name, brand=brand,
# 触客/成交
delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt,
penetration_rate=penetration_rate,
# 产值/成本/费用/毛利
store_output_value=store_output_value,
upgrade_unit_price=upgrade_unit_price,
product_cost=product_cost, store_share=store_share,
guarantee_amount=guarantee_amount, gl_share=gl_share,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
marketing_fee=marketing_fee, marketing_fee_ratio=marketing_fee_ratio,
service_fee=service_fee, service_fee_ratio=service_fee_ratio,
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step6: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step7: 批量入库 ==========
ReportEquityService.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
batch = rows_to_insert[i:i + 500]
db.session.add_all(batch)
db.session.flush()
logger.info(f"[权益] 完成入库 {len(rows_to_insert)} 条")
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 共用工具模块
================================
被 warranty_processor / equity_processor / inshop_processor / park_processor 共同引用。
统一封装 Excel 下载解析、安全除法、指标系统调用、幂等检查、临时目录清理等。
"""
import os
import logging
import tempfile
import shutil
import time as _time
from decimal import Decimal, ROUND_HALF_UP
import pandas as pd
from models import (
DataProcessTask, DataProcessFile, BizBudgetAchieve,
ReportExtendedWarranty, ReportEquityService,
ReportLightReformInshop, ReportLightReformPark,
db,
)
from oss_utils import download_file
from indicator_client import IndicatorClient
from config import Config
logger = logging.getLogger('report_utils')
# ============================================================
# 调度器常量
# ============================================================
STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings'
# biz_type 过滤值(各表不同)
BIZ_TYPE_WARRANTY = '2.3' # 延保
BIZ_TYPE_EQUITY = '2.1' # 权益
# 指标系统 biz 编码
INDICATOR_BIZ_MAP = {
'warranty': Config.INDICATOR_BIZ_WARRANTY, # 1
'equity': Config.INDICATOR_BIZ_EQUITY, # 3
'light_reform': Config.INDICATOR_BIZ_LIGHT_REFORM, # 2
}
# ============================================================
# 任务状态管理
# ============================================================
def mark_task_failed(task_id, error_msg):
"""标记任务为失败状态(独立函数,无类依赖)。"""
try:
task = DataProcessTask.query.filter_by(id=task_id).first()
if task:
task.status = 'FAILED'
task.error_msg = (error_msg or '')[:500]
db.session.commit()
logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
except Exception as e:
logger.error(f"[标记失败] 更新失败: {e}")
db.session.rollback()
raise
def cleanup_tmp_dir(tmp_dir):
"""清理临时目录(Windows 文件占用重试 3 次)。"""
try:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir, ignore_errors=True)
for _ in range(3):
if not os.path.exists(tmp_dir):
break
_time.sleep(0.5)
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)}")
def is_output_already_done(task_id, output_category):
"""幂等检查:判断输出表里是否已有该 task_id 的有效数据"""
model_map = {
'warranty': ReportExtendedWarranty,
'equity': ReportEquityService,
'inshop': ReportLightReformInshop,
'park': ReportLightReformPark,
}
model = model_map.get(output_category)
if not model:
return True
cnt = model.query.filter_by(task_id=task_id, is_deleted=0).count()
return cnt > 0
# ============================================================
# Excel 下载 & 解析
# ============================================================
def download_all_files(task_id, tmp_dir):
"""
下载 task_id 关联的所有 Excel 文件到 tmp_dir。
返回 {form_type: local_path} (下载失败则值为 None)。
"""
files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
result = {}
for f in files:
if not f.file_url:
logger.warning(f"[文件下载] form_type={f.form_type} 无 file_url,跳过")
continue
local_path = os.path.join(tmp_dir, f.file_name or f"{f.form_type}.xlsx")
try:
download_file(f.file_url, local_path)
result[f.form_type] = local_path
logger.info(f"[文件下载] {f.form_type} OK → {local_path}")
except Exception as e:
logger.error(f"[文件下载] {f.form_type} 失败: {e}")
result[f.form_type] = None
return result
def match_columns(columns, keywords_map):
"""
模糊匹配列名。
keywords_map = {标准名: [关键词列表]},返回 {标准名: 实际列名}。
"""
result = {}
for std, keywords in keywords_map.items():
for col in columns:
col_lower = str(col).lower()
for kw in keywords:
if kw.lower() in col_lower:
result[std] = col
break
if std in result:
break
return result
def find_header_row(df, max_scan=5):
"""
在 DataFrame 前 max_scan 行中找到包含'门店'的表头行索引。
找不到返回 0。
"""
for i in range(min(max_scan, len(df))):
row_vals = [str(v) if v is not None else '' for v in df.iloc[i].tolist()]
if any('门店' in v for v in row_vals):
return i
return 0
def parse_saas_base(file_path, biz_type_filter):
"""
解析 SAAS门店预算分解表 sheet1,按 biz_type_filter 过滤。
返回 list[dict]:store_name / brand / province / city / region_manager /
training_supervisor / biz_manager / resident_type
"""
logger.info(f"[SAAS预算分解] 解析 {file_path}, 过滤 biz_type={biz_type_filter}")
df_raw = pd.read_excel(file_path, sheet_name=0, header=None)
header_row = find_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=0, header=header_row)
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类', 'biz_type'],
'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省', 'province'],
'city': ['城市', '市', 'city'],
'region_manager': ['区域运营', '区域经理', '大区经理'],
'training_supervisor': ['培训督导', '督导'],
'biz_manager': ['业务经理'],
'resident_type': ['驻店类型', '驻店'],
})
logger.info(f"[SAAS预算分解] 匹配列: {col_map}")
biz_col = col_map.get('biz_type')
store_col = col_map.get('store_name')
if not store_col:
logger.error("[SAAS预算分解] 未找到门店名列")
return []
result = []
for _, row in df.iterrows():
if biz_col:
bt = str(row.get(biz_col, '')).strip()
if bt != biz_type_filter:
continue
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result.append({
'store_name': sn,
'brand': str(row.get(col_map.get('brand', ''), '')).strip() if col_map.get('brand') else '',
'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
'training_supervisor': str(row.get(col_map.get('training_supervisor', ''), '')).strip() if col_map.get('training_supervisor') else '',
'biz_manager': str(row.get(col_map.get('biz_manager', ''), '')).strip() if col_map.get('biz_manager') else '',
'resident_type': str(row.get(col_map.get('resident_type', ''), '')).strip() if col_map.get('resident_type') else '',
})
logger.info(f"[SAAS预算分解] biz_type={biz_type_filter} 共 {len(result)} 条")
return result
def parse_region_map(file_path):
"""
解析关系表,按 (业务类型, 省份) → 片区。
返回 dict[(biz_type, province)] = region_area (额外包含 ('', province) fallback)。
"""
logger.info(f"[关系表] 解析 {file_path}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning("[关系表] 读取失败,跳过")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'biz_type': ['业务类型', '业务分类'],
'province': ['省份', '省'],
'region_area': ['片区', '大区'],
})
if 'region_area' not in col_map or 'province' not in col_map:
logger.warning("[关系表] 缺少 片区/省份 关键列")
return {}
result = {}
for _, row in df.iterrows():
prov = str(row.get(col_map['province'], '')).strip()
area = str(row.get(col_map['region_area'], '')).strip()
if not prov or not area:
continue
bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
result[(bt, prov)] = area
result[('', prov)] = area
logger.info(f"[关系表] 片区映射 {len(result)} 条")
return result
def parse_delivery_table(file_path):
"""
解析主机厂交车数据表(鸿蒙/广联共用结构)。
返回 dict[store_name] = delivery_cnt (int)。
"""
logger.info(f"[主机厂交车] 解析 {file_path}")
try:
df = pd.read_excel(file_path)
except Exception:
logger.warning(f"[主机厂交车] 读取失败 {file_path}")
return {}
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'store_name': ['门店名称', '厅店名称', '基础信息-门店'],
'delivery': ['总交付', '交车数', '交付量', '主机厂数据'],
})
if 'store_name' not in col_map:
logger.warning("[主机厂交车] 未找到门店名列")
return {}
store_col = col_map['store_name']
delivery_col = col_map.get('delivery')
result = {}
for _, row in df.iterrows():
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
cnt = 0
if delivery_col:
try:
v = row.get(delivery_col, 0)
if v is not None and not pd.isna(v):
cnt = int(float(v))
except (ValueError, TypeError):
cnt = 0
result[sn] = result.get(sn, 0) + cnt
logger.info(f"[主机厂交车] {file_path} → {len(result)} 个门店")
return result
# ============================================================
# 指标系统 API
# ============================================================
def fetch_indicator_data(start_str, end_str, biz_code, item_codes):
"""
调指标系统 API,返回 {merchantName: {itemCode: itemValue}}。
start_str / end_str: 'YYYY-MM-DD' 字符串,空则返回 {}。
"""
if not start_str or not end_str or not item_codes:
return {}
client = IndicatorClient()
return client.fetch(start_str, end_str, biz_code, item_codes)
# ============================================================
# 安全除法 / 百分比
# ============================================================
def safe_div(numerator, denominator, scale=2):
"""Decimal 安全除法,分母为 0 返回 Decimal('0')。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) / Decimal(str(denominator))).quantize(
Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def safe_div_pct(numerator, denominator):
"""整数/整数 → 百分比(*100),保留百分比后 2 位小数 → Decimal(10,6)。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def safe_div_pct_decimal(numerator, denominator):
"""Decimal/Decimal → 百分比(*100)。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
Decimal('0.010000'), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def prev_month(month_str):
"""'2026-09' → '2026-08'"""
if not month_str or '-' not in month_str:
return ''
try:
parts = month_str.split('-')
y = int(parts[0])
m = int(parts[1])
if m == 1:
y -= 1
m = 12
else:
m -= 1
return f"{y}-{m:02d}"
except Exception:
return ''
def fetch_prev_month_labor_ratio(task, base_records):
"""
从上月 BizBudgetAchieve 表取人员工资占比 → 营销费用占比。
store_name 模糊匹配 target_name。
返回 dict[store_name] = Decimal
"""
current_month = getattr(task, 'month', '')
pm = prev_month(current_month)
if not pm:
return {}
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
if not store_names:
return {}
results = {}
try:
rows = BizBudgetAchieve.query.filter(
BizBudgetAchieve.month == pm,
BizBudgetAchieve.is_deleted == 0,
).all()
for row in rows:
target = getattr(row, 'target_name', '') or ''
ratio = getattr(row, 'personnel_salary_ratio_current', None)
if ratio is None:
continue
for sn in store_names:
if sn in target or target in sn:
results[sn] = Decimal(str(ratio))
break
logger.info(f"[上月占比] month={pm} 匹配 {len(results)}/{len(store_names)}")
except Exception as e:
logger.warning(f"[上月占比] 查询失败: {e}")
return results
...@@ -278,8 +278,20 @@ class NewReportScheduler: ...@@ -278,8 +278,20 @@ class NewReportScheduler:
try: try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 store_effect_earnings 待处理任务, category={self.OUTPUT_CATEGORY}") logger.info(f"[{self.JOB_NAME}] 开始扫描 store_effect_earnings 待处理任务, category={self.OUTPUT_CATEGORY}")
with self.app.app_context(): with self.app.app_context():
from earnings_report_processor import EarningsReportProcessor # 4 个输出类别各自对应独立的 Processor 模块
processor = EarningsReportProcessor(app=self.app) from earnings_report_processor import WarrantyProcessor
from equity_processor import EquityProcessor
# 轻改两个处理器后续创建,暂时用占位
_CATEGORY_CLS = {
'warranty': WarrantyProcessor,
'equity': EquityProcessor,
'inshop': WarrantyProcessor, # TODO: 后续创建 light_reform_inshop_processor.py
'park': WarrantyProcessor, # TODO: 后续创建 light_reform_park_processor.py
}
cls = _CATEGORY_CLS.get(self.OUTPUT_CATEGORY)
if not cls:
raise ValueError(f"未知的 output_category: {self.OUTPUT_CATEGORY}")
processor = cls(app=self.app)
result = processor.scan_store_effect_earnings(self.OUTPUT_CATEGORY) result = processor.scan_store_effect_earnings(self.OUTPUT_CATEGORY)
self._last_run_result = result self._last_run_result = result
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!