Fix Admin panel categories modal, add error handling, enforce cursor-pointer globally

This commit is contained in:
parsa committed 2026-06-12 21:57:09 +03:30
1 parent 69502fc380
commit 82ab454647
47 files changed
+2968 -653

No files matched your search

+21 -7
View File
@@ -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) {
+12 -2
View File
@@ -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 {}
+139 -29
View File
@@ -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 }
});
}
+32
View File
@@ -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 };
}
}
+48
View File
@@ -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 };
}
}
+62
View File
@@ -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 } });
}
}
+32
View File
@@ -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 };
}
}
+60
View File
@@ -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 };
}
}
+20
View File
@@ -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 };
}
}
+36
View File
@@ -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 } });
}
}
+25 -2
View File
@@ -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 }))
};
}
}
+32
View File
@@ -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 };
}
}
+45
View File
@@ -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 } });
}
}