-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrating-service.ts
More file actions
263 lines (226 loc) · 7.09 KB
/
rating-service.ts
File metadata and controls
263 lines (226 loc) · 7.09 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
import { ForbiddenError, NotFoundError } from "routing-controllers";
import { Inject, Service, Token } from "typedi";
import { Repository } from "typeorm";
import { IService } from ".";
import { DatabaseServiceToken, IDatabaseService } from "./database-service";
import { ISettingsService, SettingsServiceToken } from "./settings-service";
import { Rating } from "../entities/rating";
import {
RatingDTO,
ProjectRatingResultDTO,
convertBetweenEntityAndDTO,
} from "../controllers/dto";
import { User } from "../entities/user";
import { Team } from "../entities/team";
import { Project } from "../entities/project";
import { Criterion } from "../entities/criterion";
import { UserRole } from "../entities/user-role";
/**
* A service to handle rating entities.
*/
export interface IRatingService extends IService {
/**
* Get the ratings for a specific project, cast by a specific user.
* Users may only read their own created ratings.
*/
getUsersRatingsForProject(
projectId: number,
user: User,
): Promise<readonly Rating[]>;
/**
* Upsert a rating
*/
upsertRating(rating: Rating, user: User): Promise<Rating>;
/**
* Get rating by id
*/
getRatingByID(id: number, user: User): Promise<RatingDTO | undefined>;
/**
* Delete single rating by id
*/
deleteRatingByID(id: number, currentUser: User): Promise<void>;
/**
* Get all ratings for every project
*/
getRatingResults(): Promise<readonly ProjectRatingResultDTO[]>;
}
/**
* A token used to inject a concrete user service.
*/
export const RatingServiceToken = new Token<IRatingService>();
/**
* A service to handle rating entities.
*/
@Service(RatingServiceToken)
export class RatingService implements IRatingService {
private _ratings!: Repository<Rating>;
private _projects!: Repository<Project>;
private _teams!: Repository<Team>;
public constructor(
@Inject(DatabaseServiceToken) private readonly _database: IDatabaseService,
@Inject(SettingsServiceToken) private readonly _settings: ISettingsService,
) {}
/**
* Sets up the rating service.
*/
public async bootstrap(): Promise<void> {
this._ratings = this._database.getRepository(Rating);
this._projects = this._database.getRepository(Project);
this._teams = this._database.getRepository(Team);
}
/**
* Get the ratings for a specific project, cast by a specific user.
* Users may only read their own created ratings.
*/
public async getUsersRatingsForProject(
projectId: number,
user: User,
): Promise<readonly Rating[]> {
// TODO test
return this._database.getRepository(Rating).find({
where: {
project: {
id: projectId,
},
user: {
id: user.id,
},
},
});
}
/**
* Upsert a rating.
* @param rating The rating to create
*/
public async upsertRating(rating: Rating, user: User): Promise<Rating> {
await this.checkPermission(rating, user);
const existingRating = await this._ratings.findOneBy({
user: {
id: user.id,
},
project: {
id: rating.project.id,
},
criterion: {
id: rating.criterion.id,
},
});
if (existingRating) {
// Update
return this._ratings.save({
...rating,
id: existingRating.id,
});
}
return this._ratings.save(rating);
}
/**
* Gets a rating by its id.
* @param id The id of the rating
*/
public async getRatingByID(
id: number,
user: User,
): Promise<RatingDTO | undefined> {
const rating = await this._ratings.findOneBy({ id });
if (!rating) {
throw new NotFoundError("Rating not found");
}
if (rating.user.id !== user.id && user.role !== UserRole.Root) {
throw new ForbiddenError();
}
return rating ? convertBetweenEntityAndDTO(rating, RatingDTO) : undefined;
}
/**
* Deletes a rating by its id.
* @param id The id of the rating
*/
public async deleteRatingByID(id: number, currentUser: User): Promise<void> {
const rating = await this._ratings.findOneBy({ id });
if (!rating) {
throw new NotFoundError("Rating not found");
}
if (currentUser.id !== rating.user.id) {
throw new ForbiddenError("You can only delete your own ratings");
}
await this.checkPermission(rating, currentUser);
await this._ratings.delete(id);
return Promise.resolve();
}
/**
* Get the average ratings for each project
*/
public async getRatingResults(): Promise<readonly ProjectRatingResultDTO[]> {
const allProjects = await this._projects.find();
const allRatings = await this._ratings.find();
const result: ProjectRatingResultDTO[] = [];
const idToCriterion: Record<number, Criterion> = {};
for (const project of allProjects) {
const averagesPerCriterion: { criterion: Criterion; average: number }[] =
[];
// Sum up
const criterionIdToSum: Record<number, number> = {};
const criterionIdToCount: Record<number, number> = {};
for (const rating of allRatings) {
idToCriterion[rating.criterion.id] = rating.criterion;
if (rating.project.id !== project.id) {
continue;
}
const criterionId = rating.criterion.id;
if (criterionIdToSum[criterionId] === undefined) {
criterionIdToSum[criterionId] = 0;
criterionIdToCount[criterionId] = 0;
}
criterionIdToSum[criterionId] += rating.rating;
criterionIdToCount[criterionId] += 1;
}
// Calculate average
Object.keys(criterionIdToSum)
.map(Number)
.forEach((criterionId) => {
const count = criterionIdToCount[criterionId];
if (count === 0) {
return;
}
const sum = criterionIdToSum[criterionId];
const average = sum / count;
const criterion = idToCriterion[criterionId];
averagesPerCriterion.push({ criterion, average });
});
result.push({
project,
averagesPerCriterion,
});
}
return result;
}
/**
* Check if the user is permitted to create/modify/delete this rating.
*/
private async checkPermission(rating: Rating, user: User): Promise<void> {
if (!user.admitted) {
throw new ForbiddenError("Only admitted users may rate projects");
}
const settings = await this._settings.getSettings();
if (!settings.project.allowRatingProjects) {
throw new ForbiddenError("Rating is not allowed due to settings");
}
const project = await this._projects.findOneBy({ id: rating.project.id });
if (!project) {
throw new NotFoundError("Project not found");
}
if (!project.allowRating) {
throw new ForbiddenError("Rating this project is not allowed");
}
const team = await this._teams.findOneBy({ id: project.team.id });
if (!team) {
throw new NotFoundError("Team not found");
}
if (team.users.includes(user.id.toString())) {
throw new ForbiddenError("You can't rate your own project");
}
if (rating.user.id !== user.id) {
throw new ForbiddenError("You can't rate as a different user");
}
}
}