Can mark a comment as the answer, some layout changes

This commit is contained in:
jackiettran
2025-11-11 18:23:11 -05:00
parent 825389228d
commit b045fbeb01
11 changed files with 379 additions and 323 deletions

View File

@@ -29,7 +29,7 @@ const ForumPost = sequelize.define('ForumPost', {
defaultValue: 'general_discussion' defaultValue: 'general_discussion'
}, },
status: { status: {
type: DataTypes.ENUM('open', 'solved', 'closed'), type: DataTypes.ENUM('open', 'answered', 'closed'),
defaultValue: 'open' defaultValue: 'open'
}, },
viewCount: { viewCount: {
@@ -43,6 +43,14 @@ const ForumPost = sequelize.define('ForumPost', {
isPinned: { isPinned: {
type: DataTypes.BOOLEAN, type: DataTypes.BOOLEAN,
defaultValue: false defaultValue: false
},
acceptedAnswerId: {
type: DataTypes.UUID,
allowNull: true,
references: {
model: 'ForumComments',
key: 'id'
}
} }
}); });

View File

@@ -156,9 +156,11 @@ router.get('/posts/:id', async (req, res) => {
as: 'author', as: 'author',
attributes: ['id', 'username', 'firstName', 'lastName'] attributes: ['id', 'username', 'firstName', 'lastName']
} }
], ]
order: [['createdAt', 'ASC']]
} }
],
order: [
[{ model: ForumComment, as: 'comments' }, 'createdAt', 'ASC']
] ]
}); });
@@ -370,7 +372,7 @@ router.patch('/posts/:id/status', authenticateToken, async (req, res) => {
return res.status(403).json({ error: 'Only the author can update post status' }); return res.status(403).json({ error: 'Only the author can update post status' });
} }
if (!['open', 'solved', 'closed'].includes(status)) { if (!['open', 'answered', 'closed'].includes(status)) {
return res.status(400).json({ error: 'Invalid status value' }); return res.status(400).json({ error: 'Invalid status value' });
} }
@@ -411,6 +413,82 @@ router.patch('/posts/:id/status', authenticateToken, async (req, res) => {
} }
}); });
// PATCH /api/forum/posts/:id/accept-answer - Mark/unmark comment as accepted answer
router.patch('/posts/:id/accept-answer', authenticateToken, async (req, res) => {
try {
const { commentId } = req.body;
const post = await ForumPost.findByPk(req.params.id);
if (!post) {
return res.status(404).json({ error: 'Post not found' });
}
if (post.authorId !== req.user.id) {
return res.status(403).json({ error: 'Only the post author can mark answers' });
}
// If commentId is provided, validate it
if (commentId) {
const comment = await ForumComment.findByPk(commentId);
if (!comment) {
return res.status(404).json({ error: 'Comment not found' });
}
if (comment.postId !== post.id) {
return res.status(400).json({ error: 'Comment does not belong to this post' });
}
if (comment.isDeleted) {
return res.status(400).json({ error: 'Cannot mark deleted comment as answer' });
}
if (comment.parentCommentId) {
return res.status(400).json({ error: 'Only top-level comments can be marked as answers' });
}
}
// Update the post with accepted answer
await post.update({
acceptedAnswerId: commentId || null,
status: commentId ? 'answered' : 'open'
});
const updatedPost = await ForumPost.findByPk(post.id, {
include: [
{
model: User,
as: 'author',
attributes: ['id', 'username', 'firstName', 'lastName']
},
{
model: PostTag,
as: 'tags',
attributes: ['tagName']
}
]
});
const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Answer marked/unmarked", {
postId: req.params.id,
commentId: commentId || 'unmarked',
authorId: req.user.id
});
res.json(updatedPost);
} catch (error) {
const reqLogger = logger.withRequestId(req.id);
reqLogger.error("Mark answer failed", {
error: error.message,
stack: error.stack,
postId: req.params.id,
authorId: req.user.id
});
res.status(500).json({ error: error.message });
}
});
// POST /api/forum/posts/:id/comments - Add comment/reply // POST /api/forum/posts/:id/comments - Add comment/reply
router.post('/posts/:id/comments', authenticateToken, async (req, res) => { router.post('/posts/:id/comments', authenticateToken, async (req, res) => {
try { try {

View File

@@ -1,13 +1,16 @@
import React, { useState } from 'react'; import React, { useState } from "react";
import { ForumComment } from '../types'; import { ForumComment } from "../types";
import CommentForm from './CommentForm'; import CommentForm from "./CommentForm";
interface CommentThreadProps { interface CommentThreadProps {
comment: ForumComment; comment: ForumComment;
onReply: (commentId: string, content: string) => Promise<void>; onReply: (commentId: string, content: string) => Promise<void>;
onEdit?: (commentId: string, content: string) => Promise<void>; onEdit?: (commentId: string, content: string) => Promise<void>;
onDelete?: (commentId: string) => Promise<void>; onDelete?: (commentId: string) => Promise<void>;
onMarkAsAnswer?: (commentId: string) => Promise<void>;
currentUserId?: string; currentUserId?: string;
isPostAuthor?: boolean;
acceptedAnswerId?: string;
depth?: number; depth?: number;
} }
@@ -16,7 +19,10 @@ const CommentThread: React.FC<CommentThreadProps> = ({
onReply, onReply,
onEdit, onEdit,
onDelete, onDelete,
onMarkAsAnswer,
currentUserId, currentUserId,
isPostAuthor = false,
acceptedAnswerId,
depth = 0, depth = 0,
}) => { }) => {
const [showReplyForm, setShowReplyForm] = useState(false); const [showReplyForm, setShowReplyForm] = useState(false);
@@ -33,7 +39,7 @@ const CommentThread: React.FC<CommentThreadProps> = ({
const diffDays = Math.floor(diffHours / 24); const diffDays = Math.floor(diffHours / 24);
if (diffMinutes < 1) { if (diffMinutes < 1) {
return 'Just now'; return "Just now";
} else if (diffMinutes < 60) { } else if (diffMinutes < 60) {
return `${diffMinutes}m ago`; return `${diffMinutes}m ago`;
} else if (diffHours < 24) { } else if (diffHours < 24) {
@@ -60,7 +66,10 @@ const CommentThread: React.FC<CommentThreadProps> = ({
}; };
const handleDelete = async () => { const handleDelete = async () => {
if (onDelete && window.confirm('Are you sure you want to delete this comment?')) { if (
onDelete &&
window.confirm("Are you sure you want to delete this comment?")
) {
await onDelete(comment.id); await onDelete(comment.id);
} }
}; };
@@ -68,15 +77,22 @@ const CommentThread: React.FC<CommentThreadProps> = ({
const isAuthor = currentUserId === comment.authorId; const isAuthor = currentUserId === comment.authorId;
const maxDepth = 5; const maxDepth = 5;
const canNest = depth < maxDepth; const canNest = depth < maxDepth;
const isAcceptedAnswer = acceptedAnswerId === comment.id;
const canMarkAsAnswer =
isPostAuthor && depth === 0 && onMarkAsAnswer && !comment.isDeleted;
const handleMarkAsAnswer = async () => {
if (onMarkAsAnswer) {
await onMarkAsAnswer(comment.id);
}
};
if (comment.isDeleted) { if (comment.isDeleted) {
return ( return (
<div className={`comment-deleted ${depth > 0 ? 'ms-4' : ''} mb-3`}> <div className={`comment-deleted ${depth > 0 ? "ms-4" : ""} mb-3`}>
<div className="card bg-light"> <div className="card bg-light">
<div className="card-body py-2"> <div className="card-body py-2">
<small className="text-muted fst-italic"> <small className="text-muted fst-italic">[Comment deleted]</small>
[Comment deleted]
</small>
</div> </div>
</div> </div>
{comment.replies && comment.replies.length > 0 && ( {comment.replies && comment.replies.length > 0 && (
@@ -88,7 +104,10 @@ const CommentThread: React.FC<CommentThreadProps> = ({
onReply={onReply} onReply={onReply}
onEdit={onEdit} onEdit={onEdit}
onDelete={onDelete} onDelete={onDelete}
onMarkAsAnswer={onMarkAsAnswer}
currentUserId={currentUserId} currentUserId={currentUserId}
isPostAuthor={isPostAuthor}
acceptedAnswerId={acceptedAnswerId}
depth={depth + 1} depth={depth + 1}
/> />
))} ))}
@@ -99,22 +118,33 @@ const CommentThread: React.FC<CommentThreadProps> = ({
} }
return ( return (
<div className={`comment ${depth > 0 ? 'ms-4' : ''} mb-3`}> <div className={`comment ${depth > 0 ? "ms-4" : ""} mb-3`}>
<div className="card"> <div className={`card ${isAcceptedAnswer ? "border-success" : ""}`}>
<div className="card-body"> <div className="card-body">
{isAcceptedAnswer && (
<div className="mb-2">
<span className="badge bg-success">
<i className="bi bi-check-circle-fill me-1"></i>
Answer
</span>
</div>
)}
<div className="d-flex justify-content-between align-items-start mb-2"> <div className="d-flex justify-content-between align-items-start mb-2">
<div className="d-flex align-items-center"> <div className="d-flex align-items-center">
<div className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" <div
style={{ width: '32px', height: '32px', fontSize: '14px' }}> className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2"
{comment.author?.firstName?.charAt(0) || '?'} style={{ width: "32px", height: "32px", fontSize: "14px" }}
>
{comment.author?.firstName?.charAt(0) || "?"}
</div> </div>
<div> <div>
<strong className="d-block"> <strong className="d-block">
{comment.author?.firstName || 'Unknown'} {comment.author?.lastName || ''} {comment.author?.firstName || "Unknown"}{" "}
{comment.author?.lastName || ""}
</strong> </strong>
<small className="text-muted"> <small className="text-muted">
{formatDate(comment.createdAt)} {formatDate(comment.createdAt)}
{comment.updatedAt !== comment.createdAt && ' (edited)'} {comment.updatedAt !== comment.createdAt && " (edited)"}
</small> </small>
</div> </div>
</div> </div>
@@ -123,7 +153,9 @@ const CommentThread: React.FC<CommentThreadProps> = ({
className="btn btn-sm btn-link text-decoration-none" className="btn btn-sm btn-link text-decoration-none"
onClick={() => setIsCollapsed(!isCollapsed)} onClick={() => setIsCollapsed(!isCollapsed)}
> >
<i className={`bi bi-chevron-${isCollapsed ? 'down' : 'up'}`}></i> <i
className={`bi bi-chevron-${isCollapsed ? "down" : "up"}`}
></i>
</button> </button>
)} )}
</div> </div>
@@ -156,7 +188,7 @@ const CommentThread: React.FC<CommentThreadProps> = ({
</div> </div>
</div> </div>
) : ( ) : (
<p className="card-text mb-2" style={{ whiteSpace: 'pre-wrap' }}> <p className="card-text mb-2" style={{ whiteSpace: "pre-wrap" }}>
{comment.content} {comment.content}
</p> </p>
)} )}
@@ -171,6 +203,23 @@ const CommentThread: React.FC<CommentThreadProps> = ({
Reply Reply
</button> </button>
)} )}
{canMarkAsAnswer && !isEditing && (
<button
className={`btn btn-sm btn-link text-decoration-none p-0 ${
isAcceptedAnswer ? "text-success" : "text-success"
}`}
onClick={handleMarkAsAnswer}
>
<i
className={`bi ${
isAcceptedAnswer
? "bi-check-circle-fill"
: "bi-check-circle"
} me-1`}
></i>
{isAcceptedAnswer ? "Unmark Answer" : "Mark as Answer"}
</button>
)}
{isAuthor && onEdit && !isEditing && ( {isAuthor && onEdit && !isEditing && (
<button <button
className="btn btn-sm btn-link text-decoration-none p-0" className="btn btn-sm btn-link text-decoration-none p-0"
@@ -214,7 +263,10 @@ const CommentThread: React.FC<CommentThreadProps> = ({
onReply={onReply} onReply={onReply}
onEdit={onEdit} onEdit={onEdit}
onDelete={onDelete} onDelete={onDelete}
onMarkAsAnswer={onMarkAsAnswer}
currentUserId={currentUserId} currentUserId={currentUserId}
isPostAuthor={isPostAuthor}
acceptedAnswerId={acceptedAnswerId}
depth={depth + 1} depth={depth + 1}
/> />
))} ))}

View File

@@ -1,115 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { ForumPost } from '../types';
import CategoryBadge from './CategoryBadge';
import PostStatusBadge from './PostStatusBadge';
interface ForumPostCardProps {
post: ForumPost;
showActions?: boolean;
}
const ForumPostCard: React.FC<ForumPostCardProps> = ({ post, showActions = true }) => {
const formatDate = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffDays = Math.floor(diffHours / 24);
if (diffHours < 1) {
return 'Just now';
} else if (diffHours < 24) {
return `${diffHours}h ago`;
} else if (diffDays < 7) {
return `${diffDays}d ago`;
} else {
return date.toLocaleDateString();
}
};
// Strip HTML tags for preview
const getTextPreview = (html: string, maxLength: number = 150) => {
const text = html.replace(/<[^>]*>/g, '');
return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
};
return (
<div className="card h-100 shadow-sm hover-shadow">
<div className="card-body">
{post.isPinned && (
<div className="mb-2">
<span className="badge bg-danger">
<i className="bi bi-pin-angle-fill me-1"></i>
Pinned
</span>
</div>
)}
<div className="d-flex justify-content-between align-items-start mb-2">
<h5 className="card-title text-truncate flex-grow-1 me-2">{post.title}</h5>
<PostStatusBadge status={post.status} />
</div>
<div className="mb-2">
<CategoryBadge category={post.category} />
</div>
<p className="card-text text-muted small mb-2">
{getTextPreview(post.content)}
</p>
{post.tags && post.tags.length > 0 && (
<div className="mb-2">
{post.tags.slice(0, 3).map((tag) => (
<span key={tag.id} className="badge bg-light text-dark me-1 mb-1">
#{tag.tagName}
</span>
))}
{post.tags.length > 3 && (
<span className="badge bg-light text-dark">
+{post.tags.length - 3}
</span>
)}
</div>
)}
<div className="mb-2">
<small className="text-muted">
<i className="bi bi-person me-1"></i>
{post.author?.firstName || 'Unknown'} {post.author?.lastName || ''}
</small>
</div>
<div className="d-flex justify-content-between align-items-center">
<div className="d-flex gap-3">
<small className="text-muted">
<i className="bi bi-chat me-1"></i>
{post.commentCount || 0}
</small>
<small className="text-muted">
<i className="bi bi-eye me-1"></i>
{post.viewCount || 0}
</small>
</div>
<small className="text-muted">
{formatDate(post.updatedAt)}
</small>
</div>
{showActions && (
<div className="d-grid gap-2 mt-3">
<Link
to={`/forum/${post.id}`}
className="btn btn-outline-primary btn-sm"
>
View Post
</Link>
</div>
)}
</div>
</div>
);
};
export default ForumPostCard;

View File

@@ -0,0 +1,111 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { ForumPost } from '../types';
import CategoryBadge from './CategoryBadge';
import PostStatusBadge from './PostStatusBadge';
interface ForumPostListItemProps {
post: ForumPost;
}
const ForumPostListItem: React.FC<ForumPostListItemProps> = ({ post }) => {
const formatDate = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffHours = Math.floor(diffMinutes / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffMinutes < 1) {
return 'Just now';
} else if (diffMinutes < 60) {
return `${diffMinutes}m ago`;
} else if (diffHours < 24) {
return `${diffHours}h ago`;
} else if (diffDays < 7) {
return `${diffDays}d ago`;
} else {
return date.toLocaleDateString();
}
};
// Strip HTML tags for preview
const getTextPreview = (html: string, maxLength: number = 100) => {
const text = html.replace(/<[^>]*>/g, '');
return text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;
};
return (
<div className="list-group-item list-group-item-action p-3">
<Link to={`/forum/${post.id}`} className="text-decoration-none d-block">
<div className="row align-items-center">
{/* Main content - 60% */}
<div className="col-md-7">
<div className="d-flex align-items-center gap-2 mb-1">
{post.isPinned && (
<span className="badge bg-danger badge-sm">
<i className="bi bi-pin-angle-fill"></i>
</span>
)}
<CategoryBadge category={post.category} />
<PostStatusBadge status={post.status} />
{post.tags && post.tags.length > 0 && (
<>
{post.tags.slice(0, 2).map((tag) => (
<span key={tag.id} className="badge bg-light text-dark">
#{tag.tagName}
</span>
))}
{post.tags.length > 2 && (
<span className="badge bg-light text-dark">
+{post.tags.length - 2}
</span>
)}
</>
)}
</div>
<h6 className="mb-1 text-dark">
{post.title}
</h6>
<p className="text-muted small mb-0">
{getTextPreview(post.content)}
</p>
</div>
{/* Author - 20% */}
<div className="col-md-3">
<div className="d-flex align-items-center">
<div className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2"
style={{ width: '32px', height: '32px', fontSize: '14px', flexShrink: 0 }}>
{post.author?.firstName?.charAt(0) || '?'}
</div>
<div className="text-truncate">
<small className="text-dark d-block text-truncate">
{post.author?.firstName || 'Unknown'} {post.author?.lastName || ''}
</small>
<small className="text-muted">
{formatDate(post.updatedAt)}
</small>
</div>
</div>
</div>
{/* Stats - 20% */}
<div className="col-md-2 text-end">
<div className="d-flex flex-column align-items-end gap-1">
<small className="text-muted">
<i className="bi bi-chat me-1"></i>
{post.commentCount || 0} {post.commentCount === 1 ? 'reply' : 'replies'}
</small>
</div>
</div>
</div>
</Link>
</div>
);
};
export default ForumPostListItem;

View File

@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
interface PostStatusBadgeProps { interface PostStatusBadgeProps {
status: "open" | "solved" | "closed"; status: "open" | "answered" | "closed";
} }
const PostStatusBadge: React.FC<PostStatusBadgeProps> = ({ status }) => { const PostStatusBadge: React.FC<PostStatusBadgeProps> = ({ status }) => {
@@ -9,8 +9,8 @@ const PostStatusBadge: React.FC<PostStatusBadgeProps> = ({ status }) => {
switch (stat) { switch (stat) {
case 'open': case 'open':
return { label: 'Open', color: 'success', icon: 'bi-circle' }; return { label: 'Open', color: 'success', icon: 'bi-circle' };
case 'solved': case 'answered':
return { label: 'Solved', color: 'info', icon: 'bi-check-circle' }; return { label: 'Answered', color: 'info', icon: 'bi-check-circle' };
case 'closed': case 'closed':
return { label: 'Closed', color: 'secondary', icon: 'bi-x-circle' }; return { label: 'Closed', color: 'secondary', icon: 'bi-x-circle' };
default: default:

View File

@@ -109,6 +109,17 @@ const ForumPostDetail: React.FC = () => {
} }
}; };
const handleMarkAsAnswer = async (commentId: string) => {
try {
// If this comment is already the accepted answer, unmark it
const newCommentId = post?.acceptedAnswerId === commentId ? null : commentId;
await forumAPI.acceptAnswer(id!, newCommentId);
await fetchPost(); // Refresh to get updated post
} catch (err: any) {
alert(err.response?.data?.error || 'Failed to mark answer');
}
};
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
const date = new Date(dateString); const date = new Date(dateString);
return date.toLocaleString(); return date.toLocaleString();
@@ -160,86 +171,47 @@ const ForumPostDetail: React.FC = () => {
{/* Post Content */} {/* Post Content */}
<div className="card mb-4"> <div className="card mb-4">
<div className="card-body"> <div className="card-body">
<div className="d-flex justify-content-between align-items-start mb-3"> {post.isPinned && (
<div className="flex-grow-1"> <span className="badge bg-danger me-2 mb-2">
{post.isPinned && ( <i className="bi bi-pin-angle-fill me-1"></i>
<span className="badge bg-danger me-2"> Pinned
<i className="bi bi-pin-angle-fill me-1"></i> </span>
Pinned
</span>
)}
<h1 className="h3 mb-2">{post.title}</h1>
<div className="d-flex gap-2 mb-2">
<CategoryBadge category={post.category} />
<PostStatusBadge status={post.status} />
</div>
</div>
</div>
{post.tags && post.tags.length > 0 && (
<div className="mb-3">
{post.tags.map((tag) => (
<Link
key={tag.id}
to={`/forum?tag=${tag.tagName}`}
className="badge bg-light text-dark me-1 mb-1 text-decoration-none"
>
#{tag.tagName}
</Link>
))}
</div>
)} )}
<h1 className="h3 mb-2">{post.title}</h1>
<div className="mb-3"> <div className="d-flex gap-2 mb-2 flex-wrap">
<div className="d-flex align-items-center"> <CategoryBadge category={post.category} />
<div className="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" <PostStatusBadge status={post.status} />
style={{ width: '40px', height: '40px' }}> {post.tags && post.tags.length > 0 && (
{post.author?.firstName?.charAt(0) || '?'} <>
</div> {post.tags.map((tag) => (
<div> <Link
<strong> key={tag.id}
{post.author?.firstName || 'Unknown'} {post.author?.lastName || ''} to={`/forum?tag=${tag.tagName}`}
</strong> className="badge bg-light text-dark text-decoration-none"
<br /> >
<small className="text-muted"> #{tag.tagName}
Posted {formatDate(post.createdAt)} </Link>
{post.updatedAt !== post.createdAt && ' (edited)'} ))}
</small> </>
</div> )}
</div>
</div> </div>
<hr /> <div className="text-muted small mb-3">
By <strong>{post.author?.firstName || 'Unknown'} {post.author?.lastName || ''}</strong>
{' • '}
Posted {formatDate(post.createdAt)}
{post.updatedAt !== post.createdAt && ' (edited)'}
{' • '}
{post.commentCount || 0} comments
</div>
<div className="post-content mb-3" style={{ whiteSpace: 'pre-wrap' }}> <div className="post-content mb-3" style={{ whiteSpace: 'pre-wrap' }}>
{post.content} {post.content}
</div> </div>
<div className="d-flex gap-3 text-muted small">
<span>
<i className="bi bi-chat me-1"></i>
{post.commentCount || 0} comments
</span>
<span>
<i className="bi bi-eye me-1"></i>
{post.viewCount || 0} views
</span>
</div>
{isAuthor && ( {isAuthor && (
<> <div className="d-flex gap-2 flex-wrap mb-3">
<hr />
<div className="d-flex gap-2 flex-wrap">
{post.status === 'open' && (
<button
className="btn btn-sm btn-success"
onClick={() => handleStatusChange('solved')}
disabled={actionLoading}
>
<i className="bi bi-check-circle me-1"></i>
Mark as Solved
</button>
)}
{post.status !== 'closed' && ( {post.status !== 'closed' && (
<button <button
className="btn btn-sm btn-secondary" className="btn btn-sm btn-secondary"
@@ -275,120 +247,70 @@ const ForumPostDetail: React.FC = () => {
<i className="bi bi-trash me-1"></i> <i className="bi bi-trash me-1"></i>
Delete Delete
</button> </button>
</div>
</>
)}
</div>
</div>
{/* Comments Section */}
<div className="card">
<div className="card-header">
<h5 className="mb-0">
<i className="bi bi-chat-dots me-2"></i>
Comments ({post.commentCount || 0})
</h5>
</div>
<div className="card-body">
{user ? (
<div className="mb-4">
<h6>Add a comment</h6>
<CommentForm
onSubmit={handleAddComment}
placeholder="Share your thoughts..."
buttonText="Post Comment"
/>
</div>
) : (
<div className="alert alert-info mb-4">
<i className="bi bi-info-circle me-2"></i>
<AuthButton mode="login" className="alert-link" asLink>Log in</AuthButton> to join the discussion.
</div> </div>
)} )}
<hr /> <hr />
{post.comments && post.comments.length > 0 ? ( {/* Comments Section */}
<div className="comments-list"> <div className="mt-4">
{post.comments.map((comment: ForumComment) => ( <h5 className="mb-3">
<CommentThread <i className="bi bi-chat-dots me-2"></i>
key={comment.id} Comments ({post.commentCount || 0})
comment={comment} </h5>
onReply={handleReply}
onEdit={handleEditComment} {post.comments && post.comments.length > 0 ? (
onDelete={handleDeleteComment} <div className="comments-list mb-4">
currentUserId={user?.id} {[...post.comments]
.sort((a, b) => {
// Sort accepted answer to the top
if (a.id === post.acceptedAnswerId) return -1;
if (b.id === post.acceptedAnswerId) return 1;
return 0;
})
.map((comment: ForumComment) => (
<CommentThread
key={comment.id}
comment={comment}
onReply={handleReply}
onEdit={handleEditComment}
onDelete={handleDeleteComment}
onMarkAsAnswer={handleMarkAsAnswer}
currentUserId={user?.id}
isPostAuthor={isAuthor}
acceptedAnswerId={post.acceptedAnswerId}
/>
))}
</div>
) : (
<div className="text-center py-4 text-muted mb-4">
<i className="bi bi-chat display-4 d-block mb-2"></i>
<p>No comments yet. Be the first to comment!</p>
</div>
)}
<hr />
{user ? (
<div>
<h6>Add a comment</h6>
<CommentForm
onSubmit={handleAddComment}
placeholder="Share your thoughts..."
buttonText="Post Comment"
/> />
))} </div>
</div> ) : (
) : ( <div className="alert alert-info">
<div className="text-center py-4 text-muted"> <i className="bi bi-info-circle me-2"></i>
<i className="bi bi-chat display-4 d-block mb-2"></i> <AuthButton mode="login" className="alert-link" asLink>Log in</AuthButton> to join the discussion.
<p>No comments yet. Be the first to comment!</p> </div>
</div>
)}
</div>
</div>
</div>
{/* Sidebar */}
<div className="col-lg-4">
<div className="card mb-3">
<div className="card-header">
<h6 className="mb-0">About this post</h6>
</div>
<div className="card-body">
<div className="mb-2">
<small className="text-muted">Category:</small>
<div>
<CategoryBadge category={post.category} />
</div>
</div>
<div className="mb-2">
<small className="text-muted">Status:</small>
<div>
<PostStatusBadge status={post.status} />
</div>
</div>
<div className="mb-2">
<small className="text-muted">Created:</small>
<div>{formatDate(post.createdAt)}</div>
</div>
<div className="mb-2">
<small className="text-muted">Last updated:</small>
<div>{formatDate(post.updatedAt)}</div>
</div>
<div className="mb-2">
<small className="text-muted">Author:</small>
<div>
<Link to={`/users/${post.authorId}`}>
{post.author?.firstName || 'Unknown'} {post.author?.lastName || ''}
</Link>
</div>
</div>
</div>
</div>
<div className="card">
<div className="card-header">
<h6 className="mb-0">Actions</h6>
</div>
<div className="card-body">
<div className="d-grid gap-2">
<Link to="/forum" className="btn btn-outline-secondary btn-sm">
<i className="bi bi-arrow-left me-2"></i>
Back to Forum
</Link>
{user && (
<Link to="/forum/create" className="btn btn-outline-primary btn-sm">
<i className="bi bi-plus-circle me-2"></i>
Create New Post
</Link>
)} )}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); );

View File

@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { forumAPI } from '../services/api'; import { forumAPI } from '../services/api';
import { ForumPost } from '../types'; import { ForumPost } from '../types';
import ForumPostCard from '../components/ForumPostCard'; import ForumPostListItem from '../components/ForumPostListItem';
import AuthButton from '../components/AuthButton'; import AuthButton from '../components/AuthButton';
const ForumPosts: React.FC = () => { const ForumPosts: React.FC = () => {
@@ -138,7 +138,7 @@ const ForumPosts: React.FC = () => {
> >
<option value="">All Status</option> <option value="">All Status</option>
<option value="open">Open</option> <option value="open">Open</option>
<option value="solved">Solved</option> <option value="answered">Answered</option>
<option value="closed">Closed</option> <option value="closed">Closed</option>
</select> </select>
</div> </div>
@@ -151,7 +151,6 @@ const ForumPosts: React.FC = () => {
> >
<option value="recent">Most Recent</option> <option value="recent">Most Recent</option>
<option value="comments">Most Commented</option> <option value="comments">Most Commented</option>
<option value="views">Most Viewed</option>
</select> </select>
</div> </div>
</div> </div>
@@ -194,11 +193,9 @@ const ForumPosts: React.FC = () => {
</div> </div>
) : ( ) : (
<> <>
<div className="row g-4"> <div className="list-group list-group-flush mb-4">
{posts.map((post) => ( {posts.map((post) => (
<div key={post.id} className="col-md-6 col-lg-4"> <ForumPostListItem key={post.id} post={post} />
<ForumPostCard post={post} />
</div>
))} ))}
</div> </div>

View File

@@ -208,11 +208,11 @@ const MyPosts: React.FC = () => {
{post.status === 'open' && ( {post.status === 'open' && (
<button <button
className="btn btn-sm btn-outline-success" className="btn btn-sm btn-outline-success"
onClick={() => handleStatusChange(post.id, 'solved')} onClick={() => handleStatusChange(post.id, 'answered')}
disabled={actionLoading === post.id} disabled={actionLoading === post.id}
> >
<i className="bi bi-check-circle me-1"></i> <i className="bi bi-check-circle me-1"></i>
Mark Solved Mark Answered
</button> </button>
)} )}

View File

@@ -262,6 +262,8 @@ export const forumAPI = {
deletePost: (id: string) => api.delete(`/forum/posts/${id}`), deletePost: (id: string) => api.delete(`/forum/posts/${id}`),
updatePostStatus: (id: string, status: string) => updatePostStatus: (id: string, status: string) =>
api.patch(`/forum/posts/${id}/status`, { status }), api.patch(`/forum/posts/${id}/status`, { status }),
acceptAnswer: (postId: string, commentId: string | null) =>
api.patch(`/forum/posts/${postId}/accept-answer`, { commentId }),
getMyPosts: () => api.get("/forum/my-posts"), getMyPosts: () => api.get("/forum/my-posts"),
getTags: (params?: any) => api.get("/forum/tags", { params }), getTags: (params?: any) => api.get("/forum/tags", { params }),
createComment: (postId: string, data: any) => createComment: (postId: string, data: any) =>

View File

@@ -261,10 +261,11 @@ export interface ForumPost {
content: string; content: string;
authorId: string; authorId: string;
category: "item_request" | "technical_support" | "community_resources" | "general_discussion"; category: "item_request" | "technical_support" | "community_resources" | "general_discussion";
status: "open" | "solved" | "closed"; status: "open" | "answered" | "closed";
viewCount: number; viewCount: number;
commentCount: number; commentCount: number;
isPinned: boolean; isPinned: boolean;
acceptedAnswerId?: string;
author?: User; author?: User;
tags?: PostTag[]; tags?: PostTag[];
comments?: ForumComment[]; comments?: ForumComment[];