66 lines
1.7 KiB
JavaScript
66 lines
1.7 KiB
JavaScript
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);
|
|
}
|
|
next();
|
|
}
|
|
|
|
Address.beforeRemote('prototype.updateAttributes',function(ctx, modelInstance, next){
|
|
var data = ctx.req.body;
|
|
data.id = ctx.req.params.id;
|
|
getAddress(ctx, data, next);
|
|
});
|
|
|
|
function getAddress(ctx, data, next){
|
|
var address = Address.findOne( {where: { id: data.id}}, function (err, address){
|
|
if(address)
|
|
callbackGetAddress(ctx, data, address, next)
|
|
});
|
|
}
|
|
|
|
function callbackGetAddress(ctx, data, address, next){
|
|
if (data.default){
|
|
removeAllDefault(address.client);
|
|
next();
|
|
}
|
|
else if (address.default && !data.default)
|
|
next(generateErrorDefaultAddress());
|
|
else
|
|
next();
|
|
}
|
|
|
|
function getData(ctx){
|
|
if (ctx.data)
|
|
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;
|
|
}
|
|
|
|
|
|
};
|
|
|