All files / Backend/Controller recommendation.js

5.64% Statements 7/124
2.4% Branches 2/83
0% Functions 0/27
6.66% Lines 7/105

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3781x 1x 1x 1x 1x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1x        
const Event = require('../Models/Event');
const User = require('../Models/User');
const EventParticipationLog = require('../Models/EventParticipationLog');
const axios = require('axios');
const logger = require('winston');
 
// ML API configuration
const ML_API_URL = process.env.ML_API_URL || 'http://localhost:5002';
 
/**
 * Get personalized event recommendations for a user
 */
async function getEventRecommendations(req, res) {
  try {
    const userId = req.user.id;
    const { limit = 10, page = 1 } = req.query;
 
    // Get user profile data
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
 
    // Get user's event history
    const userHistory = await EventParticipationLog.find({ userId })
      .populate('eventId', 'title description tags type organizer schedule')
      .sort({ timestamp: -1 })
      .limit(20);
 
    // Get user's interests and skills
    const userProfile = {
      userId: user._id,
      userName: user.name,
      userEmail: user.email,
      interests: user.interests || [],
      skills: user.skills || [],
      attendedEvents: userHistory.filter(log => log.status === 'attended').map(log => ({
        eventId: log.eventId._id,
        title: log.eventId.title,
        type: log.eventId.type,
        tags: log.eventId.tags || [],
        organizer: log.eventId.organizer
      })),
      registeredEvents: userHistory.filter(log => log.status === 'registered').map(log => ({
        eventId: log.eventId._id,
        title: log.eventId.title,
        type: log.eventId.type,
        tags: log.eventId.tags || [],
        organizer: log.eventId.organizer
      }))
    };
 
    // Get available events for recommendation
    const availableEvents = await Event.find({
      verificationStatus: 'approved',
      'schedule.start': { $gte: new Date() }
    }).select('title description tags type organizer schedule hostUserId institutionId');
 
    // Prepare data for ML API
    const recommendationData = {
      userProfile,
      availableEvents: availableEvents.map(event => ({
        eventId: event._id,
        title: event.title,
        description: event.description,
        type: event.type,
        tags: event.tags || [],
        organizer: event.organizer,
        schedule: event.schedule
      })),
      limit: parseInt(limit),
      page: parseInt(page)
    };
 
    // Call ML API for recommendations
    try {
      const mlResponse = await axios.post(`${ML_API_URL}/recommend`, recommendationData, {
        timeout: 10000
      });
 
      const recommendations = mlResponse.data.recommendations || [];
      
      // Get full event details for recommended events
      const recommendedEventIds = recommendations.map(rec => rec.eventId);
      const recommendedEvents = await Event.find({
        _id: { $in: recommendedEventIds }
      }).populate('hostUserId', 'name email');
 
      // Map recommendations with full event details
      const finalRecommendations = recommendations.map(rec => {
        const event = recommendedEvents.find(e => e._id.toString() === rec.eventId);
        return {
          eventId: rec.eventId,
          similarityScore: rec.similarityScore,
          reason: rec.reason,
          event: event ? {
            _id: event._id,
            title: event.title,
            description: event.description,
            tags: event.tags,
            type: event.type,
            organizer: event.organizer,
            schedule: event.schedule,
            host: event.hostUserId,
            verificationStatus: event.verificationStatus,
            isPaid: event.isPaid,
            price: event.price
          } : null
        };
      }).filter(rec => rec.event !== null);
 
      return res.json({
        recommendations: finalRecommendations,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: finalRecommendations.length
        },
        userProfile: {
          interests: userProfile.interests,
          skills: userProfile.skills,
          attendedCount: userProfile.attendedEvents.length,
          registeredCount: userProfile.registeredEvents.length
        }
      });
 
    } catch (mlError) {
      logger.error('ML API error:', mlError);
      
      // Fallback: return events based on user interests
      const fallbackRecommendations = await getFallbackRecommendations(userProfile, availableEvents, limit);
      
      return res.json({
        recommendations: fallbackRecommendations,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: fallbackRecommendations.length
        },
        userProfile: {
          interests: userProfile.interests,
          skills: userProfile.skills,
          attendedCount: userProfile.attendedEvents.length,
          registeredCount: userProfile.registeredEvents.length
        },
        note: 'Using fallback recommendations (ML API unavailable)'
      });
    }
 
  } catch (error) {
    logger.error('Event recommendation error:', error);
    return res.status(500).json({ error: 'Error getting event recommendations' });
  }
}
 
/**
 * Fallback recommendation system based on user interests
 */
