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 => { let firstEmail = data.email ? data.email.split(',')[0] : null; let user = { name: data.userName, email: firstEmail, password: parseInt(Math.random() * 100000000000000) }; const Account = Self.app.models.Account; const Address = Self.app.models.Address; const tx = await Account.beginTransaction({}); try { let options = {transaction: tx}; let account = await Account.create(user, options); let 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 }, options); let address = await 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 }, options); await client.updateAttributes({ defaultAddressFk: address.id }, options); await tx.commit(); return client; } catch (e) { await tx.rollback(); throw e; } }; };