@universis/evaluations 1.0.20 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/evaluationRouter.js +14 -0
- package/dist/evaluationRouter.js.map +1 -1
- package/dist/handlers/evaluation-key-handler.js +1 -1
- package/dist/handlers/evaluation-key-handler.js.map +1 -1
- package/dist/listeners/class-instructor-event-listener.js +38 -1
- package/dist/listeners/class-instructor-event-listener.js.map +1 -1
- package/dist/locales/el.json +19 -0
- package/dist/models/class-instructor-evaluation-event-model.js +197 -172
- package/dist/models/class-instructor-evaluation-event-model.js.map +1 -1
- package/dist/models/evaluation-event-model.js +12 -3
- package/dist/models/evaluation-event-model.js.map +1 -1
- package/package.json +1 -1
- package/src/evaluationRouter.js +14 -0
- package/src/handlers/evaluation-key-handler.js +1 -1
- package/src/listeners/class-instructor-event-listener.js +38 -0
- package/src/locales/el.json +19 -0
- package/src/models/class-instructor-evaluation-event-model.js +60 -35
- package/src/models/evaluation-event-model.js +13 -4
package/dist/evaluationRouter.js
CHANGED
|
@@ -3,10 +3,24 @@ var _evaluationKeyHandler = require("./handlers/evaluation-key-handler");
|
|
|
3
3
|
var _express2 = require("@themost/express");
|
|
4
4
|
var _i18n = _interopRequireDefault(require("i18n"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
|
|
5
5
|
|
|
6
|
+
const el = require('./locales/el.json');
|
|
6
7
|
|
|
8
|
+
/**
|
|
9
|
+
*
|
|
10
|
+
* @param {ExpressDataApplication} app
|
|
11
|
+
* @returns {*}
|
|
12
|
+
*/
|
|
7
13
|
function evaluationRouter(app) {
|
|
8
14
|
|
|
9
15
|
const router = _express.default.Router();
|
|
16
|
+
// add translations
|
|
17
|
+
if (app && app.parentApplication) {
|
|
18
|
+
const translateService = app.parentApplication.getService(function TranslateService() {
|
|
19
|
+
});
|
|
20
|
+
if (translateService) {
|
|
21
|
+
translateService.setTranslation('el', el);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
10
24
|
|
|
11
25
|
router.use((req, res, next) => {
|
|
12
26
|
// create router context
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/evaluationRouter.js"],"names":["evaluationRouter","app","router","express","Router","use","req","res","next","newContext","createContext","interactiveContext","context","finalize","Object","defineProperty","enumerable","configurable","get","locale","translate","i18n","__","apply","Array","from","arguments","on","EvaluationKeyHandler","beginRequestAsync","err","assign","params","entitySetFunction","entitySet","entityFunction","post","entityAction"],"mappings":"uHAAA;AACA;AACA;AACA,oD
|
|
1
|
+
{"version":3,"sources":["../src/evaluationRouter.js"],"names":["el","require","evaluationRouter","app","router","express","Router","parentApplication","translateService","getService","TranslateService","setTranslation","use","req","res","next","newContext","createContext","interactiveContext","context","finalize","Object","defineProperty","enumerable","configurable","get","locale","translate","i18n","__","apply","Array","from","arguments","on","EvaluationKeyHandler","beginRequestAsync","err","assign","params","entitySetFunction","entitySet","entityFunction","post","entityAction"],"mappings":"uHAAA;AACA;AACA;AACA,oD;;AAEA,MAAMA,EAAE,GAAGC,OAAO,CAAC,mBAAD,CAAlB;;AAEA;AACA;AACA;AACA;AACA;AACO,SAASC,gBAAT,CAA0BC,GAA1B,EAA+B;;AAElC,QAAMC,MAAM,GAAGC,iBAAQC,MAAR,EAAf;AACA;AACA,MAAIH,GAAG,IAAIA,GAAG,CAACI,iBAAf,EAAkC;AAC9B,UAAMC,gBAAgB,GAAGL,GAAG,CAACI,iBAAJ,CAAsBE,UAAtB,CAAiC,SAASC,gBAAT,GAA4B;AACrF,KADwB,CAAzB;AAEA,QAAIF,gBAAJ,EAAsB;AAClBA,MAAAA,gBAAgB,CAACG,cAAjB,CAAgC,IAAhC,EAAsCX,EAAtC;AACH;AACJ;;AAEDI,EAAAA,MAAM,CAACQ,GAAP,CAAW,CAACC,GAAD,EAAMC,GAAN,EAAWC,IAAX,KAAoB;AAC3B;AACA,UAAMC,UAAU,GAAGb,GAAG,CAACc,aAAJ,EAAnB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AA,MAAM,CAACuC,IAAP,CAAY,WAAZ,EAAyB,CAAC9B,GAAD,EAAMC,GAAN,EAAWC,IAAX,KAAoB;AACzC;AACAM,IAAAA,MAAM,CAACiB,MAAP,CAAczB,GAAG,CAAC0B,MAAlB,EAA0B;AACtBC,MAAAA,iBAAiB,EAAG,SADE;AAEtBI,MAAAA,YAAY,EAAG,UAFO,EAA1B;;AAIA,WAAO7B,IAAI,EAAX;AACH,GAPD,EAOG,qCAAsB;AACrB0B,IAAAA,SAAS,EAAE,kBADU,EAAtB,CAPH;;;;;AAaA,SAAOrC,MAAP;AACH","sourcesContent":["import express from 'express';\nimport {EvaluationKeyHandler} from \"./handlers/evaluation-key-handler\";\nimport { getEntitySetFunction} from \"@themost/express\";\nimport i18n from \"i18n\";\nimport {postEntitySetFunction} from \"@themost/express\";\nconst el = require('./locales/el.json');\n\n/**\n *\n * @param {ExpressDataApplication} app\n * @returns {*}\n */\nexport function evaluationRouter(app) {\n\n const router = express.Router();\n // add translations\n if (app && app.parentApplication) {\n const translateService = app.parentApplication.getService(function TranslateService() {\n });\n if (translateService) {\n translateService.setTranslation('el', el);\n }\n }\n\n router.use((req, res, next) => {\n // create router context\n const newContext = app.createContext();\n /**\n * try to find if request has already a data context\n * @type {ExpressDataContext|*}\n */\n const interactiveContext = req.context;\n // finalize already assigned context\n if (interactiveContext) {\n if (typeof interactiveContext.finalize === 'function') {\n // finalize interactive context\n return interactiveContext.finalize(() => {\n // and assign new context\n Object.defineProperty(req, 'context', {\n enumerable: false,\n configurable: true,\n get: () => {\n return newContext\n }\n });\n // exit handler\n return next();\n });\n }\n }\n // otherwise assign context\n Object.defineProperty(req, 'context', {\n enumerable: false,\n configurable: true,\n get: () => {\n return newContext\n }\n });\n // and exit handler\n return next();\n });\n router.use((req, res, next) => {\n // set context locale from request\n req.context.locale = req.locale;\n // set translation\n req.context.translate = function() {\n return i18n.__.apply(req.context, Array.from(arguments));\n };\n return next();\n });\n // use this handler to finalize router context\n // important note: context finalization is very important in order\n // to close and finalize database connections, cache connections etc.\n router.use((req, res, next) => {\n req.on('end', () => {\n //on end\n if (req.context) {\n //finalize data context\n return req.context.finalize( () => {\n //\n });\n }\n });\n return next();\n });\n\n router.use(async (req, res, next) => {\n try {\n await new EvaluationKeyHandler().beginRequestAsync(req, res);\n return next();\n } catch (err) {\n return next(err);\n }\n });\n\n router.get('/', (req, res, next) => {\n // set entity set parameters\n Object.assign(req.params, {\n entitySetFunction : 'Current'\n });\n return next();\n }, getEntitySetFunction({\n entitySet: 'EvaluationEvents'\n }));\n\n router.get('/Form', (req, res, next) => {\n // set entity set parameters\n Object.assign(req.params, {\n entitySetFunction : 'Current',\n entityFunction : 'Form'\n });\n return next();\n }, getEntitySetFunction({\n entitySet: 'EvaluationEvents'\n }));\n\n router.post('/Evaluate', (req, res, next) => {\n // set entity set parameters\n Object.assign(req.params, {\n entitySetFunction : 'Current',\n entityAction : 'Evaluate'\n });\n return next();\n }, postEntitySetFunction({\n entitySet: 'EvaluationEvents'\n }));\n\n\n\n return router;\n}\n"],"file":"evaluationRouter.js"}
|
|
@@ -12,7 +12,7 @@ class EvaluationKeyHandler {
|
|
|
12
12
|
const evaluationKey = req.headers['evaluation-key'].replace(/-/ig, '');
|
|
13
13
|
return EvaluationAccessToken.inspect(req.context, evaluationKey).then((token) => {
|
|
14
14
|
if (token.active === false) {
|
|
15
|
-
return callback(new _common.HttpTokenExpiredError('Evaluation access token has been expired'));
|
|
15
|
+
return callback(new _common.HttpTokenExpiredError(req.context.__('Evaluation access token has been expired')));
|
|
16
16
|
}
|
|
17
17
|
req.context.user = req.context.user || {
|
|
18
18
|
name: 'anonymous',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handlers/evaluation-key-handler.js"],"names":["EvaluationAccessToken","require","EvaluationKeyHandler","createInstance","beginRequest","req","res","callback","Object","prototype","hasOwnProperty","call","headers","evaluationKey","replace","inspect","context","then","token","active","HttpTokenExpiredError","user","name","authenticationType","authenticationToken","access_token","authenticationScope","scope","catch","err","error","beginRequestAsync","Promise","resolve","reject"],"mappings":"iHAAA;AACA,MAAMA,qBAAqB,GAAGC,OAAO,CAAC,yCAAD,CAArC;;AAEQ,MAAMC,oBAAN,CAA2B;AACV,SAAdC,cAAc,GAAG;AACpB,WAAO,IAAID,oBAAJ,EAAP;AACH;;AAEDE,EAAAA,YAAY,CAACC,GAAD,EAAMC,GAAN,EAAWC,QAAX,EAAqB;AAC7B,QAAI;AACA,UAAIC,MAAM,CAACC,SAAP,CAAiBC,cAAjB,CAAgCC,IAAhC,CAAqCN,GAAG,CAACO,OAAzC,EAAkD,gBAAlD,CAAJ,EAAyE;AACrE,cAAMC,aAAa,GAAGR,GAAG,CAACO,OAAJ,CAAY,gBAAZ,EAA8BE,OAA9B,CAAsC,KAAtC,EAA6C,EAA7C,CAAtB;AACA,eAAOd,qBAAqB,CAACe,OAAtB,CAA8BV,GAAG,CAACW,OAAlC,EAA2CH,aAA3C,EAA0DI,IAA1D,CAA+D,CAACC,KAAD,KAAW;AAC7E,cAAIA,KAAK,CAACC,MAAN,KAAiB,KAArB,EAA4B;AACxB,mBAAOZ,QAAQ,CAAC,IAAIa,6BAAJ,
|
|
1
|
+
{"version":3,"sources":["../../src/handlers/evaluation-key-handler.js"],"names":["EvaluationAccessToken","require","EvaluationKeyHandler","createInstance","beginRequest","req","res","callback","Object","prototype","hasOwnProperty","call","headers","evaluationKey","replace","inspect","context","then","token","active","HttpTokenExpiredError","__","user","name","authenticationType","authenticationToken","access_token","authenticationScope","scope","catch","err","error","beginRequestAsync","Promise","resolve","reject"],"mappings":"iHAAA;AACA,MAAMA,qBAAqB,GAAGC,OAAO,CAAC,yCAAD,CAArC;;AAEQ,MAAMC,oBAAN,CAA2B;AACV,SAAdC,cAAc,GAAG;AACpB,WAAO,IAAID,oBAAJ,EAAP;AACH;;AAEDE,EAAAA,YAAY,CAACC,GAAD,EAAMC,GAAN,EAAWC,QAAX,EAAqB;AAC7B,QAAI;AACA,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,EAA6B,UAASwB,GAAT,EAAc;AACvC,YAAIA,GAAJ,EAAS;AACL,iBAAOK,MAAM,CAACL,GAAD,CAAb;AACH;AACD,eAAOI,OAAO,CAACJ,GAAD,CAAd;AACF,OALF;AAMF,KAPM,CAAP;;AASH,GAxC6B,C","sourcesContent":["import { HttpTokenExpiredError } from '@themost/common';\nconst EvaluationAccessToken = require('../models/evaluation-access-token-model');\n\n export class EvaluationKeyHandler {\n static createInstance() {\n return new EvaluationKeyHandler();\n }\n\n beginRequest(req, res, callback) {\n try {\n if (Object.prototype.hasOwnProperty.call(req.headers, 'evaluation-key')) {\n const evaluationKey = req.headers['evaluation-key'].replace(/-/ig, '');\n return EvaluationAccessToken.inspect(req.context, evaluationKey).then((token) => {\n if (token.active === false) {\n return callback(new HttpTokenExpiredError(req.context.__('Evaluation access token has been expired')));\n }\n req.context.user = req.context.user || {\n name: 'anonymous',\n authenticationType: 'Evaluation',\n authenticationToken: token.access_token,\n authenticationScope: token.scope\n };\n return callback();\n }).catch((err) => {\n return callback(err);\n });\n }\n return callback();\n } catch(error){\n return callback(error);\n }\n }\n\n beginRequestAsync(req, res) {\n return new Promise(((resolve, reject) => {\n this.beginRequest( req, res, function(err) {\n if (err) {\n return reject(err);\n }\n return resolve(err);\n });\n }));\n\n }\n}\n"],"file":"evaluation-key-handler.js"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.afterExecute = afterExecute;exports.afterExecuteAsync = afterExecuteAsync;exports.beforeSave = beforeSave;var _data = require("@themost/data");
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.afterExecute = afterExecute;exports.afterExecuteAsync = afterExecuteAsync;exports.beforeRemove = beforeRemove;exports.beforeSave = beforeSave;var _data = require("@themost/data");
|
|
2
2
|
/**
|
|
3
3
|
*
|
|
4
4
|
* @param {DataEventArgs} event
|
|
@@ -83,4 +83,41 @@ async function afterExecuteAsync(event) {
|
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @async
|
|
89
|
+
* @param {DataEventArgs} event
|
|
90
|
+
*/
|
|
91
|
+
async function beforeRemoveAsync(event) {
|
|
92
|
+
// ensure associations
|
|
93
|
+
const context = event.model.context;
|
|
94
|
+
const evaluationEvent = context.model('EvaluationEvent').convert(event.target);
|
|
95
|
+
const form = await evaluationEvent.property('evaluationDocument').getItem();
|
|
96
|
+
if (form && form.resultType) {
|
|
97
|
+
if (context.model(form.resultType) == null) {
|
|
98
|
+
// ensure model is added to configuration
|
|
99
|
+
await evaluationEvent.getForm();
|
|
100
|
+
}
|
|
101
|
+
const answers = await context.model(form.resultType).
|
|
102
|
+
where('evaluationEvent').equal(event.target.id).
|
|
103
|
+
silent().count();
|
|
104
|
+
if (answers) {
|
|
105
|
+
throw new Error('Cannot remove evaluation event since there are responses associated with it');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @param {DataEventArgs} event
|
|
113
|
+
* @param {Function} callback
|
|
114
|
+
*/
|
|
115
|
+
function beforeRemove(event, callback) {
|
|
116
|
+
// execute async method
|
|
117
|
+
return beforeRemoveAsync(event).then(() => {
|
|
118
|
+
return callback();
|
|
119
|
+
}).catch((err) => {
|
|
120
|
+
return callback(err);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
86
123
|
//# sourceMappingURL=class-instructor-event-listener.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/listeners/class-instructor-event-listener.js"],"names":["beforeSaveAsync","event","context","model","target","courseClassInstructor","organizer","where","equal","select","value","state","DataObjectState","Update","previous","endDate","prevEndDate","setHours","tokens","id","and","notEqual","silent","getItems","length","map","x","expires","save","beforeSave","callback","then","catch","err","afterExecute","afterExecuteAsync","emitter","$expand","Array","isArray","find","mapping","name","options","$select","$groupby","results","result","calculatedTotal","reduce","partial_sum","a","total","findUsed","used","calculatedUsed"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/listeners/class-instructor-event-listener.js"],"names":["beforeSaveAsync","event","context","model","target","courseClassInstructor","organizer","where","equal","select","value","state","DataObjectState","Update","previous","endDate","prevEndDate","setHours","tokens","id","and","notEqual","silent","getItems","length","map","x","expires","save","beforeSave","callback","then","catch","err","afterExecute","afterExecuteAsync","emitter","$expand","Array","isArray","find","mapping","name","options","$select","$groupby","results","result","calculatedTotal","reduce","partial_sum","a","total","findUsed","used","calculatedUsed","beforeRemoveAsync","evaluationEvent","convert","form","property","getItem","resultType","getForm","answers","count","Error","beforeRemove"],"mappings":"iOAAA;AACA;AACA;AACA;AACA;AACA,eAAeA,eAAf,CAA+BC,KAA/B,EAAsC;AAClC;AACA,QAAMC,OAAO,GAAGD,KAAK,CAACE,KAAN,CAAYD,OAA5B;AACA,MAAID,KAAK,CAACG,MAAN,CAAaC,qBAAjB,EAAwC;AACpC,UAAMC,SAAS,GAAG,MAAMJ,OAAO,CAACC,KAAR,CAAc,uBAAd;AACnBI,IAAAA,KADmB,CACb,IADa,EACPC,KADO,CACDP,KAAK,CAACG,MAAN,CAAaC,qBADZ;AAEnBI,IAAAA,MAFmB,CAEZ,+BAFY,EAEqBC,KAFrB,EAAxB;AAGAT,IAAAA,KAAK,CAACG,MAAN,CAAaE,SAAb,GAAyBA,SAAzB;AACH;AACD,MAAIL,KAAK,CAACU,KAAN,KAAcC,sBAAgBC,MAAlC;AACA;AACI,UAAMC,QAAQ,GAAGb,KAAK,CAACa,QAAvB;AACA;AACA,QAAIb,KAAK,CAACG,MAAN,CAAaW,OAAjB,EAA0B;AACtB,YAAMC,WAAW,GAAGf,KAAK,CAACa,QAAN,CAAeC,OAAnC;AACA,YAAMA,OAAO,GAAGd,KAAK,CAACG,MAAN,CAAaW,OAA7B;AACAC,MAAAA,WAAW,CAACC,QAAZ,CAAqB,CAArB,EAAwB,CAAxB,EAA2B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ACH,GAJM,CAAP;AAKH","sourcesContent":["import { DataObjectState } from '@themost/data';\n/**\n * \n * @param {DataEventArgs} event \n */\nasync function beforeSaveAsync(event) {\n // get organizer from courseClass\n const context = event.model.context;\n if (event.target.courseClassInstructor) {\n const organizer = await context.model('CourseClassInstructor')\n .where('id').equal(event.target.courseClassInstructor)\n .select('courseClass/course/department').value();\n event.target.organizer = organizer;\n }\n if (event.state===DataObjectState.Update)\n {\n const previous = event.previous;\n // check if endDate is changed and update expired field for tokens\n if (event.target.endDate) {\n const prevEndDate = event.previous.endDate;\n const endDate = event.target.endDate;\n prevEndDate.setHours(0, 0, 0, 0);\n endDate.setHours(0, 0, 0, 0);\n if (prevEndDate-endDate!==0) {\n let tokens = await context.model('EvaluationAccessToken').where('evaluationEvent').equal(event.target.id)\n .and('used').notEqual(1)\n .silent().getItems();\n if (tokens.length > 0) {\n tokens = tokens.map(x => {\n x.expires = event.target.endDate;\n return x;\n });\n // update tokens\n await context.model('EvaluationAccessToken').silent().save(tokens);\n }\n }\n }\n }\n}\n/**\n * @param {DataEventArgs} event\n * @param {Function} callback\n */\n export function beforeSave(event, callback) {\n beforeSaveAsync(event).then(() => {\n return callback()\n }).catch( err => {\n return callback(err);\n })\n}\n\n\nexport function afterExecute(event, callback) {\n return afterExecuteAsync(event).then(() => {\n return callback();\n }).catch(err => {\n return callback(err);\n });\n}\n\n\nexport async function afterExecuteAsync(event) {\n // calculate total tokens and total used tokens if events are expanded\n if (event.emitter && event.emitter.$expand && Array.isArray(event.emitter.$expand)) {\n // if tokens of classInstructorEvaluationEvents are expanded and $select and $groupby are present to mapping options\n if (event.emitter.$expand.find(mapping => {\n // $select and $groupby are present to mapping options\n return typeof mapping === 'object'\n ? mapping.name === 'tokens' && (mapping.options && mapping.options.$select && mapping.options.$groupby)\n : mapping === 'tokens'\n })) {\n const results = Array.isArray(event.result) ? event.result : [event.result]\n for (const result of results) {\n if (Array.isArray(result.tokens) && result.tokens.length) {\n // calculate total and used tokens\n result.calculatedTotal = result.tokens.reduce((partial_sum, a) => partial_sum + a.total, 0)\n const findUsed = result.tokens.find(x=>{\n return x.used;\n });\n result.calculatedUsed = findUsed?findUsed.total:0;\n }\n }\n }\n }\n}\n\n/**\n * @async\n * @param {DataEventArgs} event\n */\nasync function beforeRemoveAsync(event) {\n // ensure associations\n const context = event.model.context;\n const evaluationEvent = context.model('EvaluationEvent').convert(event.target);\n const form = await evaluationEvent.property('evaluationDocument').getItem();\n if (form && form.resultType) {\n if (context.model(form.resultType) == null) {\n // ensure model is added to configuration\n await evaluationEvent.getForm();\n }\n const answers = await context.model(form.resultType)\n .where('evaluationEvent').equal(event.target.id)\n .silent().count();\n if (answers) {\n throw new Error('Cannot remove evaluation event since there are responses associated with it')\n }\n }\n}\n\n\n/**\n * @param {DataEventArgs} event\n * @param {Function} callback\n */\nexport function beforeRemove(event, callback) {\n // execute async method\n return beforeRemoveAsync(event).then(() => {\n return callback();\n }).catch(err => {\n return callback(err);\n });\n}\n\n"],"file":"class-instructor-event-listener.js"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"An error occurred": "Συνέβη σφάλμα",
|
|
3
|
+
"The number of students in the class differs from the generated tokens": "Ο αριθμός των φοιτητών της τάξης διαφέρει από τα δημιουργημένα tokens",
|
|
4
|
+
"Students": "Φοιτητές",
|
|
5
|
+
"Number of tokens": "Αριθμός tokens",
|
|
6
|
+
"Send tokens action may only be executed for Open/Active events": "Η αποστολή των tokens μπορεί να γίνει μόνο για ανοιχτές αξιολογήσεις",
|
|
7
|
+
"Evaluation access token has been expired": "Ο κωδικός αξιολόγησης έχει λήξει",
|
|
8
|
+
"Token actions were not found for the specified event or they are inaccessible.": "Δε βρέθηκαν ενέργειες δημιουργίας για την αξιολόγηση ή δεν είναι διαθέσιμες",
|
|
9
|
+
"At least one student's email is null or invalid": "Τουλάχιστον ένα email φοιτητή δεν είναι έγκυρο ή είναι κενό",
|
|
10
|
+
"Student": "Φοιτητής",
|
|
11
|
+
"Sending tokens failed for all students": "Η αποστολή απέτυχε για όλους τους φοιτητές",
|
|
12
|
+
"The bulk sending of the tokens could not be completed because some of them had already been sent": "Δεν μπόρεσε να γίνει η μαζική αποστολή των tokens διότι κάποιο από αυτά είχε ήδη σταλεί",
|
|
13
|
+
"The bulk sending of the tokens could not be completed because some of them had already been used": "Δεν μπόρεσε να γίνει η μαζική αποστολή των tokens διότι κάποιο από αυτά είχε ήδη χρησιμοποιηθεί",
|
|
14
|
+
"Evaluation period for this course has not been started yet" : "Η περίοδος αξιολόγησης για το μάθημα δεν έχει ξεκινήσει ακόμη",
|
|
15
|
+
"Evaluation period for this course has been expired" : "Η περίοδος αξιολόγησης για το μάθημα έχει λήξει",
|
|
16
|
+
"Evaluation token has been expired" : "Ο κωδικός αξιολόγησης έχει λήξει",
|
|
17
|
+
"The course evaluation has been closed and is no longer available": "Η αξιολόγηση του μαθήματος έχει κλείσει και δεν είναι πλέον διαθέσιμη",
|
|
18
|
+
"Evaluation access token has been expired or is invalid.": "Ο κωδικός αξιολόγησης έχει λήξει ή δεν είναι έγκυρος"
|
|
19
|
+
}
|
|
@@ -140,196 +140,221 @@ _data.EdmMapping.action('SendEvaluationTokens', 'SendInstructorTokenAction'), _d
|
|
|
140
140
|
event.numberOfStudents = action.numberOfStudents;await context.model('ClassInstructorEvaluationEvent').save(event);if (event.numberOfStudents > 0) {await _evaluationEventModel.default.generateTokens(context, generateOptions);}generateAction.total = action.numberOfStudents;generateAction.actionStatus = { alternateName: 'CompletedActionStatus' };return await context.model('GenerateInstructorTokenAction').save(generateAction);} catch (err) {_common.TraceUtils.error(err); // update also action status
|
|
141
141
|
generateAction.total = 0;generateAction.actionStatus = { alternateName: 'FailedActionStatus' };generateAction.description = err.message;return await context.model('GenerateInstructorTokenAction').save(generateAction);}}}async getTokenStatistics() {const tokenInfo = { total: 0, used: 0, sent: 0 }; // get number if tokens
|
|
142
142
|
const tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId()).select('count(evaluationEvent) as total', 'used', 'sent').groupBy('used', 'sent', 'evaluationEvent').silent().getItems();tokens.map((item) => {tokenInfo.total += item.total;tokenInfo.used += item.used ? item.total : 0;tokenInfo.sent += item.sent ? item.total : 0;});return tokenInfo;}async sendEvaluationTokens() {const context = this.context; // get event and check if event endDate has passed
|
|
143
|
-
// get current date
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
// validate sent-used seperately for descriptive errors
|
|
170
|
-
if (tokenInfo.sent) {
|
|
171
|
-
throw new _common.DataError(`Cannot proceed with sending tokens, because ${tokenInfo.sent} of them is/are already sent.`);
|
|
172
|
-
}
|
|
173
|
-
if (tokenInfo.used) {
|
|
174
|
-
throw new _common.DataError(`Cannot proceed with sending tokens, because ${tokenInfo.used} of them is/are already used.`);
|
|
175
|
-
}
|
|
176
|
-
// start gathering students
|
|
177
|
-
let students;
|
|
178
|
-
const courseClass = event.courseClassInstructor && event.courseClassInstructor.courseClass;
|
|
179
|
-
const eventInstructor = event.courseClassInstructor && event.courseClassInstructor.instructor;
|
|
180
|
-
// get class sections
|
|
181
|
-
const sections = await context.model('CourseClassSection').where('courseClass').equal(courseClass.id).getItems();
|
|
182
|
-
// check if course class has sections
|
|
183
|
-
if (sections && sections.length > 0 && courseClass.mustRegisterSection !== 0) {
|
|
184
|
-
// get only number of students registered at specific section
|
|
185
|
-
const instructorSections = await context.model('CourseClassSectionInstructor').where('courseClass').equal(courseClass.id).
|
|
186
|
-
and('instructor').equal(eventInstructor).select('section/section as sectionId').silent().getItems();
|
|
187
|
-
if (instructorSections && instructorSections.length === 0) {
|
|
188
|
-
throw new _common.DataError('Instructor is not related with any of sections');
|
|
143
|
+
try {// get current date
|
|
144
|
+
const currentDate = (0, _moment.default)(new Date()).startOf('day').toDate(); // get only date format
|
|
145
|
+
const event = await context.model('ClassInstructorEvaluationEvent').where('id').equal(this.getId()).and('date(endDate)').greaterOrEqual(currentDate).expand({ name: 'courseClassInstructor', options: { '$expand': 'courseClass($expand=course), instructor' // expand course and instructor so their attributes are available in the mail template
|
|
146
|
+
} }, {
|
|
147
|
+
name: 'actions',
|
|
148
|
+
options: {
|
|
149
|
+
'$expand': 'actionStatus' } }).
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
getItem();
|
|
153
|
+
// validate event
|
|
154
|
+
if (event == null) {
|
|
155
|
+
throw new _common.DataNotFoundError('The event cannot be found or is inaccessible.');
|
|
156
|
+
}
|
|
157
|
+
// validate status
|
|
158
|
+
if (!(event.eventStatus && event.eventStatus.alternateName === 'EventOpened')) {
|
|
159
|
+
throw new _common.DataError('E_INVALID_PERIOD', context.__('Send tokens action may only be executed for Open/Active events'));
|
|
160
|
+
}
|
|
161
|
+
// validate event actions
|
|
162
|
+
if (!(event.actions && event.actions.length)) {
|
|
163
|
+
throw new _common.DataNotFoundError('E_NO_TOKENS', context.__('Token actions were not found for the specified event or they are inaccessible.'));
|
|
164
|
+
}
|
|
165
|
+
// find completed token generation action (can only be one)
|
|
166
|
+
const successfulTokenAction = event.actions.find((generateTokenAction) => generateTokenAction.actionStatus.alternateName === 'CompletedActionStatus');
|
|
167
|
+
if (successfulTokenAction == null) {
|
|
168
|
+
throw new _common.DataError('E_NO_TOKENS', 'The specified event does not have a completed token generation action.');
|
|
189
169
|
}
|
|
190
|
-
|
|
191
|
-
|
|
170
|
+
// get tokenInfo for this event
|
|
171
|
+
const tokenInfo = await this.getTokenStatistics();
|
|
172
|
+
// validate sent-used separately for descriptive errors
|
|
173
|
+
if (tokenInfo.sent) {
|
|
174
|
+
throw new _common.DataError('E_ALREADY_SENT', `${context.__('The bulk sending of the tokens could not be completed because some of them had already been sent')} (${tokenInfo.sent})`);
|
|
175
|
+
}
|
|
176
|
+
if (tokenInfo.used) {
|
|
177
|
+
throw new _common.DataError('E_ALREADY_USED', `${context.__('The bulk sending of the tokens could not be completed because some of them had already been used')} (${tokenInfo.used})`);
|
|
178
|
+
}
|
|
179
|
+
// start gathering students
|
|
180
|
+
let students;
|
|
181
|
+
const courseClass = event.courseClassInstructor && event.courseClassInstructor.courseClass;
|
|
182
|
+
const eventInstructor = event.courseClassInstructor && event.courseClassInstructor.instructor;
|
|
183
|
+
// get class sections
|
|
184
|
+
const sections = await context.model('CourseClassSection').where('courseClass').equal(courseClass.id).getItems();
|
|
185
|
+
// check if course class has sections
|
|
186
|
+
if (sections && sections.length > 0 && courseClass.mustRegisterSection !== 0) {
|
|
187
|
+
// get only number of students registered at specific section
|
|
188
|
+
const instructorSections = await context.model('CourseClassSectionInstructor').where('courseClass').equal(courseClass.id).
|
|
189
|
+
and('instructor').equal(eventInstructor).select('section/section as sectionId').silent().getItems();
|
|
190
|
+
if (instructorSections && instructorSections.length === 0) {
|
|
191
|
+
throw new _common.DataError('E_INVALID_SECTION', 'Instructor is not related with any of sections');
|
|
192
|
+
}
|
|
193
|
+
const sectionIds = instructorSections.map((section) => {
|
|
194
|
+
return section.sectionId;
|
|
195
|
+
});
|
|
196
|
+
// get students for specific course class sections
|
|
197
|
+
students = await context.model('StudentCourseClass').
|
|
198
|
+
where('courseClass').equal(courseClass.id).
|
|
199
|
+
and('section').in(sectionIds).
|
|
200
|
+
select('email').
|
|
201
|
+
silent().
|
|
202
|
+
getAllItems();
|
|
203
|
+
} else {
|
|
204
|
+
students = await context.model('StudentCourseClass').
|
|
205
|
+
where('courseClass').equal(courseClass.id).
|
|
206
|
+
select('email', 'student').
|
|
207
|
+
silent().
|
|
208
|
+
getAllItems();
|
|
209
|
+
}
|
|
210
|
+
if (!(Array.isArray(students) && students.length)) {
|
|
211
|
+
throw new _common.DataError('E_STUDENTS_FOUND', 'No recipients/students found.');
|
|
212
|
+
}
|
|
213
|
+
// check total of students
|
|
214
|
+
if (students.length !== tokenInfo.total) {
|
|
215
|
+
throw new _common.DataError('E_TOTAL_STUDENTS',
|
|
216
|
+
`${this.context.__("The number of students in the class differs from the generated tokens")}` +
|
|
217
|
+
`(${this.context.__("Students")}: ${students.length}, ${this.context.__("Number of tokens")}:${tokenInfo.total}.`);
|
|
218
|
+
}
|
|
219
|
+
// validate student emails, must all exist and have a valid format
|
|
220
|
+
// https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
|
|
221
|
+
const mailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
|
|
222
|
+
const invalidEmail = students.find((student) => {
|
|
223
|
+
return !(student.email && mailRegex.test(student.email));
|
|
192
224
|
});
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
225
|
+
if (invalidEmail) {
|
|
226
|
+
throw new _common.DataError('E_INVALID_EMAIL', `${context.__('At least one student\'s email is null or invalid')} (email:${invalidEmail.email || ' '} ${context.__('Student')}:${invalidEmail.student})`);
|
|
227
|
+
}
|
|
228
|
+
// get tokens
|
|
229
|
+
let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId()).
|
|
230
|
+
select('access_token').
|
|
198
231
|
silent().
|
|
199
232
|
getAllItems();
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
233
|
+
// and map them to an array
|
|
234
|
+
tokens = tokens.map((token) => token.access_token);
|
|
235
|
+
// get mail template
|
|
236
|
+
const mailTemplate = await context.model('MailConfiguration').
|
|
237
|
+
where('target').equal('SendInstructorTokenAction').
|
|
204
238
|
silent().
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
throw new _common.DataError('No recipients/students found.');
|
|
209
|
-
}
|
|
210
|
-
// check total of students
|
|
211
|
-
if (students.length !== tokenInfo.total) {
|
|
212
|
-
throw new _common.DataError(`Cannot proceed to sending tokens. Students are ${students.length} and generated tokens are ${tokenInfo.total}.`);
|
|
213
|
-
}
|
|
214
|
-
// validate student emails, must all exist and have a valid format
|
|
215
|
-
// https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
|
|
216
|
-
const mailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
|
|
217
|
-
const invalidEmail = students.find((student) => {
|
|
218
|
-
return !(student.email && mailRegex.test(student.email));
|
|
219
|
-
});
|
|
220
|
-
if (invalidEmail) {
|
|
221
|
-
throw new _common.DataError(`Cannot procced to sending tokens because at least one student's email is null or invalid. Found invalid email: ${invalidEmail.email || 'empty'}`);
|
|
222
|
-
}
|
|
223
|
-
// get tokens
|
|
224
|
-
let tokens = await this.context.model('EvaluationAccessToken').where('evaluationEvent').equal(this.getId()).
|
|
225
|
-
select('access_token').
|
|
226
|
-
silent().
|
|
227
|
-
getAllItems();
|
|
228
|
-
// and map them to an array
|
|
229
|
-
tokens = tokens.map((token) => token.access_token);
|
|
230
|
-
// get mail template
|
|
231
|
-
const mailTemplate = await context.model('MailConfiguration').
|
|
232
|
-
where('target').equal('SendInstructorTokenAction').
|
|
233
|
-
silent().
|
|
234
|
-
getItem();
|
|
235
|
-
if (mailTemplate == null) {
|
|
236
|
-
throw new _common.DataError('Cannot execute send tokens action because template is missing for SendInstructorTokenAction.');
|
|
237
|
-
}
|
|
238
|
-
const succeeded = [];
|
|
239
|
-
const failed = [];
|
|
240
|
-
try {
|
|
241
|
-
// format mail subject expected params ${course}, ${instructor}
|
|
242
|
-
const exp = new RegExp('\\$\\{\\w+\\}+', 'ig');
|
|
243
|
-
let subject = mailTemplate.subject;
|
|
244
|
-
const params = subject.match(exp);
|
|
245
|
-
if (params.length > 0) {
|
|
246
|
-
// parse only custom parameters ${instructor},${course}
|
|
247
|
-
params.forEach((param) => {
|
|
248
|
-
if (param === '${instructor}') {
|
|
249
|
-
// get instructor full name
|
|
250
|
-
subject = subject.replace(param, eventInstructor ? `${eventInstructor.familyName} ${eventInstructor.givenName}` : '');
|
|
251
|
-
} else if (param === '${course}') {
|
|
252
|
-
// get courseClass code and title
|
|
253
|
-
subject = subject.replace(param, courseClass.course ? `${courseClass.course.displayCode} ${courseClass.title}` : '');
|
|
254
|
-
} else {
|
|
255
|
-
subject = subject.replace(param, '');
|
|
256
|
-
}
|
|
257
|
-
});
|
|
239
|
+
getItem();
|
|
240
|
+
if (mailTemplate == null) {
|
|
241
|
+
throw new _common.DataError('E_MISSING_TEMPLATE', 'Cannot execute send tokens action because template is missing for SendInstructorTokenAction.');
|
|
258
242
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
243
|
+
const succeeded = [];
|
|
244
|
+
const failed = [];
|
|
245
|
+
try {
|
|
246
|
+
// format mail subject expected params ${course}, ${instructor}
|
|
247
|
+
const exp = new RegExp('\\$\\{\\w+\\}+', 'ig');
|
|
248
|
+
let subject = mailTemplate.subject;
|
|
249
|
+
const params = subject.match(exp);
|
|
250
|
+
if (params.length > 0) {
|
|
251
|
+
// parse only custom parameters ${instructor},${course}
|
|
252
|
+
params.forEach((param) => {
|
|
253
|
+
if (param === '${instructor}') {
|
|
254
|
+
// get instructor full name
|
|
255
|
+
subject = subject.replace(param, eventInstructor ? `${eventInstructor.familyName} ${eventInstructor.givenName}` : '');
|
|
256
|
+
} else if (param === '${course}') {
|
|
257
|
+
// get courseClass code and title
|
|
258
|
+
subject = subject.replace(param, courseClass.course ? `${courseClass.course.displayCode} ${courseClass.title}` : '');
|
|
259
|
+
} else {
|
|
260
|
+
subject = subject.replace(param, '');
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
// use an async function to send emails
|
|
265
|
+
await (async () => {
|
|
266
|
+
for (const student of students) {
|
|
267
|
+
// refresh mailer
|
|
268
|
+
const mailer = (0, _mailer.getMailer)(context); // maybe investigate why this has to be refreshed.
|
|
269
|
+
// pop an access token
|
|
270
|
+
const access_token = tokens.pop();
|
|
271
|
+
// send message
|
|
272
|
+
await new Promise((resolve) => {
|
|
273
|
+
mailer.
|
|
274
|
+
template(mailTemplate.template).
|
|
275
|
+
subject(subject).
|
|
276
|
+
to(student.email).
|
|
277
|
+
send(Object.assign(event, {
|
|
278
|
+
access_token }),
|
|
279
|
+
(err) => {
|
|
280
|
+
if (err) {
|
|
281
|
+
try {
|
|
282
|
+
_common.TraceUtils.error(`SendEvaluationTokensAction', 'An error occurred while trying to send token to student email ${student.email}`);
|
|
283
|
+
_common.TraceUtils.error(err);
|
|
284
|
+
} catch (err1) {
|
|
285
|
+
// do nothing
|
|
286
|
+
}
|
|
287
|
+
failed.push(access_token);
|
|
288
|
+
return resolve();
|
|
281
289
|
}
|
|
282
|
-
|
|
290
|
+
succeeded.push(access_token);
|
|
283
291
|
return resolve();
|
|
284
|
-
}
|
|
285
|
-
succeeded.push(access_token);
|
|
286
|
-
return resolve();
|
|
292
|
+
});
|
|
287
293
|
});
|
|
288
|
-
}
|
|
294
|
+
}
|
|
295
|
+
})();
|
|
296
|
+
// update successfully sent tokens
|
|
297
|
+
for (const succeededToken of succeeded) {
|
|
298
|
+
await context.model('EvaluationAccessToken').silent().save({
|
|
299
|
+
access_token: succeededToken, // access_token is primary
|
|
300
|
+
sent: true,
|
|
301
|
+
$state: 2 });
|
|
302
|
+
|
|
289
303
|
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
sent:
|
|
296
|
-
|
|
304
|
+
// create send tokens action
|
|
305
|
+
const sendTokensAction = {
|
|
306
|
+
event: this.getId(),
|
|
307
|
+
numberOfStudents: students.length,
|
|
308
|
+
total: tokenInfo.total,
|
|
309
|
+
sent: succeeded.length,
|
|
310
|
+
failed: failed.length,
|
|
311
|
+
actionStatus: {
|
|
312
|
+
alternateName: tokenInfo.total === failed.length ? 'FailedActionStatus' : 'CompletedActionStatus' },
|
|
313
|
+
|
|
314
|
+
description: tokenInfo.total === failed.length ? context.__('Sending tokens failed for all students') : null };
|
|
315
|
+
|
|
316
|
+
// and save
|
|
317
|
+
return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
|
|
318
|
+
} catch (err) {
|
|
319
|
+
// log error
|
|
320
|
+
_common.TraceUtils.error(err);
|
|
321
|
+
// update successfully sent tokens
|
|
322
|
+
for (const succeededToken of succeeded) {
|
|
323
|
+
await context.model('EvaluationAccessToken').silent().save({
|
|
324
|
+
access_token: succeededToken, // access_token is primary
|
|
325
|
+
sent: true,
|
|
326
|
+
$state: 2 });
|
|
297
327
|
|
|
328
|
+
}
|
|
329
|
+
// create send tokens action
|
|
330
|
+
const sendTokensAction = {
|
|
331
|
+
event: this.getId(),
|
|
332
|
+
numberOfStudents: students.length,
|
|
333
|
+
total: tokenInfo.total,
|
|
334
|
+
sent: succeeded.length,
|
|
335
|
+
failed: succeeded.length ? tokenInfo.total - succeeded.length : tokenInfo.total,
|
|
336
|
+
actionStatus: {
|
|
337
|
+
alternateName: 'CompletedActionStatus' } };
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
// and save
|
|
341
|
+
return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
|
|
298
342
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
numberOfStudents: students.length,
|
|
303
|
-
total: tokenInfo.total,
|
|
304
|
-
sent: succeeded.length,
|
|
305
|
-
failed: failed.length,
|
|
306
|
-
actionStatus: {
|
|
307
|
-
alternateName: 'CompletedActionStatus' } };
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
// and save
|
|
311
|
-
return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
|
|
312
|
-
} catch (err) {
|
|
313
|
-
// log error
|
|
343
|
+
}
|
|
344
|
+
catch (err)
|
|
345
|
+
{
|
|
314
346
|
_common.TraceUtils.error(err);
|
|
315
|
-
// update successfully sent tokens
|
|
316
|
-
for (const succededToken of succeeded) {
|
|
317
|
-
await context.model('EvaluationAccessToken').silent().save({
|
|
318
|
-
access_token: succededToken, // access_token is primary
|
|
319
|
-
sent: true,
|
|
320
|
-
$state: 2 });
|
|
321
|
-
|
|
322
|
-
}
|
|
323
347
|
// create send tokens action
|
|
324
348
|
const sendTokensAction = {
|
|
325
349
|
event: this.getId(),
|
|
326
|
-
numberOfStudents:
|
|
327
|
-
total:
|
|
328
|
-
sent:
|
|
329
|
-
failed:
|
|
350
|
+
numberOfStudents: 0,
|
|
351
|
+
total: 0,
|
|
352
|
+
sent: 0,
|
|
353
|
+
failed: 0,
|
|
330
354
|
actionStatus: {
|
|
331
|
-
alternateName: '
|
|
355
|
+
alternateName: 'FailedActionStatus' },
|
|
332
356
|
|
|
357
|
+
description: err.message };
|
|
333
358
|
|
|
334
359
|
// and save
|
|
335
360
|
return await context.model('SendInstructorTokenAction').silent().save(sendTokensAction);
|