@universis/evaluations 1.0.25 → 1.0.27

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.
Files changed (32) hide show
  1. package/dist/config/models/ClassInstructorEvaluationEvent.json +1 -1
  2. package/dist/config/models/CourseClassEvaluationEvent.json +89 -4
  3. package/dist/config/models/EvaluationAccessToken.json +19 -1
  4. package/dist/config/models/EvaluationDocument.json +17 -1
  5. package/dist/config/models/EvaluationEvent.json +13 -0
  6. package/dist/config/models/GenerateCourseClassTokenAction.json +57 -0
  7. package/dist/config/models/SendCourseClassTokenAction.json +52 -0
  8. package/dist/listeners/access-token-listener.js +76 -0
  9. package/dist/listeners/access-token-listener.js.map +1 -0
  10. package/dist/listeners/class-event-listener.js +184 -0
  11. package/dist/listeners/class-event-listener.js.map +1 -0
  12. package/dist/locales/el.json +3 -1
  13. package/dist/models/class-instructor-evaluation-event-model.js +1 -5
  14. package/dist/models/class-instructor-evaluation-event-model.js.map +1 -1
  15. package/dist/models/course-class-evaluation-event-model.js +340 -0
  16. package/dist/models/course-class-evaluation-event-model.js.map +1 -0
  17. package/dist/models/evaluation-event-model.js +200 -12
  18. package/dist/models/evaluation-event-model.js.map +1 -1
  19. package/package.json +1 -1
  20. package/src/config/models/ClassInstructorEvaluationEvent.json +1 -1
  21. package/src/config/models/CourseClassEvaluationEvent.json +89 -4
  22. package/src/config/models/EvaluationAccessToken.json +19 -1
  23. package/src/config/models/EvaluationDocument.json +17 -1
  24. package/src/config/models/EvaluationEvent.json +13 -0
  25. package/src/config/models/GenerateCourseClassTokenAction.json +57 -0
  26. package/src/config/models/SendCourseClassTokenAction.json +52 -0
  27. package/src/listeners/access-token-listener.js +75 -0
  28. package/src/listeners/class-event-listener.js +183 -0
  29. package/src/locales/el.json +3 -1
  30. package/src/models/class-instructor-evaluation-event-model.js +1 -5
  31. package/src/models/course-class-evaluation-event-model.js +339 -0
  32. package/src/models/evaluation-event-model.js +204 -16
