@universis/evaluations 1.0.3 → 1.0.6

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.
@@ -19,12 +19,12 @@ var _evaluationDocumentModel = _interopRequireDefault(require("./evaluation-docu
19
19
 
20
20
  var _semver = require("semver");
21
21
  var _util = _interopRequireDefault(require("util"));
22
- var _fs = _interopRequireDefault(require("fs"));var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class, _class2;function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {var desc = {};Object.keys(descriptor).forEach(function (key) {desc[key] = descriptor[key];});desc.enumerable = !!desc.enumerable;desc.configurable = !!desc.configurable;if ('value' in desc || desc.initializer) {desc.writable = true;}desc = decorators.slice().reverse().reduce(function (desc, decorator) {return decorator(target, property, desc) || desc;}, desc);if (context && desc.initializer !== void 0) {desc.value = desc.initializer ? desc.initializer.call(context) : void 0;desc.initializer = undefined;}if (desc.initializer === void 0) {Object.defineProperty(target, property, desc);desc = null;}return desc;}const EvaluationAccessToken = require('./evaluation-access-token-model');
22
+ var _fs = _interopRequireDefault(require("fs"));
23
+ var _moment = _interopRequireDefault(require("moment"));var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _class, _class2;function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {var desc = {};Object.keys(descriptor).forEach(function (key) {desc[key] = descriptor[key];});desc.enumerable = !!desc.enumerable;desc.configurable = !!desc.configurable;if ('value' in desc || desc.initializer) {desc.writable = true;}desc = decorators.slice().reverse().reduce(function (desc, decorator) {return decorator(target, property, desc) || desc;}, desc);if (context && desc.initializer !== void 0) {desc.value = desc.initializer ? desc.initializer.call(context) : void 0;desc.initializer = undefined;}if (desc.initializer === void 0) {Object.defineProperty(target, property, desc);desc = null;}return desc;}const EvaluationAccessToken = require('./evaluation-access-token-model');
24
+ const math = require('mathjs');
25
+
23
26
  /**
24
27
  * @class
25
-
26
- * @property {string} id
27
- * @augments {DataObject}
28
28
  */let
29
29
 
30
30
  EvaluationEvent = (_dec = _data.EdmMapping.entityType('EvaluationEvent'), _dec2 =
@@ -57,7 +57,6 @@ _data.EdmMapping.func('Current', 'EvaluationEvent'), _dec3 =
57
57
 
58
58
 
59
59
 
60
- _data.EdmMapping.func('form', 'Object'), _dec4 =
61
60
 
62
61
 
63
62
 
@@ -66,6 +65,7 @@ _data.EdmMapping.func('form', 'Object'), _dec4 =
66
65
 
67
66
 
68
67
 
68
+ _data.EdmMapping.func('form', 'Object'), _dec4 =
69
69
 
70
70
 
71
71
 
@@ -161,26 +161,26 @@ _data.EdmMapping.func('form', 'Object'), _dec4 =
161
161
 
162
162
 
163
163
 
164
- _data.EdmMapping.func('Results', _data.EdmType.CollectionOf('Object')), _dec5 =
165
164
 
166
165
 
167
166
 
168
167
 
169
168
 
170
- _data.EdmMapping.func('Tokens', _data.EdmType.CollectionOf('EvaluationAccessToken')), _dec6 =
171
169
 
172
170
 
173
171
 
172
+ _data.EdmMapping.func('Results', _data.EdmType.CollectionOf('Object')), _dec5 =
174
173
 
175
- _data.EdmMapping.func('FormAttributes', _data.EdmType.CollectionOf('Object')), _dec7 =
176
174
 
177
175
 
178
176
 
179
177
 
178
+ _data.EdmMapping.func('Tokens', _data.EdmType.CollectionOf('EvaluationAccessToken')), _dec6 =
180
179
 
181
180
 
182
181
 
183
182
 
183
+ _data.EdmMapping.func('FormAttributes', _data.EdmType.CollectionOf('Object')), _dec7 =
184
184
 
185
185
 
186
186
 
@@ -213,8 +213,6 @@ _data.EdmMapping.func('FormAttributes', _data.EdmType.CollectionOf('Object')), _
213
213
 
214
214
 
215
215
 
216
- _data.EdmMapping.param('data', 'Object', false, true), _dec8 =
217
- _data.EdmMapping.action('Evaluate', 'Object'), _dec9 =
218
216
 
219
217
 
220
218
 
@@ -268,15 +266,19 @@ _data.EdmMapping.action('Evaluate', 'Object'), _dec9 =
268
266
 
269
267
 
270
268
 
271
- _data.EdmMapping.param('data', 'Object', false, true), _dec10 =
272
- _data.EdmMapping.action('GenerateTokens', 'Object'), _dec(_class = (_class2 = class EvaluationEvent extends _data.DataObject {/**
269
+
270
+ _data.EdmMapping.param('data', 'Object', false, true), _dec8 =
271
+ _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class EvaluationEvent extends _data.DataObject {/**
273
272
  * @constructor
274
273
  */constructor() {super();} /**
275
274
  * Get current evaluation based on the evaluation key contained in Evaluation-Key HTTP header
276
- * @param {HttpContext} context
275
+ * @param {HttpContext} context
277
276
  */static async getCurrent(context) {// get evaluation key
278
277
  const token = await EvaluationAccessToken.inspect(context, context.user && context.user.authenticationToken);if (token.active === false) {throw new _common.HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');} // get evaluation event
279
- const evaluationEvent = await context.model('EvaluationEvent').find(token.sub).silent().getTypedItem();if (evaluationEvent == null) {throw new _common.HttpNotFoundError('The specified evaluation cannot be found');}if (evaluationEvent.additionalType !== 'EvaluationEvent') {return await evaluationEvent.getAdditionalObject();}return evaluationEvent;}async getForm() {const form = await this.property('evaluationDocument').getItem();const service = this.context.getApplication().getService(function PrivateContentService() {}); /**
278
+ // get current date
279
+ const startDate = new Date(); // get current date with time
280
+ const endDate = (0, _moment.default)(new Date()).startOf('day').toDate(); // get only date format
281
+ const evaluationEvent = await context.model('EvaluationEvent').where('id').equal(token.sub).and('date(startDate)').lowerOrEqual(startDate).and('date(endDate)').greaterOrEqual(endDate).and('eventStatus/alternateName').equal('EventOpened').silent().getTypedItem();if (evaluationEvent == null) {throw new _common.HttpNotFoundError('The specified evaluation cannot be found');}if (evaluationEvent.additionalType !== 'EvaluationEvent') {return await evaluationEvent.getAdditionalObject();}return evaluationEvent;}async getForm() {const form = await this.property('evaluationDocument').getItem();const service = this.context.getApplication().getService(function PrivateContentService() {}); /**
280
282
  * @type {string}
281
283
  */const formPath = await new Promise((resolve, reject) => {service.resolvePhysicalPath(this.context, form, (err, physicalPath) => {if (err) {return reject(err);}return resolve(physicalPath);});});const readFileAsync = _util.default.promisify(_fs.default.readFile);let content = await readFileAsync(formPath);if (content == null) {throw new _common.HttpNotFoundError('Evaluation form cannot be found');}let buffer = Buffer.from(content, 'base64');let result;result = JSON.parse(buffer.toString('utf8'));try {result.properties = result.properties || {};Object.assign(result.properties, { name: form.resultType, _id: form.id, _event: this.id }); // post-processing
282
284
  let shouldUpgrade = true;let model = this.context.model(form.resultType);if (model != null) {shouldUpgrade = (0, _semver.lt)(model.version, form.version);}if (shouldUpgrade) {// load for inspector
@@ -293,26 +295,72 @@ _data.EdmMapping.action('GenerateTokens', 'Object'), _dec(_class = (_class2 = cl
293
295
  const thisModel = dataConfiguration.model(this.getModel().name);model.privileges.push.apply(model.privileges, [{ "mask": 15, "type": "global" }, { "mask": 1, "type": "global", "account": "Administrators" }]); // add extra privileges
294
296
  if (Array.isArray(thisModel.resultPrivileges)) {model.privileges.push.apply(model.privileges, thisModel.resultPrivileges);}dataConfiguration.setModelDefinition(model); // add entity set
295
297
  const builder = this.context.getApplication().getService(_data.ODataModelBuilder);builder.addEntitySet(model.name, model.name);if (model.hidden) {builder.removeEntitySet(model.name);} // update version
296
- form.version = model.version;await this.context.model('EvaluationDocument').silent().save(form);}return result;} catch (err) {_common.TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);_common.TraceUtils.error(err);throw new _common.HttpServerError('An error occurred while decoding evaluation form.');}}async getResults() {const form = await this.getForm();return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).prepare();}async getAccessTokens() {return this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.id).prepare();}async getFormAttributes() {const result = [];const form = await this.getForm(); // get model attributes
298
+ form.version = model.version;await this.context.model('EvaluationDocument').silent().save(form);}return result;} catch (err) {_common.TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);_common.TraceUtils.error(err);throw new _common.HttpServerError('An error occurred while decoding evaluation form.');}}async getResults() {const form = await this.getForm();return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).prepare();}async getAccessTokens() {return this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.id).prepare();}async getFormAttributes() {/**
299
+ * @type {DataContext|*}
300
+ */const context = this.context;const result = [];const form = await this.getForm();this.setParentLegend(form); // get model attributes
297
301
  /**
298
302
  * @type {DataConfigurationStrategy|*}
299
- */const dataConfiguration = this.context.getApplication().getConfiguration().getStrategy(_data.DataConfigurationStrategy);const model = dataConfiguration.model(form.properties.name);const attributes = model.fields;attributes.forEach((attribute) => {const key = this.findByKey(form.components, attribute.name);if (key) {attribute = Object.assign(attribute, { name: attribute.name, label: key.label });result.push(attribute);}});return result;}findByKey(array, key) {for (let index = 0; index < array.length; index++) {const element = array[index];if (element.key === key) {return element;} else {if (element.components) {const found = this.findByKey(element.components, key);if (found) {return found;}}}}}async evaluate(data) {const token = await EvaluationAccessToken.inspect(this.context, this.context.user.authenticationToken);if (token.active === false) {throw new _common.HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');}if (this.id !== token.sub) {throw new _common.HttpBadRequestError('Evaluation access token is invalid');} // get evaluation form
303
+ */const dataConfiguration = context.getApplication().getConfiguration().getStrategy(_data.DataConfigurationStrategy);const dataTypes = dataConfiguration.dataTypes;const q = context.model(form.properties.name).asQueryable();const selectArguments = [];const model = dataConfiguration.model(form.properties.name);const attributes = model.fields;attributes.forEach((attribute) => {const key = this.findByKey(form.components, attribute.name);if (key) {attribute = Object.assign(attribute, { name: attribute.name, label: key.label });attribute.isNumber = false;attribute.legend = key.customProperties && key.customProperties.legend;if (Object.prototype.hasOwnProperty.call(dataTypes, attribute.type)) {attribute.isNumber = dataTypes[attribute.type].type === 'number';}selectArguments.push(`${attribute.name}`);result.push(attribute);}});if (selectArguments.length) {const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').equal(this.getId()).silent().getAllItems();for (let i = 0; i < result.length; i++) {const qElement = result[i];qElement.responses = [];if (qElement.isNumber) {// add mean value and standard deviation
304
+ qElement.std = responses.length ? math.std(responses.map((x) => {return x[qElement.name];})) : 0;qElement.avg = responses.length ? math.mean(responses.map((x) => {return x[qElement.name];})) : 0;} else {qElement.responses = responses.map((x) => {return x[qElement.name];});}}}return result;}findByKey(array, key) {for (let index = 0; index < array.length; index++) {const element = array[index];if (element.key === key) {return element;} else {if (element.components) {const found = this.findByKey(element.components, key);if (found) {return found;}}}}}setParentLegend(component) {if (Array.isArray(component.components)) {component.components.forEach((item) => {if (component.legend) {item.customProperties = item.customProperties || {};item.customProperties.legend = component.legend;}this.setParentLegend(item);});}}async evaluate(data) {const token = await EvaluationAccessToken.inspect(this.context, this.context.user.authenticationToken);if (token.active === false) {throw new _common.HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');}if (this.id !== token.sub) {throw new _common.HttpBadRequestError('Evaluation access token is invalid');} // get evaluation form
300
305
  const form = await this.getForm(); // get evaluation document
301
306
  if (form == null) {throw new _common.HttpNotFoundError('Evaluation form cannot be found');} // get evaluation document
302
307
  const evaluationDocument = await this.context.model(_evaluationDocumentModel.default).where('id').equal(form.properties._id).silent().getItem();if (evaluationDocument == null) {throw new _common.HttpNotFoundError('Evaluation document cannot be found');} // assign defaults
303
308
  Object.assign(data, { evaluationEvent: this.id, evaluationDocument: evaluationDocument.id }); // and finally append evaluation
304
- await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {const context = event.model.context;context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken).silent().getItem().then((token) => {if (token == null) {throw new _common.HttpTokenExpiredError('Evaluation token is required');}return context.model(EvaluationAccessToken).silent().save({ access_token: token.access_token, expires: new Date(0) // set epoch date
305
- });}).then(() => {return callback();}).catch((err) => {_common.TraceUtils.error('An error occurred while submitting evaluation');return callback(err);});}).silent().save(data);return data;} /**
306
- * Generates a number of access tokens for the given event
307
- * @param {DataContext} context
308
- * @param {{evaluationEvent: number, n: number, expires?: DateTime}|*} generateOptions
309
- */static async generateTokens(context, generateOptions) {let items = [];if (Array.isArray(generateOptions)) {let n = 0;let newItems; // eslint-disable-next-line no-unused-vars
310
- for (let itemGenerateOptions of generateOptions) {newItems = await EvaluationEvent.generateManyTokens(context, itemGenerateOptions);n += newItems.length;items.push.apply(items, newItems);}await context.model('EvaluationAccessToken').save(items);return n;} else {items = await EvaluationEvent.generateManyTokens(context, generateOptions);await context.model('EvaluationAccessToken').save(items);return items.length;}} /**
309
+ await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {const context = event.model.context;context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken).silent().getItem().then((token) => {if (token == null) {throw new _common.HttpTokenExpiredError('Evaluation token is required');}return context.model(EvaluationAccessToken).silent().save({ access_token: token.access_token, expires: new Date(0), // set epoch date
310
+ used: true });
311
+ }).then(() => {
312
+ return callback();
313
+ }).catch((err) => {
314
+ _common.TraceUtils.error('An error occurred while submitting evaluation');
315
+ return callback(err);
316
+ });
317
+ }).silent().save(data);
318
+ return data;
319
+ }
320
+
321
+ static async generateTokens(context, generateOptions) {
322
+ let items = [];
323
+ if (Array.isArray(generateOptions)) {
324
+ let n = 0;
325
+ let newItems;
326
+ // eslint-disable-next-line no-unused-vars
327
+ for (let itemGenerateOptions of generateOptions) {
328
+ newItems = await EvaluationEvent.generateManyTokens(context, itemGenerateOptions);
329
+ n += newItems.length;
330
+ items.push.apply(items, newItems);
331
+ }
332
+ await context.model('EvaluationAccessToken').save(items);
333
+ return n;
334
+ } else {
335
+ items = await EvaluationEvent.generateManyTokens(context, generateOptions);
336
+ await context.model('EvaluationAccessToken').save(items);
337
+ return items.length;
338
+ }
339
+ }
340
+ /**
311
341
  * Generates a number of access tokens for the given event
312
342
  * @param {DataContext} context
313
343
  * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions
314
- */static async generateManyTokens(context, generateOptions) {const n = generateOptions.n;_common.Args.check(typeof n === 'number', 'Expected a number greater than zero');_common.Args.check(n > 0, 'The number of access tokens must be greater than zero');let maximumGenerateTokens = _common.LangUtils.parseInt(context.getConfiguration().getSourceAt('settings/evaluation/maximumGenerateTokens'));if (maximumGenerateTokens === 0) {maximumGenerateTokens = 128;}_common.Args.check(n < maximumGenerateTokens, `The specified number of tokens exceeded the maximum allowed (${maximumGenerateTokens})`);const items = []; // generate tokens
315
- for (let index = 0; index < n; index++) {items.push({ evaluationEvent: generateOptions.evaluationEvent, expires: generateOptions.expires });}return items;}}, (_applyDecoratedDescriptor(_class2, "getCurrent", [_dec2], Object.getOwnPropertyDescriptor(_class2, "getCurrent"), _class2), _applyDecoratedDescriptor(_class2.prototype, "getForm", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "getForm"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getResults", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "getResults"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getAccessTokens", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "getAccessTokens"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getFormAttributes", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "getFormAttributes"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "evaluate", [_dec7, _dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "evaluate"), _class2.prototype), _applyDecoratedDescriptor(_class2, "generateTokens", [_dec9, _dec10], Object.getOwnPropertyDescriptor(_class2, "generateTokens"), _class2)), _class2)) || _class);
344
+ */
345
+ static async generateManyTokens(context, generateOptions) {
346
+ const n = generateOptions.n;
347
+ _common.Args.check(typeof n === 'number', 'Expected a number greater than zero');
348
+ _common.Args.check(n > 0, 'The number of access tokens must be greater than zero');
349
+ let maximumGenerateTokens = _common.LangUtils.parseInt(context.getConfiguration().getSourceAt('settings/evaluation/maximumGenerateTokens'));
350
+ if (maximumGenerateTokens === 0) {
351
+ maximumGenerateTokens = 1000;
352
+ }
353
+ _common.Args.check(n < maximumGenerateTokens, `The specified number of tokens exceeded the maximum allowed (${maximumGenerateTokens})`);
354
+ const items = [];
355
+ // generate tokens
356
+ for (let index = 0; index < n; index++) {
357
+ items.push({
358
+ evaluationEvent: generateOptions.evaluationEvent,
359
+ expires: generateOptions.expires });
360
+
361
+ }
362
+ return items;
363
+ }}, (_applyDecoratedDescriptor(_class2, "getCurrent", [_dec2], Object.getOwnPropertyDescriptor(_class2, "getCurrent"), _class2), _applyDecoratedDescriptor(_class2.prototype, "getForm", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "getForm"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getResults", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "getResults"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getAccessTokens", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "getAccessTokens"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "getFormAttributes", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "getFormAttributes"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "evaluate", [_dec7, _dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "evaluate"), _class2.prototype)), _class2)) || _class);
316
364
 
