Hadeeratef91 commited on
Commit
db2d6de
·
verified ·
1 Parent(s): 0db27b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -92
app.py CHANGED
@@ -1,18 +1,35 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import os
 
 
4
  from datetime import datetime
5
 
6
  st.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")
7
 
8
  # -----------------------------------------
9
- # تحميل أو إنشاء ملف CSV
10
- file_path = "complaints.csv"
11
- if os.path.exists(file_path):
12
- df = pd.read_csv(file_path, encoding='utf-8-sig')
13
- else:
14
- df = pd.DataFrame(columns=["complaint_id", "username", "complaint_text", "status", "response", "timestamp"])
15
- df.to_csv(file_path, index=False, encoding='utf-8-sig')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # -----------------------------------------
18
  # تهيئة session state
@@ -22,17 +39,6 @@ if "user_type" not in st.session_state:
22
  st.session_state.user_type = None
23
  if "username" not in st.session_state:
24
  st.session_state.username = ""
25
- if "last_seen_count" not in st.session_state:
26
- st.session_state.last_seen_count = len(df)
27
-
28
- # -----------------------------------------
29
- # تحميل بيانات المستخدمين
30
- users_file = "users.csv"
31
- if os.path.exists(users_file):
32
- users_df = pd.read_csv(users_file, encoding='utf-8-sig')
33
- else:
34
- st.error("⚠️ ملف المستخدمين غير موجود!")
35
- st.stop()
36
 
37
  # -----------------------------------------
38
  # تسجيل الدخول
@@ -40,12 +46,14 @@ if not st.session_state.is_logged_in:
40
  st.title("🔐 تسجيل الدخول")
41
  username = st.text_input("اسم المستخدم")
42
  password = st.text_input("كلمة المرور", type="password")
 
43
  if st.button("تسجيل الدخول"):
44
- user_row = users_df[users_df["username"] == username]
45
- if not user_row.empty:
46
- stored_password = user_row.iloc[0]["password"]
47
- role = user_row.iloc[0]["role"]
48
- if password == str(stored_password):
 
49
  st.session_state.is_logged_in = True
50
  st.session_state.username = username
51
  st.session_state.user_type = "sender" if role == "sender" else "receiver"
@@ -58,52 +66,45 @@ if not st.session_state.is_logged_in:
58
  # -----------------------------------------
59
  # مقدم الشكوى
60
  elif st.session_state.user_type == "sender":
61
- complaint_text = st.text_area("📝 وصف الشكوى", key="complaint_input")
62
 
63
  if st.button("📤 إرسال الشكوى"):
64
- existing_user_complaints = df[df["username"] == st.session_state.username]
65
- prefix = st.session_state.username[:4].lower()
66
- next_id = len(existing_user_complaints) + 1
67
- complaint_id = f"{prefix}_{next_id:06}"
68
-
69
- if complaint_id in df["complaint_id"].values:
70
- st.warning("⚠️ تم إرسال هذه الشكوى مسبقًا بناءً على المعرف!")
71
- elif complaint_text.strip() == "":
72
- st.warning("⚠️ الرجاء إدخال نص الشكوى.")
73
- else:
74
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
75
- new_complaint = {
76
- "complaint_id": complaint_id,
77
- "username": st.session_state.username,
78
- "complaint_text": complaint_text.strip(),
79
- "status": "Pending",
80
- "response": "",
81
- "timestamp": timestamp
82
- }
83
- df = pd.concat([df, pd.DataFrame([new_complaint])], ignore_index=True)
84
- df.to_csv(file_path, index=False, encoding='utf-8-sig')
85
- st.success("✅ تم تقديم الشكوى بنجاح")
86
- st.experimental_rerun()
87
-
88
-
89
-
90
- # عرض الشكاوى الخاصة بالمستخدم
91
- user_complaints = df[df["username"] == st.session_state.username]
92
  st.subheader("📋 الشكاوى السابقة")
93
- for i, row in user_complaints[::-1].iterrows():
94
- with st.expander(f"📨 {row['complaint_id']} | {row['status']}"):
95
- # السماح بالتعديل فقط إذا كانت الشكوى لم يتم الرد عليها
96
- if row["status"].lower() == "pending" and (pd.isna(row["response"]) or row["response"].strip() == ""):
97
- new_text = st.text_area("📝 تعديل الشكوى", value=row['complaint_text'], key=f"edit_{i}")
98
- if st.button("💾 حفظ التعديل", key=f"save_{i}"):
99
- df.at[i, "complaint_text"] = new_text.strip()
100
- df.to_csv(file_path, index=False, encoding='utf-8-sig')
 
 
101
  st.success("✅ تم تعديل الشكوى بنجاح")
