2018-01-29 11:37:54 +00:00
|
|
|
var UserError = require('../helpers').UserError;
|
|
|
|
var getFinalState = require('../helpers').getFinalState;
|
|
|
|
var isMultiple = require('../helpers').isMultiple;
|
|
|
|
|
|
|
|
module.exports = function(Self) {
|
|
|
|
Self.validate('isDefaultAddress', isActive,
|
2018-01-29 18:57:00 +00:00
|
|
|
{message: 'Unable to default a disabled consignee'}
|
2018-01-29 11:37:54 +00:00
|
|
|
);
|
|
|
|
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']
|
|
|
|
}
|
|
|
|
}, {
|
2018-02-28 11:07:56 +00:00
|
|
|
relation: 'agencyMode',
|
2018-01-29 11:37:54 +00:00
|
|
|
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)
|
2018-01-29 18:57:00 +00:00
|
|
|
throw new UserError('The default consignee can not be unchecked');
|
2018-01-29 11:37:54 +00:00
|
|
|
|
2018-02-03 21:53:02 +00:00
|
|
|
if (changes.isDefaultAddress == true && finalState.isActive != false) {
|
2018-01-29 11:37:54 +00:00
|
|
|
let filter = {
|
|
|
|
clientFk: finalState.clientFk,
|
|
|
|
isDefaultAddress: {neq: false}
|
|
|
|
};
|
|
|
|
await Self.updateAll(filter, {isDefaultAddress: false});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|