clean_budget_achievement.py 54.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 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
# -*- coding: utf-8 -*-
"""预算达成数据清洗脚本(第一步:结算数据汇总表 → biz_budget_achieve 前 7 个维度字段)。

处理链路:
    data_process_task(筛选:data_table_type + month + is_deleted=0 + status=PROCESSING)
        → 取任务主键 id
        → data_process_file(task_id + form_type='结算数据汇总表' + is_deleted=0)
        → 按 file_url 下载 OSS 上的 Excel
        → 解析并按维度分组
        → 写入 biz_budget_achieve

本期写入字段(维度 7 个 + 金额/占比 17 个,共 26 个):
    task_id、stat_month、is_multi_category、traffic_name、business_type、
    entity、brand、park_store、service_provider、
    order_count、gmv、revenue、cost_gmv、
    cost_gmv_ratio_current、cost_gmv_ratio_previous、
    traffic_fee_gmv、traffic_fee_gmv_ratio_current、traffic_fee_gmv_ratio_previous、
    service_fee、service_fee_ratio_current、service_fee_ratio_previous、
    cost_revenue、traffic_fee_revenue、dijia_profit_sharing、
    renovation_amortization(装修摊销,仅 1.1 业务)、
    store_consumables(门店资产耗材,按明细业务类型分别匹配预算行并分摊)、
    gmv_ratio(MGV占比=本行GMV/同业务类型且同流量方名称GMV合计,保存 gmv 时计算)、
    gmv_ratio_park(MGV占比=本行GMV/同业务类型且同园区店GMV合计,保存 gmv 时计算;
        用于装修摊销按园区店匹配时的 GMV 占比摊分;每组末行用 1-其余占比之和保证合计=1.0)

说明:
    - 金额指标按「业务类型+主体+流量方+品牌+园区店+服务商」维度累计汇总;
    - 各 *_ratio_current = 对应金额/GMV*100(保留 2 位);
    - 各 *_ratio_previous = 上月同维度比值,取自 biz_budget_achieve 中上一统计月的数据,
      若上月数据尚未处理则写 NULL,待上月跑完后重跑本脚本即可自动回填;
    - dijia_profit_sharing = GMV - 成本(GMV口径) - 流量费(GMV口径) - 服务费;
    - gmv_ratio 在保存 gmv 数据(save_budget_rows)时按「业务类型 + 流量方名称」聚合计算;
    - gmv_ratio_park 按「业务类型 + 园区店」聚合计算,装修摊销按园区店(G)匹配时用其做 GMV 占比摊分;
      两者均在每组最后一行用「1 - 其余行占比之和」回填,保证组内合计精确等于 1.0。

用法:
    python clean_budget_achievement.py --data-table-type budget_achievement --month 2026-06
    python clean_budget_achievement.py -t budget_achievement -m 2026-06 --dry-run
"""
import argparse
import logging
import os
import re
import sys
import tempfile
import traceback
from datetime import datetime
from decimal import Decimal
from urllib.parse import urlparse
import warnings
warnings.filterwarnings(
    'ignore',
    message='Workbook contains no default style, apply openpyxl\'s default',
    category=UserWarning,
    module='openpyxl.styles.stylesheet',
)

import pymysql
import requests

from config import Config
from parsers import (
    SettlementSummaryParser,
    RenovationDetailParser,
    ConsumablesDetailParser,
    normalize_bt,
)

# 数据源表单类型:结算数据汇总表 / 装修费用表 / 门店资产耗材明细表
FORM_TYPE_SETTLEMENT = '结算数据汇总表'
FORM_TYPE_RENOVATION = '装修费用表'
FORM_TYPE_CONSUMABLES = '门店资产耗材明细表'
# 装修摊销:摊销总月数(合同金额 / 摊销总月数)
RENOVATION_AMORT_MONTHS = 36
# 仅业务类型 1.1 需要装修摊销
RENOVATION_BIZ_TYPE = '1.1'
# 目标表
TARGET_TABLE = 'biz_budget_achieve'
# 任务状态:处理中
TASK_STATUS_PROCESSING = 'PROCESSING'
# 附件清洗状态:1 待清洗 / 2 清洗中 / 3 清洗完成
CLEAN_PENDING, CLEAN_RUNNING, CLEAN_DONE = 1, 2, 3

MONTH_PATTERN = re.compile(r'^\d{4}-(0[1-9]|1[0-2])$')

logger = logging.getLogger(__name__)


def log(msg):
    print(f'[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}', flush=True)


# ---------------- 数据库 ----------------


def get_conn():
    """按 config.Config(.env / .env.{APP_ENV})建立 MySQL 连接。"""
    return pymysql.connect(
        host=Config.MYSQL_HOST,
        port=Config.MYSQL_PORT,
        user=Config.MYSQL_USER,
        password=Config.MYSQL_PASSWORD,
        database=Config.MYSQL_DB,
        charset='utf8mb4',
        autocommit=False,
        connect_timeout=10,
        cursorclass=pymysql.cursors.DictCursor,
    )


def query_tasks(conn, data_table_type, month, ignore_status=False):
    """筛选任务单据:数据表类型 + 月份 + 未删除;(默认还要求 status=PROCESSING)。

    Args:
        ignore_status: True 时忽略 status 过滤(用于手动回填/重跑,不改变库内任务状态)。
    """
    if ignore_status:
        sql = (
            'SELECT id, data_table_type, month, status '
            'FROM data_process_task '
            'WHERE data_table_type = %s AND month = %s AND is_deleted = 0 '
            'ORDER BY id'
        )
        params = (data_table_type, month)
    else:
        sql = (
            'SELECT id, data_table_type, month, status '
            'FROM data_process_task '
            'WHERE data_table_type = %s AND month = %s AND is_deleted = 0 AND status = %s '
            'ORDER BY id'
        )
        params = (data_table_type, month, TASK_STATUS_PROCESSING)
    with conn.cursor() as cur:
        cur.execute(sql, params)
        return cur.fetchall()


def query_settlement_files(conn, task_id):
    """查询任务下未删除的「结算数据汇总表」附件(按 id 倒序,最新在前)。"""
    sql = (
        'SELECT id, task_id, form_type, file_name, file_url, clean_status '
        'FROM data_process_file '
        'WHERE task_id = %s AND form_type = %s AND is_deleted = 0 '
        'ORDER BY id DESC'
    )
    with conn.cursor() as cur:
        cur.execute(sql, (task_id, FORM_TYPE_SETTLEMENT))
        return cur.fetchall()


def update_clean_status(conn, file_id, status):
    """更新附件清洗状态。"""
    with conn.cursor() as cur:
        cur.execute('UPDATE data_process_file SET clean_status = %s WHERE id = %s', (status, file_id))
    conn.commit()


