guangai_processor.py 57.2 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 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
# -*- coding: utf-8 -*-
"""
广爱专项报表 处理器
===================
对应数据表类型:guangai_special(广爱专项,附件驱动)。

流程(设计见《广爱专项报表设计文档.md》,2026-10-16 已确认):
  1. 用户下载门店模板(GET /api/guangai/template,门店名称系统预填)
  2. 填 7 个字段后上传 → 提交时同步解析校验(validate_attachment_file,失败直接返回错误文件、不建任务):
     - 门店名称精确匹配系统门店清单;对不上的行追加"错误原因"列生成错误文件
     - 交车/触客 ≥0 整数;触客率留空=系统算(触客÷交车),有值按 4 位小数校验
     - 校验通过 → 新表 guangai_store_report_data(月+维度+商户 唯一,同键原地更新覆盖)
     - 校验失败 → 任务置 FAILED(错误文件 URL 写入 error_msg),可重新生成
  3. 调度器扫描 PROCESSING 任务 → 指标系统取数 → 渲染模板 → 上传 OSS → COMPLETED

周区间(累计制,严格口径):W1 = 1 日 ~ 当月第 1 个周日;WN = 1 日 ~ 第 N 个周日;
只有 4 周,无第 5 周;第 4 个周日之后的剩余日期不归任何周维度(按月维度可见)。

评灯阈值:渗透率 ≥20% 绿 / ≥10% 黄 / <10% 红(空不填)。
指标编码:A062 交车数 / A063 触客数 / A075 成交数 / A036 产值 / A098 售后订单数;
⚠ 2026-10-19:全部指标查询 biz=1(原厂权益属延保大类子类,不再单独查 biz=3)。
"""
import logging
import os
import tempfile
from copy import copy
from datetime import date, datetime, timedelta
from decimal import Decimal

import openpyxl
from openpyxl.styles import Font, PatternFill
from sqlalchemy import text, bindparam

from config import Config
from indicator_client import IndicatorClient
from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir, download_all_files, _get_biz_sql_conn
from models import DataProcessTask, GuangaiStoreReportData, db
from voyah_processor import shorten_province

logger = logging.getLogger('GuangaiProcessor')

GUANGAI_TYPE = 'guangai_special'
GROUP_NAME = '广爱'

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ATTACH_TEMPLATE_PATH = os.path.join(BASE_DIR, 'exporttemplete', '广爱专项-门店维度数据模板.xlsx')
OUTPUT_TEMPLATE_PATH = os.path.join(BASE_DIR, 'exporttemplete', '广爱8月新模板.xlsx')
OUTPUT_SHEET = '8月新模板-字段取值说明'

# 指标编码
CODE_DELIVERY = 'A062'   # 交车数
CODE_TOUCH = 'A063'      # 触客数(售前触客)
CODE_DEAL = 'A075'       # 成交数
CODE_OUTPUT = 'A036'     # 产值
CODE_AFTER_ORDER = 'A098'  # 售后订单数
CODE_REFER_COUNT = 'A084'  # 引荐台数(延保场景,biz=1)——权益区 AJ~AM/AN 分母
CODE_VEHICLE_DEAL = 'A066'        # 整车延保成交数(品牌汇总 K)
CODE_VEHICLE_DEAL_RATE = 'A067'   # 整车延保渗透率(品牌汇总 L,指标库直取)

# 评灯:渗透率 ≥20% 绿 / ≥10% 黄 / <10% 红
RATE_FILL = {'绿': 'C6EFCE', '黄': 'FFEB9C', '红': 'FFC7CE'}
# 差异 ≠0 标黄
DIFF_FILL = 'FFEB9C'

# 明细列号(1 起)
LAST_COL = 54  # BB
# 品牌汇总区域基准行(模板静态位置,行平移随门店数变化)
SEC_BASE_ROWS = {'title_cur': 39, 'note_cur': 43, 'title_prev': 45, 'note_prev': 49,
                 'week_block': 51}
SAMPLE_STORE_ROWS = 31     # 模板样例门店行数(行 7~37)
DATA_START_ROW = 7

# 明细区「比率列」(1 起):值由 _pct() 已 ×100(如 0.7652 → 76.52),
# 单元格统一用 0.00"%" 只追加 % 号、不再缩放(与 processor.py 的 RATIO_COLS 口径一致)。
# L 触客率 / O 触客渗透率 / P 交付渗透率 / U 交付渗透率 / V 达成率(目标20%) /
# W~Z 周渗透率 / AH 权益交付渗透率 / AI 权益达成率 / AJ~AM 权益周渗透率 /
# AT 达成(产值) / AV 达成(件数)
RATE_COLS = {12, 15, 16, 21, 22, 23, 24, 25, 26, 34, 35, 36, 37, 38, 39, 46, 48}
# 品牌汇总区比率列:G 触客率 / L 触客渗透率 / N 交付渗透率 / O~R 环比
BRAND_SUMMARY_RATE_COLS = {7, 12, 14, 15, 16, 17, 18}
# 比率列显示格式:仅追加 % 号,不缩放数值
RATE_NUMBER_FORMAT = '0.00"%"'


def compute_guangai_week_period(month, week_num):
    """广爱周区间(累计制,严格口径):WN = 当月 1 日 ~ 当月第 N 个周日。

    仅支持 1~4 周(无第 5 周);第 4 个周日之后的剩余日期不归任何周维度。
    :param month: 'YYYY-MM'
    :param week_num: int 1~4
    :return: (start_date, end_date)
    :raises ValueError: 月份/周序号非法
    """
    try:
        y, m = [int(x) for x in str(month).split('-')]
        first_day = date(y, m, 1)
    except (ValueError, AttributeError, TypeError):
        raise ValueError(f'月份格式错误,应为 YYYY-MM:{month}')
    if not (1 <= int(week_num) <= 4):
        raise ValueError(f'广爱专项周序号必须在 1~4 之间(无第 5 周):{week_num}')
    # 当月第 1 个周日:weekday() 周一=0..周日=6
    first_sunday = first_day + timedelta(days=(6 - first_day.weekday()) % 7)
    end = first_sunday + timedelta(days=7 * (int(week_num) - 1))
    return first_day, end


def rating_text(pct):
    """广爱评灯:渗透率(小数) ≥0.2 绿 / ≥0.1 黄 / <0.1 红;空/分母 0 → ''。"""
    if pct is None:
        return ''
    try:
        p = Decimal(str(pct))
    except Exception:
        return ''
    if p >= Decimal('0.2'):
        return '绿'
    if p >= Decimal('0.1'):
        return '黄'
    return '红'


def _q4(num):
    """保留 4 位小数并去掉末尾多余 0(float 自然去尾零);无法计算返回 None。"""
    if num is None:
        return None
    try:
        return float(round(Decimal(str(num)), 4))
    except Exception:
        return None


