81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
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;
|
|
}
|
|
|
|
const firstEmail = data.email ? data.email.split(',')[0] : null;
|
|
const user = {
|
|
name: data.userName,
|
|
email: firstEmail,
|
|
password: parseInt(Math.random() * 100000000000000)
|
|
};
|
|
|
|
try {
|
|
const account = await models.Account.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
|
|
}, 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();
|
|
throw e;
|
|
}
|
|
};
|
|
};
|