File size: 12,173 Bytes
d9e7bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

مولد الرسوم البيانية لنظام إدارة المناقصات

"""

import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import customtkinter as ctk

class ChartGenerator:
    """فئة مولد الرسوم البيانية"""
    
    def __init__(self, theme):
        """تهيئة مولد الرسوم البيانية"""
        self.theme = theme
        
        # تحديد مسار مجلد الرسوم البيانية
        self.charts_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "charts")
        
        # إنشاء مجلد الرسوم البيانية إذا لم يكن موجودًا
        os.makedirs(self.charts_dir, exist_ok=True)
        
        # تهيئة نمط الرسوم البيانية
        self._setup_chart_style()
    
    def _setup_chart_style(self):
        """إعداد نمط الرسوم البيانية"""
        # تعيين نمط الرسوم البيانية
        plt.style.use('ggplot')
        
        # تعيين الخط
        plt.rcParams['font.family'] = 'sans-serif'
        plt.rcParams['font.sans-serif'] = ['Arial', 'DejaVu Sans', 'Liberation Sans', 'Bitstream Vera Sans', 'sans-serif']
        
        # تعيين حجم الخط
        plt.rcParams['font.size'] = 10
        plt.rcParams['axes.titlesize'] = 14
        plt.rcParams['axes.labelsize'] = 12
        plt.rcParams['xtick.labelsize'] = 10
        plt.rcParams['ytick.labelsize'] = 10
        plt.rcParams['legend.fontsize'] = 10
        
        # تعيين الألوان
        if self.theme.current_theme == "light":
            plt.rcParams['figure.facecolor'] = self.theme.LIGHT_CARD_BG_COLOR
            plt.rcParams['axes.facecolor'] = self.theme.LIGHT_BG_COLOR
            plt.rcParams['axes.edgecolor'] = self.theme.LIGHT_BORDER_COLOR
            plt.rcParams['axes.labelcolor'] = self.theme.LIGHT_FG_COLOR
            plt.rcParams['xtick.color'] = self.theme.LIGHT_FG_COLOR
            plt.rcParams['ytick.color'] = self.theme.LIGHT_FG_COLOR
            plt.rcParams['text.color'] = self.theme.LIGHT_FG_COLOR
            plt.rcParams['grid.color'] = self.theme.LIGHT_BORDER_COLOR
        else:
            plt.rcParams['figure.facecolor'] = self.theme.DARK_CARD_BG_COLOR
            plt.rcParams['axes.facecolor'] = self.theme.DARK_BG_COLOR
            plt.rcParams['axes.edgecolor'] = self.theme.DARK_BORDER_COLOR
            plt.rcParams['axes.labelcolor'] = self.theme.DARK_FG_COLOR
            plt.rcParams['xtick.color'] = self.theme.DARK_FG_COLOR
            plt.rcParams['ytick.color'] = self.theme.DARK_FG_COLOR
            plt.rcParams['text.color'] = self.theme.DARK_FG_COLOR
            plt.rcParams['grid.color'] = self.theme.DARK_BORDER_COLOR
    
    def create_bar_chart(self, data, title, xlabel, ylabel):
        """إنشاء رسم بياني شريطي"""
        # إنشاء الشكل والمحاور
        fig, ax = plt.subplots(figsize=(8, 5), dpi=100)
        
        # رسم الرسم البياني الشريطي
        bars = ax.bar(data['labels'], data['values'], color=self.theme.PRIMARY_COLOR[self.theme.current_theme])
        
        # إضافة القيم فوق الأشرطة
        for bar in bars:
            height = bar.get_height()
            ax.text(bar.get_x() + bar.get_width() / 2., height + 0.1 * max(data['values']),
                    f'{height:,.0f}', ha='center', va='bottom')
        
        # تعيين العنوان والتسميات
        ax.set_title(title)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        
        # تعيين حدود المحور y
        ax.set_ylim(0, max(data['values']) * 1.2)
        
        # إضافة الشبكة
        ax.grid(True, linestyle='--', alpha=0.7)
        
        # تضييق الشكل
        fig.tight_layout()
        
        return fig
    
    def create_line_chart(self, data, title, xlabel, ylabel):
        """إنشاء رسم بياني خطي"""
        # إنشاء الشكل والمحاور
        fig, ax = plt.subplots(figsize=(8, 5), dpi=100)
        
        # رسم الرسم البياني الخطي
        line = ax.plot(data['labels'], data['values'], marker='o', linestyle='-', linewidth=2,
                      color=self.theme.PRIMARY_COLOR[self.theme.current_theme],
                      markersize=8, markerfacecolor=self.theme.SECONDARY_COLOR[self.theme.current_theme])
        
        # إضافة القيم فوق النقاط
        for i, value in enumerate(data['values']):
            ax.text(i, value + 0.05 * max(data['values']), f'{value:,.0f}', ha='center', va='bottom')
        
        # تعيين العنوان والتسميات
        ax.set_title(title)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        
        # تعيين حدود المحور y
        ax.set_ylim(0, max(data['values']) * 1.2)
        
        # إضافة الشبكة
        ax.grid(True, linestyle='--', alpha=0.7)
        
        # تضييق الشكل
        fig.tight_layout()
        
        return fig
    
    def create_pie_chart(self, data, title):
        """إنشاء رسم بياني دائري"""
        # إنشاء الشكل والمحاور
        fig, ax = plt.subplots(figsize=(8, 5), dpi=100)
        
        # تعيين الألوان
        colors = [
            self.theme.PRIMARY_COLOR[self.theme.current_theme],
            self.theme.SECONDARY_COLOR[self.theme.current_theme],
            self.theme.ACCENT_COLOR[self.theme.current_theme],
            self.theme.WARNING_COLOR[self.theme.current_theme],
            self.theme.SUCCESS_COLOR[self.theme.current_theme]
        ]
        
        # رسم الرسم البياني الدائري
        wedges, texts, autotexts = ax.pie(
            data['values'],
            labels=data['labels'],
            autopct='%1.1f%%',
            startangle=90,
            colors=colors,
            wedgeprops={'edgecolor': 'white', 'linewidth': 1},
            textprops={'color': self.theme.get_color('fg_color')}
        )
        
        # تعيين خصائص النص
        for autotext in autotexts:
            autotext.set_color('white')
            autotext.set_fontweight('bold')
        
        # تعيين العنوان
        ax.set_title(title)
        
        # جعل الرسم البياني دائريًا
        ax.axis('equal')
        
        # تضييق الشكل
        fig.tight_layout()
        
        return fig
    
    def create_stacked_bar_chart(self, data, title, xlabel, ylabel):
        """إنشاء رسم بياني شريطي متراكم"""
        # إنشاء الشكل والمحاور
        fig, ax = plt.subplots(figsize=(8, 5), dpi=100)
        
        # تعيين الألوان
        colors = [
            self.theme.PRIMARY_COLOR[self.theme.current_theme],
            self.theme.SECONDARY_COLOR[self.theme.current_theme],
            self.theme.ACCENT_COLOR[self.theme.current_theme],
            self.theme.WARNING_COLOR[self.theme.current_theme],
            self.theme.SUCCESS_COLOR[self.theme.current_theme]
        ]
        
        # رسم الرسم البياني الشريطي المتراكم
        bottom = np.zeros(len(data['labels']))
        for i, category in enumerate(data['categories']):
            values = data['values'][i]
            bars = ax.bar(data['labels'], values, bottom=bottom, label=category, color=colors[i % len(colors)])
            bottom += values
        
        # تعيين العنوان والتسميات
        ax.set_title(title)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        
        # إضافة وسيلة إيضاح
        ax.legend()
        
        # إضافة الشبكة
        ax.grid(True, linestyle='--', alpha=0.7)
        
        # تضييق الشكل
        fig.tight_layout()
        
        return fig
    
    def create_risk_matrix(self, data, title):
        """إنشاء مصفوفة المخاطر"""
        # إنشاء الشكل والمحاور
        fig, ax = plt.subplots(figsize=(8, 5), dpi=100)
        
        # تعيين الألوان
        colors = {
            'منخفض': self.theme.SUCCESS_COLOR[self.theme.current_theme],
            'متوسط': self.theme.WARNING_COLOR[self.theme.current_theme],
            'عالي': self.theme.ERROR_COLOR[self.theme.current_theme]
        }
        
        # تعيين قيم المحاور
        probability_values = {'منخفض': 1, 'متوسط': 2, 'عالي': 3}
        impact_values = {'منخفض': 1, 'متوسط': 2, 'عالي': 3}
        
        # رسم المصفوفة
        for risk in data['risks']:
            prob = probability_values[risk['probability']]
            impact = impact_values[risk['impact']]
            color = colors[risk['probability']] if prob > impact else colors[risk['impact']]
            ax.scatter(impact, prob, color=color, s=100, alpha=0.7)
            ax.annotate(risk['name'], (impact, prob), xytext=(5, 5), textcoords='offset points')
        
        # تعيين حدود المحاور
        ax.set_xlim(0.5, 3.5)
        ax.set_ylim(0.5, 3.5)
        
        # تعيين تسميات المحاور
        ax.set_xticks([1, 2, 3])
        ax.set_xticklabels(['منخفض', 'متوسط', 'عالي'])
        ax.set_yticks([1, 2, 3])
        ax.set_yticklabels(['منخفض', 'متوسط', 'عالي'])
        
        # تعيين العنوان والتسميات
        ax.set_title(title)
        ax.set_xlabel('التأثير')
        ax.set_ylabel('الاحتمالية')
        
        # إضافة الشبكة
        ax.grid(True, linestyle='--', alpha=0.7)
        
        # إضافة مناطق المخاطر
        # منطقة المخاطر المنخفضة (أخضر)
        ax.add_patch(plt.Rectangle((0.5, 0.5), 1, 1, fill=True, color=self.theme.SUCCESS_COLOR[self.theme.current_theme], alpha=0.1))
        # منطقة المخاطر المتوسطة (أصفر)
        ax.add_patch(plt.Rectangle((1.5, 0.5), 1, 1, fill=True, color=self.theme.WARNING_COLOR[self.theme.current_theme], alpha=0.1))
        ax.add_patch(plt.Rectangle((0.5, 1.5), 1, 1, fill=True, color=self.theme.WARNING_COLOR[self.theme.current_theme], alpha=0.1))
        # منطقة المخاطر العالية (أحمر)
        ax.add_patch(plt.Rectangle((2.5, 0.5), 1, 3, fill=True, color=self.theme.ERROR_COLOR[self.theme.current_theme], alpha=0.1))
        ax.add_patch(plt.Rectangle((0.5, 2.5), 2, 1, fill=True, color=self.theme.ERROR_COLOR[self.theme.current_theme], alpha=0.1))
        ax.add_patch(plt.Rectangle((1.5, 1.5), 1, 1, fill=True, color=self.theme.ERROR_COLOR[self.theme.current_theme], alpha=0.1))
        
        # تضييق الشكل
        fig.tight_layout()
        
        return fig
    
    def embed_chart_in_frame(self, parent, fig):
        """تضمين الرسم البياني في إطار"""
        # إنشاء إطار للرسم البياني
        chart_frame = ctk.CTkFrame(parent, fg_color="transparent")
        
        # تضمين الرسم البياني في الإطار
        canvas = FigureCanvasTkAgg(fig, master=chart_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        
        return chart_frame
    
    def save_chart(self, fig, name):
        """حفظ الرسم البياني"""
        # تحديد مسار الملف
        file_path = os.path.join(self.charts_dir, f"{name}.png")
        
        # حفظ الرسم البياني
        fig.savefig(file_path, dpi=100, bbox_inches='tight')
        
        return file_path