sync_audit_basic_data.py 18.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
# -*- coding: utf-8 -*-
import sys
import os
import pymysql
import logging
import datetime
import random
import argparse

import yaml

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("sync_audit_basic_data.log", encoding='utf-8')
    ]
)
logger = logging.getLogger(__name__)

def get_config():
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    config_path = os.path.join(base_dir, "config.yaml")
    if os.path.exists(config_path):
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    return {}

config = get_config()
db_config = config.get("database", {})

# Configs
TARGET_DB_CONFIG = {
    'host': db_config.get('dijia_db', {}).get('host'),
    'port': db_config.get('dijia_db', {}).get('port'),
    'user': db_config.get('dijia_db', {}).get('user'),
    'passwd': db_config.get('dijia_db', {}).get('password'),
    'db': db_config.get('dijia_db', {}).get('db_name'),
    'charset': db_config.get('dijia_db', {}).get('charset')
}

SOURCE_DB_CONFIG = {
    'host': db_config.get('glsx_dj_db', {}).get('host'),
    'port': db_config.get('glsx_dj_db', {}).get('port'),
    'user': db_config.get('glsx_dj_db', {}).get('user'),
    'passwd': db_config.get('glsx_dj_db', {}).get('password'),
    'db': db_config.get('glsx_dj_db', {}).get('db_name'),
    'charset': db_config.get('glsx_dj_db', {}).get('charset')
}

if not all(TARGET_DB_CONFIG.values()) or not all(SOURCE_DB_CONFIG.values()):
    logger.error("Database configuration missing or incomplete in config.yaml")
    sys.exit(1)

def get_connection(config):
    return pymysql.connect(
        host=config['host'],
        port=config['port'],
        user=config['user'],
        password=config['passwd'],
        db=config['db'],
        charset=config['charset'],
        cursorclass=pymysql.cursors.DictCursor
    )

def get_distinct_merchants(target_conn, year):
    table_name = f"dj_{year}_settlment_order"
    
    # Check if table exists
    with target_conn.cursor() as cursor:
        cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
        if not cursor.fetchone():
            logger.error(f"Table {table_name} does not exist in target DB.")
            return []
            
    sql = f"""
    select DISTINCT a.cus_name 
    from {table_name} a
    WHERE a.business_type = 'SAAS系统订阅服务—旧版本' 
    AND a.cus_name NOT IN ('东台宝通汽车服务有限责任公司', '广汇汽车服务有限责任公司东台分公司', '广汇汽车服务有限责任公司天津武清分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司')
    """
    
    logger.info(f"Executing query to find merchants in {table_name}...")
    with target_conn.cursor() as cursor:
        cursor.execute(sql)
        results = cursor.fetchall()
    
    return [row['cus_name'] for row in results if row['cus_name']]

def get_merchant_from_target(target_conn, merchant_name):
    # Try to find by settle_merchant_name in target
    sql = "SELECT * FROM dj_system_merchant WHERE settle_merchant_name = %s LIMIT 1"
    with target_conn.cursor() as cursor:
        cursor.execute(sql, (merchant_name,))
        result = cursor.fetchone()
    return result

def update_merchant_in_target(target_conn, merchant_data, target_id):
    if 'id' in merchant_data:
        del merchant_data['id']
        
    # We shouldn't update merchant_id if it might cause conflict, 
    # but for now let's try to update everything except created/updated fields if they shouldn't change
    # actually we usually update everything from source to keep in sync
    
    keys = list(merchant_data.keys())
    set_clause = ', '.join([f"`{k}` = %s" for k in keys])
    values = [merchant_data[k] for k in keys]
    values.append(target_id)
    
    sql = f"UPDATE dj_system_merchant SET {set_clause} WHERE id = %s"
    
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(sql, values)
        target_conn.commit()
        logger.info(f"Successfully updated merchant: {merchant_data.get('merchant_name')} (ID: {target_id})")
        return True
    except Exception as e:
        logger.error(f"Failed to update merchant {merchant_data.get('merchant_name')}: {e}")
        target_conn.rollback()
        return False

