feat: implement advanced reports, pagination for all tables, global settings, and discounts modules

This commit is contained in:
parsa committed 2026-06-12 16:28:06 +03:30
1 parent a7ebb8d792
commit 69502fc380
14 files changed
+1042 -71

No files matched your search

+69 -19
View File
@@ -1,4 +1,4 @@
import { Controller, Get, UseGuards, Param, Put, Body } 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';
@@ -18,12 +18,14 @@ export class AdminController {
@UseGuards(JwtAuthGuard)
@Get('users')
async getUsers() {
const users = await this.adminService.getUsers();
return {
success: true,
data: users
};
async getUsers(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('role') role?: string
) {
const data = await this.adminService.getUsers({ page, limit, search, role });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@@ -38,12 +40,14 @@ export class AdminController {
@UseGuards(JwtAuthGuard)
@Get('products')
async getProducts() {
const products = await this.adminService.getProducts();
return {
success: true,
data: products
};
async getProducts(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('category') category?: string
) {
const data = await this.adminService.getProducts({ page, limit, search, category });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@@ -68,12 +72,14 @@ export class AdminController {
@UseGuards(JwtAuthGuard)
@Get('orders')
async getOrders() {
const orders = await this.adminService.getOrders();
return {
success: true,
data: orders
};
async getOrders(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('status') status?: string
) {
const data = await this.adminService.getOrders({ page, limit, search, status });
return { success: true, ...data };
}
@UseGuards(JwtAuthGuard)
@@ -85,4 +91,48 @@ export class AdminController {
data: order
};
}
// --- Coupons ---
@UseGuards(JwtAuthGuard)
@Get('coupons')
async getCoupons() {
const coupons = await this.adminService.getCoupons();
return { success: true, data: coupons };
}
@UseGuards(JwtAuthGuard)
@Post('coupons')
async createCoupon(@Body() data: { code: string; discountValue: number }) {
const coupon = await this.adminService.createCoupon(data);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Put('coupons/:id/toggle')
async toggleCoupon(@Param('id') id: string, @Body('isActive') isActive: boolean) {
const coupon = await this.adminService.toggleCoupon(id, isActive);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Delete('coupons/:id')
async deleteCoupon(@Param('id') id: string) {
await this.adminService.deleteCoupon(id);
return { success: true };
}
// --- Settings ---
@UseGuards(JwtAuthGuard)
@Get('settings')
async getSettings() {
const settings = await this.adminService.getSettings();
return { success: true, data: settings };
}
@UseGuards(JwtAuthGuard)
@Put('settings')
async updateSettings(@Body() data: Record<string, string>) {
const settings = await this.adminService.updateSettings(data);
return { success: true, data: settings };
}
}
+4 -2
View File
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { ReportsController } from './reports.controller';
import { ReportsService } from './reports.service';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [AdminController],
providers: [AdminService]
controllers: [AdminController, ReportsController],
providers: [AdminService, ReportsService],
})
export class AdminModule {}
+127 -16
View File
@@ -30,10 +30,34 @@ export class AdminService {
};
}
async getUsers() {
return this.prisma.user.findMany({
orderBy: { createdAt: 'desc' },
});
async getUsers(query: any) {
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 = [
{ firstName: { contains: query.search, mode: 'insensitive' } },
{ lastName: { contains: query.search, mode: 'insensitive' } },
{ email: { contains: query.search, mode: 'insensitive' } },
{ mobile: { contains: query.search } }
];
}
if (query.role) {
if (query.role === 'B2B') {
where.role = { contains: 'B2B' };
} else {
where.role = query.role;
}
}
const [data, total] = await Promise.all([
this.prisma.user.findMany({ where, skip, take: limit, orderBy: { createdAt: 'desc' } }),
this.prisma.user.count({ where })
]);
return { data, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } };
}
async updateUserRole(id: string, role: string) {
@@ -43,10 +67,28 @@ export class AdminService {
});
}
async getProducts() {
return this.prisma.product.findMany({
orderBy: { createdAt: 'desc' },
});
async getProducts(query: any) {
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 [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 updateProduct(id: string, data: any) {
@@ -65,14 +107,28 @@ export class AdminService {
});
}
async getOrders() {
return this.prisma.order.findMany({
orderBy: { createdAt: 'desc' },
include: {
user: true,
orderItems: true
}
});
async getOrders(query: any) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
if (query.search) {
where.id = { contains: query.search };
}
if (query.status) {
where.status = query.status;
}
const [data, total] = await Promise.all([
this.prisma.order.findMany({
where, skip, take: limit, orderBy: { createdAt: 'desc' },
include: { user: true, orderItems: true }
}),
this.prisma.order.count({ where })
]);
return { data, meta: { total, page, limit, totalPages: Math.ceil(total / limit) } };
}
async updateOrderStatus(id: string, status: string) {
@@ -81,4 +137,59 @@ export class AdminService {
data: { status }
});
}
// --- Coupons ---
async getCoupons() {
return this.prisma.coupon.findMany({
orderBy: { createdAt: 'desc' },
include: { _count: { select: { orders: true } } }
});
}
async createCoupon(data: { code: string; discountValue: number }) {
return this.prisma.coupon.create({
data: {
code: data.code,
discountValue: data.discountValue,
}
});
}
async toggleCoupon(id: string, isActive: boolean) {
return this.prisma.coupon.update({
where: { id },
data: { isActive }
});
}
async deleteCoupon(id: string) {
return this.prisma.coupon.delete({
where: { id }
});
}
// --- Settings ---
async getSettings() {
const keys = ['SHIPPING_FEE', 'MIN_ORDER_AMOUNT', 'B2B_DISCOUNT_PERCENT', 'MAINTENANCE_MODE'];
const settings = await this.prisma.uiText.findMany({
where: { key: { in: keys } }
});
// Transform to an object { SHIPPING_FEE: '50000', ... }
return settings.reduce((acc, curr) => ({ ...acc, [curr.key]: curr.value }), {});
}
async updateSettings(data: Record<string, string>) {
// Upsert all keys
const operations = Object.entries(data).map(([key, value]) => {
return this.prisma.uiText.upsert({
where: { key },
update: { value: String(value) },
create: { key, value: String(value) }
});
});
await this.prisma.$transaction(operations);
return this.getSettings();
}
}
+15
View File
@@ -0,0 +1,15 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ReportsService } from './reports.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
@Controller('admin/reports')
export class ReportsController {
constructor(private readonly reportsService: ReportsService) {}
@UseGuards(JwtAuthGuard)
@Get()
async getReports() {
const data = await this.reportsService.getDashboardReports();
return { success: true, data };
}
}
+80
View File
@@ -0,0 +1,80 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class ReportsService {
constructor(private prisma: PrismaService) {}
async getDashboardReports() {
// 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 } } }
});
let totalRevenue = 0;
let totalCharity = 0;
let b2bRevenue = 0;
let b2cRevenue = 0;
const salesByDate: Record<string, number> = {};
for (const order of orders) {
const amount = Number(order.totalAmount);
totalRevenue += amount;
totalCharity += Number(order.charityDonation);
if (order.user?.role === 'B2B') {
b2bRevenue += amount;
} else {
b2cRevenue += amount;
}
// Format date YYYY-MM-DD
const dateKey = order.createdAt.toISOString().split('T')[0];
if (!salesByDate[dateKey]) salesByDate[dateKey] = 0;
salesByDate[dateKey] += amount;
}
// Format sales timeline for charts
const salesTimeline = Object.entries(salesByDate)
.map(([date, amount]) => ({ date, amount }))
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
// 2. Best selling products (by quantity)
const orderItems = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: { order: { status: { not: 'cancelled' } }, productId: { not: null } },
orderBy: { _sum: { quantity: 'desc' } },
take: 5
});
// Fetch product names for top 5
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, name: true }
});
const bestSellers = orderItems.map(item => {
const p = productsInfo.find(prod => prod.id === item.productId);
return {
name: p ? p.name : 'Unknown Product',
quantity: item._sum.quantity || 0
};
});
return {
overview: {
totalRevenue,
totalCharity,
totalOrders: orders.length,
b2bRevenue,
b2cRevenue,
},
salesTimeline,
bestSellers
};
}
}