feat(blog): implement medical review gate for blog posts
- Added new fields to the Blog entity: sources, review_status, reviewer, reviewed_at, review_note, and topic_slug.
- Created API endpoints for reviewing blog posts: GET /api/v1/admin/blog/review-queue and POST /api/v1/admin/blog/{uuid}/review.
- Updated BlogController to handle review logic, including approval and rejection of posts.
- Introduced BlogReviewPage component for admin interface to manage blog reviews.
- Added migration to update the database schema for new fields.
- Implemented tests for review queue functionality and review decision handling.
This commit is contained in:
@@ -31,6 +31,7 @@ import LogsPage from './pages/LogsPage';
|
||||
import CategoriesPage from './pages/CategoriesPage';
|
||||
import BlogsPage from './pages/BlogsPage';
|
||||
import BlogFormPage from './pages/BlogFormPage';
|
||||
import BlogReviewPage from './pages/BlogReviewPage';
|
||||
import SecretariesPage from './pages/SecretariesPage';
|
||||
import ClinicDoctorsPage from './pages/ClinicDoctorsPage';
|
||||
import SettingsPage from './pages/SettingsPage';
|
||||
@@ -204,6 +205,7 @@ export default function App() {
|
||||
<Route path="blogs" element={<RoleRoute roles={['admin']}><BlogsPage /></RoleRoute>} />
|
||||
<Route path="blogs/new" element={<RoleRoute roles={['admin']}><BlogFormPage /></RoleRoute>} />
|
||||
<Route path="blogs/:uuid/edit" element={<RoleRoute roles={['admin']}><BlogFormPage /></RoleRoute>} />
|
||||
<Route path="blog-review" element={<RoleRoute roles={['admin']}><BlogReviewPage /></RoleRoute>} />
|
||||
<Route path="secretaries" element={<RoleRoute roles={['admin']}><SecretariesPage /></RoleRoute>} />
|
||||
<Route path="clinics" element={<RoleRoute roles={['admin', 'representation']}><ClinicsPage /></RoleRoute>} />
|
||||
<Route path="settings" element={<RoleRoute roles={['admin']}><SettingsPage /></RoleRoute>} />
|
||||
|
||||
@@ -191,6 +191,11 @@ function buildSections(
|
||||
icon: DocumentTextIcon,
|
||||
label: "بلاگ",
|
||||
},
|
||||
{
|
||||
to: "/admin/blog-review",
|
||||
icon: DocumentTextIcon,
|
||||
label: "بازبینی بلاگ",
|
||||
},
|
||||
{
|
||||
to: "/admin/sms",
|
||||
icon: DevicePhoneMobileIcon,
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
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 } 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;
|
||||
|
||||
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 && (
|
||||
<div className="blog-review-preview">
|
||||
{preview.summary && <p className="muted">{preview.summary}</p>}
|
||||
<div
|
||||
className="blog-body"
|
||||
/* محتوای تولیدشده و بازبینیشده توسط ادمین است */
|
||||
dangerouslySetInnerHTML={{ __html: preview.body }}
|
||||
/>
|
||||
{preview.sources && preview.sources.length > 0 && (
|
||||
<div className="blog-sources" style={{ marginTop: 'var(--gap)' }}>
|
||||
<h4 className="section-title">منابع</h4>
|
||||
<ul>
|
||||
{preview.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>
|
||||
);
|
||||
}
|
||||
@@ -437,6 +437,15 @@ export interface Blog {
|
||||
/** null = مقاله سراسری (روی همه دامنهها، canonical روی دامنه اصلی) */
|
||||
city?: { id: string; name: string } | null;
|
||||
tags: string[];
|
||||
/** منابع E-E-A-T مقالههای تولیدشده توسط پایپلاین محتوا */
|
||||
sources?: { url: string; title: string }[];
|
||||
/** null = پست دستی ادمین، خارج از گیت بازبینی؛ در غیر این صورت وضعیت بازبینی پزشک */
|
||||
review_status?: "pending_review" | "approved" | "rejected" | null;
|
||||
reviewer?: { uuid: string; name: string } | null;
|
||||
reviewed_at?: number | null;
|
||||
review_note?: string | null;
|
||||
/** کلید یکتای موضوع پایپلاین (specialty, angle) */
|
||||
topic_slug?: string | null;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
@@ -127,6 +127,9 @@ Create a new blog post.
|
||||
| `status` | string | ❌ | `"draft"` (default) or `"published"` |
|
||||
| `image_url` | string | ❌ | Cover image path returned by the upload endpoint |
|
||||
| `city_id` | integer\|null | ❌ | City this post belongs to. **Omitting it, or sending `null`/`0`, creates a nationwide post.** An unknown city id is rejected with `422`. |
|
||||
| `sources` | array | ❌ | E-E-A-T source list. Each item `{ "url": "...", "title": "..." }`. Used by the content pipeline; shown on the published post. |
|
||||
| `review_status` | string\|null | ❌ | Medical-review gate. Omit/`null` = manual admin post (no review). The content pipeline sends `"pending_review"` so the post enters the doctor review queue (`GET /api/v1/admin/blog/review-queue`). |
|
||||
| `topic_slug` | string | ❌ | Stable pipeline topic key `(specialty, angle)`, **unique**. Makes creation **idempotent**: posting the same `topic_slug` again returns the existing post with HTTP **200** (not a duplicate `201`). |
|
||||
|
||||
### Response `201`
|
||||
```json
|
||||
@@ -202,6 +205,105 @@ Updated blog object.
|
||||
|
||||
---
|
||||
|
||||
## Medical-review gate
|
||||
|
||||
The content pipeline (`clinicpro-crawler/content/`) generates Persian health articles as **drafts** (`status=draft`, `review_status=pending_review`). A doctor/admin then approves or rejects each one before it goes public. The reviewer's identity is stored and shown on the post — the E-E-A-T signal for YMYL content. `review_status=null` posts (created manually by an admin) are outside this gate.
|
||||
|
||||
`review_status` values:
|
||||
|
||||
| Value | Meaning |
|
||||
|-------|---------|
|
||||
| `null` | Manual admin post — never entered the review workflow |
|
||||
| `pending_review` | Awaiting a doctor's decision (in the queue) |
|
||||
| `approved` | Reviewed and approved (usually also `status=published`) |
|
||||
| `rejected` | Reviewed and rejected — stays a draft |
|
||||
|
||||
---
|
||||
|
||||
## GET `/api/v1/admin/blog/review-queue`
|
||||
|
||||
List blog drafts awaiting review, newest first.
|
||||
|
||||
**Permission:** `ROLE_ADMIN`
|
||||
|
||||
### Query Parameters
|
||||
| Param | Type | Required | Default | Description |
|
||||
|-------|------|----------|---------|-------------|
|
||||
| `page` | integer | ❌ | 1 | Page number |
|
||||
| `limit` | integer | ❌ | 20 (max 50) | Items per page |
|
||||
|
||||
### Response `200`
|
||||
Paginated (`{ data:[...], meta:{ totalRecords, totalPages, currentPage } }`). Each item is the blog list shape plus `review_status`, `reviewer` (`{ uuid, name }` or `null`), and `topic_slug`.
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"uuid": "...",
|
||||
"title": "علائم سکته قلبی که نباید نادیده بگیرید",
|
||||
"slug": "...",
|
||||
"summary": "...",
|
||||
"status": "draft",
|
||||
"review_status": "pending_review",
|
||||
"reviewer": null,
|
||||
"topic_slug": "cardiology-heart-attack-symptoms",
|
||||
"city": null,
|
||||
"created_at": 1769000000
|
||||
}
|
||||
],
|
||||
"meta": { "totalRecords": 3, "totalPages": 1, "currentPage": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
### Errors
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `ERR_AUTH_001` | 401 | Missing token |
|
||||
| `ERR_AUTH_006` | 403 | Not admin |
|
||||
|
||||
---
|
||||
|
||||
## POST `/api/v1/admin/blog/{uuid}/review`
|
||||
|
||||
Record a doctor's review decision. Approving publishes the post by default.
|
||||
|
||||
**Permission:** `ROLE_ADMIN`
|
||||
|
||||
### Path Parameters
|
||||
| Param | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `uuid` | string (UUID) | Blog UUID |
|
||||
|
||||
### Request Body (`application/json`)
|
||||
```json
|
||||
{ "decision": "approved", "publish": true }
|
||||
```
|
||||
```json
|
||||
{ "decision": "rejected", "note": "ادعاهای پزشکی بدون منبع کافی" }
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `decision` | string | ✅ | `"approved"` or `"rejected"` |
|
||||
| `note` | string | ⚠️ | Reviewer note. **Required when `decision=rejected`.** |
|
||||
| `publish` | boolean | ❌ | On approval, publish immediately. Default `true`. `false` keeps it a draft. |
|
||||
|
||||
On **approve**: `review_status=approved`, `reviewer`/`reviewed_at` set, and `status=published` unless `publish:false`. On **reject**: `review_status=rejected`, note stored, `status` stays `draft`.
|
||||
|
||||
### Response `200`
|
||||
Updated blog object (full `toArray`, including `reviewer`, `reviewed_at`, `review_note`).
|
||||
|
||||
### Errors
|
||||
| Code | HTTP | Description |
|
||||
|------|------|-------------|
|
||||
| `ERR_AUTH_001` | 401 | Missing token |
|
||||
| `ERR_AUTH_006` | 403 | Not admin |
|
||||
| `ERR_NOT_FOUND_001` | 404 | Blog not found |
|
||||
| `ERR_VALIDATION_002` | 422 | Invalid `decision`, or `rejected` without a `note` |
|
||||
|
||||
---
|
||||
|
||||
## DELETE `/api/v1/blog/{uuid}`
|
||||
|
||||
Delete a blog post.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Auto-generated Migration: Please modify to your needs!
|
||||
*/
|
||||
final class Version20260723171254 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add medical-review gate fields to blogs (sources, review_status, reviewer, reviewed_at, review_note, topic_slug)';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// Scoped to the blogs table only. Unrelated project-wide schema drift that
|
||||
// doctrine:diff also emitted (messenger_messages, date_overrides, …) is
|
||||
// deliberately left out — it belongs to other migrations, not this feature.
|
||||
$this->addSql('ALTER TABLE blogs ADD sources JSON NOT NULL, ADD review_status VARCHAR(20) DEFAULT NULL, ADD reviewed_at INT DEFAULT NULL, ADD review_note VARCHAR(500) DEFAULT NULL, ADD topic_slug VARCHAR(255) DEFAULT NULL, ADD reviewer_id INT DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE blogs ADD CONSTRAINT FK_F41BCA7070574616 FOREIGN KEY (reviewer_id) REFERENCES users (id) ON DELETE SET NULL');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_F41BCA70A076FAD7 ON blogs (topic_slug)');
|
||||
$this->addSql('CREATE INDEX IDX_F41BCA7070574616 ON blogs (reviewer_id)');
|
||||
$this->addSql('CREATE INDEX idx_blogs_review_status ON blogs (review_status, created_at)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE blogs DROP FOREIGN KEY FK_F41BCA7070574616');
|
||||
$this->addSql('DROP INDEX UNIQ_F41BCA70A076FAD7 ON blogs');
|
||||
$this->addSql('DROP INDEX IDX_F41BCA7070574616 ON blogs');
|
||||
$this->addSql('DROP INDEX idx_blogs_review_status ON blogs');
|
||||
$this->addSql('ALTER TABLE blogs DROP sources, DROP review_status, DROP reviewed_at, DROP review_note, DROP topic_slug, DROP reviewer_id');
|
||||
}
|
||||
}
|
||||
@@ -221,11 +221,26 @@ class BlogController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'title و body الزامی است', 422);
|
||||
}
|
||||
|
||||
// Idempotency for the content pipeline: a topic_slug is a stable (specialty,
|
||||
// angle) key. A re-run must not create a duplicate — return the existing post.
|
||||
$topicSlug = isset($data['topic_slug']) ? trim((string) $data['topic_slug']) : '';
|
||||
if ($topicSlug !== '') {
|
||||
$existing = $this->blogRepo->findByTopicSlug($topicSlug);
|
||||
if ($existing !== null) {
|
||||
return $this->success(['data' => $existing->toArray()], 200);
|
||||
}
|
||||
}
|
||||
|
||||
$blog = new Blog($user, $title, $body);
|
||||
if (!empty($data['summary'])) $blog->setSummary($data['summary']);
|
||||
if (!empty($data['tags'])) $blog->setTags((array)$data['tags']);
|
||||
if (!empty($data['sources'])) $blog->setSources((array)$data['sources']);
|
||||
if (!empty($data['status'])) $blog->setStatus($data['status']);
|
||||
if (!empty($data['image_url'])) $blog->setImageUrl($data['image_url']);
|
||||
if ($topicSlug !== '') $blog->setTopicSlug($topicSlug);
|
||||
// review_status: null means "manual admin post". The pipeline sends
|
||||
// "pending_review" so the post enters the doctor review queue.
|
||||
if (!empty($data['review_status'])) $blog->setReviewStatus($data['review_status']);
|
||||
// نبودِ city_id یعنی سراسری — پس همیشه اعمال میشود، نه فقط وقتی مقدار دارد.
|
||||
$blog->setCity($this->resolveCity($data['city_id'] ?? null));
|
||||
|
||||
@@ -310,6 +325,98 @@ class BlogController extends BaseController
|
||||
return $this->success(['data' => $blog->toArray()]);
|
||||
}
|
||||
|
||||
// ── Medical-review gate ───────────────────────────────────────────────────
|
||||
|
||||
#[OA\Get(
|
||||
path: '/api/v1/admin/blog/review-queue',
|
||||
summary: 'List blog drafts awaiting doctor review (admin only)',
|
||||
security: [['bearerAuth' => []]],
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'page', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 1)),
|
||||
new OA\Parameter(name: 'limit', in: 'query', required: false, schema: new OA\Schema(type: 'integer', default: 20, maximum: 50)),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Paginated review queue'),
|
||||
new OA\Response(response: 401, description: 'Unauthorized'),
|
||||
new OA\Response(response: 403, description: 'Forbidden — admin role required'),
|
||||
]
|
||||
)]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
#[Route('/api/v1/admin/blog/review-queue', methods: ['GET'])]
|
||||
public function reviewQueue(Request $request): JsonResponse
|
||||
{
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(50, max(1, (int) $request->query->get('limit', 20)));
|
||||
|
||||
$items = array_map(
|
||||
fn(Blog $b) => $b->toListArray(),
|
||||
$this->blogRepo->findByReviewStatus(Blog::REVIEW_PENDING, $page, $limit)
|
||||
);
|
||||
$total = $this->blogRepo->countByReviewStatus(Blog::REVIEW_PENDING);
|
||||
|
||||
return $this->paginated($items, $total, $page, $limit);
|
||||
}
|
||||
|
||||
#[OA\Post(
|
||||
path: '/api/v1/admin/blog/{uuid}/review',
|
||||
summary: 'Approve or reject a blog draft (admin only). Approving may publish it.',
|
||||
security: [['bearerAuth' => []]],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
required: ['decision'],
|
||||
properties: [
|
||||
new OA\Property(property: 'decision', type: 'string', enum: ['approved', 'rejected']),
|
||||
new OA\Property(property: 'note', type: 'string', nullable: true, description: 'Reviewer note (required message on rejection).'),
|
||||
new OA\Property(property: 'publish', type: 'boolean', nullable: true, description: 'On approval, publish immediately (default true).'),
|
||||
]
|
||||
)
|
||||
),
|
||||
parameters: [
|
||||
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string', format: 'uuid')),
|
||||
],
|
||||
responses: [
|
||||
new OA\Response(response: 200, description: 'Review decision recorded'),
|
||||
new OA\Response(response: 401, description: 'Unauthorized'),
|
||||
new OA\Response(response: 403, description: 'Forbidden — admin role required'),
|
||||
new OA\Response(response: 404, description: 'Blog post not found'),
|
||||
new OA\Response(response: 422, description: 'Invalid decision'),
|
||||
]
|
||||
)]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
#[Route('/api/v1/admin/blog/{uuid}/review', methods: ['POST'])]
|
||||
public function review(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$blog = $this->blogRepo->findByUuid($uuid);
|
||||
if ($blog === null) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'مقاله یافت نشد', 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$decision = $data['decision'] ?? null;
|
||||
$note = isset($data['note']) ? trim((string) $data['note']) : null;
|
||||
|
||||
if (!in_array($decision, [Blog::REVIEW_APPROVED, Blog::REVIEW_REJECTED], true)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'decision باید approved یا rejected باشد', 422);
|
||||
}
|
||||
if ($decision === Blog::REVIEW_REJECTED && ($note === null || $note === '')) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'برای رد مقاله، درج دلیل الزامی است', 422);
|
||||
}
|
||||
|
||||
$blog->applyReview($decision, $user, $note);
|
||||
|
||||
// Approving publishes by default; rejecting keeps the post as a draft.
|
||||
if ($decision === Blog::REVIEW_APPROVED && ($data['publish'] ?? true)) {
|
||||
$blog->setStatus(Blog::STATUS_PUBLISHED);
|
||||
} elseif ($decision === Blog::REVIEW_REJECTED) {
|
||||
$blog->setStatus(Blog::STATUS_DRAFT);
|
||||
}
|
||||
|
||||
$this->blogRepo->save($blog);
|
||||
|
||||
return $this->success(['data' => $blog->toArray()]);
|
||||
}
|
||||
|
||||
#[OA\Delete(
|
||||
path: '/api/v1/blog/{uuid}',
|
||||
summary: 'Delete a blog post (admin only)',
|
||||
|
||||
@@ -12,12 +12,21 @@ use Symfony\Component\Uid\Uuid;
|
||||
#[ORM\Table(name: 'blogs')]
|
||||
#[ORM\Index(columns: ['status', 'created_at'], name: 'idx_blogs_status')]
|
||||
#[ORM\Index(columns: ['city_id'], name: 'idx_blogs_city')]
|
||||
#[ORM\Index(columns: ['review_status', 'created_at'], name: 'idx_blogs_review_status')]
|
||||
class Blog
|
||||
{
|
||||
public const STATUS_DRAFT = 'draft';
|
||||
public const STATUS_PUBLISHED = 'published';
|
||||
public const STATUS_ARCHIVED = 'archived';
|
||||
|
||||
// Medical-review gate. NULL is the permanent meaning "not part of the review
|
||||
// workflow" — a post created manually by an admin, which never needs a doctor's
|
||||
// approval. The content pipeline sets REVIEW_PENDING on every generated draft;
|
||||
// only REVIEW_APPROVED may be published by the pipeline.
|
||||
public const REVIEW_PENDING = 'pending_review';
|
||||
public const REVIEW_APPROVED = 'approved';
|
||||
public const REVIEW_REJECTED = 'rejected';
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
@@ -58,9 +67,34 @@ class Blog
|
||||
#[ORM\Column(type: 'json')]
|
||||
private array $tags = [];
|
||||
|
||||
// Independent sources this article's facts were drawn from — the E-E-A-T
|
||||
// signal shown on the published post. Each item: { url, title }.
|
||||
#[ORM\Column(type: 'json')]
|
||||
private array $sources = [];
|
||||
|
||||
#[ORM\Column(type: 'string', length: 20)]
|
||||
private string $status = self::STATUS_DRAFT;
|
||||
|
||||
// NULL = manual admin post, outside the review workflow. Set by the pipeline.
|
||||
#[ORM\Column(name: 'review_status', type: 'string', length: 20, nullable: true)]
|
||||
private ?string $reviewStatus = null;
|
||||
|
||||
// The doctor who reviewed. Kept even if their user is later removed.
|
||||
#[ORM\ManyToOne(targetEntity: User::class)]
|
||||
#[ORM\JoinColumn(name: 'reviewer_id', referencedColumnName: 'id', nullable: true, onDelete: 'SET NULL')]
|
||||
private ?User $reviewer = null;
|
||||
|
||||
#[ORM\Column(name: 'reviewed_at', type: 'integer', nullable: true)]
|
||||
private ?int $reviewedAt = null;
|
||||
|
||||
#[ORM\Column(name: 'review_note', type: 'string', length: 500, nullable: true)]
|
||||
private ?string $reviewNote = null;
|
||||
|
||||
// Stable identity of the pipeline topic (specialty + angle). Unique so a
|
||||
// re-run is idempotent and never creates a duplicate post. NULL for manual posts.
|
||||
#[ORM\Column(name: 'topic_slug', type: 'string', length: 255, nullable: true, unique: true)]
|
||||
private ?string $topicSlug = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
@@ -88,7 +122,13 @@ class Blog
|
||||
public function getImagePath(): ?string { return $this->imagePath; }
|
||||
public function getAuthor(): User { return $this->author; }
|
||||
public function getTags(): array { return $this->tags; }
|
||||
public function getSources(): array { return $this->sources; }
|
||||
public function getStatus(): string { return $this->status; }
|
||||
public function getReviewStatus(): ?string { return $this->reviewStatus; }
|
||||
public function getReviewer(): ?User { return $this->reviewer; }
|
||||
public function getReviewedAt(): ?int { return $this->reviewedAt; }
|
||||
public function getReviewNote(): ?string { return $this->reviewNote; }
|
||||
public function getTopicSlug(): ?string { return $this->topicSlug; }
|
||||
public function getCity(): ?City { return $this->city; }
|
||||
|
||||
public function setTitle(string $v): self { $this->title = $v; $this->touch(); return $this; }
|
||||
@@ -98,10 +138,27 @@ class Blog
|
||||
public function setImageUrl(?string $v): self { $this->imageUrl = $v; $this->touch(); return $this; }
|
||||
public function setImagePath(?string $v): self { $this->imagePath = $v; $this->touch(); return $this; }
|
||||
public function setTags(array $v): self { $this->tags = $v; $this->touch(); return $this; }
|
||||
public function setSources(array $v): self { $this->sources = $v; $this->touch(); return $this; }
|
||||
public function setStatus(string $v): self { $this->status = $v; $this->touch(); return $this; }
|
||||
public function setReviewStatus(?string $v): self { $this->reviewStatus = $v; $this->touch(); return $this; }
|
||||
public function setReviewer(?User $v): self { $this->reviewer = $v; $this->touch(); return $this; }
|
||||
public function setReviewedAt(?int $v): self { $this->reviewedAt = $v; $this->touch(); return $this; }
|
||||
public function setReviewNote(?string $v): self { $this->reviewNote = $v; $this->touch(); return $this; }
|
||||
public function setTopicSlug(?string $v): self { $this->topicSlug = $v; $this->touch(); return $this; }
|
||||
/** null = پست سراسری (روی همهٔ دامنهها، canonical روی دامنهٔ اصلی) */
|
||||
public function setCity(?City $v): self { $this->city = $v; $this->touch(); return $this; }
|
||||
|
||||
/** Record a doctor's review decision in one call. */
|
||||
public function applyReview(string $decision, User $reviewer, ?string $note = null): self
|
||||
{
|
||||
$this->reviewStatus = $decision;
|
||||
$this->reviewer = $reviewer;
|
||||
$this->reviewedAt = time();
|
||||
$this->reviewNote = $note;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function touch(): void { $this->updatedAt = time(); }
|
||||
|
||||
private function generateSlug(string $title): string
|
||||
@@ -122,7 +179,13 @@ class Blog
|
||||
'body' => $this->body,
|
||||
'image_url' => $this->imageUrl,
|
||||
'tags' => $this->tags,
|
||||
'sources' => $this->sources,
|
||||
'status' => $this->status,
|
||||
'review_status' => $this->reviewStatus,
|
||||
'reviewer' => $this->reviewerToArray(),
|
||||
'reviewed_at'=> $this->reviewedAt,
|
||||
'review_note'=> $this->reviewNote,
|
||||
'topic_slug' => $this->topicSlug,
|
||||
'author' => $this->authorToArray(),
|
||||
'city' => $this->cityToArray(),
|
||||
'created_at' => $this->createdAt,
|
||||
@@ -130,6 +193,22 @@ class Blog
|
||||
];
|
||||
}
|
||||
|
||||
/** The reviewing doctor, or null. Same defensive lazy-proxy handling as author. */
|
||||
private function reviewerToArray(): ?array
|
||||
{
|
||||
if ($this->reviewer === null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return [
|
||||
'uuid' => $this->reviewer->getUuid(),
|
||||
'name' => $this->reviewer->getRealName(),
|
||||
];
|
||||
} catch (\Doctrine\ORM\EntityNotFoundException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** null = پست سراسری. مصرفکننده روی همین null تصمیم canonical میگیرد. */
|
||||
private function cityToArray(): ?array
|
||||
{
|
||||
@@ -170,6 +249,9 @@ class Blog
|
||||
'image_url' => $this->imageUrl,
|
||||
'tags' => $this->tags,
|
||||
'status' => $this->status,
|
||||
'review_status' => $this->reviewStatus,
|
||||
'reviewer' => $this->reviewerToArray(),
|
||||
'topic_slug' => $this->topicSlug,
|
||||
'city' => $this->cityToArray(),
|
||||
'created_at' => $this->createdAt,
|
||||
];
|
||||
|
||||
@@ -12,6 +12,33 @@ class BlogRepository extends ServiceEntityRepository
|
||||
|
||||
public function findByUuid(string $uuid): ?Blog { return $this->findOneBy(['uuid' => $uuid]); }
|
||||
public function findBySlug(string $slug): ?Blog { return $this->findOneBy(['slug' => $slug]); }
|
||||
public function findByTopicSlug(string $topicSlug): ?Blog { return $this->findOneBy(['topicSlug' => $topicSlug]); }
|
||||
|
||||
/**
|
||||
* The admin review queue: posts awaiting a doctor's decision, newest first.
|
||||
* @return Blog[]
|
||||
*/
|
||||
public function findByReviewStatus(string $reviewStatus, int $page = 1, int $limit = 20): array
|
||||
{
|
||||
return $this->createQueryBuilder('b')
|
||||
->leftJoin('b.city', 'c')->addSelect('c')
|
||||
->leftJoin('b.reviewer', 'r')->addSelect('r')
|
||||
->where('b.reviewStatus = :rs')
|
||||
->setParameter('rs', $reviewStatus)
|
||||
->orderBy('b.createdAt', 'DESC')
|
||||
->setFirstResult(($page - 1) * $limit)
|
||||
->setMaxResults($limit)
|
||||
->getQuery()->getResult();
|
||||
}
|
||||
|
||||
public function countByReviewStatus(string $reviewStatus): int
|
||||
{
|
||||
return (int) $this->createQueryBuilder('b')
|
||||
->select('COUNT(b.id)')
|
||||
->where('b.reviewStatus = :rs')
|
||||
->setParameter('rs', $reviewStatus)
|
||||
->getQuery()->getSingleScalarResult();
|
||||
}
|
||||
|
||||
/** @return Blog[] published, newest first */
|
||||
public function findPublished(int $page = 1, int $limit = 20, ?string $tag = null, ?int $cityId = null): array
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Blog;
|
||||
|
||||
use App\Blog\Entity\Blog;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* The medical-review gate: the content pipeline creates drafts as
|
||||
* review_status=pending_review; a doctor/admin approves (publishes) or rejects
|
||||
* them. review_status=null stays reserved for manual admin posts outside the gate.
|
||||
*/
|
||||
class BlogReviewGateTest extends ApiTestCase
|
||||
{
|
||||
private function makePendingPost(string $title, ?string $topicSlug = null): Blog
|
||||
{
|
||||
$blog = new Blog($this->createUser(['ROLE_ADMIN']), $title, 'متن آزمایشی مقاله برای تست');
|
||||
$blog->setStatus(Blog::STATUS_DRAFT)->setReviewStatus(Blog::REVIEW_PENDING);
|
||||
if ($topicSlug !== null) {
|
||||
$blog->setTopicSlug($topicSlug);
|
||||
}
|
||||
$this->em->persist($blog);
|
||||
$this->em->flush();
|
||||
|
||||
return $blog;
|
||||
}
|
||||
|
||||
// ── review queue ──────────────────────────────────────────────────────────
|
||||
|
||||
public function testReviewQueueReturnsOnlyPendingPosts(): void
|
||||
{
|
||||
$admin = $this->createUser(['ROLE_ADMIN']);
|
||||
$tag = bin2hex(random_bytes(4));
|
||||
|
||||
$this->makePendingPost("در-انتظار-$tag");
|
||||
$published = new Blog($admin, "منتشرشده-$tag", 'متن آزمایشی مقاله برای تست');
|
||||
$published->setStatus(Blog::STATUS_PUBLISHED); // review_status null → outside the gate
|
||||
$this->em->persist($published);
|
||||
$this->em->flush();
|
||||
|
||||
$payload = $this->authJson('GET', '/api/v1/admin/blog/review-queue?limit=50', $admin);
|
||||
$titles = array_column($payload['data'], 'title');
|
||||
|
||||
$this->assertContains("در-انتظار-$tag", $titles, 'pending post must be in the queue');
|
||||
$this->assertNotContains("منتشرشده-$tag", $titles, 'non-pending post leaked into the queue');
|
||||
}
|
||||
|
||||
public function testReviewQueueRequiresAdmin(): void
|
||||
{
|
||||
$user = $this->createUser(['ROLE_USER']);
|
||||
$this->authJson('GET', '/api/v1/admin/blog/review-queue', $user);
|
||||
$this->assertSame(403, $this->responseCode());
|
||||
}
|
||||
|
||||
// ── approve ───────────────────────────────────────────────────────────────
|
||||
|
||||
public function testApprovePublishesAndRecordsReviewer(): void
|
||||
{
|
||||
$doctor = $this->createUser(['ROLE_ADMIN']);
|
||||
$post = $this->makePendingPost('مقاله ' . bin2hex(random_bytes(3)));
|
||||
|
||||
$res = $this->authJson('POST', '/api/v1/admin/blog/' . $post->getUuid() . '/review', $doctor, [
|
||||
'decision' => 'approved',
|
||||
]);
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
|
||||
$blog = $res['data']['data'];
|
||||
$this->assertSame(Blog::REVIEW_APPROVED, $blog['review_status']);
|
||||
$this->assertSame(Blog::STATUS_PUBLISHED, $blog['status'], 'approve must publish by default');
|
||||
$this->assertSame($doctor->getUuid(), $blog['reviewer']['uuid'], 'reviewer identity must be stored (E-E-A-T)');
|
||||
$this->assertNotNull($blog['reviewed_at']);
|
||||
}
|
||||
|
||||
public function testApproveWithPublishFalseKeepsDraft(): void
|
||||
{
|
||||
$doctor = $this->createUser(['ROLE_ADMIN']);
|
||||
$post = $this->makePendingPost('مقاله ' . bin2hex(random_bytes(3)));
|
||||
|
||||
$res = $this->authJson('POST', '/api/v1/admin/blog/' . $post->getUuid() . '/review', $doctor, [
|
||||
'decision' => 'approved',
|
||||
'publish' => false,
|
||||
]);
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertSame(Blog::REVIEW_APPROVED, $res['data']['data']['review_status']);
|
||||
$this->assertSame(Blog::STATUS_DRAFT, $res['data']['data']['status']);
|
||||
}
|
||||
|
||||
// ── reject ────────────────────────────────────────────────────────────────
|
||||
|
||||
public function testRejectRequiresNoteAndKeepsDraft(): void
|
||||
{
|
||||
$doctor = $this->createUser(['ROLE_ADMIN']);
|
||||
$post = $this->makePendingPost('مقاله ' . bin2hex(random_bytes(3)));
|
||||
|
||||
// boundary: rejection without a note is refused
|
||||
$this->authJson('POST', '/api/v1/admin/blog/' . $post->getUuid() . '/review', $doctor, [
|
||||
'decision' => 'rejected',
|
||||
]);
|
||||
$this->assertSame(422, $this->responseCode(), 'rejection must require a reason');
|
||||
|
||||
$res = $this->authJson('POST', '/api/v1/admin/blog/' . $post->getUuid() . '/review', $doctor, [
|
||||
'decision' => 'rejected',
|
||||
'note' => 'ادعاهای پزشکی بدون منبع کافی',
|
||||
]);
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertSame(Blog::REVIEW_REJECTED, $res['data']['data']['review_status']);
|
||||
$this->assertSame(Blog::STATUS_DRAFT, $res['data']['data']['status'], 'rejected post must not be published');
|
||||
$this->assertSame('ادعاهای پزشکی بدون منبع کافی', $res['data']['data']['review_note']);
|
||||
}
|
||||
|
||||
public function testInvalidDecisionIsRejected(): void
|
||||
{
|
||||
$doctor = $this->createUser(['ROLE_ADMIN']);
|
||||
$post = $this->makePendingPost('مقاله ' . bin2hex(random_bytes(3)));
|
||||
|
||||
$this->authJson('POST', '/api/v1/admin/blog/' . $post->getUuid() . '/review', $doctor, [
|
||||
'decision' => 'maybe',
|
||||
]);
|
||||
$this->assertSame(422, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testReviewUnknownPostReturns404(): void
|
||||
{
|
||||
$doctor = $this->createUser(['ROLE_ADMIN']);
|
||||
$this->authJson('POST', '/api/v1/admin/blog/00000000-0000-0000-0000-000000000000/review', $doctor, [
|
||||
'decision' => 'approved',
|
||||
]);
|
||||
$this->assertSame(404, $this->responseCode());
|
||||
}
|
||||
|
||||
// ── pipeline idempotency ──────────────────────────────────────────────────
|
||||
|
||||
public function testCreateIsIdempotentOnTopicSlug(): void
|
||||
{
|
||||
$admin = $this->createUser(['ROLE_ADMIN']);
|
||||
$slug = 'cardiology-chest-pain-' . bin2hex(random_bytes(3));
|
||||
|
||||
$first = $this->authJson('POST', '/api/v1/blog', $admin, [
|
||||
'title' => 'درد قفسه سینه',
|
||||
'body' => 'متن آزمایشی مقاله برای تست',
|
||||
'topic_slug' => $slug,
|
||||
'sources' => [['url' => 'https://mayoclinic.org/a', 'title' => 'Mayo']],
|
||||
'review_status' => 'pending_review',
|
||||
]);
|
||||
$this->assertSame(201, $this->responseCode());
|
||||
$this->assertSame('pending_review', $first['data']['data']['review_status']);
|
||||
$firstUuid = $first['data']['data']['uuid'];
|
||||
|
||||
// A re-run with the same topic_slug must return the SAME post, not a duplicate.
|
||||
$second = $this->authJson('POST', '/api/v1/blog', $admin, [
|
||||
'title' => 'درد قفسه سینه (دوباره)',
|
||||
'body' => 'متن دیگر',
|
||||
'topic_slug' => $slug,
|
||||
]);
|
||||
$this->assertSame(200, $this->responseCode(), 're-run must be idempotent, not 201');
|
||||
$this->assertSame($firstUuid, $second['data']['data']['uuid'], 'topic_slug must not create a duplicate');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user