etl_dwm.py 32.4 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
# -*- coding: utf-8 -*-
"""
DWM 层指标生成脚本: 从 DWS 层计算 → 写入 DWM 层指标表
包含: 基础指标 + 二级衍生指标, 按天粒度

用法:
    python etl_dwm.py                          # 全量
    python etl_dwm.py --start 2026-05-01 --end 2026-05-27
    python etl_dwm.py --tables staff_touch,merchant_touch
"""

import argparse
import sys
import time
import pymysql
from pymysql.cursors import DictCursor

TARGET_CONFIG = {
    'host': '192.168.2.155', 'port': 3308,
    'user': 'user_jiangmy', 'password': 'PYuxMTB1',
    'database': 'test_excel', 'charset': 'utf8mb4',
    'cursorclass': DictCursor,
}


def log(msg):
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def execute_sql(conn, sql, params=None, desc=""):
    try:
        with conn.cursor() as cur:
            affected = cur.execute(sql, params) if params else cur.execute(sql)
        conn.commit()
        log(f"  [OK] {desc}: {affected:,} 行" if desc else f"  [OK] {affected:,} 行")
        return affected
    except Exception as e:
        conn.rollback()
        log(f"  [FAIL] {desc}: {e}")
        raise


def delete_old(conn, table, start, end, date_col='report_date'):
    if start and end:
        execute_sql(conn, f"DELETE FROM {table} WHERE {date_col} BETWEEN %s AND %s",
                    (start, end), f"删除旧数据({start}~{end})")
    else:
        execute_sql(conn, f"TRUNCATE TABLE {table}", None, "清空表")


# ============================================================================
# 1. dwm_staff_touch_daily — 员工触客日指标
# ============================================================================
def build_staff_touch(conn, start, end):
    log("=== 构建 dwm_staff_touch_daily (员工触客日指标) ===")
    delete_old(conn, 'dwm_staff_touch_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND s.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND s.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_staff_touch_daily (
        report_date, merchant_id, merchant_name, province_name, area_supervision,
        staff_uuid, staff_name, scene_type, first_brand_id, brand_id, on_break,
        -- 基础指标
        active_staff_count, not_delivery_count,
        actual_touch_count, actual_extended_warranty_touch, actual_equity_touch, actual_after_sale_touch,
        -- 二级衍生指标
        should_touch_count, should_extended_warranty_touch, should_equity_touch,
        touch_completion_rate, extended_warranty_touch_rate, equity_touch_rate,
        to_shop_rate, avg_daily_touch, etl_date
    )
    SELECT
        s.report_date,
        s.merchant_id, s.merchant_name, s.province_name, s.area_supervision,
        s.staff_uuid, s.staff_name, s.scene_type, s.first_brand_id, s.brand_id, s.on_break,
        -- 基础: 同门店在岗人数
        IFNULL(s.staff_count, 0) AS active_staff_count,
        IFNULL(s.not_delivery_count, 0) AS not_delivery_count,
        IFNULL(s.equity_to_shop_count, 0) AS actual_touch_count,
        IFNULL(s.extended_warranty_to_shop_count, 0) AS actual_extended_warranty_touch,
        IFNULL(s.real_equity_to_shop_count, 0) AS actual_equity_touch,
        IFNULL(s.after_sale_equity_to_shop_count, 0) + IFNULL(s.after_sale_extended_warranty_to_shop_count, 0) + IFNULL(s.after_sale_real_equity_to_shop_count, 0) AS actual_after_sale_touch,
        -- 二级: 应触客数(休假=实际触客; 在岗=(未交付数/在岗人数)+实际触客)
        CASE
            WHEN s.on_break = 'Y' THEN IFNULL(s.equity_to_shop_count, 0)
            WHEN IFNULL(s.staff_count, 0) = 0 THEN 0
            ELSE (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.equity_to_shop_count, 0)
        END AS should_touch_count,
        CASE
            WHEN s.on_break = 'Y' THEN IFNULL(s.extended_warranty_to_shop_count, 0)
            WHEN IFNULL(s.staff_count, 0) = 0 THEN 0
            ELSE (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.extended_warranty_to_shop_count, 0)
        END AS should_extended_warranty_touch,
        CASE
            WHEN s.on_break = 'Y' THEN IFNULL(s.real_equity_to_shop_count, 0)
            WHEN IFNULL(s.staff_count, 0) = 0 THEN 0
            ELSE (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.real_equity_to_shop_count, 0)
        END AS should_equity_touch,
        -- 完成率 = 实际/应触客
        CASE
            WHEN s.on_break = 'Y' THEN 1.0
            WHEN IFNULL(s.staff_count, 0) = 0 THEN NULL
            WHEN (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.equity_to_shop_count, 0) = 0 THEN NULL
            ELSE IFNULL(s.equity_to_shop_count, 0) / ((IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.equity_to_shop_count, 0))
        END AS touch_completion_rate,
        CASE
            WHEN s.on_break = 'Y' THEN 1.0
            WHEN IFNULL(s.staff_count, 0) = 0 THEN NULL
            WHEN (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.extended_warranty_to_shop_count, 0) = 0 THEN NULL
            ELSE IFNULL(s.extended_warranty_to_shop_count, 0) / ((IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.extended_warranty_to_shop_count, 0))
        END AS extended_warranty_touch_rate,
        CASE
            WHEN s.on_break = 'Y' THEN 1.0
            WHEN IFNULL(s.staff_count, 0) = 0 THEN NULL
            WHEN (IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.real_equity_to_shop_count, 0) = 0 THEN NULL
            ELSE IFNULL(s.real_equity_to_shop_count, 0) / ((IFNULL(s.not_delivery_count, 0) / s.staff_count) + IFNULL(s.real_equity_to_shop_count, 0))
        END AS equity_touch_rate,
        -- 到店率 = 触客/交付
        CASE WHEN IFNULL(s.delivery_count, 0) = 0 THEN NULL
             ELSE IFNULL(s.equity_to_shop_count, 0) / s.delivery_count END AS to_shop_rate,
        -- 日均触客(=当天触客数, 累计版本在DWA层算)
        IFNULL(s.equity_to_shop_count, 0) AS avg_daily_touch,
        CURDATE()
    FROM dws_staff_daily_wide s
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入员工触客指标")


# ============================================================================
# 2. dwm_staff_transaction_daily — 员工交易日指标
# ============================================================================
def build_staff_transaction(conn, start, end):
    log("=== 构建 dwm_staff_transaction_daily (员工交易日指标) ===")
    delete_old(conn, 'dwm_staff_transaction_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND s.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND s.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_staff_transaction_daily (
        report_date, merchant_id, merchant_name, province_name,
        staff_uuid, staff_name, scene_type, first_brand_id, brand_id,
        -- 基础指标
        total_order_count, extended_warranty_count, tire_warranty_count, ax_package_count,
        battery_extended_count, battery_extended_money,
        total_order_money, cancel_order_count, cancel_order_money, delivery_count,
        -- 二级衍生指标
        net_order_money, avg_order_value, battery_conversion_rate,
        deal_rate, prev_month_deal_rate, deal_rate_change,
        cumulative_orders, cumulative_money, etl_date
    )
    SELECT
        s.report_date,
        s.merchant_id, s.merchant_name, s.province_name,
        s.staff_uuid, s.staff_name, s.scene_type, s.first_brand_id, s.brand_id,
        IFNULL(s.total_order_count, 0),
        IFNULL(s.extended_warranty_count, 0),
        IFNULL(s.tire_warranty_count, 0),
        IFNULL(s.ax_package_count, 0),
        IFNULL(s.battery_extended_warranty_count, 0),
        IFNULL(s.battery_extended_warranty_money, 0),
        IFNULL(s.total_order_money, 0),
        IFNULL(s.cancel_order_count, 0),
        IFNULL(s.cancel_order_money, 0),
        IFNULL(s.delivery_count, 0),
        -- 二级
        IFNULL(s.total_order_money, 0) - IFNULL(s.cancel_order_money, 0) AS net_order_money,
        CASE WHEN IFNULL(s.total_order_count, 0) = 0 THEN NULL
             ELSE IFNULL(s.total_order_money, 0) / s.total_order_count END AS avg_order_value,
        -- 电池转化率(成交/触客)
        CASE WHEN IFNULL(s.equity_to_shop_count, 0) = 0 THEN NULL
             ELSE IFNULL(s.battery_extended_warranty_count, 0) / s.equity_to_shop_count END AS battery_conversion_rate,
        -- 成交率(从employee_delivery_deal_rate表关联)
        edr.deal_rate,
        NULL AS prev_month_deal_rate,
        NULL AS deal_rate_change,
        -- 累计(子查询)
        cum.cum_orders AS cumulative_orders,
        cum.cum_money AS cumulative_money,
        CURDATE()
    FROM dws_staff_daily_wide s
    LEFT JOIN ods_employee_delivery_deal_rate edr
        ON s.merchant_id = edr.merchant_id
        AND s.staff_uuid = edr.staff_uuid
        AND DATE_FORMAT(STR_TO_DATE(s.report_date, '%%Y-%%m-%%d'), '%%Y-%%m') = edr.deal_month
        AND edr.deleted_flag = 'N'
    LEFT JOIN (
        SELECT merchant_id, staff_uuid, report_date,
               SUM(total_order_count) OVER(PARTITION BY merchant_id, staff_uuid ORDER BY report_date) AS cum_orders,
               SUM(total_order_money) OVER(PARTITION BY merchant_id, staff_uuid ORDER BY report_date) AS cum_money
        FROM (
            SELECT DISTINCT merchant_id, staff_uuid, report_date, scene_type, first_brand_id, brand_id,
                   total_order_count, total_order_money
            FROM dws_staff_daily_wide
        ) distinct_rows
    ) cum ON s.merchant_id = cum.merchant_id AND s.staff_uuid = cum.staff_uuid AND s.report_date = cum.report_date
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入员工交易指标")


