@universis/evaluations 1.0.10 → 1.0.12

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.
@@ -4,6 +4,8 @@
4
4
 
5
5
 
6
6
 
7
+
8
+
7
9
  var _data = require("@themost/data");
8
10
 
9
11
 
@@ -20,7 +22,7 @@ var _evaluationDocumentModel = _interopRequireDefault(require("./evaluation-docu
20
22
  var _semver = require("semver");
21
23
  var _util = _interopRequireDefault(require("util"));
22
24
  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');
25
+ var _moment = _interopRequireDefault(require("moment"));var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _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
26
  const math = require('mathjs');
25
27
 
26
28
  /**
@@ -209,6 +211,58 @@ _data.EdmMapping.func('FormAttributes', _data.EdmType.CollectionOf('Object')), _
209
211
 
210
212
 
211
213
 
214
+ _data.EdmMapping.func('FormAttributesSummary', _data.EdmType.CollectionOf('Object')), _dec8 =
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
212
266
 
213
267
 
214
268
 
@@ -321,7 +375,56 @@ _data.EdmMapping.func('FormAttributes', _data.EdmType.CollectionOf('Object')), _
321
375
 
322
376
 
323
377
 
324
- _data.EdmMapping.param('data', 'Object', false, true), _dec8 =
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
410
+
411
+
412
+
413
+
414
+
415
+
416
+
417
+
418
+
419
+
420
+
421
+
422
+
423
+
424
+
425
+
426
+
427
+ _data.EdmMapping.param('data', 'Object', false, true), _dec9 =
325
428
  _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class EvaluationEvent extends _data.DataObject {/**
326
429
  * @constructor
327
430
  */constructor() {super();} /**
@@ -350,12 +453,19 @@ _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class Ev
350
453
  const builder = this.context.getApplication().getService(_data.ODataModelBuilder);builder.addEntitySet(model.name, model.name);if (model.hidden) {builder.removeEntitySet(model.name);} // update version
351
454
  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() {/**
352
455
  * @type {DataContext|*}
353
- */const context = this.context;const result = [];const form = await this.getForm();this.setParentLegend(form); // get model attributes
456
+ */const context = this.context;const results = await this.getFormResults(context, this.getId(), null);return results.responses;}async getFormAttributesSummary() {/**
457
+ * @type {DataContext|*}
458
+ */const context = this.context;const eventModel = this.getModel().name;const results = await this.getFormResults(context, this.getId(), null);let q = this.context.model(eventModel).where('id').equal(this.getId()).expand({ 'name': 'tokens', 'options': { '$select': 'evaluationEvent,count(evaluationEvent) as total,used', '$groupby': 'evaluationEvent,used' } }, 'organizer');if (eventModel === 'ClassInstructorEvaluationEvent') {q = this.context.model(eventModel).where('id').equal(this.getId()).expand({ 'name': 'tokens', 'options': { '$select': 'evaluationEvent,count(evaluationEvent) as total,used', '$groupby': 'evaluationEvent,used' } }, { 'name': 'courseClassInstructor', 'options': { '$expand': 'courseClass($expand=year,period,course($expand=department)),instructor' } });}results.event = await q.getItem();if (results.event == null) {throw new _common.DataNotFoundError('Evaluation event not found.');} // count used tokens of event
459
+ if (results.event.tokens) {const usedTokens = results.event.tokens && results.event.tokens.find((x) => {return x.used === true;});results.event.tokensUsed = usedTokens ? usedTokens.total : 0;} // get avg of questions avg
460
+ results.event.responsesAvg = results.responses.length ? math.mean(results.responses.map((x) => {return x.avg;})) : 0;return results;}async getFormResults(context, id, events) {const result = [];const evaluationEvents = [];if (id) {evaluationEvents.push(id);} else {if (Array.isArray(events) && events.length) {evaluationEvents.push.apply(evaluationEvents, events.map((x) => {return x.id || x;}));}}if (evaluationEvents.length === 0) {throw new _common.DataError('Evaluation events not supplied.');}const form = await this.getForm();this.setParentLegend(form); // get model attributes
354
461
  /**
355
462
  * @type {DataConfigurationStrategy|*}
356
- */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}`); // clear std,avg and responses from model attribute
357
- attribute.std = 0;attribute.avg = 0;delete attribute.responses;result.push(attribute);}});const showResults = await this.showResults(context);if (selectArguments.length && showResults === true) {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
358
- 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;}async showResults(context) {// this is a custom way to get permissions based on eventStatus and user groups
463
+ */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;let totalResponses = 0;const summaryValues = [];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}`); // clear std,avg and responses from model attribute
464
+ attribute.std = 0;attribute.avg = 0;delete attribute.responses;if (attribute.isNumber && key.type === 'radio') {if (summaryValues.length === 0) {// add radio values from first key
465
+ summaryValues.push.apply(summaryValues, key.values);} else {//add values only if not exist
466
+ summaryValues.push.apply(summaryValues, key.values.filter((x) => {return summaryValues.findIndex((y) => {return y.value === x.value;}) < 0;}));}}result.push(attribute);}}); // add total = 0 to summaryValues
467
+ summaryValues.map((x) => {x.total = 0;return x;});const showResults = await this.showResults(context);if (selectArguments.length && showResults === true) {const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').in(evaluationEvents).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
468
+ 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;summaryValues.forEach((radioValue) => {const result = responses.filter((y) => {return y[qElement.name] == radioValue.value;}).length;radioValue.total += result;totalResponses += result;});} else {qElement.responses = responses.map((x) => {return x[qElement.name];});}}}const results = {};results.responses = result;results.summaryValues = [];results.summaryValues.push.apply(results.summaryValues, summaryValues.map((x) => {x.totalResponses = totalResponses;return x;}));return results;}async showResults(context) {// this is a custom way to get permissions based on eventStatus and user groups
359
469
  let showResults = true;let found = false;const eventStatusesResults = context.getConfiguration().getSourceAt('settings/evaluation/results/statuses') || [];const groupsAllowed = context.getConfiguration().getSourceAt('settings/evaluation/results/groupsAllowed') || [];if (eventStatusesResults.length > 0) {// check if eventStatus is allowed
360
470
  if (groupsAllowed.length > 0) {// but first check if user belongs to allowed groups
361
471
  const userName = context.interactiveUser ? context.interactiveUser.name : context.user.name;const user = await context.model('User').where('name').equal(userName).expand('groups').getItem();found = user.groups.some((r) => groupsAllowed.indexOf(r.name) >= 0);}if (!found) {const evaluationEvent = await context.model('EvaluationEvent').where('id').equal(this.getId()).select('id', 'eventStatus/alternateName as eventStatus').getItem();if (evaluationEvent == null) {throw new _common.HttpNotFoundError('The specified evaluation cannot be found');}showResults = eventStatusesResults.findIndex((x) => {return x === evaluationEvent.eventStatus;}) >= 0;}}return showResults;}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