def get_merchant_from_source(source_conn, merchant_name):
    # Try to find by merchant_name in source
    # Source table is also dj_system_merchant
    sql = "SELECT * FROM dj_system_merchant WHERE merchant_name = %s LIMIT 1"
    with source_conn.cursor() as cursor:
        cursor.execute(sql, (merchant_name,))
        result = cursor.fetchone()
    return result

def get_max_merchant_id(target_conn):
    sql = "SELECT MAX(merchant_id) as max_id FROM dj_system_merchant"
    with target_conn.cursor() as cursor:
        cursor.execute(sql)
        result = cursor.fetchone()
        return result['max_id'] if result and result['max_id'] else 1000000

def generate_fake_merchant(merchant_name, next_merchant_id, year):
    # Generate random contact name
    surnames = ['张', '李', '王', '赵', '刘', '陈', '杨', '黄', '周', '吴']
    names = ['伟', '芳', '娜', '秀英', '敏', '静', '丽', '强', '军', '杰', '磊', '洋', '勇', '艳']
    contact_name = random.choice(surnames) + random.choice(names)
    
    # Generate random phone
    phone = f"1{random.choice(['3', '5', '7', '8', '9'])}{random.randint(100000000, 999999999)}"
    
    return {
        'merchant_id': next_merchant_id,
        'account_name': f"user_{next_merchant_id}",
        'merchant_name': merchant_name,
        'short_name': merchant_name[:20],
        'user_type': 2,
        'merchant_type': 2,
        'contact_name': contact_name,
        'phone': phone,
        'channel_id': 0,
        'address': f"{merchant_name}附近",
        'province_id': 0,
        'province_name': '',
        'city_id': 0,
        'city_name': '',
        'area_id': 0,
        'area_name': '',
        'lng': 0.0,
        'lat': 0.0,
        'shop_photo': '',
        'business_hours': '',
        'parent_merchant_id': 0,
        'parent_merchant_name': '',
        'svr_merchant_id': 0,
        'settle_merchant_name': merchant_name,
        'svr_merchant_name': '',
        'created_by': f'admin_wxz_{year}',
        'created_date': datetime.datetime.now(),
        'updated_by': f'audio_wxz_{year}',
        'updated_date': datetime.datetime.now(),
        'deleted_flag': 'N'
    }

def insert_merchant_into_target(target_conn, merchant_data):
    if 'id' in merchant_data:
        del merchant_data['id']
        
    keys = list(merchant_data.keys())
    columns = ', '.join([f"`{k}`" for k in keys])
    placeholders = ', '.join(['%s'] * len(keys))
    values = [merchant_data[k] for k in keys]
    
    sql = f"INSERT INTO dj_system_merchant ({columns}) VALUES ({placeholders})"
    
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(sql, values)
        target_conn.commit()
        logger.info(f"Successfully inserted merchant: {merchant_data.get('merchant_name')} (ID: {merchant_data.get('merchant_id')})")
        return True
    except pymysql.err.IntegrityError as e:
        logger.warning(f"Integrity error for {merchant_data.get('merchant_name')}: {e}. Skipping.")
        target_conn.rollback()
        return False
    except Exception as e:
        logger.error(f"Failed to insert merchant {merchant_data.get('merchant_name')}: {e}")
        target_conn.rollback()
        return False

def check_and_create_basic_device_info_table(target_conn, year):
    table_name = f"dj_{year}_basic_device_info"
    
    # Check if table exists
    with target_conn.cursor() as cursor:
        cursor.execute(f"SHOW TABLES LIKE '{table_name}'")
        if cursor.fetchone():
            logger.info(f"Table {table_name} already exists.")
            return True
            
    logger.info(f"Table {table_name} does not exist. Trying to create from previous year template.")
    
    # Try to find a previous year's table
    current_year_int = int(year)
    template_table = None
    
    # Check previous 5 years
    for y in range(current_year_int - 1, current_year_int - 6, -1):
        prev_table = f"dj_{y}_basic_device_info"
        with target_conn.cursor() as cursor:
            cursor.execute(f"SHOW TABLES LIKE '{prev_table}'")
            if cursor.fetchone():
                template_table = prev_table
                break
    
    if not template_table:
        logger.error(f"Could not find a template table for {table_name} (checked 5 years back).")
        return False
        
    logger.info(f"Using {template_table} as template for {table_name}")
    
    create_sql = f"CREATE TABLE {table_name} LIKE {template_table}"
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(create_sql)
        target_conn.commit()
        logger.info(f"Successfully created table {table_name}")
        return True
    except Exception as e:
        logger.error(f"Failed to create table {table_name}: {e}")
        return False

