@universis/evaluations 1.0.2

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 (68) hide show
  1. package/.eslintignore +1 -0
  2. package/.eslintrc +34 -0
  3. package/.gitlab-ci.yml +22 -0
  4. package/LICENSE +163 -0
  5. package/README.md +38 -0
  6. package/babel.config.js +3 -0
  7. package/dist/EvaluationSchemaLoader.js +33 -0
  8. package/dist/EvaluationSchemaLoader.js.map +1 -0
  9. package/dist/EvaluationService.js +56 -0
  10. package/dist/EvaluationService.js.map +1 -0
  11. package/dist/config/models/AccessToken.json +76 -0
  12. package/dist/config/models/ClassInstructorEvaluationEvent.json +76 -0
  13. package/dist/config/models/CourseClassEvaluationEvent.json +57 -0
  14. package/dist/config/models/EvaluationAccessToken.json +101 -0
  15. package/dist/config/models/EvaluationDocument.json +72 -0
  16. package/dist/config/models/EvaluationEvent.json +50 -0
  17. package/dist/config/scope.access.json +11 -0
  18. package/dist/evaluationRouter.js +118 -0
  19. package/dist/evaluationRouter.js.map +1 -0
  20. package/dist/handlers/evaluation-key-handler.js +45 -0
  21. package/dist/handlers/evaluation-key-handler.js.map +1 -0
  22. package/dist/index.js +3 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/listeners/class-instructor-event-listener.js +27 -0
  25. package/dist/listeners/class-instructor-event-listener.js.map +1 -0
  26. package/dist/listeners/force-set-state-listener.js +47 -0
  27. package/dist/listeners/force-set-state-listener.js.map +1 -0
  28. package/dist/models/access-token-model.d.ts +37 -0
  29. package/dist/models/access-token-model.js +39 -0
  30. package/dist/models/access-token-model.js.map +1 -0
  31. package/dist/models/evaluation-access-token-model.d.ts +17 -0
  32. package/dist/models/evaluation-access-token-model.js +40 -0
  33. package/dist/models/evaluation-access-token-model.js.map +1 -0
  34. package/dist/models/evaluation-document-model.d.ts +13 -0
  35. package/dist/models/evaluation-document-model.js +150 -0
  36. package/dist/models/evaluation-document-model.js.map +1 -0
  37. package/dist/models/evaluation-event-model.d.ts +13 -0
  38. package/dist/models/evaluation-event-model.js +318 -0
  39. package/dist/models/evaluation-event-model.js.map +1 -0
  40. package/package.json +53 -0
  41. package/spec/CourseEvaluationSampleForm.json +1046 -0
  42. package/spec/EvaluationService.spec.js +9 -0
  43. package/spec/helpers/babel.js +1 -0
  44. package/spec/helpers/env.js +7 -0
  45. package/spec/helpers/reporter.js +11 -0
  46. package/spec/support/jasmine.json +13 -0
  47. package/src/EvaluationSchemaLoader.js +35 -0
  48. package/src/EvaluationService.js +57 -0
  49. package/src/config/models/AccessToken.json +76 -0
  50. package/src/config/models/ClassInstructorEvaluationEvent.json +76 -0
  51. package/src/config/models/CourseClassEvaluationEvent.json +57 -0
  52. package/src/config/models/EvaluationAccessToken.json +101 -0
  53. package/src/config/models/EvaluationDocument.json +72 -0
  54. package/src/config/models/EvaluationEvent.json +50 -0
  55. package/src/config/scope.access.json +11 -0
  56. package/src/evaluationRouter.js +117 -0
  57. package/src/handlers/evaluation-key-handler.js +45 -0
  58. package/src/index.js +2 -0
  59. package/src/listeners/class-instructor-event-listener.js +27 -0
  60. package/src/listeners/force-set-state-listener.js +46 -0
  61. package/src/models/access-token-model.d.ts +37 -0
  62. package/src/models/access-token-model.js +38 -0
  63. package/src/models/evaluation-access-token-model.d.ts +17 -0
  64. package/src/models/evaluation-access-token-model.js +39 -0
  65. package/src/models/evaluation-document-model.d.ts +13 -0
  66. package/src/models/evaluation-document-model.js +149 -0
  67. package/src/models/evaluation-event-model.d.ts +13 -0
  68. package/src/models/evaluation-event-model.js +317 -0
