Hadeeratef91 commited on
Commit
1c29de4
·
verified ·
1 Parent(s): e5f221a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -107
app.py CHANGED
@@ -4,39 +4,62 @@ from datetime import datetime
4
  from passlib.hash import bcrypt
5
  import os
6
  import shutil
 
 
7
 
8
  # تهيئة الصفحة
9
  st.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")
10
 
 
 
 
 
11
  # إدارة اتصال قاعدة البيانات
12
  def get_db_connection():
13
  conn = sqlite3.connect("complaintsBD.db", check_same_thread=False)
14
  conn.row_factory = sqlite3.Row
15
  return conn
16
 
17
- # إنشاء الجداول إذا لم تكن موجودة
18
  def init_db():
19
  conn = get_db_connection()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  conn.execute("""
21
- CREATE TABLE IF NOT EXISTS users (
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
23
- username TEXT UNIQUE,
24
- password TEXT,
25
- role TEXT
26
- )
27
  """)
 
 
28
  conn.execute("""
29
- CREATE TABLE IF NOT EXISTS complaints (
30
- id INTEGER PRIMARY KEY AUTOINCREMENT,
31
- complaint_id TEXT UNIQUE,
32
- username TEXT,
33
- complaint_text TEXT,
34
- status TEXT,
35
- response TEXT,
36
- timestamp TEXT,
37
- sender_comment TEXT
38
- )
39
  """)
 
40
  conn.commit()
41
  conn.close()
42
 
@@ -81,64 +104,64 @@ def sender_page():
81
  conn = get_db_connection()
82
  username = st.session_state.auth["username"]
83
 
84
- user_complaint_count = conn.execute(
85
- "SELECT COUNT(*) FROM complaints WHERE username = ?",
86
- (username,)
87
- ).fetchone()[0]
 
88
 
89
- complaint_id = f"{username}_{user_complaint_count + 1:06d}"
90
 
91
- complaint_text = st.text_area("📝 اكتب شكواك هنا", key="complaint_input")
92
-
93
- if st.button("📨 إرسال الشكوى"):
94
- if complaint_text.strip():
95
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
96
- conn.execute(
97
- "INSERT INTO complaints (complaint_id, username, complaint_text, status, response, timestamp, sender_comment) VALUES (?, ?, ?, ?, ?, ?, ?)",
98
- (complaint_id, username, complaint_text.strip(), "Pending", "", timestamp, "")
99
- )
100
- conn.commit()
101
- st.success(f"✅ تم إرسال الشكوى بنجاح. معرف الشكوى هو: {complaint_id}")
102
- st.rerun()
103
- else:
104
- st.warning("⚠️ لا يمكن إرسال شكوى فارغة")
105
 
106
- st.subheader("📋 الشكاوى السابقة")
107
- complaints = conn.execute(
108
- "SELECT * FROM complaints WHERE username = ? ORDER BY id DESC",
109
- (username,)
110
- ).fetchall()
111
-
112
- for complaint in complaints:
113
- with st.expander(f"📨 {complaint['complaint_id']} | الحالة: {complaint['status']}"):
114
- st.write(f"📅 تم الإرسال في: {complaint['timestamp']}")
115
- st.write(f"📄 الشكوى: {complaint['complaint_text']}")
116
-
117
- if complaint['response']:
118
- st.success(f"💬 الرد من المسؤول: {complaint['response']}")
119
- st.toast(f"📬 تم الرد على الشكوى رقم {complaint['complaint_id']}")
120
-
121
- comment_key = f"comment_{complaint['complaint_id']}"
122
- sender_comment = st.text_area("🗨️ تعليقك على الرد", value=complaint['sender_comment'] or "", key=comment_key)
123
- if st.button("💬 حفظ التعليق", key=f"save_comment_{complaint['complaint_id']}"):
124
- if sender_comment.strip():
125
- conn2 = get_db_connection()
126
- conn2.execute(
127
- "UPDATE complaints SET sender_comment = ? WHERE complaint_id = ?",
128
- (sender_comment.strip(), complaint['complaint_id'])
129
- )
130
- conn2.commit()
131
- conn2.close()
132
- st.success(" تم حفظ تعليقك على الرد")
133
- st.rerun()
134
-
135
- conn.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  # صفحة مستقبل الشكاوى مع لوحة التحكم الإدارية المحمية
138
  def receiver_page():
