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:
hamed
2026-07-23 21:01:58 +03:30
parent 2abf915f95
commit 14730e43ce
10 changed files with 746 additions and 0 deletions
+107
View File
@@ -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)',
+82
View File
@@ -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,
];
+27
View File
@@ -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