light_reform_park_processor.py 18.7 KB
# -*- 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,
    parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
    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, biz_type='1.1')

            # 商务政策表(园区店处理版)
            commerce_map = {}
            cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)')
            if cp_path:
                commerce_map = parse_commerce_policy_park(cp_path, biz_type='1.1')

            # 人力成本表
            labor_map = {}
            lc_path = file_map.get('人力成本表')
            if lc_path:
                labor_map = parse_labor_cost(lc_path, biz_type='1.1')

            # 预算达成数据(商务)→ 装修分摊/房租水电/门店耗材/服务费占比
            budget_achieve_map = {}
            budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
            if budget_path:
                budget_achieve_map = parse_budget_achieve_excel(budget_path, biz_type='1.1')

        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 暂未实现")

        # ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
        prev_budget_map = budget_achieve_map

        # ========== 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'))

            # —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
            renovation_amortization = prorate_by_period(
                extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
                period_start, period_end)
            rent_utilities = prorate_by_period(
                extract_budget_ratio(prev_budget_map, sn, 'rent_utilities'),
                period_start, period_end)
            store_consumables = prorate_by_period(
                extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
                period_start, period_end)
            # 服务费占比:直营店强制 0,服务商直接取
            sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
                prev_budget_map, sn, 'service_provider_share_ratio')

            # ======= 公式 =======

            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)