def sync_basic_device_info(target_conn, year):
    logger.info(f"Starting sync_basic_device_info for year {year}")
    
    # Ensure table exists
    if not check_and_create_basic_device_info_table(target_conn, year):
        logger.error("Skipping basic device info sync due to missing table.")
        return

    start_date = f"{year}-01-01"
    end_date = f"{int(year) + 1}-01-01"
    
    # 1. Sync current year basic device info
    # We truncate first to avoid duplicates if run multiple times
    target_table = f"dj_{year}_basic_device_info"
    truncate_sql = f"TRUNCATE TABLE {target_table}"
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(truncate_sql)
        target_conn.commit()
        logger.info(f"Truncated {target_table}")
    except Exception as e:
        logger.error(f"Failed to truncate {target_table}: {e}")
        return

    # SQL from requirement
    insert_sql = f"""
    insert into {target_table}(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc)
    select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
    from dj_{year}_settle_details where device_type =8 AND settle_time between '{start_date}' and '{end_date}'
    union
    select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
    from dj_{year}_settle_details_record where settle_time between '{start_date}' and '{end_date}'
    """
    
    try:
        logger.info(f"Executing insert for {target_table}...")
        with target_conn.cursor() as cursor:
            cursor.execute(insert_sql)
        target_conn.commit()
        logger.info(f"Successfully populated {target_table}")
    except Exception as e:
        logger.error(f"Failed to populate {target_table}: {e}")

    # 2. Sync history basic device info (dj_basic_device_info)
    # Note: This appends. 
    history_table = "dj_basic_device_info"
    logger.info(f"Syncing to {history_table}...")
    
    # Clean up old data by batch (using year as batch)
    delete_history_sql = f"DELETE FROM {history_table} WHERE batch = '{year}'"
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(delete_history_sql)
        target_conn.commit()
        logger.info(f"Deleted existing data in {history_table} for batch {year}")
    except Exception as e:
        logger.error(f"Failed to delete existing data in {history_table} for batch {year}: {e}")
        # Proceed with caution or return? Usually better to return to avoid duplicates if delete failed
        return
    
    history_insert_sql = f"""
    insert into {history_table}(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc,batch)
    select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0,'{year}'
    from dj_{year}_settle_details where device_type =8 AND settle_time between '{start_date}' and '{end_date}'
    union
    select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0,'{year}'
    from dj_{year}_settle_details_record where settle_time between '{start_date}' and '{end_date}'
    """
    
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(history_insert_sql)
        target_conn.commit()
        logger.info(f"Successfully inserted into {history_table}")
    except Exception as e:
        logger.error(f"Failed to insert into {history_table}: {e}")

    # 3. Sync return device details (dj_device_details_return)
    return_table = "dj_device_details_return"
    logger.info(f"Syncing to {return_table}...")
    
    # Delete existing data for the year range to avoid duplicates
    delete_sql = f"DELETE FROM {return_table} WHERE settle_time BETWEEN '{start_date}' AND '{end_date}'"
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(delete_sql)
        target_conn.commit()
        logger.info(f"Deleted existing data in {return_table} for range {start_date} to {end_date}")
    except Exception as e:
        logger.error(f"Failed to delete existing data in {return_table}: {e}")
        return
    
    return_insert_sql = f"""
    insert into {return_table}(channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost)
    select channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost
    from dj_{year}_settle_details_return
    """
    
    try:
        with target_conn.cursor() as cursor:
            cursor.execute(return_insert_sql)
        target_conn.commit()
        logger.info(f"Successfully inserted into {return_table}")
    except Exception as e:
        logger.error(f"Failed to insert into {return_table}: {e}")

