@universis/evaluations 1.0.20 → 1.0.22

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@universis/evaluations",
3
- "version": "1.0.20",
3
+ "version": "1.0.22",
4
4
  "description": "Universis evaluations library",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -3,10 +3,24 @@ import {EvaluationKeyHandler} from "./handlers/evaluation-key-handler";
3
3
  import { getEntitySetFunction} from "@themost/express";
4
4
  import i18n from "i18n";
5
5
  import {postEntitySetFunction} from "@themost/express";
6
+ const el = require('./locales/el.json');
6
7
 
8
+ /**
9
+ *
10
+ * @param {ExpressDataApplication} app
11
+ * @returns {*}
12
+ */
7
13
  export function evaluationRouter(app) {
8
14
 
9
15
  const router = express.Router();
16
+ // add translations
17
+ if (app && app.parentApplication) {
18
+ const translateService = app.parentApplication.getService(function TranslateService() {
19
+ });
20
+ if (translateService) {
21
+ translateService.setTranslation('el', el);
22
+ }
23
+ }
10
24
 
11
25
  router.use((req, res, next) => {
12
26
  // create router context
@@ -12,7 +12,7 @@ const EvaluationAccessToken = require('../models/evaluation-access-token-model')
12
12
  const evaluationKey = req.headers['evaluation-key'].replace(/-/ig, '');
13
13
  return EvaluationAccessToken.inspect(req.context, evaluationKey).then((token) => {
14
14
  if (token.active === false) {
15
- return callback(new HttpTokenExpiredError('Evaluation access token has been expired'))
15
+ return callback(new HttpTokenExpiredError(req.context.__('Evaluation access token has been expired')));
16
16
  }
17
17
  req.context.user = req.context.user || {
18
18
  name: 'anonymous',
@@ -83,3 +83,41 @@ export async function afterExecuteAsync(event) {
83
83
  }
84
84
  }
85
85
  }
86
+
87
+ /**
88
+ * @async
89
+ * @param {DataEventArgs} event
90
+ */
91
+ async function beforeRemoveAsync(event) {
92
+ // ensure associations
93
+ const context = event.model.context;
94
+ const evaluationEvent = context.model('EvaluationEvent').convert(event.target);
95
+ const form = await evaluationEvent.property('evaluationDocument').getItem();
96
+ if (form && form.resultType) {
97
+ if (context.model(form.resultType) == null) {
98
+ // ensure model is added to configuration
99
+ await evaluationEvent.getForm();
100
+ }
101
+ const answers = await context.model(form.resultType)
102
+ .where('evaluationEvent').equal(event.target.id)
103
+ .silent().count();
104
+ if (answers) {
105
+ throw new Error('Cannot remove evaluation event since there are responses associated with it')
106
+ }
107
+ }
108
+ }
109
+
110
+
111
+ /**
112
+ * @param {DataEventArgs} event
113
+ * @param {Function} callback
114
+ */
115
+ export function beforeRemove(event, callback) {
116
+ // execute async method
117
+ return beforeRemoveAsync(event).then(() => {
118
+ return callback();
119
+ }).catch(err => {
120
+ return callback(err);
121
+ });
122
+ }
123
+
@@ -0,0 +1,20 @@
1
+ {
2
+ "An error occurred": "Συνέβη σφάλμα",
3
+ "The number of students in the class differs from the generated tokens": "Ο αριθμός των φοιτητών της τάξης διαφέρει από τα δημιουργημένα tokens",
4
+ "Students": "Φοιτητές",
5
+ "Number of tokens": "Αριθμός tokens",
6
+ "Send tokens action may only be executed for Open/Active events": "Η αποστολή των tokens μπορεί να γίνει μόνο για ανοιχτές αξιολογήσεις",
7
+ "Evaluation access token has been expired": "Ο κωδικός αξιολόγησης έχει λήξει",
8
+ "Token actions were not found for the specified event or they are inaccessible.": "Δε βρέθηκαν ενέργειες δημιουργίας για την αξιολόγηση ή δεν είναι διαθέσιμες",
9
+ "At least one student's email is null or invalid": "Τουλάχιστον ένα email φοιτητή δεν είναι έγκυρο ή είναι κενό",
10
+ "Student": "Φοιτητής",
11
+ "Sending tokens failed for all students": "Η αποστολή απέτυχε για όλους τους φοιτητές",
12
+ "The bulk sending of the tokens could not be completed because some of them had already been sent": "Δεν μπόρεσε να γίνει η μαζική αποστολή των tokens διότι κάποιο από αυτά είχε ήδη σταλεί",
13
+ "The bulk sending of the tokens could not be completed because some of them had already been used": "Δεν μπόρεσε να γίνει η μαζική αποστολή των tokens διότι κάποιο από αυτά είχε ήδη χρησιμοποιηθεί",
14
+ "Evaluation period for this course has not been started yet" : "Η περίοδος αξιολόγησης για το μάθημα δεν έχει ξεκινήσει ακόμη",
15
+ "Evaluation period for this course has been expired" : "Η περίοδος αξιολόγησης για το μάθημα έχει λήξει",
16
+ "Evaluation token has been expired" : "Ο κωδικός αξιολόγησης έχει λήξει",
17
+ "The course evaluation has been closed and is no longer available": "Η αξιολόγηση του μαθήματος έχει κλείσει και δεν είναι πλέον διαθέσιμη",
18
+ "Evaluation access token has been expired or is invalid.": "Ο κωδικός αξιολόγησης έχει λήξει ή δεν είναι έγκυρος",
19
+ "The bulk sending process of tokens is already in progress": "Η μαζική αποστολή των μηνυμάτων έχει ήδη ξεκινήσει"
20
+ }
@@ -1,7 +1,6 @@
1
1
  import {EdmMapping, EdmType} from '@themost/data';
2
2
  import EvaluationEvent from "./evaluation-event-model";
3
3
  import {DataError, TraceUtils, DataNotFoundError} from "@themost/common";
4
- import {getMailer} from "@themost/mailer";
5
4
  import moment from "moment";
6
5
 
7
6
  /**
@@ -26,7 +25,7 @@ class ClassInstructorEvaluationEvent extends EvaluationEvent {
26
25
  }
27
26
  }
28
27
  @EdmMapping.action('GenerateEvaluationTokens', 'GenerateInstructorTokenAction')
29
- async generateEvaluationTokens() {
28
+ async generateEvaluationTokens() {
30
29
  const context = this.context;
31
30
  const action = {
32
31
  event: this.id,
@@ -82,13 +81,13 @@ class ClassInstructorEvaluationEvent extends EvaluationEvent {
82
81
  {
83
82
  evaluationEvent: event.id,
84
83
  n: action.numberOfStudents,
85
- expires : event.endDate
84
+ expires: event.endDate
86
85
  };
87
86
  try {
88
87
  // save number of students to event
89
88
  event.numberOfStudents = action.numberOfStudents;
90
89
  await context.model('ClassInstructorEvaluationEvent').save(event);
91
- if (event.numberOfStudents>0) {
90
+ if (event.numberOfStudents > 0) {
92
91
  await EvaluationEvent.generateTokens(context, generateOptions);
93
92
  }
94
93
  generateAction.total = action.numberOfStudents;
@@ -128,126 +127,149 @@ class ClassInstructorEvaluationEvent extends EvaluationEvent {
128
127
 
129
128
  @EdmMapping.action('SendEvaluationTokens', 'SendInstructorTokenAction')
130
129
  async sendEvaluationTokens() {
130
+
131
131
  const context = this.context;
132
+ let sendAction = {};
133
+ let subject;
132
134
  // get event and check if event endDate has passed
133
- // get current date
134
- const currentDate = moment(new Date()).startOf('day').toDate(); // get only date format
135
- const event = await context.model('ClassInstructorEvaluationEvent').where('id').equal(this.getId())
136
- .and('date(endDate)').greaterOrEqual(currentDate)
137
- .expand({
138
- name: 'courseClassInstructor',
139
- options: {
140
- '$expand': 'courseClass($expand=course), instructor' // expand course and instructor so their attributes are available in the mail template
141
- }
142
- },
143
- {
144
- name: 'actions',
145
- options: {
146
- '$expand': 'actionStatus'
135
+ try {
136
+ // get current date
137
+ const currentDate = moment(new Date()).startOf('day').toDate(); // get only date format
138
+ const event = await context.model('ClassInstructorEvaluationEvent').where('id').equal(this.getId())
139
+ .and('date(endDate)').greaterOrEqual(currentDate)
140
+ .expand({
141
+ name: 'courseClassInstructor',
142
+ options: {
143
+ '$expand': 'courseClass($expand=course), instructor' // expand course and instructor so their attributes are available in the mail template
144
+ }
145
+ },
146
+ {
147
+ name: 'actions',
148
+ options: {
149
+ '$expand': 'actionStatus'
150
+ }
151
+ })
152
+ .getItem();
153
+ // validate event
154
+ if (event == null) {
155
+ throw new DataNotFoundError('The event cannot be found or is inaccessible.');
156
+ }
157
+ // validate status
158
+ if (!(event.eventStatus && event.eventStatus.alternateName === 'EventOpened')) {
159
+ throw new DataError('E_INVALID_PERIOD', context.__('Send tokens action may only be executed for Open/Active events'));
160
+ }
161
+ // validate event actions
162
+ if (!(event.actions && event.actions.length)) {
163
+ throw new DataNotFoundError('E_NO_TOKENS', context.__('Token actions were not found for the specified event or they are inaccessible.'));
164
+ }
165
+ // find completed token generation action (can only be one)
166
+ const successfulTokenAction = event.actions.find(generateTokenAction => generateTokenAction.actionStatus.alternateName === 'CompletedActionStatus');
167
+ if (successfulTokenAction == null) {
168
+ throw new DataError('E_NO_TOKENS', 'The specified event does not have a completed token generation action.');
169
+ }
170
+ // get tokenInfo for this event
171
+ const tokenInfo = await this.getTokenStatistics();
172
+ // validate sent-used separately for descriptive errors
173
+ if (tokenInfo.sent) {
174
+ 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})`);
175
+ }
176
+ if (tokenInfo.used) {
177
+ 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})`);
178
+ }
179
+ // start gathering students
180
+ let students;
181
+ const courseClass = event.courseClassInstructor && event.courseClassInstructor.courseClass;
182
+ const eventInstructor = event.courseClassInstructor && event.courseClassInstructor.instructor;
183
+ // get class sections
184
+ const sections = await context.model('CourseClassSection').where('courseClass').equal(courseClass.id).getAllItems();
185
+ // check if course class has sections
186
+ if (sections && sections.length > 0 && courseClass.mustRegisterSection !== 0) {
187
+ // get only number of students registered at specific section
188
+ const instructorSections = await context.model('CourseClassSectionInstructor').where('courseClass').equal(courseClass.id)
189
+ .and('instructor').equal(eventInstructor).select('section/section as sectionId').silent().getAllItems();
190
+ if (instructorSections && instructorSections.length === 0) {
191
+ throw new DataError('E_INVALID_SECTION', 'Instructor is not related with any of sections');
147
192
  }
148
- })
149
- .getItem();
150
- // validate event
151
- if (event == null) {
152
- throw new DataNotFoundError('The event cannot be found or is inaccessible.');
153
- }
154
- // validate status
155
- if (!(event.eventStatus && event.eventStatus.alternateName === 'EventOpened')) {
156
- throw new DataError('Send tokens action may only be executed for Open/Active events.');
157
- }
158
- // validate event actions
159
- if (!(event.actions && event.actions.length)) {
160
- throw new DataNotFoundError('There are not generate token actions for the specified event or they are inaccessible.');
161
- }
162
- // find completed token generation action (can only be one)
163
- const successfulTokenAction = event.actions.find(generateTokenAction => generateTokenAction.actionStatus.alternateName === 'CompletedActionStatus');
164
- if (successfulTokenAction == null) {
165
- throw new DataError('The specified event does not have a completed token generation action.');
166
- }
167
- // get tokenInfo for this event
168
- const tokenInfo = await this.getTokenStatistics();
169
- // validate sent-used seperately for descriptive errors
170
- if (tokenInfo.sent) {
171
- throw new DataError(`Cannot proceed with sending tokens, because ${tokenInfo.sent} of them is/are already sent.`);
172
- }
173
- if (tokenInfo.used) {
174
- throw new DataError(`Cannot proceed with sending tokens, because ${tokenInfo.used} of them is/are already used.`);
175
- }
176
- // start gathering students
177
- let students;
178
- const courseClass = event.courseClassInstructor && event.courseClassInstructor.courseClass;
179
- const eventInstructor = event.courseClassInstructor && event.courseClassInstructor.instructor;
180
- // get class sections
181
- const sections = await context.model('CourseClassSection').where('courseClass').equal(courseClass.id).getItems();
182
- // check if course class has sections
183
- if (sections && sections.length > 0 && courseClass.mustRegisterSection !== 0) {
184
- // get only number of students registered at specific section
185
- const instructorSections = await context.model('CourseClassSectionInstructor').where('courseClass').equal(courseClass.id)
186
- .and('instructor').equal(eventInstructor).select('section/section as sectionId').silent().getItems();
187
- if (instructorSections && instructorSections.length === 0) {
188
- throw new DataError('Instructor is not related with any of sections');
189
- }
190
- const sectionIds = instructorSections.map(section => {
191
- return section.sectionId;
193
+ const sectionIds = instructorSections.map(section => {
194
+ return section.sectionId;
195
+ });
196
+ // get students for specific course class sections
197
+ students = await context.model('StudentCourseClass')
198
+ .where('courseClass').equal(courseClass.id)
199
+ .and('section').in(sectionIds)
200
+ .select('email')
201
+ .silent()
202
+ .getAllItems();
203
+ } else {
204
+ students = await context.model('StudentCourseClass')
205
+ .where('courseClass').equal(courseClass.id)
206
+ .select('email', 'student')
207
+ .silent()
208
+ .getAllItems();
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 class 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
+ // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
221
+ 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])?)*$/;
222
+ const invalidEmail = students.find(student => {
223
+ return !(student.email && mailRegex.test(student.email));
192
224
  });
193
- // get students for specific course class sections
194
- students = await context.model('StudentCourseClass')
195
- .where('courseClass').equal(courseClass.id)
196
- .and('section').in(sectionIds)
197
- .select('email')
225
+ if (invalidEmail) {
226
+ throw new DataError('E_INVALID_EMAIL', `${context.__('At least one student\'s email is null or invalid')} (email:${invalidEmail.email || ' '} ${context.__('Student')}:${invalidEmail.student})`);
227
+ }
228
+ // get tokens
229
+ let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
230
+ .select('access_token')
198
231
  .silent()
199
232
  .getAllItems();
200
- } else {
201
- students = await context.model('StudentCourseClass')
202
- .where('courseClass').equal(courseClass.id)
203
- .select('email')
233
+ // and map them to an array
234
+ tokens = tokens.map(token => token.access_token);
235
+ // get mail template
236
+ const mailTemplate = await context.model('MailConfiguration')
237
+ .where('target').equal('SendInstructorTokenAction')
204
238
  .silent()
205
- .getAllItems();
206
- }
207
- if (!(Array.isArray(students) && students.length)) {
208
- throw new DataError('No recipients/students found.');
209
- }
210
- // check total of students
211
- if (students.length !== tokenInfo.total) {
212
- throw new DataError(`Cannot proceed to sending tokens. Students are ${students.length} and generated tokens are ${tokenInfo.total}.`);
213
- }
214
- // validate student emails, must all exist and have a valid format
215
- // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
216
- 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])?)*$/;
217
- const invalidEmail = students.find(student => {
218
- return !(student.email && mailRegex.test(student.email));
219
- });
220
- if (invalidEmail) {
221
- throw new DataError(`Cannot procced to sending tokens because at least one student's email is null or invalid. Found invalid email: ${invalidEmail.email || 'empty'}`);
222
- }
223
- // get tokens
224
- let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
225
- .select('access_token')
226
- .silent()
227
- .getAllItems();
228
- // and map them to an array
229
- tokens = tokens.map(token => token.access_token);
230
- // get mail template
231
- const mailTemplate = await context.model('MailConfiguration')
232
- .where('target').equal('SendInstructorTokenAction')
233
- .silent()
234
- .getItem();
235
- if (mailTemplate == null) {
236
- throw new DataError('Cannot execute send tokens action because template is missing for SendInstructorTokenAction.');
237
- }
238
- const succeeded = [];
239
- const failed = [];
240
- try {
239
+ .getItem();
240
+ if (mailTemplate == null) {
241
+ throw new DataError('E_MISSING_TEMPLATE', 'Cannot execute send tokens action because template is missing for SendInstructorTokenAction.');
242
+ }
243
+ // check if there is already an active sendTokensAction
244
+ const alreadySendingTokens = await context.model('SendInstructorTokenAction')
245
+ .where('event').equal(event.id)
246
+ .and('actionStatus/alternateName').equal('ActiveActionStatus')
247
+ .silent().count();
248
+ if (alreadySendingTokens) {
249
+ throw new DataError('E_ALREADY_SENDING', `${context.__('The bulk sending process of tokens is already in progress')}`);
250
+ }
251
+ // save SendInstructorTokenAction
252
+ const sendTokenAction = {
253
+ event: this.getId(),
254
+ numberOfStudents: students.length,
255
+ total: tokenInfo.total,
256
+ sent: 0,
257
+ failed: 0,
258
+ actionStatus: {
259
+ alternateName: 'ActiveActionStatus'
260
+ }
261
+ }
262
+ sendAction = await context.model('SendInstructorTokenAction').silent().save(sendTokenAction);
241
263
  // format mail subject expected params ${course}, ${instructor}
242
- const exp = new RegExp('\\$\\{\\w+\\}+','ig');
243
- let subject = mailTemplate.subject;
264
+ const exp = new RegExp('\\$\\{\\w+\\}+', 'ig');
265
+ subject = mailTemplate.subject;
244
266
  const params = subject.match(exp);
245
- if (params.length>0) {
267
+ if (params.length > 0) {
246
268
  // parse only custom parameters ${instructor},${course}
247
269
  params.forEach(param => {
248
270
  if (param === '${instructor}') {
249
271
  // get instructor full name
250
- subject = subject.replace(param, eventInstructor? `${eventInstructor.familyName} ${eventInstructor.givenName}` : '');
272
+ subject = subject.replace(param, eventInstructor ? `${eventInstructor.familyName} ${eventInstructor.givenName}` : '');
251
273
  } else if (param === '${course}') {
252
274
  // get courseClass code and title
253
275
  subject = subject.replace(param, courseClass.course ? `${courseClass.course.displayCode} ${courseClass.title}` : '');
@@ -256,83 +278,40 @@ class ClassInstructorEvaluationEvent extends EvaluationEvent {
256
278
  }
257
279
  });
258
280
  }
259
- // use an async function to send emails
260
- await (async () => {
261
- for (const student of students) {
262
- // refresh mailer
263
- const mailer = getMailer(context); // maybe investigate why this has to be refreshed.
264
- // pop an access token
265
- const access_token = tokens.pop();
266
- // send message
267
- await new Promise(resolve => {
268
- mailer
269
- .template(mailTemplate.template)
270
- .subject(subject)
271
- .to(student.email)
272
- .send(Object.assign(event, {
273
- access_token
274
- }), (err) => {
275
- if (err) {
276
- try {
277
- TraceUtils.error(`SendEvaluationTokensAction', 'An error occurred while trying to send token to student email ${student.email}`);
278
- TraceUtils.error(err);
279
- } catch (err1) {
280
- // do nothing
281
- }
282
- failed.push(access_token);
283
- return resolve();
284
- }
285
- succeeded.push(access_token);
286
- return resolve();
287
- });
288
- });
289
- }
290
- })();
291
- // update successfully sent tokens
292
- for (const succededToken of succeeded) {
293
- await context.model('EvaluationAccessToken').silent().save({
294
- access_token: succededToken, // access_token is primary
295
- sent: true,
296
- $state: 2
297
- });
298
- }
299
- // create send tokens action
300
- const sendTokensAction = {
301
- event: this.getId(),
302
- numberOfStudents: students.length,
303
- total: tokenInfo.total,
304
- sent: succeeded.length,
305
- failed: failed.length,
306
- actionStatus: {
307
- alternateName: 'CompletedActionStatus'
308
- }
309
- }
310
- // and save
311
- return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
281
+ EvaluationEvent.sendMessages(context, students, tokens, tokenInfo, mailTemplate, subject, sendAction, event);
312
282
  } catch (err) {
313
- // log error
314
283
  TraceUtils.error(err);
315
- // update successfully sent tokens
316
- for (const succededToken of succeeded) {
317
- await context.model('EvaluationAccessToken').silent().save({
318
- access_token: succededToken, // access_token is primary
319
- sent: true,
320
- $state: 2
321
- });
322
- }
323
284
  // create send tokens action
324
- const sendTokensAction = {
285
+ const sendTokenAction = {
325
286
  event: this.getId(),
326
- numberOfStudents: students.length,
327
- total: tokenInfo.total,
328
- sent: succeeded.length,
329
- failed: succeeded.length ? tokenInfo.total - succeeded.length : tokenInfo.total,
287
+ numberOfStudents: 0,
288
+ total: 0,
289
+ sent: 0,
290
+ failed: 0,
330
291
  actionStatus: {
331
- alternateName: 'CompletedActionStatus'
332
- }
292
+ alternateName: 'FailedActionStatus'
293
+ },
294
+ description: err.message
333
295
  }
334
296
  // and save
335
- return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
297
+ if (sendAction && sendAction.id) {
298
+ sendTokenAction.id = sendAction.id;
299
+ }
300
+ if(!subject) {
301
+ // load courseClass
302
+ const item = await context.model('ClassInstructorEvaluationEvent').where('id').equal(this.getId())
303
+ .expand({
304
+ name: 'courseClassInstructor',
305
+ options: {
306
+ '$expand': 'courseClass($expand=course)'
307
+ }
308
+ })
309
+ .getItem();
310
+ const courseClass =item && item.courseClassInstructor && item.courseClassInstructor.courseClass
311
+ subject =courseClass? `${courseClass.course.displayCode} ${courseClass.title}`: '';
312
+ }
313
+ EvaluationEvent.sendSse(context.user,context, this.getId(), subject, err);
314
+ return await context.model('SendInstructorTokenAction').silent().save(sendTokenAction);
336
315
  }
337
316
  }
338
317
  }