@universis/dining
Version:
Universis api for dining
410 lines (363 loc) • 16.6 kB
JavaScript
import {DataError} from "@themost/common";
import { HttpForbiddenError } from '@themost/common/errors';
import { DataObjectState, DataModel } from "@themost/data";
// eslint-disable-next-line no-unused-vars
async function beforeSaveAsync(event) {
let runAllRules = false;
const user = event.model.context.user;
const target = event.model.convert(event.target);
const context = event.model.context;
let studentId = target.student;
let action;
let eventHasConsent;
if (!Object.prototype.hasOwnProperty.call(target,'student')) {
const actionID = event.target || event.target.id;
action = await context.model('DiningRequestAction')
.where('id')
.equal(actionID)
.select('student','diningRequestEvent/hasConsent as hasConsent','studentConsent')
.getItem();
studentId = action.student;
}
if (!studentId) {
throw new DataError('E_STUDENT', 'The student cannot be empty at this context.');
}
const student = event.model.context.model('Student').convert(studentId);
const isMe = await student.is(':me');
if (isMe) {
const isActive = await student.is(':active');
if (!isActive) {
throw new HttpForbiddenError();
}
const diningRequestEvent = target.diningRequestEvent || target.diningRequestEvent.id;
eventHasConsent = await context.model('DiningRequestEvent')
.where('id')
.equal(diningRequestEvent)
.select('hasConsent')
.silent()
.value();
}
if (event.state === 2) {
if (isMe === true) {
//check studentConsent
if (event.target && eventHasConsent === true && Object.prototype.hasOwnProperty.call(target, 'studentConsent') === false) {
const translateService = context.application.getStrategy(function TranslateService() { });
throw new DataError('E_STUDENT_CONSENT', translateService.translate('The application cannot be saved without consent about personal data.'), null, 'DiningRequestAction', 'studentConsent');
} else if (event.target && eventHasConsent === true && Object.prototype.hasOwnProperty.call(target, 'studentConsent') === true && target.studentConsent === false) {
const translateService = context.application.getStrategy(function TranslateService() { });
throw new DataError('E_STUDENT_CONSENT', translateService.translate('The application cannot be saved without consent about personal data.'), null, 'DiningRequestAction', 'studentConsent');
}
//check category
if (target && (Object.prototype.hasOwnProperty.call(target, 'category') && (target.category == null))) {
throw new HttpForbiddenError(
context.__(
'The dining request creation failed because no request category has been set.'
)
);
}
}
//UPDATE
//Load current status
const actionStatus = await event.model.where('id').equal(event.target.id).select('actionStatus/alternateName').value();
//Action is not submitted yet. Run again all rules
if (actionStatus === 'PotentialActionStatus') {
runAllRules = true;
}
else if (actionStatus === 'ActiveActionStatus' || actionStatus === 'CompletedActionStatus'){
//Dining request already submitted. Do not allow to update any property
removeAllInformationExceptStatus(event.target);
}
else if (actionStatus === 'CancelledActionStatus' && event.target.actionStatus && event.target.actionStatus.alternateName !== actionStatus && event.target.actionStatus.alternateName != 'ActiveActionStatus') {
//Dining request already cancelled.
throw new DataError('E_VALUE', 'Cannot update cancelled action.', null, 'DiningRequestAction', 'actionStatus');
}
// allow agent to change request's status when target request status = 'ActiveActionStatus' example: to reconsider a cancelled request
else if (actionStatus === 'CancelledActionStatus' && event.target.actionStatus && event.target.actionStatus.alternateName !== actionStatus && event.target.actionStatus.alternateName === 'ActiveActionStatus') {
let model = event.target;
// set loggedIn user as request's agent
if (event.previous.agent != user.id) {
model.agent = user.id;
}
}
}
else if (event.state === 1) {
// check studentConsent
if (isMe === true && eventHasConsent === true) {
if (Object.prototype.hasOwnProperty.call(target, 'studentConsent') === false) {
const translateService = context.application.getStrategy(function TranslateService() { });
throw new DataError('E_STUDENT_CONSENT', translateService.translate('The application cannot be saved without consent about personal data.'), null, 'DiningRequestAction', 'studentConsent');
} else if (eventHasConsent === true && target.studentConsent === false) {
const translateService = context.application.getStrategy(function TranslateService() { });
throw new DataError('E_STUDENT_CONSENT', translateService.translate('The application cannot be saved without consent about personal data.'), null, 'DiningRequestAction', 'studentConsent');
}
}
if (target && (Object.prototype.hasOwnProperty.call(target, 'category') === false || (target.category == null))) {
throw new HttpForbiddenError(
context.__(
'The dining request creation failed because no request category has been set.'
)
);
}
runAllRules = true;
}
if (runAllRules){
// set nullable fields to null when they don't need to have a value
let model = event.target;
if (Object.prototype.hasOwnProperty.call(model, 'militaryActive')) {
if (model.militaryActive == true) {
applyRulesForPrerequisites(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'militarySchool')) {
if (model.militarySchool == true) {
applyRulesForPrerequisites(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'studentHouseResident')) {
if (model.studentHouseResident == true) {
applyRulesForPrerequisites(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'sameDegreeHolder')) {
if (model.sameDegreeHolder == true) {
applyRulesForPrerequisites(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'foreignScholarStudent')) {
if (model.foreignScholarStudent == true) {
applyRulesForPrerequisites(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'cyprusStudent')) {
if (model.cyprusStudent == true) {
applyRulesForCyprusStudentOrForeignStudentOrChildOfGreekExpatriate(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'foreignStudentOrChildOfGreekExpatriate')) {
if (model.foreignStudentOrChildOfGreekExpatriate == true) {
applyRulesForCyprusStudentOrForeignStudentOrChildOfGreekExpatriate(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'studentReceivesUnemploymentBenefit')) {
if (model.studentReceivesUnemploymentBenefit == true){
model.institutionOrClubLocationSameAsStudentPermanentResidence = null;
model.studentSubmitsTaxReportInGreece = null;
nullifyFamilyInformation(model);
nullifyGuardianFinancialInformation(model);
nullifySpouseFinancialInformation(model);
nullifyStudentFinancialInformation(model);
return;
}
}
if (Object.prototype.hasOwnProperty.call(model, 'maritalStatus')) {
if (model.maritalStatus && model.maritalStatus.alternateName == 'single') {
model.noOfChildren = null;
nullifySpouseFinancialInformation(model);
if (model.guardianType.alternateName == 'nobody') {
model.institutionOrClubLocationSameAsGuardianPermanentResidence = null;
model.guardianNoOfChildren = null;
model.numberOfStudyingSiblings = null;
nullifyGuardianFinancialInformation(model);
}
}
else {
model.guardianType = null;
model.institutionOrClubLocationSameAsGuardianPermanentResidence = null;
model.guardianNoOfChildren = null;
model.numberOfStudyingSiblings = null;
nullifyGuardianFinancialInformation(model);
if (model.maritalStatus && model.maritalStatus.alternateName != 'married') {
nullifySpouseFinancialInformation(model);
}
}
}
}
}
function applyRulesForPrerequisites(model) {
//nullify all other properties except foreignScholarStudent, inscriptionModeTag, lessThan25yrs and allInformationSubmittedIsTrueConfirmation
nullifyPersonalInformation(model);
nullifyFamilyInformation(model);
nullifyGuardianFinancialInformation(model);
nullifySpouseFinancialInformation(model);
nullifyStudentFinancialInformation(model);
}
function applyRulesForCyprusStudentOrForeignStudentOrChildOfGreekExpatriate(model) {
//Only these from personal information
// model.studentReceivesUnemploymentBenefit = null;
// model.institutionOrClubLocationSameAsStudentPermanentResidence = null;
// model.studentSubmitsTaxReportInGreece = null;
// nullifyFamilyInformation(model);
// nullifyGuardianFinancialInformation(model);
// nullifySpouseFinancialInformation(model);
//Only this from personal financial information
model.studentAfm = null;
}
function nullifyPersonalInformation(model){
model.foreignStudentOrChildOfGreekExpatriate = null;
model.cyprusStudent = null;
model.studentDisabledPerson = null;
model.studentOrphan = null;
model.childOfVictimOfTerrorism = null;
model.studentReceivesUnemploymentBenefit = null;
model.studentSubmitsTaxReportInGreece = null;
model.institutionOrClubLocationSameAsStudentPermanentResidence = null;
}
function nullifyFamilyInformation(model){
model.noOfChildren = null;
model.maritalStatus = null;
model.numberOfStudyingSiblings = null;
model.guardianNoOfChildren = null;
model.guardianType = null;
model.institutionOrClubLocationSameAsGuadianPermanentResidence = null;
}
function nullifyGuardianFinancialInformation(model){
model.studentGuardianTotalIncome = null;
model.studentGuardianAfm = null;
model.studentGuardianReceivesUnemploymentBenefit = null;
model.studentGuardianSubmitsTaxReportInGreece = null;
}
function nullifySpouseFinancialInformation(model){
model.studentSpouseTotalIncome = null;
model.studentSpouseAfm = null;
model.studentSpouseReceivesUnemploymentBenefit = null;
}
function nullifyStudentFinancialInformation(model){
model.studentTotalIncome = null;
model.studentAfm = null;
}
function removeAllInformationExceptStatus(model){
delete model.militaryActive;
delete model.militarySchool;
delete model.studentHouseResident;
delete model.sameDegreeHolder;
delete model.foreignScholarStudent;
delete model.lessThan25yrs;
delete model.institutionOrClubLocationSameAsStudentPermanentResidence;
delete model.studentDisabledPerson;
delete model.studentOrphan;
delete model.numberOfStudyingSiblings ;
delete model.maritalStatus;
delete model.noOfChildren;
delete model.guardianType;
delete model.institutionOrClubLocationSameAsGuadianPermanentResidence;
delete model.guardianNoOfChildren;
delete model.studentReceivesUnemploymentBenefit;
delete model.childOfVictimOfTerrorism;
delete model.studentSubmitsTaxReportInGreece;
delete model.studentGuardianSubmitsTaxReportInGreece;
delete model.studentAfm;
delete model.studentTotalIncome;
delete model.studentSpouseReceivesUnemploymentBenefit;
delete model.studentSpouseAfm;
delete model.studentSpouseTotalIncome;
delete model.studentGuardianReceivesUnemploymentBenefit ;
delete model.cyprusStudent;
delete model.foreignStudentOrChildOfGreekExpatriate;
delete model.studentGuardianAfm;
delete model.studentGuardianTotalIncome;
delete model.allInformationSubmittedIsTrueConfirmation;
}
async function afterSaveAsync(event) {
// on insert
if (event.state === DataObjectState.Insert && event.target.diningRequestEvent) {
const context = event.model.context;
// try to find if the student has declared a preference on the event
const diningRequestPreference = await context.model('DiningRequestPreference')
.where('student').equal(event.target.student.id || event.target.student)
.and('diningRequestEvent').equal(event.target.diningRequestEvent.id || event.target.diningRequestEvent)
.select('id')
.silent()
.getItem();
if (diningRequestPreference == null) {
return;
}
// link request to preference
diningRequestPreference.action = event.target.id;
// and update preference
await context.model('DiningRequestPreference').silent().save(diningRequestPreference);
}
}
async function beforeRemoveAsync(event) {
const model = event.model;
const getReferenceMappings = DataModel.prototype.getReferenceMappings;
model.getReferenceMappings = async function () {
const res = await getReferenceMappings.bind(this)();
// remove dining request preference mappings before remove
// to prevent an unnecessary save here
// note: after remove also nullifies the preference "action" link
const mappings = ['DiningRequestPreference'];
return res.filter((mapping) => {
return mappings.indexOf(mapping.childModel) < 0;
});
};
}
async function afterRemoveAsync(event) {
const context = event.model.context;
// try to find if a preference exists for that event
const diningRequestPreference = await context.model('DiningRequestPreference')
.where('student').equal(event.previous.student)
.and('diningRequestEvent').equal(event.previous.diningRequestEvent)
.select('id')
.silent()
.getItem();
if (diningRequestPreference == null) {
return;
}
// alter the preference to false
diningRequestPreference.preference = false;
// nullify linked action
diningRequestPreference.action = null;
// and update preference
await context.model('DiningRequestPreference').silent().save(diningRequestPreference);
}
/**
* @param {DataEventArgs} event
* @param {Function} callback
*/
export function beforeSave(event, callback) {
return beforeSaveAsync(event).then(() => {
return callback();
}).catch((err) => {
return callback(err);
});
}
/**
* @param {DataEventArgs} event
* @param {Function} callback
*/
export function afterSave(event, callback) {
return afterSaveAsync(event).then(() => {
return callback();
}).catch((err) => {
return callback(err);
});
}
/**
* @param {DataEventArgs} event
* @param {Function} callback
*/
export function afterRemove(event, callback) {
return afterRemoveAsync(event).then(() => {
return callback();
}).catch((err) => {
return callback(err);
});
}
/**
* @param {DataEventArgs} event
* @param {Function} callback
*/
export function beforeRemove(event, callback) {
return beforeRemoveAsync(event).then(() => {
return callback();
}).catch((err) => {
return callback(err);
});
}