-
Notifications
You must be signed in to change notification settings - Fork 13
/
application.students.controller.ts
662 lines (633 loc) · 22.7 KB
/
application.students.controller.ts
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
655
656
657
658
659
660
661
662
import {
BadRequestException,
Body,
Controller,
Get,
InternalServerErrorException,
NotFoundException,
Param,
Post,
Patch,
UnprocessableEntityException,
Query,
ParseIntPipe,
DefaultValuePipe,
ParseBoolPipe,
} from "@nestjs/common";
import {
ApplicationService,
FormService,
StudentService,
ProgramYearService,
APPLICATION_DRAFT_NOT_FOUND,
MORE_THAN_ONE_APPLICATION_DRAFT_ERROR,
APPLICATION_NOT_FOUND,
APPLICATION_NOT_VALID,
EducationProgramOfferingService,
StudentAssessmentService,
INVALID_OPERATION_IN_THE_CURRENT_STATUS,
ASSESSMENT_INVALID_OPERATION_IN_THE_CURRENT_STATE,
CRAIncomeVerificationService,
SupportingUserService,
StudentAppealService,
ApplicationOfferingChangeRequestService,
} from "../../services";
import { IUserToken, StudentUserToken } from "../../auth/userToken.interface";
import BaseController from "../BaseController";
import {
SaveApplicationAPIInDTO,
ApplicationDataAPIOutDTO,
ApplicationWithProgramYearAPIOutDTO,
ApplicationIdentifiersAPIOutDTO,
ApplicationNumberParamAPIInDTO,
InProgressApplicationDetailsAPIOutDTO,
ApplicationProgressDetailsAPIOutDTO,
EnrolmentApplicationDetailsAPIOutDTO,
CompletedApplicationDetailsAPIOutDTO,
} from "./models/application.dto";
import {
AllowAuthorizedParty,
UserToken,
CheckSinValidation,
RequiresStudentAccount,
} from "../../auth/decorators";
import { AuthorizedParties } from "../../auth/authorized-parties.enum";
import { ApiProcessError, ClientTypeBaseRoute } from "../../types";
import { getPIRDeniedReason, PIR_OR_DATE_OVERLAP_ERROR } from "../../utilities";
import {
INSTITUTION_LOCATION_NOT_VALID,
INVALID_APPLICATION_NUMBER,
OFFERING_NOT_VALID,
} from "../../constants";
import {
ApiBadRequestResponse,
ApiForbiddenResponse,
ApiNotFoundResponse,
ApiTags,
ApiUnprocessableEntityResponse,
} from "@nestjs/swagger";
import { ApplicationControllerService } from "./application.controller.service";
import { CustomNamedError } from "@sims/utilities";
import { PrimaryIdentifierAPIOutDTO } from "../models/primary.identifier.dto";
import { ApplicationData } from "@sims/sims-db/entities/application.model";
import {
ApplicationOfferingChangeRequestStatus,
ApplicationStatus,
StudentAppealStatus,
} from "@sims/sims-db";
import { ConfirmationOfEnrollmentService } from "@sims/services";
@AllowAuthorizedParty(AuthorizedParties.student)
@RequiresStudentAccount()
@Controller("application")
@ApiTags(`${ClientTypeBaseRoute.Student}-application`)
export class ApplicationStudentsController extends BaseController {
constructor(
private readonly applicationService: ApplicationService,
private readonly formService: FormService,
private readonly studentService: StudentService,
private readonly programYearService: ProgramYearService,
private readonly offeringService: EducationProgramOfferingService,
private readonly confirmationOfEnrollmentService: ConfirmationOfEnrollmentService,
private readonly assessmentService: StudentAssessmentService,
private readonly applicationControllerService: ApplicationControllerService,
private readonly craIncomeVerificationService: CRAIncomeVerificationService,
private readonly supportingUserService: SupportingUserService,
private readonly studentAppealService: StudentAppealService,
private readonly applicationOfferingChangeRequestService: ApplicationOfferingChangeRequestService,
) {
super();
}
/**
* Get application details by id.
* @param id for the application to be retrieved.
* @returns application details.
*/
@Get(":id")
@ApiNotFoundResponse({
description: "Application id not found.",
})
async getByApplicationId(
@Param("id", ParseIntPipe) applicationId: number,
@UserToken() userToken: StudentUserToken,
): Promise<ApplicationDataAPIOutDTO> {
const application = await this.applicationService.getApplicationById(
applicationId,
{ loadDynamicData: true, studentId: userToken.studentId },
);
if (!application) {
throw new NotFoundException(
`Application id ${applicationId} was not found.`,
);
}
const applicationDataPromise =
this.applicationControllerService.generateApplicationFormData(
application.data,
);
const firstCOEPromise =
this.confirmationOfEnrollmentService.getFirstDisbursementScheduleByApplication(
applicationId,
);
const [applicationData, firstCOE] = await Promise.all([
applicationDataPromise,
firstCOEPromise,
]);
application.data = applicationData;
return this.applicationControllerService.transformToApplicationDetailForStudentDTO(
application,
firstCOE,
);
}
/**
* Submit an existing student application changing the status
* to submitted and triggering the necessary processes.
* The system will ensure that an application will always be
* transitioning from draft to submitted status. The student
* application is not supposed to be created directly in the
* submitted status in any scenario.
* @param payload payload to create the draft application.
* @param applicationId application id to be changed to submitted.
* @param studentToken token from the authenticated student.
*/
@CheckSinValidation()
@Patch(":applicationId/submit")
@ApiUnprocessableEntityResponse({
description:
"Program Year is not active or " +
"Selected offering id is invalid or " +
"invalid study dates or selected study start date is not within the program year" +
"or APPLICATION_NOT_VALID or INVALID_OPERATION_IN_THE_CURRENT_STATUS or ASSESSMENT_INVALID_OPERATION_IN_THE_CURRENT_STATE " +
"or INSTITUTION_LOCATION_NOT_VALID or OFFERING_NOT_VALID.",
})
@ApiBadRequestResponse({ description: "Form validation failed." })
@ApiNotFoundResponse({ description: "Application not found." })
@ApiForbiddenResponse({
description: "You have a restriction on your account.",
})
async submitApplication(
@Body() payload: SaveApplicationAPIInDTO,
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() studentToken: StudentUserToken,
): Promise<void> {
const programYear = await this.programYearService.getActiveProgramYear(
payload.programYearId,
);
if (!programYear) {
throw new UnprocessableEntityException(
"Program Year is not active. Not able to create an application invalid request.",
);
}
// studyStartDate from payload is set as studyStartDate
let studyStartDate = payload.data.studystartDate;
let studyEndDate = payload.data.studyendDate;
if (payload.data.selectedOffering) {
const offering = await this.offeringService.getOfferingById(
payload.data.selectedOffering,
);
if (!offering) {
throw new UnprocessableEntityException(
"Selected offering id is invalid.",
);
}
// if studyStartDate is not in payload
// then selectedOffering will be there in payload,
// then study start date taken from offering
studyStartDate = offering.studyStartDate;
studyEndDate = offering.studyEndDate;
// This ensures that if an offering is selected in student application,
// then the study start date and study end date present in form submission payload
// belongs to the selected offering and hence prevents these dates being modified in the
// middle before coming to API.
payload.data.selectedOfferingDate = studyStartDate;
payload.data.selectedOfferingEndDate = studyEndDate;
}
const submissionResult =
await this.formService.dryRunSubmission<ApplicationData>(
programYear.formName,
payload.data,
);
if (!submissionResult.valid) {
throw new BadRequestException(
"Not able to create an application due to an invalid request.",
);
}
await this.applicationControllerService.offeringIntensityRestrictionCheck(
studentToken.studentId,
submissionResult.data.data.howWillYouBeAttendingTheProgram,
);
const student = await this.studentService.getStudentById(
studentToken.studentId,
);
try {
await this.applicationService.validateOverlappingDatesAndPIR(
applicationId,
student.user.lastName,
studentToken.userId,
student.sinValidation.sin,
student.birthDate,
studyStartDate,
studyEndDate,
);
const { createdAssessment } =
await this.applicationService.submitApplication(
applicationId,
studentToken.userId,
student.id,
programYear.id,
submissionResult.data.data,
payload.associatedFiles,
);
await this.assessmentService.startAssessment(createdAssessment.id);
} catch (error) {
switch (error.name) {
case APPLICATION_NOT_FOUND:
throw new NotFoundException(error.message);
case APPLICATION_NOT_VALID:
case INVALID_OPERATION_IN_THE_CURRENT_STATUS:
case PIR_OR_DATE_OVERLAP_ERROR:
case INSTITUTION_LOCATION_NOT_VALID:
case OFFERING_NOT_VALID:
throw new UnprocessableEntityException(
new ApiProcessError(error.message, error.name),
);
case ASSESSMENT_INVALID_OPERATION_IN_THE_CURRENT_STATE:
throw new UnprocessableEntityException(error.message);
default:
// TODO: add logger.
throw new InternalServerErrorException(
"Unexpected error while submitting the application.",
);
}
}
}
/**
* Creates a new application draft for the authenticated student.
* The student is allowed to have only one draft application, so
* this method will create the draft or throw an exception in case
* of the draft already exists.
* @param payload payload to create the draft application.
* @param studentToken token from the authenticated student.
* @returns the application id of the created draft or an
* HTTP exception if it is not possible to create it.
*/
@CheckSinValidation()
@ApiUnprocessableEntityResponse({
description:
"Program Year is not active or MORE_THAN_ONE_APPLICATION_DRAFT_ERROR.",
})
@Post("draft")
async createDraftApplication(
@Body() payload: SaveApplicationAPIInDTO,
@UserToken() studentToken: StudentUserToken,
): Promise<PrimaryIdentifierAPIOutDTO> {
const programYear = await this.programYearService.getActiveProgramYear(
payload.programYearId,
);
if (!programYear) {
throw new UnprocessableEntityException(
"Program Year is not active, not able to create a draft application.",
);
}
try {
const draftApplication =
await this.applicationService.saveDraftApplication(
studentToken.studentId,
studentToken.userId,
payload.programYearId,
payload.data,
payload.associatedFiles,
);
return { id: draftApplication.id };
} catch (error) {
if (error.name === MORE_THAN_ONE_APPLICATION_DRAFT_ERROR) {
throw new UnprocessableEntityException(
new ApiProcessError(error.message, error.name),
);
}
throw new InternalServerErrorException(
"Unexpected error while creating the draft application.",
);
}
}
/**
* Updates an existing application draft
* @param payload payload to update the draft application.
* @param applicationId draft application id.
* @param studentToken token from the authenticated student.
*/
@CheckSinValidation()
@Patch(":applicationId/draft")
@ApiNotFoundResponse({ description: "APPLICATION_DRAFT_NOT_FOUND." })
async updateDraftApplication(
@Body() payload: SaveApplicationAPIInDTO,
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() studentToken: StudentUserToken,
): Promise<void> {
try {
await this.applicationService.saveDraftApplication(
studentToken.studentId,
studentToken.userId,
payload.programYearId,
payload.data,
payload.associatedFiles,
applicationId,
);
} catch (error) {
if (error.name === APPLICATION_DRAFT_NOT_FOUND) {
throw new NotFoundException(error);
}
throw new InternalServerErrorException(
"Unexpected error while updating the draft application.",
);
}
}
/**
* Cancel a student application.
* @param applicationId application id to be cancelled.
*/
@ApiUnprocessableEntityResponse({
description:
"Application not found or it is not in the correct state to be cancelled.",
})
@Patch(":applicationId/cancel")
async cancelStudentApplication(
@UserToken() userToken: StudentUserToken,
@Param("applicationId", ParseIntPipe) applicationId: number,
): Promise<void> {
try {
await this.applicationService.cancelStudentApplication(
applicationId,
userToken.studentId,
userToken.userId,
);
} catch (error: unknown) {
if (
error instanceof CustomNamedError &&
error.name === APPLICATION_NOT_FOUND
) {
throw new NotFoundException(error.message);
}
throw error;
}
}
/**
* Get program year details for the application.
* @param applicationId application id to be updated.
* @query includeInActivePY, if includeInActivePY is true,
* then consider both active and inactive program year.
* @returns program year details of the application
*/
@ApiNotFoundResponse({ description: "Student not found." })
@Get(":applicationId/program-year")
async programYearOfApplication(
@UserToken() userToken: IUserToken,
@Param("applicationId", ParseIntPipe) applicationId: number,
@Query("includeInActivePY", new DefaultValuePipe(false), ParseBoolPipe)
includeInActivePY: boolean,
): Promise<ApplicationWithProgramYearAPIOutDTO> {
const student = await this.studentService.getStudentByUserId(
userToken.userId,
);
if (!student) {
throw new NotFoundException("The user is not associated with a student.");
}
const applicationProgramYear =
await this.applicationService.getProgramYearOfApplication(
student.id,
applicationId,
includeInActivePY,
);
return {
applicationId: applicationId,
programYearId: applicationProgramYear.programYear.id,
formName: applicationProgramYear.programYear.formName,
active: applicationProgramYear.programYear.active,
};
}
/**
* Get application to request appeal.
** Application eligible to be requested for
** a change will be returned.
* @param applicationNumber
* @param userToken
* @returns application
*/
@ApiNotFoundResponse({
description:
"Application either not found or not eligible to request for change.",
})
@Get(":applicationNumber/appeal")
async getApplicationToRequestAppeal(
@Param() applicationNumberParam: ApplicationNumberParamAPIInDTO,
@UserToken() userToken: IUserToken,
): Promise<ApplicationIdentifiersAPIOutDTO> {
const application =
await this.applicationService.getApplicationToRequestAppeal(
userToken.userId,
applicationNumberParam.applicationNumber,
);
if (!application) {
throw new NotFoundException(
new ApiProcessError(
"Given application either does not exist or is not complete to request change.",
INVALID_APPLICATION_NUMBER,
),
);
}
return {
id: application.id,
applicationNumber: application.applicationNumber,
};
}
/**
* Get in progress details of an application by application id.
* @param applicationId application id.
* @returns application details.
*/
@Get(":applicationId/in-progress")
@ApiNotFoundResponse({
description: "Application id not found.",
})
async getInProgressApplicationDetails(
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() studentToken: StudentUserToken,
): Promise<InProgressApplicationDetailsAPIOutDTO> {
const application = await this.applicationService.getApplicationDetails(
applicationId,
studentToken.studentId,
);
if (!application) {
throw new NotFoundException(
`Application id ${applicationId} was not found.`,
);
}
const incomeVerificationDetails =
await this.craIncomeVerificationService.getAllIncomeVerificationsForAnApplication(
applicationId,
);
const incomeVerification =
this.applicationControllerService.processApplicationIncomeVerificationDetails(
incomeVerificationDetails,
);
const supportingUserDetails =
await this.supportingUserService.getSupportingUsersByApplicationId(
applicationId,
);
const supportingUser =
this.applicationControllerService.processApplicationSupportingUserDetails(
supportingUserDetails,
);
return {
id: application.id,
applicationStatus: application.applicationStatus,
pirStatus: application.pirStatus,
pirDeniedReason: getPIRDeniedReason(application),
exceptionStatus: application.applicationException?.exceptionStatus,
...incomeVerification,
...supportingUser,
};
}
/**
* Get status of all requests and confirmations in student application (Exception, PIR and COE).
* @param applicationId Student application.
* @returns application progress details.
*/
@ApiNotFoundResponse({
description: "Application not found.",
})
@Get(":applicationId/progress-details")
async getApplicationProgressDetails(
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() userToken: StudentUserToken,
): Promise<ApplicationProgressDetailsAPIOutDTO> {
const application = await this.applicationService.getApplicationDetails(
applicationId,
userToken.studentId,
);
if (!application) {
throw new NotFoundException(
`Application id ${applicationId} was not found.`,
);
}
let appealStatus: StudentAppealStatus;
let applicationOfferingChangeRequestStatus: ApplicationOfferingChangeRequestStatus;
if (application.applicationStatus === ApplicationStatus.Completed) {
const appealPromise = this.studentAppealService.getAppealsForApplication(
applicationId,
userToken.studentId,
{ limit: 1 },
);
const applicationOfferingChangeRequestPromise =
this.applicationOfferingChangeRequestService.getApplicationOfferingChangeRequest(
applicationId,
userToken.studentId,
);
const [[appeal], applicationOfferingChangeRequest] = await Promise.all([
appealPromise,
applicationOfferingChangeRequestPromise,
]);
appealStatus = appeal?.status;
applicationOfferingChangeRequestStatus =
applicationOfferingChangeRequest?.applicationOfferingChangeRequestStatus;
}
const disbursements =
application.currentAssessment?.disbursementSchedules ?? [];
disbursements.sort((a, b) =>
a.disbursementDate < b.disbursementDate ? -1 : 1,
);
const [firstDisbursement, secondDisbursement] = disbursements;
const [scholasticStandingChange] = application.studentScholasticStandings;
return {
applicationStatus: application.applicationStatus,
applicationStatusUpdatedOn: application.applicationStatusUpdatedOn,
pirStatus: application.pirStatus,
firstCOEStatus: firstDisbursement?.coeStatus,
secondCOEStatus: secondDisbursement?.coeStatus,
exceptionStatus: application.applicationException?.exceptionStatus,
appealStatus,
scholasticStandingChangeType: scholasticStandingChange?.changeType,
applicationOfferingChangeRequestStatus,
};
}
/**
* Get details for the application enrolment status of a student application.
* @param applicationId student application id.
* @returns details for the application enrolment status.
*/
@ApiNotFoundResponse({
description:
"Application not found or not in relevant status to get enrolment details.",
})
@Get(":applicationId/enrolment")
async getEnrolmentApplicationDetails(
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() userToken: StudentUserToken,
): Promise<EnrolmentApplicationDetailsAPIOutDTO> {
const application =
await this.applicationService.getApplicationAssessmentDetails(
applicationId,
{ studentId: userToken.studentId },
);
if (!application) {
throw new NotFoundException(
`Application id ${applicationId} not found or not in relevant status to get enrolment details.`,
);
}
return this.applicationControllerService.transformToEnrolmentApplicationDetailsAPIOutDTO(
application.currentAssessment.disbursementSchedules,
);
}
/**
* Get details for an application at completed status.
* @param applicationId application id.
* @returns details for an application on at completed status.
*/
@ApiNotFoundResponse({
description: `Application not found or not on ${ApplicationStatus.Completed} status.`,
})
@Get(":applicationId/completed")
async getCompletedApplicationDetails(
@Param("applicationId", ParseIntPipe) applicationId: number,
@UserToken() userToken: StudentUserToken,
): Promise<CompletedApplicationDetailsAPIOutDTO> {
const getApplicationPromise =
this.applicationService.getApplicationAssessmentDetails(applicationId, {
studentId: userToken.studentId,
applicationStatus: [ApplicationStatus.Completed],
});
const appealPromise = this.studentAppealService.getAppealsForApplication(
applicationId,
userToken.studentId,
{ limit: 1 },
);
const applicationOfferingChangeRequestPromise =
this.applicationOfferingChangeRequestService.getApplicationOfferingChangeRequest(
applicationId,
userToken.studentId,
);
const [application, [appeal], applicationOfferingChangeRequest] =
await Promise.all([
getApplicationPromise,
appealPromise,
applicationOfferingChangeRequestPromise,
]);
if (!application) {
throw new NotFoundException(
`Application not found or not on ${ApplicationStatus.Completed} status.`,
);
}
const enrolmentDetails =
this.applicationControllerService.transformToEnrolmentApplicationDetailsAPIOutDTO(
application.currentAssessment.disbursementSchedules,
);
const [scholasticStandingChange] = application.studentScholasticStandings;
return {
firstDisbursement: enrolmentDetails.firstDisbursement,
secondDisbursement: enrolmentDetails.secondDisbursement,
assessmentTriggerType: application.currentAssessment.triggerType,
appealStatus: appeal?.status,
scholasticStandingChangeType: scholasticStandingChange?.changeType,
applicationOfferingChangeRequestStatus:
applicationOfferingChangeRequest?.applicationOfferingChangeRequestStatus,
};
}
}