139
  st.title("📬 إدارة الشكاوى")
140
 
141
- # تبويب للاختيار بين إدارة الشكاوى والتحكم الإداري
142
  tab1, tab2 = st.tabs(["إدارة الشكاوى", "لوحة التحكم الإدارية"])
143
 
144
  with tab1:
@@ -155,26 +178,13 @@ def receiver_page():
155
  "SELECT * FROM complaints ORDER BY id DESC"
156
  ).fetchall()
157
 
158
- complaints_list = [
159
- {
160
- "complaint_id": row["complaint_id"],
161
- "username": row["username"],
162
- "complaint_text": row["complaint_text"],
163
- "status": row["status"],
164
- "response": row["response"] or "",
165
- "timestamp": row["timestamp"]
166
- }
167
- for row in complaints
168
- ]
169
-
170
- if not complaints_list:
171
  st.info("لا توجد شكاوى حالياً.")
172
  else:
173
  st.subheader("📋 جميع الشكاوى")
174
-
175
  selected_complaint = st.selectbox(
176
  "اختر شكوى للتعامل معها",
177
- complaints_list,
178
  format_func=lambda x: f"{x['complaint_id']} - {x['username']}"
179
  )
180
 
@@ -191,32 +201,22 @@ def receiver_page():
191
 
192
  new_response = st.text_area(
193
  "💬 الرد على الشكوى",
194
- value=selected_complaint["response"]
195
  )
196
 
197
  if st.button("💾 حفظ التعديلات"):
198
- try:
199
- conn.execute(
200
- "UPDATE complaints SET status = ?, response = ? WHERE complaint_id = ?",
201
- (new_status, new_response.strip(), selected_complaint["complaint_id"])
202
- )
203
- conn.commit()
204
- st.success("✅ تم حفظ التعديلات بنجاح")
205
- st.rerun()
206
- except sqlite3.Error as e:
207
- st.error(f"❌ حدث خطأ أثناء الحفظ: {str(e)}")
208
- except sqlite3.Error as e:
209
- st.error(f"❌ حدث خطأ في قاعدة البيانات: {str(e)}")
210
  finally:
211
  conn.close()
212
 
213
  with tab2:
214
  st.title("⚙️ لوحة التحكم الإدارية")
215
-
216
- # كلمة المرور الإدارية (يجب تغييرها في البيئة الإنتاجية)
217
- ADMIN_DB_PASSWORD = "Admin@1234"
218
-
219
- # حقل لإدخال كلمة المرور الإدارية
220
  admin_pass = st.text_input("أدخل كلمة المرور الإدارية:", type="password", key="admin_pass")
221
 
222
  if admin_pass == ADMIN_DB_PASSWORD:
@@ -225,24 +225,22 @@ def receiver_page():
225
  if os.path.exists("complaintsBD.db"):
226
  with open("complaintsBD.db", "rb") as db_file:
227
  st.download_button(
228
- label="📥 تحميل نسخة احتياطية من قاعدة البيانات",
229
  data=db_file,
230
  file_name=f"complaints_backup_{datetime.now().strftime('%Y%m%d')}.db",
231
- mime="application/octet-stream",
232
- key="db_download"
233
  )
234
 
235
- if st.button("🔄 إنشاء نسخة احتياطية جديدة", key="create_backup"):
236
  backup_name = f"backup_{datetime.now().strftime('%Y%m%d_%H%M')}.db"
237
  shutil.copy2("complaintsBD.db", backup_name)
238
  st.success(f"تم إنشاء النسخة الاحتياطية: {backup_name}")
239
-
240
- elif admin_pass: # إذا أدخل كلمة مرور ولكنها خاطئة
241
  st.error("❌ كلمة المرور الإدارية غير صحيحة")
242
 
243
  # الواجهة الرئيسية
244
  def main():
245
- init_db() # التأكد من وجود الجداول
246
 
