feat(blog): add admin endpoint for blog details and cache invalidation
- Implemented `adminDetail()` method in `BlogController` to retrieve blog posts of any status for admin editing. - Introduced `BlogCacheInvalidator` service to handle cache invalidation after blog create/update/delete actions. - Updated existing methods in `BlogController` and `RepresentationBlogController` to call cache invalidation on blog modifications. - Enhanced `BlogFormPage` and `RepresentationBlogFormPage` to utilize the new admin endpoint for fetching blog data. - Added tests for `BlogCacheInvalidator` to ensure proper functionality and error handling. - Updated documentation to reflect new API endpoint and cache invalidation behavior.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { renderWithProviders } from '@/test/utils';
|
||||
|
||||
vi.mock('@ckeditor/ckeditor5-react', () => ({ CKEditor: () => null }));
|
||||
@@ -45,3 +46,83 @@ describe('BlogFormPage — اعتبارسنجی zod (حالت ساخت)', () =>
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const BLOG_UUID = '56fd9a20-9594-4aa1-a651-346fa86720bd';
|
||||
|
||||
function renderEditPage() {
|
||||
return renderWithProviders(
|
||||
<Routes>
|
||||
<Route path="/admin/blogs/:uuid/edit" element={<BlogFormPage />} />
|
||||
</Routes>,
|
||||
{ route: `/admin/blogs/${BLOG_UUID}/edit` }
|
||||
);
|
||||
}
|
||||
|
||||
describe('BlogFormPage — حالت ویرایش', () => {
|
||||
it('پیشنویس را از اندپوینت ادمین میگیرد و فرم را پر میکند', async () => {
|
||||
get.mockImplementation((url: string) =>
|
||||
url.startsWith(`/api/v1/admin/blog/${BLOG_UUID}`)
|
||||
? Promise.resolve({
|
||||
data: {
|
||||
data: {
|
||||
uuid: BLOG_UUID,
|
||||
title: 'عنوان پیشنویس',
|
||||
body: '<p>محتوای تست</p>',
|
||||
summary: 'خلاصهٔ تست',
|
||||
status: 'draft',
|
||||
tags: ['الف', 'ب'],
|
||||
},
|
||||
},
|
||||
})
|
||||
: Promise.resolve({ data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } })
|
||||
);
|
||||
|
||||
renderEditPage();
|
||||
|
||||
expect(await screen.findByDisplayValue('عنوان پیشنویس')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('خلاصهٔ تست')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('الف, ب')).toBeInTheDocument();
|
||||
// اندپوینت عمومی (که پیشنویس را ۴۰۴ میکرد) نباید صدا زده شود
|
||||
expect(get).not.toHaveBeenCalledWith(`/api/v1/blog/${BLOG_UUID}`);
|
||||
});
|
||||
|
||||
it('خطای بارگذاری → کارت خطا بهجای فرم خالیِ قابلثبت', async () => {
|
||||
get.mockImplementation((url: string) =>
|
||||
url.startsWith(`/api/v1/admin/blog/${BLOG_UUID}`)
|
||||
? Promise.reject(new Error('مقاله یافت نشد'))
|
||||
: Promise.resolve({ data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } })
|
||||
);
|
||||
|
||||
renderEditPage();
|
||||
|
||||
expect(await screen.findByText('مقاله یافت نشد')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'بروزرسانی' })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'بازگشت به فهرست مقالات' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('مقالهٔ سراسری با faq و کلیدواژهٔ خالی بدون خطا بارگذاری میشود', async () => {
|
||||
get.mockImplementation((url: string) =>
|
||||
url.startsWith(`/api/v1/admin/blog/${BLOG_UUID}`)
|
||||
? Promise.resolve({
|
||||
data: {
|
||||
data: {
|
||||
uuid: BLOG_UUID,
|
||||
title: 'مقالهٔ سراسری',
|
||||
body: '<p>x</p>',
|
||||
status: 'draft',
|
||||
tags: [],
|
||||
faq: [],
|
||||
secondary_keywords: [],
|
||||
city: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
: Promise.resolve({ data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } })
|
||||
);
|
||||
|
||||
renderEditPage();
|
||||
|
||||
expect(await screen.findByDisplayValue('مقالهٔ سراسری')).toBeInTheDocument();
|
||||
expect(screen.getByText('سوالی افزوده نشده است.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,10 +45,13 @@ export default function BlogFormPage() {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [aiOpen, setAiOpen] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
const { data, isLoading, isError, error } = useQuery({
|
||||
queryKey: ['blog', uuid],
|
||||
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/blog/${uuid}`),
|
||||
// اندپوینت ادمین پیشنویس و آرشیو را هم برمیگرداند؛ اندپوینت عمومی فقط
|
||||
// published است و برای پیشنویس ۴۰۴ میداد → فرم خالی بدون هیچ پیام خطا.
|
||||
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/admin/blog/${uuid}`),
|
||||
enabled: isEdit,
|
||||
retry: false,
|
||||
});
|
||||
const blog = data?.data?.data;
|
||||
|
||||
@@ -59,7 +62,7 @@ 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<BlogFormData>({
|
||||
const { register, handleSubmit, control, watch, setValue, formState: { errors } } = useForm<BlogFormData>({
|
||||
resolver: zodResolver(blogFormSchema),
|
||||
defaultValues: blogDefaults(),
|
||||
values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
|
||||
@@ -88,6 +91,8 @@ export default function BlogFormPage() {
|
||||
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);
|
||||
@@ -119,6 +124,18 @@ export default function BlogFormPage() {
|
||||
);
|
||||
}
|
||||
|
||||
// فرم خالیِ قابلثبت نمایش داده نشود: کاربر باید بفهمد مقاله بارگذاری نشده.
|
||||
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
|
||||
@@ -140,18 +157,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>عنوان مقاله *</label>
|
||||
<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>خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..." className="input resize-none" />
|
||||
<label className="cp-label">خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..." className="cp-textarea resize-none" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label>محتوا *</label>
|
||||
<label className="cp-label">محتوا *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="body"
|
||||
@@ -176,7 +193,7 @@ export default function BlogFormPage() {
|
||||
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label>تصویر شاخص</label>
|
||||
<label className="cp-label">تصویر شاخص</label>
|
||||
{imageUrl ? (
|
||||
<div className="relative">
|
||||
<img src={imageUrl} alt="cover" style={{ width: '100%', height: 160, objectFit: 'cover', borderRadius: 8 }} />
|
||||
@@ -193,7 +210,7 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label>وضعیت انتشار</label>
|
||||
<label className="cp-label">وضعیت انتشار</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="status"
|
||||
@@ -208,7 +225,7 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label>شهر</label>
|
||||
<label className="cp-label">شهر</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="city_id"
|
||||
@@ -227,7 +244,7 @@ export default function BlogFormPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label>تگها (با ویرگول جدا کنید)</label>
|
||||
<label className="cp-label">تگها (با ویرگول جدا کنید)</label>
|
||||
<input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3" className="cp-input h-11" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -239,8 +256,8 @@ export default function BlogFormPage() {
|
||||
</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 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 }}>
|
||||
لغو
|
||||
|
||||
@@ -29,14 +29,15 @@ export default function RepresentationBlogFormPage() {
|
||||
});
|
||||
const cityOptions = (meQuery.data?.data?.cities ?? []).map((c) => ({ value: c.id, label: c.name }));
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
const { data, isLoading, isError, error } = useQuery({
|
||||
queryKey: ['rep-blog', uuid],
|
||||
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/representation/blog/${uuid}`),
|
||||
enabled: isEdit,
|
||||
retry: false,
|
||||
});
|
||||
const blog = data?.data?.data;
|
||||
|
||||
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<BlogFormData>({
|
||||
const { register, handleSubmit, control, formState: { errors } } = useForm<BlogFormData>({
|
||||
resolver: zodResolver(blogFormSchema),
|
||||
defaultValues: blogDefaults(),
|
||||
values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
|
||||
@@ -63,6 +64,8 @@ export default function RepresentationBlogFormPage() {
|
||||
onError: (err: Error) => toast.error(err.message),
|
||||
});
|
||||
|
||||
const saving = createMutation.isPending || updateMutation.isPending;
|
||||
|
||||
const onSubmit = (d: BlogFormData) => {
|
||||
if (!d.city_id) {
|
||||
toast.error('انتخاب شهر الزامی است');
|
||||
@@ -76,6 +79,17 @@ export default function RepresentationBlogFormPage() {
|
||||
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/representation-blogs')}>
|
||||
بازگشت به فهرست مقالات
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
@@ -88,16 +102,16 @@ export default function RepresentationBlogFormPage() {
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-5">
|
||||
<div>
|
||||
<label>عنوان مقاله *</label>
|
||||
<label className="cp-label">عنوان مقاله *</label>
|
||||
<input {...register('title')} className="cp-input h-11" placeholder="عنوان جذاب بنویسید..." />
|
||||
{errors.title && <p className="text-[var(--danger)] text-xs mt-1">{errors.title.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label>خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} className="input resize-none" />
|
||||
<label className="cp-label">خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} className="cp-textarea resize-none" />
|
||||
</div>
|
||||
<div>
|
||||
<label>محتوا *</label>
|
||||
<label className="cp-label">محتوا *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="body"
|
||||
@@ -118,7 +132,7 @@ export default function RepresentationBlogFormPage() {
|
||||
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label>شهر *</label>
|
||||
<label className="cp-label">شهر *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="city_id"
|
||||
@@ -135,7 +149,7 @@ export default function RepresentationBlogFormPage() {
|
||||
<p className="text-[12px] text-[var(--text-3)] mt-1">فقط شهرهای حوزهٔ نمایندگی شما.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label>وضعیت انتشار</label>
|
||||
<label className="cp-label">وضعیت انتشار</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="status"
|
||||
@@ -149,11 +163,11 @@ export default function RepresentationBlogFormPage() {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label>آدرس تصویر شاخص (URL)</label>
|
||||
<label className="cp-label">آدرس تصویر شاخص (URL)</label>
|
||||
<input {...register('image_url')} dir="ltr" className="cp-input h-11" placeholder="https://..." />
|
||||
</div>
|
||||
<div>
|
||||
<label>تگها (با ویرگول)</label>
|
||||
<label className="cp-label">تگها (با ویرگول)</label>
|
||||
<input {...register('tags')} dir="ltr" className="cp-input h-11" placeholder="tag1, tag2" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -164,8 +178,8 @@ export default function RepresentationBlogFormPage() {
|
||||
</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 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/representation-blogs')} className="cp-btn-secondary justify-center py-2.5" style={{ minWidth: 120 }}>لغو</button>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user