salix/modules/worker/back/methods/worker/new.js

232 lines
7.4 KiB
JavaScript

/* eslint max-len: ["error", { "code": 150 }]*/
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('new', {
description: 'Creates a new worker and returns the id',
accessType: 'WRITE',
accepts: [{
arg: 'fi',
type: 'string',
description: `The worker fi`,
}, {
arg: 'name',
type: 'string',
description: `The user name`,
}, {
arg: 'firstName',
type: 'string',
description: `The worker firstname`,
}, {
arg: 'lastNames',
type: 'string',
description: `The worker lastnames`,
}, {
arg: 'email',
type: 'string',
description: `The worker email`,
required: true,
}, {
arg: 'street',
type: 'string',
description: `The worker address`,
}, {
arg: 'city',
type: 'string',
description: `The worker city`,
}, {
arg: 'provinceFk',
type: 'number',
description: `The worker province`,
}, {
arg: 'companyFk',
type: 'number',
description: `The worker company`,
}, {
arg: 'postcode',
type: 'string',
description: `The worker postcode`,
}, {
arg: 'phone',
type: 'string',
description: `The worker phone`,
}, {
arg: 'code',
type: 'string',
description: `The worker code`,
}, {
arg: 'bossFk',
type: 'number',
description: `The worker boss`,
required: true,
}, {
arg: 'birth',
type: 'date',
description: `The worker birth`,
}, {
arg: 'payMethodFk',
type: 'number',
description: `The client payMethod`,
}, {
arg: 'iban',
type: 'string',
description: `The client iban`,
}, {
arg: 'bankEntityFk',
type: 'number',
description: `The client bank entity`,
}, {
arg: 'isFreelance',
type: 'boolean',
}],
returns: {
type: 'number',
root: true,
},
http: {
path: `/new`,
verb: 'POST',
},
});
Self.new = async(
ctx,
fi,
name,
firstName,
lastNames,
email,
street,
city,
provinceFk,
companyFk,
postcode,
phone,
code,
bossFk,
birth,
payMethodFk,
iban,
bankEntityFk,
isFreelance,
options
) => {
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
let tx;
if (typeof options == 'object') Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
let client;
let user;
try {
client = await models.Client.findOne({where: {fi}}, myOptions);
const nickname = firstName.concat(' ', lastNames);
const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required');
if (isFreelance || !client) {
const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;');
const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}});
user = await models.VnUser.create({
name,
nickname,
password,
email,
roleFk: freelancer ? freelancer.id : roleFk,
}, myOptions);
await models.Account.create({
id: user.id
}, myOptions);
} else if (client) user = await models.VnUser.findById(client.id, null, myOptions);
if (!client && !isFreelance) {
const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']});
if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN');
await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
firstName,
lastNames,
fi,
street,
postcode,
city,
provinceFk,
companyFk,
phone,
email,
user.id,
],
myOptions);
const address = await models.Address.create({
clientFk: user.id,
street: street,
city,
provinceFk,
postalCode: postcode,
mobile: phone,
nickname: nickname,
isDefaultAddress: true,
}, myOptions);
client = await models.Client.findById(user.id, {
fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']
}, myOptions);
await client.updateAttributes({
payMethod: payMethodFk,
iban,
bankEntityFk,
defaultAddressFk: address.id,
businessTypeFk,
}, myOptions);
}
await user.updateAttribute('email', email, myOptions);
let countryFk;
if (provinceFk) {
const province = await Self.app.models.Province.findById(provinceFk, {
fields: ['countryFk']
});
countryFk = province.countryFk;
}
await models.Worker.create({
id: user.id,
firstName,
lastName: lastNames,
code,
bossFk,
fi,
birth,
originCountryFk: countryFk
}, myOptions);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
const code = e.code;
const message = e.sqlMessage;
if (e.message && e.message.includes('Invalid email')) throw new UserError('Invalid email');
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
throw e;
}
await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id});
return {id: user.id};
};
};