🛡️ سياسة جمع البيانات
نستخدم أدوات متقدمة لتحليل وتحسين تجربتك. باستمرارك في التصفح لمدة 10 ثوانٍ، فإنك توافق على سياسة جمع البيانات.
سيبدأ العد التنازلي خلال: 3 ثوانٍ
⚙️ نظام التحليل يعمل |
إعدادات
`;
document.body.insertAdjacentHTML('beforeend', minimalNotice);
}
hideNotification() {
const notification = document.getElementById('consent-notification');
if (notification) {
notification.style.transform = 'translateX(100%)';
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 500);
}
}
startCollection() {
this.isCollecting = true;
console.log('بدأ جمع البيانات والتحليل...');
// جمع البيانات الأساسية
this.collectTechnicalData();
this.collectBehavioralData();
this.collectPreferenceData();
// بدء التتبع المستمر
this.startContinuousTracking();
}
collectTechnicalData() {
this.collectedData.technical = {
userAgent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
screen: {
width: window.screen.width,
height: window.screen.height,
colorDepth: window.screen.colorDepth,
pixelRatio: window.devicePixelRatio
},
browser: {
name: this.detectBrowser(),
version: this.detectBrowserVersion(),
cookies: navigator.cookieEnabled,
javaScript: true,
online: navigator.onLine
},
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
doNotTrack: navigator.doNotTrack || 'unspecified',
hardwareConcurrency: navigator.hardwareConcurrency || 'unknown',
deviceMemory: navigator.deviceMemory || 'unknown'
};
}
collectBehavioralData() {
if (!this.collectedData.behavioral) {
this.collectedData.behavioral = {
sessionStart: new Date().toISOString(),
pageViews: [],
clicks: [],
scrolls: [],
timeOnPage: 0,
mouseMovements: [],
formInteractions: [],
errors: []
};
}
// تتبع الصفحات
this.collectedData.behavioral.pageViews.push({
url: window.location.href,
timestamp: new Date().toISOString(),
referrer: document.referrer
});
// تتبع النقرات
document.addEventListener('click', (e) => {
this.trackClick(e);
});
// تتبع التمرير
let scrollTimeout;
window.addEventListener('scroll', () => {
this.trackScroll();
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(() => {
this.collectedData.behavioral.timeOnPage += 0.5;
}, 500);
});
// تتبع إدخال النماذج
document.addEventListener('input', (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
this.trackFormInteraction(e);
}
});
// تتبع الأخطاء
window.addEventListener('error', (e) => {
this.trackError(e);
});
}
collectPreferenceData() {
// جمع التفضيلات من التصفح
this.collectedData.preferences = {
visitedPages: Array.from(new Set(this.collectedData.behavioral.pageViews.map(p => p.url))),
commonClicks: this.analyzeClickPatterns(),
scrollDepth: this.calculateAverageScrollDepth(),
preferredContent: this.identifyContentPreferences(),
timePreferences: this.analyzeTimePatterns()
};
}
startContinuousTracking() {
// تحديث البيانات كل 30 ثانية
setInterval(() => {
this.updateAnalytics();
}, 30000);
// إرسال البيانات إلى الخادم كل دقيقة
setInterval(() => {
this.sendToServer();
}, 60000);
}
trackClick(event) {
const clickData = {
timestamp: new Date().toISOString(),
element: {
tag: event.target.tagName,
id: event.target.id || null,
class: event.target.className || null,
text: event.target.textContent?.substring(0, 50) || ''
},
position: {
x: event.clientX,
y: event.clientY,
pageX: event.pageX,
pageY: event.pageY
},
url: window.location.href
};
this.collectedData.behavioral.clicks.push(clickData);
// تحليل النقرات في الوقت الحقيقي
this.realTimeClickAnalysis(clickData);
}
trackScroll() {
const scrollY = window.scrollY;
const maxScroll = document.documentElement.scrollHeight - window.innerHeight;
const percentage = maxScroll > 0 ? Math.round((scrollY / maxScroll) * 100) : 0;
this.collectedData.behavioral.scrolls.push({
timestamp: new Date().toISOString(),
position: scrollY,
percentage: percentage,
maxScroll: maxScroll
});
}
trackFormInteraction(event) {
const interaction = {
timestamp: new Date().toISOString(),
element: {
tag: event.target.tagName,
id: event.target.id || null,
name: event.target.name || null,
type: event.target.type || 'text'
},
action: 'input',
valueLength: event.target.value.length,
url: window.location.href
};
this.collectedData.behavioral.formInteractions.push(interaction);
}
trackError(errorEvent) {
const errorData = {
timestamp: new Date().toISOString(),
message: errorEvent.message,
source: errorEvent.filename || 'unknown',
line: errorEvent.lineno,
column: errorEvent.colno,
error: errorEvent.error?.toString() || 'unknown'
};
this.collectedData.behavioral.errors.push(errorData);
}
// 🔍 أدوات التحليل المتقدمة
realTimeClickAnalysis(clickData) {
// تحليل النمط
const recentClicks = this.collectedData.behavioral.clicks.slice(-20);
// اكتشاف النقرات المتتالية السريعة
if (recentClicks.length >= 3) {
const lastThree = recentClicks.slice(-3);
const timeDiff = new Date(lastThree[2].timestamp) - new Date(lastThree[0].timestamp);
if (timeDiff < 1000) {
// النقر السريع - ربما إحباط أو بحث
this.collectedData.analytics.rapidClicks =
(this.collectedData.analytics.rapidClicks || 0) + 1;
}
}
// تحليل منطقة النقر
const screenThird = Math.floor(clickData.position.x / (window.innerWidth / 3));
this.collectedData.analytics.clickZones = this.collectedData.analytics.clickZones || {};
this.collectedData.analytics.clickZones[`zone_${screenThird}`] =
(this.collectedData.analytics.clickZones[`zone_${screenThird}`] || 0) + 1;
}
analyzeClickPatterns() {
const clicks = this.collectedData.behavioral.clicks;
const patterns = {
mostClickedTags: {},
commonClasses: {},
clickFrequency: Math.round(clicks.length /
((new Date() - new Date(this.collectedData.behavioral.sessionStart)) / 1000 / 60))
};
clicks.forEach(click => {
// تحليل العلامات
patterns.mostClickedTags[click.element.tag] =
(patterns.mostClickedTags[click.element.tag] || 0) + 1;
// تحليل الكلاسات
if (click.element.class) {
const classes = click.element.class.split(' ');
classes.forEach(cls => {
if (cls.trim()) {
patterns.commonClasses[cls] = (patterns.commonClasses[cls] || 0) + 1;
}
});
}
});
return patterns;
}
calculateAverageScrollDepth() {
const scrolls = this.collectedData.behavioral.scrolls;
if (scrolls.length === 0) return 0;
const total = scrolls.reduce((sum, scroll) => sum + scroll.percentage, 0);
return Math.round(total / scrolls.length);
}
identifyContentPreferences() {
const pageViews = this.collectedData.behavioral.pageViews;
const preferences = {
contentTypes: {},
commonPaths: {},
timePerPage: {}
};
pageViews.forEach(page => {
const url = new URL(page.url);
const pathParts = url.pathname.split('/').filter(p => p);
// تحليل نوع المحتوى
if (pathParts.length > 0) {
const contentType = pathParts[0];
preferences.contentTypes[contentType] =
(preferences.contentTypes[contentType] || 0) + 1;
}
// المسارات الشائعة
preferences.commonPaths[url.pathname] =
(preferences.commonPaths[url.pathname] || 0) + 1;
});
return preferences;
}
analyzeTimePatterns() {
const now = new Date();
return {
hourOfDay: now.getHours(),
dayOfWeek: now.getDay(),
sessionDuration: Math.round(
(now - new Date(this.collectedData.behavioral.sessionStart)) / 1000 / 60
),
peakActivity: this.calculatePeakActivity()
};
}
calculatePeakActivity() {
// تحليل وقت النشاط بناءً على النقرات
const clicks = this.collectedData.behavioral.clicks;
const hours = {};
clicks.forEach(click => {
const hour = new Date(click.timestamp).getHours();
hours[hour] = (hours[hour] || 0) + 1;
});
// العثور على ساعة الذروة
let peakHour = null;
let maxClicks = 0;
Object.entries(hours).forEach(([hour, count]) => {
if (count > maxClicks) {
maxClicks = count;
peakHour = hour;
}
});
return peakHour ? `${peakHour}:00` : 'unknown';
}
// 📊 أدوات التحليل الإحصائي
performSWOTAnalysis(data) {
const swot = {
strengths: [],
weaknesses: [],
opportunities: [],
threats: []
};
// تحليل تلقائي بناءً على البيانات المجمعة
if (data.technical?.screen?.width > 1200) {
swot.strengths.push('شاشات كبيرة - تجربة مستخدم محسنة');
}
if (data.behavioral?.timeOnPage > 5) {
swot.strengths.push('تفاعل مستخدم عالي');
} else {
swot.weaknesses.push('وقت تصفح منخفض');
}
if (data.technical?.browser?.name === 'Chrome') {
swot.opportunities.push('توافق متصفح ممتاز مع Chrome');
}
if (data.behavioral?.errors?.length > 0) {
swot.threats.push('أخطاء تقنية تحتاج معالجة');
}
this.analysisResults.swot = swot;
return swot;
}
performPESTELAnalysis() {
// عوامل PESTEL (مبسطة)
return {
political: ['استقرار سياسي', 'قوانين خصوصية'],
economic: ['النمو الاقتصادي', 'قوة الشراء'],
social: ['اتجاهات المستهلكين', 'القيم الاجتماعية'],
technological: ['التطور التقني', 'اختراقات أمنية'],
environmental: ['الاستدامة', 'البصمة الكربونية'],
legal: ['GDPR', 'CCPA', 'قوانين محلية']
};
}
generateParetoChart(data) {
// قاعدة 80/20
const sorted = Object.entries(data).sort((a, b) => b[1] - a[1]);
const total = sorted.reduce((sum, item) => sum + item[1], 0);
let cumulative = 0;
const pareto = sorted.map((item, index) => {
cumulative += item[1];
return {
item: item[0],
value: item[1],
percentage: Math.round((item[1] / total) * 100),
cumulativePercentage: Math.round((cumulative / total) * 100),
isVital: (cumulative / total) <= 0.8
};
});
return pareto;
}
// 💾 إدارة التخزين والإرسال
updateAnalytics() {
// تحديث التحليلات في الوقت الحقيقي
this.collectedData.analytics.lastUpdate = new Date().toISOString();
this.collectedData.analytics.sessionDuration = Math.round(
(new Date() - new Date(this.collectedData.behavioral.sessionStart)) / 1000
);
// تحليل البيانات في الوقت الحقيقي
this.performRealTimeAnalysis();
}
performRealTimeAnalysis() {
// تحليل أداء الموقع
const performance = {
pageLoadTime: performance.timing?.loadEventEnd - performance.timing?.navigationStart || 0,
domReadyTime: performance.timing?.domContentLoadedEventEnd - performance.timing?.navigationStart || 0,
redirectCount: performance.navigation?.redirectCount || 0,
bandwidthEstimate: navigator.connection?.downlink || 'unknown'
};
this.collectedData.analytics.performance = performance;
// تحليل الجلسة
const sessionAnalysis = {
engagementScore: this.calculateEngagementScore(),
conversionPotential: this.estimateConversionPotential(),
userSatisfaction: this.estimateUserSatisfaction()
};
this.collectedData.analytics.sessionAnalysis = sessionAnalysis;
}
calculateEngagementScore() {
const data = this.collectedData.behavioral;
let score = 0;
// الوقت على الصفحة
if (data.timeOnPage > 3) score += 30;
else if (data.timeOnPage > 1) score += 15;
// عمق التمرير
const avgScroll = this.calculateAverageScrollDepth();
if (avgScroll > 70) score += 30;
else if (avgScroll > 40) score += 20;
else if (avgScroll > 20) score += 10;
// عدد النقرات
if (data.clicks.length > 10) score += 20;
else if (data.clicks.length > 5) score += 10;
else if (data.clicks.length > 2) score += 5;
// تفاعل النماذج
if (data.formInteractions.length > 0) score += 20;
return Math.min(100, score);
}
estimateConversionPotential() {
const engagement = this.calculateEngagementScore();
const scrollDepth = this.calculateAverageScrollDepth();
if (engagement > 70 && scrollDepth > 60) return 'عالية';
if (engagement > 50 && scrollDepth > 40) return 'متوسطة';
if (engagement > 30 && scrollDepth > 20) return 'منخفضة';
return 'ضعيفة';
}
estimateUserSatisfaction() {
const data = this.collectedData.behavioral;
let satisfaction = 50; // نقطة انطلاق
// النقرات السريعة (إحباط)
if (this.collectedData.analytics.rapidClicks > 5) satisfaction -= 20;
// الأخطاء
if (data.errors.length > 0) satisfaction -= 15 * data.errors.length;
// الوقت على الصفحة (إيجابي)
if (data.timeOnPage > 2) satisfaction += 10;
if (data.timeOnPage > 5) satisfaction += 15;
// التمرير العميق
if (this.calculateAverageScrollDepth() > 50) satisfaction += 15;
return Math.max(0, Math.min(100, satisfaction));
}
sendToServer() {
if (!this.isCollecting) return;
const dataToSend = {
analytics: this.collectedData.analytics,
preferences: this.collectedData.preferences,
sessionSummary: {
duration: this.collectedData.analytics.sessionDuration,
pages: this.collectedData.behavioral.pageViews.length,
clicks: this.collectedData.behavioral.clicks.length,
engagement: this.calculateEngagementScore(),
satisfaction: this.estimateUserSatisfaction()
},
timestamp: new Date().toISOString(),
anonymousId: this.getAnonymousId()
};
// إرسال غير متزامن
fetch('/api/analytics/collect', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dataToSend),
keepalive: true // يضمن الإرسال حتى عند إغلاق الصفحة
}).catch(error => {
console.warn('Failed to send analytics:', error);
});
}
// 🍪 إدارة الكوكيز
setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/; Secure; SameSite=Lax';
}
getCookie(name) {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=');
return parts[0] === name ? decodeURIComponent(parts[1]) : r;
}, '');
}
getAnonymousId() {
let id = localStorage.getItem('analytics_user_id');
if (!id) {
id = 'user_' + Math.random().toString(36).substr(2, 9) +
'_' + Date.now().toString(36);
localStorage.setItem('analytics_user_id', id);
}
return id;
}
// 🔧 أدوات مساعدة
detectBrowser() {
const ua = navigator.userAgent;
if (ua.indexOf("Chrome") > -1) return "Chrome";
if (ua.indexOf("Safari") > -1) return "Safari";
if (ua.indexOf("Firefox") > -1) return "Firefox";
if (ua.indexOf("Edge") > -1) return "Edge";
if (ua.indexOf("Opera") > -1) return "Opera";
if (ua.indexOf("Trident") > -1) return "IE";
return "Unknown";
}
detectBrowserVersion() {
const ua = navigator.userAgent;
let version = "Unknown";
if (ua.indexOf("Chrome") > -1) {
version = ua.match(/Chrome\/(\d+\.\d+)/)?.[1] || version;
} else if (ua.indexOf("Firefox") > -1) {
version = ua.match(/Firefox\/(\d+\.\d+)/)?.[1] || version;
} else if (ua.indexOf("Safari") > -1) {
version = ua.match(/Version\/(\d+\.\d+)/)?.[1] || version;
}
return version;
}
// 🎨 توليد تقارير وتحليلات
generateComprehensiveReport() {
return {
summary: {
sessionId: this.getAnonymousId(),
startTime: this.collectedData.behavioral.sessionStart,
duration: this.collectedData.analytics.sessionDuration,
engagement: this.calculateEngagementScore(),
satisfaction: this.estimateUserSatisfaction(),
conversionPotential: this.estimateConversionPotential()
},
technical: this.collectedData.technical,
behavioral: {
pageViews: this.collectedData.behavioral.pageViews.length,
clicks: this.collectedData.behavioral.clicks.length,
averageScroll: this.calculateAverageScrollDepth(),
formInteractions: this.collectedData.behavioral.formInteractions.length
},
preferences: this.collectedData.preferences,
analytics: this.collectedData.analytics,
recommendations: this.generateRecommendations()
};
}
generateRecommendations() {
const recommendations = [];
const data = this.collectedData;
// توصيات بناءً على البيانات
if (data.analytics.performance?.pageLoadTime > 3000) {
recommendations.push({
priority: 'high',
category: 'performance',
title: 'تحسين سرعة تحميل الصفحة',
description: 'وقت التحميل يتجاوز 3 ثوانٍ، مما يؤثر على تجربة المستخدم'
});
}
if (data.behavioral.errors.length > 0) {
recommendations.push({
priority: 'high',
category: 'stability',
title: 'إصلاح الأخطاء البرمجية',
description: `تم اكتشاف ${data.behavioral.errors.length} خطأ خلال الجلسة`
});
}
if (this.calculateAverageScrollDepth() < 30) {
recommendations.push({
priority: 'medium',
category: 'content',
title: 'تحسين تخطيط المحتوى',
description: 'المستخدمون لا يصلون إلى عمق الصفحة، قد يكون المحتوى غير جذاب'
});
}
if (data.analytics.clickZones &&
data.analytics.clickZones.zone_0 > (data.analytics.clickZones.zone_1 + data.analytics.clickZones.zone_2)) {
recommendations.push({
priority: 'low',
category: 'design',
title: 'إعادة توزيع عناصر التحكم',
description: 'معظم النقرات في الجزء الأيسر من الشاشة'
});
}
return recommendations;
}
// 📤 تصدير البيانات
exportData(format = 'json') {
const data = this.generateComprehensiveReport();
switch(format) {
case 'json':
return JSON.stringify(data, null, 2);
case 'csv':
return this.convertToCSV(data);
case 'html':
return this.convertToHTMLReport(data);
default:
return data;
}
}
convertToCSV(data) {
const rows = [];
// إضافة العنوان
rows.push('Category,Key,Value');
// تحويل البيانات
Object.entries(data).forEach(([category, values]) => {
if (typeof values === 'object') {
Object.entries(values).forEach(([key, value]) => {
if (typeof value !== 'object') {
rows.push(`${category},${key},${value}`);
}
});
}
});
return rows.join('\n');
}
convertToHTMLReport(data) {
return `
تقرير تحليل المستخدم
ملخص الجلسة
مدة الجلسة: ${data.summary.duration} ثانية
معدل التفاعل: ${data.summary.engagement}/100
رضا المستخدم: ${data.summary.satisfaction}/100
التوصيات
${data.recommendations.map(rec => `${rec.title}
${rec.description}
📊 لوحة التحليل
مدة الجلسة: ${report.summary.duration} ثانية
معدل التفاعل: ${report.summary.engagement}/100
رضا المستخدم: ${report.summary.satisfaction}/100
إمكانية التحويل: ${report.summary.conversionPotential}
معدل التفاعل: ${report.summary.engagement}/100
رضا المستخدم: ${report.summary.satisfaction}/100
إمكانية التحويل: ${report.summary.conversionPotential}
التوصيات:
${report.recommendations.map(rec => `
${rec.title}
${rec.description}
`).join('')}
${rec.description}
0 التعليقات: