50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
var UserError = require('../helpers').UserError;
|
|
var getFinalState = require('../helpers').getFinalState;
|
|
var isMultiple = require('../helpers').isMultiple;
|
|
|
|
module.exports = function(Self) {
|
|
Self.validate('isDefaultAddress', isActive,
|
|
{message: 'No se puede poner predeterminado un consignatario desactivado'}
|
|
);
|
|
function isActive(err) {
|
|
if (!this.isActive && this.isDefaultAddress) err();
|
|
}
|
|
|
|
Self.beforeRemote('findById', function(ctx, modelInstance, next) {
|
|
ctx.args.filter = {
|
|
include: [{
|
|
relation: 'province',
|
|
scope: {
|
|
fields: ['id', 'name']
|
|
}
|
|
}, {
|
|
relation: 'agency',
|
|
scope: {
|
|
fields: ['id', 'name']
|
|
}
|
|
}]
|
|
};
|
|
next();
|
|
});
|
|
|
|
// Helpers
|
|
|
|
Self.observe('before save', async function(ctx) {
|
|
if (isMultiple(ctx)) return;
|
|
|
|
let changes = ctx.data || ctx.instance;
|
|
let finalState = getFinalState(ctx);
|
|
|
|
if (changes.isActive == false && finalState.isDefaultAddress)
|
|
throw new UserError('No se puede desmarcar el consignatario predeterminado');
|
|
|
|
if (changes.isDefaultAddress == true) {
|
|
let filter = {
|
|
clientFk: finalState.clientFk,
|
|
isDefaultAddress: {neq: false}
|
|
};
|
|
await Self.updateAll(filter, {isDefaultAddress: false});
|
|
}
|
|
});
|
|
};
|