@universis/candidates
Version:
Universis api server plugin for study program candidates, internship selection etc
227 lines (109 loc) • 8.04 kB
JavaScript
;Object.defineProperty(exports, "__esModule", { value: true });exports.afterSave = afterSave;exports.StudentCarePreferenceService = void 0;var _data = require("@themost/data");
var _common = require("@themost/common");
var _semver = require("semver");
var _path = _interopRequireDefault(require("path"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {Promise.resolve(value).then(_next, _throw);}}function _asyncToGenerator(fn) {return function () {var self = this,args = arguments;return new Promise(function (resolve, reject) {var gen = fn.apply(self, args);function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);}function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);}_next(undefined);});};}
/**
*
* @param {DataEventArgs} event
*/function
afterSaveAsync(_x) {return _afterSaveAsync.apply(this, arguments);}
/**
* @param {DataEventArgs} event
* @param {Function} callback
*/function _afterSaveAsync() {_afterSaveAsync = _asyncToGenerator(function* (event) {// operate only on update (active to completed status)
if (!(event.state === _data.DataObjectState.Update && event.target.hasOwnProperty('actionStatus'))) {return;}const context = event.model.context; // before everything, validate the required service/models that this listener handles
// first, the dining service itself
const diningService = context.getApplication().getStrategy(function DiningService() {});if (diningService == null) {_common.TraceUtils.info('[StudentCarePreferenceService]: DiningService is not enabled and thus a DiningRequestPreference cannot be created.');return;} // then, validate DiningPreference
// note: at a later stage, the getDiningPreferenceEffective student status method is validated
// which covers the existance of all the other related models
const diningPreferenceModel = context.model('DiningRequestPreference');if (diningPreferenceModel == null) {_common.TraceUtils.info('[StudentCarePreferenceService]: DiningRequestPreference model is absent in the current application context and thus a DiningRequestPreference cannot be created.');return;} // get previous action status
const previousActionStatus = event.previous && event.previous.actionStatus;if (previousActionStatus == null) {throw new _common.DataError('E_PREVIOUS_STATUS', 'The previous action status of the object cannot be empty at this context.', null, 'StudyProgramRegisterAction');} // and target action status
const targetActionStatus = yield context.model('ActionStatusType').find(event.target.actionStatus).select('alternateName').value(); // if this is not an accept action, exit
if (!(previousActionStatus.alternateName === 'ActiveActionStatus' && targetActionStatus === 'CompletedActionStatus')) {return;} // get the dining preference value from the register action
const enrollmentDiningPreference = yield context.model('StudyProgramRegisterAction').where('id').equal(event.target.id).select('intendsToApplyForDining').silent().value(); // important: proceed only if enrollmentDiningPreference is of type boolean
// which means that it has actually been declared by the student
// this field, of course, does not have a default value and may be null
if (typeof enrollmentDiningPreference !== 'boolean') {return;} // ensure that a student has been created for the candidate
const student = context.model('Student').convert(yield context.model('CandidateStudent').find(event.previous.candidate).select('student as id').flatten().getItem());if (student == null) {return;} // validate getDiningPreferenceEffectiveStatus method
if (typeof student.getDiningPreferenceEffectiveStatus !== 'function') {_common.TraceUtils.info('[StudentCarePreferenceService]: The DiningPreference creation is not supported by the current DiningService version.');return;} // get diningRequestEvent event from effective status method
const { diningRequestEvent } = yield student.getDiningPreferenceEffectiveStatus(); // and validate it
if (diningRequestEvent == null) {return;} // create a dining preference
const diningRequestPreference = { student: student.id, diningRequestEvent, preference: enrollmentDiningPreference }; // and save silently
yield diningPreferenceModel.silent().save(diningRequestPreference);});return _afterSaveAsync.apply(this, arguments);}function afterSave(event, callback) {return afterSaveAsync(event).then(() => {return callback();}).catch(err => {return callback(err);});}class StudentCarePreferenceService extends _common.ApplicationService {constructor(app) {super(app);this.install();}install() {try {/**
* get data configuration
* @type {DataConfigurationStrategy}
*/
const configuration = this.getApplication().
getConfiguration().
getStrategy(_data.DataConfigurationStrategy);
// get StudyProgramRegisterAction model definition
const model = configuration.getModelDefinition(
'StudyProgramRegisterAction');
if (model == null) {
throw new Error(
'The StudyProgramRegisterAction model cannot be found in the current application context, or it has not been loaded yet.');
}
// ensure model fields
model.fields = model.fields || [];
let updateModelDefinition = false;
// apply extra attributes/fields
[
{
name: 'intendsToApplyForDining',
title: 'Dining preference',
description:
'Indicates whether the student intends to receive dining services from the university facilities.',
type: 'Boolean' },
{
name: 'intendsToApplyForHousing',
title: 'Housing preference',
description:
'Indicates whether the student intends to receive housing services from the university facilities.',
type: 'Boolean' }].
forEach(attribute => {
// try to find attribute
const attributeExists = model.fields.find(
field => field.name === attribute.name);
if (attributeExists) {
return;
}
// if it does not exist, add it to the fields collection
model.fields.push(attribute);
updateModelDefinition = true;
});
// get this file path relative to application execution path
const listenerType =
'./' +
_path.default.relative(
this.getApplication().getConfiguration().getExecutionPath(),
__filename);
// ensure model event listeners
model.eventListeners = model.eventListeners || [];
// try to find event listener
const findIndex = model.eventListeners.findIndex(listener => {
return (
listener.type === listenerType ||
listener.type === listenerType.replace(/\.js$/, ''));
});
if (findIndex < 0) {
// add event listener
model.eventListeners.push({
type: listenerType });
updateModelDefinition = true;
}
if (!updateModelDefinition) {
return;
}
// update model version for migrations
model.version = (0, _semver.inc)((0, _semver.valid)((0, _semver.coerce)(model.version || '1.0.0')), 'minor');
configuration.setModelDefinition(model);
// write to log
_common.TraceUtils.info(
`Services: ${this.constructor.name} service has been successfully installed.`);
} catch (err) {
_common.TraceUtils.error(
`An error occured while trying to install ${this.constructor.name} service.`);
_common.TraceUtils.error(err);
}
}}exports.StudentCarePreferenceService = StudentCarePreferenceService;
//# sourceMappingURL=StudentCarePreferenceService.js.map