feat: add charity reporting & financial breakdowns in admin, fix mobile scroll restoration and OTP numeric keyboard
Deploy Canina / deploy (push) Successful in 1m44s

This commit is contained in:
parsa committed 2026-08-26 00:12:33 +03:30
1 parent 7b89e141c5
commit cf9ae234b9
230 files changed
+266394 -123714

No files matched your search

+5
View File
@@ -2,6 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { AdminService } from './admin.service';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
describe('AdminService', () => {
let service: AdminService;
@@ -12,6 +13,10 @@ describe('AdminService', () => {
AdminService,
{ provide: PrismaService, useValue: {} },
{ provide: RedisService, useValue: {} },
{
provide: RevalidationService,
useValue: { revalidateTag: jest.fn(), revalidatePath: jest.fn() },
},
],
}).compile();
+23 -5
View File
@@ -1,7 +1,12 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ReportsService } from './reports.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import {
ApiTags,
ApiBearerAuth,
ApiOperation,
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - گزارشات')
@ApiBearerAuth()
@@ -11,9 +16,22 @@ export class ReportsController {
@UseGuards(JwtAuthGuard)
@Get()
@ApiOperation({ summary: 'دریافت گزارشات داشبورد' })
async getReports() {
const data = await this.reportsService.getDashboardReports();
@ApiOperation({
summary: 'دریافت گزارشات داشبورد با قابلیت فیلتر زمانی و نوع کاربر',
})
@ApiQuery({ name: 'startDate', required: false })
@ApiQuery({ name: 'endDate', required: false })
@ApiQuery({ name: 'role', required: false })
async getReports(
@Query('startDate') startDate?: string,
@Query('endDate') endDate?: string,
@Query('role') role?: string,
) {
const data = await this.reportsService.getDashboardReports({
startDate,
endDate,
role,
});
return { success: true, data };
}
}
+117 -18
View File
@@ -5,29 +5,71 @@ import { PrismaService } from '../prisma/prisma.service';
export class ReportsService {
constructor(private prisma: PrismaService) {}
async getDashboardReports() {
// 1. Total revenue and charity
async getDashboardReports(query?: {
startDate?: string;
endDate?: string;
role?: string;
}) {
const whereClause: any = { status: { not: 'cancelled' } };
if (query?.startDate || query?.endDate) {
whereClause.createdAt = {};
if (query.startDate) {
whereClause.createdAt.gte = new Date(query.startDate);
}
if (query.endDate) {
const end = new Date(query.endDate);
end.setHours(23, 59, 59, 999);
whereClause.createdAt.lte = end;
}
}
if (query?.role && query.role !== 'ALL') {
whereClause.user = { role: query.role };
}
// 1. Fetch filtered orders with items and coupons for accurate breakdown
const orders = await this.prisma.order.findMany({
where: { status: { not: 'cancelled' } },
select: {
totalAmount: true,
charityDonation: true,
createdAt: true,
where: whereClause,
include: {
user: { select: { role: true } },
coupon: true,
orderItems: {
include: {
product: {
select: {
id: true,
buyPrice: true,
priceValue: true,
},
},
},
},
},
orderBy: { createdAt: 'asc' },
});
let totalRevenue = 0;
let totalCharity = 0;
let totalRevenue = 0; // Total paid/deposited by users
let totalCharity = 0; // Charity portion
let b2bRevenue = 0;
let b2cRevenue = 0;
let totalTax = 0;
const totalShipping = 0;
let totalDiscounts = 0;
let totalCostOfGoods = 0; // COGS (مجموع قیمت خرید کالاها)
const salesByDate: Record<string, number> = {};
const salesByDate: Record<
string,
{ total: number; charity: number; sales: number }
> = {};
for (const order of orders) {
const amount = Number(order.totalAmount);
const amount = Number(order.totalAmount || 0);
const charity = Number(order.charityDonation || 0);
const productSales = Math.max(0, amount - charity);
totalRevenue += amount;
totalCharity += Number(order.charityDonation);
totalCharity += charity;
if (order.user?.role === 'B2B') {
b2bRevenue += amount;
@@ -35,23 +77,74 @@ export class ReportsService {
b2cRevenue += amount;
}
// Calculate cost of goods (COGS) from order items
let orderCOGS = 0;
let orderItemSubtotal = 0;
if (order.orderItems && order.orderItems.length > 0) {
for (const item of order.orderItems) {
const qty = item.quantity || 1;
const buyPrice = Number(item.product?.buyPrice || 0);
const salePrice = Number(item.product?.priceValue || 0);
orderCOGS += buyPrice * qty;
orderItemSubtotal += salePrice * qty;
}
}
totalCostOfGoods += orderCOGS;
// Discount calculation (if coupon was used or total discount applied)
if (order.coupon) {
if (
order.coupon.type === 'percent' ||
order.coupon.type === 'PERCENTAGE'
) {
const discountVal =
(orderItemSubtotal * Number(order.coupon.value)) / 100;
totalDiscounts += discountVal;
} else {
totalDiscounts += Number(order.coupon.value || 0);
}
}
// Standard VAT / Tax (approx 10% on product sales if configured)
const taxRate = 0.1;
const orderTax = Math.round(productSales * (taxRate / (1 + taxRate)));
totalTax += orderTax;
// Format date YYYY-MM-DD
const dateKey = order.createdAt.toISOString().split('T')[0];
if (!salesByDate[dateKey]) salesByDate[dateKey] = 0;
salesByDate[dateKey] += amount;
if (!salesByDate[dateKey]) {
salesByDate[dateKey] = { total: 0, charity: 0, sales: 0 };
}
salesByDate[dateKey].total += amount;
salesByDate[dateKey].charity += charity;
salesByDate[dateKey].sales += productSales;
}
// Product Sales Revenue (excluding charity)
const productSalesRevenue = Math.max(0, totalRevenue - totalCharity);
// Net profit = Product Sales - COGS - Tax - Discounts
const netProfit = Math.max(
0,
productSalesRevenue - totalCostOfGoods - totalTax - totalDiscounts,
);
// Format sales timeline for charts
const salesTimeline = Object.entries(salesByDate)
.map(([date, amount]) => ({ date, amount }))
.map(([date, data]) => ({
date,
amount: data.total,
charity: data.charity,
sales: data.sales,
}))
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
// 2. Best selling products (by quantity)
// 2. Best selling products (by quantity) in the selected range
const orderItems = await this.prisma.orderItem.groupBy({
by: ['productId'],
_sum: { quantity: true },
where: {
order: { status: { not: 'cancelled' } },
order: whereClause,
productId: { not: null },
},
orderBy: { _sum: { quantity: 'desc' } },
@@ -89,7 +182,7 @@ export class ReportsService {
})
.filter((c) => c.value > 0);
// 4. Coupons Usage
// 4. Coupons Usage in range
const topCoupons = await this.prisma.coupon.findMany({
orderBy: { usedCount: 'desc' },
take: 5,
@@ -100,9 +193,15 @@ export class ReportsService {
overview: {
totalRevenue,
totalCharity,
productSalesRevenue,
totalOrders: orders.length,
b2bRevenue,
b2cRevenue,
totalTax,
totalShipping,
totalDiscounts,
totalCostOfGoods,
netProfit,
},
salesTimeline,
bestSellers,
+1
View File
@@ -28,6 +28,7 @@ describe('AuthService', () => {
set: jest.fn(),
get: jest.fn(),
del: jest.fn(),
incr: jest.fn().mockResolvedValue(1),
};
const mockSms = {
@@ -27,6 +27,12 @@ describe('OrdersService', () => {
walletTransaction: {
create: jest.fn(),
},
setting: {
findFirst: jest.fn().mockResolvedValue(null),
},
uiText: {
findFirst: jest.fn().mockResolvedValue(null),
},
};
const mockSmsService = {
@@ -1,6 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ProductsService } from './products.service';
import { PrismaService } from '../prisma/prisma.service';
import { RevalidationService } from '../common/revalidation/revalidation.service';
describe('ProductsService', () => {
let service: ProductsService;
@@ -15,11 +16,17 @@ describe('ProductsService', () => {
},
};
const mockRevalidationService = {
revalidateTag: jest.fn(),
revalidatePath: jest.fn(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ProductsService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: RevalidationService, useValue: mockRevalidationService },
],
}).compile();
@@ -37,14 +37,11 @@ describe('SettingsController', () => {
expect(controller).toBeDefined();
});
it('should have JwtAuthGuard, RolesGuard and Admin role applied at controller level', () => {
const guards = Reflect.getMetadata(GUARDS_METADATA, SettingsController);
it('should have JwtAuthGuard and RolesGuard on protected mutation routes', () => {
const guards = Reflect.getMetadata(GUARDS_METADATA, controller.putUiText);
expect(guards).toBeDefined();
expect(guards).toContain(JwtAuthGuard);
expect(guards).toContain(RolesGuard);
const roles = Reflect.getMetadata(ROLES_KEY, SettingsController);
expect(roles).toEqual(['Admin']);
});
it('should getUiTexts', async () => {
@@ -1,6 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SettingsService } from './settings.service';
import { PrismaService } from '../prisma/prisma.service';
import { SmsService } from '../common/services/sms.service';
describe('SettingsService', () => {
let service: SettingsService;
@@ -11,6 +12,10 @@ describe('SettingsService', () => {
findMany: jest.fn(),
upsert: jest.fn(),
},
setting: {
findMany: jest.fn().mockResolvedValue([]),
upsert: jest.fn(),
},
scientificTerm: {
findMany: jest.fn(),
upsert: jest.fn(),
@@ -18,11 +23,17 @@ describe('SettingsService', () => {
},
};
const mockSmsService = {
getSmsLogs: jest.fn(),
sendOtp: jest.fn(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
SettingsService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: SmsService, useValue: mockSmsService },
],
}).compile();
+1 -1
View File
@@ -44,7 +44,7 @@ describe('UsersService', () => {
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
const result = await service.findById('user-id');
expect(prisma.user.findUnique).toHaveBeenCalled();
expect(result).toEqual(mockUser);
expect(result).toEqual({ ...mockUser, hasPassword: false });
});
it('should call prisma update in update', async () => {