dj-loadExcelData.py 12.5 KB
import pandas as pd
import pymysql
import yaml
import os

def get_config():
    # 路径更新:由于移动到了 dj 子文件夹,需要多跳一级目录
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    config_path = os.path.join(base_dir, "config.yaml")
    with open(config_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

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

g_pro_biz_dbcfg = {
    "host": db_config["host"],
    "port": db_config["port"],  
    "user": db_config["user"],
    "password": db_config["password"],
    "db": db_config["db_name"],
    "charset": db_config["charset"],
}


def loadFinnanceExcelToMysql(fileName, sheetName, year=2025):
    # tableName = "dj_2023_settlment_order_finance"
    # tableName = "dj_2024_settlment_order_finance"
    tableName = f"dj_{year}_settlment_order_finance"

    """将Excel表数据导入mysql"""
    conn_updata = pymysql.Connect(**g_pro_biz_dbcfg)

    # pd.set_option('display.max_columns', 40)
    data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
    # 清理列名空格
    data.columns = [str(c).strip() for c in data.columns]
    
    newData = data[
        [
            "单据类型",
            "单据编号",
            "业务日期",
            "客户",
            "渠道",
            "物料编码",
            "物料名称",
            "产品类型",
            "设备类型",
            "计价数量",
            "含税单价",
            "单价",
            "收入",
            "业务类型",
            "分摊期限",
            "成本金额",
        ]
    ]
    """
    newData.rename(columns={'单据类型': 'order_type', '单据编号':'order_no', '业务日期':'finance_time',
                                      '客户':'cus_name', '渠道':'sale_type', '物料编码':'product_code',
                            '物料名称':'product_name', '产品类型':'product_type', '设备类型':'device_type',
                            '计价数量':'total', '含税单价':'hw_unit_price_tax', '单价':'hw_unit_price',
                            '收入':'income', '业务类型':'business_type', '分摊期限':'hw_term'})
    """
    newData["含税单价"].fillna(0, inplace=True)
    newData["单价"].fillna(0, inplace=True)
    newData["收入"].fillna(0, inplace=True)
    newData["分摊期限"].fillna(0, inplace=True)
    newData["设备类型"].fillna("", inplace=True)
    newData["产品类型"].fillna("", inplace=True)
    newData["计价数量"].fillna(0, inplace=True)
    newData["业务类型"].fillna("", inplace=True)

    newData["物料名称"].fillna("", inplace=True)
    newData["物料编码"].fillna("", inplace=True)

    newData["单据类型"].fillna("", inplace=True)
    newData["单据编号"].fillna("", inplace=True)
    newData["业务日期"].fillna("", inplace=True)
    newData["客户"].fillna("", inplace=True)
    newData["渠道"].fillna("", inplace=True)
    newData["成本金额"].fillna(0, inplace=True)

    # print(newData.head())
    valueArr = []
    for idx in newData.index:
        hwPriceTax = newData.loc[idx, "含税单价"]
        hwPrice = newData.loc[idx, "单价"]
        value = (
            newData.loc[idx, "单据类型"],
            newData.loc[idx, "单据编号"],
            newData.loc[idx, "业务日期"],
            newData.loc[idx, "客户"],
            newData.loc[idx, "渠道"],
            newData.loc[idx, "物料编码"],
            newData.loc[idx, "物料名称"],
            newData.loc[idx, "产品类型"],
            newData.loc[idx, "设备类型"],
            newData.loc[idx, "计价数量"],
            hwPriceTax,
            hwPrice,
            newData.loc[idx, "收入"],
            newData.loc[idx, "业务类型"],
            newData.loc[idx, "分摊期限"],
            newData.loc[idx, "成本金额"],
        )
        # print(value)
        valueArr.append(value)

    cs = conn_updata.cursor()
    sql = (
        "insert into "
        + tableName
        + "(order_type,order_no,finance_time,cus_name,sale_type,product_code,"
        "product_name,product_type,device_type,total,hw_unit_price_tax,"
        "hw_unit_price,income,business_type,hw_term,cost) values "
        "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    )
    cs.executemany(sql, valueArr)
    conn_updata.commit()
    cs.close()


def loadDjExcelToMysql(fileName, sheetName, year=2025):
    # tableName = "dj_2023_settlment_order"
    # tableName = "dj_2024_settlment_order"
    tableName = f"dj_{year}_settlment_order"

    """将Excel表数据导入mysql"""
    conn_updata = pymysql.Connect(**g_pro_biz_dbcfg)
    data = pd.read_excel(fileName, sheet_name=sheetName, header=0)
    # 清理列名空格
    data.columns = [str(c).strip() for c in data.columns]
    
    newData = data[
        [
            "单据类型",
            "单据编号",
            "业务日期",
            "客户",
            "渠道",
            "物料编码",
            "物料名称",
            "产品类型",
            "设备类型",
            "计价数量",
            "含税单价",
            "单价",
            "硬件",
            "硬件税率",
            "服务(不含税)",
            "服务税率",
            "服务套餐",
            "收入",
            "业务类型",
            "分摊期限",
            "安装",
            "安装税率",
            "成本金额",
        ]
    ]
    newData["含税单价"].fillna(0, inplace=True)
    newData["单价"].fillna(0, inplace=True)
    newData["收入"].fillna(0, inplace=True)
    newData["分摊期限"].fillna(0, inplace=True)
    newData["硬件"].fillna(0, inplace=True)
    newData["硬件税率"].fillna(0, inplace=True)
    newData["服务(不含税)"].fillna(0, inplace=True)
    newData["服务税率"].fillna(0, inplace=True)
    newData["服务套餐"].fillna("", inplace=True)
    newData["产品类型"].fillna("", inplace=True)
    newData["设备类型"].fillna("", inplace=True)
    newData["安装"].fillna(0, inplace=True)
    newData["安装税率"].fillna(0, inplace=True)
    newData["成本金额"].fillna(0, inplace=True)

    # 替换剩余的 NaN 为 None,以兼容 MySQL
    newData = newData.where(pd.notnull(newData), None)

    # print(newData)
    valueArr = []
    for idx in newData.index:
        hwPriceTax = newData.loc[idx, "含税单价"]
        hwPrice = newData.loc[idx, "单价"]
        newHwPrice = newData.loc[idx, "硬件"]
        newHwTaxRate = newData.loc[idx, "硬件税率"]
        if newHwPrice != 0:
            hwPrice = newHwPrice
            hwPriceTax = newHwTaxRate
        pkPrice = newData.loc[idx, "服务(不含税)"]
        pkPriceRate = newData.loc[idx, "服务税率"]
        client = newData.loc[idx, "客户"].strip()
        value = (
            newData.loc[idx, "单据类型"],
            newData.loc[idx, "单据编号"],
            newData.loc[idx, "业务日期"],
            client,
            newData.loc[idx, "渠道"],
            newData.loc[idx, "物料编码"],
            newData.loc[idx, "物料名称"],
            newData.loc[idx, "产品类型"],
            newData.loc[idx, "设备类型"],
            newData.loc[idx, "计价数量"],
            hwPriceTax,
            hwPrice,
            pkPrice,
            pkPriceRate,
            newData.loc[idx, "服务套餐"],
            newData.loc[idx, "收入"],
            newData.loc[idx, "业务类型"],
            newData.loc[idx, "分摊期限"],
            newData.loc[idx, "分摊期限"],
            newData.loc[idx, "安装"],
            newData.loc[idx, "安装税率"],
            newData.loc[idx, "成本金额"],
        )
        # print(value)

        valueArr.append(value)

    cs = conn_updata.cursor()
    sql = (
        "insert into "
        + tableName
        + "(order_type,order_no,finance_time,cus_name,sale_type,product_code,"
        "product_name,product_type,device_type,total,hw_unit_price_tax,"
        "hw_unit_price,pk_unit_price,pk_unit_price_tax,pk_name,income,"
        "business_type,hw_term,pk_term,install_unit_price,install_unit_price_tax,cost) "
        "values "
        "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    )
    cs.executemany(sql, valueArr)
    conn_updata.commit()



def runScript():

    # 允许通过命令行参数传入路径 and 年份
    import sys
    import os
    
    filePath = None
    year = 2025  # 默认年份
    is_rerun = False
    
    if len(sys.argv) > 1:
        filePath = sys.argv[1]
        print(f"正在从指定目录加载数据: {filePath}")
        
    if len(sys.argv) > 2:
        try:
            year = int(sys.argv[2])
            print(f"指定年份: {year}")
        except ValueError:
            if sys.argv[2].lower() == "rerun":
                is_rerun = True
            else:
                print(f"⚠️ 警告:年份参数 '{sys.argv[2]}' 无效,将使用默认年份 {year}")

    if len(sys.argv) > 3:
        if sys.argv[3].lower() == "rerun":
            is_rerun = True

    if filePath:
        # 如果是重跑模式,尝试提取月份并删除已有数据
        if is_rerun:
            import re
            # 尝试从路径中匹配月份,例如 "2025年8月" or "08"
            month_match = re.search(r'(\d+)月', filePath)
            if month_match:
                month = int(month_match.group(1))
                print(f"[RERUN] 重跑模式已开启,准备删除 {year}年{month}月 的已有数据...")
                delete_data_by_month(year, month)
            else:
                print(f"[WARN] 警告:重跑模式开启,但无法从路径 '{filePath}' 中提取月份,跳过删除步骤。")

        # 检查目录下是否存在整合后的文件
        found_finance = False
        found_business = False
        found_channel = False
        
        for f in os.listdir(filePath):
             f_path = os.path.join(filePath, f)
             if not os.path.isfile(f_path) or f.startswith('~$'):
                 continue
             
             # 1. 财务文件 (带有 -财务 后缀)
             if f.endswith("-财务.xlsx") or f.endswith("-财务.xls"):
                 print(f"找到财务文件: {f}")
                 loadFinnanceExcelToMysql(f_path, "激活调整", year=year)
                 found_finance = True
             
             # 2. 商务文件 (带有 -商务 后缀)
             elif f.endswith("-商务.xlsx") or f.endswith("-商务.xls"):
                 print(f"找到商务文件: {f}")
                 loadDjExcelToMysql(f_path, "渠道应收单原表", year=year)
                 found_business = True
                 
             # 3. 渠道文件 (其他 Excel 文件)
             elif f.endswith(".xlsx") or f.endswith(".xls"):
                 print(f"找到渠道文件: {f}")
                 loadDjExcelToMysql(f_path, "渠道数据", year=year)
                 found_channel = True
        
        if not (found_finance or found_business or found_channel):
            print(f"⚠️ 警告:在目录 {filePath} 中未找到符合命名规则的整合文件。")
    else:
        pass



# 增加一个删除三张表指定月份的 finance_time 的数据的方法
def delete_data_by_month(year, month):
    """
    删除指定年月份的财务数据, 根据传入的年份和月份删除 dj_YYYY_settlment_order_finance and dj_YYYY_settlment_order 表的数据.
    """
    conn_updata = pymysql.Connect(**g_pro_biz_dbcfg)
    
    cs = conn_updata.cursor()
    
    table_finance = f"dj_{year}_settlment_order_finance"
    table_order = f"dj_{year}_settlment_order"
    
    month_str = f"{year}-{month:02d}"
    
    try:
        # 为了更精确地匹配月份,我们使用 DATE_FORMAT
        sql_delete_finance = f"DELETE FROM {table_finance} WHERE DATE_FORMAT(finance_time, '%Y-%m') = '{month_str}'"
        print(f"Executing: {sql_delete_finance}")
        cs.execute(sql_delete_finance)
        
        sql_delete_order = f"DELETE FROM {table_order} WHERE DATE_FORMAT(finance_time, '%Y-%m') = '{month_str}'"
        print(f"Executing: {sql_delete_order}")
        cs.execute(sql_delete_order)
        
        conn_updata.commit()
        print(f"成功删除 {table_finance} 和 {table_order} 中 {month_str} 的数据。")
        
    except Exception as e:
        conn_updata.rollback()
        print(f"删除数据时出错: {e}")
        
    finally:
        cs.close()
        conn_updata.close()


if __name__ == "__main__":
    runScript()
    print("done")

    #重跑删除本月数据,重跑时开启!!!
    # delete_data_by_month(2025, 8)