@@ -364,14 +474,7 @@ _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class Ev
364
474
  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
365
475
  Object.assign(data, { evaluationEvent: this.id, evaluationDocument: evaluationDocument.id }); // and finally append evaluation
366
476
  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
367
- used: true });}).then(() => {return callback();}).catch((err) => {
368
- _common.TraceUtils.error('An error occurred while submitting evaluation');
369
- return callback(err);
370
- });
371
- }).silent().save(data);
372
- return data;
373
- }
374
-
477
+ used: true });}).then(() => {return callback();}).catch((err) => {_common.TraceUtils.error('An error occurred while submitting evaluation');return callback(err);});}).silent().save(data);return data;}
375
478
  static async generateTokens(context, generateOptions) {
376
479
  let items = [];
377
480
  if (Array.isArray(generateOptions)) {
@@ -392,7 +495,7 @@ _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class Ev
392
495
  }
393
496
  }
394
497
  /**
395
- * Generates a number of access tokens for the given event
498
+ * Generates a number of access tokens for the given event
396
499
  * @param {DataContext} context
397
500
  * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions
398
501
  */
@@ -414,7 +517,7 @@ _data.EdmMapping.action('Evaluate', 'Object'), _dec(_class = (_class2 = class Ev
414
517
 
415
518
  }
416
519
  return items;
417
- }}, (_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);
520
+ }}, (_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, "getFormAttributesSummary", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "getFormAttributesSummary"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "evaluate", [_dec8, _dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "evaluate"), _class2.prototype)), _class2)) || _class);
418
521
 
419
522
  module.exports = EvaluationEvent;
420
523
  //# sourceMappingURL=evaluation-event-model.js.map
