Files
clinicpro/assets/admin/pages/BlogReviewPage.tsx
T

279 lines
12 KiB
TypeScript

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse, PaginatedResponse } from '../lib/api';
import type { Blog } from '../types';
import { formatDate, formatNumber } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import Pagination from '../components/ui/Pagination';
import Modal from '../components/ui/Modal';
import ConfirmDialog from '../components/ui/ConfirmDialog';
const limit = 15;
/** وضعیت بازبینی → رنگ نشان. مقاله‌های صف همه pending_review هستند. */
function reviewBadgeColor(status?: string | null): string {
switch (status) {
case 'approved': return 'green';
case 'rejected': return 'red';
case 'pending_review': return 'amber';
default: return 'gray';
}
}
function reviewBadgeLabel(status?: string | null): string {
switch (status) {
case 'approved': return 'تأییدشده';
case 'rejected': return 'ردشده';
case 'pending_review': return 'در انتظار بازبینی';
default: return status ?? '—';
}
}
export default function BlogReviewPage() {
const qc = useQueryClient();
const [page, setPage] = useState(1);
const [preview, setPreview] = useState<Blog | null>(null);
const [rejectTarget, setRejectTarget] = useState<Blog | null>(null);
const [rejectNote, setRejectNote] = useState('');
const { data, isLoading } = useQuery({
queryKey: ['blog-review-queue', page],
queryFn: () => {
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
return api.get<PaginatedResponse<Blog>>(`/api/v1/admin/blog/review-queue?${params}`);
},
});
const items = data?.data ?? [];
const total = data?.meta?.totalRecords ?? 0;
/**
* ردیف‌های صف از `toListArray()` می‌آیند و `body`/`faq`/`sources` ندارند — مودال
* بازبینی با آن‌ها یک قاب خالی بود. متن کامل هنگام باز شدن مودال از اندپوینت
* جزئیاتِ موجود گرفته می‌شود، نه با سنگین‌کردن پاسخ فهرست برای ۱۵ ردیف.
*
* شکل پاسخ عمداً double-nested است (`data.data`) — همان قراردادی که فرم ویرایش
* مقاله هم مصرف می‌کند.
*/
const { data: detail, isLoading: detailLoading } = useQuery({
queryKey: ['admin-blog', preview?.uuid],
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/admin/blog/${preview!.uuid}`),
enabled: !!preview,
});
const full = detail?.data?.data ?? null;
const approveMutation = useMutation({
mutationFn: (blog: Blog) =>
api.post<ApiResponse<Blog>>(`/api/v1/admin/blog/${blog.uuid}/review`, {
decision: 'approved',
publish: true,
}),
onSuccess: () => {
toast.success('مقاله تأیید و منتشر شد');
setPreview(null);
qc.invalidateQueries({ queryKey: ['blog-review-queue'] });
},
onError: (err: Error) => toast.error(err.message),
});
const rejectMutation = useMutation({
mutationFn: (vars: { blog: Blog; note: string }) =>
api.post<ApiResponse<Blog>>(`/api/v1/admin/blog/${vars.blog.uuid}/review`, {
decision: 'rejected',
note: vars.note,
}),
onSuccess: () => {
toast.success('مقاله رد شد');
setRejectTarget(null);
setRejectNote('');
setPreview(null);
qc.invalidateQueries({ queryKey: ['blog-review-queue'] });
},
onError: (err: Error) => toast.error(err.message),
});
const columns: Column<Blog>[] = [
{ key: 'title', header: 'عنوان', render: (b) => <span className="fw-600">{b.title}</span> },
{
key: 'topic_slug',
header: 'موضوع',
render: (b) => <span className="muted mono">{b.topic_slug ?? '—'}</span>,
},
{
key: 'review_status',
header: 'وضعیت',
render: (b) => (
<span className={`badge ${reviewBadgeColor(b.review_status)}`}>
<span className="bdot" />
{reviewBadgeLabel(b.review_status)}
</span>
),
},
{ key: 'created_at', header: 'تاریخ', render: (b) => formatDate(b.created_at) },
];
return (
<div className="fade-in">
<PageHeader
title="بازبینی مقالات بلاگ"
description="پیش‌نویس‌های تولیدشده توسط پایپ‌لاین محتوا؛ پس از بازبینی پزشک منتشر می‌شوند."
breadcrumbs={[{ label: 'بلاگ', to: '/admin/blogs' }, { label: 'بازبینی' }]}
/>
<div className="card card-pad" style={{ marginTop: 'var(--gap)' }}>
<DataTable<Blog>
columns={columns}
data={items}
loading={isLoading}
emptyMessage="مقاله‌ای در انتظار بازبینی نیست"
actions={(b) => (
<button className="mini-btn" onClick={() => setPreview(b)}>
بازبینی
</button>
)}
/>
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
</div>
{/* پیش‌نمایش کامل + تصمیم */}
<Modal
open={!!preview}
title={preview?.title ?? ''}
size="xl"
onClose={() => setPreview(null)}
footer={
preview ? (
<div className="row-actions">
<button
className="btn danger sm"
disabled={approveMutation.isPending}
onClick={() => {
setRejectTarget(preview);
setRejectNote('');
}}
>
رد مقاله
</button>
<button
className="btn primary sm"
disabled={approveMutation.isPending}
onClick={() => approveMutation.mutate(preview)}
>
{approveMutation.isPending ? 'در حال انتشار...' : 'تأیید و انتشار'}
</button>
</div>
) : undefined
}
>
{preview && detailLoading && !full && (
<p className="muted">در حال بارگذاری مقاله...</p>
)}
{full && (
<div className="blog-review-preview">
{full.image_url && (
<img
src={full.image_url}
alt=""
style={{
width: '100%', maxHeight: 320, objectFit: 'cover',
borderRadius: 'var(--r)', marginBottom: 'var(--gap)',
}}
/>
)}
{/* شناسنامهٔ مقاله: بازبین بدون این‌ها نمی‌داند چه چیزی را تأیید می‌کند */}
<div
className="muted"
style={{ display: 'flex', gap: 10, flexWrap: 'wrap', fontSize: 12.5, marginBottom: 10 }}
>
{full.topic_slug && <span className="mono">{full.topic_slug}</span>}
{full.reading_time ? <span>{formatNumber(full.reading_time)} دقیقه مطالعه</span> : null}
{full.primary_keyword && <span>کلیدواژه: {full.primary_keyword}</span>}
<span>{formatDate(full.created_at)}</span>
</div>
{full.summary && <p className="muted">{full.summary}</p>}
<div
className="blog-body"
/* محتوای تولیدشده و بازبینی‌شده توسط ادمین است */
dangerouslySetInnerHTML={{ __html: full.body }}
/>
{full.faq && full.faq.length > 0 && (
<div style={{ marginTop: 'var(--gap)' }}>
<h4 className="section-title">پرسش‌های متداول</h4>
{full.faq.map((f, i) => (
<div key={i} style={{ marginBottom: 10 }}>
<div style={{ fontWeight: 600 }}>{f.q}</div>
<div className="muted">{f.a}</div>
</div>
))}
</div>
)}
{full.tags && full.tags.length > 0 && (
<div style={{ marginTop: 'var(--gap)', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{full.tags.map((t) => (
<span key={t} className="badge gray">{t}</span>
))}
</div>
)}
{full.sources && full.sources.length > 0 && (
<div className="blog-sources" style={{ marginTop: 'var(--gap)' }}>
<h4 className="section-title">منابع</h4>
<ul>
{full.sources.map((s) => (
<li key={s.url}>
<a href={s.url} target="_blank" rel="noopener noreferrer">
{s.title || s.url}
</a>
</li>
))}
</ul>
</div>
)}
</div>
)}
</Modal>
{/* رد با درج دلیل الزامی */}
<ConfirmDialog
open={!!rejectTarget}
title="رد مقاله"
message="دلیل رد را وارد کنید. مقاله در وضعیت پیش‌نویس باقی می‌ماند و منتشر نمی‌شود."
confirmLabel="ثبت رد"
danger
loading={rejectMutation.isPending}
onConfirm={() => {
if (!rejectTarget) return;
if (!rejectNote.trim()) {
toast.error('درج دلیل الزامی است');
return;
}
rejectMutation.mutate({ blog: rejectTarget, note: rejectNote.trim() });
}}
onCancel={() => {
setRejectTarget(null);
setRejectNote('');
}}
>
<textarea
className="field"
rows={3}
placeholder="مثلاً: ادعای پزشکی بدون منبع کافی"
value={rejectNote}
onChange={(e) => setRejectNote(e.target.value)}
style={{ width: '100%', marginTop: 8 }}
/>
</ConfirmDialog>
</div>
);
}