def _pct(num):
    """比率 → 百分数:×100 四舍五入保留 2 位小数(如 0.7652 → 76.52);空返回 None。"""
    if num is None:
        return None
    try:
        return float((Decimal(str(num)) * 100).quantize(
            Decimal('0.01'), rounding='ROUND_HALF_UP'))
    except Exception:
        return None


def _div(num, den):
    """num/den(小数);分母空/0 或分子空 → None。"""
    if num is None or den is None:
        return None
    try:
        num_d, den_d = Decimal(str(num)), Decimal(str(den))
    except Exception:
        return None
    if den_d == 0:
        return None
    return float(num_d / den_d)


class GuangaiProcessor:
    """广爱专项处理器(附件校验入库 + 报表生成 + 调度扫描)"""

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

    # ============================================================
    # 门店清单 / 周区间
    # ============================================================

    def load_store_list(self):
        """广爱门店清单(merchant_id/merchant_name),ORDER BY g.id, r.merchant_id。"""
        conn = _get_biz_sql_conn()
        if conn is None:
            raise Exception("业务库(dj_smartcarlife)连接失败")
        try:
            rows = conn.execute(text(
                "select r.merchant_id, r.merchant_name "
                "from pg_group_info g "
                "join pg_group_store_rel r on r.group_id = g.id and r.deleted_flag = 'N' "
                "where g.deleted_flag = 'N' and g.group_name = :gname "
                "order by g.id, r.merchant_id"
            ), {'gname': GROUP_NAME}).fetchall()
            return [{'merchant_id': str(r[0]), 'merchant_name': r[1]} for r in rows]
        finally:
            conn.close()

    def load_month_end_snapshot_stores(self, month_end_dt_str):
        """上月底生效门店快照(还原 T 时点广爱分组成员,口径取自取值说明 C47/O41 SQL):
        r.created_date <= 月末 且(未删除 或 updated_date > 月末)。"""
        conn = _get_biz_sql_conn()
        if conn is None:
            raise Exception("业务库(dj_smartcarlife)连接失败")
        try:
            rows = conn.execute(text(
                "select r.merchant_id, r.merchant_name "
                "from pg_group_store_rel r "
                "join pg_group_info g on g.id = r.group_id and g.deleted_flag = 'N' "
                "  and g.created_date <= :t_end "
                "where g.group_name = :gname "
                "  and r.created_date <= :t_end "
                "  and (r.deleted_flag = 'N' or r.updated_date > :t_end) "
                "order by r.merchant_id"
            ), {'gname': GROUP_NAME, 't_end': month_end_dt_str}).fetchall()
            return [str(r[0]) for r in rows]
        finally:
            conn.close()

    def fetch_original_equity(self, d_start, d_end, m_ids):
        """原厂权益(商品类目 189)业务库统计:成交数 + 产值。

        与已有产值报表 querySingleMerchantOutputValue / getSubOrderGoodsTypeCount
        同口径(2026-10-19 设计确认);指标库无该商品类目粒度,故走业务库 SQL。

        :return: {merchant_id(str): {'deal': int, 'output': Decimal}}
        """
        if not m_ids:
            return {}
        goods_type = int(Config.GUANGAI_ORIGINAL_EQUITY_GOODS_TYPE)
        conn = _get_biz_sql_conn()
        if conn is None:
            raise Exception("业务库(dj_smartcarlife)连接失败")
        try:
            rows = conn.execute(text(
                "select go.merchant_id, "
                "       count(gso.id) as deal_count, "
                "       sum(gso.total_price - ifnull(gso.refund_amount, 0)) as output_value "
                "from dj_car_life_goods_sub_order gso "
                "left join dj_car_life_goods_order go "
                "  on go.order_code = gso.order_code and go.deleted_flag = 'N' "
                "where gso.deleted_flag = 'N' and gso.status = 1 "
                "  and go.scene_type = 0 "
                "  and go.status in (4, 6, 12) "
                "  and go.install_upgrade_time >= :d_start "
                "  and go.install_upgrade_time <= :d_end "
                "  and (gso.upgrade_goods_type = :gt "
                "       or gso.upgrade_secondary_goods_type = :gt "
                "       or gso.upgrade_third_level_goods_type = :gt) "
                "  and go.merchant_id in :mids "
                "group by go.merchant_id"
            ).bindparams(bindparam('mids', expanding=True)), {
                'd_start': d_start.strftime('%Y-%m-%d 00:00:00')
                    if isinstance(d_start, date) else f'{d_start} 00:00:00',
                'd_end': d_end.strftime('%Y-%m-%d 23:59:59')
                    if isinstance(d_end, date) else f'{d_end} 23:59:59',
                'gt': goods_type,
                'mids': [str(m) for m in m_ids],
            }).fetchall()
            result = {}
            for r in rows:
                deal = int(r[1]) if r[1] is not None else 0
                output = Decimal(str(r[2])) if r[2] is not None else Decimal('0')
                result[str(r[0])] = {'deal': deal, 'output': output}
            return result
        finally:
            conn.close()

    # ============================================================
    # 附件模板下载(门店名称预填)
    # ============================================================

    def build_attachment_template(self):
        """基于附件模板预填门店名称,返回临时文件路径(调用方负责发送/清理)。

        ⚠ 生产环境存在同名商户(商户号不同):模板按门店名称去重,同名只预填
        第一次出现的行(ORDER BY g.id, r.merchant_id 的第一个商户号)。
        """
        stores = self.load_store_list()
        seen = set()
        uniq = []
        for store in stores:
            if store['merchant_name'] in seen:
                continue
            seen.add(store['merchant_name'])
            uniq.append(store)
        wb = openpyxl.load_workbook(ATTACH_TEMPLATE_PATH)
        ws = wb.worksheets[0]
        for idx, store in enumerate(uniq):
            ws.cell(row=4 + idx, column=1, value=store['merchant_name'])
        tmp_dir = tempfile.mkdtemp(prefix='guangai_tpl_')
        path = os.path.join(tmp_dir, '广爱专项-门店维度数据模板.xlsx')
        wb.save(path)
        return path, tmp_dir

    # ============================================================
    # 附件解析校验 + 入库(任务创建/重新生成时同步调用)
    # ============================================================

    # 附件模板列(1 起):门店名称/品牌/是否有打通售后/一店一群·交车数/一店一群·触客数/触客率/产值目标/件数目标
    VALID_BRANDS = ('广汽丰田', '广汽本田', '广汽传祺')

    def download_attachment(self, file_url, tmp_dir):
        """下载 OSS 附件到临时目录,返回本地路径(调用方清理 tmp_dir)。"""
        from oss_utils import download_file
        local_path = os.path.join(tmp_dir, '门店维度数据.xlsx')
        download_file(file_url, local_path)
        return local_path

    def validate_attachment_file(self, attach_path, month, period_type,
                                 week_num, period_start, period_end):
        """解析并校验附件(纯校验,不写库、不建任务)。

        :return: {'ok': bool, 'rows': [GuangaiStoreReportData...], 'errors': {行号: 原因}}
        """
        stores = self.load_store_list()
        # 同名商户(商户号不同)取第一个(ORDER BY g.id, r.merchant_id 首条);
        # 不再做"文件内门店名称重复"校验(2026-10-19 用户确认屏蔽)。
        name_map = {}
        for s_ in stores:
            if s_['merchant_name'] not in name_map:
                name_map[s_['merchant_name']] = s_

        wb = openpyxl.load_workbook(attach_path)
        ws = wb.worksheets[0]
        header_row = None
        for r in range(1, min(ws.max_row, 10) + 1):
            if str(ws.cell(row=r, column=1).value or '').strip() == '门店名称':
                header_row = r
                break
        if header_row is None:
            raise ValueError('附件格式错误:未找到"门店名称"表头列')

        errors = {}
        parsed = []
        for r in range(header_row + 1, ws.max_row + 1):
            name = ws.cell(row=r, column=1).value
            # 模板自带"填写说明"行(首列 = "系统预填,请勿修改…"),非数据行,跳过
            if name is not None and ('系统预填' in str(name) or '请勿修改' in str(name)):
                continue
            brand = ws.cell(row=r, column=2).value
            after = ws.cell(row=r, column=3).value
            delivery = ws.cell(row=r, column=4).value
            refer = ws.cell(row=r, column=5).value
            rate = ws.cell(row=r, column=6).value
            out_target = ws.cell(row=r, column=7).value
            unit_target = ws.cell(row=r, column=8).value
            if all(v is None or str(v).strip() == ''
                   for v in (name, brand, after, delivery, refer, rate,
                             out_target, unit_target)):
                continue
            row_errors = []

            name_s = str(name).strip() if name is not None else ''
            store = name_map.get(name_s)
            if not name_s:
                row_errors.append('门店名称为空')
            elif not store:
                row_errors.append('门店名称在系统中不存在(须与系统完全一致)')

            brand_s = str(brand).strip() if brand is not None else ''
            if brand_s not in self.VALID_BRANDS:
                row_errors.append('品牌必须为 广汽丰田/广汽本田/广汽传祺 之一')

            after_s = str(after).strip() if after is not None else ''
            if after_s not in ('是', '否'):
                row_errors.append('是否有打通售后必须为 是/否')

            delivery_v = self._parse_nonneg_int(delivery)
            if delivery is None or str(delivery).strip() == '' or delivery_v is None:
                row_errors.append('一店一群·交车数必须为 ≥0 的整数(必填)')
                delivery_v = None
            refer_v = self._parse_nonneg_int(refer)
            if refer is None or str(refer).strip() == '' or refer_v is None:
                row_errors.append('一店一群·触客数必须为 ≥0 的整数(必填)')
                refer_v = None

            rate_v = None
            if rate is not None and str(rate).strip() != '':
                try:
                    rate_v = Decimal(str(rate).strip().replace('%', '')) / (
                        Decimal('100') if '%' in str(rate) else Decimal('1'))
                except Exception:
                    row_errors.append('触客率格式错误')
                    rate_v = None
            if rate_v is not None and delivery_v is not None:
                expect = _q4(Decimal(refer_v) / Decimal(delivery_v)) \
                    if delivery_v else None
                if expect is None:
                    row_errors.append('交车数为 0 时触客率必须留空')
                    rate_v = None
                elif _q4(rate_v) != expect:
                    row_errors.append(
                        f'触客率与 触客数÷交车数 不一致(应为 {expect})')
                    rate_v = None
            if rate_v is not None:
                rate_v = _q4(rate_v)

            out_v = self._parse_nonneg_num(out_target, '产值目标', row_errors)
            unit_v = self._parse_nonneg_int(unit_target, allow_empty=True,
                                            label='件数目标', errors=row_errors)

            if row_errors:
                errors[r] = ';'.join(row_errors)
            elif store:
                parsed.append(GuangaiStoreReportData(
                    month=month,
                    period_type=period_type or 'month',
                    week_num=week_num if period_type == 'week' else None,
                    period_start=period_start,
                    period_end=period_end,
                    merchant_id=store['merchant_id'],
                    merchant_name=store['merchant_name'],
                    brand=brand_s,
                    after_sales_enabled=after_s,
                    group_delivery_cnt=delivery_v,
                    group_refer_cnt=refer_v,
                    refer_rate=rate_v,
                    output_target=out_v,
                    unit_target=unit_v,
                ))
        # 同名商户映射到第一个商户号后,文件内可能出现重复 merchant_id
        # (旧模板预填含重复门店名)→ 按商户号去重,保留首次出现的行,
        # 否则同一批 INSERT 自撞唯一键 uq_guangai_store_dim(2026-10-19 实测)
        dedup = {}
        for row in parsed:
            if row.merchant_id not in dedup:
                dedup[row.merchant_id] = row
        parsed = list(dedup.values())
        return {'ok': not errors, 'rows': parsed, 'errors': errors}

    def build_error_file(self, attach_path, errors, out_path):
        """在原附件最后追加"错误原因"列并另存为错误文件。"""
        wb = openpyxl.load_workbook(attach_path)
        ws = wb.worksheets[0]
        header_row = None
        for r in range(1, min(ws.max_row, 10) + 1):
            if str(ws.cell(row=r, column=1).value or '').strip() == '门店名称':
                header_row = r
                break
        err_col = ws.max_column + 1
        hc = ws.cell(row=header_row, column=err_col, value='错误原因')
        hc.font = Font(bold=True, color='FF0000')
        for r, msg in errors.items():
            ws.cell(row=r, column=err_col, value=msg)
        wb.save(out_path)
        return out_path

    # 原地更新时需同步的业务字段(不覆盖 id / created_at / creator)
    UPSERT_FIELDS = ('merchant_name', 'brand', 'after_sales_enabled',
                     'group_delivery_cnt', 'group_refer_cnt', 'refer_rate',
                     'output_target', 'unit_target',
                     'period_start', 'period_end')

    def store_validated_rows(self, rows, task_id, operator):
        """校验通过的行入库:按 月+维度+商户 **原地更新**(不存在才新增)。

        ⚠ 不能"软删旧行再插新行":唯一键 uq_guangai_store_dim 为
          (month, period_type, week_num, merchant_id),不含 is_deleted/task_id,
          软删的行仍占键 → 同一周期重新生成(task_id 不变)或重复上传必然
          撞 1062 Duplicate entry(2026-10-20 实测:2026-09-week-3 重新生成报错)。
          month 维度因 week_num 为 NULL 不参与唯一性判定,才侥幸没暴露。
        因此改为:命中已有行 → 原地覆盖业务字段并复活;文件里已不存在的门店
        才软删(保留可追溯,后续重新出现会被复活)。
        """
        if not rows:
            return 0
        from datetime import datetime as _dt
        now = _dt.now()
        first = rows[0]
        # 取该 月+维度 下的全部行(含已软删),按商户号分组:有效行优先
        existing = GuangaiStoreReportData.query.filter_by(
            month=first.month,
            period_type=first.period_type,
            week_num=first.week_num,
        ).order_by(GuangaiStoreReportData.is_deleted.asc(),
                   GuangaiStoreReportData.id.asc()).all()
        by_mid = {}
        for e in existing:
            by_mid.setdefault(e.merchant_id, []).append(e)

        keep_mids = set()
        inserted = updated = purged = 0
        for row in rows:
            keep_mids.add(row.merchant_id)
            hits = by_mid.get(row.merchant_id) or []
            if hits:
                target = hits[0]
                for f in self.UPSERT_FIELDS:
                    setattr(target, f, getattr(row, f))
                target.task_id = task_id
                target.updater = operator
                target.is_deleted = 0
                target.deleted_at = None
                updated += 1
                # 历史重复行(同一商户多行)物理删除,避免继续占用唯一键
                for dup in hits[1:]:
                    db.session.delete(dup)
                    purged += 1
            else:
                row.task_id = task_id
                row.creator = operator
                row.updater = operator
                db.session.add(row)
                inserted += 1

        # 本次附件中已不存在的门店 → 软删
        removed = 0
        for mid, ents in by_mid.items():
            if mid in keep_mids:
                continue
            for e in ents:
                if not e.is_deleted:
                    e.is_deleted = 1
                    e.deleted_at = now
                    e.updater = operator
                    removed += 1

        db.session.commit()
        logger.info(f"[广爱专项] 附件数据入库:新增 {inserted} 行、更新 {updated} 行、"
                    f"软删 {removed} 行、清理重复 {purged} 行")
        return inserted + updated

    @staticmethod
    def _parse_nonneg_int(val, allow_empty=False, label='', errors=None):
        if val is None or str(val).strip() == '':
            if allow_empty:
                return None
            return None  # 交车/触客必填:由调用方另行判空报错
        try:
            from decimal import Decimal as _D
            d = _D(str(val).strip())
            if d != d.to_integral_value() or d < 0:
                raise ValueError
            return int(d)
        except Exception:
            if errors is not None:
                errors.append(f'{label}必须为 ≥0 的整数')
            return None

    @staticmethod
    def _parse_nonneg_num(val, label, errors):
        if val is None or str(val).strip() == '':
            return None
        try:
            d = Decimal(str(val).strip())
            if d < 0:
                raise ValueError
            return d
        except Exception:
            errors.append(f'{label}必须为 ≥0 的数值')
            return None

    # ============================================================
    # 调度器入口 / 单任务处理
    # ============================================================

    def scan_guangai(self):
        """扫描 guangai_special 类型的 PROCESSING 任务并逐个处理。"""
        logger.info("[广爱专项] 开始扫描 guangai_special 待处理任务")
        tasks = DataProcessTask.query.filter_by(
            data_table_type=GUANGAI_TYPE,
            status='PROCESSING',
            is_deleted=0,
        ).order_by(DataProcessTask.id.asc()).all()
        logger.info(f"[广爱专项] 扫描到 {len(tasks)} 个待处理任务")

        success_count, fail_count = 0, 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):
        """处理单个广爱专项任务:取数 → 渲染 Excel → 上传 OSS → 回填任务状态。"""
        task_id = task.id
        try:
            period_start = task.period_start
            period_end = task.period_end
            if not period_start or not period_end:
                raise Exception("缺少所属周期(period_start/period_end),无法处理")
            period_start = self._as_date(period_start)
            period_end = self._as_date(period_end)
            if (period_start.year, period_start.month) != (period_end.year, period_end.month):
                raise Exception(f"所属周期不能跨月: {period_start} ~ {period_end}")
            # 按周时校验 period_end = 第 week_num 个周日(累计制)
            if task.period_type == 'week':
                w_start, w_end = compute_guangai_week_period(task.month, task.week_num)
                if period_start != w_start or period_end != w_end:
                    raise Exception(
                        f"按周周期与周区间定义不符: {period_start}~{period_end} "
                        f"应为 {w_start}~{w_end}")

            logger.info(f"[广爱专项] 开始处理 task_id={task_id}, "
                        f"周期={period_start}~{period_end}, "
                        f"维度={task.period_type}"
                        + (f"W{task.week_num}" if task.period_type == 'week' else ''))

            data = self.collect_data(task)
            logger.info(f"[广爱专项] 取数完成: {len(data['stores'])} 个门店")

            ts = datetime.now().strftime('%Y%m%d%H%M%S')
            file_name = (f"广爱专项_{period_start.strftime('%Y%m%d')}"
                         f"-{period_end.strftime('%Y%m%d')}_{ts}.xlsx")
            tmp_dir = tempfile.mkdtemp(prefix=f'guangai_{task_id}_')
            try:
                excel_path = os.path.join(tmp_dir, file_name)
                self.build_workbook(data, task, period_start, period_end, excel_path)
                object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
                              f"/{file_name}")
                file_url = upload_file(excel_path, object_key)
            finally:
                cleanup_tmp_dir(tmp_dir)

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

    # ============================================================
    # 数据采集
    # ============================================================

    def collect_data(self, task):
        """采集渲染所需全部数据。"""
        period_start = self._as_date(task.period_start)
        period_end = self._as_date(task.period_end)
        start_str = period_start.strftime('%Y-%m-%d')
        end_str = period_end.strftime('%Y-%m-%d')
        month_first = date(period_start.year, period_start.month, 1)

        # 上月整月区间
        first_of_month = date(period_start.year, period_start.month, 1)
        last_of_prev = first_of_month - timedelta(days=1)
        prev_first = date(last_of_prev.year, last_of_prev.month, 1)
        prev_last = last_of_prev
        prev_start_str = prev_first.strftime('%Y-%m-%d')
        prev_end_str = prev_last.strftime('%Y-%m-%d')

        # 门店清单 + 系统字段(B/C/G/H)
        stores = self.load_store_list()
        mids = [s['merchant_id'] for s in stores]
        province, shop_type, director, biz_dev_date = {}, {}, {}, {}
        conn = _get_biz_sql_conn()
        if conn is None:
            raise Exception("业务库(dj_smartcarlife)连接失败")
        try:
            # B 省份
            for r in conn.execute(text(
                "select merchant_id, province_name from dj_car_life_service_merchant "
                "where deleted_flag='N' and merchant_id in :mids"
            ).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
                province[str(r[0])] = shorten_province(r[1])
            # C 驻店类型:yqmerchant_config.partner_merchant_id == D+ 主服务商户 ID → 直营
            # ⚠ 真实表列名为 merchant_id(无 shop_merchant_id),2026-10-19 实测修正;
            #   同商户可能有多条配置,任一命中 D+ 主服务商户 ID 即直营
            dj_id = str(Config.GUANGAI_DJ_SERVICE_MERCHANT_ID)
            partners = {}
            for r in conn.execute(text(
                "select merchant_id, partner_merchant_id "
                "from dj_car_life_yqmerchant_config "
                "where merchant_id in :mids and deleted_flag='N' "
                "group by merchant_id, partner_merchant_id"
            ).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
                partners.setdefault(str(r[0]), set()).add(
                    str(r[1]) if r[1] is not None else '')
            for mid in mids:
                vals = partners.get(str(mid))
                shop_type[str(mid)] = (
                    '直营' if vals and dj_id in vals else '非直营')
            # G 运营经理:director_type=9(2.1 区域运营),多值 / 分割
            for r in conn.execute(text(
                "select merchant_id, director_name "
                "from dj_car_life_shop_merchant_director_config "
                "where deleted_flag='N' and director_type=9 and merchant_id in :mids"
            ).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
                mid = str(r[0])
                seen = director.setdefault(mid, [])
                if r[1] and r[1] not in seen:
                    seen.append(r[1])
            director = {k: '/'.join(v) for k, v in director.items()}
            # H 业务开展日期:首笔延保订单时间(scene_type=0)
            for r in conn.execute(text(
                "select go.merchant_id, min(go.order_time) as first_order_time "
                "from dj_car_life_goods_order go "
                "where go.deleted_flag='N' and go.scene_type=0 "
                "  and go.merchant_id in :mids "
                "group by go.merchant_id"
            ).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
                v = r[1]
                biz_dev_date[str(r[0])] = v.strftime('%Y-%m-%d') if v else None
        finally:
            conn.close()

        client = IndicatorClient()
        weeks = []   # [(week_num, start, end)] 周期内存在的周(累计制)
        for w in range(1, 5):
            w_start, w_end = compute_guangai_week_period(
                period_start.strftime('%Y-%m'), w)
            if w_start >= period_start and w_end <= period_end:
                weeks.append((w, w_start, w_end))

        def fetch(d_start, d_end, biz, codes, m_ids):
            if not m_ids:
                return {}
            return client.fetch_by_merchant_ids(
                d_start.strftime('%Y-%m-%d') if isinstance(d_start, date) else d_start,
                d_end.strftime('%Y-%m-%d') if isinstance(d_end, date) else d_end,
                codes, m_ids, biz=biz)

        # 本月周期(⚠ 2026-10-19:全部 biz=1,去掉 biz=3——原厂权益属延保大类子类)
        cur_b1 = fetch(period_start, period_end, 1,
                       [CODE_DELIVERY, CODE_TOUCH, CODE_DEAL, CODE_OUTPUT,
                        CODE_AFTER_ORDER, CODE_REFER_COUNT,
                        CODE_VEHICLE_DEAL, CODE_VEHICLE_DEAL_RATE], mids)
        # 上月整月(本月门店口径:明细 M/N、AT/AV)
        prev_b1 = fetch(prev_first, prev_last, 1,
                        [CODE_DEAL, CODE_OUTPUT], mids)
        # 周区间累计(W1~W4 中 ≤ 周期结束的):AJ~AM 分母 A084
        week_ind = {}
        for w, w_start, w_end in weeks:
            week_ind[w] = fetch(w_start, w_end, 1,
                                [CODE_DEAL, CODE_DELIVERY, CODE_REFER_COUNT], mids)
        # 本月累计(1 日~周期结束,AN 评灯 / 品牌汇总 N 的 A084 分母)
        cum_b1 = fetch(month_first, period_end, 1, [CODE_REFER_COUNT], mids)

        # 上月底生效门店快照(品牌汇总·上月 / 环比口径)
        prev_month_end = prev_last.strftime('%Y-%m-%d 23:59:59')
        snapshot_mids = self.load_month_end_snapshot_stores(prev_month_end)
        prev_snap_b1 = fetch(prev_first, prev_last, 1,
                             [CODE_DELIVERY, CODE_TOUCH, CODE_OUTPUT,
                              CODE_AFTER_ORDER, CODE_REFER_COUNT,
                              CODE_VEHICLE_DEAL, CODE_VEHICLE_DEAL_RATE],
                             snapshot_mids)

        # 原厂权益(商品类目 189)业务库 SQL:明细 AF/AG、AJ~AM 分子、AN、品牌汇总 M/N
        oe_cur = self.fetch_original_equity(period_start, period_end, mids)
        oe_cum = self.fetch_original_equity(month_first, period_end, mids)
        oe_week = {w: self.fetch_original_equity(w_start, w_end, mids)
                   for w, w_start, w_end in weeks}
        oe_prev_snap = self.fetch_original_equity(prev_first, prev_last, snapshot_mids)

        # 附件数据:当前维度(月/周)+ 上月整月
        cur_rows = GuangaiStoreReportData.query.filter_by(
            month=task.month, period_type=task.period_type or 'month',
            week_num=task.week_num if task.period_type == 'week' else None,
            is_deleted=0).all()
        cur_attach = {r.merchant_id: r for r in cur_rows}
        prev_rows = GuangaiStoreReportData.query.filter_by(
            month=prev_first.strftime('%Y-%m'), period_type='month',
            is_deleted=0).all()
        prev_attach = {r.merchant_id: r for r in prev_rows}

        return {
            'stores': stores,
            'province': province,
            'shop_type': shop_type,
            'director': director,
            'biz_dev_date': biz_dev_date,
            'cur_b1': cur_b1,
            'prev_b1': prev_b1,
            'week_ind': week_ind, 'weeks': weeks,
            'cum_b1': cum_b1,
            'snapshot_mids': snapshot_mids,
            'prev_snap_b1': prev_snap_b1,
            'oe_cur': oe_cur, 'oe_cum': oe_cum,
            'oe_week': oe_week, 'oe_prev_snap': oe_prev_snap,
            'cur_attach': cur_attach, 'prev_attach': prev_attach,
            'prev_first': prev_first, 'prev_last': prev_last,
        }

    # ============================================================
    # Excel 渲染
    # ============================================================

    def build_workbook(self, data, task, period_start, period_end, out_path):
        """按模板渲染广爱专项报表并保存到 out_path。"""
        period_start = self._as_date(period_start)
        period_end = self._as_date(period_end)
        stores = data['stores']
        n = len(stores)
        delta = n - SAMPLE_STORE_ROWS

        wb = openpyxl.load_workbook(OUTPUT_TEMPLATE_PATH)
        ws = wb[OUTPUT_SHEET]

        # ---------- 0) 清空模板条件格式 ----------
        from openpyxl.formatting.formatting import ConditionalFormattingList
        ws.conditional_formatting = ConditionalFormattingList()

        # ---------- 1) 行1 标题动态替换 ----------
        t1 = ws.cell(row=1, column=1)
        if t1.value:
            title = str(t1.value)
            title = title.replace('2026-08-16', period_end.strftime('%Y-%m-%d'))
            title = title.replace('8.16', f'{period_end.month}.{period_end.day}')
            title = title.replace('8月', f'{period_start.month}月')
            t1.value = title

        # ---------- 2) 解除 38 行以下全部合并(品牌汇总/周区间区,行平移后重建) ----------
        below_merges = []
        for rng in [r for r in ws.merged_cells.ranges if r.min_row >= 38]:
            below_merges.append((rng.min_row, rng.min_col, rng.max_row, rng.max_col,
                                 ws.cell(row=rng.min_row, column=rng.min_col).value))
            ws.unmerge_cells(str(rng))

        # ---------- 3) 捕获数据行样式(模板第 7 行样例) ----------
        row_styles = {c: copy(ws.cell(row=DATA_START_ROW, column=c)._style)
                      for c in range(1, LAST_COL + 1)}

        # ---------- 4) 调整门店行数(模板样例 31 行) ----------
        if delta > 0:
            ws.insert_rows(DATA_START_ROW + 1, delta)
        elif delta < 0:
            ws.delete_rows(DATA_START_ROW + n, -delta)

        # ---------- 5) 写门店明细(行 7 起)+ 合计行(行 6) ----------
        self._write_detail(ws, data, task, stores, period_start, period_end,
                           row_styles, delta)

        # ---------- 6) 品牌汇总(本月/上月,各 1 行) ----------
        self._write_brand_summary(ws, data, task, period_start, period_end, delta)

        # ---------- 7) 重建 38 行以下合并区(行平移 delta) ----------
        for (min_row, min_col, max_row, max_col, _v) in below_merges:
            ws.merge_cells(start_row=min_row + delta, start_column=min_col,
                           end_row=max_row + delta, end_column=max_col)

        wb.save(out_path)
        logger.info(f"[广爱专项] Excel 已生成: {out_path}({n} 门店, 维度="
                    f"{task.period_type}" + (f"W{task.week_num}" if task.period_type == 'week' else '') + ")")
        return out_path

    # ---------------- 明细 ----------------

    def _write_detail(self, ws, data, task, stores, period_start, period_end,
                      row_styles, delta):
        cur_b1 = data['cur_b1']
        prev_b1 = data['prev_b1']
        week_ind, weeks = data['week_ind'], data['weeks']
        cum_b1 = data['cum_b1']
        oe_cur = data['oe_cur']
        oe_cum = data['oe_cum']
        oe_week = data['oe_week']
        cur_attach, prev_attach = data['cur_attach'], data['prev_attach']
        province, shop_type = data['province'], data['shop_type']
        director, biz_dev = data['director'], data['biz_dev_date']

        def g1(ind, code):
            # ind 已是按商户取出的 {itemCode: value} 字典
            return (ind or {}).get(code)

        # 合计累加器(行 6)
        totals = {c: None for c in range(1, LAST_COL + 1)}
        sum_cols = [10, 11, 13, 14, 17, 18, 19, 20, 32, 33, 49, 50, 52, 53]  # J K M N Q R S T AF AG AW AX AZ BA
        sums = {c: Decimal('0') for c in sum_cols}
        has_val = {c: False for c in sum_cols}
        week_sums = {w: {'deal': Decimal('0'), 'deli': Decimal('0'), 'has': False}
                     for w, _s, _e in weeks}
        week_a084_sums = {w: Decimal('0') for w, _s, _e in weeks}
        week_a084_has = {w: False for w, _s, _e in weeks}
        week_oe_sums = {w: Decimal('0') for w, _s, _e in weeks}
        week_oe_has = {w: False for w, _s, _e in weeks}

        week_end_map = {w: w_end for w, _s, w_end in weeks}

        for idx, store in enumerate(stores):
            r = DATA_START_ROW + idx
            mid = store['merchant_id']
            att = cur_attach.get(mid)
            prev_att = prev_attach.get(mid)
            b1 = cur_b1.get(mid) or {}
            pb1 = prev_b1.get(mid) or {}
            cum = cum_b1.get(mid) or {}
            oe_c = oe_cur.get(mid) or {}
            oe_cm = oe_cum.get(mid) or {}

            delivery_cur = g1(b1, CODE_DELIVERY)         # A062 本月
            touch_cur = g1(b1, CODE_TOUCH)               # A063 本月
            deal_cur = g1(b1, CODE_DEAL)                 # A075 延保本月
            output_cur = g1(b1, CODE_OUTPUT)             # A036 延保本月
            refer_cur = g1(b1, CODE_REFER_COUNT)         # A084 本月引荐

            # 上月(⚠ bizs 调整:延保大类已含原厂权益,A075/A036 biz=1 直取)
            deal_prev = g1(pb1, CODE_DEAL)
            output_prev = g1(pb1, CODE_OUTPUT)

            # 附件当前维度
            q_val = att.group_delivery_cnt if att else None    # Q 一店一群交车
            r_val = att.group_refer_cnt if att else None       # R 一店一群触客
            # 附件上月整月
            j_val = prev_att.group_delivery_cnt if prev_att else None
            k_val = prev_att.group_refer_cnt if prev_att else None
            l_val = prev_att.refer_rate if (prev_att and prev_att.refer_rate is not None) \
                else _div(k_val, j_val)

            u_val = _div(deal_cur, delivery_cur)               # U 延保成交/A062
            v_val = _div(u_val, Decimal('0.2')) if u_val is not None else None

            # W1~W4 渗透率(周区间累计 延保成交/延保交车)
            w_vals = {}
            for w, _ws, _we in weeks:
                wi = (week_ind.get(w) or {}).get(mid) or {}
                w_vals[w] = _div(g1(wi, CODE_DEAL), g1(wi, CODE_DELIVERY))

            aa_val = _div(g1(cum, CODE_DEAL), g1(cum, CODE_DELIVERY))
            aa_text = rating_text(aa_val)
            # 原厂权益(业务库 SQL,类目 189)
            oe_deal_cur = (oe_c.get('deal') or 0) if oe_c else 0
            oe_output_cur = oe_c.get('output') if oe_c else None
            ah_val = _div(oe_deal_cur, r_val)                  # AH = AF / R(附件触客)
            ai_val = _div(ah_val, Decimal('0.2')) if ah_val is not None else None
            an_val = _div((oe_cm.get('deal') or 0) if oe_cm else 0,
                          g1(cum, CODE_REFER_COUNT))           # AN 对象:周期累计 AF / 累计 A084

            values = {
                1: idx + 1,                                    # A 序号
                2: province.get(mid, '') or None,              # B 省份
                3: shop_type.get(mid, '') or None,             # C 驻店类型
                4: store['merchant_name'],                     # D 门店名称
                5: att.brand if att else None,                 # E 品牌(附件)
                6: '延保',                                     # F 门店类型
                7: director.get(mid, '') or None,              # G 运营经理
                8: biz_dev.get(mid) or None,                   # H 业务开展日期
                9: (att.after_sales_enabled if att else None),  # I 是否打通售后
                10: j_val,                                     # J 上月一店一群交车
                11: k_val,                                     # K 上月一店一群触客
                12: _pct(l_val),                               # L 上月触客率
                13: deal_prev,                                 # M 上月订单数(A075 biz=1)
                14: output_prev,                               # N 上月产值(A036 biz=1)
                15: _pct(_div(deal_prev, k_val)),              # O 上月触客渗透率
                16: _pct(_div(deal_prev, j_val)),              # P 上月交付渗透率
                17: q_val,                                     # Q 一店一群交车(附件)
                18: r_val,                                     # R 一店一群触客(附件)
                19: deal_cur,                                  # S 延保成交
                20: output_cur,                                # T 延保产值
                21: _pct(u_val),                               # U 交付渗透率
                22: _pct(v_val),                               # V 达成率
                27: rating_text(aa_val),                       # AA 延保评灯
                32: oe_deal_cur,                               # AF 原厂权益成交数(SQL 类目189)
                33: oe_output_cur,                             # AG 原厂权益产值(SQL)
                34: _pct(ah_val),                              # AH = AF / R
                35: _pct(ai_val),                              # AI = AH ÷ 20%
                45: att.output_target if att else None,        # AS 产值目标
                47: att.unit_target if att else None,          # AU 件数目标
                49: q_val,                                     # AW 一店一群(同Q)
                50: delivery_cur,                              # AX 产值表 A062
                52: r_val,                                     # AZ 一店一群(同R)
                53: touch_cur,                                 # BA 产值表 A063
            }
            # W1~W4 渗透率 + 评灯(仅周期内已结束的周)
            for w, _ws, _we in weeks:
                values[22 + w] = _pct(w_vals.get(w))           # W=23..Z=26
                values[27 + w] = rating_text(w_vals.get(w))    # AB=28..AE=31
                # 权益 W1~W4 渗透率 = 该周区间累计 AF ÷ 该区间累计 A084(Q11 确认同构)
                wk_oe = (oe_week.get(w) or {}).get(mid) or {}
                wk_a084 = g1((week_ind.get(w) or {}).get(mid), CODE_REFER_COUNT)
                wk_eq_rate = _div((wk_oe.get('deal') or 0), wk_a084)
                values[35 + w] = _pct(wk_eq_rate)              # AJ=36..AM=39
                values[40 + w] = rating_text(wk_eq_rate)       # AO=41..AR=44
            # AN 权益评灯 = 周期累计 AF ÷ 累计 A084(Q12 确认)
            values[40] = rating_text(an_val)                   # AN=40
            # 差异列 AY(51)=Q-AX;BB(54)=R-BA
            ay = None
            if q_val is not None and delivery_cur is not None:
                ay = int(q_val) - int(delivery_cur)
            bb = None
            if r_val is not None and touch_cur is not None:
                bb = int(r_val) - int(touch_cur)
            values[51] = ay
            values[54] = bb
            # AT(46)/AV(48) 目标达成(⚠ bizs 调整:上月+本月 各一个 biz=1 值)
            as_t = att.output_target if att else None
            au_t = att.unit_target if att else None
            total_output = self._sum2(output_prev, output_cur)
            total_deal = self._sum2(deal_prev, deal_cur)
            values[46] = _pct(_div(total_output, as_t)) if as_t else None
            values[48] = _pct(_div(total_deal, au_t)) if au_t else None

            ws.row_dimensions[r].height = 20
            for col in range(1, LAST_COL + 1):
                cell = ws.cell(row=r, column=col)
                cell._style = copy(row_styles.get(col))
                val = values.get(col)
                cell.value = val if val is not None else None
                # 比率列统一追加 % 号(值已是 ×100 的百分数,格式不再缩放)
                if col in RATE_COLS:
                    cell.number_format = RATE_NUMBER_FORMAT
                fill = RATE_FILL.get(val) if isinstance(val, str) else None
                if fill:
                    cell.fill = PatternFill(start_color=fill, end_color=fill,
                                            fill_type='solid')
                elif col in (51, 54) and val not in (None, 0):
                    cell.fill = PatternFill(start_color=DIFF_FILL,
                                            end_color=DIFF_FILL, fill_type='solid')

            # 合计累加
            for c in sum_cols:
                v = values.get(c)
                if v is not None:
                    sums[c] += Decimal(str(v))
                    has_val[c] = True
            for w, _ws, _we in weeks:
                wi = week_ind.get(w) or {}
                a84 = g1(wi, CODE_REFER_COUNT)
                if a84 is not None:
                    week_a084_sums[w] += Decimal(str(a84))
                    week_a084_has[w] = True
                wk_oe = (oe_week.get(w) or {}).get(mid) or {}
                if wk_oe.get('deal') is not None:
                    week_oe_sums[w] += Decimal(str(wk_oe['deal']))
                    week_oe_has[w] = True

        # 合计行(行 6)
        def set6(col, val):
            cell = ws.cell(row=6, column=col)
            cell.value = val if val is not None else None
            # 比率列统一追加 % 号(与明细行同口径)
            if col in RATE_COLS:
                cell.number_format = RATE_NUMBER_FORMAT

        set6(1, '合计')
        for c in range(2, 10):
            set6(c, None)
        for c in sum_cols:
            set6(c, float(sums[c]) if has_val[c] else None)
        set6(12, _pct(_div(sums[11], sums[10]) if has_val[11] and has_val[10] else None))
        set6(15, _pct(_div(sums[13], sums[11]) if has_val[13] and has_val[11] else None))
        set6(16, _pct(_div(sums[13], sums[10]) if has_val[13] and has_val[10] else None))
        set6(21, _pct(_div(sums[19], sums[50]) if has_val[19] and has_val[50] else None))
        u6 = _div(sums[19], sums[50]) if has_val[19] and has_val[50] else None
        set6(22, _pct(_div(u6, Decimal('0.2'))) if u6 is not None else None)
        for w, _ws, _we in weeks:
            set6(22 + w, _pct(_div(week_sums[w]['deal'], week_sums[w]['deli'])
                             if week_sums[w]['has'] and week_sums[w]['deli'] else None))
        for col in (27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48):
            set6(col, '-')
        # AH 合计 = ΣAF ÷ ΣR(附件触客);AI = AH ÷ 20%
        ah6 = _div(sums[32], sums[18]) if has_val[32] and has_val[18] else None
        set6(34, _pct(ah6))
        set6(35, _pct(_div(ah6, Decimal('0.2'))) if ah6 is not None else None)
        # 权益 W1~W4 合计渗透率 = Σ周区间 AF ÷ Σ该区间 A084
        for w, _ws, _we in weeks:
            set6(35 + w, _pct(_div(week_oe_sums[w], week_a084_sums[w])
                             if week_oe_has[w] and week_a084_has[w] else None))
        set6(51, int(sums[49] - sums[50]) if has_val[49] and has_val[50] else None)
        set6(54, int(sums[52] - sums[53]) if has_val[52] and has_val[53] else None)

    # ---------------- 品牌汇总(本月 / 上月,各 1 行) ----------------

    def _write_brand_summary(self, ws, data, task, period_start, period_end, delta):
        stores = data['stores']
        mids = [s['merchant_id'] for s in stores]
        cur_b1 = data['cur_b1']
        snap_b1 = data['prev_snap_b1']
        cur_attach, prev_attach = data['cur_attach'], data['prev_attach']
        snap_mids = data['snapshot_mids']
        prev_last = data['prev_last']
        oe_cur, oe_cum = data['oe_cur'], data['oe_cum']
        oe_prev_snap = data['oe_prev_snap']

        def total(ind, mids_, code):
            s = Decimal('0')
            has = False
            for m in mids_:
                v = (ind.get(m) or {}).get(code)
                if v is not None:
                    s += Decimal(str(v))
                    has = True
            return (float(s) if has else None)

        def count_yes(attach, mids_):
            return sum(1 for m in mids_
                       if m in attach and attach[m].after_sales_enabled == '是')

        def oe_deal_total(oe, mids_):
            s = Decimal('0')
            has = False
            for m in mids_:
                v = (oe.get(m) or {}).get('deal')
                if v is not None:
                    s += Decimal(str(v))
                    has = True
            return (float(s) if has else None)

        def oe_deal_sum_all(oe, mids_):
            """原厂权益成交合计(无数据记 0,分母参与计算)"""
            s = Decimal('0')
            for m in mids_:
                v = (oe.get(m) or {}).get('deal')
                if v is not None:
                    s += Decimal(str(v))
            return float(s)

        brands = sorted({a.brand for a in cur_attach.values()} |
                        {a.brand for a in prev_attach.values()})
        brand_label = '广爱 ' + '/'.join(
            b.replace('广汽', '') for b in brands) if brands else '广爱'

        # ---- 本月行(模板行 42 = 数据行;41 是"取值说明"行不可覆盖,2026-10-19 修正) ----
        r_cur = 42 + delta
        store_cnt = len(stores)
        # D = 本月 A036 ÷ 10000(延保大类含原厂权益,bizs=1 单值)
        output_wan = _q4(_div(total(cur_b1, mids, CODE_OUTPUT), Decimal('10000')))
        deli = total(cur_b1, mids, CODE_DELIVERY)
        touch = total(cur_b1, mids, CODE_TOUCH)
        g_cur = _div(touch, deli)
        h_cur = count_yes(cur_attach, mids)
        i_cur = _q4(_div(h_cur, store_cnt)) if store_cnt else None
        k_cur = total(cur_b1, mids, CODE_VEHICLE_DEAL)       # A066 整车延保成交数
        l_cur = total(cur_b1, mids, CODE_VEHICLE_DEAL_RATE)  # A067 整车延保渗透率
        m_cur = oe_deal_sum_all(oe_cur, mids)                # Σ明细 AF(SQL 类目189)
        # N = 累计 AF ÷ 累计 A084(1 日~统计日期)
        oe_cum_total = oe_deal_sum_all(oe_cum, mids)
        a084_cum_total = total(data['cum_b1'], mids, CODE_REFER_COUNT)
        n_cur = _div(oe_cum_total, a084_cum_total)
        row_cur = {
            1: '广爱', 2: brand_label, 3: store_cnt,
            4: output_wan, 5: deli, 6: touch, 7: _pct(g_cur),
            8: h_cur, 9: i_cur, 10: total(cur_b1, mids, CODE_AFTER_ORDER),
            11: k_cur, 12: _pct(l_cur),
            13: m_cur, 14: _pct(n_cur),
        }

        # ---- 上月行(模板行 48,平移 delta;快照门店) ----
        r_prev = 48 + delta
        snap_store_cnt = len(snap_mids)
        output_wan_p = _q4(_div(total(snap_b1, snap_mids, CODE_OUTPUT),
                                Decimal('10000')))
        deli_p = total(snap_b1, snap_mids, CODE_DELIVERY)
        touch_p = total(snap_b1, snap_mids, CODE_TOUCH)
        g_prev = _div(touch_p, deli_p)
        h_prev = count_yes(prev_attach, snap_mids)
        i_prev = _q4(_div(h_prev, snap_store_cnt)) if snap_store_cnt else None
        k_prev = total(snap_b1, snap_mids, CODE_VEHICLE_DEAL)
        l_prev = total(snap_b1, snap_mids, CODE_VEHICLE_DEAL_RATE)
        m_prev = oe_deal_sum_all(oe_prev_snap, snap_mids)    # 上月整月原厂权益成交
        a084_prev_total = total(snap_b1, snap_mids, CODE_REFER_COUNT)
        n_prev = _div(oe_deal_sum_all(oe_prev_snap, snap_mids), a084_prev_total)
        row_prev = {
            1: '广爱', 2: brand_label, 3: snap_store_cnt,
            4: output_wan_p, 5: deli_p, 6: touch_p, 7: _pct(g_prev),
            8: h_prev, 9: i_prev, 10: total(snap_b1, snap_mids, CODE_AFTER_ORDER),
            11: k_prev, 12: _pct(l_prev),
            13: m_prev, 14: _pct(n_prev),
        }

        # 环比 O~R(本月行):(本月 − 上月) ÷ 上月
        def mom(cur, prev):
            if cur is None or prev in (None, 0):
                return None
            return _pct(_div(Decimal(str(cur)) - Decimal(str(prev)), Decimal(str(prev))))

        row_cur[15] = mom(i_cur, i_prev)
        row_cur[16] = mom(g_cur, g_prev)
        row_cur[17] = mom(l_cur, l_prev)
        row_cur[18] = mom(n_cur, n_prev)

        for r, row in ((r_cur, row_cur), (r_prev, row_prev)):
            for col, val in row.items():
                cell = ws.cell(row=r, column=col)
                cell.value = val
                # 品牌汇总比率列一并追加 % 号
                if col in BRAND_SUMMARY_RATE_COLS:
                    cell.number_format = RATE_NUMBER_FORMAT
        # 上月行 O~R 留空(环比只在本月行)
        for col in range(15, 19):
            ws.cell(row=r_prev, column=col).value = None
        # 清掉本月/上月行未被覆盖的残留列(如样例 42 行的 O~R)
        for col in range(19, 55):
            ws.cell(row=r_cur, column=col).value = None
            ws.cell(row=r_prev, column=col).value = None

        # 行 39 / 45 标题动态替换(月字样)
        t39 = ws.cell(row=39 + delta, column=1)
        if t39.value:
            t39.value = str(t39.value).replace('8月', f'{period_start.month}月')
        t45 = ws.cell(row=45 + delta, column=1)
        if t45.value:
            t45.value = str(t45.value).replace('7月', f'{prev_last.month}月')

    # ---------------- 工具 ----------------

    @staticmethod
    def _sum2(a, b):
        """两数求和,全空返回 None。"""
        if a is None and b is None:
            return None
        s = Decimal('0')
        if a is not None:
            s += Decimal(str(a))
        if b is not None:
            s += Decimal(str(b))
        return s

    @staticmethod
    def _as_date(val):
        if isinstance(val, datetime):
            return val.date()
        if isinstance(val, date):
            return val
        return datetime.strptime(str(val)[:10], '%Y-%m-%d').date()