bhaskarhhp commited on
Commit
9532c4e
Β·
verified Β·
1 Parent(s): 3d3671e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +1226 -65
src/streamlit_app.py CHANGED
@@ -1,21 +1,37 @@
1
  import streamlit as st
 
2
  import firebase_admin
3
  from firebase_admin import credentials, firestore
 
 
 
 
 
 
 
 
 
4
 
5
  # Initialize Firebase
6
  if not firebase_admin._apps:
7
- cred = credentials.Certificate("/app/src/firebase_key.json")
8
  firebase_admin.initialize_app(cred)
9
 
10
  db = firestore.client()
11
-
12
  st.Page.title="Swiftcom DMS"
 
 
 
 
13
  # -------------------------------
14
  # πŸ” LOGIN SECTION
15
  # -------------------------------
 
16
  def login():
17
- st.title("πŸ” Login")
 
18
  with st.form("login_form"):
 
19
  username = st.text_input("Username").strip().upper()
20
  password = st.text_input("Password", type="password")
21
  submitted = st.form_submit_button("Login")
@@ -49,7 +65,7 @@ st.markdown("""
49
  height: 45px;
50
  font-size: 16px;
51
  margin-bottom: 8px;
52
- background-color: #31333f;
53
  color: white;
54
  border: none;
55
  border-radius: 6px;
@@ -67,34 +83,62 @@ st.markdown("""
67
  def show_sidebar():
68
  user_role = st.session_state.get("user_role")
69
  with st.sidebar:
70
- st.markdown(f"**πŸ‘€ {st.session_state.get('username')} ({user_role})**")
71
  st.title("πŸ“‚ Navigation")
72
 
73
  # All roles: Home
74
  if st.button("🏠 Home"):
75
  st.session_state.selected_page = "Home"
76
 
77
- if st.button("πŸ•’ Attendance"):
78
- st.session_state.selected_page = "Attendance"
79
-
80
- if st.button("πŸ“¦ Order"):
81
- st.session_state.selected_page = "Order"
82
 
83
- if st.button("🚚 Logistics"):
84
- st.session_state.selected_page = "Logistics"
 
 
 
85
 
86
- if st.button("πŸ› οΈ Utility"):
87
- st.session_state.selected_page = "Utility"
88
 
89
- # Admin & Standard: Users
 
 
 
 
 
90
  if user_role in ["Admin", "Back Office"]:
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  if st.button("πŸ“ Users"):
92
  st.session_state.selected_page = "Users"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- # Admin only: Distributors
95
- if user_role == "Admin":
96
- if st.button("πŸ“Š Distributors"):
97
- st.session_state.selected_page = "Distributors"
98
 
99
  if st.button("ℹ️ About"):
100
  st.session_state.selected_page = "About"
@@ -118,49 +162,212 @@ def users_page():
118
  st.error("Access denied.")
119
  return
120
 
121
- st.title("πŸ“ User Management")
 
 
 
 
 
 
 
 
 
 
122
  # Choose form actions
123
  options = ["View User"]
124
- if user_role in ["Admin", "Standard"]:
125
  options.append("Add User")
126
  if user_role == "Admin":
127
  options.extend(["Delete User", "Update User"])
128
- st.divider()
129
  user_option = st.radio("Choose action", options, horizontal=True)
130
  st.divider()
131
 
 
 
132
  # Add User
133
  if user_option == "Add User":
134
  st.subheader("Add New User")
 
135
  with st.form("add_user_form"):
136
- name = st.text_input("Name").strip().upper()
137
- user_type = st.selectbox("Type", ["Admin", "Back Office","Standard", "Guest"])
138
- password = st.text_input("Password", type="password")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  submitted = st.form_submit_button("Submit")
140
- if submitted:
141
- users_ref = db.collection("users")
142
- all_users = users_ref.stream()
143
- max_id = 0
144
- for doc in all_users:
145
- data = doc.to_dict()
146
- if isinstance(data.get("id"), int):
147
- max_id = max(max_id, data["id"])
148
- new_id = max_id + 1
149
- users_ref.add({"id": new_id, "name": name, "type": user_type, "pass": password})
150
- st.success(f"βœ… User '{name}' added with ID {new_id}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # View User
153
  elif user_option == "View User":
154
- st.subheader("πŸ“‹ List of Users")
155
- try:
156
- docs = db.collection("users").get()
157
- user_data = [{**doc.to_dict(), "doc_id": doc.id} for doc in docs]
158
- if user_data:
159
- st.dataframe(user_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  else:
161
- st.info("No users found.")
162
- except Exception as e:
163
- st.error(f"Error fetching users: {e}")
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  # Delete User (Admin only)
166
  elif user_option == "Delete User":
@@ -179,31 +386,963 @@ def users_page():
179
  # Update User (Admin only)
180
  elif user_option == "Update User":
181
  st.subheader("✏️ Update User")
182
- docs = db.collection("users").get()
183
- usernames = [doc.to_dict().get("name") for doc in docs]
184
- to_update = st.selectbox("Select user to update", usernames)
185
- new_type = st.selectbox("New Type", ["Admin", "Standard", "Guest"])
186
- new_pass = st.text_input("New Password", type="password")
187
- if st.button("Update"):
188
- for doc in docs:
189
- if doc.to_dict().get("name") == to_update:
190
- update_data = {}
191
- if new_type:
192
- update_data["type"] = new_type
193
- if new_pass:
194
- update_data["pass"] = new_pass
195
- db.collection("users").document(doc.id).update(update_data)
196
- st.success(f"Updated user {to_update}.")
197
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
- # Distributors placeholder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
  def distributors_page():
202
- if st.session_state.get("user_role") != "Admin":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  st.error("Access denied.")
204
  return
205
- st.title("πŸ“Š Distributor Management")
206
- st.write("Manage distributors here.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
  # -------------------------------
209
  # πŸš€ MAIN APP
@@ -217,6 +1356,7 @@ def main():
217
  if "selected_page" not in st.session_state:
218
  st.session_state.selected_page = "Home"
219
 
 
220
  show_sidebar()
221
 
222
  page = st.session_state.selected_page
@@ -226,6 +1366,27 @@ def main():
226
  users_page()
227
  elif page == "Distributors":
228
  distributors_page()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
  if __name__ == "__main__":
231
  main()
 
1
  import streamlit as st
2
+ import pandas as pd
3
  import firebase_admin
4
  from firebase_admin import credentials, firestore
5
+ import io
6
+ from io import StringIO
7
+ from datetime import datetime, timedelta
8
+ import time
9
+ import uuid
10
+ from PIL import Image
11
+ import os
12
+ import base64
13
+
14
 
15
  # Initialize Firebase
16
  if not firebase_admin._apps:
17
+ cred = credentials.Certificate("firebase_key.json")
18
  firebase_admin.initialize_app(cred)
19
 
20
  db = firestore.client()
 
21
  st.Page.title="Swiftcom DMS"
22
+ st.set_page_config(layout="wide")
23
+
24
+
25
+
26
  # -------------------------------
27
  # πŸ” LOGIN SECTION
28
  # -------------------------------
29
+ @st.dialog("πŸ” Login")
30
  def login():
31
+
32
+ #st.title("πŸ” Login")
33
  with st.form("login_form"):
34
+
35
  username = st.text_input("Username").strip().upper()
36
  password = st.text_input("Password", type="password")
37
  submitted = st.form_submit_button("Login")
 
65
  height: 45px;
66
  font-size: 16px;
67
  margin-bottom: 8px;
68
+ background-color: #125078;
69
  color: white;
70
  border: none;
71
  border-radius: 6px;
 
83
  def show_sidebar():
84
  user_role = st.session_state.get("user_role")
85
  with st.sidebar:
86
+ st.markdown(f"**πŸ‘€ {st.session_state.get('username')} (:blue[{user_role}])**")
87
  st.title("πŸ“‚ Navigation")
88
 
89
  # All roles: Home
90
  if st.button("🏠 Home"):
91
  st.session_state.selected_page = "Home"
92
 
 
 
 
 
 
93
 
94
+ # Admin , "Standard", "Back Office": -----------------------------------------------------------------------------
95
+ if user_role in ["Admin", "Standard", "Back Office"]:
96
+ if st.button("πŸ•’ Attendance"):
97
+ st.session_state.selected_page = "Attendance"
98
+
99
 
 
 
100
 
101
+ # Admin , "Standard", "Guest": -----------------------------------------------------------------------------
102
+ if user_role in ["Admin", "Standard", "Guest"]:
103
+ if st.button("πŸ“¦Purchase Order"):
104
+ st.session_state.selected_page = "Order"
105
+
106
+ # Admin , Back Office: -----------------------------------------------------------------------------
107
  if user_role in ["Admin", "Back Office"]:
108
+ if st.button("πŸ“¦ Update Order"):
109
+ st.session_state.selected_page = "Update Order"
110
+ if st.button("πŸ“± Devices"):
111
+ st.session_state.selected_page = "Devices"
112
+ if st.button("πŸ“Š Distributors"):
113
+ st.session_state.selected_page = "Distributors"
114
+ if st.button("πŸ“’ Distributors Ledgers"):
115
+ st.session_state.selected_page = "Distributors Ledgers"
116
+ if st.button("🚚 Logistics"):
117
+ st.session_state.selected_page = "Logistics"
118
+
119
+ # Admin Only --------------------------------------------------------------------------------------
120
+ if user_role in ["Admin"]:
121
  if st.button("πŸ“ Users"):
122
  st.session_state.selected_page = "Users"
123
+ if st.button("πŸ› οΈ Utility"):
124
+ st.session_state.selected_page = "Utility"
125
+ if st.button("πŸ•’ Attendance Managment"):
126
+ st.session_state.selected_page = "Attendance Managment"
127
+
128
+ # Guest Only --------------------------------------------------------------------------------------
129
+ if user_role in ["Guest"]:
130
+ if st.button("πŸ“ Ledger"):
131
+ st.session_state.selected_page = "Ledger"
132
+
133
+ # --------------------------------------------------------------------------------------------------
134
+
135
+ # Standard Only --------------------------------------------------------------------------------------
136
+ if user_role in ["Standard"]:
137
+ if st.button("πŸ“ Ledgers"):
138
+ st.session_state.selected_page = "Ledgers"
139
+
140
+ # --------------------------------------------------------------------------------------------------
141
 
 
 
 
 
142
 
143
  if st.button("ℹ️ About"):
144
  st.session_state.selected_page = "About"
 
162
  st.error("Access denied.")
163
  return
164
 
165
+ #---------------------- individual page title------------------
166
+ st.markdown(
167
+ """
168
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
169
+ πŸ“ User Management
170
+ </h5>
171
+ """,
172
+ unsafe_allow_html=True
173
+ )
174
+ #----------------------------------------------------------------
175
+
176
  # Choose form actions
177
  options = ["View User"]
178
+ if user_role in ["Admin", "Back Office"]:
179
  options.append("Add User")
180
  if user_role == "Admin":
181
  options.extend(["Delete User", "Update User"])
182
+ #st.divider()
183
  user_option = st.radio("Choose action", options, horizontal=True)
184
  st.divider()
185
 
186
+
187
+
188
  # Add User
189
  if user_option == "Add User":
190
  st.subheader("Add New User")
191
+ image_file = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"])
192
  with st.form("add_user_form"):
193
+ #image_file = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"])
194
+ col1, col2 = st.columns([1,3],gap="small",border=True)
195
+ with col1:
196
+ # Image preview
197
+ if image_file:
198
+ st.write("Image Uploaded:")
199
+ try:
200
+ image = Image.open(image_file)
201
+
202
+ st.image(image, caption="Image Preview", width=150)
203
+ except Exception as e:
204
+ st.error(f"Error opening image: {e}")
205
+ else:
206
+ st.write("Image not uploaded")
207
+ with col2:
208
+ name = st.text_input("User Name").strip().upper()
209
+ user_type = st.selectbox("Type", ["Admin", "Back Office", "Standard", "Guest"])
210
+ password = st.text_input("Password", type="password")
211
+
212
+ with st.expander("Add additional user details"):
213
+ col3, col4 = st.columns(2,gap="small",border=True)
214
+ with col3:
215
+ full_name=st.text_input("Full Name").strip().upper()
216
+ doj_in=st.date_input("Date of Joining")
217
+ doj = doj_in.strftime("%d-%m-%Y")
218
+ dob_in=st.date_input("Date of Birth")
219
+ dob = dob_in.strftime("%d-%m-%Y")
220
+ status=st.selectbox("Status", ["Active", "Inactive"])
221
+ contact=st.text_input("Contact").strip().upper()
222
+ work_area=st.text_input("Work Area").strip().upper()
223
+ work_profile=st.text_input("Work Profile").strip().upper()
224
+ Brand=st.text_input("Brand").strip().upper()
225
+ with col4:
226
+ fname=st.text_input("Father's Name").strip().upper()
227
+ address=st.text_area("Address").strip().upper()
228
+ email=st.text_input("Email").strip().upper()
229
+ doc_url=st.text_input("Document URL").strip()
230
+ Closing_Date_in=st.date_input("Closing Date")
231
+ Closing_Date=Closing_Date_in.strftime("%d-%m-%Y")
232
+
233
+
234
+ # Submit button
235
  submitted = st.form_submit_button("Submit")
236
+
237
+ if submitted:
238
+ users_ref = db.collection("users")
239
+ all_users = users_ref.stream()
240
+
241
+ # Check for duplicate user name
242
+ name_exists = False
243
+ max_id = 0
244
+ for doc in all_users:
245
+ data = doc.to_dict()
246
+ if data.get("name") == name:
247
+ name_exists = True
248
+ if isinstance(data.get("id"), int):
249
+ max_id = max(max_id, data["id"])
250
+
251
+ image_b64 = ""
252
+ if image_file:
253
+ img = Image.open(image_file)
254
+ buffered = io.BytesIO()
255
+ img.save(buffered, format="PNG")
256
+ image_b64 = base64.b64encode(buffered.getvalue()).decode()
257
+
258
+
259
+ if name_exists:
260
+ st.error(f"⚠️ User name '{name}' already exists. Please choose another name.")
261
+ else:
262
+ new_id = max_id + 1
263
+ users_ref.add({"id": new_id,"image_b64":image_b64, "name": name, "type": user_type, "pass": password, "full_name":full_name, "doj":doj,"dob":dob,"status":status,"contact":contact,"work_area":work_area,"work_profile":work_profile,"Brand":Brand,"fname":fname,"address":address,"email":email,"doc_url":doc_url,"Closing_Date":Closing_Date})
264
+ st.success(f"βœ… User '{name}' added with ID {new_id}.")
265
 
266
  # View User
267
  elif user_option == "View User":
268
+ st.subheader("πŸ“‹ View Users Database ")
269
+ docs = db.collection("users").stream()
270
+ all_users = [doc.to_dict() for doc in docs]
271
+ brand_options = sorted(set(user.get("Brand", "N/A") for user in all_users if user.get("Brand")))
272
+ selected_brands = st.multiselect("Select Brands to filter", brand_options, default=brand_options)
273
+ selected_type=st.selectbox("Select Type to filter",["Admin", "Back Office", "Standard", "Guest"])
274
+
275
+ # Create 3 tabs
276
+ tab1, tab2, tab3 = st.tabs(["🟒 Active Users", "πŸ”΄ Inactive Users", "❔ No Status Users"])
277
+
278
+ # Fetch all users once
279
+ docs = db.collection("users").stream()
280
+ all_users = [doc.to_dict() for doc in docs]
281
+
282
+ # Display helper function
283
+ def show_users(users_list):
284
+ for data in users_list:
285
+ with st.container():
286
+ st.markdown(
287
+ """
288
+ <div style="border: 1px solid #2196F3; border-radius: 5px; padding: 1px; margin-bottom: 10px;">
289
+ """,
290
+ unsafe_allow_html=True
291
+ )
292
+
293
+ cols = st.columns([1, 3])
294
+ with cols[0]:
295
+ if data.get("image_b64"):
296
+ img_bytes = base64.b64decode(data["image_b64"])
297
+ st.image(img_bytes, width=80)
298
+ else:
299
+ st.write("❌ No Image")
300
+ st.markdown(f"`{data.get('full_name', 'N/A')}`")
301
+ with cols[1]:
302
+ c1, c2=st.columns(2,gap="small",border=True)
303
+ with c1:
304
+ st.markdown(f"**πŸ‘€ User Name:** {data.get('name', 'N/A')}")
305
+ st.markdown(f"**πŸ§‘β€πŸ’» Type:** {data.get('type', 'N/A')}")
306
+ st.markdown(f"**πŸ“Œ Status:** {data.get('status', '❌ Not Set')}")
307
+ st.markdown(f"**πŸ’Ό Brand:** {data.get('Brand', 'N/A')}")
308
+ with c2:
309
+ st.markdown(f"**πŸ“… Date of Joining:** {data.get('doj', 'N/A')}")
310
+ st.markdown(f"**πŸ“… Date of Birth:** {data.get('dob', 'N/A')}")
311
+ st.markdown(f"**πŸ“ž Contact:** {data.get('contact', 'N/A')}")
312
+
313
+ with st.expander(" πŸ“‚ `View additional user details`"):
314
+ c3, c4=st.columns(2,gap="small",border=True)
315
+ with c3:
316
+ st.markdown(f"**πŸ’Ό Work Area:** {data.get('work_area', 'N/A')}")
317
+ st.markdown(f"**πŸ’Ό Work Profile:** {data.get('work_profile', 'N/A')}")
318
+ st.markdown(f"**πŸ“§ Email:** {data.get('email', 'N/A')}")
319
+ st.markdown(f"**πŸ“… Closing Date:** {data.get('Closing_Date', 'N/A')}")
320
+ with c4:
321
+ st.markdown(f"**πŸ‘€ Father Name:** {data.get('fname', 'N/A')}")
322
+ st.markdown(f"**🏠 Address:** {data.get('address', 'N/A')}")
323
+
324
+
325
+ #st.markdown(f"**πŸ“„ Document URL:** {data.get('doc_url', 'N/A')}")
326
+ doc_url = data.get("doc_url")
327
+ if doc_url:
328
+ st.link_button("πŸ“„ Open Document", doc_url)
329
+ else:
330
+ st.write("❌ No Document URL")
331
+
332
+
333
+ st.markdown("</div>", unsafe_allow_html=True)
334
+
335
+ # 🟒 Active
336
+ with tab1:
337
+ active_users = [
338
+ u for u in all_users
339
+ if u.get("status", "").lower() == "active" and u.get("Brand") in selected_brands and u.get("type") == selected_type
340
+ ]
341
+ if active_users:
342
+ st.write(f"🎯 {len(active_users)} `active user(s) matched with selected brands.`")
343
+ show_users(active_users)
344
+ else:
345
+ st.info("No active users found.")
346
+
347
+ # πŸ”΄ Inactive
348
+ with tab2:
349
+ inactive_users = [
350
+ u for u in all_users
351
+ if u.get("status", "").lower() == "inactive" and u.get("Brand") in selected_brands and u.get("type") == selected_type
352
+ ]
353
+ if inactive_users:
354
+ st.write(f"🎯 {len(inactive_users)} `inactive user(s) matched with selected brands.`")
355
+ show_users(inactive_users)
356
  else:
357
+ st.info("No inactive users found.")
358
+
359
+ # ❔ No Status
360
+ with tab3:
361
+ no_status_users = [
362
+ u for u in all_users
363
+ if not u.get("status") or not u.get("Brand")
364
+ ]
365
+ if no_status_users:
366
+ st.write(f"🎯 {len(no_status_users)} ` user(s) found without STATUS or BRAND selected.`")
367
+ show_users(no_status_users)
368
+ else:
369
+ st.info("All users have status set.")
370
+
371
 
372
  # Delete User (Admin only)
373
  elif user_option == "Delete User":
 
386
  # Update User (Admin only)
387
  elif user_option == "Update User":
388
  st.subheader("✏️ Update User")
389
+
390
+ users_ref = db.collection("users")
391
+ docs = users_ref.stream()
392
+ user_list = []
393
+ user_dict = {}
394
+ for doc in docs:
395
+ data = doc.to_dict()
396
+ name = data.get("name", "")
397
+ user_list.append(name)
398
+ user_dict[name] = {"doc_id": doc.id, "data": data}
399
+
400
+ selected_user = st.selectbox("Select User to Update", user_list)
401
+
402
+ if selected_user:
403
+ user_data = user_dict[selected_user]["data"]
404
+ doc_id = user_dict[selected_user]["doc_id"]
405
+
406
+ image_file = st.file_uploader("Upload New Image (optional)", type=["png", "jpg", "jpeg"])
407
+
408
+ with st.form("update_user_form"):
409
+ col1, col2 = st.columns([1, 3], gap="small", border=True)
410
+ with col1:
411
+ if image_file:
412
+ st.write("New Image Uploaded:")
413
+ try:
414
+ image = Image.open(image_file)
415
+ st.image(image, caption="Preview", width=150)
416
+ except Exception as e:
417
+ st.error(f"Error opening image: {e}")
418
+ elif user_data.get("image_b64"):
419
+ st.image(base64.b64decode(user_data["image_b64"]), width=150)
420
+ else:
421
+ st.write("❌ No image available")
422
+
423
+ with col2:
424
+ name = st.text_input("User Name", value=user_data.get("name", "")).strip().upper()
425
+ user_type = st.selectbox("Type", ["Admin", "Back Office", "Standard", "Guest"], index=["Admin", "Back Office", "Standard", "Guest"].index(user_data.get("type", "Standard")))
426
+ password = st.text_input("Password", value=user_data.get("pass", ""), type="password")
427
 
428
+ with st.expander("Update additional user details"):
429
+ col3, col4 = st.columns(2, gap="small", border=True)
430
+ with col3:
431
+ full_name = st.text_input("Full Name", value=user_data.get("full_name", "")).strip().upper()
432
+
433
+ doj_in=st.text_input("Date of Joining", value=user_data.get("doj"))
434
+ dob_in=st.text_input("Date of Birth", value=user_data.get("dob"))
435
+ status = st.selectbox("Status", ["Active", "Inactive"], index=["Active", "Inactive"].index(user_data.get("status", "Active")))
436
+ contact = st.text_input("Contact", value=user_data.get("contact", "")).strip().upper()
437
+ work_area = st.text_input("Work Area", value=user_data.get("work_area", "")).strip().upper()
438
+ work_profile = st.text_input("Work Profile", value=user_data.get("work_profile", "")).strip().upper()
439
+ Brand = st.text_input("Brand", value=user_data.get("Brand", "")).strip().upper()
440
+ with col4:
441
+ fname = st.text_input("Father's Name", value=user_data.get("fname", "")).strip().upper()
442
+ address = st.text_area("Address", value=user_data.get("address", "")).strip().upper()
443
+ email = st.text_input("Email", value=user_data.get("email", "")).strip().upper()
444
+ doc_url = st.text_input("Document URL", value=user_data.get("doc_url", "")).strip()
445
+ Closing_Date_in = st.text_input("Closing Date", value=user_data.get("Closing_Date"))
446
+ # Submit button
447
+ submitted = st.form_submit_button("Update User")
448
+ if submitted:
449
+ image_b64 = user_data.get("image_b64", "")
450
+ if image_file:
451
+ img = Image.open(image_file)
452
+ buffered = io.BytesIO()
453
+ img.save(buffered, format="PNG")
454
+ image_b64 = base64.b64encode(buffered.getvalue()).decode()
455
+
456
+ updated_data = {
457
+ "name": name,
458
+ "type": user_type,
459
+ "pass": password,
460
+ "image_b64": image_b64,
461
+ "full_name": full_name,
462
+ "doj": doj_in,
463
+ "dob": dob_in,
464
+ "status": status,
465
+ "contact": contact,
466
+ "work_area": work_area,
467
+ "work_profile": work_profile,
468
+ "Brand": Brand,
469
+ "fname": fname,
470
+ "address": address,
471
+ "email": email,
472
+ "doc_url": doc_url,
473
+ "Closing_Date": Closing_Date_in
474
+ }
475
+
476
+ users_ref.document(doc_id).update(updated_data)
477
+ st.success(f"βœ… User '{name}' updated successfully.")
478
+
479
+ # -----------------------------------------Distributors placeholder
480
 
481
  def distributors_page():
482
+ if st.session_state.get("user_role") not in ["Admin", "Back Office"]:
483
+ st.error("Access denied.")
484
+ return
485
+ #---------------------- individual page title------------------
486
+ st.markdown(
487
+ """
488
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
489
+ πŸ“Š Distributors
490
+ </h5>
491
+ """,
492
+ unsafe_allow_html=True
493
+ )
494
+ #--------------------------------------------------------------------
495
+
496
+ COLLECTION = "Dist"
497
+
498
+ # Firebase operations
499
+ def add_distributor(data):
500
+ db.collection(COLLECTION).add(data)
501
+
502
+ def get_distributors():
503
+ docs = db.collection(COLLECTION).stream()
504
+ return [{**doc.to_dict(), "id": doc.id} for doc in docs]
505
+
506
+ def update_distributor(doc_id, data):
507
+ db.collection(COLLECTION).document(doc_id).update(data)
508
+
509
+ def delete_distributor(doc_id):
510
+ db.collection(COLLECTION).document(doc_id).delete()
511
+
512
+ # Streamlit UI
513
+
514
+ option = st.radio("Select Operation", ["View", "Add", "Bulk Add", "Update", "Delete"],horizontal=True)
515
+ st.divider()
516
+
517
+ if option == "View":
518
+ st.subheader("View Distributors")
519
+ records = get_distributors()
520
+ if records:
521
+ # Specify the desired column order
522
+ df = pd.DataFrame(records)
523
+ column_order = ["name", "location","address", "contact", "email", "company"] # Rearrange as needed
524
+ ordered_columns = [col for col in column_order if col in df.columns] + [col for col in df.columns if col not in column_order and col != "id"]
525
+ st.dataframe(df[ordered_columns])
526
+ else:
527
+ st.info("No distributors found.")
528
+
529
+ elif option == "Add":
530
+ st.subheader("Add Distributor")
531
+
532
+
533
+ records = get_distributors()
534
+ df1 = pd.DataFrame(records)
535
+ loc = st.selectbox("Location", df1["location"]).strip().upper()
536
+ st.write("if location not in the list, prefer add new location Checkbox[]")
537
+
538
+ if st.checkbox("Add New Loaction"):
539
+ location = st.text_input("Location").strip().upper()
540
+ else:
541
+ location = loc
542
+
543
+ st.divider()
544
+ name = st.text_input("Name")
545
+ address = st.text_area("Address (multiline)")
546
+ contact = st.text_input("Contact")
547
+ email = st.text_input("Email")
548
+ company = st.selectbox("Company", ["SWIFTCOM", "SHREE AGENCY"])
549
+
550
+
551
+ st.divider()
552
+
553
+ if st.button("Add"):
554
+ if name:
555
+ add_distributor({"name": name, "location": location,"address": address, "contact": contact, "email": email, "company": company})
556
+ st.success("Distributor added.")
557
+ else:
558
+ st.warning("Name is required.")
559
+
560
+ elif option == "Bulk Add":
561
+ st.subheader("Bulk Add Distributors (CSV)")
562
+ st.markdown("CSV columns: name, location, address, contact, email, company, brand")
563
+ # Download CSV template
564
+ template_df = pd.DataFrame(columns=["name", "location", "address", "contact", "email", "company", "brand"])
565
+ csv = template_df.to_csv(index=False).encode("utf-8")
566
+ st.download_button("πŸ“₯ Download CSV Template", csv, "distributor_template.csv", "text/csv")
567
+
568
+ # Upload CSV
569
+ file = st.file_uploader("Upload CSV", type="csv")
570
+ if file:
571
+ df = pd.read_csv(file)
572
+ if all(col in df.columns for col in ["name", "location", "address", "contact", "email", "company"]):
573
+ for _, row in df.iterrows():
574
+ add_distributor(row.to_dict())
575
+ st.success("Bulk upload complete.")
576
+ else:
577
+ st.error("CSV must have columns: name, location, address, contact, email, company")
578
+
579
+ elif option == "Update":
580
+ st.subheader("Update Distributor")
581
+ records = get_distributors()
582
+ if records:
583
+ df = pd.DataFrame(records)
584
+ selected = st.selectbox("Select Distributor by Name", df["name"])
585
+ selected_data = df[df["name"] == selected].iloc[0]
586
+ st.divider()
587
+ doc_id = selected_data["id"]
588
+ name = st.text_input("Name", selected_data["name"])
589
+ location = st.text_input("Location", selected_data["location"]).strip().upper()
590
+ address = st.text_area("Address", selected_data["address"])
591
+ contact = st.text_input("Contact", selected_data["contact"])
592
+ email = st.text_input("Email", selected_data["email"])
593
+
594
+ options = ["SWIFTCOM", "SHREE AGENCY"]
595
+ selected_value = selected_data["company"]
596
+ # Find index of selected_value in options list
597
+ index = options.index(selected_value) if selected_value in options else 0
598
+ # Show selectbox with selected value
599
+ company = st.selectbox("Company", options, index=index)
600
+
601
+ st.divider()
602
+ if st.button("Update"):
603
+ update_distributor(doc_id, {"name": name, "location": location,"address": address, "contact": contact, "email": email, "company": company})
604
+ st.success("Distributor updated.")
605
+ else:
606
+ st.info("No distributors available.")
607
+
608
+ elif option == "Delete":
609
+ st.subheader("Delete Distributor")
610
+ records = get_distributors()
611
+ if records:
612
+ df = pd.DataFrame(records)
613
+ selected = st.selectbox("Select Distributor to Delete", df["name"])
614
+ doc_id = df[df["name"] == selected]["id"].values[0]
615
+ if st.button("Delete"):
616
+ delete_distributor(doc_id)
617
+ st.success("Distributor deleted.")
618
+ else:
619
+ st.info("No distributors to delete.")
620
+
621
+
622
+ # ---------------------------------------------------------------Distributors Ledgers Page----------------------
623
+ def distributors_ledgers_page():
624
+
625
+ if st.session_state.get("user_role") not in ["Admin", "Back Office"]:
626
  st.error("Access denied.")
627
  return
628
+ #---------------------- individual page title------------------
629
+
630
+ #st.header("πŸ“Š Distributors Ledgers")
631
+
632
+ # --- Fetch ledger entries ---
633
+ docs = db.collection("Dist").stream()
634
+ ledger_data = [doc.to_dict() for doc in docs]
635
+ df_ledger = pd.DataFrame(ledger_data)
636
+
637
+
638
+
639
+ #---------------------- individual page title------------------
640
+ st.markdown(
641
+ """
642
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white; text-align: center'>
643
+ πŸ“’ Distributors Ledger Viewer
644
+ </h5>
645
+ """,
646
+ unsafe_allow_html=True
647
+ )
648
+
649
+ #st.divider()
650
+ #----------------------------------------------------------------
651
+
652
+
653
+
654
+ # Google Drive file IDs
655
+ file_id = '1Qt_dcHn8YNeVL6s7m7647YssIoukdNoB'
656
+ bal_file_id = '1F39ERDJAiRTOYnNTnThtF-sIl_-zX3j5'
657
+
658
+ # Construct direct download URLs
659
+ csv_url = f'https://drive.google.com/uc?id={file_id}'
660
+ bal_csv_url = f'https://drive.google.com/uc?id={bal_file_id}'
661
+
662
+ # Load CSVs
663
+ df = pd.read_csv(csv_url)
664
+ bal_df = pd.read_csv(bal_csv_url)
665
+
666
+ tab1, tab2, tab3=st.tabs(["πŸ’° Ledger Balance", "πŸ“– Daybook", "πŸ“˜ Ledger & Voucher"])
667
+
668
+ with tab1:
669
+ st.info("Tab Selected : πŸ’° Ledger Balance")
670
+ st.write("πŸ” Select ")
671
+
672
+ colb, colc = st.columns(2)
673
+ with colb:
674
+ # --- UI Filters: Company ---
675
+ company_list = sorted(df_ledger["company"].dropna().unique())
676
+ selected_companies = st.multiselect("Select Company(s)", company_list)
677
+
678
+ # Filter dataframe by selected companies
679
+ if selected_companies:
680
+ filtered_by_company = df_ledger[df_ledger["company"].isin(selected_companies)]
681
+ else:
682
+ filtered_by_company = df_ledger.copy()
683
+ with colc:
684
+ # --- Filter by selected company, then Brand ---
685
+ brand_list = sorted(filtered_by_company["brand"].dropna().unique())
686
+ selected_brands = st.multiselect("Select Brand(s)", brand_list)
687
+
688
+ # Further filter by selected brands
689
+ if selected_brands:
690
+ filtered_by_brand = filtered_by_company[filtered_by_company["brand"].isin(selected_brands)]
691
+ else:
692
+ filtered_by_brand = filtered_by_company.copy()
693
+
694
+ # --- Filter by Brand ---
695
+
696
+ location_list = sorted(filtered_by_brand["location"].dropna().unique())
697
+ selected_locations = st.multiselect("Select Location(s)", location_list)
698
+
699
+ if selected_locations:
700
+ filtered_ledgers = filtered_by_brand[filtered_by_brand["location"].isin(selected_locations)]
701
+ final_ledgers = filtered_ledgers["name"].tolist()
702
+ else:
703
+ final_ledgers = []
704
+
705
+ st.divider()
706
+
707
+ # --- Load balance CSV from Google Drive ---
708
+ csv_url = "https://drive.google.com/uc?id=1F39ERDJAiRTOYnNTnThtF-sIl_-zX3j5"
709
+ df_bal = pd.read_csv(csv_url)
710
+
711
+ # --- Filter matching ledgers ---
712
+ df_bal_filtered = df_bal[df_bal["Ledger Name"].isin(final_ledgers)]
713
+
714
+ # --- Clean Closing Balance ---
715
+ df_bal_filtered["Closing Balance"] = df_bal_filtered["Closing Balance"].astype(str)
716
+
717
+ def parse_balance(val):
718
+ val = val.replace("Cr", "").replace("Dr", "").replace(",", "").strip()
719
+ try:
720
+ return float(val)
721
+ except:
722
+ return 0.0
723
+
724
+ df_bal_filtered["BalanceValue"] = df_bal_filtered["Closing Balance"].apply(parse_balance)
725
+
726
+ # --- Split into Dr and Cr based on sign ---
727
+ df_dr = df_bal_filtered[df_bal_filtered["BalanceValue"] < 0][["Ledger Name", "Closing Balance"]].reset_index(drop=True)
728
+ df_cr = df_bal_filtered[df_bal_filtered["BalanceValue"] >= 0][["Ledger Name", "Closing Balance"]].reset_index(drop=True)
729
+
730
+ # --- Totals ---
731
+ total_cr = df_bal_filtered[df_bal_filtered["BalanceValue"] >= 0]["BalanceValue"].sum()
732
+ total_dr = df_bal_filtered[df_bal_filtered["BalanceValue"] < 0]["BalanceValue"].sum()
733
+
734
+ # --- Display in two columns ---
735
+ col1, col2 = st.columns(2)
736
+
737
+ with col1:
738
+ st.markdown("### πŸ’š Cr. Balance")
739
+ st.dataframe(df_cr)
740
+ st.success(f"**Total Cr: β‚Ή {total_cr:,.2f}**")
741
+
742
+ with col2:
743
+ st.markdown("### πŸ”΄ Dr. Balance (Oustanding)")
744
+ st.dataframe(df_dr)
745
+ st.error(f"**Total Dr: β‚Ή {abs(total_dr):,.2f}**")
746
+
747
+ with tab2:
748
+ st.info("Tab Selected : πŸ“– Daybook")
749
+
750
+ required_columns = {'Date', 'LedgerName', 'Ledger', 'Type', 'VoucherNo', 'DrAmt', 'CrAmt'}
751
+ if required_columns.issubset(df.columns):
752
+ # Convert 'Date' to datetime
753
+ df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
754
+
755
+ # Ledger Type filter (from 'Type' column)
756
+ type_options = sorted(df['Type'].dropna().unique())
757
+ selected_types = st.multiselect("πŸ“Œ Select Ledger Type(s)", type_options, default=type_options)
758
+
759
+ # Date range
760
+ today = datetime.today()
761
+ default_from = today - timedelta(days=1)
762
+ default_to = today
763
+
764
+ col1, col2 = st.columns(2)
765
+ with col1:
766
+ from_date = st.date_input("πŸ—“οΈ From Date", default_from)
767
+ with col2:
768
+ to_date = st.date_input("πŸ—“οΈ To Date", default_to)
769
+
770
+ st.markdown(f"πŸ—“οΈ Showing entries from **{from_date.strftime('%d-%m-%y')}** to **{to_date.strftime('%d-%m-%y')}**")
771
+
772
+ # Filter data
773
+ filtered_df = df[
774
+ (df['Date'] >= pd.to_datetime(from_date)) &
775
+ (df['Date'] <= pd.to_datetime(to_date)) &
776
+ (df['Type'].isin(selected_types))
777
+ ]
778
+
779
+ if not filtered_df.empty:
780
+ # Format date
781
+ filtered_df['Date'] = filtered_df['Date'].dt.strftime('%d-%m-%y')
782
+
783
+ # Reorder columns
784
+ display_cols = ['Date', 'LedgerName', 'Ledger', 'Type', 'VoucherNo', 'DrAmt', 'CrAmt']
785
+ filtered_df = filtered_df[display_cols]
786
+
787
+ # Show table
788
+ st.subheader("πŸ“„ Daybook Entries")
789
+ st.dataframe(filtered_df, use_container_width=True, hide_index=True)
790
+
791
+ # Totals
792
+ total_dr = filtered_df['DrAmt'].sum()
793
+ total_cr = filtered_df['CrAmt'].sum()
794
+ st.success(f"**Total Dr: β‚Ή {total_dr:,.2f} | Total Cr: β‚Ή {total_cr:,.2f}**")
795
+ else:
796
+ st.warning("⚠️ No matching entries found.")
797
+ else:
798
+ st.error("❌ Required columns not found. Expected: Date, LedgerName, Ledger, Type, VoucherNo, DrAmt, CrAmt")
799
+
800
+ with tab3:
801
+ st.info("Tab Selected : πŸ“˜ Ledger & Voucher")
802
+ # UI block for ledger selection
803
+
804
+ if 'LedgerName' in df.columns and 'Date' in df.columns:
805
+ # Convert 'Date' column to datetime if not already
806
+ df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
807
+
808
+ # Get unique ledger names
809
+ ledger_options = df['LedgerName'].dropna().unique()
810
+ selected_ledger = st.selectbox("πŸ” Select Ledger", sorted(ledger_options))
811
+
812
+ # Default date range: last 2 months
813
+ today = datetime.today()
814
+ default_from_date = today - timedelta(days=60)
815
+ default_to_date = today
816
+
817
+ # Date inputs (shown to user)
818
+ col1, col2=st.columns(2)
819
+ with col1:
820
+ from_date = st.date_input("πŸ—“οΈFrom Date", default_from_date)
821
+ with col2:
822
+ to_date = st.date_input("πŸ—“οΈTo Date", default_to_date)
823
+ st.markdown(f"πŸ—“οΈ Showing ledger from **{from_date.strftime('%d-%m-%y')}** to **{to_date.strftime('%d-%m-%y')}**")
824
+ st.divider()
825
+
826
+ # Filter dataframe
827
+ filtered_df = df[
828
+ (df['LedgerName'] == selected_ledger) &
829
+ (df['Date'] >= pd.to_datetime(from_date)) &
830
+ (df['Date'] <= pd.to_datetime(to_date))
831
+ ].drop(columns=['LedgerName'])
832
+
833
+ # πŸ‘‰ Format 'Date' for display as dd-mm-yy
834
+ if 'Date' in filtered_df.columns:
835
+ filtered_df['Date'] = filtered_df['Date'].dt.strftime('%d-%m-%y')
836
+
837
+ st.subheader("πŸ“‘ Ledger Details")
838
+ st.dataframe(filtered_df, use_container_width=True, hide_index=True)
839
+
840
+ else:
841
+ st.error("❌ 'LedgerName' or 'Date' column not found in the main ledger data.")
842
+
843
+ # Show closing balance
844
+ if 'Ledger Name' in bal_df.columns:
845
+ filtered_bal_df = bal_df[bal_df['Ledger Name'] == selected_ledger]
846
+ if not filtered_bal_df.empty:
847
+ closing_balance = filtered_bal_df['Closing Balance'].values[0]
848
+ st.markdown(f"πŸ’° **Closing Balance**")
849
+ if closing_balance < 0:
850
+ st.error(f"Closing Balance for **{selected_ledger}** is: β‚Ή {closing_balance:,.2f} Dr.")
851
+ else:
852
+ st.success(f"Closing Balance for **{selected_ledger}** is: β‚Ή {closing_balance:,.2f} Cr.")
853
+ else:
854
+ st.warning("No balance information found for the selected ledger.")
855
+ else:
856
+ st.error("❌ 'Ledger Name' column not found in the balance data.")
857
+
858
+
859
+
860
+
861
+
862
+ # ---------------------------------------------------------------Order Page----------------------
863
+ def order_page():
864
+ if st.session_state.get("user_role") not in ["Admin", "Standard", "Guest"]:
865
+ st.error("Access denied.")
866
+ #---------------------- individual page title------------------
867
+ st.markdown(
868
+ """
869
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
870
+ πŸ“¦ Order Management
871
+ </h5>
872
+ """,
873
+ unsafe_allow_html=True
874
+ )
875
+ #--------------------------------------------------------------------
876
+
877
+ # func for add device
878
+ def add_device(data):
879
+ db.collection("device").add(data)
880
+
881
+ #---------------------------------------------------------------------------
882
+ # --- Function to get unique brand/type values to delete device---
883
+ @st.cache_data
884
+ def get_unique_values():
885
+ docs = db.collection("device").stream()
886
+ brands = set()
887
+ types = set()
888
+ for doc in docs:
889
+ data = doc.to_dict()
890
+ if "brand" in data:
891
+ brands.add(data["brand"])
892
+ if "type" in data:
893
+ types.add(data["type"])
894
+ return sorted(brands), sorted(types)
895
+
896
+ def device_exists(article, model):
897
+ # Implement your DB lookup logic here.
898
+ # Return True if the device already exists, else False.
899
+ pass
900
+
901
+
902
+ # ---------------------------------------------------------------Order Page----------------------
903
+ def devices_page():
904
+ if st.session_state.get("user_role") not in ["Admin", "Back Office"]:
905
+ st.error("Access denied.")
906
+ #---------------------- individual page title------------------
907
+ st.markdown(
908
+ """
909
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
910
+ πŸ“± Devices
911
+ </h5>
912
+ """,
913
+ unsafe_allow_html=True
914
+ )
915
+ #--------------------------------------------------------------------
916
+ tab_view, tab_add, tab_add_bulk, tab_delete,tab_delete_all, tab_update = st.tabs(["πŸ“±Existing Device ", " βž•Add Device ", " πŸ“¦βž•Add Bulk Device.csv ", " πŸ—‘οΈDelete ", " πŸ“¦πŸ—‘οΈDelete All ", " ✏️Update "])
917
+ with tab_view:
918
+
919
+ st.subheader("πŸ“± Existing Devices")
920
+
921
+ # Fetch devices from Firestore (simulate)
922
+ docs = db.collection("device").get()
923
+ user_data = [{**doc.to_dict(), "doc_id": doc.id} for doc in docs]
924
+
925
+ if user_data:
926
+ df = pd.DataFrame(user_data)
927
+
928
+ # Get unique brand and type options
929
+ brand_options = sorted(df["brand"].dropna().unique())
930
+ type_options = sorted(df["type"].dropna().unique())
931
+
932
+ # Show filters at the top
933
+ selected_brands = st.multiselect("Filter by Brand", brand_options, default=brand_options)
934
+ selected_types = st.multiselect("Filter by Type", type_options, default=type_options)
935
+
936
+ # Filter dataframe based on selections
937
+ filtered_df = df[
938
+ (df["brand"].isin(selected_brands)) &
939
+ (df["type"].isin(selected_types))
940
+ ]
941
+
942
+ # Display dataframe container below filters
943
+ container = st.container()
944
+
945
+ column_order = ["brand", "type", "model", "article", "stock"]
946
+ ordered_columns = [col for col in column_order if col in filtered_df.columns] + \
947
+ [col for col in filtered_df.columns if col not in column_order and col != "doc_id"]
948
+
949
+ if not filtered_df.empty:
950
+ container.dataframe(filtered_df[ordered_columns])
951
+ else:
952
+ container.info("No devices match the selected filters.")
953
+ else:
954
+ st.info("No Device found.")
955
+
956
+
957
+
958
+ with tab_add:
959
+ # Simulated Firestore fetch
960
+ docs = db.collection("device").get()
961
+ user_data = [{**doc.to_dict(), "doc_id": doc.id} for doc in docs]
962
+ df = pd.DataFrame(user_data)
963
+
964
+ # Initialize session state for new entries
965
+ #if "new_brand" not in st.session_state:
966
+ # st.session_state.new_brand = ""
967
+ #if "new_type" not in st.session_state:
968
+ # st.session_state.new_type = ""
969
+ col1, col2= st.columns(2,vertical_alignment="top",gap="small",border=True)
970
+
971
+ with col1:
972
+ if not df.empty:
973
+ brand_options = sorted(df["brand"].dropna().unique().tolist())
974
+ with st.popover("Add New Brand"):
975
+ new_brand=st.text_input("Enter New Brand Name",key="new_brand_input").strip().upper()
976
+ if new_brand:
977
+ brand_options.append(new_brand)
978
+ col1.markdown(f"`{new_brand} `: Added in the Brand list")
979
+
980
+
981
+ with col2:
982
+ if not df.empty:
983
+ type_options = sorted(df["type"].dropna().unique().tolist())
984
+ with st.popover("Add New Type"):
985
+ new_type = st.text_input("Enter New Type",key="new_type_input").strip().upper()
986
+ if new_type:
987
+ type_options.append(new_type)
988
+ col2.markdown(f"`{new_type} `: Added in the type list")
989
+
990
+
991
+
992
+
993
+
994
+ # Add "New Brand" and "Add New" options
995
+
996
+ with st.form("add_device_form"):
997
+ # --- Brand Selection ---
998
+ st.subheader(" βž• Add Device")
999
+ if not df.empty:
1000
+ selected_brand = st.selectbox("Select Brand", brand_options)
1001
+ else:
1002
+ selected_brand = st.text_input("Enter Brand").strip().upper()
1003
+
1004
+ brand = selected_brand
1005
+
1006
+ # --- Type Selection ---
1007
+ if not df.empty:
1008
+ selected_type = st.selectbox("Select Type", type_options)
1009
+ else:
1010
+ selected_type = st.text_input("Enter Type").strip().upper()
1011
+
1012
+
1013
+ dev_type = selected_type
1014
+
1015
+ # Other Fields
1016
+ article = st.text_input("Article Number (if any)")
1017
+ model = st.text_input("Model")
1018
+ stock = st.text_input("Stock", "0")
1019
+
1020
+ # Submit Button
1021
+ submitted = st.form_submit_button("Add Device")
1022
+
1023
+ if submitted:
1024
+ if not brand or not dev_type:
1025
+ st.warning("Please enter both a valid Brand and Type.")
1026
+ else:
1027
+ # Here you can write to Firestore or show results
1028
+ new_device = {
1029
+ "brand": brand,
1030
+ "type": dev_type,
1031
+ "article": article,
1032
+ "model": model,
1033
+ "stock": stock
1034
+ }
1035
+ db.collection("device").add(new_device) # Uncomment to add to Firestore
1036
+ st.toast("Device added successfully!")
1037
+ new_brand=None
1038
+ new_type=None
1039
+
1040
+ #st.session_state["new_brand_input"] = ""
1041
+ #st.session_state["new_type_input"] = ""
1042
+ #st.json(new_device)
1043
+ #st.rerun()
1044
+
1045
+ with tab_add_bulk:
1046
+ st.subheader("πŸ“¦ Bulk Add Devices")
1047
+ st.markdown("**CSV format:** `article`,`brand`,`type`,`model`,`stock`")
1048
+
1049
+ # Download template
1050
+ template_df = pd.DataFrame(columns=["article", "brand", "type", "model", "stock"])
1051
+ csv = template_df.to_csv(index=False).encode("utf-8")
1052
+ st.download_button("πŸ“₯ Download CSV Template", csv, "device_template.csv", "text/csv")
1053
+
1054
+ # Initialize session state
1055
+ if "bulk_upload_done" not in st.session_state:
1056
+ st.session_state.bulk_upload_done = False
1057
+
1058
+ # Upload filled CSV
1059
+ file = st.file_uploader("Upload your CSV", type="csv")
1060
+
1061
+ # Show upload button only if file is uploaded and not already processed
1062
+ if file and not st.session_state.bulk_upload_done:
1063
+ try:
1064
+ df = pd.read_csv(file)
1065
+ required_columns = {"article", "brand", "type", "model", "stock"}
1066
+
1067
+ if required_columns.issubset(df.columns):
1068
+ with st.spinner("Adding devices..."):
1069
+ for _, row in df.iterrows():
1070
+ data = row.to_dict()
1071
+ try:
1072
+ data["stock"] = int(data["stock"])
1073
+ except:
1074
+ data["stock"] = 0
1075
+ add_device(data)
1076
+
1077
+ st.success("βœ… Devices added successfully.")
1078
+ st.dataframe(df)
1079
+ st.session_state.bulk_upload_done = True # Set flag to prevent reprocessing
1080
+ else:
1081
+ st.error("❌ CSV must have columns: article, brand, type, model, stock")
1082
+ except Exception as e:
1083
+ st.error(f"❌ Error reading CSV: {e}")
1084
+
1085
+ # Optionally allow user to reset for a new upload
1086
+ if st.session_state.bulk_upload_done:
1087
+ if st.button("πŸ”„ Upload Another File"):
1088
+ st.session_state.bulk_upload_done = False
1089
+
1090
+
1091
+
1092
+ with tab_delete:
1093
+ # Fetch device data
1094
+ docs = db.collection("device").get()
1095
+ user_data = [{**doc.to_dict(), "doc_id": doc.id} for doc in docs]
1096
+ df = pd.DataFrame(user_data)
1097
+
1098
+ st.header(" πŸ—‘οΈ Delete Device")
1099
+
1100
+ if df.empty:
1101
+ st.info("No devices available.")
1102
+ else:
1103
+ # Step 1: Select Brand
1104
+ brands = sorted(df["brand"].dropna().unique())
1105
+ selected_brand = st.selectbox("Select Brand", brands)
1106
+
1107
+ # Step 2: Filter by Brand β†’ Type
1108
+ type_df = df[df["brand"] == selected_brand]
1109
+ types = sorted(type_df["type"].dropna().unique())
1110
+ selected_type = st.selectbox("Select Type", types)
1111
+
1112
+ # Step 3: Filter by Brand + Type β†’ Model
1113
+ model_df = type_df[type_df["type"] == selected_type]
1114
+ models = sorted(model_df["model"].dropna().unique())
1115
+ selected_model = st.selectbox("Select Model", models)
1116
+
1117
+ # Step 4: Filter by Brand + Type + Model β†’ article
1118
+ article_df = model_df[model_df["model"] == selected_model]
1119
+ article = sorted(article_df["article"].dropna().unique())
1120
+ selected_article = st.selectbox("Select Article :", article)
1121
+
1122
+ # Step 5: Filter by Brand + Type + Model + Color β†’ Spec
1123
+ #spec_df = color_df[color_df["color"] == selected_color]
1124
+ #specs = sorted(spec_df["spec"].dropna().unique())
1125
+ #selected_spec = st.selectbox("Select Specification", specs)
1126
+
1127
+ # Final match
1128
+ final_df = article_df[article_df["article"] == selected_article]
1129
+
1130
+ if not final_df.empty:
1131
+ doc_id = final_df.iloc[0]["doc_id"]
1132
+ st.markdown(f"**Ready to delete:** `{selected_brand} | {selected_type} | {selected_model} {selected_article}`")
1133
+
1134
+ if st.button("Delete Device"):
1135
+ db.collection("device").document(doc_id).delete()
1136
+ st.success("Device deleted successfully!")
1137
+ st.rerun()
1138
+ else:
1139
+ st.warning("Matching device or article not found.")
1140
+
1141
+
1142
+ with tab_delete_all:
1143
+ # --- Delete filtered devices ---
1144
+ def delete_filtered_devices(selected_brands, selected_types):
1145
+ docs = db.collection("device").stream()
1146
+ count = 0
1147
+ for doc in docs:
1148
+ data = doc.to_dict()
1149
+ brand_match = not selected_brands or data.get("brand") in selected_brands
1150
+ type_match = not selected_types or data.get("type") in selected_types
1151
+ if brand_match and type_match:
1152
+ doc.reference.delete()
1153
+ count += 1
1154
+ return count
1155
+
1156
+ # --- UI ---
1157
+ st.subheader("πŸ—‘οΈ Delete Devices by Filter")
1158
+
1159
+ brands, types = get_unique_values()
1160
+
1161
+ # Filters
1162
+ col1, col2 = st.columns(2)
1163
+ with col1:
1164
+ selected_brands = st.multiselect("Select Brand(s)", brands)
1165
+ with col2:
1166
+ selected_types = st.multiselect("Select Type(s)", types)
1167
+
1168
+ # Show selected filters
1169
+ st.markdown(f"**Selected brands:** `{', '.join(selected_brands) or 'All'}`")
1170
+ st.markdown(f"**Selected types:** `{', '.join(selected_types) or 'All'}`")
1171
+
1172
+ # Delete button
1173
+ if st.button("🚨 Delete Filtered Devices"):
1174
+ with st.spinner("Deleting..."):
1175
+ deleted_count = delete_filtered_devices(selected_brands, selected_types)
1176
+ st.success(f"βœ… Deleted {deleted_count} matching device(s).")
1177
+ time.sleep(5)
1178
+ st.rerun()
1179
+
1180
+
1181
+ with tab_update:
1182
+ # Load data from Firestore
1183
+ docs = db.collection("device").get()
1184
+ user_data = [{**doc.to_dict(), "doc_id": doc.id} for doc in docs]
1185
+ df = pd.DataFrame(user_data)
1186
+
1187
+ st.header(" ✏️ Update Device")
1188
+
1189
+ if df.empty:
1190
+ st.info("No devices available.")
1191
+ else:
1192
+ # Step 1: Select Brand
1193
+ brands = sorted(df["brand"].dropna().unique())
1194
+ selected_brand = st.selectbox("Select Brand", brands, key="brand_select")
1195
+
1196
+ # Step 2: Filter by Brand β†’ Type
1197
+ type_df = df[df["brand"] == selected_brand]
1198
+ types = sorted(type_df["type"].dropna().unique())
1199
+ selected_type = st.selectbox("Select Type", types, key="type_select")
1200
+
1201
+ # Step 3: Filter by Brand + Type β†’ Model
1202
+ model_df = type_df[type_df["type"] == selected_type]
1203
+ models = sorted(model_df["model"].dropna().unique())
1204
+ selected_model = st.selectbox("Select Model", models, key="model_select")
1205
+
1206
+ # Step 4: Filter by Brand + Type + Model β†’ Color
1207
+ #color_df = model_df[model_df["model"] == selected_model]
1208
+ #colors = sorted(color_df["color"].dropna().unique())
1209
+ #selected_color = st.selectbox("Select Color", colors, key="color_select")
1210
+
1211
+ # Step 5: Filter by Brand + Type + Model + Color β†’ Spec
1212
+ #spec_df = color_df[color_df["color"] == selected_color]
1213
+ #specs = sorted(spec_df["spec"].dropna().unique())
1214
+ #selected_spec = st.selectbox("Select Specification", specs, key="spec_select")
1215
+
1216
+ # Final filtered record
1217
+ final_df = model_df[model_df["model"] == selected_model]
1218
+
1219
+ if not final_df.empty:
1220
+ record = final_df.iloc[0]
1221
+ doc_id = record["doc_id"]
1222
+
1223
+ st.markdown("### Edit Device Fields")
1224
+
1225
+ # Editable input fields with unique keys
1226
+ new_brand = st.text_input("Brand", value=record["brand"], key="edit_brand")
1227
+ new_type = st.text_input("Type", value=record["type"], key="edit_type")
1228
+ new_model = st.text_input("Model", value=record["model"], key="edit_model")
1229
+ new_article = st.text_input("Article", value=record["article"], key="edit_article")
1230
+ new_stock = st.text_area("Stock", value=record["stock"], key="edit_stock")
1231
+
1232
+ if st.button("Update Device", key="update_button"):
1233
+ db.collection("device").document(doc_id).update({
1234
+ "brand": new_brand.strip().upper(),
1235
+ "type": new_type.strip().capitalize(),
1236
+ "model": new_model.strip(),
1237
+ "article": new_article.strip(),
1238
+ "stock": new_stock.strip()
1239
+ })
1240
+ st.success("Device updated successfully!")
1241
+ st.rerun()
1242
+ else:
1243
+ st.warning("Matching device not found.")
1244
+
1245
+ # ---------------------------------------------------------------Logistics Page----------------------
1246
+ def logistics_page():
1247
+ if st.session_state.get("user_role") not in ["Admin", "Back Office"]:
1248
+ st.error("Access denied.")
1249
+
1250
+ #---------------------- individual page title------------------
1251
+ st.markdown(
1252
+ """
1253
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1254
+ 🚚 Logistics
1255
+ </h5>
1256
+ """,
1257
+ unsafe_allow_html=True
1258
+ )
1259
+ #--------------------------------------------------------------------
1260
+
1261
+ # ---------------------------------------------------------------Utility Page----------------------
1262
+ def utility_page():
1263
+ if st.session_state.get("user_role") not in ["Admin"]:
1264
+ st.error("Access denied.")
1265
+ #---------------------- individual page title------------------
1266
+ st.markdown(
1267
+ """
1268
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1269
+ πŸ› οΈ Utility
1270
+ </h5>
1271
+ """,
1272
+ unsafe_allow_html=True
1273
+ )
1274
+ #--------------------------------------------------------------------
1275
+
1276
+
1277
+ # ---------------------------------------------------------------Attendance Page----------------------
1278
+ def attendance_page():
1279
+ #---------------------- individual page title------------------
1280
+ st.markdown(
1281
+ """
1282
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1283
+ πŸ•’ Attendance
1284
+ </h5>
1285
+ """,
1286
+ unsafe_allow_html=True
1287
+ )
1288
+ #--------------------------------------------------------------------
1289
+
1290
+ st.write("Attendance Page comming soon")
1291
+
1292
+
1293
+
1294
+ # ---------------------------------------------------------------About Page----------------------
1295
+ def about_page():
1296
+ #---------------------- individual page title------------------
1297
+ st.markdown(
1298
+ """
1299
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1300
+ ℹ️ About
1301
+ </h5>
1302
+ """,
1303
+ unsafe_allow_html=True
1304
+ )
1305
+ #--------------------------------------------------------------------
1306
+
1307
+ st.write("About page is comming soon")
1308
+
1309
+
1310
+ # ---------------------------------------------------------------Update Order Page----------------------
1311
+ def update_order_page():
1312
+ if st.session_state.get("user_role") not in ["Admin", "Back Office"]:
1313
+ st.error("Access denied.")
1314
+ #---------------------- individual page title------------------
1315
+ st.markdown(
1316
+ """
1317
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1318
+ πŸ“¦ Update Order
1319
+ </h5>
1320
+ """,
1321
+ unsafe_allow_html=True
1322
+ )
1323
+ #--------------------------------------------------------------------
1324
+
1325
+ st.write("Update Order page is comming soon")
1326
+
1327
+
1328
+
1329
+ # ---------------------------------------------------------------Attendance Managment Page----------------------
1330
+ def att_managment_page():
1331
+ if st.session_state.get("user_role") not in ["Admin"]:
1332
+ st.error("Access denied.")
1333
+ #---------------------- individual page title------------------
1334
+ st.markdown(
1335
+ """
1336
+ <h5 style='background-color:#125078; padding:10px; border-radius:10px; color:white;'>
1337
+ πŸ•’ Attendance Managment
1338
+ </h5>
1339
+ """,
1340
+ unsafe_allow_html=True
1341
+ )
1342
+ #--------------------------------------------------------------------
1343
+
1344
+ st.write("Attendance Managment page is comming soon")
1345
+
1346
 
1347
  # -------------------------------
1348
  # πŸš€ MAIN APP
 
1356
  if "selected_page" not in st.session_state:
1357
  st.session_state.selected_page = "Home"
1358
 
1359
+
1360
  show_sidebar()
1361
 
1362
  page = st.session_state.selected_page
 
1366
  users_page()
1367
  elif page == "Distributors":
1368
  distributors_page()
1369
+ elif page == "Order":
1370
+ order_page()
1371
+ elif page == "Logistics":
1372
+ logistics_page()
1373
+ elif page == "Utility":
1374
+ utility_page()
1375
+ elif page == "Attendance":
1376
+ attendance_page()
1377
+ elif page == "About":
1378
+ about_page()
1379
+ elif page == "Update Order":
1380
+ update_order_page()
1381
+ elif page == "Attendance Managment":
1382
+ att_managment_page()
1383
+ elif page == "Devices":
1384
+ devices_page()
1385
+ elif page == "Distributors Ledgers":
1386
+ distributors_ledgers_page()
1387
+
1388
+
1389
+
1390
 
1391
  if __name__ == "__main__":
1392
  main()