Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617183 unmodified lines22232425262728293031323334353637381 unmodified line4041424344454647484950516 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081095 unmodified lines115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import streamlit as stimport pandas as pdimport osfrom datetime import datetimest.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")# -----------------------------------------# تحميل أو إنشاء ملف CSVfile_path = "complaints.csv"if os.path.exists(file_path):df = pd.read_csv(file_path, encoding='utf-8-sig')else:df = pd.DataFrame(columns=["complaint_id", "username", "complaint_text", "status", "response", "timestamp"])df.to_csv(file_path, index=False, encoding='utf-8-sig')# -----------------------------------------# تهيئة session state3 unmodified linesst.session_state.user_type = Noneif "username" not in st.session_state:st.session_state.username = ""if "last_seen_count" not in st.session_state:st.session_state.last_seen_count = len(df)# -----------------------------------------# تحميل بيانات المستخدمينusers_file = "users.csv"if os.path.exists(users_file):users_df = pd.read_csv(users_file, encoding='utf-8-sig')else:st.error("⚠️ ملف المستخدمين غير موجود!")st.stop()# -----------------------------------------# تسجيل الدخول1 unmodified linest.title("🔐 تسجيل الدخول")username = st.text_input("اسم المستخدم")password = st.text_input("كلمة المرور", type="password")if st.button("تسجيل الدخول"):user_row = users_df[users_df["username"] == username]if not user_row.empty:stored_password = user_row.iloc[0]["password"]role = user_row.iloc[0]["role"]if password == str(stored_password):st.session_state.is_logged_in = Truest.session_state.username = usernamest.session_state.user_type = "sender" if role == "sender" else "receiver"6 unmodified lines# -----------------------------------------# مقدم الشكوىelif st.session_state.user_type == "sender":complaint_text = st.text_area("📝 وصف الشكوى", key="complaint_input")if st.button("📤 إرسال الشكوى"):existing_user_complaints = df[df["username"] == st.session_state.username]prefix = st.session_state.username[:4].lower()next_id = len(existing_user_complaints) + 1complaint_id = f"{prefix}_{next_id:06}"if complaint_id in df["complaint_id"].values:st.warning("⚠️ تم إرسال هذه الشكوى مسبقًا بناءً على المعرف!")elif complaint_text.strip() == "":st.warning("⚠️ الرجاء إدخال نص الشكوى.")else:timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")new_complaint = {"complaint_id": complaint_id,"username": st.session_state.username,"complaint_text": complaint_text.strip(),"status": "Pending","response": "","timestamp": timestamp}df = pd.concat([df, pd.DataFrame([new_complaint])], ignore_index=True)df.to_csv(file_path, index=False, encoding='utf-8-sig')st.success("✅ تم تقديم الشكوى بنجاح")st.experimental_rerun()# عرض الشكاوى الخاصة بالمستخدمuser_complaints = df[df["username"] == st.session_state.username]st.subheader("📋 الشكاوى السابقة")for i, row in user_complaints[::-1].iterrows():with st.expander(f"📨 {row['complaint_id']} | {row['status']}"):# السماح بالتعديل فقط إذا كانت الشكوى لم يتم الرد عليهاif row["status"].lower() == "pending" and (pd.isna(row["response"]) or row["response"].strip() == ""):new_text = st.text_area("📝 تعديل الشكوى", value=row['complaint_text'], key=f"edit_{i}")if st.button("💾 حفظ التعديل", key=f"save_{i}"):df.at[i, "complaint_text"] = new_text.strip()df.to_csv(file_path, index=False, encoding='utf-8-sig')st.success("✅ تم تعديل الشكوى بنجاح")st.rerun()else:st.info(f"📢 تم تحديث حالة الشكوى إلى: {row['status']}")if row["response"].strip():st.success(f"💬 الرد: {row['response']}")if st.button("🚪 تسجيل الخروج"):st.session_state.is_logged_in = False5 unmodified lines# مستقبل الشكوىelif st.session_state.user_type == "receiver":st.title("📬 إدارة الشكاوى")if df.empty:st.info("لا توجد شكاوى حالياً للتعامل معها.")else:current_count = len(df)new_complaints = current_count - st.session_state.last_seen_countif new_complaints > 0:st.success(f"📬 تم تقديم {new_complaints} شكوى جديدة منذ آخر زيارة.")st.session_state.last_seen_count = current_countst.subheader("📋 جميع الشكاوى")selected_index = st.selectbox("اختر شكوى للتعامل معها",df.index,format_func=lambda i: f"{df.loc[i, 'complaint_id']} - {df.loc[i, 'username']}",key="select_complaint")selected_row = df.loc[selected_index]st.write(f"### ✉️ شكوى: {selected_row['complaint_id']}")st.write(f"**مقدم الشكوى:** {selected_row['username']}")st.write(f"**الوصف:** {selected_row['complaint_text']}")new_status = st.selectbox("🔄 تحديث الحالة", ["Pending", "In Progress", "Resolved"], index=["Pending", "In Progress", "Resolved"].index(selected_row["status"]))new_response = st.text_area("📝 الرد على الشكوى", value=selected_row["response"] or "")if st.button("💾 حفظ التعديلات"):df.at[selected_index, "status"] = new_statusdf.at[selected_index, "response"] = new_response.strip()df.to_csv(file_path, index=False, encoding='utf-8-sig')st.success("✅ تم حفظ التعديلات")st.rerun()st.download_button(label="📥 تحميل الشكاوى كـ CSV",data=df.to_csv(index=False, encoding='utf-8-sig'),file_name="complaints_export.csv",mime="text/csv")if st.button("🚪 تسجيل الخروج"):st.session_state.is_logged_in = Falsest.session_state.user_type = None12345678910111213141516171819202122232425262728293031323334353 unmodified lines3940414243441 unmodified line46474849505152535455565758596 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091105 unmodified lines116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import streamlit as stimport pandas as pdimport osimport sqlite3import bcryptfrom datetime import datetimest.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")# -----------------------------------------# الاتصال بقاعدة البيانات وإنشاء الجداول إذا لم تكن موجودةconn = sqlite3.connect("complaints_system.db", check_same_thread=False)c = conn.cursor()c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,username TEXT UNIQUE,password TEXT,role TEXT)''')c.execute('''CREATE TABLE IF NOT EXISTS complaints (id INTEGER PRIMARY KEY AUTOINCREMENT,complaint_id TEXT UNIQUE,username TEXT,complaint_text TEXT,status TEXT,response TEXT,timestamp TEXT)''')conn.commit()# -----------------------------------------# تهيئة session state3 unmodified linesst.session_state.user_type = Noneif "username" not in st.session_state:st.session_state.username = ""# -----------------------------------------# تسجيل الدخول1 unmodified linest.title("🔐 تسجيل الدخول")username = st.text_input("اسم المستخدم")password = st.text_input("كلمة المرور", type="password")if st.button("تسجيل الدخول"):c.execute("SELECT * FROM users WHERE username=?", (username,))user = c.fetchone()if user:stored_hashed_password = user[2]role = user[3]if bcrypt.checkpw(password.encode("utf-8"), stored_hashed_password):st.session_state.is_logged_in = Truest.session_state.username = usernamest.session_state.user_type = "sender" if role == "sender" else "receiver"6 unmodified lines# -----------------------------------------# مقدم الشكوىelif st.session_state.user_type == "sender":complaint_text = st.text_area("📝 وصف الشكوى")if st.button("📤 إرسال الشكوى"):c.execute("SELECT * FROM complaints WHERE username=?", (st.session_state.username,))user_complaints = c.fetchall()prefix = st.session_state.username[:4].lower()next_id = len(user_complaints) + 1complaint_id = f"{prefix}_{next_id:06}"c.execute("SELECT * FROM complaints WHERE complaint_id=?", (complaint_id,))if c.fetchone():st.warning("⚠️ تم إرسال هذه الشكوى مسبقًا بناءً على المعرف!")elif complaint_text.strip() == "":st.warning("⚠️ الرجاء إدخال نص الشكوى.")else:timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")c.execute("INSERT INTO complaints (complaint_id, username, complaint_text, status, response, timestamp) VALUES (?, ?, ?, ?, ?, ?)",(complaint_id, st.session_state.username, complaint_text.strip(), "Pending", "", timestamp))conn.commit()st.success("✅ تم تقديم الشكوى بنجاح")st.experimental_rerun()st.subheader("📋 الشكاوى السابقة")c.execute("SELECT * FROM complaints WHERE username=? ORDER BY id DESC", (st.session_state.username,))complaints = c.fetchall()for row in complaints:comp_id, username, text, status, response, timestamp = row[1], row[2], row[3], row[4], row[5], row[6]with st.expander(f"📨 {comp_id} | {status}"):if status.lower() == "pending" and (not response or response.strip() == ""):new_text = st.text_area("📝 تعديل الشكوى", value=text, key=f"edit_{comp_id}")if st.button("💾 حفظ التعديل", key=f"save_{comp_id}"):c.execute("UPDATE complaints SET complaint_text=? WHERE complaint_id=?", (new_text.strip(), comp_id))conn.commit()st.success("✅ تم تعديل الشكوى بنجاح")st.rerun()else:st.info(f"📢 تم تحديث حالة الشكوى إلى: {status}")if response and response.strip():st.success(f"💬 الرد: {response}")if st.button("🚪 تسجيل الخروج"):st.session_state.is_logged_in = False5 unmodified lines# مستقبل الشكوىelif st.session_state.user_type == "receiver":st.title("📬 إدارة الشكاوى")c.execute("SELECT * FROM complaints")complaints = c.fetchall()if not complaints:st.info("لا توجد شكاوى حالياً للتعامل معها.")else:st.subheader("📋 جميع الشكاوى")options = {f"{row[1]} - {row[2]}": row for row in complaints}selected = st.selectbox("اختر شكوى للتعامل معها", list(options.keys()))selected_row = options[selected]st.write(f"### ✉️ شكوى: {selected_row[1]}")st.write(f"**مقدم الشكوى:** {selected_row[2]}")st.write(f"**الوصف:** {selected_row[3]}")new_status = st.selectbox("🔄 تحديث الحالة", ["Pending", "In Progress", "Resolved"], index=["Pending", "In Progress", "Resolved"].index(selected_row[4]))new_response = st.text_area("📝 الرد على الشكوى", value=selected_row[5] or "")if st.button("💾 حفظ التعديلات"):c.execute("UPDATE complaints SET status=?, response=? WHERE complaint_id=?", (new_status, new_response.strip(), selected_row[1]))conn.commit()st.success("✅ تم حفظ التعديلات")st.rerun()if st.button("🚪 تسجيل الخروج"):st.session_state.is_logged_in = Falsest.session_state.user_type = None
app.py+78-92