def prev_month_str(month):
    """'YYYY-MM' → 上一统计月字符串(如 2026-01 → 2025-12)。"""
    year, mon = month.split('-')
    year, mon = int(year), int(mon)
    if mon == 1:
        year, mon = year - 1, 12
    else:
        mon -= 1
    return f'{year:04d}-{mon:02d}'


def query_previous_month_metrics(conn, prev_month):
    """查询上一统计月 biz_budget_achieve 中各维度组的成本/GMV/流量费/服务费累计值。

    用于计算各"上月占比"字段。按 6 维度聚合,返回 dict:
    key=(traffic_name, business_type, entity, brand, park_store, service_provider),
    value={'cost_gmv':float, 'gmv':float, 'traffic_fee_gmv':float, 'service_fee':float}。

    若上月数据尚未处理(查无记录),返回空 dict,对应比值写 None。
    """
    sql = (
        'SELECT traffic_name, business_type, entity, brand, park_store, service_provider, '
        'SUM(cost_gmv) AS cost_gmv, SUM(gmv) AS gmv, '
        'SUM(traffic_fee_gmv) AS traffic_fee_gmv, SUM(service_fee) AS service_fee '
        'FROM biz_budget_achieve '
        'WHERE stat_month = %s '
        'GROUP BY traffic_name, business_type, entity, brand, park_store, service_provider'
    )
    result = {}
    with conn.cursor() as cur:
        cur.execute(sql, (prev_month,))
        for r in cur.fetchall():
            key = (r['traffic_name'], r['business_type'], r['entity'],
                   r['brand'], r['park_store'], r['service_provider'])
            result[key] = {
                'cost_gmv': float(r['cost_gmv'] or 0),
                'gmv': float(r['gmv'] or 0),
                'traffic_fee_gmv': float(r['traffic_fee_gmv'] or 0),
                'service_fee': float(r['service_fee'] or 0),
            }
    return result


def save_budget_rows(conn, task_id, stat_month, rows):
    """写入预算达成数据表:同一任务重跑先清空旧数据,再批量插入(单事务)。

    写入字段(共 26 列:含 task_id/stat_month 2 个控制列 + 维度 7 个 + 金额指标 17 个)。
    gmv_ratio / gmv_ratio_park 均在保存 gmv 数据时按「业务类型 + 流量方名称」/
    「业务类型 + 园区店」聚合计算。
    """
    # 计算 gmv_ratio:本行 GMV / 同业务类型且同流量方名称 GMV 合计(保留 6 位)
    # 计算 gmv_ratio_park:本行 GMV / 同业务类型且同园区店 GMV 合计(保留 6 位)
    # 为保证组内占比合计精确等于 1.0,每组最后一行的占比用 1 - 其余行占比之和回填。
    from collections import defaultdict
    # 入库前将流量方名称(traffic_name) / 园区店(park_store) 归一为字典表标准名;
    # 若不存在映射则保留结算数据汇总表中的原始名称(用户要求)。
    load_alias_maps(conn)
    for r in rows:
        r['traffic_name'] = to_standard(r['traffic_name'], '4s')
        r['park_store'] = to_standard(r['park_store'], 'yq')
    bt_gmv = defaultdict(float)        # (business_type, traffic_name) -> GMV 合计
    btp_gmv = defaultdict(float)       # (business_type, park_store)   -> GMV 合计
    for r in rows:
        bt_gmv[(r['business_type'], r['traffic_name'])] += float(r['gmv'] or 0)
        btp_gmv[(r['business_type'], r['park_store'])] += float(r['gmv'] or 0)

    def _fill_ratio(field, key_of, denom_of):
        """按组计算占比;每组最后一行用 1 - 其余占比之和,使组内合计精确为 1.0。"""
        groups = defaultdict(list)     # key -> [行下标]
        for i, r in enumerate(rows):
            groups[key_of(r)].append(i)
        for key, idxs in groups.items():
            denom = denom_of(key)
            if denom <= 0:
                for i in idxs:
                    rows[i][field] = None
                continue
            for i in idxs[:-1]:
                rows[i][field] = round(float(rows[i]['gmv'] or 0) / denom, 6)
            others = sum(rows[i][field] for i in idxs[:-1])
            last_val = round(1.0 - others, 6)
            # 兜底:极端四舍五入导致负数时退回自身正常占比,避免负值
            if last_val < 0:
                last_val = round(float(rows[idxs[-1]]['gmv'] or 0) / denom, 6)
            rows[idxs[-1]][field] = last_val

    _fill_ratio('gmv_ratio',
                lambda r: (r['business_type'], r['traffic_name']),
                lambda k: bt_gmv.get(k) or 0.0)
    _fill_ratio('gmv_ratio_park',
                lambda r: (r['business_type'], r['park_store']),
                lambda k: btp_gmv.get(k) or 0.0)

    insert_sql = (
        f'INSERT INTO {TARGET_TABLE} '
        '(task_id, stat_month, is_multi_category, traffic_name, business_type, '
        ' entity, brand, park_store, service_provider, '
        ' order_count, gmv, revenue, cost_gmv, '
        ' cost_gmv_ratio_current, cost_gmv_ratio_previous, '
        ' traffic_fee_gmv, traffic_fee_gmv_ratio_current, traffic_fee_gmv_ratio_previous, '
        ' service_fee, service_fee_ratio_current, service_fee_ratio_previous, '
        ' cost_revenue, traffic_fee_revenue, dijia_profit_sharing, gmv_ratio, gmv_ratio_park) '
        'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, '
        '        %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
    )
    params = [
        (
            task_id,
            stat_month,
            r['is_multi_category'],
            r['traffic_name'] or None,
            r['business_type'] or None,
            r['entity'] or None,
            r['brand'] or None,
            r['park_store'] or None,
            r['service_provider'] or None,
            r['order_count'],
            r['gmv'],
            r['revenue'],
            r['cost_gmv'],
            r['cost_gmv_ratio_current'],
            r['cost_gmv_ratio_previous'],
            r['traffic_fee_gmv'],
            r['traffic_fee_gmv_ratio_current'],
            r['traffic_fee_gmv_ratio_previous'],
            r['service_fee'],
            r['service_fee_ratio_current'],
            r['service_fee_ratio_previous'],
            r['cost_revenue'],
            r['traffic_fee_revenue'],
            r['dijia_profit_sharing'],
            r['gmv_ratio'],
            r['gmv_ratio_park'],
        )
        for r in rows
    ]
    try:
        with conn.cursor() as cur:
            cur.execute(f'DELETE FROM {TARGET_TABLE} WHERE task_id = %s AND stat_month = %s',
                        (task_id, stat_month))
            deleted = cur.rowcount
            cur.executemany(insert_sql, params)
        conn.commit()
        return deleted, len(params)
    except Exception:
        conn.rollback()
        raise


