UNPKG

@universis/dining

Version:

Universis api for dining

194 lines (70 loc) 8.46 kB
"use strict"; var _data = require("@themost/data"); var _common = require("@themost/common"); var _moment = _interopRequireDefault(require("moment"));var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _class, _class2;function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {var desc = {};Object.keys(descriptor).forEach(function (key) {desc[key] = descriptor[key];});desc.enumerable = !!desc.enumerable;desc.configurable = !!desc.configurable;if ('value' in desc || desc.initializer) {desc.writable = true;}desc = decorators.slice().reverse().reduce(function (desc, decorator) {return decorator(target, property, desc) || desc;}, desc);if (context && desc.initializer !== void 0) {desc.value = desc.initializer ? desc.initializer.call(context) : void 0;desc.initializer = undefined;}if (desc.initializer === void 0) {Object.defineProperty(target, property, desc);desc = null;}return desc;} /** * @class * @property {number} id * @property {number} serialNumber * @property {boolean} active * @property {string} cancelReason * @property {string} notes * @property {DiningRequestAction|any} action * @property {AcademicYear|any} academicYear * @property {AcademicPeriod|any} academicPeriod * @property {Date} dateCreated * @property {Date} dateModified * @property {Date} validFrom * @property {Date} validThrough * @property {User|any} student */let StudentDiningCard = (_dec = _data.EdmMapping.entityType('StudentDiningCard'), _dec2 = _data.EdmMapping.param('data', 'Object', false, true), _dec3 = _data.EdmMapping.action('cancel', 'StudentDiningCard'), _dec4 = _data.EdmMapping.param('data', 'Object', false, true), _dec5 = _data.EdmMapping.action('analytics', _data.EdmType.CollectionOf('StudentDiningCard')), _dec6 = _data.EdmMapping.param('data', 'Object', false, true), _dec7 = _data.EdmMapping.action('cancelExpired', _data.EdmType.CollectionOf('Object')), _dec(_class = (_class2 = class StudentDiningCard extends _data.DataObject {/** * @constructor */constructor() {super();} /** * POST StudentDiningCards/:id/Cancel */async cancel(data) {if (!data.cancelReason) {throw new _common.DataError('E_CANCEL_REASON', 'Cancel Reason should be provided');}await this.context.executeInTransactionAsync(async () => {// find StudentDiningCard from id const studentDiningCard = await this.context.model('StudentDiningCard').where('id').equal(this.getId()).select('id', 'active', 'action', 'student', 'academicPeriod', 'academicYear').flatten().getItem(); // validate existance and permission if (studentDiningCard == null) {throw new _common.DataNotFoundError('The specified Student Dining Card cannot be found or is inaccessible');} // studentDiningCard already cancelled throw error if (studentDiningCard.active === false) {throw new _common.DataError('E_ACTIVE', 'The specified Student Dining Card is already cancelled');} //validate DiningRequestAction if (studentDiningCard.action == null) {throw new _common.DataError('E_ACTION', 'The Student Dining Card is not linked to a Dining Request Action');} // cancel studentDiningCard studentDiningCard.active = false;studentDiningCard.cancelReason = data.cancelReason;studentDiningCard.dateCancelled = new Date();await this.context.model('StudentDiningCard').save(studentDiningCard);const action = await this.context.model('DiningRequestAction').where('id').equal(studentDiningCard.action).select('id', 'actionStatus/alternateName as requestStatus').getItem(); //validate DiningRequestAction if (action == null) {throw new _common.DataError('E_ACTION', 'The specified DiningRequestAction cannot be found or is inaccessible');}if (action.requestStatus !== 'CompletedActionStatus') {throw new _common.DataError('E_ACTION', 'The specified DiningRequestAction is not in Completed state');}action.actionStatus = { alternateName: "ActiveActionStatus" };delete action.requestStatus;await this.context.model('DiningRequestAction').save(action);});} /** * POST StudentDiningCards/analytics */static async analytics(context, data) {_common.Args.notEmpty(data, 'Data');_common.Args.notEmpty(data.validFrom, 'Valid from');_common.Args.notEmpty(data.validThrough, 'Valid through');const validFrom = (0, _moment.default)(new Date(data.validFrom)).startOf('day').toDate(); // get only date format const validThrough = (0, _moment.default)(new Date(data.validThrough)).endOf('day').toDate(); // get only date format const model = context.model('StudentDiningCard');const queryCards = model.where('date(validThrough)').greaterOrEqual(validFrom).and('date(validFrom)').lowerOrEqual(validThrough);if (data.department) {const localDepartment = await context.model('LocalDepartment').where('id').equal(data.department).getItem();if (localDepartment == null) {throw new _common.DataNotFoundError('Department not found or is inaccessible.', null, 'LocalDepartment');}queryCards.and('student/department').equal(data.department);}if (data.location) {_common.Args.notNumber(data.location, 'Location');const location = await context.model('DiningPlace').where('id').equal(data.location).getItem();if (location == null) {throw new _common.DataNotFoundError('Location not found or is inaccessible.', null, 'DiningPlace');}queryCards.and('location').equal(data.location);}const cards = await queryCards.getAllItems();const dates = enumerateDaysBetweenDates(validFrom, validThrough);let previousActive = 0;for (let i = 0; i < dates.length; i++) {const checkDate = dates[i].date;dates[i].active = cards.filter(x => {const startDate = (0, _moment.default)(new Date(x.validFrom)).startOf('day').toDate();let endDate = x.dateCancelled || x.validThrough;endDate = (0, _moment.default)(new Date(endDate)).startOf('day').toDate();return (0, _moment.default)(endDate) >= (0, _moment.default)(checkDate) && (0, _moment.default)(startDate) <= (0, _moment.default)(checkDate);}).length; // Delta is a commonly used term in mathematics and science to represent the difference or change between two values. dates[i].delta = dates[i].active - previousActive;previousActive = dates[i].active;}return dates;} /** * POST StudentDiningCards/CancelExpired */static async cancelExpired(context, data) {const translateService = context.application.getStrategy(function TranslateService() {});const todayDate = (0, _moment.default)(new Date()).startOf('day').toDate(); // if there are find active diningCards that have expired const cardsToCancel = await context.model('StudentDiningCards').where('active').equal(true).and('validThrough').lowerThan(todayDate).silent().getAllItems(); // if there are, set active to false, set system cancelReason and save if (Array.isArray(cardsToCancel)) {if (cardsToCancel.length > 0) { const cancelReason = data.cancelReason || translateService.translate('StudentDiningCardSystemCancelReasonDiningRequestEventExpired'); cardsToCancel.map(el => { el.active = false; el.cancelReason = cancelReason; el.dateCancelled = new Date(); return el; }); await context.model('StudentDiningCard').silent().save(cardsToCancel); } _common.TraceUtils.log("Dining: Automatically Canceled " + cardsToCancel.length + " StudentDiningCards"); return { "totalCancelled": cardsToCancel.length }; } }}, (_applyDecoratedDescriptor(_class2.prototype, "cancel", [_dec2, _dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "cancel"), _class2.prototype), _applyDecoratedDescriptor(_class2, "analytics", [_dec4, _dec5], Object.getOwnPropertyDescriptor(_class2, "analytics"), _class2), _applyDecoratedDescriptor(_class2, "cancelExpired", [_dec6, _dec7], Object.getOwnPropertyDescriptor(_class2, "cancelExpired"), _class2)), _class2)) || _class); function enumerateDaysBetweenDates(startDate, endDate) { let firstDate = (0, _moment.default)(startDate).format('YYYY-MM-DD'); const dates = []; while ((0, _moment.default)(firstDate) <= (0, _moment.default)(endDate)) { dates.push({ date: firstDate, active: 0 }); firstDate = (0, _moment.default)(firstDate).add(1, 'days').format("YYYY-MM-DD"); } return dates; } module.exports = StudentDiningCard; //# sourceMappingURL=StudentDiningCard.js.map