salix/services/client/common/models/address.js

73 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-01-18 09:42:53 +00:00
module.exports = function(Address) {
Address.validate('default',isEnabled,{message: 'No se puede poner predeterminado un consignatario desactivado'});
function isEnabled(err) {
if (!this.isEnabled && this.default) err();
2017-01-18 09:42:53 +00:00
}
Address.beforeRemote('create',function(ctx, modelInstance, next){
var data = ctx.req.body;
create(data, next);
});
function create(data, next){
if(data.default){
removeAllDefault(data.client);
}
2017-01-23 09:56:12 +00:00
next();
}
2017-09-28 12:34:18 +00:00
Address.beforeRemote('prototype.patchAttributes',function(ctx, modelInstance, next){
let newData = ctx.req.body;
newData.id = ctx.req.params.id;
getAddress(ctx, newData, next);
2017-01-18 09:42:53 +00:00
});
2017-09-28 09:29:01 +00:00
Address.beforeRemote('findById', function(ctx, modelInstance, next) {
ctx.args.filter = {
"include": {
"relation": "province",
"scope": {
"fields": ["id", "name"]
}
}
};
next();
});
2017-01-18 13:48:35 +00:00
2017-09-28 12:34:18 +00:00
function getAddress(ctx, newData, next){
Address.findOne( {where: { id: newData.id}}, function (err, oldData){
if(oldData)
callbackGetAddress(ctx, newData, oldData, next);
});
}
2017-09-28 12:34:18 +00:00
function callbackGetAddress(ctx, newData, oldData, next){
if (newData.default){
removeAllDefault(oldData.client, next);
}
2017-09-28 12:34:18 +00:00
else if (oldData.default && newData.hasOwnProperty('default') && !newData.default)
next(generateErrorDefaultAddress());
2017-01-30 07:23:18 +00:00
else
next();
}
2017-01-18 13:48:35 +00:00
function getData(ctx){
if (ctx.data)
2017-01-18 13:48:35 +00:00
return ctx.data;
else
return ctx.instance;
}
2017-09-28 12:34:18 +00:00
function removeAllDefault(client, next){
Address.updateAll({clientFk: client.id, default: true}, {default: false}, next);
}
function generateErrorDefaultAddress(){
var error = new Error();
error.message = "No se puede desmarcar el consignatario predeterminado";
error.status = 500;
return error;
}
};