# ---------------- 装修摊销 ----------------


def query_renovation_file(conn, task_id):
    """查询任务下未删除的「装修费用表」附件(按 id 倒序,最新在前)。"""
    sql = (
        'SELECT id, task_id, form_type, file_name, file_url, clean_status '
        'FROM data_process_file '
        'WHERE task_id = %s AND form_type = %s AND is_deleted = 0 '
        'ORDER BY id DESC'
    )
    with conn.cursor() as cur:
        cur.execute(sql, (task_id, FORM_TYPE_RENOVATION))
        return cur.fetchall()


def query_task_biz_rows(conn, task_id, stat_month, business_type):
    """查询本任务下指定业务类型的预算达成结果行(用于装修摊销的 GMV 占比分摊)。

    Returns:
        list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, service_provider}
    """
    sql = (
        'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, service_provider '
        'FROM biz_budget_achieve '
        'WHERE task_id = %s AND stat_month = %s AND business_type = %s'
    )
    with conn.cursor() as cur:
        cur.execute(sql, (task_id, stat_month, business_type))
        return cur.fetchall()


def _month_index(year, month):
    """年份月份 → 0 基月序号(便于区间比较)。"""
    return year * 12 + month - 1


def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOVATION_AMORT_MONTHS):
    """按规则计算每行预算达成数据的「装修摊销」金额。

    规则(用户提供,逐条明细定模式、避免重复计提):
      1. 仅 business_type='1.1' 的结果行参与(biz_rows 已按此过滤)。
      2. 基数 = 明细表「合同金额」(L) ÷ 摊销总月数(n_months);
         合同金额为负时作为冲减(负摊销)参与计算,不整条丢弃;
         仅取明细中存在「实际验收日期」(T) 的记录,且 stat_month 落在
         [验收次月, 验收+摊销总月数] 区间内才计提
         (用户明确规则:当前月份须 ∈ [验收+1月, 验收+36月])。
      3. 每条装修明细独立判定匹配模式:
         - 先用明细「门店名称」(F) 匹配结果行的 traffic_name:
           命中 → 该明细费用计入 F 池(key=归一化门店名称),
           按命中结果行的 GMV 占比分摊;
         - 若「门店名称」匹配不到任何结果行的 traffic_name,且「门店名称」列为空,
           再用明细「系统园区店名称」(G) 匹配结果行的 park_store(限 1.1):
           命中 → 计入 G 池(key=归一化系统园区店名称),按命中结果行 GMV 占比分摊。
           注:门店名称非空但未命中 F 的明细,不允许再落到 G 池。
      4. 每条明细只计一次(F / G 二选一),因此不会重复计提;
         同一匹配池(同一 traffic_name / 同一 park_store)下有多条结果行的,
         按各行 GMV 占比摊分该池的装修摊销总额。

    Args:
        detail_rows: RenovationDetailParser.parse() 的结果列表。
        biz_rows:    query_task_biz_rows() 的结果列表(仅 1.1)。
        stat_month:  'YYYY-MM'。
        n_months:    摊销总月数,默认 36。

    Returns:
        dict: {biz_row_id: 装修摊销金额(float, 已四舍五入 2 位)}
              未匹配到明细的结果行不出现在返回 dict 中(保持 NULL)。
    """
    from collections import defaultdict
    cur_y, cur_m = (int(x) for x in stat_month.split('-'))
    cur_idx = _month_index(cur_y, cur_m)

    def in_window(accept_date):
        """实际验收日期对应记录是否在计提窗口内。
        用户明确规则:当前月份须落在 [验收日期+1月, 验收日期+36月] 区间内。
        即 下限=验收次月(次月起算),上限=验收+36月。
        """
        if accept_date is None or not hasattr(accept_date, 'year'):
            return False
        start_idx = _month_index(accept_date.year, accept_date.month) + 1   # 次月
        end_idx = _month_index(accept_date.year, accept_date.month) + n_months
        return start_idx <= cur_idx <= end_idx

    # 预建立:归一化名称 → 命中结果行列表(仅 1.1)
    # 预算行名称已是标准名(入库时归一);再做 strip_if_dplus 使 D+ 前缀不参与比较,
    # 与明细侧口径一致。别名经 to_standard 已归并到标准名下。
    f_rows = defaultdict(list)   # 归一化 traffic_name → 1.1 结果行
    g_rows = defaultdict(list)   # 归一化 park_store → 1.1 结果行
    for r in biz_rows:
        tn = strip_if_dplus(to_standard(r['traffic_name'] or '', '4s'))
        ps = strip_if_dplus(to_standard(r['park_store'] or '', 'yq'))
        if tn:
            f_rows[tn].append(r)
        if ps:
            g_rows[ps].append(r)

    # 每条明细独立判定 F / G 模式,各自累加进对应池(每条明细只计一次)
    f_pool = defaultdict(float)   # key=归一化门店名称(F) → 应摊总额
    g_pool = defaultdict(float)   # key=归一化系统园区店名称(G) → 应摊总额
    total_detail_amount = Decimal('0')   # 所有有效明细(in_window 且 amt!=0)的金额合计
    unmatched_amount = Decimal('0')      # 未匹配到任何 pool 的明细金额合计
    for d in detail_rows:
        if not in_window(d['accept_date']):
            continue
        amt = (d['contract_amount'] or 0.0) / n_months
        if amt == 0:
            continue
        total_detail_amount += Decimal(str(amt))
        # 明细名先归一为标准名(别名归并),再 strip D+ 与预算行口径一致
        fn = strip_if_dplus(to_standard(d['store_name'], '4s'))
        gn = strip_if_dplus(to_standard(d['park_store_name'], 'yq'))
        if fn and fn in f_rows:
            f_pool[fn] += amt                       # F 模式:按门店名称匹配
        elif gn and gn in g_rows and not fn:
            # G 模式(兜底):仅当「门店名称」列为空时才允许按系统园区店名称匹配;
            # 门店名称非空但未命中 F 的明细,不允许再落到 G 池。
            g_pool[gn] += amt
        else:
            unmatched_amount += Decimal(str(amt))   # 未匹配到任何 pool

    # 按 GMV 占比分摊各池
    #   - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
    #   - G 池(按系统园区店名称/park_store 匹配):用 mgv_ratio_park(按业务类型+园区店)
    #     作为该行的摊分系数,更直接体现「同业务类型+同园区店」的 GMV 占比。
    result = {}
    # 用于 _allocate 内部把"全非嘀加被跳过"的悬空金额转进 unmatched_amount
    _unmatched_skipped = Decimal('0')

    def _allocate(pool, row_map, field='gmv'):
        nonlocal _unmatched_skipped
        for key, total in pool.items():
            if total == 0:
                continue
            rows = row_map[key]
            # --- 服务商过滤:只保留 service_provider 含"嘀加"的行(嘀加自营/嘀加直营) ---
            dijia_rows = [r for r in rows if _is_dijia_row(r)]
            if not dijia_rows:
                # 全是非嘀加
                if len(rows) == 1:
                    # 只有一条行,即使不是嘀加自营,也分摊给他
                    logger.info(f"[装修摊销] key={key}: 仅 1 行且非嘀加 → 兜底全部分摊给该行")
                    dijia_rows = rows
                else:
                    # 多行全非嘀加 → 不分摊(费用=0),跳过 → 悬空金额进未匹配
                    logger.info(f"[装修摊销] key={key}: {len(rows)} 行全非嘀加 → 跳过(进未匹配)")
                    _unmatched_skipped += Decimal(str(total))
                    continue
            if len(dijia_rows) < len(rows):
                logger.info(f"[装修摊销] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
                            f" 服务商=嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
            rows = dijia_rows

            if field == 'mgv_ratio_park':
                # 优先用 mgv_ratio_park(同业务类型+同园区店 GMV 占比);
                # 若某行 mgv_ratio_park 为空(如 dry-run 预览时尚未写库),
                # 整池回退到本行 GMV 占比,避免漏配。
                ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None
                          for r in rows]
                if all(x is not None for x in ratios):
                    dist = distribute_by_weight(
                        total, [(r['id'], rp) for r, rp in zip(rows, ratios)])
                    for rid, amt in dist.items():
                        result[rid] = result.get(rid, 0) + amt
                    continue
                # 回退:按 GMV 占比
                gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
                if gmv_sum <= 0:
                    dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
                else:
                    dist = distribute_by_weight(
                        total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
                for rid, amt in dist.items():
                    result[rid] = result.get(rid, 0) + amt
                continue
            # 默认:按本行 GMV 占比摊分
            gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
            if gmv_sum <= 0:
                dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
            else:
                dist = distribute_by_weight(
                    total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
            for rid, amt in dist.items():
                result[rid] = result.get(rid, 0) + amt

    _allocate(f_pool, f_rows, field='gmv')
    _allocate(g_pool, g_rows, field='mgv_ratio_park')
    # 把池内"全非嘀加被跳过"的悬空金额并入未匹配
    if _unmatched_skipped:
        unmatched_amount += _unmatched_skipped
        logger.info(f"[装修摊销] 池内全非嘀加跳过的悬空金额={float(_unmatched_skipped):.2f} → 并入未匹配")
    # 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
    reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
    # 记录未匹配金额到返回 dict 的特殊 key
    pools_total = Decimal(str(round(sum(f_pool.values()) + sum(g_pool.values()), 2)))
    residual = total_detail_amount - pools_total - unmatched_amount
    if abs(float(residual)) >= 0.005:
        logger.info(
            f"[装修摊销对账] 明细总额={float(total_detail_amount):.2f} "
            f"池合计={float(pools_total):.2f} 未匹配={float(unmatched_amount):.2f} "
            f"残差={float(residual):.2f}"
        )
    result['_unmatched'] = float(unmatched_amount)
    return result


def strip_if_dplus(name):
    """返回字符串(保留 D+ 前缀)。"""
    return name or ''


# ---------------- 标准名 / 别名映射(merchant_4s 流量方、merchant_yq 园区店) ----------------

_ALIAS_MAPS = {}   # kind('4s'|'yq') -> {alias_name: standard_name}


def load_alias_maps(conn):
    """从 merchant_4s(流量方字典表)与 merchant_yq(园区店字典表)加载 别名→标准名 映射。

    一个标准名可对应多行别名;以 alias_name 为键、standard_name 为值。
    结果缓存到模块级 _ALIAS_MAPS,整个进程只加载一次(已加载则跳过)。
    用途:预算达成表统一存标准名;匹配/查询时别名数据归属到标准名下。
    """
    global _ALIAS_MAPS
    if _ALIAS_MAPS:
        return _ALIAS_MAPS
    maps = {}
    for kind, table in (('4s', 'merchant_4s'), ('yq', 'merchant_yq')):
        m = {}
        with conn.cursor() as cur:
            cur.execute(f'SELECT standard_name, alias_name FROM `{table}`')
            for r in cur.fetchall():
                sn = (r['standard_name'] or '').strip()
                an = (r['alias_name'] or '').strip()
                if an:
                    m[an] = sn
        maps[kind] = m
    _ALIAS_MAPS = maps
    return _ALIAS_MAPS


def to_standard(raw, kind):
    """将流量方名称(kind='4s')或园区店名称(kind='yq')归一为字典表中的标准名。

    - raw 在别名映射中 → 返回对应 standard_name(园区店标准名含 'D+' 前缀);
    - 否则尝试去 'D+' 前缀后再查一次别名映射;
    - 均查不到 → 返回 raw 原值(即使用结算数据汇总表中的原始名称,符合用户要求)。
    幂等:对已是标准名的输入返回其自身(alias==standard 行、或未映射名均如此)。
    """
    if raw is None:
        return raw
    raw = raw.strip()
    if not raw:
        return raw
    m = _ALIAS_MAPS.get(kind, {})
    if raw in m:
        return m[raw]
    s = strip_if_dplus(raw)
    if s and s != raw and s in m:
        return m[s]
    return raw



def distribute_by_weight(total, items):
    """将 total 按权重分摊到各 (row_id, weight),每行四舍五入到 2 位小数;

    为保证各池分摊金额合计精确等于该池匹配到的明细金额总和,最后一行
    (items 中最后一个 weight>0 的行)用 ``total - 前面各行已算金额`` 回填,
    吸收四舍五入残差,使本池合计精确 = total。

    Args:
        total: 该池应摊总额(float)。
        items: list of (row_id, weight),weight<=0 的行被忽略(不参与分摊)。
    Returns:
        dict: {row_id: 金额(float, 已四舍五入 2 位)},仅含 weight>0 的行。
    """
    pos = [(rid, w) for rid, w in items if w and w > 0]
    if not pos:
        return {}
    wsum = sum(w for _, w in pos)
    if wsum <= 0:
        return {}
    # 池总额先对齐到「分」,使末行余额补差后各池分摊合计精确等于该池金额(无舍入残差)
    total = round(total, 2)
    out = {}
    n = len(pos)
    acc = 0.0
    for i, (rid, w) in enumerate(pos):
        if i == n - 1:
            amt = round(total - acc, 2)          # 末行余额补差,吸收残差
        else:
            amt = round(total * w / wsum, 2)
            acc += amt
        out[rid] = amt
    return out


def reconcile_total(result, target_total):
    """把 result 中各行金额合计对齐到 target_total(2 位小数)。

    各池已分别做末行余额补差,但跨池四舍五入可能残留最多几分钱的差异;
    这里把残差加到金额最大的一行,保证「各方金额合计 == 匹配明细金额总和」
    精确成立(残差通常仅几分钱,加到最大行对相对占比扰动最小)。

    Args:
        result: dict {biz_row_id: 金额},会被原地修改。
        target_total: 该口径下匹配到的明细金额总和(2 位小数)。
    """
    if not result:
        return
    cur = round(sum(result.values()), 2)
    diff = round(target_total - cur, 2)
    if abs(diff) < 0.005:
        return
    rid = max(result, key=lambda k: result[k])   # 加到金额最大的行,最小化扰动
    result[rid] = round(result[rid] + diff, 2)


def update_renovation(conn, amounts):
    """把计算好的装修摊销写回 biz_budget_achieve(按主键 id 更新)。

    Args:
        amounts: dict {biz_row_id: 装修摊销金额}。空 dict 则不更新。
    Returns:
        int: 更新行数。
    """
    if not amounts:
        return 0
    sql = f'UPDATE {TARGET_TABLE} SET renovation_amortization = %s WHERE id = %s'
    params = [(amt, rid) for rid, amt in amounts.items()]
    try:
        with conn.cursor() as cur:
            cur.executemany(sql, params)
        conn.commit()
        return len(params)
    except Exception:
        conn.rollback()
        raise


# ---------------- 门店资产耗材 ----------------


def query_consumables_file(conn, task_id):
    """查询任务下未删除的「门店资产耗材明细表」附件(按 id 倒序,最新在前)。"""
    sql = (
        'SELECT id, task_id, form_type, file_name, file_url, clean_status '
        'FROM data_process_file '
        'WHERE task_id = %s AND form_type = %s AND is_deleted = 0 '
        'ORDER BY id DESC'
    )
    with conn.cursor() as cur:
        cur.execute(sql, (task_id, FORM_TYPE_CONSUMABLES))
        return cur.fetchall()


def query_all_biz_rows(conn, task_id, stat_month):
    """查询本任务下指定统计月的全部预算达成结果行(门店资产耗材按业务类型分别匹配用)。

    Returns:
        list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, business_type, service_provider}
    """
    sql = (
        'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, business_type, service_provider '
        'FROM biz_budget_achieve '
        'WHERE task_id = %s AND stat_month = %s'
    )
    with conn.cursor() as cur:
        cur.execute(sql, (task_id, stat_month))
        return cur.fetchall()


_DIJIA_SPIDER = '%嘀加%'   # 匹配服务商含"嘀加"的行(DB 实际值:嘀加自营/嘀加直营)


def _is_dijia_row(row):
    """判断 biz_budget_achieve 行的 service_provider 是否含"嘀加"(嘀加自营/嘀加直营)。"""
    sp = (row.get('service_provider') or row.get('serviceProvider') or '').strip()
    return '嘀加' in sp


def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
    """按规则计算每行预算达成数据的「门店资产耗材」金额。

    负数金额按冲减处理:明细金额为负时保留为负贡献,并入对应 F/G 池,
    最终按 GMV 占比摊成各行的负摊消(与装修摊销口径一致)。

    逻辑与装修摊销高度相似,差异:
      - 金额直接作为分摊基数,不做除法(无摊销总月数);
      - 不限制业务类型:按明细自身的业务类型(归一化后)分别匹配对应业务的预算行;
      - 仅取与 stat_month 同月的明细(月份标签如 '6月')。

    匹配规则(每条明细只计一次,F 优先):
      耗材明细的「门店名称」列实际混含公司名与园区店名,故采用候选名匹配:
      将明细的「门店名称」与「系统园区店名称」均作为候选名(去重,保留原值、不去 'D+' 前缀):
      1. 先任一轮候选名命中【同业务类型】结果行的 traffic_name(F) → 计入 F 池,
         按命中结果行 GMV 占比分摊;
      2. 否则任一轮候选名命中【同业务类型】结果行的 park_store(G) → 计入 G 池,
         按命中结果行 gmv_ratio_park(同业务类型+同园区店)分摊;
      3. 每条明细只计一次(F / G 二选一),与装修摊销一致不允许双重命中。

    Args:
        detail_rows: ConsumablesDetailParser.parse() 的结果列表。
        biz_rows:    query_all_biz_rows() 的结果列表(全部业务类型)。
        stat_month:  'YYYY-MM'。

    Returns:
        dict: {biz_row_id: 金额(float, 已四舍五入 2 位)}
              未匹配到明细的结果行不出现在返回 dict 中(保持 NULL)。
    """
    from collections import defaultdict
    cur_m = int(stat_month.split('-')[1])
    month_label = f'{cur_m}月'

    # 按业务类型分桶预算行,并预建 F/G 映射
    # 预算行名称已是标准名(入库时归一);这里再做 to_standard(幂等)统一口径,
    # 保留标准名中的 'D+' 前缀(与装修摊销不同:耗材匹配不去 D+)。
    bt_f = defaultdict(dict)   # bt -> {标准流量方名称: [biz rows]}
    bt_g = defaultdict(dict)   # bt -> {标准园区店名称: [biz rows]}
    for r in biz_rows:
        bt = r['business_type']
        tn = to_standard(r['traffic_name'] or '', '4s')
        ps = to_standard(r['park_store'] or '', 'yq')
        if tn:
            bt_f[bt].setdefault(tn, []).append(r)
        if ps:
            bt_g[bt].setdefault(ps, []).append(r)

    # 每条明细独立判定 F / G,累加进对应池(按 (bt, 名称) 聚合,每条明细只计一次)
    f_pool = defaultdict(float)   # (bt, 标准流量方名称) -> 应摊总额
    g_pool = defaultdict(float)   # (bt, 标准园区店名称) -> 应摊总额
    total_detail_amount = Decimal('0')   # 所有有效明细(本月且 amt!=0)的金额合计
    unmatched_amount = Decimal('0')      # 未匹配到任何 pool 的明细金额合计
    for d in detail_rows:
        if d.get('month') != month_label:
            continue
        amt = float(d['amount'] or 0)
        if amt == 0:
            continue   # 负数金额保留为负贡献,按园区店/流量方 GMV 占比作冲减扣减
        total_detail_amount += Decimal(str(amt))
        bt = normalize_bt(d['business_type'])
        fmap = bt_f.get(bt, {})
        gmap = bt_g.get(bt, {})
        # 候选名:门店名称 + 系统园区店名称,均作候选(去重);
        # 每个原始名分别归一为「流量方标准名(4s)」与「园区店标准名(yq)」,
        # 使别名数据归属到标准名下(保留标准名中的 D+ 前缀)。
        f_cands = []   # 用于匹配 traffic_name(F) 的归一化候选
        g_cands = []   # 用于匹配 park_store(G) 的归一化候选
        for raw in (d['store_name'], d['park_store_name']):
            n = str(raw or '').strip()
            if not n:
                continue
            s4 = to_standard(n, '4s')
            sy = to_standard(n, 'yq')
            if s4 and s4 not in f_cands:
                f_cands.append(s4)
            if sy and sy not in g_cands:
                g_cands.append(sy)
        # F 优先:任一 4s 候选名命中 traffic_name
        fkey = next((c for c in f_cands if c in fmap), None)
        if fkey:
            f_pool[(bt, fkey)] += amt                       # F 模式:按门店名称匹配
        else:
            gkey = next((c for c in g_cands if c in gmap), None)
            if gkey:
                g_pool[(bt, gkey)] += amt                   # G 模式(兜底):按系统园区店名称匹配
            else:
                unmatched_amount += Decimal(str(amt))       # 未匹配到任何 pool

    # 按 GMV 占比分摊各池
    #   - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
    #   - G 池(按系统园区店名称/park_store 匹配):用 gmv_ratio_park(同业务类型+同园区店)
    #     作为该行的摊分系数,更直接体现「同业务类型+同园区店」的 GMV 占比。
    result = {}

    def _alloc(pool, row_map, field='gmv'):
        for key, total in pool.items():
            if total == 0:
                continue   # 净额为 0 才跳过;净负池同样分配成负摊消(冲减)
            rows = row_map[key]
            # --- 服务商过滤:只保留 service_provider 含"嘀加"的行(嘀加自营/嘀加直营) ---
            dijia_rows = [r for r in rows if _is_dijia_row(r)]
            if not dijia_rows:
                # 全是非嘀加 → 不分摊(费用=0),跳过
                continue
            if len(dijia_rows) < len(rows):
                logger.info(f"[耗材分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
                            f" 服务商=嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
            rows = dijia_rows

            if field == 'mgv_ratio_park':
                ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None
                          for r in rows]
                if all(x is not None for x in ratios):
                    dist = distribute_by_weight(
                        total, [(r['id'], rp) for r, rp in zip(rows, ratios)])
                    for rid, amt in dist.items():
                        result[rid] = result.get(rid, 0) + amt
                    continue
                # 回退:按 GMV 占比(如 dry-run 尚未写库、或 0-GMV 组)
                gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
                if gmv_sum <= 0:
                    dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
                else:
                    dist = distribute_by_weight(
                        total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
                for rid, amt in dist.items():
                    result[rid] = result.get(rid, 0) + amt
                continue
            # 默认:按本行 GMV 占比摊分
            gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
            if gmv_sum <= 0:
                dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
            else:
                dist = distribute_by_weight(
                    total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
            for rid, amt in dist.items():
                result[rid] = result.get(rid, 0) + amt

    _alloc(f_pool, {(bt, n): bt_f[bt][n] for (bt, n) in f_pool}, field='gmv')
    _alloc(g_pool, {(bt, n): bt_g[bt][n] for (bt, n) in g_pool}, field='mgv_ratio_park')
    # 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
    reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
    # 记录未匹配金额到返回 dict 的特殊 key
    pools_total = Decimal(str(round(sum(f_pool.values()) + sum(g_pool.values()), 2)))
    residual = total_detail_amount - pools_total - unmatched_amount
    if abs(float(residual)) >= 0.005:
        logger.info(
            f"[耗材对账] 明细总额={float(total_detail_amount):.2f} "
            f"池合计={float(pools_total):.2f} 未匹配={float(unmatched_amount):.2f} "
            f"残差={float(residual):.2f}"
        )
    result['_unmatched'] = float(unmatched_amount)
    return result


def update_consumables(conn, amounts):
    """把计算好的门店资产耗材写回 biz_budget_achieve(按主键 id 更新)。

    Args:
        amounts: dict {biz_row_id: 金额}。空 dict 则不更新。
    Returns:
        int: 更新行数。
    """
    if not amounts:
        return 0
    sql = f'UPDATE {TARGET_TABLE} SET store_consumables = %s WHERE id = %s'
    params = [(amt, rid) for rid, amt in amounts.items()]
    try:
        with conn.cursor() as cur:
            cur.executemany(sql, params)
        conn.commit()
        return len(params)
    except Exception:
        conn.rollback()
        raise


UNMATCHED_FEE_TABLE = 'biz_unmatched_fee'
# 未匹配费用的 fee_type 取值
UNMATCHED_FEE_RENOVATION = 'renovation_amortization'   # 装修摊销
UNMATCHED_FEE_CONSUMABLES = 'store_consumables'        # 门店资产耗材


def write_unmatched_fee(conn, task_id, stat_month, renovation_unmatched, consumables_unmatched):
    """把未匹配到预算行的明细金额写入 biz_unmatched_fee 表(先删后插,幂等)。

    Args:
        conn: pymysql 连接。
        task_id: 任务主键。
        stat_month: 统计月 'YYYY-MM'。
        renovation_unmatched: 装修摊销未匹配金额(float)。
        consumables_unmatched: 门店资产耗材未匹配金额(float)。
    Returns:
        int: 插入行数。
    """
    # 先删后插,保证重跑幂等
    try:
        with conn.cursor() as cur:
            cur.execute(
                f'DELETE FROM {UNMATCHED_FEE_TABLE} WHERE task_id = %s AND stat_month = %s '
                f"AND fee_type IN ('{UNMATCHED_FEE_RENOVATION}', '{UNMATCHED_FEE_CONSUMABLES}')",
                (task_id, stat_month),
            )
        # 只有存在非零未匹配金额时才插入(全 0 不写)
        rows = []
        if abs(renovation_unmatched) > 0.005:
            rows.append((task_id, stat_month, UNMATCHED_FEE_RENOVATION, renovation_unmatched))
        if abs(consumables_unmatched) > 0.005:
            rows.append((task_id, stat_month, UNMATCHED_FEE_CONSUMABLES, consumables_unmatched))
        if rows:
            with conn.cursor() as cur:
                cur.executemany(
                    f'INSERT INTO {UNMATCHED_FEE_TABLE} '
                    f'(task_id, stat_month, fee_type, unmatched_amount) '
                    f'VALUES (%s, %s, %s, %s)',
                    rows,
                )
            conn.commit()
            logger.info(
                f"[未匹配写库] clean 侧: renovation_amortization={renovation_unmatched:.2f} "
                f"store_consumables={consumables_unmatched:.2f} → 插入 {len(rows)} 行"
            )
            return len(rows)
        # 全 0,只删除不插入
        conn.commit()
        logger.info(
            f"[未匹配写库] clean 侧: renovation_amortization={renovation_unmatched:.2f} "
            f"store_consumables={consumables_unmatched:.2f} → 全 0 不写入"
        )
        return 0
    except Exception:
        conn.rollback()
        raise


# ---------------- 文件下载 ----------------


def download_file(file_url, dest_dir):
    """下载 OSS 文件到本地临时目录,返回本地路径。"""
    name = os.path.basename(urlparse(file_url).path) or 'settlement.xlsx'
    local_path = os.path.join(dest_dir, name)
    with requests.get(file_url, stream=True, timeout=120) as resp:
        resp.raise_for_status()
        with open(local_path, 'wb') as f:
            for chunk in resp.iter_content(chunk_size=1024 * 256):
                if chunk:
                    f.write(chunk)
    size = os.path.getsize(local_path)
    log(f'  文件已下载:{name}({size / 1024 / 1024:.2f} MB)')
    return local_path


# ---------------- 主流程 ----------------


def process_task(conn, task, dry_run=False):
    """处理单个任务:下载附件 → 解析 → 写库。返回写入行数。"""
    task_id, stat_month = task['id'], task['month']
    log(f'处理任务 #{task_id}({task["data_table_type"]} / {stat_month})')
    # 预加载 流量方/园区店 标准名→别名 映射(供入库归一与装修/耗材匹配复用)
    load_alias_maps(conn)

    files = query_settlement_files(conn, task_id)
    if not files:
        log(f'  跳过:未找到未删除的「{FORM_TYPE_SETTLEMENT}」附件')
        return 0
    if len(files) > 1:
        log(f'  注意:存在 {len(files)} 个未删除的「{FORM_TYPE_SETTLEMENT}」附件,取最新一个(id={files[0]["id"]})')
    file_row = files[0]
    log(f'  附件 #{file_row["id"]}:{file_row["file_name"]}')

    # 上月数据(用于计算 cost_gmv_ratio_previous),写库阶段才查库
    prev_month = prev_month_str(stat_month)
    prev_metrics = query_previous_month_metrics(conn, prev_month) if not dry_run else {}
    if not dry_run:
        log(f'  上月统计月 {prev_month}:命中维度组 {len(prev_metrics)} 个'
            f'(缺失则该组上月占比写 NULL)')

    if not dry_run:
        update_clean_status(conn, file_row['id'], CLEAN_RUNNING)

    try:
        with tempfile.TemporaryDirectory(prefix='budget_') as tmp:
            local_path = download_file(file_row['file_url'], tmp)
            parser = SettlementSummaryParser(local_path)
            records = parser.parse()
            # 最终合并使用标准名:流量方→merchant_4s 标准名,园区店→merchant_yq 标准名
            rows = parser.generate_budget_metrics(
                prev_metrics=prev_metrics,
                traffic_std=lambda x: to_standard(x, '4s'),
                park_std=lambda x: to_standard(x, 'yq'),
            )
            log(f'  解析明细 {len(records)} 行 → 分组后 {len(rows)} 行'
                f'(多品类 {sum(1 for r in rows if r["is_multi_category"] == "是")} 行)')

        if dry_run:
            log('  dry-run:不写库,样例前 3 行:')
            for r in rows[:3]:
                log(f'    {r}')
            # dry-run 也演示装修摊销预览(依赖库内已有的结果行)
            _preview_renovation(conn, task_id, stat_month, dry_run=True)
            # 2026-10 精简:门店资产耗材已移除,跳过预览
            # _preview_consumables(conn, task_id, stat_month)
            return len(rows)

        deleted, inserted = save_budget_rows(conn, task_id, stat_month, rows)
        log(f'  写入 {TARGET_TABLE}:清理旧数据 {deleted} 行,新增 {inserted} 行'
            f'(本月成本占比非空 {sum(1 for r in rows if r["cost_gmv_ratio_current"] is not None)} 行'
            f',本月流量费占比非空 {sum(1 for r in rows if r["traffic_fee_gmv_ratio_current"] is not None)} 行'
            f',本月服务费占比非空 {sum(1 for r in rows if r["service_fee_ratio_current"] is not None)} 行)')
        update_clean_status(conn, file_row['id'], CLEAN_DONE)

        # 第二步:装修摊销(来自「装修费用表」附件,仅 1.1 业务)
        ren_updated, ren_unmatched = process_renovation(conn, task_id, stat_month, dry_run=False)
        # 第三步:门店资产耗材 —— 2026-10 精简:门店资产耗材明细表已移除,跳过此步骤
        log(f'  [门店资产耗材] 已移除(2026-10 精简),跳过 process_consumables')
        cons_updated, cons_unmatched = 0, 0.0
        # 第四步:未匹配金额写库(biz_unmatched_fee,先删后插幂等)
        # 2026-10 精简:cons_unmatched 固定为 0(门店耗材不再处理)
        unmatched_rows = write_unmatched_fee(conn, task_id, stat_month, ren_unmatched, cons_unmatched)
        if unmatched_rows:
            log(f'  写入 {UNMATCHED_FEE_TABLE}:新增 {unmatched_rows} 行未匹配费用记录')
        return inserted + ren_updated
    except Exception:
        if not dry_run:
            update_clean_status(conn, file_row['id'], CLEAN_PENDING)   # 失败回退为待清洗
        raise


def _preview_renovation(conn, task_id, stat_month, dry_run=False):
    """演示装修摊销计算(dry-run 用),不写库。"""
    ren_files = query_renovation_file(conn, task_id)
    if not ren_files:
        log('  [装修摊销预览] 未找到「装修费用表」附件,跳过')
        return 0
    with tempfile.TemporaryDirectory(prefix='renov_') as tmp:
        local = download_file(ren_files[0]['file_url'], tmp)
        details = RenovationDetailParser(local).parse()
    biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE)
    amounts = compute_renovation_amounts(details, biz_rows, stat_month)
    unmatched = amounts.pop('_unmatched', 0)
    log(f'  [装修摊销预览] 明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
        f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}'
        f' / 未匹配 {unmatched:.2f}')
    for rid, amt in list(amounts.items())[:5]:
        br = next((b for b in biz_rows if b['id'] == rid), None)
        log(f'    行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}')


def process_renovation(conn, task_id, stat_month, dry_run=False):
    """处理装修摊销:下载装修费用表 → 匹配 1.1 结果行 → GMV 占比分摊 → 写回。

    Returns:
        tuple: (更新行数, 未匹配金额float)。无附件/无结果行时返回 (0, 0.0)。
    """
    ren_files = query_renovation_file(conn, task_id)
    if not ren_files:
        log(f'  跳过装修摊销:未找到未删除的「{FORM_TYPE_RENOVATION}」附件')
        return (0, 0.0)
    if len(ren_files) > 1:
        log(f'  注意:存在 {len(ren_files)} 个未删除的「{FORM_TYPE_RENOVATION}」附件,取最新一个(id={ren_files[0]["id"]})')
    ren_file = ren_files[0]
    log(f'  装修摊销附件 #{ren_file["id"]}:{ren_file["file_name"]}')

    with tempfile.TemporaryDirectory(prefix='renov_') as tmp:
        local = download_file(ren_file['file_url'], tmp)
        details = RenovationDetailParser(local).parse()

    biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE)
    if not biz_rows:
        log('  无 1.1 业务结果行,装修摊销跳过')
        return (0, 0.0)
    amounts = compute_renovation_amounts(details, biz_rows, stat_month)
    unmatched = amounts.pop('_unmatched', 0)
    log(f'  装修摊销:明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
        f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}'
        f' / 未匹配 {unmatched:.2f}')

    if dry_run:
        return (len(amounts), unmatched)
    # 先清:把该任务所有行 renovation_amortization 置 0,确保未匹配行默认为 0
    # (update_renovation 只写匹配命中的行,其他行需要明确的 0 而非 NULL)
    try:
        with conn.cursor() as cur:
            cur.execute(
                f"UPDATE {TARGET_TABLE} SET renovation_amortization = 0 "
                "WHERE task_id = %s AND stat_month = %s",
                (task_id, stat_month),
            )
        conn.commit()
        log(f'  先清 renovation_amortization:影响 {cur.rowcount} 行')
    except Exception:
        conn.rollback()
        raise
    updated = update_renovation(conn, amounts)
    log(f'  写入 renovation_amortization:更新 {updated} 行(未匹配行已默认为 0)')
    return (updated, unmatched)


