earnings_report_processor.py 26.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 独立处理引擎
================================
覆盖 4 张输出表:延保 / 权益 / 轻改店中店汇总 / 轻改园区店汇总。
统一扫描 data_table_type='store_effect_earnings' 类型的 PROCESSING 任务,
但根据 output_category 参数只处理对应的输出表(4 个独立调度器各自调各自的 category)。

流程(每张表通用):
  Step1  Excel 解析(SAAS预算分解表 + 关系表 + 主机厂交车)
  Step2  指标系统 API(IndicatorClient)
  Step3  业务系统 SQL(TODO 占位,后续完善)
  Step4  系统公式计算 + 上月预算达成关联
  Step5  排名 + 批量入库
"""
import os
import logging
import tempfile
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('EarningsReportProcessor')


class EarningsReportProcessor:
    """红黄门店盈利测算 - 独立处理引擎"""

    # store_effect_earnings 任务类型:4 张输出表共享同一批上传文件
    STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings'

    def __init__(self, app=None):
        self.app = app

    # ============================================================
    # 调度器入口 / 任务分发
    # ============================================================

    def scan_store_effect_earnings(self, output_category):
        """
        独立调度器入口:统一扫描 store_effect_earnings 类型的 PROCESSING 任务,
        但根据 output_category 只处理对应的输出表。
        参数:
          - output_category: 输出类别 'warranty' / 'equity' / 'inshop' / 'park'
        """
        logger.info(f"[{output_category}] 开始扫描 store_effect_earnings 待处理任务")

        tasks = DataProcessTask.query.filter_by(
            data_table_type=self.STORE_EFFECT_EARNINGS_TYPE,
            status='PROCESSING',
            is_deleted=0
        ).order_by(DataProcessTask.id.asc()).all()

        logger.info(f"[{output_category}] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process_store_effect_earnings_category(task, output_category)
                success_count += 1
                logger.info(f"[{output_category}] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback
                fail_count += 1
                logger.error(f"[{output_category}] 任务 {task.id} 处理失败: {str(e)}")
                logger.error(traceback.format_exc())
                try:
                    self._mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[{output_category}] 标记任务失败时出错: {str(mark_err)}")

        logger.info(f"[{output_category}] 完成, 成功 {success_count}, 失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}

    def process_store_effect_earnings_category(self, task, output_category):
        """
        store_effect_earnings 单任务-单输出类别处理入口。
        同一份上传文件,4 个调度器各自只写自己的输出表。
        """
        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}")

        # 幂等:输出表已有该 task_id 数据则跳过
        if self._is_output_already_done(task_id, output_category):
            logger.info(f"[{output_category}] 任务 {task_id} 已处理过该类别,跳过(输出表已有数据)")
            return

        try:
            if output_category == 'warranty':
                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()
            logger.info(f"[{output_category}] 任务 {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:
            logger.error(f"[标记失败] 更新任务失败状态时出错: {str(e)}")
            db.session.rollback()
            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):
        """
        延保盈利测算完整处理流程:
          Step1 Excel(SAAS预算分解表 biz_type=2.3 + 关系表 + 主机厂交车)
          Step2 指标系统 API(biz=1 延保)
          Step3 业务系统 SQL(TODO 占位)
          Step4 系统公式计算 + 上月预算达成占比
          Step5 排名 + 批量入库 report_extended_warranty
        """
        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"warranty_{task_id}_")
        try:
            file_map = self._download_and_decrypt(task.id, tmp_dir)

            saas_path = file_map.get('SAAS门店预算分解表')
            if not saas_path:
                raise Exception("缺少必需文件: SAAS门店预算分解表")
            base_records = self._parse_warranty_base(saas_path)

            rel_path = file_map.get('关系表')
            region_map = self._parse_region_map(rel_path) if rel_path else {}

            delivery_map = {}
            for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'):
                fpath = file_map.get(ftype)
                if fpath:
                    part = self._parse_delivery_table(fpath)
                    for k, v in part.items():
                        delivery_map[k] = delivery_map.get(k, 0) + v

        finally:
            self._cleanup_tmp_dir(tmp_dir)

        # ========== Step2: 指标系统 ==========
        indicator = IndicatorClient()
        warranty_codes = ['A084', 'A075', 'A066', 'A070', 'A086', 'A036']
        indicator_data = {}
        if start_str and end_str:
            indicator_data = indicator.fetch(start_str, end_str, Config.INDICATOR_BIZ_WARRANTY, warranty_codes)

        # ========== Step3: 业务系统 SQL(TODO 占位) ==========
        biz_sql_data = {}
        logger.warning("[延保] Step3 业务系统 SQL 暂未实现")

        # ========== Step4: 上月营销费用占比 ==========
        prev_labor_ratio_map = self._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))))
            vehicle_warranty_cnt = int(Decimal(str(ind.get('A066', 0))))
            battery_warranty_cnt = int(Decimal(str(ind.get('A070', 0))))
            easy_bag_cnt = int(Decimal(str(ind.get('A086', 0))))
            store_output_value = Decimal(str(ind.get('A036', 0)))

            # 公式
            penetration_rate = self._safe_div_pct(deal_cnt, delivery_cnt)
            vehicle_warranty_penetration = self._safe_div_pct(vehicle_warranty_cnt, delivery_cnt)
            vehicle_warranty_touch_convert = self._safe_div_pct(vehicle_warranty_cnt, touch_cnt)
            battery_warranty_penetration = self._safe_div_pct(battery_warranty_cnt, delivery_cnt)
            easy_bag_penetration = self._safe_div_pct(easy_bag_cnt, delivery_cnt)
            upgrade_unit_price = self._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 = self._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 = self._safe_div_pct_decimal(service_fee, store_output_value)

            total_cost = market_fee + marketing_fee + service_fee
            cost_ratio = self._safe_div_pct_decimal(total_cost, store_output_value)
            gross_profit = gl_share - total_cost
            gross_profit_rate = self._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(('2.3', province), '') or region_map.get(('', province), '')

            row = ReportExtendedWarranty(
                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,
                vehicle_warranty_cnt=vehicle_warranty_cnt,
                vehicle_warranty_penetration=vehicle_warranty_penetration,
                vehicle_warranty_touch_convert=vehicle_warranty_touch_convert,
                battery_warranty_cnt=battery_warranty_cnt,
                battery_warranty_penetration=battery_warranty_penetration,
                easy_bag_cnt=easy_bag_cnt,
                easy_bag_penetration=easy_bag_penetration,
                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: 批量入库 ==========
        ReportExtendedWarranty.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)} 条")

    # ============================================================
    # 表 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