salix/modules/client/back/methods/client/createWithUser.js

108 lines
3.3 KiB
JavaScript

/* eslint max-len: ["error", { "code": 150 }]*/
const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethod('createWithUser', {
description: 'Creates both client and its web account',
accepts: {
arg: 'data',
type: 'object',
http: {source: 'body'}
},
returns: {
root: true,
type: 'boolean'
},
http: {
verb: 'post',
path: '/createWithUser'
}
});
Self.createWithUser = async(data, options) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
if (!data.email)
throw new UserError('An email is necessary');
const firstEmail = data.email.split(',')[0];
const user = {
name: data.userName,
email: firstEmail,
password: String(Math.random() * 100000000000000)
};
try {
const province = await models.Province.findOne({
where: {id: data.provinceFk},
fields: ['autonomyFk']
});
const autonomy = province ? await models.Autonomy.findOne({
where: {id: province.autonomyFk},
fields: ['hasDailyInvoice']
}) : null;
const country = await models.Country.findOne({
where: {id: data.countryFk},
fields: ['hasDailyInvoice']
});
const hasDailyInvoice = (autonomy?.hasDailyInvoice ?? country?.hasDailyInvoice) || false;
const account = await models.VnUser.create(user, myOptions);
const client = await Self.create({
id: account.id,
name: data.name,
fi: data.fi,
socialName: data.socialName,
email: data.email,
salesPersonFk: data.salesPersonFk,
postcode: data.postcode,
street: data.street,
city: data.city,
provinceFk: data.provinceFk,
countryFk: data.countryFk,
isEqualizated: data.isEqualizated,
businessTypeFk: data.businessTypeFk,
hasDailyInvoice: hasDailyInvoice
}, myOptions);
const address = await models.Address.create({
clientFk: client.id,
nickname: client.name,
city: client.city,
street: client.street,
postalCode: client.postcode,
provinceFk: client.provinceFk,
isEqualizated: client.isEqualizated,
isActive: true
}, myOptions);
await client.updateAttributes({
defaultAddressFk: address.id
}, myOptions);
if (tx) await tx.commit();
return client;
} catch (e) {
if (tx) await tx.rollback();
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`The web user's email already exists`);
throw e;
}
};
};