style: apply standard ESLint & Prettier formatting across backend
Deploy Canina / deploy (push) Successful in 4m58s

This commit is contained in:
parsa aghaei committed 2026-07-29 15:41:53 +03:30
1 parent ae636c8b03
commit 62bd8811fa
66 files changed
+1398 -607

No files matched your search

+68 -19
View File
@@ -1,7 +1,22 @@
import { Controller, Get, UseGuards, Param, Put, Post, Body, Delete, Query } from '@nestjs/common';
import {
Controller,
Get,
UseGuards,
Param,
Put,
Post,
Body,
Delete,
Query,
} from '@nestjs/common';
import { AdminService } from './admin.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - پنل مدیریت')
@ApiBearerAuth()
@@ -16,7 +31,7 @@ export class AdminController {
const stats = await this.adminService.getDashboardStats();
return {
success: true,
data: stats
data: stats,
};
}
@@ -25,15 +40,28 @@ export class AdminController {
@ApiOperation({ summary: 'لیست کاربران' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو در نام یا ایمیل' })
@ApiQuery({ name: 'role', required: false, description: 'فیلتر بر اساس نقش کاربر' })
@ApiQuery({
name: 'search',
required: false,
description: 'جستجو در نام یا ایمیل',
})
@ApiQuery({
name: 'role',
required: false,
description: 'فیلتر بر اساس نقش کاربر',
})
async getUsers(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('role') role?: string
@Query('role') role?: string,
) {
const data = await this.adminService.getUsers({ page, limit, search, role });
const data = await this.adminService.getUsers({
page,
limit,
search,
role,
});
return { success: true, ...data };
}
@@ -44,7 +72,7 @@ export class AdminController {
const user = await this.adminService.updateUserRole(id, role);
return {
success: true,
data: user
data: user,
};
}
@@ -54,14 +82,23 @@ export class AdminController {
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({ name: 'categoryId', required: false, description: 'شناسه دسته‌بندی' })
@ApiQuery({
name: 'categoryId',
required: false,
description: 'شناسه دسته‌بندی',
})
async getProducts(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('categoryId') categoryId?: string
@Query('categoryId') categoryId?: string,
) {
const data = await this.adminService.getProducts({ page, limit, search, categoryId });
const data = await this.adminService.getProducts({
page,
limit,
search,
categoryId,
});
return { success: true, ...data };
}
@@ -80,7 +117,7 @@ export class AdminController {
const product = await this.adminService.updateProduct(id, data);
return {
success: true,
data: product
data: product,
};
}
@@ -91,7 +128,7 @@ export class AdminController {
await this.adminService.deleteProduct(id);
return {
success: true,
message: 'Product deleted'
message: 'Product deleted',
};
}
@@ -106,9 +143,14 @@ export class AdminController {
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('status') status?: string
@Query('status') status?: string,
) {
const data = await this.adminService.getOrders({ page, limit, search, status });
const data = await this.adminService.getOrders({
page,
limit,
search,
status,
});
return { success: true, ...data };
}
@@ -118,12 +160,16 @@ export class AdminController {
async updateOrderStatus(
@Param('id') id: string,
@Body('status') status: string,
@Body('trackingNumber') trackingNumber?: string
@Body('trackingNumber') trackingNumber?: string,
) {
const order = await this.adminService.updateOrderStatus(id, status, trackingNumber);
const order = await this.adminService.updateOrderStatus(
id,
status,
trackingNumber,
);
return {
success: true,
data: order
data: order,
};
}
@@ -158,7 +204,10 @@ export class AdminController {
@UseGuards(JwtAuthGuard)
@Put('coupons/:id/toggle')
@ApiOperation({ summary: 'فعال/غیرفعال کردن کد تخفیف' })
async toggleCoupon(@Param('id') id: string, @Body('isActive') isActive: boolean) {
async toggleCoupon(
@Param('id') id: string,
@Body('isActive') isActive: boolean,
) {
const coupon = await this.adminService.toggleCoupon(id, isActive);
return { success: true, data: coupon };
}
+18 -2
View File
@@ -18,7 +18,23 @@ import { RedisModule } from '../redis/redis.module';
@Module({
imports: [PrismaModule, RedisModule],
controllers: [AdminController, ReportsController, MediaController, CategoriesController, BlogsController, WikiController, PetsController],
providers: [AdminService, ReportsService, MediaService, CategoriesService, BlogsService, WikiService, PetsService],
controllers: [
AdminController,
ReportsController,
MediaController,
CategoriesController,
BlogsController,
WikiController,
PetsController,
],
providers: [
AdminService,
ReportsService,
MediaService,
CategoriesService,
BlogsService,
WikiService,
PetsService,
],
})
export class AdminModule {}
+121 -77
View File
@@ -13,14 +13,14 @@ export class AdminService {
// total revenue
const orders = await this.prisma.order.findMany({
where: { status: { not: 'failed' } },
select: { totalAmount: true }
select: { totalAmount: true },
});
const revenue = orders.reduce((sum, o) => sum + Number(o.totalAmount), 0);
// new orders count (processing status)
const newOrders = await this.prisma.order.count({
where: { status: 'processing' }
where: { status: 'processing' },
});
// active users count
@@ -40,7 +40,7 @@ export class AdminService {
revenue,
newOrders,
users,
todayVisits
todayVisits,
};
}
@@ -55,7 +55,7 @@ export class AdminService {
{ firstName: { contains: query.search, mode: 'insensitive' } },
{ lastName: { contains: query.search, mode: 'insensitive' } },
{ email: { contains: query.search, mode: 'insensitive' } },
{ mobile: { contains: query.search } }
{ mobile: { contains: query.search } },
];
}
if (query.role) {
@@ -67,17 +67,25 @@ export class AdminService {
}
const [data, total] = await Promise.all([
this.prisma.user.findMany({ where, skip, take: limit, orderBy: { createdAt: 'desc' } }),
this.prisma.user.count({ where })
this.prisma.user.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
}),
this.prisma.user.count({ where }),
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
};
}
async updateUserRole(id: string, role: string) {
return this.prisma.user.update({
where: { id },
data: { role }
data: { role },
});
}
@@ -91,7 +99,7 @@ export class AdminService {
if (query.search) {
where.OR = [
{ name: { contains: query.search, mode: 'insensitive' } },
{ artNo: { contains: query.search } }
{ artNo: { contains: query.search } },
];
}
if (query.categoryId) {
@@ -99,16 +107,22 @@ export class AdminService {
}
const [data, total] = await Promise.all([
this.prisma.product.findMany({
where, skip, take: limit, orderBy: { createdAt: 'desc' },
include: { category: true, symptoms: true }
this.prisma.product.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: { category: true, symptoms: true },
}),
this.prisma.product.count({ where })
this.prisma.product.count({ where }),
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
};
} catch (error) {
console.error("[AdminService] getProducts error:", error);
console.error('[AdminService] getProducts error:', error);
throw new HttpException(error.message || 'Error fetching products', 500);
}
}
@@ -136,15 +150,17 @@ export class AdminService {
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
slug: data.slug || data.artNo,
}
},
});
if (data.symptoms && Array.isArray(data.symptoms)) {
await this.prisma.productSymptom.createMany({
data: data.symptoms.map((s: string) => ({
productId: product.id,
symptom: s.trim()
})).filter((s: any) => s.symptom.length > 0)
data: data.symptoms
.map((s: string) => ({
productId: product.id,
symptom: s.trim(),
}))
.filter((s: any) => s.symptom.length > 0),
});
}
@@ -175,17 +191,19 @@ export class AdminService {
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
slug: data.slug || data.artNo,
}
},
});
if (data.symptoms !== undefined && Array.isArray(data.symptoms)) {
await this.prisma.productSymptom.deleteMany({ where: { productId: id } });
if (data.symptoms.length > 0) {
await this.prisma.productSymptom.createMany({
data: data.symptoms.map((s: string) => ({
productId: id,
symptom: s.trim()
})).filter((s: any) => s.symptom.length > 0)
data: data.symptoms
.map((s: string) => ({
productId: id,
symptom: s.trim(),
}))
.filter((s: any) => s.symptom.length > 0),
});
}
}
@@ -209,9 +227,11 @@ export class AdminService {
where.OR = [
{ id: { contains: query.search } },
{ trackingNumber: { contains: query.search, mode: 'insensitive' } },
{ user: { firstName: { contains: query.search, mode: 'insensitive' } } },
{
user: { firstName: { contains: query.search, mode: 'insensitive' } },
},
{ user: { lastName: { contains: query.search, mode: 'insensitive' } } },
{ user: { phone: { contains: query.search } } }
{ user: { phone: { contains: query.search } } },
];
}
if (query.status) {
@@ -219,25 +239,28 @@ export class AdminService {
}
const [data, total] = await Promise.all([
this.prisma.order.findMany({
where,
skip,
take: limit,
this.prisma.order.findMany({
where,
skip,
take: limit,
orderBy: { createdAt: 'desc' },
include: {
user: true,
include: {
user: true,
orderItems: {
include: {
product: true
}
product: true,
},
},
coupon: true
}
coupon: true,
},
}),
this.prisma.order.count({ where })
this.prisma.order.count({ where }),
]);
return { data, meta: { total, page, limit, lastPage: Math.ceil(total / limit) } };
return {
data,
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
};
}
async updateOrderStatus(id: string, status: string, trackingNumber?: string) {
@@ -252,10 +275,10 @@ export class AdminService {
user: true,
orderItems: {
include: {
product: true
}
}
}
product: true,
},
},
},
});
}
@@ -263,23 +286,30 @@ export class AdminService {
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 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
include: { targets: true }, // Include polymorphic targets
}),
this.prisma.coupon.count({ where })
this.prisma.coupon.count({ where }),
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
},
};
}
@@ -294,16 +324,19 @@ export class AdminService {
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
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 }
include: { targets: true },
});
}
@@ -322,41 +355,52 @@ export class AdminService {
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
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 }
include: { targets: true },
});
}
async toggleCoupon(id: string, isActive: boolean) {
return this.prisma.coupon.update({
where: { id },
data: { isActive }
data: { isActive },
});
}
async deleteCoupon(id: string) {
return this.prisma.coupon.delete({
where: { id }
where: { id },
});
}
// --- Settings ---
async getSettings() {
const keys = ['SHIPPING_FEE', 'MIN_ORDER_AMOUNT', 'B2B_DISCOUNT_PERCENT', 'MAINTENANCE_MODE'];
const keys = [
'SHIPPING_FEE',
'MIN_ORDER_AMOUNT',
'B2B_DISCOUNT_PERCENT',
'MAINTENANCE_MODE',
];
const settings = await this.prisma.uiText.findMany({
where: { key: { in: keys } }
where: { key: { in: keys } },
});
// Transform to an object { SHIPPING_FEE: '50000', ... }
return settings.reduce((acc, curr) => ({ ...acc, [curr.key]: curr.value }), {});
return settings.reduce(
(acc, curr) => ({ ...acc, [curr.key]: curr.value }),
{},
);
}
async updateSettings(data: Record<string, string>) {
@@ -365,10 +409,10 @@ export class AdminService {
return this.prisma.uiText.upsert({
where: { key },
update: { value: String(value) },
create: { key, value: String(value) }
create: { key, value: String(value) },
});
});
await this.prisma.$transaction(operations);
return this.getSettings();
}
+18 -2
View File
@@ -1,7 +1,23 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards, Request } from '@nestjs/common';
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';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - مدیریت مقالات (بلاگ)')
@ApiBearerAuth()
+15 -8
View File
@@ -8,29 +8,36 @@ export class BlogsService {
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 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 } } }
include: { author: { select: { firstName: true, lastName: true } } },
}),
this.prisma.blog.count({ where })
this.prisma.blog.count({ where }),
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
},
};
}
async createBlog(data: any, authorId: string) {
return this.prisma.blog.create({
data: { ...data, authorId }
return this.prisma.blog.create({
data: { ...data, authorId },
});
}
+17 -2
View File
@@ -1,7 +1,22 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
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';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - مدیریت دسته‌بندی‌ها')
@ApiBearerAuth()
+19 -11
View File
@@ -8,22 +8,29 @@ export class CategoriesService {
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 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' }
orderBy: { createdAt: 'desc' },
}),
this.prisma.category.count({ where })
this.prisma.category.count({ where }),
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
},
};
}
@@ -33,21 +40,22 @@ export class CategoriesService {
async createCategory(data: any) {
const cleanData = { ...data };
Object.keys(cleanData).forEach(k => {
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();
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 => {
Object.keys(cleanData).forEach((k) => {
if (cleanData[k] === '') cleanData[k] = null;
});
+11 -1
View File
@@ -1,4 +1,14 @@
import { Controller, Get, Post, Delete, Param, UseGuards, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
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';
+7 -3
View File
@@ -9,7 +9,7 @@ export class MediaService {
async getAllMedia() {
return this.prisma.media.findMany({
orderBy: { createdAt: 'desc' }
orderBy: { createdAt: 'desc' },
});
}
@@ -39,7 +39,7 @@ export class MediaService {
url,
mimetype: file.mimetype,
size: file.size,
}
},
});
return media;
@@ -49,7 +49,11 @@ export class MediaService {
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));
const filePath = path.join(
process.cwd(),
'uploads',
path.basename(media.url),
);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
+14 -2
View File
@@ -1,7 +1,19 @@
import { Controller, Get, Delete, Param, Query, UseGuards } from '@nestjs/common';
import {
Controller,
Get,
Delete,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { PetsService } from './pets.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - مدیریت حیوانات خانگی')
@ApiBearerAuth()
+22 -6
View File
@@ -8,23 +8,39 @@ export class PetsService {
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 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 } } }
include: {
user: {
select: {
firstName: true,
lastName: true,
email: true,
mobile: true,
},
},
},
}),
this.prisma.pet.count({ where })
this.prisma.pet.count({ where }),
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
},
};
}
+33 -17
View File
@@ -9,7 +9,12 @@ export class ReportsService {
// 1. Total revenue and charity
const orders = await this.prisma.order.findMany({
where: { status: { not: 'cancelled' } },
select: { totalAmount: true, charityDonation: true, createdAt: true, user: { select: { role: true } } }
select: {
totalAmount: true,
charityDonation: true,
createdAt: true,
user: { select: { role: true } },
},
});
let totalRevenue = 0;
@@ -23,7 +28,7 @@ export class ReportsService {
const amount = Number(order.totalAmount);
totalRevenue += amount;
totalCharity += Number(order.charityDonation);
if (order.user?.role === 'B2B') {
b2bRevenue += amount;
} else {
@@ -45,23 +50,28 @@ export class ReportsService {
const orderItems = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: { order: { status: { not: 'cancelled' } }, productId: { not: null } },
where: {
order: { status: { not: 'cancelled' } },
productId: { not: null },
},
orderBy: { _sum: { quantity: 'desc' } },
take: 5
take: 5,
});
// Fetch product names for top 5
const topProductsIds = orderItems.map(item => item.productId).filter(Boolean) as string[];
const topProductsIds = orderItems
.map((item) => item.productId)
.filter(Boolean) as string[];
const productsInfo = await this.prisma.product.findMany({
where: { id: { in: topProductsIds } },
select: { id: true, nameFa: true, nameEn: true }
select: { id: true, nameFa: true, nameEn: true },
});
const bestSellers = orderItems.map(item => {
const p = productsInfo.find(prod => prod.id === item.productId);
const bestSellers = orderItems.map((item) => {
const p = productsInfo.find((prod) => prod.id === item.productId);
return {
name: p ? `${p.nameFa} (${p.nameEn})` : 'محصول نامشخص',
quantity: item._sum.quantity || 0
quantity: item._sum.quantity || 0,
};
});
@@ -72,18 +82,24 @@ export class ReportsService {
// 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);
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 }
select: { code: true, usedCount: true },
});
return {
@@ -97,7 +113,7 @@ export class ReportsService {
salesTimeline,
bestSellers,
categoryDistribution: catSalesDist,
topCoupons: topCoupons.map(c => ({ name: c.code, value: c.usedCount }))
topCoupons: topCoupons.map((c) => ({ name: c.code, value: c.usedCount })),
};
}
}
+17 -2
View File
@@ -1,7 +1,22 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
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';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - مدیریت دانشنامه (اصطلاحات علمی)')
@ApiBearerAuth()
+19 -8
View File
@@ -8,22 +8,29 @@ export class WikiService {
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 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' }
orderBy: { term: 'asc' },
}),
this.prisma.scientificTerm.count({ where })
this.prisma.scientificTerm.count({ where }),
]);
return {
data,
meta: { total, page: Number(page), limit: Number(limit), lastPage: Math.ceil(total / Number(limit)) }
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
},
};
}
@@ -32,13 +39,17 @@ export class WikiService {
}
async updateTerm(key: string, data: any) {
const term = await this.prisma.scientificTerm.findUnique({ where: { key } });
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 } });
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 } });
}