From 9dac97dbd4956f347a8285175892e9f7a447459d Mon Sep 17 00:00:00 2001 From: Heer64 <202401066@daiict.ac.in> Date: Fri, 20 Nov 2026 20:58:00 +0530 Subject: [PATCH] feat(sprint7): M3 comments and replies on feed posts Comment on a post, reply one level deep, edit/delete your own (placeholder when replies exist), comment count on the post card, seed --reset cleanup, optional Reply notification. --- README.md | 2 +- backend/src/app.js | 2 + backend/src/lib/commentRules.js | 171 ++++++++ backend/src/lib/moderation.js | 4 +- backend/src/lib/notifications.js | 3 +- backend/src/lib/postComments.js | 90 +++++ backend/src/lib/postRules.js | 4 +- backend/src/models/Notification.js | 6 +- backend/src/models/Post.js | 3 + backend/src/models/PostComment.js | 42 ++ backend/src/routes/postComments.js | 269 +++++++++++++ backend/src/routes/posts.js | 4 + backend/src/seed/seedData.js | 21 +- backend/test/commentRules.test.js | 124 ++++++ backend/test/notifications.test.js | 5 +- backend/test/postComments.test.js | 372 ++++++++++++++++++ backend/test/seed.test.js | 44 +++ frontend/src/api.js | 23 ++ frontend/src/comments.js | 88 +++++ frontend/src/comments.test.js | 80 ++++ frontend/src/components/NotificationBell.jsx | 4 +- .../src/components/PostCard.comments.test.jsx | 87 ++++ frontend/src/components/PostCard.jsx | 48 ++- frontend/src/components/PostComments.css | 39 ++ frontend/src/components/PostComments.jsx | 326 +++++++++++++++ frontend/src/components/PostComments.test.jsx | 201 ++++++++++ 26 files changed, 2046 insertions(+), 16 deletions(-) create mode 100644 backend/src/lib/commentRules.js create mode 100644 backend/src/lib/postComments.js create mode 100644 backend/src/models/PostComment.js create mode 100644 backend/src/routes/postComments.js create mode 100644 backend/test/commentRules.test.js create mode 100644 backend/test/postComments.test.js create mode 100644 frontend/src/comments.js create mode 100644 frontend/src/comments.test.js create mode 100644 frontend/src/components/PostCard.comments.test.jsx create mode 100644 frontend/src/components/PostComments.css create mode 100644 frontend/src/components/PostComments.jsx create mode 100644 frontend/src/components/PostComments.test.jsx diff --git a/README.md b/README.md index 95a814e..be20ff6 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ Both commands pass `--reset` to the seed script. **Warning:** Reset deletes and recreates the demo accounts, their projects and associated test data. Use only with a development database. The seed script refuses to run when `NODE_ENV=production`. -`--reset` also removes everything made with the demo accounts or inside the demo projects while you tested: decisions, docs, task comments, files (and their stored bytes), invitations, join requests, notifications, GitHub connection records, posts (with images), votes, reports, follows, direct messages, sessions, password reset links and profile photos. A real post a demo account voted on is recounted. A GitHub webhook created for a demo project is not removed on GitHub (the seed works offline): delete it in the repository's Settings → Webhooks. +`--reset` also removes everything made with the demo accounts or inside the demo projects while you tested: decisions, docs, task comments, files (and their stored bytes), invitations, join requests, notifications, GitHub connection records, posts (with images), votes, reports, post comments and replies, follows, direct messages, sessions, password reset links and profile photos. A real post a demo account voted on or commented on is recounted (a demo comment that a real user replied to stays as "Comment deleted", so the real reply is kept). A GitHub webhook created for a demo project is not removed on GitHub (the seed works offline): delete it in the repository's Settings → Webhooks. Then start both parts: diff --git a/backend/src/app.js b/backend/src/app.js index 0980da7..3fc98db 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -25,6 +25,7 @@ import projectFileRoutes from './routes/projectFiles.js'; // [Sprint 4 · M5] US import docRoutes from './routes/docs.js'; // [Sprint 4 · M6] US-38 import publicProjectRoutes from './routes/publicProjects.js'; // [Sprint 5 · M1] US-45 public Discover (no login) import { portfolioRoutes, publicPortfolioRoutes } from './routes/portfolio.js'; // [Sprint 5 · M5] US-49 portfolio +import postCommentRoutes from './routes/postComments.js'; // [Sprint 7 · M3] comments and replies on posts import postRoutes from './routes/posts.js'; // [Sprint 5 · M6] US-50, US-51 public posts import postVoteRoutes from './routes/postVotes.js'; // [Sprint 5 · M7] US-52 vote on a post import postReportRoutes from './routes/postReports.js'; // [Sprint 6 · M6] US-55 report a post @@ -165,6 +166,7 @@ export function createApp() { // [Sprint 5 · M7] US-52. Mounted before the post routes so only vote URLs reach it. app.use('/api/posts/trending', trendingRoutes); // [Sprint 5 · M8] US-53 (before /api/posts, so "trending" is not a post ID) app.use('/api/posts/:postId/vote', postVoteRoutes); + app.use('/api/posts/:postId/comments', postCommentRoutes); // [Sprint 7 · M3] comments + replies (before /api/posts) app.use('/api/posts/:postId/report', postReportRoutes); // [Sprint 6 · M6] US-55 (before /api/posts, so only report URLs reach it) app.use('/api/posts', postRoutes); // [Sprint 5 · M6] US-50/US-51 public posts (login; only /:postId/image is open) app.use('/api/direct-messages', directMessageRoutes); // [Sprint 6 · M2] US-19 direct messages (only the two participants) diff --git a/backend/src/lib/commentRules.js b/backend/src/lib/commentRules.js new file mode 100644 index 0000000..069fd0e --- /dev/null +++ b/backend/src/lib/commentRules.js @@ -0,0 +1,171 @@ +import { normalizePostText } from './postRules.js'; + +/* + * [Sprint 7 · M3] Comments and replies on feed posts (Sprint 7 "Miscellaneous", M3). + * + * No database imports, so these rules are tested on their own (backend/test/commentRules.test.js) + * and the route, the tests, the README and the frontend (frontend/src/comments.js) use the same numbers. + * + * A comment is + * text required, 1 to 500 characters after trimming (same cleaning as a post: line breaks kept, + * invisible control characters removed) + * parent null for a comment on the post, or the ID of a comment on the SAME post for a reply. + * Replies are one level deep: you can reply to a comment, not to a reply. + * + * Who may do what + * Any logged-in user can comment on any post and reply to any comment. + * Only the author can edit or delete their own comment or reply (anyone else gets 403). + * + * Deleting + * A reply, or a comment without replies, is removed completely. + * A comment that still has replies becomes a "Comment deleted" placeholder (text and author hidden), + * so the replies under it still make sense. When its last reply is deleted the placeholder goes too. + * + * Counting + * post.commentCount = comments + replies that are not deleted. It is moved with one atomic $inc per + * change (create +1, delete -1), so two people commenting at the same moment both count. + */ + +export const COMMENT_TEXT_MAX = 500; +export const COMMENTS_PAGE_DEFAULT = 20; +export const COMMENTS_PAGE_MAX = 50; + +export const COMMENT_TEXT_REQUIRED_MESSAGE = 'Write a comment first.'; +export const COMMENT_TEXT_TOO_LONG_MESSAGE = `Comments must be ${COMMENT_TEXT_MAX} characters or fewer.`; +export const COMMENT_TEXT_TYPE_MESSAGE = 'Comment text must be text.'; +export const COMMENT_NOT_FOUND_MESSAGE = 'Comment not found. It may have been deleted.'; +export const COMMENT_NOT_AUTHOR_MESSAGE = 'You can only edit or delete your own comments.'; +export const COMMENT_REPLY_TO_REPLY_MESSAGE = 'You can reply to a comment, but not to a reply.'; +export const COMMENT_PARENT_NOT_FOUND_MESSAGE = 'The comment you are replying to was deleted.'; +export const COMMENT_CREATED_MESSAGE = 'Your comment was added.'; +export const REPLY_CREATED_MESSAGE = 'Your reply was added.'; +export const COMMENT_UPDATED_MESSAGE = 'Your comment was updated.'; +export const COMMENT_DELETED_MESSAGE = 'Your comment was deleted.'; +export const COMMENT_DELETED_PLACEHOLDER = 'Comment deleted'; + +// The comment text sent by the client. Returns { ok: true, value } or { ok: false, message }. +export function readCommentText(raw) { + if (raw === undefined || raw === null) return { ok: false, message: COMMENT_TEXT_REQUIRED_MESSAGE }; + if (typeof raw !== 'string') return { ok: false, message: COMMENT_TEXT_TYPE_MESSAGE }; + const value = normalizePostText(raw); + if (!value) return { ok: false, message: COMMENT_TEXT_REQUIRED_MESSAGE }; + if (value.length > COMMENT_TEXT_MAX) return { ok: false, message: COMMENT_TEXT_TOO_LONG_MESSAGE }; + return { ok: true, value }; +} + +// Page size for the list of comments: a whole number from 1 to COMMENTS_PAGE_MAX (default COMMENTS_PAGE_DEFAULT). +export function readCommentLimit(raw) { + const value = Number.parseInt(raw, 10); + if (!Number.isFinite(value) || value < 1) return COMMENTS_PAGE_DEFAULT; + return Math.min(value, COMMENTS_PAGE_MAX); +} + +const idOf = (value) => { + if (!value) return ''; + if (typeof value === 'object' && value._id) return String(value._id); + return String(value); +}; + +// True when userId wrote the comment (comment.author may be an id or a populated user). +export function isCommentAuthor(comment, userId) { + if (!comment || !userId) return false; + const author = idOf(comment.author); + return Boolean(author) && author === String(userId); +} + +/* + * What happens when the author deletes a comment: + * 'remove' it is a reply, or a comment with no replies left -> delete the row + * 'placeholder' it is a comment that still has replies -> keep it as "Comment deleted" + */ +export function deleteMode(comment, replyCount) { + if (comment?.parent) return 'remove'; + return replyCount > 0 ? 'placeholder' : 'remove'; +} + +/* + * API shape of one comment or reply: + * { _id, post, parent | null, author { _id, name, username, avatarUrl } | null, text, + * edited, editedAt, deleted, createdAt, updatedAt, isMine } + * A deleted placeholder has text '', author null and isMine false: nothing about it is shown or editable. + * Top-level comments also get replies: [...] and replyCount from the route. + */ +export function commentView(comment, viewerId = null) { + const deleted = Boolean(comment.deletedAt); + const author = !deleted && comment.author && typeof comment.author === 'object' && comment.author.name !== undefined + ? { + _id: String(comment.author._id), + name: comment.author.name, + username: comment.author.username, + avatarUrl: comment.author.avatarUrl || '', + } + : null; + return { + _id: String(comment._id), + post: idOf(comment.post), + parent: comment.parent ? idOf(comment.parent) : null, + author, + text: deleted ? '' : comment.text, + edited: !deleted && Boolean(comment.editedAt), + editedAt: deleted ? null : comment.editedAt || null, + deleted, + createdAt: comment.createdAt, + updatedAt: comment.updatedAt, + isMine: !deleted && isCommentAuthor(comment, viewerId), + }; +} + +/* + * Builds the list the client shows: top-level comments (oldest first, in the order given), each with + * its replies (oldest first) and replyCount. Replies whose comment is not on this page are left out. + */ +export function threadComments(topLevel, replies, viewerId = null) { + const byParent = new Map(); + for (const reply of replies) { + const key = idOf(reply.parent); + if (!byParent.has(key)) byParent.set(key, []); + byParent.get(key).push(reply); + } + return topLevel.map((comment) => { + const own = (byParent.get(String(comment._id)) || []) + .slice() + .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt) || String(a._id).localeCompare(String(b._id))); + return { + ...commentView(comment, viewerId), + replyCount: own.length, + replies: own.map((reply) => commentView(reply, viewerId)), + }; + }); +} + +/* + * [Sprint 7 · M3] Optional part: the notification text when someone comments on your post or replies + * to your comment. Short excerpts only, so a long post or comment does not fill the notification list. + */ +export const COMMENT_EXCERPT_MAX = 60; + +export function commentExcerpt(text, max = COMMENT_EXCERPT_MAX) { + const flat = String(text ?? '').replace(/\s+/g, ' ').trim(); + if (flat.length <= max) return flat; + return `${flat.slice(0, max - 1).trimEnd()}…`; +} + +// The UI shows " " (like every notification with an actor), so no name here. +export function replyNotificationSummary({ isReply, targetText }) { + const what = isReply ? 'replied to your comment' : 'commented on your post'; + const excerpt = commentExcerpt(targetText); + return excerpt ? `${what} "${excerpt}"` : what; +} + +// One notification per comment or reply, even if the same request is retried. +export const replyDedupeKey = (commentId) => `post_reply:${commentId}`; + +/* + * --------------------------------------------------------------------------- + * [Sprint 7 · M3] What this file does + * The rules for comments on public posts: text up to 500 characters, replies only + * one level deep, only the author edits or deletes, a deleted comment with replies + * stays as "Comment deleted". Also turns comments into their API shape and builds + * the text of the "someone replied" notification. + * --------------------------------------------------------------------------- + */ diff --git a/backend/src/lib/moderation.js b/backend/src/lib/moderation.js index df82e2a..e2b8cd6 100644 --- a/backend/src/lib/moderation.js +++ b/backend/src/lib/moderation.js @@ -8,6 +8,7 @@ import { validId } from './projectAccess.js'; import { openReportQueue } from './postReports.js'; import { deletePostImage } from './postImages.js'; import { deleteVotesForPost } from './postVotes.js'; +import { deleteCommentsForPost } from './postComments.js'; // [Sprint 7 · M3] import { createPersonalNotification } from './notifications.js'; import { postView } from './postRules.js'; import { REPORT_STATUS_OPEN, REPORT_STATUS_RESOLVED, reportReasonLabel, summarizeReasons } from './reportRules.js'; @@ -187,11 +188,12 @@ export async function moderatePost({ postId, action, moderatorId }) { let message = MODERATION_MESSAGES.dismissed; if (action === MODERATION_ACTION_REMOVE) { - // Same clean-up as the author's own delete (routes/posts.js DELETE): the post, its image and its votes. + // Same clean-up as the author's own delete (routes/posts.js DELETE): the post, its image, its votes and comments. const removed = await Post.findOneAndDelete({ _id: post }); if (removed) { await deletePostImage(removed.image?.storageId); await deleteVotesForPost(removed._id); + await deleteCommentsForPost(removed._id); // [Sprint 7 · M3] its comments and replies go with it } message = MODERATION_MESSAGES.removed; } else if (action === MODERATION_ACTION_WARN) { diff --git a/backend/src/lib/notifications.js b/backend/src/lib/notifications.js index aa7948e..dcadc19 100644 --- a/backend/src/lib/notifications.js +++ b/backend/src/lib/notifications.js @@ -63,8 +63,9 @@ async function publish(saved) { * moderation_warning a Content Moderator warned them about their post (no project) * join_approved their join request was approved (project = that project) * join_rejected their join request was declined (project = that project; they are NOT a member) + * post_reply [Sprint 7 · M3] someone commented on their post or replied to their comment (no project) * Unlike createNotification() there is no "must be a member" check, because these people may not be members. - * Only these three types are accepted. Same rules otherwise: never to the actor themselves, idempotent with a + * Only these types (PERSONAL_NOTIFICATION_TYPES) are accepted. Same rules otherwise: never to the actor themselves, idempotent with a * dedupeKey, never throws (returns null), pushed live like every other notification. */ export async function createPersonalNotification({ diff --git a/backend/src/lib/postComments.js b/backend/src/lib/postComments.js new file mode 100644 index 0000000..d80814c --- /dev/null +++ b/backend/src/lib/postComments.js @@ -0,0 +1,90 @@ +import Post from '../models/Post.js'; +import PostComment from '../models/PostComment.js'; +import { createPersonalNotification } from './notifications.js'; +import { commentExcerpt, isCommentAuthor, replyDedupeKey, replyNotificationSummary } from './commentRules.js'; + +/* + * [Sprint 7 · M3] Database helpers for comments on public posts. Used by routes/postComments.js and by the + * places that delete a post (routes/posts.js DELETE, lib/moderation.js "remove", seed --reset). + * + * changeCommentCount(postId, by) one atomic $inc of post.commentCount (never below 0); returns the new + * count, or null when the post is gone + * recountPostComments(postId) sets post.commentCount from the comment rows (repair / seed reset) + * deleteCommentsForPost(postId) removes every comment and reply of a deleted post + * notifyCommentReply(...) optional part: tells the post author / comment author (never throws) + */ + +export const COMMENT_LINK = '/feed'; + +export async function changeCommentCount(postId, by) { + if (by >= 0) { + const post = await Post.findOneAndUpdate({ _id: postId }, { $inc: { commentCount: by } }, { new: true }) + .select('commentCount') + .lean(); + return post ? post.commentCount : null; + } + // Only lower the count while it is high enough, so it can never go below 0. + const post = await Post.findOneAndUpdate( + { _id: postId, commentCount: { $gte: -by } }, + { $inc: { commentCount: by } }, + { new: true } + ) + .select('commentCount') + .lean(); + if (post) return post.commentCount; + // The stored count was already too low (e.g. an old post): repair it from the rows instead. + return recountPostComments(postId); +} + +export async function recountPostComments(postId) { + const count = await PostComment.countDocuments({ post: postId, deletedAt: null }); + const post = await Post.findOneAndUpdate({ _id: postId }, { $set: { commentCount: count } }, { new: true }) + .select('commentCount') + .lean(); + return post ? post.commentCount : null; +} + +export async function deleteCommentsForPost(postId) { + if (!postId) return 0; + const result = await PostComment.deleteMany({ post: postId }); + return result.deletedCount || 0; +} + +/* + * Optional part of M3: a "Reply" notification (type post_reply, no project). + * a comment on a post -> the post's author + * a reply to a comment -> that comment's author (if the comment is not a deleted placeholder) + * Never to the person who wrote the new comment. One per new comment (dedupeKey), pushed live. + */ +export async function notifyCommentReply({ comment, post, parent = null }) { + try { + const isReply = Boolean(parent); + const target = isReply ? parent : post; + if (!target || (isReply && target.deletedAt)) return null; + const recipient = target.author && typeof target.author === 'object' && target.author._id ? target.author._id : target.author; + if (!recipient || isCommentAuthor({ author: recipient }, comment.author)) return null; + + return await createPersonalNotification({ + recipient, + type: 'post_reply', + project: null, + actor: comment.author, + summary: replyNotificationSummary({ isReply, targetText: target.text }), + targetType: 'comment', + targetId: comment._id, + targetLabel: commentExcerpt(comment.text), + link: COMMENT_LINK, + dedupeKey: replyDedupeKey(String(comment._id)), + }); + } catch { + return null; // a notification must never make the comment itself fail + } +} + +/* + * --------------------------------------------------------------------------- + * [Sprint 7 · M3] What this file does + * Keeps each post's comment count right (atomic +1 / -1), removes the comments of a + * deleted post, and sends the optional "someone replied" notification. + * --------------------------------------------------------------------------- + */ diff --git a/backend/src/lib/postRules.js b/backend/src/lib/postRules.js index e6c16fc..79f9e78 100644 --- a/backend/src/lib/postRules.js +++ b/backend/src/lib/postRules.js @@ -140,7 +140,8 @@ export function readPageLimit(raw) { * API shape of one post. The GridFS id of the image stays on the server. * { _id, author { _id, name, username, avatarUrl } | null, text, imageUrl | null, * image { contentType, size } | null, edited, editedAt, createdAt, updatedAt, - * upvotes, downvotes, score, isMine } + * upvotes, downvotes, score, commentCount, isMine } + * [Sprint 7 · M3] commentCount = comments + replies on the post (routes/postComments.js). * upvotes / downvotes / score are kept up to date by the vote engine (Sprint 5 · M7, lib/postVotes.js). * The routes add myVote (the viewer's own vote: 1, -1 or 0) with attachMyVotes(). */ @@ -168,6 +169,7 @@ export function postView(post, viewerId = null) { upvotes: post.upvotes || 0, downvotes: post.downvotes || 0, score: post.score || 0, + commentCount: Math.max(0, post.commentCount || 0), // [Sprint 7 · M3] isMine: isPostAuthor(post, viewerId), }; } diff --git a/backend/src/models/Notification.js b/backend/src/models/Notification.js index d4b1d57..c0e5447 100644 --- a/backend/src/models/Notification.js +++ b/backend/src/models/Notification.js @@ -12,10 +12,11 @@ import mongoose from 'mongoose'; // [Sprint 6 · M7] US-56 (FR-27, FR-33 "moderation warning") and FR-20 (the requester is told the outcome of a // join request). These are about the recipient personally, so they are shown to them whether or not they are a // member of a project (a warned post belongs to no project; a declined requester never became a member). -export const PERSONAL_NOTIFICATION_TYPES = ['moderation_warning', 'join_approved', 'join_rejected']; +// [Sprint 7 · M3] post_reply: someone commented on your public post or replied to your comment (no project). +export const PERSONAL_NOTIFICATION_TYPES = ['moderation_warning', 'join_approved', 'join_rejected', 'post_reply']; export const NOTIFICATION_TYPES = ['mention', 'assignment', 'deadline', ...PERSONAL_NOTIFICATION_TYPES]; // [Sprint 6 · M7] + personal types // Types that belong to no project (the project field stays empty). -export const PROJECTLESS_NOTIFICATION_TYPES = ['moderation_warning']; +export const PROJECTLESS_NOTIFICATION_TYPES = ['moderation_warning', 'post_reply']; // [Sprint 7 · M3] + post_reply // Label the UI shows for each type (US-30 acceptance criteria wording). export const NOTIFICATION_LABELS = { @@ -25,6 +26,7 @@ export const NOTIFICATION_LABELS = { moderation_warning: 'Moderation warning', // [Sprint 6 · M7] US-56 join_approved: 'Join request approved', // [Sprint 6 · M7] FR-20 join_rejected: 'Join request declined', // [Sprint 6 · M7] FR-20 + post_reply: 'Reply', // [Sprint 7 · M3] a comment on your post, or a reply to your comment }; // What a notification points at. Same names as Activity TARGET_TYPES (shared event schema). diff --git a/backend/src/models/Post.js b/backend/src/models/Post.js index 73de017..6c1d0f5 100644 --- a/backend/src/models/Post.js +++ b/backend/src/models/Post.js @@ -53,6 +53,9 @@ const postSchema = new mongoose.Schema( // [Sprint 5 · M8] US-53: score / (ageHours + 2)^1.5, written only by lib/trending.js at least every // 5 minutes (FR-25, NFR-15). A new post starts at 0, which is its true value (no votes yet). trendingScore: { type: Number, default: 0 }, + // [Sprint 7 · M3] Comments + replies that are not deleted. Moved only by lib/postComments.js + // with one atomic $inc per change. Posts made before Sprint 7 have no field and count as 0. + commentCount: { type: Number, default: 0, min: 0 }, }, { timestamps: true } ); diff --git a/backend/src/models/PostComment.js b/backend/src/models/PostComment.js new file mode 100644 index 0000000..d95bec4 --- /dev/null +++ b/backend/src/models/PostComment.js @@ -0,0 +1,42 @@ +import mongoose from 'mongoose'; +import { COMMENT_TEXT_MAX } from '../lib/commentRules.js'; + +/* + * [Sprint 7 · M3] A comment on a public post, or a reply to such a comment (one level deep). + * + * parent: null -> a comment on the post + * parent: -> a reply to that comment (the parent is always a comment, never a reply) + * + * deletedAt is only set on a comment that still had replies when its author deleted it: it then shows + * as "Comment deleted" so the replies keep their context (lib/commentRules.js deleteMode()). + * Everything else that is deleted is removed from the collection. + * + * The post's commentCount (models/Post.js) counts the rows here whose deletedAt is null. + * Rules: lib/commentRules.js. API: routes/postComments.js. + */ +const postCommentSchema = new mongoose.Schema( + { + post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post', required: true }, + author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, + parent: { type: mongoose.Schema.Types.ObjectId, ref: 'PostComment', default: null }, + text: { + type: String, + trim: true, + maxlength: [COMMENT_TEXT_MAX, `Comments must be ${COMMENT_TEXT_MAX} characters or fewer.`], + // A deleted placeholder keeps no text; every live comment has some. + required: [function textRequired() { return !this.deletedAt; }, 'Write a comment first.'], + default: '', + }, + editedAt: { type: Date, default: null }, + deletedAt: { type: Date, default: null }, + }, + { timestamps: true } +); + +// The comments of one post in reading order (oldest first), and the replies of one comment. +postCommentSchema.index({ post: 1, parent: 1, _id: 1 }); +postCommentSchema.index({ parent: 1, _id: 1 }); +// Seed --reset and account clean-up find everything one user wrote. +postCommentSchema.index({ author: 1 }); + +export default mongoose.model('PostComment', postCommentSchema); diff --git a/backend/src/routes/postComments.js b/backend/src/routes/postComments.js new file mode 100644 index 0000000..10cf6d8 --- /dev/null +++ b/backend/src/routes/postComments.js @@ -0,0 +1,269 @@ +import { Router } from 'express'; + +import Post from '../models/Post.js'; +import PostComment from '../models/PostComment.js'; +import { requireAuth } from '../middleware/auth.js'; +import { validId } from '../lib/projectAccess.js'; +import { POST_NOT_FOUND_MESSAGE } from '../lib/postRules.js'; +import { + COMMENT_CREATED_MESSAGE, + COMMENT_DELETED_MESSAGE, + COMMENT_NOT_AUTHOR_MESSAGE, + COMMENT_NOT_FOUND_MESSAGE, + COMMENT_PARENT_NOT_FOUND_MESSAGE, + COMMENT_REPLY_TO_REPLY_MESSAGE, + COMMENT_UPDATED_MESSAGE, + REPLY_CREATED_MESSAGE, + commentView, + deleteMode, + isCommentAuthor, + readCommentLimit, + readCommentText, + threadComments, +} from '../lib/commentRules.js'; +import { changeCommentCount, notifyCommentReply } from '../lib/postComments.js'; + +/* + * [Sprint 7 · M3] Comments and replies on public posts. Mounted at /api/posts/:postId/comments (see app.js), + * before the post routes, so only comment URLs reach it. Login needed for everything. + * + * GET / ?limit=1..50 (default 20) &after= + * -> { comments, nextAfter, commentCount } + * comments: the post's comments, OLDEST first (reading order), each with replyCount and + * replies: [...] (oldest first). nextAfter is null on the last page. + * POST / JSON { text, parentId? } + * parentId missing/null -> a comment on the post; parentId = a comment of this post -> a reply + * -> 201 { comment, commentCount, message } + * 400 { message } text missing / too long / not text, invalid IDs, reply to a reply, + * or replying to a comment that was deleted + * 404 { message } unknown or deleted post + * PATCH /:commentId author only, JSON { text } + * -> { comment, message } the comment now has edited: true + * 403 not the author 404 unknown, deleted or on another post + * DELETE /:commentId author only (the UI asks for confirmation first) + * -> { commentId, deleted: 'removed' | 'placeholder', comment | null, commentCount, message } + * 'placeholder': it was a comment with replies, now shown as "Comment deleted" (comment = its view) + * 403 not the author 404 unknown, already deleted or on another post + * + * Each comment: commentView() in lib/commentRules.js (isMine says whether the viewer may edit/delete it). + * post.commentCount (comments + replies) is also returned in every post of GET /api/posts. + */ + +const router = Router({ mergeParams: true }); +const AUTHOR_FIELDS = 'name username avatarUrl'; + +router.use(requireAuth); + +// Loads the post (only what is needed). Answers 400/404 and returns null otherwise. +async function findPost(req, res) { + if (!validId(req.params.postId)) { + res.status(400).json({ message: 'Invalid post ID.' }); + return null; + } + const post = await Post.findById(req.params.postId).select('author text commentCount').lean(); + if (!post) { + res.status(404).json({ message: POST_NOT_FOUND_MESSAGE }); + return null; + } + return post; +} + +// Loads a live comment of this post that the current user wrote. Answers 400/404/403 otherwise. +async function findOwnComment(req, res, post) { + if (!validId(req.params.commentId)) { + res.status(400).json({ message: 'Invalid comment ID.' }); + return null; + } + const comment = await PostComment.findOne({ _id: req.params.commentId, post: post._id, deletedAt: null }); + if (!comment) { + res.status(404).json({ message: COMMENT_NOT_FOUND_MESSAGE }); + return null; + } + if (!isCommentAuthor(comment, req.user.id)) { + res.status(403).json({ message: COMMENT_NOT_AUTHOR_MESSAGE }); + return null; + } + return comment; +} + +async function viewOf(commentId, viewerId) { + const saved = await PostComment.findById(commentId).populate('author', AUTHOR_FIELDS).lean(); + return saved ? commentView(saved, viewerId) : null; +} + +// --- Read --------------------------------------------------------------------------------------- + +router.get('/', async (req, res, next) => { + try { + const post = await findPost(req, res); + if (!post) return undefined; + + const limit = readCommentLimit(req.query.limit); + const filter = { post: post._id, parent: null }; + if (req.query.after !== undefined) { + if (!validId(req.query.after)) return res.status(400).json({ message: 'Invalid "after" comment ID.' }); + filter._id = { $gt: req.query.after }; + } + + // ObjectIds grow with creation time, so _id ascending is oldest first and a stable cursor. + const rows = await PostComment.find(filter).sort({ _id: 1 }).limit(limit + 1).populate('author', AUTHOR_FIELDS).lean(); + const page = rows.slice(0, limit); + const replies = page.length + ? await PostComment.find({ post: post._id, parent: { $in: page.map((comment) => comment._id) } }) + .sort({ _id: 1 }) + .populate('author', AUTHOR_FIELDS) + .lean() + : []; + + res.set('Cache-Control', 'no-store'); + return res.json({ + comments: threadComments(page, replies, req.user.id), + nextAfter: rows.length > limit ? String(page[page.length - 1]._id) : null, + commentCount: Math.max(0, post.commentCount || 0), + }); + } catch (error) { + return next(error); + } +}); + +// --- Create a comment or a reply ---------------------------------------------------------------- + +router.post('/', async (req, res, next) => { + try { + const post = await findPost(req, res); + if (!post) return undefined; + + const text = readCommentText(req.body?.text); + if (!text.ok) return res.status(400).json({ message: text.message }); + + // A reply: the parent must be a live, top-level comment of THIS post (one level deep). + let parent = null; + const parentId = req.body?.parentId; + if (parentId !== undefined && parentId !== null && parentId !== '') { + if (typeof parentId !== 'string' || !validId(parentId)) return res.status(400).json({ message: 'Invalid comment ID to reply to.' }); + parent = await PostComment.findOne({ _id: parentId, post: post._id }).select('author text parent deletedAt').lean(); + if (!parent || parent.deletedAt) return res.status(400).json({ message: COMMENT_PARENT_NOT_FOUND_MESSAGE, code: 'parent_deleted' }); + if (parent.parent) return res.status(400).json({ message: COMMENT_REPLY_TO_REPLY_MESSAGE, code: 'reply_to_reply' }); + } + + const created = await PostComment.create({ + post: post._id, + author: req.user.id, + parent: parent ? parent._id : null, + text: text.value, + }); + + // If the post (or the comment replied to) was deleted while this was being saved, do not leave an orphan. + const [postStill, parentStill] = await Promise.all([ + Post.exists({ _id: post._id }), + parent ? PostComment.exists({ _id: parent._id }) : Promise.resolve(true), + ]); + if (!postStill || !parentStill) { + await PostComment.deleteOne({ _id: created._id }); + if (!postStill) return res.status(404).json({ message: POST_NOT_FOUND_MESSAGE }); + return res.status(400).json({ message: COMMENT_PARENT_NOT_FOUND_MESSAGE, code: 'parent_deleted' }); + } + + const commentCount = await changeCommentCount(post._id, 1); + await notifyCommentReply({ comment: created, post, parent }); // optional part; never throws + + return res.status(201).json({ + comment: { ...(await viewOf(created._id, req.user.id)), ...(parent ? {} : { replyCount: 0, replies: [] }) }, + commentCount: commentCount ?? 0, + message: parent ? REPLY_CREATED_MESSAGE : COMMENT_CREATED_MESSAGE, + }); + } catch (error) { + return next(error); + } +}); + +// --- Edit and delete your own ------------------------------------------------------------------- + +router.patch('/:commentId', async (req, res, next) => { + try { + const post = await findPost(req, res); + if (!post) return undefined; + const comment = await findOwnComment(req, res, post); + if (!comment) return undefined; + + const text = readCommentText(req.body?.text); + if (!text.ok) return res.status(400).json({ message: text.message }); + + // Saving the same text again is not an edit, so it does not get the "edited" mark. + if (text.value !== comment.text) { + comment.text = text.value; + comment.editedAt = new Date(); + await comment.save(); + } + + return res.json({ comment: await viewOf(comment._id, req.user.id), message: COMMENT_UPDATED_MESSAGE }); + } catch (error) { + return next(error); + } +}); + +router.delete('/:commentId', async (req, res, next) => { + try { + const post = await findPost(req, res); + if (!post) return undefined; + const comment = await findOwnComment(req, res, post); + if (!comment) return undefined; + + const replyCount = comment.parent ? 0 : await PostComment.countDocuments({ parent: comment._id }); + const mode = deleteMode(comment, replyCount); + let view = null; + + if (mode === 'placeholder') { + // Only the first of two delete clicks changes anything (the second finds deletedAt already set). + const marked = await PostComment.findOneAndUpdate( + { _id: comment._id, author: req.user.id, deletedAt: null }, + { $set: { deletedAt: new Date(), text: '', editedAt: null } }, + { new: true } + ).lean(); + if (!marked) return res.status(404).json({ message: COMMENT_NOT_FOUND_MESSAGE }); + view = commentView(marked, req.user.id); + } else { + const removed = await PostComment.findOneAndDelete({ _id: comment._id, author: req.user.id, deletedAt: null }); + if (!removed) return res.status(404).json({ message: COMMENT_NOT_FOUND_MESSAGE }); + // A reply arrived between counting and deleting: keep that reply, as a reply to a placeholder. + if (!removed.parent && (await PostComment.exists({ parent: removed._id }))) { + await PostComment.create({ + _id: removed._id, + post: removed.post, + author: removed.author, + parent: null, + text: '', + deletedAt: new Date(), + createdAt: removed.createdAt, + }); + } + } + + let commentCount = await changeCommentCount(post._id, -1); + + // The last reply under a "Comment deleted" placeholder is gone: the placeholder has nothing left to explain. + if (comment.parent) { + const placeholder = await PostComment.findOne({ _id: comment.parent, deletedAt: { $ne: null } }).select('_id').lean(); + if (placeholder && !(await PostComment.exists({ parent: placeholder._id }))) { + await PostComment.deleteOne({ _id: placeholder._id, deletedAt: { $ne: null } }); + } + } + + if (commentCount === null) commentCount = 0; + return res.json({ commentId: String(comment._id), deleted: mode === 'placeholder' ? 'placeholder' : 'removed', comment: view, commentCount, message: COMMENT_DELETED_MESSAGE }); + } catch (error) { + return next(error); + } +}); + +export default router; + +/* + * --------------------------------------------------------------------------- + * [Sprint 7 · M3] What this file does + * REST API for comments on public posts: list a post's comments with their replies, + * add a comment or a reply (one level deep), and let ONLY the author edit + * ("edited") or delete their own. A deleted comment that still has replies stays as + * "Comment deleted". Every change keeps the post's commentCount right. + * --------------------------------------------------------------------------- + */ diff --git a/backend/src/routes/posts.js b/backend/src/routes/posts.js index 0eb200a..07329fe 100644 --- a/backend/src/routes/posts.js +++ b/backend/src/routes/posts.js @@ -27,6 +27,7 @@ import { import { deletePostImage, openPostImage, postImageExists, storePostImage } from '../lib/postImages.js'; import { attachMyVotes, deleteVotesForPost } from '../lib/postVotes.js'; // [Sprint 5 · M7] US-52 import { deleteOpenReportsForPost } from '../lib/postReports.js'; // [Sprint 6 · M6] US-55 +import { deleteCommentsForPost } from '../lib/postComments.js'; // [Sprint 7 · M3] /* * [Sprint 5 · M6] Public posts (US-50 Create a public post, US-51 Edit or delete my post; @@ -56,6 +57,7 @@ import { deleteOpenReportsForPost } from '../lib/postReports.js'; // [Sprint 6 * Each post: see postView() in lib/postRules.js, plus myVote (1, -1 or 0) for the logged-in user. * [Sprint 5 · M7] Voting (US-52) lives in routes/postVotes.js: PUT/DELETE /api/posts/:postId/vote. * [Sprint 6 · M6] Reporting (US-55) lives in routes/postReports.js: GET/POST /api/posts/:postId/report. + * [Sprint 7 · M3] Comments and replies live in routes/postComments.js: /api/posts/:postId/comments. */ const router = Router(); @@ -296,6 +298,8 @@ router.delete('/:postId', async (req, res, next) => { await deleteVotesForPost(removed._id); // [Sprint 6 · M6] US-55: a deleted post has nothing left to review, so its open reports leave the moderator queue. await deleteOpenReportsForPost(removed._id); + // [Sprint 7 · M3] its comments and replies go with it. + await deleteCommentsForPost(removed._id); return res.json({ postId: String(removed._id), message: POST_DELETED_MESSAGE }); } catch (error) { diff --git a/backend/src/seed/seedData.js b/backend/src/seed/seedData.js index fbd7477..fefb2dd 100644 --- a/backend/src/seed/seedData.js +++ b/backend/src/seed/seedData.js @@ -29,6 +29,7 @@ import PostVote from '../models/PostVote.js'; import PostVoteLog from '../models/PostVoteLog.js'; import PostCreateLog from '../models/PostCreateLog.js'; import PostReport from '../models/PostReport.js'; +import PostComment from '../models/PostComment.js'; // [Sprint 7 · M3] import Session from '../models/Session.js'; import PasswordResetToken from '../models/PasswordResetToken.js'; // [Sprint 6 · M1] US-04 import ModerationAction from '../models/ModerationAction.js'; // [Sprint 6 · M7] US-56 @@ -36,6 +37,7 @@ import { deleteFileBytes } from '../lib/projectFiles.js'; import { deletePostImage } from '../lib/postImages.js'; import { removeAvatarFile } from '../lib/avatar.js'; import { recountPostVotes } from '../lib/postVotes.js'; +import { recountPostComments } from '../lib/postComments.js'; // [Sprint 7 · M3] import { ensureDefaultChannel } from '../lib/channels.js'; import { logActivity, quote } from '../lib/activity.js'; import { domainTags } from '../lib/projectSetup.js'; @@ -56,7 +58,8 @@ import { PLATFORM_ROLE_ADMIN, PLATFORM_ROLE_USER, platformRoleLabel } from '../l * projects (tasks, milestones, channels, messages, activity, decisions, docs, task comments, files * and their stored bytes, invitations, join requests, notifications, GitHub connection records), * plus what the seed accounts themselves created anywhere (posts with their images, votes, reports, - * follows, direct messages, sessions, password reset links, profile photos), then seeds again. Real users and their + * comments and replies [Sprint 7 · M3], follows, direct messages, sessions, password reset links, + * profile photos), then seeds again. Real users and their * projects are kept; a real post's score is recounted if a seed account had voted on it. * - It refuses to run when NODE_ENV=production (scripts/seed.js). * - [Sprint 6 · M8] FR-27: it also creates the first Platform Admin for development and demos, @@ -269,6 +272,22 @@ export async function removeSeedData() { await Promise.all(posts.map((post) => deletePostImage(post.image?.storageId))); await Promise.all([PostVote.deleteMany({ post: { $in: postIds } }), PostReport.deleteMany({ post: { $in: postIds } })]); await Post.deleteMany({ _id: { $in: postIds } }); + // [Sprint 7 · M3] Comments: everything on the seed posts goes with them. + await PostComment.deleteMany({ post: { $in: postIds } }); + // Comments and replies seed accounts wrote on real posts. A seed comment that a real user replied to + // becomes a "Comment deleted" placeholder, so the real reply is kept; then the counts are recounted. + const commentedPostIds = await PostComment.distinct('post', { author: bySeedUsers }); + await PostComment.deleteMany({ author: bySeedUsers, parent: { $ne: null } }); + const seedComments = await PostComment.find({ author: bySeedUsers, parent: null }).select('_id').lean(); + const answered = await PostComment.distinct('parent', { parent: { $in: seedComments.map((c) => c._id) } }); + const answeredIds = new Set(answered.map(String)); + await PostComment.deleteMany({ _id: { $in: seedComments.filter((c) => !answeredIds.has(String(c._id))).map((c) => c._id) } }); + await PostComment.updateMany({ _id: { $in: answered } }, { $set: { deletedAt: new Date(), text: '', editedAt: null } }); + // Placeholders whose only replies were by seed accounts have nothing left to explain. + const placeholders = await PostComment.find({ post: { $in: commentedPostIds }, parent: null, deletedAt: { $ne: null } }).select('_id').lean(); + const stillAnswered = new Set((await PostComment.distinct('parent', { parent: { $in: placeholders.map((c) => c._id) } })).map(String)); + await PostComment.deleteMany({ _id: { $in: placeholders.filter((c) => !stillAnswered.has(String(c._id))).map((c) => c._id) } }); + await Promise.all(commentedPostIds.map((postId) => recountPostComments(postId))); // Votes seed accounts cast on real posts: remove them, then recount those posts so their scores stay right. const votedPostIds = await PostVote.distinct('post', { user: bySeedUsers }); await PostVote.deleteMany({ user: bySeedUsers }); diff --git a/backend/test/commentRules.test.js b/backend/test/commentRules.test.js new file mode 100644 index 0000000..97cb4f9 --- /dev/null +++ b/backend/test/commentRules.test.js @@ -0,0 +1,124 @@ +// [Sprint 7 · M3] Rules for comments and replies on feed posts (no database). +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + COMMENT_TEXT_MAX, + COMMENT_TEXT_REQUIRED_MESSAGE, + COMMENT_TEXT_TOO_LONG_MESSAGE, + COMMENT_TEXT_TYPE_MESSAGE, + COMMENTS_PAGE_DEFAULT, + COMMENTS_PAGE_MAX, + commentExcerpt, + commentView, + deleteMode, + isCommentAuthor, + readCommentLimit, + readCommentText, + replyDedupeKey, + replyNotificationSummary, + threadComments, +} from '../src/lib/commentRules.js'; + +const author = { _id: 'u1', name: 'Asha', username: 'asha', avatarUrl: '' }; +const at = (minute) => new Date(Date.UTC(2026, 10, 20, 10, minute)); +const row = (extra = {}) => ({ + _id: 'c1', + post: 'p1', + parent: null, + author, + text: 'Nice work', + editedAt: null, + deletedAt: null, + createdAt: at(0), + updatedAt: at(0), + ...extra, +}); + +test('comment text: required, trimmed, line breaks kept, at most 500 characters', () => { + assert.deepEqual(readCommentText(' Hello\r\nthere '), { ok: true, value: 'Hello\nthere' }); + assert.deepEqual(readCommentText(undefined), { ok: false, message: COMMENT_TEXT_REQUIRED_MESSAGE }); + assert.deepEqual(readCommentText(' \n '), { ok: false, message: COMMENT_TEXT_REQUIRED_MESSAGE }); + assert.deepEqual(readCommentText(42), { ok: false, message: COMMENT_TEXT_TYPE_MESSAGE }); + assert.deepEqual(readCommentText({ text: 'x' }), { ok: false, message: COMMENT_TEXT_TYPE_MESSAGE }); + assert.equal(readCommentText('a'.repeat(COMMENT_TEXT_MAX)).ok, true); + assert.deepEqual(readCommentText('a'.repeat(COMMENT_TEXT_MAX + 1)), { ok: false, message: COMMENT_TEXT_TOO_LONG_MESSAGE }); + // Invisible control characters do not count and are removed. + assert.deepEqual(readCommentText('\u0007Hi\u0000'), { ok: true, value: 'Hi' }); +}); + +test('page size: default 20, at most 50, junk falls back to the default', () => { + assert.equal(readCommentLimit(undefined), COMMENTS_PAGE_DEFAULT); + assert.equal(readCommentLimit('0'), COMMENTS_PAGE_DEFAULT); + assert.equal(readCommentLimit('abc'), COMMENTS_PAGE_DEFAULT); + assert.equal(readCommentLimit('5'), 5); + assert.equal(readCommentLimit('500'), COMMENTS_PAGE_MAX); +}); + +test('only the author owns a comment (id or populated author)', () => { + assert.equal(isCommentAuthor(row(), 'u1'), true); + assert.equal(isCommentAuthor(row({ author: 'u1' }), 'u1'), true); + assert.equal(isCommentAuthor(row(), 'u2'), false); + assert.equal(isCommentAuthor(row(), null), false); + assert.equal(isCommentAuthor(null, 'u1'), false); +}); + +test('delete: a reply or a comment without replies is removed; a comment with replies becomes a placeholder', () => { + assert.equal(deleteMode(row({ parent: 'c0' }), 0), 'remove'); + assert.equal(deleteMode(row({ parent: 'c0' }), 3), 'remove'); + assert.equal(deleteMode(row(), 0), 'remove'); + assert.equal(deleteMode(row(), 2), 'placeholder'); +}); + +test('API shape of a comment, an edited comment and a deleted placeholder', () => { + const view = commentView(row(), 'u1'); + assert.deepEqual(view, { + _id: 'c1', + post: 'p1', + parent: null, + author: { _id: 'u1', name: 'Asha', username: 'asha', avatarUrl: '' }, + text: 'Nice work', + edited: false, + editedAt: null, + deleted: false, + createdAt: at(0), + updatedAt: at(0), + isMine: true, + }); + assert.equal(commentView(row(), 'u2').isMine, false); + assert.equal(commentView(row({ editedAt: at(5) }), 'u1').edited, true); + assert.equal(commentView(row({ parent: 'c0' })).parent, 'c0'); + + const placeholder = commentView(row({ deletedAt: at(9), text: '' }), 'u1'); + assert.equal(placeholder.deleted, true); + assert.equal(placeholder.text, ''); + assert.equal(placeholder.author, null, 'nothing about the deleted comment is shown'); + assert.equal(placeholder.isMine, false, 'a placeholder cannot be edited or deleted again'); + + // A removed account: no author, the comment itself still reads fine. + assert.equal(commentView(row({ author: null })).author, null); +}); + +test('threadComments puts each reply under its comment, oldest first, with replyCount', () => { + const comments = [row({ _id: 'c1' }), row({ _id: 'c2', createdAt: at(1) })]; + const replies = [ + row({ _id: 'r2', parent: 'c1', createdAt: at(4) }), + row({ _id: 'r1', parent: 'c1', createdAt: at(2) }), + row({ _id: 'r9', parent: 'elsewhere', createdAt: at(3) }), + ]; + const thread = threadComments(comments, replies, 'u1'); + assert.deepEqual(thread.map((c) => c._id), ['c1', 'c2']); + assert.deepEqual(thread[0].replies.map((r) => r._id), ['r1', 'r2']); + assert.equal(thread[0].replyCount, 2); + assert.deepEqual(thread[1].replies, []); + assert.equal(thread[1].replyCount, 0); +}); + +test('reply notification text (optional part)', () => { + assert.equal(replyNotificationSummary({ isReply: false, targetText: 'Our new release' }), 'commented on your post "Our new release"'); + assert.equal(replyNotificationSummary({ isReply: true, targetText: 'Great idea' }), 'replied to your comment "Great idea"'); + assert.equal(replyNotificationSummary({ isReply: true, targetText: '' }), 'replied to your comment'); + const long = commentExcerpt('word '.repeat(40)); + assert.ok(long.length <= 60); + assert.ok(long.endsWith('…')); + assert.equal(replyDedupeKey('abc'), 'post_reply:abc'); +}); diff --git a/backend/test/notifications.test.js b/backend/test/notifications.test.js index dd2187b..4b256ec 100644 --- a/backend/test/notifications.test.js +++ b/backend/test/notifications.test.js @@ -63,8 +63,9 @@ test('Notification types match US-30 (Mention, Assignment, Deadline)', () => { // [Sprint 6 · M7] US-56 and FR-20 add three personal types after the US-30 ones (moderation warning, join outcome). assert.deepEqual(NOTIFICATION_TYPES.slice(0, 3), ['mention', 'assignment', 'deadline']); assert.deepEqual(NOTIFICATION_TYPES.slice(0, 3).map((type) => NOTIFICATION_LABELS[type]), ['Mention', 'Assignment', 'Deadline']); - assert.deepEqual(NOTIFICATION_TYPES.slice(3), ['moderation_warning', 'join_approved', 'join_rejected']); - assert.deepEqual(NOTIFICATION_TYPES.slice(3).map((type) => NOTIFICATION_LABELS[type]), ['Moderation warning', 'Join request approved', 'Join request declined']); + // [Sprint 7 · M3] + post_reply (a comment on your post, or a reply to your comment). + assert.deepEqual(NOTIFICATION_TYPES.slice(3), ['moderation_warning', 'join_approved', 'join_rejected', 'post_reply']); + assert.deepEqual(NOTIFICATION_TYPES.slice(3).map((type) => NOTIFICATION_LABELS[type]), ['Moderation warning', 'Join request approved', 'Join request declined', 'Reply']); }); test('A stored notification is unread by default and has timestamps', async () => { diff --git a/backend/test/postComments.test.js b/backend/test/postComments.test.js new file mode 100644 index 0000000..304f4c0 --- /dev/null +++ b/backend/test/postComments.test.js @@ -0,0 +1,372 @@ +// [Sprint 7 · M3] Comments and replies on feed posts, against a real MongoDB. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import mongoose from 'mongoose'; +import request from 'supertest'; +import { setup, teardown, signup, authed } from './helpers.js'; +import User from '../src/models/User.js'; +import Post from '../src/models/Post.js'; +import PostComment from '../src/models/PostComment.js'; +import PostCreateLog from '../src/models/PostCreateLog.js'; +import Notification from '../src/models/Notification.js'; +import { + COMMENT_CREATED_MESSAGE, + COMMENT_DELETED_MESSAGE, + COMMENT_NOT_AUTHOR_MESSAGE, + COMMENT_NOT_FOUND_MESSAGE, + COMMENT_PARENT_NOT_FOUND_MESSAGE, + COMMENT_REPLY_TO_REPLY_MESSAGE, + COMMENT_TEXT_MAX, + COMMENT_TEXT_REQUIRED_MESSAGE, + COMMENT_TEXT_TOO_LONG_MESSAGE, + COMMENT_UPDATED_MESSAGE, + REPLY_CREATED_MESSAGE, +} from '../src/lib/commentRules.js'; +import { POST_NOT_FOUND_MESSAGE } from '../src/lib/postRules.js'; + +let app; +let asha, ben, cara, moderator; + +const as = (account) => authed(app, account.token); +const url = (postId, commentId = '') => `/api/posts/${postId}/comments${commentId ? `/${commentId}` : ''}`; +const comment = (account, postId, text, parentId) => + as(account).post(url(postId)).send(parentId === undefined ? { text } : { text, parentId }); +const list = (account, postId, query = '') => as(account).get(`${url(postId)}${query}`); +const edit = (account, postId, commentId, text) => as(account).patch(url(postId, commentId)).send({ text }); +const remove = (account, postId, commentId) => as(account).delete(url(postId, commentId)); +const storedCount = async (postId) => (await Post.findById(postId).select('commentCount').lean())?.commentCount; + +const newPost = async (account = asha, text = 'Our first release is out') => { + await PostCreateLog.deleteMany({ user: account.user.id }); // the 10-posts-per-hour limit is tested elsewhere + const res = await as(account).post('/api/posts').send({ text }); + assert.equal(res.status, 201, JSON.stringify(res.body)); + return res.body.post._id; +}; +const added = async (account, postId, text, parentId) => { + const res = await comment(account, postId, text, parentId); + assert.equal(res.status, 201, JSON.stringify(res.body)); + return res.body.comment; +}; + +before(async () => { + ({ app } = await setup()); + [asha, ben, cara, moderator] = await Promise.all(['Asha Author', 'Ben Other', 'Cara Third', 'Mo Moderator'].map((name) => signup(app, name))); + await User.updateOne({ _id: moderator.user.id }, { $set: { platformRole: 'moderator' } }); +}); + +after(teardown); + +// --- Login (NFR-19) ----------------------------------------------------------------------------------- + +test('listing, commenting, editing and deleting comments need a login', async () => { + const id = new mongoose.Types.ObjectId().toString(); + assert.equal((await request(app).get(url(id))).status, 401); + assert.equal((await request(app).post(url(id)).send({ text: 'Hi' })).status, 401); + assert.equal((await request(app).patch(url(id, id)).send({ text: 'Hi' })).status, 401); + assert.equal((await request(app).delete(url(id, id))).status, 401); +}); + +// --- Comment on a post -------------------------------------------------------------------------------- + +test('comment on a post: saved with author and time, counted on the post card', async () => { + const postId = await newPost(); + const res = await comment(ben, postId, ' Congrats on the launch!\r\nWell done. '); + assert.equal(res.status, 201, JSON.stringify(res.body)); + assert.equal(res.body.message, COMMENT_CREATED_MESSAGE); + assert.equal(res.body.commentCount, 1); + const saved = res.body.comment; + assert.equal(saved.text, 'Congrats on the launch!\nWell done.'); + assert.equal(saved.post, postId); + assert.equal(saved.parent, null); + assert.equal(saved.author._id, ben.user.id); + assert.equal(saved.author.name, 'Ben Other'); + assert.equal(saved.isMine, true); + assert.equal(saved.edited, false); + assert.equal(saved.deleted, false); + assert.ok(saved.createdAt); + assert.deepEqual(saved.replies, []); + + // The count is on the post everywhere posts are shown. + assert.equal((await as(cara).get(`/api/posts/${postId}`)).body.post.commentCount, 1); + const feed = await as(cara).get('/api/posts'); + assert.equal(feed.body.posts.find((post) => post._id === postId).commentCount, 1); + const trending = await as(cara).get('/api/posts/trending'); + assert.equal(trending.body.posts.find((post) => post._id === postId).commentCount, 1); + + // Someone else sees it, but not as theirs. + const seen = await list(cara, postId); + assert.equal(seen.status, 200); + assert.equal(seen.body.commentCount, 1); + assert.equal(seen.body.comments.length, 1); + assert.equal(seen.body.comments[0].isMine, false); +}); + +test('a comment that fails validation is refused with a message and nothing is stored', async () => { + const postId = await newPost(); + const cases = [ + [{}, COMMENT_TEXT_REQUIRED_MESSAGE], + [{ text: ' ' }, COMMENT_TEXT_REQUIRED_MESSAGE], + [{ text: 'a'.repeat(COMMENT_TEXT_MAX + 1) }, COMMENT_TEXT_TOO_LONG_MESSAGE], + [{ text: 12 }, 'Comment text must be text.'], + ]; + for (const [body, message] of cases) { + const res = await as(ben).post(url(postId)).send(body); + assert.equal(res.status, 400, JSON.stringify(body)); + assert.equal(res.body.message, message); + } + assert.equal((await comment(ben, postId, 'a'.repeat(COMMENT_TEXT_MAX))).status, 201, 'exactly 500 characters is fine'); + assert.equal(await PostComment.countDocuments({ post: postId }), 1); + assert.equal(await storedCount(postId), 1); +}); + +test('unknown, deleted or invalid posts: 404 / 400', async () => { + const missing = new mongoose.Types.ObjectId().toString(); + assert.equal((await comment(ben, missing, 'Hello')).status, 404); + assert.equal((await comment(ben, missing, 'Hello')).body.message, POST_NOT_FOUND_MESSAGE); + assert.equal((await list(ben, missing)).status, 404); + assert.equal((await comment(ben, 'not-an-id', 'Hello')).status, 400); + assert.equal((await list(ben, 'not-an-id')).status, 400); +}); + +// --- Replies (one level deep) ------------------------------------------------------------------------- + +test('reply to a comment: shown under it, oldest first, counted on the post', async () => { + const postId = await newPost(); + const first = await added(ben, postId, 'First comment'); + const second = await added(cara, postId, 'Second comment'); + const res = await comment(asha, postId, 'Thanks Ben!', first._id); + assert.equal(res.status, 201, JSON.stringify(res.body)); + assert.equal(res.body.message, REPLY_CREATED_MESSAGE); + assert.equal(res.body.comment.parent, first._id); + assert.equal(res.body.commentCount, 3, 'comments and replies both count'); + await added(cara, postId, 'Agreed', first._id); + + const { body } = await list(ben, postId); + assert.deepEqual(body.comments.map((c) => c._id), [first._id, second._id], 'oldest comment first'); + assert.equal(body.comments[0].replyCount, 2); + assert.deepEqual(body.comments[0].replies.map((r) => r.text), ['Thanks Ben!', 'Agreed']); + assert.equal(body.comments[1].replyCount, 0); + assert.equal(body.commentCount, 4); + assert.equal(await storedCount(postId), 4); +}); + +test('replies are one level deep: a reply to a reply is refused', async () => { + const postId = await newPost(); + const top = await added(ben, postId, 'Top'); + const reply = await added(cara, postId, 'Reply', top._id); + const res = await comment(asha, postId, 'Reply to reply', reply._id); + assert.equal(res.status, 400); + assert.equal(res.body.message, COMMENT_REPLY_TO_REPLY_MESSAGE); + assert.equal(res.body.code, 'reply_to_reply'); + assert.equal(await storedCount(postId), 2); +}); + +test('a reply must point at a comment of the SAME post', async () => { + const one = await newPost(); + const other = await newPost(); + const elsewhere = await added(ben, other, 'On the other post'); + const res = await comment(cara, one, 'Sneaky', elsewhere._id); + assert.equal(res.status, 400); + assert.equal(res.body.message, COMMENT_PARENT_NOT_FOUND_MESSAGE); + assert.equal((await comment(cara, one, 'Bad', 'xyz')).status, 400); + assert.equal((await comment(cara, one, 'Bad', { $ne: null })).status, 400, 'an object is not an ID'); + assert.equal(await PostComment.countDocuments({ post: one }), 0); +}); + +// --- Edit your own ------------------------------------------------------------------------------------- + +test('edit your own comment or reply: new text shows with "edited"; same text is not an edit', async () => { + const postId = await newPost(); + const top = await added(ben, postId, 'Typo hree'); + const reply = await added(cara, postId, 'Reply', top._id); + + const same = await edit(ben, postId, top._id, 'Typo hree'); + assert.equal(same.status, 200); + assert.equal(same.body.comment.edited, false); + + const res = await edit(ben, postId, top._id, 'Typo here'); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.message, COMMENT_UPDATED_MESSAGE); + assert.equal(res.body.comment.text, 'Typo here'); + assert.equal(res.body.comment.edited, true); + assert.ok(res.body.comment.editedAt); + + const replyEdit = await edit(cara, postId, reply._id, 'Reply (fixed)'); + assert.equal(replyEdit.status, 200); + assert.equal(replyEdit.body.comment.edited, true); + + const { body } = await list(asha, postId); + assert.equal(body.comments[0].text, 'Typo here'); + assert.equal(body.comments[0].edited, true); + assert.equal(body.comments[0].replies[0].text, 'Reply (fixed)'); + + assert.equal((await edit(ben, postId, top._id, '')).status, 400); + assert.equal((await edit(ben, postId, top._id, 'a'.repeat(COMMENT_TEXT_MAX + 1))).body.message, COMMENT_TEXT_TOO_LONG_MESSAGE); +}); + +test("nobody can edit or delete someone else's comment (403), not even the post's author", async () => { + const postId = await newPost(asha); + const theirs = await added(ben, postId, 'Ben wrote this'); + for (const account of [asha, cara]) { + const editRes = await edit(account, postId, theirs._id, 'Hacked'); + assert.equal(editRes.status, 403); + assert.equal(editRes.body.message, COMMENT_NOT_AUTHOR_MESSAGE); + const delRes = await remove(account, postId, theirs._id); + assert.equal(delRes.status, 403); + } + const stored = await PostComment.findById(theirs._id).lean(); + assert.equal(stored.text, 'Ben wrote this'); + assert.equal(stored.editedAt, null); + assert.equal(await storedCount(postId), 1); +}); + +test('a comment is only found under its own post (404 elsewhere); bad IDs are 400', async () => { + const one = await newPost(); + const other = await newPost(); + const mine = await added(ben, one, 'Mine'); + assert.equal((await edit(ben, other, mine._id, 'Moved?')).status, 404); + assert.equal((await remove(ben, other, mine._id)).status, 404); + assert.equal((await edit(ben, one, 'nope', 'x')).status, 400); + assert.equal((await remove(ben, one, new mongoose.Types.ObjectId().toString())).body.message, COMMENT_NOT_FOUND_MESSAGE); +}); + +// --- Delete your own ----------------------------------------------------------------------------------- + +test('delete your own reply, or a comment without replies: it is removed and the count goes down', async () => { + const postId = await newPost(); + const top = await added(ben, postId, 'Top'); + const reply = await added(cara, postId, 'Reply', top._id); + const lonely = await added(ben, postId, 'No replies'); + assert.equal(await storedCount(postId), 3); + + const res = await remove(cara, postId, reply._id); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.deleted, 'removed'); + assert.equal(res.body.message, COMMENT_DELETED_MESSAGE); + assert.equal(res.body.commentCount, 2); + + const res2 = await remove(ben, postId, lonely._id); + assert.equal(res2.body.deleted, 'removed'); + assert.equal(res2.body.commentCount, 1); + assert.equal(await PostComment.exists({ _id: lonely._id }), null); + + // A second delete click finds nothing. + assert.equal((await remove(ben, postId, lonely._id)).status, 404); + assert.equal(await storedCount(postId), 1); +}); + +test('delete a comment that has replies: it shows as "Comment deleted" and the replies stay', async () => { + const postId = await newPost(); + const top = await added(ben, postId, 'Something I regret'); + const r1 = await added(cara, postId, 'First reply', top._id); + const r2 = await added(asha, postId, 'Second reply', top._id); + + const res = await remove(ben, postId, top._id); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.deleted, 'placeholder'); + assert.equal(res.body.comment.deleted, true); + assert.equal(res.body.commentCount, 2, 'only the two replies still count'); + + const { body } = await list(cara, postId); + assert.equal(body.comments.length, 1); + const shown = body.comments[0]; + assert.equal(shown.deleted, true); + assert.equal(shown.text, '', 'the deleted text is not sent'); + assert.equal(shown.author, null, 'nor who wrote it'); + assert.equal(shown.isMine, false); + assert.deepEqual(shown.replies.map((r) => r.text), ['First reply', 'Second reply']); + + // The placeholder cannot be edited, deleted again, or replied to. + assert.equal((await edit(ben, postId, top._id, 'Back')).status, 404); + assert.equal((await remove(ben, postId, top._id)).status, 404); + const late = await comment(asha, postId, 'Late reply', top._id); + assert.equal(late.status, 400); + assert.equal(late.body.code, 'parent_deleted'); + + // When the last reply goes, the placeholder goes too. + await remove(cara, postId, r1._id); + assert.ok(await PostComment.exists({ _id: top._id }), 'one reply is left, so the placeholder stays'); + const last = await remove(asha, postId, r2._id); + assert.equal(last.body.commentCount, 0); + assert.equal(await PostComment.exists({ _id: top._id }), null); + assert.deepEqual((await list(cara, postId)).body.comments, []); +}); + +test('deleting the post removes its comments and replies', async () => { + const postId = await newPost(asha); + const top = await added(ben, postId, 'Top'); + await added(cara, postId, 'Reply', top._id); + assert.equal((await as(asha).delete(`/api/posts/${postId}`)).status, 200); + assert.equal(await PostComment.countDocuments({ post: postId }), 0); + assert.equal((await list(ben, postId)).status, 404); + assert.equal((await comment(ben, postId, 'Too late')).status, 404); +}); + +test('a moderator removing a reported post removes its comments too', async () => { + const postId = await newPost(asha, 'Buy cheap followers now'); + await added(ben, postId, 'This is spam'); + assert.equal((await as(cara).post(`/api/posts/${postId}/report`).send({ reason: 'spam' })).status, 201); + const res = await as(moderator).post(`/api/moderation/reports/${postId}/remove`).send({}); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(await Post.exists({ _id: postId }), null); + assert.equal(await PostComment.countDocuments({ post: postId }), 0); +}); + +// --- List: pages ----------------------------------------------------------------------------------------- + +test('comments come in pages, oldest first, with nextAfter', async () => { + const postId = await newPost(); + for (const text of ['c1', 'c2', 'c3']) await added(ben, postId, text); + const page1 = await list(cara, postId, '?limit=2'); + assert.deepEqual(page1.body.comments.map((c) => c.text), ['c1', 'c2']); + assert.ok(page1.body.nextAfter); + const page2 = await list(cara, postId, `?limit=2&after=${page1.body.nextAfter}`); + assert.deepEqual(page2.body.comments.map((c) => c.text), ['c3']); + assert.equal(page2.body.nextAfter, null); + assert.equal((await list(cara, postId, '?after=junk')).status, 400); +}); + +// --- Count stays right under load --------------------------------------------------------------------- + +test('ten comments sent at the same moment are all counted', async () => { + const postId = await newPost(); + const results = await Promise.all(Array.from({ length: 10 }, (_, i) => comment(i % 2 ? ben : cara, postId, `Comment ${i}`))); + assert.ok(results.every((res) => res.status === 201)); + assert.equal(await storedCount(postId), 10); + assert.equal(await PostComment.countDocuments({ post: postId }), 10); +}); + +// --- Optional part: "someone replied" notification ------------------------------------------------------ + +test('the post author is told about a new comment, and a comment author about a reply', async () => { + const postId = await newPost(asha, 'Looking for a designer'); + const top = await added(ben, postId, 'I can help with that'); + + const forAsha = await Notification.find({ recipient: asha.user.id, type: 'post_reply', targetId: top._id }).lean(); + assert.equal(forAsha.length, 1); + assert.equal(String(forAsha[0].actor), ben.user.id); + assert.equal(forAsha[0].summary, 'commented on your post "Looking for a designer"'); + assert.equal(forAsha[0].project, null); + assert.equal(forAsha[0].link, '/feed'); + assert.equal(String(forAsha[0].targetId), top._id); + + const reply = await added(cara, postId, 'Me too', top._id); + const forBen = await Notification.find({ recipient: ben.user.id, type: 'post_reply', targetId: reply._id }).lean(); + assert.equal(forBen.length, 1); + assert.equal(forBen[0].summary, 'replied to your comment "I can help with that"'); + + // It shows in the bell (personal type, no project needed). + const bell = await as(ben).get('/api/notifications'); + assert.equal(bell.status, 200); + assert.ok(bell.body.notifications.some((n) => n.type === 'post_reply' && String(n.targetId) === reply._id)); + // The post author is not told about a reply between other people (only the comment's author is). + assert.equal(await Notification.countDocuments({ recipient: asha.user.id, targetId: reply._id }), 0); +}); + +test('no notification for commenting on your own post or replying to yourself', async () => { + const postId = await newPost(asha, 'My own post'); + const mine = await added(asha, postId, 'Adding a detail'); + await added(asha, postId, 'And another', mine._id); + assert.equal(await Notification.countDocuments({ recipient: asha.user.id, type: 'post_reply', targetId: mine._id }), 0); + assert.equal(await Notification.countDocuments({ actor: asha.user.id, recipient: asha.user.id }), 0); +}); diff --git a/backend/test/seed.test.js b/backend/test/seed.test.js index 30dc4d2..d08d1e1 100644 --- a/backend/test/seed.test.js +++ b/backend/test/seed.test.js @@ -29,6 +29,7 @@ import PostReport from '../src/models/PostReport.js'; import Session from '../src/models/Session.js'; import PasswordResetToken from '../src/models/PasswordResetToken.js'; import ModerationAction from '../src/models/ModerationAction.js'; // [Sprint 6 · M7] US-56 +import PostComment from '../src/models/PostComment.js'; // [Sprint 7 · M3] import { storeFileBytes, fileBytesExist } from '../src/lib/projectFiles.js'; import { storePostImage, postImageExists } from '../src/lib/postImages.js'; import { saveAvatar, findAvatar, AVATAR_URL_PREFIX } from '../src/lib/avatar.js'; @@ -188,6 +189,49 @@ test('--reset also removes what testers made with seed accounts, and keeps real assert.ok(await Project.exists({ _id: realProject._id })); }); +// [Sprint 7 · M3] Comments and replies made with seed accounts are removed; a real reply is never lost. +test('--reset removes comments and replies of seed accounts and recounts real posts', async () => { + const raw = (Model, doc) => Model.collection.insertOne(doc); + const aarav = await User.findOne({ email: seedEmail('aarav') }).lean(); + const riya = await User.findOne({ email: seedEmail('riya') }).lean(); + const outsiderId = new mongoose.Types.ObjectId(outsider.user.id); + const live = { editedAt: null, deletedAt: null, createdAt: new Date(), updatedAt: new Date() }; + + const seedPost = await raw(Post, { author: aarav._id, text: 'Seed post', commentCount: 1 }); + const realPost = await raw(Post, { author: outsiderId, text: 'Real post', commentCount: 6 }); + const on = (postId) => ({ post: postId.insertedId }); + + // On the seed post: everything goes with the post, even a real user's comment. + const onSeedPost = await raw(PostComment, { ...on(seedPost), author: outsiderId, parent: null, text: 'Hi', ...live }); + // On the real post: + const seedAlone = await raw(PostComment, { ...on(realPost), author: aarav._id, parent: null, text: 'Seed, no replies', ...live }); + const seedAnswered = await raw(PostComment, { ...on(realPost), author: riya._id, parent: null, text: 'Seed, answered', ...live }); + const realReply = await raw(PostComment, { ...on(realPost), author: outsiderId, parent: seedAnswered.insertedId, text: 'Real reply', ...live }); + const realComment = await raw(PostComment, { ...on(realPost), author: outsiderId, parent: null, text: 'Real comment', ...live }); + const seedReply = await raw(PostComment, { ...on(realPost), author: aarav._id, parent: realComment.insertedId, text: 'Seed reply', ...live }); + const realPlaceholder = await raw(PostComment, { ...on(realPost), author: outsiderId, parent: null, text: '', ...live, deletedAt: new Date() }); + const onlySeedReply = await raw(PostComment, { ...on(realPost), author: riya._id, parent: realPlaceholder.insertedId, text: 'Only reply', ...live }); + + const result = await seedDatabase({ reset: true, password: 'seed-password-123' }); + assert.equal(result.seeded, true); + + const exists = (inserted) => PostComment.exists({ _id: inserted.insertedId }); + assert.equal(await exists(onSeedPost), null, 'comments on the seed post are removed with it'); + assert.equal(await exists(seedAlone), null, 'a seed comment without replies is removed'); + assert.equal(await exists(seedReply), null, 'a seed reply is removed'); + assert.equal(await exists(onlySeedReply), null); + assert.equal(await exists(realPlaceholder), null, 'a placeholder left with no replies is removed'); + assert.ok(await exists(realComment), 'a real comment is kept'); + assert.ok(await exists(realReply), 'a real reply is kept'); + const answered = await PostComment.findById(seedAnswered.insertedId).lean(); + assert.ok(answered?.deletedAt, 'a seed comment a real user replied to becomes "Comment deleted"'); + assert.equal(answered.text, ''); + + const post = await Post.findById(realPost.insertedId).lean(); + assert.equal(post.commentCount, 2, 'the real post counts only the real comment and the real reply'); + assert.equal(await PostComment.countDocuments({ author: { $in: [aarav._id, riya._id] }, deletedAt: null }), 0); +}); + test('the seed password follows the sign-up rule', async () => { await assert.rejects(() => seedDatabase({ reset: true, password: 'short' }), /8 to 128/); }); diff --git a/frontend/src/api.js b/frontend/src/api.js index 4b59a92..40377f9 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -241,6 +241,29 @@ export const postApi = { }, }; +// [Sprint 7 · M3] Comments and replies on a feed post. Contract: backend/src/routes/postComments.js +// list(postId, { after, limit }) -> { comments (oldest first, each with replies + replyCount), nextAfter, commentCount } +// create(postId, { text, parentId }) -> 201 { comment, commentCount, message } (parentId = reply to that comment) +// update(postId, commentId, { text }) -> { comment, message } (author only, 403 otherwise) +// remove(postId, commentId) -> { commentId, deleted: 'removed' | 'placeholder', comment, commentCount, message } +const postCommentPath = (postId, commentId = '') => + `${postPath(postId)}/comments${commentId ? `/${encodeURIComponent(commentId)}` : ''}`; + +export const postCommentApi = { + list: (postId, { after, limit } = {}) => { + const query = new URLSearchParams(); + if (after) query.set('after', after); + if (limit) query.set('limit', String(limit)); + const text = query.toString(); + return api(`${postCommentPath(postId)}${text ? `?${text}` : ''}`); + }, + create: (postId, { text, parentId = null }) => + api(postCommentPath(postId), { method: 'POST', body: JSON.stringify(parentId ? { text, parentId } : { text }) }), + update: (postId, commentId, { text }) => + api(postCommentPath(postId, commentId), { method: 'PATCH', body: JSON.stringify({ text }) }), + remove: (postId, commentId) => api(postCommentPath(postId, commentId), { method: 'DELETE' }), +}; + export const projectApi = { list: () => api('/projects'), create: (payload) => api('/projects', { method: 'POST', body: JSON.stringify(payload) }), diff --git a/frontend/src/comments.js b/frontend/src/comments.js new file mode 100644 index 0000000..29e7d59 --- /dev/null +++ b/frontend/src/comments.js @@ -0,0 +1,88 @@ +/* + * [Sprint 7 · M3] Comments and replies on feed posts: the same rules and messages as the server + * (backend/src/lib/commentRules.js), so the form can refuse bad input before sending it. + */ +import { postTextLength } from './posts'; + +export const COMMENT_TEXT_MAX = 500; +export const COMMENTS_PAGE_SIZE = 20; + +export const COMMENT_TEXT_REQUIRED_MESSAGE = 'Write a comment first.'; +export const COMMENT_TEXT_TOO_LONG_MESSAGE = `Comments must be ${COMMENT_TEXT_MAX} characters or fewer.`; +export const COMMENT_DELETED_PLACEHOLDER = 'Comment deleted'; + +// Counted like the server counts (line endings as one character, ends trimmed). +export const commentTextLength = postTextLength; + +// Returns an error message, or '' when the text can be sent. +export function checkCommentText(text) { + const length = commentTextLength(text); + if (length === 0) return COMMENT_TEXT_REQUIRED_MESSAGE; + if (length > COMMENT_TEXT_MAX) return COMMENT_TEXT_TOO_LONG_MESSAGE; + return ''; +} + +// "No comments", "1 comment", "12 comments". +export function commentCountLabel(count) { + const n = Math.max(0, Number(count) || 0); + if (n === 0) return 'No comments'; + return n === 1 ? '1 comment' : `${n} comments`; +} + +// A readable message for a failed comment request. +export function commentErrorMessage(error, fallback = 'Something went wrong. Please try again.') { + if (!error) return fallback; + if (error.status === 403) return error.message || 'You can only edit or delete your own comments.'; + if (error.status === 404) return error.message || 'Comment not found. It may have been deleted.'; + return error.message || fallback; +} + +/* + * List helpers. `comments` is the shape GET /comments returns: top-level comments, each with replies. + * Each helper returns a new list and never changes the one it was given. + */ +export function addComment(comments, comment) { + if (!comment?._id) return comments; + if (!comment.parent) { + if (comments.some((item) => item._id === comment._id)) return comments; + return [...comments, { replyCount: 0, replies: [], ...comment }]; + } + return comments.map((item) => { + if (item._id !== comment.parent || item.replies?.some((reply) => reply._id === comment._id)) return item; + const replies = [...(item.replies || []), comment]; + return { ...item, replies, replyCount: replies.length }; + }); +} + +export function replaceComment(comments, comment) { + if (!comment?._id) return comments; + return comments.map((item) => { + if (item._id === comment._id) return { ...item, ...comment, replies: item.replies, replyCount: item.replyCount }; + if (!item.replies?.some((reply) => reply._id === comment._id)) return item; + return { ...item, replies: item.replies.map((reply) => (reply._id === comment._id ? { ...reply, ...comment } : reply)) }; + }); +} + +/* + * After a delete. `result` is the server answer ({ commentId, deleted, comment }). + * 'placeholder' -> the comment stays as "Comment deleted" with its replies + * 'removed' -> it leaves the list; a reply leaves its comment, and a "Comment deleted" + * placeholder left with no replies leaves too (as on the server) + */ +export function removeComment(comments, result) { + const id = result?.commentId; + if (!id) return comments; + if (result.deleted === 'placeholder') { + return comments.map((item) => (item._id === id + ? { ...item, ...(result.comment || {}), deleted: true, text: '', author: null, isMine: false, edited: false, replies: item.replies, replyCount: item.replyCount } + : item)); + } + return comments + .filter((item) => item._id !== id) + .map((item) => { + if (!item.replies?.some((reply) => reply._id === id)) return item; + const replies = item.replies.filter((reply) => reply._id !== id); + return { ...item, replies, replyCount: replies.length }; + }) + .filter((item) => !(item.deleted && (item.replies || []).length === 0)); +} diff --git a/frontend/src/comments.test.js b/frontend/src/comments.test.js new file mode 100644 index 0000000..4ee1376 --- /dev/null +++ b/frontend/src/comments.test.js @@ -0,0 +1,80 @@ +// [Sprint 7 · M3] Comment rules and list helpers (no rendering). +import { describe, expect, it } from 'vitest'; +import { + COMMENT_TEXT_MAX, + COMMENT_TEXT_REQUIRED_MESSAGE, + COMMENT_TEXT_TOO_LONG_MESSAGE, + addComment, + checkCommentText, + commentCountLabel, + commentErrorMessage, + removeComment, + replaceComment, +} from './comments'; + +const c = (id, extra = {}) => ({ _id: id, parent: null, text: id, deleted: false, isMine: true, author: { name: 'A' }, replies: [], replyCount: 0, ...extra }); +const r = (id, parent, extra = {}) => ({ _id: id, parent, text: id, deleted: false, isMine: true, author: { name: 'B' }, ...extra }); + +describe('comment rules', () => { + it('checks the text like the server', () => { + expect(checkCommentText('')).toBe(COMMENT_TEXT_REQUIRED_MESSAGE); + expect(checkCommentText(' \r\n ')).toBe(COMMENT_TEXT_REQUIRED_MESSAGE); + expect(checkCommentText('Hi')).toBe(''); + expect(checkCommentText('a'.repeat(COMMENT_TEXT_MAX))).toBe(''); + expect(checkCommentText('a'.repeat(COMMENT_TEXT_MAX + 1))).toBe(COMMENT_TEXT_TOO_LONG_MESSAGE); + }); + + it('labels the count', () => { + expect(commentCountLabel(0)).toBe('No comments'); + expect(commentCountLabel(undefined)).toBe('No comments'); + expect(commentCountLabel(1)).toBe('1 comment'); + expect(commentCountLabel(12)).toBe('12 comments'); + }); + + it('turns failures into readable messages', () => { + expect(commentErrorMessage({ status: 403 })).toBe('You can only edit or delete your own comments.'); + expect(commentErrorMessage({ status: 404, message: 'Gone.' })).toBe('Gone.'); + expect(commentErrorMessage(null, 'Fallback')).toBe('Fallback'); + }); +}); + +describe('comment list helpers', () => { + it('adds a comment at the end and a reply under its comment, once', () => { + let list = [c('c1')]; + list = addComment(list, c('c2')); + list = addComment(list, r('r1', 'c1')); + list = addComment(list, r('r1', 'c1')); + expect(list.map((item) => item._id)).toEqual(['c1', 'c2']); + expect(list[0].replies.map((item) => item._id)).toEqual(['r1']); + expect(list[0].replyCount).toBe(1); + expect(addComment(list, c('c2'))).toBe(list); + }); + + it('replaces an edited comment or reply and keeps the replies', () => { + const list = [c('c1', { replies: [r('r1', 'c1')], replyCount: 1 })]; + const edited = replaceComment(list, { _id: 'c1', text: 'new', edited: true }); + expect(edited[0].text).toBe('new'); + expect(edited[0].replies).toHaveLength(1); + const reply = replaceComment(list, { _id: 'r1', text: 'fixed', edited: true }); + expect(reply[0].replies[0].text).toBe('fixed'); + expect(list[0].replies[0].text).toBe('r1'); + }); + + it('removes a reply, a comment, or keeps a "Comment deleted" placeholder', () => { + const list = [c('c1', { replies: [r('r1', 'c1'), r('r2', 'c1')], replyCount: 2 }), c('c2')]; + const noReply = removeComment(list, { commentId: 'r1', deleted: 'removed' }); + expect(noReply[0].replies.map((item) => item._id)).toEqual(['r2']); + expect(noReply[0].replyCount).toBe(1); + + const noComment = removeComment(list, { commentId: 'c2', deleted: 'removed' }); + expect(noComment.map((item) => item._id)).toEqual(['c1']); + + const placeholder = removeComment(list, { commentId: 'c1', deleted: 'placeholder', comment: { _id: 'c1', deleted: true } }); + expect(placeholder[0]).toMatchObject({ deleted: true, text: '', author: null, isMine: false }); + expect(placeholder[0].replies).toHaveLength(2); + + // The last reply under a placeholder goes: the placeholder goes too. + const lone = [c('c1', { deleted: true, text: '', author: null, replies: [r('r1', 'c1')], replyCount: 1 })]; + expect(removeComment(lone, { commentId: 'r1', deleted: 'removed' })).toEqual([]); + }); +}); diff --git a/frontend/src/components/NotificationBell.jsx b/frontend/src/components/NotificationBell.jsx index a34701d..b45c296 100644 --- a/frontend/src/components/NotificationBell.jsx +++ b/frontend/src/components/NotificationBell.jsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { AtSign, Bell, Clock3, ShieldAlert, UserCheck, UserX } from 'lucide-react'; // [Sprint 6 · M7] + ShieldAlert, UserX +import { AtSign, Bell, Clock3, MessageCircle, ShieldAlert, UserCheck, UserX } from 'lucide-react'; // [Sprint 6 · M7] + ShieldAlert, UserX; [Sprint 7 · M3] + MessageCircle import { notificationApi } from '../api'; import { timeAgo } from './activityDisplay'; @@ -22,6 +22,8 @@ export const NOTIFICATION_KINDS = { moderation_warning: { label: 'Moderation warning', icon: ShieldAlert, tone: 'orange' }, join_approved: { label: 'Join request approved', icon: UserCheck, tone: 'blue' }, join_rejected: { label: 'Join request declined', icon: UserX, tone: '' }, + // [Sprint 7 · M3] someone commented on your post or replied to your comment (opens the feed). + post_reply: { label: 'Reply', icon: MessageCircle, tone: 'purple' }, }; const PAGE_SIZE = 20; diff --git a/frontend/src/components/PostCard.comments.test.jsx b/frontend/src/components/PostCard.comments.test.jsx new file mode 100644 index 0000000..4c91a37 --- /dev/null +++ b/frontend/src/components/PostCard.comments.test.jsx @@ -0,0 +1,87 @@ +// [Sprint 7 · M3] The post card's comment button: count, open/close, and the count reaching the list. +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import PostCard from './PostCard'; + +const NOW = Date.parse('2026-11-20T10:00:00.000Z'); + +const post = (extra = {}) => ({ + _id: 'p1', + author: { _id: 'u1', name: 'Asha Author', username: 'asha', avatarUrl: '' }, + text: 'Our first release is out', + imageUrl: null, + image: null, + edited: false, + editedAt: null, + createdAt: '2026-11-20T09:00:00.000Z', + updatedAt: '2026-11-20T09:00:00.000Z', + upvotes: 0, + downvotes: 0, + score: 0, + commentCount: 3, + isMine: false, + ...extra, +}); + +const commentApi = (count = 3) => ({ + list: vi.fn(() => Promise.resolve({ + comments: [{ + _id: 'c1', post: 'p1', parent: null, author: { _id: 'u2', name: 'Ben Shah', username: 'ben', avatarUrl: '' }, + text: 'Congrats!', edited: false, editedAt: null, deleted: false, createdAt: '2026-11-20T09:30:00.000Z', isMine: false, replies: [], replyCount: 0, + }], + nextAfter: null, + commentCount: count, + })), + create: vi.fn((postId, { text }) => Promise.resolve({ + comment: { _id: 'c9', post: 'p1', parent: null, author: { _id: 'u3', name: 'Me', username: 'me', avatarUrl: '' }, text, edited: false, deleted: false, createdAt: '2026-11-20T10:00:00.000Z', isMine: true }, + commentCount: count + 1, + message: 'Your comment was added.', + })), + update: vi.fn(), + remove: vi.fn(), +}); + +describe('PostCard · comments (Sprint 7 M3)', () => { + it('shows the comment count; comments load only when opened', async () => { + const api = commentApi(); + render(); + const toggle = screen.getByRole('button', { name: '3 comments' }); + expect(toggle.getAttribute('aria-expanded')).toBe('false'); + expect(api.list).not.toHaveBeenCalled(); + + fireEvent.click(toggle); + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(await screen.findByText('Congrats!')).toBeTruthy(); + expect(api.list).toHaveBeenCalledWith('p1', { limit: 20 }); + + fireEvent.click(toggle); + expect(screen.queryByText('Congrats!')).toBeNull(); + }); + + it('a post with no comments (or from before Sprint 7) shows "Add a comment"', () => { + render(); + expect(screen.getByRole('button', { name: 'Add a comment' })).toBeTruthy(); + }); + + it('a new comment updates the button and reaches the list through onUpdated', async () => { + const api = commentApi(); + const onUpdated = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: '3 comments' })); + await screen.findByText('Congrats!'); + + fireEvent.change(screen.getByLabelText('Write a comment'), { target: { value: 'Nice one' } }); + fireEvent.click(screen.getByRole('button', { name: 'Comment' })); + expect(await screen.findByText('Nice one')).toBeTruthy(); + expect(screen.getByRole('button', { name: '4 comments' })).toBeTruthy(); + await waitFor(() => expect(onUpdated).toHaveBeenCalledWith(expect.objectContaining({ _id: 'p1', commentCount: 4, text: 'Our first release is out' }))); + }); + + it('opening does not call onUpdated when the count has not changed', async () => { + const onUpdated = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: '3 comments' })); + await screen.findByText('Congrats!'); + expect(onUpdated).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/components/PostCard.jsx b/frontend/src/components/PostCard.jsx index 7759419..b20bc20 100644 --- a/frontend/src/components/PostCard.jsx +++ b/frontend/src/components/PostCard.jsx @@ -1,13 +1,15 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { Link, useInRouterContext } from 'react-router-dom'; // [Sprint 5 · M8] -import { Flag, Pencil, Trash2 } from 'lucide-react'; -import { assetUrl, postApi } from '../api'; +import { Flag, MessageCircle, Pencil, Trash2 } from 'lucide-react'; +import { assetUrl, postApi, postCommentApi } from '../api'; import { Avatar, initialsOf } from './ui'; import ConfirmDialog from './ConfirmDialog'; import PostVotes from './PostVotes'; // [Sprint 5 · M7] US-52 import ReportPostDialog from './ReportPostDialog'; // [Sprint 6 · M6] US-55 import { POST_TEXT_MAX, checkPostText, postErrorMessage, postTextLength, postTimeAgo } from '../posts'; import { REPORT_CREATED_MESSAGE } from '../reports'; // [Sprint 6 · M6] US-55 +import PostComments from './PostComments'; // [Sprint 7 · M3] +import { commentCountLabel } from '../comments'; // [Sprint 7 · M3] /* * [Sprint 5 · M6] One public post, with US-51 Edit or delete my post. @@ -25,8 +27,13 @@ import { REPORT_CREATED_MESSAGE } from '../reports'; // [Sprint 6 · M6] US-55 * pick a reason and send it to the moderators. After sending, the card says so; reporting the same * post again says "You have already reported this post." Your own posts have Edit/Delete instead. * - * Props: post (API shape, see api.js postApi), api, onUpdated(post) (also called after a vote), - * onDeleted(postId), now (tests). + * [Sprint 7 · M3] Under the post a "N comments" button opens the comments (PostComments): comment, reply + * one level deep, edit or delete your own. The comments load only when opened, and the button keeps the + * post's comment count up to date (it also reaches the list through onUpdated). + * + * Props: post (API shape, see api.js postApi), api, onUpdated(post) (also called after a vote or a comment), + * onDeleted(postId), now (tests), commentApi (postCommentApi, swapped in tests), + * commentsOpen (start with the comments open). */ // [Sprint 5 · M8] A link to /people/:username. Uses the router when there is one (the app), and a @@ -39,7 +46,7 @@ export function ProfileLink({ username, className, children, ...rest }) { ? {children} : {children}; } -export default function PostCard({ post, api = postApi, onUpdated, onDeleted, now }) { +export default function PostCard({ post, api = postApi, onUpdated, onDeleted, now, commentApi = postCommentApi, commentsOpen = false }) { const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(post.text); const [saving, setSaving] = useState(false); @@ -51,6 +58,16 @@ export default function PostCard({ post, api = postApi, onUpdated, onDeleted, no const [reporting, setReporting] = useState(false); const [reported, setReported] = useState(false); const [reportNotice, setReportNotice] = useState(''); + // [Sprint 7 · M3] comments: closed until asked for; the count follows every change made here. + const [showComments, setShowComments] = useState(commentsOpen); + const [countHere, setCountHere] = useState(null); + useEffect(() => { setCountHere(null); }, [post.commentCount]); + const commentCount = countHere ?? Math.max(0, post.commentCount || 0); + const commentsChanged = (count) => { + if (count === commentCount) return; + setCountHere(count); + onUpdated?.({ ...post, commentCount: count }); + }; const author = post.author || { name: 'Deleted user', username: '' }; const length = postTextLength(draft); @@ -174,6 +191,25 @@ export default function PostCard({ post, api = postApi, onUpdated, onDeleted, no + {/* [Sprint 7 · M3] comments and replies */} +
+ +
+ {showComments && ( +
+ +
+ )} + PostComments has no import cycle. +function ProfileLink({ username, className, children, ...rest }) { + const inRouter = useInRouterContext(); + if (!username) return {children}; + const to = `/people/${encodeURIComponent(username)}`; + return inRouter + ? {children} + : {children}; +} + +// The box used for a new comment, a reply and an edit. +function CommentForm({ label, submitLabel, initial = '', busyLabel = 'Saving…', onSubmit, onCancel, autoFocus = false }) { + const [text, setText] = useState(initial); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const length = commentTextLength(text); + const over = length > COMMENT_TEXT_MAX; + + const submit = async (event) => { + event.preventDefault(); + if (busy) return; + const problem = checkCommentText(text); + if (problem) { setError(problem); return; } + setBusy(true); + setError(''); + try { + const ok = await onSubmit(text); + if (ok !== false) setText(''); + } catch (failure) { + setError(commentErrorMessage(failure, 'It could not be saved. Please try again.')); + } finally { + setBusy(false); + } + }; + + return ( +
+