async function getFallbackRecommendations(userProfile, availableEvents, limit) {
  const userInterests = userProfile.interests.map(interest => interest.toLowerCase());
  const userSkills = userProfile.skills.map(skill => skill.toLowerCase());
  
  // Score events based on user interests and skills
  const scoredEvents = availableEvents.map(event => {
    let score = 0;
    const eventTags = (event.tags || []).map(tag => tag.toLowerCase());
    const eventType = (event.type || '').toLowerCase();
    const eventDescription = (event.description || '').toLowerCase();
    
    // Score based on interests
    userInterests.forEach(interest => {
      if (eventTags.includes(interest)) score += 3;
      if (eventType.includes(interest)) score += 2;
      if (eventDescription.includes(interest)) score += 1;
    });
    
    // Score based on skills
    userSkills.forEach(skill => {
      if (eventTags.includes(skill)) score += 2;
      if (eventType.includes(skill)) score += 1;
    });
    
    // Bonus for events from same organizer as attended events
    const attendedOrganizers = userProfile.attendedEvents.map(e => e.organizer);
    if (attendedOrganizers.includes(event.organizer)) score += 1;
    
    return {
      eventId: event._id,
      similarityScore: score,
      reason: score > 0 ? 'Based on your interests and skills' : 'Popular events',
      event: {
        _id: event._id,
        title: event.title,
        description: event.description,
        tags: event.tags,
        type: event.type,
        organizer: event.organizer,
        schedule: event.schedule
      }
    };
  });
  
  // Sort by score and return top recommendations
  return scoredEvents
    .sort((a, b) => b.similarityScore - a.similarityScore)
    .slice(0, parseInt(limit));
}
 
/**
 * Get similar events based on a specific event
 */
async function getSimilarEvents(req, res) {
  try {
    const { eventId } = req.params;
    const { limit = 5 } = req.query;
 
    const event = await Event.findById(eventId);
    if (!event) {
      return res.status(404).json({ error: 'Event not found' });
    }
 
    // Find events with similar tags, type, or organizer
    const similarEvents = await Event.find({
      _id: { $ne: eventId },
      verificationStatus: 'approved',
      'schedule.start': { $gte: new Date() },
      $or: [
        { tags: { $in: event.tags || [] } },
        { type: event.type },
        { organizer: event.organizer }
      ]
    })
      .populate('hostUserId', 'name email')
      .limit(parseInt(limit))
      .sort({ 'schedule.start': 1 });
 
    const recommendations = similarEvents.map(similarEvent => ({
      eventId: similarEvent._id,
      similarityScore: calculateSimilarityScore(event, similarEvent),
      reason: getSimilarityReason(event, similarEvent),
      event: {
        _id: similarEvent._id,
        title: similarEvent.title,
        description: similarEvent.description,
        tags: similarEvent.tags,
        type: similarEvent.type,
        organizer: similarEvent.organizer,
        schedule: similarEvent.schedule,
        host: similarEvent.hostUserId,
        verificationStatus: similarEvent.verificationStatus,
        isPaid: similarEvent.isPaid,
        price: similarEvent.price
      }
    }));
 
    return res.json({
      baseEvent: {
        _id: event._id,
        title: event.title,
        description: event.description,
        tags: event.tags,
        type: event.type,
        organizer: event.organizer
      },
      similarEvents: recommendations
    });
 
  } catch (error) {
    logger.error('Similar events error:', error);
    return res.status(500).json({ error: 'Error getting similar events' });
  }
}
 
/**
 * Calculate similarity score between two events
 */
function calculateSimilarityScore(event1, event2) {
  let score = 0;
  
  // Tag similarity
  const tags1 = new Set(event1.tags || []);
  const tags2 = new Set(event2.tags || []);
  const tagIntersection = new Set([...tags1].filter(x => tags2.has(x)));
  score += tagIntersection.size * 2;
  
  // Type similarity
  if (event1.type === event2.type) score += 3;
  
  // Organizer similarity
  if (event1.organizer === event2.organizer) score += 2;
  
  return score;
}
 
/**
 * Get reason for similarity
 */
function getSimilarityReason(event1, event2) {
  const reasons = [];
  
  if (event1.type === event2.type) {
    reasons.push('Same event type');
  }
  
  const tags1 = new Set(event1.tags || []);
  const tags2 = new Set(event2.tags || []);
  const commonTags = [...tags1].filter(x => tags2.has(x));
  
  if (commonTags.length > 0) {
    reasons.push(`Similar tags: ${commonTags.join(', ')}`);
  }
  
  if (event1.organizer === event2.organizer) {
    reasons.push('Same organizer');
  }
  
  return reasons.join(', ');
}
 
/**
 * Update user preferences based on event interaction
 */
async function updateUserPreferences(req, res) {
  try {
    const userId = req.user.id;
    const { eventId, action } = req.body; // action: 'view', 'like', 'attend', 'register'
 
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
 
    const event = await Event.findById(eventId);
    if (!event) {
      return res.status(404).json({ error: 'Event not found' });
    }
 
    // Update user preferences based on action
    const updatedInterests = [...(user.interests || [])];
    const updatedSkills = [...(user.skills || [])];
 
    if (action === 'like' || action === 'attend') {
      // Add event tags to interests if not already present
      (event.tags || []).forEach(tag => {
        if (!updatedInterests.includes(tag)) {
          updatedInterests.push(tag);
        }
      });
 
      // Add event type to interests if not already present
      if (event.type && !updatedInterests.includes(event.type)) {
        updatedInterests.push(event.type);
      }
    }
 
    // Update user profile
    await User.findByIdAndUpdate(userId, {
      interests: updatedInterests,
      skills: updatedSkills
    });
 
    return res.json({
      message: 'User preferences updated successfully',
      updatedInterests,
      updatedSkills
    });
 
  } catch (error) {
    logger.error('Update user preferences error:', error);
    return res.status(500).json({ error: 'Error updating user preferences' });
  }
}
 
module.exports = {
  getEventRecommendations,
  getSimilarEvents,
  updateUserPreferences
};