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

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-10-11 13:36:47 +00:00
module.exports = function(Self) {
Self.validate('default',isEnabled,{message: 'No se puede poner predeterminado un consignatario desactivado'});
2017-01-18 09:42:53 +00:00
function isEnabled(err) {
if (!this.isEnabled && this.isDefaultAddress) err();
2017-01-18 09:42:53 +00:00
}
2017-10-11 13:36:47 +00:00
Self.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();
}
}
2017-10-11 13:36:47 +00:00
Self.beforeRemote('prototype.patchAttributes',function(ctx, modelInstance, next){
2017-09-28 12:34:18 +00:00
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
2017-10-11 13:36:47 +00:00
Self.beforeRemote('findById', function(ctx, modelInstance, next) {
2017-09-28 09:29:01 +00:00
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){
2017-10-11 13:36:47 +00:00
Self.findOne( {where: { id: newData.id}}, function (err, oldData){
2017-09-28 12:34:18 +00:00
if(oldData)
callbackGetAddress(ctx, newData, oldData, next);
});
}
2017-09-28 12:34:18 +00:00
function callbackGetAddress(ctx, newData, oldData, next){
if (newData.isDefaultAddress){
2017-09-28 12:34:18 +00:00
removeAllDefault(oldData.client, next);
}
else if (oldData.isDefaultAddress && newData.hasOwnProperty('isDefaultAddress') && !newData.isDefaultAddress)
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){
2017-10-11 13:36:47 +00:00
Self.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;
}
};