def sync_merchants(target_conn, source_conn, year):
    """
    同步商户信息:
    1. 从目标数据库的年度结算单表中获取所有涉及的商户名称。
    2. 遍历每个商户:
       - 检查该商户是否已存在于目标数据库的商户表 (dj_system_merchant)。
       - 检查该商户是否存在于源数据库的商户表。
    3. 同步逻辑:
       - 如果目标库已存在该商户:
         - 若源库也有该商户数据,则用源库数据更新目标库(确保信息最新)。
       - 如果目标库不存在该商户:
         - 若源库有该商户数据,则从源库插入到目标库。
         - 若源库也没有该商户数据(可能是脏数据或测试数据),则生成伪造的商户数据并插入目标库,以保证外键完整性。
    """
    logger.info(f"Starting merchant sync for year {year}")
    try:
        # 获取本年度结算单中出现的所有去重商户名称
        merchants_to_sync = get_distinct_merchants(target_conn, year)
        logger.info(f"Found {len(merchants_to_sync)} merchants to sync for year {year}")
        
        # 获取当前目标库中最大的商户ID,用于生成伪造数据时的ID起始值
        current_max_id = get_max_merchant_id(target_conn)
        fake_id_counter = current_max_id + 1
        
        for name in merchants_to_sync:
            # 1. 在目标库中查找该商户是否存在
            target_merchant = get_merchant_from_target(target_conn, name)
            # 2. 在源库中查找该商户是否存在
            source_data = get_merchant_from_source(source_conn, name)
            
            if target_merchant:
                # 情况A: 目标库已有该商户 -> 执行更新操作
                if source_data:
                    logger.info(f"Updating existing merchant: {name}")
                    # 确保 settle_merchant_name 字段有值
                    if not source_data.get('settle_merchant_name'):
                        source_data['settle_merchant_name'] = name
                    # 使用源库的最新数据更新目标库
                    update_merchant_in_target(target_conn, source_data, target_merchant['id'])
            else:
                # 情况B: 目标库没有该商户 -> 执行插入操作
                if source_data:
                    # 子情况B1: 源库有数据 -> 正常同步插入
                    logger.info(f"Found in Source DB: {name}, Inserting...")
                    if not source_data.get('settle_merchant_name'):
                        source_data['settle_merchant_name'] = name
                    insert_merchant_into_target(target_conn, source_data)
                else:
                    # 子情况B2: 源库也没数据 -> 生成伪造数据插入
                    # 说明:结算单里有这个商户名,但商户表里没查到,可能是历史遗留或脏数据。
                    # 为了保证数据完整性(如外键约束或报表展示),需要生成一条占位记录。
                    logger.info(f"Not found in Source DB, generating fake data: {name}")
                    fake_data = generate_fake_merchant(name, fake_id_counter, year)
                    if insert_merchant_into_target(target_conn, fake_data):
                        fake_id_counter += 1
    except Exception as e:
        logger.error(f"Error in sync_merchants: {e}")

def main(year):
    logger.info(f"Starting audit basic data sync for year {year}")
    
    try:
        target_conn = get_connection(TARGET_DB_CONFIG)
        logger.info("Connected to Target DB")
    except Exception as e:
        logger.error(f"Failed to connect to Target DB: {e}")
        return

    try:
        source_conn = get_connection(SOURCE_DB_CONFIG)
        logger.info("Connected to Source DB")
    except Exception as e:
        logger.error(f"Failed to connect to Source DB: {e}")
        if target_conn.open: target_conn.close()
        return
    
    try:
        # 1. Sync Merchants,不在此处同步门店了,迁移到第4页签了
        # sync_merchants(target_conn, source_conn, year)
        
        # 2. Sync Basic Device Info & Returns
        sync_basic_device_info(target_conn, year)
                
    finally:
        if target_conn.open: target_conn.close()
        if source_conn.open: source_conn.close()
        logger.info("All tasks done.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Sync Merchant Info')
    parser.add_argument('--year', type=str, default='2024', help='Year for settlement order table')
    args = parser.parse_args()
    
    main(args.year)