def _preview_consumables(conn, task_id, stat_month):
    """演示门店资产耗材计算(dry-run 用),不写库。"""
    cons_files = query_consumables_file(conn, task_id)
    if not cons_files:
        log('  [门店资产耗材预览] 未找到「门店资产耗材明细表」附件,跳过')
        return 0
    with tempfile.TemporaryDirectory(prefix='cons_') as tmp:
        local = download_file(cons_files[0]['file_url'], tmp)
        details = ConsumablesDetailParser(local).parse()
    biz_rows = query_all_biz_rows(conn, task_id, stat_month)
    amounts = compute_consumables_amounts(details, biz_rows, stat_month)
    unmatched = amounts.pop('_unmatched', 0)
    cur_m = int(stat_month.split('-')[1])
    m_label = f'{cur_m}月'
    m_cnt = sum(1 for d in details if d.get('month') == m_label)
    log(f'  [门店资产耗材预览] 明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
        f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行'
        f' / 金额总额 {sum(amounts.values()):.2f} / 未匹配 {unmatched:.2f}')
    for rid, amt in list(amounts.items())[:5]:
        br = next((b for b in biz_rows if b['id'] == rid), None)
        log(f'    行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}')


def process_consumables(conn, task_id, stat_month, dry_run=False):
    """处理门店资产耗材:下载明细表 → 按业务类型匹配预算行 → GMV 占比分摊 → 写回。

    Returns:
        tuple: (更新行数, 未匹配金额float)。无附件/无结果行时返回 (0, 0.0)。
    """
    cons_files = query_consumables_file(conn, task_id)
    if not cons_files:
        log(f'  跳过门店资产耗材:未找到未删除的「{FORM_TYPE_CONSUMABLES}」附件')
        return (0, 0.0)
    if len(cons_files) > 1:
        log(f'  注意:存在 {len(cons_files)} 个未删除的「{FORM_TYPE_CONSUMABLES}」附件,取最新一个(id={cons_files[0]["id"]})')
    cons_file = cons_files[0]
    log(f'  门店资产耗材附件 #{cons_file["id"]}:{cons_file["file_name"]}')

    with tempfile.TemporaryDirectory(prefix='cons_') as tmp:
        local = download_file(cons_file['file_url'], tmp)
        details = ConsumablesDetailParser(local).parse()

    biz_rows = query_all_biz_rows(conn, task_id, stat_month)
    if not biz_rows:
        log('  无预算达成结果行,门店资产耗材跳过')
        return (0, 0.0)
    amounts = compute_consumables_amounts(details, biz_rows, stat_month)
    unmatched = amounts.pop('_unmatched', 0)
    cur_m = int(stat_month.split('-')[1])
    m_label = f'{cur_m}月'
    m_cnt = sum(1 for d in details if d.get('month') == m_label)
    log(f'  门店资产耗材:明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
        f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行'
        f' / 金额总额 {sum(amounts.values()):.2f} / 未匹配 {unmatched:.2f}')

    if dry_run:
        return (len(amounts), unmatched)
    updated = update_consumables(conn, amounts)
    log(f'  写入 store_consumables:更新 {updated} 行(未匹配行保持 NULL)')
    return (updated, unmatched)