247
  if not st.session_state.auth["is_logged_in"]:
248
  login_page()
 
4
  from passlib.hash import bcrypt
5
  import os
6
  import shutil
7
+ from dotenv import load_dotenv
8
+ import os
9
 
10
  # تهيئة الصفحة
11
  st.set_page_config(page_title="نظام إدارة الشكاوى", layout="centered")
12
 
13
+ # تحميل متغيرات البيئة
14
+ load_dotenv()
15
+ ADMIN_DB_PASSWORD = os.getenv("ADMIN_DB_PASS", "Admin@1234") # كلمة مرور افتراضية إذا لم يتم تعيينها
16
+
17
  # إدارة اتصال قاعدة البيانات
18
  def get_db_connection():
19
  conn = sqlite3.connect("complaintsBD.db", check_same_thread=False)
20
  conn.row_factory = sqlite3.Row
21
  return conn
22
 
23
+ # إنشاء الجداول والتأكد من وجود جميع الأعمدة
24
  def init_db():
25
  conn = get_db_connection()
26
+
27
+ # إنشاء جدول المستخدمين إذا لم يكن موجوداً
28
+ conn.execute("""
29
+ CREATE TABLE IF NOT EXISTS users (
30
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
31
+ username TEXT UNIQUE,
32
+ password TEXT,
33
+ role TEXT
34
+ )
35
+ """)
36
+
37
+ # إنشاء جدول الشكاوى مع جميع الأعمدة المطلوبة
38
+ conn.execute("""
39
+ CREATE TABLE IF NOT EXISTS complaints (
40
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
41
+ complaint_id TEXT UNIQUE,
42
+ username TEXT,
43
+ complaint_text TEXT,
44
+ status TEXT,
45
+ response TEXT,
46
+ timestamp TEXT,
47
+ sender_comment TEXT DEFAULT ''
48
+ )
49
+ """)
50
+
51
+ # إنشاء جدول معلومات قاعدة البيانات
52
  conn.execute("""
53
+ CREATE TABLE IF NOT EXISTS db_info (
54
+ version INTEGER PRIMARY KEY
55
+ )
 
 
 
56
  """)
57
+
58
+ # إدراج الإصدار الأول إذا لم يكن موجوداً
59
  conn.execute("""
60
+ INSERT OR IGNORE INTO db_info (version) VALUES (1)
 
 
 
 
 
 
 
 
 
61
  """)
62
+
63
  conn.commit()
64
  conn.close()
65
 
 
104
  conn = get_db_connection()
105
  username = st.session_state.auth["username"]
106
 
107
+ try:
108
+ user_complaint_count = conn.execute(
109
+ "SELECT COUNT(*) FROM complaints WHERE username = ?",
110
+ (username,)
111
+ ).fetchone()[0]
112
 
113
+ complaint_id = f"{username}_{user_complaint_count + 1:06d}"
114
 
115
+ complaint_text = st.text_area("📝 اكتب شكواك هنا", key="complaint_input")
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ if st.button("📨 إرسال الشكوى"):
118
+ if complaint_text.strip():
119
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
120
+ conn.execute(
121
+ "INSERT INTO complaints (complaint_id, username, complaint_text, status, response, timestamp, sender_comment) VALUES (?, ?, ?, ?, ?, ?, ?)",
122
+ (complaint_id, username, complaint_text.strip(), "Pending", "", timestamp, "")
123
+ )
124
+ conn.commit()
125
+ st.success(f" تم إرسال الشكوى بنجاح. معرف الشكوى هو: {complaint_id}")
126
+ st.rerun()
127
+ else:
128
+ st.warning("⚠️ لا يمكن إرسال شكوى فارغة")
129
+
130
+ st.subheader("📋 الشكاوى السابقة")
131
+ complaints = conn.execute(
132
+ "SELECT * FROM complaints WHERE username = ? ORDER BY id DESC",
133
+ (username,)
134
+ ).fetchall()
135
+
136
+ for complaint in complaints:
137
+ with st.expander(f"📨 {complaint['complaint_id']} | الحالة: {complaint['status']}"):
138
+ st.write(f"📅 تم الإرسال في: {complaint['timestamp']}")
139
+ st.write(f"📄 الشكوى: {complaint['complaint_text']}")
140
+
141
+ if complaint['response']:
142
+ st.success(f"💬 الرد من المسؤول: {complaint['response']}")
143
+ st.toast(f"📬 تم الرد على الشكوى رقم {complaint['complaint_id']}")
144
+
145
+ comment_key = f"comment_{complaint['complaint_id']}"
146
+ sender_comment = st.text_area("🗨️ تعليقك على الرد",
147
+ value=complaint['sender_comment'] or "",
148
+ key=comment_key)
149
+ if st.button("💬 حفظ التعليق", key=f"save_comment_{complaint['complaint_id']}"):
150
+ if sender_comment.strip():
151
+ conn.execute(
152
+ "UPDATE complaints SET sender_comment = ? WHERE complaint_id = ?",
153
+ (sender_comment.strip(), complaint['complaint_id'])
154
+ )
155
+ conn.commit()
156
+ st.success("✅ تم حفظ تعليقك على الرد")
157
+ st.rerun()
158
+ finally:
159
+ conn.close()
160
 
