Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files5 unmodified lines6789101112142 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019111 unmodified lines20320420520620720820913 unmodified lines223224225226227228229230101 unmodified lines332333334335336337338339340341342343344345346347348349350351352353354355356357358515 unmodified lines87487587687787887988045 unmodified lines92692792892993093193215 unmodified lines9489499509519529535 unmodified linesfrom datetime import datetime, timedeltaimport plotly.express as pximport plotly.graph_objects as gofrom dateutil.relativedelta import relativedelta # 用於產生月份# --- 頁面配置 ---st.set_page_config(142 unmodified linesreturn materials_df, products_df, suppliers_df, purchase_records_df# -----------------------------------------------------------------# ⭐️ 1. 新增:模擬歷史庫存趨勢的函式# -----------------------------------------------------------------@st.cache_resourcedef generate_historical_inventory_data():"""模擬生成過去12個月的庫存狀態資料。注意:這份資料與主資料(materials_df)無關,僅供儀表板趨勢圖使用。"""data = []today = datetime.now()for i in range(12, 0, -1): # 倒序,從12個月前到上個月month_date = today - relativedelta(months=i)month_str = month_date.strftime('%Y-%m')# 模擬一個趨勢:低庫存項目在近幾個月逐漸減少low_stock_count = random.randint(100 - i*5, 140 - i*5)# 總項目數 400normal_stock_count = 400 - low_stock_countdata.append({'年月': month_str,'庫存狀態': '正常','項目數量': normal_stock_count})data.append({'年月': month_str,'庫存狀態': '低於安全庫存','項目數量': low_stock_count})return pd.DataFrame(data)# --- 輔助函數 (Callback) ---11 unmodified linesst.session_state.purchase_records_df) = generate_mock_data()# ⭐️ 2. 載入新的模擬資料st.session_state.hist_inventory_df = generate_historical_inventory_data()# --- 初始化 Session State ---13 unmodified linesproducts_df = st.session_state.products_dfsuppliers_df = st.session_state.suppliers_dfpurchase_records_df = st.session_state.purchase_records_df# ⭐️ 載入新的模擬資料hist_inventory_df = st.session_state.hist_inventory_df# ==================================================================# ⭐️ 頁面函式 1: 儀表板 (Page Dashboard) - 修改101 unmodified linesst.success("✅ 所有物料庫存正常")# -----------------------------------------------------------------# ⭐️ 3. 新增:庫存狀態月度趨勢圖# -----------------------------------------------------------------st.markdown("---")st.subheader("📈 庫存狀態月度趨勢")# 繪製堆疊長條圖fig4 = px.bar(hist_inventory_df,x='年月',y='項目數量',color='庫存狀態',title='每月庫存狀態趨勢 (正常 vs. 低於安全庫存)',barmode='stack', # 堆疊color_discrete_map={ # 自定義顏色'正常': '#00CC96','低於安全庫存': '#EF553B'})fig4.update_layout(height=400, margin=dict(l=0, r=0, t=40, b=0))st.plotly_chart(fig4, use_container_width=True)st.info("ℹ️ 此圖表為模擬的歷史趨勢資料,用以展示儀表板功能。")# ==================================================================# ⭐️ 頁面函式 2: 產品報價 (Page Quotation) - (無變更)515 unmodified lines# ==================================================================# --- 側邊欄 (Side Bar) ---# ⭐️⭐️⭐️ (上次修正的邏輯,無變更) ⭐️⭐️⭐️# ==================================================================with st.sidebar:st.image("https://via.placeholder.com/150x50/667eea/ffffff?text=SCM+System", use_container_width=True)45 unmodified lines# ==================================================================# --- 主程式執行 (Main App Execution) ---# ⭐️⭐️⭐️ (上次修正的邏輯,無變更) ⭐️⭐️⭐️# ==================================================================if st.session_state.current_page == "🏠 儀表板":15 unmodified linesst.markdown("---")st.markdown("""<div style='text-align: center; color: #666; padding: 20px;'><p>📊 供應鏈管理系統 v2.3 | 💻 Powered by Streamlit | 📧 support@scm-system.com</p></div>""", unsafe_allow_html=True)5 unmodified lines678910111213142 unmodified lines15615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621711 unmodified lines22923023123223323423513 unmodified lines249250251252253254255101 unmodified lines357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431515 unmodified lines94794894995095195295345 unmodified lines99910001001100210031004100515 unmodified lines1021102210231024102510265 unmodified linesfrom datetime import datetime, timedeltaimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplots # ⭐️ 1. 導入 make_subplotsfrom dateutil.relativedelta import relativedelta# --- 頁面配置 ---st.set_page_config(142 unmodified linesreturn materials_df, products_df, suppliers_df, purchase_records_df# -----------------------------------------------------------------# ⭐️ 2. 升級:模擬歷史庫存 (同時包含數量與金額)# -----------------------------------------------------------------@st.cache_resourcedef generate_historical_inventory_data():"""模擬生成過去12個月的庫存狀態資料,包含類別、數量和金額。"""data = []today = datetime.now()categories = ['原料', '包材', '添加物', '輔料']# 假設 400 項目平均分佈在 4 個類別total_items_per_category = 100# 假設不同類別的平均單位價值avg_value_multiplier = {'原料': 1500, # 原料最貴'添加物': 1000,'輔料': 300,'包材': 500 # 包材次之}for i in range(12, 0, -1): # 倒序,從12個月前到上個月month_date = today - relativedelta(months=i)month_str = month_date.strftime('%Y-%m')for cat in categories:# 1. 模擬數量 (低庫存項目隨時間減少)low_stock_count = random.randint( (total_items_per_category // 4) - i, (total_items_per_category // 3) - i)low_stock_count = max(5, low_stock_count) # 確保至少有 5 個normal_stock_count = total_items_per_category - low_stock_count# 2. 模擬金額 (隨時間微幅上漲)value_trend = (1 + (12-i) * 0.02) # 價值隨時間微幅上漲avg_val = avg_value_multiplier.get(cat, 700)normal_stock_value = int(normal_stock_count * avg_val * random.uniform(0.9, 1.1) * value_trend)low_stock_value = int(low_stock_count * avg_val * random.uniform(0.9, 1.1) * value_trend)# 3. 儲存 '正常' 狀態的資料data.append({'年月': month_str,'類別': cat,'庫存狀態': '正常','項目數量': normal_stock_count,'庫存金額': normal_stock_value})# 4. 儲存 '低於安全庫存' 狀態的資料data.append({'年月': month_str,'類別': cat,'庫存狀態': '低於安全庫存','項目數量': low_stock_count,'庫存金額': low_stock_value})return pd.DataFrame(data)# --- 輔助函數 (Callback) ---11 unmodified linesst.session_state.purchase_records_df) = generate_mock_data()# ⭐️ 載入升級後的模擬資料st.session_state.hist_inventory_df = generate_historical_inventory_data()# --- 初始化 Session State ---13 unmodified linesproducts_df = st.session_state.products_dfsuppliers_df = st.session_state.suppliers_dfpurchase_records_df = st.session_state.purchase_records_dfhist_inventory_df = st.session_state.hist_inventory_df # ⭐️ 載入新的模擬資料# ==================================================================# ⭐️ 頁面函式 1: 儀表板 (Page Dashboard) - 修改101 unmodified linesst.success("✅ 所有物料庫存正常")# -----------------------------------------------------------------# ⭐️ 3. 修改:庫存狀態月度趨勢圖 (改為雙軸 + 按類別)# -----------------------------------------------------------------st.markdown("---")st.subheader("📈 庫存狀態月度趨勢 (按類別)")st.info("ℹ️ 柱狀圖 (左軸) 為項目數量,折線圖 (右軸) 為總庫存金額 (模擬資料)。")# 獲取所有類別categories_to_plot = hist_inventory_df['類別'].unique()for category in categories_to_plot:# 1. 篩選出該類別的資料cat_df = hist_inventory_df[hist_inventory_df['類別'] == category].copy()# 2. 準備 Bar Chart 資料 (數量)df_normal = cat_df[cat_df['庫存狀態'] == '正常']df_low = cat_df[cat_df['庫存狀態'] == '低於安全庫存']# 3. 準備 Line Chart 資料 (金額 - 需要加總)line_df = cat_df.groupby('年月')['庫存金額'].sum().reset_index()# 4. 建立雙軸圖fig = make_subplots(specs=[[{"secondary_y": True}]])# 5. 加入 Bar Traces (左 Y 軸 - 數量)fig.add_trace(go.Bar(x=df_normal['年月'],y=df_normal['項目數量'],name='正常 (數量)',marker_color='#00CC96'),secondary_y=False,)fig.add_trace(go.Bar(x=df_low['年月'],y=df_low['項目數量'],name='低庫存 (數量)',marker_color='#EF553B'),secondary_y=False,)# 6. 加入 Line Trace (右 Y 軸 - 金額)fig.add_trace(go.Scatter(x=line_df['年月'],y=line_df['庫存金額'],name='總金額',mode='lines+markers',line=dict(color='#667eea') # 線條顏色),secondary_y=True,)# 7. 美化圖表fig.update_layout(barmode='stack', # 堆疊柱狀圖height=400,margin=dict(l=0, r=0, t=40, b=0),title_text=f"類別:{category}", # 每個圖表一個標題legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))fig.update_xaxes(title_text="年月")fig.update_yaxes(title_text="項目數量 (個)", secondary_y=False)fig.update_yaxes(title_text="庫存金額 ($)", secondary_y=True, showgrid=False)st.plotly_chart(fig, use_container_width=True)# ==================================================================# ⭐️ 頁面函式 2: 產品報價 (Page Quotation) - (無變更)515 unmodified lines# ==================================================================# --- 側邊欄 (Side Bar) ---# (上次修正的邏輯,無變更)# ==================================================================with st.sidebar:st.image("https://via.placeholder.com/150x50/667eea/ffffff?text=SCM+System", use_container_width=True)45 unmodified lines# ==================================================================# --- 主程式執行 (Main App Execution) ---# (上次修正的邏輯,無變更)# ==================================================================if st.session_state.current_page == "🏠 儀表板":15 unmodified linesst.markdown("---")st.markdown("""<div style='text-align: center; color: #666; padding: 20px;'><p>📊 供應鏈管理系統 v2.4 | 💻 Powered by Streamlit | 📧 support@scm-system.com</p></div>""", unsafe_allow_html=True)
src/streamlit_app.py+118-45