Spaces:
Paused
Paused
Update src/app.py
Browse files9 unmodified lines10111213141516171819202122232412 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273742 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911929 unmodified lines# --- 1. 資料庫基礎邏輯 ---DB_PATH = os.path.join(os.getcwd(), 'spv_management.db')def init_db():conn = sqlite3.connect(DB_PATH)c = conn.cursor()# 財務數據表c.execute('''CREATE TABLE IF NOT EXISTS finance_data(month INTEGER, type TEXT, construction REAL, loan REAL, admin REAL,PRIMARY KEY (month, type))''')# 工程階段表c.execute('''CREATE TABLE IF NOT EXISTS project_stages(id INTEGER PRIMARY KEY AUTOINCREMENT,stage_name TEXT, start_month INTEGER, duration INTEGER,12 unmodified linesconn.commit()conn.close()# --- 2. PDF 報表生成邏輯 ---def create_pdf_report(comp_df, eac, gap, loan_limit, total_budget):pdf = FPDF()pdf.add_page()pdf.set_font("Arial", 'B', 16)pdf.cell(200, 10, txt="SPV Financial Status Report", ln=True, align='C')pdf.set_font("Arial", size=12)pdf.ln(10)pdf.cell(200, 10, txt=f"Report Date: {datetime.date.today()}", ln=True)pdf.cell(200, 10, txt=f"Project Original Budget: {total_budget:,.0f} units", ln=True)pdf.cell(200, 10, txt=f"Bank Loan Limit: {loan_limit:,.0f} units", ln=True)pdf.cell(200, 10, txt=f"Estimated Cost at Completion (EAC): {eac:,.0f} units", ln=True)if gap < 0:pdf.set_text_color(255, 0, 0)pdf.cell(200, 10, txt=f"WARNING: Predicted Funding Gap: {abs(gap):,.0f} units", ln=True)else:pdf.set_text_color(0, 128, 0)pdf.cell(200, 10, txt=f"Status: Funding Healthy. Surplus: {gap:,.0f} units", ln=True)pdf.set_text_color(0, 0, 0)pdf.ln(10)pdf.set_font("Arial", 'B', 11)pdf.cell(20, 10, "Month", 1)pdf.cell(45, 10, "Budget Spend", 1)pdf.cell(45, 10, "Actual Spend", 1)pdf.cell(40, 10, "Variance", 1)pdf.cell(30, 10, "Overrun%", 1)pdf.ln()pdf.set_font("Arial", size=10)for _, row in comp_df.iterrows():pdf.cell(20, 10, str(int(row['month'])), 1)pdf.cell(45, 10, f"{row['construction_預算']:,.0f}", 1)2 unmodified linespdf.cell(30, 10, f"{row['超支率%']}%", 1)pdf.ln()return pdf.output(dest='S').encode('latin-1')# --- 3. 初始化 ---init_db()st.set_page_config(page_title="SPV 財務監控系統", layout="wide")st.title("🏗️ SPV 都更計畫財務監控 PRO")# --- 4. 側邊欄控制項 ---with st.sidebar:st.header("⚙️ 專案基礎設定")total_budget = st.number_input("專案總工程預算 (萬)", value=50000, step=1000)loan_limit = st.number_input("銀行總授信額度 (萬)", value=55000)alert_threshold = st.slider("超支紅字預警閾值 (%)", 0, 20, 5)st.divider()if st.button("🗑️ 清空並重設專案"):run_query("DELETE FROM finance_data", is_select=False)run_query("DELETE FROM project_stages", is_select=False)st.rerun()# --- 5. 分頁佈局 ---tab1, tab2, tab3 = st.tabs(["📋 專案維護與排程", "🔮 預算對照與缺口預測", "✍️ 實際數據錄入"])# --- Tab 1: 專案階段維護 ---with tab1:st.subheader("🛠️ 維護工程工項與里程碑")with st.expander("➕ 新增工項節點", expanded=True):c1, c2, c3 = st.columns(3)name = c1.text_input("工項名稱")s_m = c2.number_input("開始月份 (從0起算)", min_value=0, step=1)dur = c3.number_input("持續月數", min_value=1, step=1)cp = st.slider("工程支出佔比 (%)", 0, 100, 10)lp = st.slider("銀行撥款佔比 (%)", 0, 100, 10)if st.button("確認加入工項"):run_query("INSERT INTO project_stages (stage_name, start_month, duration, cost_pct, loan_draw_pct) VALUES (?,?,?,?,?)",(name, s_m, dur, cp, lp), is_select=False)st.rerun()stages_df = run_query("SELECT * FROM project_stages")if not stages_df.empty:st.write("目前工程清單")st.dataframe(stages_df, use_container_width=True)# 自動預算按鈕if st.button("🚀 根據工項自動生成每月預算基準線"):max_m = (stages_df['start_month'] + stages_df['duration']).max()run_query("DELETE FROM finance_data WHERE type='Budget'", is_select=False)for m in range(int(max_m)+1):c_val = sum([(total_budget * r['cost_pct']/100)/r['duration'] for _, r in stages_df.iterrows() if r['start_month'] <= m < r['start_month']+r['duration']])l_val = sum([total_budget * r['loan_draw_pct']/100 for _, r in stages_df.iterrows() if r['start_month'] == m])run_query("INSERT INTO finance_data (month, type, construction, loan, admin) VALUES (?,?,?,?,?)",(m+1, 'Budget', c_val, l_val, 50.0), is_select=False)st.success("預算 Baseline 生成成功!")# --- Tab 2: 監控與預測 ---with tab2:all_f = run_query("SELECT * FROM finance_data")if not all_f.empty:b_df = all_f[all_f['type'] == 'Budget'].sort_values('month')a_df = all_f[all_f['type'] == 'Actual'].sort_values('month')if not b_df.empty and not a_df.empty:comp = pd.merge(b_df, a_df, on='month', suffixes=('_預算', '_實際'))comp['支出差異'] = comp['construction_實際'] - comp['construction_預算']comp['超支率%'] = (comp['支出差異'] / comp['construction_預算'] * 100).round(1)# 缺口預測邏輯current_spent = a_df['construction'].sum()avg_overrun = comp['超支率%'].mean() / 100rem_budget = b_df[b_df['month'] > a_df['month'].max()]['construction'].sum()eac = current_spent + (rem_budget * (1 + avg_overrun))gap = loan_limit - eacst.subheader("🔮 資金缺口分析儀表板")k1, k2, k3 = st.columns(3)k1.metric("目前已累計支出", f"{current_spent:,.0f} 萬")k2.metric("預估完工總成本 (EAC)", f"{eac:,.0f} 萬", f"{eac - total_budget:,.1f} 萬", delta_color="inverse")k3.metric("預計資金餘絀/缺口", f"{gap:,.0f} 萬", "額度不足" if gap < 0 else "額度充足", delta_color="normal" if gap >= 0 else "inverse")if gap < 0:st.error(f"🚨 警告:依目前超支趨勢,專案結束將缺款 {abs(gap):,.0f} 萬。建議協商增貸。")st.write("### 📢 每月執行明細 (紅字預警)")def apply_style(val):color = 'red' if isinstance(val, float) and val > alert_threshold else 'black'return f'color: {color}'st.dataframe(comp.style.applymap(apply_style, subset=['超支率%']), use_container_width=True)# S-Curve 圖表fig = go.Figure()fig.add_trace(go.Scatter(x=comp['month'], y=comp['construction_預算'].cumsum(), name="預計累計支出", line=dict(dash='dash')))fig.add_trace(go.Scatter(x=comp['month'], y=comp['construction_實際'].cumsum(), name="實際累計支出", line=dict(color='red')))st.plotly_chart(fig, use_container_width=True)# 下載報表pdf_out = create_pdf_report(comp, eac, gap, loan_limit, total_budget)st.download_button("📥 下載正式 PDF 月報表", data=pdf_out, file_name=f"SPV_Report_{datetime.date.today()}.pdf", mime="application/pdf")else:st.info("請先生成預算並在『實際數據錄入』分頁填寫資料。")# --- Tab 3: 資料錄入 ---with tab3:st.subheader("✍️ 錄入當月實際執行額")with st.form("actual_input"):c1, c2, c3 = st.columns(3)m_val = c1.number_input("執行月份", min_value=1, step=1)cons_val = c2.number_input("實際工程支出 (萬)", value=0.0)loan_val = c3.number_input("實際撥款流入 (萬)", value=0.0)if st.form_submit_button("儲存當月數據"):run_query("INSERT OR REPLACE INTO finance_data (month, type, construction, loan, admin) VALUES (?,?,?,?,?)",(m_val, 'Actual', cons_val, loan_val, 50.0), is_select=False)st.success(f"第 {m_val} 月數據已錄入。")st.rerun()9 unmodified lines101112131415161718192021222312 unmodified lines3637383940414243444546474849505152535455565758596061626364656667686970717273747576777879802 unmodified lines83848586878889909192939495969798999 unmodified lines# --- 1. 資料庫基礎邏輯 ---DB_PATH = os.path.join(os.getcwd(), 'spv_management.db')FONT_PATH = os.path.join(os.getcwd(), 'src', 'kaiu.ttf') # 指向你上傳的字體檔def init_db():conn = sqlite3.connect(DB_PATH)c = conn.cursor()c.execute('''CREATE TABLE IF NOT EXISTS finance_data(month INTEGER, type TEXT, construction REAL, loan REAL, admin REAL,PRIMARY KEY (month, type))''')c.execute('''CREATE TABLE IF NOT EXISTS project_stages(id INTEGER PRIMARY KEY AUTOINCREMENT,stage_name TEXT, start_month INTEGER, duration INTEGER,12 unmodified linesconn.commit()conn.close()# --- 2. PDF 報表生成邏輯 (支援中文) ---def create_pdf_report(comp_df, eac, gap, loan_limit, total_budget):pdf = FPDF()pdf.add_page()# 載入中文字體if os.path.exists(FONT_PATH):pdf.add_font('Kaiu', '', FONT_PATH, uni=True)pdf.set_font('Kaiu', '', 16)else:pdf.set_font("Arial", 'B', 16) # 若找不到字體則退回 Arialpdf.cell(200, 10, txt="SPV 都更專案財務月報表", ln=True, align='C')if os.path.exists(FONT_PATH): pdf.set_font('Kaiu', '', 12)pdf.ln(10)pdf.cell(200, 10, txt=f"報告日期: {datetime.date.today()}", ln=True)pdf.cell(200, 10, txt=f"專案原始預算: {total_budget:,.0f} 萬", ln=True)pdf.cell(200, 10, txt=f"銀行總授信額度: {loan_limit:,.0f} 萬", ln=True)pdf.cell(200, 10, txt=f"預估完工總成本 (EAC): {eac:,.0f} 萬", ln=True)if gap < 0:pdf.set_text_color(255, 0, 0)pdf.cell(200, 10, txt=f"警報:預計資金缺口為 {abs(gap):,.0f} 萬", ln=True)else:pdf.set_text_color(0, 128, 0)pdf.cell(200, 10, txt=f"狀態:金流健康。預計剩餘額度: {gap:,.0f} 萬", ln=True)pdf.set_text_color(0, 0, 0)pdf.ln(10)# 表格標題pdf.cell(20, 10, "月份", 1)pdf.cell(45, 10, "預算支出", 1)pdf.cell(45, 10, "實際支出", 1)pdf.cell(40, 10, "差異額", 1)pdf.cell(30, 10, "超支%", 1)pdf.ln()for _, row in comp_df.iterrows():pdf.cell(20, 10, str(int(row['month'])), 1)pdf.cell(45, 10, f"{row['construction_預算']:,.0f}", 1)2 unmodified linespdf.cell(30, 10, f"{row['超支率%']}%", 1)pdf.ln()# 這裡必須將 bytes 輸出return pdf.output(dest='S')# --- 3. 初始化 ---init_db()st.set_page_config(page_title="SPV 財務監控系統", layout="wide")st.title("🏗️ SPV 都更計畫財務監控 PRO")# (其餘 Tab 1, 2, 3 邏輯維持不變,僅需在 Tab 2 的下載按鈕處更新呼叫)# --- 此處省略部分重複介面代碼,確保 Tab 2 的 pdf_out 呼叫如下 ---# 在 Tab 2 中:# pdf_out = create_pdf_report(comp, eac, gap, loan_limit, total_budget)# st.download_button("📥 下載正式 PDF 中文月報表", data=pdf_out, file_name=f"SPV_Report_{datetime.date.today()}.pdf", mime="application/pdf")
src/app.py+32-125