102
  st.rerun()
103
  else:
104
- st.info(f"📢 تم تحديث حالة الشكوى إلى: {row['status']}")
105
- if row["response"].strip():
106
- st.success(f"💬 الرد: {row['response']}")
107
 
108
  if st.button("🚪 تسجيل الخروج"):
109
  st.session_state.is_logged_in = False
@@ -115,45 +116,30 @@ elif st.session_state.user_type == "sender":
115
  # مستقبل الشكوى
116
  elif st.session_state.user_type == "receiver":
117
  st.title("📬 إدارة الشكاوى")
118
- if df.empty:
 
 
 
119
  st.info("لا توجد شكاوى حالياً للتعامل معها.")
120
  else:
121
- current_count = len(df)
122
- new_complaints = current_count - st.session_state.last_seen_count
123
- if new_complaints > 0:
124
- st.success(f"📬 تم تقديم {new_complaints} شكوى جديدة منذ آخر زيارة.")
125
- st.session_state.last_seen_count = current_count
126
-
127
  st.subheader("📋 جميع الشكاوى")
128
- selected_index = st.selectbox(
129
- "اختر شكوى للتعامل معها",
130
- df.index,
131
- format_func=lambda i: f"{df.loc[i, 'complaint_id']} - {df.loc[i, 'username']}",
132
- key="select_complaint"
133
- )
134
- selected_row = df.loc[selected_index]
135
 
136
- st.write(f"### ✉️ شكوى: {selected_row['complaint_id']}")
137
- st.write(f"**مقدم الشكوى:** {selected_row['username']}")
138
- st.write(f"**الوصف:** {selected_row['complaint_text']}")
139
 
140
- new_status = st.selectbox("🔄 تحديث الحالة", ["Pending", "In Progress", "Resolved"], index=["Pending", "In Progress", "Resolved"].index(selected_row["status"]))
141
- new_response = st.text_area("📝 الرد على الشكوى", value=selected_row["response"] or "")
142
 
143
  if st.button("💾 حفظ التعديلات"):
144
- df.at[selected_index, "status"] = new_status
145
- df.at[selected_index, "response"] = new_response.strip()
146
- df.to_csv(file_path, index=False, encoding='utf-8-sig')
147
  st.success("✅ تم حفظ التعديلات")
148
  st.rerun()
149
 
150
- st.download_button(
151
- label="📥 تحميل الشكاوى كـ CSV",
152
- data=df.to_csv(index=False, encoding='utf-8-sig'),
153
- file_name="complaints_export.csv",
154
- mime="text/csv"
155
- )
156
-
157
  if st.button("🚪 تسجيل الخروج"):
158
  st.session_state.is_logged_in = False
159
  st.session_state.user_type = None
 
1
  import streamlit as st
2
  import pandas as pd
3
  import os
4
+ import sqlite3
5
+ import bcrypt
6
  from datetime import datetime
7
 
8
  st.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")
9
 
10
  # -----------------------------------------
11
+ # الاتصال بقاعدة البيانات وإنشاء الجداول إذا لم تكن موجودة
12
+ conn = sqlite3.connect("complaints_system.db", check_same_thread=False)
13
+ c = conn.cursor()
14
+
15
+ c.execute('''CREATE TABLE IF NOT EXISTS users (
16
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
17
+ username TEXT UNIQUE,
18
+ password TEXT,
19
+ role TEXT
20
+ )''')
21
+
22
+ c.execute('''CREATE TABLE IF NOT EXISTS complaints (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ complaint_id TEXT UNIQUE,
25
+ username TEXT,
26
+ complaint_text TEXT,
27
+ status TEXT,
28
+ response TEXT,
29
+ timestamp TEXT
30
+ )''')
31
+
32
+ conn.commit()
33
 
34
  # -----------------------------------------
35
  # تهيئة session state
 
39
  st.session_state.user_type = None
40
  if "username" not in st.session_state:
41
  st.session_state.username = ""
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  # -----------------------------------------
44
  # تسجيل الدخول
 
46
  st.title("🔐 تسجيل الدخول")
47
  username = st.text_input("اسم المستخدم")
48
  password = st.text_input("كلمة المرور", type="password")
49
+
50
  if st.button("تسجيل الدخول"):
51
+ c.execute("SELECT * FROM users WHERE username=?", (username,))
52
+ user = c.fetchone()
53
+ if user:
54
+ stored_hashed_password = user[2]
55
+ role = user[3]
56
+ if bcrypt.checkpw(password.encode("utf-8"), stored_hashed_password):
57
  st.session_state.is_logged_in = True
