-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathadmin.service.ts
More file actions
103 lines (95 loc) · 2.82 KB
/
admin.service.ts
File metadata and controls
103 lines (95 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* @fileoverview Service for admin-specific functionalities, like dashboard analytics.
* @issue #206
*/
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../database/prisma/prisma.service';
import {
AdminDashboardQueryDto,
AdminDashboardResponseDto,
} from './dto/dashboard.dto';
@Injectable()
export class AdminService {
constructor(private readonly prisma: PrismaService) {}
async getDashboardAnalytics(
query: AdminDashboardQueryDto,
): Promise<AdminDashboardResponseDto> {
const { startDate, endDate } = query;
const dateFilter =
startDate && endDate ? { gte: startDate, lte: endDate } : undefined;
const [
userCounts,
projectCounts,
donationStats,
feeStats,
recentActivity,
] = await this.prisma.$transaction([
// 1. Get user counts by role
this.prisma.user.groupBy({
by: ['role'],
_count: { id: true },
where: dateFilter ? { createdAt: dateFilter } : undefined,
}),
// 2. Get project counts by status
this.prisma.project.groupBy({
by: ['status'],
_count: { id: true },
where: dateFilter ? { createdAt: dateFilter } : undefined,
}),
// 3. Get total donation amount and count
this.prisma.donation.aggregate({
_sum: { amount: true },
_count: { id: true },
where: dateFilter ? { createdAt: dateFilter } : undefined,
}),
// 4. Get total platform fees collected
this.prisma.platformFee.aggregate({
_sum: { amount: true },
where: dateFilter ? { createdAt: dateFilter } : undefined,
}),
// 5. Get recent platform activity
this.prisma.activityLog.findMany({
take: 20,
orderBy: { createdAt: 'desc' },
where: dateFilter ? { createdAt: dateFilter } : undefined,
}),
]);
// Format user stats
const usersByRole = userCounts.reduce((acc, item) => {
acc[item.role] = item._count.id;
return acc;
}, {});
const totalUsers = userCounts.reduce((sum, item) => sum + item._count.id, 0);
// Format project stats
const projectsByStatus = projectCounts.reduce((acc, item) => {
acc[item.status] = item._count.id;
return acc;
}, {});
const totalProjects = projectCounts.reduce(
(sum, item) => sum + item._count.id,
0,
);
return {
userStats: {
total: totalUsers,
byRole: usersByRole,
},
projectStats: {
total: totalProjects,
byStatus: projectsByStatus,
},
donationStats: {
totalAmount: donationStats._sum.amount || 0,
totalCount: donationStats._count.id || 0,
},
platformFees: {
totalCollected: feeStats._sum.amount || 0,
},
recentActivity,
query: {
startDate,
endDate,
},
};
}
}