diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 9c75b2ef..7cd46c9b 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -104,26 +104,80 @@ model Category { @@map("categories") } +model BlogCategory { + id String @id @default(uuid()) @db.Uuid + name String @db.VarChar(150) + slug String @unique @db.VarChar(150) + description String? @db.Text + parentId String? @map("parent_id") @db.Uuid + imageUrl String? @map("image_url") @db.Text + order Int @default(0) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() + + parent BlogCategory? @relation("BlogSubCategories", fields: [parentId], references: [id], onDelete: Cascade) + children BlogCategory[] @relation("BlogSubCategories") + blogs Blog[] + + @@map("blog_categories") +} + +model BlogTag { + id String @id @default(uuid()) @db.Uuid + name String @unique @db.VarChar(100) + slug String @unique @db.VarChar(100) + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + + blogs Blog[] + + @@map("blog_tags") +} + model Blog { - id String @id @default(uuid()) @db.Uuid - title String @db.VarChar(200) - slug String @unique @db.VarChar(200) - content String @db.Text - authorId String @map("author_id") @db.Uuid - imageUrl String? @map("image_url") @db.Text - metaTitle String? @map("meta_title") @db.VarChar(200) - metaDescription String? @map("meta_description") @db.Text - keywords String? @db.Text - isPublished Boolean @default(true) @map("is_published") - viewCount Int @default(0) @map("view_count") - showOnHome Boolean @default(false) @map("show_on_home") - homeDisplayMode String @default("selected") @map("home_display_mode") @db.VarChar(30) - createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() - updatedAt DateTime @default(now()) @map("updated_at") @db.Timestamptz() + id String @id @default(uuid()) @db.Uuid + title String @db.VarChar(200) + slug String @unique @db.VarChar(200) + content String @db.Text + excerpt String? @db.Text + authorId String @map("author_id") @db.Uuid + categoryId String? @map("category_id") @db.Uuid + imageUrl String? @map("image_url") @db.Text + imageAlt String? @map("image_alt") @db.VarChar(255) + imageCaption String? @map("image_caption") @db.Text + metaTitle String? @map("meta_title") @db.VarChar(200) + metaDescription String? @map("meta_description") @db.Text + keywords String? @db.Text + focusKeywords String? @map("focus_keywords") @db.Text + canonicalUrl String? @map("canonical_url") @db.Text + noIndex Boolean @default(false) @map("no_index") + noFollow Boolean @default(false) @map("no_follow") + schemaType String @default("BlogPosting") @map("schema_type") @db.VarChar(50) + ogTitle String? @map("og_title") @db.VarChar(200) + ogDescription String? @map("og_description") @db.Text + ogImage String? @map("og_image") @db.Text + status String @default("PUBLISHED") @db.VarChar(20) // DRAFT, PUBLISHED, SCHEDULED, ARCHIVED + isPublished Boolean @default(true) @map("is_published") + publishedAt DateTime? @map("published_at") @db.Timestamptz() + readingTime Int @default(3) @map("reading_time") + featured Boolean @default(false) + allowComments Boolean @default(true) @map("allow_comments") + viewCount Int @default(0) @map("view_count") + showOnHome Boolean @default(false) @map("show_on_home") + homeDisplayMode String @default("selected") @map("home_display_mode") @db.VarChar(30) + relatedProductIds String[] @default([]) @map("related_product_ids") + relatedBlogIds String[] @default([]) @map("related_blog_ids") + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz() + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz() author User @relation(fields: [authorId], references: [id]) + category BlogCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull) + tags BlogTag[] comments BlogComment[] + @@index([categoryId]) + @@index([status]) + @@index([publishedAt]) + @@index([featured]) @@map("blogs") } diff --git a/backend/src/admin/blogs.controller.ts b/backend/src/admin/blogs.controller.ts index 9fe205b9..e10da4b9 100644 --- a/backend/src/admin/blogs.controller.ts +++ b/backend/src/admin/blogs.controller.ts @@ -34,14 +34,84 @@ export class BlogsController { @ApiQuery({ name: 'page', required: false }) @ApiQuery({ name: 'limit', required: false }) @ApiQuery({ name: 'search', required: false }) - async getBlogs(@Query() query: PaginationDto) { + @ApiQuery({ name: 'status', required: false }) + @ApiQuery({ name: 'categoryId', required: false }) + async getBlogs( + @Query() query: PaginationDto & { status?: string; categoryId?: string; tagId?: string }, + ) { return this.blogsService.getBlogs(query); } + @Get('authors') + @ApiOperation({ summary: 'لیست کاربران برای انتخاب به عنوان نویسنده' }) + async getAuthors() { + const data = await this.blogsService.getAuthors(); + return { success: true, data }; + } + + @Get('categories') + @ApiOperation({ summary: 'لیست دسته‌بندی‌های وبلاگ' }) + async getBlogCategories() { + const data = await this.blogsService.getBlogCategories(); + return { success: true, data }; + } + + @Post('categories') + @ApiOperation({ summary: 'ایجاد دسته‌بندی جدید برای وبلاگ' }) + async createBlogCategory(@Body() body: Prisma.BlogCategoryCreateInput) { + const data = await this.blogsService.createBlogCategory(body); + return { success: true, data }; + } + + @Put('categories/:id') + @ApiOperation({ summary: 'ویرایش دسته‌بندی وبلاگ' }) + async updateBlogCategory( + @Param('id') id: string, + @Body() body: Prisma.BlogCategoryUpdateInput, + ) { + const data = await this.blogsService.updateBlogCategory(id, body); + return { success: true, data }; + } + + @Delete('categories/:id') + @ApiOperation({ summary: 'حذف دسته‌بندی وبلاگ' }) + async deleteBlogCategory(@Param('id') id: string) { + await this.blogsService.deleteBlogCategory(id); + return { success: true }; + } + + @Get('tags') + @ApiOperation({ summary: 'لیست تگ‌های وبلاگ' }) + async getBlogTags() { + const data = await this.blogsService.getBlogTags(); + return { success: true, data }; + } + + @Post('tags') + @ApiOperation({ summary: 'ایجاد تگ جدید برای وبلاگ' }) + async createBlogTag(@Body() body: { name: string; slug?: string }) { + const data = await this.blogsService.createBlogTag(body); + return { success: true, data }; + } + + @Delete('tags/:id') + @ApiOperation({ summary: 'حذف تگ وبلاگ' }) + async deleteBlogTag(@Param('id') id: string) { + await this.blogsService.deleteBlogTag(id); + return { success: true }; + } + + @Get(':id') + @ApiOperation({ summary: 'دریافت مشخصات یک مقاله' }) + async getBlogById(@Param('id') id: string) { + const data = await this.blogsService.getBlogById(id); + return { success: true, data }; + } + @Post() @ApiOperation({ summary: 'ایجاد مقاله جدید' }) async createBlog( - @Body() body: Prisma.BlogCreateWithoutAuthorInput, + @Body() body: any, @Request() req: { user: { id: string } }, ) { const data = await this.blogsService.createBlog(body, req.user.id); @@ -52,7 +122,7 @@ export class BlogsController { @ApiOperation({ summary: 'ویرایش مقاله' }) async updateBlog( @Param('id') id: string, - @Body() body: Prisma.BlogUpdateInput, + @Body() body: any, ) { const data = await this.blogsService.updateBlog(id, body); return { success: true, data }; diff --git a/backend/src/admin/blogs.service.ts b/backend/src/admin/blogs.service.ts index 739c503e..1183cc81 100644 --- a/backend/src/admin/blogs.service.ts +++ b/backend/src/admin/blogs.service.ts @@ -7,14 +7,28 @@ import { PaginationDto } from '../common/dto/pagination.dto'; export class BlogsService { constructor(private prisma: PrismaService) {} - async getBlogs(query: PaginationDto) { + async getBlogs(query: PaginationDto & { status?: string; categoryId?: string; tagId?: string }) { const page = Number(query.page) || 1; const limit = Number(query.limit) || 10; const skip = (page - 1) * limit; - const where: Prisma.BlogWhereInput = query.search - ? { title: { contains: query.search, mode: 'insensitive' } } - : {}; + const where: Prisma.BlogWhereInput = {}; + + if (query.search) { + where.OR = [ + { title: { contains: query.search, mode: 'insensitive' } }, + { excerpt: { contains: query.search, mode: 'insensitive' } }, + { slug: { contains: query.search, mode: 'insensitive' } }, + ]; + } + + if (query.status) { + where.status = query.status; + } + + if (query.categoryId) { + where.categoryId = query.categoryId; + } const [data, total] = await Promise.all([ this.prisma.blog.findMany({ @@ -23,7 +37,9 @@ export class BlogsService { take: limit, orderBy: { createdAt: 'desc' }, include: { - author: { select: { firstName: true, lastName: true } }, + author: { select: { id: true, firstName: true, lastName: true, email: true } }, + category: { select: { id: true, name: true, slug: true } }, + tags: { select: { id: true, name: true, slug: true } }, _count: { select: { comments: true } }, }, }), @@ -36,24 +52,124 @@ export class BlogsService { total, page, limit, - lastPage: Math.ceil(total / limit), + lastPage: Math.ceil(total / limit) || 1, }, }; } - async createBlog( - data: Prisma.BlogCreateWithoutAuthorInput, - authorId: string, - ) { + async getBlogById(id: string) { + const blog = await this.prisma.blog.findUnique({ + where: { id }, + include: { + author: { select: { id: true, firstName: true, lastName: true } }, + category: true, + tags: true, + }, + }); + if (!blog) throw new NotFoundException('Blog not found'); + return blog; + } + + async createBlog(data: any, currentUserId: string) { + const { + tags, + tagNames, + categoryId, + authorId, + publishedAt, + readingTime, + ...rest + } = data; + + // Connect or create tags + const tagConnectOrCreate = []; + if (Array.isArray(tagNames) && tagNames.length > 0) { + for (const tName of tagNames) { + const trimmed = String(tName).trim(); + if (trimmed) { + const slug = trimmed.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, ''); + tagConnectOrCreate.push({ + where: { name: trimmed }, + create: { name: trimmed, slug: slug || `tag-${Date.now()}` }, + }); + } + } + } + + const targetAuthorId = authorId || currentUserId; + + const createPayload: Prisma.BlogCreateInput = { + ...rest, + readingTime: readingTime ? Number(readingTime) : 3, + publishedAt: publishedAt ? new Date(publishedAt) : (rest.status === 'PUBLISHED' ? new Date() : null), + author: { connect: { id: targetAuthorId } }, + ...(categoryId ? { category: { connect: { id: categoryId } } } : {}), + ...(tagConnectOrCreate.length > 0 ? { tags: { connectOrCreate: tagConnectOrCreate } } : {}), + }; + return this.prisma.blog.create({ - data: { ...data, author: { connect: { id: authorId } } }, + data: createPayload, + include: { + author: { select: { firstName: true, lastName: true } }, + category: true, + tags: true, + }, }); } - async updateBlog(id: string, data: Prisma.BlogUpdateInput) { + async updateBlog(id: string, data: any) { const blog = await this.prisma.blog.findUnique({ where: { id } }); if (!blog) throw new NotFoundException('Blog not found'); - return this.prisma.blog.update({ where: { id }, data }); + + const { + tags, + tagNames, + categoryId, + authorId, + publishedAt, + readingTime, + ...rest + } = data; + + const updatePayload: Prisma.BlogUpdateInput = { + ...rest, + ...(readingTime !== undefined ? { readingTime: Number(readingTime) } : {}), + ...(publishedAt !== undefined ? { publishedAt: publishedAt ? new Date(publishedAt) : null } : {}), + ...(authorId ? { author: { connect: { id: authorId } } } : {}), + ...(categoryId !== undefined + ? categoryId + ? { category: { connect: { id: categoryId } } } + : { category: { disconnect: true } } + : {}), + }; + + if (Array.isArray(tagNames)) { + const tagConnectOrCreate = []; + for (const tName of tagNames) { + const trimmed = String(tName).trim(); + if (trimmed) { + const slug = trimmed.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, ''); + tagConnectOrCreate.push({ + where: { name: trimmed }, + create: { name: trimmed, slug: slug || `tag-${Date.now()}` }, + }); + } + } + updatePayload.tags = { + set: [], // clear previous relations + connectOrCreate: tagConnectOrCreate, + }; + } + + return this.prisma.blog.update({ + where: { id }, + data: updatePayload, + include: { + author: { select: { firstName: true, lastName: true } }, + category: true, + tags: true, + }, + }); } async deleteBlog(id: string) { @@ -62,6 +178,59 @@ export class BlogsService { return this.prisma.blog.delete({ where: { id } }); } + // Authors (Users who can write) + async getAuthors() { + return this.prisma.user.findMany({ + select: { id: true, firstName: true, lastName: true, email: true, role: true }, + orderBy: { firstName: 'asc' }, + }); + } + + // Blog Categories Management + async getBlogCategories() { + return this.prisma.blogCategory.findMany({ + orderBy: { order: 'asc' }, + include: { + parent: true, + children: true, + _count: { select: { blogs: true } }, + }, + }); + } + + async createBlogCategory(data: Prisma.BlogCategoryCreateInput) { + return this.prisma.blogCategory.create({ data }); + } + + async updateBlogCategory(id: string, data: Prisma.BlogCategoryUpdateInput) { + return this.prisma.blogCategory.update({ where: { id }, data }); + } + + async deleteBlogCategory(id: string) { + return this.prisma.blogCategory.delete({ where: { id } }); + } + + // Blog Tags Management + async getBlogTags() { + return this.prisma.blogTag.findMany({ + orderBy: { createdAt: 'desc' }, + include: { + _count: { select: { blogs: true } }, + }, + }); + } + + async createBlogTag(data: { name: string; slug?: string }) { + const slug = data.slug || data.name.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\u0600-\u06FF-]+/g, ''); + return this.prisma.blogTag.create({ + data: { name: data.name, slug: slug || `tag-${Date.now()}` }, + }); + } + + async deleteBlogTag(id: string) { + return this.prisma.blogTag.delete({ where: { id } }); + } + // Blog Comments Management async getComments(query: { page?: number; @@ -93,7 +262,7 @@ export class BlogsService { return { data, - meta: { total, page, limit, lastPage: Math.ceil(total / limit) }, + meta: { total, page, limit, lastPage: Math.ceil(total / limit) || 1 }, }; } diff --git a/backend/src/blogs/blogs.controller.ts b/backend/src/blogs/blogs.controller.ts index 1ab47889..77527512 100644 --- a/backend/src/blogs/blogs.controller.ts +++ b/backend/src/blogs/blogs.controller.ts @@ -37,6 +37,18 @@ export class BlogsController { return this.blogsService.findAll(query); } + @Get('categories') + @ApiOperation({ summary: 'دریافت لیست دسته‌بندی‌های وبلاگ' }) + findCategories() { + return this.blogsService.getCategories(); + } + + @Get('tags') + @ApiOperation({ summary: 'دریافت لیست تگ‌های وبلاگ' }) + findTags() { + return this.blogsService.getTags(); + } + @Get('homepage') @ApiOperation({ summary: 'دریافت مقالات برای نمایش در صفحه اصلی' }) @ApiOkResponse({ description: 'مقالات انتخاب شده برای صفحه اصلی' }) diff --git a/backend/src/blogs/blogs.service.ts b/backend/src/blogs/blogs.service.ts index eb30fb92..fa88fa27 100644 --- a/backend/src/blogs/blogs.service.ts +++ b/backend/src/blogs/blogs.service.ts @@ -3,41 +3,83 @@ import { Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; import { PaginationDto } from '../common/dto/pagination.dto'; +export interface BlogFilterDto extends PaginationDto { + categorySlug?: string; + tagSlug?: string; + featured?: boolean | string; +} + @Injectable() export class BlogsService { constructor(private prisma: PrismaService) {} - async findAll(filters: PaginationDto) { + async findAll(filters: BlogFilterDto) { const { search, page = 1, limit = 10, - sortBy = 'createdAt', + sortBy = 'publishedAt', sortOrder = 'desc', + categorySlug, + tagSlug, + featured, } = filters; - const whereClause: Prisma.BlogWhereInput = { isPublished: true }; + const now = new Date(); + const whereClause: Prisma.BlogWhereInput = { + isPublished: true, + status: 'PUBLISHED', + OR: [ + { publishedAt: null }, + { publishedAt: { lte: now } }, + ], + }; + if (search) { - whereClause.OR = [ - { title: { contains: search, mode: 'insensitive' } }, - { content: { contains: search, mode: 'insensitive' } }, + whereClause.AND = [ + { + OR: [ + { title: { contains: search, mode: 'insensitive' } }, + { excerpt: { contains: search, mode: 'insensitive' } }, + { content: { contains: search, mode: 'insensitive' } }, + { keywords: { contains: search, mode: 'insensitive' } }, + ], + }, ]; } - const skip = (page - 1) * limit; + if (categorySlug) { + whereClause.category = { slug: categorySlug }; + } + + if (tagSlug) { + whereClause.tags = { some: { slug: tagSlug } }; + } + + if (featured !== undefined && featured !== '') { + whereClause.featured = String(featured) === 'true'; + } + + const skip = (Number(page) - 1) * Number(limit); const [data, total] = await Promise.all([ this.prisma.blog.findMany({ where: whereClause, skip, - take: limit, - orderBy: { [sortBy]: sortOrder }, + take: Number(limit), + orderBy: { [sortBy === 'createdAt' ? 'createdAt' : 'publishedAt']: sortOrder }, include: { author: { select: { firstName: true, lastName: true }, }, + category: { + select: { id: true, name: true, slug: true }, + }, + tags: { + select: { id: true, name: true, slug: true }, + }, _count: { - select: { comments: true }, + select: { comments: { where: { status: 'APPROVED' } } }, }, }, }), @@ -48,22 +90,31 @@ export class BlogsService { data, meta: { total, - page, - lastPage: Math.ceil(total / limit), - limit, + page: Number(page), + lastPage: Math.ceil(total / Number(limit)) || 1, + limit: Number(limit), }, }; } async findHomepage() { + const now = new Date(); + const baseWhere: Prisma.BlogWhereInput = { + isPublished: true, + status: 'PUBLISHED', + OR: [{ publishedAt: null }, { publishedAt: { lte: now } }], + }; + // Find blogs that have showOnHome = true (selected mode) const selectedBlogs = await this.prisma.blog.findMany({ - where: { isPublished: true, showOnHome: true }, - take: 3, - orderBy: { createdAt: 'desc' }, + where: { ...baseWhere, showOnHome: true }, + take: 4, + orderBy: { publishedAt: 'desc' }, include: { author: { select: { firstName: true, lastName: true } }, - _count: { select: { comments: true } }, + category: { select: { id: true, name: true, slug: true } }, + tags: { select: { id: true, name: true, slug: true } }, + _count: { select: { comments: { where: { status: 'APPROVED' } } } }, }, }); @@ -71,14 +122,16 @@ export class BlogsService { return { mode: 'selected', blogs: selectedBlogs }; } - // Fallback: return newest 3 published blogs + // Fallback: return newest published blogs const newestBlogs = await this.prisma.blog.findMany({ - where: { isPublished: true }, - take: 3, - orderBy: { createdAt: 'desc' }, + where: baseWhere, + take: 4, + orderBy: { publishedAt: 'desc' }, include: { author: { select: { firstName: true, lastName: true } }, - _count: { select: { comments: true } }, + category: { select: { id: true, name: true, slug: true } }, + tags: { select: { id: true, name: true, slug: true } }, + _count: { select: { comments: { where: { status: 'APPROVED' } } } }, }, }); @@ -86,14 +139,21 @@ export class BlogsService { } async findOneBySlug(slug: string) { + const now = new Date(); const blog = await this.prisma.blog.findUnique({ - where: { slug, isPublished: true }, + where: { slug }, include: { author: { select: { firstName: true, lastName: true }, }, + category: { + select: { id: true, name: true, slug: true }, + }, + tags: { + select: { id: true, name: true, slug: true }, + }, _count: { - select: { comments: true }, + select: { comments: { where: { status: 'APPROVED' } } }, }, }, }); @@ -102,25 +162,105 @@ export class BlogsService { throw new NotFoundException('مقاله یافت نشد'); } - // Increment view count + // Fetch related products if any + let relatedProducts: any[] = []; + if (blog.relatedProductIds && blog.relatedProductIds.length > 0) { + relatedProducts = await this.prisma.product.findMany({ + where: { id: { in: blog.relatedProductIds } }, + select: { + id: true, + nameFa: true, + slug: true, + priceValue: true, + priceDisplay: true, + imageUrl: true, + categorySlug: true, + unit: true, + }, + }); + } + + // Fetch related blogs if any or fallback to same category + let relatedBlogs: any[] = []; + if (blog.relatedBlogIds && blog.relatedBlogIds.length > 0) { + relatedBlogs = await this.prisma.blog.findMany({ + where: { id: { in: blog.relatedBlogIds }, isPublished: true, status: 'PUBLISHED' }, + select: { + id: true, + title: true, + slug: true, + imageUrl: true, + readingTime: true, + publishedAt: true, + createdAt: true, + category: { select: { name: true, slug: true } }, + }, + }); + } else if (blog.categoryId) { + relatedBlogs = await this.prisma.blog.findMany({ + where: { + categoryId: blog.categoryId, + id: { not: blog.id }, + isPublished: true, + status: 'PUBLISHED', + }, + take: 3, + select: { + id: true, + title: true, + slug: true, + imageUrl: true, + readingTime: true, + publishedAt: true, + createdAt: true, + category: { select: { name: true, slug: true } }, + }, + }); + } + + // Increment view count asynchronously await this.prisma.blog.update({ where: { id: blog.id }, data: { viewCount: { increment: 1 } }, - }); + }).catch(() => null); - return { ...blog, viewCount: blog.viewCount + 1 }; + return { + ...blog, + viewCount: blog.viewCount + 1, + relatedProducts, + relatedBlogs, + }; + } + + async getCategories() { + return this.prisma.blogCategory.findMany({ + orderBy: { order: 'asc' }, + include: { + children: true, + _count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } }, + }, + }); + } + + async getTags() { + return this.prisma.blogTag.findMany({ + orderBy: { createdAt: 'desc' }, + include: { + _count: { select: { blogs: { where: { isPublished: true, status: 'PUBLISHED' } } } }, + }, + }); } async findCommentsBySlug(slug: string) { const blog = await this.prisma.blog.findUnique({ - where: { slug, isPublished: true }, - select: { id: true }, + where: { slug }, + select: { id: true, allowComments: true }, }); if (!blog) throw new NotFoundException('مقاله یافت نشد'); return this.prisma.blogComment.findMany({ where: { blogId: blog.id, status: 'APPROVED' }, - orderBy: { createdAt: 'asc' }, + orderBy: { createdAt: 'desc' }, }); } @@ -129,10 +269,13 @@ export class BlogsService { data: { userName: string; content: string; userId?: string }, ) { const blog = await this.prisma.blog.findUnique({ - where: { slug, isPublished: true }, - select: { id: true }, + where: { slug }, + select: { id: true, allowComments: true }, }); if (!blog) throw new NotFoundException('مقاله یافت نشد'); + if (!blog.allowComments) { + throw new NotFoundException('ارسال دیدگاه برای این مقاله غیرفعال است'); + } return this.prisma.blogComment.create({ data: { diff --git a/frontend/admin-panel/src/components/ui/RichTextEditor.tsx b/frontend/admin-panel/src/components/ui/RichTextEditor.tsx index ef01056c..6261e71f 100644 --- a/frontend/admin-panel/src/components/ui/RichTextEditor.tsx +++ b/frontend/admin-panel/src/components/ui/RichTextEditor.tsx @@ -6,6 +6,7 @@ import { Heading1, Heading2, Heading3, + Heading4, List, ListOrdered, Link as LinkIcon, @@ -18,19 +19,29 @@ import { Redo, Code, RemoveFormatting, + Image as ImageIcon, + Video, + Music, + Table as TableIcon, + Quote, + Minus, + Maximize2, + Minimize2, } from 'lucide-react'; +import MediaSelector from './MediaSelector'; interface RichTextEditorProps { value: string; onChange: (html: string) => void; placeholder?: string; className?: string; + minHeight?: string; } const PRESET_COLORS = [ { label: 'سیاه / پیش‌فرض', value: '#111827' }, { label: 'خاکستری', value: '#4b5563' }, - { label: 'آبی کنینا', value: '#1d4ed8' }, + { label: 'آبی کنینا', value: '#0052cc' }, { label: 'بنفش اختصاصی', value: '#7c3aed' }, { label: 'سبز درمانی', value: '#059669' }, { label: 'قرمز هشدار', value: '#dc2626' }, @@ -54,27 +65,42 @@ interface ActiveStates { isH1: boolean; isH2: boolean; isH3: boolean; + isH4: boolean; isP: boolean; isUL: boolean; isOL: boolean; + isBlockquote: boolean; align: 'right' | 'center' | 'left' | 'justify'; } export default function RichTextEditor({ value, onChange, - placeholder, + placeholder = 'محتوای مقاله یا متن خود را اینجا بنویسید...', className = '', + minHeight = 'min-h-[300px]', }: RichTextEditorProps) { const editorRef = useRef(null); const isTypingRef = useRef(false); const isMountedRef = useRef(false); const [isCodeMode, setIsCodeMode] = useState(false); + const [isFullscreen, setIsFullscreen] = useState(false); const [showColorPicker, setShowColorPicker] = useState(false); const [showBgColorPicker, setShowBgColorPicker] = useState(false); const [customColor, setCustomColor] = useState('#111827'); const [customBgColor, setCustomBgColor] = useState('#fef08a'); + // Media selector modal state + const [mediaModalOpen, setMediaModalOpen] = useState(false); + const [mediaTargetType, setMediaTargetType] = useState<'image' | 'video' | 'audio'>('image'); + const savedSelectionRef = useRef(null); + + // Inline Image Alt Modal + const [showImagePrompt, setShowImagePrompt] = useState(false); + const [pendingImageUrl, setPendingImageUrl] = useState(''); + const [imageAlt, setImageAlt] = useState(''); + const [imageCaption, setImageCaption] = useState(''); + const [activeStates, setActiveStates] = useState({ isBold: false, isItalic: false, @@ -82,12 +108,30 @@ export default function RichTextEditor({ isH1: false, isH2: false, isH3: false, + isH4: false, isP: false, isUL: false, isOL: false, + isBlockquote: false, align: 'right', }); + // Save selection before opening modal + const saveSelection = () => { + const sel = window.getSelection(); + if (sel && sel.rangeCount > 0) { + savedSelectionRef.current = sel.getRangeAt(0).cloneRange(); + } + }; + + const restoreSelection = () => { + const sel = window.getSelection(); + if (sel && savedSelectionRef.current) { + sel.removeAllRanges(); + sel.addRange(savedSelectionRef.current); + } + }; + // Query formatting states on cursor/selection change const updateActiveStates = useCallback(() => { if (!editorRef.current || isCodeMode) return; @@ -98,11 +142,11 @@ export default function RichTextEditor({ const isUnderline = doc.queryCommandState ? doc.queryCommandState('underline') : false; const isUL = doc.queryCommandState ? doc.queryCommandState('insertUnorderedList') : false; const isOL = doc.queryCommandState ? doc.queryCommandState('insertOrderedList') : false; - + let block = (doc.queryCommandValue ? doc.queryCommandValue('formatBlock') : '') || ''; block = block.toLowerCase().replace(/[<>]/g, ''); - // Check parent tag if queryCommandValue is ambiguous + // Check parent tag const selection = window.getSelection(); let parentTag = ''; if (selection && selection.rangeCount > 0) { @@ -112,7 +156,7 @@ export default function RichTextEditor({ } while (node && node !== editorRef.current) { const tag = (node as HTMLElement).tagName?.toLowerCase(); - if (['h1', 'h2', 'h3', 'p', 'ul', 'ol'].includes(tag)) { + if (['h1', 'h2', 'h3', 'h4', 'p', 'ul', 'ol', 'blockquote'].includes(tag)) { parentTag = tag; break; } @@ -129,7 +173,9 @@ export default function RichTextEditor({ isH1: activeBlock === 'h1', isH2: activeBlock === 'h2', isH3: activeBlock === 'h3', - isP: activeBlock === 'p' || (!['h1', 'h2', 'h3'].includes(activeBlock) && !isUL && !isOL), + isH4: activeBlock === 'h4', + isBlockquote: activeBlock === 'blockquote', + isP: activeBlock === 'p' || (!['h1', 'h2', 'h3', 'h4', 'blockquote'].includes(activeBlock) && !isUL && !isOL), isUL, isOL, align: doc.queryCommandState && doc.queryCommandState('justifyCenter') @@ -139,7 +185,7 @@ export default function RichTextEditor({ : 'right', }); } catch { - // Ignored if document commands aren't ready + // Ignored } }, [isCodeMode]); @@ -169,18 +215,14 @@ export default function RichTextEditor({ setTimeout(updateActiveStates, 20); }; - // Robust formatBlock handler for H1, H2, H3, P - const setBlockTag = (tagName: 'h1' | 'h2' | 'h3' | 'p') => { + const setBlockTag = (tagName: 'h1' | 'h2' | 'h3' | 'h4' | 'p' | 'blockquote') => { if (isCodeMode) return; editorRef.current?.focus(); - - // Cross-browser formatBlock const blockValue = `<${tagName}>`; const success = document.execCommand('formatBlock', false, blockValue); if (!success) { document.execCommand('formatBlock', false, tagName); } - if (editorRef.current) { onChange(editorRef.current.innerHTML); } @@ -195,6 +237,97 @@ export default function RichTextEditor({ } }; + const handleInsertHorizontalRule = () => { + if (isCodeMode) return; + exec('insertHorizontalRule'); + }; + + const handleInsertTable = () => { + if (isCodeMode) return; + const rows = 3; + const cols = 3; + let tableHtml = ''; + for (let c = 0; c < cols; c++) { + tableHtml += ``; + } + tableHtml += ''; + for (let r = 0; r < rows; r++) { + tableHtml += ''; + for (let c = 0; c < cols; c++) { + tableHtml += ''; + } + tableHtml += ''; + } + tableHtml += '
عنوان ${c + 1}
داده


'; + + editorRef.current?.focus(); + document.execCommand('insertHTML', false, tableHtml); + if (editorRef.current) { + onChange(editorRef.current.innerHTML); + } + }; + + const openMediaModal = (type: 'image' | 'video' | 'audio') => { + saveSelection(); + setMediaTargetType(type); + setMediaModalOpen(true); + }; + + const handleMediaSelect = (url: string) => { + setMediaModalOpen(false); + restoreSelection(); + + if (mediaTargetType === 'image') { + setPendingImageUrl(url); + setImageAlt(''); + setImageCaption(''); + setShowImagePrompt(true); + } else if (mediaTargetType === 'video') { + const videoHtml = ` +
+ +
+


+ `; + editorRef.current?.focus(); + document.execCommand('insertHTML', false, videoHtml); + if (editorRef.current) onChange(editorRef.current.innerHTML); + } else if (mediaTargetType === 'audio') { + const audioHtml = ` +
+ + 🎵 فایل صوتی / پادکست + + +
+


+ `; + editorRef.current?.focus(); + document.execCommand('insertHTML', false, audioHtml); + if (editorRef.current) onChange(editorRef.current.innerHTML); + } + }; + + const confirmInsertImage = () => { + if (!pendingImageUrl) return; + const figureHtml = ` +
+ ${imageAlt.replace(/ + ${imageCaption ? `
${imageCaption}
` : ''} +
+


+ `; + editorRef.current?.focus(); + document.execCommand('insertHTML', false, figureHtml); + if (editorRef.current) onChange(editorRef.current.innerHTML); + setShowImagePrompt(false); + setPendingImageUrl(''); + }; + const handleInput = () => { if (editorRef.current) { isTypingRef.current = true; @@ -212,21 +345,26 @@ export default function RichTextEditor({ }; return ( -
+
{/* Toolbar */} -
+
+ {/* Headings */}
+
- {/* Basic Formats (Bold, Italic, Underline) */} + {/* Basic Formats */}
@@ -294,11 +444,9 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('italic')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.isItalic - ? 'bg-purple-600 text-white shadow-xs' - : 'text-gray-700 hover:bg-gray-100' + activeStates.isItalic ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-700 hover:bg-gray-100' }`} - title="ایتالیک (کج)" + title="مورب (Italic)" > @@ -307,20 +455,29 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('underline')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.isUnderline - ? 'bg-purple-600 text-white shadow-xs' - : 'text-gray-700 hover:bg-gray-100' + activeStates.isUnderline ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-700 hover:bg-gray-100' }`} - title="خط زیرین (Underline)" + title="زیرخط (Underline)" > + @@ -333,9 +490,7 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('justifyRight')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.align === 'right' - ? 'bg-purple-50 text-purple-700 font-bold' - : 'text-gray-700 hover:bg-gray-100' + activeStates.align === 'right' ? 'bg-purple-50 text-purple-700 font-bold' : 'text-gray-700 hover:bg-gray-100' }`} title="راست‌چین" > @@ -346,9 +501,7 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('justifyCenter')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.align === 'center' - ? 'bg-purple-50 text-purple-700 font-bold' - : 'text-gray-700 hover:bg-gray-100' + activeStates.align === 'center' ? 'bg-purple-50 text-purple-700 font-bold' : 'text-gray-700 hover:bg-gray-100' }`} title="وسط‌چین" > @@ -359,9 +512,7 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('justifyLeft')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.align === 'left' - ? 'bg-purple-50 text-purple-700 font-bold' - : 'text-gray-700 hover:bg-gray-100' + activeStates.align === 'left' ? 'bg-purple-50 text-purple-700 font-bold' : 'text-gray-700 hover:bg-gray-100' }`} title="چپ‌چین" > @@ -376,11 +527,9 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('insertUnorderedList')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.isUL - ? 'bg-purple-600 text-white shadow-xs' - : 'text-gray-700 hover:bg-gray-100' + activeStates.isUL ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-700 hover:bg-gray-100' }`} - title="لیست بالت‌دار (نقطه‌ای)" + title="لیست نقطه‌ای" > @@ -389,11 +538,9 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('insertOrderedList')} className={`p-1.5 rounded-lg transition-all cursor-pointer disabled:opacity-40 ${ - activeStates.isOL - ? 'bg-purple-600 text-white shadow-xs' - : 'text-gray-700 hover:bg-gray-100' + activeStates.isOL ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-700 hover:bg-gray-100' }`} - title="لیست شماره‌دار" + title="لیست عددی" > @@ -406,9 +553,61 @@ export default function RichTextEditor({ > + +
- {/* Text Color Picker & Custom HEX */} + {/* Inline Media Insert Buttons (Image, Video, Audio) */} +
+ + + +
+ + {/* Text Color Picker */}
-
- {/* Background Color Picker & Custom HEX */} + {/* Background Color Picker */}
-
- {/* HTML Code View vs Visual */} -
+ {/* View Mode & Fullscreen */} +
+ + -
- {/* Undo / Redo */} -
@@ -581,7 +780,7 @@ export default function RichTextEditor({ disabled={isCodeMode} onClick={() => exec('redo')} className="p-1.5 hover:bg-gray-200 disabled:opacity-40 rounded-lg transition-colors cursor-pointer" - title="حرکت به جلو (Redo)" + title="Redo" > @@ -594,7 +793,7 @@ export default function RichTextEditor({ value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder="کد HTML را اینجا وارد یا ویرایش کنید..." - className="w-full p-4 min-h-[140px] max-h-[350px] font-mono text-xs text-emerald-400 bg-slate-950 outline-none resize-y leading-relaxed" + className={`w-full p-4 ${minHeight} ${isFullscreen ? 'flex-1' : 'max-h-[500px]'} font-mono text-xs text-emerald-400 bg-slate-950 outline-none resize-y leading-relaxed`} dir="ltr" spellCheck={false} /> @@ -609,10 +808,79 @@ export default function RichTextEditor({ onClick={updateActiveStates} onFocus={updateActiveStates} data-placeholder={placeholder} - className="p-4 min-h-[140px] max-h-[350px] overflow-y-auto outline-none text-sm leading-relaxed text-gray-800 font-vazir empty:before:content-[attr(data-placeholder)] empty:before:text-gray-400 [&_h1]:text-2xl [&_h1]:font-black [&_h1]:my-2.5 [&_h1]:text-gray-900 [&_h2]:text-xl [&_h2]:font-bold [&_h2]:my-2 [&_h2]:text-gray-900 [&_h3]:text-lg [&_h3]:font-bold [&_h3]:my-1.5 [&_h3]:text-gray-900 [&_p]:my-1 [&_p]:leading-relaxed [&_ul]:list-disc [&_ul]:ms-6 [&_ul]:my-2 [&_ol]:list-decimal [&_ol]:ms-6 [&_ol]:my-2 [&_a]:text-blue-600 [&_a]:underline" + className={`p-5 ${minHeight} ${isFullscreen ? 'flex-1 overflow-y-auto' : 'max-h-[500px] overflow-y-auto'} outline-none text-sm leading-loose text-gray-800 font-vazir empty:before:content-[attr(data-placeholder)] empty:before:text-gray-400 [&_h1]:text-2xl [&_h1]:font-black [&_h1]:my-4 [&_h1]:text-gray-900 [&_h2]:text-xl [&_h2]:font-bold [&_h2]:my-3.5 [&_h2]:text-gray-900 [&_h3]:text-lg [&_h3]:font-bold [&_h3]:my-3 [&_h3]:text-gray-900 [&_h4]:text-base [&_h4]:font-bold [&_h4]:my-2 [&_h4]:text-gray-800 [&_p]:my-2 [&_p]:leading-loose [&_ul]:list-disc [&_ul]:ms-6 [&_ul]:my-3 [&_ol]:list-decimal [&_ol]:ms-6 [&_ol]:my-3 [&_blockquote]:border-r-4 [&_blockquote]:border-purple-600 [&_blockquote]:pr-4 [&_blockquote]:py-2 [&_blockquote]:my-4 [&_blockquote]:bg-purple-50/50 [&_blockquote]:rounded-l-xl [&_blockquote]:italic [&_blockquote]:text-gray-700 [&_a]:text-blue-600 [&_a]:underline [&_table]:border-collapse [&_table]:w-full [&_table]:my-4 [&_table_td]:border [&_table_td]:p-2.5 [&_table_th]:border [&_table_th]:p-2.5 [&_hr]:my-6 [&_hr]:border-gray-200`} dir="rtl" /> )} + + {/* Media Selector Modal */} + setMediaModalOpen(false)} + onSelect={handleMediaSelect} + /> + + {/* Inline Image Alt & Caption Prompt Modal */} + {showImagePrompt && ( +
+
+
+
+ +
+
+

تنظیمات تصویر درون متن

+

متن جایگزین (Alt برای سئو) و زیرنویس عکس را مشخص کنید

+
+
+ +
+ preview +
+ +
+
+ + setImageAlt(e.target.value)} + placeholder="مثال: عکس تشویقی و مکمل غذایی سگ کنینا" + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none" + /> +
+
+ + setImageCaption(e.target.value)} + placeholder="توضیحات تکمیلی زیر تصویر..." + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none" + /> +
+
+ +
+ + +
+
+
+ )}
); } + diff --git a/frontend/admin-panel/src/pages/Blogs.tsx b/frontend/admin-panel/src/pages/Blogs.tsx index b6b0cd4b..854f2915 100644 --- a/frontend/admin-panel/src/pages/Blogs.tsx +++ b/frontend/admin-panel/src/pages/Blogs.tsx @@ -1,5 +1,30 @@ import { useState, useEffect, useCallback } from 'react'; -import { Search, Plus, Edit2, Trash2, FileText, Image as ImageIcon, CheckCircle2, XCircle } from 'lucide-react'; +import { + Search, + Plus, + Edit2, + Trash2, + FileText, + Image as ImageIcon, + CheckCircle2, + XCircle, + Eye, + Clock, + Tag, + FolderTree, + Calendar, + Globe, + Share2, + MessageSquare, + Sparkles, + Layers, + X, + ExternalLink, + ShoppingBag, + HelpCircle, + Pin, + Send, +} from 'lucide-react'; import { toast } from 'react-hot-toast'; import api, { BASE_DOMAIN } from '../services/api'; import Spinner from '../components/ui/Spinner'; @@ -8,48 +33,131 @@ import MediaSelector from '../components/ui/MediaSelector'; import ConfirmModal from '../components/ui/ConfirmModal'; import Button from '../components/ui/Button'; import Modal from '../components/ui/Modal'; - - - +import RichTextEditor from '../components/ui/RichTextEditor'; import { useSearchParams } from 'react-router-dom'; +export interface BlogCategory { + id: string; + name: string; + slug: string; + parentId?: string | null; + children?: BlogCategory[]; + parent?: BlogCategory | null; +} + +export interface BlogTag { + id: string; + name: string; + slug: string; +} + +export interface AuthorUser { + id: string; + firstName: string; + lastName: string; + email?: string; + role?: string; +} + +export interface ProductSimple { + id: string; + nameFa: string; + slug: string; + imageUrl?: string; + priceValue?: number; +} + export interface BlogPost { - author?: { - firstName?: string; - lastName?: string; - }; id: string; title: string; slug: string; content: string; - isPublished: boolean; + excerpt?: string; + authorId?: string; + author?: { + id?: string; + firstName?: string; + lastName?: string; + email?: string; + }; + categoryId?: string | null; + category?: BlogCategory | null; + tags?: BlogTag[]; + imageUrl?: string; + imageAlt?: string; + imageCaption?: string; metaTitle?: string; metaDescription?: string; keywords?: string; - imageUrl?: string; + canonicalUrl?: string; + ogTitle?: string; + ogDescription?: string; + ogImage?: string; + status: 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED'; + isPublished: boolean; + publishedAt?: string | null; + readingTime: number; + featured: boolean; + allowComments: boolean; + viewCount: number; + showOnHome: boolean; + relatedProductIds: string[]; + relatedBlogIds: string[]; createdAt?: string; + updatedAt?: string; + _count?: { + comments: number; + }; } export default function Blogs() { const [searchParams, setSearchParams] = useSearchParams(); const [blogs, setBlogs] = useState([]); + const [categories, setCategories] = useState([]); + const [tagsList, setTagsList] = useState([]); + const [authors, setAuthors] = useState([]); + const [allProducts, setAllProducts] = useState([]); + const [isLoading, setIsLoading] = useState(true); const [search, setSearch] = useState(() => searchParams.get('search') || ''); + const [statusFilter, setStatusFilter] = useState(() => searchParams.get('status') || 'ALL'); + const [categoryFilter, setCategoryFilter] = useState(() => searchParams.get('categoryId') || 'ALL'); const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1); const [totalPages, setTotalPages] = useState(1); const limit = 10; + // Active Tab inside Blog Form Modal + const [activeFormTab, setActiveFormTab] = useState<'content' | 'media' | 'seo' | 'relations' | 'publishing'>('content'); + + // Modals state const [isModalOpen, setIsModalOpen] = useState(false); + const [isLivePreviewOpen, setIsLivePreviewOpen] = useState(false); const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false); + const [mediaSelectTarget, setMediaSelectTarget] = useState<'featured' | 'ogImage'>('featured'); const [editingBlog, setEditingBlog] = useState(null); const [deleteTargetId, setDeleteTargetId] = useState(null); + // Category & Tag Management Modal + const [isCatTagModalOpen, setIsCatTagModalOpen] = useState(false); + const [newCatName, setNewCatName] = useState(''); + const [newCatSlug, setNewCatSlug] = useState(''); + const [newCatParentId, setNewCatParentId] = useState(''); + const [newTagName, setNewTagName] = useState(''); + + // Tag Input in Edit Form + const [currentTagInput, setCurrentTagInput] = useState(''); + + // Auto-slug manual override flag + const [isSlugManuallyEdited, setIsSlugManuallyEdited] = useState(false); + const updateUrlParams = (paramsObj: Record) => { const current = Object.fromEntries(searchParams.entries()); const merged = { ...current, ...paramsObj }; const cleaned: Record = {}; Object.entries(merged).forEach(([k, v]) => { - if (v !== undefined && v !== null && String(v).trim() !== '') cleaned[k] = String(v); + if (v !== undefined && v !== null && String(v).trim() !== '' && String(v) !== 'ALL') { + cleaned[k] = String(v); + } }); setSearchParams(cleaned, { replace: true }); }; @@ -58,32 +166,144 @@ export default function Blogs() { title: '', slug: '', content: '', - isPublished: true, + excerpt: '', + authorId: '', + categoryId: '', + tagNames: [] as string[], + imageUrl: '', + imageAlt: '', + imageCaption: '', metaTitle: '', metaDescription: '', keywords: '', - imageUrl: '' + focusKeywords: '', + canonicalUrl: '', + noIndex: false, + noFollow: false, + schemaType: 'BlogPosting', + ogTitle: '', + ogDescription: '', + ogImage: '', + status: 'PUBLISHED' as 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED', + isPublished: true, + publishedAt: '', + readingTime: 3, + featured: false, + allowComments: true, + showOnHome: false, + relatedProductIds: [] as string[], + relatedBlogIds: [] as string[], }); + // Calculate reading time automatically based on word count + const calculateReadingTime = (htmlContent: string) => { + const textOnly = htmlContent.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); + const wordCount = textOnly ? textOnly.split(' ').length : 0; + const wordsPerMinute = 200; + const minutes = Math.max(1, Math.ceil(wordCount / wordsPerMinute)); + return minutes; + }; + + // Auto-generate slug from title + const generateSlug = (text: string) => { + return text + .trim() + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^\w\u0600-\u06FF-]+/g, '') + .substring(0, 180); + }; + + const handleTitleChange = (newTitle: string) => { + setFormData((prev) => { + const updated = { ...prev, title: newTitle }; + if (!isSlugManuallyEdited && (!editingBlog || !prev.slug)) { + updated.slug = generateSlug(newTitle); + } + return updated; + }); + }; + + const handleContentChange = (newContent: string) => { + setFormData((prev) => ({ + ...prev, + content: newContent, + readingTime: calculateReadingTime(newContent), + })); + }; + const openModal = (blog: BlogPost | null = null) => { + setActiveFormTab('content'); + setIsSlugManuallyEdited(false); if (blog) { setEditingBlog(blog); updateUrlParams({ modal: 'edit', blogId: blog.id }); setFormData({ title: blog.title, slug: blog.slug, - content: blog.content, - isPublished: blog.isPublished, + content: blog.content || '', + excerpt: blog.excerpt || '', + authorId: blog.authorId || (blog.author?.id || ''), + categoryId: blog.categoryId || '', + tagNames: blog.tags ? blog.tags.map((t) => t.name) : [], + imageUrl: blog.imageUrl || '', + imageAlt: blog.imageAlt || '', + imageCaption: blog.imageCaption || '', metaTitle: blog.metaTitle || '', metaDescription: blog.metaDescription || '', keywords: blog.keywords || '', - imageUrl: blog.imageUrl || '' + focusKeywords: (blog as any).focusKeywords || '', + canonicalUrl: blog.canonicalUrl || '', + noIndex: Boolean((blog as any).noIndex), + noFollow: Boolean((blog as any).noFollow), + schemaType: (blog as any).schemaType || 'BlogPosting', + ogTitle: blog.ogTitle || '', + ogDescription: blog.ogDescription || '', + ogImage: blog.ogImage || '', + status: blog.status || (blog.isPublished ? 'PUBLISHED' : 'DRAFT'), + isPublished: blog.isPublished !== false, + publishedAt: blog.publishedAt ? new Date(blog.publishedAt).toISOString().slice(0, 16) : '', + readingTime: blog.readingTime || calculateReadingTime(blog.content || ''), + featured: Boolean(blog.featured), + allowComments: blog.allowComments !== false, + showOnHome: Boolean(blog.showOnHome), + relatedProductIds: blog.relatedProductIds || [], + relatedBlogIds: blog.relatedBlogIds || [], }); } else { setEditingBlog(null); updateUrlParams({ modal: 'create', blogId: undefined }); setFormData({ - title: '', slug: '', content: '', isPublished: true, metaTitle: '', metaDescription: '', keywords: '', imageUrl: '' + title: '', + slug: '', + content: '', + excerpt: '', + authorId: authors[0]?.id || '', + categoryId: '', + tagNames: [], + imageUrl: '', + imageAlt: '', + imageCaption: '', + metaTitle: '', + metaDescription: '', + keywords: '', + focusKeywords: '', + canonicalUrl: '', + noIndex: false, + noFollow: false, + schemaType: 'BlogPosting', + ogTitle: '', + ogDescription: '', + ogImage: '', + status: 'PUBLISHED', + isPublished: true, + publishedAt: new Date().toISOString().slice(0, 16), + readingTime: 3, + featured: false, + allowComments: true, + showOnHome: false, + relatedProductIds: [], + relatedBlogIds: [], }); } setIsModalOpen(true); @@ -94,10 +314,40 @@ export default function Blogs() { updateUrlParams({ modal: undefined, blogId: undefined }); }; + const fetchAuxiliaryData = useCallback(async () => { + try { + const [catsRes, tagsRes, authorsRes, prodsRes] = await Promise.allSettled([ + api.get('/admin/blogs/categories'), + api.get('/admin/blogs/tags'), + api.get('/admin/blogs/authors'), + api.get('/admin/products', { params: { limit: 100 } }), + ]); + + if (catsRes.status === 'fulfilled' && catsRes.value.data?.data) { + setCategories(catsRes.value.data.data); + } + if (tagsRes.status === 'fulfilled' && tagsRes.value.data?.data) { + setTagsList(tagsRes.value.data.data); + } + if (authorsRes.status === 'fulfilled' && authorsRes.value.data?.data) { + setAuthors(authorsRes.value.data.data); + } + if (prodsRes.status === 'fulfilled' && prodsRes.value.data?.data) { + setAllProducts(prodsRes.value.data.data); + } + } catch (error) { + console.error('Failed to load auxiliary blog data', error); + } + }, []); + const fetchBlogs = useCallback(async () => { try { setIsLoading(true); - const res = await api.get('/admin/blogs', { params: { page, limit, search } }); + const params: any = { page, limit, search }; + if (statusFilter !== 'ALL') params.status = statusFilter; + if (categoryFilter !== 'ALL') params.categoryId = categoryFilter; + + const res = await api.get('/admin/blogs', { params }); if (res.data?.data) { const blogList: BlogPost[] = res.data.data; setBlogs(blogList); @@ -114,30 +364,66 @@ export default function Blogs() { } } catch (err) { console.error(err); + toast.error('خطا در دریافت لیست مقالات'); } finally { setIsLoading(false); } - }, [page, search, searchParams]); + }, [page, search, statusFilter, categoryFilter, searchParams]); + + useEffect(() => { + fetchAuxiliaryData(); + }, [fetchAuxiliaryData]); useEffect(() => { const timer = setTimeout(() => { fetchBlogs(); - }, 500); + }, 400); return () => clearTimeout(timer); }, [fetchBlogs]); + // Tag helper + const addTag = (tagText: string) => { + const trimmed = tagText.trim().replace(/^#/, ''); + if (trimmed && !formData.tagNames.includes(trimmed)) { + setFormData((prev) => ({ ...prev, tagNames: [...prev.tagNames, trimmed] })); + } + setCurrentTagInput(''); + }; + + const removeTag = (tagToRemove: string) => { + setFormData((prev) => ({ + ...prev, + tagNames: prev.tagNames.filter((t) => t !== tagToRemove), + })); + }; + const handleSave = async (e: React.FormEvent) => { e.preventDefault(); + if (!formData.title.trim()) { + toast.error('عنوان مقاله نمی‌تواند خالی باشد'); + return; + } + if (!formData.slug.trim()) { + toast.error('اسلاگ (Slug) مقاله الزامی است'); + return; + } + try { + const payload = { + ...formData, + isPublished: formData.status === 'PUBLISHED', + }; + if (editingBlog) { - await api.put(`/admin/blogs/${editingBlog.id}`, formData); - toast.success('مقاله با موفقیت ویرایش شد'); + await api.put(`/admin/blogs/${editingBlog.id}`, payload); + toast.success('مقاله با موفقیت ویرایش و بروزرسانی شد'); } else { - await api.post('/admin/blogs', formData); + await api.post('/admin/blogs', payload); toast.success('مقاله جدید با موفقیت ذخیره شد'); } closeModal(); fetchBlogs(); + fetchAuxiliaryData(); } catch (error) { console.error('Save failed', error); toast.error('خطا در ذخیره مقاله'); @@ -158,87 +444,264 @@ export default function Blogs() { } }; + // Quick Category creation + const handleCreateCategory = async (e: React.FormEvent) => { + e.preventDefault(); + if (!newCatName.trim()) return; + try { + const slug = newCatSlug.trim() || generateSlug(newCatName); + await api.post('/admin/blogs/categories', { + name: newCatName.trim(), + slug, + ...(newCatParentId ? { parent: { connect: { id: newCatParentId } } } : {}), + }); + toast.success('دسته‌بندی جدید ایجاد شد'); + setNewCatName(''); + setNewCatSlug(''); + setNewCatParentId(''); + fetchAuxiliaryData(); + } catch { + toast.error('خطا در ایجاد دسته‌بندی'); + } + }; + // Quick Tag creation + const handleCreateTag = async (e: React.FormEvent) => { + e.preventDefault(); + if (!newTagName.trim()) return; + try { + await api.post('/admin/blogs/tags', { name: newTagName.trim() }); + toast.success('برچسب جدید ایجاد شد'); + setNewTagName(''); + fetchAuxiliaryData(); + } catch { + toast.error('خطا در ایجاد تگ'); + } + }; + + // Helper status badge + const renderStatusBadge = (status: string, isPublished: boolean) => { + switch (status) { + case 'PUBLISHED': + return ( + + + منتشر شده + + ); + case 'SCHEDULED': + return ( + + + زمان‌بندی شده + + ); + case 'ARCHIVED': + return ( + + + بایگانی + + ); + case 'DRAFT': + default: + return ( + + + پیش‌نویس + + ); + } + }; return ( -
-
+
+ {/* Header Bar */} +
-

