Mark-Lasfar commited on
Commit
a7205bd
·
1 Parent(s): 5d6679a

Add GraphQL

Browse files
Files changed (1) hide show
  1. server.js +116 -28
server.js CHANGED
@@ -4560,15 +4560,38 @@ profileAnalyticsSchema.index({ 'profileViews.viewedAt': -1 });
4560
  const ProfileAnalytics = mongoose.model('ProfileAnalytics', profileAnalyticsSchema);
4561
 
4562
  // ============================================
4563
- // Also Viewed Schema - المستخدمين الذين شاهدوا هذا الملف أيضاً
4564
  // ============================================
4565
  const alsoViewedSchema = new mongoose.Schema({
4566
- targetUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
4567
- viewerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
4568
- viewedAt: { type: Date, default: Date.now }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4569
  });
4570
 
4571
- alsoViewedSchema.index({ targetUserId: 1, viewerId: 1 }, { unique: true });
 
 
 
 
 
 
 
 
4572
  alsoViewedSchema.index({ targetUserId: 1, viewedAt: -1 });
4573
 
4574
  const AlsoViewed = mongoose.model('AlsoViewed', alsoViewedSchema);
@@ -18378,22 +18401,61 @@ app.get('/api/analytics/also-viewed', async (req, res) => {
18378
  return res.status(400).json({ error: 'userId is required' });
18379
  }
18380
 
18381
- // جلب آخر 5 مستخدمين شاهدوا هذا الملف الشخصي
18382
  const alsoViewed = await AlsoViewed.find({ targetUserId: userId })
18383
  .sort({ viewedAt: -1 })
18384
- .limit(5)
18385
- .populate('viewerId', 'username profile.nickname profile.avatar profile.jobTitle profile.portfolioName');
18386
-
18387
- // تنسيق البيانات
18388
- const formattedViewers = alsoViewed.map(item => ({
18389
- _id: item.viewerId?._id,
18390
- name: item.viewerId?.profile?.nickname || item.viewerId?.username || 'Someone',
18391
- nickname: item.viewerId?.profile?.nickname,
18392
- username: item.viewerId?.username,
18393
- avatar: item.viewerId?.profile?.avatar || '/assets/img/default-avatar.png',
18394
- title: item.viewerId?.profile?.jobTitle || 'Professional',
18395
- viewedAt: item.viewedAt
18396
- }));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18397
 
18398
  res.json(formattedViewers);
18399
 
@@ -18403,7 +18465,6 @@ app.get('/api/analytics/also-viewed', async (req, res) => {
18403
  }
18404
  });
18405
 
18406
-
18407
  // ============================================
18408
  // GET /api/pages/suggestions - جلب اقتراحات ال��فحات
18409
  // ============================================