# ============================================================================
# 3. dwm_merchant_touch_daily — 门店触客日指标
# ============================================================================
def build_merchant_touch(conn, start, end):
    log("=== 构建 dwm_merchant_touch_daily (门店触客日指标) ===")
    delete_old(conn, 'dwm_merchant_touch_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND m.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND m.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_merchant_touch_daily (
        report_date, merchant_id, merchant_name, province_name,
        area_supervision, online_supervision, flight_supervision,
        scene_type, first_brand_id, brand_id,
        -- 基础指标
        total_staff, active_staff, on_break_staff,
        total_pre_sale_touch, total_after_sale_touch, total_touch,
        extended_warranty_touch, equity_touch,
        -- 二级衍生指标
        avg_touch_per_staff, total_should_touch, touch_completion_rate, to_shop_rate,
        yesterday_touch, last_week_same_day_touch, wow_touch_change, etl_date
    )
    SELECT
        m.report_date,
        m.merchant_id, m.merchant_name, m.province_name,
        m.area_supervision, m.online_supervision, m.flight_supervision,
        m.scene_type, m.first_brand_id, m.brand_id,
        IFNULL(m.total_staff, 0), IFNULL(m.active_staff, 0), IFNULL(m.on_break_staff, 0),
        IFNULL(m.sum_equity_to_shop, 0) AS total_pre_sale_touch,
        IFNULL(m.sum_after_sale_to_shop, 0) AS total_after_sale_touch,
        IFNULL(m.sum_equity_to_shop, 0) + IFNULL(m.sum_after_sale_to_shop, 0) AS total_touch,
        IFNULL(m.sum_extended_warranty_to_shop, 0) AS extended_warranty_touch,
        IFNULL(m.sum_real_equity_to_shop, 0) AS equity_touch,
        -- 二级
        CASE WHEN IFNULL(m.active_staff, 0) = 0 THEN NULL
             ELSE (IFNULL(m.sum_equity_to_shop, 0) + IFNULL(m.sum_after_sale_to_shop, 0)) / m.active_staff END AS avg_touch_per_staff,
        -- 应触客数 = SUM(员工应触客), 从dwm_staff_touch_daily聚合
        st.sum_should_touch,
        CASE WHEN IFNULL(st.sum_should_touch, 0) = 0 THEN NULL
             ELSE (IFNULL(m.sum_equity_to_shop, 0) + IFNULL(m.sum_after_sale_to_shop, 0)) / st.sum_should_touch END AS touch_completion_rate,
        CASE WHEN IFNULL(m.delivery_count, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_equity_to_shop, 0) / m.delivery_count END AS to_shop_rate,
        -- 同环比
        yd.total_touch AS yesterday_touch,
        wd.total_touch AS last_week_same_day_touch,
        CASE WHEN IFNULL(yd.total_touch, 0) = 0 THEN NULL
             ELSE (IFNULL(m.sum_equity_to_shop, 0) + IFNULL(m.sum_after_sale_to_shop, 0) - yd.total_touch) / yd.total_touch END AS wow_touch_change,
        CURDATE()
    FROM dws_merchant_daily_wide m
    LEFT JOIN (
        SELECT merchant_id, scene_type, first_brand_id, brand_id, report_date,
               SUM(should_touch_count) AS sum_should_touch
        FROM dwm_staff_touch_daily
        GROUP BY merchant_id, scene_type, first_brand_id, brand_id, report_date
    ) st ON m.merchant_id = st.merchant_id AND m.scene_type = st.scene_type
         AND m.first_brand_id = st.first_brand_id AND m.brand_id = st.brand_id
         AND m.report_date = st.report_date
    -- 昨日数据
    LEFT JOIN (
        SELECT merchant_id, scene_type, first_brand_id, brand_id, report_date,
               sum_equity_to_shop + IFNULL(sum_after_sale_to_shop, 0) AS total_touch
        FROM dws_merchant_daily_wide
    ) yd ON m.merchant_id = yd.merchant_id AND m.scene_type = yd.scene_type
         AND m.first_brand_id = yd.first_brand_id AND m.brand_id = yd.brand_id
         AND STR_TO_DATE(m.report_date, '%%Y-%%m-%%d') = DATE_ADD(STR_TO_DATE(yd.report_date, '%%Y-%%m-%%d'), INTERVAL 1 DAY)
    -- 上周同日数据
    LEFT JOIN (
        SELECT merchant_id, scene_type, first_brand_id, brand_id, report_date,
               sum_equity_to_shop + IFNULL(sum_after_sale_to_shop, 0) AS total_touch
        FROM dws_merchant_daily_wide
    ) wd ON m.merchant_id = wd.merchant_id AND m.scene_type = wd.scene_type
         AND m.first_brand_id = wd.first_brand_id AND m.brand_id = wd.brand_id
         AND STR_TO_DATE(m.report_date, '%%Y-%%m-%%d') = DATE_ADD(STR_TO_DATE(wd.report_date, '%%Y-%%m-%%d'), INTERVAL 7 DAY)
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入门店触客指标")


