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