@@ -18548,26 +18609,28 @@ app.post('/api/analytics/track-view', async (req, res) => {
18548
  return res.status(400).json({ error: 'targetUserId is required' });
18549
  }
18550
 
18551
- // لا تسجل مشاهدة لنفس المستخدم
18552
  if (req.user?.userId === targetUserId) {
18553
  return res.json({ success: true, message: 'Self view not tracked' });
18554
  }
18555
 
 
 
 
18556
  let analytics = await ProfileAnalytics.findOne({ userId: targetUserId });
18557
 
18558
  if (!analytics) {
18559
  analytics = new ProfileAnalytics({ userId: targetUserId });
18560
  }
18561
 
18562
- // إضافة مشاهدة جديدة
18563
  analytics.profileViews = analytics.profileViews || [];
18564
  analytics.profileViews.push({
18565
- viewerId: req.user?.userId,
18566
- viewerIp: req.ip || req.connection.remoteAddress,
18567
  viewedAt: new Date()
18568
  });
18569
 
18570
- // الاحتفاظ بآخر 100 مشاهدة فقط
18571
  if (analytics.profileViews.length > 100) {
18572
  analytics.profileViews = analytics.profileViews.slice(-100);
18573
  }
@@ -18575,20 +18638,45 @@ app.post('/api/analytics/track-view', async (req, res) => {
18575
  analytics.lastUpdated = new Date();
18576
  await analytics.save();
18577
 
18578
- // تسجيل في Also Viewed
 
 
 
 
18579
  if (req.user?.userId) {
 
18580
  await AlsoViewed.findOneAndUpdate(
18581
  { targetUserId, viewerId: req.user.userId },
18582
- { viewedAt: new Date() },
 
 
 
18583
  { upsert: true }
18584
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18585
  }
18586
 
18587
  res.json({ success: true });
18588
 
18589
  } catch (error) {
18590
  logger.error(`Error tracking profile view: ${error.message}`);
18591
- // لا نرسل خطأ للمستخدم حتى لا يسبب مشاكل
18592
  res.json({ success: true });
18593
  }
18594
  });
 
4560
  const ProfileAnalytics = mongoose.model('ProfileAnalytics', profileAnalyticsSchema);
4561
 
4562
  // ============================================
4563
+ // Also Viewed Schema - محدث مع دعم الزوار
4564
  // ============================================
4565
  const alsoViewedSchema = new mongoose.Schema({
4566
+ targetUserId: {
4567
+ type: mongoose.Schema.Types.ObjectId,
4568
+ ref: 'User',
4569
+ required: true
4570
+ },
4571
+ viewerId: {
4572
+ type: mongoose.Schema.Types.ObjectId,
4573
+ ref: 'User',
4574
+ default: null
4575
+ },
4576
+ viewerIp: {
4577
+ type: String,
4578
+ default: null
4579
+ },
4580
+ viewedAt: {
4581
+ type: Date,
4582
+ default: Date.now
4583
+ }
4584
  });
4585
 
4586
+ // ✅ فهارس محسنة
4587
+ alsoViewedSchema.index({ targetUserId: 1, viewerId: 1 }, {
4588
+ unique: true,
4589
+ sparse: true
4590
+ });
4591
+ alsoViewedSchema.index({ targetUserId: 1, viewerIp: 1 }, {
4592
+ unique: true,
4593
+ sparse: true
4594
+ });
4595
  alsoViewedSchema.index({ targetUserId: 1, viewedAt: -1 });
4596
 
4597
  const AlsoViewed = mongoose.model('AlsoViewed', alsoViewedSchema);
 
18401
  return res.status(400).json({ error: 'userId is required' });
18402
  }
18403
 
18404
+ // ✅ جلب آخر 5 مشاهدات (مسجلين + زوار)
18405
  const alsoViewed = await AlsoViewed.find({ targetUserId: userId })
18406
  .sort({ viewedAt: -1 })
18407
+ .limit(5);
18408
+
18409
+ if (!alsoViewed || alsoViewed.length === 0) {
18410
+ return res.json([]);
18411
+ }
18412
+
18413
+ // ✅ استخراج الـ userIds للمستخدمين المسجلين
18414
+ const userIds = alsoViewed
18415
+ .filter(item => item.viewerId)
18416
+ .map(item => item.viewerId);
18417
+
18418
+ // ✅ جلب بيانات المستخدمين المسجلين
18419
+ let userMap = {};
18420
+ if (userIds.length > 0) {
18421
+ const users = await User.find({ _id: { $in: userIds } })
18422
+ .select('username profile.nickname profile.avatar profile.jobTitle');
18423
+
18424
+ users.forEach(u => {
18425
+ userMap[u._id.toString()] = u;
18426
+ });
18427
+ }
18428
+
18429
+ // ✅ تنسيق النتيجة
18430
+ const formattedViewers = alsoViewed.map(item => {
18431
+ if (item.viewerId && userMap[item.viewerId.toString()]) {
18432
+ // ✅ مستخدم مسجل
18433
+ const user = userMap[item.viewerId.toString()];
18434
+ return {
18435
+ _id: user._id,
18436
+ name: user.profile?.nickname || user.username || 'Someone',
18437
+ nickname: user.profile?.nickname,
18438
+ username: user.username,
18439
+ avatar: user.profile?.avatar || '/assets/img/default-avatar.png',
18440
+ title: user.profile?.jobTitle || 'Professional',
18441
+ viewedAt: item.viewedAt,
18442
+ isGuest: false
18443
+ };
18444
+ } else {
18445
+ // ✅ زائر (غير مسجل)
18446
+ return {
18447
+ _id: null,
18448
+ name: `Guest ${item.viewerIp ? '🌐' : ''}`,
18449
+ nickname: null,
18450
+ username: null,
18451
+ avatar: '/assets/img/default-avatar.png',
18452
+ title: 'Guest Visitor',
18453
+ viewedAt: item.viewedAt,
18454
+ isGuest: true,
18455
+ viewerIp: item.viewerIp || 'Unknown'
18456
+ };
18457
+ }
18458
+ });
18459
 