@@ -0,0 +1,339 @@
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
+ /**
7
+ * @class
8
+ */
9
+ @EdmMapping.entityType('CourseClassEvaluationEvent')
10
+ class CourseClassEvaluationEvent extends EvaluationEvent {
11
+ /**
12
+ * @constructor
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ @EdmMapping.func('Results', EdmType.CollectionOf('Object'))
19
+ async getResults() {
20
+ // check access to ClassInstructorEvaluationEvent and get results silently
21
+ const event = await this.context.model('CourseClassEvaluationEvent').where('id').equal(this.getId());
22
+ if (event) {
23
+ const form = await this.getForm();
24
+ return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).silent().prepare();
25
+ }
26
+ }
27
+ @EdmMapping.action('GenerateEvaluationTokens', 'GenerateCourseClassTokenAction')
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 courseClass event
37
+ const event = await context.model('CourseClassEvaluationEvent').where('id').equal(this.id)
38
+ .expand('courseClass')
39
+ .getItem();
40
+ if (event) {
41
+ //check if a GenerateCourseClassTokenAction exists
42
+ const prevAction = await context.model('GenerateCourseClassTokenAction').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 courseClass = event.courseClass;
49
+ action.numberOfStudents = await context.model('StudentCourseClass')
50
+ .where('courseClass').equal(courseClass.id).silent().count();
51
+
52
+ // save action and then generateTokens
53
+ const generateAction = await context.model('GenerateCourseClassTokenAction').save(action);
54
+ const generateOptions =
55
+ {
56
+ evaluationEvent: event.id,
57
+ n: action.numberOfStudents,
58
+ expires: event.endDate
59
+ };
60
+ try {
61
+ // save number of students to event
62
+ event.numberOfStudents = action.numberOfStudents;
63
+ await context.model('CourseClassEvaluationEvent').save(event);
64
+ if (event.numberOfStudents > 0) {
65
+ const studentMetadata = context.getConfiguration().getSourceAt('settings/evaluation/useStudentInfoAtMetadata') || false;
66
+ await EvaluationEvent.generateTokens(context, generateOptions);
67
+ // get all generated tokens and generate tokens for child events
68
+ const tokens = await context.model('EvaluationAccessToken')
69
+ .where('evaluationEvent').equal(event.id).silent().getAllItems();
70
+ const students = await this.getStudentEvaluationEvents(context, event, courseClass);
71
+ for (const student of students) {
72
+ const access_token = tokens.pop();
73
+ // student.id
74
+ const metadata = {
75
+ id: studentMetadata ? student.id: null,
76
+ student: studentMetadata ? student.student : null,
77
+ semester: student.semester,
78
+ registrationType: student.registrationType
79
+ };
80
+ for (let i = 0; i < student.events.length; i++) {
81
+ const studentEvent = student.events[i];
82
+ if (event.id === studentEvent.id) {
83
+ await context.model('EvaluationAccessToken').silent().save({
84
+ access_token: access_token.access_token,
85
+ metadata
86
+ });
87
+ } else {
88
+ await context.model('EvaluationAccessToken').silent().save({
89
+ evaluationEvent: studentEvent,
90
+ expires: generateOptions.expires,
91
+ parentToken: access_token,
92
+ metadata
93
+ });
94
+ }
95
+ }
96
+ }
97
+ }
98
+ generateAction.total = action.numberOfStudents;
99
+ generateAction.actionStatus = {alternateName: 'CompletedActionStatus'}
100
+ return await context.model('GenerateCourseClassTokenAction').save(generateAction);
101
+ }
102
+ catch (err) {
103
+ TraceUtils.error(err);
104
+ // update also action status
105
+ generateAction.total = 0;
106
+ generateAction.actionStatus = {alternateName: 'FailedActionStatus'}
107
+ generateAction.description = err.message;
108
+ return await context.model('GenerateCourseClassTokenAction').save(generateAction);
109
+
110
+ }
111
+ }
112
+ }
113
+ @EdmMapping.func('TokenInfo', EdmType.CollectionOf('Object'))
114
+ async getTokenStatistics() {
115
+ const tokenInfo = {
116
+ total: 0,
117
+ used: 0,
118
+ sent: 0
119
+ };
120
+ // get number of tokens
121
+ const tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
122
+ .select('count(evaluationEvent) as total', 'used', 'sent')
123
+ .groupBy('used', 'sent', 'evaluationEvent')
124
+ .silent().getItems();
125
+ tokens.map(item => {
126
+ tokenInfo.total += item.total;
127
+ tokenInfo.used += item.used ? item.total : 0;
128
+ tokenInfo.sent += item.sent ? item.total : 0;
129
+ });
130
+ return tokenInfo;
131
+ }
132
+
133
+ @EdmMapping.action('SendEvaluationTokens', 'SendCourseClassTokenAction')
134
+ async sendEvaluationTokens() {
135
+
136
+ const context = this.context;
137
+ let sendAction = {};
138
+ let subject;
139
+ // get event and check if event endDate has passed
140
+ try {
141
+ // get current date
142
+ const currentDate = moment(new Date()).startOf('day').toDate(); // get only date format
143
+ const event = await context.model('CourseClassEvaluationEvent').where('id').equal(this.getId())
144
+ .and('date(endDate)').greaterOrEqual(currentDate)
145
+ .expand({
146
+ name: 'courseClass',
147
+ options: {
148
+ '$expand': 'course'
149
+ }
150
+ },
151
+ {
152
+ name: 'actions',
153
+ options: {
154
+ '$expand': 'actionStatus'
155
+ }
156
+ }
157
+ )
158
+ .getItem();
159
+ // validate event
160
+ if (event == null) {
161
+ throw new DataNotFoundError('The event cannot be found or is inaccessible.');
162
+ }
163
+ // validate status
164
+ if (!(event.eventStatus && event.eventStatus.alternateName === 'EventOpened')) {
165
+ throw new DataError('E_INVALID_PERIOD', context.__('Send tokens action may only be executed for Open/Active events'));
166
+ }
167
+ // validate event actions
168
+ if (!(event.actions && event.actions.length)) {
169
+ throw new DataNotFoundError('E_NO_TOKENS', context.__('Token actions were not found for the specified event or they are inaccessible.'));
170
+ }
171
+ // find completed token generation action (can only be one)
172
+ const successfulTokenAction = event.actions.find(generateTokenAction => generateTokenAction.actionStatus.alternateName === 'CompletedActionStatus');
173
+ if (successfulTokenAction == null) {
174
+ throw new DataError('E_NO_TOKENS', 'The specified event does not have a completed token generation action.');
175
+ }
176
+ // get tokenInfo for this event
177
+ const tokenInfo = await this.getTokenStatistics();
178
+ // validate sent-used separately for descriptive errors
179
+ if (tokenInfo.sent) {
180
+ 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})`);
181
+ }
182
+ if (tokenInfo.used) {
183
+ 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})`);
184
+ }
185
+ // start gathering students
186
+ const courseClass = event.courseClass;
187
+ const students = await this.getStudentEvaluationEvents(context,event,courseClass);
188
+
189
+ if (!(Array.isArray(students) && students.length)) {
190
+ throw new DataError('E_STUDENTS_FOUND', 'No recipients/students found.');
191
+ }
192
+ // check total of students
193
+ if (students.length !== tokenInfo.total) {
194
+ throw new DataError('E_TOTAL_STUDENTS',
195
+ `${this.context.__("The number of students in the class differs from the generated tokens")}` +
196
+ `(${this.context.__("Students")}: ${students.length}, ${this.context.__("Number of tokens")}:${tokenInfo.total}.`);
197
+ }
198
+ // validate student emails, must all exist and have a valid format
199
+ // https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
200
+ 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])?)*$/;
201
+ const invalidEmail = students.find(student => {
202
+ return !(student.email && mailRegex.test(student.email));
203
+ });
204
+ if (invalidEmail) {
205
+ throw new DataError('E_INVALID_EMAIL', `${context.__('At least one student\'s email is null or invalid')} (email:${invalidEmail.email || ' '} ${context.__('Student')}:${invalidEmail.student})`);
206
+ }
207
+ // get tokens
208
+ let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId())
209
+ .silent()
210
+ .getAllItems();
211
+
212
+ // get mail template
213
+ const mailTemplate = await context.model('MailConfiguration')
214
+ .where('target').equal('SendCourseClassTokenAction')
215
+ .silent()
216
+ .getItem();
217
+ if (mailTemplate == null) {
218
+ throw new DataError('E_MISSING_TEMPLATE', 'Cannot execute send tokens action because template is missing for SendCourseClassTokenAction.');
219
+ }
220
+ // check if there is already an active sendTokensAction
221
+ const alreadySendingTokens = await context.model('SendCourseClassTokenAction')
222
+ .where('event').equal(event.id)
223
+ .and('actionStatus/alternateName').equal('ActiveActionStatus')
224
+ .silent().count();
225
+ if (alreadySendingTokens) {
226
+ throw new DataError('E_ALREADY_SENDING', `${context.__('The bulk sending process of tokens is already in progress')}`);
227
+ }
228
+ // save SendInstructorTokenAction
229
+ const sendTokenAction = {
230
+ event: this.getId(),
231
+ numberOfStudents: students.length,
232
+ total: tokenInfo.total,
233
+ sent: 0,
234
+ failed: 0,
235
+ actionStatus: {
236
+ alternateName: 'ActiveActionStatus'
237
+ }
238
+ }
239
+ sendAction = await context.model('SendCourseClassTokenAction').silent().save(sendTokenAction);
240
+ // format mail subject expected params ${course}
241
+ const exp = new RegExp('\\$\\{\\w+\\}+', 'ig');
242
+ subject = mailTemplate.subject;
243
+ const params = subject.match(exp);
244
+ if (params.length > 0) {
245
+ // parse only custom parameters ${instructor},${course}
246
+ params.forEach(param => {
247
+ if (param === '${course}') {
248
+ // get courseClass code and title
249
+ subject = subject.replace(param, courseClass.course ? `${courseClass.course.displayCode} ${courseClass.title}` : '');
250
+ } else {
251
+ subject = subject.replace(param, '');
252
+ }
253
+ });
254
+ }
255
+ EvaluationEvent.sendMessages(context, students, tokens, tokenInfo, mailTemplate, subject, sendAction, event);
256
+ } catch (err) {
257
+ TraceUtils.error(err);
258
+ // create send tokens action
259
+ const sendTokenAction = {
260
+ event: this.getId(),
261
+ numberOfStudents: 0,
262
+ total: 0,
263
+ sent: 0,
264
+ failed: 0,
265
+ actionStatus: {
266
+ alternateName: 'FailedActionStatus'
267
+ },
268
+ description: err.message
269
+ }
270
+ // and save
271
+ if (sendAction && sendAction.id) {
272
+ sendTokenAction.id = sendAction.id;
273
+ }
274
+ if(!subject) {
275
+ // load courseClass
276
+ const item = await context.model('CourseClassEvaluationEvent').where('id').equal(this.getId())
277
+ .expand({
278
+ name: 'courseClass',
279
+ options: {
280
+ '$expand': 'course'
281
+ }
282
+ })
283
+ .getItem();
284
+ const courseClass =item && item.courseClass
285
+ subject =courseClass? `${courseClass.course.displayCode} ${courseClass.title}`: '';
286
+ }
287
+ EvaluationEvent.sendSse(context.user,context, this.getId(), subject, err);
288
+ return await context.model('SendCourseClassTokenAction').silent().save(sendTokenAction);
289
+ }
290
+ }
291
+
292
+ async getStudentEvaluationEvents(context, event, courseClass) {
293
+ // get child events (classInstructorEvaluationEvents)
294
+ const classInstructorEvaluationEvents = await context.model('ClassInstructorEvaluationEvents')
295
+ .where('superEvent')
296
+ .equal(event.id)
297
+ .expand({
298
+ name: 'courseClassInstructor',
299
+ options: {
300
+ '$expand': 'courseClass($expand=sections)'
301
+ }
302
+ })
303
+ .getAllItems();
304
+
305
+ // get course class sections' instructors
306
+ const instructorSections = await context.model('CourseClassSectionInstructor').where('courseClass').equal(courseClass.id)
307
+ .select('section/section as section', 'instructor').flatten().silent().getAllItems();
308
+ const students = await context.model('StudentCourseClass').where('courseClass')
309
+ .equal(courseClass.id).getAllItems();
310
+ for (const student of students) {
311
+ student.events = [];
312
+ student.events.push(event);
313
+ if (classInstructorEvaluationEvents && classInstructorEvaluationEvents.length > 0) {
314
+ let instructorEvents = [];
315
+ if (instructorSections && instructorSections.length && LangUtils.parseInt(courseClass.mustRegisterSection)===1) {
316
+ instructorEvents = classInstructorEvaluationEvents.filter(x => {
317
+ return x.courseClassInstructor && instructorSections.filter(x => {
318
+ return student.section === x.section
319
+ }).map(x => {
320
+ return x.instructor;
321
+ }).includes(x.courseClassInstructor.instructor)
322
+ });
323
+ }
324
+ if (instructorEvents && instructorEvents.length) {
325
+ instructorEvents.forEach(x => {
326
+ student.events.push(x);
327
+ })
328
+ }
329
+ else {
330
+ student.events.push.apply(student.events, classInstructorEvaluationEvents);
331
+ }
332
+ }
333
+ }
334
+ return students;
335
+ }
336
+
337
+
338
+ }
339
+ module.exports = CourseClassEvaluationEvent;
@@ -54,7 +54,7 @@ class EvaluationEvent extends DataObject {
54
54
  // get current date
55
55
  let evaluationEvent = await context.model('EvaluationEvent')
56
56
  .where('id').equal(token.sub)
57
- .expand('eventStatus')
57
+ .expand('eventStatus','subEvents')
58
58
  .silent().getTypedItem();
59
59
  if (evaluationEvent == null) {
60
60
  throw new HttpNotFoundError('The specified evaluation cannot be found');
@@ -75,8 +75,10 @@ class EvaluationEvent extends DataObject {
75
75
  if (currentDate > endDate) {
76
76
  throw new DataError('E_EXPIRED',context.__('Evaluation period for this course has been expired'));
77
77
  }
78
- if (evaluationEvent.additionalType !== 'EvaluationEvent') {
79
- if (evaluationEvent.additionalType === 'ClassInstructorEvaluationEvent') {
78
+ let courseClass;
79
+ let courseClassTitle;
80
+ switch (evaluationEvent.additionalType) {
81
+ case 'ClassInstructorEvaluationEvent':
80
82
  const event = await context.model('ClassInstructorEvaluationEvent')
81
83
  .where('id').equal(token.sub)
82
84
  .expand({
@@ -86,15 +88,56 @@ class EvaluationEvent extends DataObject {
86
88
  }
87
89
  })
88
90
  .silent().getTypedItem();
89
- const courseClass= event.courseClassInstructor.courseClass;
91
+ courseClass = event.courseClassInstructor.courseClass;
90
92
  const instructor = event.courseClassInstructor.instructor;
91
- const courseClassTitle = courseClass.locale && courseClass.locale.title || courseClass.title;
93
+ courseClassTitle = courseClass.locale && courseClass.locale.title || courseClass.title;
92
94
  evaluationEvent.courseClass = `${courseClass.course.displayCode}-${courseClassTitle} (${courseClass.year.alternateName}-${courseClass.period.name}) `;
93
95
  evaluationEvent.instructor = `${instructor.familyName} ${instructor.givenName}`;
94
- } else {
96
+ break;
97
+ case 'CourseClassEvaluationEvent':
98
+ const courseEvent = await context.model('CourseClassEvaluationEvent')
99
+ .where('id').equal(token.sub)
100
+ .expand({
101
+ name: 'courseClass',
102
+ options: {
103
+ $expand: 'course,year,period,locale,instructors($expand=instructor)'
104
+ }
105
+ })
106
+ .silent().getTypedItem();
107
+ courseClass = courseEvent.courseClass;
108
+ courseClassTitle = courseClass.locale && courseClass.locale.title || courseClass.title;
109
+ evaluationEvent.courseClass = `${courseClass.course.displayCode}-${courseClassTitle} (${courseClass.year.alternateName}-${courseClass.period.name}) `;
110
+ // check if child evaluation tokens
111
+ const instructorTokens = await context.model('EvaluationAccessToken').where('parentToken')
112
+ .equal(token.access_token).silent().getAllItems();
113
+
114
+ if (instructorTokens && instructorTokens.length>0) {
115
+ evaluationEvent.subEvents = [];
116
+ for (let i = 0; i < instructorTokens.length; i++) {
117
+ const instructorToken = await EvaluationAccessToken.inspect(context, instructorTokens[i].access_token);
118
+ if (instructorToken.active) {
119
+ // load evaluation event for getting instructor name
120
+ const subEvent = await context.model('ClassInstructorEvaluationEvent')
121
+ .where('id').equal(instructorTokens[i].evaluationEvent)
122
+ .and('superEvent').equal(evaluationEvent.id)
123
+ .and('eventStatus/alternateName').equal('EventOpened')
124
+ .select('id', 'courseClassInstructor/instructor/familyName as familyName',
125
+ 'courseClassInstructor/instructor/givenName as givenName')
126
+ .silent().getItem();
127
+ if (subEvent) {
128
+ subEvent.instructor = `${subEvent.familyName} ${subEvent.givenName}`;
129
+ subEvent.access_token = instructorTokens[i].access_token;
130
+ evaluationEvent.subEvents.push(subEvent);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ break;
136
+ case 'default':
95
137
  evaluationEvent = await evaluationEvent.silent().getAdditionalObject();
96
- }
138
+ break;
97
139
  }
140
+
98
141
  return evaluationEvent;
99
142
  }
100
143
 
@@ -194,6 +237,62 @@ class EvaluationEvent extends DataObject {
194
237
  form.version= model.version;
195
238
  await this.context.model('EvaluationDocument').silent().save(form);
196
239
  }
240
+ // check if event has sub events and append form to result
241
+ if (this.subEvents && this.subEvents.length) {
242
+ // get first subEvent for
243
+ const subEvent = this.context.model('EvaluationEvent').convert(this.subEvents[0]);
244
+ const subResult = await subEvent.getForm();
245
+ // add select boxes for each instructor
246
+ if (this.subEvents.length>1) {
247
+ const label = this.context.__('Select at least one instructor to evaluate')
248
+ const selectInstructorsComponent =
249
+ {
250
+ "label": label,
251
+ "optionsLabelPosition": "right",
252
+ "tableView": false,
253
+ "key": "instructors",
254
+ "type": "selectboxes",
255
+ "input": true,
256
+ "inputType": "checkbox",
257
+ "validate": {
258
+ "required": true,
259
+ }
260
+ };
261
+ this.subEvents.sort((a, b) => (a.instructor < b.instructor) ? -1 : 1);
262
+ selectInstructorsComponent.values = this.subEvents
263
+ .map(x => {
264
+ x.label = x.instructor;
265
+ x.value= x.id ;
266
+ return x;
267
+ });
268
+
269
+ result.components.push(selectInstructorsComponent);
270
+ const headerComponent = subResult.components[0];
271
+ headerComponent.customConditional = "show =(data && data.instructors[row.id])";
272
+ headerComponent.refreshOn= "instructors";
273
+ }
274
+ // create panel
275
+ const repeaterComponent =
276
+ {
277
+ "label": " ",
278
+ "disableAddingRemovingRows": true,
279
+ "reorder": false,
280
+ "customClass": "border-0",
281
+ "addAnotherPosition": "bottom",
282
+ "layoutFixed": false,
283
+ "enableRowGroups": false,
284
+ "initEmpty": false,
285
+ "hideLabel": true,
286
+ "tableView": false,
287
+ "key": "subEvents",
288
+ "type": "datagrid",
289
+ "input": true,
290
+ "components": []
291
+ };
292
+
293
+ repeaterComponent.components.push.apply(repeaterComponent.components, subResult.components);
294
+ result.components.push(repeaterComponent);
295
+ }
197
296
  return result;
198
297
  } catch (err) {
199
298
  TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);
@@ -264,9 +363,9 @@ class EvaluationEvent extends DataObject {
264
363
  results.event.tokensUsed = usedTokens ? usedTokens.total : 0;
265
364
  }
266
365
  // get avg of questions avg
267
- results.event.responsesAvg = results.responses.length ? math.mean(results.responses.filter(x => !!x.isNumber).map(x => {
268
- return x.avg;
269
- })) : 0;
366
+ const avg = this.getAvgValues(context, results);
367
+ results.event.responsesAvg = avg.responsesAvg;
368
+ results.event.questionsAvg = avg.questionsAvg;
270
369
  return results;
271
370
  }
272
371
 
@@ -381,6 +480,11 @@ class EvaluationEvent extends DataObject {
381
480
  radioValue.total += result;
382
481
  totalResponses += result;
383
482
  });
483
+ qElement.responses = responses.map(x => {
484
+ if ((x[qElement.name]>0 && ignoreZeroValues) || !ignoreZeroValues) {
485
+ return x[qElement.name];
486
+ }
487
+ });
384
488
  } else {
385
489
  qElement.responses = responses.map(x => {
386
490
  return x[qElement.name];
@@ -488,15 +592,36 @@ class EvaluationEvent extends DataObject {
488
592
  await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {
489
593
  const context = event.model.context;
490
594
  context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken)
491
- .silent().getItem().then((token) => {
595
+ .silent().getItem().then(async (token) => {
492
596
  if (token == null) {
493
597
  throw new HttpTokenExpiredError('Evaluation token is required');
494
598
  }
599
+ // check if subEvents have been evaluated
600
+ const subEvents = event.target.subEvents;
601
+ if (subEvents && subEvents.length) {
602
+ // evaluate each sub event
603
+ for (let i = 0; i < subEvents.length; i++) {
604
+ context.user.authenticationToken = subEvents[i].access_token;
605
+ const subEvent = context.model('EvaluationEvent').convert(subEvents[i].id);
606
+ delete subEvents[i].id;
607
+ if (subEvents.length>1 && event.target.instructors) {
608
+ // check if instructor has been evaluated
609
+ if (event.target.instructors[subEvent.id] === true) {
610
+ await subEvent.evaluate(subEvents[i]);
611
+ }
612
+ }
613
+ else {
614
+ await subEvent.evaluate(subEvents[i]);
615
+ }
616
+ }
617
+
618
+ }
495
619
  return context.model(EvaluationAccessToken).silent().save({
496
620
  access_token: token.access_token,
497
621
  expires: new Date(0), // set epoch date
498
622
  used: true
499
623
  });
624
+
500
625
  }).then(() => {
501
626
  return callback();
502
627
  }).catch((err) => {
@@ -577,7 +702,32 @@ class EvaluationEvent extends DataObject {
577
702
  // refresh mailer
578
703
  const mailer = getMailer(context); // maybe investigate why this has to be refreshed.
579
704
  // pop an access token
580
- const access_token = tokens.pop();
705
+ let access_token;
706
+ const studentMetadata = context.getConfiguration().getSourceAt('settings/evaluation/useStudentInfoAtMetadata') || false;
707
+ // student metadata contains student identifiers only if setting useStudentInfoAtMetadata is true
708
+ // otherwise only semester and registrationType are stored
709
+ const metadata = {
710
+ id: studentMetadata ? student.id: null,
711
+ student: studentMetadata ? student.student : null,
712
+ semester: student.semester,
713
+ registrationType: student.registrationType
714
+ };
715
+ if (studentMetadata) {
716
+ // try to find access token for specific student
717
+ access_token = tokens.find(x=>{
718
+ return x.metadata && x.metadata.student === student.id;
719
+ });
720
+ }
721
+ if (!access_token) {
722
+ access_token = tokens.pop();
723
+ // update metadata
724
+ }
725
+ else {
726
+ //
727
+ TraceUtils.log('test')
728
+ }
729
+ access_token.metadata = metadata;
730
+
581
731
  // send message
582
732
  await new Promise(resolve => {
583
733
  mailer.transporter(transporter)
@@ -585,7 +735,7 @@ class EvaluationEvent extends DataObject {
585
735
  .subject(subject)
586
736
  .to(student.email)
587
737
  .send(Object.assign(evaluationEvent, {
588
- access_token
738
+ access_token: access_token.access_token
589
739
  }), (err) => {
590
740
  if (err) {
591
741
  try {
@@ -600,8 +750,9 @@ class EvaluationEvent extends DataObject {
600
750
  succeeded.push(access_token);
601
751
  // update successfully sent token
602
752
  return context.model('EvaluationAccessToken').silent().save({
603
- access_token: access_token, // access_token is primary
753
+ access_token: access_token.access_token, // access_token is primary
604
754
  sent: true,
755
+ metadata:access_token.metadata,
605
756
  $state: 2
606
757
  }).then(χ => {
607
758
  return resolve();
@@ -629,7 +780,7 @@ class EvaluationEvent extends DataObject {
629
780
  description: tokenInfo.total === failed.length ? context.__('Sending tokens failed for all students') : null
630
781
  }
631
782
  // and save
632
- return context.model('SendInstructorTokenAction').silent().save(sendTokensAction).then(item => {
783
+ return context.model(action.additionalType).silent().save(sendTokensAction).then(item => {
633
784
  EvaluationEvent.sendSse(user,context,evaluationEvent.id,message, sendTokensAction.description?{message: sendTokensAction.description}:null);
634
785
  }).catch(err => {
635
786
  TraceUtils.error(err);
@@ -662,7 +813,7 @@ class EvaluationEvent extends DataObject {
662
813
  description: tokenInfo.total === failed.length ? context.__('Sending tokens failed for all students') : null
663
814
  }
664
815
  // and save
665
- return context.model('SendInstructorTokenAction').silent().save(sendTokensAction).then(tokenAction => {
816
+ return context.model(action.additionalType).silent().save(sendTokensAction).then(tokenAction => {
666
817
  EvaluationEvent.sendSse(user,context,evaluationEvent.id,message,err);
667
818
  }).catch(err => {
668
819
  TraceUtils.error(err);
@@ -704,5 +855,42 @@ class EvaluationEvent extends DataObject {
704
855
  }
705
856
  }
706
857
  }
858
+ getAvgValues (context, results)
859
+ {
860
+ const avg = {
861
+ responsesAvg:0,
862
+ questionsAvg:0
863
+ }
864
+ // get avg of questions avg
865
+ const ignoreZeroValues = context.getConfiguration().getSourceAt('settings/evaluation/ignoreZeroValues') || false;
866
+ // filter only numbers
867
+ const filteredResults = results.responses.filter(x=> {
868
+ return !!x.isNumber;
869
+ });
870
+ // filter avg values
871
+ const filteredByValueResults =filteredResults
872
+ .filter(x=>{
873
+ return (ignoreZeroValues && x.avg > 0 || !ignoreZeroValues);
874
+ });
875
+ avg.responsesAvg = filteredByValueResults.length ? math.mean(filteredByValueResults
876
+ .map(x => {
877
+ return x.avg ;
878
+ })) : 0;
879
+
880
+ // get all answers
881
+ const questionResults = filteredResults.length? filteredResults.reduce((prev, curr)=>{
882
+ if (curr.responses) {
883
+ prev.push(...curr.responses.filter(y => {
884
+ return y !== undefined;
885
+ }).map(y => {
886
+ return y;
887
+ }));
888
+ }
889
+ return prev;
890
+ }, []):[];
891
+
892
+ avg.questionsAvg = questionResults.length? math.mean(questionResults):0;
893
+ return avg;
894
+ }
707
895
  }
708
896
  module.exports = EvaluationEvent;