Files
clinicpro/assets/admin/pages/BlogFormPage.tsx
T
hamed 47323daa27 feat: add RichTextEditor component for rich text editing in articles
feat: create SanitizeBlogBodiesCommand to clean existing blog bodies according to current HTML sanitization policies

test: add AppointmentTreatmentSessionLinkTest to ensure appointment booking functionality works correctly with treatment session links
2026-08-08 11:40:17 +03:30

276 lines
12 KiB
TypeScript

import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import RichTextEditor from '../components/RichTextEditor';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Blog, City } from '../types';
import type { PaginatedResponse } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import { blogFormSchema, blogDefaults, buildBlogPayload } from '../lib/blogForm';
import type { BlogFormData } from '../lib/blogForm';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';
import BlogSeoFields from '../components/BlogSeoFields';
import Modal from '../components/ui/Modal';
async function uploadBlogImage(file: File): Promise<string> {
const token = useAuthStore.getState().token;
const fd = new FormData();
fd.append('file', file);
const res = await fetch('/file/upload/clinic_pro/blog/field_image', {
method: 'POST',
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
body: fd,
});
const json = await res.json().catch(() => ({}));
if (res.status === 401) {
useAuthStore.getState().logout();
window.location.replace('/admin/login');
throw new Error('نشست منقضی شده است');
}
if (!res.ok) throw new Error(json?.errors?.[0]?.message ?? 'خطا در آپلود تصویر');
return json.data.image_url as string;
}
export default function BlogFormPage() {
const { uuid } = useParams<{ uuid: string }>();
const navigate = useNavigate();
const qc = useQueryClient();
const isEdit = !!uuid;
const [uploading, setUploading] = useState(false);
const [aiOpen, setAiOpen] = useState(false);
const { data, isLoading, isError, error } = useQuery({
queryKey: ['blog', uuid],
// اندپوینت ادمین پیش‌نویس و آرشیو را هم برمی‌گرداند؛ اندپوینت عمومی فقط
// published است و برای پیش‌نویس ۴۰۴ می‌داد → فرم خالی بدون هیچ پیام خطا.
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/admin/blog/${uuid}`),
enabled: isEdit,
retry: false,
});
const blog = data?.data?.data;
const citiesQuery = useQuery({
queryKey: ['cities-select'],
queryFn: () => api.get<PaginatedResponse<City>>('/api/v1/admin/cities?limit=200'),
staleTime: 5 * 60_000,
});
const cityOptions = (citiesQuery.data?.data ?? []).map((c) => ({ value: c.id, label: c.name }));
const { register, handleSubmit, control, watch, setValue, formState: { errors } } = useForm<BlogFormData>({
resolver: zodResolver(blogFormSchema),
defaultValues: blogDefaults(),
values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
});
const imageUrl = watch('image_url');
const createMutation = useMutation({
mutationFn: (d: BlogFormData) => api.post<ApiResponse<Blog>>('/api/v1/blog', buildBlogPayload(d)),
onSuccess: () => {
toast.success('مقاله ذخیره شد');
qc.invalidateQueries({ queryKey: ['blogs'] });
navigate('/admin/blogs');
},
onError: (err: Error) => toast.error(err.message),
});
const updateMutation = useMutation({
mutationFn: (d: BlogFormData) => api.patch<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`, buildBlogPayload(d)),
onSuccess: () => {
toast.success('مقاله بروزرسانی شد');
qc.invalidateQueries({ queryKey: ['blogs'] });
qc.invalidateQueries({ queryKey: ['blog', uuid] });
navigate('/admin/blogs');
},
onError: (err: Error) => toast.error(err.message),
});
const saving = createMutation.isPending || updateMutation.isPending;
const onSubmit = (d: BlogFormData) => {
if (isEdit) updateMutation.mutate(d);
else createMutation.mutate(d);
};
const onImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
try {
const url = await uploadBlogImage(file);
setValue('image_url', url, { shouldValidate: true });
toast.success('تصویر آپلود شد');
} catch (err) {
toast.error((err as Error).message);
} finally {
setUploading(false);
e.target.value = '';
}
};
if (isEdit && isLoading) {
return (
<div className="cp-card p-6 space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="h-10 rounded-lg skeleton" />
))}
</div>
);
}
// فرم خالیِ قابل‌ثبت نمایش داده نشود: کاربر باید بفهمد مقاله بارگذاری نشده.
if (isEdit && (isError || !blog)) {
return (
<div className="cp-card p-6 text-center space-y-4">
<p className="text-[var(--danger)]">{(error as Error | null)?.message ?? 'مقاله یافت نشد'}</p>
<button type="button" className="cp-btn-secondary" onClick={() => navigate('/admin/blogs')}>
بازگشت به فهرست مقالات
</button>
</div>
);
}
return (
<div>
<PageHeader
backTo="/admin/blogs"
title={isEdit ? 'ویرایش مقاله' : 'نوشتن مقاله جدید'}
breadcrumbs={[
{ label: 'داشبورد', to: '/admin/dashboard' },
{ label: 'بلاگ', to: '/admin/blogs' },
{ label: isEdit ? 'ویرایش' : 'جدید' },
]}
action={
<button type="button" className="cp-btn-secondary" onClick={() => setAiOpen(true)}>
تولید با هوش مصنوعی
</button>
}
/>
<div className="cp-card p-6">
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-5">
<div>
<label className="cp-label">عنوان مقاله *</label>
<input {...register('title')} placeholder="عنوان جذاب بنویسید..." className="cp-input h-11" />
{errors.title && <p className="text-[var(--danger)] text-xs mt-1">{errors.title.message}</p>}
</div>
<div>
<label className="cp-label">خلاصه</label>
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..." className="cp-textarea resize-none" />
</div>
<div>
<label className="cp-label">محتوا *</label>
<Controller
control={control}
name="body"
render={({ field }) => (
<RichTextEditor value={field.value ?? ''} onChange={field.onChange} />
)}
/>
{errors.body && <p className="text-[var(--danger)] text-xs mt-1">{errors.body.message}</p>}
</div>
</div>
<div className="space-y-5">
<div>
<label className="cp-label">تصویر شاخص</label>
{imageUrl ? (
<div className="relative">
<img src={imageUrl} alt="cover" style={{ width: '100%', height: 160, objectFit: 'cover', borderRadius: 8 }} />
<button type="button" onClick={() => setValue('image_url', '', { shouldValidate: true })} className="cp-btn-secondary w-full justify-center py-2 mt-2">
حذف تصویر
</button>
</div>
) : (
<label className="cp-btn-secondary w-full justify-center py-2.5 cursor-pointer" style={{ display: 'flex' }}>
{uploading ? 'در حال آپلود...' : 'انتخاب تصویر'}
<input type="file" accept="image/*" hidden disabled={uploading} onChange={onImageSelect} />
</label>
)}
</div>
<div>
<label className="cp-label">وضعیت انتشار</label>
<Controller
control={control}
name="status"
render={({ field }) => (
<SearchableSelect
options={[{ value: 'draft', label: 'پیش‌نویس' }, { value: 'published', label: 'منتشر شده' }]}
value={field.value ?? null}
onChange={(v) => field.onChange(v ?? 'draft')}
/>
)}
/>
</div>
<div>
<label className="cp-label">شهر</label>
<Controller
control={control}
name="city_id"
render={({ field }) => (
<SearchableSelect
options={[{ value: 0, label: 'سراسری (همه شهرها)' }, ...cityOptions]}
value={field.value ?? 0}
onChange={(v) => field.onChange(v ? Number(v) : null)}
placeholder="سراسری (همه شهرها)"
/>
)}
/>
<p className="text-[12px] text-[var(--text-3)] mt-1">
مقاله سراسری روی همه دامنه‌های شهری نمایش داده می‌شود؛ مقاله شهری فقط به دامنه همان شهر نسبت داده می‌شود.
</p>
</div>
<div>
<label className="cp-label">تگ‌ها (با ویرگول جدا کنید)</label>
<input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3" className="cp-input h-11" />
</div>
</div>
</div>
{/* SEO + FAQ + scheduling — full width */}
<div className="cp-card p-5" style={{ background: 'var(--surface-2)' }}>
<BlogSeoFields control={control} register={register} />
</div>
<div className="flex gap-3">
<button type="submit" disabled={saving} className="cp-btn-primary justify-center py-2.5" style={{ minWidth: 160 }}>
{saving ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
</button>
<button type="button" onClick={() => navigate('/admin/blogs')} className="cp-btn-secondary justify-center py-2.5" style={{ minWidth: 120 }}>
لغو
</button>
</div>
</form>
</div>
<Modal open={aiOpen} title="تولید محتوا با هوش مصنوعی" size="md" onClose={() => setAiOpen(false)}>
<div className="space-y-3">
<p>
تولید خودکار مقاله توسط «پایپ‌لاین محتوای سلامت» انجام می‌شود: چند منبع معتبر خزش، به فارسی
ترجمه و سپس یک مقالهٔ اصیل و کاملاً سئو تولید می‌شود.
</p>
<p>
مقالهٔ تولیدشده به‌صورت <b>پیش‌نویس</b> و در وضعیت <b>در انتظار بازبینی</b> ثبت می‌شود و پس از
تأیید پزشک در صفحهٔ «بازبینی بلاگ» منتشر می‌گردد.
</p>
<button className="cp-btn-primary justify-center py-2" onClick={() => navigate('/admin/blog-review')}>
رفتن به صف بازبینی
</button>
</div>
</Modal>
</div>
);
}