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

66 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-10-11 13:36:47 +00:00
module.exports = function(Self) {
2017-10-19 07:12:27 +00:00
Self.validate('default', isEnabled, {message: 'No se puede poner predeterminado un consignatario desactivado'});
2017-01-18 09:42:53 +00:00
function isEnabled(err) {
2017-10-19 07:12:27 +00:00
if (!this.isEnabled && this.isDefaultAddress) err();
2017-01-18 09:42:53 +00:00
}
2017-10-19 07:12:27 +00:00
Self.beforeRemote('create', function(ctx, modelInstance, next) {
var data = ctx.req.body;
create(data, next);
});
2017-10-19 07:12:27 +00:00
function create(data, next) {
if (data.isDefaultAddress) {
removeAllDefault(data.client, next);
2017-10-19 07:12:27 +00:00
} else {
next();
}
}
2017-10-19 07:12:27 +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 = {
2017-10-19 07:12:27 +00:00
"include": {
2017-09-28 09:29:01 +00:00
"relation": "province",
"scope": {
"fields": ["id", "name"]
}
}
};
next();
});
2017-01-18 13:48:35 +00:00
2017-10-19 07:12:27 +00:00
function getAddress(ctx, newData, next) {
Self.findOne({where: {id: newData.id}}, (_, oldData) => {
if (oldData)
2017-09-28 12:34:18 +00:00
callbackGetAddress(ctx, newData, oldData, next);
2017-10-19 07:12:27 +00:00
});
}
2017-10-19 07:12:27 +00:00
function callbackGetAddress(ctx, newData, oldData, next) {
if (newData.isDefaultAddress) {
2017-09-28 12:34:18 +00:00
removeAllDefault(oldData.client, next);
2017-10-19 07:12:27 +00:00
} else if (oldData.isDefaultAddress && newData.hasOwnProperty('isDefaultAddress') && !newData.isDefaultAddress) {
next(generateErrorDefaultAddress());
2017-10-19 07:12:27 +00:00
} else
2017-01-30 07:23:18 +00:00
next();
}
2017-10-19 07:12:27 +00:00
function removeAllDefault(client, next) {
2017-10-24 11:37:27 +00:00
Self.updateAll({clientFk: client.id, isDefaultAddress: {neq: 0}}, {isDefaultAddress: false}, next);
}
2017-10-19 07:12:27 +00:00
function generateErrorDefaultAddress() {
var error = new Error();
error.message = "No se puede desmarcar el consignatario predeterminado";
error.status = 500;
return error;
}
};