caiwubatchsqlcreate.py 16.1 KB
import logging
import os
import py_compile
import sys

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect


sourcePro = 'U2605271648553410008,U2504200151069900018,MG2026052817061966004;U2605271648553410010,U2504200151069900020,MG2026052817062332335;U2605271648553410012,U2504200151069900021,MG2026052817062754084;U2605271648553410009,U2504200151069900019,MG2026052817063022180;U2605271648553410011,U2504200151069900022,MG2026052817063395392;U2605271648553410013,U2504200151069900023,MG2026052817063761667;U2605271803409840009,U2412251821196430010,MG2026052817064086554;U2605271803409840010,U2412251821196430010,MG2026052817064482035;U2605271803409840004,U2412251821196430012,MG2026052817064888089;U2605271803409840005,U2412251821196430011,MG2026052817065173670;U2605271803409840006,U2412251821196430011,MG2026052817065446954;U2605271803409840008,U2412251821196430013,MG2026052817065818331;U2605271701126020014,U2508041358033720010,MG2026052817070122836;U2605271701126020015,U2508041358033720010,MG2026052817070575408;U2605271701126020018,U2508041358033720012,MG2026052817070847367;U2605271701126020016,U2508041358033720011,MG2026052817071289830;U2605271701126020017,U2508041358033720011,MG2026052817071685491;U2605271701126020019,U2508041358033720013,MG2026052817071970155'
merchantIds = '44213763,44211844,44211644,44215210,44214154,44214992,44211914,44212690,44215713,44215543,44215196,44215197,44215198,44214232,44214387,44214026,44214027,44215415,44212653,44215413,44215414,44215092,44214755,44215099,44211600,44211853,44211889,44212129,44211651,44212813,44211825,44212814,44215373,44206253,44215106,44215187,44214837,44214899,44214946,44214951,44214966,44214742,44215186,44215188,44215190,44214923,44190589,44205697,44215189,44215182,44214025,44214382,44211664,44215212,44215081,44186335,44214157,44214435,44215407,44212635,44211870,44214590,44213783,44214053,44215240,44212964,44215351,44214137,44211085,44212978,44211623,44216458,44216457,44214101,44215271,44215611,44215422,44191926,44191990,44212443,44215124,44213999,44212127,44211698,44211700,44211699,44213218,44212434,44212233,44213988,44213785,44211894,44211937,44214180,44211893,44212085,44212091,44212770,44213746,44214135,44213741,44215262,44214407,44211749,44214379,44215644,44212793,44212307,44215474,44214538,44215147,44215442,44215534,44212050,44212048,44215563,44215126,44216506,44216505,44216508,44216552,44216507,44216734,44216696,44216813,44216807,44216851,44216969,44216998,44216815,44216971,44217075,44217186,44217111,44217135,44210094,44214930'

operator = 'wangxw_sql_202605285'
insertBatchSize = 500
outputSqlFile = 'caiwubatchsqlcreate_20260420.sql'

log_name = './log/djcardrenewal/handlemain.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)


