@universis/evaluations 1.0.34 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,307 @@
1
+ import {EdmMapping, EdmType} from '@themost/data';
2
+ import EvaluationEvent from "./evaluation-event-model";
3
+ import {DataError, TraceUtils, DataNotFoundError, LangUtils} from "@themost/common";
4
+ import moment from "moment";
5
+ /**
6
+ * @class
7
+ */
8
+ @EdmMapping.entityType('StudyProgramEvaluationEvent')
9
+ class StudyProgramEvaluationEvent extends EvaluationEvent {
10
+ /**
11
+ * @constructor
12
+ */
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ @EdmMapping.func('Results', EdmType.CollectionOf('Object'))
18
+ async getResults() {
19
+ // check access to StudyProgramEvaluationEvent and get results silently
20
+ const event = await this.context.model('StudyProgramEvaluationEvent').where('id').equal(this.getId());
21
+ if (event) {
22
+ const form = await this.getForm();
23
+ return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).silent().prepare();
24
+ }
25
+ }
26
+
27
+ @EdmMapping.action('GenerateEvaluationTokens', 'GenerateStudyProgramTokenAction')
28
+ async generateEvaluationTokens() {
29
+ const context = this.context;
30
+ const action = {
31
+ event: this.id,
32
+ numberOfStudents: 0,
33
+ total: 0,
34
+ actionStatus: {alternateName: 'PotentialActionStatus'}
35
+ };
36
+ // get event
37
+ const event = await context.model('StudyProgramEvaluationEvent').where('id').equal(this.id)
38
+ .expand('studyProgram')
39
+ .getItem();
40
+ if (event) {
41
+ //check if a GenerateTokenAction exists
42
+ const prevAction = await context.model('GenerateStudyProgramTokenAction').where('event').equal(this.id)
43
+ .and('actionStatus/alternateName').notEqual('FailedActionStatus')
44
+ .silent().getItem();
45
+ if (prevAction) {
46
+ throw new Error(context.__('A previous action for generating evaluation tokens has been found.'));
47
+ }
48
+ const studyProgram = event.studyProgram;
49
+ const studentStatuses = context.getConfiguration().getSourceAt('settings/universis/evaluations/studyProgramStudentStatuses') || ['graduated','declared'];
50
+ let students;
51
+ try {
52
+ students = await this.getStudents(studyProgram, event.academicYear, event.academicPeriod, studentStatuses);
53
+ }
54
+ catch (err) {
55
+ throw new DataError(err);
56
+ }
57
+ if (!(Array.isArray(students) && students.length)) {
58
+ throw new DataError('E_STUDENTS_FOUND', context.__('No students available to evaluate this study program'));
59
+ }
60
+ action.numberOfStudents = students.length;
61
+ // save action and then generateTokens
62
+ const generateAction = await context.model('GenerateStudyProgramTokenAction').save(action);
63
+ const generateOptions =
64
+ {
65
+ evaluationEvent: event.id,
66
+ n: action.numberOfStudents,
67
+ expires: event.endDate
68
+ };
69
+ try {
70
+ // save number of students to event
71
+ event.numberOfStudents = action.numberOfStudents;
72
+ await context.model('StudyProgramEvaluationEvent').save(event);
73
+ if (event.numberOfStudents > 0) {
74
+ await EvaluationEvent.generateTokens(context, generateOptions);
75
+ }
76
+ generateAction.total = action.numberOfStudents;
77
+ generateAction.actionStatus = {alternateName: 'CompletedActionStatus'}
78
+ return await context.model('GenerateStudyProgramTokenAction').save(generateAction);
79
+ } catch (err) {
80
+ TraceUtils.error(err);
81
+ // update also action status
82
+ generateAction.total = 0;
83
+ generateAction.actionStatus = {alternateName: 'FailedActionStatus'}
84
+ generateAction.description = err.message;
85
+ return await context.model('GenerateStudyProgramTokenAction').save(generateAction);
86
+
87
+ }
88
+
89
+
90
+ }
91
+ }
92
+
93
+ async getStudents(studyProgram, academicYear, academicPeriod, studentStatuses) {
94
+ try {
95
+ const serviceProvider = await this.context.model('ServiceProvider')
96
+ .where('alternateName').equal('universis')
97
+ .silent().getTypedItem();
98
+ if (serviceProvider == null) {
99
+ TraceUtils.error(`Universis service provider not found.`);
100
+ return new DataError(`Cannot get students for study program. Universis service provider not found.`);
101
+ }
102
+ let url = `Students?$select=id as student,person/email as email&$filter=studyProgram eq ${studyProgram.id}`
103
+ if (Array.isArray(studentStatuses) && studentStatuses.length > 0) {
104
+ const filters = [];
105
+ // get active student for specific inscription year and period
106
+ if (studentStatuses.includes('active')) {
107
+ filters.push(`(studentStatus/alternateName eq 'active' and inscriptionYear eq ${academicYear} and inscriptionPeriod eq ${academicPeriod}))`);
108
+ }
109
+ if (studentStatuses.includes('graduated')) {
110
+ filters.push(`(studentStatus/alternateName eq 'graduated' and graduationYear eq ${academicYear} and graduationPeriod eq ${academicPeriod})`);
111
+ }
112
+ if (studentStatuses.includes('declared')) {
113
+ filters.push(
114
+ `(studentStatus/alternateName eq 'declared' and declaration/declaredYear eq ${academicYear} and declaration/declaredPeriod eq ${academicPeriod})`
115
+ );
116
+ }
117
+ if (filters.length > 0) {
118
+ url += ` and (${filters.join(' or ')})`;
119
+ }
120
+ }
121
+ const response = await serviceProvider.execute({
122
+ "url": url,
123
+ "method": 'GET'
124
+ });
125
+ return response && response.value;
126
+ } catch (err) {
127
+ TraceUtils.error(err);
128
+ throw (err);
129
+ }
130
+ }
131
+
132
+ @EdmMapping.func('TokenInfo', EdmType.CollectionOf('Object'))
133
+ async getTokenStatistics() {
134
+ const tokenInfo = {
135
+ total: 0,
136
+ used: 0,
137
+ sent: 0
138
+ };
139
+ // get number of tokens
140
+ const tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
141
+ .select('count(evaluationEvent) as total', 'used', 'sent')
142
+ .groupBy('used', 'sent', 'evaluationEvent')
143
+ .silent().getItems();
144
+ tokens.map(item => {
145
+ tokenInfo.total += item.total;
146
+ tokenInfo.used += item.used ? item.total : 0;
147
+ tokenInfo.sent += item.sent ? item.total : 0;
148
+ });
149
+ return tokenInfo;
150
+ }
151
+
152
+ @EdmMapping.action('SendEvaluationTokens', 'SendStudyProgramTokenAction')
153
+ async sendEvaluationTokens() {
154
+
155
+ const context = this.context;
156
+ let sendAction = {};
157
+ let subject;
158
+ // get event and check if event endDate has passed
159
+ try {
160
+ // get current date
161
+ const currentDate = moment(new Date()).startOf('day').toDate(); // get only date format
162
+ const event = await context.model('StudyProgramEvaluationEvent').where('id').equal(this.getId())
163
+ .and('date(endDate)').greaterOrEqual(currentDate)
164
+ .expand({
165
+ name: 'studyProgram',
166
+ options: {
167
+ '$expand': 'department'
168
+ }
169
+ },
170
+ {
171
+ name: 'actions',
172
+ options: {
173
+ '$expand': 'actionStatus'
174
+ }
175
+ })
176
+ .getItem();
177
+ // validate event
178
+ if (event == null) {
179
+ throw new DataNotFoundError('The event cannot be found or is inaccessible.');
180
+ }
181
+ // validate status
182
+ if (!(event.eventStatus && event.eventStatus.alternateName === 'EventOpened')) {
183
+ throw new DataError('E_INVALID_PERIOD', context.__('Send tokens action may only be executed for Open/Active events'));
184
+ }
185
+ // validate event actions
186
+ if (!(event.actions && event.actions.length)) {
187
+ throw new DataNotFoundError('E_NO_TOKENS', context.__('Token actions were not found for the specified event or they are inaccessible.'));
188
+ }
189
+ // find completed token generation action (can only be one)
190
+ const successfulTokenAction = event.actions.find(generateTokenAction => generateTokenAction.actionStatus.alternateName === 'CompletedActionStatus');
191
+ if (successfulTokenAction == null) {
192
+ throw new DataError('E_NO_TOKENS', 'The specified event does not have a completed token generation action.');
193
+ }
194
+ // get tokenInfo for this event
195
+ const tokenInfo = await this.getTokenStatistics();
196
+ // validate sent-used separately for descriptive errors
197
+ if (tokenInfo.sent) {
198
+ throw new DataError('E_ALREADY_SENT', `${context.__('The bulk sending of the tokens could not be completed because some of them had already been sent')} (${tokenInfo.sent})`);
199
+ }
200
+ if (tokenInfo.used) {
201
+ throw new DataError('E_ALREADY_USED', `${context.__('The bulk sending of the tokens could not be completed because some of them had already been used')} (${tokenInfo.used})`);
202
+ }
203
+ // start gathering students
204
+ let students;
205
+ const studyProgram = event.studyProgram;
206
+ // get students
207
+ const studentStatuses = ['graduated','declared','active']
208
+ students = await this.getStudents(studyProgram,event.academicYear,event.academicPeriod,studentStatuses);
209
+
210
+ if (!(Array.isArray(students) && students.length)) {
211
+ throw new DataError('E_STUDENTS_FOUND', 'No recipients/students found.');
212
+ }
213
+ // check total of students
214
+ if (students.length !== tokenInfo.total) {
215
+ throw new DataError('E_TOTAL_STUDENTS',
216
+ `${this.context.__("The number of students in the study program differs from the generated tokens")}` +
217
+ `(${this.context.__("Students")}: ${students.length}, ${this.context.__("Number of tokens")}:${tokenInfo.total}.`);
218
+ }
219
+ // validate student emails, must all exist and have a valid format
220
+ const mailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
221
+ const invalidEmail = students.find(student => {
222
+ return !(student.email && mailRegex.test(student.email));
223
+ });
224
+ if (invalidEmail) {
225
+ throw new DataError('E_INVALID_EMAIL', `${context.__('At least one student\'s email is null or invalid')} (email:${invalidEmail.email || ' '} ${context.__('Student')}:${invalidEmail.student})`);
226
+ }
227
+ // get tokens
228
+ let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
229
+ .silent()
230
+ .getAllItems();
231
+
232
+ // get mail template
233
+ const mailTemplate = await context.model('MailConfiguration')
234
+ .where('target').equal('SendStudyProgramTokenAction')
235
+ .silent()
236
+ .getItem();
237
+ if (mailTemplate == null) {
238
+ throw new DataError('E_MISSING_TEMPLATE', 'Cannot execute send tokens action because template is missing for SendStudyProgramTokenAction.');
239
+ }
240
+ // check if there is already an active sendTokensAction
241
+ const alreadySendingTokens = await context.model('SendStudyProgramTokenAction')
242
+ .where('event').equal(event.id)
243
+ .and('actionStatus/alternateName').equal('ActiveActionStatus')
244
+ .silent().count();
245
+ if (alreadySendingTokens) {
246
+ throw new DataError('E_ALREADY_SENDING', `${context.__('The bulk sending process of tokens is already in progress')}`);
247
+ }
248
+ // save SendInstructorTokenAction
249
+ const sendTokenAction = {
250
+ event: this.getId(),
251
+ numberOfStudents: students.length,
252
+ total: tokenInfo.total,
253
+ sent: 0,
254
+ failed: 0,
255
+ actionStatus: {
256
+ alternateName: 'ActiveActionStatus'
257
+ }
258
+ }
259
+ sendAction = await context.model('SendStudyProgramTokenAction').silent().save(sendTokenAction);
260
+ // format mail subject expected params ${course}, ${instructor}
261
+ const exp = new RegExp('\\$\\{\\w+\\}+', 'ig');
262
+ subject = mailTemplate.subject;
263
+ const params = subject.match(exp);
264
+ if (params.length > 0) {
265
+ // parse only custom parameters ${studyProgram}
266
+ params.forEach(param => {
267
+ if (param === '${studyProgram}') {
268
+ // get studyProgram full name
269
+ subject = subject.replace(param, studyProgram ? `${studyProgram.name}` : '');
270
+ } else {
271
+ subject = subject.replace(param, '');
272
+ }
273
+ });
274
+ }
275
+ EvaluationEvent.sendMessages(context, students, tokens, tokenInfo, mailTemplate, subject, sendAction, event);
276
+ } catch (err) {
277
+ TraceUtils.error(err);
278
+ // create send tokens action
279
+ const sendTokenAction = {
280
+ event: this.getId(),
281
+ numberOfStudents: 0,
282
+ total: 0,
283
+ sent: 0,
284
+ failed: 0,
285
+ actionStatus: {
286
+ alternateName: 'FailedActionStatus'
287
+ },
288
+ description: err.message
289
+ }
290
+ // and save
291
+ if (sendAction && sendAction.id) {
292
+ sendTokenAction.id = sendAction.id;
293
+ }
294
+ if (!subject) {
295
+ // load courseClass
296
+ const item = await context.model('StudyProgramEvaluationEvent').where('id').equal(this.getId())
297
+ .expand('studyProgram')
298
+ .getItem();
299
+ const studyProgram = item && item.studyProgram
300
+ subject = studyProgram ? `${studyProgram.name}` : '';
301
+ }
302
+ EvaluationEvent.sendSse(context.user, context, this.getId(), subject, err);
303
+ return await context.model('SendStudyProgramTokenAction').silent().save(sendTokenAction);
304
+ }
305
+ }
306
+ }
307
+ module.exports = StudyProgramEvaluationEvent;