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

62 lines
1.7 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.enabled && this.default) err();
}
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();
}
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){
if(address)
2017-07-03 12:23:53 +00:00
callbackGetAddress(ctx, data, address, next);
});
}
function callbackGetAddress(ctx, data, address, next){
if (data.default){
2017-01-30 07:23:18 +00:00
removeAllDefault(address.client);
next();
}
else if (address.default && data.hasOwnProperty('default') && !data.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;
}
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;
}
};