diff --git a/backend/package-lock.json b/backend/package-lock.json index 3ca9ae10..29f0eb2f 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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", diff --git a/backend/package.json b/backend/package.json index 98b66649..243637ad 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 40d44f0f..969fd182 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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") } diff --git a/backend/prisma/seed-products.ts b/backend/prisma/seed-products.ts new file mode 100644 index 00000000..e9040f10 --- /dev/null +++ b/backend/prisma/seed-products.ts @@ -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(); + }); diff --git a/backend/prisma/seed.ts b/backend/prisma/seed.ts index 815f38b1..9b206b01 100644 --- a/backend/prisma/seed.ts +++ b/backend/prisma/seed.ts @@ -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: "تخصص دارویی از آلمان", diff --git a/backend/src/admin/admin.controller.ts b/backend/src/admin/admin.controller.ts index bc1408e9..4c72e011 100644 --- a/backend/src/admin/admin.controller.ts +++ b/backend/src/admin/admin.controller.ts @@ -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) { diff --git a/backend/src/admin/admin.module.ts b/backend/src/admin/admin.module.ts index 50b66fd2..978f49d8 100644 --- a/backend/src/admin/admin.module.ts +++ b/backend/src/admin/admin.module.ts @@ -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 {} diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts index f281a10c..31c17e2d 100644 --- a/backend/src/admin/admin.service.ts +++ b/backend/src/admin/admin.service.ts @@ -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 } }); } diff --git a/backend/src/admin/blogs.controller.ts b/backend/src/admin/blogs.controller.ts new file mode 100644 index 00000000..b2588c8f --- /dev/null +++ b/backend/src/admin/blogs.controller.ts @@ -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 }; + } +} diff --git a/backend/src/admin/blogs.service.ts b/backend/src/admin/blogs.service.ts new file mode 100644 index 00000000..cffab493 --- /dev/null +++ b/backend/src/admin/blogs.service.ts @@ -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 } }); + } +} diff --git a/backend/src/admin/categories.controller.ts b/backend/src/admin/categories.controller.ts new file mode 100644 index 00000000..3b631920 --- /dev/null +++ b/backend/src/admin/categories.controller.ts @@ -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 }; + } +} diff --git a/backend/src/admin/categories.service.ts b/backend/src/admin/categories.service.ts new file mode 100644 index 00000000..78d77baf --- /dev/null +++ b/backend/src/admin/categories.service.ts @@ -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 } }); + } +} diff --git a/backend/src/admin/media.controller.ts b/backend/src/admin/media.controller.ts new file mode 100644 index 00000000..c02718c2 --- /dev/null +++ b/backend/src/admin/media.controller.ts @@ -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 }; + } +} diff --git a/backend/src/admin/media.service.ts b/backend/src/admin/media.service.ts new file mode 100644 index 00000000..d3c77caa --- /dev/null +++ b/backend/src/admin/media.service.ts @@ -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 }; + } +} diff --git a/backend/src/admin/pets.controller.ts b/backend/src/admin/pets.controller.ts new file mode 100644 index 00000000..506cd283 --- /dev/null +++ b/backend/src/admin/pets.controller.ts @@ -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 }; + } +} diff --git a/backend/src/admin/pets.service.ts b/backend/src/admin/pets.service.ts new file mode 100644 index 00000000..10c6ee2d --- /dev/null +++ b/backend/src/admin/pets.service.ts @@ -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 } }); + } +} diff --git a/backend/src/admin/reports.service.ts b/backend/src/admin/reports.service.ts index 02735748..52dc840a 100644 --- a/backend/src/admin/reports.service.ts +++ b/backend/src/admin/reports.service.ts @@ -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 = {}; + 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 })) }; } } diff --git a/backend/src/admin/wiki.controller.ts b/backend/src/admin/wiki.controller.ts new file mode 100644 index 00000000..296c865b --- /dev/null +++ b/backend/src/admin/wiki.controller.ts @@ -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 }; + } +} diff --git a/backend/src/admin/wiki.service.ts b/backend/src/admin/wiki.service.ts new file mode 100644 index 00000000..0aeb2209 --- /dev/null +++ b/backend/src/admin/wiki.service.ts @@ -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 } }); + } +} diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 0d357f3f..9122066e 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -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), }, }; diff --git a/backend/src/auth/jwt.strategy.ts b/backend/src/auth/jwt.strategy.ts index 524ad225..77e30a24 100644 --- a/backend/src/auth/jwt.strategy.ts +++ b/backend/src/auth/jwt.strategy.ts @@ -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); diff --git a/backend/src/main.ts b/backend/src/main.ts index 1abc48cc..d81a1394 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -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(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 diff --git a/backend/src/products/products.service.ts b/backend/src/products/products.service.ts index 2d734320..1b27bb36 100644 --- a/backend/src/products/products.service.ts +++ b/backend/src/products/products.service.ts @@ -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, diff --git a/backend/uploads/1781288429353-508765350.jpg b/backend/uploads/1781288429353-508765350.jpg new file mode 100644 index 00000000..a9b4b946 Binary files /dev/null and b/backend/uploads/1781288429353-508765350.jpg differ diff --git a/frontend/admin-panel/package-lock.json b/frontend/admin-panel/package-lock.json index be959c39..f59cc53f 100644 --- a/frontend/admin-panel/package-lock.json +++ b/frontend/admin-panel/package-lock.json @@ -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", diff --git a/frontend/admin-panel/package.json b/frontend/admin-panel/package.json index 6b7b87e6..bdcb402b 100644 --- a/frontend/admin-panel/package.json +++ b/frontend/admin-panel/package.json @@ -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" diff --git a/frontend/admin-panel/src/App.tsx b/frontend/admin-panel/src/App.tsx index 99910166..296e4c62 100644 --- a/frontend/admin-panel/src/App.tsx +++ b/frontend/admin-panel/src/App.tsx @@ -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 ( + } /> }> @@ -24,6 +30,10 @@ function App() { } /> } /> } /> + } /> + } /> + } /> + } /> diff --git a/frontend/admin-panel/src/components/Sidebar.tsx b/frontend/admin-panel/src/components/Sidebar.tsx index dcd52cfd..109f6096 100644 --- a/frontend/admin-panel/src/components/Sidebar.tsx +++ b/frontend/admin-panel/src/components/Sidebar.tsx @@ -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) {