clean_budget_achievement.py 27.9 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
# -*- 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 业务)、
    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 os
import re
import sys
import tempfile
import traceback
from datetime import datetime
from urllib.parse import urlparse

import pymysql
import requests

from config import Config
from parsers import SettlementSummaryParser, RenovationDetailParser

# 数据源表单类型:结算数据汇总表 / 装修费用表
FORM_TYPE_SETTLEMENT = '结算数据汇总表'
FORM_TYPE_RENOVATION = '装修费用表'
# 装修摊销:摊销总月数(合同金额 / 摊销总月数)
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])$')


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
    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}
    """
    sql = (
        'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park '
        '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 占比分摊。
      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)
    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(r['traffic_name'] or '')
        ps = strip_if_dplus(r['park_store'] or '')
        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) → 应摊总额
    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
        fn = strip_if_dplus(d['store_name'])
        gn = strip_if_dplus(d['park_store_name'])
        if fn and fn in f_rows:
            f_pool[fn] += amt                       # F 模式:按门店名称匹配
        elif gn and gn in g_rows:
            g_pool[gn] += amt                       # G 模式(兜底):按系统园区店名称匹配

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

    def _allocate(pool, row_map, field='gmv'):
        for key, total in pool.items():
            if total <= 0:
                continue
            rows = row_map[key]
            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):
                    for r, rp in zip(rows, ratios):
                        if rp > 0:
                            result[r['id']] = result.get(r['id'], 0) + round(total * rp, 2)
                    continue
                # 回退:按 GMV 占比
                gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
                if gmv_sum <= 0:
                    share = round(total / len(rows), 2)
                    for r in rows:
                        result[r['id']] = result.get(r['id'], 0) + share
                else:
                    for r in rows:
                        result[r['id']] = result.get(r['id'], 0) + round(
                            total * float(r['gmv'] or 0) / gmv_sum, 2)
                continue
            # 默认:按本行 GMV 占比摊分
            gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
            if gmv_sum <= 0:
                share = round(total / len(rows), 2)
                for r in rows:
                    result[r['id']] = result.get(r['id'], 0) + share
            else:
                for r in rows:
                    result[r['id']] = result.get(r['id'], 0) + round(
                        total * float(r['gmv'] or 0) / gmv_sum, 2)

    _allocate(f_pool, f_rows, field='gmv')
    _allocate(g_pool, g_rows, field='mgv_ratio_park')
    return result


def strip_if_dplus(name):
    """去 'D+' 前缀的归一化(避免重复 import)。"""
    if name and name.startswith('D+'):
        return name[2:]
    return name or ''


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 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})')

    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()
            rows = parser.generate_budget_metrics(prev_metrics=prev_metrics)
            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 也演示装修摊销预览(依赖库内已有的 1.1 行)
            _preview_renovation(conn, task_id, stat_month, dry_run=True)
            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 = process_renovation(conn, task_id, stat_month, dry_run=False)
        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)
    log(f'  [装修摊销预览] 明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
        f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.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 占比分摊 → 写回。"""
    ren_files = query_renovation_file(conn, task_id)
    if not ren_files:
        log(f'  跳过装修摊销:未找到未删除的「{FORM_TYPE_RENOVATION}」附件')
        return 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
    amounts = compute_renovation_amounts(details, biz_rows, stat_month)
    log(f'  装修摊销:明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
        f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}')

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


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())