161
  # صفحة مستقبل الشكاوى مع لوحة التحكم الإدارية المحمية
162
  def receiver_page():
163
  st.title("📬 إدارة الشكاوى")
164
 
 
165
  tab1, tab2 = st.tabs(["إدارة الشكاوى", "لوحة التحكم الإدارية"])
166
 
167
  with tab1:
 
178
  "SELECT * FROM complaints ORDER BY id DESC"
179
  ).fetchall()
180
 
181
+ if not complaints:
 
 
 
 
 
 
 
 
 
 
 
 
182
  st.info("لا توجد شكاوى حالياً.")
183
  else:
184
  st.subheader("📋 جميع الشكاوى")
 
185
  selected_complaint = st.selectbox(
186
  "اختر شكوى للتعامل معها",
187
+ complaints,
188
  format_func=lambda x: f"{x['complaint_id']} - {x['username']}"
189
  )
190
 
 
201
 
202
  new_response = st.text_area(
203
  "💬 الرد على الشكوى",
204
+ value=selected_complaint["response"] or ""
205
  )
206
 
207
  if st.button("💾 حفظ التعديلات"):
208
+ conn.execute(
209
+ "UPDATE complaints SET status = ?, response = ? WHERE complaint_id = ?",
210
+ (new_status, new_response.strip(), selected_complaint["complaint_id"])
211
+ )
212
+ conn.commit()
213
+ st.success("✅ تم حفظ التعديلات بنجاح")
214
+ st.rerun()
 
 
 
 
 
215
  finally:
216
  conn.close()
217
 
218
  with tab2:
219
  st.title("⚙️ لوحة التحكم الإدارية")
 
 
 
 
 
220
  admin_pass = st.text_input("أدخل كلمة المرور الإدارية:", type="password", key="admin_pass")
221
 
222
  if admin_pass == ADMIN_DB_PASSWORD:
 
225
  if os.path.exists("complaintsBD.db"):
226
  with open("complaintsBD.db", "rb") as db_file:
227
  st.download_button(
228
+ label="📥 تحميل نسخة احتياطية",
229
  data=db_file,
230
  file_name=f"complaints_backup_{datetime.now().strftime('%Y%m%d')}.db",
231
+ mime="application/octet-stream"
 
232
  )
233
 
234
+ if st.button("🔄 إنشاء نسخة احتياطية جديدة"):
235
  backup_name = f"backup_{datetime.now().strftime('%Y%m%d_%H%M')}.db"
236
  shutil.copy2("complaintsBD.db", backup_name)
237
  st.success(f"تم إنشاء النسخة الاحتياطية: {backup_name}")
238
+ elif admin_pass:
 
239
  st.error("❌ كلمة المرور الإدارية غير صحيحة")
240
 
241
  # الواجهة الرئيسية
242
  def main():
243
+ init_db() # تهيئة قاعدة البيانات
244
 
245
  if not st.session_state.auth["is_logged_in"]:
246
  login_page()