def main():
    ap = argparse.ArgumentParser(description='预算达成数据清洗:结算数据汇总表 → biz_budget_achieve')
    ap.add_argument('-t', '--data-table-type', required=True,
                    help='数据表类型编码,对应 data_process_task.data_table_type,如 budget_achievement')
    ap.add_argument('-m', '--month', required=True,
                    help='所属月份,对应 data_process_task.month,格式 YYYY-MM,如 2026-06')
    ap.add_argument('--dry-run', action='store_true', help='只解析不写库,用于校验数据')
    ap.add_argument('--force', action='store_true',
                    help='忽略 status=PROCESSING 过滤(用于手动回填/重跑,不改库内任务状态)')
    args = ap.parse_args()

    if not MONTH_PATTERN.match(args.month):
        log(f'月份格式错误:{args.month},应为 YYYY-MM')
        return 2

    log(f'开始清洗:data_table_type={args.data_table_type},month={args.month}'
        f'{"(dry-run)" if args.dry_run else ""}{"(--force)" if args.force else ""}')
    log(f'数据库:{Config.MYSQL_USER}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}')

    conn = get_conn()
    total, failed = 0, 0
    try:
        tasks = query_tasks(conn, args.data_table_type, args.month, ignore_status=args.force)
        if not tasks:
            log(f'没有符合条件的任务(状态={TASK_STATUS_PROCESSING}、未删除),流程结束')
            return 0
        log(f'命中任务 {len(tasks)} 个:{[t["id"] for t in tasks]}')
        for task in tasks:
            try:
                total += process_task(conn, task, dry_run=args.dry_run)
            except Exception as e:
                failed += 1
                log(f'  任务 #{task["id"]} 处理失败:{e}')
                traceback.print_exc()
    finally:
        conn.close()

    log(f'清洗结束:累计 {total} 行,失败任务 {failed} 个')
    return 1 if failed else 0


if __name__ == '__main__':
    sys.exit(main())