Spaces:
Sleeping
Sleeping
File size: 8,691 Bytes
0b355ec | 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 | const { validationResult } = require('express-validator');
const User = require('../models/User');
const Conversation = require('../models/Conversation');
const logger = require('../utils/logger');
class UserController {
async getProfile(req, res) {
try {
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id;
const user = await User.findById(userId).select('-passwordHash -integrationTokens');
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
res.json({
success: true,
data: user
});
} catch (error) {
logger.error('Get profile error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch profile'
});
}
}
async updateProfile(req, res) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
const updateData = {};
const allowedFields = ['firstName', 'lastName', 'displayName', 'college', 'department', 'major', 'classification'];
allowedFields.forEach(field => {
if (req.body[field] !== undefined) {
updateData[field] = req.body[field];
}
});
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const user = await User.findByIdAndUpdate(
req.user.id,
updateData,
{ new: true, runValidators: true }
).select('-passwordHash -integrationTokens');
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
logger.info('Profile updated', { userId: req.user.id, updates: Object.keys(updateData) });
res.json({
success: true,
data: user,
message: 'Profile updated successfully'
});
} catch (error) {
logger.error('Update profile error:', error);
res.status(500).json({
success: false,
error: 'Failed to update profile'
});
}
}
async getPreferences(req, res) {
try {
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const user = await User.findById(req.user.id).select('preferences');
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
res.json({
success: true,
data: user.preferences
});
} catch (error) {
logger.error('Get preferences error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch preferences'
});
}
}
async updatePreferences(req, res) {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
const updateData = {};
// Handle nested preference updates
if (req.body.theme) updateData['preferences.theme'] = req.body.theme;
if (req.body.language) updateData['preferences.language'] = req.body.language;
if (req.body.chatHistory !== undefined) updateData['preferences.chatHistory'] = req.body.chatHistory;
// Handle notifications object
if (req.body.notifications) {
if (req.body.notifications.email !== undefined) {
updateData['preferences.notifications.email'] = req.body.notifications.email;
}
if (req.body.notifications.push !== undefined) {
updateData['preferences.notifications.push'] = req.body.notifications.push;
}
if (req.body.notifications.sms !== undefined) {
updateData['preferences.notifications.sms'] = req.body.notifications.sms;
}
}
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const user = await User.findByIdAndUpdate(
req.user.id,
updateData,
{ new: true, runValidators: true }
).select('preferences');
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
logger.info('Preferences updated', { userId: req.user.id, updates: Object.keys(updateData) });
res.json({
success: true,
data: user.preferences,
message: 'Preferences updated successfully'
});
} catch (error) {
logger.error('Update preferences error:', error);
res.status(500).json({
success: false,
error: 'Failed to update preferences'
});
}
}
async getStats(req, res) {
try {
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const userId = req.user.id;
const user = await User.findById(userId).select('stats');
if (!user) {
return res.status(404).json({
success: false,
error: 'User not found'
});
}
// Ensure stats object exists and has default values
const userStats = user.stats || {
totalChats: 0,
totalQuestions: 0,
favoriteTopics: [],
lastActive: new Date()
};
// Get additional conversation statistics
const conversationStats = await Conversation.aggregate([
{ $match: { userId: userId, isActive: true } },
{
$group: {
_id: '$category',
count: { $sum: 1 },
avgMessageCount: { $avg: '$stats.messageCount' },
totalMessages: { $sum: '$stats.messageCount' }
}
}
]);
const totalConversations = await Conversation.countDocuments({
userId: userId,
isActive: true
});
const stats = {
totalChats: userStats.totalChats || 0,
totalQuestions: userStats.totalQuestions || 0,
favoriteTopics: userStats.favoriteTopics || [],
lastActive: userStats.lastActive || new Date(),
totalConversations,
conversationsByCategory: conversationStats,
averageConversationLength: conversationStats.reduce((acc, cat) => acc + (cat.avgMessageCount || 0), 0) / (conversationStats.length || 1)
};
res.json({
success: true,
data: stats
});
} catch (error) {
logger.error('Get stats error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch statistics'
});
}
}
async getConversationsSummary(req, res) {
try {
const { limit = 10, category } = req.query;
// Require authenticated user
if (!req.user || !req.user.id) {
return res.status(401).json({
success: false,
error: 'Authentication required'
});
}
const matchQuery = { userId: req.user.id, isActive: true };
if (category && category !== 'all') {
matchQuery.category = category;
}
const conversations = await Conversation.find(matchQuery)
.select('title category lastActivity stats.messageCount stats.userSatisfaction')
.sort({ lastActivity: -1 })
.limit(parseInt(limit));
const summary = {
recentConversations: conversations,
totalActive: await Conversation.countDocuments({ userId: req.user.id, isActive: true }),
categories: await Conversation.aggregate([
{ $match: { userId: req.user.id, isActive: true } },
{ $group: { _id: '$category', count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
};
res.json({
success: true,
data: summary
});
} catch (error) {
logger.error('Get conversations summary error:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch conversations summary'
});
}
}
}
module.exports = new UserController(); |