class CaiWuBatchSqlCreate:
    def __init__(self, created_by, batch_size, connect_db=True):
        self.created_by = created_by
        self.batch_size = batch_size
        self.release_db_smartcarlife = MysqlHelper(DbConect.DB_saasadd_release_slave) if connect_db else None

    def close(self):
        if self.release_db_smartcarlife:
            self.release_db_smartcarlife.close_con()

    @staticmethod
    def _escape_sql(value):
        return str(value).replace("'", "''")

    @staticmethod
    def _parse_source_pairs(source_pro):
        pairs = []
        for item in source_pro.split(';'):
            pair_text = item.strip()
            if not pair_text:
                continue
            split_arr = pair_text.split(',')
            if len(split_arr) != 3:
                logging.warning("skip invalid pair: %s", pair_text)
                continue
            new_product_id = split_arr[0].strip()
            old_product_id = split_arr[1].strip()
            mg_product_code = split_arr[2].strip()
            if not new_product_id or not old_product_id:
                logging.warning("skip empty product pair: %s", pair_text)
                continue
            pairs.append((new_product_id, old_product_id, mg_product_code)) 
        return pairs

    @staticmethod
    def _normalize_merchant_ids(merchant_ids):
        id_arr = []
        for merchant_id in merchant_ids.split(','):
            mid = merchant_id.strip()
            if not mid:
                continue
            if not mid.isdigit():
                raise ValueError(f'invalid merchant id: {mid}')
            id_arr.append(mid)
        if not id_arr:
            raise ValueError('merchantIds is empty')
        return ','.join(id_arr)

    def _query_rule_type_1_rows(self, old_product_id, new_product_id, merchant_ids_sql, mg_product_code):
        old_safe = self._escape_sql(old_product_id)
        new_safe = self._escape_sql(new_product_id)
        sql = f"""
select a.id as goods_type_group_rule_id,
       dclug2.id as upgrade_goods_id,
       '{mg_product_code}' as mg_product_code
from (
      select dclgtg.id
      from dj_car_life_division_rule_effect_record dcldrer
               left join dj_car_life_merchant_goods_type_group_settle_rule dclmgtgsr
                         on dcldrer.rule_id = dclmgtgsr.settle_rule_id and dcldrer.deleted_flag = 'N'
               left join dj_car_life_goods_type_group dclgtg
                         on dclmgtgsr.goods_type_group_id = dclgtg.id and dclgtg.deleted_flag = 'N'
      where dcldrer.merchant_id in
            ({merchant_ids_sql})
        and dcldrer.scene_type = 0
        and dcldrer.base_scene_code  = '110201'
        and dcldrer.rule_type = 1
        and (effect_end_date is null
          or effect_end_date > now())
        and exists(select 1
                   from dj_car_life_goods_type_group_relation dclgtgr
                            left join dj_car_life_upgrade_goods dclug on dclug.id = dclgtgr.upgrade_goods_id
                   where dclgtgr.goods_type_group_rule_id = dclgtg.id
                     and dclgtgr.deleted_flag = 'N'
                     and dclgtgr.category_type = 2
                     and dclgtgr.rule_type = 1
                     and dclug.commodity_code = '{old_safe}')
    ) a
         left join dj_car_life_upgrade_goods dclug2
                   on dclug2.commodity_code in
                      ('{new_safe}')
where dclug2.id is not null
"""
        result = self.release_db_smartcarlife.execute_select(sql)
        return result if result else []

    def _query_rule_type_3_rows(self, old_product_id, new_product_id, merchant_ids_sql, mg_product_code):
        old_safe = self._escape_sql(old_product_id)
        new_safe = self._escape_sql(new_product_id)
        sql = f"""
select a.id as goods_type_group_rule_id,
       dclug2.id as upgrade_goods_id,
       '{mg_product_code}' as mg_product_code
from (
      select dclmgtgsr.id
      from dj_car_life_division_rule_effect_record dcldrer
               left join dj_car_life_merchant_goods_type_group_reconciliation_rule dclmgtgsr
                         on dcldrer.rule_id = dclmgtgsr.reconciliation_rule_id and dcldrer.deleted_flag = 'N'
      where dcldrer.merchant_id in
            ({merchant_ids_sql})
        and dcldrer.scene_type = 0
        and dcldrer.base_scene_code  = '110201'
        and dcldrer.rule_type = 3
        and (effect_end_date is null
          or effect_end_date > now())
        and exists(select 1
                   from dj_car_life_goods_type_group_relation dclgtgr
                            left join dj_car_life_upgrade_goods dclug on dclug.id = dclgtgr.upgrade_goods_id
                   where dclgtgr.goods_type_group_rule_id = dclmgtgsr.id
                     and dclgtgr.deleted_flag = 'N'
                     and dclgtgr.rule_type = 3
                     and dclgtgr.category_type = 2
                     and dclug.commodity_code = '{old_safe}')
    ) a
         left join dj_car_life_upgrade_goods dclug2
                   on dclug2.commodity_code in
                      ('{new_safe}')
where dclug2.id is not null
"""
        result = self.release_db_smartcarlife.execute_select(sql)
        return result if result else []

    def _rows_to_value_items(self, rows, rule_type):
        value_items = []
        for row in rows:
            goods_type_group_rule_id = row[0]
            upgrade_goods_id = row[1]
            mg_product_code = row[2]
            try:
                group_rule_id_num = int(goods_type_group_rule_id)
                upgrade_goods_id_num = int(upgrade_goods_id)
            except (TypeError, ValueError):
                logging.warning("skip invalid row(rule_type=%s): %s", rule_type, row)
                continue

            value_items.append(
                f"({rule_type}, {group_rule_id_num}, 2, {upgrade_goods_id_num}, '{mg_product_code}',"
                f"'{self.created_by}', now(), '{self.created_by}', now(), 'N')"
            )
        return value_items

    def _build_batch_insert_statements(self, value_items):
        if not value_items:
            return []

        insert_prefix = (
            "insert into dj_car_life_goods_type_group_relation("
            "rule_type, goods_type_group_rule_id, category_type, upgrade_goods_id, merchant_goods_code,"
            "created_by, created_date, updated_by, updated_date, deleted_flag)\nvalues"
        )

        statements = []
        for i in range(0, len(value_items), self.batch_size):
            batch_values = value_items[i:i + self.batch_size]
            values_sql = ',\n'.join(batch_values)
            statements.append(f"{insert_prefix}\n{values_sql};")
        return statements

    @staticmethod
    def _derive_output_file_name(output_file_name, rule_type):
        base_name = os.path.basename(output_file_name)
        root, ext = os.path.splitext(base_name)
        suffix = f"_rule_type_{rule_type}"
        if ext:
            return f"{root}{suffix}{ext}"
        return f"{root}{suffix}"

    @staticmethod
    def _ensure_parent_dir(file_path):
        parent = os.path.dirname(file_path)
        if parent and not os.path.exists(parent):
            os.makedirs(parent, exist_ok=True)

    @staticmethod
    def _write_sql_file(output_path, rule_type, value_items, statements):
        CaiWuBatchSqlCreate._ensure_parent_dir(output_path)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(f'-- finance/reconciliation batch insert sql (rule_type={rule_type})\n')
            f.write(f'-- generated rows: {len(value_items)}\n')
            f.write(f'-- statement count: {len(statements)}\n\n')
            for statement in statements:
                f.write(statement + '\n\n')

    def generate_sql_file(self, source_pro, merchant_ids, output_file_name):
        source_pairs = self._parse_source_pairs(source_pro)
        merchant_ids_sql = self._normalize_merchant_ids(merchant_ids)
        value_items_by_rule_type = {1: [], 3: []}

        for idx, product_pair in enumerate(source_pairs, start=1):
            new_product_id = product_pair[0]
            old_product_id = product_pair[1]
            mg_product_code = product_pair[2]
            print(f'[{idx}/{len(source_pairs)}] processing old={old_product_id}, new={new_product_id}, mg={mg_product_code}')

            rule_type_1_rows = self._query_rule_type_1_rows(old_product_id, new_product_id, merchant_ids_sql, mg_product_code)
            rule_type_3_rows = self._query_rule_type_3_rows(old_product_id, new_product_id, merchant_ids_sql, mg_product_code)

            rule_type_1_values = self._rows_to_value_items(rule_type_1_rows, 1)
            rule_type_3_values = self._rows_to_value_items(rule_type_3_rows, 3)

            value_items_by_rule_type[1].extend(rule_type_1_values)
            value_items_by_rule_type[3].extend(rule_type_3_values)

            print(
                f'  rule_type=1 rows: {len(rule_type_1_values)}, '
                f'rule_type=3 rows: {len(rule_type_3_values)}'
            )

        result = {}
        base_dir = os.path.dirname(__file__)
        for rule_type in (1, 3):
            derived_name = self._derive_output_file_name(output_file_name, rule_type)
            output_path = os.path.join(base_dir, derived_name)
            value_items = value_items_by_rule_type[rule_type]
            statements = self._build_batch_insert_statements(value_items)
            self._write_sql_file(output_path, rule_type, value_items, statements)
            result[rule_type] = {
                'file_path': output_path,
                'row_count': len(value_items),
                'statement_count': len(statements),
            }

        return result


