alphascript-server
Version:
CRUD operations for mongo and other functionalities to get started quickly in any CMS project
113 lines (87 loc) • 3.08 kB
JavaScript
var api = require('../../../../');
var moment = require('moment');
module.exports = {
collection: function () {
return api.common.License;
},
populate: "owner customer",
sort: { updated_at: -1 },
query: function (req, pageId, pageAction) {
if (req.user.role.admin) {
return {};
}
return { customer: req.user.owner._id };
},
validate: function (data, callback, req) {
if (!data.customer) return callback("O campo cliente é obrigatório");
if (!data.dateStart) return callback("O campo data início é obrigatório");
var start = moment(data.dateStart);
if (!start.isValid) return callback("Data início inválida");
if (!data.dateEnd) return callback("O campo data fim é obrigatório");
var end = moment(data.dateEnd);
if (!end.isValid()) return callback("Data fim inválida");
if (start >= end) return callback("Periodo de licenciamento inválido");
isLicensed(data.customer, function (err, licenses, isValid) {
if (err) {
api.error.log(err);
return callback(api.error.DB_GENERIC);
}
var collision = api.date.collisionDetection(data.dateStart, data.dateEnd, licenses || []);
if (collision && !data._id) return callback('Módulo já licenciado no intervalo de datas indicado');
callback();
});
},
beforeAdd: function (data, callback, req) {
data.owner = req.user._id;
callback(null, data);
},
afterAdd: function (data, callback) {
callback(null, data);
},
beforeEdit: function (data, callback, req) {
data.owner = req.user._id;
callback(null, data);
},
afterEdit: function (data, callback) {
callback(null, data);
},
remove: function (id, callback) {
callback("Não é permitido remover licenciamentos");
},
isValid: function (req, res) {
if (!req.user) return res.sendStatus(401); //unauthorized
var moduleId = req.params.module || null;
if (!moduleId) return res.sendStatus(400); //bad request
isValid(moduleId, function (err, isValid) {
if (err) return res.status(500).send(err);
res.send(isValid);
});
},
isLicensed: isLicensed,
_isValid: isValid,
_isLicensed: isLicensed
};
function isValid(req, moduleId) {
isLicensed(req.user.owner._id, function (err, licenses, isValid) {
if (err) return callback(err);
if (!isValid) return callback(null, false);
var hasModule = licenses[0].modules.some(function (licensedModule) {
return licensedModule === moduleId;
});
callback(null, hasModule);
});
}
function isLicensed(owner, callback) {
api.common.License.find({ customer: owner }).sort({ dateStart: -1 }).lean().exec(function (err, licenses) {
if (err) {
api.error.log(err);
return callback(api.error.DB_GENERIC);
}
if (licenses.length === 0) return callback(null, null, false);
var now = new Date();
var isValid = licenses.some(function (license) {
return (now <= license.dateEnd && now >= license.dateStart);
});
callback(null, licenses, isValid);
});
}