Commit 2769193a by zhouhaibao

feat(data-process): 添加轻改店中店和园区店处理器

- 新增 LightReformInshopProcessor 处理器用于轻改店中店数据处理
- 新增 LightReformParkProcessor 处理器用于轻改园区店数据处理
- 实现店中店和园区店的独立数据扫描和处理流程
- 添加 Excel 文件解析和业务数据计算功能
- 实现双优先级数据取值策略(Excel 优先,SQL 回退)
- 添加园区店专用的反过滤解析方法 parse_saas_base_sheet2_exclude
- 实现批量数据入库和排名计算功能
1 parent dbc4d0cc
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 轻改店中店汇总独立处理器
============================================
对应 ORM 表:report_light_reform_inshop
输出类别:inshop
指标系统 biz 编码:2(轻改)
取值优先级:Excel 第一优先,SQL/指标系统第二优先(双优先模式)。
SQL 相关字段暂为 TODO 占位(biz_sql_data 默认空)。
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base_sheet2, parse_region_map,
parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand,
fetch_prev_month_budget_detail,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformInshop, db
logger = logging.getLogger('LightReformInshopProcessor')
class LightReformInshopProcessor:
"""轻改店中店汇总独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='inshop'):
"""扫描 store_effect_earnings 任务并处理轻改店中店汇总"""
from models import DataProcessTask
logger.info(f"[inshop] 开始扫描 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"[inshop] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[inshop] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[inshop] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的店中店汇总输出"""
task_id = task.id
category = 'inshop'
if is_subtask_completed(task_id, category):
logger.info(f"[inshop] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_light_reform_inshop(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[inshop] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
# ============================================================
# 核心处理
# ============================================================
def _process_light_reform_inshop(self, task):
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"inshop_{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门店预算分解表")
base_records = parse_saas_base_sheet2(saas_path)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 店中店交车触客表(区域运营填的,Excel 第一优先)
delivery_touch_map = {}
dt_path = file_map.get('店中店交车触客表')
if dt_path:
delivery_touch_map = parse_inshop_delivery_touch(dt_path)
# 商务政策表(店中店处理版)
commerce_map = {}
cp_path = file_map.get('商务政策表(店中店)') or file_map.get('商务政策表(店中店)')
if cp_path:
commerce_map = parse_commerce_policy_inshop(cp_path)
# 人力成本表
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path)
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 业务系统 SQL(TODO 占位) ==========
# 轻改店中店完全不调指标系统,所有 SQL 来源字段统一走 biz_sql_data
# 包含:成交数/产值、品类成交数、各类产值/成本、门店分成、市场费、施工收入等
biz_sql_data = {}
logger.warning("[轻改店中店] Step2 业务系统 SQL 暂未实现,相关字段默认 0")
# ========== Step4: 上月预算明细 ==========
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
prev_budget_map = fetch_prev_month_budget_detail(task, store_names)
# ========== Step5: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
# —— 基础维度 ——
region_area = region_map.get(('', province), '')
brand_category = is_luxury_brand(brand)
# —— 双优先:Excel 第一,SQL 回退 ——
dt_excel = delivery_touch_map.get(sn, {})
sql_data = biz_sql_data.get(sn, {})
sales_order_cnt = get_with_fallback(
dt_excel.get('sales_order_cnt'), sql_data.get('sales_order_cnt', 0))
sales_touch_cnt = get_with_fallback(
dt_excel.get('sales_touch_cnt'), sql_data.get('sales_touch_cnt', 0))
delivery_cnt = get_with_fallback(
dt_excel.get('delivery_cnt'), sql_data.get('delivery_cnt', 0))
delivery_touch_cnt = get_with_fallback(
dt_excel.get('delivery_touch_cnt'), sql_data.get('delivery_touch_cnt', 0))
aftersales_baohui_cnt = get_with_fallback(
dt_excel.get('aftersales_baohui_cnt'), sql_data.get('aftersales_baohui_cnt', 0))
aftersales_shigu_cnt = get_with_fallback(
dt_excel.get('aftersales_shigu_cnt'), sql_data.get('aftersales_shigu_cnt', 0))
aftersales_touch_cnt = get_with_fallback(
dt_excel.get('aftersales_touch_cnt'), sql_data.get('aftersales_touch_cnt', 0))
purchase_indicator = dt_excel.get('purchase_indicator', '')
# —— 业务系统 SQL 取值(TODO 占位,后续补 SQL 映射)——
total_deal_cnt = int(Decimal(str(sql_data.get('total_deal_cnt', 0))))
store_output_value = Decimal(str(sql_data.get('store_output_value', 0)))
# —— 成交数/产值相关 SQL(TODO 占位,从 biz_sql_data 读)——
window_film_oe_cnt = sql_data.get('window_film_oe_cnt', 0)
window_film_nonoe_cnt = sql_data.get('window_film_nonoe_cnt', 0)
car_wrap_oe_cnt = sql_data.get('car_wrap_oe_cnt', 0)
car_wrap_nonoe_cnt = sql_data.get('car_wrap_nonoe_cnt', 0)
premium_oe_cnt = sql_data.get('premium_oe_cnt', 0)
premium_nonoe_cnt = sql_data.get('premium_nonoe_cnt', 0)
pedal_cnt = sql_data.get('pedal_cnt', 0)
internal_settle_value = sql_data.get('internal_settle_value', Decimal('0'))
oe_output_value = sql_data.get('oe_output_value', Decimal('0'))
nonoe_output_value = sql_data.get('nonoe_output_value', Decimal('0'))
product_cost_finance = sql_data.get('product_cost_finance', Decimal('0'))
internal_settle_cost = sql_data.get('internal_settle_cost', Decimal('0'))
oe_product_cost = sql_data.get('oe_product_cost', Decimal('0'))
nonoe_product_cost = sql_data.get('nonoe_product_cost', Decimal('0'))
window_film_cost = sql_data.get('window_film_cost', Decimal('0'))
car_wrap_cost = sql_data.get('car_wrap_cost', Decimal('0'))
premium_cost = sql_data.get('premium_cost', Decimal('0'))
store_share = sql_data.get('store_share', Decimal('0'))
construction_income = sql_data.get('construction_income', Decimal('0'))
market_fee_raw = sql_data.get('market_fee', Decimal('0'))
# —— 商务政策(店中店)——
cp = commerce_map.get(sn, {})
oe_film_unit = Decimal(str(cp.get('oe_window_film_cost', 0)))
oe_wrap_unit = Decimal(str(cp.get('oe_car_wrap_cost', 0)))
oe_premium_unit = Decimal(str(cp.get('oe_premium_cost', 0)))
pedal_unit = Decimal(str(cp.get('pedal_cost', 0)))
nonoe_film_unit = Decimal(str(cp.get('nonoe_window_film_cost', 0)))
nonoe_wrap_unit = Decimal(str(cp.get('nonoe_car_wrap_cost', 0)))
nonoe_premium_unit = Decimal(str(cp.get('nonoe_premium_cost', 0)))
construction_cost_post = Decimal(str(cp.get('construction_cost_post', 0)))
frontline_ratio_cp = Decimal(str(cp.get('frontline_incentive_ratio', 0)))
# —— 上月预算明细 ——
pb = prev_budget_map.get(sn, {})
renovation_amortization = pb.get('renovation_amortization', Decimal('0'))
rent_utilities = pb.get('rent_utilities', Decimal('0'))
store_consumables = pb.get('store_consumables', Decimal('0'))
sp_ratio = pb.get('service_provider_share_ratio', Decimal('0'))
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
# ======= 公式计算 =======
# 触客率
sales_touch_rate = safe_div_pct(sales_touch_cnt, sales_order_cnt)
delivery_touch_rate = safe_div_pct(delivery_touch_cnt, delivery_cnt)
aftersales_denom = aftersales_baohui_cnt + aftersales_shigu_cnt
aftersales_touch_rate = safe_div_pct(aftersales_touch_cnt, aftersales_denom)
total_touch_cnt = sales_touch_cnt + delivery_touch_cnt + aftersales_touch_cnt
# 产值/合计
total_output_value = store_output_value + internal_settle_value
# 施工成本(前置 = 数量 * 单价)
construction_cost_oe = (
window_film_oe_cnt * oe_film_unit +
car_wrap_oe_cnt * oe_wrap_unit +
premium_oe_cnt * oe_premium_unit +
pedal_cnt * pedal_unit
)
construction_cost_nonoe = (
window_film_nonoe_cnt * nonoe_film_unit +
car_wrap_nonoe_cnt * nonoe_wrap_unit +
premium_nonoe_cnt * nonoe_premium_unit
)
# 直营才加后置施工费(按主订单台次 = delivery_cnt)
construction_cost_post_total = Decimal('0')
if operate_type != '服务商':
construction_cost_post_total = construction_cost_post * Decimal(str(delivery_cnt))
construction_cost = construction_cost_oe + construction_cost_nonoe + construction_cost_post_total
construction_cost_ratio = safe_div_pct_decimal(construction_cost, store_output_value)
# 一线激励
frontline_incentive = (store_output_value * frontline_ratio_cp).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
frontline_incentive_ratio = frontline_ratio_cp
# 进销差(未分成)
gross_profit_pre_share = (
store_output_value - product_cost_finance - construction_cost - frontline_incentive
)
gross_profit_pre_share_ratio = safe_div_pct_decimal(gross_profit_pre_share, store_output_value)
# 门店分成占比/单车利润
store_share_ratio = safe_div_pct_decimal(store_share, store_output_value)
store_share_per_car = safe_div(store_share, delivery_cnt, 2)
guarantee_amount = Decimal('0')
gl_share = gross_profit_pre_share - store_share - guarantee_amount
gl_share_ratio = safe_div_pct_decimal(gl_share, store_output_value)
# 内部结算
internal_settle_profit = internal_settle_value - internal_settle_cost
# 广联总分成
gl_total_share = gl_share + construction_income + internal_settle_profit
# 客单价/渗透
avg_unit_price_delivery = safe_div(store_output_value, delivery_cnt, 2)
avg_price_target = rec.get('avg_price_target', Decimal('0'))
avg_price_diff = avg_unit_price_delivery - avg_price_target
delivery_touch_unit_price = safe_div(store_output_value, delivery_touch_cnt, 2)
upgrade_unit_price = safe_div(store_output_value, total_deal_cnt, 2)
total_penetration_rate = safe_div_pct(total_deal_cnt, delivery_cnt)
window_film_penetration = safe_div_pct(window_film_oe_cnt, delivery_cnt)
car_wrap_penetration = safe_div_pct(car_wrap_oe_cnt, delivery_cnt)
premium_penetration = safe_div_pct(premium_oe_cnt, delivery_cnt)
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value)
# 市场费:若一线激励存在(不为 0),则只算管理层市场费1+2
# 这里 market_fee_raw 已经是 TODO 占位值,先原样取
market_fee = market_fee_raw
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
# 营销人员成本
marketing_personnel_cost = Decimal('0')
if operate_type == '直营':
marketing_personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') +
store_output_value * Decimal('0.04')
)
marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value)
# 服务商分成
service_provider_share = (store_output_value * sp_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_provider_share_ratio = sp_ratio
# 成本总计
total_cost = (
marketing_personnel_cost + construction_cost + market_fee +
renovation_amortization + rent_utilities + store_consumables +
service_provider_share
)
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
# 毛利
gross_profit = gl_total_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 = '亏损'
row = ReportLightReformInshop(
task_id=task_id, period_start=period_start, period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', ''), biz_line=rec.get('biz_line', '1.12'),
operate_type=operate_type, region_manager=rec.get('region_manager', ''),
park_name=rec.get('park_name', ''), store_name=sn, brand=brand,
brand_category=brand_category, purchase_indicator=purchase_indicator,
# 销售
sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt,
sales_touch_rate=sales_touch_rate,
# 交付
delivery_cnt=delivery_cnt, delivery_touch_cnt=delivery_touch_cnt,
delivery_touch_rate=delivery_touch_rate,
# 售后
aftersales_baohui_cnt=aftersales_baohui_cnt,
aftersales_shigu_cnt=aftersales_shigu_cnt,
aftersales_touch_cnt=aftersales_touch_cnt,
aftersales_touch_rate=aftersales_touch_rate,
total_touch_cnt=total_touch_cnt, total_deal_cnt=total_deal_cnt,
# 品类成交
window_film_oe_cnt=window_film_oe_cnt,
window_film_nonoe_cnt=window_film_nonoe_cnt,
car_wrap_oe_cnt=car_wrap_oe_cnt,
car_wrap_nonoe_cnt=car_wrap_nonoe_cnt,
premium_oe_cnt=premium_oe_cnt,
premium_nonoe_cnt=premium_nonoe_cnt,
pedal_cnt=pedal_cnt,
# 产值
store_output_value=store_output_value,
internal_settle_value=internal_settle_value,
total_output_value=total_output_value,
oe_output_value=oe_output_value,
nonoe_output_value=nonoe_output_value,
# 客单/渗透
avg_unit_price_delivery=avg_unit_price_delivery,
avg_price_target=avg_price_target,
avg_price_diff=avg_price_diff,
delivery_touch_unit_price=delivery_touch_unit_price,
upgrade_unit_price=upgrade_unit_price,
total_penetration_rate=total_penetration_rate,
window_film_penetration=window_film_penetration,
car_wrap_penetration=car_wrap_penetration,
premium_penetration=premium_penetration,
# 产品成本
product_cost_finance=product_cost_finance,
internal_settle_cost=internal_settle_cost,
oe_product_cost=oe_product_cost,
nonoe_product_cost=nonoe_product_cost,
window_film_cost=window_film_cost,
car_wrap_cost=car_wrap_cost,
premium_cost=premium_cost,
product_cost_ratio=product_cost_ratio,
# 施工/激励/进销差/门店分成/兜底/广联
construction_cost=construction_cost,
construction_cost_ratio=construction_cost_ratio,
frontline_incentive=frontline_incentive,
frontline_incentive_ratio=frontline_incentive_ratio,
gross_profit_pre_share=gross_profit_pre_share,
gross_profit_pre_share_ratio=gross_profit_pre_share_ratio,
store_share=store_share,
store_share_per_car=store_share_per_car,
guarantee_amount=guarantee_amount,
gl_share=gl_share,
gl_share_ratio=gl_share_ratio,
# 广联总分成
construction_income=construction_income,
internal_settle_profit=internal_settle_profit,
gl_total_share=gl_total_share,
# 营销/市场/装修/服务商
marketing_personnel_cost=marketing_personnel_cost,
marketing_personnel_ratio=marketing_personnel_ratio,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
renovation_amortization=renovation_amortization,
rent_utilities=rent_utilities,
store_consumables=store_consumables,
service_provider_share=service_provider_share,
service_provider_share_ratio=service_provider_share_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: 批量入库 ==========
ReportLightReformInshop.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)} 条")
return len(rows_to_insert)
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 轻改园区店汇总独立处理器
============================================
对应 ORM 表:report_light_reform_park
输出类别:park
指标系统:✅ 有(成交数 A075 — 用户明确指定)
关键差异(对比店中店):
- sheet2 反过滤(不包含鸿蒙/AITO/问界/智界/享界/尚界/尊界)
- 用"园区店交车触客表"和"商务政策表(园区店)"
- 施工成本是固定公式(窗膜×95 + 车衣×900 + 精品×60 + 无效×50)
- 园区名称从 Excel park_name 列直接取
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base_sheet2_exclude, parse_region_map,
parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand,
fetch_prev_month_budget_detail, fetch_indicator_data,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformPark, db
logger = logging.getLogger('LightReformParkProcessor')
class LightReformParkProcessor:
"""轻改园区店汇总独立处理器"""
def __init__(self, app=None):
self.app = app
def scan_store_effect_earnings(self, output_category='park'):
from models import DataProcessTask
logger.info(f"[park] 开始扫描 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"[park] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[park] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[park] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
task_id = task.id
category = 'park'
if is_subtask_completed(task_id, category):
logger.info(f"[park] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_light_reform_park(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
# ============================================================
# 核心处理
# ============================================================
def _process_light_reform_park(self, task):
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"park_{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门店预算分解表")
# 园区店用反过滤(不包含品牌关键字)
base_records = parse_saas_base_sheet2_exclude(saas_path)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 园区店交车触客表
delivery_touch_map = {}
dt_path = file_map.get('园区店交车触客表')
if dt_path:
delivery_touch_map = parse_park_delivery_touch(dt_path)
# 商务政策表(园区店处理版)
commerce_map = {}
cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)')
if cp_path:
commerce_map = parse_commerce_policy_park(cp_path)
# 人力成本表
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path)
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统 biz=2 轻改 ==========
park_codes = ['A075'] # A075=成交数(园区店唯一指标)
indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP.get('light_reform', 2), park_codes)
# ========== Step3: 业务系统 SQL(TODO 占位) ==========
# 窗膜/车衣/精品成交数、产值、产品成本、流量费、市场费、预估流量等
biz_sql_data = {}
logger.warning("[轻改园区店] Step3 业务系统 SQL 暂未实现,相关字段默认 0")
# ========== Step4: 上月预算明细 ==========
store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
prev_budget_map = fetch_prev_month_budget_detail(task, store_names)
# ========== Step5: 合作门店数量(按 park_name 聚合) ==========
from collections import Counter
park_counter = Counter(r.get('park_name', '') for r in base_records if r.get('park_name'))
# ========== Step6: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
park_name = rec.get('park_name', '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand) # 类型=豪华/非豪华
partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 ——
pt_excel = delivery_touch_map.get(sn, {})
sql_data = biz_sql_data.get(sn, {})
delivery_cnt = get_with_fallback(
pt_excel.get('delivery_cnt'), sql_data.get('delivery_cnt', 0))
arrival_cnt = get_with_fallback(
pt_excel.get('arrival_cnt'), sql_data.get('arrival_cnt', 0))
arrival_invalid_cnt = get_with_fallback(
pt_excel.get('arrival_invalid_cnt'), sql_data.get('arrival_invalid_cnt', 0))
purchase_indicator = pt_excel.get('purchase_indicator', '')
# —— 指标系统 A075 ——
ind = indicator_data.get(sn, {})
deal_cnt = int(Decimal(str(ind.get('A075', sql_data.get('deal_cnt', 0)))))
# —— SQL 取值(TODO 占位)——
store_sales_output = Decimal(str(sql_data.get('store_sales_output', 0)))
internal_settle_value = Decimal(str(sql_data.get('internal_settle_value', Decimal('0'))))
window_film_cnt = sql_data.get('window_film_cnt', 0)
car_wrap_cnt = sql_data.get('car_wrap_cnt', 0)
premium_cnt = sql_data.get('premium_cnt', 0)
est_traffic = sql_data.get('est_traffic', 0)
product_cost_finance = Decimal(str(sql_data.get('product_cost_finance', Decimal('0'))))
internal_settle_cost = Decimal(str(sql_data.get('internal_settle_cost', Decimal('0'))))
traffic_fee_finance = Decimal(str(sql_data.get('traffic_fee_finance', Decimal('0'))))
market_fee_weighted = Decimal(str(sql_data.get('market_fee_weighted', Decimal('0'))))
# —— 商务政策(园区店)——
cp = commerce_map.get(sn, {})
traffic_fee_per_car = Decimal(str(cp.get('traffic_fee_per_car', 0)))
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
# —— 预算目标 ——
avg_price_target = rec.get('avg_price_target', Decimal('0'))
est_delivery_cnt = rec.get('est_delivery_cnt', 0)
est_output_value_raw = rec.get('est_output_value', Decimal('0'))
# —— 上月预算明细 ——
pb = prev_budget_map.get(sn, {})
renovation_amortization = pb.get('renovation_amortization', Decimal('0'))
rent_utilities = pb.get('rent_utilities', Decimal('0'))
store_consumables = pb.get('store_consumables', Decimal('0'))
sp_ratio = pb.get('service_provider_share_ratio', Decimal('0'))
# ======= 公式 =======
total_output_value = store_sales_output + internal_settle_value
# 产值达成进度(预估总产值按交车数占比分摊)
# 简化:直接用 est_output_value_raw(后续如有同 park 多门店需分摊逻辑再改)
est_output_value = est_output_value_raw
if est_output_value and est_output_value > 0:
# 同 park 多门店时按预估交车数占比分摊
pass # TODO: 如果 Excel 有 park 维度总量,这里需按 store 分摊
output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
# 转化率链路
valid_arrival = arrival_cnt - arrival_invalid_cnt # 有效到店
invalid_arrival_rate = safe_div_pct(arrival_invalid_cnt, arrival_cnt)
arrival_rate = safe_div_pct(arrival_cnt, delivery_cnt)
conversion_rate = safe_div_pct(deal_cnt, arrival_cnt)
avg_unit_price_arrival = safe_div(store_sales_output, valid_arrival, 2)
avg_price_diff = avg_unit_price_arrival - avg_price_target
upgrade_unit_price = safe_div(store_sales_output, deal_cnt, 2)
# 品类转化率
window_film_convert = safe_div_pct(window_film_cnt, arrival_cnt)
car_wrap_convert = safe_div_pct(car_wrap_cnt, arrival_cnt)
premium_convert = safe_div_pct(premium_cnt, arrival_cnt)
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_sales_output)
# 流量费:优先商务政策按台次算,否则用财务列表流量费
traffic_fee_order = (traffic_fee_per_car * Decimal(str(valid_arrival))
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
store_traffic_fee = traffic_fee_order if traffic_fee_order and traffic_fee_order > 0 else traffic_fee_finance
traffic_fee_ratio = safe_div_pct_decimal(store_traffic_fee, store_sales_output)
# 广联分成
gl_share = store_sales_output - product_cost_finance - store_traffic_fee
gl_share_ratio = safe_div_pct_decimal(gl_share, store_sales_output)
internal_settle_profit = internal_settle_value - internal_settle_cost
gl_total_share = gl_share + internal_settle_profit
# 人员成本(直营才算)
personnel_cost = Decimal('0')
if operate_type == '直营':
personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') +
store_sales_output * Decimal('0.04')
)
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
# 施工成本(直营固定公式)
construction_cost = Decimal('0')
if operate_type != '服务商':
construction_cost = (
Decimal(str(window_film_cnt)) * Decimal('95') +
Decimal(str(car_wrap_cnt)) * Decimal('900') +
Decimal(str(premium_cnt)) * Decimal('60') +
Decimal(str(arrival_invalid_cnt)) * Decimal('50')
)
construction_cost_ratio = safe_div_pct_decimal(construction_cost, store_sales_output)
market_fee_weighted_ratio = safe_div_pct_decimal(market_fee_weighted, store_sales_output)
# 服务费
service_fee = (store_sales_output * sp_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = sp_ratio if operate_type != '直营' else Decimal('0')
renovation_ratio = safe_div_pct_decimal(renovation_amortization, store_sales_output)
rent_utilities_ratio = safe_div_pct_decimal(rent_utilities, store_sales_output)
store_consumables_ratio = safe_div_pct_decimal(store_consumables, store_sales_output)
# 成本总计
total_cost = (
personnel_cost + construction_cost + market_fee_weighted +
service_fee + renovation_amortization + rent_utilities + store_consumables
)
cost_ratio = safe_div_pct_decimal(total_cost, store_sales_output)
# 毛利
gross_profit = gl_total_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_sales_output)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
row = ReportLightReformPark(
task_id=task_id, period_start=period_start, period_end=period_end,
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', '园区店'),
operate_type=operate_type, partner_store_cnt=partner_store_cnt,
region_manager=rec.get('region_manager', ''),
park_name=park_name, store_name=sn, brand=brand,
biz_type=biz_type, purchase_indicator=purchase_indicator,
# 触客/交车/转化
delivery_cnt=delivery_cnt, arrival_cnt=arrival_cnt,
arrival_invalid_cnt=arrival_invalid_cnt,
invalid_arrival_rate=invalid_arrival_rate,
arrival_rate=arrival_rate,
deal_cnt=deal_cnt, conversion_rate=conversion_rate,
# 产值/客单
store_sales_output=store_sales_output,
internal_settle_value=internal_settle_value,
total_output_value=total_output_value,
output_progress=output_progress,
avg_unit_price_arrival=avg_unit_price_arrival,
avg_price_target=avg_price_target,
avg_price_diff=avg_price_diff,
upgrade_unit_price=upgrade_unit_price,
# 品类成交+转化
window_film_cnt=window_film_cnt, window_film_convert=window_film_convert,
car_wrap_cnt=car_wrap_cnt, car_wrap_convert=car_wrap_convert,
premium_cnt=premium_cnt, premium_convert=premium_convert,
# 预算
est_traffic=est_traffic,
est_delivery_cnt=est_delivery_cnt,
est_output_value=est_output_value,
# 成本/流量费/广联
product_cost_finance=product_cost_finance,
product_cost_ratio=product_cost_ratio,
internal_settle_cost=internal_settle_cost,
traffic_fee_finance=traffic_fee_finance,
traffic_fee_per_car=traffic_fee_per_car,
traffic_fee_order=traffic_fee_order,
store_traffic_fee=store_traffic_fee,
traffic_fee_ratio=traffic_fee_ratio,
gl_share=gl_share, gl_share_ratio=gl_share_ratio,
internal_settle_profit=internal_settle_profit,
gl_total_share=gl_total_share,
# 人/施/市/服/装/租/耗
personnel_cost=personnel_cost,
personnel_cost_ratio=personnel_cost_ratio,
construction_cost=construction_cost,
construction_cost_ratio=construction_cost_ratio,
market_fee_weighted=market_fee_weighted,
market_fee_weighted_ratio=market_fee_weighted_ratio,
service_fee=service_fee,
service_fee_ratio=service_fee_ratio,
renovation_amortization=renovation_amortization,
renovation_ratio=renovation_ratio,
rent_utilities=rent_utilities,
rent_utilities_ratio=rent_utilities_ratio,
store_consumables=store_consumables,
store_consumables_ratio=store_consumables_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)
# ========== Step7: 排名 ==========
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
# ========== Step8: 批量入库 ==========
ReportLightReformPark.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
db.session.add_all(rows_to_insert[i:i + 500])
db.session.flush()
logger.info(f"[轻改园区店] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)
...@@ -586,6 +586,68 @@ def parse_saas_base_sheet2(file_path): ...@@ -586,6 +586,68 @@ def parse_saas_base_sheet2(file_path):
return result return result
def parse_saas_base_sheet2_exclude(file_path):
"""
解析 SAAS门店预算分解表 sheet2,按品牌关键字**反过滤**(不包含关键字的保留)。
用于轻改园区店。
返回 list[dict]:同 parse_saas_base_sheet2,额外带 est_delivery_cnt / est_output_value / est_output_value_original
"""
logger.info(f"[SAAS预算分解-sheet2-exclude] 解析 {file_path}")
df_raw = pd.read_excel(file_path, sheet_name=1, header=None)
header_row = find_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=1, header=header_row)
df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, {
'park_name': ['园区名称', '园区'],
'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
'brand': ['品牌', 'brand'],
'province': ['省份', '省'],
'city': ['城市', '市'],
'park_type': ['园区类型'],
'operate_type': ['驻店类型', '经营属性', '驻店'],
'region_manager': ['区域经理', '区域运营'],
'avg_price_target': ['预估平均客单价', '平客目标值'],
'est_delivery_cnt': ['预估交车数'],
'est_output_value': ['预估产值纠偏', '预估产值(纠偏)', '预估总产值'],
})
if 'store_name' not in col_map:
logger.error("[SAAS预算分解-sheet2-exclude] 未找到门店名列")
return []
brand_col = col_map.get('brand')
store_col = col_map['store_name']
result = []
for _, row in df.iterrows():
brand_val = str(row.get(brand_col, '')).strip() if brand_col else ''
brand_text = (brand_val + ' ' + str(row.get(store_col, ''))).strip()
# 反过滤:包含关键字 → 跳过
if brand_val and any(kw in brand_text for kw in LIGHT_REFORM_BRAND_KEYWORDS):
continue
sn = str(row.get(store_col, '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result.append({
'park_name': str(row.get(col_map.get('park_name', ''), '')).strip() if col_map.get('park_name') else '',
'store_name': sn,
'brand': brand_val,
'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 '',
'park_type': str(row.get(col_map.get('park_type', ''), '')).strip() if col_map.get('park_type') else '园区店',
'operate_type': str(row.get(col_map.get('operate_type', ''), '')).strip() if col_map.get('operate_type') else '',
'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
'avg_price_target': _to_decimal(row.get(col_map.get('avg_price_target', ''), '')) if col_map.get('avg_price_target') else Decimal('0'),
'est_delivery_cnt': _to_int(row.get(col_map.get('est_delivery_cnt', ''), 0)) if col_map.get('est_delivery_cnt') else 0,
'est_output_value': _to_decimal(row.get(col_map.get('est_output_value', ''), '')) if col_map.get('est_output_value') else Decimal('0'),
})
logger.info(f"[SAAS预算分解-sheet2-exclude] 反过滤后共 {len(result)} 条")
return result
def _to_decimal(val): def _to_decimal(val):
"""安全转 Decimal""" """安全转 Decimal"""
if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'): if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'):
...@@ -806,3 +868,75 @@ def is_luxury_brand(brand_name): ...@@ -806,3 +868,75 @@ def is_luxury_brand(brand_name):
if row and row.is_luxury == 1: if row and row.is_luxury == 1:
return '豪华' return '豪华'
return '非豪华' return '非豪华'
def parse_park_delivery_touch(file_path):
"""
解析园区店交车触客表(区域运营填写)。
返回 dict[store_name] = {delivery_cnt, arrival_cnt, arrival_invalid_cnt, purchase_indicator}
"""
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_cnt': ['交车数', '交车', '新车交付'],
'arrival_cnt': ['到店数', '到店'],
'arrival_invalid_cnt': ['到店无效', '无效客户数', '到店无效客户'],
'purchase_indicator': ['采买', '兜底指标', '采买兜底'],
})
if 'store_name' not in col_map:
logger.warning("[园区店交车触客表] 未找到门店名列")
return {}
result = {}
for _, row in df.iterrows():
sn = str(row.get(col_map['store_name'], '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result[sn] = {
'delivery_cnt': _to_int(row.get(col_map.get('delivery_cnt', ''), 0)),
'arrival_cnt': _to_int(row.get(col_map.get('arrival_cnt', ''), 0)),
'arrival_invalid_cnt': _to_int(row.get(col_map.get('arrival_invalid_cnt', ''), 0)),
'purchase_indicator': str(row.get(col_map.get('purchase_indicator', ''), '')).strip() if col_map.get('purchase_indicator') else '',
}
logger.info(f"[园区店交车触客表] {len(result)} 个门店")
return result
def parse_commerce_policy_park(file_path):
"""
解析商务政策表(园区店处理版)。
返回 dict[store_name] = {traffic_fee_per_car, ...} —— 门店分成参考(按单台计算流量/台)
"""
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': ['门店名称', '门店名'],
'traffic_fee_per_car': ['门店分成参考', '按单台计算流量', '流量费/台', '单台流量费'],
})
if 'store_name' not in col_map:
logger.warning("[商务政策-园区店] 未找到门店名列")
return {}
result = {}
for _, row in df.iterrows():
sn = str(row.get(col_map['store_name'], '')).strip()
if not sn or sn in ('nan', 'None', ''):
continue
result[sn] = {
'traffic_fee_per_car': _to_decimal(row.get(col_map.get('traffic_fee_per_car', ''), 0)),
}
logger.info(f"[商务政策-园区店] {len(result)} 个门店")
return result
...@@ -282,12 +282,12 @@ class NewReportScheduler: ...@@ -282,12 +282,12 @@ class NewReportScheduler:
from earnings_report_processor import WarrantyProcessor from earnings_report_processor import WarrantyProcessor
from equity_processor import EquityProcessor from equity_processor import EquityProcessor
from light_reform_inshop_processor import LightReformInshopProcessor from light_reform_inshop_processor import LightReformInshopProcessor
# 轻改园区店后续创建,暂时用占位 from light_reform_park_processor import LightReformParkProcessor
_CATEGORY_CLS = { _CATEGORY_CLS = {
'warranty': WarrantyProcessor, 'warranty': WarrantyProcessor,
'equity': EquityProcessor, 'equity': EquityProcessor,
'inshop': LightReformInshopProcessor, 'inshop': LightReformInshopProcessor,
'park': WarrantyProcessor, # TODO: 后续创建 light_reform_park_processor.py 'park': LightReformParkProcessor,
} }
cls = _CATEGORY_CLS.get(self.OUTPUT_CATEGORY) cls = _CATEGORY_CLS.get(self.OUTPUT_CATEGORY)
if not cls: if not cls:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!