forked from MindBlockLabs/mindBlock_app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogress-calculation.provider.ts
More file actions
282 lines (245 loc) · 8.41 KB
/
Copy pathprogress-calculation.provider.ts
File metadata and controls
282 lines (245 loc) · 8.41 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindOptionsWhere, MoreThan, Repository } from 'typeorm';
import { Puzzle } from '../../puzzles/entities/puzzle.entity';
import { UserProgress } from '../entities/progress.entity';
import { SubmitAnswerDto } from '../dtos/submit-answer.dto';
import { XpLevelService } from '../../users/providers/xp-level.service';
import { User } from '../../users/user.entity';
import { DailyQuest } from '../../quests/entities/daily-quest.entity';
import { getPointsByDifficulty } from '../../puzzles/enums/puzzle-difficulty.enum';
export interface AnswerValidationResult {
isCorrect: boolean;
pointsEarned: number;
normalizedAnswer: string;
}
export interface ProgressCalculationResult {
userProgress: UserProgress;
validation: AnswerValidationResult;
}
@Injectable()
export class ProgressCalculationProvider {
constructor(
@InjectRepository(Puzzle)
private readonly puzzleRepository: Repository<Puzzle>,
@InjectRepository(UserProgress)
private readonly userProgressRepository: Repository<UserProgress>,
private readonly xpLevelService: XpLevelService,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
@InjectRepository(DailyQuest)
private readonly dailyQuestRepository: Repository<DailyQuest>,
) {}
/**
* Validates user answer against puzzle correct answer
* Trims whitespace and performs case-insensitive comparison
*/
validateAnswer(
userAnswer: string,
correctAnswer: string,
): AnswerValidationResult {
const normalizedUserAnswer = userAnswer.trim().toLowerCase();
const normalizedCorrectAnswer = correctAnswer.trim().toLowerCase();
const isCorrect = normalizedUserAnswer === normalizedCorrectAnswer;
return {
isCorrect,
pointsEarned: 0, // Will be calculated separately
normalizedAnswer: normalizedUserAnswer,
};
}
/**
* Calculates points based on puzzle difficulty and time spent
* Base points from puzzle difficulty with optional time bonus/penalty
*/
calculatePoints(
puzzle: Puzzle,
timeSpent: number,
isCorrect: boolean,
): number {
if (!isCorrect) {
return 0;
}
const basePoints = getPointsByDifficulty(puzzle.difficulty);
const timeLimit = puzzle.timeLimit;
// Time bonus: (timeLimit - timeSpent) / timeLimit * 0.5 (max 0.5 bonus)
let timeBonusMultiplier = 0;
if (timeSpent < timeLimit) {
timeBonusMultiplier = ((timeLimit - timeSpent) / timeLimit) * 0.5;
}
// Accuracy multiplier (currently 1.0 for correct, 0.0 for incorrect)
const accuracyMultiplier = 1.0;
return Math.round(
basePoints * (1 + timeBonusMultiplier) * accuracyMultiplier,
);
}
/**
* Calculates level based on total XP
*/
calculateLevel(totalXP: number): number {
if (totalXP < 1000) return 1;
if (totalXP < 2500) return 2;
if (totalXP < 5000) return 3;
if (totalXP < 10000) return 4;
// Level 5+: Exponential scaling: 10000 + (level - 4) * some_growth
// Simplified: level 5 starts at 10000, each level after adds 5000+
return Math.floor((totalXP - 10000) / 5000) + 5;
}
/**
* Processes answer submission and creates user progress record
*/
async processAnswerSubmission(
submitAnswerDto: SubmitAnswerDto,
): Promise<ProgressCalculationResult> {
// Get puzzle to validate against
const puzzle = await this.puzzleRepository.findOne({
where: { id: submitAnswerDto.puzzleId },
});
// In processAnswerSubmission, check for recent duplicate:
const recentAttempt = await this.userProgressRepository.findOne({
where: {
userId: submitAnswerDto.userId,
puzzleId: submitAnswerDto.puzzleId,
attemptedAt: MoreThan(new Date(Date.now() - 5000)), // 5 second window
},
});
if (!puzzle) {
throw new NotFoundException(
`Puzzle with ID ${submitAnswerDto.puzzleId} not found`,
);
}
if (recentAttempt) {
throw new Error('Duplicate submission detected');
}
// Validate answer
const validation = this.validateAnswer(
submitAnswerDto.userAnswer,
puzzle.correctAnswer,
);
// Calculate points
let pointsEarned = this.calculatePoints(
puzzle,
submitAnswerDto.timeSpent,
validation.isCorrect,
);
// Fetch user and apply streak bonus
const user = await this.userRepository.findOne({
where: { id: submitAnswerDto.userId },
relations: ['streak'],
});
if (user && validation.isCorrect) {
const streakCount = user.streak?.currentStreak || 0;
let streakMultiplier = 0;
if (streakCount >= 7) {
streakMultiplier = 0.25;
} else if (streakCount >= 3) {
streakMultiplier = 0.1;
}
pointsEarned = Math.round(pointsEarned * (1 + streakMultiplier));
// Update User XP and Level
user.xp += pointsEarned;
user.level = this.calculateLevel(user.xp);
await this.userRepository.save(user);
}
validation.pointsEarned = pointsEarned;
// Check for Daily Quest completion
const todayDate = new Date().toISOString().split('T')[0];
const dailyQuest = await this.dailyQuestRepository.findOne({
where: { userId: submitAnswerDto.userId, questDate: todayDate },
relations: ['questPuzzles'],
});
if (dailyQuest && !dailyQuest.isCompleted) {
const isQuestPuzzle = dailyQuest.questPuzzles.some(
(qp) => qp.puzzleId === submitAnswerDto.puzzleId,
);
if (isQuestPuzzle && validation.isCorrect) {
// Double check if this puzzle was already completed today for this quest
const alreadyCompleted = await this.userProgressRepository.findOne({
where: {
userId: submitAnswerDto.userId,
puzzleId: submitAnswerDto.puzzleId,
dailyQuestId: dailyQuest.id,
isCorrect: true,
},
});
if (!alreadyCompleted) {
dailyQuest.completedQuestions += 1;
if (dailyQuest.completedQuestions >= dailyQuest.totalQuestions) {
dailyQuest.isCompleted = true;
dailyQuest.completedAt = new Date();
// Award bonus XP for daily quest completion (e.g., 50 XP as hinted in "completion screen")
if (user) {
user.xp += 50;
user.level = this.calculateLevel(user.xp);
await this.userRepository.save(user);
}
}
await this.dailyQuestRepository.save(dailyQuest);
}
}
}
// Create user progress record
const userProgress = this.userProgressRepository.create({
userId: submitAnswerDto.userId,
puzzleId: submitAnswerDto.puzzleId,
categoryId: submitAnswerDto.categoryId,
dailyQuestId: dailyQuest?.id,
isCorrect: validation.isCorrect,
userAnswer: submitAnswerDto.userAnswer,
pointsEarned,
timeSpent: submitAnswerDto.timeSpent,
attemptedAt: new Date(),
});
// Save to database
await this.userProgressRepository.save(userProgress);
if (validation.isCorrect && pointsEarned > 0) {
await this.xpLevelService.addXp(submitAnswerDto.userId, pointsEarned);
}
return {
userProgress,
validation,
};
}
/**
* Gets user progress statistics for a category
*/
async getUserProgressStats(userId: string, categoryId: string) {
const where: FindOptionsWhere<UserProgress> = {
userId,
categoryId,
};
const progressRecords = await this.userProgressRepository.find({ where });
if (progressRecords.length === 0) {
return {
totalAttempts: 0,
correctAttempts: 0,
totalPoints: 0,
averageTimeSpent: 0,
accuracy: 0,
};
}
const totalAttempts = progressRecords.length;
const correctAttempts = progressRecords.reduce(
(sum, record) => sum + (record.isCorrect ? 1 : 0),
0,
);
const totalPoints = progressRecords.reduce(
(sum, record) => sum + record.pointsEarned,
0,
);
const totalTimeSpent = progressRecords.reduce(
(sum, record) => sum + record.timeSpent,
0,
);
const averageTimeSpent =
totalAttempts > 0 ? totalTimeSpent / totalAttempts : 0;
const accuracy =
totalAttempts > 0 ? (correctAttempts / totalAttempts) * 100 : 0;
return {
totalAttempts,
correctAttempts,
totalPoints,
averageTimeSpent,
accuracy,
};
}
}