File size: 7,608 Bytes
10d7cc0 3a6aab5 10d7cc0 3a6aab5 10d7cc0 3a6aab5 10d7cc0 3a6aab5 10d7cc0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | # -*- 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}") |