feat(blog): add representation blog management features including listing, creating, and editing blogs
This commit is contained in:
@@ -3,7 +3,6 @@ import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { CKEditor } from '@ckeditor/ckeditor5-react';
|
||||
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
|
||||
@@ -12,20 +11,12 @@ 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';
|
||||
|
||||
const schema = z.object({
|
||||
title: z.string().min(3, 'عنوان الزامی است'),
|
||||
summary: z.string().optional(),
|
||||
body: z.string().min(10, 'محتوا الزامی است'),
|
||||
tags: z.string().optional(),
|
||||
status: z.enum(['draft', 'published']),
|
||||
image_url: z.string().optional(),
|
||||
// null = مقاله سراسری؛ حالت دائمی است نه مقدار تنظیمنشده
|
||||
city_id: z.number().nullable().optional(),
|
||||
});
|
||||
type FormData = z.infer<typeof schema>;
|
||||
import BlogSeoFields from '../components/BlogSeoFields';
|
||||
import Modal from '../components/ui/Modal';
|
||||
|
||||
async function uploadBlogImage(file: File): Promise<string> {
|
||||
const token = useAuthStore.getState().token;
|
||||
@@ -52,14 +43,13 @@ export default function BlogFormPage() {
|
||||
const qc = useQueryClient();
|
||||
const isEdit = !!uuid;
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [aiOpen, setAiOpen] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['blog', uuid],
|
||||
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/blog/${uuid}`),
|
||||
enabled: isEdit,
|
||||
});
|
||||
|
||||
// detail endpoint is double-nested: success(['data' => $blog->toArray()])
|
||||
const blog = data?.data?.data;
|
||||
|
||||
const citiesQuery = useQuery({
|
||||
@@ -69,37 +59,16 @@ export default function BlogFormPage() {
|
||||
});
|
||||
const cityOptions = (citiesQuery.data?.data ?? []).map((c) => ({ value: c.id, label: c.name }));
|
||||
|
||||
const { register, handleSubmit, control, watch, setValue, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { status: 'draft' },
|
||||
values: blog
|
||||
? {
|
||||
title: blog.title,
|
||||
summary: blog.summary ?? '',
|
||||
body: blog.body,
|
||||
tags: blog.tags?.join(', ') ?? '',
|
||||
status: blog.status,
|
||||
image_url: blog.image_url ?? '',
|
||||
city_id: blog.city ? Number(blog.city.id) : null,
|
||||
}
|
||||
: undefined,
|
||||
const { register, handleSubmit, control, watch, setValue, formState: { errors, isSubmitting } } = useForm<BlogFormData>({
|
||||
resolver: zodResolver(blogFormSchema),
|
||||
defaultValues: blogDefaults(),
|
||||
values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
|
||||
});
|
||||
|
||||
const imageUrl = watch('image_url');
|
||||
|
||||
const buildPayload = (d: FormData) => ({
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
summary: d.summary,
|
||||
status: d.status,
|
||||
image_url: d.image_url ?? '',
|
||||
tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
|
||||
// همیشه فرستاده میشود؛ null یعنی «سراسری» و باید شهر قبلی را پاک کند
|
||||
city_id: d.city_id ?? null,
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (d: FormData) => api.post<ApiResponse<Blog>>('/api/v1/blog', buildPayload(d)),
|
||||
mutationFn: (d: BlogFormData) => api.post<ApiResponse<Blog>>('/api/v1/blog', buildBlogPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله ذخیره شد');
|
||||
qc.invalidateQueries({ queryKey: ['blogs'] });
|
||||
@@ -109,7 +78,7 @@ export default function BlogFormPage() {
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (d: FormData) => api.patch<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`, buildPayload(d)),
|
||||
mutationFn: (d: BlogFormData) => api.patch<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`, buildBlogPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله بروزرسانی شد');
|
||||
qc.invalidateQueries({ queryKey: ['blogs'] });
|
||||
@@ -119,7 +88,7 @@ export default function BlogFormPage() {
|
||||
onError: (err: Error) => toast.error(err.message),
|
||||
});
|
||||
|
||||
const onSubmit = (d: FormData) => {
|
||||
const onSubmit = (d: BlogFormData) => {
|
||||
if (isEdit) updateMutation.mutate(d);
|
||||
else createMutation.mutate(d);
|
||||
};
|
||||
@@ -159,6 +128,11 @@ export default function BlogFormPage() {
|
||||
{ label: 'بلاگ', to: '/admin/blogs' },
|
||||
{ label: isEdit ? 'ویرایش' : 'جدید' },
|
||||
]}
|
||||
action={
|
||||
<button type="button" className="cp-btn-secondary" onClick={() => setAiOpen(true)}>
|
||||
تولید با هوش مصنوعی
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="cp-card p-6">
|
||||
@@ -166,20 +140,18 @@ export default function BlogFormPage() {
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-5">
|
||||
<div>
|
||||
<label className="">عنوان مقاله *</label>
|
||||
<input {...register('title')} placeholder="عنوان جذاب بنویسید..."
|
||||
className="cp-input h-11" />
|
||||
<label>عنوان مقاله *</label>
|
||||
<input {...register('title')} placeholder="عنوان جذاب بنویسید..." className="cp-input h-11" />
|
||||
{errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..."
|
||||
className="input resize-none" />
|
||||
<label>خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..." className="input resize-none" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">محتوا *</label>
|
||||
<label>محتوا *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="body"
|
||||
@@ -188,18 +160,11 @@ export default function BlogFormPage() {
|
||||
<CKEditor
|
||||
editor={ClassicEditor as never}
|
||||
data={field.value ?? ''}
|
||||
onChange={(_evt: unknown, editor: { getData: () => string }) =>
|
||||
field.onChange(editor.getData())
|
||||
}
|
||||
onChange={(_evt: unknown, editor: { getData: () => string }) => field.onChange(editor.getData())}
|
||||
config={{
|
||||
licenseKey: 'GPL',
|
||||
language: 'fa',
|
||||
toolbar: [
|
||||
'heading', '|',
|
||||
'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|',
|
||||
'blockQuote', 'insertTable', '|',
|
||||
'undo', 'redo',
|
||||
],
|
||||
toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'blockQuote', 'insertTable', '|', 'undo', 'redo'],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -211,19 +176,16 @@ export default function BlogFormPage() {
|
||||
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label className="">تصویر شاخص</label>
|
||||
<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">
|
||||
<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' }}>
|
||||
<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>
|
||||
@@ -231,16 +193,13 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">وضعیت انتشار</label>
|
||||
<label>وضعیت انتشار</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="status"
|
||||
render={({ field }) => (
|
||||
<SearchableSelect
|
||||
options={[
|
||||
{ value: 'draft', label: 'پیشنویس' },
|
||||
{ value: 'published', label: 'منتشر شده' },
|
||||
]}
|
||||
options={[{ value: 'draft', label: 'پیشنویس' }, { value: 'published', label: 'منتشر شده' }]}
|
||||
value={field.value ?? null}
|
||||
onChange={(v) => field.onChange(v ?? 'draft')}
|
||||
/>
|
||||
@@ -249,7 +208,7 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">شهر</label>
|
||||
<label>شهر</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="city_id"
|
||||
@@ -268,25 +227,43 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">تگها (با ویرگول جدا کنید)</label>
|
||||
<input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3"
|
||||
className="cp-input h-11" />
|
||||
</div>
|
||||
|
||||
<div className="pt-4 space-y-3">
|
||||
<button type="submit" disabled={isSubmitting}
|
||||
className="cp-btn-primary w-full justify-center py-2.5">
|
||||
{isSubmitting ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
|
||||
</button>
|
||||
<button type="button" onClick={() => navigate('/admin/blogs')}
|
||||
className="cp-btn-secondary w-full justify-center py-2.5">
|
||||
لغو
|
||||
</button>
|
||||
<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={isSubmitting} className="cp-btn-primary justify-center py-2.5" style={{ minWidth: 160 }}>
|
||||
{isSubmitting ? 'در حال ذخیره...' : 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>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user