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

74 lines
2.2 KiB
JavaScript

module.exports = function(Address) {
Address.validate('default',isEnabled,{message: 'No se puede poner predeterminado un consignatario desactivado'});
function isEnabled(err) {
if (!this.isEnabled && this.isDefaultAddress) err();
}
Address.beforeRemote('create',function(ctx, modelInstance, next){
var data = ctx.req.body;
create(data, next);
});
function create(data, next){
if(data.isDefaultAddress){
removeAllDefault(data.client, next);
} else {
next();
}
}
Address.beforeRemote('prototype.patchAttributes',function(ctx, modelInstance, next){
let newData = ctx.req.body;
newData.id = ctx.req.params.id;
getAddress(ctx, newData, next);
});
Address.beforeRemote('findById', function(ctx, modelInstance, next) {
ctx.args.filter = {
"include": {
"relation": "province",
"scope": {
"fields": ["id", "name"]
}
}
};
next();
});
function getAddress(ctx, newData, next){
Address.findOne( {where: { id: newData.id}}, function (err, oldData){
if(oldData)
callbackGetAddress(ctx, newData, oldData, next);
});
}
function callbackGetAddress(ctx, newData, oldData, next){
if (newData.isDefaultAddress){
removeAllDefault(oldData.client, next);
}
else if (oldData.isDefaultAddress && newData.hasOwnProperty('isDefaultAddress') && !newData.isDefaultAddress)
next(generateErrorDefaultAddress());
else
next();
}
function getData(ctx){
if (ctx.data)
return ctx.data;
else
return ctx.instance;
}
function removeAllDefault(client, next){
Address.updateAll({clientFk: client.id, isDefaultAddress: true}, {isDefaultAddress: false}, next);
}
function generateErrorDefaultAddress(){
var error = new Error();
error.message = "No se puede desmarcar el consignatario predeterminado";
error.status = 500;
return error;
}
};