output_value_processor.py 26.6 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
# -*- coding: utf-8 -*-
"""
产值达成表 独立处理器
====================
对应 ORM 表:saas_business_achievement
数据来源:SAAS门店预算分解表(sheet1=权益延保 2.1+2.3 / sheet2=轻改 1.1)+ 关系表

处理流程(对齐结果表《产值达成表.xlsx》「业务达成总览」口径):
  Step1 下载附件(SAAS门店预算分解表、关系表)
  Step2 解析 SAAS 表:按业务类型取对应 sheet 的明细
        A列 业务类型:2.1+2.3 → sheet1(权益延保);1.1 → sheet2(轻改)
  Step3 解析关系表:业务线 → {区域经理(E列): 大区经理(D列)}
  Step4 按 C 列(区域运营)聚合:
        B列 大区经理  = 关系表按 C 列查 E 列 → 取 D 列
        E列 运营门店数 = 全部明细按「门店」去重计数
        F列 直营门店数 = 驻店类型=直营 的明细按「门店」去重计数
        H列 存量预算  = 存量/性质=存量 的「预估产值(纠偏)」合计
        K列 新店预算  = 存量/性质=新增 的「预估产值(纠偏)」合计
  Step5 入库 saas_business_achievement(按 task_id 先删后插,幂等)

接口列(待接入,暂落 NULL 以示「未获取」而非 0):
  G列 当日新增GMV / I列 存量门店实际达成 / L列 新店实际达成
  依赖接口值的 J/M/N/O 列同步留空,接口接入后自动计算。
"""
import calendar
import logging
import os
import tempfile
from collections import defaultdict
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP

import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from oss_utils import upload_file
from config import Config

from report_utils import (
    mark_task_failed, cleanup_tmp_dir, download_all_files,
    parse_saas_achieve_details, parse_operator_relation,
    safe_div_pct_decimal,
)
from models import DataProcessTask, SaasBusinessAchievement, db

logger = logging.getLogger('OutputValueProcessor')

OUTPUT_VALUE_TYPE = 'output_value'

# 业务类型 → (SAAS 表 sheet 关键字, sheet 索引回退, 关系表业务线关键字)
BIZ_SHEET_CONF = {
    '2.1+2.3': (['权益延保', '门店'], 0, '权益延保'),
    '1.1': (['轻改', '门店'], 1, '轻改'),
}


