audit_deduction.py 6.69 KB
import pandas as pd
import yaml
import os

from sqlalchemy import create_engine
import pymysql


def get_config():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # 向上寻找直到找到 project 目录
    # config.yaml 在 ../../../config.yaml
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))
    config_path = os.path.join(base_dir, "config.yaml")
    
    # 如果找不到,尝试直接在上级目录找(兼容调试)
    if not os.path.exists(config_path):
        base_dir = os.path.dirname(os.path.dirname(current_dir))
        config_path = os.path.join(base_dir, "config.yaml")

    with open(config_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

def get_db_url(db_config):
    return f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['db_name']}?charset={db_config['charset']}"


def get_query_condition(year, table_name):
    """
    获取查询条件
    :param year: 年份
    :param table_name: 表名
    :return: SQL 查询条件字符串
    """
    if year >= 2025:
        return f"batch = '{year}'"
    else:
        start_time = f"{year}-00"
        end_time = f"{year + 1}-00"
        
        # t_eshield_device 在 2025 年之前没有时间过滤逻辑
        if table_name == 't_eshield_device':
            return "1=1"
            
        return f"settle_time > '{start_time}' and settle_time < '{end_time}'"


def process_audit_deduction(year):
    """
    执行审计抵扣逻辑
    :param year: 年份,如 2024
    """
    config = get_config()
    db_conf = config['database']['device_detail_db']
    engine = create_engine(get_db_url(db_conf))

    start_time = f"{year}-00"
    end_time = f"{year + 1}-00"
    
    # 定义表名
    receivables_out_table = 't_eshield_receivables'
    device_table = 't_eshield_device'
    device_detail_table = 't_eshield_device_detail'
    renewal_table = 'd_eshield_renewal'

    print(f"开始执行 {year} 年的审计抵扣计算流程...")
    print(f"时间范围: {start_time} < settle_time < {end_time}")

    # 从 t_eshield_receivables 表中获取数量和结算商户以及结算时间
    receivables_condition = get_query_condition(year, receivables_out_table)
    receivables = pd.read_sql(f"SELECT settle_merchant, sum(num) as Valuation_Quantity FROM "
                              f" {receivables_out_table} where num>0 and {receivables_condition}  group by settle_merchant", con=engine)


    # 从设备表中获取数据
    device_condition = get_query_condition(year, device_table)
    # 如果条件不为空(例如 1=1 或 batch='...'),则添加 WHERE 子句
    # 注意:如果 device_condition 是 "1=1",加上去也没问题
    raw_dev_df = pd.read_sql(f'SELECT sn,max(device_type) as device_type,'
                             ' max(delivery_time) as delivery_time,'
                             ' max(delivery_merchant) as delivery_merchant, '
                             ' max(active_time) as active_time,'
                             ' max(active_merchant) as active_merchant,'
                             f' max(classid) as classid FROM {device_table} WHERE {device_condition} group by sn', con=engine)

    devices = pd.DataFrame()


    device_detail_condition = get_query_condition(year, device_detail_table)
    # receivables_out 在 join 子查询中也需要应用条件
    # 注意:这里的 receivables_out 子查询和上面的 receivables 查询略有不同(上面有 sum(num)),这里是 SELECT *
    receivables_sub_condition = get_query_condition(year, receivables_out_table)
    
    devices = pd.read_sql(f"\
        select\
    A.*\
    from (\
            SELECT * FROM {device_detail_table} WHERE   {device_detail_condition} ) A left join (select * from {receivables_out_table} WHERE   {receivables_sub_condition}  ) B\
            on substring(A.settle_time,1,7) = B.settle_time and A. settle_merchant = B.settle_merchant and A.device_price = B.device_price\
                and A.service_price=B.service_price", con=engine)

    result_df = pd.merge(devices[['sn','device_period','settle_merchant','device_type','settle_time','device_price','install_price','from_type']], raw_dev_df[['sn','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')

    # 创建 t_eshield_device_detail_output 表,并将结果保存到该表中
    dev=result_df[['sn','device_type','delivery_time','delivery_merchant'
        ,'active_time','active_merchant','device_period','settle_merchant'
        ,'settle_time','device_price','install_price'
        ,'from_type','classid'
                 ]]
    target_device_detail_table = 't_eshield_device_detail_'+str(year)+'_output'
    dev.to_sql(target_device_detail_table, con=engine, if_exists='replace', index=False)
    print(f"已生成表: {target_device_detail_table}")


    # 从续费明细表中获取数据
    renewal_condition = get_query_condition(year, renewal_table)
    renewal_df = pd.read_sql(f"SELECT * FROM {renewal_table} where {renewal_condition} ", con=engine)


    devices.rename(columns={'device_period':'service_period'},inplace=True)
    services=devices[devices['service_price']!=0]

    # 服务信息表整合
    # 设备服务
    dev_service_res_df = pd.merge(services[['sn','device_type','service_period','settle_merchant','settle_time','service_price','from_type']],
                              raw_dev_df[['sn','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')
    # 续费
    renewal_res_df = pd.merge(renewal_df[['sn','service_period','settle_merchant','settle_time','service_price','from_type']],
                              raw_dev_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')



    df1 = dev_service_res_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant'
        ,'service_period','settle_merchant'
        ,'settle_time'
        ,'service_price','from_type','classid']]


    df2 = renewal_res_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant'
        ,'service_period','settle_merchant'
        ,'settle_time'
        ,'service_price','from_type','classid']]


    merge_df = pd.concat([df1,df2])
    target_service_detail_table = 't_eshield_service_detail_'+str(year)+'_output'
    merge_df.to_sql(target_service_detail_table, con=engine, if_exists='replace', index=False)
    print(f"已生成表: {target_service_detail_table}")
    
    print(f"{year} 年审计抵扣流程执行完毕!")

if __name__ == "__main__":
    # 示例调用
    process_audit_deduction(2024)