18460
  res.json(formattedViewers);
18461
 
 
18465
  }
18466
  });
18467
 
 
18468
  // ============================================
18469
  // GET /api/pages/suggestions - جلب اقتراحات ال��فحات
18470
  // ============================================
 
18609
  return res.status(400).json({ error: 'targetUserId is required' });
18610
  }
18611
 
18612
+ // ✅ لا تسجل مشاهدة لنفس المستخدم
18613
  if (req.user?.userId === targetUserId) {
18614
  return res.json({ success: true, message: 'Self view not tracked' });
18615
  }
18616
 
18617
+ // ============================
18618
+ // 📊 1. تسجيل في ProfileAnalytics (لكل المشاهدات)
18619
+ // ============================
18620
  let analytics = await ProfileAnalytics.findOne({ userId: targetUserId });
18621
 
18622
  if (!analytics) {
18623
  analytics = new ProfileAnalytics({ userId: targetUserId });
18624
  }
18625
 
 
18626
  analytics.profileViews = analytics.profileViews || [];
18627
  analytics.profileViews.push({
18628
+ viewerId: req.user?.userId || null,
18629
+ viewerIp: req.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress,
18630
  viewedAt: new Date()
18631
  });
18632
 
18633
+ // ✅ الاحتفاظ بآخر 100 مشاهدة فقط
18634
  if (analytics.profileViews.length > 100) {
18635
  analytics.profileViews = analytics.profileViews.slice(-100);
18636
  }
 
18638
  analytics.lastUpdated = new Date();
18639
  await analytics.save();
18640
 
18641
+ // ============================
18642
+ // 👥 2. تسجيل في AlsoViewed (للمستخدمين المسجلين والزوار)
18643
+ // ============================
18644
+ const viewerIp = req.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
18645
+
18646
  if (req.user?.userId) {
18647
+ // ✅ مستخدم مسجل
18648
  await AlsoViewed.findOneAndUpdate(
18649
  { targetUserId, viewerId: req.user.userId },
18650
+ {
18651
+ viewedAt: new Date(),
18652
+ viewerIp: viewerIp
18653
+ },
18654
  { upsert: true }
18655
  );
18656
+ } else {
18657
+ // ✅ زائر (غير مسجل) - نستخدم IP
18658
+ // نتحقق إذا كان هذا الـ IP شاهد خلال آخر 24 ساعة
18659
+ const existingView = await AlsoViewed.findOne({
18660
+ targetUserId,
18661
+ viewerIp: viewerIp,
18662
+ viewedAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }
18663
+ });
18664
+
18665
+ if (!existingView) {
18666
+ await AlsoViewed.create({
18667
+ targetUserId,
18668
+ viewerId: null,
18669
+ viewerIp: viewerIp,
18670
+ viewedAt: new Date()
18671
+ });
18672
+ }
18673
  }
18674
 
18675
  res.json({ success: true });
18676
 
18677
  } catch (error) {
18678
  logger.error(`Error tracking profile view: ${error.message}`);
18679
+ // ✅ لا نرسل خطأ للمستخدم حتى لا يسبب مشاكل
18680
  res.json({ success: true });
18681
  }
18682
  });