@@ -1 +1 @@
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","evaluationEvent","model","where","equal","sub","and","silent","getTypedItem","HttpNotFoundError","currentDate","Date","setHours","startDate","endDate","additionalType","event","expand","name","options","$expand","courseClass","courseClassInstructor","instructor","course","displayCode","title","year","alternateName","period","familyName","givenName","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","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","std","avg","responses","showResults","length","select","getId","getAllItems","i","qElement","map","x","mean","found","eventStatusesResults","getSourceAt","groupsAllowed","userName","interactiveUser","groups","some","r","indexOf","findIndex","eventStatus","array","index","element","component","item","evaluate","data","HttpBadRequestError","evaluationDocument","EvaluationDocument","on","callback","then","access_token","expires","used","catch","generateTokens","generateOptions","items","n","newItems","itemGenerateOptions","generateManyTokens","Args","check","maximumGenerateTokens","LangUtils","parseInt","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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CAF,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAA1B;AACAI,iBAAKC,KAAL,CAAW,OAAOL,CAAP,KAAa,QAAxB,EAAkC,qCAAlC;AACAI,iBAAKC,KAAL,CAAWL,CAAC,GAAG,CAAf,EAAkB,uDAAlB;AACA,QAAIM,qBAAqB,GAAGC,kBAAUC,QAAV,CAAmBvL,OAAO,CAAC0F,gBAAR,GAA2BuD,WAA3B,CAAuC,2CAAvC,CAAnB,CAA5B;AACA,QAAIoC,qBAAqB,KAAK,CAA9B,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,IAAIlB,KAAK,GAAG,CAAjB,EAAoBA,KAAK,GAAGmB,CAA5B,EAA+BnB,KAAK,EAApC,EAAwC;AACpCkB,MAAAA,KAAK,CAAC5F,IAAN,CAAW;AACP3E,QAAAA,eAAe,EAAEsK,eAAe,CAACtK,eAD1B;AAEPkK,QAAAA,OAAO,EAAEI,eAAe,CAACJ,OAFlB,EAAX;;AAIH;AACD,WAAOK,KAAP;AACH,GAnYoC,C;;AAqYzCU,MAAM,CAACC,OAAP,GAAiBpM,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 let evaluationEvent = await context.model('EvaluationEvent')\n .where('id').equal(token.sub)\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 // check dates\n const currentDate = new Date().setHours(0,0,0,0);\n const startDate = evaluationEvent.startDate.setHours(0,0,0,0);\n const endDate = evaluationEvent.endDate.setHours(0,0,0,0);\n if (startDate>currentDate || endDate<currentDate) {\n throw new HttpNotFoundError('The specified evaluation cannot be found, it is expired or not started.');\n }\n if (evaluationEvent.additionalType !== 'EvaluationEvent') {\n if (evaluationEvent.additionalType === 'ClassInstructorEvaluationEvent') {\n const event = await context.model('ClassInstructorEvaluationEvent')\n .where('id').equal(token.sub)\n .expand({\n name: 'courseClassInstructor',\n options: {\n $expand: 'courseClass($expand=course,year,period),instructor'\n }\n })\n .silent().getTypedItem();\n const courseClass= event.courseClassInstructor.courseClass;\n const instructor = event.courseClassInstructor.instructor;\n evaluationEvent.courseClass = `${courseClass.course.displayCode}-${courseClass.title} (${courseClass.year.alternateName}-${courseClass.period.name}) `;\n evaluationEvent.instructor = `${instructor.familyName} ${instructor.givenName}`;\n } else {\n evaluationEvent = await evaluationEvent.silent().getAdditionalObject();\n }\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 // clear std,avg and responses from model attribute\n attribute.std = 0;\n attribute.avg = 0;\n delete attribute.responses;\n result.push(attribute);\n }\n\n });\n const showResults = await this.showResults(context);\n if (selectArguments.length && showResults === true) {\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 async showResults (context) {\n\n // this is a custom way to get permissions based on eventStatus and user groups\n let showResults = true;\n let found = false;\n const eventStatusesResults = context.getConfiguration().getSourceAt('settings/evaluation/results/statuses') || [];\n const groupsAllowed = context.getConfiguration().getSourceAt('settings/evaluation/results/groupsAllowed') || [];\n if (eventStatusesResults.length > 0) {\n // check if eventStatus is allowed\n if (groupsAllowed.length > 0) {\n // but first check if user belongs to allowed groups\n const userName = context.interactiveUser ? context.interactiveUser.name : context.user.name;\n const user = await context.model('User').where('name').equal(userName).expand('groups').getItem();\n found = user.groups.some(r => groupsAllowed.indexOf(r.name) >= 0);\n }\n if (!found) {\n const evaluationEvent = await context.model('EvaluationEvent').where('id').equal(this.getId())\n .select('id', 'eventStatus/alternateName as eventStatus')\n .getItem();\n if (evaluationEvent == null) {\n throw new HttpNotFoundError('The specified evaluation cannot be found');\n }\n showResults = eventStatusesResults.findIndex(x => {\n return x === evaluationEvent.eventStatus;\n }) >= 0;\n }\n }\n return showResults;\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').silent().save(items);\n return n\n } else {\n items = await EvaluationEvent.generateManyTokens(context, generateOptions);\n await context.model('EvaluationAccessToken').silent().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"}
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","evaluationEvent","model","where","equal","sub","and","silent","getTypedItem","HttpNotFoundError","currentDate","Date","setHours","startDate","endDate","additionalType","event","expand","name","options","$expand","courseClass","courseClassInstructor","instructor","course","displayCode","title","year","alternateName","period","familyName","givenName","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","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","results","getFormResults","getId","responses","getFormAttributesSummary","eventModel","q","DataNotFoundError","tokens","usedTokens","find","x","used","tokensUsed","total","responsesAvg","length","mean","map","avg","events","evaluationEvents","DataError","setParentLegend","dataTypes","asQueryable","selectArguments","attributes","totalResponses","summaryValues","forEach","attribute","key","findByKey","components","label","isNumber","legend","customProperties","prototype","hasOwnProperty","call","std","values","filter","findIndex","y","value","showResults","select","in","getAllItems","i","qElement","radioValue","found","eventStatusesResults","getSourceAt","groupsAllowed","userName","interactiveUser","groups","some","r","indexOf","eventStatus","array","index","element","component","item","evaluate","data","HttpBadRequestError","evaluationDocument","EvaluationDocument","on","callback","then","access_token","expires","catch","generateTokens","generateOptions","items","n","newItems","itemGenerateOptions","generateManyTokens","Args","check","maximumGenerateTokens","LangUtils","parseInt","module","exports"],"mappings":"aAAA;;;;;;;;AAQA;;;;;;;;AAQA;AACA;AACA;;;AAGA;AACA;AACA;AACA,wD,62BAJA,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CAF,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;;;;;;;;;;AAUAJ,iBAAWE,IAAX,CAAgB,uBAAhB,EAAyCC,cAAQC,YAAR,CAAqB,QAArB,CAAzC,C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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estError,\n Args,\n LangUtils, DataError, DataNotFoundError\n} 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 let evaluationEvent = await context.model('EvaluationEvent')\n .where('id').equal(token.sub)\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 // check dates\n const currentDate = new Date().setHours(0,0,0,0);\n const startDate = evaluationEvent.startDate.setHours(0,0,0,0);\n const endDate = evaluationEvent.endDate.setHours(0,0,0,0);\n if (startDate>currentDate || endDate<currentDate) {\n throw new HttpNotFoundError('The specified evaluation cannot be found, it is expired or not started.');\n }\n if (evaluationEvent.additionalType !== 'EvaluationEvent') {\n if (evaluationEvent.additionalType === 'ClassInstructorEvaluationEvent') {\n const event = await context.model('ClassInstructorEvaluationEvent')\n .where('id').equal(token.sub)\n .expand({\n name: 'courseClassInstructor',\n options: {\n $expand: 'courseClass($expand=course,year,period),instructor'\n }\n })\n .silent().getTypedItem();\n const courseClass= event.courseClassInstructor.courseClass;\n const instructor = event.courseClassInstructor.instructor;\n evaluationEvent.courseClass = `${courseClass.course.displayCode}-${courseClass.title} (${courseClass.year.alternateName}-${courseClass.period.name}) `;\n evaluationEvent.instructor = `${instructor.familyName} ${instructor.givenName}`;\n } else {\n evaluationEvent = await evaluationEvent.silent().getAdditionalObject();\n }\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 results = await this.getFormResults (context,this.getId(),null);\n return results.responses;\n }\n\n @EdmMapping.func('FormAttributesSummary', EdmType.CollectionOf('Object'))\n async getFormAttributesSummary() {\n /**\n * @type {DataContext|*}\n */\n const context = this.context;\n const eventModel = this.getModel().name;\n const results = await this.getFormResults(context, this.getId(), null);\n let q = this.context.model(eventModel).where('id').equal(this.getId()).expand({\n 'name': 'tokens',\n 'options': {\n '$select': 'evaluationEvent,count(evaluationEvent) as total,used',\n '$groupby': 'evaluationEvent,used'\n }},'organizer');\n if (eventModel==='ClassInstructorEvaluationEvent') {\n q = this.context.model(eventModel).where('id').equal(this.getId()).expand({\n 'name': 'tokens',\n 'options': {\n '$select': 'evaluationEvent,count(evaluationEvent) as total,used',\n '$groupby': 'evaluationEvent,used'\n }\n }\n , {\n 'name': 'courseClassInstructor',\n 'options': {\n '$expand': 'courseClass($expand=year,period,course($expand=department)),instructor'\n }\n });\n }\n results.event = await q.getItem();\n if (results.event==null) {\n throw new DataNotFoundError('Evaluation event not found.');\n }\n // count used tokens of event\n if (results.event.tokens) {\n const usedTokens = results.event.tokens && results.event.tokens.find(x => {\n return x.used === true;\n });\n results.event.tokensUsed = usedTokens ? usedTokens.total : 0;\n }\n // get avg of questions avg\n results.event.responsesAvg = results.responses.length ? math.mean(results.responses.map(x => {\n return x.avg;\n })) : 0;\n return results;\n }\n\n async getFormResults (context, id, events)\n {\n const result = [];\n const evaluationEvents = [];\n if (id)\n {evaluationEvents.push(id);}\n else {\n if (Array.isArray(events) && events.length) {\n evaluationEvents.push.apply(evaluationEvents, events.map(x => {\n return x.id || x;\n }));\n }\n }\n if (evaluationEvents.length===0)\n {\n throw new DataError('Evaluation events not supplied.');\n }\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 let totalResponses = 0;\n const summaryValues = [];\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 // clear std,avg and responses from model attribute\n attribute.std = 0;\n attribute.avg = 0;\n delete attribute.responses;\n if (attribute.isNumber && key.type === 'radio') {\n if (summaryValues.length === 0) {\n // add radio values from first key\n summaryValues.push.apply(summaryValues, key.values);\n } else {\n //add values only if not exist\n summaryValues.push.apply(summaryValues, key.values.filter(x => {\n return summaryValues.findIndex(y => {\n return y.value === x.value\n }) < 0;\n }));\n }\n }\n result.push(attribute);\n }\n\n });\n // add total = 0 to summaryValues\n summaryValues.map(x => {\n x.total = 0;\n return x;\n });\n const showResults = await this.showResults(context);\n if (selectArguments.length && showResults === true) {\n const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').in(evaluationEvents).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 summaryValues.forEach(radioValue => {\n const result = responses.filter(y => {\n return y[qElement.name] == radioValue.value;\n }).length;\n radioValue.total += result;\n totalResponses += result;\n });\n } else {\n qElement.responses = responses.map(x => {\n return x[qElement.name];\n });\n }\n }\n }\n const results={};\n results.responses = result;\n results.summaryValues = [];\n results.summaryValues.push.apply(results.summaryValues, summaryValues.map(x=>{\n x.totalResponses= totalResponses;\n return x;\n }));\n return results;\n }\n\n async showResults (context) {\n\n // this is a custom way to get permissions based on eventStatus and user groups\n let showResults = true;\n let found = false;\n const eventStatusesResults = context.getConfiguration().getSourceAt('settings/evaluation/results/statuses') || [];\n const groupsAllowed = context.getConfiguration().getSourceAt('settings/evaluation/results/groupsAllowed') || [];\n if (eventStatusesResults.length > 0) {\n // check if eventStatus is allowed\n if (groupsAllowed.length > 0) {\n // but first check if user belongs to allowed groups\n const userName = context.interactiveUser ? context.interactiveUser.name : context.user.name;\n const user = await context.model('User').where('name').equal(userName).expand('groups').getItem();\n found = user.groups.some(r => groupsAllowed.indexOf(r.name) >= 0);\n }\n if (!found) {\n const evaluationEvent = await context.model('EvaluationEvent').where('id').equal(this.getId())\n .select('id', 'eventStatus/alternateName as eventStatus')\n .getItem();\n if (evaluationEvent == null) {\n throw new HttpNotFoundError('The specified evaluation cannot be found');\n }\n showResults = eventStatusesResults.findIndex(x => {\n return x === evaluationEvent.eventStatus;\n }) >= 0;\n }\n }\n return showResults;\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').silent().save(items);\n return n\n } else {\n items = await EvaluationEvent.generateManyTokens(context, generateOptions);\n await context.model('EvaluationAccessToken').silent().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.10",
3
+ "version": "1.0.12",
4
4
  "description": "Universis evaluations library",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -1,8 +1,10 @@
