feat: Add bulletin board system

- Add BoardCategory and BoardPost models with multi-language support
- Add bulletin API endpoints (CRUD, notice toggle, pin toggle)
- Add board_enabled setting to control menu visibility
- Create frontend board pages (list, detail, write, edit)
- Create admin board management and category management pages
- Update Header.tsx with conditional Board menu between Inquiry and Contact Us
- Update admin settings with board_enabled toggle
- Add Board menu to admin sidebar

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
AutonetSellCar Deploy
2026-01-10 01:34:41 +09:00
parent 04bec0d2c7
commit e0c1f4540b
17 changed files with 2630 additions and 2 deletions

View File

@@ -0,0 +1,195 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardPost } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';
export default function BoardPostPage() {
const router = useRouter();
const params = useParams();
const postId = parseInt(params.id as string);
const { user, isLoggedIn } = useAuthStore();
const { translate, language } = useTranslate();
const [post, setPost] = useState<BoardPost | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
useEffect(() => {
const fetchPost = async () => {
try {
const data = await boardApi.getPost(postId);
setPost(data);
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to load post');
} finally {
setLoading(false);
}
};
fetchPost();
}, [postId]);
const getCategoryName = (post: BoardPost) => {
if (!post.category) return '-';
if (language === 'en' && post.category.name_en) return post.category.name_en;
if (language === 'mn' && post.category.name_mn) return post.category.name_mn;
if (language === 'ru' && post.category.name_ru) return post.category.name_ru;
return post.category.name;
};
const canEdit = isLoggedIn && post && (user?.id === post.author_id || user?.is_admin);
const handleDelete = async () => {
if (!confirm(translate('Are you sure you want to delete this post?'))) return;
setDeleting(true);
try {
await boardApi.deletePost(postId);
router.push('/board');
} catch (err: any) {
alert(err.response?.data?.detail || 'Failed to delete post');
} finally {
setDeleting(false);
}
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
</div>
);
}
if (error || !post) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<p className="text-red-600 mb-4">{error || 'Post not found'}</p>
<Link href="/board" className="text-blue-600 hover:underline">
{translate('Back to list')}
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-4xl mx-auto px-4 py-8">
{/* Back Button */}
<div className="mb-6">
<Link
href="/board"
className="inline-flex items-center text-gray-600 hover:text-gray-900"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
{translate('Back to list')}
</Link>
</div>
{/* Post */}
<article className="bg-white rounded-lg shadow-sm overflow-hidden">
{/* Header */}
<div className="p-6 border-b border-gray-200">
{/* Notice Badge */}
{post.is_notice && (
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 mb-3">
Notice
</span>
)}
{/* Title */}
<h1 className="text-2xl font-bold text-gray-900 mb-4">
{post.title}
</h1>
{/* Meta */}
<div className="flex flex-wrap items-center gap-4 text-sm text-gray-500">
{/* Category */}
<span className="inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
</svg>
{getCategoryName(post)}
</span>
{/* Author */}
<span className="inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
{post.author?.name || post.author?.email || 'Unknown'}
{post.author?.is_admin && (
<span className="ml-1 px-1.5 py-0.5 text-xs bg-blue-100 text-blue-800 rounded">Admin</span>
)}
</span>
{/* Date */}
<span className="inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
{new Date(post.created_at).toLocaleString()}
</span>
{/* Views */}
<span className="inline-flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
{post.view_count} {translate('views')}
</span>
</div>
</div>
{/* Content */}
<div className="p-6">
<div
className="prose prose-sm max-w-none text-gray-700"
style={{ whiteSpace: 'pre-wrap' }}
>
{post.content}
</div>
</div>
{/* Actions */}
{canEdit && (
<div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end gap-3">
<Link
href={`/board/edit/${post.id}`}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
>
{translate('Edit')}
</Link>
<button
onClick={handleDelete}
disabled={deleting}
className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
>
{deleting ? translate('Deleting...') : translate('Delete')}
</button>
</div>
)}
</article>
{/* Navigation Buttons */}
<div className="mt-6 flex justify-center">
<Link
href="/board"
className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
>
{translate('List')}
</Link>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,260 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardCategory, BoardPost } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';
export default function BoardEditPage() {
const router = useRouter();
const params = useParams();
const postId = parseInt(params.id as string);
const { user, isLoggedIn } = useAuthStore();
const { translate, language } = useTranslate();
const [post, setPost] = useState<BoardPost | null>(null);
const [categories, setCategories] = useState<BoardCategory[]>([]);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [categoryId, setCategoryId] = useState<number | ''>('');
const [isNotice, setIsNotice] = useState(false);
const [isPinned, setIsPinned] = useState(false);
useEffect(() => {
if (!isLoggedIn) {
router.push('/login?redirect=/board');
return;
}
const fetchData = async () => {
try {
const [postData, categoriesRes] = await Promise.all([
boardApi.getPost(postId),
boardApi.getCategories(),
]);
// Check permission
if (postData.author_id !== user?.id && !user?.is_admin) {
router.push('/board');
return;
}
setPost(postData);
setCategories(categoriesRes.categories);
setTitle(postData.title);
setContent(postData.content);
setCategoryId(postData.category_id);
setIsNotice(postData.is_notice);
setIsPinned(postData.is_pinned);
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to load post');
} finally {
setLoading(false);
}
};
fetchData();
}, [isLoggedIn, postId, user, router]);
const getCategoryName = (cat: BoardCategory) => {
if (language === 'en' && cat.name_en) return cat.name_en;
if (language === 'mn' && cat.name_mn) return cat.name_mn;
if (language === 'ru' && cat.name_ru) return cat.name_ru;
return cat.name;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim()) {
setError(translate('Please enter a title'));
return;
}
if (!content.trim()) {
setError(translate('Please enter content'));
return;
}
if (!categoryId) {
setError(translate('Please select a category'));
return;
}
setSubmitting(true);
setError(null);
try {
await boardApi.updatePost(postId, {
title: title.trim(),
content: content.trim(),
category_id: categoryId as number,
is_notice: user?.is_admin ? isNotice : undefined,
is_pinned: user?.is_admin ? isPinned : undefined,
});
router.push(`/board/${postId}`);
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to update post');
} finally {
setSubmitting(false);
}
};
if (!isLoggedIn || loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
</div>
);
}
if (error && !post) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<p className="text-red-600 mb-4">{error}</p>
<Link href="/board" className="text-blue-600 hover:underline">
{translate('Back to list')}
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-4xl mx-auto px-4 py-8">
{/* Back Button */}
<div className="mb-6">
<Link
href={`/board/${postId}`}
className="inline-flex items-center text-gray-600 hover:text-gray-900"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
{translate('Cancel')}
</Link>
</div>
{/* Form */}
<div className="bg-white rounded-lg shadow-sm overflow-hidden">
<div className="p-6 border-b border-gray-200">
<h1 className="text-xl font-bold text-gray-900">
{translate('Edit Post')}
</h1>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-6">
{error && (
<div className="p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
{error}
</div>
)}
{/* Category */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Category')} <span className="text-red-500">*</span>
</label>
<select
value={categoryId}
onChange={(e) => setCategoryId(e.target.value ? parseInt(e.target.value) : '')}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
>
<option value="">{translate('Select a category')}</option>
{categories.map((cat) => (
<option key={cat.id} value={cat.id}>
{getCategoryName(cat)}
</option>
))}
</select>
</div>
{/* Title */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Title')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder={translate('Enter title')}
maxLength={200}
required
/>
</div>
{/* Content */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Content')} <span className="text-red-500">*</span>
</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[300px]"
placeholder={translate('Enter content')}
required
/>
</div>
{/* Admin Options */}
{user?.is_admin && (
<div className="space-y-3 p-4 bg-gray-50 rounded-lg">
<h3 className="text-sm font-medium text-gray-700">{translate('Admin Options')}</h3>
<div className="flex items-center gap-2">
<input
type="checkbox"
id="isNotice"
checked={isNotice}
onChange={(e) => setIsNotice(e.target.checked)}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
<label htmlFor="isNotice" className="text-sm text-gray-700">
{translate('Notice')}
</label>
</div>
<div className="flex items-center gap-2">
<input
type="checkbox"
id="isPinned"
checked={isPinned}
onChange={(e) => setIsPinned(e.target.checked)}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
<label htmlFor="isPinned" className="text-sm text-gray-700">
{translate('Pin to top')}
</label>
</div>
</div>
)}
{/* Submit Buttons */}
<div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
<Link
href={`/board/${postId}`}
className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
>
{translate('Cancel')}
</Link>
<button
type="submit"
disabled={submitting}
className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
>
{submitting ? translate('Saving...') : translate('Save')}
</button>
</div>
</form>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,293 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardPostListItem, BoardCategory, BoardPostListResponse, BoardCategoryListResponse } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';
export default function BoardPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { user, isLoggedIn } = useAuthStore();
const { translate, language } = useTranslate();
const [posts, setPosts] = useState<BoardPostListItem[]>([]);
const [notices, setNotices] = useState<BoardPostListItem[]>([]);
const [categories, setCategories] = useState<BoardCategory[]>([]);
const [total, setTotal] = useState(0);
const [totalPages, setTotalPages] = useState(1);
const [loading, setLoading] = useState(true);
const page = parseInt(searchParams.get('page') || '1');
const categoryId = searchParams.get('category') ? parseInt(searchParams.get('category')!) : undefined;
const search = searchParams.get('search') || '';
const getCategoryName = (cat: BoardCategory) => {
if (language === 'en' && cat.name_en) return cat.name_en;
if (language === 'mn' && cat.name_mn) return cat.name_mn;
if (language === 'ru' && cat.name_ru) return cat.name_ru;
return cat.name;
};
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const [postsRes, categoriesRes] = await Promise.all([
boardApi.getPosts({ page, page_size: 20, category_id: categoryId, search }),
boardApi.getCategories(),
]);
setPosts(postsRes.posts);
setNotices(postsRes.notices);
setTotal(postsRes.total);
setTotalPages(postsRes.total_pages);
setCategories(categoriesRes.categories);
} catch (error) {
console.error('Failed to fetch board data:', error);
} finally {
setLoading(false);
}
};
fetchData();
}, [page, categoryId, search]);
const formatDate = (dateStr: string) => {
const date = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} else if (days < 7) {
return `${days}d ago`;
} else {
return date.toLocaleDateString();
}
};
const handleCategoryChange = (catId: number | undefined) => {
const params = new URLSearchParams();
if (catId) params.set('category', catId.toString());
if (search) params.set('search', search);
router.push(`/board?${params.toString()}`);
};
const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const searchValue = formData.get('search') as string;
const params = new URLSearchParams();
if (categoryId) params.set('category', categoryId.toString());
if (searchValue) params.set('search', searchValue);
router.push(`/board?${params.toString()}`);
};
const renderPostRow = (post: BoardPostListItem, isNotice: boolean = false) => (
<tr
key={post.id}
className={`hover:bg-gray-50 cursor-pointer ${isNotice ? 'bg-amber-50' : ''}`}
onClick={() => router.push(`/board/${post.id}`)}
>
<td className="px-4 py-3 text-center text-sm text-gray-500">
{isNotice ? (
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
Notice
</span>
) : (
post.id
)}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
{post.is_pinned && !isNotice && (
<span className="text-amber-500" title="Pinned">
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path d="M5.5 16a3.5 3.5 0 01-.369-6.98 4 4 0 117.753-1.977A4.5 4.5 0 1113.5 16h-8z" />
</svg>
</span>
)}
<span className={`text-sm ${isNotice ? 'font-semibold text-red-700' : 'text-gray-900'}`}>
{post.title}
</span>
</div>
</td>
<td className="px-4 py-3 text-sm text-gray-500 hidden md:table-cell">
{post.category_name || '-'}
</td>
<td className="px-4 py-3 text-sm text-gray-500 hidden sm:table-cell">
{post.author_name || 'Unknown'}
</td>
<td className="px-4 py-3 text-sm text-gray-500 text-center hidden sm:table-cell">
{post.view_count}
</td>
<td className="px-4 py-3 text-sm text-gray-500 text-right">
{formatDate(post.created_at)}
</td>
</tr>
);
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-6xl mx-auto px-4 py-8">
{/* Header */}
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">
{translate('Board')}
</h1>
{isLoggedIn && (
<Link
href="/board/write"
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
{translate('Write')}
</Link>
)}
</div>
{/* Categories & Search */}
<div className="bg-white rounded-lg shadow-sm p-4 mb-6">
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
{/* Category Tabs */}
<div className="flex flex-wrap gap-2">
<button
onClick={() => handleCategoryChange(undefined)}
className={`px-3 py-1.5 text-sm rounded-full transition-colors ${
!categoryId
? 'bg-blue-600 text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
{translate('All')}
</button>
{categories.map((cat) => (
<button
key={cat.id}
onClick={() => handleCategoryChange(cat.id)}
className={`px-3 py-1.5 text-sm rounded-full transition-colors ${
categoryId === cat.id
? 'bg-blue-600 text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
{getCategoryName(cat)} ({cat.post_count})
</button>
))}
</div>
{/* Search */}
<form onSubmit={handleSearch} className="flex gap-2">
<input
type="text"
name="search"
defaultValue={search}
placeholder={translate('Search...')}
className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
/>
<button
type="submit"
className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</button>
</form>
</div>
</div>
{/* Posts Table */}
<div className="bg-white rounded-lg shadow-sm overflow-hidden">
{loading ? (
<div className="p-8 text-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
</div>
) : notices.length === 0 && posts.length === 0 ? (
<div className="p-8 text-center text-gray-500">
{translate('No posts yet')}
</div>
) : (
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider w-20">
#
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{translate('Title')}
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hidden md:table-cell w-32">
{translate('Category')}
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:table-cell w-32">
{translate('Author')}
</th>
<th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:table-cell w-20">
{translate('Views')}
</th>
<th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider w-28">
{translate('Date')}
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{notices.map((notice) => renderPostRow(notice, true))}
{posts.map((post) => renderPostRow(post, false))}
</tbody>
</table>
)}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="mt-6 flex justify-center">
<nav className="flex items-center gap-1">
<button
onClick={() => {
const params = new URLSearchParams(searchParams.toString());
params.set('page', (page - 1).toString());
router.push(`/board?${params.toString()}`);
}}
disabled={page <= 1}
className="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
Prev
</button>
<span className="px-4 py-2 text-sm text-gray-700">
{page} / {totalPages}
</span>
<button
onClick={() => {
const params = new URLSearchParams(searchParams.toString());
params.set('page', (page + 1).toString());
router.push(`/board?${params.toString()}`);
}}
disabled={page >= totalPages}
className="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
Next
</button>
</nav>
</div>
)}
{/* Login prompt for non-logged in users */}
{!isLoggedIn && (
<div className="mt-6 p-4 bg-blue-50 rounded-lg text-center">
<p className="text-sm text-blue-800">
{translate('Please login to write a post')}.{' '}
<Link href="/login" className="font-medium underline">
{translate('Login')}
</Link>
</p>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,218 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { boardApi, BoardCategory } from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { useTranslate } from '@/lib/useTranslate';
export default function BoardWritePage() {
const router = useRouter();
const { user, isLoggedIn } = useAuthStore();
const { translate, language } = useTranslate();
const [categories, setCategories] = useState<BoardCategory[]>([]);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [categoryId, setCategoryId] = useState<number | ''>('');
const [isNotice, setIsNotice] = useState(false);
useEffect(() => {
if (!isLoggedIn) {
router.push('/login?redirect=/board/write');
return;
}
const fetchCategories = async () => {
try {
const res = await boardApi.getCategories();
setCategories(res.categories);
if (res.categories.length > 0) {
setCategoryId(res.categories[0].id);
}
} catch (err) {
console.error('Failed to fetch categories:', err);
} finally {
setLoading(false);
}
};
fetchCategories();
}, [isLoggedIn, router]);
const getCategoryName = (cat: BoardCategory) => {
if (language === 'en' && cat.name_en) return cat.name_en;
if (language === 'mn' && cat.name_mn) return cat.name_mn;
if (language === 'ru' && cat.name_ru) return cat.name_ru;
return cat.name;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!title.trim()) {
setError(translate('Please enter a title'));
return;
}
if (!content.trim()) {
setError(translate('Please enter content'));
return;
}
if (!categoryId) {
setError(translate('Please select a category'));
return;
}
setSubmitting(true);
setError(null);
try {
const post = await boardApi.createPost({
title: title.trim(),
content: content.trim(),
category_id: categoryId as number,
is_notice: user?.is_admin ? isNotice : false,
});
router.push(`/board/${post.id}`);
} catch (err: any) {
setError(err.response?.data?.detail || 'Failed to create post');
} finally {
setSubmitting(false);
}
};
if (!isLoggedIn) {
return null;
}
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
<div className="max-w-4xl mx-auto px-4 py-8">
{/* Back Button */}
<div className="mb-6">
<Link
href="/board"
className="inline-flex items-center text-gray-600 hover:text-gray-900"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
{translate('Back to list')}
</Link>
</div>
{/* Form */}
<div className="bg-white rounded-lg shadow-sm overflow-hidden">
<div className="p-6 border-b border-gray-200">
<h1 className="text-xl font-bold text-gray-900">
{translate('Write Post')}
</h1>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-6">
{error && (
<div className="p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
{error}
</div>
)}
{/* Category */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Category')} <span className="text-red-500">*</span>
</label>
<select
value={categoryId}
onChange={(e) => setCategoryId(e.target.value ? parseInt(e.target.value) : '')}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required
>
<option value="">{translate('Select a category')}</option>
{categories.map((cat) => (
<option key={cat.id} value={cat.id}>
{getCategoryName(cat)}
</option>
))}
</select>
</div>
{/* Title */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Title')} <span className="text-red-500">*</span>
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder={translate('Enter title')}
maxLength={200}
required
/>
</div>
{/* Content */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{translate('Content')} <span className="text-red-500">*</span>
</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[300px]"
placeholder={translate('Enter content')}
required
/>
</div>
{/* Notice Option (Admin Only) */}
{user?.is_admin && (
<div className="flex items-center gap-2">
<input
type="checkbox"
id="isNotice"
checked={isNotice}
onChange={(e) => setIsNotice(e.target.checked)}
className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
/>
<label htmlFor="isNotice" className="text-sm font-medium text-gray-700">
{translate('Post as Notice')} ({translate('Admin only')})
</label>
</div>
)}
{/* Submit Buttons */}
<div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
<Link
href="/board"
className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
>
{translate('Cancel')}
</Link>
<button
type="submit"
disabled={submitting}
className="px-6 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
>
{submitting ? translate('Submitting...') : translate('Submit')}
</button>
</div>
</form>
</div>
</div>
</div>
);
}