# ============================================================================
# 4. dwm_merchant_transaction_daily — 门店交易日指标
# ============================================================================
def build_merchant_transaction(conn, start, end):
    log("=== 构建 dwm_merchant_transaction_daily (门店交易日指标) ===")
    delete_old(conn, 'dwm_merchant_transaction_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND m.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND m.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_merchant_transaction_daily (
        report_date, merchant_id, merchant_name, province_name,
        scene_type, first_brand_id, brand_id,
        -- 基础指标
        total_orders, extended_warranty_orders, tire_warranty_orders, ax_package_orders,
        battery_extended_orders, total_output_value, extended_warranty_value, battery_extended_value,
        -- 二级衍生指标
        avg_order_value, extended_warranty_rate, battery_rate,
        month_output_target, output_completion_rate,
        cumulative_output, cumulative_orders, etl_date
    )
    SELECT
        m.report_date,
        m.merchant_id, m.merchant_name, m.province_name,
        m.scene_type, m.first_brand_id, m.brand_id,
        IFNULL(m.sum_order_count, 0),
        IFNULL(m.sum_extended_warranty, 0),
        0 AS tire_warranty_orders,
        0 AS ax_package_orders,
        IFNULL(m.sum_battery_extended, 0),
        IFNULL(m.sum_total_order_money, 0) AS total_output_value,
        0 AS extended_warranty_value,
        IFNULL(m.sum_battery_money, 0) AS battery_extended_value,
        -- 二级
        CASE WHEN IFNULL(m.sum_order_count, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_total_order_money, 0) / m.sum_order_count END AS avg_order_value,
        CASE WHEN IFNULL(m.sum_order_count, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_extended_warranty, 0) / m.sum_order_count END AS extended_warranty_rate,
        CASE WHEN IFNULL(m.sum_order_count, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_battery_extended, 0) / m.sum_order_count END AS battery_rate,
        NULL AS month_output_target,
        NULL AS output_completion_rate,
        NULL AS cumulative_output,
        NULL AS cumulative_orders,
        CURDATE()
    FROM dws_merchant_daily_wide m
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入门店交易指标")

    # 补充产值(从订单明细表)
    log("  补充产值数据...")
    update_sql = """
    UPDATE dwm_merchant_transaction_daily t
    INNER JOIN (
        SELECT merchant_id, install_date,
               SUM(net_price) AS total_output
        FROM dws_order_detail_wide
        WHERE order_status IN (2, 4, 6)
        GROUP BY merchant_id, install_date
    ) o ON t.merchant_id = o.merchant_id AND t.report_date = o.install_date
    SET t.total_output_value = o.total_output
    """
    try:
        execute_sql(conn, update_sql, None, "更新产值")
    except Exception as e:
        log(f"  [WARN] 产值更新跳过: {e}")


