156 lines
5.4 KiB
JavaScript
156 lines
5.4 KiB
JavaScript
var app = require('../../server/server');
|
|
|
|
module.exports = function(Self) {
|
|
var models = app.models;
|
|
var loopBackContext = require('loopback-context');
|
|
// Methods
|
|
|
|
require('../methods/client/activate.js')(Self);
|
|
require('../methods/client/addresses.js')(Self);
|
|
require('../methods/client/before-save.js')(Self);
|
|
require('../methods/client/card.js')(Self);
|
|
require('../methods/client/create.js')(Self);
|
|
require('../methods/client/employee.js')(Self);
|
|
require('../methods/client/filter.js')(Self);
|
|
require('../methods/client/roles.js')(Self);
|
|
require('../methods/client/salesperson.js')(Self);
|
|
require('../methods/client/addressesPropagateRe.js')(Self);
|
|
|
|
// Validations
|
|
|
|
Self.validatesUniquenessOf('name', {
|
|
message: 'El nombre debe ser único'
|
|
});
|
|
Self.validatesUniquenessOf('fi', {
|
|
message: 'El NIF/CIF debe ser único'
|
|
});
|
|
Self.validatesPresenceOf('socialName', {
|
|
message: 'Debe especificarse la razón social'
|
|
});
|
|
Self.validatesUniquenessOf('socialName', {
|
|
message: 'La razón social debe ser única'
|
|
});
|
|
Self.validatesFormatOf('postcode', {
|
|
message: 'El código postal solo debe contener números',
|
|
allowNull: true,
|
|
allowBlank: true,
|
|
with: /^\d+$/
|
|
});
|
|
Self.validatesFormatOf('email', {
|
|
message: 'Correo electrónico inválido',
|
|
allowNull: true,
|
|
allowBlank: true,
|
|
with: /^[\w|\.|\-]+@\w[\w|\.|\-]*\w(,[\w|\.|\-]+@\w[\w|\.|\-]*\w)*$/
|
|
});
|
|
Self.validatesLengthOf('postcode', {
|
|
allowNull: true,
|
|
allowBlank: true,
|
|
min: 3, max: 10
|
|
});
|
|
|
|
var validateIban = require('../validations/validateIban');
|
|
Self.validateBinded('iban',validateIban,{
|
|
message:'El iban no tiene el formato correcto'
|
|
});
|
|
|
|
Self.validate('payMethod', hasSalesMan, {
|
|
message: 'No se puede cambiar la forma de pago si no hay comercial asignado'
|
|
});
|
|
function hasSalesMan(err) {
|
|
if(this.payMethod && !this.salesPerson)
|
|
err();
|
|
}
|
|
Self.validateAsync('payMethodFk', hasIban, {
|
|
message: 'El método de pago seleccionado requiere que se especifique el IBAN'
|
|
});
|
|
function hasIban(err, done) {
|
|
models.PayMethod.findById(this.payMethodFk, (_, instance) => {
|
|
if (instance && instance.ibanRequired && !this.iban)
|
|
err();
|
|
done();
|
|
});
|
|
}
|
|
|
|
Self.validateAsync('credit', validateCredit, {
|
|
message: 'No tienes privilegios para modificar el crédito'
|
|
});
|
|
function validateCredit(err, done) {
|
|
let ctx = loopBackContext.getCurrentContext();
|
|
let accessToken = ctx && ctx.get('accessToken');
|
|
let userId = accessToken.userId;
|
|
let self = this;
|
|
|
|
// Comprueba si el rol del usuario puede asignar esa cantidad
|
|
// para ello mira que roles pueden asignar la cantidad que el usuario ha indicado
|
|
let filter = {
|
|
fields: ['roleFk'],
|
|
where: {
|
|
maxAmount: {gt: self.credit}
|
|
}
|
|
};
|
|
models.ClientCreditLimit.find(filter,
|
|
(_, res) => limitCb(_, res));
|
|
|
|
function limitCb(_, instances) {
|
|
let requiredRoles = [];
|
|
for (instance of instances)
|
|
requiredRoles.push (instance.roleFk);
|
|
|
|
let where = {
|
|
roleId: {inq: requiredRoles},
|
|
principalType: 'USER',
|
|
principalId: userId
|
|
};
|
|
models.RoleMapping.count(where,
|
|
(_, res) => roleCb(_, res));
|
|
}
|
|
function roleCb(_, count) {
|
|
//si el usuario no tiene alguno de los roles no continua
|
|
if (!(count > 0)) {
|
|
err();
|
|
done();
|
|
} else
|
|
validate(); //si tiene el rol hay que validar que el último movimiento no fuese crédito 0 insertado por gerencia
|
|
}
|
|
|
|
// Si se puso a 0 por gerencia, solo gerencia puede aumentarlo
|
|
function validate() {
|
|
let query = 'SELECT * FROM ClientCredit WHERE clientFk = ? ORDER BY created DESC LIMIT 1';
|
|
Self.dataSource.connector.execute (query, [self.id],
|
|
(_, res) => maxCb(_, res));
|
|
}
|
|
|
|
function maxCb(_, instances) {
|
|
//console.log('maxCb', instances);
|
|
if(!instances){
|
|
err();
|
|
return;
|
|
}
|
|
|
|
if (instances.length !== 1 || instances[0].employeeFk == userId || instances[0].amount > 0) {
|
|
done();
|
|
return;
|
|
}
|
|
|
|
//el ultimo registro tiene valor 0, hay que comprobar que no fue editado por un gerente
|
|
let sql = `SELECT count(distinct r.id) as hasManagerRole
|
|
FROM ClientCredit cc
|
|
JOIN Employee em ON (em.id = cc.employeeFk)
|
|
JOIN Account ac ON (ac.id = em.userFk)
|
|
JOIN RoleMapping rm ON (rm.principalId = ac.id)
|
|
JOIN Role r on (r.id = rm.roleId)
|
|
WHERE rm.principalType = 'USER'
|
|
AND cc.employeeFk = ${instances[0].employeeFk}
|
|
AND r.\`name\` = 'manager'`;
|
|
|
|
Self.dataSource.connector.execute(sql, [], (_, res) => clientCreditCb(_, res));
|
|
}
|
|
|
|
function clientCreditCb(_, instance) {
|
|
if (!instance || (instance.length && instance[0].hasManagerRole > 0 ))
|
|
err();
|
|
done();
|
|
}
|
|
}
|
|
|
|
}; |