Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +584 -8
src/streamlit_app.py
CHANGED
|
@@ -1,12 +1,588 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
st.title("Open Link in New Tab")
|
| 4 |
|
| 5 |
-
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
st.
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import os
|
| 5 |
+
from datetime import datetime
|
| 6 |
|
|
|
|
| 7 |
|
| 8 |
+
# --- Clear cached data ---
|
| 9 |
+
st.cache_data.clear()
|
| 10 |
|
| 11 |
+
# --- Page config ---
|
| 12 |
+
st.set_page_config(page_title="Model Manager", page_icon="π οΈ")
|
| 13 |
+
|
| 14 |
+
# --- Connect to DB ---
|
| 15 |
+
db_path = os.path.join(os.getcwd(), "data.db")
|
| 16 |
+
|
| 17 |
+
conn = sqlite3.connect("data.db", check_same_thread=False)
|
| 18 |
+
cursor = conn.cursor()
|
| 19 |
+
|
| 20 |
+
# --- Create tables if not exist ---
|
| 21 |
+
cursor.execute("""
|
| 22 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 23 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 24 |
+
name TEXT,
|
| 25 |
+
type TEXT,
|
| 26 |
+
pass TEXT
|
| 27 |
+
)
|
| 28 |
+
""")
|
| 29 |
+
|
| 30 |
+
cursor.execute("""
|
| 31 |
+
CREATE TABLE IF NOT EXISTS models (
|
| 32 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 33 |
+
brand TEXT,
|
| 34 |
+
model TEXT,
|
| 35 |
+
color TEXT,
|
| 36 |
+
specs TEXT
|
| 37 |
+
)
|
| 38 |
+
""")
|
| 39 |
+
|
| 40 |
+
cursor.execute("""
|
| 41 |
+
CREATE TABLE IF NOT EXISTS dist (
|
| 42 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 43 |
+
name TEXT,
|
| 44 |
+
address TEXT,
|
| 45 |
+
location TEXT,
|
| 46 |
+
contact TEXT,
|
| 47 |
+
email TEXT,
|
| 48 |
+
added_by TEXT
|
| 49 |
+
)
|
| 50 |
+
""")
|
| 51 |
+
|
| 52 |
+
cursor.execute("""
|
| 53 |
+
CREATE TABLE IF NOT EXISTS po (
|
| 54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 55 |
+
date TEXT,
|
| 56 |
+
time TEXT,
|
| 57 |
+
dist TEXT,
|
| 58 |
+
location TEXT,
|
| 59 |
+
model TEXT,
|
| 60 |
+
color TEXT,
|
| 61 |
+
spec TEXT,
|
| 62 |
+
quantity INTEGER,
|
| 63 |
+
status TEXT,
|
| 64 |
+
remark TEXT,
|
| 65 |
+
added_by TEXT,
|
| 66 |
+
update_by TEXT
|
| 67 |
+
)
|
| 68 |
+
""")
|
| 69 |
+
|
| 70 |
+
conn.commit()
|
| 71 |
+
|
| 72 |
+
# --- Initialize session state ---
|
| 73 |
+
if "logged_in" not in st.session_state:
|
| 74 |
+
st.session_state.logged_in = False
|
| 75 |
+
if "username" not in st.session_state:
|
| 76 |
+
st.session_state.username = ""
|
| 77 |
+
if "usertype" not in st.session_state:
|
| 78 |
+
st.session_state.usertype = ""
|
| 79 |
+
if "page" not in st.session_state:
|
| 80 |
+
st.session_state.page = None
|
| 81 |
+
|
| 82 |
+
# --- Login section ---
|
| 83 |
+
if not st.session_state.logged_in:
|
| 84 |
+
st.title("π Login")
|
| 85 |
+
username = st.text_input("Username")
|
| 86 |
+
password = st.text_input("Password", type="password")
|
| 87 |
+
|
| 88 |
+
if st.button("Login"):
|
| 89 |
+
cursor.execute("SELECT * FROM users WHERE name = ? AND pass = ?", (username.strip().upper(), password))
|
| 90 |
+
user = cursor.fetchone()
|
| 91 |
+
if user:
|
| 92 |
+
st.session_state.logged_in = True
|
| 93 |
+
st.session_state.username = user[1]
|
| 94 |
+
st.session_state.usertype = user[2]
|
| 95 |
+
st.success(f"Welcome {user[1]}! You are logged in as {user[2]}.")
|
| 96 |
+
st.rerun()
|
| 97 |
+
else:
|
| 98 |
+
st.error("Invalid credentials. Try again.")
|
| 99 |
+
|
| 100 |
+
# --- After login ---
|
| 101 |
+
if st.session_state.logged_in:
|
| 102 |
+
st.sidebar.image("logo.png", use_container_width=True)
|
| 103 |
+
st.sidebar.title("Navigation")
|
| 104 |
+
st.sidebar.success(f"Logged in as: {st.session_state.username} ({st.session_state.usertype})")
|
| 105 |
+
|
| 106 |
+
if st.session_state.usertype == "Admin":
|
| 107 |
+
st.session_state.page = st.sidebar.radio(
|
| 108 |
+
"Choose page",
|
| 109 |
+
[
|
| 110 |
+
"π¦ Dashboard",
|
| 111 |
+
"π€ Add User",
|
| 112 |
+
"ποΈ Delete User",
|
| 113 |
+
"β Add/Delete Model",
|
| 114 |
+
"πͺ Add/Delete Distributor",
|
| 115 |
+
"Create Order",
|
| 116 |
+
"Update Order"
|
| 117 |
+
]
|
| 118 |
+
)
|
| 119 |
+
elif st.session_state.usertype == "Standard":
|
| 120 |
+
st.session_state.page = st.sidebar.radio(
|
| 121 |
+
"Choose page",
|
| 122 |
+
[
|
| 123 |
+
"π¦ Dashboard",
|
| 124 |
+
"Create Order",
|
| 125 |
+
"Update Order"
|
| 126 |
+
]
|
| 127 |
+
)
|
| 128 |
+
elif st.session_state.usertype == "Guest":
|
| 129 |
+
st.session_state.page = st.sidebar.radio(
|
| 130 |
+
"Choose page",
|
| 131 |
+
[
|
| 132 |
+
"π¦ Dashboard",
|
| 133 |
+
"Create Order"
|
| 134 |
+
]
|
| 135 |
+
)
|
| 136 |
+
elif st.session_state.usertype == "Back Office":
|
| 137 |
+
st.session_state.page = st.sidebar.radio(
|
| 138 |
+
"Choose page",
|
| 139 |
+
[
|
| 140 |
+
"π¦ Dashboard",
|
| 141 |
+
"Create Order",
|
| 142 |
+
"Update Order"
|
| 143 |
+
]
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
else:
|
| 147 |
+
st.session_state.page = st.sidebar.radio(
|
| 148 |
+
"Choose page",
|
| 149 |
+
[
|
| 150 |
+
"π¦ Dashboard",
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
]
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# --- Logout ---
|
| 157 |
+
if st.sidebar.button("Logout"):
|
| 158 |
+
for key in ["logged_in", "username", "usertype", "page"]:
|
| 159 |
+
st.session_state.pop(key, None)
|
| 160 |
+
st.rerun()
|
| 161 |
+
|
| 162 |
+
# --- Pages ---
|
| 163 |
+
|
| 164 |
+
# View Users
|
| 165 |
+
if st.session_state.page == "π¦ Dashboard":
|
| 166 |
+
st.title("All Users")
|
| 167 |
+
df = pd.read_sql_query("SELECT * FROM users", conn)
|
| 168 |
+
st.dataframe(df, use_container_width=True)
|
| 169 |
+
|
| 170 |
+
st.title("All Distributors")
|
| 171 |
+
df = pd.read_sql_query("SELECT * FROM dist", conn)
|
| 172 |
+
st.dataframe(df, use_container_width=True)
|
| 173 |
+
|
| 174 |
+
st.title("All Models")
|
| 175 |
+
df = pd.read_sql_query("SELECT * FROM models", conn)
|
| 176 |
+
st.dataframe(df, use_container_width=True)
|
| 177 |
+
|
| 178 |
+
# add user
|
| 179 |
+
elif st.session_state.page == "π€ Add User":
|
| 180 |
+
st.title("All Users")
|
| 181 |
+
df = pd.read_sql_query("SELECT * FROM users", conn)
|
| 182 |
+
st.dataframe(df, use_container_width=True)
|
| 183 |
+
st.title("Add New User")
|
| 184 |
+
with st.form("add_form"):
|
| 185 |
+
name = st.text_input("Enter User Name: ").strip().upper()
|
| 186 |
+
user_type = st.selectbox("User Type", ["Admin", "Standard", "Guest", "Back Office"])
|
| 187 |
+
password = st.text_input("Create Password", type="password")
|
| 188 |
+
submit = st.form_submit_button("Add")
|
| 189 |
+
|
| 190 |
+
if submit:
|
| 191 |
+
if not name or not password:
|
| 192 |
+
st.warning("Please provide both a name and a password.")
|
| 193 |
+
else:
|
| 194 |
+
cursor.execute("INSERT INTO users (name, type, pass) VALUES (?, ?, ?)", (name, user_type, password))
|
| 195 |
+
conn.commit()
|
| 196 |
+
st.success(f"User '{name}' added!")
|
| 197 |
+
st.rerun()
|
| 198 |
+
|
| 199 |
+
st.markdown("---")
|
| 200 |
+
with open("add-bulk.csv", "rb") as f:
|
| 201 |
+
st.download_button("π₯ Download CSV Format", data=f, file_name="add-bulk.csv", mime="text/csv")
|
| 202 |
+
|
| 203 |
+
st.subheader("π Upload CSV to Add Users in Bulk")
|
| 204 |
+
csv_file = st.file_uploader("Upload a CSV file with columns: name, type, pass", type="csv")
|
| 205 |
+
|
| 206 |
+
if csv_file and "processed_bulk_upload" not in st.session_state:
|
| 207 |
+
try:
|
| 208 |
+
df = pd.read_csv(csv_file)
|
| 209 |
+
df.columns = df.columns.str.lower()
|
| 210 |
+
df["name"] = df["name"].str.strip().str.upper()
|
| 211 |
+
for _, row in df.iterrows():
|
| 212 |
+
cursor.execute("INSERT INTO users (name, type, pass) VALUES (?, ?, ?)",
|
| 213 |
+
(row["name"], row["type"], row["pass"]))
|
| 214 |
+
conn.commit()
|
| 215 |
+
st.success(f"{len(df)} users added successfully!")
|
| 216 |
+
st.session_state.processed_bulk_upload = True
|
| 217 |
+
except Exception as e:
|
| 218 |
+
st.error(f"Error processing file: {e}")
|
| 219 |
+
## delete user
|
| 220 |
+
elif st.session_state.page == "ποΈ Delete User":
|
| 221 |
+
st.title("Delete a User")
|
| 222 |
+
df = pd.read_sql_query("SELECT * FROM users", conn)
|
| 223 |
+
|
| 224 |
+
if df.empty:
|
| 225 |
+
st.info("No users found.")
|
| 226 |
+
else:
|
| 227 |
+
st.dataframe(df)
|
| 228 |
+
selected_id = st.selectbox("Select User ID to Delete", df["id"])
|
| 229 |
+
selected_user = df[df["id"] == selected_id]
|
| 230 |
+
st.write("Selected User:")
|
| 231 |
+
st.table(selected_user)
|
| 232 |
+
|
| 233 |
+
if st.button("Delete"):
|
| 234 |
+
cursor.execute("DELETE FROM users WHERE id = ?", (selected_id,))
|
| 235 |
+
conn.commit()
|
| 236 |
+
st.success(f"User with ID {selected_id} deleted.")
|
| 237 |
+
st.rerun()
|
| 238 |
+
|
| 239 |
+
confirm_reset = st.checkbox("Are you sure you want to delete all Users?")
|
| 240 |
+
if st.button("Reset All Users Data"):
|
| 241 |
+
if confirm_reset:
|
| 242 |
+
cursor.execute("DELETE FROM users")
|
| 243 |
+
conn.commit()
|
| 244 |
+
st.success("All users have been deleted.")
|
| 245 |
+
st.rerun()
|
| 246 |
+
else:
|
| 247 |
+
st.info("Please check the box to confirm before resetting the Users.", icon="β οΈ")
|
| 248 |
+
|
| 249 |
+
#add model
|
| 250 |
+
elif st.session_state.page == "β Add/Delete Model":
|
| 251 |
+
st.title("π Existing Models")
|
| 252 |
+
df_models = pd.read_sql_query("SELECT * FROM models", conn)
|
| 253 |
+
if df_models.empty:
|
| 254 |
+
st.info("No models added yet.")
|
| 255 |
+
else:
|
| 256 |
+
st.dataframe(df_models, use_container_width=True)
|
| 257 |
+
|
| 258 |
+
st.markdown("---")
|
| 259 |
+
st.title("β Add New Model")
|
| 260 |
+
|
| 261 |
+
# Add model form
|
| 262 |
+
with st.form("add_model_form"):
|
| 263 |
+
all_brands = df_models["brand"].unique().tolist()
|
| 264 |
+
custom_brand = st.text_input("Or type a new brand (If Brand not in list)")
|
| 265 |
+
selected_brand = st.selectbox("Select a brand", all_brands)
|
| 266 |
+
|
| 267 |
+
brand = custom_brand if custom_brand else selected_brand
|
| 268 |
+
model = st.text_input("Model Name")
|
| 269 |
+
color = st.text_input("Color")
|
| 270 |
+
specs = st.text_area("Specifications")
|
| 271 |
+
submit = st.form_submit_button("Add Model")
|
| 272 |
+
|
| 273 |
+
if submit:
|
| 274 |
+
if not brand or not model or not color or not specs:
|
| 275 |
+
st.warning("Please fill in all fields.")
|
| 276 |
+
else:
|
| 277 |
+
cursor.execute("INSERT INTO models (brand, model, color, specs) VALUES (?, ?, ?, ?)", (brand, model, color, specs))
|
| 278 |
+
conn.commit()
|
| 279 |
+
st.success(f"Model '{model}' added successfully!")
|
| 280 |
+
st.rerun()
|
| 281 |
+
# Download CSV template
|
| 282 |
+
model_template = pd.DataFrame(columns=["brand", "model", "color", "specs"])
|
| 283 |
+
st.download_button("π₯ Download Model CSV Template", model_template.to_csv(index=False).encode(), "model-template.csv", "text/csv")
|
| 284 |
+
# Upload CSV
|
| 285 |
+
st.subheader("π Upload CSV to Add Models in Bulk")
|
| 286 |
+
csv_model_file = st.file_uploader("Upload CSV with columns: model, color, specs", type="csv")
|
| 287 |
+
# Process CSV
|
| 288 |
+
if csv_model_file and "processed_bulk_upload_models" not in st.session_state:
|
| 289 |
+
try:
|
| 290 |
+
df = pd.read_csv(csv_model_file)
|
| 291 |
+
df.columns = df.columns.str.lower()
|
| 292 |
+
for _, row in df.iterrows():
|
| 293 |
+
cursor.execute("INSERT INTO models (brand, model, color, specs) VALUES (?, ?, ?, ?)",
|
| 294 |
+
(row["brand"], row["model"], row["color"], row["specs"]))
|
| 295 |
+
conn.commit()
|
| 296 |
+
st.success(f"{len(df)} models added successfully!")
|
| 297 |
+
st.session_state.processed_bulk_upload_models = True
|
| 298 |
+
except Exception as e:
|
| 299 |
+
st.error(f"Error uploading models: {e}")
|
| 300 |
+
# Delete model
|
| 301 |
+
st.markdown("---")
|
| 302 |
+
st.subheader("ποΈ Delete a Model Entry")
|
| 303 |
+
|
| 304 |
+
# Smart select or input for Brand
|
| 305 |
+
brands = df_models["brand"].unique().tolist()
|
| 306 |
+
|
| 307 |
+
if "selected_brand" not in st.session_state:
|
| 308 |
+
st.session_state.selected_brand = ""
|
| 309 |
+
if "custom_brand" not in st.session_state:
|
| 310 |
+
st.session_state.custom_brand = ""
|
| 311 |
+
|
| 312 |
+
def on_select_brand():
|
| 313 |
+
st.session_state.custom_brand = ""
|
| 314 |
+
|
| 315 |
+
def on_custom_brand():
|
| 316 |
+
st.session_state.selected_brand = ""
|
| 317 |
+
|
| 318 |
+
st.selectbox("Select Existing Brand", options=[""] + brands, key="selected_brand", on_change=on_select_brand)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# Use typed brand if provided, else selected
|
| 322 |
+
brand = st.session_state.custom_brand.strip() if st.session_state.custom_brand.strip() else st.session_state.selected_brand
|
| 323 |
+
|
| 324 |
+
if brand:
|
| 325 |
+
filtered_by_brand = df_models[df_models["brand"] == brand]
|
| 326 |
+
models = filtered_by_brand["model"].unique().tolist()
|
| 327 |
+
|
| 328 |
+
if models:
|
| 329 |
+
selected_model = st.selectbox("Select Model", models)
|
| 330 |
+
filtered_by_model = filtered_by_brand[filtered_by_brand["model"] == selected_model]
|
| 331 |
+
|
| 332 |
+
colors = filtered_by_model["color"].unique().tolist()
|
| 333 |
+
selected_color = st.selectbox("Select Color", colors)
|
| 334 |
+
|
| 335 |
+
filtered_by_color = filtered_by_model[filtered_by_model["color"] == selected_color]
|
| 336 |
+
specs = filtered_by_color["specs"].unique().tolist()
|
| 337 |
+
selected_specs = st.selectbox("Select Specifications", specs)
|
| 338 |
+
|
| 339 |
+
if st.button("Delete Selected Model Entry"):
|
| 340 |
+
cursor.execute(
|
| 341 |
+
"DELETE FROM models WHERE brand = ? AND model = ? AND color = ? AND specs = ?",
|
| 342 |
+
(brand, selected_model, selected_color, selected_specs)
|
| 343 |
+
)
|
| 344 |
+
conn.commit()
|
| 345 |
+
st.success(f"Deleted model: {brand} / {selected_model} / {selected_color}")
|
| 346 |
+
st.rerun()
|
| 347 |
+
else:
|
| 348 |
+
st.info("No models found for selected brand.")
|
| 349 |
+
else:
|
| 350 |
+
st.warning("Please select or type a brand.")
|
| 351 |
+
|
| 352 |
+
# Reset Table Option
|
| 353 |
+
st.markdown("---")
|
| 354 |
+
confirm_reset = st.checkbox("Are you sure you want to delete all models?")
|
| 355 |
+
if st.button("Reset Models Table"):
|
| 356 |
+
if confirm_reset:
|
| 357 |
+
cursor.execute("DELETE FROM models")
|
| 358 |
+
conn.commit()
|
| 359 |
+
st.success("All models have been deleted.")
|
| 360 |
+
st.rerun()
|
| 361 |
+
else:
|
| 362 |
+
st.info("Please check the box to confirm before resetting the models.", icon="β οΈ")
|
| 363 |
+
|
| 364 |
+
# Distribuutor page - Display Existing Distributors
|
| 365 |
+
elif st.session_state.page == "πͺ Add/Delete Distributor":
|
| 366 |
+
st.title("π Existing Distributors")
|
| 367 |
+
df_dist = pd.read_sql_query("SELECT * FROM dist", conn)
|
| 368 |
+
if df_dist.empty:
|
| 369 |
+
st.info("No distributors available.")
|
| 370 |
+
else:
|
| 371 |
+
st.dataframe(df_dist, use_container_width=True)
|
| 372 |
+
|
| 373 |
+
dist_ids = df_dist["id"].tolist()
|
| 374 |
+
dist_id_to_delete = st.selectbox("Select Distributor ID to Delete", dist_ids)
|
| 375 |
+
|
| 376 |
+
if st.button("Delete Selected Distributor"):
|
| 377 |
+
cursor.execute("SELECT name FROM dist WHERE id = ?", (dist_id_to_delete,))
|
| 378 |
+
dist_name = cursor.fetchone()[0]
|
| 379 |
+
cursor.execute("DELETE FROM dist WHERE id = ?", (dist_id_to_delete,))
|
| 380 |
+
cursor.execute("DELETE FROM users WHERE name = ? AND type = 'Guest'", (dist_name,))
|
| 381 |
+
conn.commit()
|
| 382 |
+
st.success("Distributor and corresponding Guest user deleted.")
|
| 383 |
+
st.rerun()
|
| 384 |
+
# Add Distributor form
|
| 385 |
+
st.markdown("---")
|
| 386 |
+
st.title("β Add Distributor")
|
| 387 |
+
|
| 388 |
+
with st.form("add_distributor_form"):
|
| 389 |
+
col1, col2 = st.columns(2)
|
| 390 |
+
with col1:
|
| 391 |
+
dist_name = st.text_input("Distributor Name").strip().upper()
|
| 392 |
+
location = st.text_input("Location").strip().title()
|
| 393 |
+
contact = st.text_input("Contact Number").strip()
|
| 394 |
+
with col2:
|
| 395 |
+
address = st.text_area("Address").strip().title()
|
| 396 |
+
email = st.text_input("Email").strip()
|
| 397 |
+
|
| 398 |
+
submit = st.form_submit_button("Add Distributor")
|
| 399 |
+
|
| 400 |
+
if submit:
|
| 401 |
+
if not dist_name or not address or not location or not contact or not email:
|
| 402 |
+
st.warning("Please fill in all fields.")
|
| 403 |
+
else:
|
| 404 |
+
try:
|
| 405 |
+
cursor.execute("""
|
| 406 |
+
INSERT INTO dist (name, address, location, contact, email, added_by)
|
| 407 |
+
VALUES (?, ?, ?, ?, ?, ?)
|
| 408 |
+
""", (dist_name, address, location, contact, email, st.session_state.username))
|
| 409 |
+
|
| 410 |
+
cursor.execute("""
|
| 411 |
+
INSERT INTO users (name, type, pass) VALUES (?, 'Guest', '1234')
|
| 412 |
+
""", (dist_name,))
|
| 413 |
+
|
| 414 |
+
conn.commit()
|
| 415 |
+
st.success(f"Distributor '{dist_name}' added with Guest login.")
|
| 416 |
+
st.rerun()
|
| 417 |
+
except Exception as e:
|
| 418 |
+
st.error(f"Error adding distributor: {e}")
|
| 419 |
+
# Create Order
|
| 420 |
+
elif st.session_state.page == "Create Order":
|
| 421 |
+
st.header("π¦ Create Order")
|
| 422 |
+
|
| 423 |
+
# Get locations
|
| 424 |
+
cursor.execute("SELECT DISTINCT location FROM dist")
|
| 425 |
+
locations = [row[0] for row in cursor.fetchall()]
|
| 426 |
+
selected_location = st.selectbox("Select Location", locations)
|
| 427 |
+
|
| 428 |
+
# Filtered distributors
|
| 429 |
+
cursor.execute("SELECT name FROM dist WHERE location = ?", (selected_location,))
|
| 430 |
+
distributors = [row[0] for row in cursor.fetchall()]
|
| 431 |
+
selected_dist = st.selectbox("Select Distributor", distributors)
|
| 432 |
+
|
| 433 |
+
# filtered brands then models, colors, specs
|
| 434 |
+
df_models = pd.read_sql_query("SELECT * FROM models", conn)
|
| 435 |
+
brands = df_models["brand"].unique().tolist()
|
| 436 |
+
|
| 437 |
+
if "selected_brand" not in st.session_state:
|
| 438 |
+
st.session_state.selected_brand = ""
|
| 439 |
+
if "custom_brand" not in st.session_state:
|
| 440 |
+
st.session_state.custom_brand = ""
|
| 441 |
+
|
| 442 |
+
def on_select_brand():
|
| 443 |
+
st.session_state.custom_brand = ""
|
| 444 |
+
|
| 445 |
+
def on_custom_brand():
|
| 446 |
+
st.session_state.selected_brand = ""
|
| 447 |
+
|
| 448 |
+
st.selectbox("Select Existing Brand", options=[""] + brands, key="selected_brand", on_change=on_select_brand)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
# Use typed brand if provided, else selected
|
| 452 |
+
brand = st.session_state.custom_brand.strip() if st.session_state.custom_brand.strip() else st.session_state.selected_brand
|
| 453 |
+
|
| 454 |
+
if brand:
|
| 455 |
+
filtered_by_brand = df_models[df_models["brand"] == brand]
|
| 456 |
+
models = filtered_by_brand["model"].unique().tolist()
|
| 457 |
+
|
| 458 |
+
if models:
|
| 459 |
+
selected_model = st.selectbox("Select Model", models)
|
| 460 |
+
filtered_by_model = filtered_by_brand[filtered_by_brand["model"] == selected_model]
|
| 461 |
+
|
| 462 |
+
colors = filtered_by_model["color"].unique().tolist()
|
| 463 |
+
selected_color = st.selectbox("Select Color", colors)
|
| 464 |
+
|
| 465 |
+
filtered_by_color = filtered_by_model[filtered_by_model["color"] == selected_color]
|
| 466 |
+
specs = filtered_by_color["specs"].unique().tolist()
|
| 467 |
+
selected_specs = st.selectbox("Select Specifications", specs)
|
| 468 |
+
|
| 469 |
+
quantity = st.number_input("Quantity", min_value=1, step=1)
|
| 470 |
+
|
| 471 |
+
if st.button("Create Order"):
|
| 472 |
+
now = datetime.now()
|
| 473 |
+
date = now.strftime("%d-%m-%Y")
|
| 474 |
+
time = now.strftime("%H:%M:%S")
|
| 475 |
+
status = "New"
|
| 476 |
+
remark = ""
|
| 477 |
+
added_by = st.session_state["username"]
|
| 478 |
+
update_by = added_by
|
| 479 |
+
|
| 480 |
+
cursor.execute("""
|
| 481 |
+
INSERT INTO po (date, time, dist, location, model, color, spec, quantity, status, remark, added_by, update_by)
|
| 482 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 483 |
+
""", (date, time, selected_dist, selected_location, selected_model, selected_color, selected_specs, quantity, status, remark, added_by, update_by))
|
| 484 |
+
conn.commit()
|
| 485 |
+
st.success("β
Order created successfully!")
|
| 486 |
+
#st.toast("Saved successfully! β
")
|
| 487 |
+
#st.snow()
|
| 488 |
+
st.balloons()
|
| 489 |
+
|
| 490 |
+
# -----------Upate Order page --------------
|
| 491 |
+
# ----------- Update Order page --------------
|
| 492 |
+
if st.session_state.page == "Update Order":
|
| 493 |
+
st.title("π¦ Update Orders")
|
| 494 |
+
if st.button("π Refresh"):
|
| 495 |
+
st.rerun()
|
| 496 |
+
|
| 497 |
+
status_options = ["New", "Processing", "Biling Done", "Dispatched", "Delivered", "Cancelled"]
|
| 498 |
+
selected_status = st.radio("Select Order Status to Filter", status_options, horizontal=True)
|
| 499 |
+
|
| 500 |
+
# Date range filter for Delivered and Cancelled
|
| 501 |
+
date_filter_applied = False
|
| 502 |
+
if selected_status in ["Delivered", "Cancelled"]:
|
| 503 |
+
col1, col2 = st.columns(2)
|
| 504 |
+
with col1:
|
| 505 |
+
start_date = st.date_input("Start Date")
|
| 506 |
+
with col2:
|
| 507 |
+
end_date = st.date_input("End Date")
|
| 508 |
+
date_filter_applied = True
|
| 509 |
+
# Format dates as dd-mm-yyyy
|
| 510 |
+
formatted_start = start_date.strftime("%d-%m-%Y")
|
| 511 |
+
formatted_end = end_date.strftime("%d-%m-%Y")
|
| 512 |
+
|
| 513 |
+
# Build query with optional date range
|
| 514 |
+
base_query = "SELECT * FROM po WHERE status = ?"
|
| 515 |
+
params = [selected_status]
|
| 516 |
+
|
| 517 |
+
if date_filter_applied:
|
| 518 |
+
base_query += " AND date BETWEEN ? AND ?"
|
| 519 |
+
params.extend([formatted_start, formatted_end])
|
| 520 |
+
st.markdown(f"ποΈ Start Date: **{formatted_start}**")
|
| 521 |
+
st.markdown(f"ποΈ End Date: **{formatted_end}**")
|
| 522 |
+
|
| 523 |
+
df_orders = pd.read_sql_query(base_query, conn, params=params)
|
| 524 |
+
|
| 525 |
+
if df_orders.empty:
|
| 526 |
+
st.info(f"No orders with status '{selected_status}' found.")
|
| 527 |
+
else:
|
| 528 |
+
# Filter by distributor
|
| 529 |
+
dist_names = df_orders["dist"].unique().tolist()
|
| 530 |
+
selected_dist = st.selectbox("Select Distributor", dist_names)
|
| 531 |
+
|
| 532 |
+
df_filtered = df_orders[df_orders["dist"] == selected_dist]
|
| 533 |
+
|
| 534 |
+
# β
Show reduced view using st.data_editor
|
| 535 |
+
display_cols = ["id", "location", "model", "color", "spec", "quantity"]
|
| 536 |
+
st.subheader("Orders for Selected Distributor")
|
| 537 |
+
st.data_editor(
|
| 538 |
+
df_filtered[display_cols],
|
| 539 |
+
use_container_width=True,
|
| 540 |
+
disabled=True, # Read-only
|
| 541 |
+
hide_index=True
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# π½ Download full dataset (all columns)
|
| 545 |
+
csv_data = df_filtered.to_csv(index=False).encode("utf-8")
|
| 546 |
+
st.download_button("π₯ Download All Order Details (CSV)", data=csv_data, file_name="orders_full.csv", mime="text/csv")
|
| 547 |
+
|
| 548 |
+
# Select and update order
|
| 549 |
+
order_ids = df_filtered["id"].tolist()
|
| 550 |
+
selected_order_id = st.selectbox("Select Order ID to Update", order_ids)
|
| 551 |
+
selected_order = df_filtered[df_filtered["id"] == selected_order_id].iloc[0]
|
| 552 |
+
|
| 553 |
+
with st.form("update_order_form"):
|
| 554 |
+
new_status = st.selectbox("Update Status", status_options, index=status_options.index(selected_order["status"]))
|
| 555 |
+
new_remark = st.text_area("Remark", value=selected_order["remark"] or "")
|
| 556 |
+
col1, col2 = st.columns(2)
|
| 557 |
+
with col1:
|
| 558 |
+
submit_update = st.form_submit_button("Update Order")
|
| 559 |
+
with col2:
|
| 560 |
+
submit_all = st.form_submit_button("π Update All Orders")
|
| 561 |
+
|
| 562 |
+
if submit_update:
|
| 563 |
+
cursor.execute("""
|
| 564 |
+
UPDATE po SET status = ?, remark = ?, update_by = ?
|
| 565 |
+
WHERE id = ?
|
| 566 |
+
""", (new_status, new_remark.strip(), st.session_state.username, selected_order_id))
|
| 567 |
+
conn.commit()
|
| 568 |
+
st.success(f"Order ID {selected_order_id} updated successfully!")
|
| 569 |
+
st.rerun()
|
| 570 |
+
|
| 571 |
+
if submit_all:
|
| 572 |
+
ids_to_update = df_filtered["id"].tolist()
|
| 573 |
+
for oid in ids_to_update:
|
| 574 |
+
cursor.execute("""
|
| 575 |
+
UPDATE po SET status = ?, remark = ?, update_by = ?
|
| 576 |
+
WHERE id = ?
|
| 577 |
+
""", (new_status, new_remark.strip(), st.session_state.username, oid))
|
| 578 |
+
conn.commit()
|
| 579 |
+
st.success(f"β
{len(ids_to_update)} orders updated successfully!")
|
| 580 |
+
st.rerun()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
#else:
|
| 584 |
+
# st.title("π Home")
|
| 585 |
+
# st.write("Welcome to the Model Manager dashboard.\n\nUse the sidebar to navigate through the application.")
|
| 586 |
+
|
| 587 |
+
# --- Close DB connection ---
|
| 588 |
+
conn.close()
|