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

145 lines
4.1 KiB
JavaScript

module.exports = function(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();
};
// 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();
}
);
}
});
// Methods
Client.remoteMethod('activate', {
description: 'Activate or deactive client',
accepts: {
arg: 'id',
type: 'number',
required: true,
description: 'Model id',
http: {source: 'path'}
},
returns: {
arg: 'active',
type: 'boolean'
},
http: {
verb: 'put',
path: '/:id/activate'
}
});
Client.activate = function(id, cb) {
console.log(id);
Client.findById(id, function(err, client) {
if(!err) {
Client.update({id: client.id}, {active: !client.active});
cb(null, !client.active);
}
});
};
// 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
};
}
// Client addresses
Client.remoteMethod('addressesList', {
description: 'List items using a filter',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'string',
required: true,
description: 'Model id',
http: {source: 'path'}
},
{
arg: 'filter',
type: 'object',
required: true,
description: 'Filter defining where',
http: function(ctx) {
return ctx.req.query;
}
}
],
returns: {
arg: 'data',
type: ['Address'],
root: true
},
http: {
path: `/:id/addressesList`,
verb: 'get'
}
});
Client.addressesList = function(id, p, cb) {
let filter = {
where: {
clientFk: id,
},
skip: (p.page - 1) * p.size,
limit: p.size
};
Client.app.models.Address.find(filter, function(err, instances) {
if(!err) {
cb(null, instances);
}
})
};
};