# ============================================================================
# 5. dwm_merchant_delivery_daily — 门店交付日指标
# ============================================================================
def build_merchant_delivery(conn, start, end):
    log("=== 构建 dwm_merchant_delivery_daily (门店交付日指标) ===")
    delete_old(conn, 'dwm_merchant_delivery_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND t.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND t.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_merchant_delivery_daily (
        report_date, merchant_id, merchant_name, province_name,
        -- 基础指标
        store_delivery, host_plant_delivery, total_delivery,
        customer_loss_count, not_delivery_count,
        -- 二级衍生指标
        delivery_gap, loss_rate, month_deliver_target, delivery_completion_rate,
        cumulative_delivery, cumulative_host_delivery, etl_date
    )
    SELECT
        t.report_date,
        t.merchant_id, t.merchant_name, t.province_name,
        IFNULL(t.store_delivery_count, 0) AS store_delivery,
        IFNULL(t.host_plant_delivery_count, 0) AS host_plant_delivery,
        IFNULL(t.total_delivery_count, 0) AS total_delivery,
        IFNULL(t.customer_loss_count, 0),
        0 AS not_delivery_count,
        -- 二级
        IFNULL(t.store_delivery_count, 0) - IFNULL(t.host_plant_delivery_count, 0) AS delivery_gap,
        CASE WHEN IFNULL(t.total_delivery_count, 0) = 0 THEN NULL
             ELSE IFNULL(t.customer_loss_count, 0) / t.total_delivery_count END AS loss_rate,
        NULL AS month_deliver_target,
        NULL AS delivery_completion_rate,
        NULL AS cumulative_delivery,
        NULL AS cumulative_host_delivery,
        CURDATE()
    FROM dws_merchant_daily_target_wide t
    WHERE 1=1
    {date_filter}
    GROUP BY t.merchant_id, t.report_date
    """
    execute_sql(conn, sql, params if params else None, "写入门店交付指标")


# ============================================================================
# 6. dwm_battery_analysis_daily — 电池延保分析日指标
# ============================================================================
def build_battery_analysis(conn, start, end):
    log("=== 构建 dwm_battery_analysis_daily (电池延保分析日指标) ===")
    delete_old(conn, 'dwm_battery_analysis_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND m.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND m.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_battery_analysis_daily (
        report_date, merchant_id, merchant_name, store_code, province_name, area_supervision,
        -- 基础指标
        battery_touch_count, battery_order_count, battery_output_value,
        host_plant_delivery, store_delivery, staff_count,
        -- 二级衍生指标
        battery_should_touch, battery_conversion_rate,
        avg_battery_per_staff, avg_output_per_staff, touch_coverage_rate,
        cumulative_battery_orders, cumulative_battery_value, etl_date
    )
    SELECT
        m.report_date,
        m.merchant_id, m.merchant_name, m.store_code, m.province_name, m.area_supervision,
        IFNULL(m.sum_equity_to_shop, 0) AS battery_touch_count,
        IFNULL(m.sum_battery_extended, 0) AS battery_order_count,
        IFNULL(m.sum_battery_money, 0) AS battery_output_value,
        IFNULL(t.host_plant_delivery_count, 0) AS host_plant_delivery,
        IFNULL(m.delivery_count, 0) AS store_delivery,
        IFNULL(m.active_staff, 0) AS staff_count,
        -- 二级
        CASE WHEN IFNULL(m.active_staff, 0) = 0 THEN 0
             ELSE IFNULL(m.sum_not_delivery, 0) / m.active_staff + IFNULL(m.sum_equity_to_shop, 0) END AS battery_should_touch,
        CASE WHEN IFNULL(m.sum_equity_to_shop, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_battery_extended, 0) / m.sum_equity_to_shop END AS battery_conversion_rate,
        CASE WHEN IFNULL(m.active_staff, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_battery_extended, 0) / m.active_staff END AS avg_battery_per_staff,
        CASE WHEN IFNULL(m.active_staff, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_battery_money, 0) / m.active_staff END AS avg_output_per_staff,
        CASE WHEN IFNULL(m.delivery_count, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_equity_to_shop, 0) / m.delivery_count END AS touch_coverage_rate,
        NULL AS cumulative_battery_orders,
        NULL AS cumulative_battery_value,
        CURDATE()
    FROM dws_merchant_daily_wide m
    LEFT JOIN dws_merchant_daily_target_wide t
        ON m.merchant_id = t.merchant_id AND m.report_date = t.report_date
    WHERE 1=1
    -- 电池分析聚焦问界(brand_id=2695)或鸿蒙智行(first_brand_id=2365)
    AND (m.first_brand_id = 2365 OR m.brand_id = 2695)
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入电池延保分析指标")


# ============================================================================
# 7. dwm_guarantee_daily — 兜底保障日指标
# ============================================================================
def build_guarantee(conn, start, end):
    log("=== 构建 dwm_guarantee_daily (兜底保障日指标) ===")
    delete_old(conn, 'dwm_guarantee_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND m.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND m.report_date <= %s"; params.append(end)

    sql = f"""
    INSERT IGNORE INTO dwm_guarantee_daily (
        report_date, merchant_id, merchant_name, province_name,
        product_type, brand,
        -- 基础指标(配置)
        target_conversion_rate, unit_compensation, guarantee_type,
        -- 基础指标(实际)
        actual_touch_count, actual_order_count, actual_delivery_count,
        -- 二级衍生指标
        actual_conversion_rate, is_triggered, gap_count, estimated_compensation, etl_date
    )
    SELECT
        m.report_date,
        m.merchant_id, m.merchant_name, m.province_name,
        CASE
            WHEN m.first_brand_id = 2365 THEN '鸿蒙智行'
            WHEN m.brand_id = 2695 THEN '问界'
            ELSE '其他'
        END AS product_type,
        m.first_brand_name AS brand,
        gc.target_conversion_rate,
        gc.unit_compensation_amount AS unit_compensation,
        gc.guarantee_type,
        IFNULL(m.sum_equity_to_shop, 0) AS actual_touch_count,
        IFNULL(m.sum_battery_extended, 0) AS actual_order_count,
        IFNULL(m.delivery_count, 0) AS actual_delivery_count,
        -- 二级
        CASE WHEN IFNULL(m.sum_equity_to_shop, 0) = 0 THEN NULL
             ELSE IFNULL(m.sum_battery_extended, 0) / m.sum_equity_to_shop END AS actual_conversion_rate,
        CASE
            WHEN gc.target_conversion_rate IS NOT NULL
             AND IFNULL(m.sum_equity_to_shop, 0) > 0
             AND (IFNULL(m.sum_battery_extended, 0) / m.sum_equity_to_shop) < gc.target_conversion_rate
            THEN 'Y' ELSE 'N'
        END AS is_triggered,
        CASE
            WHEN gc.target_conversion_rate IS NOT NULL
             AND IFNULL(m.sum_equity_to_shop, 0) > 0
             AND (IFNULL(m.sum_battery_extended, 0) / m.sum_equity_to_shop) < gc.target_conversion_rate
            THEN m.sum_equity_to_shop * gc.target_conversion_rate - m.sum_battery_extended
            ELSE 0
        END AS gap_count,
        CASE
            WHEN gc.target_conversion_rate IS NOT NULL
             AND IFNULL(m.sum_equity_to_shop, 0) > 0
             AND (IFNULL(m.sum_battery_extended, 0) / m.sum_equity_to_shop) < gc.target_conversion_rate
            THEN (m.sum_equity_to_shop * gc.target_conversion_rate - m.sum_battery_extended) * gc.unit_compensation_amount
            ELSE 0
        END AS estimated_compensation,
        CURDATE()
    FROM dws_merchant_daily_wide m
    LEFT JOIN ods_guarantee_config gc
        ON m.merchant_id = gc.merchant_id
        AND gc.effective_date <= m.report_date
        AND (gc.expire_date IS NULL OR gc.expire_date >= m.report_date)
        AND gc.deleted_flag = 'N'
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入兜底保障指标")


