report_utils.py 37 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
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 共用工具模块
================================
被 warranty_processor / equity_processor / inshop_processor / park_processor 共同引用。
统一封装 Excel 下载解析、安全除法、指标系统调用、幂等检查、临时目录清理等。
"""
import os
import logging
import tempfile
import shutil
import time as _time
from decimal import Decimal, ROUND_HALF_UP

import pandas as pd

from models import (
    DataProcessTask, DataProcessFile, BizBudgetAchieve,
    ReportExtendedWarranty, ReportEquityService,
    ReportLightReformInshop, ReportLightReformPark,
    db,
)
from oss_utils import download_file
from indicator_client import IndicatorClient
from config import Config

logger = logging.getLogger('report_utils')


# ============================================================
# 调度器常量
# ============================================================
STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings'

# biz_type 过滤值(各表不同)
BIZ_TYPE_WARRANTY = '2.3'   # 延保
BIZ_TYPE_EQUITY = '2.1'     # 权益

# 指标系统 biz 编码
INDICATOR_BIZ_MAP = {
    'warranty': Config.INDICATOR_BIZ_WARRANTY,        # 1
    'equity': Config.INDICATOR_BIZ_EQUITY,            # 3
    'light_reform': Config.INDICATOR_BIZ_LIGHT_REFORM,  # 2
}


# ============================================================
# 任务状态管理
# ============================================================

def mark_task_failed(task_id, error_msg):
    """标记任务为失败状态(独立函数,无类依赖)。"""
    try:
        task = DataProcessTask.query.filter_by(id=task_id).first()
        if task:
            task.status = 'FAILED'
            task.error_msg = (error_msg or '')[:500]
            db.session.commit()
            logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
    except Exception as e:
        logger.error(f"[标记失败] 更新失败: {e}")
        db.session.rollback()
        raise


def cleanup_tmp_dir(tmp_dir):
    """清理临时目录(Windows 文件占用重试 3 次)。"""
    try:
        if os.path.exists(tmp_dir):
            shutil.rmtree(tmp_dir, ignore_errors=True)
            for _ in range(3):
                if not os.path.exists(tmp_dir):
                    break
                _time.sleep(0.5)
                shutil.rmtree(tmp_dir, ignore_errors=True)
            if not os.path.exists(tmp_dir):
                logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
            else:
                logger.warning(f"[清理] 临时目录仍被占用,跳过: {tmp_dir}")
    except Exception as e:
        logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")


# ============================================================
# 子任务管理(DataProcessSubtask)
# ============================================================

# 4 张输出表的类别常量
ALL_OUTPUT_CATEGORIES = ['warranty', 'equity', 'inshop', 'park']

# 子任务状态常量
SUBTASK_PENDING = 'PENDING'
SUBTASK_PROCESSING = 'PROCESSING'
SUBTASK_COMPLETED = 'COMPLETED'
SUBTASK_FAILED = 'FAILED'


def create_subtasks_for_task(task_id, output_categories=None):
    """
    为一条主任务创建 4 条子任务记录(状态 PENDING)。
    已存在的 category 会跳过(幂等)。
    """
    from models import DataProcessSubtask
    if output_categories is None:
        output_categories = ALL_OUTPUT_CATEGORIES

    created = 0
    for cat in output_categories:
        existing = DataProcessSubtask.query.filter_by(
            task_id=task_id, output_category=cat, is_deleted=0).first()
        if existing:
            continue
        sub = DataProcessSubtask(
            task_id=task_id,
            output_category=cat,
            status=SUBTASK_PENDING,
        )
        db.session.add(sub)
        created += 1
    if created:
        db.session.commit()
        logger.info(f"[子任务] task_id={task_id} 新建 {created} 条子任务")
    return created


def get_subtask(task_id, output_category):
    """查子任务,返回 DataProcessSubtask 对象或 None"""
    from models import DataProcessSubtask
    return DataProcessSubtask.query.filter_by(
        task_id=task_id, output_category=output_category, is_deleted=0).first()


def get_subtask_status(task_id, output_category):
    """查子任务状态,返回字符串或 None(不存在)"""
    sub = get_subtask(task_id, output_category)
    return sub.status if sub else None


def update_subtask(task_id, output_category, status, error_msg='', row_count=None):
    """更新子任务状态/错误信息/写入行数"""
    from models import DataProcessSubtask
    sub = DataProcessSubtask.query.filter_by(
        task_id=task_id, output_category=output_category, is_deleted=0).first()
    if not sub:
        # 不存在则创建一条
        sub = DataProcessSubtask(task_id=task_id, output_category=output_category, status=status)
        db.session.add(sub)
    sub.status = status
    if error_msg:
        sub.error_msg = error_msg[:500]
    if row_count is not None:
        sub.row_count = row_count
    db.session.flush()
    logger.info(f"[子任务] task_id={task_id} category={output_category} → {status}"
                + (f" ({row_count} 行)" if row_count is not None else ''))


def is_subtask_completed(task_id, output_category):
    """判断该类别子任务是否已 COMPLETED(调度器跳过用)"""
    return get_subtask_status(task_id, output_category) == SUBTASK_COMPLETED


def check_all_subtasks_done(task_id):
    """
    判断 4 条 output_category 是否都到达终态(COMPLETED 或 FAILED)。
    用于调度器最后把主任务置为 COMPLETED。
    返回 (all_done: bool, completed_count: int, failed_count: int, pending_count: int)
    """
    from models import DataProcessSubtask
    subs = DataProcessSubtask.query.filter_by(task_id=task_id, is_deleted=0).all()
    if not subs:
        return False, 0, 0, len(ALL_OUTPUT_CATEGORIES)

    completed = sum(1 for s in subs if s.status == SUBTASK_COMPLETED)
    failed = sum(1 for s in subs if s.status == SUBTASK_FAILED)
    processing = sum(1 for s in subs if s.status == SUBTASK_PROCESSING)
    pending = sum(1 for s in subs if s.status == SUBTASK_PENDING)
    all_done = (completed + failed) == len(ALL_OUTPUT_CATEGORIES) and processing == 0
    return all_done, completed, failed, pending


# 主任务状态规则:
#   - 有子任务 FAILED → 主任务置为 FAILED(自动推)
#   - 全部 COMPLETED → 主任务保持 PROCESSING(等总表逻辑来推)
# 总表逻辑后续统一接入 finalize_all_subtasks_done() 时再启用

def promote_subtask_failure_to_main_task(task_id):
    """
    子任务处理失败时调用:
      查该 task_id 下是否有 FAILED 的子任务 → 有则把主任务置为 FAILED。
      error_msg 汇总所有 FAILED 子任务的错误。
    """
    from models import DataProcessTask, DataProcessSubtask
    subs = DataProcessSubtask.query.filter_by(task_id=task_id, is_deleted=0).all()
    if not subs:
        return

    failed = [s for s in subs if s.status == SUBTASK_FAILED]
    if not failed:
        return

    task = DataProcessTask.query.filter_by(id=task_id).first()
    if task and task.status == 'PROCESSING':
        err_parts = [f"{s.output_category}: {s.error_msg or 'unknown'}" for s in failed]
        task.status = 'FAILED'
        task.error_msg = f"子任务失败 {len(failed)}/{len(subs)}: " + '; '.join(err_parts)[:500]
        db.session.commit()
        logger.info(f"[主任务] task_id={task_id} → FAILED (失败 {len(failed)} 条子任务)")


# 保留旧函数名做兼容,内部改为查子任务表
def is_output_already_done(task_id, output_category):
    """幂等检查(兼容旧调用):判断子任务是否已 COMPLETED"""
    return is_subtask_completed(task_id, output_category)


# ============================================================
# Excel 下载 & 解析
# ============================================================

def download_all_files(task_id, tmp_dir):
    """
    下载 task_id 关联的所有 Excel 文件到 tmp_dir。
    返回 {form_type: local_path} (下载失败则值为 None)。
    """
    files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
    result = {}
    for f in files:
        if not f.file_url:
            logger.warning(f"[文件下载] form_type={f.form_type} 无 file_url,跳过")
            continue
        local_path = os.path.join(tmp_dir, f.file_name or f"{f.form_type}.xlsx")
        try:
            download_file(f.file_url, local_path)
            result[f.form_type] = local_path
            logger.info(f"[文件下载] {f.form_type} OK → {local_path}")
        except Exception as e:
            logger.error(f"[文件下载] {f.form_type} 失败: {e}")
            result[f.form_type] = None
    return result


def match_columns(columns, keywords_map):
    """
    模糊匹配列名。
    keywords_map = {标准名: [关键词列表]},返回 {标准名: 实际列名}。
    """
    result = {}
    for std, keywords in keywords_map.items():
        for col in columns:
            col_lower = str(col).lower()
            for kw in keywords:
                if kw.lower() in col_lower:
                    result[std] = col
                    break
            if std in result:
                break
    return result


def find_header_row(df, max_scan=5):
    """
    在 DataFrame 前 max_scan 行中找到包含'门店'的表头行索引。
    找不到返回 0。
    """
    for i in range(min(max_scan, len(df))):
        row_vals = [str(v) if v is not None else '' for v in df.iloc[i].tolist()]
        if any('门店' in v for v in row_vals):
            return i
    return 0


def parse_saas_base(file_path, biz_type_filter):
    """
    解析 SAAS门店预算分解表 sheet1,按 biz_type_filter 过滤。
    返回 list[dict]:store_name / brand / province / city / region_manager /
    training_supervisor / biz_manager / resident_type
    """
    logger.info(f"[SAAS预算分解] 解析 {file_path}, 过滤 biz_type={biz_type_filter}")
    df_raw = pd.read_excel(file_path, sheet_name=0, header=None)
    header_row = find_header_row(df_raw)
    df = pd.read_excel(file_path, sheet_name=0, header=header_row)
    df.columns = [str(c).strip() if c else '' for c in df.columns]

    col_map = match_columns(df.columns, {
        'biz_type': ['业务类型', '业务分类', 'biz_type'],
        'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
        'brand': ['品牌', 'brand'],
        'province': ['省份', '省', 'province'],
        'city': ['城市', '市', 'city'],
        'region_manager': ['区域运营', '区域经理', '大区经理'],
        'training_supervisor': ['培训督导', '督导'],
        'biz_manager': ['业务经理'],
        'resident_type': ['驻店类型', '驻店'],
    })
    logger.info(f"[SAAS预算分解] 匹配列: {col_map}")

    biz_col = col_map.get('biz_type')
    store_col = col_map.get('store_name')
    if not store_col:
        logger.error("[SAAS预算分解] 未找到门店名列")
        return []

    result = []
    for _, row in df.iterrows():
        if biz_col:
            bt = str(row.get(biz_col, '')).strip()
            if bt != biz_type_filter:
                continue
        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue

        result.append({
            'store_name': sn,
            'brand': str(row.get(col_map.get('brand', ''), '')).strip() if col_map.get('brand') else '',
            'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
            'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
            'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
            'training_supervisor': str(row.get(col_map.get('training_supervisor', ''), '')).strip() if col_map.get('training_supervisor') else '',
            'biz_manager': str(row.get(col_map.get('biz_manager', ''), '')).strip() if col_map.get('biz_manager') else '',
            'resident_type': str(row.get(col_map.get('resident_type', ''), '')).strip() if col_map.get('resident_type') else '',
        })
    logger.info(f"[SAAS预算分解] biz_type={biz_type_filter} 共 {len(result)} 条")
    return result


def parse_region_map(file_path):
    """
    解析关系表,按 (业务类型, 省份) → 片区。
    返回 dict[(biz_type, province)] = region_area (额外包含 ('', province) fallback)。
    """
    logger.info(f"[关系表] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning("[关系表] 读取失败,跳过")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'biz_type': ['业务类型', '业务分类'],
        'province': ['省份', '省'],
        'region_area': ['片区', '大区'],
    })
    if 'region_area' not in col_map or 'province' not in col_map:
        logger.warning("[关系表] 缺少 片区/省份 关键列")
        return {}

    result = {}
    for _, row in df.iterrows():
        prov = str(row.get(col_map['province'], '')).strip()
        area = str(row.get(col_map['region_area'], '')).strip()
        if not prov or not area:
            continue
        bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
        result[(bt, prov)] = area
        result[('', prov)] = area

    logger.info(f"[关系表] 片区映射 {len(result)} 条")
    return result


def parse_delivery_table(file_path):
    """
    解析主机厂交车数据表(鸿蒙/广联共用结构)。
    返回 dict[store_name] = delivery_cnt (int)。
    """
    logger.info(f"[主机厂交车] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[主机厂交车] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '厅店名称', '基础信息-门店'],
        'delivery': ['总交付', '交车数', '交付量', '主机厂数据'],
    })
    if 'store_name' not in col_map:
        logger.warning("[主机厂交车] 未找到门店名列")
        return {}

    store_col = col_map['store_name']
    delivery_col = col_map.get('delivery')

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        cnt = 0
        if delivery_col:
            try:
                v = row.get(delivery_col, 0)
                if v is not None and not pd.isna(v):
                    cnt = int(float(v))
            except (ValueError, TypeError):
                cnt = 0
        result[sn] = result.get(sn, 0) + cnt

    logger.info(f"[主机厂交车] {file_path} → {len(result)} 个门店")
    return result


# ============================================================
# 指标系统 API
# ============================================================

def fetch_indicator_data(start_str, end_str, biz_code, item_codes):
    """
    调指标系统 API,返回 {merchantName: {itemCode: itemValue}}。
    start_str / end_str: 'YYYY-MM-DD' 字符串,空则返回 {}。
    """
    if not start_str or not end_str or not item_codes:
        return {}
    client = IndicatorClient()
    return client.fetch(start_str, end_str, biz_code, item_codes)


# ============================================================
# 安全除法 / 百分比
# ============================================================

def safe_div(numerator, denominator, scale=2):
    """Decimal 安全除法,分母为 0 返回 Decimal('0')。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) / Decimal(str(denominator))).quantize(
            Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def safe_div_pct(numerator, denominator):
    """整数/整数 → 百分比(*100),保留百分比后 2 位小数 → Decimal(10,6)。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
            Decimal('0.010000'), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def safe_div_pct_decimal(numerator, denominator):
    """Decimal/Decimal → 百分比(*100)。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
            Decimal('0.010000'), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def prev_month(month_str):
    """'2026-09' → '2026-08'"""
    if not month_str or '-' not in month_str:
        return ''
    try:
        parts = month_str.split('-')
        y = int(parts[0])
        m = int(parts[1])
        if m == 1:
            y -= 1
            m = 12
        else:
            m -= 1
        return f"{y}-{m:02d}"
    except Exception:
        return ''


def fetch_prev_month_labor_ratio(task, base_records):
    """
    从上月 BizBudgetAchieve 表取人员工资占比 → 营销费用占比。
    store_name 模糊匹配 target_name。
    返回 dict[store_name] = Decimal
    """
    current_month = getattr(task, 'month', '')
    pm = prev_month(current_month)
    if not pm:
        return {}

    store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
    if not store_names:
        return {}

    results = {}
    try:
        rows = BizBudgetAchieve.query.filter(
            BizBudgetAchieve.month == pm,
            BizBudgetAchieve.is_deleted == 0,
        ).all()
        for row in rows:
            target = getattr(row, 'target_name', '') or ''
            ratio = getattr(row, 'personnel_salary_ratio_current', None)
            if ratio is None:
                continue
            for sn in store_names:
                if sn in target or target in sn:
                    results[sn] = Decimal(str(ratio))
                    break
        logger.info(f"[上月占比] month={pm} 匹配 {len(results)}/{len(store_names)}")
    except Exception as e:
        logger.warning(f"[上月占比] 查询失败: {e}")

    return results


# ============================================================
# 轻改店中店 - 专属解析函数
# ============================================================

# 轻改品牌关键字(sheet2 过滤用)
LIGHT_REFORM_BRAND_KEYWORDS = ['鸿蒙', 'AITO', '问界', '智界', '享界', '尚界', '尊界']

# 经营属性映射(驻店类型 → 直营/服务商)
RESIDENT_TYPE_MAP = {
    '直营': '直营',
    '服务商': '服务商',
}


def parse_saas_base_sheet2(file_path):
    """
    解析 SAAS门店预算分解表 sheet2,按品牌关键字过滤。
    返回 list[dict]:基础门店维度(园区/品牌/业务线/经营属性等)。
    """
    logger.info(f"[SAAS预算分解-sheet2] 解析 {file_path}")
    df_raw = pd.read_excel(file_path, sheet_name=1, header=None)
    header_row = find_header_row(df_raw)
    df = pd.read_excel(file_path, sheet_name=1, header=header_row)
    df.columns = [str(c).strip() if c else '' for c in df.columns]

    col_map = match_columns(df.columns, {
        'park_name': ['园区名称', '园区'],
        'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
        'brand': ['品牌', 'brand'],
        'province': ['省份', '省'],
        'city': ['城市', '市'],
        'park_type': ['园区类型'],
        'biz_line': ['业务线'],
        'operate_type': ['驻店类型', '经营属性', '驻店'],
        'region_manager': ['区域经理', '区域运营'],
        'avg_price_target': ['预估平均客单价', '平客目标值', '预估平均客单价'],
    })
    logger.info(f"[SAAS预算分解-sheet2] 匹配列: {col_map}")

    if 'store_name' not in col_map:
        logger.error("[SAAS预算分解-sheet2] 未找到门店名列")
        return []

    brand_col = col_map.get('brand')
    store_col = col_map['store_name']
    park_col = col_map.get('park_name')

    result = []
    for _, row in df.iterrows():
        # 品牌关键字过滤
        brand_val = str(row.get(brand_col, '')).strip() if brand_col else ''
        brand_text = (brand_val + ' ' + str(row.get(store_col, ''))).strip()
        if brand_val and not any(kw in brand_text for kw in LIGHT_REFORM_BRAND_KEYWORDS):
            continue

        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue

        result.append({
            'park_name': str(row.get(col_map.get('park_name', ''), '')).strip() if col_map.get('park_name') else '',
            'store_name': sn,
            'brand': brand_val,
            'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
            'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
            'park_type': str(row.get(col_map.get('park_type', ''), '')).strip() if col_map.get('park_type') else '',
            'biz_line': str(row.get(col_map.get('biz_line', ''), '')).strip() if col_map.get('biz_line') else '1.12',
            'operate_type': str(row.get(col_map.get('operate_type', ''), '')).strip() if col_map.get('operate_type') else '',
            'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
            'avg_price_target': _to_decimal(row.get(col_map.get('avg_price_target', ''), '')) if col_map.get('avg_price_target') else Decimal('0'),
        })
    logger.info(f"[SAAS预算分解-sheet2] 品牌过滤后共 {len(result)} 条")
    return result


def parse_saas_base_sheet2_exclude(file_path):
    """
    解析 SAAS门店预算分解表 sheet2,按品牌关键字**反过滤**(不包含关键字的保留)。
    用于轻改园区店。
    返回 list[dict]:同 parse_saas_base_sheet2,额外带 est_delivery_cnt / est_output_value / est_output_value_original
    """
    logger.info(f"[SAAS预算分解-sheet2-exclude] 解析 {file_path}")
    df_raw = pd.read_excel(file_path, sheet_name=1, header=None)
    header_row = find_header_row(df_raw)
    df = pd.read_excel(file_path, sheet_name=1, header=header_row)
    df.columns = [str(c).strip() if c else '' for c in df.columns]

    col_map = match_columns(df.columns, {
        'park_name': ['园区名称', '园区'],
        'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
        'brand': ['品牌', 'brand'],
        'province': ['省份', '省'],
        'city': ['城市', '市'],
        'park_type': ['园区类型'],
        'operate_type': ['驻店类型', '经营属性', '驻店'],
        'region_manager': ['区域经理', '区域运营'],
        'avg_price_target': ['预估平均客单价', '平客目标值'],
        'est_delivery_cnt': ['预估交车数'],
        'est_output_value': ['预估产值纠偏', '预估产值(纠偏)', '预估总产值'],
    })

    if 'store_name' not in col_map:
        logger.error("[SAAS预算分解-sheet2-exclude] 未找到门店名列")
        return []

    brand_col = col_map.get('brand')
    store_col = col_map['store_name']

    result = []
    for _, row in df.iterrows():
        brand_val = str(row.get(brand_col, '')).strip() if brand_col else ''
        brand_text = (brand_val + ' ' + str(row.get(store_col, ''))).strip()
        # 反过滤:包含关键字 → 跳过
        if brand_val and any(kw in brand_text for kw in LIGHT_REFORM_BRAND_KEYWORDS):
            continue

        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue

        result.append({
            'park_name': str(row.get(col_map.get('park_name', ''), '')).strip() if col_map.get('park_name') else '',
            'store_name': sn,
            'brand': brand_val,
            'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
            'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
            'park_type': str(row.get(col_map.get('park_type', ''), '')).strip() if col_map.get('park_type') else '园区店',
            'operate_type': str(row.get(col_map.get('operate_type', ''), '')).strip() if col_map.get('operate_type') else '',
            'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
            'avg_price_target': _to_decimal(row.get(col_map.get('avg_price_target', ''), '')) if col_map.get('avg_price_target') else Decimal('0'),
            'est_delivery_cnt': _to_int(row.get(col_map.get('est_delivery_cnt', ''), 0)) if col_map.get('est_delivery_cnt') else 0,
            'est_output_value': _to_decimal(row.get(col_map.get('est_output_value', ''), '')) if col_map.get('est_output_value') else Decimal('0'),
        })
    logger.info(f"[SAAS预算分解-sheet2-exclude] 反过滤后共 {len(result)} 条")
    return result


def _to_decimal(val):
    """安全转 Decimal"""
    if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'):
        return Decimal('0')
    try:
        return Decimal(str(val))
    except Exception:
        return Decimal('0')


def parse_inshop_delivery_touch(file_path):
    """
    解析店中店交车触客表(区域运营填写)。
    返回 dict[store_name] = {sales_order_cnt, sales_touch_cnt, delivery_cnt, delivery_touch_cnt,
                           aftersales_baohui_cnt, aftersales_shigu_cnt, aftersales_touch_cnt, purchase_indicator}
    """
    logger.info(f"[店中店交车触客表] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[店中店交车触客表] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '门店名'],
        'sales_order_cnt': ['销售大定数', '销售大定'],
        'sales_touch_cnt': ['销售触客数', '销售触客'],
        'delivery_cnt': ['交车数', '交车'],
        'delivery_touch_cnt': ['交付触客数', '交付触客'],
        'aftersales_baohui_cnt': ['售后首保回厂', '首保回厂'],
        'aftersales_shigu_cnt': ['售后事故回厂', '事故回厂'],
        'aftersales_touch_cnt': ['售后触客数', '售后触客'],
        'purchase_indicator': ['采买', '兜底指标', '采买兜底'],
    })

    if 'store_name' not in col_map:
        logger.warning("[店中店交车触客表] 未找到门店名列")
        return {}

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(col_map['store_name'], '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        result[sn] = {
            'sales_order_cnt': _to_int(row.get(col_map.get('sales_order_cnt', ''), 0)),
            'sales_touch_cnt': _to_int(row.get(col_map.get('sales_touch_cnt', ''), 0)),
            'delivery_cnt': _to_int(row.get(col_map.get('delivery_cnt', ''), 0)),
            'delivery_touch_cnt': _to_int(row.get(col_map.get('delivery_touch_cnt', ''), 0)),
            'aftersales_baohui_cnt': _to_int(row.get(col_map.get('aftersales_baohui_cnt', ''), 0)),
            'aftersales_shigu_cnt': _to_int(row.get(col_map.get('aftersales_shigu_cnt', ''), 0)),
            'aftersales_touch_cnt': _to_int(row.get(col_map.get('aftersales_touch_cnt', ''), 0)),
            'purchase_indicator': str(row.get(col_map.get('purchase_indicator', ''), '')).strip() if col_map.get('purchase_indicator') else '',
        }
    logger.info(f"[店中店交车触客表] {len(result)} 个门店")
    return result


