feat: resolve doctors query error, add FAQ, testimonials, blog preview, and full menu management
Deploy Canina / deploy (push) Successful in 1m41s

This commit is contained in:
parsa aghaei committed 2026-08-19 17:20:01 +03:30
1 parent 70d58e7086
commit 2c452215c3
31 files changed
+1987 -76

No files matched your search

+75 -15
View File
@@ -31,6 +31,7 @@ model User {
paymentTransactions PaymentTransaction[]
tickets Ticket[]
reviews ProductReview[]
blogComments BlogComment[]
@@map("users")
}
@@ -114,10 +115,14 @@ model Blog {
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()
author User @relation(fields: [authorId], references: [id])
author User @relation(fields: [authorId], references: [id])
comments BlogComment[]
@@map("blogs")
}
@@ -463,20 +468,23 @@ model SmartAdvisorRule {
}
model Doctor {
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(150)
title String? @db.VarChar(150)
clinicName String? @map("clinic_name") @db.VarChar(200)
avatarUrl String? @map("avatar_url") @db.Text
bio String? @db.Text
cv String? @db.Text
phone String? @db.VarChar(50)
email String? @db.VarChar(150)
instagram String? @db.VarChar(100)
isActive Boolean @default(true) @map("is_active")
order Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(150)
title String? @db.VarChar(150)
clinicName String? @map("clinic_name") @db.VarChar(200)
avatarUrl String? @map("avatar_url") @db.Text
bio String? @db.Text
cv String? @db.Text
phone String? @db.VarChar(50)
email String? @db.VarChar(150)
instagram String? @db.VarChar(100)
quote String? @db.Text
quoteProductRef String? @map("quote_product_ref") @db.VarChar(200)
showQuoteOnHome Boolean @default(false) @map("show_quote_on_home")
isActive Boolean @default(true) @map("is_active")
order Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz()
videos Video[]
@@ -553,6 +561,7 @@ model Testimonial {
rating Int @default(5)
isFeatured Boolean @default(false) @map("is_featured")
isActive Boolean @default(true) @map("is_active")
showOnHome Boolean @default(false) @map("show_on_home")
order Int @default(0)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@ -720,3 +729,54 @@ model ProductReview {
}
model BlogComment {
id String @id @default(uuid()) @db.Uuid
blogId String @map("blog_id") @db.Uuid
userId String? @map("user_id") @db.Uuid
userName String @map("user_name") @db.VarChar(100)
content String @db.Text
status String @default("PENDING") @db.VarChar(20)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
blog Blog @relation(fields: [blogId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
@@index([blogId])
@@index([status])
@@map("blog_comments")
}
model FAQ {
id String @id @default(uuid()) @db.Uuid
question String @db.Text
answer String @db.Text
order Int @default(0)
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
@@map("faqs")
}
model MenuItem {
id String @id @default(uuid()) @db.Uuid
menuType String @map("menu_type") @db.VarChar(30)
label String @db.VarChar(150)
href String @db.VarChar(500)
parentId String? @map("parent_id") @db.Uuid
order Int @default(0)
isActive Boolean @default(true) @map("is_active")
isExternal Boolean @default(false) @map("is_external")
icon String? @db.VarChar(100)
badge String? @db.VarChar(50)
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz()
parent MenuItem? @relation("MenuChildren", fields: [parentId], references: [id])
children MenuItem[] @relation("MenuChildren")
@@index([menuType])
@@index([parentId])
@@map("menu_items")
}
+43 -4
View File
@@ -3,6 +3,7 @@ import {
Get,
Post,
Put,
Patch,
Delete,
Body,
Param,
@@ -19,7 +20,6 @@ import {
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
@ApiTags('Admin - مدیریت مقالات (بلاگ)')
@@ -31,9 +31,9 @@ export class BlogsController {
@Get()
@ApiOperation({ summary: 'لیست مقالات' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({ name: 'page', required: false })
@ApiQuery({ name: 'limit', required: false })
@ApiQuery({ name: 'search', required: false })
async getBlogs(@Query() query: PaginationDto) {
return this.blogsService.getBlogs(query);
}
@@ -64,4 +64,43 @@ export class BlogsController {
await this.blogsService.deleteBlog(id);
return { success: true };
}
// Blog Comments endpoints
@Get('comments')
@ApiOperation({ summary: 'لیست نظرات مقالات' })
@ApiQuery({
name: 'status',
required: false,
description: 'PENDING | APPROVED | REJECTED',
})
@ApiQuery({ name: 'blogId', required: false })
@ApiQuery({ name: 'page', required: false })
@ApiQuery({ name: 'limit', required: false })
async getComments(
@Query()
query: {
page?: number;
limit?: number;
status?: string;
blogId?: string;
},
) {
return this.blogsService.getComments(query);
}
@Patch('comments/:id/status')
@ApiOperation({ summary: 'تغییر وضعیت نظر (تأیید/رد)' })
async updateCommentStatus(
@Param('id') id: string,
@Body() body: { status: 'APPROVED' | 'REJECTED' },
) {
return this.blogsService.updateCommentStatus(id, body.status);
}
@Delete('comments/:id')
@ApiOperation({ summary: 'حذف نظر' })
async deleteComment(@Param('id') id: string) {
await this.blogsService.deleteComment(id);
return { success: true };
}
}
+53 -8
View File
@@ -1,18 +1,13 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class BlogQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
import { PaginationDto } from '../common/dto/pagination.dto';
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: BlogQuery = {}) {
async getBlogs(query: PaginationDto) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
@@ -27,7 +22,10 @@ export class BlogsService {
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: { author: { select: { firstName: true, lastName: true } } },
include: {
author: { select: { firstName: true, lastName: true } },
_count: { select: { comments: true } },
},
}),
this.prisma.blog.count({ where }),
]);
@@ -63,4 +61,51 @@ export class BlogsService {
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.delete({ where: { id } });
}
// Blog Comments Management
async getComments(query: {
page?: number;
limit?: number;
status?: string;
blogId?: string;
}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 20;
const skip = (page - 1) * limit;
const where: Prisma.BlogCommentWhereInput = {};
if (query.status) where.status = query.status;
if (query.blogId) where.blogId = query.blogId;
const [data, total] = await Promise.all([
this.prisma.blogComment.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: {
blog: { select: { title: true, slug: true } },
user: { select: { firstName: true, lastName: true, mobile: true } },
},
}),
this.prisma.blogComment.count({ where }),
]);
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
};
}
async updateCommentStatus(id: string, status: 'APPROVED' | 'REJECTED') {
const comment = await this.prisma.blogComment.findUnique({ where: { id } });
if (!comment) throw new NotFoundException('Comment not found');
return this.prisma.blogComment.update({ where: { id }, data: { status } });
}
async deleteComment(id: string) {
const comment = await this.prisma.blogComment.findUnique({ where: { id } });
if (!comment) throw new NotFoundException('Comment not found');
return this.prisma.blogComment.delete({ where: { id } });
}
}
+4
View File
@@ -31,6 +31,8 @@ import { PaymentModule } from './payment/payment.module';
import { TicketsModule } from './tickets/tickets.module';
import { ReviewsModule } from './reviews/reviews.module';
import { DoctorsModule } from './doctors/doctors.module';
import { FaqModule } from './faq/faq.module';
import { MenuModule } from './menu/menu.module';
import { Request, Response, NextFunction } from 'express';
@@ -70,6 +72,8 @@ import { Request, Response, NextFunction } from 'express';
IngredientsModule,
PrescriptionsModule,
B2BModule,
FaqModule,
MenuModule,
],
controllers: [MetricsController],
providers: [
+41 -1
View File
@@ -1,4 +1,14 @@
import { Controller, Get, Param, HttpStatus, Query } from '@nestjs/common';
import {
Controller,
Get,
Post,
Param,
Body,
HttpStatus,
Query,
UseGuards,
Request,
} from '@nestjs/common';
import { BlogsService } from './blogs.service';
import {
ApiTags,
@@ -6,8 +16,10 @@ import {
ApiResponse,
ApiOkResponse,
ApiNotFoundResponse,
ApiBearerAuth,
} from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
@ApiTags('Blogs - مجله سلامت')
@Controller('blogs')
@@ -25,6 +37,13 @@ export class BlogsController {
return this.blogsService.findAll(query);
}
@Get('homepage')
@ApiOperation({ summary: 'دریافت مقالات برای نمایش در صفحه اصلی' })
@ApiOkResponse({ description: 'مقالات انتخاب شده برای صفحه اصلی' })
findHomepage() {
return this.blogsService.findHomepage();
}
@Get(':slug')
@ApiOperation({ summary: 'دریافت مقاله با اسلاگ (Slug)' })
@ApiOkResponse({ description: 'اطلاعات کامل مقاله' })
@@ -32,4 +51,25 @@ export class BlogsController {
findOne(@Param('slug') slug: string) {
return this.blogsService.findOneBySlug(slug);
}
@Get(':slug/comments')
@ApiOperation({ summary: 'دریافت نظرات تأیید شده مقاله' })
findComments(@Param('slug') slug: string) {
return this.blogsService.findCommentsBySlug(slug);
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Post(':slug/comments')
@ApiOperation({ summary: 'ارسال نظر برای مقاله (نیازمند ورود)' })
addComment(
@Param('slug') slug: string,
@Body() body: { userName: string; content: string },
@Request() req: any,
) {
return this.blogsService.addComment(slug, {
...body,
userId: req.user?.id,
});
}
}
+77 -1
View File
@@ -36,6 +36,9 @@ export class BlogsService {
author: {
select: { firstName: true, lastName: true },
},
_count: {
select: { comments: true },
},
},
}),
this.prisma.blog.count({ where: whereClause }),
@@ -52,6 +55,36 @@ export class BlogsService {
};
}
async findHomepage() {
// 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' },
include: {
author: { select: { firstName: true, lastName: true } },
_count: { select: { comments: true } },
},
});
if (selectedBlogs.length > 0) {
return { mode: 'selected', blogs: selectedBlogs };
}
// Fallback: return newest 3 published blogs
const newestBlogs = await this.prisma.blog.findMany({
where: { isPublished: true },
take: 3,
orderBy: { createdAt: 'desc' },
include: {
author: { select: { firstName: true, lastName: true } },
_count: { select: { comments: true } },
},
});
return { mode: 'newest', blogs: newestBlogs };
}
async findOneBySlug(slug: string) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
@@ -59,6 +92,9 @@ export class BlogsService {
author: {
select: { firstName: true, lastName: true },
},
_count: {
select: { comments: true },
},
},
});
@@ -66,6 +102,46 @@ export class BlogsService {
throw new NotFoundException('مقاله یافت نشد');
}
return blog;
// Increment view count
await this.prisma.blog.update({
where: { id: blog.id },
data: { viewCount: { increment: 1 } },
});
return { ...blog, viewCount: blog.viewCount + 1 };
}
async findCommentsBySlug(slug: string) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
select: { id: true },
});
if (!blog) throw new NotFoundException('مقاله یافت نشد');
return this.prisma.blogComment.findMany({
where: { blogId: blog.id, status: 'APPROVED' },
orderBy: { createdAt: 'asc' },
});
}
async addComment(
slug: string,
data: { userName: string; content: string; userId?: string },
) {
const blog = await this.prisma.blog.findUnique({
where: { slug, isPublished: true },
select: { id: true },
});
if (!blog) throw new NotFoundException('مقاله یافت نشد');
return this.prisma.blogComment.create({
data: {
blogId: blog.id,
userName: data.userName,
content: data.content,
userId: data.userId,
status: 'PENDING',
},
});
}
}
+3 -2
View File
@@ -10,7 +10,8 @@ import {
UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { DoctorsService, DoctorQuery } from './doctors.service';
import { DoctorsService } from './doctors.service';
import { DoctorQueryDto } from './dto/doctor-query.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { Prisma } from '@prisma/client';
@@ -21,7 +22,7 @@ export class DoctorsController {
@Get()
@ApiOperation({ summary: 'Get list of all doctors / specialists' })
findAll(@Query() query: DoctorQuery) {
findAll(@Query() query: DoctorQueryDto) {
return this.doctorsService.findAll(query);
}
+4 -8
View File
@@ -1,26 +1,22 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { DoctorQueryDto } from './dto/doctor-query.dto';
export class DoctorQuery {
page?: number | string;
limit?: number | string;
search?: string;
activeOnly?: boolean | string;
}
export { DoctorQueryDto as DoctorQuery };
@Injectable()
export class DoctorsService {
constructor(private readonly prisma: PrismaService) {}
async findAll(query: DoctorQuery = {}) {
async findAll(query: DoctorQueryDto = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 50;
const skip = (page - 1) * limit;
const where: Prisma.DoctorWhereInput = {};
if (query.activeOnly === 'true' || query.activeOnly === true) {
if (query.activeOnly === true) {
where.isActive = true;
}
@@ -0,0 +1,38 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsInt, Min, IsString, IsBoolean } from 'class-validator';
import { Type, Transform } from 'class-transformer';
export class DoctorQueryDto {
@ApiPropertyOptional({ description: 'شماره صفحه', minimum: 1, default: 1 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
page?: number = 1;
@ApiPropertyOptional({
description: 'تعداد آیتم در هر صفحه',
minimum: 1,
default: 50,
})
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
limit?: number = 50;
@ApiPropertyOptional({ description: 'عبارت جستجو' })
@IsOptional()
@IsString()
search?: string;
@ApiPropertyOptional({ description: 'فقط پزشکان فعال' })
@IsOptional()
@Transform(({ value }) => {
if (value === 'true' || value === true) return true;
if (value === 'false' || value === false) return false;
return undefined;
})
@IsBoolean()
activeOnly?: boolean;
}
+89
View File
@@ -0,0 +1,89 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
UseGuards,
} from '@nestjs/common';
import { FaqService } from './faq.service';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
@ApiTags('FAQ - سوالات متداول')
@Controller('faq')
export class FaqController {
constructor(private readonly faqService: FaqService) {}
@Get()
@ApiOperation({ summary: 'دریافت سوالات متداول فعال برای صفحه اصلی' })
findActive() {
return this.faqService.findActive();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('admin')
@ApiOperation({ summary: 'دریافت تمام سوالات (ادمین)' })
findAll() {
return this.faqService.findAll();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Post()
@ApiOperation({ summary: 'ایجاد سوال متداول جدید' })
create(
@Body()
body: {
question: string;
answer: string;
order?: number;
isActive?: boolean;
},
) {
return this.faqService.create(body);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Put('reorder')
@ApiOperation({ summary: 'مرتب‌سازی سوالات' })
reorder(@Body() body: { items: { id: string; order: number }[] }) {
return this.faqService.reorder(body.items);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Put(':id')
@ApiOperation({ summary: 'ویرایش سوال متداول' })
update(
@Param('id') id: string,
@Body()
body: Partial<{
question: string;
answer: string;
order: number;
isActive: boolean;
}>,
) {
return this.faqService.update(id, body);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Delete(':id')
@ApiOperation({ summary: 'حذف سوال متداول' })
remove(@Param('id') id: string) {
return this.faqService.remove(id);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { FaqController } from './faq.controller';
import { FaqService } from './faq.service';
@Module({
controllers: [FaqController],
providers: [FaqService],
})
export class FaqModule {}
+63
View File
@@ -0,0 +1,63 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class FaqService {
constructor(private prisma: PrismaService) {}
// Public: only active FAQs
async findActive() {
return this.prisma.fAQ.findMany({
where: { isActive: true },
orderBy: { order: 'asc' },
});
}
// Admin: all FAQs
async findAll() {
return this.prisma.fAQ.findMany({
orderBy: { order: 'asc' },
});
}
async create(data: {
question: string;
answer: string;
order?: number;
isActive?: boolean;
}) {
return this.prisma.fAQ.create({ data });
}
async update(
id: string,
data: Partial<{
question: string;
answer: string;
order: number;
isActive: boolean;
}>,
) {
const faq = await this.prisma.fAQ.findUnique({ where: { id } });
if (!faq) throw new NotFoundException('سوال یافت نشد');
return this.prisma.fAQ.update({ where: { id }, data });
}
async remove(id: string) {
const faq = await this.prisma.fAQ.findUnique({ where: { id } });
if (!faq) throw new NotFoundException('سوال یافت نشد');
return this.prisma.fAQ.delete({ where: { id } });
}
async reorder(items: { id: string; order: number }[]) {
await Promise.all(
items.map((item) =>
this.prisma.fAQ.update({
where: { id: item.id },
data: { order: item.order },
}),
),
);
return { success: true };
}
}
+111
View File
@@ -0,0 +1,111 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { MenuService } from './menu.service';
import {
ApiTags,
ApiOperation,
ApiBearerAuth,
ApiQuery,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
@ApiTags('Menu - مدیریت منو')
@Controller('menu')
export class MenuController {
constructor(private readonly menuService: MenuService) {}
@Get()
@ApiOperation({ summary: 'دریافت منو عمومی بر اساس نوع' })
@ApiQuery({
name: 'type',
required: true,
description: 'HEADER | FOOTER_COL1 | FOOTER_COL2 | FOOTER_COL3',
})
findByType(@Query('type') type: string) {
return this.menuService.findByType(type);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Get('admin')
@ApiOperation({ summary: 'دریافت تمام آیتم‌های منو (ادمین)' })
@ApiQuery({ name: 'type', required: false })
findAllAdmin(@Query('type') type?: string) {
return this.menuService.findAllAdmin(type);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Post()
@ApiOperation({ summary: 'ایجاد آیتم منو جدید' })
create(
@Body()
body: {
menuType: string;
label: string;
href: string;
parentId?: string;
order?: number;
isActive?: boolean;
isExternal?: boolean;
icon?: string;
badge?: string;
},
) {
return this.menuService.create(body);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Put('reorder')
@ApiOperation({ summary: 'مرتب‌سازی آیتم‌های منو' })
reorder(@Body() body: { items: { id: string; order: number }[] }) {
return this.menuService.reorder(body.items);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Put(':id')
@ApiOperation({ summary: 'ویرایش آیتم منو' })
update(
@Param('id') id: string,
@Body()
body: Partial<{
menuType: string;
label: string;
href: string;
parentId: string | null;
order: number;
isActive: boolean;
isExternal: boolean;
icon: string;
badge: string;
}>,
) {
return this.menuService.update(id, body);
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@Delete(':id')
@ApiOperation({ summary: 'حذف آیتم منو' })
remove(@Param('id') id: string) {
return this.menuService.remove(id);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { MenuController } from './menu.controller';
import { MenuService } from './menu.service';
@Module({
controllers: [MenuController],
providers: [MenuService],
exports: [MenuService],
})
export class MenuModule {}
+145
View File
@@ -0,0 +1,145 @@
import { Injectable, NotFoundException, OnModuleInit } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
export type MenuType = 'HEADER' | 'FOOTER_COL1' | 'FOOTER_COL2' | 'FOOTER_COL3';
@Injectable()
export class MenuService implements OnModuleInit {
constructor(private prisma: PrismaService) {}
async onModuleInit() {
await this.seedIfEmpty();
}
private async seedIfEmpty() {
const count = await this.prisma.menuItem.count();
if (count > 0) return;
// Seed with current site navigation
const headerItems = [
{ label: 'راهکارهای درمانی', href: '/shop?view=symptoms', order: 1 },
{ label: 'محصولات تخصصی', href: '/shop', order: 2 },
{ label: 'دانشنامه علمی', href: '/wiki', order: 3 },
{ label: 'مجله سلامت پت', href: '/blog', order: 4 },
{ label: 'شناسنامه پت‌ها', href: '/dashboard/pets', order: 5 },
{ label: 'ویدیوها', href: '/videos', order: 6 },
];
const footerCol1 = [
{ label: 'درباره کنینا آلمان', href: '/about', order: 1 },
{ label: 'تماس با ما', href: '/contact', order: 2 },
{ label: 'مجوزها و گواهی‌ها', href: '/trust-seals', order: 3 },
{ label: 'حریم خصوصی', href: '/privacy', order: 4 },
];
const footerCol2 = [
{ label: 'فروشگاه تخصصی', href: '/shop', order: 1 },
{ label: 'دستهٔ‌بندی درمانی', href: '/shop?view=symptoms', order: 2 },
{ label: 'دانشنامه علمی', href: '/wiki', order: 3 },
{ label: 'مجله سلامت پت', href: '/blog', order: 4 },
];
const footerCol3 = [
{ label: 'شناسنامه پت‌ها', href: '/dashboard/pets', order: 1 },
{ label: 'سفارشات من', href: '/dashboard/orders', order: 2 },
{ label: 'ردیابی سفارش', href: '/track', order: 3 },
{ label: 'ورود / ثبت‌نام', href: '/?login=1', order: 4 },
];
const createItems = (items: typeof headerItems, menuType: MenuType) =>
items.map((item) => ({
...item,
menuType,
isActive: true,
isExternal: false,
}));
await this.prisma.menuItem.createMany({
data: [
...createItems(headerItems, 'HEADER'),
...createItems(footerCol1, 'FOOTER_COL1'),
...createItems(footerCol2, 'FOOTER_COL2'),
...createItems(footerCol3, 'FOOTER_COL3'),
],
});
}
async findByType(menuType: string) {
const items = await this.prisma.menuItem.findMany({
where: { menuType, isActive: true, parentId: null },
orderBy: { order: 'asc' },
include: {
children: {
where: { isActive: true },
orderBy: { order: 'asc' },
},
},
});
return items;
}
async findAllAdmin(menuType?: string) {
return this.prisma.menuItem.findMany({
where: menuType ? { menuType } : undefined,
orderBy: [{ menuType: 'asc' }, { order: 'asc' }],
include: {
children: {
orderBy: { order: 'asc' },
},
},
});
}
async create(data: {
menuType: string;
label: string;
href: string;
parentId?: string;
order?: number;
isActive?: boolean;
isExternal?: boolean;
icon?: string;
badge?: string;
}) {
return this.prisma.menuItem.create({ data });
}
async update(
id: string,
data: Partial<{
menuType: string;
label: string;
href: string;
parentId: string | null;
order: number;
isActive: boolean;
isExternal: boolean;
icon: string;
badge: string;
}>,
) {
const item = await this.prisma.menuItem.findUnique({ where: { id } });
if (!item) throw new NotFoundException('Menu item not found');
return this.prisma.menuItem.update({ where: { id }, data });
}
async remove(id: string) {
const item = await this.prisma.menuItem.findUnique({ where: { id } });
if (!item) throw new NotFoundException('Menu item not found');
// Delete children first
await this.prisma.menuItem.deleteMany({ where: { parentId: id } });
return this.prisma.menuItem.delete({ where: { id } });
}
async reorder(items: { id: string; order: number }[]) {
await Promise.all(
items.map((item) =>
this.prisma.menuItem.update({
where: { id: item.id },
data: { order: item.order },
}),
),
);
return { success: true };
}
}
+69 -24
View File
@@ -167,88 +167,133 @@ export const DEFAULT_UI_TEXTS: Record<string, string> = {
title_separator: '|',
title_position: 'suffix',
defaultMetaTitle: 'کنینا ایران | نماینده رسمی مکمل‌های دارویی Canina آلمان',
defaultMetaDescription: 'فروشگاه تخصصی و نماینده انحصاری مکمل‌های درمانی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی.',
defaultMetaDescription:
'فروشگاه تخصصی و نماینده انحصاری مکمل‌های درمانی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی.',
canonicalBaseUrl: 'https://canina.ir',
ogImageUrl: '/assets/images/regenerated_image_1779109861747.png',
// === Page-by-Page SEO Metadata Defaults ===
home_meta_title: 'کنینا ایران | نماینده رسمی مکمل‌های دارویی Canina آلمان',
home_meta_desc: 'فروشگاه تخصصی و نماینده انحصاری مکمل‌های درمانی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی.',
home_keywords: 'کنینا, مکمل سگ, مکمل گربه, مکمل دارویی حیوانات, Canina Germany',
home_meta_desc:
'فروشگاه تخصصی و نماینده انحصاری مکمل‌های درمانی و تقویتی سگ و گربه کنینا آلمان با فرمولاسیون دارویی و تاییدیه بالینی.',
home_keywords:
'کنینا, مکمل سگ, مکمل گربه, مکمل دارویی حیوانات, Canina Germany',
home_canonical: 'https://canina.ir',
shop_meta_title: 'فروشگاه تخصصی مکمل‌های دارویی سگ و گربه',
shop_meta_desc: 'خرید آنلاین انواع مکمل‌های درمانی مفاصل، پوست و مو، گوارش و ایمنی، رشد و ویتامینه سگ و گربه با ضمانت اصالت کنینا آلمان.',
shop_keywords: 'خرید مکمل سگ, خرید مکمل گربه, مکمل مفاصل پت, پت شاپ تخصصی دارویی',
shop_meta_desc:
'خرید آنلاین انواع مکمل‌های درمانی مفاصل، پوست و مو، گوارش و ایمنی، رشد و ویتامینه سگ و گربه با ضمانت اصالت کنینا آلمان.',
shop_keywords:
'خرید مکمل سگ, خرید مکمل گربه, مکمل مفاصل پت, پت شاپ تخصصی دارویی',
shop_canonical: 'https://canina.ir/shop',
catalog_meta_title: 'کاتالوگ رسمی مکمل‌های درمانی و دارویی',
catalog_meta_desc: 'مشاهده و مطالعه کاتالوگ جامع دارویی و مکمل‌های تغذیه‌ای تخصصی کنینا آلمان با قابلیت ورق‌زدن تعاملی و ثبت پیش‌خرید.',
catalog_keywords: 'کاتالوگ کنینا, کاتالوگ محصولات Canina, راهنمای مکمل‌های دارویی پت',
catalog_meta_desc:
'مشاهده و مطالعه کاتالوگ جامع دارویی و مکمل‌های تغذیه‌ای تخصصی کنینا آلمان با قابلیت ورق‌زدن تعاملی و ثبت پیش‌خرید.',
catalog_keywords:
'کاتالوگ کنینا, کاتالوگ محصولات Canina, راهنمای مکمل‌های دارویی پت',
catalog_canonical: 'https://canina.ir/catalog',
blog_meta_title: 'مجله سلامت و دانشنامه مقالات تخصصی پت',
blog_meta_desc: 'جدیدترین مقالات علمی، راهنمای تغذیه، بیماری‌های سگ و گربه و توصیه‌های بالینی متخصصان و دامپزشکان کنینا.',
blog_keywords: 'مقالات سگ و گربه, مجله سلامت حیوانات, تغذیه پت, بیماریهای سگ و گربه',
blog_meta_desc:
'جدیدترین مقالات علمی، راهنمای تغذیه، بیماری‌های سگ و گربه و توصیه‌های بالینی متخصصان و دامپزشکان کنینا.',
blog_keywords:
'مقالات سگ و گربه, مجله سلامت حیوانات, تغذیه پت, بیماریهای سگ و گربه',
blog_canonical: 'https://canina.ir/blog',
wiki_meta_title: 'دانشنامه علمی ترکیبات و اصطلاحات دارویی',
wiki_meta_desc: 'مرجع تخصصی اثرات بالینی، مواد تشکیل‌دهنده، ویتامین‌ها و ترکیبات ارگانیک به کار رفته در مکمل‌های دارویی کنینا آلمان.',
wiki_keywords: 'دانشنامه دارویی پت, ترکیبات مکمل سگ, گلوکوزامین سگ, صدف سبز نیوزیلند',
wiki_meta_desc:
'مرجع تخصصی اثرات بالینی، مواد تشکیل‌دهنده، ویتامین‌ها و ترکیبات ارگانیک به کار رفته در مکمل‌های دارویی کنینا آلمان.',
wiki_keywords:
'دانشنامه دارویی پت, ترکیبات مکمل سگ, گلوکوزامین سگ, صدف سبز نیوزیلند',
wiki_canonical: 'https://canina.ir/wiki',
about_meta_title: 'درباره شرکت کنینا ایران و اصالت آلمانی',
about_meta_desc: 'داستان کنینا ایران و بیش از ۴۰ سال سابقه درخشان شرکت Canina pharma GmbH آلمان در تولید مکمل‌های فوق‌تخصصی دامپزشکی.',
about_keywords: 'درباره کنینا, شرکت Canina pharma, تاریخچه مکمل کنینا, استاندارد دارویی آلمان',
about_meta_desc:
'داستان کنینا ایران و بیش از ۴۰ سال سابقه درخشان شرکت Canina pharma GmbH آلمان در تولید مکمل‌های فوق‌تخصصی دامپزشکی.',
about_keywords:
'درباره کنینا, شرکت Canina pharma, تاریخچه مکمل کنینا, استاندارد دارویی آلمان',
about_canonical: 'https://canina.ir/about',
contact_meta_title: 'تماس با ما و مشاوره تخصصی دامپزشکی',
contact_meta_desc: 'راه‌های ارتباطی با دفتر مرکزی کنینا ایران، مشاوره تلفنی رایگان، پشتیبانی آنلاین و نشانی.',
contact_meta_desc:
'راه‌های ارتباطی با دفتر مرکزی کنینا ایران، مشاوره تلفنی رایگان، پشتیبانی آنلاین و نشانی.',
contact_keywords: 'تماس با کنینا, پشتیبانی کنینا ایران, مشاوره دارویی پت',
contact_canonical: 'https://canina.ir/contact',
b2b_meta_title: 'پرتال همکاران تجاری، کلینیک‌ها و پت‌شاپ‌ها',
b2b_meta_desc: 'ثبت‌نام و خرید عمده مکمل‌های دارویی کنینا ویژه کلینیک‌های دامپزشکی، بیمارستان‌ها و پت‌شاپ‌های سراسر کشور با تخفیف سازمانی.',
b2b_meta_desc:
'ثبت‌نام و خرید عمده مکمل‌های دارویی کنینا ویژه کلینیک‌های دامپزشکی، بیمارستان‌ها و پت‌شاپ‌های سراسر کشور با تخفیف سازمانی.',
b2b_keywords: 'خرید عمده مکمل پت, نمایندگی کنینا, فروش سازمانی دامپزشکی',
b2b_canonical: 'https://canina.ir/b2b',
videos_meta_title: 'ویدئوهای آموزشی و توصیه‌های بالینی دامپزشکان',
videos_meta_desc: 'مشاهده ویدئوهای تخصصی نحوه مصرف مکمل‌های درمانی، نظرات دامپزشکان و راهکارهای بالینی تصویری.',
videos_keywords: 'ویدیوهای آموزشی پت, راهنمای مصرف مکمل سگ, فیلم های دامپزشکی',
videos_meta_desc:
'مشاهده ویدئوهای تخصصی نحوه مصرف مکمل‌های درمانی، نظرات دامپزشکان و راهکارهای بالینی تصویری.',
videos_keywords:
'ویدیوهای آموزشی پت, راهنمای مصرف مکمل سگ, فیلم های دامپزشکی',
videos_canonical: 'https://canina.ir/videos',
search_meta_title: 'جستجوی هوشمند مکمل‌ها و دانشنامه سلامت',
search_meta_desc: 'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.',
search_meta_desc:
'جستجوی سریع در کاتالوگ محصولات، بیماری‌ها، علائم بالینی و مقالات سلامت کنینا ایران.',
search_keywords: 'جستجوی داروی پت, سرچ مکمل کنینا',
search_canonical: 'https://canina.ir/search',
dashboard_meta_title: 'داشبورد کاربری و پیگیری سفارشات',
dashboard_meta_desc: 'مشاهده تاریخچه خریدها، وضعیت کیف پول، پیگیری آنلاین بسته‌های پستی و مدیریت پت‌ها.',
dashboard_meta_desc:
'مشاهده تاریخچه خریدها، وضعیت کیف پول، پیگیری آنلاین بسته‌های پستی و مدیریت پت‌ها.',
dashboard_keywords: 'داشبورد کاربری, پروفایل کنینا',
dashboard_canonical: 'https://canina.ir/dashboard',
profile_pets_meta_title: 'پرونده الکترونیک سلامت پت',
profile_pets_meta_desc: 'مدیریت و ثبت پرونده سلامت سگ و گربه، تنظیم یادآورهای دوز دارو و تاریخچه تغذیه مکمل‌ها.',
profile_pets_meta_desc:
'مدیریت و ثبت پرونده سلامت سگ و گربه، تنظیم یادآورهای دوز دارو و تاریخچه تغذیه مکمل‌ها.',
profile_pets_keywords: 'پرونده سلامت سگ, یادآور داروی پت, شناسنامه گربه',
profile_pets_canonical: 'https://canina.ir/profile',
checkout_meta_title: 'تسویه‌حساب و پرداخت امن',
checkout_meta_desc: 'انتخاب آدرس تحویل، روش ارسال و تسویه‌حساب سریع و امن سفارشات مکمل‌های کنینا.',
checkout_meta_desc:
'انتخاب آدرس تحویل، روش ارسال و تسویه‌حساب سریع و امن سفارشات مکمل‌های کنینا.',
checkout_keywords: 'خرید آنلاین مکمل, پرداخت سفارش',
checkout_canonical: 'https://canina.ir/checkout',
track_meta_title: 'پیگیری آنلاین سفارش و مرسوله پستی',
track_meta_desc: 'پیگیری وضعیت لحظه‌ای پردازش، بسته‌بندی و کد رهگیری پست پیشتاز سفارشات کنینا ایران.',
track_meta_desc:
'پیگیری وضعیت لحظه‌ای پردازش، بسته‌بندی و کد رهگیری پست پیشتاز سفارشات کنینا ایران.',
track_keywords: 'رهگیری پست پیشتاز, پیگیری سفارش کنینا',
track_canonical: 'https://canina.ir/track',
trust_seals_meta_title: 'مجوزهای رسمی، گواهی اصالت و اینماد',
trust_seals_meta_desc: 'بررسی تاییدیه‌های رسمی سازمان دامپزشکی کشور، گواهی استاندارد آلمان و اینماد رسمی کنینا ایران.',
trust_seals_meta_desc:
'بررسی تاییدیه‌های رسمی سازمان دامپزشکی کشور، گواهی استاندارد آلمان و اینماد رسمی کنینا ایران.',
trust_seals_keywords: 'اینماد کنینا, مجوز دامپزشکی مکمل, اصالت کالا کنینا',
trust_seals_canonical: 'https://canina.ir/trust-seals',
privacy_meta_title: 'حریم خصوصی و شرایط استفاده',
privacy_meta_desc: 'سیاست‌های حفاظت از اطلاعات شخصی کاربران، امنیت داده‌های پزشکی و قوانین استفاده از خدمات کنینا ایران.',
privacy_meta_desc:
'سیاست‌های حفاظت از اطلاعات شخصی کاربران، امنیت داده‌های پزشکی و قوانین استفاده از خدمات کنینا ایران.',
privacy_keywords: 'قوانین کنینا, شرایط مرجوعی, حریم خصوصی',
privacy_canonical: 'https://canina.ir/privacy',
// === Testimonials Section (Homepage) ===
testimonials_badge: 'صداهای واقعی، تجربه‌های اصیل',
testimonials_title: 'مشتریان کنینا چه می‌گویند؟',
testimonials_subtitle:
'نظرات صادقانه صاحبان پت که از محصولات تخصصی کنینا استفاده کرده‌اند',
// === Blog Preview Section (Homepage) ===
blog_preview_badge: 'آخرین مطالب تخصصی',
blog_preview_title: 'مجله سلامت پت کنینا',
blog_preview_subtitle:
'مقالات علمی و تخصصی دامپزشکی برای مراقبت بهتر از حیوان خانگی شما',
blog_preview_read_more: 'مشاهده همه مقالات',
blog_preview_read_article: 'خواندن مقاله',
blog_preview_views: 'بازدید',
blog_preview_comments: 'نظر',
// === FAQ Section (Homepage) ===
faq_badge: 'سوالات پرتکرار',
faq_title: 'سوالات متداول',
faq_subtitle: 'پاسخ سوالاتی که اغلب از ما می‌پرسید',
};
+6 -2
View File
@@ -513,10 +513,14 @@ export class SettingsService implements OnModuleInit {
updates['brand_name_en'] = brandEn;
}
if (obj.titleSeparator || obj.title_separator) {
updates['title_separator'] = String(obj.titleSeparator || obj.title_separator);
updates['title_separator'] = String(
obj.titleSeparator || obj.title_separator,
);
}
if (obj.titlePosition || obj.title_position) {
updates['title_position'] = String(obj.titlePosition || obj.title_position);
updates['title_position'] = String(
obj.titlePosition || obj.title_position,
);
}
if (obj.defaultMetaTitle) {
updates['defaultMetaTitle'] = String(obj.defaultMetaTitle);
@@ -26,6 +26,12 @@ export class TestimonialsController {
return this.testimonialsService.findAll();
}
@Get('homepage')
@ApiOperation({ summary: 'دریافت نظرات فعال برای نمایش در صفحه اصلی' })
findHomepage() {
return this.testimonialsService.findHomepage();
}
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('Admin')
@ApiBearerAuth()
@@ -12,6 +12,13 @@ export class TestimonialsService {
});
}
async findHomepage() {
return this.prisma.testimonial.findMany({
where: { isActive: true, showOnHome: true },
orderBy: { order: 'asc' },
});
}
async create(data: Prisma.TestimonialCreateInput) {
return this.prisma.testimonial.create({
data,
+7
View File
@@ -18,5 +18,12 @@ export default defineConfig([
languageOptions: {
globals: globals.browser,
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
'react-hooks/set-state-in-effect': 'off',
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
},
])
@@ -32,6 +32,8 @@ import {
ChevronDown,
Star,
Layers,
HelpCircle,
Menu,
} from 'lucide-react';
import api from '../services/api';
@@ -146,6 +148,8 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
{ icon: UserCheck, label: 'پزشکان و کادر علمی', path: '/doctors' },
{ icon: MessageSquareQuote, label: 'نظرات و گواهی متخصصان', path: '/testimonials' },
{ icon: Video, label: 'ویدئوها و آموزش‌ها', path: '/videos' },
{ icon: HelpCircle, label: 'سوالات متداول (FAQ)', path: '/faq' },
{ icon: Menu, label: 'مدیریت منو و فوتر', path: '/menu' },
{ icon: Image, label: 'کتابخانه رسانه', path: '/media' },
],
},
@@ -0,0 +1,316 @@
import { useState, useEffect, useCallback } from 'react';
import { HelpCircle, Plus, Edit2, Trash2, X, GripVertical, ToggleLeft, ToggleRight } from 'lucide-react';
import { toast } from 'react-hot-toast';
import api from '../services/api';
import Spinner from '../components/ui/Spinner';
import ConfirmModal from '../components/ui/ConfirmModal';
interface FAQ {
id: string;
question: string;
answer: string;
order: number;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
export default function FAQManager() {
const [faqs, setFaqs] = useState<FAQ[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingFaq, setEditingFaq] = useState<FAQ | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [formData, setFormData] = useState({
question: '',
answer: '',
order: 0,
isActive: true,
});
const fetchFaqs = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/faq/admin');
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setFaqs(data);
} catch (err) {
console.error('Failed to fetch FAQs:', err);
toast.error('خطا در دریافت سوالات متداول');
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchFaqs();
}, [fetchFaqs]);
const openModal = (item: FAQ | null = null) => {
if (item) {
setEditingFaq(item);
setFormData({
question: item.question,
answer: item.answer,
order: item.order,
isActive: item.isActive,
});
} else {
setEditingFaq(null);
setFormData({
question: '',
answer: '',
order: faqs.length,
isActive: true,
});
}
setIsModalOpen(true);
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.question.trim() || !formData.answer.trim()) {
toast.error('سوال و جواب اجباری هستند');
return;
}
try {
setIsSaving(true);
if (editingFaq) {
await api.put(`/faq/${editingFaq.id}`, formData);
toast.success('سوال با موفقیت بروزرسانی شد');
} else {
await api.post('/faq', formData);
toast.success('سوال جدید اضافه شد');
}
setIsModalOpen(false);
fetchFaqs();
} catch (err) {
console.error('Failed to save FAQ:', err);
toast.error('خطا در ذخیره سوال');
} finally {
setIsSaving(false);
}
};
const toggleActive = async (item: FAQ) => {
try {
await api.put(`/faq/${item.id}`, { isActive: !item.isActive });
toast.success(item.isActive ? 'غیرفعال شد' : 'فعال شد');
fetchFaqs();
} catch {
toast.error('خطا در تغییر وضعیت');
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/faq/${deleteTargetId}`);
toast.success('سوال حذف شد');
fetchFaqs();
} catch {
toast.error('خطا در حذف');
} finally {
setDeleteTargetId(null);
}
};
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<HelpCircle className="w-6 h-6 text-orange-500" />
سوالات متداول (FAQ)
</h2>
<p className="text-gray-500 font-medium mt-1">
سوالات و پاسخ‌هایی که در صفحه اصلی سایت نمایش داده می‌شوند — با Schema.org FAQPage برای SEO
</p>
</div>
<button
onClick={() => openModal()}
className="bg-orange-500 hover:bg-orange-600 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-orange-200"
>
<Plus className="w-5 h-5" />
افزودن سوال جدید
</button>
</div>
{/* Info Box */}
<div className="bg-orange-50 border border-orange-200 rounded-xl p-4 text-sm text-orange-800">
<strong>💡 نکته SEO:</strong> سوالات فعال به صورت خودکار با markup <code className="bg-orange-100 px-1 rounded">FAQPage</code> در صفحه اصلی نمایش داده می‌شوند و در نتایج گوگل به عنوان Rich Snippet ظاهر می‌شوند.
</div>
{/* List */}
<div className="space-y-3">
{isLoading ? (
<div className="flex justify-center py-12">
<Spinner size="lg" className="text-orange-500" />
</div>
) : faqs.length === 0 ? (
<div className="bg-white rounded-2xl border border-gray-200 py-16 text-center">
<HelpCircle className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500 font-medium">هیچ سوالی ثبت نشده است</p>
<button
onClick={() => openModal()}
className="mt-4 text-orange-500 font-bold hover:underline text-sm"
>
اولین سوال را اضافه کنید
</button>
</div>
) : (
faqs.map((faq, idx) => (
<div
key={faq.id}
className={`bg-white rounded-2xl border p-5 transition-all ${
faq.isActive ? 'border-gray-200' : 'border-dashed border-gray-300 opacity-60'
}`}
>
<div className="flex items-start gap-4">
<div className="flex items-center gap-2 shrink-0 mt-1">
<GripVertical className="w-4 h-4 text-gray-300" />
<span className="text-xs font-black text-gray-400 w-5 text-center">{idx + 1}</span>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<span className="font-black text-gray-900 text-sm">{faq.question}</span>
{!faq.isActive && (
<span className="px-2 py-0.5 bg-gray-100 text-gray-500 text-[10px] font-bold rounded">
غیرفعال
</span>
)}
</div>
<p className="text-gray-600 text-sm leading-relaxed line-clamp-2">{faq.answer}</p>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={() => toggleActive(faq)}
className={`p-2 rounded-lg transition-colors ${
faq.isActive
? 'text-green-600 hover:bg-green-50'
: 'text-gray-400 hover:bg-gray-50'
}`}
title={faq.isActive ? 'غیرفعال کردن' : 'فعال کردن'}
>
{faq.isActive ? <ToggleRight className="w-5 h-5" /> : <ToggleLeft className="w-5 h-5" />}
</button>
<button
onClick={() => openModal(faq)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(faq.id)}
className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
</div>
))
)}
</div>
{/* Form Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm">
<div className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl overflow-hidden">
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
<h3 className="text-lg font-bold text-gray-900">
{editingFaq ? 'ویرایش سوال متداول' : 'افزودن سوال جدید'}
</h3>
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-lg">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<form onSubmit={handleSave} className="p-6 space-y-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">
سوال <span className="text-red-500">*</span>
</label>
<input
type="text"
required
value={formData.question}
onChange={(e) => setFormData({ ...formData, question: e.target.value })}
placeholder="مثال: آیا محصولات کنینا برای سگ‌های حساس مناسب است؟"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-orange-400 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">
پاسخ <span className="text-red-500">*</span>
</label>
<textarea
required
rows={5}
value={formData.answer}
onChange={(e) => setFormData({ ...formData, answer: e.target.value })}
placeholder="پاسخ کامل، واضح و مفید..."
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-orange-400 outline-none text-sm resize-none"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">ترتیب نمایش</label>
<input
type="number"
value={formData.order}
onChange={(e) => setFormData({ ...formData, order: Number(e.target.value) })}
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-orange-400 outline-none text-sm"
/>
</div>
<div className="flex items-end">
<label className="flex items-center justify-between p-3 bg-orange-50 rounded-xl border border-orange-200 cursor-pointer w-full">
<span className="text-xs font-bold text-orange-700">✅ فعال و قابل نمایش</span>
<input
type="checkbox"
checked={formData.isActive}
onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
className="rounded text-orange-500 focus:ring-orange-400"
/>
</label>
</div>
</div>
<div className="pt-4 flex justify-end gap-3 border-t border-gray-100">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-5 py-2.5 rounded-xl border border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors"
>
انصراف
</button>
<button
type="submit"
disabled={isSaving}
className="px-6 py-2.5 rounded-xl bg-orange-500 text-white font-bold hover:bg-orange-600 transition-colors shadow-md shadow-orange-200 flex items-center gap-2"
>
{isSaving && <Spinner size="sm" />}
ذخیره
</button>
</div>
</form>
</div>
</div>
)}
{deleteTargetId && (
<ConfirmModal
isOpen={true}
title="حذف سوال"
message="آیا از حذف این سوال متداول اطمینان دارید؟"
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
)}
</div>
);
}
@@ -0,0 +1,448 @@
import { useState, useEffect, useCallback } from 'react';
import {
Menu, Plus, Edit2, Trash2, X, ExternalLink,
Eye, EyeOff, ChevronDown, ChevronRight
} from 'lucide-react';
import { toast } from 'react-hot-toast';
import api from '../services/api';
import Spinner from '../components/ui/Spinner';
import ConfirmModal from '../components/ui/ConfirmModal';
interface MenuItem {
id: string;
menuType: string;
label: string;
href: string;
parentId: string | null;
order: number;
isActive: boolean;
isExternal: boolean;
icon: string | null;
badge: string | null;
children?: MenuItem[];
}
type MenuType = 'HEADER' | 'FOOTER_COL1' | 'FOOTER_COL2' | 'FOOTER_COL3';
const MENU_TABS: { key: MenuType; label: string; color: string }[] = [
{ key: 'HEADER', label: '📌 منوی هدر', color: 'blue' },
{ key: 'FOOTER_COL1', label: '🔗 فوتر — ستون ۱', color: 'purple' },
{ key: 'FOOTER_COL2', label: '🔗 فوتر — ستون ۲', color: 'indigo' },
{ key: 'FOOTER_COL3', label: '🔗 فوتر — ستون ۳', color: 'violet' },
];
export default function MenuManager() {
const [activeTab, setActiveTab] = useState<MenuType>('HEADER');
const [allItems, setAllItems] = useState<MenuItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingItem, setEditingItem] = useState<MenuItem | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [formData, setFormData] = useState({
menuType: 'HEADER' as MenuType,
label: '',
href: '',
parentId: null as string | null,
order: 0,
isActive: true,
isExternal: false,
icon: '',
badge: '',
});
const fetchAll = useCallback(async () => {
try {
setIsLoading(true);
const res = await api.get('/menu/admin');
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setAllItems(data);
} catch (err) {
console.error('Failed to fetch menu items:', err);
toast.error('خطا در دریافت آیتم‌های منو');
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const currentItems = allItems.filter(
(item) => item.menuType === activeTab && item.parentId === null
);
const openModal = (item: MenuItem | null = null, parentId?: string) => {
if (item) {
setEditingItem(item);
setFormData({
menuType: item.menuType as MenuType,
label: item.label,
href: item.href,
parentId: item.parentId,
order: item.order,
isActive: item.isActive,
isExternal: item.isExternal,
icon: item.icon || '',
badge: item.badge || '',
});
} else {
setEditingItem(null);
setFormData({
menuType: activeTab,
label: '',
href: '',
parentId: parentId || null,
order: currentItems.length,
isActive: true,
isExternal: false,
icon: '',
badge: '',
});
}
setIsModalOpen(true);
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.label.trim() || !formData.href.trim()) {
toast.error('عنوان و لینک اجباری هستند');
return;
}
try {
setIsSaving(true);
const payload = {
...formData,
icon: formData.icon || null,
badge: formData.badge || null,
};
if (editingItem) {
await api.put(`/menu/${editingItem.id}`, payload);
toast.success('آیتم منو بروزرسانی شد');
} else {
await api.post('/menu', payload);
toast.success('آیتم جدید اضافه شد');
}
setIsModalOpen(false);
fetchAll();
} catch (err) {
console.error('Failed to save menu item:', err);
toast.error('خطا در ذخیره');
} finally {
setIsSaving(false);
}
};
const toggleActive = async (item: MenuItem) => {
try {
await api.put(`/menu/${item.id}`, { isActive: !item.isActive });
toast.success(item.isActive ? 'مخفی شد' : 'فعال شد');
fetchAll();
} catch {
toast.error('خطا در تغییر وضعیت');
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/menu/${deleteTargetId}`);
toast.success('آیتم حذف شد');
fetchAll();
} catch {
toast.error('خطا در حذف');
} finally {
setDeleteTargetId(null);
}
};
const parentItems = allItems.filter(
(item) => item.menuType === formData.menuType && item.parentId === null && item.id !== editingItem?.id
);
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<Menu className="w-6 h-6 text-blue-600" />
مدیریت منو
</h2>
<p className="text-gray-500 font-medium mt-1">
مدیریت آیتم‌های هدر و فوتر سایت — تغییرات بلادرنگ اعمال می‌شوند
</p>
</div>
<button
onClick={() => openModal()}
className="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-blue-200"
>
<Plus className="w-5 h-5" />
آیتم جدید
</button>
</div>
{/* Tabs */}
<div className="flex gap-2 flex-wrap">
{MENU_TABS.map((tab) => (
<button
key={tab.key}
onClick={() => setActiveTab(tab.key)}
className={`px-4 py-2 rounded-xl text-sm font-bold transition-all ${
activeTab === tab.key
? 'bg-blue-600 text-white shadow-md shadow-blue-200'
: 'bg-white border border-gray-200 text-gray-600 hover:border-blue-300'
}`}
>
{tab.label}
</button>
))}
</div>
{/* Menu Items List */}
{isLoading ? (
<div className="flex justify-center py-12">
<Spinner size="lg" className="text-blue-600" />
</div>
) : currentItems.length === 0 ? (
<div className="bg-white rounded-2xl border border-dashed border-gray-300 py-16 text-center">
<Menu className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500 font-medium">هیچ آیتمی در این منو وجود ندارد</p>
<button
onClick={() => openModal()}
className="mt-4 text-blue-600 font-bold hover:underline text-sm"
>
اولین آیتم را اضافه کنید
</button>
</div>
) : (
<div className="space-y-2">
{currentItems.map((item) => (
<div key={item.id} className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
{/* Parent Item */}
<div className={`flex items-center gap-3 p-4 ${!item.isActive ? 'opacity-50' : ''}`}>
<div className="flex items-center gap-2 text-gray-400 shrink-0">
<ChevronRight className="w-4 h-4" />
<span className="text-xs font-mono text-gray-300">#{item.order}</span>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
{item.icon && <span className="text-base">{item.icon}</span>}
<span className="font-bold text-gray-900">{item.label}</span>
{item.badge && (
<span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-[10px] font-bold rounded">
{item.badge}
</span>
)}
{item.isExternal && <ExternalLink className="w-3 h-3 text-gray-400" />}
</div>
<span className="text-xs text-gray-400 font-mono mt-0.5 block">{item.href}</span>
</div>
<div className="flex items-center gap-1 shrink-0">
<button
onClick={() => toggleActive(item)}
className={`p-2 rounded-lg transition-colors ${item.isActive ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-50'}`}
title={item.isActive ? 'مخفی کردن' : 'نمایش'}
>
{item.isActive ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
</button>
<button
onClick={() => openModal(item)}
className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => setDeleteTargetId(item.id)}
className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
{/* Children */}
{item.children && item.children.length > 0 && (
<div className="border-t border-gray-100 bg-gray-50/50">
{item.children.map((child) => (
<div key={child.id} className={`flex items-center gap-3 px-6 py-3 border-b border-gray-100 last:border-0 ${!child.isActive ? 'opacity-50' : ''}`}>
<ChevronDown className="w-3.5 h-3.5 text-gray-300 shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-bold text-gray-700">{child.label}</span>
{child.isExternal && <ExternalLink className="w-3 h-3 text-gray-400" />}
</div>
<span className="text-xs text-gray-400 font-mono">{child.href}</span>
</div>
<div className="flex items-center gap-1">
<button onClick={() => openModal(child)} className="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg">
<Edit2 className="w-3.5 h-3.5" />
</button>
<button onClick={() => setDeleteTargetId(child.id)} className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg">
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
))}
</div>
)}
</div>
))}
</div>
)}
{/* Form Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm">
<div className="bg-white rounded-2xl w-full max-w-xl shadow-2xl overflow-hidden">
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
<h3 className="text-lg font-bold text-gray-900">
{editingItem ? 'ویرایش آیتم منو' : 'افزودن آیتم جدید'}
</h3>
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-lg">
<X className="w-5 h-5 text-gray-500" />
</button>
</div>
<form onSubmit={handleSave} className="p-6 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">موقعیت در منو</label>
<select
value={formData.menuType}
onChange={(e) => setFormData({ ...formData, menuType: e.target.value as MenuType, parentId: null })}
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm bg-white"
>
{MENU_TABS.map((tab) => (
<option key={tab.key} value={tab.key}>{tab.label}</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">زیر آیتم از</label>
<select
value={formData.parentId || ''}
onChange={(e) => setFormData({ ...formData, parentId: e.target.value || null })}
className="w-full px-3 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm bg-white"
>
<option value="">— آیتم اصلی —</option>
{parentItems.map((p) => (
<option key={p.id} value={p.id}>{p.label}</option>
))}
</select>
</div>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">عنوان <span className="text-red-500">*</span></label>
<input
required
type="text"
value={formData.label}
onChange={(e) => setFormData({ ...formData, label: e.target.value })}
placeholder="مثال: فروشگاه تخصصی"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">لینک (href) <span className="text-red-500">*</span></label>
<input
required
type="text"
value={formData.href}
onChange={(e) => setFormData({ ...formData, href: e.target.value })}
placeholder="مثال: /shop یا https://..."
dir="ltr"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm font-mono"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">آیکون (اختیاری)</label>
<input
type="text"
value={formData.icon}
onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
placeholder="🐕 یا نام آیکون"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">Badge (اختیاری)</label>
<input
type="text"
value={formData.badge}
onChange={(e) => setFormData({ ...formData, badge: e.target.value })}
placeholder="مثال: جدید"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm"
/>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">ترتیب</label>
<input
type="number"
value={formData.order}
onChange={(e) => setFormData({ ...formData, order: Number(e.target.value) })}
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-blue-400 outline-none text-sm"
/>
</div>
<label className="flex items-center justify-between p-3 bg-green-50 rounded-xl border border-green-200 cursor-pointer col-span-1 mt-auto">
<span className="text-xs font-bold text-green-700">✅ فعال</span>
<input
type="checkbox"
checked={formData.isActive}
onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
className="rounded text-green-600"
/>
</label>
<label className="flex items-center justify-between p-3 bg-gray-50 rounded-xl border border-gray-200 cursor-pointer col-span-1 mt-auto">
<span className="text-xs font-bold text-gray-700">🔗 لینک خارجی</span>
<input
type="checkbox"
checked={formData.isExternal}
onChange={(e) => setFormData({ ...formData, isExternal: e.target.checked })}
className="rounded"
/>
</label>
</div>
<div className="pt-4 flex justify-end gap-3 border-t border-gray-100">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-5 py-2.5 rounded-xl border border-gray-200 text-gray-600 font-bold hover:bg-gray-50"
>
انصراف
</button>
<button
type="submit"
disabled={isSaving}
className="px-6 py-2.5 rounded-xl bg-blue-600 text-white font-bold hover:bg-blue-700 shadow-md shadow-blue-200 flex items-center gap-2"
>
{isSaving && <Spinner size="sm" />}
ذخیره
</button>
</div>
</form>
</div>
</div>
)}
{deleteTargetId && (
<ConfirmModal
isOpen={true}
title="حذف آیتم منو"
message="آیا از حذف این آیتم اطمینان دارید؟ آیتم‌های زیرمجموعه نیز حذف خواهند شد."
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
)}
</div>
);
}
@@ -24,6 +24,7 @@ export default function TestimonialsManager() {
rating: 5,
isFeatured: true,
isActive: true,
showOnHome: false,
order: 0,
});
@@ -71,6 +72,7 @@ export default function TestimonialsManager() {
rating: item.rating || 5,
isFeatured: item.isFeatured ?? true,
isActive: item.isActive ?? true,
showOnHome: (item as any).showOnHome ?? false,
order: item.order || 0,
});
} else {
@@ -83,6 +85,7 @@ export default function TestimonialsManager() {
rating: 5,
isFeatured: true,
isActive: true,
showOnHome: false,
order: testimonials.length,
});
}
@@ -213,6 +216,11 @@ export default function TestimonialsManager() {
ویژه (Featured)
</span>
)}
{(item as any).showOnHome && (
<span className="px-2 py-0.5 bg-blue-50 text-blue-700 text-[11px] font-bold rounded border border-blue-200">
🏠 صفحه اصلی
</span>
)}
{item.isActive ? (
<span className="inline-flex items-center gap-0.5 text-green-600 text-xs font-bold">
<CheckCircle2 className="w-3.5 h-3.5" /> فعال
@@ -337,7 +345,7 @@ export default function TestimonialsManager() {
</div>
</div>
<div className="pt-2 grid grid-cols-2 gap-4">
<div className="pt-2 grid grid-cols-3 gap-3">
<label className="flex items-center justify-between p-3 bg-gray-50 rounded-xl border border-gray-200 cursor-pointer">
<span className="text-xs font-bold text-gray-700">نمایش ویژه (Featured)</span>
<input
@@ -357,6 +365,16 @@ export default function TestimonialsManager() {
className="rounded text-purple-600 focus:ring-purple-500"
/>
</label>
<label className="flex items-center justify-between p-3 bg-blue-50 rounded-xl border border-blue-200 cursor-pointer">
<span className="text-xs font-bold text-blue-700">🏠 صفحه اصلی</span>
<input
type="checkbox"
checked={formData.showOnHome}
onChange={(e) => setFormData({ ...formData, showOnHome: e.target.checked })}
className="rounded text-blue-600 focus:ring-blue-500"
/>
</label>
</div>
<div className="pt-4 flex justify-end gap-3 border-t border-gray-100">
@@ -41,6 +41,8 @@ const Transactions = lazyWithRetry(() => import('../pages/Transactions'));
const Tickets = lazyWithRetry(() => import('../pages/Tickets'));
const Reviews = lazyWithRetry(() => import('../pages/Reviews'));
const DoctorsManager = lazyWithRetry(() => import('../pages/DoctorsManager'));
const FAQManager = lazyWithRetry(() => import('../pages/FAQManager'));
const MenuManager = lazyWithRetry(() => import('../pages/MenuManager'));
export interface AdminRouteConfig {
path: string;
@@ -97,6 +99,8 @@ export const router = createBrowserRouter([
{ path: 'contact/*', element: <ContactSubmissions /> },
{ path: 'tickets/*', element: <Tickets /> },
{ path: 'reviews/*', element: <Reviews /> },
{ path: 'faq/*', element: <FAQManager /> },
{ path: 'menu/*', element: <MenuManager /> },
],
},
],
+5
View File
@@ -6,6 +6,8 @@ import SmartAdvisor from "../components/SmartAdvisor";
import FeaturedProducts from "../components/FeaturedProducts";
import VetGallery from "../components/VetGallery";
import TestimonialsSection from "../components/TestimonialsSection";
import BlogPreviewSection from "../components/BlogPreviewSection";
import FAQSection from "../components/FAQSection";
import BannerPlacement from "../components/BannerPlacement";
import Link from 'next/link';
import { toPersian } from "../lib/utils";
@@ -64,6 +66,9 @@ export default function HomeClient({ initialData }: HomeClientProps) {
<FeaturedProducts />
<VetGallery testimonials={testimonials} />
<TestimonialsSection />
<BlogPreviewSection />
<FAQSection />
{/* Navigation to Sections */}
<section className="py-12 bg-medical-gray-50 border-y border-medical-gray-100 font-sans">
@@ -0,0 +1,178 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { BookOpen, Calendar, Eye, MessageSquare, ArrowLeft } from "lucide-react";
import { motion } from "motion/react";
import SafeImage from "./SafeImage";
import { useSettingsStore } from "../lib/store/settingsStore";
import api, { BASE_DOMAIN } from "../lib/services/api";
import { toPersian } from "../lib/utils";
export interface BlogPost {
id: string;
title: string;
slug: string;
content: string;
imageUrl?: string;
viewCount: number;
createdAt: string;
author?: {
firstName: string;
lastName: string;
};
_count?: {
comments: number;
};
}
export default function BlogPreviewSection() {
const getText = useSettingsStore((state) => state.getText);
const [blogs, setBlogs] = useState<BlogPost[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function loadBlogs() {
try {
setIsLoading(true);
const res = await api.get("/blogs/homepage");
const list = Array.isArray(res.data?.blogs)
? res.data.blogs
: Array.isArray(res.data)
? res.data
: [];
setBlogs(list);
} catch (err) {
console.error("Failed to load homepage blogs:", err);
setBlogs([]);
} finally {
setIsLoading(false);
}
}
loadBlogs();
}, []);
if (!isLoading && blogs.length === 0) {
return null;
}
return (
<section className="py-20 bg-white font-vazir" dir="rtl">
<div className="max-w-7xl mx-auto px-4">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-4">
<div>
<div className="inline-flex items-center gap-2 px-3 py-1 bg-canina-blue/10 text-canina-blue rounded-full text-xs font-black uppercase tracking-widest mb-3">
<BookOpen className="w-4 h-4" />
<span>{getText("blog_preview_badge", "آخرین مطالب تخصصی")}</span>
</div>
<h2 className="text-3xl md:text-4xl font-black text-medical-gray-900 font-lalezar leading-tight">
{getText("blog_preview_title", "مجله سلامت پت کنینا")}
</h2>
<p className="text-sm md:text-base text-medical-gray-500 font-medium mt-2">
{getText(
"blog_preview_subtitle",
"مقالات علمی و تخصصی دامپزشکی برای مراقبت بهتر از حیوان خانگی شما"
)}
</p>
</div>
<Link
href="/blog"
className="inline-flex items-center gap-2 text-canina-blue font-bold hover:gap-3 transition-all text-sm shrink-0"
>
<span>{getText("blog_preview_read_more", "مشاهده همه مقالات")}</span>
<ArrowLeft className="w-4 h-4" />
</Link>
</div>
{/* Blog Grid */}
{isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{[1, 2, 3].map((i) => (
<div
key={i}
className="bg-medical-gray-50 rounded-3xl p-4 border border-medical-gray-100 animate-pulse space-y-4"
>
<div className="h-48 bg-medical-gray-200 rounded-2xl" />
<div className="h-6 bg-medical-gray-200 rounded-md w-3/4" />
<div className="h-4 bg-medical-gray-200 rounded-md w-1/2" />
</div>
))}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
{blogs.map((blog, idx) => {
const image = blog.imageUrl?.startsWith("http")
? blog.imageUrl
: blog.imageUrl
? `${BASE_DOMAIN}${blog.imageUrl}`
: "/assets/images/blog-placeholder.png";
const authorName = blog.author
? `${blog.author.firstName || ""} ${blog.author.lastName || ""}`.trim()
: "تحریریه کنینا";
const formattedDate = new Date(blog.createdAt).toLocaleDateString("fa-IR");
return (
<motion.article
key={blog.id || idx}
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: idx * 0.1 }}
className="bg-medical-gray-50/60 rounded-[2rem] border border-medical-gray-100 overflow-hidden hover:shadow-lg hover:-translate-y-1 transition-all flex flex-col group"
>
<Link href={`/blog/${blog.slug}`} className="block relative h-52 overflow-hidden bg-medical-gray-100">
<SafeImage
src={image}
alt={blog.title}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
/>
</Link>
<div className="p-6 flex-1 flex flex-col justify-between space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-4 text-xs text-medical-gray-400 font-medium">
<span className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5" />
{toPersian(formattedDate)}
</span>
<span className="flex items-center gap-1">
<Eye className="w-3.5 h-3.5" />
{toPersian(blog.viewCount || 0)} {getText("blog_preview_views", "بازدید")}
</span>
<span className="flex items-center gap-1">
<MessageSquare className="w-3.5 h-3.5" />
{toPersian(blog._count?.comments || 0)} {getText("blog_preview_comments", "نظر")}
</span>
</div>
<Link href={`/blog/${blog.slug}`}>
<h3 className="text-lg font-black text-medical-gray-900 group-hover:text-canina-blue transition-colors line-clamp-2 leading-snug">
{blog.title}
</h3>
</Link>
</div>
<div className="pt-4 border-t border-medical-gray-200/60 flex items-center justify-between">
<span className="text-xs font-bold text-medical-gray-500">
{authorName}
</span>
<Link
href={`/blog/${blog.slug}`}
className="text-xs font-black text-canina-blue group-hover:underline flex items-center gap-1"
>
{getText("blog_preview_read_article", "خواندن مقاله")}
<ArrowLeft className="w-3 h-3" />
</Link>
</div>
</div>
</motion.article>
);
})}
</div>
)}
</div>
</section>
);
}
@@ -0,0 +1,132 @@
"use client";
import React, { useEffect, useState } from "react";
import { HelpCircle, ChevronDown } from "lucide-react";
import { motion, AnimatePresence } from "motion/react";
import { useSettingsStore } from "../lib/store/settingsStore";
import api from "../lib/services/api";
export interface FAQItem {
id: string;
question: string;
answer: string;
order: number;
}
export default function FAQSection() {
const getText = useSettingsStore((state) => state.getText);
const [faqs, setFaqs] = useState<FAQItem[]>([]);
const [openIndex, setOpenIndex] = useState<number | null>(0);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function loadFaqs() {
try {
setIsLoading(true);
const res = await api.get("/faq");
const list = Array.isArray(res.data) ? res.data : [];
setFaqs(list);
} catch (err) {
console.error("Failed to load FAQs:", err);
setFaqs([]);
} finally {
setIsLoading(false);
}
}
loadFaqs();
}, []);
if (!isLoading && faqs.length === 0) {
return null;
}
// Schema.org FAQPage JSON-LD structure
const faqSchema = {
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": faqs.map((faq) => ({
"@type": "Question",
"name": faq.question,
"acceptedAnswer": {
"@type": "Answer",
"text": faq.answer,
},
})),
};
return (
<section className="py-20 bg-medical-gray-50/70 border-t border-medical-gray-100 font-vazir" dir="rtl">
{/* Schema.org FAQPage Rich Snippet */}
{faqs.length > 0 && (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(faqSchema) }}
/>
)}
<div className="max-w-4xl mx-auto px-4">
{/* Header */}
<div className="text-center mb-12">
<div className="inline-flex items-center gap-2 px-3 py-1 bg-amber-500/10 text-amber-600 rounded-full text-xs font-black uppercase tracking-widest mb-3">
<HelpCircle className="w-4 h-4" />
<span>{getText("faq_badge", "سوالات پرتکرار")}</span>
</div>
<h2 className="text-3xl md:text-4xl font-black text-medical-gray-900 font-lalezar leading-tight">
{getText("faq_title", "سوالات متداول")}
</h2>
<p className="text-sm md:text-base text-medical-gray-500 font-medium mt-2">
{getText("faq_subtitle", "پاسخ سوالاتی که اغلب از ما می‌پرسید")}
</p>
</div>
{/* FAQ List */}
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<div key={i} className="h-16 bg-white rounded-2xl border border-medical-gray-100 animate-pulse" />
))}
</div>
) : (
<div className="space-y-4">
{faqs.map((faq, idx) => {
const isOpen = openIndex === idx;
return (
<div
key={faq.id || idx}
className="bg-white rounded-2xl border border-medical-gray-100 overflow-hidden shadow-xs hover:border-canina-blue/30 transition-all"
>
<button
onClick={() => setOpenIndex(isOpen ? null : idx)}
className="w-full p-6 text-right flex items-center justify-between gap-4 font-bold text-medical-gray-900 hover:text-canina-blue transition-colors"
>
<span className="text-base font-shabnam">{faq.question}</span>
<ChevronDown
className={`w-5 h-5 shrink-0 text-medical-gray-400 transition-transform duration-300 ${
isOpen ? "rotate-180 text-canina-blue" : ""
}`}
/>
</button>
<AnimatePresence initial={false}>
{isOpen && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.25 }}
className="overflow-hidden"
>
<div className="px-6 pb-6 pt-0 text-sm text-medical-gray-600 leading-relaxed font-normal border-t border-medical-gray-50">
{faq.answer}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
})}
</div>
)}
</div>
</section>
);
}
@@ -26,7 +26,7 @@ export default function TestimonialsSection() {
async function loadTestimonials() {
try {
setIsLoading(true);
const res = await api.get('/testimonials');
const res = await api.get('/testimonials/homepage');
const raw = res.data;
const list = Array.isArray(raw?.testimonials)
? raw.testimonials
@@ -46,6 +46,7 @@ export default function TestimonialsSection() {
}
}
loadTestimonials();
}, []);
if (!isLoading && testimonials.length === 0) {
@@ -26,7 +26,7 @@ export default function UserDashboard() {
const { pets, activePetId, setActivePet, removePet } = usePetStore();
const isWithdrawalEnabled = useSettingsStore((s) => s.getBoolean('wallet_withdrawal_enabled', false));
const isCatalogMode = useSettingsStore((s) => s.getBoolean('catalog_mode', false));
const isWalletRechargeAllowed = !isCatalogMode && useSettingsStore((s) => s.getBoolean('wallet_recharge_enabled', true));
const isWalletRechargeAllowed = useSettingsStore((s) => !s.getBoolean('catalog_mode', false) && s.getBoolean('wallet_recharge_enabled', true));
React.useEffect(() => {
if (!isLoggedIn && typeof window !== "undefined") {
@@ -216,6 +216,15 @@ export default function UserDashboard() {
};
}, [profile]);
// Password Management State
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [showCurrentPass, setShowCurrentPass] = useState(false);
const [showNewPass, setShowNewPass] = useState(false);
const [showConfirmPass, setShowConfirmPass] = useState(false);
const [isSavingPassword, setIsSavingPassword] = useState(false);
if (!isLoggedIn) {
return null;
}
@@ -240,14 +249,6 @@ export default function UserDashboard() {
}
};
// Password Management State
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [showCurrentPass, setShowCurrentPass] = useState(false);
const [showNewPass, setShowNewPass] = useState(false);
const [showConfirmPass, setShowConfirmPass] = useState(false);
const [isSavingPassword, setIsSavingPassword] = useState(false);
const handleSavePassword = async (e: React.FormEvent) => {
e.preventDefault();
+9
View File
@@ -13,6 +13,15 @@ const eslintConfig = defineConfig([
"build/**",
"next-env.d.ts",
]),
{
rules: {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
"react-hooks/set-state-in-effect": "off",
"react-hooks/exhaustive-deps": "warn",
},
},
]);
export default eslintConfig;