# -*- coding: utf-8 -*- """Order & Profit Tracker Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1fHxAYay8sQTVp2vNAkLi-v7B67e37eu4 """ import streamlit as st import pandas as pd import json import firebase_admin from firebase_admin import credentials, firestore # --- Firebase Initialization and Authentication --- # Check if Firebase app is already initialized if not firebase_admin._apps: # Use Streamlit secrets to securely store Firebase credentials try: cred_dict = json.loads(st.secrets["firebase"]["service_account_key"]) cred = credentials.Certificate(cred_dict) firebase_admin.initialize_app(cred) except Exception as e: st.error("❌ Firebase credentials are not configured correctly. Please check your Streamlit secrets.") st.stop() db = firestore.client() # A simple password-based authentication for the team def check_password(): """Returns `True` if the user is authenticated, `False` otherwise.""" st.markdown("---") st.subheader("تسجيل الدخول") password = st.secrets["app_password"] if "password_correct" not in st.session_state: st.session_state["password_correct"] = False if not st.session_state["password_correct"]: st.text_input("أدخل كلمة مرور التطبيق", type="password", key="auth_password") if st.button("تسجيل الدخول"): if st.session_state.auth_password == password: st.session_state["password_correct"] = True st.experimental_rerun() else: st.warning("كلمة المرور خاطئة. حاول مرة أخرى.") return False else: return True # --- Product Data --- # Product data from the user's table (COGS, price, and price with print) product_data = { 'استيكر': {'cogs': 1, 'price': 5, 'price_with_print': None}, 'بالطو اوكسفورد': {'cogs': 330, 'price': 430, 'price_with_print': 450}, 'بالطو جبردين': {'cogs': 210, 'price': 320, 'price_with_print': 340}, 'قلم عادي': {'cogs': 10, 'price': 20, 'price_with_print': None}, 'قلم مضيئ': {'cogs': 40, 'price': 60, 'price_with_print': None}, 'ميدالية': {'cogs': 15, 'price': 35, 'price_with_print': None}, } # --- Streamlit App UI and Logic --- if not check_password(): st.stop() # Get a dummy user ID for the sake of the app since we're not using email auth # In a real app, you would use a proper user management system user_id = "team_member_1" # App title and user info st.title("Order & Profit Tracker") st.markdown("---") st.info(f"مرحباً بك! أنت مسجل الدخول الآن. سيتم حفظ جميع الطلبات الخاصة بك ومشاركتها مع فريقك.") # Order form st.subheader("إدخال طلب جديد") with st.form("order_form"): st.markdown("---") col1, col2, col3 = st.columns(3) with col1: order_id = st.text_input("رقم الطلب", help="مثال: ORD-12345") with col2: customer_name = st.text_input("اسم العميل", help="مثال: أحمد محمد") with col3: phone_number = st.text_input("رقم التليفون", help="مثال: 01001234567") col4, col5 = st.columns(2) with col4: address = st.text_input("العنوان", help="مثال: 10 ش النصر، القاهرة") with col5: product_status = st.selectbox( "حالة المنتج", ["قيد التجهيز", "استلم العميل", "تم الإلغاء"] ) col6, col7 = st.columns(2) with col6: item_name = st.selectbox("اسم المنتج", list(product_data.keys())) with col7: with_printing = st.checkbox("مع طباعة/تطريز/لوجو") col8, col9 = st.columns(2) with col8: quantity = st.number_input("الكمية", min_value=1, value=1) with col9: packaging_cost = st.number_input("تكلفة التغليف ($)", min_value=0.0, value=0.0, step=0.01) shipping_cost = st.number_input("تكلفة الشحن ($)", min_value=0.0, value=0.0, step=0.01) # Calculate unit price and COGS dynamically selected_product_info = product_data.get(item_name) if selected_product_info: cogs = selected_product_info['cogs'] unit_price = selected_product_info['price'] if with_printing and selected_product_info['price_with_print'] is not None: unit_price = selected_product_info['price_with_print'] else: cogs = 0 unit_price = 0 st.markdown(f"**سعر الوحدة**: ${unit_price:,.2f}") st.markdown(f"**تكلفة البضاعة المباعة (COGS)**: ${cogs:,.2f}") submitted = st.form_submit_button("حساب وحفظ الطلب") if submitted: # Perform calculations subtotal = quantity * unit_price total_costs = (quantity * cogs) + packaging_cost + shipping_cost profit = subtotal - total_costs # Display results st.subheader("نتائج الطلب") results_df = pd.DataFrame({ 'المبلغ الإجمالي': [f"${subtotal:,.2f}"], 'إجمالي التكاليف': [f"${total_costs:,.2f}"], 'الربح': [f"${profit:,.2f}"] }).T.rename(columns={0: 'القيمة'}) st.table(results_df) # Save to Firestore order_data = { 'order_id': order_id, 'customer_name': customer_name, 'phone_number': phone_number, 'address': address, 'item_name': item_name, 'product_status': product_status, 'quantity': quantity, 'unit_price': unit_price, 'cogs': cogs, 'packaging_cost': packaging_cost, 'shipping_cost': shipping_cost, 'subtotal': subtotal, 'total_costs': total_costs, 'profit': profit, 'user_id': user_id, 'timestamp': firestore.SERVER_TIMESTAMP } try: db.collection("orders").add(order_data) st.success("✅ تم حفظ الطلب بنجاح!") except Exception as e: st.error(f"❌ حدث خطأ أثناء حفظ الطلب: {e}") # Display recent orders st.subheader("الطلبات الأخيرة") try: orders_ref = db.collection("orders") orders_query = orders_ref.order_by("timestamp", direction=firestore.Query.DESCENDING).limit(20) orders_docs = orders_query.stream() orders = [] for doc in orders_docs: orders.append(doc.to_dict()) if orders: orders_df = pd.DataFrame(orders) orders_df = orders_df.rename(columns={ 'order_id': 'رقم الطلب', 'customer_name': 'العميل', 'item_name': 'المنتج', 'quantity': 'الكمية', 'profit': 'الربح', 'product_status': 'الحالة', 'timestamp': 'التاريخ', 'user_id': 'المستخدم' }) orders_df['التاريخ'] = orders_df['التاريخ'].apply(lambda x: x.strftime("%Y-%m-%d %H:%M:%S") if x else "") st.dataframe(orders_df[['رقم الطلب', 'العميل', 'المنتج', 'الكمية', 'الربح', 'الحالة', 'التاريخ', 'المستخدم']]) else: st.info("لا توجد طلبات حتى الآن.") except Exception as e: st.error(f"❌ فشل تحميل الطلبات: {e}")