1
- import { HttpNotFoundError, HttpTokenExpiredError, HttpServerError,
2
- TraceUtils,
1
+ import {
2
+ HttpNotFoundError, HttpTokenExpiredError, HttpServerError,
3
+ TraceUtils,
3
4
  HttpBadRequestError,
4
5
  Args,
5
- LangUtils} from '@themost/common';
6
+ LangUtils, DataError, DataNotFoundError
7
+ } from '@themost/common';
6
8
 
7
9
  import {
8
10
  DataConfigurationStrategy,
@@ -205,7 +207,74 @@ class EvaluationEvent extends DataObject {
205
207
  * @type {DataContext|*}
206
208
  */
207
209
  const context = this.context;
210
+ const results = await this.getFormResults (context,this.getId(),null);
211
+ return results.responses;
212
+ }
213
+
214
+ @EdmMapping.func('FormAttributesSummary', EdmType.CollectionOf('Object'))
215
+ async getFormAttributesSummary() {
216
+ /**
217
+ * @type {DataContext|*}
218
+ */
219
+ const context = this.context;
220
+ const eventModel = this.getModel().name;
221
+ const results = await this.getFormResults(context, this.getId(), null);
222
+ let q = this.context.model(eventModel).where('id').equal(this.getId()).expand({
223
+ 'name': 'tokens',
224
+ 'options': {
225
+ '$select': 'evaluationEvent,count(evaluationEvent) as total,used',
226
+ '$groupby': 'evaluationEvent,used'
227
+ }},'organizer');
228
+ if (eventModel==='ClassInstructorEvaluationEvent') {
229
+ q = this.context.model(eventModel).where('id').equal(this.getId()).expand({
230
+ 'name': 'tokens',
231
+ 'options': {
232
+ '$select': 'evaluationEvent,count(evaluationEvent) as total,used',
233
+ '$groupby': 'evaluationEvent,used'
234
+ }
235
+ }
236
+ , {
237
+ 'name': 'courseClassInstructor',
238
+ 'options': {
239
+ '$expand': 'courseClass($expand=year,period,course($expand=department)),instructor'
240
+ }
241
+ });
242
+ }
243
+ results.event = await q.getItem();
244
+ if (results.event==null) {
245
+ throw new DataNotFoundError('Evaluation event not found.');
246
+ }
247
+ // count used tokens of event
248
+ if (results.event.tokens) {
249
+ const usedTokens = results.event.tokens && results.event.tokens.find(x => {
250
+ return x.used === true;
251
+ });
252
+ results.event.tokensUsed = usedTokens ? usedTokens.total : 0;
253
+ }
254
+ // get avg of questions avg
255
+ results.event.responsesAvg = results.responses.length ? math.mean(results.responses.map(x => {
256
+ return x.avg;
257
+ })) : 0;
258
+ return results;
259
+ }
260
+
261
+ async getFormResults (context, id, events)
262
+ {
208
263
  const result = [];
264
+ const evaluationEvents = [];
265
+ if (id)
266
+ {evaluationEvents.push(id);}
267
+ else {
268
+ if (Array.isArray(events) && events.length) {
269
+ evaluationEvents.push.apply(evaluationEvents, events.map(x => {
270
+ return x.id || x;
271
+ }));
272
+ }
273
+ }
274
+ if (evaluationEvents.length===0)
275
+ {
276
+ throw new DataError('Evaluation events not supplied.');
277
+ }
209
278
  const form = await this.getForm();
210
279
  this.setParentLegend(form);
211
280
  // get model attributes
@@ -219,6 +288,8 @@ class EvaluationEvent extends DataObject {
219
288
  const selectArguments = [];
220
289
  const model = dataConfiguration.model(form.properties.name);
221
290
  const attributes = model.fields;
291
+ let totalResponses = 0;
292
+ const summaryValues = [];
222
293
  attributes.forEach(attribute => {
223
294
  const key = this.findByKey(form.components, attribute.name);
224
295
  if (key) {
@@ -235,13 +306,31 @@ class EvaluationEvent extends DataObject {
235
306
  attribute.std = 0;
236
307
  attribute.avg = 0;
237
308
  delete attribute.responses;
309
+ if (attribute.isNumber && key.type === 'radio') {
310
+ if (summaryValues.length === 0) {
311
+ // add radio values from first key
312
+ summaryValues.push.apply(summaryValues, key.values);
313
+ } else {
314
+ //add values only if not exist
315
+ summaryValues.push.apply(summaryValues, key.values.filter(x => {
316
+ return summaryValues.findIndex(y => {
317
+ return y.value === x.value
318
+ }) < 0;
319
+ }));
320
+ }
321
+ }
238
322
  result.push(attribute);
239
323
  }
240
324
 
241
325
  });
242
- const showResults = await this.showResults(context);
326
+ // add total = 0 to summaryValues
327
+ summaryValues.map(x => {
328
+ x.total = 0;
329
+ return x;
330
+ });
331
+ const showResults = await this.showResults(context);
243
332
  if (selectArguments.length && showResults === true) {
244
- const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').equal(this.getId()).silent().getAllItems();
333
+ const responses = await q.select.apply(q, selectArguments).where('evaluationEvent').in(evaluationEvents).silent().getAllItems();
245
334
  for (let i = 0; i < result.length; i++) {
246
335
  const qElement = result[i];
247
336
  qElement.responses=[];
@@ -253,6 +342,13 @@ class EvaluationEvent extends DataObject {
253
342
  qElement.avg = responses.length? math.mean(responses.map(x => {
254
343
  return x[qElement.name];
255
344
  })):0;
345
+ summaryValues.forEach(radioValue => {
346
+ const result = responses.filter(y => {
347
+ return y[qElement.name] == radioValue.value;
348
+ }).length;
349
+ radioValue.total += result;
350
+ totalResponses += result;
351
+ });
256
352
  } else {
257
353
  qElement.responses = responses.map(x => {
258
354
  return x[qElement.name];
@@ -260,7 +356,14 @@ class EvaluationEvent extends DataObject {
260
356
  }
261
357
  }
262
358
  }
263
- return result;
359
+ const results={};
360
+ results.responses = result;
361
+ results.summaryValues = [];
362
+ results.summaryValues.push.apply(results.summaryValues, summaryValues.map(x=>{
363
+ x.totalResponses= totalResponses;
364
+ return x;
365
+ }));
366
+ return results;
264
367
  }
265
368
 
266
369
  async showResults (context) {
@@ -354,15 +457,15 @@ class EvaluationEvent extends DataObject {
354
457
  const context = event.model.context;
355
458
  context.model(EvaluationAccessToken).where('access_token').equal(context.user && context.user.authenticationToken)
356
459
  .silent().getItem().then((token) => {
357
- if (token == null) {
358
- throw new HttpTokenExpiredError('Evaluation token is required');
359
- }
360
- return context.model(EvaluationAccessToken).silent().save({
361
- access_token: token.access_token,
362
- expires: new Date(0), // set epoch date
363
- used: true
364
- });
365
- }).then(() => {
460
+ if (token == null) {
461
+ throw new HttpTokenExpiredError('Evaluation token is required');
462
+ }
463
+ return context.model(EvaluationAccessToken).silent().save({
464
+ access_token: token.access_token,
465
+ expires: new Date(0), // set epoch date
466
+ used: true
467
+ });
468
+ }).then(() => {
366
469
  return callback();
367
470
  }).catch((err) => {
368
471
  TraceUtils.error('An error occurred while submitting evaluation');
@@ -389,10 +492,10 @@ class EvaluationEvent extends DataObject {
389
492
  items = await EvaluationEvent.generateManyTokens(context, generateOptions);
390
493
  await context.model('EvaluationAccessToken').silent().save(items);
391
494
  return items.length;
392
- }
495
+ }
393
496
  }
394
497
  /**
395
- * Generates a number of access tokens for the given event
498
+ * Generates a number of access tokens for the given event
396
499
  * @param {DataContext} context
397
500
  * @param {{evaluationEvent: number, n: number, expires?: DateTime}} generateOptions
398
501
  */