# ============================================================================
# 8. dwm_store_ranking_daily — 门店排行日指标
# ============================================================================
def build_store_ranking(conn, start, end):
    log("=== 构建 dwm_store_ranking_daily (门店排行日指标) ===")
    delete_old(conn, 'dwm_store_ranking_daily', start, end)

    date_filter = ""
    params = []
    if start:
        date_filter += " AND t.report_date >= %s"; params.append(start)
    if end:
        date_filter += " AND t.report_date <= %s"; params.append(end)

    # 先插入基础数据
    sql = f"""
    INSERT IGNORE INTO dwm_store_ranking_daily (
        report_date, merchant_id, merchant_name, store_code, province_name, area_supervision,
        total_staff, active_staff,
        store_touch_count, store_order_count, store_output_value, store_delivery,
        avg_touch_per_staff, avg_order_per_staff, avg_output_per_staff,
        top_touch_staff_uuid, top_touch_staff_name, top_touch_count,
        top_output_staff_uuid, top_output_staff_name, top_output_value,
        province_rank_touch, province_rank_output,
        is_excellent_store, store_grade, etl_date
    )
    SELECT
        t.report_date,
        t.merchant_id, t.merchant_name, t.store_code, t.province_name, t.area_supervision,
        IFNULL(t.active_staff, 0) + IFNULL(t.on_break_staff, 0) AS total_staff,
        IFNULL(t.active_staff, 0),
        IFNULL(t.total_touch_count, 0) AS store_touch_count,
        IFNULL(t.total_order_count, 0) AS store_order_count,
        IFNULL(t.total_output_value, 0) AS store_output_value,
        IFNULL(t.store_delivery_count, 0) AS store_delivery,
        CASE WHEN IFNULL(t.active_staff, 0) = 0 THEN NULL
             ELSE t.total_touch_count / t.active_staff END AS avg_touch_per_staff,
        CASE WHEN IFNULL(t.active_staff, 0) = 0 THEN NULL
             ELSE t.total_order_count / t.active_staff END AS avg_order_per_staff,
        CASE WHEN IFNULL(t.active_staff, 0) = 0 THEN NULL
             ELSE t.total_output_value / t.active_staff END AS avg_output_per_staff,
        NULL, NULL, NULL,
        NULL, NULL, NULL,
        NULL, NULL,
        'N', NULL,
        CURDATE()
    FROM dws_merchant_daily_target_wide t
    WHERE 1=1
    {date_filter}
    """
    execute_sql(conn, sql, params if params else None, "写入门店排行基础数据")

    # 更新省内排名
    log("  计算省内排名...")
    rank_sql = """
    UPDATE dwm_store_ranking_daily r
    INNER JOIN (
        SELECT id,
               ROW_NUMBER() OVER(PARTITION BY province_name, report_date ORDER BY store_touch_count DESC) AS r_touch,
               ROW_NUMBER() OVER(PARTITION BY province_name, report_date ORDER BY store_output_value DESC) AS r_output
        FROM dwm_store_ranking_daily
    ) t ON r.id = t.id
    SET r.province_rank_touch = t.r_touch, r.province_rank_output = t.r_output
    """
    try:
        execute_sql(conn, rank_sql, None, "更新省内排名")
    except Exception as e:
        log(f"  [WARN] 排名更新需要MySQL 8.0+: {e}")

    # 更新TOP员工
    log("  计算TOP员工...")
    top_sql = """
    UPDATE dwm_store_ranking_daily r
    INNER JOIN (
        SELECT merchant_id, report_date,
               staff_uuid AS top_staff, staff_name AS top_name, total_order_count AS top_orders
        FROM (
            SELECT s.merchant_id, s.report_date, s.staff_uuid, s.staff_name, s.total_order_count,
                   ROW_NUMBER() OVER(PARTITION BY s.merchant_id, s.report_date ORDER BY s.total_order_count DESC) AS rn
            FROM dws_staff_daily_wide s
        ) ranked WHERE rn = 1
    ) t ON r.merchant_id = t.merchant_id AND r.report_date = t.report_date
    SET r.top_touch_staff_uuid = t.top_staff,
        r.top_touch_staff_name = t.top_name,
        r.top_touch_count = t.top_orders
    """
    try:
        execute_sql(conn, top_sql, None, "更新TOP员工")
    except Exception as e:
        log(f"  [WARN] TOP员工更新需要MySQL 8.0+: {e}")


