module.exports = function(Client) { // Methods 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', { message: 'El código postal solo debe contener números', allowNull: true, with: /^\d+$/ }); Client.validatesFormatOf('email', { message: 'Correo electrónico inválido', allowNull: true, with: /^[\w|\.|\-]+@\w[\w|\.|\-]*\w$/ }); Client.validatesLengthOf('postcode', { allowNull: true, min: 3, max: 10 }); Client.validatesLengthOf('iban', { allowNull: true, allowBlank: true, max: 23 }); 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.validateAsync('payMethodFk', hasIban, { message: 'El método de pago seleccionado requiere que se especifique el IBAN' }); function hasIban(err, done) { let iban = this.iban; let PayMethod = Client.app.models.PayMethod; PayMethod.findById(this.payMethodFk, function (_, instance){ if (instance.ibanRequired && !iban) err(); done(); }); }; // 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 }; } };