common_equity_processor.py 38.1 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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
# -*- coding: utf-8 -*-
"""
通用+权益 独立处理器
====================
对应 ORM 表:data_process_task (data_table_type='common_equity')
数据来源:dj_smartcarlife / scrm_account / cyb_os / region_province_mapping
输出:门店维度的延保 + 广联权益 Excel 报表

处理流程:
  Step1 从任务获取基础信息(data_table_type_name, period_start, period_end)
  Step2 批量查询门店基础信息(4s店/省份/运营模式/大区/区域运营/品牌/交付台数)
  Step3 批量查询延保指标(触客/订单/收入/整车订单/原厂权益订单)
  Step4 批量查询广联权益指标(触客/订单/收入)
  Step5 计算派生字段(触客率/客单价/渗透率等)
  Step6 生成结果 Excel(两级合并表头)并上传 OSS
"""
import logging
import os
import tempfile
from collections import defaultdict
from datetime import datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP

import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from sqlalchemy import create_engine, text as sa_text

from config import Config
from models import DataProcessTask, db
from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir

logger = logging.getLogger('CommonEquityProcessor')

COMMON_EQUITY_TYPE = 'common_equity'


# ============================================================
# 数据库连接工具
# ============================================================

def _engine(url_key):
    """创建外部数据库 SQLAlchemy engine(参考 build_store_effect_board._engine)"""
    url = getattr(Config, url_key, None)
    if not url:
        raise ValueError(f"配置项 {url_key} 未设置")
    return create_engine(url, echo=False, pool_pre_ping=True)


def _in_params(ids, prefix):
    """把列表转成 SQLAlchemy text 的具名 IN 参数。空列表返回 (None, None)。"""
    if not ids:
        return None, None
    params = {f'{prefix}{i}': v for i, v in enumerate(ids)}
    placeholders = ', '.join(f':{prefix}{i}' for i in range(len(ids)))
    return params, placeholders


