Spaces:
Sleeping
Sleeping
Delete streamlit_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import streamlit as stimport pandas as pdimport numpy as npimport randomimport uuid # 用於生成唯一的ID
# --- 1. 模擬資料生成 ---@st.cache_resource # 緩存資源,避免每次運行都重新生成數據def generate_mock_data(): st.write("正在生成模擬資料,請稍候...")
# 1.1 模擬 400 種原物料 material_data = [] for i in range(1, 401): material_id = f"MAT{str(i).zfill(3)}" material_name = f"原物料 {chr(64 + i // 26)}{chr(65 + i % 26)}" if i > 26 else f"原物料 {chr(64 + i)}" unit_price = round(random.uniform(0.1, 100.0), 2) material_data.append({'ID': material_id, '名稱': material_name, '單價': unit_price}) materials_df = pd.DataFrame(material_data) materials_df.set_index('ID', inplace=True) # 以ID作為索引
# 1.2 模擬 40 種產品組合 product_data = [] for i in range(1, 41): product_id = f"PROD{str(i).zfill(2)}" product_name = f"產品 {chr(64 + i // 26)}{chr(65 + i % 26)}" if i > 26 else f"產品 {chr(64 + i)}" # 每個產品隨機選擇 5 到 20 種原物料 num_materials_per_product = random.randint(5, 20) selected_materials = random.sample(materials_df.index.tolist(), num_materials_per_product) material_details = [] for mat_id in selected_materials: quantity = random.randint(1, 10) # 每個原物料的用量 material_details.append({'MaterialID': mat_id, '用量': quantity}) indirect_cost = round(random.uniform(10.0, 200.0), 2) # 間接費用 product_data.append({ 'ID': product_id, '名稱': product_name, '間接費用': indirect_cost, '原物料明細': material_details # 儲存一個列表,包含每個原物料的ID和用量 }) products_df = pd.DataFrame(product_data) products_df.set_index('ID', inplace=True) # 以ID作為索引 st.success("模擬資料生成完成!") return materials_df, products_df
# --- 2. 應用程式主體 ---st.set_page_config(layout="wide", page_title="產品報價系統")
st.title("🚀 產品報價系統")
# 在 session state 中儲存數據,確保刷新不會丟失if 'materials_df' not in st.session_state or 'products_df' not in st.session_state: st.session_state.materials_df, st.session_state.products_df = generate_mock_data()
materials_df = st.session_state.materials_dfproducts_df = st.session_state.products_df
# --- 側邊欄導覽 ---st.sidebar.title("導覽")page = st.sidebar.radio("選擇功能", ["📊 產品報價", "📦 原物料管理"])
# --- 頁面內容 ---if page == "📊 產品報價": st.header("產品報價")
# 選擇產品 product_names = products_df['名稱'].tolist() selected_product_name = st.selectbox("選擇產品進行報價", product_names)
if selected_product_name: selected_product = products_df[products_df['名稱'] == selected_product_name].iloc[0] st.write(f"**產品 ID:** {selected_product.name}") st.write(f"**產品名稱:** {selected_product['名稱']}") st.subheader("原物料成本明細") # 建立一個 DataFrame 來顯示原物料明細 product_materials_list = [] total_material_cost = 0.0 for item in selected_product['原物料明細']: mat_id = item['MaterialID'] quantity = item['用量'] if mat_id in materials_df.index: mat_info = materials_df.loc[mat_id] mat_name = mat_info['名稱'] mat_unit_price = mat_info['單價'] item_cost = round(mat_unit_price * quantity, 2) total_material_cost += item_cost product_materials_list.append({ '原物料 ID': mat_id, '原物料名稱': mat_name, '單價': mat_unit_price, '用量': quantity, '小計': item_cost }) else: product_materials_list.append({ '原物料 ID': mat_id, '原物料名稱': "資料缺失", '單價': 0.0, '用量': quantity, '小計': 0.0 }) product_materials_df = pd.DataFrame(product_materials_list) st.dataframe(product_materials_df, use_container_width=True) st.markdown(f"**總原物料成本:** <font color='red'>${total_material_cost:.2f}</font>", unsafe_allow_html=True) st.markdown(f"**間接費用:** <font color='blue'>${selected_product['間接費用']:.2f}</font>", unsafe_allow_html=True) # 報價調整 st.subheader("報價調整") col1, col2 = st.columns(2) with col1: coefficient = st.number_input("應用係數 (例如 1.2 表示 20% 利潤)", min_value=0.0, value=1.20, step=0.01) with col2: discount_percentage = st.slider("折扣百分比 (%)", 0, 100, 0, step=1) # 計算最終報價 base_price = total_material_cost + selected_product['間接費用'] price_after_coefficient = base_price * coefficient final_price = price_after_coefficient * (1 - discount_percentage / 100) st.markdown("---") st.markdown(f"### 總成本 (原物料 + 間接費用): <font color='green'>${base_price:.2f}</font>", unsafe_allow_html=True) st.markdown(f"### 應用係數後價格: <font color='green'>${price_after_coefficient:.2f}</font>", unsafe_allow_html=True) st.markdown(f"## **最終報價:** <font color='purple'>${final_price:.2f}</font>", unsafe_allow_html=True)
elif page == "📦 原物料管理": st.header("原物料管理")
st.subheader("所有原物料") # 搜尋功能 search_term = st.text_input("搜尋原物料 (ID 或 名稱)", "").strip().lower() if search_term: filtered_materials_df = materials_df[ materials_df.index.str.lower().str.contains(search_term) | materials_df['名稱'].str.lower().str.contains(search_term) ] st.dataframe(filtered_materials_df, use_container_width=True) st.write(f"找到 {len(filtered_materials_df)} 筆結果。") else: st.dataframe(materials_df, use_container_width=True) st.write(f"共 {len(materials_df)} 種原物料。") st.subheader("新增/編輯原物料 (簡化版)") # 可以添加一個表單來新增或編輯原物料 with st.expander("點擊展開 新增原物料"): with st.form("add_material_form"): new_id = st.text_input("新原物料 ID (留空自動生成)", value=f"MAT{str(len(materials_df) + 1).zfill(3)}") new_name = st.text_input("新原物料 名稱", placeholder="例如:晶片 A1") new_price = st.number_input("新原物料 單價", min_value=0.0, value=1.0, step=0.01) add_material_submitted = st.form_submit_button("新增原物料")
if add_material_submitted: if not new_id: new_id = f"MAT{str(len(materials_df) + 1).zfill(3)}_{uuid.uuid4().hex[:4].upper()}" # 自動生成唯一ID if new_id in materials_df.index: st.error(f"錯誤:原物料 ID '{new_id}' 已存在!") elif not new_name: st.error("錯誤:原物料名稱不能為空!") else: st.session_state.materials_df.loc[new_id] = {'名稱': new_name, '單價': new_price} st.success(f"原物料 '{new_name}' (ID: {new_id}) 已新增。") st.experimental_rerun() # 刷新頁面顯示更新後的數據
# 刪除功能 (可選,但為了簡潔,這裡不實作) # st.subheader("刪除原物料") # material_to_delete = st.selectbox("選擇要刪除的原物料", materials_df.index.tolist()) # if st.button("刪除選定原物料"): # if material_to_delete: # st.session_state.materials_df = st.session_state.materials_df.drop(material_to_delete) # st.success(f"原物料 {material_to_delete} 已刪除。") # st.experimental_rerun()streamlit_app.pyDeleted-186