diff --git a/client/js/messages-page.js b/client/js/messages-page.js index e0411d5..bf5f335 100644 --- a/client/js/messages-page.js +++ b/client/js/messages-page.js @@ -194,15 +194,20 @@ $(document).ready(function () { }, success: function (message) { $('#messageModal').remove(); - - const canReply = currentUsername !== message.sender.username; - + + const canReply = type === 'inbox' || type === 'archive'; + + console.log('Received message:', message); // Add this line for debugging + console.log('Sender object:', message.sender); + console.log('Recipient object:', message.recipient); + + const formattedMessage = ` - From: ${escapeHtml(message.sender.username)}
- Date: ${new Date(message.sentAt).toLocaleString()}

- ${escapeHtml(message.message).replace(/\n/g, '
')} + From: ${escapeHtml(message.sender && message.sender.username ? message.sender.username : 'Unknown')}
+ Date: ${new Date(message.sentAt).toLocaleString()}

+ ${escapeHtml(message.message).replace(/\n/g, '
')} `; - + const messageHtml = ` @@ -263,27 +244,68 @@ $(document).ready(function () { `; $('body').append(messageHtml); $('#messageModal').modal('show'); - + if (canReply) { $('#reply-button').on('click', function () { - $('#reply-form-container').toggle(); + const replyFormHtml = ` +
+
+
+ + +
+
+ +
+ +
+
+ `; + $('.modal-body').append(replyFormHtml); + $('#reply-button').prop('disabled', true); }); - - $('#reply-form').on('submit', function (e) { + + $('body').on('submit', '#reply-form', function (e) { e.preventDefault(); const replyMessage = $('#reply-message').val().trim(); const includeOriginal = $('#include-original').is(':checked'); - + if (replyMessage) { let fullMessage = replyMessage; if (includeOriginal) { - fullMessage += `\n\n--- Original Message ---\nFrom: ${escapeHtml( - message.sender.username - )} on ${new Date(message.sentAt).toLocaleString()}\n${ - message.message - }`; + const senderUsername = message.sender && message.sender.username ? message.sender.username : 'Unknown'; + fullMessage += `\n\n--- Original Message ---\nFrom: ${escapeHtml(senderUsername)} on ${new Date(message.sentAt).toLocaleString()}\n${escapeHtml(message.message)}`; } - + + // Truncate the message if it's too long + if (fullMessage.length > 1000) { + fullMessage = fullMessage.substring(0, 997) + '...'; + } + + // Truncate the subject if it's too long + let subject = `Re: ${message.subject}`; + if (subject.length > 100) { + subject = subject.substring(0, 97) + '...'; + } + + // Use the sender's username as the recipient for the reply + const recipient = message.sender && message.sender.username ? message.sender.username : null; + + console.log('Sending reply:', { recipient, subject, message: fullMessage }); + + if (!recipient) { + showAlert('danger', 'Invalid recipient. Unable to send reply.'); + return; + } + + const token = localStorage.getItem('token'); + if (!token) { + showAlert('danger', 'You must be logged in to send a reply.'); + return; + } + $.ajax({ url: '/api/messages/send', method: 'POST', @@ -292,15 +314,17 @@ $(document).ready(function () { 'Content-Type': 'application/json', }, data: JSON.stringify({ - recipient: message.sender.username, - subject: `Re: ${message.subject}`, + recipient: recipient, + subject: subject, message: fullMessage, }), success: function (response) { showAlert('success', 'Reply sent successfully.'); $('#reply-form')[0].reset(); - $('#reply-form-container').hide(); + $('#reply-form-container').remove(); + $('#reply-button').prop('disabled', false); $('#messageModal').modal('hide'); + loadMessages(type); }, error: function (xhr) { const errorMsg = @@ -308,6 +332,10 @@ $(document).ready(function () { ? xhr.responseJSON.error : 'Failed to send reply.'; showAlert('danger', errorMsg); + console.error('Error details:', xhr.responseJSON); + if (xhr.responseJSON && xhr.responseJSON.details) { + console.error('Validation errors:', xhr.responseJSON.details); + } }, }); } else { @@ -315,7 +343,7 @@ $(document).ready(function () { } }); } - + $('#messageModal').on('hidden.bs.modal', function () { $(this).remove(); }); diff --git a/server/functions/api/routes/messages.js b/server/functions/api/routes/messages.js index a2677c7..cd26954 100644 --- a/server/functions/api/routes/messages.js +++ b/server/functions/api/routes/messages.js @@ -168,31 +168,26 @@ router.get('/archived', authenticateToken, async (req, res) => { }); // Get a specific message by ID -router.get('/:id', authenticateToken, async (req, res) => { - const messageId = req.params.id; - try { - const message = await Message.findById(messageId) - .populate('sender', 'userId') - .populate('recipient', 'userId'); +router.get( + '/:id', + authenticateToken, + async (req, res) => { + try { + const message = await Message.findById(req.params.id) + .populate('sender', 'username') // Populate sender with username + .populate('recipient', 'username'); // Populate recipient with username - if (!message) { - return res.status(404).json({ error: 'Message not found' }); - } + if (!message) { + return res.status(404).json({ error: 'Message not found.' }); + } - // Verify that the requester is either the sender or the recipient - if ( - message.sender.userId !== req.user.userId && - message.recipient.userId !== req.user.userId - ) { - return res.status(403).json({ error: 'Access denied' }); + res.json(message); + } catch (error) { + console.error('Error fetching message:', error); + res.status(500).json({ error: 'Internal server error.' }); } - - res.json(message); - } catch (error) { - console.error('Error fetching message:', error); - res.status(500).json({ error: 'Internal server error' }); } -}); +); // (Optional) Delete a message router.delete('/:id', authenticateToken, async (req, res) => {