def _safe_decimal(val, scale=2):
    """安全转 Decimal,None/NaN 返回 Decimal('0'),保留指定精度。"""
    if val is None:
        return Decimal('0')
    try:
        d = Decimal(str(val))
        return d.quantize(Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def _safe_pct(numerator, denominator, scale=2):
    """百分比计算:(numerator / denominator) * 100,分母为0返回0。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))
                ).quantize(Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


class CommonEquityProcessor:
    """通用+权益独立处理器"""

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

    # ============================================================
    # 调度器入口
    # ============================================================

    def scan_common_equity(self):
        """扫描 common_equity 类型的 PROCESSING 任务"""
        logger.info("[通用+权益] 开始扫描 common_equity 待处理任务")

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

        logger.info(f"[通用+权益] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process(task)
                success_count += 1
                logger.info(f"[通用+权益] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback
                fail_count += 1
                logger.error(f"[通用+权益] 任务 {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"[通用+权益] 标记任务失败时出错: {mark_err}")

        logger.info(f"[通用+权益] 扫描完成,成功 {success_count},失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}

    # ============================================================
    # 单任务处理
    # ============================================================

    def process(self, task):
        """处理单个通用+权益任务"""
        task_id = task.id
        try:
            data = self._fetch_all_data(task)
            result_file_url = self.generate_result_excel(task, data)

            task = DataProcessTask.query.filter_by(id=task_id).first()
            task.status = 'COMPLETED'
            task.result_file_url = result_file_url
            task.error_msg = ''
            db.session.commit()
            logger.info(f"[通用+权益] 任务 {task_id} 处理完成,结果文件: {result_file_url}")
        except Exception as e:
            db.session.rollback()
            mark_task_failed(task_id, str(e))
            raise

    # ============================================================
    # 数据聚合
    # ============================================================

    def _fetch_all_data(self, task):
        """批量获取所有门店数据,返回 list[dict],每个 dict 为一行输出数据。"""
        task_id = task.id
        period_start = task.period_start
        period_end = task.period_end
        if not period_start or not period_end:
            raise Exception("任务缺少所属周期(period_start / period_end)")

        start_str = period_start.strftime('%Y-%m-%d')
        end_str = period_end.strftime('%Y-%m-%d')
        start_dt = f"{start_str} 00:00:00"
        end_dt = f"{end_str} 23:59:59"

        logger.info(f"[通用+权益] task_id={task_id}, 周期={start_str}~{end_str}")

        # ---- Step1: 基础门店列表 (dj_smartcarlife) ----
        store_map = self._fetch_stores()
        if not store_map:
            raise Exception("未查询到任何门店数据(pg_group_store_rel)")

        merchant_ids = list(store_map.keys())
        logger.info(f"[通用+权益] 基础门店 {len(merchant_ids)} 个")

        # ---- Step2: 运营模式 ----
        operate_mode_map = self._fetch_operate_mode(merchant_ids)

        # ---- Step3: 大区 ----
        provinces = list({s['province_name'] for s in store_map.values() if s['province_name']})
        region_map = self._fetch_region(provinces)

        # ---- Step4: 区域运营 ----
        director_map = self._fetch_directors(merchant_ids)

        # ---- Step5: 品牌 ----
        brand_map = self._fetch_brands(merchant_ids)

        # ---- Step6: 门店交付台数 ----
        delivery_map = self._fetch_delivery_count(merchant_ids, start_str, end_str)

        # ---- Step7: 延保触客 ----
        extend_touch_map = self._fetch_extend_touch(merchant_ids, start_str, end_str)

        # ---- Step8: 延保售前/售后订单 ----
        extend_pre_order_map = self._fetch_extend_orders(merchant_ids, start_dt, end_dt, sales_type=0)
        extend_post_order_map = self._fetch_extend_orders(merchant_ids, start_dt, end_dt, sales_type=1)

        # ---- Step9: 延保累计收入 ----
        extend_income_map = self._fetch_extend_income(merchant_ids, start_dt, end_dt)

        # ---- Step10: 延保整车订单数 ----
        extend_car_order_map = self._fetch_extend_special_orders(merchant_ids, start_dt, end_dt, upgrade_goods_type=155)

        # ---- Step11: 延保原厂权益订单数 ----
        extend_equity_order_map = self._fetch_extend_special_orders(merchant_ids, start_dt, end_dt, upgrade_goods_type=126)

        # ---- Step12: 广联权益触客 ----
        equity_touch_map = self._fetch_equity_touch(merchant_ids, start_str, end_str)

        # ---- Step13: 广联权益售前/售后订单 ----
        equity_pre_order_map = self._fetch_equity_orders(merchant_ids, start_dt, end_dt, sales_type=0)
        equity_post_order_map = self._fetch_equity_orders(merchant_ids, start_dt, end_dt, sales_type=1)

        # ---- Step14: 广联权益累计收入 ----
        equity_income_map = self._fetch_equity_income(merchant_ids, start_dt, end_dt)

        # ---- 组装结果 ----
        rows = []
        for mid, store in store_map.items():
            mname = store['merchant_name']
            province = store['province_name']

            # 基础字段
            operate_mode = operate_mode_map.get(mid, '非直营')
            region = region_map.get(province, '')
            director = director_map.get(mid, '')
            brand = brand_map.get(mid, '')
            delivery_cnt = delivery_map.get(mid, 0)

            # 延保字段
            ext_pre_touch = extend_touch_map.get(mid, {}).get('pre', 0)
            ext_post_touch = extend_touch_map.get(mid, {}).get('post', 0)
            ext_pre_touch_rate = _safe_pct(ext_pre_touch, delivery_cnt)
            ext_pre_order = extend_pre_order_map.get(mid, 0)
            ext_post_order = extend_post_order_map.get(mid, 0)
            ext_order_total = ext_pre_order + ext_post_order
            ext_income = extend_income_map.get(mid, Decimal('0'))
            ext_unit_price = (ext_income / Decimal(str(ext_order_total))).quantize(
                Decimal('0.01'), rounding=ROUND_HALF_UP) if ext_order_total > 0 else Decimal('0')
            ext_car_order = extend_car_order_map.get(mid, 0)
            ext_car_penetration = _safe_pct(ext_car_order, delivery_cnt)
            ext_equity_order = extend_equity_order_map.get(mid, 0)
            ext_equity_penetration = _safe_pct(ext_equity_order, delivery_cnt)

            # 广联权益字段
            eq_pre_touch = equity_touch_map.get(mid, {}).get('pre', 0)
            eq_post_touch = equity_touch_map.get(mid, {}).get('post', 0)
            eq_pre_touch_rate = _safe_pct(eq_pre_touch, delivery_cnt)
            eq_pre_order = equity_pre_order_map.get(mid, 0)
            eq_post_order = equity_post_order_map.get(mid, 0)
            eq_order_total = eq_pre_order + eq_post_order
            eq_income = equity_income_map.get(mid, Decimal('0'))
            eq_delivery_penetration = _safe_pct(ext_order_total, delivery_cnt)
            eq_unit_price = (eq_income / Decimal(str(eq_order_total))).quantize(
                Decimal('0.01'), rounding=ROUND_HALF_UP) if eq_order_total > 0 else Decimal('0')

            rows.append({
                'merchant_name': mname,
                'operate_mode': operate_mode,
                'brand': brand,
                'region': region,
                'province': province,
                'director': director,
                'delivery_cnt': delivery_cnt,
                # 延保
                'ext_pre_touch': ext_pre_touch,
                'ext_pre_touch_rate': ext_pre_touch_rate,
                'ext_post_touch': ext_post_touch,
                'ext_pre_order': ext_pre_order,
                'ext_post_order': ext_post_order,
                'ext_order_total': ext_order_total,
                'ext_income': ext_income,
                'ext_unit_price': ext_unit_price,
                'ext_car_order': ext_car_order,
                'ext_car_penetration': ext_car_penetration,
                'ext_equity_order': ext_equity_order,
                'ext_equity_penetration': ext_equity_penetration,
                # 广联权益
                'eq_pre_touch': eq_pre_touch,
                'eq_pre_touch_rate': eq_pre_touch_rate,
                'eq_post_touch': eq_post_touch,
                'eq_pre_order': eq_pre_order,
                'eq_post_order': eq_post_order,
                'eq_order_total': eq_order_total,
                'eq_income': eq_income,
                'eq_pre_touch_convert_rate': eq_pre_touch_rate,
                'eq_delivery_penetration': eq_delivery_penetration,
                'eq_unit_price': eq_unit_price,
            })

        logger.info(f"[通用+权益] 数据组装完成,共 {len(rows)} 行")
        return rows

    # ============================================================
    # 各数据源查询方法
    # ============================================================

    def _fetch_stores(self):
        """Step1: 基础门店列表 (dj_smartcarlife)"""
        group_id = Config.COMMON_EQUITY_GROUP_ID
        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT sr.merchant_id, sr.merchant_name, sm.province_name "
            "FROM pg_group_store_rel sr "
            "LEFT JOIN dj_car_life_service_merchant sm "
            "  ON sm.merchant_id = sr.merchant_id AND sm.deleted_flag = 'N' "
            "WHERE sr.deleted_flag = 'N' "
            "  AND sr.group_id = :group_id"
        )
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, {'group_id': group_id}).fetchall():
                mid = r[0]
                if mid:
                    result[mid] = {
                        'merchant_name': str(r[1] or '').strip(),
                        'province_name': str(r[2] or '').strip(),
                    }
        eng.dispose()
        logger.info(f"[通用+权益] 门店列表: {len(result)} 个")
        return result

    def _fetch_operate_mode(self, merchant_ids):
        """Step2: 运营模式 (dj_smartcarlife) — 有 partner_merchant_id=基准值 则直营"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        partner_id = Config.COMMON_EQUITY_PARTNER_MERCHANT_ID
        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT smr.main_merchant_id, yc.partner_merchant_id "
            "FROM dj_car_life_scene_merchant_ref smr "
            "LEFT JOIN dj_car_life_yqmerchant_config yc "
            "  ON smr.sub_merchant_id = yc.merchant_id AND yc.deleted_flag = 'N' "
            "WHERE smr.deleted_flag = 'N' "
            "  AND smr.main_merchant_type = 2 "
            "  AND smr.scene = 0 "
            "  AND smr.sub_merchant_type IN (6, 8) "
            f"  AND smr.main_merchant_id IN ({ph})"
        )
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid = r[0]
                pid = r[1]
                if mid not in result:
                    result[mid] = '非直营'
                if pid == partner_id:
                    result[mid] = '直营'
        eng.dispose()
        logger.info(f"[通用+权益] 运营模式: {len(result)} 个匹配")
        return result

    def _fetch_region(self, provinces):
        """Step3: 大区 (data_report 主库 region_province_mapping)"""
        if not provinces:
            return {}
        p, ph = _in_params(provinces, 'p')
        if p is None:
            return {}

        eng = create_engine(Config.SQLALCHEMY_DATABASE_URI, echo=False, pool_pre_ping=True)
        sql = sa_text(
            f"SELECT province_name, region_name FROM region_province_mapping "
            f"WHERE province_name IN ({ph}) "
            f"GROUP BY province_name, region_name"
        )
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                prov = str(r[0] or '').strip()
                region = str(r[1] or '').strip()
                if prov and region and prov not in result:
                    result[prov] = region
        eng.dispose()
        logger.info(f"[通用+权益] 大区映射: {len(result)} 个省份")
        return result

    def _fetch_directors(self, merchant_ids):
        """Step4: 区域运营 (dj_smartcarlife)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT merchant_id, GROUP_CONCAT(director_name SEPARATOR '/') AS director_names "
            "FROM dj_car_life_shop_merchant_director_config "
            "WHERE deleted_flag = 'N' AND director_type = 9 "
            f"AND merchant_id IN ({ph}) "
            "GROUP BY merchant_id"
        )
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid = r[0]
                names = str(r[1] or '').strip()
                if mid and names:
                    result[mid] = names
        eng.dispose()
        logger.info(f"[通用+权益] 区域运营: {len(result)} 个匹配")
        return result

    def _fetch_brands(self, merchant_ids):
        """Step5: 品牌 (scrm_account → cyb_os)"""
        # 5a: merchant_id → brand_ids
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng_scrm = _engine('SCRM_DATABASE_URL')
        merchant_brands = defaultdict(set)  # merchant_id → set(brand_id)
        with eng_scrm.connect() as conn:
            sql = sa_text(
                "SELECT merchant_id, first_brand_id FROM platform_merchant_brand "
                f"WHERE del_flag = 0 AND merchant_id IN ({ph})"
            )
            for r in conn.execute(sql, p).fetchall():
                mid, bid = r[0], r[1]
                if mid and bid:
                    merchant_brands[mid].add(bid)
        eng_scrm.dispose()

        # 5b: brand_id → brand_name
        all_bids = set()
        for bids in merchant_brands.values():
            all_bids |= bids

        bid_name = {}
        if all_bids:
            bp, bph = _in_params(list(all_bids), 'b')
            eng_cyb = _engine('CYB_OS_DATABASE_URL')
            with eng_cyb.connect() as conn:
                sql = sa_text(f"SELECT bid, brand FROM platform_carbrand WHERE bid IN ({bph})")
                for r in conn.execute(sql, bp).fetchall():
                    bid, nm = r[0], r[1]
                    if bid and nm:
                        bid_name[bid] = str(nm).strip()
            eng_cyb.dispose()

        # 组装: merchant_id → "品牌A/品牌B"
        result = {}
        for mid, bids in merchant_brands.items():
            names = sorted({bid_name[b] for b in bids if b in bid_name})
            if names:
                result[mid] = '/'.join(names)

        logger.info(f"[通用+权益] 品牌映射: {len(result)} 个商户")
        return result

    def _fetch_delivery_count(self, merchant_ids, start_str, end_str):
        """Step6: 门店交付台数 (dj_smartcarlife)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT merchant_id, SUM(delivery_count) AS total "
            "FROM dj_car_life_merchant_daily_report_huawei "
            "WHERE deleted_flag = 'N' "
            "  AND brand_id = -1 AND first_brand_id = -1 and scene_type = 0"
            f"  AND merchant_id IN ({ph}) "
            "  AND report_date >= :start_date AND report_date <= :end_date "
            "GROUP BY merchant_id"
        )
        p['start_date'] = start_str
        p['end_date'] = end_str
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = int(total or 0)
        eng.dispose()
        logger.info(f"[通用+权益] 交付台数: {len(result)} 个门店")
        return result

    def _fetch_extend_touch(self, merchant_ids, start_str, end_str):
        """Step7: 延保触客 (dj_smartcarlife staff_daily_report)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT merchant_id, "
            "  SUM(extended_warranty_to_shop_count) AS pre_touch, "
            "  IFNULL(SUM(after_sale_extended_warranty_to_shop_count), 0) AS post_touch "
            "FROM dj_car_life_staff_daily_report_huawei "
            "WHERE deleted_flag = 'N' "
            "  AND brand_id = -1 AND first_brand_id = -1 "
            "  AND scene_type = 0 "
            f"  AND merchant_id IN ({ph}) "
            "  AND report_date >= :start_date AND report_date <= :end_date "
            "GROUP BY merchant_id"
        )
        p['start_date'] = start_str
        p['end_date'] = end_str
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid = r[0]
                if mid:
                    result[mid] = {'pre': int(r[1] or 0), 'post': int(r[2] or 0)}
        eng.dispose()
        logger.info(f"[通用+权益] 延保触客: {len(result)} 个门店")
        return result

    def _fetch_extend_orders(self, merchant_ids, start_dt, end_dt, sales_type=0):
        """Step8: 延保订单 (售前 sales_type=0 / 售后 sales_type=1)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
            "FROM dj_car_life_goods_sub_order gso "
            "INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
            "LEFT JOIN dj_car_life_goods_order_customer goc ON lgo.order_code = goc.order_code "
            "LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
            "WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' AND goc.deleted_flag = 'N' "
            "  AND lgo.base_scene_code IN (110201, 110202) "
            f"  AND goc.sales_type = {sales_type} "
            "  AND lgo.status = 4 "
            "  AND gso.supplier_code = 22 "
            f"  AND lgo.merchant_id IN ({ph}) "
            "  AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
            "GROUP BY lgo.merchant_id"
        )
        p['start_dt'] = start_dt
        p['end_dt'] = end_dt
        result = {}
        label = '售前' if sales_type == 0 else '售后'
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = int(total or 0)
        eng.dispose()
        logger.info(f"[通用+权益] 延保{label}订单: {len(result)} 个门店")
        return result

    def _fetch_extend_income(self, merchant_ids, start_dt, end_dt):
        """Step9: 延保累计收入"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT lgo.merchant_id, IFNULL(SUM(lgo.total_price), 0) AS extendTotalPrice "
            "FROM dj_car_life_goods_order lgo "
            "LEFT JOIN dj_car_life_goods_sub_order gso ON gso.order_code = lgo.order_code "
            "LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
            "WHERE lgo.deleted_flag = 'N' AND gso.deleted_flag = 'N' "
            "  AND lgo.base_scene_code IN (110201, 110202) "
            "  AND lgo.status = 4 "
            "  AND gso.supplier_code = 22 "
            f"  AND lgo.merchant_id IN ({ph}) "
            "  AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
            "GROUP BY lgo.merchant_id"
        )
        p['start_dt'] = start_dt
        p['end_dt'] = end_dt
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = _safe_decimal(total)
        eng.dispose()
        logger.info(f"[通用+权益] 延保累计收入: {len(result)} 个门店")
        return result

    def _fetch_extend_special_orders(self, merchant_ids, start_dt, end_dt, upgrade_goods_type):
        """Step10/11: 延保整车订单(155) / 原厂权益订单(126)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
            "FROM dj_car_life_goods_sub_order gso "
            "INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
            "LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
            "WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' "
            "  AND lgo.base_scene_code IN (110201, 110202) "
            "  AND lgo.status = 4 "
            "  AND gso.supplier_code = 22 "
            f"  AND gso.upgrade_goods_type = {upgrade_goods_type} "
            f"  AND lgo.merchant_id IN ({ph}) "
            "  AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
            "GROUP BY lgo.merchant_id"
        )
        p['start_dt'] = start_dt
        p['end_dt'] = end_dt
        type_label = '整车' if upgrade_goods_type == 155 else '原厂权益'
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = int(total or 0)
        eng.dispose()
        logger.info(f"[通用+权益] 延保{type_label}订单: {len(result)} 个门店")
        return result

    def _fetch_equity_touch(self, merchant_ids, start_str, end_str):
        """Step12: 广联权益触客 (dj_smartcarlife staff_daily_report)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT merchant_id, "
            "  IFNULL(SUM(real_equity_to_shop_count), 0) AS pre_touch, "
            "  IFNULL(SUM(after_sale_real_equity_to_shop_count), 0) AS post_touch "
            "FROM dj_car_life_staff_daily_report_huawei "
            "WHERE deleted_flag = 'N' "
            "  AND brand_id = -1 AND first_brand_id = -1 "
            "  AND scene_type = 0 "
            f"  AND merchant_id IN ({ph}) "
            "  AND report_date >= :start_date AND report_date <= :end_date "
            "GROUP BY merchant_id"
        )
        p['start_date'] = start_str
        p['end_date'] = end_str
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid = r[0]
                if mid:
                    result[mid] = {'pre': int(r[1] or 0), 'post': int(r[2] or 0)}
        eng.dispose()
        logger.info(f"[通用+权益] 广联权益触客: {len(result)} 个门店")
        return result

    def _fetch_equity_orders(self, merchant_ids, start_dt, end_dt, sales_type=0):
        """Step13: 广联权益订单 (售前 sales_type=0 / 售后 sales_type=1)"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
            "FROM dj_car_life_goods_sub_order gso "
            "INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
            "LEFT JOIN dj_car_life_goods_order_customer goc ON lgo.order_code = goc.order_code "
            "LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
            "WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' AND goc.deleted_flag = 'N' "
            "  AND lgo.scene_type = 0 "
            f"  AND goc.sales_type = {sales_type} "
            "  AND lgo.status = 4 "
            "  AND gso.supplier_code = 12 "
            f"  AND lgo.merchant_id IN ({ph}) "
            "  AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
            "GROUP BY lgo.merchant_id"
        )
        p['start_dt'] = start_dt
        p['end_dt'] = end_dt
        label = '售前' if sales_type == 0 else '售后'
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = int(total or 0)
        eng.dispose()
        logger.info(f"[通用+权益] 广联权益{label}订单: {len(result)} 个门店")
        return result

    def _fetch_equity_income(self, merchant_ids, start_dt, end_dt):
        """Step14: 广联权益累计收入"""
        p, ph = _in_params(merchant_ids, 'm')
        if p is None:
            return {}

        eng = _engine('BIZ_SQL_DATABASE_URL')
        sql = sa_text(
            "SELECT lgo.merchant_id, IFNULL(SUM(lgo.total_price), 0) AS equityTotalPrice "
            "FROM dj_car_life_goods_order lgo "
            "LEFT JOIN dj_car_life_goods_sub_order gso ON gso.order_code = lgo.order_code "
            "LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
            "WHERE lgo.deleted_flag = 'N' AND gso.deleted_flag = 'N' "
            "  AND lgo.scene_type = 0 "
            "  AND lgo.status = 4 "
            "  AND gso.supplier_code = 12 "
            f"  AND lgo.merchant_id IN ({ph}) "
            "  AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
            "GROUP BY lgo.merchant_id"
        )
        p['start_dt'] = start_dt
        p['end_dt'] = end_dt
        result = {}
        with eng.connect() as conn:
            for r in conn.execute(sql, p).fetchall():
                mid, total = r[0], r[1]
                if mid:
                    result[mid] = _safe_decimal(total)
        eng.dispose()
        logger.info(f"[通用+权益] 广联权益累计收入: {len(result)} 个门店")
        return result

    # ============================================================
    # 结果 Excel 生成
    # ============================================================

    # 输出列定义:(表头名, 数据 key, 类型)
    # 类型:'text' / 'int' / 'decimal' / 'pct'
    RESULT_COLUMNS = [
        # 基础字段 A~G
        ('4s店', 'merchant_name', 'text'),
        ('运营模式', 'operate_mode', 'text'),
        ('品牌', 'brand', 'text'),
        ('大区', 'region', 'text'),
        ('省份', 'province', 'text'),
        ('区域运营', 'director', 'text'),
        ('门店交付台数', 'delivery_cnt', 'int'),
        # 延保 H~R
        ('售前触客', 'ext_pre_touch', 'int'),
        ('售前触客率', 'ext_pre_touch_rate', 'pct'),
        ('售后触客', 'ext_post_touch', 'int'),
        ('售前订单', 'ext_pre_order', 'int'),
        ('售后订单', 'ext_post_order', 'int'),
        ('订单数合计', 'ext_order_total', 'int'),
        ('累计收入', 'ext_income', 'decimal'),
        ('客单价', 'ext_unit_price', 'decimal'),
        ('整车订单数', 'ext_car_order', 'int'),
        ('整车渗透率', 'ext_car_penetration', 'pct'),
        ('原厂权益订单数', 'ext_equity_order', 'int'),
        ('权益渗透率', 'ext_equity_penetration', 'pct'),
        # 广联权益 S~AB
        ('售前触客', 'eq_pre_touch', 'int'),
        ('售前触客率', 'eq_pre_touch_rate', 'pct'),
        ('售后触客', 'eq_post_touch', 'int'),
        ('售前订单', 'eq_pre_order', 'int'),
        ('售后订单', 'eq_post_order', 'int'),
        ('订单数合计', 'eq_order_total', 'int'),
        ('累计收入', 'eq_income', 'decimal'),
        ('售前触客转化率', 'eq_pre_touch_convert_rate', 'pct'),
        ('交付渗透率', 'eq_delivery_penetration', 'pct'),
        ('客单价', 'eq_unit_price', 'decimal'),
    ]

    def generate_result_excel(self, task, data):
        """根据聚合数据生成《通用+权益》结果 Excel 并上传,返回 URL。

        行结构:
          行1: 两级表头(基础字段合并行1-2,延保/广联权益各有上级表头)
          行2: 子表头
          行3+: 数据行
        """
        task_id = task.id
        period_start = task.period_start
        start_str = period_start.strftime('%Y-%m-%d') if period_start else ''

        # ---------- 构建工作簿 ----------
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = '门店展示表'

        # 样式定义
        header_font = Font(name='微软雅黑', size=11, bold=True, color='FFFFFF')
        header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
        cell_font = Font(name='微软雅黑', size=10)
        center = Alignment(horizontal='center', vertical='center', wrap_text=True)
        right_align = Alignment(horizontal='right', vertical='center')
        thin = Border(
            left=Side(style='thin'), right=Side(style='thin'),
            top=Side(style='thin'), bottom=Side(style='thin'),
        )

        total_cols = len(self.RESULT_COLUMNS)  # 29列

        # ---------- 行1-2: 两级表头 ----------
        # 基础字段(A~G, 列1-7):行1-2 合并
        basic_cols = 7
        for i in range(basic_cols):
            col = i + 1
            header, _, _ = self.RESULT_COLUMNS[i]
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center
            cell.border = thin
            ws.merge_cells(start_row=1, start_column=col, end_row=2, end_column=col)

        # 延保上级表头(H~R, 列8-19):行1 合并
        extend_start = 8
        extend_end = 19
        cell = ws.cell(row=1, column=extend_start, value='延保')
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = center
        cell.border = thin
        ws.merge_cells(start_row=1, start_column=extend_start, end_row=1, end_column=extend_end)
        # 补边框(合并区域中间列)
        for c in range(extend_start + 1, extend_end + 1):
            ws.cell(row=1, column=c).border = thin

        # 延保子表头(行2)
        for i in range(extend_start - 1, extend_end):
            col = i + 1
            header, _, _ = self.RESULT_COLUMNS[i]
            cell = ws.cell(row=2, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center
            cell.border = thin

        # 广联权益上级表头(S~AB, 列20-29):行1 合并
        equity_start = 20
        equity_end = total_cols
        cell = ws.cell(row=1, column=equity_start, value='广联权益')
        cell.font = header_font
        cell.fill = header_fill
        cell.alignment = center
        cell.border = thin
        ws.merge_cells(start_row=1, start_column=equity_start, end_row=1, end_column=equity_end)
        # 补边框
        for c in range(equity_start + 1, equity_end + 1):
            ws.cell(row=1, column=c).border = thin

        # 广联权益子表头(行2)
        for i in range(equity_start - 1, equity_end):
            col = i + 1
            header, _, _ = self.RESULT_COLUMNS[i]
            cell = ws.cell(row=2, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center
            cell.border = thin

        # ---------- 行3+: 数据行 ----------
        for row_idx, row_data in enumerate(data, start=3):
            for col_idx, (_header, key, kind) in enumerate(self.RESULT_COLUMNS, start=1):
                val = row_data.get(key)
                cell = ws.cell(row=row_idx, column=col_idx)
                cell.border = thin

                if kind == 'text':
                    cell.value = str(val) if val else ''
                    cell.font = cell_font
                    cell.alignment = center
                elif kind == 'int':
                    try:
                        cell.value = int(val) if val else 0
                        cell.number_format = '#,##0'
                    except (ValueError, TypeError):
                        cell.value = 0
                    cell.font = cell_font
                    cell.alignment = right_align
                elif kind == 'decimal':
                    try:
                        cell.value = float(val) if val else 0.0
                        cell.number_format = '#,##0.00'
                    except (ValueError, TypeError):
                        cell.value = 0.0
                    cell.font = cell_font
                    cell.alignment = right_align
                elif kind == 'pct':
                    try:
                        cell.value = float(val) if val else 0.0
                        cell.number_format = '0.00"%"'
                    except (ValueError, TypeError):
                        cell.value = 0.0
                    cell.font = cell_font
                    cell.alignment = right_align

        # ---------- 列宽 ----------
        col_widths = {
            '4s店': 20, '运营模式': 10, '品牌': 15, '大区': 10, '省份': 16,
            '区域运营': 14, '门店交付台数': 12,
            '售前触客': 10, '售前触客率': 12, '售后触客': 10,
            '售前订单': 10, '售后订单': 10, '订单数合计': 12,
            '累计收入': 14, '客单价': 10, '整车订单数': 12,
            '整车渗透率': 12, '原厂权益订单数': 14, '权益渗透率': 12,
            '售前触客转化率': 14, '交付渗透率': 12,
        }
        for i, (header, _key, _kind) in enumerate(self.RESULT_COLUMNS, start=1):
            col_letter = openpyxl.utils.get_column_letter(i)
            ws.column_dimensions[col_letter].width = col_widths.get(header, 12)

        # 冻结窗格(冻结表头行)
        ws.freeze_panes = 'A3'
        ws.row_dimensions[1].height = 24
        ws.row_dimensions[2].height = 30

        # ---------- 保存 + 上传 ----------
        tmp_dir = tempfile.mkdtemp(prefix=f'common_equity_{task_id}_')
        try:
            period_label = start_str.replace('-', '') if start_str else 'unknown'
            excel_path = os.path.join(tmp_dir, f'通用+权益_{period_label}.xlsx')
            wb.save(excel_path)

            object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
                          f"/common_equity_{period_label}_{task_id}.xlsx")
            file_url = upload_file(excel_path, object_key)
            logger.info(f"[通用+权益] 结果表已生成并上传: {file_url}({len(data)} 行数据)")
            return file_url
        finally:
            cleanup_tmp_dir(tmp_dir)