forked from MindBlockLabs/mindBlock_app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget-overall-stats.provider.ts
More file actions
57 lines (51 loc) · 1.69 KB
/
Copy pathget-overall-stats.provider.ts
File metadata and controls
57 lines (51 loc) · 1.69 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
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserProgress } from '../entities/progress.entity';
import { OverallStatsDto } from '../dtos/overall-stats.dto';
interface OverallStatsRaw {
totalAttempts: string;
totalCorrect: string;
totalPointsEarned: string;
totalTimeSpent: string;
}
@Injectable()
export class GetOverallStatsProvider {
constructor(
@InjectRepository(UserProgress)
private readonly progressRepo: Repository<UserProgress>,
) {}
async getOverallStats(userId: string): Promise<OverallStatsDto> {
const result = await this.progressRepo
.createQueryBuilder('progress')
.select('COUNT(*)', 'totalAttempts')
.addSelect(
'SUM(CASE WHEN progress.isCorrect = true THEN 1 ELSE 0 END)',
'totalCorrect',
)
.addSelect('SUM(progress.pointsEarned)', 'totalPointsEarned')
.addSelect('SUM(progress.timeSpent)', 'totalTimeSpent')
.where('progress.userId = :userId', { userId })
.getRawOne<OverallStatsRaw>();
if (!result) {
return {
totalAttempts: 0,
totalCorrect: 0,
accuracy: 0,
totalPointsEarned: 0,
totalTimeSpent: 0,
};
}
const totalAttempts = parseInt(result.totalAttempts, 10) || 0;
const totalCorrect = parseInt(result.totalCorrect, 10) || 0;
const accuracy =
totalAttempts > 0 ? Math.round((totalCorrect / totalAttempts) * 100) : 0;
return {
totalAttempts,
totalCorrect,
accuracy,
totalPointsEarned: parseInt(result.totalPointsEarned, 10) || 0,
totalTimeSpent: parseInt(result.totalTimeSpent, 10) || 0,
};
}
}