merchant_goods_code_processor.py 27.5 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
merchant_goods_code 补齐处理器
根据文档第11章节实现两轮补数逻辑
"""

import logging
from datetime import datetime
from scene_type_mapping import DATA_MIGRATION_USER


class MerchantGoodsCodeProcessor:
    """merchant_goods_code 补齐处理器"""

    def __init__(self, db_helper, test_mode=False):
        """
        初始化处理器

        Args:
            db_helper: 数据库辅助实例
            test_mode: 是否为测试模式
        """
        self.db = db_helper
        self.test_mode = test_mode
        self.logger = logging.getLogger(__name__)

        # 临时表名
        self.context_table = 'tmp_goods_relation_context'
        self.detail_table = 'tmp_merchant_goods_code_detail'
        self.exception_table = 'tmp_merchant_goods_code_exception'

    def create_temp_tables(self):
        """创建临时表"""
        self.logger.info("创建临时表...")

        # 1. 规则上下文表
        create_context_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.context_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '规则关系表ID',
            rule_type TINYINT NOT NULL COMMENT '规则类型:1=财务,3=对账',
            goods_type_group_rule_id BIGINT NOT NULL COMMENT '商品分组规则ID',
            upgrade_goods_id BIGINT COMMENT '升级商品ID',
            merchant_id BIGINT COMMENT '商户ID',
            scene_type TINYINT COMMENT '场景类型',
            base_scene_code VARCHAR(20) COMMENT '细分场景编码',
            settle_rule_id BIGINT COMMENT '财务规则ID',
            division_rule_id BIGINT COMMENT '分账规则ID',
            reconciliation_rule_id BIGINT COMMENT '对账规则ID',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_rule_type (rule_type, goods_type_group_rule_id),
            KEY idx_merchant_scene (merchant_id, scene_type, base_scene_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='规则商品关系上下文临时表';
        """

        # 2. 补数明细表
        create_detail_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.detail_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '原规则关系表ID',
            rule_type TINYINT NOT NULL COMMENT '规则类型',
            goods_type_group_rule_id BIGINT NOT NULL COMMENT '商品分组规则ID',
            upgrade_goods_id BIGINT COMMENT '升级商品ID',
            merchant_id BIGINT COMMENT '商户ID',
            scene_type TINYINT COMMENT '场景类型',
            base_scene_code VARCHAR(20) COMMENT '细分场景编码',
            merchant_goods_code VARCHAR(100) COMMENT '推导出的商品编码',
            source_type VARCHAR(50) COMMENT '来源类型:MERCHANT_GOODS_REF/ORDER_HISTORY',
            action_type VARCHAR(50) COMMENT '处理动作:UPDATE_ORIGIN/INSERT_COPY/SKIP',
            skip_reason VARCHAR(500) COMMENT '跳过原因或异常原因',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_merchant_goods (merchant_id, merchant_goods_code)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='merchant_goods_code补数明细表';
        """

        # 3. 异常清单表
        create_exception_sql = f"""
        CREATE TABLE IF NOT EXISTS {self.exception_table} (
            id BIGINT AUTO_INCREMENT PRIMARY KEY,
            relation_id BIGINT NOT NULL COMMENT '规则关系表ID',
            exception_type VARCHAR(100) COMMENT '异常类型',
            exception_desc TEXT COMMENT '异常描述',
            created_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_relation (relation_id),
            KEY idx_type (exception_type)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='merchant_goods_code补数异常清单表';
        """

        self.db.execute_update(create_context_sql)
        self.db.execute_update(create_detail_sql)
        self.db.execute_update(create_exception_sql)
        self.logger.info("临时表创建完成")

    def drop_temp_tables(self):
        """删除临时表"""
        self.logger.info("删除临时表...")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.context_table};")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.detail_table};")
        self.db.execute_update(f"DROP TABLE IF EXISTS {self.exception_table};")
        self.logger.info("临时表删除完成")

    def build_rule_context(self):
        """
        构造规则上下文
        将 dj_car_life_goods_type_group_relation 中需要补齐的记录
        反推出规则上下文(merchant_id, scene_type, base_scene_code)
        """
        self.logger.info("=" * 80)
        self.logger.info("开始构造规则上下文...")

        # 清空上下文表
        self.db.execute_update(f"TRUNCATE TABLE {self.context_table};")

        # 1. 处理财务规则(rule_type=1)
        self.logger.info("处理财务规则上下文(rule_type=1)...")
        self._build_finance_context()

        # 2. 处理对账规则(rule_type=3)
        self.logger.info("处理对账规则上下文(rule_type=3)...")
        self._build_reconciliation_context()

        # 统计
        count_sql = f"SELECT COUNT(*) FROM {self.context_table};"
        result = self.db.execute_query_one(count_sql)
        total_count = result[0] if result else 0
        self.logger.info(f"规则上下文构造完成,共 {total_count} 条记录")

    def _build_finance_context(self):
        """构造财务规则上下文"""
        # 财务规则链路:
        # dj_car_life_goods_type_group_relation.goods_type_group_rule_id
        #   -> dj_car_life_goods_type_group.id
        #   -> dj_car_life_merchant_goods_type_group_settle_rule.goods_type_group_id
        #   -> dj_car_life_merchant_settle_account_rule.id
        # 同时关联分账规则:
        #   -> dj_car_life_merchant_goods_type_group_division_rule.goods_type_group_id
        #   -> dj_car_life_merchant_division_rule.id

        insert_sql = f"""
        INSERT INTO {self.context_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, settle_rule_id, division_rule_id)
        SELECT DISTINCT
            gtgr.id AS relation_id,
            1 AS rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            sar.merchant_id,
            sar.scene_type,
            sar.base_scene_code,
            sar.id AS settle_rule_id,
            dr.id AS division_rule_id
        FROM dj_car_life_goods_type_group_relation gtgr
        JOIN dj_car_life_goods_type_group gtg
          ON gtg.id = gtgr.goods_type_group_rule_id
         AND gtg.deleted_flag = 'N'
        JOIN dj_car_life_merchant_goods_type_group_settle_rule gtgsr
          ON gtgsr.goods_type_group_id = gtg.id
         AND gtgsr.deleted_flag = 'N'
        JOIN dj_car_life_merchant_settle_account_rule sar
          ON sar.id = gtgsr.settle_rule_id
         AND sar.deleted_flag = 'N'
        JOIN dj_car_life_merchant_goods_type_group_division_rule gtgdr
          ON gtgdr.goods_type_group_id = gtg.id
         AND gtgdr.deleted_flag = 'N'
        JOIN dj_car_life_merchant_division_rule dr
          ON dr.id = gtgdr.division_rule_id
         AND dr.deleted_flag = 'N'
         AND dr.merchant_id = sar.merchant_id
         AND dr.scene_type = sar.scene_type
         AND dr.base_scene_code = sar.base_scene_code
        WHERE gtgr.deleted_flag = 'N'
          AND gtgr.rule_type = 1
          AND gtgr.category_type = 2
          AND gtgr.upgrade_goods_id IS NOT NULL
          AND (gtgr.merchant_goods_code IS NULL OR gtgr.merchant_goods_code = '');
        """

        if self.db.execute_update(insert_sql):
            count_sql = f"SELECT COUNT(*) FROM {self.context_table} WHERE rule_type = 1;"
            result = self.db.execute_query_one(count_sql)
            count = result[0] if result else 0
            self.logger.info(f"  财务规则上下文:{count} 条")

    def _build_reconciliation_context(self):
        """构造对账规则上下文"""
        # 对账规则链路:
        # dj_car_life_goods_type_group_relation.goods_type_group_rule_id
        #   -> dj_car_life_merchant_goods_type_group_reconciliation_rule.id
        #   -> dj_car_life_merchant_reconciliation_rule.id

        insert_sql = f"""
        INSERT INTO {self.context_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, reconciliation_rule_id)
        SELECT DISTINCT
            gtgr.id AS relation_id,
            3 AS rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            rr.merchant_id,
            rr.scene_type,
            rr.base_scene_code,
            rr.id AS reconciliation_rule_id
        FROM dj_car_life_goods_type_group_relation gtgr
        JOIN dj_car_life_merchant_goods_type_group_reconciliation_rule gtgrr
          ON gtgrr.id = gtgr.goods_type_group_rule_id
         AND gtgrr.deleted_flag = 'N'
        JOIN dj_car_life_merchant_reconciliation_rule rr
          ON rr.id = gtgrr.reconciliation_rule_id
         AND rr.deleted_flag = 'N'
        WHERE gtgr.deleted_flag = 'N'
          AND gtgr.rule_type = 3
          AND gtgr.category_type = 2
          AND gtgr.upgrade_goods_id IS NOT NULL
          AND (gtgr.merchant_goods_code IS NULL OR gtgr.merchant_goods_code = '');
        """

        if self.db.execute_update(insert_sql):
            count_sql = f"SELECT COUNT(*) FROM {self.context_table} WHERE rule_type = 3;"
            result = self.db.execute_query_one(count_sql)
            count = result[0] if result else 0
            self.logger.info(f"  对账规则上下文:{count} 条")

    def round1_fill_from_merchant_goods(self):
        """
        第一轮补数:从商品上架数据和商户商品关联表补齐
        """
        self.logger.info("=" * 80)
        self.logger.info("第一轮补数:从商品上架数据补齐...")

        # 查询所有需要处理的上下文
        query_sql = f"""
        SELECT id, relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
               merchant_id, scene_type, base_scene_code
        FROM {self.context_table}
        ORDER BY id;
        """

        contexts = self.db.execute_query(query_sql)
        self.logger.info(f"共 {len(contexts)} 条记录需要处理")

        processed = 0
        updated = 0
        inserted = 0
        skipped = 0

        for ctx in contexts:
            ctx_id, relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id, \
            merchant_id, scene_type, base_scene_code = ctx

            # 查询匹配的 merchant_goods_code
            merchant_goods_codes = self._query_merchant_goods_codes(
                merchant_id, base_scene_code, upgrade_goods_id
            )

            if not merchant_goods_codes:
                # 没有匹配到,跳过,进入第二轮
                skipped += 1
                continue

            # 处理匹配结果
            if len(merchant_goods_codes) == 1:
                # 只有一条,更新原记录
                code = merchant_goods_codes[0]
                self._update_original_record(relation_id, code, 'MERCHANT_GOODS_REF')
                updated += 1
            else:
                # 多条,原记录更新第一条,其余复制插入
                first_code = merchant_goods_codes[0]
                self._update_original_record(relation_id, first_code, 'MERCHANT_GOODS_REF')
                updated += 1

                for code in merchant_goods_codes[1:]:
                    self._insert_copy_record(
                        relation_id, rule_type, goods_type_group_rule_id, code, 'MERCHANT_GOODS_REF'
                    )
                    inserted += 1

            processed += 1
            if processed % 100 == 0:
                self.logger.info(f"  已处理 {processed}/{len(contexts)} 条")

        self.logger.info(f"第一轮补数完成:处理 {processed} 条,更新 {updated} 条,插入 {inserted} 条,跳过 {skipped} 条")

    def _query_merchant_goods_codes(self, merchant_id, base_scene_code, upgrade_goods_id):
        """
        查询商户商品编码

        Args:
            merchant_id: 商户ID
            base_scene_code: 细分场景编码
            upgrade_goods_id: 升级商品ID

        Returns:
            list: merchant_goods_code 列表,按 id 排序
        """
        query_sql = f"""
        SELECT DISTINCT mgi.merchant_goods_code
        FROM dj_car_life_merchant_goods_info mgi
        JOIN dj_car_life_merchant_goods_ref mgr
          ON mgr.merchant_goods_id = mgi.id
         AND mgr.deleted_flag = 'N'
         AND mgr.merchant_id = {merchant_id}
        WHERE mgi.deleted_flag = 'N'
          AND mgi.upgrade_goods_id = {upgrade_goods_id}
          AND mgi.base_scene_code = '{base_scene_code}'
          AND mgi.merchant_goods_code IS NOT NULL
          AND mgi.merchant_goods_code != ''
        ORDER BY mgi.id, mgi.merchant_goods_code;
        """

        results = self.db.execute_query(query_sql)
        return [row[0] for row in results]

    def _update_original_record(self, relation_id, merchant_goods_code, source_type):
        """更新原记录的 merchant_goods_code"""
        update_sql = f"""
        UPDATE dj_car_life_goods_type_group_relation
        SET merchant_goods_code = '{merchant_goods_code}',
            updated_by = '{DATA_MIGRATION_USER}',
            updated_date = NOW()
        WHERE id = {relation_id};
        """

        if self.db.execute_update(update_sql):
            # 记录到明细表
            self._log_detail(relation_id, merchant_goods_code, source_type, 'UPDATE_ORIGIN', None)

    def _insert_copy_record(self, relation_id, rule_type, goods_type_group_rule_id,
                           merchant_goods_code, source_type):
        """复制插入新记录"""
        # 先检查是否已存在
        check_sql = f"""
        SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
        WHERE deleted_flag = 'N'
          AND rule_type = {rule_type}
          AND goods_type_group_rule_id = {goods_type_group_rule_id}
          AND category_type = 2
          AND merchant_goods_code = '{merchant_goods_code}';
        """
        result = self.db.execute_query_one(check_sql)
        if result and result[0] > 0:
            # 已存在,跳过
            self._log_detail(relation_id, merchant_goods_code, source_type, 'SKIP', '已存在相同记录')
            return

        # 复制插入
        insert_sql = f"""
        INSERT INTO dj_car_life_goods_type_group_relation
        (rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
         merchant_goods_code, goods_type, goods_type_name, package_code, package_name,
         deleted_flag, created_by, created_date, updated_by, updated_date)
        SELECT
            rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id,
            '{merchant_goods_code}' AS merchant_goods_code,
            goods_type, goods_type_name, package_code, package_name,
            deleted_flag, '{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW()
        FROM dj_car_life_goods_type_group_relation
        WHERE id = {relation_id};
        """

        if self.db.execute_update(insert_sql):
            self._log_detail(relation_id, merchant_goods_code, source_type, 'INSERT_COPY', None)

    def _log_detail(self, relation_id, merchant_goods_code, source_type, action_type, skip_reason):
        """记录补数明细"""
        # 查询上下文信息
        query_sql = f"""
        SELECT rule_type, goods_type_group_rule_id, upgrade_goods_id,
               merchant_id, scene_type, base_scene_code
        FROM {self.context_table}
        WHERE relation_id = {relation_id}
        LIMIT 1;
        """
        result = self.db.execute_query_one(query_sql)
        if not result:
            return

        rule_type, goods_type_group_rule_id, upgrade_goods_id, \
        merchant_id, scene_type, base_scene_code = result

        skip_reason_str = f"'{skip_reason}'" if skip_reason else 'NULL'

        insert_sql = f"""
        INSERT INTO {self.detail_table}
        (relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id,
         merchant_id, scene_type, base_scene_code, merchant_goods_code,
         source_type, action_type, skip_reason)
        VALUES ({relation_id}, {rule_type}, {goods_type_group_rule_id}, {upgrade_goods_id},
                {merchant_id}, {scene_type}, '{base_scene_code}', '{merchant_goods_code}',
                '{source_type}', '{action_type}', {skip_reason_str});
        """
        self.db.execute_update(insert_sql)

    def round2_fill_from_order_history(self):
        """
        第二轮补数:从历史订单补下架商品
        注意:第一轮已补的记录,如果订单中还有其他merchant_goods_code,第二轮仍需补充
        """
        self.logger.info("=" * 80)
        self.logger.info("第二轮补数:从历史订单补齐...")

        # 查询所有上下文记录(包括第一轮已处理的)
        query_sql = f"""
        SELECT ctx.id, ctx.relation_id, ctx.rule_type, ctx.goods_type_group_rule_id,
               ctx.upgrade_goods_id, ctx.merchant_id, ctx.scene_type, ctx.base_scene_code,
               ctx.settle_rule_id, ctx.division_rule_id, ctx.reconciliation_rule_id
        FROM {self.context_table} ctx
        ORDER BY ctx.id;
        """

        contexts = self.db.execute_query(query_sql)
        self.logger.info(f"共 {len(contexts)} 条记录需要检查订单补齐")

        processed = 0
        updated = 0
        inserted = 0
        skipped = 0

        for ctx in contexts:
            ctx_id, relation_id, rule_type, goods_type_group_rule_id, upgrade_goods_id, \
            merchant_id, scene_type, base_scene_code, settle_rule_id, division_rule_id, \
            reconciliation_rule_id = ctx

            # 根据规则类型查询订单中的 merchant_goods_code
            if rule_type == 1:
                # 财务规则
                merchant_goods_codes = self._query_order_goods_codes_finance(
                    settle_rule_id, division_rule_id, base_scene_code, upgrade_goods_id
                )
            else:
                # 对账规则
                merchant_goods_codes = self._query_order_goods_codes_reconciliation(
                    reconciliation_rule_id, base_scene_code, upgrade_goods_id
                )

            if not merchant_goods_codes:
                # 订单中没有找到,检查第一轮是否已处理
                first_round_processed = self._check_first_round_processed(relation_id)
                if not first_round_processed:
                    # 第一轮也没处理,记录异常
                    self._log_exception(relation_id, 'NO_MERCHANT_GOODS_CODE',
                                       '两轮补数均未找到匹配的merchant_goods_code')
                skipped += 1
                continue

            # 处理订单中找到的 merchant_goods_code
            for code in merchant_goods_codes:
                # 检查是否已存在(包括第一轮补的和已有的)
                if self._check_merchant_goods_code_exists(rule_type, goods_type_group_rule_id, code):
                    # 已存在,跳过
                    self._log_detail(relation_id, code, 'ORDER_HISTORY', 'SKIP', '已存在相同记录')
                    continue

                # 检查原记录是否已有 merchant_goods_code
                original_has_code = self._check_original_has_code(relation_id)

                if not original_has_code:
                    # 原记录还没有 merchant_goods_code,更新原记录
                    self._update_original_record(relation_id, code, 'ORDER_HISTORY')
                    updated += 1
                else:
                    # 原记录已有 merchant_goods_code,复制插入新记录
                    self._insert_copy_record(
                        relation_id, rule_type, goods_type_group_rule_id, code, 'ORDER_HISTORY'
                    )
                    inserted += 1

            processed += 1
            if processed % 100 == 0:
                self.logger.info(f"  已处理 {processed}/{len(contexts)} 条")

        self.logger.info(f"第二轮补数完成:处理 {processed} 条,更新 {updated} 条,插入 {inserted} 条,跳过 {skipped} 条")

    def _check_first_round_processed(self, relation_id):
        """检查第一轮是否已处理"""
        query_sql = f"""
        SELECT COUNT(*) FROM {self.detail_table}
        WHERE relation_id = {relation_id}
          AND action_type IN ('UPDATE_ORIGIN', 'INSERT_COPY');
        """
        result = self.db.execute_query_one(query_sql)
        return result and result[0] > 0

    def _check_merchant_goods_code_exists(self, rule_type, goods_type_group_rule_id, merchant_goods_code):
        """检查指定的 merchant_goods_code 是否已存在"""
        check_sql = f"""
        SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
        WHERE deleted_flag = 'N'
          AND rule_type = {rule_type}
          AND goods_type_group_rule_id = {goods_type_group_rule_id}
          AND category_type = 2
          AND merchant_goods_code = '{merchant_goods_code}';
        """
        result = self.db.execute_query_one(check_sql)
        return result and result[0] > 0

    def _check_original_has_code(self, relation_id):
        """检查原记录是否已有 merchant_goods_code"""
        query_sql = f"""
        SELECT merchant_goods_code FROM dj_car_life_goods_type_group_relation
        WHERE id = {relation_id};
        """
        result = self.db.execute_query_one(query_sql)
        if result and result[0]:
            code = result[0].strip()
            return code != ''
        return False

    def _query_order_goods_codes_finance(self, settle_rule_id, division_rule_id,
                                        base_scene_code, upgrade_goods_id):
        """从订单查询财务规则的商品编码"""
        query_sql = f"""
        SELECT DISTINCT sub.merchant_goods_code
        FROM dj_car_life_goods_order ord
        JOIN dj_car_life_goods_sub_order sub
          ON sub.order_code = ord.order_code
         AND sub.deleted_flag = 'N'
         AND sub.upgrade_goods_id = {upgrade_goods_id}
         AND sub.merchant_goods_code IS NOT NULL
         AND sub.merchant_goods_code != ''
        WHERE ord.deleted_flag = 'N'
          AND ord.specify_account_rule_id = {settle_rule_id}
          AND ord.specify_division_rule_id = {division_rule_id}
          AND ord.base_scene_code = '{base_scene_code}'
        ORDER BY sub.merchant_goods_code;
        """

        results = self.db.execute_query(query_sql)
        return [row[0] for row in results]

    def _query_order_goods_codes_reconciliation(self, reconciliation_rule_id,
                                               base_scene_code, upgrade_goods_id):
        """从订单查询对账规则的商品编码"""
        query_sql = f"""
        SELECT DISTINCT sub.merchant_goods_code
        FROM dj_car_life_goods_order ord
        JOIN dj_car_life_goods_sub_order sub
          ON sub.order_code = ord.order_code
         AND sub.deleted_flag = 'N'
         AND sub.upgrade_goods_id = {upgrade_goods_id}
         AND sub.merchant_goods_code IS NOT NULL
         AND sub.merchant_goods_code != ''
        WHERE ord.deleted_flag = 'N'
          AND ord.specify_reconciliation_rule_id = {reconciliation_rule_id}
          AND ord.base_scene_code = '{base_scene_code}'
        ORDER BY sub.merchant_goods_code;
        """

        results = self.db.execute_query(query_sql)
        return [row[0] for row in results]

    def _log_exception(self, relation_id, exception_type, exception_desc):
        """记录异常"""
        insert_sql = f"""
        INSERT INTO {self.exception_table}
        (relation_id, exception_type, exception_desc)
        VALUES ({relation_id}, '{exception_type}', '{exception_desc}');
        """
        self.db.execute_update(insert_sql)

    def validate_results(self):
        """验证补数结果"""
        self.logger.info("=" * 80)
        self.logger.info("验证补数结果...")

        # 1. 仍未补齐的记录
        query_sql = """
        SELECT rule_type, COUNT(*) as cnt
        FROM dj_car_life_goods_type_group_relation
        WHERE deleted_flag = 'N'
          AND category_type = 2
          AND upgrade_goods_id IS NOT NULL
          AND (merchant_goods_code IS NULL OR merchant_goods_code = '')
        GROUP BY rule_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning("仍未补齐的记录:")
            for row in results:
                self.logger.warning(f"  rule_type={row[0]}: {row[1]} 条")
        else:
            self.logger.info("所有记录已补齐")

        # 2. 同一规则分组下重复商品编码
        query_sql = """
        SELECT rule_type, goods_type_group_rule_id, merchant_goods_code, COUNT(*) as cnt
        FROM dj_car_life_goods_type_group_relation
        WHERE deleted_flag = 'N'
          AND category_type = 2
          AND merchant_goods_code IS NOT NULL
          AND merchant_goods_code != ''
        GROUP BY rule_type, goods_type_group_rule_id, merchant_goods_code
        HAVING COUNT(*) > 1;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning(f"发现 {len(results)} 组重复商品编码")
        else:
            self.logger.info("未发现重复商品编码")

        # 3. 统计补数明细
        query_sql = f"""
        SELECT source_type, action_type, COUNT(*) as cnt
        FROM {self.detail_table}
        GROUP BY source_type, action_type
        ORDER BY source_type, action_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.info("补数明细统计:")
            for row in results:
                self.logger.info(f"  {row[0]} - {row[1]}: {row[2]} 条")

        # 4. 统计异常
        query_sql = f"""
        SELECT exception_type, COUNT(*) as cnt
        FROM {self.exception_table}
        GROUP BY exception_type;
        """
        results = self.db.execute_query(query_sql)
        if results:
            self.logger.warning("异常统计:")
            for row in results:
                self.logger.warning(f"  {row[0]}: {row[1]} 条")

    def export_exception_report(self, output_file='merchant_goods_code_exceptions.csv'):
        """导出异常报告"""
        self.logger.info(f"导出异常报告到 {output_file}...")

        query_sql = f"""
        SELECT
            exc.relation_id,
            gtgr.rule_type,
            gtgr.goods_type_group_rule_id,
            gtgr.upgrade_goods_id,
            exc.exception_type,
            exc.exception_desc,
            exc.created_date
        FROM {self.exception_table} exc
        JOIN dj_car_life_goods_type_group_relation gtgr
          ON gtgr.id = exc.relation_id
        ORDER BY exc.id;
        """

        results = self.db.execute_query(query_sql)

        if not results:
            self.logger.info("没有异常记录")
            return

        import csv
        with open(output_file, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(['relation_id', 'rule_type', 'goods_type_group_rule_id',
                           'upgrade_goods_id', 'exception_type', 'exception_desc', 'created_date'])
            writer.writerows(results)

        self.logger.info(f"异常报告已导出,共 {len(results)} 条")