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

120 lines
3.0 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethodCtx('createAddress', {
description: 'Creates client address updating default address',
accepts: [{
arg: 'clientFk',
type: 'number',
description: 'The client id',
http: {source: 'path'}
},
{
arg: 'nickname',
type: 'string',
required: true
},
{
arg: 'city',
type: 'string',
required: true
},
{
arg: 'street',
type: 'string',
required: true
},
{
arg: 'phone',
type: 'string'
},
{
arg: 'mobile',
type: 'string'
},
{
arg: 'postalCode',
type: 'string'
},
{
arg: 'provinceFk',
type: 'number'
},
{
arg: 'agencyModeFk',
type: 'number'
},
{
arg: 'incotermsFk',
type: 'string'
},
{
arg: 'customsAgentFk',
type: 'number'
},
{
arg: 'isActive',
type: 'boolean'
},
{
arg: 'isDefaultAddress',
type: 'boolean'
}],
returns: {
root: true,
type: 'object'
},
http: {
verb: 'post',
path: '/:clientFk/createAddress'
}
});
Self.createAddress = async(ctx, clientFk, options) => {
const models = Self.app.models;
const args = ctx.args;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const province = await models.Province.findById(args.provinceFk, {
include: {
relation: 'country'
}
}, myOptions);
const isUeeMember = province.country().isUeeMember;
if (!isUeeMember && !args.incotermsFk)
throw new UserError(`Incoterms is required for a non UEE member`);
if (!isUeeMember && !args.customsAgentFk)
throw new UserError(`Customs agent is required for a non UEE member`);
delete args.ctx; // Remove unwanted properties
const newAddress = await models.Address.create(args, myOptions);
const client = await Self.findById(clientFk, null, myOptions);
if (args.isDefaultAddress) {
await client.updateAttributes({
defaultAddressFk: newAddress.id
}, myOptions);
}
if (tx) await tx.commit();
return newAddress;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};