Fix Admin panel categories modal, add error handling, enforce cursor-pointer globally
This commit is contained in:
1 parent
69502fc380
commit
82ab454647
47 files changed
+2968
-653
No files matched your search
Generated
+11
@@ -37,6 +37,7 @@
|
||||
"@types/bcrypt": "^6.0.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^24.12.4",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/supertest": "^7.0.0",
|
||||
@@ -2989,6 +2990,16 @@
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/multer": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.1.0.tgz",
|
||||
"integrity": "sha512-zYZb0+nJhOHtPpGDb3vqPjwpdeGlGC157VpkqNQL+UU2qwoacoQ7MpsAmUptI/0Oa127X32JzWDqQVEXp2RcIA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/express": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.12.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.4.tgz",
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
"@types/bcrypt": "^6.0.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^24.12.4",
|
||||
"@types/passport-jwt": "^4.0.1",
|
||||
"@types/supertest": "^7.0.0",
|
||||
|
||||
@@ -23,6 +23,7 @@ model User {
|
||||
walletTransactions WalletTransaction[]
|
||||
pets Pet[]
|
||||
orders Order[]
|
||||
blogs Blog[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
@@ -61,14 +62,64 @@ model WalletTransaction {
|
||||
@@map("wallet_transactions")
|
||||
}
|
||||
|
||||
model Media {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
filename String @db.VarChar(200)
|
||||
url String @db.Text
|
||||
mimetype String @db.VarChar(50)
|
||||
size Int
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
@@map("media")
|
||||
}
|
||||
|
||||
model Category {
|
||||
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
|
||||
metaTitle String? @map("meta_title") @db.VarChar(200)
|
||||
metaDescription String? @map("meta_description") @db.Text
|
||||
keywords String? @db.Text
|
||||
imageUrl String? @map("image_url") @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
parent Category? @relation("SubCategories", fields: [parentId], references: [id])
|
||||
children Category[] @relation("SubCategories")
|
||||
products Product[]
|
||||
|
||||
@@map("categories")
|
||||
}
|
||||
|
||||
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")
|
||||
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])
|
||||
|
||||
@@map("blogs")
|
||||
}
|
||||
|
||||
model Product {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
artNo String @unique @map("art_no") @db.VarChar(20)
|
||||
slug String @unique @db.VarChar(150)
|
||||
name String @db.VarChar(200)
|
||||
scientificTagline String? @map("scientific_tagline") @db.VarChar(250)
|
||||
description String @db.Text
|
||||
shortDescription String? @map("short_description") @db.Text
|
||||
category String @db.VarChar(100)
|
||||
categoryId String @map("category_id") @db.Uuid
|
||||
categorySlug String @map("category_slug") @db.VarChar(100)
|
||||
priceValue Decimal @map("price_value") @db.Decimal(15, 2)
|
||||
priceDisplay String @map("price_display") @db.VarChar(50)
|
||||
@@ -83,6 +134,7 @@ model Product {
|
||||
keywords String? @db.Text
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
category Category @relation(fields: [categoryId], references: [id])
|
||||
ingredients ProductIngredient[]
|
||||
symptoms ProductSymptom[]
|
||||
reminders Reminder[]
|
||||
@@ -188,15 +240,36 @@ model HealthLog {
|
||||
model Coupon {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique @db.VarChar(50)
|
||||
discountValue Decimal @map("discount_value") @db.Decimal(15, 2)
|
||||
type String @default("percent") @db.VarChar(20) // fixed, percent
|
||||
value Decimal @db.Decimal(15, 2)
|
||||
minCartValue Decimal? @map("min_cart_value") @db.Decimal(15, 2)
|
||||
maxCartValue Decimal? @map("max_cart_value") @db.Decimal(15, 2)
|
||||
maxUses Int? @map("max_uses")
|
||||
usedCount Int @default(0) @map("used_count")
|
||||
expiresAt DateTime? @map("expires_at") @db.Timestamptz()
|
||||
isActive Boolean @default(true) @map("is_active")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz()
|
||||
|
||||
orders Order[]
|
||||
targets CouponTarget[]
|
||||
|
||||
@@map("coupons")
|
||||
}
|
||||
|
||||
model CouponTarget {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
couponId String @map("coupon_id") @db.Uuid
|
||||
targetType String @map("target_type") @db.VarChar(50) // USER, PET, ROLE, PRODUCT, CATEGORY
|
||||
targetId String @map("target_id") @db.VarChar(100) // UUID or role name
|
||||
modifierType String @default("override") @map("modifier_type") @db.VarChar(20) // override, add, subtract
|
||||
modifierValue Decimal? @map("modifier_value") @db.Decimal(15, 2)
|
||||
|
||||
coupon Coupon @relation(fields: [couponId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([targetType, targetId])
|
||||
@@map("coupon_targets")
|
||||
}
|
||||
|
||||
model Order {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
@@ -238,8 +311,11 @@ model UiText {
|
||||
model ScientificTerm {
|
||||
key String @id @db.VarChar(100)
|
||||
term String @db.VarChar(150)
|
||||
definition String @db.Text
|
||||
wikiId String @map("wiki_id") @db.VarChar(50)
|
||||
definition String @db.Text
|
||||
wikiId String @map("wiki_id") @db.VarChar(50)
|
||||
metaTitle String? @map("meta_title") @db.VarChar(200)
|
||||
metaDescription String? @map("meta_description") @db.Text
|
||||
keywords String? @db.Text
|
||||
|
||||
@@map("scientific_terms")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
console.log('Seeding products and blogs...');
|
||||
|
||||
// 1. Create a default category
|
||||
const category = await prisma.category.upsert({
|
||||
where: { slug: 'supplements' },
|
||||
update: {},
|
||||
create: {
|
||||
name: 'مکملهای غذایی و درمانی',
|
||||
slug: 'supplements',
|
||||
description: 'انواع مکملهای اورجینال کانینا آلمان',
|
||||
metaTitle: 'خرید مکمل کانینا',
|
||||
metaDescription: 'بهترین مکملهای کانینا'
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Read products.json
|
||||
const productsPath = 'C:/Users/parsa/.gemini/antigravity-ide/brain/951ff86f-dc4e-4670-9a62-78e1f9c8c223/scratch/products.json';
|
||||
if (fs.existsSync(productsPath)) {
|
||||
const productsRaw = fs.readFileSync(productsPath, 'utf8');
|
||||
const products = JSON.parse(productsRaw);
|
||||
|
||||
let count = 0;
|
||||
for (const p of products) {
|
||||
// Parse price "1,550,000 T"
|
||||
let price = 0;
|
||||
if (p.price) {
|
||||
price = parseInt(p.price.replace(/,/g, '').replace(' T', ''));
|
||||
}
|
||||
|
||||
const artNo = p.article_number || `ART-${count}`;
|
||||
const slug = (p.product_name_en || p.product_name_fa || `product-${count}`).replace(/\s+/g, '-').toLowerCase().replace(/[^a-z0-9-]/g, '');
|
||||
const priceVal = price || 0;
|
||||
const imageUrl = '/placeholder.png'; // Fallback
|
||||
|
||||
await prisma.product.upsert({
|
||||
where: { artNo: artNo },
|
||||
update: {
|
||||
categoryId: category.id,
|
||||
categorySlug: category.slug,
|
||||
slug: slug,
|
||||
},
|
||||
create: {
|
||||
artNo: artNo,
|
||||
slug: slug,
|
||||
name: p.product_name_fa || p.product_name_en || 'بدون نام',
|
||||
scientificTagline: p.product_name_en || null,
|
||||
description: p.description || '',
|
||||
categoryId: category.id,
|
||||
categorySlug: category.slug,
|
||||
priceValue: priceVal,
|
||||
priceDisplay: p.price || '0 T',
|
||||
unit: p.volume_weight?.includes('ml') ? 'ml' : 'g',
|
||||
packageSize: parseFloat(p.volume_weight || '100') || 100,
|
||||
suitableFor: 'هر دو', // Default
|
||||
imageUrl: imageUrl,
|
||||
}
|
||||
});
|
||||
count++;
|
||||
}
|
||||
console.log(`Seeded ${count} products.`);
|
||||
} else {
|
||||
console.log('products.json not found at', productsPath);
|
||||
}
|
||||
|
||||
// Create admin user for blogs
|
||||
const adminId = '12345678-1234-1234-1234-123456789012';
|
||||
await prisma.user.upsert({
|
||||
where: { mobile: '09120000000' },
|
||||
update: { id: adminId, role: 'admin' },
|
||||
create: {
|
||||
id: adminId,
|
||||
mobile: '09120000000',
|
||||
email: 'admin@canina-iran.com',
|
||||
firstName: 'Admin',
|
||||
lastName: 'User',
|
||||
role: 'admin'
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Seed some Blogs
|
||||
const blogs = [
|
||||
{
|
||||
title: 'راهنمای جامع تغذیه سگهای بالغ',
|
||||
slug: 'adult-dog-nutrition-guide',
|
||||
content: 'محتوای کامل مقاله در مورد تغذیه سگهای بالغ...',
|
||||
authorId: '12345678-1234-1234-1234-123456789012', // Admin UUID
|
||||
isPublished: true,
|
||||
},
|
||||
{
|
||||
title: 'چرا مکملهای کانینا؟',
|
||||
slug: 'why-canina-supplements',
|
||||
content: 'محتوای کامل مقاله در مورد محصولات کانینا...',
|
||||
authorId: '12345678-1234-1234-1234-123456789012',
|
||||
isPublished: true,
|
||||
}
|
||||
];
|
||||
|
||||
for (const b of blogs) {
|
||||
await prisma.blog.upsert({
|
||||
where: { slug: b.slug },
|
||||
update: {},
|
||||
create: b
|
||||
});
|
||||
}
|
||||
console.log('Seeded blogs.');
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
+15
-65
@@ -24,75 +24,25 @@ async function main() {
|
||||
await prisma.coupon.deleteMany();
|
||||
await prisma.uiText.deleteMany();
|
||||
await prisma.scientificTerm.deleteMany();
|
||||
await prisma.category.deleteMany();
|
||||
await prisma.blog.deleteMany();
|
||||
console.log('Database successfully wiped.');
|
||||
|
||||
console.log('Seeding database with products...');
|
||||
|
||||
const productsFilePath = path.join(__dirname, '..', '..', 'src', 'data', 'products.ts');
|
||||
const fileContent = fs.readFileSync(productsFilePath, 'utf-8');
|
||||
|
||||
const jsCode = ts.transpile(fileContent, {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2018,
|
||||
console.log('Creating Admin User...');
|
||||
await prisma.user.upsert({
|
||||
where: { id: '12345678-1234-1234-1234-123456789012' },
|
||||
update: {},
|
||||
create: {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
firstName: 'Admin',
|
||||
lastName: 'System',
|
||||
email: 'admin@canina.ir',
|
||||
role: 'ADMIN',
|
||||
mobile: '09000000000'
|
||||
}
|
||||
});
|
||||
|
||||
const context = { exports: {} };
|
||||
vm.createContext(context);
|
||||
vm.runInContext(jsCode, context);
|
||||
|
||||
const PRODUCTS = (context.exports as any).PRODUCTS;
|
||||
|
||||
if (!PRODUCTS || !Array.isArray(PRODUCTS)) {
|
||||
console.error('Could not load PRODUCTS from src/data/products.ts');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const productData of PRODUCTS) {
|
||||
const p = await prisma.product.upsert({
|
||||
where: { artNo: productData.artNo },
|
||||
update: {},
|
||||
create: {
|
||||
artNo: productData.artNo,
|
||||
name: productData.name,
|
||||
scientificTagline: productData.scientificTagline,
|
||||
description: productData.description,
|
||||
shortDescription: productData.shortDescription || '',
|
||||
category: productData.category,
|
||||
categorySlug: productData.categorySlug || 'general',
|
||||
priceValue: productData.priceValue,
|
||||
priceDisplay: productData.price,
|
||||
unit: productData.unit,
|
||||
packageSize: productData.packageSize,
|
||||
dosageLogic: productData.dosage_logic,
|
||||
suitableFor: productData.suitableFor,
|
||||
imageUrl: productData.image,
|
||||
}
|
||||
});
|
||||
|
||||
if (productData.main_ingredients) {
|
||||
for (const ing of productData.main_ingredients) {
|
||||
await prisma.productIngredient.upsert({
|
||||
where: { productId_ingredient: { productId: p.id, ingredient: ing } },
|
||||
update: {},
|
||||
create: { productId: p.id, ingredient: ing }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (productData.symptoms) {
|
||||
for (const sym of productData.symptoms) {
|
||||
await prisma.productSymptom.upsert({
|
||||
where: { productId_symptom: { productId: p.id, symptom: sym } },
|
||||
update: {},
|
||||
create: { productId: p.id, symptom: sym }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Seeded product: ${p.name}`);
|
||||
}
|
||||
|
||||
// 1. Seed UI Texts
|
||||
// Seeding UI Texts
|
||||
console.log('Seeding UI Texts...');
|
||||
const uiTexts = {
|
||||
hero_badge: "تخصص دارویی از آلمان",
|
||||
|
||||
@@ -44,12 +44,19 @@ export class AdminController {
|
||||
@Query('page') page?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('search') search?: string,
|
||||
@Query('category') category?: string
|
||||
@Query('categoryId') categoryId?: string
|
||||
) {
|
||||
const data = await this.adminService.getProducts({ page, limit, search, category });
|
||||
const data = await this.adminService.getProducts({ page, limit, search, categoryId });
|
||||
return { success: true, ...data };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('products')
|
||||
async createProduct(@Body() data: any) {
|
||||
const product = await this.adminService.createProduct(data);
|
||||
return { success: true, data: product };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('products/:id')
|
||||
async updateProduct(@Param('id') id: string, @Body() data: any) {
|
||||
@@ -61,7 +68,7 @@ export class AdminController {
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('products/:id/delete')
|
||||
@Delete('products/:id')
|
||||
async deleteProduct(@Param('id') id: string) {
|
||||
await this.adminService.deleteProduct(id);
|
||||
return {
|
||||
@@ -95,18 +102,25 @@ export class AdminController {
|
||||
// --- Coupons ---
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get('coupons')
|
||||
async getCoupons() {
|
||||
const coupons = await this.adminService.getCoupons();
|
||||
return { success: true, data: coupons };
|
||||
async getCoupons(@Query() query: any) {
|
||||
const coupons = await this.adminService.getCoupons(query);
|
||||
return { success: true, ...coupons };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('coupons')
|
||||
async createCoupon(@Body() data: { code: string; discountValue: number }) {
|
||||
async createCoupon(@Body() data: any) {
|
||||
const coupon = await this.adminService.createCoupon(data);
|
||||
return { success: true, data: coupon };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('coupons/:id')
|
||||
async updateCoupon(@Param('id') id: string, @Body() data: any) {
|
||||
const coupon = await this.adminService.updateCoupon(id, data);
|
||||
return { success: true, data: coupon };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put('coupons/:id/toggle')
|
||||
async toggleCoupon(@Param('id') id: string, @Body('isActive') isActive: boolean) {
|
||||
|
||||
@@ -3,11 +3,21 @@ import { AdminController } from './admin.controller';
|
||||
import { AdminService } from './admin.service';
|
||||
import { ReportsController } from './reports.controller';
|
||||
import { ReportsService } from './reports.service';
|
||||
import { MediaController } from './media.controller';
|
||||
import { MediaService } from './media.service';
|
||||
import { CategoriesController } from './categories.controller';
|
||||
import { CategoriesService } from './categories.service';
|
||||
import { BlogsController } from './blogs.controller';
|
||||
import { BlogsService } from './blogs.service';
|
||||
import { WikiController } from './wiki.controller';
|
||||
import { WikiService } from './wiki.service';
|
||||
import { PetsController } from './pets.controller';
|
||||
import { PetsService } from './pets.service';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [AdminController, ReportsController],
|
||||
providers: [AdminService, ReportsService],
|
||||
controllers: [AdminController, ReportsController, MediaController, CategoriesController, BlogsController, WikiController, PetsController],
|
||||
providers: [AdminService, ReportsService, MediaService, CategoriesService, BlogsService, WikiService, PetsService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, HttpException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
@@ -68,35 +68,86 @@ export class AdminService {
|
||||
}
|
||||
|
||||
async getProducts(query: any) {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
try {
|
||||
const page = Number(query.page) || 1;
|
||||
const limit = Number(query.limit) || 10;
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: any = {};
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ name: { contains: query.search, mode: 'insensitive' } },
|
||||
{ artNo: { contains: query.search } }
|
||||
];
|
||||
}
|
||||
if (query.category) {
|
||||
where.category = query.category;
|
||||
const where: any = {};
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ name: { contains: query.search, mode: 'insensitive' } },
|
||||
{ artNo: { contains: query.search } }
|
||||
];
|
||||
}
|
||||
if (query.categoryId) {
|
||||
where.categoryId = query.categoryId;
|
||||
}
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.product.findMany({
|
||||
where, skip, take: limit, orderBy: { createdAt: 'desc' },
|
||||
include: { category: true }
|
||||
}),
|
||||
this.prisma.product.count({ where })
|
||||
]);
|
||||
|
||||
return { data, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } };
|
||||
} catch (error) {
|
||||
console.error("[AdminService] getProducts error:", error);
|
||||
throw new HttpException(error.message || 'Error fetching products', 500);
|
||||
}
|
||||
}
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.product.findMany({ where, skip, take: limit, orderBy: { createdAt: 'desc' } }),
|
||||
this.prisma.product.count({ where })
|
||||
]);
|
||||
|
||||
return { data, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } };
|
||||
async createProduct(data: any) {
|
||||
return this.prisma.product.create({
|
||||
data: {
|
||||
artNo: data.artNo,
|
||||
name: data.name,
|
||||
scientificTagline: data.scientificTagline,
|
||||
description: data.description,
|
||||
shortDescription: data.shortDescription,
|
||||
categoryId: data.categoryId,
|
||||
categorySlug: data.categorySlug || 'general',
|
||||
priceValue: data.priceValue,
|
||||
priceDisplay: data.priceDisplay,
|
||||
unit: data.unit,
|
||||
packageSize: data.packageSize,
|
||||
dosageLogic: data.dosageLogic,
|
||||
suitableFor: data.suitableFor,
|
||||
imageUrl: data.imageUrl,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
slug: data.slug || data.artNo,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async updateProduct(id: string, data: any) {
|
||||
return this.prisma.product.update({
|
||||
where: { id },
|
||||
data: {
|
||||
packageSize: data.packageSize,
|
||||
artNo: data.artNo,
|
||||
name: data.name,
|
||||
scientificTagline: data.scientificTagline,
|
||||
description: data.description,
|
||||
shortDescription: data.shortDescription,
|
||||
categoryId: data.categoryId,
|
||||
categorySlug: data.categorySlug,
|
||||
priceValue: data.priceValue,
|
||||
priceDisplay: data.priceDisplay,
|
||||
unit: data.unit,
|
||||
packageSize: data.packageSize,
|
||||
dosageLogic: data.dosageLogic,
|
||||
suitableFor: data.suitableFor,
|
||||
imageUrl: data.imageUrl,
|
||||
metaTitle: data.metaTitle,
|
||||
metaDescription: data.metaDescription,
|
||||
keywords: data.keywords,
|
||||
canonicalUrl: data.canonicalUrl,
|
||||
slug: data.slug || data.artNo,
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -138,20 +189,79 @@ export class AdminService {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Coupons ---
|
||||
async getCoupons() {
|
||||
return this.prisma.coupon.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { _count: { select: { orders: true } } }
|
||||
});
|
||||
// --- Coupons Engine ---
|
||||
async getCoupons(query: any) {
|
||||
const { page = 1, limit = 10, search = '' } = query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
const where = search ? { code: { contains: search, mode: 'insensitive' as any } } : {};
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.coupon.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { targets: true } // Include polymorphic targets
|
||||
}),
|
||||
this.prisma.coupon.count({ where })
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: { total, page: Number(page), limit: Number(limit), totalPages: Math.ceil(total / Number(limit)) }
|
||||
};
|
||||
}
|
||||
|
||||
async createCoupon(data: { code: string; discountValue: number }) {
|
||||
async createCoupon(data: any) {
|
||||
return this.prisma.coupon.create({
|
||||
data: {
|
||||
code: data.code,
|
||||
discountValue: data.discountValue,
|
||||
}
|
||||
type: data.type || 'percent',
|
||||
value: data.value,
|
||||
minCartValue: data.minCartValue || null,
|
||||
maxCartValue: data.maxCartValue || null,
|
||||
maxUses: data.maxUses || null,
|
||||
expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
|
||||
isActive: data.isActive !== undefined ? data.isActive : true,
|
||||
targets: data.targets && data.targets.length > 0 ? {
|
||||
create: data.targets.map((t: any) => ({
|
||||
targetType: t.targetType,
|
||||
targetId: t.targetId,
|
||||
modifierType: t.modifierType || 'override',
|
||||
modifierValue: t.modifierValue || null
|
||||
}))
|
||||
} : undefined
|
||||
},
|
||||
include: { targets: true }
|
||||
});
|
||||
}
|
||||
|
||||
async updateCoupon(id: string, data: any) {
|
||||
// Delete old targets and recreate them
|
||||
await this.prisma.couponTarget.deleteMany({ where: { couponId: id } });
|
||||
|
||||
return this.prisma.coupon.update({
|
||||
where: { id },
|
||||
data: {
|
||||
code: data.code,
|
||||
type: data.type,
|
||||
value: data.value,
|
||||
minCartValue: data.minCartValue,
|
||||
maxCartValue: data.maxCartValue,
|
||||
maxUses: data.maxUses,
|
||||
expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
|
||||
isActive: data.isActive,
|
||||
targets: data.targets && data.targets.length > 0 ? {
|
||||
create: data.targets.map((t: any) => ({
|
||||
targetType: t.targetType,
|
||||
targetId: t.targetId,
|
||||
modifierType: t.modifierType || 'override',
|
||||
modifierValue: t.modifierValue || null
|
||||
}))
|
||||
} : undefined
|
||||
},
|
||||
include: { targets: true }
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
|
||||
import { BlogsService } from './blogs.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('admin/blogs')
|
||||
export class BlogsController {
|
||||
constructor(private readonly blogsService: BlogsService) {}
|
||||
|
||||
@Get()
|
||||
async getBlogs(@Query() query: any) {
|
||||
return this.blogsService.getBlogs(query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
async createBlog(@Body() body: any, @Request() req: any) {
|
||||
const data = await this.blogsService.createBlog(body, req.user.id);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
async updateBlog(@Param('id') id: string, @Body() body: any) {
|
||||
const data = await this.blogsService.updateBlog(id, body);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async deleteBlog(@Param('id') id: string) {
|
||||
await this.blogsService.deleteBlog(id);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class BlogsService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getBlogs(query: any) {
|
||||
const { page = 1, limit = 10, search = '' } = query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
const where = search ? { title: { contains: search, mode: 'insensitive' as any } } : {};
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.blog.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { author: { select: { firstName: true, lastName: true } } }
|
||||
}),
|
||||
this.prisma.blog.count({ where })
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: { total, page: Number(page), limit: Number(limit), totalPages: Math.ceil(total / Number(limit)) }
|
||||
};
|
||||
}
|
||||
|
||||
async createBlog(data: any, authorId: string) {
|
||||
return this.prisma.blog.create({
|
||||
data: { ...data, authorId }
|
||||
});
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
async deleteBlog(id: string) {
|
||||
const blog = await this.prisma.blog.findUnique({ where: { id } });
|
||||
if (!blog) throw new NotFoundException('Blog not found');
|
||||
return this.prisma.blog.delete({ where: { id } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { CategoriesService } from './categories.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('admin/categories')
|
||||
export class CategoriesController {
|
||||
constructor(private readonly categoriesService: CategoriesService) {}
|
||||
|
||||
@Get()
|
||||
async getCategories(@Query() query: any) {
|
||||
return this.categoriesService.getCategories(query);
|
||||
}
|
||||
|
||||
@Get('all')
|
||||
async getAllCategoriesRaw() {
|
||||
const data = await this.categoriesService.getAllCategoriesRaw();
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Post()
|
||||
async createCategory(@Body() body: any) {
|
||||
const data = await this.categoriesService.createCategory(body);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
async updateCategory(@Param('id') id: string, @Body() body: any) {
|
||||
const data = await this.categoriesService.updateCategory(id, body);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async deleteCategory(@Param('id') id: string) {
|
||||
await this.categoriesService.deleteCategory(id);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class CategoriesService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getCategories(query: any) {
|
||||
const { page = 1, limit = 10, search = '' } = query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
const where = search ? { name: { contains: search, mode: 'insensitive' as any } } : {};
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.category.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: { createdAt: 'desc' }
|
||||
}),
|
||||
this.prisma.category.count({ where })
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: { total, page: Number(page), limit: Number(limit), totalPages: Math.ceil(total / Number(limit)) }
|
||||
};
|
||||
}
|
||||
|
||||
async getAllCategoriesRaw() {
|
||||
return this.prisma.category.findMany({ orderBy: { name: 'asc' } });
|
||||
}
|
||||
|
||||
async createCategory(data: any) {
|
||||
const cleanData = { ...data };
|
||||
Object.keys(cleanData).forEach(k => {
|
||||
if (cleanData[k] === '') cleanData[k] = null;
|
||||
});
|
||||
// Ensure required fields
|
||||
if (!cleanData.slug) cleanData.slug = cleanData.name.replace(/\s+/g, '-').toLowerCase();
|
||||
|
||||
return this.prisma.category.create({ data: cleanData });
|
||||
}
|
||||
|
||||
async updateCategory(id: string, data: any) {
|
||||
const category = await this.prisma.category.findUnique({ where: { id } });
|
||||
if (!category) throw new NotFoundException('Category not found');
|
||||
|
||||
const cleanData = { ...data };
|
||||
Object.keys(cleanData).forEach(k => {
|
||||
if (cleanData[k] === '') cleanData[k] = null;
|
||||
});
|
||||
|
||||
return this.prisma.category.update({ where: { id }, data: cleanData });
|
||||
}
|
||||
|
||||
async deleteCategory(id: string) {
|
||||
const category = await this.prisma.category.findUnique({ where: { id } });
|
||||
if (!category) throw new NotFoundException('Category not found');
|
||||
return this.prisma.category.delete({ where: { id } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Controller, Get, Post, Delete, Param, UseGuards, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { MediaService } from './media.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
|
||||
@Controller('admin/media')
|
||||
export class MediaController {
|
||||
constructor(private readonly mediaService: MediaService) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Get()
|
||||
async getAllMedia() {
|
||||
const data = await this.mediaService.getAllMedia();
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('upload')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadFile(@UploadedFile() file: Express.Multer.File) {
|
||||
if (!file) throw new BadRequestException('File is missing');
|
||||
const data = await this.mediaService.uploadFile(file);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Delete(':id')
|
||||
async deleteMedia(@Param('id') id: string) {
|
||||
const data = await this.mediaService.deleteMedia(id);
|
||||
return { success: true, data };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Injectable, BadRequestException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
|
||||
@Injectable()
|
||||
export class MediaService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getAllMedia() {
|
||||
return this.prisma.media.findMany({
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
}
|
||||
|
||||
async uploadFile(file: Express.Multer.File) {
|
||||
if (!file) {
|
||||
throw new BadRequestException('No file uploaded');
|
||||
}
|
||||
|
||||
const uploadDir = path.join(process.cwd(), 'uploads');
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const ext = path.extname(file.originalname);
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
fs.writeFileSync(filePath, file.buffer);
|
||||
|
||||
// Assuming we serve static files from '/uploads' route prefix
|
||||
const url = `/uploads/${filename}`;
|
||||
|
||||
const media = await this.prisma.media.create({
|
||||
data: {
|
||||
filename: file.originalname,
|
||||
url,
|
||||
mimetype: file.mimetype,
|
||||
size: file.size,
|
||||
}
|
||||
});
|
||||
|
||||
return media;
|
||||
}
|
||||
|
||||
async deleteMedia(id: string) {
|
||||
const media = await this.prisma.media.findUnique({ where: { id } });
|
||||
if (!media) throw new BadRequestException('Media not found');
|
||||
|
||||
const filePath = path.join(process.cwd(), 'uploads', path.basename(media.url));
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
|
||||
await this.prisma.media.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Controller, Get, Delete, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { PetsService } from './pets.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('admin/pets')
|
||||
export class PetsController {
|
||||
constructor(private readonly petsService: PetsService) {}
|
||||
|
||||
@Get()
|
||||
async getPets(@Query() query: any) {
|
||||
return this.petsService.getPets(query);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
async deletePet(@Param('id') id: string) {
|
||||
await this.petsService.deletePet(id);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class PetsService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getPets(query: any) {
|
||||
const { page = 1, limit = 10, search = '' } = query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
const where = search ? { name: { contains: search, mode: 'insensitive' as any } } : {};
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.pet.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { user: { select: { firstName: true, lastName: true, email: true, mobile: true } } }
|
||||
}),
|
||||
this.prisma.pet.count({ where })
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: { total, page: Number(page), limit: Number(limit), totalPages: Math.ceil(total / Number(limit)) }
|
||||
};
|
||||
}
|
||||
|
||||
async deletePet(id: string) {
|
||||
const pet = await this.prisma.pet.findUnique({ where: { id } });
|
||||
if (!pet) throw new NotFoundException('Pet not found');
|
||||
return this.prisma.pet.delete({ where: { id } });
|
||||
}
|
||||
}
|
||||
@@ -60,11 +60,32 @@ export class ReportsService {
|
||||
const bestSellers = orderItems.map(item => {
|
||||
const p = productsInfo.find(prod => prod.id === item.productId);
|
||||
return {
|
||||
name: p ? p.name : 'Unknown Product',
|
||||
name: p ? p.name : 'محصول نامشخص',
|
||||
quantity: item._sum.quantity || 0
|
||||
};
|
||||
});
|
||||
|
||||
// 3. Category Distribution
|
||||
const categorySales: Record<string, number> = {};
|
||||
for (const item of orderItems) {
|
||||
if (item.productId) {
|
||||
// Since we didn't fetch category id in the grouping, we'll approximate with full product list query
|
||||
}
|
||||
}
|
||||
const categories = await this.prisma.category.findMany({ include: { products: { select: { id: true } } } });
|
||||
const catSalesDist = categories.map(cat => {
|
||||
const pIds = cat.products.map(p => p.id);
|
||||
const catSales = orderItems.filter(oi => oi.productId && pIds.includes(oi.productId)).reduce((sum, oi) => sum + (oi._sum.quantity || 0), 0);
|
||||
return { name: cat.name, value: catSales };
|
||||
}).filter(c => c.value > 0);
|
||||
|
||||
// 4. Coupons Usage
|
||||
const topCoupons = await this.prisma.coupon.findMany({
|
||||
orderBy: { usedCount: 'desc' },
|
||||
take: 5,
|
||||
select: { code: true, usedCount: true }
|
||||
});
|
||||
|
||||
return {
|
||||
overview: {
|
||||
totalRevenue,
|
||||
@@ -74,7 +95,9 @@ export class ReportsService {
|
||||
b2cRevenue,
|
||||
},
|
||||
salesTimeline,
|
||||
bestSellers
|
||||
bestSellers,
|
||||
categoryDistribution: catSalesDist,
|
||||
topCoupons: topCoupons.map(c => ({ name: c.code, value: c.usedCount }))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { WikiService } from './wiki.service';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Controller('admin/wiki')
|
||||
export class WikiController {
|
||||
constructor(private readonly wikiService: WikiService) {}
|
||||
|
||||
@Get()
|
||||
async getTerms(@Query() query: any) {
|
||||
return this.wikiService.getTerms(query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
async createTerm(@Body() body: any) {
|
||||
const data = await this.wikiService.createTerm(body);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Put(':key')
|
||||
async updateTerm(@Param('key') key: string, @Body() body: any) {
|
||||
const data = await this.wikiService.updateTerm(key, body);
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Delete(':key')
|
||||
async deleteTerm(@Param('key') key: string) {
|
||||
await this.wikiService.deleteTerm(key);
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class WikiService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async getTerms(query: any) {
|
||||
const { page = 1, limit = 10, search = '' } = query;
|
||||
const skip = (Number(page) - 1) * Number(limit);
|
||||
|
||||
const where = search ? { term: { contains: search, mode: 'insensitive' as any } } : {};
|
||||
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.scientificTerm.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(limit),
|
||||
orderBy: { term: 'asc' }
|
||||
}),
|
||||
this.prisma.scientificTerm.count({ where })
|
||||
]);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: { total, page: Number(page), limit: Number(limit), totalPages: Math.ceil(total / Number(limit)) }
|
||||
};
|
||||
}
|
||||
|
||||
async createTerm(data: any) {
|
||||
return this.prisma.scientificTerm.create({ data });
|
||||
}
|
||||
|
||||
async updateTerm(key: string, data: any) {
|
||||
const term = await this.prisma.scientificTerm.findUnique({ where: { key } });
|
||||
if (!term) throw new NotFoundException('Scientific Term not found');
|
||||
return this.prisma.scientificTerm.update({ where: { key }, data });
|
||||
}
|
||||
|
||||
async deleteTerm(key: string) {
|
||||
const term = await this.prisma.scientificTerm.findUnique({ where: { key } });
|
||||
if (!term) throw new NotFoundException('Scientific Term not found');
|
||||
return this.prisma.scientificTerm.delete({ where: { key } });
|
||||
}
|
||||
}
|
||||
@@ -66,11 +66,11 @@ export class AuthService {
|
||||
|
||||
async adminLogin(body: any) {
|
||||
if (body.email === 'admin@canina-iran.com' && body.password === 'admin123') {
|
||||
const payload = { sub: 'admin-123', email: body.email, role: 'Admin' };
|
||||
const payload = { sub: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' };
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: { id: 'admin-123', email: body.email, role: 'Admin' },
|
||||
user: { id: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' },
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14,8 +14,9 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
}
|
||||
|
||||
async validate(payload: any) {
|
||||
if (payload.sub === 'admin-123') {
|
||||
return { id: 'admin-123', email: 'admin@canina-iran.com', role: 'ADMIN' };
|
||||
// Bypass DB lookup for local admin user to prevent UUID casting errors
|
||||
if (payload.sub === '12345678-1234-1234-1234-123456789012') {
|
||||
return { id: payload.sub, email: payload.email, role: payload.role };
|
||||
}
|
||||
|
||||
const user = await this.usersService.findById(payload.sub);
|
||||
|
||||
+8
-1
@@ -1,12 +1,19 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { AppModule } from './app.module';
|
||||
import { join } from 'path';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
|
||||
import helmet from 'helmet';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule);
|
||||
|
||||
// Serve static uploads folder
|
||||
app.useStaticAssets(join(process.cwd(), 'uploads'), {
|
||||
prefix: '/uploads/',
|
||||
});
|
||||
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: false, // Avoid blocking Swagger UI scripts and assets
|
||||
|
||||
@@ -37,9 +37,10 @@ export class ProductsService {
|
||||
return products;
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
return this.prisma.product.findUnique({
|
||||
where: { id },
|
||||
async findOne(idOrSlug: string) {
|
||||
const isUuid = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(idOrSlug);
|
||||
return this.prisma.product.findFirst({
|
||||
where: isUuid ? { id: idOrSlug } : { slug: idOrSlug },
|
||||
include: {
|
||||
ingredients: true,
|
||||
symptoms: true,
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
Generated
+27
-1
@@ -13,6 +13,7 @@
|
||||
"lucide-react": "^1.17.0",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-router-dom": "^7.17.0",
|
||||
"recharts": "^3.8.1",
|
||||
"zustand": "^5.0.14"
|
||||
@@ -1906,7 +1907,6 @@
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
@@ -2617,6 +2617,15 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/goober": {
|
||||
"version": "2.1.19",
|
||||
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.19.tgz",
|
||||
"integrity": "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"csstype": "^3.0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
@@ -3444,6 +3453,23 @@
|
||||
"react": "^19.2.7"
|
||||
}
|
||||
},
|
||||
"node_modules/react-hot-toast": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
|
||||
"integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"csstype": "^3.1.3",
|
||||
"goober": "^2.1.16"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16",
|
||||
"react-dom": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"lucide-react": "^1.17.0",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react-hot-toast": "^2.6.0",
|
||||
"react-router-dom": "^7.17.0",
|
||||
"recharts": "^3.8.1",
|
||||
"zustand": "^5.0.14"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BrowserRouter, Routes, Route } from 'react-router-dom';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import Layout from './components/Layout';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import Login from './pages/Login';
|
||||
@@ -9,10 +10,15 @@ import Orders from './pages/Orders';
|
||||
import Coupons from './pages/Coupons';
|
||||
import Settings from './pages/Settings';
|
||||
import Reports from './pages/Reports';
|
||||
import Categories from './pages/Categories';
|
||||
import Blogs from './pages/Blogs';
|
||||
import Wiki from './pages/Wiki';
|
||||
import Pets from './pages/Pets';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Toaster position="top-center" toastOptions={{ className: 'font-vazir' }} />
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
@@ -24,6 +30,10 @@ function App() {
|
||||
<Route path="coupons" element={<Coupons />} />
|
||||
<Route path="settings" element={<Settings />} />
|
||||
<Route path="reports" element={<Reports />} />
|
||||
<Route path="categories" element={<Categories />} />
|
||||
<Route path="blogs" element={<Blogs />} />
|
||||
<Route path="wiki" element={<Wiki />} />
|
||||
<Route path="pets" element={<Pets />} />
|
||||
</Route>
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -1,14 +1,43 @@
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { Home, Users, ShoppingBag, ShoppingCart, Tag, Settings, LogOut, TrendingUp } from 'lucide-react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Home, Users, ShoppingBag, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard } from 'lucide-react';
|
||||
|
||||
const menuItems = [
|
||||
{ icon: Home, label: 'داشبورد', path: '/' },
|
||||
{ icon: Users, label: 'کاربران', path: '/users' },
|
||||
{ icon: ShoppingBag, label: 'محصولات', path: '/products' },
|
||||
{ icon: ShoppingCart, label: 'سفارشات', path: '/orders' },
|
||||
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
||||
{ icon: TrendingUp, label: 'گزارشات', path: '/reports' },
|
||||
{ icon: Settings, label: 'تنظیمات', path: '/settings' },
|
||||
const menuGroups = [
|
||||
{
|
||||
title: 'اصلی',
|
||||
items: [
|
||||
{ icon: LayoutDashboard, label: 'داشبورد', path: '/' },
|
||||
{ icon: TrendingUp, label: 'گزارشات', path: '/reports' },
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'فروشگاه',
|
||||
items: [
|
||||
{ icon: ShoppingCart, label: 'سفارشات', path: '/orders' },
|
||||
{ icon: Package, label: 'محصولات', path: '/products' },
|
||||
{ icon: FolderTree, label: 'دستهبندیها', path: '/categories' },
|
||||
{ icon: Tag, label: 'کدهای تخفیف', path: '/coupons' },
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'مدیریت و کاربران',
|
||||
items: [
|
||||
{ icon: Users, label: 'کاربران', path: '/users' },
|
||||
{ icon: Heart, label: 'حیوانات (Pets)', path: '/pets' },
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'محتوا',
|
||||
items: [
|
||||
{ icon: FileText, label: 'وبلاگ', path: '/blogs' },
|
||||
{ icon: BookOpen, label: 'دانشنامه', path: '/wiki' },
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'سیستم',
|
||||
items: [
|
||||
{ icon: Settings, label: 'تنظیمات', path: '/settings' },
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
interface SidebarProps {
|
||||
@@ -18,6 +47,12 @@ interface SidebarProps {
|
||||
|
||||
export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -32,34 +67,41 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
|
||||
<aside className={`w-64 bg-white border-l border-gray-200 h-screen fixed lg:sticky top-0 flex flex-col font-vazir shadow-sm z-50 transform transition-transform duration-300 ease-in-out ${
|
||||
isOpen ? 'translate-x-0' : 'translate-x-full lg:translate-x-0'
|
||||
}`}>
|
||||
<div className="h-16 flex items-center justify-center border-b border-gray-200">
|
||||
<div className="h-16 flex items-center justify-center border-b border-gray-200 shrink-0">
|
||||
<h1 className="text-xl font-black text-purple-600">کانینا | ادمینپنل</h1>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 overflow-y-auto py-4 px-3 space-y-1">
|
||||
{menuItems.map((item) => {
|
||||
const isActive = location.pathname === item.path || (item.path !== '/' && location.pathname.startsWith(item.path));
|
||||
const Icon = item.icon;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={`flex items-center gap-3 px-3 py-3 rounded-xl transition-all font-bold ${
|
||||
isActive
|
||||
? 'bg-purple-50 text-purple-600'
|
||||
: 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5" />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
<nav className="flex-1 overflow-y-auto py-4 px-3 space-y-6">
|
||||
{menuGroups.map((group, idx) => (
|
||||
<div key={idx}>
|
||||
<h3 className="px-3 mb-2 text-xs font-black text-gray-400 uppercase tracking-wider">{group.title}</h3>
|
||||
<div className="space-y-1">
|
||||
{group.items.map((item) => {
|
||||
const isActive = location.pathname === item.path || (item.path !== '/' && location.pathname.startsWith(item.path));
|
||||
const Icon = item.icon;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all font-bold ${
|
||||
isActive
|
||||
? 'bg-purple-50 text-purple-600'
|
||||
: 'text-gray-500 hover:bg-gray-50 hover:text-gray-900'
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5" />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="p-4 border-t border-gray-200">
|
||||
<button className="flex items-center gap-3 px-3 py-3 w-full text-red-500 hover:bg-red-50 rounded-xl transition-all font-bold">
|
||||
<button onClick={handleLogout} className="flex items-center gap-3 px-3 py-3 w-full text-red-500 hover:bg-red-50 rounded-xl transition-all font-bold">
|
||||
<LogOut className="w-5 h-5" />
|
||||
<span>خروج از حساب</span>
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { X, Upload, Image as ImageIcon, Trash2, CheckCircle2 } from 'lucide-react';
|
||||
import api from '../../services/api';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
interface Media {
|
||||
id: string;
|
||||
url: string;
|
||||
filename: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface MediaSelectorProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (url: string) => void;
|
||||
multiple?: boolean;
|
||||
}
|
||||
|
||||
export default function MediaSelector({ isOpen, onClose, onSelect, multiple = false }: MediaSelectorProps) {
|
||||
const [mediaList, setMediaList] = useState<Media[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
fetchMedia();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const fetchMedia = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await api.get('/admin/media');
|
||||
if (res.data?.success) {
|
||||
setMediaList(res.data.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching media', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files || e.target.files.length === 0) return;
|
||||
const file = e.target.files[0];
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
try {
|
||||
setIsUploading(true);
|
||||
await api.post('/admin/media/upload', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' }
|
||||
});
|
||||
fetchMedia();
|
||||
} catch (error) {
|
||||
console.error('Upload failed', error);
|
||||
alert('خطا در آپلود تصویر');
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (!window.confirm('آیا از حذف این تصویر مطمئن هستید؟')) return;
|
||||
|
||||
try {
|
||||
await api.delete(`/admin/media/${id}`);
|
||||
setMediaList(mediaList.filter(m => m.id !== id));
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm transition-opacity">
|
||||
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden animate-in fade-in zoom-in duration-200">
|
||||
|
||||
{/* Header */}
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-purple-100 text-purple-600 flex items-center justify-center">
|
||||
<ImageIcon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">گالری رسانه</h3>
|
||||
<p className="text-xs text-gray-500 font-medium">تصویر مورد نظر را انتخاب یا آپلود کنید</p>
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={onClose} className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors">
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="p-4 border-b border-gray-100 flex justify-between items-center bg-white">
|
||||
<p className="text-sm font-bold text-gray-600">{mediaList.length} فایل موجود</p>
|
||||
<div>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleUpload}
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
/>
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="bg-purple-600 hover:bg-purple-700 disabled:opacity-70 text-white px-4 py-2 rounded-xl flex items-center gap-2 text-sm font-bold transition-colors"
|
||||
>
|
||||
{isUploading ? <Spinner size="sm" /> : <Upload className="w-4 h-4" />}
|
||||
آپلود تصویر جدید
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Grid */}
|
||||
<div className="p-6 overflow-y-auto flex-1 bg-gray-50/30">
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center items-center h-40">
|
||||
<Spinner size="lg" className="text-purple-600" />
|
||||
</div>
|
||||
) : mediaList.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center h-60 text-gray-400">
|
||||
<ImageIcon className="w-16 h-16 mb-4 opacity-20" />
|
||||
<p className="font-medium text-gray-500">گالری خالی است. اولین عکس را آپلود کنید!</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||
{mediaList.map((media) => {
|
||||
const imgUrl = media.url.startsWith('http') ? media.url : `http://localhost:4001${media.url}`;
|
||||
return (
|
||||
<div
|
||||
key={media.id}
|
||||
onClick={() => {
|
||||
onSelect(imgUrl);
|
||||
if (!multiple) onClose();
|
||||
}}
|
||||
className="group relative aspect-square bg-gray-100 rounded-xl overflow-hidden border-2 border-transparent hover:border-purple-500 cursor-pointer transition-all hover:shadow-lg hover:shadow-purple-100"
|
||||
>
|
||||
<img
|
||||
src={imgUrl}
|
||||
alt={media.filename}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={(e) => handleDelete(media.id, e)}
|
||||
className="w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transform hover:scale-110 transition-transform"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
className="w-8 h-8 rounded-full bg-purple-500 text-white flex items-center justify-center hover:bg-purple-600 transform hover:scale-110 transition-transform"
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,31 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100;300;400;500;700;900&family=Inter:wght@400;500;600;700;800;900&display=swap');
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "Vazirmatn", "Inter", sans-serif;
|
||||
--font-vazir: "Vazirmatn", sans-serif;
|
||||
--font-inter: "Inter", sans-serif;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
font-family: "Vazirmatn", "Inter", sans-serif !important;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--color-gray-50);
|
||||
color: var(--color-gray-900);
|
||||
margin: 0;
|
||||
font-family: "Vazirmatn", "Inter", sans-serif !important;
|
||||
}
|
||||
|
||||
button, a {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.font-vazir {
|
||||
font-family: "Vazirmatn", sans-serif;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Search, Plus, Edit2, Trash2, FileText, Image as ImageIcon, CheckCircle2, XCircle } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
|
||||
export default function Blogs() {
|
||||
const [blogs, setBlogs] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const limit = 10;
|
||||
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
|
||||
const [editingBlog, setEditingBlog] = useState<any>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
title: '',
|
||||
slug: '',
|
||||
content: '',
|
||||
isPublished: true,
|
||||
metaTitle: '',
|
||||
metaDescription: '',
|
||||
keywords: '',
|
||||
imageUrl: ''
|
||||
});
|
||||
|
||||
const fetchBlogs = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await api.get('/admin/blogs', { params: { page, limit, search } });
|
||||
if (res.data?.data) {
|
||||
setBlogs(res.data.data);
|
||||
setTotalPages(res.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
fetchBlogs();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, page]);
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
if (editingBlog) {
|
||||
await api.put(`/admin/blogs/${editingBlog.id}`, formData);
|
||||
} else {
|
||||
await api.post('/admin/blogs', formData);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
fetchBlogs();
|
||||
} catch (error) {
|
||||
console.error('Save failed', error);
|
||||
alert('خطا در ذخیره مقاله');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('آیا از حذف این مقاله مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/blogs/${id}`);
|
||||
fetchBlogs();
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
const openModal = (blog: any = null) => {
|
||||
if (blog) {
|
||||
setEditingBlog(blog);
|
||||
setFormData({
|
||||
title: blog.title,
|
||||
slug: blog.slug,
|
||||
content: blog.content,
|
||||
isPublished: blog.isPublished,
|
||||
metaTitle: blog.metaTitle || '',
|
||||
metaDescription: blog.metaDescription || '',
|
||||
keywords: blog.keywords || '',
|
||||
imageUrl: blog.imageUrl || ''
|
||||
});
|
||||
} else {
|
||||
setEditingBlog(null);
|
||||
setFormData({
|
||||
title: '', slug: '', content: '', isPublished: true, metaTitle: '', metaDescription: '', keywords: '', imageUrl: ''
|
||||
});
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<FileText className="w-6 h-6 text-purple-600" />
|
||||
وبلاگ و مقالات
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت محتوای آموزشی و مقالات علمی سایت</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => openModal()}
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
مقاله جدید
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در مقالات..."
|
||||
value={search}
|
||||
onChange={(e) => { 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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">عنوان مقاله</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">نویسنده</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">وضعیت انتشار</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
<tr><td colSpan={5} className="py-12 text-center"><Spinner size="lg" className="mx-auto text-purple-600" /></td></tr>
|
||||
) : blogs.length === 0 ? (
|
||||
<tr><td colSpan={5} className="py-12 text-center text-gray-500 font-medium">هیچ مقالهای یافت نشد</td></tr>
|
||||
) : (
|
||||
blogs.map((blog) => (
|
||||
<tr key={blog.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-3 px-6">
|
||||
{blog.imageUrl ? (
|
||||
<img src={blog.imageUrl.startsWith('http') ? blog.imageUrl : `http://localhost:4001${blog.imageUrl}`} alt="blog" className="w-16 h-10 rounded-lg object-cover border border-gray-200" />
|
||||
) : (
|
||||
<div className="w-16 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400">
|
||||
<ImageIcon className="w-4 h-4" />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6 font-bold text-gray-900">{blog.title}</td>
|
||||
<td className="py-4 px-6 text-gray-500 text-sm">{(blog.author?.firstName && blog.author?.lastName) ? `${blog.author.firstName} ${blog.author.lastName}` : 'نامشخص'}</td>
|
||||
<td className="py-4 px-6">
|
||||
{blog.isPublished ? (
|
||||
<span className="flex items-center gap-1 text-green-600 text-sm font-bold"><CheckCircle2 className="w-4 h-4"/>منتشر شده</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-orange-600 text-sm font-bold"><XCircle className="w-4 h-4"/>پیشنویس</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => openModal(blog)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"><Edit2 className="w-4 h-4" /></button>
|
||||
<button onClick={() => handleDelete(blog.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"><Trash2 className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{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-4xl max-h-[95vh] flex flex-col shadow-2xl animate-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
|
||||
<h3 className="text-xl font-bold text-gray-900">
|
||||
{editingBlog ? 'ویرایش مقاله' : 'افزودن مقاله جدید'}
|
||||
</h3>
|
||||
<button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500 transition-colors">
|
||||
<XCircle className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-6 overflow-y-auto flex-1">
|
||||
<form id="blogForm" onSubmit={handleSave} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">عنوان مقاله *</label>
|
||||
<input required type="text" value={formData.title} onChange={(e) => 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" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">اسلاگ (Slug) *</label>
|
||||
<input required type="text" value={formData.slug} dir="ltr" onChange={(e) => 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" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">محتوای اصلی مقاله *</label>
|
||||
<textarea required value={formData.content} onChange={(e) => setFormData({...formData, content: e.target.value})} rows={10} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-mono text-sm" dir="rtl" placeholder="محتوای مقاله (متن ساده یا HTML)"></textarea>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-4">
|
||||
<label className="text-sm font-bold text-gray-700">تصویر شاخص</label>
|
||||
<div className="flex items-center gap-4">
|
||||
{formData.imageUrl ? (
|
||||
<img src={formData.imageUrl.startsWith('http') ? formData.imageUrl : `http://localhost:4001${formData.imageUrl}`} alt="preview" className="w-24 h-16 rounded-xl object-cover border border-gray-200" />
|
||||
) : (
|
||||
<div className="w-24 h-16 rounded-xl bg-gray-100 flex items-center justify-center text-gray-400">
|
||||
<ImageIcon className="w-6 h-6" />
|
||||
</div>
|
||||
)}
|
||||
<button type="button" onClick={() => setIsMediaSelectorOpen(true)} className="px-4 py-2 border-2 border-dashed border-gray-300 rounded-xl text-gray-600 font-bold hover:border-purple-500 hover:text-purple-600">انتخاب از گالری</button>
|
||||
</div>
|
||||
<label className="flex items-center gap-3 cursor-pointer p-4 border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors">
|
||||
<input type="checkbox" checked={formData.isPublished} onChange={(e) => setFormData({...formData, isPublished: e.target.checked})} className="w-5 h-5 text-purple-600 rounded focus:ring-purple-500" />
|
||||
<span className="font-bold text-gray-700">انتشار فوری در سایت</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 border border-gray-200 p-4 rounded-xl bg-gray-50/50">
|
||||
<h4 className="font-bold text-purple-700 text-sm mb-2">تنظیمات سئو (SEO)</h4>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">عنوان متا</label>
|
||||
<input type="text" value={formData.metaTitle} onChange={(e) => setFormData({...formData, metaTitle: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">کلمات کلیدی</label>
|
||||
<input type="text" value={formData.keywords} onChange={(e) => setFormData({...formData, keywords: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">توضیحات متا</label>
|
||||
<textarea rows={2} value={formData.metaDescription} onChange={(e) => setFormData({...formData, metaDescription: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 rounded-b-2xl">
|
||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-5 py-2.5 rounded-xl font-bold text-gray-600 hover:bg-gray-200 transition-colors">انصراف</button>
|
||||
<button type="submit" form="blogForm" className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2.5 rounded-xl font-bold transition-all shadow-md shadow-purple-200">ذخیره مقاله</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MediaSelector isOpen={isMediaSelectorOpen} onClose={() => setIsMediaSelectorOpen(false)} onSelect={(url) => setFormData({...formData, imageUrl: url})} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Search, Plus, Edit2, Trash2, FolderTree, Image as ImageIcon, X } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
|
||||
export default function Categories() {
|
||||
const [categories, setCategories] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const limit = 10;
|
||||
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
|
||||
const [editingCategory, setEditingCategory] = useState<any>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
slug: '',
|
||||
description: '',
|
||||
metaTitle: '',
|
||||
metaDescription: '',
|
||||
keywords: '',
|
||||
imageUrl: ''
|
||||
});
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await api.get('/admin/categories', { params: { page, limit, search } });
|
||||
if (res.data?.data) {
|
||||
setCategories(res.data.data);
|
||||
setTotalPages(res.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
fetchCategories();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, page]);
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
if (editingCategory) {
|
||||
await api.put(`/admin/categories/${editingCategory.id}`, formData);
|
||||
} else {
|
||||
await api.post('/admin/categories', formData);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
fetchCategories();
|
||||
} catch (error) {
|
||||
console.error('Save failed', error);
|
||||
alert('خطا در ذخیره دستهبندی');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('آیا مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/categories/${id}`);
|
||||
fetchCategories();
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
const openModal = (category: any = null) => {
|
||||
if (category) {
|
||||
setEditingCategory(category);
|
||||
setFormData({
|
||||
name: category.name,
|
||||
slug: category.slug,
|
||||
description: category.description || '',
|
||||
metaTitle: category.metaTitle || '',
|
||||
metaDescription: category.metaDescription || '',
|
||||
keywords: category.keywords || '',
|
||||
imageUrl: category.imageUrl || ''
|
||||
});
|
||||
} else {
|
||||
setEditingCategory(null);
|
||||
setFormData({
|
||||
name: '', slug: '', description: '', metaTitle: '', metaDescription: '', keywords: '', imageUrl: ''
|
||||
});
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<FolderTree className="w-6 h-6 text-purple-600" />
|
||||
مدیریت دستهبندیها
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">ایجاد دستهبندی محصولات و تنظیمات سئو (SEO)</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => openModal()}
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
دستهبندی جدید
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در نام و اسلاگ..."
|
||||
value={search}
|
||||
onChange={(e) => { 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 focus:ring-2 focus:ring-purple-200 outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">نام دستهبندی</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">Slug</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">وضعیت سئو</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-12 text-center">
|
||||
<Spinner size="lg" className="mx-auto text-purple-600" />
|
||||
</td>
|
||||
</tr>
|
||||
) : categories.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={5} className="py-12 text-center text-gray-500 font-medium">هیچ دستهبندی یافت نشد</td>
|
||||
</tr>
|
||||
) : (
|
||||
categories.map((cat) => (
|
||||
<tr key={cat.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-3 px-6">
|
||||
{cat.imageUrl ? (
|
||||
<img src={cat.imageUrl.startsWith('http') ? cat.imageUrl : `http://localhost:4001${cat.imageUrl}`} alt={cat.name} className="w-12 h-12 rounded-xl object-cover border border-gray-200" />
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center text-gray-400">
|
||||
<ImageIcon className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6 font-bold text-gray-900">{cat.name}</td>
|
||||
<td className="py-4 px-6 text-gray-500 font-mono text-sm">{cat.slug}</td>
|
||||
<td className="py-4 px-6">
|
||||
{cat.metaTitle && cat.metaDescription ? (
|
||||
<span className="px-3 py-1 bg-green-100 text-green-700 rounded-lg text-xs font-bold">تکمیل</span>
|
||||
) : (
|
||||
<span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-lg text-xs font-bold">ناقص</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => openModal(cat)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(cat.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 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 max-h-[90vh] flex flex-col shadow-2xl animate-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
|
||||
<h3 className="text-xl font-bold text-gray-900">
|
||||
{editingCategory ? 'ویرایش دستهبندی' : 'افزودن دستهبندی جدید'}
|
||||
</h3>
|
||||
<button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500 transition-colors">
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-6 overflow-y-auto flex-1">
|
||||
<form id="categoryForm" onSubmit={handleSave} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نام دستهبندی *</label>
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({...formData, name: e.target.value})}
|
||||
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">اسلاگ (Slug) *</label>
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
value={formData.slug}
|
||||
dir="ltr"
|
||||
onChange={(e) => 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 transition-all font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">تصویر دستهبندی</label>
|
||||
<div className="flex items-center gap-4">
|
||||
{formData.imageUrl ? (
|
||||
<img src={formData.imageUrl.startsWith('http') ? formData.imageUrl : `http://localhost:4001${formData.imageUrl}`} alt="preview" className="w-16 h-16 rounded-xl object-cover border border-gray-200" />
|
||||
) : (
|
||||
<div className="w-16 h-16 rounded-xl bg-gray-100 flex items-center justify-center text-gray-400">
|
||||
<ImageIcon className="w-6 h-6" />
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsMediaSelectorOpen(true)}
|
||||
className="px-4 py-2 border-2 border-dashed border-gray-300 rounded-xl text-gray-600 font-bold hover:border-purple-500 hover:text-purple-600 transition-colors"
|
||||
>
|
||||
انتخاب از گالری
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیحات دستهبندی</label>
|
||||
<textarea
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({...formData, description: e.target.value})}
|
||||
rows={3}
|
||||
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none transition-all"
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-gray-100">
|
||||
<h4 className="font-bold text-purple-700 mb-4">تنظیمات سئو (SEO)</h4>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">عنوان متا (Meta Title)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.metaTitle}
|
||||
onChange={(e) => setFormData({...formData, metaTitle: e.target.value})}
|
||||
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیحات متا (Meta Description)</label>
|
||||
<textarea
|
||||
value={formData.metaDescription}
|
||||
onChange={(e) => setFormData({...formData, metaDescription: e.target.value})}
|
||||
rows={2}
|
||||
className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none transition-all"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 rounded-b-2xl">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsModalOpen(false)}
|
||||
className="px-5 py-2.5 rounded-xl font-bold text-gray-600 hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
انصراف
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
form="categoryForm"
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2.5 rounded-xl font-bold transition-all shadow-md shadow-purple-200"
|
||||
>
|
||||
ذخیره دستهبندی
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Media Selector Modal */}
|
||||
<MediaSelector
|
||||
isOpen={isMediaSelectorOpen}
|
||||
onClose={() => setIsMediaSelectorOpen(false)}
|
||||
onSelect={(url) => setFormData({...formData, imageUrl: url})}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,214 +1,347 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Tag, Plus, Search, Check, X, Trash2 } from 'lucide-react';
|
||||
import { Tag, Plus, Edit2, Trash2, Search, XCircle, CheckCircle2, User, Heart, ShoppingBag, FolderTree, Shield } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
|
||||
export default function Coupons() {
|
||||
const [coupons, setCoupons] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const limit = 10;
|
||||
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [couponToDelete, setCouponToDelete] = useState<string | null>(null);
|
||||
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
const [newCoupon, setNewCoupon] = useState({ code: '', discountValue: 0 });
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingCoupon, setEditingCoupon] = useState<any>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
code: '', type: 'percent', value: 0, minCartValue: '', maxCartValue: '', maxUses: '', expiresAt: '', isActive: true,
|
||||
targets: [] as any[]
|
||||
});
|
||||
|
||||
const fetchCoupons = async () => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await api.get('/admin/coupons');
|
||||
if (response.data?.success) {
|
||||
setCoupons(response.data.data);
|
||||
const res = await api.get('/admin/coupons', { params: { page, limit, search } });
|
||||
if (res.data?.data) {
|
||||
setCoupons(res.data.data);
|
||||
setTotalPages(res.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch coupons', err);
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchCoupons();
|
||||
}, []);
|
||||
const timer = setTimeout(() => fetchData(), 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, page]);
|
||||
|
||||
const handleAdd = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newCoupon.code || newCoupon.discountValue <= 0) return;
|
||||
try {
|
||||
setIsAdding(true);
|
||||
await api.post('/admin/coupons', newCoupon);
|
||||
setNewCoupon({ code: '', discountValue: 0 });
|
||||
fetchCoupons();
|
||||
} catch (err) {
|
||||
console.error('Failed to add coupon', err);
|
||||
} finally {
|
||||
setIsAdding(false);
|
||||
const openModal = (coupon: any = null) => {
|
||||
if (coupon) {
|
||||
setEditingCoupon(coupon);
|
||||
setFormData({
|
||||
code: coupon.code,
|
||||
type: coupon.type,
|
||||
value: Number(coupon.value),
|
||||
minCartValue: coupon.minCartValue ? String(coupon.minCartValue) : '',
|
||||
maxCartValue: coupon.maxCartValue ? String(coupon.maxCartValue) : '',
|
||||
maxUses: coupon.maxUses ? String(coupon.maxUses) : '',
|
||||
expiresAt: coupon.expiresAt ? new Date(coupon.expiresAt).toISOString().split('T')[0] : '',
|
||||
isActive: coupon.isActive,
|
||||
targets: coupon.targets || []
|
||||
});
|
||||
} else {
|
||||
setEditingCoupon(null);
|
||||
setFormData({
|
||||
code: '', type: 'percent', value: 0, minCartValue: '', maxCartValue: '', maxUses: '', expiresAt: '', isActive: true, targets: []
|
||||
});
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
value: Number(formData.value),
|
||||
minCartValue: formData.minCartValue ? Number(formData.minCartValue) : null,
|
||||
maxCartValue: formData.maxCartValue ? Number(formData.maxCartValue) : null,
|
||||
maxUses: formData.maxUses ? Number(formData.maxUses) : null,
|
||||
expiresAt: formData.expiresAt || null,
|
||||
targets: formData.targets.map(t => ({
|
||||
...t, modifierValue: t.modifierValue ? Number(t.modifierValue) : null
|
||||
}))
|
||||
};
|
||||
|
||||
if (editingCoupon) await api.put(`/admin/coupons/${editingCoupon.id}`, payload);
|
||||
else await api.post('/admin/coupons', payload);
|
||||
|
||||
setIsModalOpen(false);
|
||||
fetchData();
|
||||
} catch (err) {
|
||||
console.error('Save error', err);
|
||||
alert('خطا در ذخیره کد تخفیف');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('آیا از حذف این کد تخفیف مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/coupons/${id}`);
|
||||
fetchData();
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
const handleToggle = async (id: string, currentStatus: boolean) => {
|
||||
try {
|
||||
await api.put(`/admin/coupons/${id}/toggle`, { isActive: !currentStatus });
|
||||
fetchCoupons();
|
||||
} catch (err) {
|
||||
console.error('Failed to toggle coupon', err);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (couponToDelete) {
|
||||
await api.delete(`/admin/coupons/${couponToDelete}`);
|
||||
setIsDeleteModalOpen(false);
|
||||
setCouponToDelete(null);
|
||||
fetchCoupons();
|
||||
}
|
||||
fetchData();
|
||||
} catch (err) {}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<Tag className="w-6 h-6 text-purple-600" />
|
||||
مدیریت کدهای تخفیف
|
||||
تخفیفهای پلیمورفیک (Polymorphic)
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">ساخت و مدیریت کدهای تخفیف فروشگاه</p>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت کدهای تخفیف با اهداف چندگانه (کاربران، حیوانات، محصولات و ...)</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<Search className="w-5 h-5 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجوی کد تخفیف..."
|
||||
className="pl-4 pr-10 py-2 border border-gray-200 rounded-xl outline-none focus:ring-2 focus:ring-purple-500 w-full sm:w-64 font-medium"
|
||||
dir="rtl"
|
||||
/>
|
||||
</div>
|
||||
<button onClick={() => openModal()} className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200">
|
||||
<Plus className="w-5 h-5" />
|
||||
کد تخفیف جدید
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input type="text" placeholder="جستجوی کد..." value={search} onChange={(e) => { 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" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Add Coupon Form */}
|
||||
<div className="col-span-1">
|
||||
<form onSubmit={handleAdd} className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6 flex items-center gap-2">
|
||||
<Plus className="w-5 h-5 text-purple-600" />
|
||||
افزودن کد جدید
|
||||
</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">کد تخفیف (انگلیسی)</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
dir="ltr"
|
||||
value={newCoupon.code}
|
||||
onChange={(e) => setNewCoupon({...newCoupon, code: e.target.value})}
|
||||
className="w-full border border-gray-200 rounded-xl p-3 outline-none focus:ring-2 focus:ring-purple-500 font-bold text-gray-900"
|
||||
placeholder="e.g. YALDA1403"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">مبلغ تخفیف (تومان)</label>
|
||||
<input
|
||||
type="number"
|
||||
required
|
||||
value={newCoupon.discountValue || ''}
|
||||
onChange={(e) => setNewCoupon({...newCoupon, discountValue: Number(e.target.value)})}
|
||||
className="w-full border border-gray-200 rounded-xl p-3 outline-none focus:ring-2 focus:ring-purple-500 font-bold text-gray-900"
|
||||
placeholder="50000"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isAdding}
|
||||
className="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded-xl transition-colors flex justify-center items-center gap-2"
|
||||
>
|
||||
{isAdding ? <Spinner size="sm" /> : <Check className="w-5 h-5" />}
|
||||
ثبت کد تخفیف
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Coupons List */}
|
||||
<div className="col-span-1 lg:col-span-2">
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right font-vazir">
|
||||
<thead className="bg-gray-50 text-gray-500 text-sm border-b border-gray-200">
|
||||
<tr>
|
||||
<th className="py-4 px-6 font-bold">کد تخفیف</th>
|
||||
<th className="py-4 px-6 font-bold">مبلغ تخفیف</th>
|
||||
<th className="py-4 px-6 font-bold">تعداد استفاده</th>
|
||||
<th className="py-4 px-6 font-bold">وضعیت</th>
|
||||
<th className="py-4 px-6 font-bold text-center">عملیات</th>
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">کد</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">پایه تخفیف</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">تعداد اهداف اختصاصی</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">استفاده شده</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">وضعیت</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
<tr><td colSpan={6} className="py-12 text-center"><Spinner size="lg" className="mx-auto text-purple-600" /></td></tr>
|
||||
) : coupons.length === 0 ? (
|
||||
<tr><td colSpan={6} className="py-12 text-center text-gray-500 font-medium">هیچ کدی یافت نشد</td></tr>
|
||||
) : (
|
||||
coupons.map((c) => (
|
||||
<tr key={c.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-4 px-6 font-mono font-bold text-lg text-gray-900">{c.code}</td>
|
||||
<td className="py-4 px-6 font-bold text-purple-700">
|
||||
{c.type === 'percent' ? `${c.value}٪` : `${Number(c.value).toLocaleString()} تومان`}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<span className="inline-flex items-center justify-center px-3 py-1 bg-purple-100 text-purple-700 rounded-full font-bold text-sm">
|
||||
{c.targets?.length || 0} هدف
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<span className="font-bold text-gray-800">{c.usedCount}</span>
|
||||
{c.maxUses && <span className="text-gray-400 text-xs mr-1">/ {c.maxUses}</span>}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<button onClick={() => handleToggle(c.id, c.isActive)} className={`px-3 py-1 text-xs font-bold rounded-lg transition-colors flex items-center gap-1 ${c.isActive ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
|
||||
{c.isActive ? <CheckCircle2 className="w-3 h-3" /> : <XCircle className="w-3 h-3" />}
|
||||
{c.isActive ? 'فعال' : 'غیرفعال'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => openModal(c)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"><Edit2 className="w-4 h-4" /></button>
|
||||
<button onClick={() => handleDelete(c.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"><Trash2 className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
Array.from({ length: 3 }).map((_, i) => (
|
||||
<tr key={i}>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-16" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-16" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-8 w-20 mx-auto" /></td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
coupons.map((coupon) => (
|
||||
<tr key={coupon.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-4 px-6 font-bold text-gray-900" dir="ltr">{coupon.code}</td>
|
||||
<td className="py-4 px-6 font-bold text-purple-600">{Number(coupon.discountValue).toLocaleString()} تومان</td>
|
||||
<td className="py-4 px-6 text-gray-500 font-bold">{coupon._count?.orders || 0} بار</td>
|
||||
<td className="py-4 px-6">
|
||||
<button
|
||||
onClick={() => handleToggle(coupon.id, coupon.isActive)}
|
||||
className={`px-3 py-1 rounded-full text-xs font-bold transition-colors ${
|
||||
coupon.isActive ? 'bg-green-100 text-green-700 hover:bg-red-100 hover:text-red-700' : 'bg-gray-100 text-gray-700 hover:bg-green-100 hover:text-green-700'
|
||||
}`}
|
||||
>
|
||||
{coupon.isActive ? 'فعال' : 'غیرفعال'}
|
||||
</button>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setCouponToDelete(coupon.id);
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors"
|
||||
title="حذف"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isModalOpen && <CouponModal formData={formData} setFormData={setFormData} onSave={handleSave} onClose={() => setIsModalOpen(false)} isEditing={!!editingCoupon} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Sub-component for Modal to keep code clean
|
||||
function CouponModal({ formData, setFormData, onSave, onClose, isEditing }: any) {
|
||||
const addTarget = () => {
|
||||
setFormData({
|
||||
...formData,
|
||||
targets: [...formData.targets, { targetType: 'USER', targetId: '', modifierType: 'override', modifierValue: '' }]
|
||||
});
|
||||
};
|
||||
|
||||
const removeTarget = (index: number) => {
|
||||
const nt = [...formData.targets];
|
||||
nt.splice(index, 1);
|
||||
setFormData({ ...formData, targets: nt });
|
||||
};
|
||||
|
||||
const updateTarget = (index: number, key: string, val: any) => {
|
||||
const nt = [...formData.targets];
|
||||
nt[index][key] = val;
|
||||
setFormData({ ...formData, targets: nt });
|
||||
};
|
||||
|
||||
const getTypeIcon = (type: string) => {
|
||||
switch (type) {
|
||||
case 'USER': return <User className="w-4 h-4 text-blue-500" />;
|
||||
case 'PET': return <Heart className="w-4 h-4 text-pink-500" />;
|
||||
case 'PRODUCT': return <ShoppingBag className="w-4 h-4 text-orange-500" />;
|
||||
case 'CATEGORY': return <FolderTree className="w-4 h-4 text-emerald-500" />;
|
||||
case 'ROLE': return <Shield className="w-4 h-4 text-indigo-500" />;
|
||||
default: return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<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-4xl max-h-[90vh] flex flex-col shadow-2xl animate-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
|
||||
<h3 className="text-xl font-bold text-gray-900">{isEditing ? 'ویرایش تخفیف' : 'ساخت تخفیف جدید'}</h3>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-red-500 transition-colors"><XCircle className="w-6 h-6" /></button>
|
||||
</div>
|
||||
|
||||
<div className="p-6 overflow-y-auto flex-1">
|
||||
<form id="couponForm" onSubmit={onSave} className="space-y-8">
|
||||
{/* Base Settings */}
|
||||
<div className="space-y-4">
|
||||
<h4 className="font-bold text-gray-800 border-b border-gray-100 pb-2">تنظیمات پایه</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">کد تخفیف *</label>
|
||||
<input required type="text" value={formData.code} onChange={e => setFormData({...formData, code: e.target.value.toUpperCase()})} dir="ltr" className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-mono text-center uppercase font-bold" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نوع *</label>
|
||||
<select required value={formData.type} onChange={e => setFormData({...formData, type: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 bg-white">
|
||||
<option value="percent">درصدی (٪)</option>
|
||||
<option value="fixed">مبلغ ثابت (تومان)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">مقدار *</label>
|
||||
<input required type="number" min="0" value={formData.value} onChange={e => setFormData({...formData, value: e.target.value})} dir="ltr" className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">حداقل خرید</label>
|
||||
<input type="number" min="0" value={formData.minCartValue} onChange={e => setFormData({...formData, minCartValue: e.target.value})} dir="ltr" className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">حداکثر تخفیف</label>
|
||||
<input type="number" min="0" value={formData.maxCartValue} onChange={e => setFormData({...formData, maxCartValue: e.target.value})} dir="ltr" className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">دفعات مجاز</label>
|
||||
<input type="number" min="1" value={formData.maxUses} onChange={e => setFormData({...formData, maxUses: e.target.value})} dir="ltr" className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">انقضا</label>
|
||||
<input type="date" value={formData.expiresAt} onChange={e => setFormData({...formData, expiresAt: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 text-sm" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Target Builder */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-2">
|
||||
<h4 className="font-bold text-gray-800">اهداف اختصاصی (Targets & Modifiers)</h4>
|
||||
<button type="button" onClick={addTarget} className="text-sm font-bold text-purple-600 bg-purple-50 px-3 py-1.5 rounded-lg hover:bg-purple-100 transition-colors flex items-center gap-1">
|
||||
<Plus className="w-4 h-4" /> افزودن هدف
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{formData.targets.length === 0 ? (
|
||||
<div className="bg-gray-50 border border-dashed border-gray-300 rounded-xl p-8 text-center text-gray-500 text-sm">
|
||||
هیچ هدف اختصاصی تعریف نشده است. این کد تخفیف با مقادیر پایه برای همه اعمال میشود (مگر محدودیت دیگری وجود داشته باشد).
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{formData.targets.map((t: any, i: number) => (
|
||||
<div key={i} className="flex flex-col sm:flex-row gap-3 items-end bg-white border border-gray-200 p-4 rounded-xl shadow-sm hover:border-purple-300 transition-colors relative">
|
||||
<div className="space-y-1 w-full sm:w-1/5">
|
||||
<label className="text-xs font-bold text-gray-500 flex items-center gap-1">{getTypeIcon(t.targetType)} نوع هدف</label>
|
||||
<select value={t.targetType} onChange={(e) => updateTarget(i, 'targetType', e.target.value)} className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm bg-gray-50 focus:bg-white focus:border-purple-500 outline-none">
|
||||
<option value="USER">کاربر خاص</option>
|
||||
<option value="PET">پت (حیوان)</option>
|
||||
<option value="ROLE">گروه کاربری</option>
|
||||
<option value="PRODUCT">محصول خاص</option>
|
||||
<option value="CATEGORY">دستهبندی</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 w-full sm:w-1/4">
|
||||
<label className="text-xs font-bold text-gray-500">شناسه هدف (UUID / Role Name)</label>
|
||||
<input type="text" placeholder={t.targetType === 'ROLE' ? 'B2B' : 'شناسه...'} value={t.targetId} onChange={(e) => updateTarget(i, 'targetId', e.target.value)} dir="ltr" className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm outline-none focus:border-purple-500 font-mono text-xs" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 w-full sm:w-1/5">
|
||||
<label className="text-xs font-bold text-gray-500">نوع تغییردهنده (Modifier)</label>
|
||||
<select value={t.modifierType} onChange={(e) => updateTarget(i, 'modifierType', e.target.value)} className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm bg-gray-50 focus:bg-white focus:border-purple-500 outline-none">
|
||||
<option value="override">جایگزین مقدار پایه (Override)</option>
|
||||
<option value="add">افزایش به پایه (+)</option>
|
||||
<option value="subtract">کاهش از پایه (-)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 w-full sm:w-1/5">
|
||||
<label className="text-xs font-bold text-gray-500">مقدار جدید (اختیاری)</label>
|
||||
<input type="number" placeholder="مقدار پایه" value={t.modifierValue} onChange={(e) => updateTarget(i, 'modifierValue', e.target.value)} dir="ltr" className="w-full px-3 py-2 rounded-lg border border-gray-200 text-sm outline-none focus:border-purple-500" />
|
||||
</div>
|
||||
|
||||
<button type="button" onClick={() => removeTarget(i)} className="p-2.5 text-red-500 bg-red-50 hover:bg-red-100 rounded-lg transition-colors shrink-0">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<label className="flex items-center gap-3 cursor-pointer p-3 border border-green-200 bg-green-50/50 rounded-xl w-full">
|
||||
<input type="checkbox" checked={formData.isActive} onChange={(e) => setFormData({...formData, isActive: e.target.checked})} className="w-5 h-5 text-green-600 rounded" />
|
||||
<span className="font-bold text-green-800">کد تخفیف در سیستم فعال باشد</span>
|
||||
</label>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 rounded-b-2xl">
|
||||
<button type="button" onClick={onClose} className="px-5 py-2.5 rounded-xl font-bold text-gray-600 hover:bg-gray-200 transition-colors">انصراف</button>
|
||||
<button type="submit" form="couponForm" className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2.5 rounded-xl font-bold transition-all shadow-md shadow-purple-200">ثبت تخفیف</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={isDeleteModalOpen}
|
||||
title="حذف کد تخفیف"
|
||||
message="آیا از حذف این کد تخفیف اطمینان دارید؟ اگر این کد در سفارشاتی استفاده شده باشد، تاریخچه آن باقی میماند."
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setIsDeleteModalOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Search, Trash2, Heart, Image as ImageIcon } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
|
||||
export default function Pets() {
|
||||
const [pets, setPets] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const limit = 10;
|
||||
|
||||
const fetchPets = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await api.get('/admin/pets', { params: { page, limit, search } });
|
||||
if (res.data?.data) {
|
||||
setPets(res.data.data);
|
||||
setTotalPages(res.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
fetchPets();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, page]);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('آیا از حذف پروفایل این حیوان خانگی مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/pets/${id}`);
|
||||
fetchPets();
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<Heart className="w-6 h-6 text-purple-600 fill-purple-100" />
|
||||
حیوانات خانگی کاربران (Pets)
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مشاهده و مدیریت پروفایل حیوانات خانگی ثبت شده توسط کاربران</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در نام حیوان..."
|
||||
value={search}
|
||||
onChange={(e) => { 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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">نام و نژاد</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">صاحب حیوان</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">مشخصات فیزیکی</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
<tr><td colSpan={5} className="py-12 text-center"><Spinner size="lg" className="mx-auto text-purple-600" /></td></tr>
|
||||
) : pets.length === 0 ? (
|
||||
<tr><td colSpan={5} className="py-12 text-center text-gray-500 font-medium">هیچ حیوانی یافت نشد</td></tr>
|
||||
) : (
|
||||
pets.map((pet) => (
|
||||
<tr key={pet.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-3 px-6">
|
||||
{pet.imageUrl ? (
|
||||
<img src={pet.imageUrl.startsWith('http') ? pet.imageUrl : `http://localhost:4001${pet.imageUrl}`} alt={pet.name} className="w-12 h-12 rounded-full object-cover border-2 border-purple-100" />
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-full bg-purple-50 flex items-center justify-center text-purple-300 border-2 border-purple-100">
|
||||
<ImageIcon className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="font-bold text-gray-900">{pet.name} <span className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded-lg">{pet.type}</span></div>
|
||||
<div className="text-gray-500 text-sm">{pet.breed}</div>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="font-bold text-gray-700">{pet.user?.firstName} {pet.user?.lastName}</div>
|
||||
<div className="text-gray-500 text-xs font-mono">{pet.user?.mobile || pet.user?.email}</div>
|
||||
</td>
|
||||
<td className="py-4 px-6 text-gray-600 text-sm">
|
||||
{pet.age} ساله، {pet.weight} کیلوگرم<br/>
|
||||
<span className="text-xs text-gray-400">تحرک: {pet.activityLevel}</span>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => handleDelete(pet.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"><Trash2 className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,240 +1,428 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Package, Plus, Edit3, Trash2, Search, Check, X } from 'lucide-react';
|
||||
import { Search, Filter, Box, Plus, Edit2, Trash2, Image as ImageIcon, X } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import ConfirmModal from '../components/ui/ConfirmModal';
|
||||
import Skeleton from '../components/ui/Skeleton';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import MediaSelector from '../components/ui/MediaSelector';
|
||||
|
||||
export default function Products() {
|
||||
const [products, setProducts] = useState<any[]>([]);
|
||||
const [categories, setCategories] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// Queries
|
||||
const [page, setPage] = useState(1);
|
||||
// Filters
|
||||
const [search, setSearch] = useState('');
|
||||
const [category, setCategory] = useState('');
|
||||
const [categoryFilter, setCategoryFilter] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
|
||||
// Confirm Modal state
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [productToDelete, setProductToDelete] = useState<string | null>(null);
|
||||
const limit = 10;
|
||||
|
||||
// Edit Mode state
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editForm, setEditForm] = useState({ packageSize: 0, priceValue: 0 });
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
// Modal State
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
|
||||
const [editingProduct, setEditingProduct] = useState<any>(null);
|
||||
const [activeTab, setActiveTab] = useState('general');
|
||||
|
||||
const fetchProducts = async () => {
|
||||
const [formData, setFormData] = useState({
|
||||
artNo: '',
|
||||
name: '',
|
||||
scientificTagline: '',
|
||||
description: '',
|
||||
shortDescription: '',
|
||||
categoryId: '',
|
||||
priceValue: 0,
|
||||
priceDisplay: '',
|
||||
unit: '',
|
||||
packageSize: 0,
|
||||
dosageLogic: '',
|
||||
suitableFor: 'سگ و گربه',
|
||||
imageUrl: '',
|
||||
metaTitle: '',
|
||||
metaDescription: '',
|
||||
keywords: '',
|
||||
canonicalUrl: '',
|
||||
slug: ''
|
||||
});
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const params = new URLSearchParams();
|
||||
params.append('page', page.toString());
|
||||
if (search) params.append('search', search);
|
||||
if (category) params.append('category', category);
|
||||
|
||||
const response = await api.get(`/admin/products?${params.toString()}`);
|
||||
if (response.data?.success) {
|
||||
setProducts(response.data.data);
|
||||
setTotalPages(response.data.meta?.totalPages || 1);
|
||||
// Fetch products first
|
||||
const prodRes = await api.get('/admin/products', { params: { page, limit, search, categoryId: categoryFilter } });
|
||||
if (prodRes.data?.data) {
|
||||
setProducts(prodRes.data.data);
|
||||
setTotalPages(prodRes.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch products', err);
|
||||
|
||||
// Fetch categories separately so it doesn't break products
|
||||
try {
|
||||
const catRes = await api.get('/admin/categories');
|
||||
if (catRes.data?.data) {
|
||||
setCategories(catRes.data.data);
|
||||
} else if (Array.isArray(catRes.data)) {
|
||||
setCategories(catRes.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not fetch categories', err);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error(err);
|
||||
toast.error('خطا در دریافت لیست محصولات: ' + (err.response?.data?.message || err.message));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const delayDebounceFn = setTimeout(() => {
|
||||
fetchProducts();
|
||||
const timer = setTimeout(() => {
|
||||
fetchData();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, categoryFilter, page]);
|
||||
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [page, search, category]);
|
||||
|
||||
const openDeleteModal = (id: string) => {
|
||||
setProductToDelete(id);
|
||||
setIsDeleteModalOpen(true);
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (productToDelete) {
|
||||
await api.get(`/admin/products/${productToDelete}/delete`);
|
||||
setIsDeleteModalOpen(false);
|
||||
setProductToDelete(null);
|
||||
fetchProducts();
|
||||
const openModal = (product: any = null) => {
|
||||
if (product) {
|
||||
setEditingProduct(product);
|
||||
setFormData({
|
||||
artNo: product.artNo,
|
||||
name: product.name,
|
||||
scientificTagline: product.scientificTagline || '',
|
||||
description: product.description || '',
|
||||
shortDescription: product.shortDescription || '',
|
||||
categoryId: product.categoryId || '',
|
||||
priceValue: Number(product.priceValue),
|
||||
priceDisplay: product.priceDisplay || '',
|
||||
unit: product.unit || '',
|
||||
packageSize: Number(product.packageSize),
|
||||
dosageLogic: product.dosageLogic || '',
|
||||
suitableFor: product.suitableFor || 'سگ و گربه',
|
||||
imageUrl: product.imageUrl || '',
|
||||
metaTitle: product.metaTitle || '',
|
||||
metaDescription: product.metaDescription || '',
|
||||
keywords: product.keywords || '',
|
||||
canonicalUrl: product.canonicalUrl || '',
|
||||
slug: product.slug || ''
|
||||
});
|
||||
} else {
|
||||
setEditingProduct(null);
|
||||
setFormData({
|
||||
artNo: '', name: '', scientificTagline: '', description: '', shortDescription: '', categoryId: '',
|
||||
priceValue: 0, priceDisplay: '', unit: '', packageSize: 0, dosageLogic: '', suitableFor: 'سگ و گربه',
|
||||
imageUrl: '', metaTitle: '', metaDescription: '', keywords: '', canonicalUrl: '', slug: ''
|
||||
});
|
||||
}
|
||||
setActiveTab('general');
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEditClick = (product: any) => {
|
||||
setEditingId(product.id);
|
||||
setEditForm({ packageSize: Number(product.packageSize), priceValue: Number(product.priceValue) });
|
||||
};
|
||||
|
||||
const handleSaveEdit = async (id: string) => {
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
setIsSaving(true);
|
||||
await api.put(`/admin/products/${id}`, editForm);
|
||||
setEditingId(null);
|
||||
fetchProducts();
|
||||
} catch (err) {
|
||||
console.error('Failed to update product', err);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
if (editingProduct) {
|
||||
await api.put(`/admin/products/${editingProduct.id}`, formData);
|
||||
} else {
|
||||
await api.post('/admin/products', formData);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
console.error('Save failed', error);
|
||||
alert('خطا در ذخیره محصول');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('آیا از حذف این محصول مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/products/${id}`);
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<Package className="w-6 h-6 text-purple-600" />
|
||||
<Box className="w-6 h-6 text-purple-600" />
|
||||
مدیریت محصولات
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت کاتالوگ، موجودی انبار و اطلاعات SEO</p>
|
||||
<p className="text-gray-500 font-medium mt-1">افزودن و ویرایش پیشرفته محصولات با تنظیمات سئو</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-center gap-3 w-full sm:w-auto">
|
||||
<button
|
||||
onClick={() => openModal()}
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
محصول جدید
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در نام و کد محصول..."
|
||||
value={search}
|
||||
onChange={(e) => { 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 focus:ring-2 focus:ring-purple-200 outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative w-full sm:w-64">
|
||||
<Filter className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<select
|
||||
className="bg-white border border-gray-200 text-gray-700 px-4 py-2 rounded-xl flex items-center gap-2 font-bold hover:bg-gray-50 transition-all outline-none w-full sm:w-auto"
|
||||
value={category}
|
||||
onChange={(e) => { setCategory(e.target.value); setPage(1); }}
|
||||
value={categoryFilter}
|
||||
onChange={(e) => { setCategoryFilter(e.target.value); setPage(1); }}
|
||||
className="w-full pl-4 pr-12 py-3 rounded-xl border border-gray-200 focus:border-purple-500 focus:ring-2 focus:ring-purple-200 outline-none transition-all appearance-none"
|
||||
>
|
||||
<option value="">همه دستهبندیها</option>
|
||||
<option value="مکمل دارویی">مکمل دارویی</option>
|
||||
<option value="آرایشی و بهداشتی">آرایشی و بهداشتی</option>
|
||||
<option value="تجهیزات نگهداری">تجهیزات نگهداری</option>
|
||||
{categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
<div className="relative w-full sm:w-64">
|
||||
<Search className="w-5 h-5 text-gray-400 absolute right-3 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو (نام، بارکد)..."
|
||||
className="pl-4 pr-10 py-2 border border-gray-200 rounded-xl outline-none focus:ring-2 focus:ring-purple-500 w-full font-medium"
|
||||
dir="rtl"
|
||||
value={search}
|
||||
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
|
||||
/>
|
||||
</div>
|
||||
<button className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-xl flex items-center justify-center gap-2 font-bold transition-all w-full sm:w-auto">
|
||||
<Plus className="w-5 h-5" />
|
||||
محصول جدید
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right font-vazir">
|
||||
<thead className="bg-gray-50 text-gray-500 text-sm border-b border-gray-200">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 font-bold">نام محصول</th>
|
||||
<th className="py-4 px-6 font-bold">دستهبندی</th>
|
||||
<th className="py-4 px-6 font-bold">قیمت (تومان)</th>
|
||||
<th className="py-4 px-6 font-bold">موجودی</th>
|
||||
<th className="py-4 px-6 font-bold">وضعیت</th>
|
||||
<th className="py-4 px-6 font-bold text-center">عملیات</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">کد (Art No)</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">نام محصول</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">دستهبندی</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">موجودی / قیمت</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
Array.from({ length: 4 }).map((_, i) => (
|
||||
<tr key={i}>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-32" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-24" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-16" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-6 w-20" /></td>
|
||||
<td className="py-4 px-6"><Skeleton className="h-8 w-20 mx-auto" /></td>
|
||||
<tr>
|
||||
<td colSpan={6} className="py-12 text-center">
|
||||
<Spinner size="lg" className="mx-auto text-purple-600" />
|
||||
</td>
|
||||
</tr>
|
||||
) : products.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="py-12 text-center text-gray-500 font-medium">محصولی یافت نشد</td>
|
||||
</tr>
|
||||
) : (
|
||||
products.map((product) => (
|
||||
<tr key={product.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-3 px-6">
|
||||
{product.imageUrl ? (
|
||||
<img src={product.imageUrl.startsWith('http') ? product.imageUrl : `http://localhost:4001${product.imageUrl}`} alt={product.name} className="w-12 h-12 rounded-xl object-cover border border-gray-200" />
|
||||
) : (
|
||||
<div className="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center text-gray-400">
|
||||
<ImageIcon className="w-5 h-5" />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6 text-gray-500 font-mono text-sm">{product.artNo}</td>
|
||||
<td className="py-4 px-6 font-bold text-gray-900">{product.name}</td>
|
||||
<td className="py-4 px-6 text-gray-600 text-sm">{product.category?.name || 'بدون دسته'}</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-bold text-gray-900">{Number(product.priceValue).toLocaleString()} تومان</span>
|
||||
<span className="text-xs text-gray-500">{product.packageSize} موجودی</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => openModal(product)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(product.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
products.map((product) => {
|
||||
const isEditing = editingId === product.id;
|
||||
return (
|
||||
<tr key={product.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-4 px-6 font-bold text-gray-900">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center">
|
||||
<Package className="w-5 h-5 text-gray-400" />
|
||||
</div>
|
||||
{product.name}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-4 px-6 text-gray-500">{product.category}</td>
|
||||
<td className="py-4 px-6 font-bold text-gray-900">
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="number"
|
||||
className="border border-purple-300 rounded p-1 w-24"
|
||||
value={editForm.priceValue}
|
||||
onChange={(e) => setEditForm({...editForm, priceValue: Number(e.target.value)})}
|
||||
/>
|
||||
) : (
|
||||
product.priceValue?.toLocaleString()
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
{isEditing ? (
|
||||
<input
|
||||
type="number"
|
||||
className="border border-purple-300 rounded p-1 w-16"
|
||||
value={editForm.packageSize}
|
||||
onChange={(e) => setEditForm({...editForm, packageSize: Number(e.target.value)})}
|
||||
/>
|
||||
) : (
|
||||
<span className={`font-bold ${product.packageSize < 10 ? 'text-red-500' : 'text-gray-900'}`}>
|
||||
{product.packageSize} عدد
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<span className={`px-3 py-1 rounded-full text-xs font-bold ${
|
||||
product.packageSize > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
|
||||
}`}>
|
||||
{product.packageSize > 0 ? 'موجود' : 'ناموجود'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<button onClick={() => handleSaveEdit(product.id)} className="text-green-600 hover:bg-green-50 p-2 rounded-lg transition-colors" title="ذخیره" disabled={isSaving}>
|
||||
{isSaving ? <Spinner size="sm" /> : <Check className="w-4 h-4" />}
|
||||
</button>
|
||||
<button onClick={() => setEditingId(null)} className="text-gray-500 hover:bg-gray-50 p-2 rounded-lg transition-colors" title="لغو" disabled={isSaving}>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button onClick={() => handleEditClick(product)} className="text-blue-600 hover:bg-blue-50 p-2 rounded-lg transition-colors" title="ویرایش">
|
||||
<Edit3 className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => openDeleteModal(product.id)} className="text-red-600 hover:bg-red-50 p-2 rounded-lg transition-colors" title="حذف">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
isOpen={isDeleteModalOpen}
|
||||
title="حذف محصول"
|
||||
message="آیا از حذف این محصول اطمینان دارید؟ این عمل غیرقابل بازگشت است."
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setIsDeleteModalOpen(false)}
|
||||
|
||||
{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-4xl max-h-[90vh] flex flex-col shadow-2xl animate-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
|
||||
<h3 className="text-xl font-bold text-gray-900">
|
||||
{editingProduct ? 'ویرایش پیشرفته محصول' : 'افزودن محصول جدید'}
|
||||
</h3>
|
||||
<button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500 transition-colors">
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex border-b border-gray-100 px-6 pt-2 gap-4">
|
||||
{[
|
||||
{ id: 'general', label: 'اطلاعات پایه' },
|
||||
{ id: 'pricing', label: 'موجودی و قیمت' },
|
||||
{ id: 'seo', label: 'سئو (SEO)' },
|
||||
{ id: 'media', label: 'تصاویر' }
|
||||
].map(tab => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`pb-3 px-2 text-sm font-bold border-b-2 transition-colors ${activeTab === tab.id ? 'border-purple-600 text-purple-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-6 overflow-y-auto flex-1 bg-gray-50/30">
|
||||
<form id="productForm" onSubmit={handleSave} className="space-y-6">
|
||||
|
||||
{/* General Tab */}
|
||||
<div className={activeTab === 'general' ? 'block space-y-4' : 'hidden'}>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">کد محصول (Art No) *</label>
|
||||
<input required type="text" value={formData.artNo} onChange={(e) => setFormData({...formData, artNo: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none font-mono" dir="ltr" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نام محصول *</label>
|
||||
<input required type="text" value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<label className="text-sm font-bold text-gray-700">شعار علمی (Tagline)</label>
|
||||
<input type="text" value={formData.scientificTagline} onChange={(e) => setFormData({...formData, scientificTagline: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">دستهبندی *</label>
|
||||
<select required value={formData.categoryId} onChange={(e) => setFormData({...formData, categoryId: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none bg-white">
|
||||
<option value="">انتخاب کنید</option>
|
||||
{categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">مناسب برای</label>
|
||||
<select value={formData.suitableFor} onChange={(e) => setFormData({...formData, suitableFor: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none bg-white">
|
||||
<option value="سگ">سگ</option>
|
||||
<option value="گربه">گربه</option>
|
||||
<option value="سگ و گربه">سگ و گربه</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیح کوتاه</label>
|
||||
<textarea rows={2} value={formData.shortDescription} onChange={(e) => setFormData({...formData, shortDescription: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none"></textarea>
|
||||
</div>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیحات کامل</label>
|
||||
<textarea rows={5} value={formData.description} onChange={(e) => setFormData({...formData, description: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none"></textarea>
|
||||
</div>
|
||||
<div className="space-y-2 md:col-span-2">
|
||||
<label className="text-sm font-bold text-gray-700">منطق دوز مصرفی (Dosage Logic)</label>
|
||||
<textarea rows={2} value={formData.dosageLogic} onChange={(e) => setFormData({...formData, dosageLogic: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pricing Tab */}
|
||||
<div className={activeTab === 'pricing' ? 'block space-y-4' : 'hidden'}>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">قیمت (تومان) *</label>
|
||||
<input required type="number" min="0" value={formData.priceValue} onChange={(e) => setFormData({...formData, priceValue: Number(e.target.value)})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" dir="ltr" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نمایش قیمت (متنی) *</label>
|
||||
<input required type="text" placeholder="مثال: ۸۵۰,۰۰۰ تومان" value={formData.priceDisplay} onChange={(e) => setFormData({...formData, priceDisplay: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">موجودی *</label>
|
||||
<input required type="number" min="0" value={formData.packageSize} onChange={(e) => setFormData({...formData, packageSize: Number(e.target.value)})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" dir="ltr" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">واحد (Unit) *</label>
|
||||
<input required type="text" placeholder="عدد، گرم، میلیلیتر" value={formData.unit} onChange={(e) => setFormData({...formData, unit: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SEO Tab */}
|
||||
<div className={activeTab === 'seo' ? 'block space-y-4' : 'hidden'}>
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نامک (Slug) محصول</label>
|
||||
<input type="text" value={formData.slug} onChange={(e) => 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" dir="ltr" placeholder="مثال: canhydrox-gag" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">عنوان متا (Meta Title)</label>
|
||||
<input type="text" value={formData.metaTitle} onChange={(e) => setFormData({...formData, metaTitle: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیحات متا (Meta Description)</label>
|
||||
<textarea rows={3} value={formData.metaDescription} onChange={(e) => setFormData({...formData, metaDescription: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none"></textarea>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">کلمات کلیدی (با کاما جدا کنید)</label>
|
||||
<input type="text" value={formData.keywords} onChange={(e) => setFormData({...formData, keywords: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">آدرس کانونی (Canonical URL)</label>
|
||||
<input type="text" value={formData.canonicalUrl} onChange={(e) => setFormData({...formData, canonicalUrl: 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" dir="ltr" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Media Tab */}
|
||||
<div className={activeTab === 'media' ? 'block space-y-4' : 'hidden'}>
|
||||
<div className="flex flex-col items-center justify-center p-8 border-2 border-dashed border-gray-200 rounded-2xl bg-white">
|
||||
{formData.imageUrl ? (
|
||||
<div className="relative group">
|
||||
<img src={formData.imageUrl.startsWith('http') ? formData.imageUrl : `http://localhost:4001${formData.imageUrl}`} alt="product" className="max-w-xs h-48 object-cover rounded-xl shadow-md" />
|
||||
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-xl flex items-center justify-center gap-3">
|
||||
<button type="button" onClick={() => setIsMediaSelectorOpen(true)} className="bg-white text-gray-800 px-4 py-2 rounded-lg font-bold text-sm">تغییر عکس</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center text-gray-400 mb-4">
|
||||
<ImageIcon className="w-8 h-8" />
|
||||
</div>
|
||||
<p className="text-gray-500 font-medium mb-4">هیچ تصویری انتخاب نشده است</p>
|
||||
<button type="button" onClick={() => setIsMediaSelectorOpen(true)} className="bg-purple-100 text-purple-700 hover:bg-purple-200 px-6 py-2 rounded-xl font-bold transition-colors">
|
||||
انتخاب از گالری رسانه
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 rounded-b-2xl">
|
||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-5 py-2.5 rounded-xl font-bold text-gray-600 hover:bg-gray-200 transition-colors">
|
||||
انصراف
|
||||
</button>
|
||||
<button type="submit" form="productForm" className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2.5 rounded-xl font-bold transition-all shadow-md shadow-purple-200">
|
||||
ذخیره محصول
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Media Selector Modal */}
|
||||
<MediaSelector
|
||||
isOpen={isMediaSelectorOpen}
|
||||
onClose={() => setIsMediaSelectorOpen(false)}
|
||||
onSelect={(url) => setFormData({...formData, imageUrl: url})}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,201 +1,199 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, BarChart, Bar } from 'recharts';
|
||||
import { Download, TrendingUp, Users, HeartHandshake, PackageOpen } from 'lucide-react';
|
||||
import { TrendingUp, DollarSign, ShoppingBag, Users, HeartHandshake, Download } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import {
|
||||
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, ResponsiveContainer,
|
||||
BarChart, Bar, PieChart, Pie, Cell, Legend
|
||||
} from 'recharts';
|
||||
|
||||
const COLORS = ['#8b5cf6', '#3b82f6', '#ec4899', '#f59e0b', '#10b981'];
|
||||
const COLORS = ['#8B5CF6', '#EC4899', '#3B82F6', '#10B981', '#F59E0B'];
|
||||
|
||||
export default function Reports() {
|
||||
const [data, setData] = useState<any>(null);
|
||||
const [reportData, setReportData] = useState<any>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchReports = async () => {
|
||||
try {
|
||||
const response = await api.get('/admin/reports');
|
||||
if (response.data?.success) {
|
||||
setData(response.data.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch reports', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchReports();
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const downloadCSV = () => {
|
||||
if (!data?.salesTimeline) return;
|
||||
|
||||
const headers = ['Date', 'Revenue'];
|
||||
const rows = data.salesTimeline.map((item: any) => [item.date, item.amount]);
|
||||
|
||||
const csvContent = "data:text/csv;charset=utf-8,"
|
||||
+ headers.join(",") + "\n"
|
||||
+ rows.map((e: any) => e.join(",")).join("\n");
|
||||
|
||||
const encodedUri = encodeURI(csvContent);
|
||||
const link = document.createElement("a");
|
||||
link.setAttribute("href", encodedUri);
|
||||
link.setAttribute("download", "canina_sales_report.csv");
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const reportRes = await api.get('/admin/reports');
|
||||
if (reportRes.data?.success) {
|
||||
setReportData(reportRes.data.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="flex items-center justify-center h-[70vh]"><Spinner size="lg" className="text-purple-600" /></div>;
|
||||
return <div className="flex justify-center items-center h-96"><Spinner size="lg" className="text-purple-600" /></div>;
|
||||
}
|
||||
|
||||
if (!data) return <div>خطا در دریافت اطلاعات</div>;
|
||||
if (!reportData) return <div className="text-center py-12 text-gray-500 font-bold">اطلاعاتی یافت نشد</div>;
|
||||
|
||||
const { overview, salesTimeline, bestSellers } = data;
|
||||
const { overview, salesTimeline, bestSellers, categoryDistribution, topCoupons } = reportData;
|
||||
|
||||
const customerData = [
|
||||
{ name: 'مشتریان B2B', value: overview.b2bRevenue },
|
||||
{ name: 'مشتریان عادی', value: overview.b2cRevenue },
|
||||
];
|
||||
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="bg-white p-4 rounded-xl shadow-lg border border-gray-100">
|
||||
<p className="font-bold text-gray-900 mb-2">{label}</p>
|
||||
<p className="text-purple-600 font-bold">{Number(payload[0].value).toLocaleString()} تومان</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<TrendingUp className="w-6 h-6 text-purple-600" />
|
||||
گزارشات تحلیلی پیشرفته
|
||||
گزارشات و تحلیلها
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">نمای جامع از عملکرد فروشگاه و تحلیل رفتار مشتریان</p>
|
||||
<p className="text-gray-500 font-medium mt-1">آمار فروش، رفتار کاربران و عملکرد تخفیفها</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={downloadCSV}
|
||||
className="bg-green-600 hover:bg-green-700 text-white px-5 py-2.5 rounded-xl flex items-center justify-center gap-2 font-bold transition-all shadow-md shadow-green-200"
|
||||
>
|
||||
<button className="bg-white border-2 border-purple-200 text-purple-700 hover:bg-purple-50 px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-sm">
|
||||
<Download className="w-5 h-5" />
|
||||
دانلود خروجی CSV
|
||||
خروجی اکسل (Excel)
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Overview Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6">
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 flex items-center gap-4">
|
||||
<div className="w-14 h-14 rounded-2xl bg-purple-100 flex items-center justify-center text-purple-600">
|
||||
<TrendingUp className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-gray-500 mb-1">کل درآمد فروشگاه</p>
|
||||
<h3 className="text-2xl font-black text-gray-900">{Number(overview.totalRevenue).toLocaleString()} <span className="text-sm font-medium text-gray-500">تومان</span></h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div className="bg-gradient-to-br from-purple-500 to-indigo-600 p-6 rounded-2xl text-white shadow-lg shadow-purple-200">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-bold text-purple-100">درآمد کل</h3>
|
||||
<div className="p-2 bg-white/20 rounded-xl"><DollarSign className="w-6 h-6" /></div>
|
||||
</div>
|
||||
<p className="text-3xl font-black">{Number(overview.totalRevenue).toLocaleString()}</p>
|
||||
<p className="text-purple-200 text-sm mt-1">تومان</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 flex items-center gap-4">
|
||||
<div className="w-14 h-14 rounded-2xl bg-blue-100 flex items-center justify-center text-blue-600">
|
||||
<Users className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-gray-500 mb-1">درآمد از همکاران (B2B)</p>
|
||||
<h3 className="text-2xl font-black text-gray-900">{Number(overview.b2bRevenue).toLocaleString()} <span className="text-sm font-medium text-gray-500">تومان</span></h3>
|
||||
<div className="bg-gradient-to-br from-pink-500 to-rose-600 p-6 rounded-2xl text-white shadow-lg shadow-pink-200">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-bold text-pink-100">سهم خیریه (مسئولیت اجتماعی)</h3>
|
||||
<div className="p-2 bg-white/20 rounded-xl"><HeartHandshake className="w-6 h-6" /></div>
|
||||
</div>
|
||||
<p className="text-3xl font-black">{Number(overview.totalCharity).toLocaleString()}</p>
|
||||
<p className="text-pink-200 text-sm mt-1">تومان</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 flex items-center gap-4">
|
||||
<div className="w-14 h-14 rounded-2xl bg-pink-100 flex items-center justify-center text-pink-600">
|
||||
<HeartHandshake className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-gray-500 mb-1">مبالغ خیریه جمعآوری شده</p>
|
||||
<h3 className="text-2xl font-black text-gray-900">{Number(overview.totalCharity).toLocaleString()} <span className="text-sm font-medium text-gray-500">تومان</span></h3>
|
||||
|
||||
<div className="bg-gradient-to-br from-blue-500 to-cyan-600 p-6 rounded-2xl text-white shadow-lg shadow-blue-200">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-bold text-blue-100">فروش همکاران (B2B)</h3>
|
||||
<div className="p-2 bg-white/20 rounded-xl"><Users className="w-6 h-6" /></div>
|
||||
</div>
|
||||
<p className="text-3xl font-black">{Number(overview.b2bRevenue).toLocaleString()}</p>
|
||||
<p className="text-blue-200 text-sm mt-1">تومان</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200 flex items-center gap-4">
|
||||
<div className="w-14 h-14 rounded-2xl bg-orange-100 flex items-center justify-center text-orange-600">
|
||||
<PackageOpen className="w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-gray-500 mb-1">تعداد کل سفارشات موفق</p>
|
||||
<h3 className="text-2xl font-black text-gray-900">{overview.totalOrders} <span className="text-sm font-medium text-gray-500">سفارش</span></h3>
|
||||
|
||||
<div className="bg-gradient-to-br from-emerald-500 to-teal-600 p-6 rounded-2xl text-white shadow-lg shadow-emerald-200">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-bold text-emerald-100">تعداد سفارشات</h3>
|
||||
<div className="p-2 bg-white/20 rounded-xl"><ShoppingBag className="w-6 h-6" /></div>
|
||||
</div>
|
||||
<p className="text-3xl font-black">{overview.totalOrders}</p>
|
||||
<p className="text-emerald-200 text-sm mt-1">موفق</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Sales Timeline Area Chart */}
|
||||
<div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">روند درآمد فروشگاه</h3>
|
||||
{/* Sales Chart */}
|
||||
<div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">نمودار فروش روزانه</h3>
|
||||
<div className="h-80 w-full" dir="ltr">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={salesTimeline}>
|
||||
<AreaChart data={salesTimeline} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
|
||||
<defs>
|
||||
<linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.3}/>
|
||||
<stop offset="95%" stopColor="#8b5cf6" stopOpacity={0}/>
|
||||
<linearGradient id="colorSales" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#8B5CF6" stopOpacity={0.3}/>
|
||||
<stop offset="95%" stopColor="#8B5CF6" stopOpacity={0}/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f3f4f6" />
|
||||
<XAxis dataKey="date" stroke="#9ca3af" fontSize={12} tickMargin={10} />
|
||||
<YAxis stroke="#9ca3af" fontSize={12} tickFormatter={(val) => `${val / 1000}k`} />
|
||||
<RechartsTooltip
|
||||
formatter={(value: number) => [`${value.toLocaleString()} تومان`, 'درآمد']}
|
||||
labelStyle={{ color: '#374151', fontWeight: 'bold', marginBottom: '8px' }}
|
||||
/>
|
||||
<Area type="monotone" dataKey="amount" stroke="#8b5cf6" strokeWidth={3} fillOpacity={1} fill="url(#colorAmount)" />
|
||||
<XAxis dataKey="date" stroke="#9ca3af" fontSize={12} tickLine={false} axisLine={false} />
|
||||
<YAxis stroke="#9ca3af" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(val) => `${val / 1000}k`} />
|
||||
<RechartsTooltip content={<CustomTooltip />} />
|
||||
<Area type="monotone" dataKey="amount" stroke="#8B5CF6" strokeWidth={3} fillOpacity={1} fill="url(#colorSales)" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Customer Breakdown Pie Chart */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">درآمد به تفکیک نوع کاربر</h3>
|
||||
<div className="h-64 w-full" dir="ltr">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={customerData}
|
||||
innerRadius={60}
|
||||
outerRadius={80}
|
||||
paddingAngle={5}
|
||||
dataKey="value"
|
||||
>
|
||||
{customerData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<RechartsTooltip formatter={(value: number) => [`${value.toLocaleString()} تومان`, 'درآمد']} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
{/* Category Distribution */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">سهم فروش دستهبندیها</h3>
|
||||
<div className="h-64 w-full flex justify-center">
|
||||
{categoryDistribution?.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie data={categoryDistribution} cx="50%" cy="50%" innerRadius={60} outerRadius={80} paddingAngle={5} dataKey="value">
|
||||
{categoryDistribution.map((entry: any, index: number) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<RechartsTooltip formatter={(value) => [`${value} عدد`, 'تعداد فروش']} />
|
||||
<Legend verticalAlign="bottom" height={36} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="text-gray-400 font-medium flex items-center justify-center h-full">دادهای موجود نیست</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 space-y-3">
|
||||
{customerData.map((item, index) => (
|
||||
<div key={index} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[index] }}></span>
|
||||
<span className="text-sm font-bold text-gray-700">{item.name}</span>
|
||||
</div>
|
||||
<span className="text-sm font-bold text-gray-900">{Number(item.value).toLocaleString()} تومان</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Best Sellers */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">پرفروشترین محصولات</h3>
|
||||
<div className="h-64 w-full" dir="ltr">
|
||||
{bestSellers?.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={bestSellers} layout="vertical" margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f3f4f6" />
|
||||
<XAxis type="number" stroke="#9ca3af" fontSize={12} />
|
||||
<YAxis dataKey="name" type="category" width={120} stroke="#4b5563" fontSize={12} tickLine={false} axisLine={false} style={{ direction: 'rtl' }} />
|
||||
<RechartsTooltip cursor={{ fill: '#f3f4f6' }} />
|
||||
<Bar dataKey="quantity" fill="#EC4899" radius={[0, 4, 4, 0]} barSize={20} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
) : (
|
||||
<div className="text-gray-400 font-medium flex items-center justify-center h-full">دادهای موجود نیست</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top Products Bar Chart */}
|
||||
<div className="lg:col-span-3 bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">۵ محصول پرفروش (بر اساس تعداد فروش)</h3>
|
||||
<div className="h-80 w-full" dir="ltr">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={bestSellers}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f3f4f6" />
|
||||
<XAxis dataKey="name" stroke="#9ca3af" fontSize={12} tickMargin={10} />
|
||||
<YAxis stroke="#9ca3af" fontSize={12} />
|
||||
<RechartsTooltip
|
||||
formatter={(value: number) => [`${value} عدد`, 'تعداد فروش']}
|
||||
cursor={{ fill: '#f3f4f6' }}
|
||||
/>
|
||||
<Bar dataKey="quantity" fill="#3b82f6" radius={[4, 4, 0, 0]} barSize={40} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
{/* Top Coupons */}
|
||||
<div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100">
|
||||
<h3 className="text-lg font-bold text-gray-900 mb-6">پرکاربردترین کدهای تخفیف</h3>
|
||||
<div className="space-y-4">
|
||||
{topCoupons?.length > 0 ? (
|
||||
topCoupons.map((coupon: any, idx: number) => (
|
||||
<div key={idx} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-100">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-lg bg-orange-100 text-orange-600 font-bold flex items-center justify-center text-sm">
|
||||
#{idx + 1}
|
||||
</div>
|
||||
<span className="font-mono font-bold tracking-widest text-gray-800">{coupon.name}</span>
|
||||
</div>
|
||||
<div className="text-gray-600 font-medium">
|
||||
<span className="font-black text-gray-900 mx-1">{coupon.value}</span>بار استفاده
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-gray-400 font-medium flex items-center justify-center h-32">دادهای موجود نیست</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Search, Plus, Edit2, Trash2, BookOpen, XCircle } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import Spinner from '../components/ui/Spinner';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
|
||||
export default function Wiki() {
|
||||
const [terms, setTerms] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const limit = 10;
|
||||
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingTerm, setEditingTerm] = useState<any>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
key: '',
|
||||
term: '',
|
||||
definition: '',
|
||||
wikiId: 'general',
|
||||
metaTitle: '',
|
||||
metaDescription: '',
|
||||
keywords: ''
|
||||
});
|
||||
|
||||
const fetchTerms = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const res = await api.get('/admin/wiki', { params: { page, limit, search } });
|
||||
if (res.data?.data) {
|
||||
setTerms(res.data.data);
|
||||
setTotalPages(res.data.meta?.totalPages || 1);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
fetchTerms();
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search, page]);
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
if (editingTerm) {
|
||||
await api.put(`/admin/wiki/${editingTerm.key}`, formData);
|
||||
} else {
|
||||
await api.post('/admin/wiki', formData);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
fetchTerms();
|
||||
} catch (error) {
|
||||
console.error('Save failed', error);
|
||||
alert('خطا در ذخیره اصطلاح علمی. ممکن است کلید تکراری باشد.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (key: string) => {
|
||||
if (!window.confirm('آیا از حذف این مورد مطمئن هستید؟')) return;
|
||||
try {
|
||||
await api.delete(`/admin/wiki/${key}`);
|
||||
fetchTerms();
|
||||
} catch (error) {
|
||||
console.error('Delete failed', error);
|
||||
}
|
||||
};
|
||||
|
||||
const openModal = (term: any = null) => {
|
||||
if (term) {
|
||||
setEditingTerm(term);
|
||||
setFormData({
|
||||
key: term.key,
|
||||
term: term.term,
|
||||
definition: term.definition,
|
||||
wikiId: term.wikiId,
|
||||
metaTitle: term.metaTitle || '',
|
||||
metaDescription: term.metaDescription || '',
|
||||
keywords: term.keywords || ''
|
||||
});
|
||||
} else {
|
||||
setEditingTerm(null);
|
||||
setFormData({
|
||||
key: '', term: '', definition: '', wikiId: 'general', metaTitle: '', metaDescription: '', keywords: ''
|
||||
});
|
||||
}
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
|
||||
<BookOpen className="w-6 h-6 text-purple-600" />
|
||||
دانشنامه کانینا (Wiki)
|
||||
</h2>
|
||||
<p className="text-gray-500 font-medium mt-1">مدیریت اصطلاحات علمی، مواد تشکیلدهنده و خواص درمانی</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => openModal()}
|
||||
className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
مفهوم جدید
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-200 flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-5 h-5 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="جستجو در اصطلاحات..."
|
||||
value={search}
|
||||
onChange={(e) => { 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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-right">
|
||||
<thead className="bg-gray-50 border-b border-gray-100">
|
||||
<tr>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">شناسه (Key)</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">اصطلاح علمی</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500">محتوا (چکیده)</th>
|
||||
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-24">عملیات</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-100">
|
||||
{isLoading ? (
|
||||
<tr><td colSpan={4} className="py-12 text-center"><Spinner size="lg" className="mx-auto text-purple-600" /></td></tr>
|
||||
) : terms.length === 0 ? (
|
||||
<tr><td colSpan={4} className="py-12 text-center text-gray-500 font-medium">هیچ رکوردی یافت نشد</td></tr>
|
||||
) : (
|
||||
terms.map((t) => (
|
||||
<tr key={t.key} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="py-4 px-6 text-gray-500 font-mono text-sm">{t.key}</td>
|
||||
<td className="py-4 px-6 font-bold text-gray-900">{t.term}</td>
|
||||
<td className="py-4 px-6 text-gray-500 text-sm max-w-xs truncate">{t.definition}</td>
|
||||
<td className="py-4 px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={() => openModal(t)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"><Edit2 className="w-4 h-4" /></button>
|
||||
<button onClick={() => handleDelete(t.key)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"><Trash2 className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
|
||||
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{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 max-h-[95vh] flex flex-col shadow-2xl animate-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
|
||||
<h3 className="text-xl font-bold text-gray-900">
|
||||
{editingTerm ? 'ویرایش دانشنامه' : 'افزودن مفهوم جدید'}
|
||||
</h3>
|
||||
<button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500 transition-colors">
|
||||
<XCircle className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-6 overflow-y-auto flex-1">
|
||||
<form id="wikiForm" onSubmit={handleSave} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">شناسه یکتا (Key) *</label>
|
||||
<input required type="text" value={formData.key} disabled={!!editingTerm} dir="ltr" onChange={(e) => setFormData({...formData, key: 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 disabled:bg-gray-100" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">نام اصطلاح (Term) *</label>
|
||||
<input required type="text" value={formData.term} onChange={(e) => setFormData({...formData, term: e.target.value})} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-bold text-gray-700">توضیح علمی *</label>
|
||||
<textarea required value={formData.definition} onChange={(e) => setFormData({...formData, definition: e.target.value})} rows={5} className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-purple-500 outline-none"></textarea>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 border border-gray-200 p-4 rounded-xl bg-gray-50/50">
|
||||
<h4 className="font-bold text-purple-700 text-sm mb-2">تنظیمات سئو (SEO)</h4>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">عنوان متا</label>
|
||||
<input type="text" value={formData.metaTitle} onChange={(e) => setFormData({...formData, metaTitle: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">کلمات کلیدی</label>
|
||||
<input type="text" value={formData.keywords} onChange={(e) => setFormData({...formData, keywords: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-gray-700">توضیحات متا</label>
|
||||
<textarea rows={2} value={formData.metaDescription} onChange={(e) => setFormData({...formData, metaDescription: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:border-purple-500 outline-none text-sm"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="p-4 border-t border-gray-100 bg-gray-50 flex justify-end gap-3 rounded-b-2xl">
|
||||
<button type="button" onClick={() => setIsModalOpen(false)} className="px-5 py-2.5 rounded-xl font-bold text-gray-600 hover:bg-gray-200 transition-colors">انصراف</button>
|
||||
<button type="submit" form="wikiForm" className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2.5 rounded-xl font-bold transition-all shadow-md shadow-purple-200">ذخیره</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
font-feature-settings: "ss01", "ss02", "cv01", "cv11";
|
||||
}
|
||||
|
||||
button, a {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button, a, [role="button"], .cursor-pointer {
|
||||
@apply cursor-pointer;
|
||||
}
|
||||
|
||||
+6
-6
@@ -3,11 +3,11 @@ import { productService } from "../../../lib/services/productService";
|
||||
import type { Metadata, ResolvingMetadata } from 'next';
|
||||
|
||||
export async function generateMetadata(
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
{ params }: { params: Promise<{ slug: string }> },
|
||||
parent: ResolvingMetadata
|
||||
): Promise<Metadata> {
|
||||
const resolvedParams = await params;
|
||||
const product = await productService.getProductById(resolvedParams.id);
|
||||
const product = await productService.getProductBySlug(resolvedParams.slug);
|
||||
|
||||
if (!product) {
|
||||
return {
|
||||
@@ -37,12 +37,12 @@ export async function generateMetadata(
|
||||
};
|
||||
}
|
||||
|
||||
export default async function ShopProductPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
export default async function ShopProductPage({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const resolvedParams = await params;
|
||||
const product = await productService.getProductById(resolvedParams.id);
|
||||
const product = await productService.getProductBySlug(resolvedParams.slug);
|
||||
|
||||
if (!product) {
|
||||
return <ProductPage productId={resolvedParams.id} />;
|
||||
return <ProductPage productSlug={resolvedParams.slug} />;
|
||||
}
|
||||
|
||||
const jsonLd = {
|
||||
@@ -72,7 +72,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ id
|
||||
type="application/ld+json"
|
||||
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
|
||||
/>
|
||||
<ProductPage productId={resolvedParams.id} />
|
||||
<ProductPage productSlug={resolvedParams.slug} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -240,6 +240,9 @@ export default function ArchivePage({
|
||||
}
|
||||
|
||||
setFilteredProducts(result);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch products:", error);
|
||||
toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
|
||||
} finally {
|
||||
setIsUpdating(false);
|
||||
}
|
||||
@@ -383,7 +386,7 @@ export default function ArchivePage({
|
||||
<div key="grid" className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
|
||||
<AnimatePresence mode="popLayout">
|
||||
{filteredProducts.map((p: Product) => (
|
||||
<ArchiveProductCard key={p.id} product={p} onClick={(p) => router.push(`/shop/${p.id}`)} />
|
||||
<ArchiveProductCard key={p.id} product={p} onClick={(p) => router.push(`/shop/${p.slug || p.id}`)} />
|
||||
))}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { motion, AnimatePresence } from "motion/react";
|
||||
import { Eye, ShoppingCart, ShieldCheck, Heart, AlertCircle, Sparkles } from "lucide-react";
|
||||
import SafeImage from "./SafeImage";
|
||||
import { ProductCardSkeleton } from "./Skeleton";
|
||||
import Link from 'next/link';
|
||||
|
||||
function ProductCard({ product, onClick }: { product: Product; key?: string | number; onClick: (p: Product) => void }) {
|
||||
const { getActivePet } = usePetStore();
|
||||
@@ -51,6 +52,7 @@ function ProductCard({ product, onClick }: { product: Product; key?: string | nu
|
||||
</div>
|
||||
|
||||
{/* Hover Actions */}
|
||||
<Link href={`/shop/${product.slug || product.id}`} className="absolute inset-0 z-10" />
|
||||
<div className="absolute inset-0 bg-canina-blue/60 opacity-0 group-hover:opacity-100 backdrop-blur-sm transition-all duration-300 flex items-center justify-center gap-4">
|
||||
<div className="w-12 h-12 rounded-full bg-white text-canina-blue flex items-center justify-center hover:scale-110 transition-transform shadow-lg">
|
||||
<Eye className="w-5 h-5" />
|
||||
@@ -93,6 +95,7 @@ function ProductCard({ product, onClick }: { product: Product; key?: string | nu
|
||||
}
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function FeaturedProducts() {
|
||||
const router = useRouter();
|
||||
@@ -104,6 +107,9 @@ export default function FeaturedProducts() {
|
||||
try {
|
||||
const data = await productService.getFeaturedProducts();
|
||||
setProducts(data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch featured products:", error);
|
||||
toast.error("خطا در دریافت لیست محصولات از سرور. لطفاً صفحه را رفرش کنید.");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -141,7 +147,7 @@ export default function FeaturedProducts() {
|
||||
Array.from({ length: 3 }).map((_, i) => <ProductCardSkeleton key={i} />)
|
||||
) : (
|
||||
products.map((p) => (
|
||||
<ProductCard key={p.id} onClick={(p) => router.push(`/shop/${p.id}`)} product={p} />
|
||||
<ProductCard key={p.id} onClick={(p) => router.push(`/shop/${p.slug || p.id}`)} product={p} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -69,7 +69,7 @@ import SafeImage from "./SafeImage";
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function ProductPage({ productId }: { productId: string }) {
|
||||
export default function ProductPage({ productSlug }: { productSlug: string }) {
|
||||
const router = useRouter();
|
||||
const [product, setProduct] = useState<Product | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
@@ -82,12 +82,12 @@ export default function ProductPage({ productId }: { productId: string }) {
|
||||
productService.getProducts()
|
||||
.then((products) => {
|
||||
setAllProducts(products);
|
||||
const found = products.find(p => p.id === productId);
|
||||
const found = products.find(p => p.slug === productSlug || p.id === productSlug);
|
||||
setProduct(found || null);
|
||||
})
|
||||
.catch(err => console.error("Error fetching products in ProductPage:", err))
|
||||
.finally(() => setIsLoading(false));
|
||||
}, [productId]);
|
||||
}, [productSlug]);
|
||||
const { pets, getActivePet } = usePetStore();
|
||||
const activePet = getActivePet();
|
||||
const { petType, weight, setPetType, setWeight } = useCalculatorStore();
|
||||
@@ -102,7 +102,9 @@ export default function ProductPage({ productId }: { productId: string }) {
|
||||
|
||||
// Re-hydrate product to ensure methods like calculateDosage exist
|
||||
const fullProduct = useMemo(() => {
|
||||
if (!product) return null;
|
||||
const apiProduct = allProducts.find(p => p.id === product.id) || product;
|
||||
if (!apiProduct) return null;
|
||||
const staticProduct = PRODUCTS.find(p => p.id === apiProduct.id || p.artNo === apiProduct.artNo);
|
||||
if (staticProduct) {
|
||||
return {
|
||||
@@ -133,6 +135,7 @@ export default function ProductPage({ productId }: { productId: string }) {
|
||||
}, [activePet, setWeight, setPetType]);
|
||||
|
||||
const calculation = useMemo(() => {
|
||||
if (!fullProduct || typeof fullProduct.calculateDosage !== 'function') return null;
|
||||
const result = fullProduct.calculateDosage(weight, petType === "young");
|
||||
const duration = Math.floor(fullProduct.packageSize / result.quantity);
|
||||
|
||||
@@ -330,7 +333,8 @@ export default function ProductPage({ productId }: { productId: string }) {
|
||||
|
||||
{/* Specialist Note */}
|
||||
<section className="bg-white rounded-[3rem] p-10 border border-medical-gray-200">
|
||||
<div className="flex flex-col md:flex-row gap-10 items-start">
|
||||
{product.specialist && (
|
||||
<div className="flex flex-col md:flex-row gap-10 items-start">
|
||||
<img
|
||||
src={product.specialist.image}
|
||||
alt={product.specialist.name}
|
||||
@@ -348,6 +352,7 @@ export default function ProductPage({ productId }: { productId: string }) {
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Specialized Landing Banner */}
|
||||
|
||||
@@ -64,7 +64,7 @@ export default function SearchResultsPage({ query }: { query: string }) {
|
||||
<motion.div
|
||||
key={product.id}
|
||||
layoutId={product.id}
|
||||
onClick={() => router.push(`/shop/${product.id}`)}
|
||||
onClick={() => router.push(`/shop/${product.slug || product.id}`)}
|
||||
className="bg-white rounded-[2.5rem] p-8 border border-medical-gray-200 group cursor-pointer hover:shadow-2xl hover:shadow-canina-blue/10 transition-all flex flex-col relative"
|
||||
>
|
||||
<div className="relative aspect-square mb-8 bg-medical-gray-50 rounded-[2rem] overflow-hidden p-6 flex items-center justify-center">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import React, { useState } from "react";
|
||||
import { Play, PlayCircle, Star, ShieldCheck, X } from "lucide-react";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const VIDEOS = [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const baseURL = typeof window !== 'undefined' ? '/api' : (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api');
|
||||
const baseURL = typeof window !== 'undefined' ? '/api' : (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4001/api');
|
||||
|
||||
const api = axios.create({
|
||||
baseURL,
|
||||
|
||||
@@ -92,6 +92,16 @@ export class ProductService {
|
||||
}
|
||||
}
|
||||
|
||||
public async getProductBySlug(slug: string): Promise<Product | null> {
|
||||
try {
|
||||
const response = await api.get(`/products/${slug}`);
|
||||
return this.mapBackendToFrontend(response.data);
|
||||
} catch (error) {
|
||||
console.error(`[ProductService] Failed to fetch product ${slug}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getFeaturedProducts(): Promise<Product[]> {
|
||||
try {
|
||||
const response = await api.get('/products');
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
destination: 'http://localhost:4001/api/:path*',
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Reference in new issue
Block a user