def _verify_py_compile():
    py_compile.compile(__file__, doraise=True)
    print(f'py_compile ok: {__file__}')


def _local_minimal_validation(output_file_name):
    builder = CaiWuBatchSqlCreate(created_by='local_validate', batch_size=2, connect_db=False)
    try:
        base_dir = os.path.dirname(__file__)

        def write_case(case_output_file_name, value_items_by_rule_type):
            result = {}
            for rule_type in (1, 3):
                derived_name = builder._derive_output_file_name(case_output_file_name, rule_type)
                output_path = os.path.join(base_dir, derived_name)
                value_items = value_items_by_rule_type[rule_type]
                statements = builder._build_batch_insert_statements(value_items)
                builder._write_sql_file(output_path, rule_type, value_items, statements)
                result[rule_type] = {
                    'file_path': output_path,
                    'row_count': len(value_items),
                    'statement_count': len(statements),
                }
            return result

        case_1_value_items = {
            1: builder._rows_to_value_items([(10001, 20001), (10002, 20002)], 1),
            3: builder._rows_to_value_items([(30001, 40001)], 3),
        }
        result = write_case(output_file_name, case_1_value_items)

        for rule_type in (1, 3):
            file_path = result[rule_type]['file_path']
            if not os.path.exists(file_path):
                raise RuntimeError(f'local validation failed, file not found: {file_path}')
            if f'_rule_type_{rule_type}' not in os.path.basename(file_path):
                raise RuntimeError(f'local validation failed, bad file name: {file_path}')

        root, ext = os.path.splitext(output_file_name)
        case_2_output = f"{root}_empty_case{ext}" if ext else f"{root}_empty_case"
        case_2_value_items = {
            1: builder._rows_to_value_items([(11001, 21001)], 1),
            3: [],
        }
        empty_result = write_case(case_2_output, case_2_value_items)
        empty_rule_type_3_path = empty_result[3]['file_path']
        with open(empty_rule_type_3_path, 'r', encoding='utf-8') as f:
            header = [f.readline().strip(), f.readline().strip(), f.readline().strip()]
        if header[1] != '-- generated rows: 0' or header[2] != '-- statement count: 0':
            raise RuntimeError(f'local validation failed, empty header mismatch: {empty_rule_type_3_path}')

        print('local validation ok')
        return result
    finally:
        builder.close()


if __name__ == "__main__":
    print("sys config " + __name__)
    _verify_py_compile()

    if '--local-validate' in sys.argv:
        validate_result = _local_minimal_validation(outputSqlFile)
        for rule_type in (1, 3):
            info = validate_result[rule_type]
            print(f'rule_type={rule_type} generated file: {info["file_path"]}')
            print(f'rule_type={rule_type} generated rows: {info["row_count"]}')
            print(f'rule_type={rule_type} statement count: {info["statement_count"]}')
        raise SystemExit(0)

    builder = CaiWuBatchSqlCreate(created_by=operator, batch_size=insertBatchSize)
    try:
        result = builder.generate_sql_file(
            source_pro=sourcePro,
            merchant_ids=merchantIds,
            output_file_name=outputSqlFile
        )
        for rule_type in (1, 3):
            info = result[rule_type]
            print(f'rule_type={rule_type} generated file: {info["file_path"]}')
            print(f'rule_type={rule_type} generated rows: {info["row_count"]}')
            print(f'rule_type={rule_type} statement count: {info["statement_count"]}')
    finally:
        builder.close()