317
365
  module.exports = EvaluationEvent;
318
366
  //# sourceMappingURL=evaluation-event-model.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/models/evaluation-event-model.js"],"names":["EvaluationAccessToken","require","EvaluationEvent","EdmMapping","entityType","func","EdmType","CollectionOf","param","action","DataObject","constructor","getCurrent","context","token","inspect","user","authenticationToken","active","HttpTokenExpiredError","evaluationEvent","model","find","sub","silent","getTypedItem","HttpNotFoundError","additionalType","getAdditionalObject","getForm","form","property","getItem","service","getApplication","getService","PrivateContentService","formPath","Promise","resolve","reject","resolvePhysicalPath","err","physicalPath","readFileAsync","util","promisify","fs","readFile","content","buffer","Buffer","from","result","JSON","parse","toString","properties","Object","assign","name","resultType","_id","id","_event","shouldUpgrade","version","inspector","JsonFormInspector","source","view","hidden","fields","push","apply","type","getModel","editable","nullable","indexed","dataConfiguration","getConfiguration","getStrategy","DataConfigurationStrategy","privileges","splice","thisModel","Array","isArray","resultPrivileges","setModelDefinition","builder","ODataModelBuilder","addEntitySet","removeEntitySet","save","TraceUtils","error","HttpServerError","getResults","where","equal","prepare","getAccessTokens","getFormAttributes","attributes","forEach","attribute","key","findByKey","components","label","array","index","length","element","found","evaluate","data","HttpBadRequestError","evaluationDocument","EvaluationDocument","on","event","callback","then","access_token","expires","Date","catch","generateTokens","generateOptions","items","n","newItems","itemGenerateOptions","generateManyTokens","Args","check","maximumGenerateTokens","LangUtils","parseInt","getSourceAt","module","exports"],"mappings":"aAAA;;;;;;AAMA;;;;;;;;AAQA;AACA;AACA;;;AAGA;AACA;AACA,gD,q3BAHA,MAAMA,qBAAqB,GAAGC,OAAO,CAAC,iCAAD,CAArC;AAIA;AACA;AACA;AACA;AACA;AACA,G;;AAEMC,e,WADLC,iBAAWC,UAAX,CAAsB,iBAAtB,C;;;;;;;;;;;;AAaID,iBAAWE,IAAX,CAAgB,SAAhB,EAA2B,iBAA3B,C;;;;;;;;;;;;;;;;;;AAkBAF,iBAAWE,IAAX,CAAgB,MAAhB,EAAwB,QAAxB,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGAF,iBAAWE,IAAX,CAAgB,SAAhB,EAA2BC,cAAQC,YAAR,CAAqB,QAArB,CAA3B,C;;;;;;AAMAJ,iBAAWE,IAAX,CAAgB,QAAhB,EAA0BC,cAAQC,YAAR,CAAqB,uBAArB,CAA1B,C;;;;;AAKAJ,iBAAWE,IAAX,CAAgB,gBAAhB,EAAkCC,cAAQC,YAAR,CAAqB,QAArB,CAAlC,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCAJ,iBA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AIH,qBAAqB,KAAK,CAA9B,EAAiC,CAC7BA,qBAAqB,GAAG,GAAxB,CACH,CACDF,aAAKC,KAAL,CAAWL,CAAC,GAAGM,qBAAf,EAAuC,gEAA+DA,qBAAsB,GAA5H,EACA,MAAMP,KAAK,GAAG,EAAd,CATsD,CAUtD;AACA,SAAK,IAAInB,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGoB,CAA5B,EAA+BpB,KAAK,EAApC,EAAwC,CACpCmB,KAAK,CAAC3D,IAAN,CAAW,EACPrD,eAAe,EAAE+G,eAAe,CAAC/G,eAD1B,EAEP2G,OAAO,EAAEI,eAAe,CAACJ,OAFlB,EAAX,EAIH,CACD,OAAOK,KAAP,CACH,CA7RoC,C;;AA+RzCW,MAAM,CAACC,OAAP,GAAiB9I,eAAjB","sourcesContent":["import { HttpNotFoundError, HttpTokenExpiredError, HttpServerError,\n TraceUtils, \n HttpBadRequestError,\n Args,\n LangUtils} from '@themost/common';\n\nimport {\n DataConfigurationStrategy,\n DataContext,\n DataObject,\n EdmMapping,\n EdmType,\n ODataModelBuilder\n} from '@themost/data';\nimport { HttpContext } from '@themost/web';\nimport { JsonFormInspector } from '@themost/form-inspector';\nimport EvaluationDocument from './evaluation-document-model';\n\nconst EvaluationAccessToken = require('./evaluation-access-token-model');\nimport {lt} from 'semver';\nimport util from \"util\";\nimport fs from \"fs\";\n/**\n * @class\n \n * @property {string} id\n * @augments {DataObject}\n */\n@EdmMapping.entityType('EvaluationEvent')\nclass EvaluationEvent extends DataObject {\n /**\n * @constructor\n */\n constructor() {\n super();\n }\n\n /**\n * Get current evaluation based on the evaluation key contained in Evaluation-Key HTTP header\n * @param {HttpContext} context \n */\n @EdmMapping.func('Current', 'EvaluationEvent')\n static async getCurrent(context) {\n // get evaluation key\n const token = await EvaluationAccessToken.inspect(context, context.user && context.user.authenticationToken);\n if (token.active === false) {\n throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');\n }\n // get evaluation event\n const evaluationEvent = await context.model('EvaluationEvent').find(token.sub).silent().getTypedItem();\n if (evaluationEvent == null) {\n throw new HttpNotFoundError('The specified evaluation cannot be found');\n }\n if (evaluationEvent.additionalType !== 'EvaluationEvent') {\n return await evaluationEvent.getAdditionalObject();\n }\n return evaluationEvent;\n }\n\n @EdmMapping.func('form', 'Object')\n async getForm() {\n const form = await this.property('evaluationDocument').getItem();\n const service = this.context.getApplication().getService(function PrivateContentService(){});\n /**\n * @type {string}\n */\n const formPath = await new Promise((resolve, reject) => {\n service.resolvePhysicalPath(this.context, form, (err, physicalPath) => {\n if (err) {\n return reject(err);\n }\n return resolve(physicalPath);\n })\n });\n const readFileAsync = util.promisify(fs.readFile);\n let content = await readFileAsync(formPath);\n if (content == null) {\n throw new HttpNotFoundError('Evaluation form cannot be found');\n }\n let buffer = Buffer.from(content,'base64');\n let result;\n result = JSON.parse(buffer.toString('utf8'));\n\n try {\n result.properties = result.properties || {};\n Object.assign(result.properties, {\n name: form.resultType,\n _id: form.id,\n _event: this.id\n });\n // post-processing\n let shouldUpgrade = true;\n let model = this.context.model(form.resultType);\n if (model != null) {\n shouldUpgrade = lt(model.version, form.version)\n }\n if (shouldUpgrade) {\n // load for inspector\n const inspector = new JsonFormInspector();\n model = inspector.inspect(result);\n // post processing steps\n Object.assign(model, {\n source: form.resultType, // add source from evaluation document e.g. Evaluation1\n view: form.resultType, // add view from evaluation document e.g. Evaluation1\n version: model.version ,// set version (follow updates)\n hidden: true\n });\n // add evaluation event and evaluation document associations\n // for further processing of evaluation results\n model.fields.push.apply(model.fields, [\n {\n name: 'evaluationEvent',\n type: this.getModel().name,\n editable: false,\n nullable: false,\n indexed: true,\n }\n ]);\n // reset privileges\n /**\n * @type {DataConfigurationStrategy|*}\n */\n const dataConfiguration = this.context.getApplication()\n .getConfiguration().getStrategy(DataConfigurationStrategy);\n\n model.privileges.splice(0);\n // get resultPrivileges\n const thisModel = dataConfiguration.model(this.getModel().name);\n\n model.privileges.push.apply(model.privileges, [\n {\n \"mask\": 15,\n \"type\": \"global\"\n },\n {\n \"mask\": 1,\n \"type\": \"global\",\n \"account\": \"Administrators\"\n }\n ]);\n // add extra privileges\n if (Array.isArray(thisModel.resultPrivileges)) {\n model.privileges.push.apply(model.privileges, thisModel.resultPrivileges);\n }\n dataConfiguration.setModelDefinition(model);\n // add entity set\n const builder = this.context.getApplication().getService(ODataModelBuilder);\n builder.addEntitySet(model.name, model.name);\n if (model.hidden) {\n builder.removeEntitySet(model.name);\n }\n // update version\n form.version= model.version;\n await this.context.model('EvaluationDocument').silent().save(form);\n }\n return result;\n } catch (err) {\n TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);\n TraceUtils.error(err);\n throw new HttpServerError('An error occurred while decoding evaluation form.');\n }\n }\n\n @EdmMapping.func('Results', EdmType.CollectionOf('Object'))\n async getResults() {\n const form = await this.getForm();\n return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).prepare();\n }\n\n @EdmMapping.func('Tokens', EdmType.CollectionOf('EvaluationAccessToken'))\n async getAccessTokens() {\n return this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.id).prepare();\n }\n\n @EdmMapping.func('FormAttributes', EdmType.CollectionOf('Object'))\n async getFormAttributes() {\n const result = [];\n const form = await this.getForm();\n // get model attributes\n /**\n * @type {DataConfigurationStrategy|*}\n */\n const dataConfiguration = this.context.getApplication()\n .getConfiguration().getStrategy(DataConfigurationStrategy);\n\n const model = dataConfiguration.model(form.properties.name);\n const attributes = model.fields;\n attributes.forEach(attribute => {\n const key = this.findByKey(form.components, attribute.name);\n if (key) {\n attribute = Object.assign(attribute,{\n name: attribute.name, label: key.label\n });\n result.push(attribute);\n }\n });\n return result;\n }\n\n findByKey(array, key) {\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n if (element.key === key) {\n return element;\n } else {\n if (element.components) {\n const found = this.findByKey(element.components, key);\n if (found) {\n return found;\n }\n }\n }\n }\n }\n\n @EdmMapping.param('data', 'Object', false, true)\n @EdmMapping.action('Evaluate', 'Object')\n async evaluate(data) {\n const token = await EvaluationAccessToken.inspect(this.context, this.context.user.authenticationToken);\n if (token.active === false) {\n throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');\n }\n if (this.id !== token.sub) {\n throw new HttpBadRequestError('Evaluation access token is invalid');\n }\n // get evaluation form\n const form = await this.getForm();\n // get evaluation document\n if (form == null) {\n throw new HttpNotFoundError('Evaluation form cannot be found');\n }\n // get evaluation document\n const evaluationDocument = await this.context.model(EvaluationDocument)\n .where('id').equal(form.properties._id)\n .silent().getItem();\n if (evaluationDocument == null) {\n throw new HttpNotFoundError('Evaluation document cannot be found');\n }\n // assign defaults\n Object.assign(data, {\n evaluationEvent: this.id,\n evaluationDocument: evaluationDocument.id\n });\n // and finally append evaluation\n await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {\n const context = event.model.context;\n context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken)\n .silent().getItem().then((token) => {\n if (token == null) {\n throw new HttpTokenExpiredError('Evaluation token is required');\n }\n return context.model(EvaluationAccessToken).silent().save({\n access_token: token.access_token,\n expires: new Date(0) // set epoch date\n });\n }).then(() => {\n return callback();\n }).catch((err) => {\n TraceUtils.error('An error occurred while submitting evaluation');\n return callback(err);\n });\n }).silent().save(data);\n return data;\n }\n\n /**\n * Generates a number of access tokens for the given event\n * @param {DataContext} context\n * @param {{evaluationEvent: number, n: number, expires?: DateTime}|*} generateOptions\n */\n @EdmMapping.param('data', 'Object', false, true)\n @EdmMapping.action('GenerateTokens', 'Object')\n static async generateTokens(context, generateOptions) {\n let items = [];\n if (Array.isArray(generateOptions)) {\n let n = 0;\n let newItems;\n // eslint-disable-next-line no-unused-vars\n for(let itemGenerateOptions of generateOptions) {\n newItems = await EvaluationEvent.generateManyTokens(context, itemGenerateOptions);\n n += newItems.length;\n items.push.apply(items, newItems);\n }\n await context.model('EvaluationAccessToken').save(items);\n return n\n } else {\n items = await EvaluationEvent.generateManyTokens(context, generateOptions);\n await context.model('EvaluationAccessToken').save(items);\n return items.length;\n } \n }\n /**\n * Generates a number of access tokens for the given event \n * @param {DataContext} context\n * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions\n */\n static async generateManyTokens(context, generateOptions) {\n const n = generateOptions.n;\n Args.check(typeof n === 'number', 'Expected a number greater than zero');\n Args.check(n > 0, 'The number of access tokens must be greater than zero');\n let maximumGenerateTokens = LangUtils.parseInt(context.getConfiguration().getSourceAt('settings/evaluation/maximumGenerateTokens'));\n if (maximumGenerateTokens === 0) {\n maximumGenerateTokens = 128;\n }\n Args.check(n < maximumGenerateTokens, `The specified number of tokens exceeded the maximum allowed (${maximumGenerateTokens})`);\n const items = [];\n // generate tokens\n for (let index = 0; index < n; index++) {\n items.push({\n evaluationEvent: generateOptions.evaluationEvent,\n expires: generateOptions.expires\n });\n }\n return items;\n }\n}\nmodule.exports = EvaluationEvent;\n"],"file":"evaluation-event-model.js"}
