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.enabled && this.default) err();
|
|
|
|
}
|
|
|
|
|
2017-01-26 14:00:13 +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-01-26 14:00:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Address.beforeRemote('prototype.updateAttributes',function(ctx, modelInstance, next){
|
|
|
|
var data = ctx.req.body;
|
|
|
|
data.id = ctx.req.params.id;
|
2017-01-30 07:23:18 +00:00
|
|
|
getAddress(ctx, data, next);
|
2017-01-18 09:42:53 +00:00
|
|
|
});
|
2017-01-18 13:48:35 +00:00
|
|
|
|
2017-01-30 07:23:18 +00:00
|
|
|
function getAddress(ctx, data, next){
|
|
|
|
var address = Address.findOne( {where: { id: data.id}}, function (err, address){
|
2017-01-26 14:00:13 +00:00
|
|
|
if(address)
|
2017-07-03 12:23:53 +00:00
|
|
|
callbackGetAddress(ctx, data, address, next);
|
2017-01-26 14:00:13 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function callbackGetAddress(ctx, data, address, next){
|
|
|
|
if (data.default){
|
2017-01-30 07:23:18 +00:00
|
|
|
removeAllDefault(address.client);
|
2017-01-26 14:00:13 +00:00
|
|
|
next();
|
|
|
|
}
|
2017-06-01 06:44:37 +00:00
|
|
|
else if (address.default && data.hasOwnProperty('default') && !data.default)
|
2017-01-26 14:00:13 +00:00
|
|
|
next(generateErrorDefaultAddress());
|
2017-01-30 07:23:18 +00:00
|
|
|
else
|
|
|
|
next();
|
2017-01-26 14:00:13 +00:00
|
|
|
}
|
|
|
|
|
2017-01-18 13:48:35 +00:00
|
|
|
function getData(ctx){
|
2017-01-26 14:00:13 +00:00
|
|
|
if (ctx.data)
|
2017-01-18 13:48:35 +00:00
|
|
|
return ctx.data;
|
|
|
|
else
|
|
|
|
return ctx.instance;
|
|
|
|
}
|
|
|
|
|
2017-01-26 14:00:13 +00:00
|
|
|
function removeAllDefault(cl){
|
|
|
|
Address.update({client: cl}, {default: false});
|
|
|
|
}
|
|
|
|
|
|
|
|
function generateErrorDefaultAddress(){
|
|
|
|
var error = new Error();
|
|
|
|
error.message = "No se puede desmarcar el consignatario predeterminado";
|
|
|
|
error.status = 500;
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|