- - وبلاگ و مقالات +

+
+ +
+ مدیریت جامع وبلاگ و دانشنامه سلامت

-

مدیریت محتوای آموزشی و مقالات علمی سایت

+

+ سیستم انتشار مقالات علمی، ادیتور پیشرفته چندرسانه‌ای، مدیریت دسته‌بندی و سئو +

+

+
+ +
-
-
-
- + {/* Filter Bar */} +
+
+ { setSearch(e.target.value); setPage(1); }} - className="w-full pl-4 pr-12 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none transition-all" + onChange={(e) => { + setSearch(e.target.value); + setPage(1); + }} + className="w-full pl-4 pr-11 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 text-xs sm:text-sm outline-none" />
+ +
+ + + +
-
+ {/* Main Table */} +
- + - - - - - + + + + + + + {isLoading ? ( - + + + ) : blogs.length === 0 ? ( - + + + ) : ( blogs.map((blog) => ( - + - - - + + + + + - )) )}
تصویرعنوان مقالهنویسندهوضعیت انتشارعملیاتتصویرعنوان و خلاصه مقالهدسته‌بندی و تگ‌هانویسندهزمان مطالعهوضعیتعملیات
+ +
هیچ مقاله‌ای یافت نشد
+ هیچ مقاله‌ای یافت نشد. +
{blog.imageUrl ? ( - blog + {blog.imageAlt ) : ( -
- +
+
)}
{blog.title}{(blog.author?.firstName && blog.author?.lastName) ? `${blog.author.firstName} ${blog.author.lastName}` : 'نامشخص'} - {blog.isPublished ? ( - منتشر شده - ) : ( - پیش‌نویس - )} -
+ {blog.featured && ( + + + ویژه + + )} + {blog.title} +
+

+ {blog.excerpt || 'بدون چکیده'} +

+ + /{blog.slug} + +
+ {blog.category ? ( + + {blog.category.name} + + ) : ( + دسته‌بندی نشده + )} +
+ {blog.tags?.slice(0, 2).map((t) => ( + + #{t.name} + + ))} +
+
+ {blog.author?.firstName ? `${blog.author.firstName} ${blog.author.lastName || ''}` : 'نامشخص'} + +
+ + {blog.readingTime || 3} دقیقه +
+ + {blog.viewCount || 0} بازدید + +
{renderStatusBadge(blog.status, blog.isPublished)} +
+ {!isLoading && totalPages > 1 && (
@@ -263,110 +727,962 @@ export default function Blogs() { )}
+ {/* Main Blog Create/Edit Modal */} {isModalOpen && ( - + + پیش‌نمایش زنده مقاله + - +
+ + +
} >
-
-
-
- - setFormData({ ...formData, title: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" /> -
-
- - setFormData({ ...formData, slug: e.target.value })} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-mono text-sm" /> -
-
+ {/* Form Tabs */} +
+ {[ + { id: 'content', label: '۱. محتوا و متن', icon: FileText }, + { id: 'media', label: '۲. تصویر شاخص و رسانه', icon: ImageIcon }, + { id: 'publishing', label: '۳. زمان‌بندی و انتشار', icon: Calendar }, + { id: 'seo', label: '۴. سئو و سوشال', icon: Globe }, + { id: 'relations', label: '۵. آیتم‌های مرتبط', icon: ShoppingBag }, + ].map((tab) => { + const Icon = tab.icon; + return ( + + ); + })} +
-
- - -
+ + {/* TAB 1: CONTENT */} + {activeFormTab === 'content' && ( +
+
+
+ + handleTitleChange(e.target.value)} + placeholder="مثال: راهنمای جامع مراقبت و تغذیه سگ‌های ژرمن شپرد" + className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-bold" + /> +
-
-
- -
- {formData.imageUrl ? ( - preview - ) : ( -
- +
+ + { + setIsSlugManuallyEdited(true); + setFormData({ ...formData, slug: e.target.value }); + }} + placeholder="german-shepherd-care-guide" + className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-mono" + /> +
+
+ + {/* Excerpt */} +
+ + + {/* TAB 2: MEDIA */} + {activeFormTab === 'media' && ( +
+
+

تصویر شاخص و اصلی مقاله (Featured Image)

+
+ {formData.imageUrl ? ( + preview + ) : ( +
+ +
+ )} +
+ + {formData.imageUrl && ( + + )} +
+
+ +
+
+ + setFormData({ ...formData, imageAlt: e.target.value })} + placeholder="توضیح کوتاه تصویر برای موتورهای جستجو..." + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none" + /> +
+
+ + setFormData({ ...formData, imageCaption: e.target.value })} + placeholder="زیرنویس نمایش داده شده زیر تصویر اصلی..." + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none" + /> +
+
-
+ )} + + {/* TAB 3: PUBLISHING WORKFLOW */} + {activeFormTab === 'publishing' && ( +
+
+
+ + +
+ +
+ + setFormData({ ...formData, publishedAt: e.target.value })} + className="w-full px-3.5 py-2 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-white font-sans" + dir="ltr" + /> +

+ در صورت تنظیم وضعیت روی "زمان‌بندی شده"، این مقاله تا رسیدن این تاریخ نمایش داده نخواهد شد. +

+
+
+ +
+ + + + + +
+
+ )} + + {/* TAB 4: ADVANCED SEO & SOCIAL */} + {activeFormTab === 'seo' && ( +
+ {/* Real-time SEO Content Analyzer */} + {(() => { + const content = formData.content || ''; + const title = formData.title || ''; + const metaTitle = formData.metaTitle || ''; + const metaDesc = formData.metaDescription || ''; + const focusKey = formData.focusKeywords ? formData.focusKeywords.toLowerCase().trim() : ''; + + const textOnly = content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); + const wordsCount = textOnly ? textOnly.split(' ').length : 0; + + const hasH1InContent = /]*>/i.test(content); + const h2Matches = (content.match(/]*>/gi) || []).length; + const h3Matches = (content.match(/]*>/gi) || []).length; + + const imgTags = content.match(/]+>/gi) || []; + const imgsCount = imgTags.length + (formData.imageUrl ? 1 : 0); + const imgsWithoutAlt = imgTags.filter(img => !/alt=["'][^"']+["']/i.test(img)).length + (!formData.imageAlt && formData.imageUrl ? 1 : 0); + + const hasInternalLinks = /href=["'](\/|https?:\/\/(www\.)?canina\.ir)[^"']*["']/i.test(content); + const hasExternalLinks = /href=["']https?:\/\/(?!(www\.)?canina\.ir)[^"']+["']/i.test(content); + + let keyDensity = 0; + let keywordFoundInTitle = false; + let keywordFoundInDesc = false; + let keywordFoundInContent = false; + + if (focusKey) { + const regex = new RegExp(focusKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'); + const occurrences = (textOnly.match(regex) || []).length; + keyDensity = wordsCount > 0 ? Number(((occurrences / wordsCount) * 100).toFixed(1)) : 0; + keywordFoundInTitle = (title + ' ' + metaTitle).toLowerCase().includes(focusKey); + keywordFoundInDesc = metaDesc.toLowerCase().includes(focusKey); + keywordFoundInContent = occurrences > 0; + } + + return ( +
+
+
+ + تحلیلگر هوشمند سئو و محتوا (Real-time SEO Analyzer) +
+ + طول کل متن: {wordsCount} کلمه + +
+ +
+ {/* Word count audit */} +
= 300 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}> + {wordsCount >= 300 ? : } + حجم محتوا: {wordsCount >= 300 ? 'عالی (بیش از ۳۰۰ کلمه)' : 'کوتاه (حداقل ۳۰۰ کلمه توصیه می‌شود)'} +
+ + {/* Headings audit */} +
0 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}> + {h2Matches > 0 ? : } + ساختار عناوین: {h2Matches} تیتر H2 و {h3Matches} تیتر H3 +
+ + {/* Image Alt audit */} +
0 && imgsWithoutAlt === 0 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}> + {imgsCount > 0 && imgsWithoutAlt === 0 ? : } + متن جایگزین (Alt): {imgsWithoutAlt === 0 ? 'همه تصاویر دارای Alt' : `${imgsWithoutAlt} تصویر بدون Alt`} +
+ + {/* Link audit */} +
+ {hasInternalLinks ? : } + لینک‌های داخلی: {hasInternalLinks ? 'موجود' : 'یافت نشد'} +
+ + {/* Focus keyword in Title & Desc */} + {focusKey ? ( + <> +
+ {keywordFoundInTitle ? : } + کلمه کلیدی در عنوان: {keywordFoundInTitle ? 'تایید' : 'یافت نشد'} +
+
= 0.5 && keyDensity <= 3 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-blue-50 border-blue-200 text-blue-800'}`}> + + چگالی کلمه کلیدی: {keyDensity}% ({keyDensity >= 0.5 && keyDensity <= 3 ? 'مطلوب' : 'متوسط'}) +
+ + ) : ( +
+ 💡 کلمه کلیدی کانونی (Focus Keyword) را در زیر وارد کنید تا آنالیز دقیق‌تر فعال شود. +
+ )} +
+
+ ); + })()} + + {/* Google SERP Preview Box */} +
+ پیش‌نمایش در نتایج جستجوی گوگل (Google SERP Preview): +
+ + https://canina.ir/blog/{formData.slug || 'slug'} + +
+ {formData.metaTitle || formData.title || 'عنوان مقاله در گوگل'} | مکمل‌های کنینا آلمان +
+

+ {formData.metaDescription || formData.excerpt || 'توضیحات متای مقاله در اینجا نمایش داده خواهد شد...'} +

+
+
+ + {/* Focus Keywords and Schema Type */} +
+
+ + setFormData({ ...formData, focusKeywords: e.target.value })} + placeholder="مثال: تغذیه سگ، مکمل مفاصل، ویتامین گربه" + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none font-bold" + /> +
+ +
+ + +
+
+ + {/* Meta Title and Canonical */} +
+
+
+ + = 50 && (formData.metaTitle || '').length <= 65) ? 'text-emerald-600 font-bold' : 'text-gray-400'}`}> + {(formData.metaTitle || '').length} / 60 + +
+ setFormData({ ...formData, metaTitle: e.target.value })} + placeholder="عنوان سئو در تب مرورگر و نتایج سرچ..." + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none" + /> +
+ +
+ + setFormData({ ...formData, canonicalUrl: e.target.value })} + placeholder="https://canina.ir/blog/custom-slug" + className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs font-mono focus:border-purple-500 outline-none" + /> +
+
+ + {/* Meta Description */} +
+
+ + = 140 && (formData.metaDescription || '').length <= 160) ? 'text-emerald-600 font-bold' : 'text-gray-400'}`}> + {(formData.metaDescription || '').length} / 160 + +
+