equity_processor.py 10.9 KB
# -*- 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,
    update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
    SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
    download_all_files,
    parse_saas_base, parse_region_map, parse_delivery_table,
    parse_budget_achieve_excel,
    fetch_indicator_data,
    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
        category = 'equity'

        if is_subtask_completed(task_id, category):
            logger.info(f"[equity] 任务 {task_id} 子任务已 COMPLETED,跳过")
            return

        update_subtask(task_id, category, SUBTASK_PROCESSING)
        db.session.commit()

        row_count = 0
        try:
            row_count = self._process_equity_service(task)
            update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
            db.session.commit()
            logger.info(f"[equity] 任务 {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_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

            # 预算达成数据(商务)→ 人员工资占比 = 营销费用占比
            budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
            prev_labor_ratio_map = {}
            if budget_path:
                prev_labor_ratio_map = parse_budget_achieve_excel(budget_path)

        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: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========

        # ========== 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)} 条")
        return len(rows_to_insert)