# ============================================================================
DWM_BUILDERS = {
    'staff_touch':       ('dwm_staff_touch_daily',           build_staff_touch),
    'staff_transaction': ('dwm_staff_transaction_daily',     build_staff_transaction),
    'merchant_touch':    ('dwm_merchant_touch_daily',        build_merchant_touch),
    'merchant_transaction': ('dwm_merchant_transaction_daily', build_merchant_transaction),
    'merchant_delivery': ('dwm_merchant_delivery_daily',     build_merchant_delivery),
    'battery_analysis':  ('dwm_battery_analysis_daily',      build_battery_analysis),
    'guarantee':         ('dwm_guarantee_daily',             build_guarantee),
    'store_ranking':     ('dwm_store_ranking_daily',         build_store_ranking),
}


def main():
    parser = argparse.ArgumentParser(description='DWM层指标生成脚本')
    parser.add_argument('--start', type=str, default='', help='开始日期 YYYY-MM-DD')
    parser.add_argument('--end', type=str, default='', help='结束日期 YYYY-MM-DD')
    parser.add_argument('--tables', type=str, default='', help='指定表')
    args = parser.parse_args()

    start = args.start if args.start else None
    end = args.end if args.end else None

    log("=" * 60)
    log(f"DWM层指标生成脚本启动")
    log(f"日期范围: {start or '全部'} ~ {end or '全部'}")
    log("=" * 60)

    builders = DWM_BUILDERS
    if args.tables:
        names = [s.strip() for s in args.tables.split(',')]
        builders = {k: v for k, v in DWM_BUILDERS.items() if k in names}
        if not builders:
            log(f"[FAIL] 无效表名, 可选: {', '.join(DWM_BUILDERS.keys())}")
            sys.exit(1)

    conn = pymysql.connect(**TARGET_CONFIG)
    log("数据库连接成功")

    total_start = time.time()
    for name, (table_name, builder) in builders.items():
        try:
            builder(conn, start, end)
        except Exception as e:
            log(f"[FAIL] {name} 构建失败: {e}")

    log("=" * 60)
    log(f"DWM生成完成! 耗时 {time.time()-total_start:.1f}s")
    log("=" * 60)
    conn.close()


if __name__ == '__main__':
    main()