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

70 lines
2.4 KiB
JavaScript

module.exports = function(Client) {
require("../scopes/client/card.js")(Client);
require("../scopes/client/activate.js")(Client);
require("../scopes/client/addresses.js")(Client);
// 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.validatesFormatOf('postcode', {allowNull: true, with: /^\d+$/, message: 'El código postal solo debe contener números'});
Client.validatesLengthOf('postcode', {allowNull: true, min: 3, max: 10});
Client.validatesFormatOf('email', {allowNull: true, with: /^[\w|\.|\-]+@\w[\w|\.|\-]*\w$/, message: 'Correo electrónico inválido'});
Client.validate('payMethod', hasCC, {message: 'Introduzca el iban del cliente'});
function hasCC(err) {
if (this.payMethod == 2 && !this.iban) err();
};
Client.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();
};
Client.validatesLengthOf('iban', {allowNull: true, min: 23, max: 23});
// Hooks
Client.observe('before save', function(ctx, next) {
if(ctx.instance) {
if (!ctx.instance.dueDay){
ctx.instance.dueDay = 5;
}
next();
}
else {
Client.findById(ctx.where.id,
function(err, item) {
if (!err) {
if (item.payMethod != ctx.data.payMethod && item.dueDay == ctx.data.dueDay) {
ctx.data.dueDay = 5;
}
}
next();
}
);
}
});
// Basic filter
Client.installMethod('filter', filterClients);
function filterClients(p) {
return {
where: {
id: p.id,
name: {regexp: p.name},
cif: p.cif,
socialName: {regexp: p.socialName},
city: {regexp: p.city},
postcode: p.postcode,
email: {regexp: p.email},
phone: p.phone
},
skip: (p.page - 1) * p.size,
limit: p.size
};
}
};