@@ -0,0 +1,317 @@
1
+ import { HttpNotFoundError, HttpTokenExpiredError, HttpServerError,
2
+ TraceUtils,
3
+ HttpBadRequestError,
4
+ Args,
5
+ LangUtils} from '@themost/common';
6
+
7
+ import {
8
+ DataConfigurationStrategy,
9
+ DataContext,
10
+ DataObject,
11
+ EdmMapping,
12
+ EdmType,
13
+ ODataModelBuilder
14
+ } from '@themost/data';
15
+ import { HttpContext } from '@themost/web';
16
+ import { JsonFormInspector } from '@themost/form-inspector';
17
+ import EvaluationDocument from './evaluation-document-model';
18
+
19
+ const EvaluationAccessToken = require('./evaluation-access-token-model');
20
+ import {lt} from 'semver';
21
+ import util from "util";
22
+ import fs from "fs";
23
+ /**
24
+ * @class
25
+
26
+ * @property {string} id
27
+ * @augments {DataObject}
28
+ */
29
+ @EdmMapping.entityType('EvaluationEvent')
30
+ class EvaluationEvent extends DataObject {
31
+ /**
32
+ * @constructor
33
+ */
34
+ constructor() {
35
+ super();
36
+ }
37
+
38
+ /**
39
+ * Get current evaluation based on the evaluation key contained in Evaluation-Key HTTP header
40
+ * @param {HttpContext} context
41
+ */
42
+ @EdmMapping.func('Current', 'EvaluationEvent')
43
+ static async getCurrent(context) {
44
+ // get evaluation key
45
+ const token = await EvaluationAccessToken.inspect(context, context.user && context.user.authenticationToken);
46
+ if (token.active === false) {
47
+ throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');
48
+ }
49
+ // get evaluation event
50
+ const evaluationEvent = await context.model('EvaluationEvent').find(token.sub).silent().getTypedItem();
51
+ if (evaluationEvent == null) {
52
+ throw new HttpNotFoundError('The specified evaluation cannot be found');
53
+ }
54
+ if (evaluationEvent.additionalType !== 'EvaluationEvent') {
55
+ return await evaluationEvent.getAdditionalObject();
56
+ }
57
+ return evaluationEvent;
58
+ }
59
+
60
+ @EdmMapping.func('form', 'Object')
61
+ async getForm() {
62
+ const form = await this.property('evaluationDocument').getItem();
63
+ const service = this.context.getApplication().getService(function PrivateContentService(){});
64
+ /**
65
+ * @type {string}
66
+ */
67
+ const formPath = await new Promise((resolve, reject) => {
68
+ service.resolvePhysicalPath(this.context, form, (err, physicalPath) => {
69
+ if (err) {
70
+ return reject(err);
71
+ }
72
+ return resolve(physicalPath);
73
+ })
74
+ });
75
+ const readFileAsync = util.promisify(fs.readFile);
76
+ let content = await readFileAsync(formPath);
77
+ if (content == null) {
78
+ throw new HttpNotFoundError('Evaluation form cannot be found');
79
+ }
80
+ let buffer = Buffer.from(content,'base64');
81
+ let result;
82
+ result = JSON.parse(buffer.toString('utf8'));
83
+
84
+ try {
85
+ result.properties = result.properties || {};
86
+ Object.assign(result.properties, {
87
+ name: form.resultType,
88
+ _id: form.id,
89
+ _event: this.id
90
+ });
91
+ // post-processing
92
+ let shouldUpgrade = true;
93
+ let model = this.context.model(form.resultType);
94
+ if (model != null) {
95
+ shouldUpgrade = lt(model.version, form.version)
96
+ }
97
+ if (shouldUpgrade) {
98
+ // load for inspector
99
+ const inspector = new JsonFormInspector();
100
+ model = inspector.inspect(result);
101
+ // post processing steps
102
+ Object.assign(model, {
103
+ source: form.resultType, // add source from evaluation document e.g. Evaluation1
104
+ view: form.resultType, // add view from evaluation document e.g. Evaluation1
105
+ version: model.version ,// set version (follow updates)
106
+ hidden: true
107
+ });
108
+ // add evaluation event and evaluation document associations
109
+ // for further processing of evaluation results
110
+ model.fields.push.apply(model.fields, [
111
+ {
112
+ name: 'evaluationEvent',
113
+ type: this.getModel().name,
114
+ editable: false,
115
+ nullable: false,
116
+ indexed: true,
117
+ }
118
+ ]);
119
+ // reset privileges
120
+ /**
121
+ * @type {DataConfigurationStrategy|*}
122
+ */
123
+ const dataConfiguration = this.context.getApplication()
124
+ .getConfiguration().getStrategy(DataConfigurationStrategy);
125
+
126
+ model.privileges.splice(0);
127
+ // get resultPrivileges
128
+ const thisModel = dataConfiguration.model(this.getModel().name);
129
+
130
+ model.privileges.push.apply(model.privileges, [
131
+ {
132
+ "mask": 15,
133
+ "type": "global"
134
+ },
135
+ {
136
+ "mask": 1,
137
+ "type": "global",
138
+ "account": "Administrators"
139
+ }
140
+ ]);
141
+ // add extra privileges
142
+ if (Array.isArray(thisModel.resultPrivileges)) {
143
+ model.privileges.push.apply(model.privileges, thisModel.resultPrivileges);
144
+ }
145
+ dataConfiguration.setModelDefinition(model);
146
+ // add entity set
147
+ const builder = this.context.getApplication().getService(ODataModelBuilder);
148
+ builder.addEntitySet(model.name, model.name);
149
+ if (model.hidden) {
150
+ builder.removeEntitySet(model.name);
151
+ }
152
+ // update version
153
+ form.version= model.version;
154
+ await this.context.model('EvaluationDocument').silent().save(form);
155
+ }
156
+ return result;
157
+ } catch (err) {
158
+ TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);
159
+ TraceUtils.error(err);
160
+ throw new HttpServerError('An error occurred while decoding evaluation form.');
161
+ }
162
+ }
163
+
164
+ @EdmMapping.func('Results', EdmType.CollectionOf('Object'))
165
+ async getResults() {
166
+ const form = await this.getForm();
167
+ return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).prepare();
168
+ }
169
+
170
+ @EdmMapping.func('Tokens', EdmType.CollectionOf('EvaluationAccessToken'))
171
+ async getAccessTokens() {
172
+ return this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.id).prepare();
173
+ }
174
+
175
+ @EdmMapping.func('FormAttributes', EdmType.CollectionOf('Object'))
176
+ async getFormAttributes() {
177
+ const result = [];
178
+ const form = await this.getForm();
179
+ // get model attributes
180
+ /**
181
+ * @type {DataConfigurationStrategy|*}
182
+ */
183
+ const dataConfiguration = this.context.getApplication()
184
+ .getConfiguration().getStrategy(DataConfigurationStrategy);
185
+
186
+ const model = dataConfiguration.model(form.properties.name);
187
+ const attributes = model.fields;
188
+ attributes.forEach(attribute => {
189
+ const key = this.findByKey(form.components, attribute.name);
190
+ if (key) {
191
+ attribute = Object.assign(attribute,{
192
+ name: attribute.name, label: key.label
193
+ });
194
+ result.push(attribute);
195
+ }
196
+ });
197
+ return result;
198
+ }
199
+
200
+ findByKey(array, key) {
201
+ for (let index = 0; index < array.length; index++) {
202
+ const element = array[index];
203
+ if (element.key === key) {
204
+ return element;
205
+ } else {
206
+ if (element.components) {
207
+ const found = this.findByKey(element.components, key);
208
+ if (found) {
209
+ return found;
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ @EdmMapping.param('data', 'Object', false, true)
217
+ @EdmMapping.action('Evaluate', 'Object')
218
+ async evaluate(data) {
219
+ const token = await EvaluationAccessToken.inspect(this.context, this.context.user.authenticationToken);
220
+ if (token.active === false) {
221
+ throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');
222
+ }
223
+ if (this.id !== token.sub) {
224
+ throw new HttpBadRequestError('Evaluation access token is invalid');
225
+ }
226
+ // get evaluation form
227
+ const form = await this.getForm();
228
+ // get evaluation document
229
+ if (form == null) {
230
+ throw new HttpNotFoundError('Evaluation form cannot be found');
231
+ }
232
+ // get evaluation document
233
+ const evaluationDocument = await this.context.model(EvaluationDocument)
234
+ .where('id').equal(form.properties._id)
235
+ .silent().getItem();
236
+ if (evaluationDocument == null) {
237
+ throw new HttpNotFoundError('Evaluation document cannot be found');
238
+ }
239
+ // assign defaults
240
+ Object.assign(data, {
241
+ evaluationEvent: this.id,
242
+ evaluationDocument: evaluationDocument.id
243
+ });
244
+ // and finally append evaluation
245
+ await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {
246
+ const context = event.model.context;
247
+ context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken)
248
+ .silent().getItem().then((token) => {
249
+ if (token == null) {
250
+ throw new HttpTokenExpiredError('Evaluation token is required');
251
+ }
252
+ return context.model(EvaluationAccessToken).silent().save({
253
+ access_token: token.access_token,
254
+ expires: new Date(0) // set epoch date
255
+ });
256
+ }).then(() => {
257
+ return callback();
258
+ }).catch((err) => {
259
+ TraceUtils.error('An error occurred while submitting evaluation');
260
+ return callback(err);
261
+ });
262
+ }).silent().save(data);
263
+ return data;
264
+ }
265
+
266
+ /**
267
+ * Generates a number of access tokens for the given event
268
+ * @param {DataContext} context
269
+ * @param {{evaluationEvent: number, n: number, expires?: DateTime}|*} generateOptions
270
+ */
271
+ @EdmMapping.param('data', 'Object', false, true)
272
+ @EdmMapping.action('GenerateTokens', 'Object')
273
+ static async generateTokens(context, generateOptions) {
274
+ let items = [];
275
+ if (Array.isArray(generateOptions)) {
276
+ let n = 0;
277
+ let newItems;
278
+ // eslint-disable-next-line no-unused-vars
279
+ for(let itemGenerateOptions of generateOptions) {
280
+ newItems = await EvaluationEvent.generateManyTokens(context, itemGenerateOptions);
281
+ n += newItems.length;
282
+ items.push.apply(items, newItems);
283
+ }
284
+ await context.model('EvaluationAccessToken').save(items);
285
+ return n
286
+ } else {
287
+ items = await EvaluationEvent.generateManyTokens(context, generateOptions);
288
+ await context.model('EvaluationAccessToken').save(items);
289
+ return items.length;
290
+ }
291
+ }
292
+ /**
293
+ * Generates a number of access tokens for the given event
294
+ * @param {DataContext} context
295
+ * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions
296
+ */
297
+ static async generateManyTokens(context, generateOptions) {
298
+ const n = generateOptions.n;
299
+ Args.check(typeof n === 'number', 'Expected a number greater than zero');
300
+ Args.check(n > 0, 'The number of access tokens must be greater than zero');
301
+ let maximumGenerateTokens = LangUtils.parseInt(context.getConfiguration().getSourceAt('settings/evaluation/maximumGenerateTokens'));
302
+ if (maximumGenerateTokens === 0) {
303
+ maximumGenerateTokens = 128;
304
+ }
305
+ Args.check(n < maximumGenerateTokens, `The specified number of tokens exceeded the maximum allowed (${maximumGenerateTokens})`);
306
+ const items = [];
307
+ // generate tokens
308
+ for (let index = 0; index < n; index++) {
309
+ items.push({
310
+ evaluationEvent: generateOptions.evaluationEvent,
311
+ expires: generateOptions.expires
312
+ });
313
+ }
314
+ return items;
315
+ }
316
+ }
317
+ module.exports = EvaluationEvent;