salix/services/loopback/common/methods/client/createWithUser.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

let md5 = require('md5');
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 = (data, callback) => {
let firstEmail = data.email ? data.email.split(',')[0] : null;
let user = {
name: data.userName,
email: firstEmail,
password: md5(parseInt(Math.random() * 100000000000000))
};
let Account = Self.app.models.Account;
Account.beginTransaction({}, (error, transaction) => {
if (error) return callback(error);
Account.create(user, {transaction}, (error, account) => {
if (error) {
transaction.rollback();
return callback(error);
}
let client = {
name: data.name,
fi: data.fi,
socialName: data.socialName,
id: account.id,
email: data.email,
salesPersonFk: data.salesPersonFk
};
Self.create(client, {transaction}, (error, newClient) => {
if (error) {
transaction.rollback();
return callback(error);
}
transaction.commit();
callback(null, newClient);
});
});
});
};
};