edun_sync.py 1.99 KB
import streamlit as st
import importlib.util
import os
import sys
import datetime

def load_module(module_name, file_path):
    module_dir = os.path.dirname(file_path)
    if module_dir not in sys.path:
        sys.path.insert(0, module_dir)
        
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

def show():
    st.info("将分摊计算结果同步到外部审计数据库。")
    
    # 动态加载 audit_calculation.py
    # 路径回退到 project/3-amortization_process/edun
    base_dir = os.path.dirname(os.path.abspath(__file__))
    project_dir = os.path.dirname(os.path.dirname(base_dir)) # project
    
    audit_calc_path = os.path.join(project_dir, "3-amortization_process", "edun", "audit_calculation.py")
    
    if not os.path.exists(audit_calc_path):
        st.error(f"找不到文件: {audit_calc_path}")
        return

    try:
        audit_module = load_module("audit_calculation", audit_calc_path)
        
        # 获取可用年份
        # 这里简单硬编码几个年份,或者默认当前年份
        current_year = datetime.datetime.now().year
        years = [current_year, current_year - 1, current_year - 2]
        selected_year = st.selectbox("选择年份", years, index=0)
        
        if st.button("开始同步"):
            with st.spinner(f"正在同步 {selected_year} 年数据..."):
                try:
                    # 调用同步函数
                    audit_module.sync_to_external_db(year=selected_year)
                    st.success(f"{selected_year} 年数据同步完成!")
                except Exception as e:
                    st.error(f"同步失败: {e}")
                    import traceback
                    st.code(traceback.format_exc())
                    
    except Exception as e:
        st.error(f"加载审计计算模块失败: {e}")
        import traceback
        st.code(traceback.format_exc())