@universis/candidates
Version:
Universis api server plugin for study program candidates, internship selection etc
170 lines (85 loc) • 7.54 kB
JavaScript
;Object.defineProperty(exports, "__esModule", { value: true });exports.afterSave = afterSave;exports.SendSmsAfterCreateCandidateUser = void 0;
var _data = require("@themost/data");
var _common = require("@themost/common");
var _path = _interopRequireDefault(require("path"));
var _mailer = require("@themost/mailer");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) {const context = event.model.context;let shouldContinue = false; // get candidate student user
const user = yield context.model(event.model.name).where('id').equal(event.target.id).select('user').silent().value();if (event.state === _data.DataObjectState.Insert) {shouldContinue = user != null;} else if (event.state === _data.DataObjectState.Update) {const previous = event.previous;if (previous == null) {throw new _common.DataError('E_STATE', 'Invalid configuration. The previous state of an object cannot be determined.', null, 'CandidateStudent');}shouldContinue = previous.user == null && user != null;}if (shouldContinue === false) {// exit
return;} // validate sms service
const service = context.getApplication().getService(function SmsService() {});if (service == null) {throw new Error('Invalid application configuration. Messaging service is missing or is inaccessible state.');} // send sms message
// first of all get register web application
const application = yield context.model('WebApplication').where('alternateName').equal('register').and('applicationSuite').equal('universis').silent().getItem();if (application == null) {throw new _common.DataNotFoundError('A required object for account activation notification is missing. User cannot be notified for this action.', null, 'WebApplication');} // get candidate
const candidate = yield context.model('CandidateStudent').where('user').equal(user).expand('person').silent().getItem();const candidateUser = yield context.model('CandidateUser').where('id').equal(user).silent().getItem(); // assign user
Object.assign(candidate, { user: candidateUser });if (candidate.user == null) {throw new _common.DataNotFoundError('Candidate user cannot be found. The operation cannot be completed.', null, 'CandidateUser', 'activationCode');}if (candidate.user.activationCode == null) {throw new _common.DataError('E_USER', 'User state is invalid. The operation cannot be completed.', null, 'CandidateUser', 'activationCode');}const mailer = (0, _mailer.getMailer)(context);let mailTemplate = yield context.model('MailConfiguration').where('target').equal('NotifyCandidateUserAction').and('state').equal(_data.DataObjectState.Update).silent().getItem();if (mailTemplate == null) {// throw error
throw new _common.DataNotFoundError('Sms template for account activation notification is missing. User cannot be notified for this action.', null, 'MailConfiguration');}const result = yield new Promise((resolve, reject) => {mailer.template(mailTemplate.template).test(true).send({ model: { candidate, application } }, (err, body) => {if (err) {_common.TraceUtils.error('NotifyCandidateUserAction', 'An error occurred while trying to send an sms notification for account activation.');return reject(err);} // send message
return resolve(body);});}); // create message
yield context.model('SMS').silent().save({ sender: context.user, recipient: user, body: result.html });});return _afterSaveAsync.apply(this, arguments);}function afterSave(event, callback) {return afterSaveAsync(event).then(() => {return callback();}).catch(err => {return callback(err);});}class SendSmsAfterCreateCandidateUser extends _common.ApplicationService {/**
* @param {*=} app
*/
constructor(app) {
// call super constructor
super(app);
if (app != null) {
// if application is defined, install service
this.install('CandidateUser', __filename);
}
}
install() {
/**
* get data configuration
* @type {DataConfigurationStrategy}
*/
const configuration = this.getApplication().getConfiguration().getStrategy(_data.DataConfigurationStrategy);
// get StudentRequestAction model definition
const model = configuration.getModelDefinition('CandidateStudent');
// 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 });
// update StudentRequestAction model definition
configuration.setModelDefinition(model);
// write to log
_common.TraceUtils.info(`Services: ${this.constructor.name} service has been successfully installed`);
}
}
/**
* @param {DataContext} context
* @param {{id: number, user: *}} candidate
*/
send(context, candidate) {return _asyncToGenerator(function* () {
const CandidateStudents = context.model('CandidateStudent');
// get candidate and validate
const target = yield CandidateStudents.where('id').equal(candidate).getTypedItem();
if (target == null) {
_common.TraceUtils.error('SendSmsAfterCreateCandidateUser', 'An attempt of sending sms notification to a candidate failed because the specified candidate was not found.');
throw new _common.DataNotFoundError('Candidate cannot be found or is inaccessible', null, 'CandidateStudent');
}
if (target.user == null) {
_common.TraceUtils.error('SendSmsAfterCreateCandidateUser', 'An attempt of sending sms notification to a candidate failed because the specified candidate does not have an associated user or user was not found.');
throw new _common.DataNotFoundError('User cannot be found or is inaccessible', null, 'CandidateUser');
}
yield afterSaveAsync({
model: CandidateStudents, // set event model
state: _data.DataObjectState.Insert, // set state to insert to force sending message
target: target // set candidate as target object
});
return true;})();
}}exports.SendSmsAfterCreateCandidateUser = SendSmsAfterCreateCandidateUser;
//# sourceMappingURL=send-sms-after-create-candidate-user-action.js.map