rerun_baic_900002.py 4.92 KB
# -*- coding: utf-8 -*-
"""临时脚本:重跑北汽专项任务 900002(2026-08)并核对『截止目前产值(status=4) + 延保/权益订单数』落库与结果表。
说明:直接复用 app 上下文(config 会在导入时自动加载 .env,无需手动传 DB 密码),
调用 BaicSpecialProcessor().process(task) 与线上调度器等价。
"""
import os
import sys
from collections import defaultdict

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import app, db
from baic_special_processor import BaicSpecialProcessor, BAIC_BIZ_EXT_WARRANTY, BAIC_BIZ_RIGHTS
from models import (
    DataProcessTask, BaicSpecialMonthData, BaicSpecialMonthlyBusiness,
)

TASK_ID = 900002


def main():
    with app.app_context():
        task = DataProcessTask.query.filter_by(id=TASK_ID).first()
        if not task:
            print(f"[ERROR] 任务 {TASK_ID} 不存在")
            return

        # ---- 重跑前快照(用于对比 status=4 影响)----
        before = BaicSpecialMonthData.query.filter_by(task_id=TASK_ID, is_deleted=0).all()
        before_map = {d.store_name: (d.output_current_wan, d.achievement_rate) for d in before}
        before_biz = BaicSpecialMonthlyBusiness.query.filter(
            BaicSpecialMonthlyBusiness.store_id.in_([d.store_id for d in before])
        ).count() if before else 0
        print(f"== 重跑前 ==")
        print(f"任务状态: {task.status} | 明细活跃行: {len(before)} | 业务(延保/权益)行: {before_biz}")

        # ---- 重跑 ----
        print(f"\n== 开始重跑任务 {TASK_ID} ==")
        BaicSpecialProcessor().process(task)
        print(f"重跑完成 -> 任务状态: {task.status} | result_file_url 已刷新")

        # ---- 重跑后核对 ----
        detail = BaicSpecialMonthData.query.filter_by(task_id=TASK_ID, is_deleted=0).all()
        store_ids = [d.store_id for d in detail]
        biz = BaicSpecialMonthlyBusiness.query.filter(
            BaicSpecialMonthlyBusiness.store_id.in_(store_ids)).all() if store_ids else []
        biz_map = defaultdict(dict)
        for b in biz:
            biz_map[b.store_id][b.business_type] = b.order_cnt

        print(f"\n== 重跑后核对 ==")
        print(f"明细活跃行: {len(detail)} | 业务(延保/权益)行: {len(biz)}")
        print(f"{'门店':<28}{'延保订单数':>10}{'权益订单数':>10}{'截止产值(万)':>14}{'达成率':>10}{'产值变化':>12}")
        print("-" * 96)
        diff_cnt = 0
        for d in detail:
            ext = biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY)
            rig = biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS)
            old_val, _ = before_map.get(d.store_name, (None, None))
            if old_val is not None and d.output_current_wan is not None and old_val != d.output_current_wan:
                diff_cnt += 1
                chg = f"{d.output_current_wan - old_val:+.2f}"
            else:
                chg = "-"
            name = (d.store_name or "")[:26]
            print(f"{name:<28}{str(ext if ext is not None else '-'):>10}"
                  f"{str(rig if rig is not None else '-'):>10}"
                  f"{str(d.output_current_wan if d.output_current_wan is not None else '-'):>14}"
                  f"{str(d.achievement_rate if d.achievement_rate is not None else '-'):>10}"
                  f"{chg:>12}")
        print("-" * 96)
        print(f"延保订单数有值的门店: {sum(1 for d in detail if biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) is not None)}")
        print(f"权益订单数有值的门店: {sum(1 for d in detail if biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) is not None)}")
        print(f"截止目前产值因 status=4 发生变化的门店: {diff_cnt}")

        # ---- 结果 Excel 本地副本核对(Q=17 订单数列)----
        local_xlsx = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  'outputs', f'baic_special_2026-08_task900002.xlsx')
        if os.path.exists(local_xlsx):
            import openpyxl
            wb = openpyxl.load_workbook(local_xlsx, data_only=True)
            ws = wb[wb.sheetnames[0]]
            print(f"\n== 结果表本地副本: {local_xlsx} (sheet={ws.title}) ==")
            # 简易校验:扫描业务=I/权益 行,Q(17) 应与 DB 一致
            mismatch = 0
            checked = 0
            for r in range(1, ws.max_row + 1):
                bizname = ws.cell(r, 9).value  # I 列业务
                if bizname in ('延保', '权益'):
                    q = ws.cell(r, 17).value
                    checked += 1
                    # 仅打印前若干行示例
                    if checked <= 8:
                        print(f"  r{r} 业务={bizname} Q(订单数)={q}")
            print(f"  (已扫描 {checked} 行业务明细,示例见上)")
        else:
            print(f"\n[WARN] 未找到本地结果表: {local_xlsx}")

    sys.stdout.flush()
    os._exit(0)


if __name__ == '__main__':
    main()