@universis/dining
Version:
Universis api for dining
100 lines (82 loc) • 2.77 kB
JavaScript
import { DataPermissionEventListener, PermissionMask } from "@themost/data";
import { DataError } from '@themost/common';
import { promisify } from "util";
import moment from 'moment';
async function beforeSaveAsync(event) {
//
if (event.state !== 2) {
return;
}
const context = event.model.context;
const previous = event.previous;
if (previous == null) {
throw new DataError('E_PREVIOUS', 'The previous state of the object cannot be determined');
}
const target = event.target;
if (target.active === false && previous.active === true) {
// get validator listener
const validator = new DataPermissionEventListener();
// noinspection JSUnresolvedFunction
const validateAsync = promisify(validator.validate)
.bind(validator);
// required when user cancels StudentDiningCard and sets the DiningRequest in ActiveActionStatus
// set today (now) studentDiningCard validThrough date
const todayDate = new Date();
if (moment(previous.validThrough).isAfter(todayDate)){
target.validThrough = todayDate;
} else {
target.validThrough = previous.validThrough;
}
// validate StudentDiningCard/Cancel execute permission
const validateEvent = {
model: context.model('StudentDiningCard'),
privilege: 'StudentDiningCard/Cancel',
mask: PermissionMask.Execute,
target: event.target && event.target.id,
throwError: true
}
await validateAsync(validateEvent);
}
}
async function afterSaveAsync(event) {
if (event.state !== 2) {
return;
}
const context = event.model.context;
const previous = event.previous;
if (previous == null) {
throw new DataError('E_PREVIOUS', 'The previous state of the object cannot be determined');
}
const target = event.target;
if (target.active === false && previous.active === true) {
//save
await context.model('CancelDiningCardAction').save({
diningCard: target.id,
actionStatus: {
alternateName: 'CompletedActionStatus'
}
})
}
}
/**
* @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);
});
}