58
  st.session_state.username = username
59
  st.session_state.user_type = "sender" if role == "sender" else "receiver"
 
66
  # -----------------------------------------
67
  # مقدم الشكوى
68
  elif st.session_state.user_type == "sender":
69
+ complaint_text = st.text_area("📝 وصف الشكوى")
70
 
71
  if st.button("📤 إرسال الشكوى"):
72
+ c.execute("SELECT * FROM complaints WHERE username=?", (st.session_state.username,))
73
+ user_complaints = c.fetchall()
74
+ prefix = st.session_state.username[:4].lower()
75
+ next_id = len(user_complaints) + 1
76
+ complaint_id = f"{prefix}_{next_id:06}"
77
+
78
+ c.execute("SELECT * FROM complaints WHERE complaint_id=?", (complaint_id,))
79
+ if c.fetchone():
80
+ st.warning("⚠️ تم إرسال هذه الشكوى مسبقًا بناءً على المعرف!")
81
+ elif complaint_text.strip() == "":
82
+ st.warning("⚠️ الرجاء إدخال نص الشكوى.")
83
+ else:
84
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
85
+ c.execute("INSERT INTO complaints (complaint_id, username, complaint_text, status, response, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
86
+ (complaint_id, st.session_state.username, complaint_text.strip(), "Pending", "", timestamp))
87
+ conn.commit()
88
+ st.success(" تم تقديم الشكوى بنجاح")
89
+ st.experimental_rerun()
90
+
 
 
 
 
 
 
 
 
 
91
  st.subheader("📋 الشكاوى السابقة")
92
+ c.execute("SELECT * FROM complaints WHERE username=? ORDER BY id DESC", (st.session_state.username,))
93
+ complaints = c.fetchall()
94
+ for row in complaints:
95
+ comp_id, username, text, status, response, timestamp = row[1], row[2], row[3], row[4], row[5], row[6]
96
+ with st.expander(f"📨 {comp_id} | {status}"):
97
+ if status.lower() == "pending" and (not response or response.strip() == ""):
98
+ new_text = st.text_area("📝 تعديل الشكوى", value=text, key=f"edit_{comp_id}")
99
+ if st.button("💾 حفظ التعديل", key=f"save_{comp_id}"):
100
+ c.execute("UPDATE complaints SET complaint_text=? WHERE complaint_id=?", (new_text.strip(), comp_id))
101
+ conn.commit()
102
  st.success("✅ تم تعديل الشكوى بنجاح")
103
  st.rerun()
104
  else:
105
+ st.info(f"📢 تم تحديث حالة الشكوى إلى: {status}")
106
+ if response and response.strip():
107
+ st.success(f"💬 الرد: {response}")
108
 
109
  if st.button("🚪 تسجيل الخروج"):
110
  st.session_state.is_logged_in = False
 
116
  # مستقبل الشكوى
117
  elif st.session_state.user_type == "receiver":
118
  st.title("📬 إدارة الشكاوى")
119
+ c.execute("SELECT * FROM complaints")
120
+ complaints = c.fetchall()
121
+
122
+ if not complaints:
123
  st.info("لا توجد شكاوى حالياً للتعامل معها.")
124
  else:
 
 
 
 
 
 
125
  st.subheader("📋 جميع الشكاوى")
126
+ options = {f"{row[1]} - {row[2]}": row for row in complaints}
127
+ selected = st.selectbox("اختر شكوى للتعامل معها", list(options.keys()))
128
+ selected_row = options[selected]
 
 
 
 
129
 
130
+ st.write(f"### ✉️ شكوى: {selected_row[1]}")
131
+ st.write(f"**مقدم الشكوى:** {selected_row[2]}")
132
+ st.write(f"**الوصف:** {selected_row[3]}")
133
 
134
+ new_status = st.selectbox("🔄 تحديث الحالة", ["Pending", "In Progress", "Resolved"], index=["Pending", "In Progress", "Resolved"].index(selected_row[4]))
135
+ new_response = st.text_area("📝 الرد على الشكوى", value=selected_row[5] or "")
136
 
137
  if st.button("💾 حفظ التعديلات"):
138
+ c.execute("UPDATE complaints SET status=?, response=? WHERE complaint_id=?", (new_status, new_response.strip(), selected_row[1]))
139
+ conn.commit()
 
140
  st.success("✅ تم حفظ التعديلات")
141
  st.rerun()
142
 
 
 
 
 
 
 
 
143
  if st.button("🚪 تسجيل الخروج"):
144
  st.session_state.is_logged_in = False
145
  st.session_state.user_type = None