class OutputValueProcessor:
    """产值达成表独立处理器"""

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

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

    def scan_output_value(self):
        """扫描 output_value 类型的 PROCESSING 任务并处理产值达成表"""
        logger.info("[产值达成] 开始扫描 output_value 待处理任务")

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

        logger.info(f"[产值达成] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process(task)
                success_count += 1
                logger.info(f"[产值达成] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback
                fail_count += 1
                logger.error(f"[产值达成] 任务 {task.id} 处理失败: {str(e)}")
                logger.error(traceback.format_exc())
                try:
                    mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[产值达成] 标记任务失败时出错: {mark_err}")

        logger.info(f"[产值达成] 扫描完成,成功 {success_count},失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}

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

    def process(self, task):
        """处理单个任务的产值达成表输出"""
        task_id = task.id
        try:
            row_count = self._process_output_value(task)

            # 生成结果表 Excel 并上传到 OSS,回写 result_file_url
            result_file_url = self.generate_result_excel(task)

            task = DataProcessTask.query.filter_by(id=task_id).first()
            task.status = 'COMPLETED'
            task.result_file_url = result_file_url
            task.error_msg = ''
            db.session.commit()
            logger.info(f"[产值达成] 任务 {task_id} 处理完成,写入 {row_count} 行,结果文件: {result_file_url}")
        except Exception as e:
            db.session.rollback()
            mark_task_failed(task_id, str(e))
            raise

    def _process_output_value(self, task):
        """产值达成表完整处理流程,返回写入行数"""
        task_id = task.id
        period_start = getattr(task, 'period_start', None)
        period_end = getattr(task, 'period_end', None)
        start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
        end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
        stat_month = task.month or ''

        logger.info(f"[产值达成] 开始处理 task_id={task_id}, 周期={start_str}~{end_str}")

        # ========== Step1: 下载附件 ==========
        tmp_dir = tempfile.mkdtemp(prefix=f"output_value_{task_id}_")
        details_by_biz = {}
        relation = {}
        try:
            file_map = download_all_files(task_id, tmp_dir)

            saas_path = file_map.get('SAAS门店预算分解表')
            if not saas_path:
                raise Exception("缺少必需文件: SAAS门店预算分解表")

            rel_path = file_map.get('关系表')

            # ========== Step2: 解析 SAAS 明细(按业务类型取 sheet) ==========
            for biz_type, (keywords, idx, _line) in BIZ_SHEET_CONF.items():
                details_by_biz[biz_type] = parse_saas_achieve_details(saas_path, keywords, idx)
                logger.info(f"[产值达成] 业务类型 {biz_type}: {len(details_by_biz[biz_type])} 行明细")

            # ========== Step3: 解析关系表 ==========
            if rel_path:
                relation = parse_operator_relation(rel_path)
            else:
                logger.warning("[产值达成] 缺少关系表,B 列(大区经理)将为空")
        finally:
            cleanup_tmp_dir(tmp_dir)

        # ========== Step4: 按区域运营聚合 ==========
        rows_to_insert = []
        for biz_type, (_kw, _idx, line_kw) in BIZ_SHEET_CONF.items():
            records = details_by_biz.get(biz_type) or []

            # 关系表:取该业务线对应的 区域经理 → 大区经理 映射
            line_map = {}
            for line, mapping in relation.items():
                if line_kw and line_kw in str(line):
                    line_map.update(mapping)
            if not line_map:
                # 业务线未命中时回退:合并全部业务线(避免 B 列大面积为空)
                for mapping in relation.values():
                    line_map.update(mapping)

            group = defaultdict(list)
            for r in records:
                group[r['region_operator']].append(r)

            for region_operator, items in group.items():
                # E 列:全部明细按门店去重
                store_set = {it['store_name'] for it in items if it['store_name']}
                operated_stores = len(store_set)

                # F 列:驻店类型=直营 的明细按门店去重
                direct_set = {it['store_name'] for it in items
                              if it['store_name'] and it['resident_type'] == '直营'}
                direct_stores = len(direct_set)

                # H / K 列:按 存量/新增 汇总「预估产值(纠偏)」
                existing_budget = sum((it['budget_corrected'] for it in items
                                       if it['store_kind'] == '存量'), Decimal('0'))
                new_budget = sum((it['budget_corrected'] for it in items
                                  if it['store_kind'] == '新增'), Decimal('0'))

                # B 列:关系表 E(区域经理) → D(大区经理)
                manager = line_map.get(region_operator, '')
                # 关系表哨兵值('/'、'nan'、'None')归一为空,结果表显示为空而非字面斜杠
                if not manager or manager.strip() in ('/', 'nan', 'None', '无'):
                    manager = ''

                # G / I / L 列来自接口,暂未接入 → 落 NULL
                daily_new_gmv = None
                existing_actual = None
                new_actual = None

                # J / M / N / O 列依赖接口值,接口缺失时留空(不置 0,避免误导)
                existing_rate = (safe_div_pct_decimal(existing_actual, existing_budget)
                                 if existing_actual is not None else None)
                new_rate = (safe_div_pct_decimal(new_actual, new_budget)
                            if new_actual is not None else None)
                total_actual_gmv = (existing_actual + new_actual
                                    if (existing_actual is not None and new_actual is not None)
                                    else None)
                total_rate = (safe_div_pct_decimal(total_actual_gmv, existing_budget + new_budget)
                              if total_actual_gmv is not None else None)

                rows_to_insert.append(SaasBusinessAchievement(
                    task_id=task_id,
                    stat_month=stat_month,
                    start_date=start_str,
                    end_date=end_str,
                    business_type=biz_type,
                    manager=manager or None,
                    region_operator=region_operator,
                    online_operator=None,
                    operated_stores=operated_stores,
                    direct_stores=direct_stores,
                    daily_new_gmv=daily_new_gmv,
                    existing_budget=existing_budget,
                    existing_actual=existing_actual,
                    existing_rate=existing_rate,
                    new_budget=new_budget,
                    new_actual=new_actual,
                    new_rate=new_rate,
                    total_actual_gmv=total_actual_gmv,
                    total_rate=total_rate,
                ))

            logger.info(f"[产值达成] 业务类型 {biz_type}: 聚合 {len(group)} 个区域运营")

        # ========== Step5: 入库(按 task_id 先删后插,幂等) ==========
        SaasBusinessAchievement.query.filter_by(task_id=task_id).delete()
        # 先 flush 删除,避免同事务内 insert 与未生效的 delete 触发唯一约束冲突
        db.session.flush()
        # 用 add_all 而非 bulk_save_objects:bulk 会省略 None 列,使 MySQL 套用列默认值 0.00,
        # 导致接口列(G/I/L 及达成率)的 NULL 被误存为 0;add_all 会显式写入 NULL,
        # 这样「0」才能唯一表示「接口已接入且真实为 0」,未接入则留空。
        db.session.add_all(rows_to_insert)
        db.session.commit()

        logger.info(f"[产值达成] 入库完成:{len(rows_to_insert)} 行(task_id={task_id})")
        return len(rows_to_insert)

    # ============================================================
    # 结果表 Excel 生成(任务完成后输出《产值达成表》结果文件)
    # ============================================================

    # 结果表「业务达成总览」列定义:(表头, ORM 属性, 类型)
    # 对齐《产值达成表》模板:A 业务类型 / B=大区经理 / C=区域运营 / D 线上运营 / E~O 指标
    # B 列取值:以 C 列(区域运营) 为键,查关系表 E(区域经理)→D(大区经理) 得到,库存于 manager 字段
    RESULT_COLUMNS = [
        ('业务类型', 'business_type', 'text'),
        ('大区经理', 'manager', 'text'),           # B:关系表 E(区域运营)→D(大区经理)
        ('区域运营', 'region_operator', 'text'),   # C:SAAS 表区域运营
        ('线上运营', 'online_operator', 'text'),
        ('运营门店(家)', 'operated_stores', 'int'),
        ('直营门店(家)', 'direct_stores', 'int'),
        ('当日新增GMV', 'daily_new_gmv', 'amount'),
        ('存量门店预算', 'existing_budget', 'amount'),
        ('存量门店实际达成', 'existing_actual', 'amount'),
        ('存量目标达成率(%)', 'existing_rate', 'rate'),
        ('新店预算', 'new_budget', 'amount'),
        ('新店实际达成', 'new_actual', 'amount'),
        ('新店目标达成率(%)', 'new_rate', 'rate'),
        ('实际达成GMV合计', 'total_actual_gmv', 'amount'),
        ('总预算达成率(%)', 'total_rate', 'rate'),
    ]

    # 统计行(小计/合计)需汇总的列:int/amount 求和,rate 由汇总值重算
    _SUM_COLS = ['operated_stores', 'direct_stores', 'daily_new_gmv',
                 'existing_budget', 'existing_actual', 'new_budget', 'new_actual',
                 'total_actual_gmv']

    @staticmethod
    def _safe_none_sum(values):
        """对可空数值求和:全为空返回 None(保持「未接入」空白),否则忽略 None 求和"""
        nums = [v for v in values if v is not None]
        return sum(nums) if nums else None

    @staticmethod
    def _safe_rate_pct(num, den):
        """达成率(×100,与数据行一致):除数为空/0 时返回 None"""
        if num is None or den is None or den == 0:
            return None
        return round(num / den * 100, 2)

    @staticmethod
    def _merge_same_vertical(ws, start_row, end_row, col, values, border):
        """在 [start_row, end_row] 行范围内,对 col 列中相邻相同的值做纵向合并,并补边框。

        values 为按行顺序(相对 start_row)的值列表;合并后隐藏单元格的边框由
        逐格补 border 保证显示完整边线(openpyxl 合并后仅顶/底可见单元格边框生效)。
        """
        r = start_row
        n = end_row - start_row + 1
        while r <= end_row:
            v = values[r - start_row] if (r - start_row) < len(values) else None
            # 空值(None / 空串)不合并:仅逐格补边框,单列处理
            if v is None or v == '':
                ws.cell(row=r, column=col).border = border
                r += 1
                continue
            run_start = r
            while (r + 1 <= end_row
                   and (r + 1 - start_row) < len(values)
                   and values[r + 1 - start_row] == v):
                r += 1
            if r > run_start:  # 存在 ≥2 个相邻相同值才合并
                ws.merge_cells(start_row=run_start, start_column=col,
                               end_row=r, end_column=col)
            for rr in range(run_start, r + 1):
                ws.cell(row=rr, column=col).border = border
            r += 1

    def _aggregate(self, rows):
        """对一组明细行做汇总,返回各列汇总值(rate 列由汇总后的值重算)"""
        agg = {c: self._safe_none_sum([getattr(r, c) for r in rows])
               for c in self._SUM_COLS}
        existing_budget = agg['existing_budget']
        new_budget = agg['new_budget']
        existing_actual = agg['existing_actual']
        new_actual = agg['new_actual']
        total_actual = agg['total_actual_gmv']
        agg['existing_rate'] = self._safe_rate_pct(existing_actual, existing_budget)
        agg['new_rate'] = self._safe_rate_pct(new_actual, new_budget)
        denom = (existing_budget or 0) + (new_budget or 0)
        agg['total_rate'] = (self._safe_rate_pct(total_actual, denom)
                             if total_actual is not None else None)
        return agg

    def _write_cell(self, ws, row, col, value, kind, font, border, align):
        cell = ws.cell(row=row, column=col)
        if value is None or value == '':
            cell.value = ''
        elif kind == 'int':
            try:
                cell.value = int(value)
                cell.number_format = '#,##0'
            except (ValueError, TypeError):
                cell.value = ''
        elif kind == 'amount':
            try:
                cell.value = float(value)
                cell.number_format = '#,##0.00'
            except (ValueError, TypeError):
                cell.value = ''
        elif kind == 'rate':
            # 数据行/汇总值已是 ×100(如 75.50 表示 75.50%),
            # 用 0.00"%" 仅追加 % 号、不缩放,与预算达成表口径一致
            try:
                cell.value = float(value)
                cell.number_format = '0.00"%"'
            except (ValueError, TypeError):
                cell.value = ''
        else:
            cell.value = str(value)
        cell.font = font
        cell.border = border
        cell.alignment = align

    def generate_result_excel(self, task):
        """根据 saas_business_achievement 生成《产值达成表》结果 Excel 并上传,返回 URL。

        结构对齐《产值达成表》模板(A~O 列):标题(行1,合并居中) / 表头(行2,B+C合并) /
        各业务类型明细(行3+,A 列按业务类型纵向合并、B(大区经理)/C(区域运营) 列相同相邻值纵向合并) /
        每业务类型小计(A:B合并) / 全部业务合计(A:B合并,C 补边框) /
        模板末两行(二手车、总合计:A~L 合并加边框,M 标签,N/O 留空加边框)。
        G/I/L 接口列及依赖它们的 J/M/N/O 达成率列在接口未接入时留空。
        """
        task_id = task.id
        stat_month = task.month or ''

        # 统计周期起止(页面参数「所属周期」的起止时间)
        period_start = getattr(task, 'period_start', None)
        period_end = getattr(task, 'period_end', None)
        # 统计周期最后一天(截止日期),用所属周期的结束时间替换
        end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
        # 时间进度 = 所属周期天数 / 统计月总天数 × 100%,四舍五入保留 2 位小数
        time_progress_pct = None
        if stat_month:
            try:
                y, m = (int(x) for x in stat_month.split('-'))
                days_in_month = calendar.monthrange(y, m)[1]
                if period_start and period_end and days_in_month:
                    days_in_period = (period_end - period_start).days + 1
                    time_progress_pct = round(days_in_period / days_in_month * 100, 2)
            except (ValueError, TypeError):
                time_progress_pct = None

        # 业务类型排序:2.1+2.3 在前,1.1 在后
        biz_order = ['2.1+2.3', '1.1']
        rows = (SaasBusinessAchievement.query
                .filter_by(task_id=task_id)
                .order_by(SaasBusinessAchievement.business_type,
                          SaasBusinessAchievement.manager,
                          SaasBusinessAchievement.region_operator)
                .all())
        from collections import OrderedDict
        groups = OrderedDict()
        for r in rows:
            groups.setdefault(r.business_type, []).append(r)
        rows.sort(key=lambda r: (biz_order.index(r.business_type) if r.business_type in biz_order else 9,
                                 r.manager or '', r.region_operator or ''))

        # ---------- 构建工作簿 ----------
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = '业务达成总览'

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

        # 行1:标题(合并 A1:M1 并居中显示)
        title_cell = ws.cell(
            row=1, column=1,
            value=f'{stat_month}月SAAS+业务各区域预算达成率-运营(截止"{end_date_str}")')
        title_cell.font = title_font
        title_cell.alignment = center
        ws.merge_cells('A1:M1')

        # 行1:时间进度(N 列标签,O 列填实际计算结果)
        n_cell = ws.cell(row=1, column=14, value='时间进度')
        n_cell.font = title_font
        n_cell.alignment = center
        o_cell = ws.cell(row=1, column=15)
        if time_progress_pct is not None:
            o_cell.value = time_progress_pct
            o_cell.number_format = '0.00"%"'
        else:
            o_cell.value = '(统计周期天数/统计月份总天数)×100%'
        o_cell.font = title_font
        o_cell.alignment = center

        # 行2:表头(B=大区经理、C=区域运营,分列显示,不合并)
        for c, (header, _attr, _kind) in enumerate(self.RESULT_COLUMNS, 1):
            cell = ws.cell(row=2, column=c, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = center
            cell.border = thin

        # 行3 起:明细 + 各业务类型小计
        cur = 3
        all_rows = []
        for biz in biz_order:
            grp = groups.get(biz) or []
            if not grp:
                continue
            biz_start = cur
            region_seq = []   # 本业务类型每行 C 列(区域运营) 值,供纵向相同合并
            manager_seq = []  # 本业务类型每行 B 列(大区经理) 值,供纵向相同合并
            for r in grp:
                for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
                    # 数据行:B=大区经理、C=区域运营,各自为独立单元格(不横向合并)
                    self._write_cell(ws, cur, c, getattr(r, attr), kind, cell_font, thin,
                                     right if kind in ('int', 'amount', 'rate') else center)
                manager_seq.append(getattr(r, 'manager') or '')
                region_seq.append(getattr(r, 'region_operator') or '')
                cur += 1
            biz_end = cur - 1

            # 业务类型 A 列纵向合并(2.1+2.3 / 1.1 各合并为一格,对齐原产值达成表)
            if biz_end > biz_start:
                ws.merge_cells(start_row=biz_start, start_column=1, end_row=biz_end, end_column=1)
            # B 列(大区经理)、C 列(区域运营):相同相邻值纵向合并(与原始产值达成表口径一致)
            self._merge_same_vertical(ws, biz_start, biz_end, 2, manager_seq, thin)
            self._merge_same_vertical(ws, biz_start, biz_end, 3, region_seq, thin)

            # 业务类型小计(标签占 A:B 合并,B/C 均补边框)
            sub = self._aggregate(grp)
            a_cell = ws.cell(row=cur, column=1, value=f'{biz}小计')
            a_cell.font = cell_font
            a_cell.alignment = center
            a_cell.border = thin
            ws.cell(row=cur, column=2).border = thin  # B 合并区补边框
            ws.cell(row=cur, column=3).border = thin  # C 单列补边框
            for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
                if c in (1, 2, 3):  # A=标签(已写),B 合并区,C 已补边框
                    continue
                self._write_cell(ws, cur, c, sub.get(attr), kind, cell_font, thin,
                                 right if kind in ('int', 'amount', 'rate') else center)
            ws.merge_cells(start_row=cur, start_column=1, end_row=cur, end_column=2)
            cur += 1
            all_rows.extend(grp)

        # 全部业务合计(标签占 A:B 合并,B/C 均补边框)
        gt = self._aggregate(all_rows)
        a_cell = ws.cell(row=cur, column=1, value='合计')
        a_cell.font = cell_font
        a_cell.alignment = center
        a_cell.border = thin
        ws.cell(row=cur, column=2).border = thin
        ws.cell(row=cur, column=3).border = thin
        for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
            if c in (1, 2, 3):
                continue
            self._write_cell(ws, cur, c, gt.get(attr), kind, cell_font, thin,
                             right if kind in ('int', 'amount', 'rate') else center)
        ws.merge_cells(start_row=cur, start_column=1, end_row=cur, end_column=2)
        cur += 1

        # 模板末两行:二手车、总合计(A~L 合并+边框,M 标签,N/O 留空但加边框)
        uc_row = cur
        tc_row = cur + 1
        for _row, _label in ((uc_row, '二手车'), (tc_row, '总合计')):
            # 前面列 A~L 合并并加边框
            for c in range(1, 13):
                ws.cell(row=_row, column=c).border = thin
            ws.merge_cells(start_row=_row, start_column=1, end_row=_row, end_column=12)
            # M 列标签
            m = ws.cell(row=_row, column=13, value=_label)
            m.font = cell_font
            m.alignment = center
            m.border = thin
            # N、O 列留空但加边框
            ws.cell(row=_row, column=14).border = thin
            ws.cell(row=_row, column=15).border = thin

        # 列宽
        widths = {
            '业务类型': 12, '区域运营': 12, '线上运营': 14,
            '运营门店(家)': 12, '直营门店(家)': 12, '当日新增GMV': 14,
            '存量门店预算': 14, '存量门店实际达成': 14, '存量目标达成率(%)': 14,
            '新店预算': 14, '新店实际达成': 14, '新店目标达成率(%)': 14,
            '实际达成GMV合计': 14, '总预算达成率(%)': 14,
        }
        for c, (header, _a, _k) in enumerate(self.RESULT_COLUMNS, 1):
            ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = widths.get(header, 12)

        ws.freeze_panes = 'A3'
        ws.row_dimensions[1].height = 24
        ws.row_dimensions[2].height = 30

        # ---------- 保存 + 上传 ----------
        tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
        try:
            excel_path = os.path.join(tmp_dir, f'产值达成表_{stat_month}.xlsx')
            wb.save(excel_path)
            object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
                          f"/output_value_{stat_month}_{task_id}.xlsx")
            file_url = upload_file(excel_path, object_key)
            logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
            return file_url
        finally:
            cleanup_tmp_dir(tmp_dir)