-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapplication-service.ts
More file actions
654 lines (549 loc) · 18.1 KB
/
application-service.ts
File metadata and controls
654 lines (549 loc) · 18.1 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import { Inject, Service, Token } from "typedi";
import { Repository } from "typeorm";
import { IService } from ".";
import { Answer } from "../entities/answer";
import { Question } from "../entities/question";
import { QuestionType } from "../entities/question-type";
import { User } from "../entities/user";
import { enforceExhaustiveSwitch } from "../utils/switch";
import { DatabaseServiceToken, IDatabaseService } from "./database-service";
import {
EmailTemplateServiceToken,
IEmailTemplateService,
} from "./email-template-service";
import {
IQuestionGraphService,
QuestionGraph,
QuestionGraphServiceToken,
} from "./question-service";
import { ISettingsService, SettingsServiceToken } from "./settings-service";
import { IUserService, UserServiceToken } from "./user-service";
/**
* A form containing questions and given answers.
*/
export interface IForm {
questions: readonly Question[];
answers: readonly Answer[];
}
/**
* A raw answer
*/
export interface IRawAnswer {
questionID: number;
value: string;
}
/**
* An application for a user and their answers.
*/
export interface IApplication {
user: User;
answers: readonly Answer[];
}
/**
* A service to handle applications.
*/
export interface IApplicationService extends IService {
/**
* Gets the profile form with the user's given answers.
* @param user The user requesting their profile form
*/
getProfileForm(user: User): Promise<IForm>;
/**
* Saves the answers for the profile form for the given user.
* @param user The user storing their profile form
* @param answers The given answers
*/
storeProfileFormAnswers(
user: User,
answers: readonly IRawAnswer[],
): Promise<void>;
/**
* Admits the given users.
* @param users The users to admit
*/
admit(users: readonly User[]): Promise<void>;
/**
* Gets the confirmation form with the user's previously given answers. This
* form includes questions the user didn't answer in the profile form because
* they were added after the user submitted the profile form.
* @param user The user requesting their confirmation form
*/
getConfirmationForm(user: User): Promise<IForm>;
/**
* Saves the answers for the confirmation form for the given user.
* @param user The user storing their confirmation form
* @param answers The given answers
*/
storeConfirmationFormAnswers(
user: User,
answers: readonly IRawAnswer[],
): Promise<void>;
/**
* Gets all existing applications.
*/
getAll(): Promise<readonly IApplication[]>;
/**
* Delete a user's answers.
* @param user The user whose answers to delete
*/
deleteAnswers(user: User): Promise<void>;
/**
* Declines the given user's spot.
* @param user The user declining their spot
*/
declineSpot(user: User): Promise<void>;
/**
* Checks in the given user.
* @param user The user we're checking in
*/
checkIn(user: User): Promise<void>;
}
/**
* A token used to inject a concrete application service.
*/
export const ApplicationServiceToken = new Token<IApplicationService>();
@Service(ApplicationServiceToken)
export class ApplicationService implements IApplicationService {
private _answers!: Repository<Answer>;
constructor(
@Inject(QuestionGraphServiceToken)
private readonly _graph: IQuestionGraphService,
@Inject(DatabaseServiceToken) private readonly _database: IDatabaseService,
@Inject(SettingsServiceToken) private readonly _settings: ISettingsService,
@Inject(UserServiceToken) private readonly _users: IUserService,
@Inject(EmailTemplateServiceToken)
private readonly _email: IEmailTemplateService,
) {}
/**
* @inheritdoc
*/
public async bootstrap(): Promise<void> {
this._answers = this._database.getRepository(Answer);
}
/**
* Returns whether the given question was answered correctly.
* @param question The answered question
* @param answer The answer to the answered question
*/
private isAnswerValid(question: Question, answer: Answer): boolean {
const configuration = question.configuration;
if (!question.mandatory && answer.value === "") {
return true;
}
switch (configuration.type) {
case QuestionType.Choices:
const parsedAnswers = answer.value.split(",");
if (!configuration.allowMultiple && parsedAnswers.length > 1) {
return false;
}
const allAnswersAreChoices = parsedAnswers.every((value) =>
configuration.choices.includes(value),
);
return allAnswersAreChoices;
case QuestionType.Country:
case QuestionType.Text:
return answer.value.trim().length > 0;
case QuestionType.Number:
const numberValue = Number(answer.value);
const hasDecimals = Math.floor(numberValue) !== numberValue;
if (!configuration.allowDecimals && hasDecimals) {
return false;
}
const biggerThanMin =
configuration.minValue == null ||
configuration.minValue <= numberValue;
const smallerThanMax =
configuration.maxValue == null ||
numberValue <= configuration.maxValue;
return biggerThanMin && smallerThanMax;
default:
enforceExhaustiveSwitch(configuration);
return false;
}
}
/**
* Resolves the given raw answers from the user to either existing @see Answer
* entities or creates fresh ones.
* @param user The user giving the answers
* @param existingAnswers The user's already given answers
* @param questionGraph The question graph for the user's current form
* @param rawAnswers The answers provided by the user
*/
private resolveAnswersToEntities(
user: User,
existingAnswers: readonly Answer[],
questionGraph: QuestionGraph,
rawAnswers: readonly IRawAnswer[],
): readonly Answer[] {
return rawAnswers.map((rawAnswer) => {
const existingAnswer = existingAnswers.find(
({ question: { id } }) => rawAnswer.questionID === id,
);
if (existingAnswer) {
existingAnswer.value = rawAnswer.value;
return existingAnswer;
}
const answer = new Answer();
answer.value = rawAnswer.value;
answer.user = user;
const node = questionGraph.get(rawAnswer.questionID);
if (!node) {
throw new QuestionNotFoundError(rawAnswer.questionID);
}
answer.question = node.question;
return answer;
});
}
/**
* Replaces a user's answers to a given set of questions.
* @param user The user giving the answers
* @param questions A set of questions the user should answer
* @param givenAnswers The user's new answers for these questions
*/
private async replaceAnswers(
user: User,
questions: readonly Question[],
givenAnswers: readonly IRawAnswer[],
) {
const questionGraph = this._graph.buildQuestionGraph(questions);
const startNodes = [...questionGraph.values()].filter(
({ parentNode }) => parentNode == null,
);
const existingAnswers = await this.findAllExistingAnswers(user);
const answers = this.resolveAnswersToEntities(
user,
existingAnswers,
questionGraph,
givenAnswers,
);
const modifiedAnswers = [] as Answer[];
for (const node of startNodes) {
let nodesToVisit = [node];
while (nodesToVisit.length > 0) {
const [currentNode, ...rest] = nodesToVisit;
nodesToVisit = [...rest, ...currentNode.childNodes];
const currentQuestion = currentNode.question;
const answerForCurrentQuestion = answers.find(
({ question: { id } }) => id === currentQuestion.id,
);
if (
!answerForCurrentQuestion ||
answerForCurrentQuestion.value === ""
) {
// if a question is purely optional, we can ignore that it's missing
if (!currentQuestion.mandatory) {
continue;
}
const parentNode = currentNode.parentNode;
// if we don't have a parent question and didn't find an answer, the
// user didn't answer it and we expected an answer
if (!parentNode) {
throw new QuestionNotAnsweredError(
currentQuestion.title,
currentQuestion.id,
);
}
const parentQuestion = parentNode.question;
const parentAnswer = givenAnswers.find(
({ questionID }) => questionID === parentQuestion.id,
);
// we're going top-down, so we already know the parent question is valid
if (!parentAnswer) {
throw new QuestionGraphBrokenError();
}
const parentQuestionAnswerMatchedExpectedValue =
currentQuestion.showIfParentHasValue === parentAnswer.value;
// the question was shown, because the parent question was answered
// with the expected value
// consider this question:
//
// What's your profession? [ ] Student [ ] Professional
//
// if we want to ask which semester a student is in, we expect
// "Student" and thus require the question to be answered
if (parentQuestionAnswerMatchedExpectedValue) {
throw new QuestionNotAnsweredError(
currentQuestion.title,
currentQuestion.id,
);
}
// the question might be mandatory, but we didn't show it to the user
// in the first place, therefore we can ignore it
continue;
}
if (!this.isAnswerValid(currentQuestion, answerForCurrentQuestion)) {
throw new InvalidAnswerError(
currentQuestion.title,
currentQuestion.id,
answerForCurrentQuestion.value,
);
}
modifiedAnswers.push(answerForCurrentQuestion);
}
}
await this._answers.save(modifiedAnswers);
}
/**
* Finds all answers for the given user.
* @param user A user whose answers we want to get
*/
private async findAllExistingAnswers(user: User): Promise<Answer[]> {
return await this._answers.findBy({
user: {
id: user.id,
},
});
}
/**
* @inheritdoc
*/
public async getProfileForm(user: User): Promise<IForm> {
const settings = await this._settings.getSettings();
const questions = settings.application.profileForm.questions.filter(
({ createdAt }) =>
user.initialProfileFormSubmittedAt == null ||
createdAt.getTime() <= user.initialProfileFormSubmittedAt.getTime(),
);
const questionIDs = questions.map(({ id }) => id);
const allAnswers = await this.findAllExistingAnswers(user);
const answers = allAnswers.filter(({ question: { id } }) =>
questionIDs.includes(id),
);
return {
answers,
questions,
};
}
/**
* @inheritdoc
*/
public async storeProfileFormAnswers(
user: User,
answers: readonly IRawAnswer[],
): Promise<void> {
if (user.admitted) {
throw new AlreadyAdmittedError();
}
const settings = await this._settings.getSettings();
const now = Date.now();
const isBeforeWindow =
now < settings.application.allowProfileFormFrom.getTime();
const isAfterWindow =
settings.application.allowProfileFormUntil.getTime() < now;
if (isBeforeWindow || isAfterWindow) {
throw new FormNotAvailableError(
settings.application.allowProfileFormFrom,
settings.application.allowProfileFormUntil,
);
}
const questions = settings.application.profileForm.questions;
await this.replaceAnswers(user, questions, answers);
if (user.initialProfileFormSubmittedAt == null) {
user.initialProfileFormSubmittedAt = new Date();
// send mail to user about successful submission
await this._email.sendSubmissionEmail(user);
await this._users.updateUser(user);
}
user.profileSubmitted = true;
await this._users.updateUser(user);
}
/**
* @inheritdoc
*/
public async admit(users: readonly User[]): Promise<void> {
const settings = await this._settings.getSettings();
const now = Date.now();
const millisecondsInHour = 60 * 60 * 1000;
for (const user of users) {
user.confirmationExpiresAt = new Date(
now + settings.application.hoursToConfirm * millisecondsInHour,
);
user.admitted = true;
}
await this._users.updateUsers(users);
const emailPromises = users.map((user) =>
this._email.sendAdmittedEmail(user),
);
await Promise.all(emailPromises);
}
/**
* @inheritdoc
*/
public async getConfirmationForm(user: User): Promise<IForm> {
const settings = await this._settings.getSettings();
if (user.confirmationExpiresAt == null) {
throw new NotAdmittedError();
}
const skippedProfileQuestions =
settings.application.profileForm.questions.filter(
({ createdAt }) =>
user.initialProfileFormSubmittedAt != null &&
createdAt.getTime() > user.initialProfileFormSubmittedAt.getTime(),
);
try {
// if the graph built correctly, then the skipped questions are a locally
// connected subgraph of the profile form
this._graph.buildQuestionGraph(skippedProfileQuestions);
// in the future, we might allow conditional questions, but that requires
// more work and isn't really worth it. we mostly need this feature to add
// questions that were exempt during the initial process while, e.g., MLH
// registration is pending and we need users to, e.g., consent to a CoC.
// if people don't confirm their spot over this question, their place will
// be freed anyways. therefore, something like a "if you're a student,
// what's your major and minor" question can be implemented as a separate
// two questions again checking the student situation. and in the end,
// there are humans checking registrations anyways
} catch (error) {
throw new IncompleteProfileFormError();
}
const questions = [
...skippedProfileQuestions,
...settings.application.confirmationForm.questions,
];
const questionIDs = questions.map(({ id }) => id);
const allAnswers = await this.findAllExistingAnswers(user);
const answers = allAnswers.filter(({ question: { id } }) =>
questionIDs.includes(id),
);
return {
answers,
questions,
};
}
/**
* @inheritdoc
*/
public async storeConfirmationFormAnswers(
user: User,
answers: readonly IRawAnswer[],
): Promise<void> {
if (user.declined) {
throw new AlreadyDeclinedError();
}
if (user.confirmationExpiresAt == null) {
throw new NotAdmittedError();
}
const isAfterDeadline = user.confirmationExpiresAt.getTime() < Date.now();
if (isAfterDeadline) {
throw new ConfirmationDeadlineFailedError(user.confirmationExpiresAt);
}
const { questions } = await this.getConfirmationForm(user);
await this.replaceAnswers(user, questions, answers);
if (!user.confirmed) {
user.confirmed = true;
await this._users.updateUser(user);
}
}
/**
* @inheritdoc
*/
public async getAll(): Promise<readonly IApplication[]> {
const allAnswers = await this._answers.find();
const allUsers = await this._users.findAll();
const answersByUserID = new Map<User["id"], Answer[]>();
for (const answer of allAnswers) {
try {
if (answer.user !== null) {
const answers = answersByUserID.get(answer.user.id) ?? [];
answers.push(answer);
answersByUserID.set(answer.user.id, answers);
}
} catch (error) {
throw new IncompleteProfileFormError();
}
}
const applications = allUsers.map<IApplication>((user) => ({
answers: answersByUserID.get(user.id) ?? [],
user,
}));
applications.sort(
(a, b) => a.user.createdAt.getTime() - b.user.createdAt.getTime(),
);
return applications;
}
/**
* @inheritdoc
*/
public async deleteAnswers(user: User): Promise<void> {
await this._answers.delete({
user: {
id: user.id,
},
});
}
/**
* @inheritdoc
*/
public async declineSpot(user: User): Promise<void> {
user.declined = true;
await this._users.updateUser(user);
}
/**
* @inheritdoc
*/
public async checkIn(user: User): Promise<void> {
user.checkedIn = true;
await this._users.updateUser(user);
}
}
export class QuestionNotFoundError extends Error {
constructor(questionID: number) {
super(`Question '${questionID}' not found`);
}
}
export class QuestionNotAnsweredError extends Error {
constructor(questionTitle: string, questionID: number) {
super(`Question '${questionTitle}' (#${questionID}) was not answered`);
}
}
export class InvalidAnswerError extends Error {
constructor(questionTitle: string, questionID: number, answer: string) {
super(
`Answer '${answer}' to question '${questionTitle}' (#${questionID}) is not valid`,
);
}
}
export class FormNotAvailableError extends Error {
constructor(from: Date, to: Date) {
super(
Date.now() < from.getTime()
? `This form is available from ${from.toISOString()}`
: `This form is available until ${to.toISOString()}`,
);
}
}
export class QuestionGraphBrokenError extends Error {
constructor() {
super("The question graph is apparently broken. Nice");
}
}
export class ProfileFormNotSubmittedError extends Error {
constructor() {
super("Profile form not submitted yet");
}
}
export class NotAdmittedError extends Error {
constructor() {
super("Your application was not yet admitted. Be patient");
}
}
export class IncompleteProfileFormError extends Error {
constructor() {
super("The profile form was incomplete");
}
}
export class ConfirmationDeadlineFailedError extends Error {
constructor(deadline: Date) {
super(`Your confirmation deadline was on ${deadline.toISOString()}`);
}
}
export class AlreadyDeclinedError extends Error {
constructor() {
super("You already declined your application");
}
}
export class AlreadyAdmittedError extends Error {
constructor() {
super("You're already admitted and can't change your previous answers");
}
}