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

150 lines
5.3 KiB
JavaScript
Raw Normal View History

2017-06-01 16:23:41 +00:00
var app = require('../../server/server');
2017-01-12 10:02:22 +00:00
module.exports = function(Client) {
2017-06-01 16:23:41 +00:00
var models = app.models;
2017-10-04 06:18:31 +00:00
var loopBackContext = require('loopback-context');
// Methods
2017-06-03 11:01:47 +00:00
require('../methods/client/activate.js')(Client);
require('../methods/client/addresses.js')(Client);
require('../methods/client/before-save.js')(Client);
require('../methods/client/card.js')(Client);
require('../methods/client/create.js')(Client);
2017-06-30 07:26:55 +00:00
require('../methods/client/employee.js')(Client);
require('../methods/client/filter.js')(Client);
require('../methods/client/roles.js')(Client);
2017-09-27 07:25:33 +00:00
require('../methods/client/salesperson.js')(Client);
2017-02-08 11:45:55 +00:00
// Validations
Client.validatesUniquenessOf('name', {
message: 'El nombre debe ser único'
});
Client.validatesUniquenessOf('fi', {
message: 'El NIF/CIF debe ser único'
});
Client.validatesPresenceOf('socialName', {
message: 'Debe especificarse la razón social'
});
Client.validatesUniquenessOf('socialName', {
message: 'La razón social debe ser única'
});
Client.validatesFormatOf('postcode', {
message: 'El código postal solo debe contener números',
allowNull: true,
2017-07-03 07:42:51 +00:00
allowBlank: true,
with: /^\d+$/
});
Client.validatesFormatOf('email', {
message: 'Correo electrónico inválido',
allowNull: true,
2017-07-03 07:42:51 +00:00
allowBlank: true,
2017-06-01 12:05:23 +00:00
with: /^[\w|\.|\-]+@\w[\w|\.|\-]*\w(,[\w|\.|\-]+@\w[\w|\.|\-]*\w)*$/
});
Client.validatesLengthOf('postcode', {
allowNull: true,
2017-07-03 07:42:51 +00:00
allowBlank: true,
min: 3, max: 10
});
2017-09-25 15:40:02 +00:00
var validateIban = require('../validations/validateIban');
Client.validateBinded('iban',validateIban,{
message:'El iban no tiene el formato correcto'
});
2017-09-25 15:40:02 +00:00
Client.validate('payMethod', hasSalesMan, {
message: 'No se puede cambiar la forma de pago si no hay comercial asignado'
});
2017-01-16 08:57:06 +00:00
function hasSalesMan(err) {
2017-05-26 15:05:33 +00:00
if(this.payMethod && !this.salesPerson)
err();
}
Client.validateAsync('payMethodFk', hasIban, {
2017-05-26 12:44:56 +00:00
message: 'El método de pago seleccionado requiere que se especifique el IBAN'
});
function hasIban(err, done) {
2017-06-01 16:23:41 +00:00
models.PayMethod.findById(this.payMethodFk, (_, instance) => {
if (instance && instance.ibanRequired && !this.iban)
err();
done();
});
2017-05-26 15:05:33 +00:00
}
2017-10-04 06:18:31 +00:00
2017-06-01 16:23:41 +00:00
Client.validateAsync('credit', validateCredit, {
message: 'No tienes privilegios para modificar el crédito'
});
function validateCredit(err, done) {
2017-10-04 06:18:31 +00:00
let ctx = loopBackContext.getCurrentContext();
let accessToken = ctx && ctx.get('accessToken');
let userId = accessToken.userId;
let self = this;
2017-06-01 16:23:41 +00:00
// Comprueba si el rol del usuario puede asignar esa cantidad
2017-10-04 06:18:31 +00:00
// para ello mira que roles pueden asignar la cantidad que el usuario ha indicado
2017-06-01 16:23:41 +00:00
let filter = {
fields: ['roleFk'],
where: {
2017-10-04 06:18:31 +00:00
maxAmount: {gt: self.credit}
2017-06-01 16:23:41 +00:00
}
};
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) {
2017-10-04 06:18:31 +00:00
//si el usuario no tiene alguno de los roles no continua
2017-06-01 16:23:41 +00:00
if (!(count > 0)) {
err();
done();
} else
2017-10-04 06:18:31 +00:00
validate(); //si tiene el rol hay que validar que el último movimiento no fuese crédito 0 insertado por gerencia
2017-06-01 16:23:41 +00:00
}
// Si se puso a 0 por gerencia, solo gerencia puede aumentarlo
function validate() {
2017-10-04 06:18:31 +00:00
let query = 'SELECT * FROM ClientCredit WHERE clientFk = ? ORDER BY created DESC LIMIT 1';
Client.dataSource.connector.execute (query, [self.id],
2017-06-01 16:23:41 +00:00
(_, res) => maxCb(_, res));
}
2017-10-04 06:18:31 +00:00
2017-06-01 16:23:41 +00:00
function maxCb(_, instances) {
2017-10-04 06:18:31 +00:00
//console.log('maxCb', instances);
if (instances && (instances.length !== 1 || instances[0].employeeFk == userId || instances[0].amount > 0)) {
2017-06-01 16:23:41 +00:00
done();
return;
}
2017-10-04 06:18:31 +00:00
//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'`;
2017-06-01 16:23:41 +00:00
2017-10-04 06:18:31 +00:00
Client.dataSource.connector.execute(sql, [], (_, res) => clientCreditCb(_, res));
2017-06-01 16:23:41 +00:00
}
2017-10-04 06:18:31 +00:00
function clientCreditCb(_, instance) {
if (instance.length && instance[0].hasManagerRole > 0 )
2017-06-01 16:23:41 +00:00
err();
done();
}
}
2017-10-04 06:18:31 +00:00
2017-01-12 10:02:22 +00:00
};