def _to_int(val):
    if val is None or (isinstance(val, float) and pd.isna(val)) or str(val).strip() in ('', 'nan', 'None'):
        return 0
    try:
        return int(float(val))
    except Exception:
        return 0


def parse_commerce_policy_inshop(file_path):
    """
    解析商务政策表(店中店处理版)。
    返回 dict[store_name] = {
        oe_window_film_cost, nonoe_window_film_cost,
        oe_car_wrap_cost, nonoe_car_wrap_cost,
        oe_premium_cost, nonoe_premium_cost,
        pedal_cost, construction_cost_post,
        frontline_incentive_ratio,
    }
    """
    logger.info(f"[商务政策-店中店] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[商务政策-店中店] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '门店名'],
        'frontline_incentive_ratio': ['一线激励', '一线激励占比', '一线激励前置'],
        'construction_cost_post': ['施工费后置', '施工成本后置'],
        # 原厂各品类前置施工成本
        'oe_window_film_cost': ['原厂窗膜前置', '窗膜原厂前置', '原厂膜前置'],
        'oe_car_wrap_cost': ['原厂车衣前置', '车衣原厂前置'],
        'oe_premium_cost': ['原厂精品前置', '精品原厂前置'],
        'pedal_cost': ['踏板前置', '踏板施工'],
        # 副厂
        'nonoe_window_film_cost': ['副厂窗膜前置', '窗膜副厂前置'],
        'nonoe_car_wrap_cost': ['副厂车衣前置', '车衣副厂前置'],
        'nonoe_premium_cost': ['副厂精品前置', '精品副厂前置'],
    })

    if 'store_name' not in col_map:
        logger.warning("[商务政策-店中店] 未找到门店名列")
        return {}

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(col_map['store_name'], '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        result[sn] = {k: _to_decimal(row.get(v, 0)) for k, v in col_map.items() if k != 'store_name'}
    logger.info(f"[商务政策-店中店] {len(result)} 个门店")
    return result


def parse_labor_cost(file_path):
    """
    解析人力成本表。
    返回 dict[store_name] = headcount (int) — AF列核验=TUER, 业务类型=1.1, 岗位=门店销售/精品内勤/前台/调度质检员
    """
    logger.info(f"[人力成本表] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[人力成本表] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['入驻门店', '门店名称', '门店名'],
        'verify': ['核验', 'AF', 'AF列'],
        'biz_type': ['业务类型'],
        'position': ['岗位', '职位'],
    })
    if 'store_name' not in col_map:
        return {}

    target_positions = ['门店销售', '精品内勤', '前台', '调度质检员']
    result = {}
    for _, row in df.iterrows():
        verify_val = str(row.get(col_map.get('verify', ''), '')).strip() if col_map.get('verify') else ''
        if verify_val != 'TUER':
            continue
        bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
        if bt != '1.1':
            continue
        pos = str(row.get(col_map.get('position', ''), '')).strip() if col_map.get('position') else ''
        if pos and not any(t in pos for t in target_positions):
            continue
        sn = str(row.get(col_map['store_name'], '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        result[sn] = result.get(sn, 0) + 1
    logger.info(f"[人力成本表] {len(result)} 个门店匹配到人数")
    return result


def get_with_fallback(primary, secondary):
    """
    第一优先取值(Excel),为空/0 时回退到第二优先(SQL/指标系统)。
    用于轻改店中店的"双优先"取值模式。
    """
    if primary is not None and primary != 0 and str(primary).strip() not in ('', 'nan', 'None'):
        return primary
    return secondary


def fetch_prev_month_budget_detail(task, store_names):
    """
    从上月 BizBudgetAchieve 表取轻改店中店需要的多字段:
      renovation_amortization / rent_utilities / store_consumables / service_provider_share_ratio
    返回 dict[store_name] = dict{字段: Decimal}
    """
    from models import BizBudgetAchieve
    current_month = getattr(task, 'month', '')
    pm = prev_month(current_month)
    if not pm or not store_names:
        return {}

    results = {}
    try:
        rows = BizBudgetAchieve.query.filter(
            BizBudgetAchieve.month == pm,
            BizBudgetAchieve.is_deleted == 0,
        ).all()
        fields = [
            ('renovation_amortization', '装修分摊'),
            ('rent_utilities', '房租水电'),
            ('store_consumables', '门店耗材'),
            ('service_provider_share_ratio', '服务费占比'),
        ]
        for row in rows:
            target = getattr(row, 'target_name', '') or ''
            for sn in store_names:
                if sn in target or target in sn:
                    if sn not in results:
                        results[sn] = {}
                    for attr, _label in fields:
                        val = getattr(row, attr, None)
                        if val is not None:
                            results[sn][attr] = Decimal(str(val))
                    break
        logger.info(f"[上月预算明细] month={pm} 匹配 {len(results)}/{len(store_names)}")
    except Exception as e:
        logger.warning(f"[上月预算明细] 查询失败: {e}")

    return results


def is_luxury_brand(brand_name):
    """查豪华品牌表,判断是否豪华品牌。找不到默认非豪华。"""
    from models import LuxuryBrandConfig
    if not brand_name:
        return '非豪华'
    row = LuxuryBrandConfig.query.filter_by(
        brand_name=brand_name, is_deleted=0).first()
    if row and row.is_luxury == 1:
        return '豪华'
    return '非豪华'


def parse_park_delivery_touch(file_path):
    """
    解析园区店交车触客表(区域运营填写)。
    返回 dict[store_name] = {delivery_cnt, arrival_cnt, arrival_invalid_cnt, purchase_indicator}
    """
    logger.info(f"[园区店交车触客表] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[园区店交车触客表] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '门店名'],
        'delivery_cnt': ['交车数', '交车', '新车交付'],
        'arrival_cnt': ['到店数', '到店'],
        'arrival_invalid_cnt': ['到店无效', '无效客户数', '到店无效客户'],
        'purchase_indicator': ['采买', '兜底指标', '采买兜底'],
    })
    if 'store_name' not in col_map:
        logger.warning("[园区店交车触客表] 未找到门店名列")
        return {}

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(col_map['store_name'], '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        result[sn] = {
            'delivery_cnt': _to_int(row.get(col_map.get('delivery_cnt', ''), 0)),
            'arrival_cnt': _to_int(row.get(col_map.get('arrival_cnt', ''), 0)),
            'arrival_invalid_cnt': _to_int(row.get(col_map.get('arrival_invalid_cnt', ''), 0)),
            'purchase_indicator': str(row.get(col_map.get('purchase_indicator', ''), '')).strip() if col_map.get('purchase_indicator') else '',
        }
    logger.info(f"[园区店交车触客表] {len(result)} 个门店")
    return result


def parse_commerce_policy_park(file_path):
    """
    解析商务政策表(园区店处理版)。
    返回 dict[store_name] = {traffic_fee_per_car, ...} —— 门店分成参考(按单台计算流量/台)
    """
    logger.info(f"[商务政策-园区店] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[商务政策-园区店] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '门店名'],
        'traffic_fee_per_car': ['门店分成参考', '按单台计算流量', '流量费/台', '单台流量费'],
    })
    if 'store_name' not in col_map:
        logger.warning("[商务政策-园区店] 未找到门店名列")
        return {}

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(col_map['store_name'], '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        result[sn] = {
            'traffic_fee_per_car': _to_decimal(row.get(col_map.get('traffic_fee_per_car', ''), 0)),
        }
    logger.info(f"[商务政策-园区店] {len(result)} 个门店")
    return result