Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 2 additions & 0 deletions backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
171 changes: 171 additions & 0 deletions backend/src/lib/commentRules.js
Original file line number Diff line number Diff line change
@@ -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 "<actor name> <summary>" (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.
* ---------------------------------------------------------------------------
*/
4 changes: 3 additions & 1 deletion backend/src/lib/moderation.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion backend/src/lib/notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
90 changes: 90 additions & 0 deletions backend/src/lib/postComments.js
Original file line number Diff line number Diff line change
@@ -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.
* ---------------------------------------------------------------------------
*/
4 changes: 3 additions & 1 deletion backend/src/lib/postRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -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().
*/
Expand Down Expand Up @@ -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),
};
}
Expand Down
6 changes: 4 additions & 2 deletions backend/src/models/Notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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).
Expand Down
Loading
Loading