File size: 55,571 Bytes
25d2b3e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
وحدة نظام الإشعارات الذكي لتحديثات المشروع والتنبيهات
تتيح هذه الوحدة متابعة تحديثات المشاريع وإرسال تنبيهات ذكية مخصصة للمستخدمين بناءً على أدوارهم واهتماماتهم
"""
import os
import sys
import streamlit as st
import pandas as pd
import numpy as np
import json
import datetime
import time
import threading
import logging
from typing import List, Dict, Any, Tuple, Optional, Union
# إضافة مسار النظام للوصول للملفات المشتركة
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
# استيراد مكونات واجهة المستخدم
from utils.components.header import render_header
from utils.components.credits import render_credits
from utils.helpers import format_number, format_currency, styled_button
class SmartNotificationSystem:
"""فئة نظام الإشعارات الذكي لتحديثات المشروع والتنبيهات"""
def __init__(self):
"""تهيئة نظام الإشعارات الذكي"""
# تهيئة مجلدات حفظ البيانات
self.data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data/notifications"))
os.makedirs(self.data_dir, exist_ok=True)
# تهيئة قائمة الإشعارات
if 'notifications' not in st.session_state:
st.session_state.notifications = []
if 'unread_count' not in st.session_state:
st.session_state.unread_count = 0
if 'notification_channels' not in st.session_state:
st.session_state.notification_channels = {
"browser": True,
"email": False,
"sms": False,
"mobile_app": False
}
if 'notification_preferences' not in st.session_state:
st.session_state.notification_preferences = {
"project_updates": True,
"document_analysis": True,
"deadline_reminders": True,
"risk_alerts": True,
"price_changes": True,
"team_mentions": True,
"system_updates": True
}
# تحميل الإشعارات المحفوظة
self._load_notifications()
# تسجيل الأحداث
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.join(self.data_dir, "notifications.log")),
logging.StreamHandler()
]
)
self.logger = logging.getLogger("smart_notifications")
def render(self):
"""عرض واجهة نظام الإشعارات الذكي"""
render_header("نظام الإشعارات الذكي")
# تبويبات الوحدة
tabs = st.tabs([
"جميع الإشعارات",
"إشعارات غير مقروءة",
"إعدادات الإشعارات",
"جدولة الإشعارات",
"تقارير وإحصائيات"
])
# تبويب جميع الإشعارات
with tabs[0]:
self._render_all_notifications()
# تبويب الإشعارات غير المقروءة
with tabs[1]:
self._render_unread_notifications()
# تبويب إعدادات الإشعارات
with tabs[2]:
self._render_notification_settings()
# تبويب جدولة الإشعارات
with tabs[3]:
self._render_notification_scheduling()
# تبويب تقارير وإحصائيات
with tabs[4]:
self._render_notification_analytics()
# عرض حقوق النشر
render_credits()
def _render_all_notifications(self):
"""عرض جميع الإشعارات"""
st.markdown("""
<div class='custom-box info-box'>
<h3>🔔 جميع الإشعارات</h3>
<p>عرض كافة الإشعارات والتنبيهات الخاصة بالمشاريع والنظام.</p>
</div>
""", unsafe_allow_html=True)
# أزرار التحكم
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
if styled_button("تحديث الإشعارات", key="refresh_notifications", type="primary", icon="🔄"):
self._load_notifications()
st.success("تم تحديث الإشعارات بنجاح")
with col2:
if styled_button("تعليم الكل كمقروء", key="mark_all_read", type="secondary", icon="✓"):
self._mark_all_as_read()
st.success("تم تعليم جميع الإشعارات كمقروءة")
with col3:
if styled_button("حذف جميع الإشعارات", key="clear_notifications", type="danger", icon="🗑️"):
confirmed = st.text_input("اكتب 'تأكيد' لحذف جميع الإشعارات", key="confirm_clear")
if confirmed == "تأكيد":
self._clear_all_notifications()
st.success("تم حذف جميع الإشعارات بنجاح")
# فلترة الإشعارات
filter_col1, filter_col2 = st.columns(2)
with filter_col1:
notification_type = st.multiselect(
"تصفية حسب النوع",
options=[
"تحديث مشروع", "وثيقة جديدة", "تذكير موعد نهائي",
"تنبيه مخاطر", "تغيير سعر", "إشارة فريق العمل", "تحديث النظام"
],
key="filter_notification_type"
)
with filter_col2:
date_range = st.date_input(
"نطاق التاريخ",
value=(
datetime.datetime.now() - datetime.timedelta(days=30),
datetime.datetime.now()
),
key="filter_date_range"
)
# تصفية الإشعارات
filtered_notifications = self._filter_notifications(
notification_type=notification_type,
date_range=date_range
)
# عرض الإشعارات المصفاة
if filtered_notifications:
for notification in filtered_notifications:
self._render_notification_card(notification)
else:
st.info("لا توجد إشعارات متاحة")
def _render_unread_notifications(self):
"""عرض الإشعارات غير المقروءة"""
st.markdown("""
<div class='custom-box info-box'>
<h3>🔔 الإشعارات غير المقروءة</h3>
<p>عرض الإشعارات والتنبيهات التي لم تتم قراءتها بعد.</p>
</div>
""", unsafe_allow_html=True)
# أزرار التحكم
col1, col2 = st.columns(2)
with col1:
if styled_button("تحديث الإشعارات", key="refresh_unread", type="primary", icon="🔄"):
self._load_notifications()
st.success("تم تحديث الإشعارات بنجاح")
with col2:
if styled_button("تعليم الكل كمقروء", key="mark_unread_read", type="secondary", icon="✓"):
self._mark_all_as_read()
st.success("تم تعليم جميع الإشعارات كمقروءة")
# فلترة الإشعارات غير المقروءة
unread_notifications = [n for n in st.session_state.notifications if not n.get("read", False)]
# عرض الإشعارات غير المقروءة
if unread_notifications:
for notification in unread_notifications:
self._render_notification_card(notification, show_mark_button=True)
else:
st.success("لا توجد إشعارات غير مقروءة")
def _render_notification_settings(self):
"""عرض إعدادات الإشعارات"""
st.markdown("""
<div class='custom-box info-box'>
<h3>⚙️ إعدادات الإشعارات</h3>
<p>تخصيص إعدادات وتفضيلات الإشعارات الخاصة بك.</p>
</div>
""", unsafe_allow_html=True)
# قسم قنوات الإشعارات
st.markdown("### قنوات الإشعارات")
st.markdown("حدد الطرق التي ترغب في تلقي الإشعارات من خلالها.")
channels_col1, channels_col2 = st.columns(2)
with channels_col1:
st.session_state.notification_channels["browser"] = st.checkbox(
"إشعارات المتصفح",
value=st.session_state.notification_channels.get("browser", True),
key="channel_browser"
)
st.session_state.notification_channels["email"] = st.checkbox(
"البريد الإلكتروني",
value=st.session_state.notification_channels.get("email", False),
key="channel_email"
)
if st.session_state.notification_channels["email"]:
email = st.text_input(
"البريد الإلكتروني للإشعارات",
value=st.session_state.get("notification_email", ""),
key="notification_email"
)
st.session_state.notification_email = email
with channels_col2:
st.session_state.notification_channels["sms"] = st.checkbox(
"الرسائل النصية (SMS)",
value=st.session_state.notification_channels.get("sms", False),
key="channel_sms"
)
if st.session_state.notification_channels["sms"]:
phone = st.text_input(
"رقم الهاتف للإشعارات",
value=st.session_state.get("notification_phone", ""),
key="notification_phone"
)
st.session_state.notification_phone = phone
st.session_state.notification_channels["mobile_app"] = st.checkbox(
"تطبيق الهاتف المحمول",
value=st.session_state.notification_channels.get("mobile_app", False),
key="channel_mobile_app"
)
# قسم تفضيلات الإشعارات
st.markdown("### أنواع الإشعارات")
st.markdown("حدد أنواع الإشعارات التي ترغب في تلقيها.")
prefs_col1, prefs_col2 = st.columns(2)
with prefs_col1:
st.session_state.notification_preferences["project_updates"] = st.checkbox(
"تحديثات المشاريع",
value=st.session_state.notification_preferences.get("project_updates", True),
key="pref_project_updates"
)
st.session_state.notification_preferences["document_analysis"] = st.checkbox(
"تحليل المستندات",
value=st.session_state.notification_preferences.get("document_analysis", True),
key="pref_document_analysis"
)
st.session_state.notification_preferences["deadline_reminders"] = st.checkbox(
"تذكيرات المواعيد النهائية",
value=st.session_state.notification_preferences.get("deadline_reminders", True),
key="pref_deadline_reminders"
)
st.session_state.notification_preferences["risk_alerts"] = st.checkbox(
"تنبيهات المخاطر",
value=st.session_state.notification_preferences.get("risk_alerts", True),
key="pref_risk_alerts"
)
with prefs_col2:
st.session_state.notification_preferences["price_changes"] = st.checkbox(
"تغييرات الأسعار",
value=st.session_state.notification_preferences.get("price_changes", True),
key="pref_price_changes"
)
st.session_state.notification_preferences["team_mentions"] = st.checkbox(
"إشارات فريق العمل",
value=st.session_state.notification_preferences.get("team_mentions", True),
key="pref_team_mentions"
)
st.session_state.notification_preferences["system_updates"] = st.checkbox(
"تحديثات النظام",
value=st.session_state.notification_preferences.get("system_updates", True),
key="pref_system_updates"
)
# إعدادات التكرار
st.markdown("### إعدادات التكرار")
frequency = st.radio(
"تكرار الإشعارات المتشابهة",
options=["فوري", "تجميع كل ساعة", "تجميع كل يوم", "مخصص"],
index=0,
key="notification_frequency"
)
if frequency == "مخصص":
custom_hours = st.number_input(
"التجميع كل (ساعات)",
min_value=1,
max_value=24,
value=4,
key="custom_frequency_hours"
)
st.session_state.custom_frequency_hours = custom_hours
# إعدادات متقدمة
with st.expander("إعدادات متقدمة"):
st.checkbox(
"عرض الإشعارات عند بدء تشغيل النظام",
value=True,
key="show_on_startup"
)
st.checkbox(
"الإشعارات الصوتية",
value=False,
key="audio_notifications"
)
st.checkbox(
"حفظ سجل الإشعارات",
value=True,
key="log_notifications"
)
# استدعاء القيمة من session_state إذا كانت موجودة أو استخدام القيمة الافتراضية
retention_days = st.slider(
"الاحتفاظ بالإشعارات (أيام)",
min_value=7,
max_value=365,
value=st.session_state.get("retention_days_value", 90),
key="retention_days"
)
# حفظ القيمة في مفتاح آخر بعد تحديثها عن طريق المستخدم
if "retention_days_value" not in st.session_state:
st.session_state.retention_days_value = retention_days
# زر حفظ الإعدادات
if styled_button("حفظ الإعدادات", key="save_notification_settings", type="primary", icon="💾"):
self._save_notification_settings()
st.success("تم حفظ إعدادات الإشعارات بنجاح")
def _render_notification_scheduling(self):
"""عرض واجهة جدولة الإشعارات"""
st.markdown("""
<div class='custom-box info-box'>
<h3>🕒 جدولة الإشعارات</h3>
<p>إنشاء وإدارة الإشعارات المجدولة والتذكيرات الدورية.</p>
</div>
""", unsafe_allow_html=True)
# إنشاء تذكير جديد
st.markdown("### إنشاء تذكير جديد")
col1, col2 = st.columns(2)
with col1:
reminder_name = st.text_input("عنوان التذكير", key="new_reminder_name")
reminder_desc = st.text_area("وصف التذكير", key="new_reminder_desc")
reminder_date = st.date_input("تاريخ التذكير", key="new_reminder_date")
reminder_time = st.time_input("وقت التذكير", key="new_reminder_time")
with col2:
reminder_type = st.selectbox(
"نوع التذكير",
options=[
"موعد نهائي للمناقصة",
"اجتماع مشروع",
"زيارة موقع",
"تسليم مستندات",
"دفعة مالية",
"مراجعة أداء",
"أخرى"
],
key="new_reminder_type"
)
reminder_priority = st.select_slider(
"الأولوية",
options=["منخفضة", "متوسطة", "عالية", "حرجة"],
value="متوسطة",
key="new_reminder_priority"
)
reminder_repeat = st.selectbox(
"التكرار",
options=[
"مرة واحدة",
"يومياً",
"أسبوعياً",
"شهرياً",
"سنوياً"
],
key="new_reminder_repeat"
)
if reminder_type == "أخرى":
custom_type = st.text_input("حدد نوع التذكير", key="custom_reminder_type")
# زر إضافة التذكير
if styled_button("إضافة التذكير", key="add_reminder", type="primary", icon="➕"):
if not reminder_name or not reminder_desc:
st.error("يرجى تعبئة حقول العنوان والوصف")
else:
self._add_scheduled_notification(
title=reminder_name,
message=reminder_desc,
notification_date=datetime.datetime.combine(reminder_date, reminder_time),
notification_type=reminder_type if reminder_type != "أخرى" else custom_type,
priority=reminder_priority,
repeat=reminder_repeat
)
st.success("تم إضافة التذكير بنجاح")
# عرض التذكيرات المجدولة
st.markdown("### التذكيرات المجدولة")
# التحقق من وجود تذكيرات مجدولة
scheduled_notifications = self._get_scheduled_notifications()
if scheduled_notifications:
# عرض التذكيرات في جدول
scheduled_df = pd.DataFrame(scheduled_notifications)
# تنسيق البيانات للعرض
display_df = scheduled_df.copy()
display_df["التاريخ والوقت"] = display_df["notification_date"].apply(lambda x: x.strftime("%Y-%m-%d %H:%M"))
display_df["العنوان"] = display_df["title"]
display_df["النوع"] = display_df["notification_type"]
display_df["الأولوية"] = display_df["priority"]
display_df["التكرار"] = display_df["repeat"]
# عرض الجدول
st.dataframe(
display_df[["العنوان", "النوع", "التاريخ والوقت", "الأولوية", "التكرار"]],
use_container_width=True
)
# عرض الإشعارات المجدولة كبطاقات
for notification in scheduled_notifications:
with st.expander(f"{notification['title']} - {notification['notification_date'].strftime('%Y-%m-%d %H:%M')}"):
notification_col1, notification_col2 = st.columns([3, 1])
with notification_col1:
st.markdown(f"**الوصف:** {notification['message']}")
st.markdown(f"**النوع:** {notification['notification_type']}")
st.markdown(f"**الأولوية:** {notification['priority']}")
st.markdown(f"**التكرار:** {notification['repeat']}")
with notification_col2:
if styled_button("تعديل", key=f"edit_{notification['id']}", type="secondary", icon="✏️"):
# تنفيذ في المرحلة القادمة
st.info("ميزة التعديل قيد التطوير")
if styled_button("حذف", key=f"delete_{notification['id']}", type="danger", icon="🗑️"):
self._delete_scheduled_notification(notification['id'])
st.rerun()
else:
st.info("لا توجد تذكيرات مجدولة")
def _render_notification_analytics(self):
"""عرض تقارير وإحصائيات الإشعارات"""
st.markdown("""
<div class='custom-box info-box'>
<h3>📊 تقارير وإحصائيات الإشعارات</h3>
<p>تحليل وعرض إحصائيات الإشعارات والتنبيهات.</p>
</div>
""", unsafe_allow_html=True)
# إحصائيات عامة
st.markdown("### إحصائيات عامة")
# التحقق من وجود إشعارات
if st.session_state.notifications:
# إعداد البيانات
total_count = len(st.session_state.notifications)
read_count = len([n for n in st.session_state.notifications if n.get("read", False)])
unread_count = total_count - read_count
# تصنيف الإشعارات حسب النوع
notification_types = {}
for notification in st.session_state.notifications:
notification_type = notification.get("notification_type", "أخرى")
notification_types[notification_type] = notification_types.get(notification_type, 0) + 1
# عرض الإحصائيات
metric_col1, metric_col2, metric_col3 = st.columns(3)
with metric_col1:
st.metric("إجمالي الإشعارات", total_count)
with metric_col2:
st.metric("الإشعارات المقروءة", read_count, delta=f"{read_count/total_count*100:.1f}%" if total_count > 0 else "0%")
with metric_col3:
st.metric("الإشعارات غير المقروءة", unread_count, delta=f"{unread_count/total_count*100:.1f}%" if total_count > 0 else "0%")
# رسم بياني لتوزيع الإشعارات حسب النوع
st.markdown("### توزيع الإشعارات حسب النوع")
# إنشاء DataFrame للرسم البياني
types_df = pd.DataFrame({
"النوع": list(notification_types.keys()),
"العدد": list(notification_types.values())
})
# رسم بياني دائري
import plotly.express as px
fig = px.pie(
types_df,
values="العدد",
names="النوع",
title="توزيع الإشعارات حسب النوع",
color_discrete_sequence=px.colors.sequential.RdBu
)
fig.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig, use_container_width=True)
# رسم بياني لتوزيع الإشعارات حسب الوقت
st.markdown("### توزيع الإشعارات حسب الوقت")
# تحويل التواريخ إلى DataFrame
dates = [
n.get("timestamp", datetime.datetime.now()).replace(hour=0, minute=0, second=0, microsecond=0)
for n in st.session_state.notifications
if "timestamp" in n
]
if dates:
date_counts = pd.Series(dates).value_counts().sort_index()
# إنشاء DataFrame للرسم البياني
date_df = pd.DataFrame({
"التاريخ": date_counts.index,
"العدد": date_counts.values
})
# رسم بياني خطي
fig2 = px.line(
date_df,
x="التاريخ",
y="العدد",
title="توزيع الإشعارات حسب التاريخ",
markers=True
)
fig2.update_layout(
title_font_size=20,
font_family="Arial",
font_size=14,
height=400
)
st.plotly_chart(fig2, use_container_width=True)
# تصدير البيانات
st.markdown("### تصدير بيانات الإشعارات")
export_col1, export_col2 = st.columns(2)
with export_col1:
if styled_button("تصدير CSV", key="export_csv", type="primary", icon="📄"):
# تحويل الإشعارات إلى DataFrame
export_df = pd.DataFrame(st.session_state.notifications)
# تنسيق البيانات
if "timestamp" in export_df.columns:
export_df["timestamp"] = export_df["timestamp"].apply(
lambda x: x.strftime("%Y-%m-%d %H:%M:%S") if isinstance(x, datetime.datetime) else str(x)
)
# تصدير إلى CSV
csv_data = export_df.to_csv(index=False)
# تنزيل الملف
st.download_button(
label="تنزيل ملف CSV",
data=csv_data,
file_name=f"notifications_export_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv"
)
with export_col2:
if styled_button("تصدير JSON", key="export_json", type="primary", icon="📄"):
# تنسيق البيانات
export_data = []
for notification in st.session_state.notifications:
export_item = notification.copy()
if "timestamp" in export_item and isinstance(export_item["timestamp"], datetime.datetime):
export_item["timestamp"] = export_item["timestamp"].strftime("%Y-%m-%d %H:%M:%S")
export_data.append(export_item)
# تحويل إلى JSON
json_data = json.dumps(export_data, ensure_ascii=False, indent=2)
# تنزيل الملف
st.download_button(
label="تنزيل ملف JSON",
data=json_data,
file_name=f"notifications_export_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
mime="application/json"
)
else:
st.info("لا توجد بيانات كافية لعرض الرسم البياني")
else:
st.info("لا توجد إشعارات لعرض الإحصائيات")
def _render_notification_card(self, notification, show_mark_button=False):
"""عرض بطاقة إشعار"""
# تعيين نمط البطاقة حسب الأولوية والحالة
card_style = "notification-card"
if not notification.get("read", False):
card_style += " unread-notification"
priority = notification.get("priority", "متوسطة")
if priority == "عالية" or priority == "حرجة":
card_style += " high-priority-notification"
# تعيين الأيقونة حسب نوع الإشعار
icon_map = {
"تحديث مشروع": "🔄",
"وثيقة جديدة": "📄",
"تذكير موعد نهائي": "⏰",
"تنبيه مخاطر": "⚠️",
"تغيير سعر": "💰",
"إشارة فريق العمل": "👥",
"تحديث النظام": "🖥️"
}
notification_type = notification.get("notification_type", "تحديث مشروع")
icon = icon_map.get(notification_type, "🔔")
# تنسيق التاريخ
timestamp = notification.get("timestamp", datetime.datetime.now())
if isinstance(timestamp, datetime.datetime):
time_str = timestamp.strftime("%Y-%m-%d %H:%M")
else:
time_str = str(timestamp)
# إنشاء HTML للبطاقة
card_html = f"""
<div class="{card_style}">
<div class="notification-header">
<span class="notification-icon">{icon}</span>
<span class="notification-title">{notification.get('title', 'إشعار جديد')}</span>
<span class="notification-time">{time_str}</span>
</div>
<div class="notification-body">
<p>{notification.get('message', '')}</p>
</div>
<div class="notification-footer">
<span class="notification-type">{notification_type}</span>
<span class="notification-priority">{priority}</span>
</div>
</div>
"""
# عرض البطاقة
st.markdown(card_html, unsafe_allow_html=True)
# إضافة أزرار التحكم
if show_mark_button:
col1, col2 = st.columns([1, 4])
with col1:
if styled_button("تعليم كمقروء", key=f"mark_read_{notification.get('id', '')}", type="secondary", icon="✓"):
self._mark_notification_as_read(notification.get('id', ''))
st.rerun()
with col2:
if notification.get("link"):
if styled_button("عرض التفاصيل", key=f"view_details_{notification.get('id', '')}", type="primary", icon="🔍"):
# افتح الرابط المرتبط بالإشعار
# ملاحظة: هذا سيعمل بشكل مختلف حسب بيئة التشغيل
st.markdown(f"[عرض التفاصيل]({notification.get('link')})")
def add_notification(self, title, message, notification_type="تحديث مشروع", priority="متوسطة", link=None):
"""
إضافة إشعار جديد
المعلمات:
title: عنوان الإشعار
message: نص الإشعار
notification_type: نوع الإشعار
priority: أولوية الإشعار
link: رابط مرتبط بالإشعار (اختياري)
الإرجاع:
معرف الإشعار الجديد
"""
# إنشاء معرف فريد للإشعار
notification_id = f"notif_{int(time.time())}_{len(st.session_state.notifications)}"
# إنشاء كائن الإشعار
notification = {
"id": notification_id,
"title": title,
"message": message,
"notification_type": notification_type,
"priority": priority,
"read": False,
"timestamp": datetime.datetime.now(),
"link": link
}
# إضافة الإشعار لقائمة الإشعارات
st.session_state.notifications.append(notification)
# زيادة عداد الإشعارات غير المقروءة
st.session_state.unread_count += 1
# حفظ الإشعارات
self._save_notifications()
# تسجيل الإشعار
self.logger.info(
f"تمت إضافة إشعار جديد: {title} ({notification_type})"
)
return notification_id
def _mark_notification_as_read(self, notification_id):
"""
تعليم إشعار كمقروء
المعلمات:
notification_id: معرف الإشعار
الإرجاع:
قيمة بوليانية تشير إلى نجاح العملية
"""
# البحث عن الإشعار
for i, notification in enumerate(st.session_state.notifications):
if notification.get("id") == notification_id and not notification.get("read", False):
# تعليم الإشعار كمقروء
st.session_state.notifications[i]["read"] = True
# تحديث عداد الإشعارات غير المقروءة
st.session_state.unread_count = max(0, st.session_state.unread_count - 1)
# حفظ الإشعارات
self._save_notifications()
return True
return False
def _mark_all_as_read(self):
"""
تعليم جميع الإشعارات كمقروءة
الإرجاع:
عدد الإشعارات التي تم تعليمها
"""
count = 0
# تعليم جميع الإشعارات كمقروءة
for i, notification in enumerate(st.session_state.notifications):
if not notification.get("read", False):
st.session_state.notifications[i]["read"] = True
count += 1
# إعادة تعيين عداد الإشعارات غير المقروءة
st.session_state.unread_count = 0
# حفظ الإشعارات
self._save_notifications()
return count
def _clear_all_notifications(self):
"""
حذف جميع الإشعارات
الإرجاع:
عدد الإشعارات التي تم حذفها
"""
count = len(st.session_state.notifications)
# مسح قائمة الإشعارات
st.session_state.notifications = []
# إعادة تعيين عداد الإشعارات غير المقروءة
st.session_state.unread_count = 0
# حفظ الإشعارات
self._save_notifications()
return count
def _filter_notifications(self, notification_type=None, date_range=None):
"""
تصفية الإشعارات حسب النوع والتاريخ
المعلمات:
notification_type: قائمة أنواع الإشعارات
date_range: نطاق تاريخ الإشعارات
الإرجاع:
قائمة الإشعارات المصفاة
"""
filtered_notifications = st.session_state.notifications.copy()
# تصفية حسب النوع
if notification_type and len(notification_type) > 0:
filtered_notifications = [
n for n in filtered_notifications
if n.get("notification_type") in notification_type
]
# تصفية حسب نطاق التاريخ
if date_range and len(date_range) == 2:
start_date, end_date = date_range
# تحويل التواريخ إلى datetime
start_date = datetime.datetime.combine(start_date, datetime.time.min)
end_date = datetime.datetime.combine(end_date, datetime.time.max)
filtered_notifications = [
n for n in filtered_notifications
if isinstance(n.get("timestamp"), datetime.datetime) and
start_date <= n.get("timestamp") <= end_date
]
return filtered_notifications
def _add_scheduled_notification(self, title, message, notification_date, notification_type="تذكير", priority="متوسطة", repeat="مرة واحدة"):
"""
إضافة إشعار مجدول
المعلمات:
title: عنوان الإشعار
message: نص الإشعار
notification_date: تاريخ ووقت الإشعار
notification_type: نوع الإشعار
priority: أولوية الإشعار
repeat: نمط تكرار الإشعار
الإرجاع:
معرف الإشعار المجدول
"""
# إنشاء معرف فريد للإشعار المجدول
scheduled_id = f"sched_{int(time.time())}_{len(self._get_scheduled_notifications())}"
# إنشاء كائن الإشعار المجدول
scheduled_notification = {
"id": scheduled_id,
"title": title,
"message": message,
"notification_date": notification_date,
"notification_type": notification_type,
"priority": priority,
"repeat": repeat,
"created_at": datetime.datetime.now(),
"last_triggered": None
}
# إضافة الإشعار المجدول للقائمة
scheduled_notifications = self._get_scheduled_notifications()
scheduled_notifications.append(scheduled_notification)
# حفظ الإشعارات المجدولة
self._save_scheduled_notifications(scheduled_notifications)
# تسجيل الإشعار المجدول
self.logger.info(
f"تمت إضافة إشعار مجدول: {title} ({notification_date.strftime('%Y-%m-%d %H:%M')})"
)
return scheduled_id
def _delete_scheduled_notification(self, notification_id):
"""
حذف إشعار مجدول
المعلمات:
notification_id: معرف الإشعار المجدول
الإرجاع:
قيمة بوليانية تشير إلى نجاح العملية
"""
scheduled_notifications = self._get_scheduled_notifications()
# البحث عن الإشعار المجدول
for i, notification in enumerate(scheduled_notifications):
if notification.get("id") == notification_id:
# حذف الإشعار المجدول
del scheduled_notifications[i]
# حفظ الإشعارات المجدولة
self._save_scheduled_notifications(scheduled_notifications)
# تسجيل الحذف
self.logger.info(
f"تم حذف الإشعار المجدول: {notification_id}"
)
return True
return False
def _get_scheduled_notifications(self):
"""
الحصول على قائمة الإشعارات المجدولة
الإرجاع:
قائمة الإشعارات المجدولة
"""
try:
# التحقق من وجود ملف الإشعارات المجدولة
scheduled_file = os.path.join(self.data_dir, "scheduled_notifications.json")
if os.path.exists(scheduled_file):
with open(scheduled_file, 'r', encoding='utf-8') as f:
scheduled_data = json.load(f)
# تحويل التواريخ من نصوص إلى كائنات datetime
for notification in scheduled_data:
if "notification_date" in notification:
notification["notification_date"] = datetime.datetime.fromisoformat(notification["notification_date"])
if "created_at" in notification:
notification["created_at"] = datetime.datetime.fromisoformat(notification["created_at"])
if "last_triggered" in notification and notification["last_triggered"]:
notification["last_triggered"] = datetime.datetime.fromisoformat(notification["last_triggered"])
return scheduled_data
return []
except Exception as e:
self.logger.error(f"حدث خطأ أثناء قراءة الإشعارات المجدولة: {str(e)}")
return []
def _save_scheduled_notifications(self, scheduled_notifications):
"""
حفظ قائمة الإشعارات المجدولة
المعلمات:
scheduled_notifications: قائمة الإشعارات المجدولة
"""
try:
# التأكد من وجود المجلد
os.makedirs(self.data_dir, exist_ok=True)
# تحويل كائنات datetime إلى نصوص
scheduled_data = []
for notification in scheduled_notifications:
notification_copy = notification.copy()
if "notification_date" in notification_copy and isinstance(notification_copy["notification_date"], datetime.datetime):
notification_copy["notification_date"] = notification_copy["notification_date"].isoformat()
if "created_at" in notification_copy and isinstance(notification_copy["created_at"], datetime.datetime):
notification_copy["created_at"] = notification_copy["created_at"].isoformat()
if "last_triggered" in notification_copy and isinstance(notification_copy["last_triggered"], datetime.datetime):
notification_copy["last_triggered"] = notification_copy["last_triggered"].isoformat()
scheduled_data.append(notification_copy)
# حفظ البيانات
scheduled_file = os.path.join(self.data_dir, "scheduled_notifications.json")
with open(scheduled_file, 'w', encoding='utf-8') as f:
json.dump(scheduled_data, f, ensure_ascii=False, indent=2)
except Exception as e:
self.logger.error(f"حدث خطأ أثناء حفظ الإشعارات المجدولة: {str(e)}")
def _save_notification_settings(self):
"""حفظ إعدادات الإشعارات"""
try:
# التأكد من وجود المجلد
os.makedirs(self.data_dir, exist_ok=True)
# إعداد البيانات
settings_data = {
"notification_channels": st.session_state.notification_channels,
"notification_preferences": st.session_state.notification_preferences,
"notification_email": st.session_state.get("notification_email", ""),
"notification_phone": st.session_state.get("notification_phone", ""),
"notification_frequency": st.session_state.get("notification_frequency", "فوري"),
"custom_frequency_hours": st.session_state.get("custom_frequency_hours", 4),
"show_on_startup": st.session_state.get("show_on_startup", True),
"audio_notifications": st.session_state.get("audio_notifications", False),
"log_notifications": st.session_state.get("log_notifications", True),
"retention_days": st.session_state.get("retention_days", 90)
}
# حفظ البيانات
settings_file = os.path.join(self.data_dir, "notification_settings.json")
with open(settings_file, 'w', encoding='utf-8') as f:
json.dump(settings_data, f, ensure_ascii=False, indent=2)
# تسجيل الحفظ
self.logger.info("تم حفظ إعدادات الإشعارات بنجاح")
except Exception as e:
self.logger.error(f"حدث خطأ أثناء حفظ إعدادات الإشعارات: {str(e)}")
def _load_notification_settings(self):
"""تحميل إعدادات الإشعارات"""
try:
# التحقق من وجود ملف الإعدادات
settings_file = os.path.join(self.data_dir, "notification_settings.json")
if os.path.exists(settings_file):
with open(settings_file, 'r', encoding='utf-8') as f:
settings_data = json.load(f)
# تحديث حالة الجلسة
st.session_state.notification_channels = settings_data.get("notification_channels", {})
st.session_state.notification_preferences = settings_data.get("notification_preferences", {})
st.session_state.notification_email = settings_data.get("notification_email", "")
st.session_state.notification_phone = settings_data.get("notification_phone", "")
st.session_state.notification_frequency = settings_data.get("notification_frequency", "فوري")
st.session_state.custom_frequency_hours = settings_data.get("custom_frequency_hours", 4)
st.session_state.show_on_startup = settings_data.get("show_on_startup", True)
st.session_state.audio_notifications = settings_data.get("audio_notifications", False)
st.session_state.log_notifications = settings_data.get("log_notifications", True)
st.session_state.retention_days = settings_data.get("retention_days", 90)
# تسجيل التحميل
self.logger.info("تم تحميل إعدادات الإشعارات بنجاح")
except Exception as e:
self.logger.error(f"حدث خطأ أثناء تحميل إعدادات الإشعارات: {str(e)}")
def _save_notifications(self):
"""حفظ الإشعارات"""
try:
# التأكد من وجود المجلد
os.makedirs(self.data_dir, exist_ok=True)
# تحويل كائنات datetime إلى نصوص
notifications_data = []
for notification in st.session_state.notifications:
notification_copy = notification.copy()
if "timestamp" in notification_copy and isinstance(notification_copy["timestamp"], datetime.datetime):
notification_copy["timestamp"] = notification_copy["timestamp"].isoformat()
notifications_data.append(notification_copy)
# حفظ البيانات
notifications_file = os.path.join(self.data_dir, "notifications.json")
with open(notifications_file, 'w', encoding='utf-8') as f:
json.dump(notifications_data, f, ensure_ascii=False, indent=2)
except Exception as e:
self.logger.error(f"حدث خطأ أثناء حفظ الإشعارات: {str(e)}")
def _load_notifications(self):
"""تحميل الإشعارات"""
try:
# التحقق من وجود ملف الإشعارات
notifications_file = os.path.join(self.data_dir, "notifications.json")
if os.path.exists(notifications_file):
with open(notifications_file, 'r', encoding='utf-8') as f:
notifications_data = json.load(f)
# تحويل النصوص إلى كائنات datetime
for notification in notifications_data:
if "timestamp" in notification:
notification["timestamp"] = datetime.datetime.fromisoformat(notification["timestamp"])
# تحديث حالة الجلسة
st.session_state.notifications = notifications_data
# حساب عدد الإشعارات غير المقروءة
st.session_state.unread_count = len([
n for n in st.session_state.notifications
if not n.get("read", False)
])
# تحميل إعدادات الإشعارات
self._load_notification_settings()
# تسجيل التحميل
self.logger.info(f"تم تحميل {len(notifications_data)} إشعار بنجاح")
except Exception as e:
self.logger.error(f"حدث خطأ أثناء تحميل الإشعارات: {str(e)}")
def check_scheduled_notifications(self):
"""
التحقق من الإشعارات المجدولة وإطلاقها إذا حان وقتها
الإرجاع:
عدد الإشعارات التي تم إطلاقها
"""
count = 0
# الحصول على الإشعارات المجدولة
scheduled_notifications = self._get_scheduled_notifications()
# الوقت الحالي
now = datetime.datetime.now()
# التحقق من كل إشعار مجدول
for notification in scheduled_notifications:
notification_date = notification.get("notification_date")
if notification_date and notification_date <= now:
# إنشاء إشعار جديد
self.add_notification(
title=notification.get("title"),
message=notification.get("message"),
notification_type=notification.get("notification_type"),
priority=notification.get("priority")
)
# تحديث آخر مرة تم فيها إطلاق الإشعار
notification["last_triggered"] = now
# التعامل مع التكرار
repeat = notification.get("repeat", "مرة واحدة")
if repeat == "مرة واحدة":
# حذف الإشعار المجدول
self._delete_scheduled_notification(notification.get("id"))
else:
# حساب التاريخ التالي
if repeat == "يومياً":
new_date = notification_date + datetime.timedelta(days=1)
elif repeat == "أسبوعياً":
new_date = notification_date + datetime.timedelta(weeks=1)
elif repeat == "شهرياً":
# إضافة شهر (تقريبي)
new_month = notification_date.month + 1
new_year = notification_date.year
if new_month > 12:
new_month = 1
new_year += 1
new_date = notification_date.replace(year=new_year, month=new_month)
elif repeat == "سنوياً":
new_date = notification_date.replace(year=notification_date.year + 1)
else:
# افتراضي: يومياً
new_date = notification_date + datetime.timedelta(days=1)
# تحديث تاريخ الإشعار المجدول
notification["notification_date"] = new_date
count += 1
# حفظ الإشعارات المجدولة إذا تم تغييرها
if count > 0:
self._save_scheduled_notifications(scheduled_notifications)
return count
# تطبيق وحدة نظام الإشعارات الذكي
class NotificationsApp:
"""وحدة تطبيق نظام الإشعارات الذكي"""
def __init__(self):
"""تهيئة وحدة تطبيق نظام الإشعارات الذكي"""
self.smart_notification_system = SmartNotificationSystem()
def render(self):
"""عرض واجهة وحدة تطبيق نظام الإشعارات الذكي"""
st.markdown("<h2 class='module-title'>نظام الإشعارات الذكي لتحديثات المشروع والتنبيهات</h2>", unsafe_allow_html=True)
st.markdown("""
<div class="module-description">
يتيح لك نظام الإشعارات الذكي متابعة تحديثات المشاريع وتلقي تنبيهات مخصصة حسب أدوارك واهتماماتك.
يمكنك تخصيص إعدادات الإشعارات وجدولة التذكيرات للمواعيد النهائية والمهام.
</div>
""", unsafe_allow_html=True)
# عرض نظام الإشعارات الذكي
self.smart_notification_system.render()
# تشغيل التطبيق بشكل مستقل عند استدعاء الملف مباشرة
if __name__ == "__main__":
st.set_page_config(
page_title="نظام الإشعارات الذكي | WAHBi AI",
page_icon="🔔",
layout="wide",
initial_sidebar_state="expanded"
)
app = NotificationsApp()
app.render() |