feat(blog): add representation blog management features including listing, creating, and editing blogs
This commit is contained in:
@@ -39,6 +39,8 @@ import FinancialReportPage from './pages/FinancialReportPage';
|
||||
import RepresentationSettlementPage from './pages/RepresentationSettlementPage';
|
||||
import RepresentationFinancePage from './pages/RepresentationFinancePage';
|
||||
import RepresentationProfilePage from './pages/RepresentationProfilePage';
|
||||
import RepresentationBlogsPage from './pages/RepresentationBlogsPage';
|
||||
import RepresentationBlogFormPage from './pages/RepresentationBlogFormPage';
|
||||
import DoctorProfilePage from './pages/DoctorProfilePage';
|
||||
import MyPatientsPage from './pages/MyPatientsPage';
|
||||
import MyPaymentsPage from './pages/MyPaymentsPage';
|
||||
@@ -223,6 +225,9 @@ export default function App() {
|
||||
<Route path="representation-settlement" element={<RoleRoute roles={['representation']}><RepresentationSettlementPage /></RoleRoute>} />
|
||||
<Route path="representation-finance" element={<RoleRoute roles={['representation']}><RepresentationFinancePage /></RoleRoute>} />
|
||||
<Route path="representation-profile" element={<RoleRoute roles={['representation']}><RepresentationProfilePage /></RoleRoute>} />
|
||||
<Route path="representation-blogs" element={<RoleRoute roles={['representation', 'admin']}><RepresentationBlogsPage /></RoleRoute>} />
|
||||
<Route path="representation-blogs/new" element={<RoleRoute roles={['representation', 'admin']}><RepresentationBlogFormPage /></RoleRoute>} />
|
||||
<Route path="representation-blogs/:uuid/edit" element={<RoleRoute roles={['representation', 'admin']}><RepresentationBlogFormPage /></RoleRoute>} />
|
||||
<Route path="doctors" element={<RoleRoute roles={['admin', 'representation']}><DoctorsPage /></RoleRoute>} />
|
||||
<Route path="doctor-claims" element={<RoleRoute roles={['admin']}><DoctorClaimsPage /></RoleRoute>} />
|
||||
<Route path="doctors/new" element={<RoleRoute roles={['admin', 'representation']}><DoctorFormPage /></RoleRoute>} />
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Controller, useFieldArray } from 'react-hook-form';
|
||||
import type { Control, UseFormRegister } from 'react-hook-form';
|
||||
import type { BlogFormData } from '../lib/blogForm';
|
||||
import PersianDatePicker from './ui/PersianDatePicker';
|
||||
|
||||
interface Props {
|
||||
control: Control<BlogFormData>;
|
||||
register: UseFormRegister<BlogFormData>;
|
||||
}
|
||||
|
||||
/** SEO + FAQ + scheduling fields, shared by admin and representative blog forms. */
|
||||
export default function BlogSeoFields({ control, register }: Props) {
|
||||
const { fields, append, remove } = useFieldArray({ control, name: 'faq' });
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h3 className="section-title">سئو و زمانبندی</h3>
|
||||
|
||||
<div>
|
||||
<label>عنوان متا (Meta Title)</label>
|
||||
<input {...register('meta_title')} className="cp-input h-11" placeholder="عنوان برای موتور جستجو" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label>توضیح متا (Meta Description)</label>
|
||||
<textarea {...register('meta_description')} rows={2} className="input resize-none"
|
||||
placeholder="حداکثر ۱۵۵ کاراکتر" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label>کلیدواژهٔ اصلی</label>
|
||||
<input {...register('primary_keyword')} className="cp-input h-11" />
|
||||
</div>
|
||||
<div>
|
||||
<label>کلیدواژههای فرعی (با ویرگول)</label>
|
||||
<input {...register('secondary_keywords')} className="cp-input h-11" placeholder="کلمه۱، کلمه۲" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label>لینکهای داخلی (URL با ویرگول)</label>
|
||||
<input {...register('internal_links')} dir="ltr" className="cp-input h-11" placeholder="/a, /b" />
|
||||
</div>
|
||||
<div>
|
||||
<label>لینکهای خارجی (URL با ویرگول)</label>
|
||||
<input {...register('external_links')} dir="ltr" className="cp-input h-11" placeholder="https://..." />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label>زمان مطالعه (دقیقه)</label>
|
||||
<input type="number" {...register('reading_time', { setValueAs: (v) => (v === '' || v == null ? null : Number(v)) })}
|
||||
className="cp-input h-11" min={1} />
|
||||
</div>
|
||||
<div>
|
||||
<label>زمانبندی انتشار</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="scheduled_at"
|
||||
render={({ field }) => <ScheduleField value={field.value ?? null} onChange={field.onChange} />}
|
||||
/>
|
||||
<p className="text-[12px] text-[var(--text-3)] mt-1">
|
||||
خالی = انتشار دستی. مقالهٔ نیازمند بازبینی فقط پس از تأیید پزشک منتشر میشود.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="!mb-0">سوالات متداول (FAQ)</label>
|
||||
<button type="button" className="mini-btn" onClick={() => append({ q: '', a: '' })}>
|
||||
+ افزودن سوال
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{fields.map((f, i) => (
|
||||
<div key={f.id} className="card card-pad" style={{ padding: 12 }}>
|
||||
<input {...register(`faq.${i}.q` as const)} className="cp-input h-10 mb-2" placeholder="سوال" />
|
||||
<textarea {...register(`faq.${i}.a` as const)} rows={2} className="input resize-none" placeholder="پاسخ" />
|
||||
<button type="button" className="mini-btn danger mt-2" onClick={() => remove(i)}>حذف</button>
|
||||
</div>
|
||||
))}
|
||||
{fields.length === 0 && <p className="muted">سوالی افزوده نشده است.</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Gregorian date + time → unix seconds, and back. */
|
||||
function ScheduleField({ value, onChange }: { value: number | null; onChange: (v: number | null) => void }) {
|
||||
const d = value ? new Date(value * 1000) : null;
|
||||
const dateStr = d ? d.toISOString().slice(0, 10) : '';
|
||||
const timeStr = d ? d.toTimeString().slice(0, 5) : '00:00';
|
||||
|
||||
const emit = (nextDate: string, nextTime: string) => {
|
||||
if (!nextDate) return onChange(null);
|
||||
const ms = Date.parse(`${nextDate}T${nextTime || '00:00'}:00`);
|
||||
onChange(Number.isNaN(ms) ? null : Math.floor(ms / 1000));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 items-center">
|
||||
<PersianDatePicker value={dateStr} onChange={(v) => emit(v, timeStr)} />
|
||||
<input type="time" className="cp-input h-10" style={{ width: 110 }} value={timeStr}
|
||||
onChange={(e) => emit(dateStr, e.target.value)} />
|
||||
{value && (
|
||||
<button type="button" className="mini-btn" onClick={() => onChange(null)}>پاک کردن</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -494,6 +494,16 @@ function buildSections(
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "محتوا",
|
||||
items: [
|
||||
{
|
||||
to: "/admin/representation-blogs",
|
||||
icon: DocumentTextIcon,
|
||||
label: "وبلاگ من",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "مالی",
|
||||
items: [
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
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 { toast } from 'sonner';
|
||||
import { CKEditor } from '@ckeditor/ckeditor5-react';
|
||||
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { Blog } from '../types';
|
||||
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';
|
||||
|
||||
interface RepMe { cities: { id: number; name: string }[] }
|
||||
|
||||
export default function RepresentationBlogFormPage() {
|
||||
const { uuid } = useParams<{ uuid: string }>();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const isEdit = !!uuid;
|
||||
|
||||
const meQuery = useQuery({
|
||||
queryKey: ['rep-me-cities'],
|
||||
queryFn: () => api.get<ApiResponse<RepMe>>('/api/v1/representation/me'),
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
const cityOptions = (meQuery.data?.data?.cities ?? []).map((c) => ({ value: c.id, label: c.name }));
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['rep-blog', uuid],
|
||||
queryFn: () => api.get<ApiResponse<{ data: Blog }>>(`/api/v1/representation/blog/${uuid}`),
|
||||
enabled: isEdit,
|
||||
});
|
||||
const blog = data?.data?.data;
|
||||
|
||||
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<BlogFormData>({
|
||||
resolver: zodResolver(blogFormSchema),
|
||||
defaultValues: blogDefaults(),
|
||||
values: blog ? (blogDefaults(blog) as BlogFormData) : undefined,
|
||||
});
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (d: BlogFormData) => api.post<ApiResponse<Blog>>('/api/v1/representation/blog', buildBlogPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله ذخیره شد');
|
||||
qc.invalidateQueries({ queryKey: ['rep-blogs'] });
|
||||
navigate('/admin/representation-blogs');
|
||||
},
|
||||
onError: (err: Error) => toast.error(err.message),
|
||||
});
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (d: BlogFormData) => api.patch<ApiResponse<Blog>>(`/api/v1/representation/blog/${uuid}`, buildBlogPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله بروزرسانی شد');
|
||||
qc.invalidateQueries({ queryKey: ['rep-blogs'] });
|
||||
qc.invalidateQueries({ queryKey: ['rep-blog', uuid] });
|
||||
navigate('/admin/representation-blogs');
|
||||
},
|
||||
onError: (err: Error) => toast.error(err.message),
|
||||
});
|
||||
|
||||
const onSubmit = (d: BlogFormData) => {
|
||||
if (!d.city_id) {
|
||||
toast.error('انتخاب شهر الزامی است');
|
||||
return;
|
||||
}
|
||||
if (isEdit) updateMutation.mutate(d);
|
||||
else createMutation.mutate(d);
|
||||
};
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader
|
||||
title={isEdit ? 'ویرایش مقاله' : 'نوشتن مقالهٔ جدید'}
|
||||
breadcrumbs={[{ label: 'وبلاگ من', to: '/admin/representation-blogs' }, { label: isEdit ? 'ویرایش' : 'جدید' }]}
|
||||
/>
|
||||
|
||||
<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>عنوان مقاله *</label>
|
||||
<input {...register('title')} className="cp-input h-11" placeholder="عنوان جذاب بنویسید..." />
|
||||
{errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>}
|
||||
</div>
|
||||
<div>
|
||||
<label>خلاصه</label>
|
||||
<textarea {...register('summary')} rows={2} className="input resize-none" />
|
||||
</div>
|
||||
<div>
|
||||
<label>محتوا *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="body"
|
||||
render={({ field }) => (
|
||||
<div dir="rtl" className="ck-rtl">
|
||||
<CKEditor
|
||||
editor={ClassicEditor as never}
|
||||
data={field.value ?? ''}
|
||||
onChange={(_e: unknown, editor: { getData: () => string }) => field.onChange(editor.getData())}
|
||||
config={{ licenseKey: 'GPL', language: 'fa', toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'blockQuote', 'insertTable', '|', 'undo', 'redo'] }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{errors.body && <p className="text-red-500 text-xs mt-1">{errors.body.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label>شهر *</label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="city_id"
|
||||
render={({ field }) => (
|
||||
<SearchableSelect
|
||||
options={cityOptions}
|
||||
value={field.value ?? null}
|
||||
onChange={(v) => field.onChange(v ? Number(v) : null)}
|
||||
placeholder="یکی از شهرهای حوزهٔ شما"
|
||||
isLoading={meQuery.isLoading}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<p className="text-[12px] text-[var(--text-3)] mt-1">فقط شهرهای حوزهٔ نمایندگی شما.</p>
|
||||
</div>
|
||||
<div>
|
||||
<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>آدرس تصویر شاخص (URL)</label>
|
||||
<input {...register('image_url')} dir="ltr" className="cp-input h-11" placeholder="https://..." />
|
||||
</div>
|
||||
<div>
|
||||
<label>تگها (با ویرگول)</label>
|
||||
<input {...register('tags')} dir="ltr" className="cp-input h-11" placeholder="tag1, tag2" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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/representation-blogs')} className="cp-btn-secondary justify-center py-2.5" style={{ minWidth: 120 }}>لغو</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
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 ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
|
||||
const limit = 15;
|
||||
const STATUS_LABEL: Record<string, string> = { draft: 'پیشنویس', published: 'منتشر شده', archived: 'آرشیو' };
|
||||
|
||||
export default function RepresentationBlogsPage() {
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const [page, setPage] = useState(1);
|
||||
const [deleteTarget, setDeleteTarget] = useState<Blog | null>(null);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['rep-blogs', page],
|
||||
queryFn: () => {
|
||||
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
return api.get<PaginatedResponse<Blog>>(`/api/v1/representation/blogs?${params}`);
|
||||
},
|
||||
});
|
||||
|
||||
const items = data?.data ?? [];
|
||||
const total = data?.meta?.totalRecords ?? 0;
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (b: Blog) => api.delete<ApiResponse<null>>(`/api/v1/representation/blog/${b.uuid}`),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله حذف شد');
|
||||
setDeleteTarget(null);
|
||||
qc.invalidateQueries({ queryKey: ['rep-blogs'] });
|
||||
},
|
||||
onError: (err: Error) => toast.error(err.message),
|
||||
});
|
||||
|
||||
const columns: Column<Blog>[] = [
|
||||
{ key: 'title', header: 'عنوان', render: (b) => <span className="fw-600">{b.title}</span> },
|
||||
{ key: 'status', header: 'وضعیت', render: (b) => <span className="badge gray"><span className="bdot" />{STATUS_LABEL[b.status] ?? b.status}</span> },
|
||||
{ key: 'city', header: 'شهر', render: (b) => b.city?.name ?? '—' },
|
||||
{ key: 'scheduled_at', header: 'زمانبندی', render: (b) => (b.scheduled_at ? formatDate(b.scheduled_at) : '—') },
|
||||
{ key: 'created_at', header: 'تاریخ', render: (b) => formatDate(b.created_at) },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="fade-in">
|
||||
<PageHeader
|
||||
title="وبلاگ من"
|
||||
description="مقالات مخصوص دامنه و برند شما."
|
||||
action={<button className="cp-btn-primary" onClick={() => navigate('/admin/representation-blogs/new')}>مقالهٔ جدید</button>}
|
||||
/>
|
||||
|
||||
<div className="card card-pad" style={{ marginTop: 'var(--gap)' }}>
|
||||
<DataTable<Blog>
|
||||
columns={columns}
|
||||
data={items}
|
||||
loading={isLoading}
|
||||
emptyMessage="هنوز مقالهای ننوشتهاید"
|
||||
actions={(b) => (
|
||||
<div className="row-actions">
|
||||
<button className="mini-btn" onClick={() => navigate(`/admin/representation-blogs/${b.uuid}/edit`)}>ویرایش</button>
|
||||
<button className="mini-btn danger" onClick={() => setDeleteTarget(b)}>حذف</button>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!deleteTarget}
|
||||
title="حذف مقاله"
|
||||
message={`«${deleteTarget?.title ?? ''}» حذف شود؟`}
|
||||
danger
|
||||
loading={deleteMutation.isPending}
|
||||
onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
|
||||
onCancel={() => setDeleteTarget(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -224,6 +224,7 @@ A representative (`ROLE_REPRESENTATION`) manages their own posts for their own d
|
||||
| Route | Method | Path | Permission |
|
||||
|-------|--------|------|------------|
|
||||
| list own | GET | `/api/v1/representation/blogs` | `ROLE_REPRESENTATION` (`page`,`limit`,`status`) |
|
||||
| get own | GET | `/api/v1/representation/blog/{uuid}` | `ROLE_REPRESENTATION` |
|
||||
| create | POST | `/api/v1/representation/blog` | `ROLE_REPRESENTATION` |
|
||||
| update own | PATCH | `/api/v1/representation/blog/{uuid}` | `ROLE_REPRESENTATION` |
|
||||
| delete own | DELETE | `/api/v1/representation/blog/{uuid}` | `ROLE_REPRESENTATION` |
|
||||
|
||||
@@ -87,6 +87,15 @@ class RepresentationBlogController extends BaseController
|
||||
return $this->paginated($items, $total, $page, $limit);
|
||||
}
|
||||
|
||||
#[OA\Get(path: '/api/v1/representation/blog/{uuid}', summary: "Get one of the representative's own posts", security: [['bearerAuth' => []]])]
|
||||
#[Route('/api/v1/representation/blog/{uuid}', methods: ['GET'])]
|
||||
public function detail(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$rep = $this->currentRepresentation($user);
|
||||
$blog = $this->ownedBlogOr404($uuid, $rep);
|
||||
return $this->success(['data' => $blog->toArray()]);
|
||||
}
|
||||
|
||||
#[OA\Post(path: '/api/v1/representation/blog', summary: 'Create a post owned by the representative', security: [['bearerAuth' => []]])]
|
||||
#[Route('/api/v1/representation/blog', methods: ['POST'])]
|
||||
public function create(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
|
||||
@@ -109,6 +109,25 @@ class BlogV2FieldsTest extends ApiTestCase
|
||||
$this->assertNotContains("مالB-$tag", $titles, "another rep's post leaked");
|
||||
}
|
||||
|
||||
public function testRepresentativeCanGetOwnPostButNotOthers(): void
|
||||
{
|
||||
$yasuj = $this->makeCity('یاسوج');
|
||||
$repA = $this->makeRepresentation([$yasuj]);
|
||||
$repB = $this->makeRepresentation([$yasuj]);
|
||||
|
||||
$created = $this->authJson('POST', '/api/v1/representation/blog', $repA->getUser(), [
|
||||
'title' => 'مقالهٔ A', 'body' => 'متن آزمایشی مقاله برای تست', 'city_id' => $yasuj->getId(),
|
||||
]);
|
||||
$uuid = $created['data']['data']['uuid'];
|
||||
|
||||
$own = $this->authJson('GET', "/api/v1/representation/blog/$uuid", $repA->getUser());
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertSame('مقالهٔ A', $own['data']['data']['title']);
|
||||
|
||||
$this->authJson('GET', "/api/v1/representation/blog/$uuid", $repB->getUser());
|
||||
$this->assertSame(404, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testRepresentativeCannotEditOthersPost(): void
|
||||
{
|
||||
$yasuj = $this->makeCity('یاسوج');
|
||||
|
||||
Reference in New Issue
Block a user