1
+ {"version":3,"sources":["../../src/models/evaluation-event-model.js"],"names":["EvaluationAccessToken","require","math","EvaluationEvent","EdmMapping","entityType","func","EdmType","CollectionOf","param","action","DataObject","constructor","getCurrent","context","token","inspect","user","authenticationToken","active","HttpTokenExpiredError","startDate","Date","endDate","startOf","toDate","evaluationEvent","model","where","equal","sub","and","lowerOrEqual","greaterOrEqual","silent","getTypedItem","HttpNotFoundError","additionalType","getAdditionalObject","getForm","form","property","getItem","service","getApplication","getService","PrivateContentService","formPath","Promise","resolve","reject","resolvePhysicalPath","err","physicalPath","readFileAsync","util","promisify","fs","readFile","content","buffer","Buffer","from","result","JSON","parse","toString","properties","Object","assign","name","resultType","_id","id","_event","shouldUpgrade","version","inspector","JsonFormInspector","source","view","hidden","fields","push","apply","type","getModel","editable","nullable","indexed","dataConfiguration","getConfiguration","getStrategy","DataConfigurationStrategy","privileges","splice","thisModel","Array","isArray","resultPrivileges","setModelDefinition","builder","ODataModelBuilder","addEntitySet","removeEntitySet","save","TraceUtils","error","HttpServerError","getResults","prepare","getAccessTokens","getFormAttributes","setParentLegend","dataTypes","q","asQueryable","selectArguments","attributes","forEach","attribute","key","findByKey","components","label","isNumber","legend","customProperties","prototype","hasOwnProperty","call","length","responses","select","getId","getAllItems","i","qElement","std","map","x","avg","mean","array","index","element","found","component","item","evaluate","data","HttpBadRequestError","evaluationDocument","EvaluationDocument","on","event","callback","then","access_token","expires","used","catch","generateTokens","generateOptions","items","n","newItems","itemGenerateOptions","generateManyTokens","Args","check","maximumGenerateTokens","LangUtils","parseInt","getSourceAt","module","exports"],"mappings":"aAAA;;;;;;AAMA;;;;;;;;AAQA;AACA;AACA;;;AAGA;AACA;AACA;AACA,wD,s2BAJA,MAAMA,qBAAqB,GAAGC,OAAO,CAAC,iCAAD,CAArC;AAKA,MAAMC,IAAI,GAAGD,OAAO,CAAC,QAAD,CAApB;;AAEA;AACA;AACA,G;;AAEME,e,WADLC,iBAAWC,UAAX,CAAsB,iBAAtB,C;;;;;;;;;;;;AAaID,iBAAWE,IAAX,CAAgB,SAAhB,EAA2B,iBAA3B,C;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BAF,iBAAWE,IAAX,CAAgB,MAAhB,EAAwB,QAAxB,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGAF,iBAAWE,IAAX,CAAgB,SAAhB,EAA2BC,cAAQC,YAAR,CAAqB,QAArB,CAA3B,C;;;;;;AAMAJ,iBAAWE,IAAX,CAAgB,QAAhB,EAA0BC,cAAQC,YAAR,CAAqB,uBAArB,CAA1B,C;;;;;AAKAJ,iBAAWE,IAAX,CAAgB,gBAAhB,EAAkCC,cAAQC,YAAR,CAAqB,QAArB,CAAlC,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFAJ,iBAAWK,KAAX,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A9B,EAAiC;AAC7BA,MAAAA,qBAAqB,GAAG,IAAxB;AACH;AACDF,iBAAKC,KAAL,CAAWL,CAAC,GAAGM,qBAAf,EAAuC,gEAA+DA,qBAAsB,GAA5H;AACA,UAAMP,KAAK,GAAG,EAAd;AACA;AACA,SAAK,IAAIpB,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGqB,CAA5B,EAA+BrB,KAAK,EAApC,EAAwC;AACpCoB,MAAAA,KAAK,CAACjF,IAAN,CAAW;AACPzD,QAAAA,eAAe,EAAEyI,eAAe,CAACzI,eAD1B;AAEPqI,QAAAA,OAAO,EAAEI,eAAe,CAACJ,OAFlB,EAAX;;AAIH;AACD,WAAOK,KAAP;AACH,GA7UoC,C;;AA+UzCW,MAAM,CAACC,OAAP,GAAiB7K,eAAjB","sourcesContent":["import { HttpNotFoundError, HttpTokenExpiredError, HttpServerError,\n TraceUtils, \n HttpBadRequestError,\n Args,\n LangUtils} from '@themost/common';\n\nimport {\n DataConfigurationStrategy,\n DataContext,\n DataObject,\n EdmMapping,\n EdmType,\n ODataModelBuilder\n} from '@themost/data';\nimport { HttpContext } from '@themost/web';\nimport { JsonFormInspector } from '@themost/form-inspector';\nimport EvaluationDocument from './evaluation-document-model';\n\nconst EvaluationAccessToken = require('./evaluation-access-token-model');\nimport {lt} from 'semver';\nimport util from \"util\";\nimport fs from \"fs\";\nimport moment from \"moment\";\nconst math = require('mathjs');\n\n/**\n * @class\n */\n@EdmMapping.entityType('EvaluationEvent')\nclass EvaluationEvent extends DataObject {\n /**\n * @constructor\n */\n constructor() {\n super();\n }\n\n /**\n * Get current evaluation based on the evaluation key contained in Evaluation-Key HTTP header\n * @param {HttpContext} context\n */\n @EdmMapping.func('Current', 'EvaluationEvent')\n static async getCurrent(context) {\n // get evaluation key\n const token = await EvaluationAccessToken.inspect(context, context.user && context.user.authenticationToken);\n if (token.active === false) {\n throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');\n }\n // get evaluation event\n // get current date\n const startDate = new Date(); // get current date with time\n const endDate = moment(new Date()).startOf('day').toDate(); // get only date format\n const evaluationEvent = await context.model('EvaluationEvent')\n .where('id').equal(token.sub)\n .and('date(startDate)').lowerOrEqual(startDate)\n .and('date(endDate)').greaterOrEqual(endDate)\n .and('eventStatus/alternateName').equal('EventOpened')\n .silent().getTypedItem();\n if (evaluationEvent == null) {\n throw new HttpNotFoundError('The specified evaluation cannot be found');\n }\n if (evaluationEvent.additionalType !== 'EvaluationEvent') {\n return await evaluationEvent.getAdditionalObject();\n }\n return evaluationEvent;\n }\n\n @EdmMapping.func('form', 'Object')\n async getForm() {\n const form = await this.property('evaluationDocument').getItem();\n const service = this.context.getApplication().getService(function PrivateContentService(){});\n /**\n * @type {string}\n */\n const formPath = await new Promise((resolve, reject) => {\n service.resolvePhysicalPath(this.context, form, (err, physicalPath) => {\n if (err) {\n return reject(err);\n }\n return resolve(physicalPath);\n })\n });\n const readFileAsync = util.promisify(fs.readFile);\n let content = await readFileAsync(formPath);\n if (content == null) {\n throw new HttpNotFoundError('Evaluation form cannot be found');\n }\n let buffer = Buffer.from(content,'base64');\n let result;\n result = JSON.parse(buffer.toString('utf8'));\n\n try {\n result.properties = result.properties || {};\n Object.assign(result.properties, {\n name: form.resultType,\n _id: form.id,\n _event: this.id\n });\n // post-processing\n let shouldUpgrade = true;\n let model = this.context.model(form.resultType);\n if (model != null) {\n shouldUpgrade = lt(model.version, form.version)\n }\n if (shouldUpgrade) {\n // load for inspector\n const inspector = new JsonFormInspector();\n model = inspector.inspect(result);\n // post processing steps\n Object.assign(model, {\n source: form.resultType, // add source from evaluation document e.g. Evaluation1\n view: form.resultType, // add view from evaluation document e.g. Evaluation1\n version: model.version ,// set version (follow updates)\n hidden: true\n });\n // add evaluation event and evaluation document associations\n // for further processing of evaluation results\n model.fields.push.apply(model.fields, [\n {\n name: 'evaluationEvent',\n type: this.getModel().name,\n editable: false,\n nullable: false,\n indexed: true,\n }\n ]);\n // reset privileges\n /**\n * @type {DataConfigurationStrategy|*}\n */\n const dataConfiguration = this.context.getApplication()\n .getConfiguration().getStrategy(DataConfigurationStrategy);\n\n model.privileges.splice(0);\n // get resultPrivileges\n const thisModel = dataConfiguration.model(this.getModel().name);\n\n model.privileges.push.apply(model.privileges, [\n {\n \"mask\": 15,\n \"type\": \"global\"\n },\n {\n \"mask\": 1,\n \"type\": \"global\",\n \"account\": \"Administrators\"\n }\n ]);\n // add extra privileges\n if (Array.isArray(thisModel.resultPrivileges)) {\n model.privileges.push.apply(model.privileges, thisModel.resultPrivileges);\n }\n dataConfiguration.setModelDefinition(model);\n // add entity set\n const builder = this.context.getApplication().getService(ODataModelBuilder);\n builder.addEntitySet(model.name, model.name);\n if (model.hidden) {\n builder.removeEntitySet(model.name);\n }\n // update version\n form.version= model.version;\n await this.context.model('EvaluationDocument').silent().save(form);\n }\n return result;\n } catch (err) {\n TraceUtils.error(`Error while decoding evaluation form ${form.id} content.`);\n TraceUtils.error(err);\n throw new HttpServerError('An error occurred while decoding evaluation form.');\n }\n }\n\n @EdmMapping.func('Results', EdmType.CollectionOf('Object'))\n async getResults() {\n const form = await this.getForm();\n return this.context.model(form.properties.name).where('evaluationEvent').equal(this.id).prepare();\n }\n\n @EdmMapping.func('Tokens', EdmType.CollectionOf('EvaluationAccessToken'))\n async getAccessTokens() {\n return this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.id).prepare();\n }\n\n @EdmMapping.func('FormAttributes', EdmType.CollectionOf('Object'))\n async getFormAttributes() {\n /**\n * @type {DataContext|*}\n */\n const context = this.context;\n const result = [];\n const form = await this.getForm();\n this.setParentLegend(form);\n // get model attributes\n /**\n * @type {DataConfigurationStrategy|*}\n */\n const dataConfiguration = context.getApplication()\n .getConfiguration().getStrategy(DataConfigurationStrategy);\n const dataTypes = dataConfiguration.dataTypes;\n const q = context.model(form.properties.name).asQueryable();\n const selectArguments = [];\n const model = dataConfiguration.model(form.properties.name);\n const attributes = model.fields;\n attributes.forEach(attribute => {\n const key = this.findByKey(form.components, attribute.name);\n if (key) {\n attribute = Object.assign(attribute, {\n name: attribute.name, label: key.label\n });\n attribute.isNumber = false;\n attribute.legend = key.customProperties && key.customProperties.legend;\n if (Object.prototype.hasOwnProperty.call(dataTypes, attribute.type)) {\n attribute.isNumber = dataTypes[attribute.type].type === 'number';\n }\n selectArguments.push(`${attribute.name}`);\n result.push(attribute);\n }\n\n });\n if (selectArguments.length) {\n const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').equal(this.getId()).silent().getAllItems();\n for (let i = 0; i < result.length; i++) {\n const qElement = result[i];\n qElement.responses=[];\n if (qElement.isNumber) {\n // add mean value and standard deviation\n qElement.std = responses.length? math.std(responses.map(x => {\n return x[qElement.name];\n })):0;\n qElement.avg = responses.length? math.mean(responses.map(x => {\n return x[qElement.name];\n })):0;\n } else {\n qElement.responses = responses.map(x => {\n return x[qElement.name];\n });\n }\n }\n }\n return result;\n }\n\n findByKey(array, key) {\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n if (element.key === key) {\n return element;\n } else {\n if (element.components) {\n const found = this.findByKey(element.components, key);\n if (found) {\n return found;\n }\n }\n }\n }\n }\n\n setParentLegend(component) {\n if (Array.isArray(component.components)) {\n component.components.forEach(item => {\n if (component.legend) {\n item.customProperties = item.customProperties || {};\n item.customProperties.legend = component.legend;\n }\n this.setParentLegend(item);\n });\n }\n }\n\n @EdmMapping.param('data', 'Object', false, true)\n @EdmMapping.action('Evaluate', 'Object')\n async evaluate(data) {\n const token = await EvaluationAccessToken.inspect(this.context, this.context.user.authenticationToken);\n if (token.active === false) {\n throw new HttpTokenExpiredError('Evaluation access token has been expired or is invalid.');\n }\n if (this.id !== token.sub) {\n throw new HttpBadRequestError('Evaluation access token is invalid');\n }\n // get evaluation form\n const form = await this.getForm();\n // get evaluation document\n if (form == null) {\n throw new HttpNotFoundError('Evaluation form cannot be found');\n }\n // get evaluation document\n const evaluationDocument = await this.context.model(EvaluationDocument)\n .where('id').equal(form.properties._id)\n .silent().getItem();\n if (evaluationDocument == null) {\n throw new HttpNotFoundError('Evaluation document cannot be found');\n }\n // assign defaults\n Object.assign(data, {\n evaluationEvent: this.id,\n evaluationDocument: evaluationDocument.id\n });\n // and finally append evaluation\n await this.context.model(evaluationDocument.resultType).on('after.save', (event, callback) => {\n const context = event.model.context;\n context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken)\n .silent().getItem().then((token) => {\n if (token == null) {\n throw new HttpTokenExpiredError('Evaluation token is required');\n }\n return context.model(EvaluationAccessToken).silent().save({\n access_token: token.access_token,\n expires: new Date(0), // set epoch date\n used: true\n });\n }).then(() => {\n return callback();\n }).catch((err) => {\n TraceUtils.error('An error occurred while submitting evaluation');\n return callback(err);\n });\n }).silent().save(data);\n return data;\n }\n\n static async generateTokens(context, generateOptions) {\n let items = [];\n if (Array.isArray(generateOptions)) {\n let n = 0;\n let newItems;\n // eslint-disable-next-line no-unused-vars\n for(let itemGenerateOptions of generateOptions) {\n newItems = await EvaluationEvent.generateManyTokens(context, itemGenerateOptions);\n n += newItems.length;\n items.push.apply(items, newItems);\n }\n await context.model('EvaluationAccessToken').save(items);\n return n\n } else {\n items = await EvaluationEvent.generateManyTokens(context, generateOptions);\n await context.model('EvaluationAccessToken').save(items);\n return items.length;\n } \n }\n /**\n * Generates a number of access tokens for the given event \n * @param {DataContext} context\n * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions\n */\n static async generateManyTokens(context, generateOptions) {\n const n = generateOptions.n;\n Args.check(typeof n === 'number', 'Expected a number greater than zero');\n Args.check(n > 0, 'The number of access tokens must be greater than zero');\n let maximumGenerateTokens = LangUtils.parseInt(context.getConfiguration().getSourceAt('settings/evaluation/maximumGenerateTokens'));\n if (maximumGenerateTokens === 0) {\n maximumGenerateTokens = 1000;\n }\n Args.check(n < maximumGenerateTokens, `The specified number of tokens exceeded the maximum allowed (${maximumGenerateTokens})`);\n const items = [];\n // generate tokens\n for (let index = 0; index < n; index++) {\n items.push({\n evaluationEvent: generateOptions.evaluationEvent,\n expires: generateOptions.expires\n });\n }\n return items;\n }\n}\nmodule.exports = EvaluationEvent;\n"],"file":"evaluation-event-model.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@universis/evaluations",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "description": "Universis evaluations library",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -6,7 +6,8 @@
6
6
  "abstract": false,
7
7
  "sealed": false,
8
8
  "inherits": "EvaluationEvent",
9
- "version": "1.0",
9
+ "classPath": "./models/class-instructor-evaluation-event-model",
10
+ "version": "1.1",
10
11
  "fields": [
11
12
  {
12
13
  "@id": "http://schema.org/courseClassInstructor",
@@ -14,12 +15,7 @@
14
15
  "title": "Course Class Instructor",
15
16
  "type": "CourseClassInstructor",
16
17
  "nullable": false,
17
- "expandable": true,
18
- "mapping": {
19
- "options": {
20
- "$expand": "courseClass,instructor"
21
- }
22
- }
18
+ "expandable": true
23
19
  },
24
20
  {
25
21
  "@id": "http://schema.org/organizer",
@@ -36,9 +32,47 @@
36
32
  "type": "Text",
37
33
  "readonly": true,
38
34
  "value": "javascript:return this.model.name;"
35
+ },
36
+ {
37
+ "name": "tokens",
38
+ "title": "Evaluation tokens",
39
+ "type": "EvaluationAccessToken",
40
+ "many": true,
41
+ "mapping": {
42
+ "parentModel": "ClassInstructorEvaluationEvent",
43
+ "childModel": "EvaluationAccessToken",
44
+ "parentField": "id",
45
+ "childField": "evaluationEvent",
46
+ "cascade": "delete",
47
+ "associationType": "association"
48
+ }
49
+ },
50
+ {
51
+ "name": "actions",
52
+ "title": "Generate token actions",
53
+ "type": "GenerateTokenAction",
54
+ "many": true,
55
+ "mapping": {
56
+ "parentModel": "ClassInstructorEvaluationEvent",
57
+ "childModel": "GenerateTokenAction",
58
+ "parentField": "id",
59
+ "childField": "event",
60
+ "cascade": "delete",
61
+ "associationType": "association"
62
+ }
63
+ },
64
+ {
65
+ "name": "numberOfStudents",
66
+ "title": "Μέγιστος αριθμός φοιτητών",
67
+ "description": "Αριθμός φοιτητών που μπορούν να αξιολογήσουν",
68
+ "type": "Integer",
69
+ "nullable": true
39
70
  }
40
71
  ],
41
72
  "eventListeners": [
73
+ {
74
+ "type": "@themost/data/previous-state-listener"
75
+ },
42
76
  {
43
77
  "type": "./listeners/class-instructor-event-listener"
44
78
  }
@@ -8,7 +8,7 @@
8
8
  "sealed": false,
9
9
  "hidden": false,
10
10
  "inherits": "AccessToken",
11
- "version": "1.0",
11
+ "version": "1.2",
12
12
  "classPath": "./models/evaluation-access-token-model",
13
13
  "fields": [
14
14
  {
@@ -78,6 +78,21 @@
78
78
  "title": "Web Application",
79
79
  "type": "Text",
80
80
  "nullable": true
81
+ },
82
+ {
83
+ "@id": "https://themost.io/sent",
84
+ "name": "sent",
85
+ "title": "Token sent",
86
+ "description": "A boolean which represents whether the token has been sent",
87
+ "type": "Boolean",
88
+ "value": "javascript:return 0;"
89
+ },
90
+ {
91
+ "name": "used",
92
+ "title": "Token used",
93
+ "description": "A boolean which represents whether the token has been used",
94
+ "type": "Boolean",
95
+ "value": "javascript:return 0;"
81
96
  }
82
97
  ],
83
98
  "constraints": [
@@ -0,0 +1,40 @@
1
+ {
2
+ "$schema": "https://themost-framework.github.io/themost/models/2018/2/schema.json",
3
+ "@id": "http://schema.org/GenerateInstructorTokenAction",
4
+ "name": "GenerateInstructorTokenAction",
5
+ "description": "The act of organizing tasks/objects/events by associating resources to it.",
6
+ "title": "GenerateInstructorTokenAction",
7
+ "abstract": false,
8
+ "sealed": false,
9
+ "inherits": "GenerateTokenAction",
10
+ "version": "1.0",
11
+ "fields": [
12
+ {
13
+ "name": "event",
14
+ "title": "Γεγονός αξιολόγησης",
15
+ "type": "ClassInstructorEvaluationEvent",
16
+ "nullable": false
17
+ },
18
+ {
19
+ "name": "numberOfStudents",
20
+ "description": "Σύνολο φοιτητών",
21
+ "type": "Integer"
22
+ },
23
+ {
24
+ "name": "total",
25
+ "description": "Σύνολο tokens που δημιουργήθηκαν",
26
+ "type": "Integer"
27
+ }
28
+ ],
29
+ "privileges": [
30
+ {
31
+ "mask": 15,
32
+ "type": "global"
33
+ },
34
+ {
35
+ "mask": 15,
36
+ "type": "global",
37
+ "account": "Administrators"
38
+ }
39
+ ]
40
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "$schema": "https://themost-framework.github.io/themost/models/2018/2/schema.json",
3
+ "@id": "http://schema.org/GenerateTokenAction",
4
+ "name": "GenerateTokenAction",
5
+ "description": "The act of organizing tasks/objects/events by associating resources to it.",
6
+ "title": "GenerateTokenAction",
7
+ "abstract": false,
8
+ "sealed": false,
9
+ "inherits": "Action",
10
+ "version": "1.0",
11
+ "fields": [
12
+ {
13
+ "name": "event",
14
+ "title": "Γεγονός αξιολόγησης",
15
+ "type": "EvaluationEvent",
16
+ "nullable": false
17
+ },
18
+ {
19
+ "name": "total",
20
+ "description": "Σύνολο tokens που δημιουργήθηκαν",
21
+ "type": "Integer"
22
+ }
23
+ ],
24
+ "privileges": [
25
+ {
26
+ "mask": 15,
27
+ "type": "global"
28
+ },
29
+ {
30
+ "mask": 15,
31
+ "type": "global",
32
+ "account": "Administrators"
33
+ }
34
+ ]
35
+ }
package/src/index.js CHANGED
@@ -1,2 +1,4 @@
1
1
  export * from './EvaluationSchemaLoader';
2
2
  export * from './EvaluationService';
3
+ export * from './evaluationRouter';
4
+ export EvaluationDocument from './models/evaluation-document-model';
@@ -12,6 +12,30 @@ async function beforeSaveAsync(event) {
12
12
  .select('courseClass/course/department').value();
13
13
  event.target.organizer = organizer;
14
14
  }
15
+ if (event.state===DataObjectState.Update)
16
+ {
17
+ const previous = event.previous;
18
+ // check if endDate is changed and update expired field for tokens
19
+ if (event.target.endDate) {
20
+ const prevEndDate = event.previous.endDate;
21
+ const endDate = event.target.endDate;
22
+ prevEndDate.setHours(0, 0, 0, 0);
23
+ endDate.setHours(0, 0, 0, 0);
24
+ if (prevEndDate-endDate!==0) {
25
+ let tokens = await context.model('EvaluationAccessToken').where('evaluationEvent').equal(event.target.id)
26
+ .and('used').notEqual(1)
27
+ .silent().getItems();
28
+ if (tokens.length > 0) {
29
+ tokens = tokens.map(x => {
30
+ x.expires = event.target.endDate;
31
+ return x;
32
+ });
33
+ // update tokens
34
+ await context.model('EvaluationAccessToken').silent().save(tokens);
35
+ }
36
+ }
37
+ }
38
+ }
15
39
  }
16
40
  /**
17
41
  * @param {DataEventArgs} event