salix/services/loopback/common/methods/order/new.js

58 lines
1.7 KiB
JavaScript

let UserError = require('../../helpers').UserError;
module.exports = Self => {
Self.remoteMethod('new', {
description: 'Create a new order and returns the new ID',
accessType: 'WRITE',
accepts: [{
arg: 'params',
type: 'object',
http: {source: 'body'}
}],
returns: {
type: 'number',
root: true
},
http: {
path: `/new`,
verb: 'post'
}
});
Self.new = async params => {
let address = await Self.app.models.Address.findOne({
where: {id: params.addressFk},
fields: ['clientFk'],
include: [
{relation: 'client'}
]
});
let clientFk = address.clientFk;
if (address.client().isFreezed)
throw new UserError(`You can't create an order for a frozen client`);
if (!address.client().isActive)
throw new UserError(`You can't create an order for a inactive client`);
if (!address.client().isTaxDataChecked)
throw new UserError(`You can't create an order for a client that doesn't has tax data verified`);
let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
let clientDebt = await Self.rawSql(query, [clientFk]);
if (address.client().credit - clientDebt[0].debt <= 0)
throw new UserError(`You can't create an order for a client that has a debt`);
query = `CALL vn.orderListCreate(?, ?, ?, ?);`;
[result] = await Self.rawSql(query, [
params.landed,
params.agencyModeFk,
params.addressFk,
'SALIX'
]);
return result[0].vOrderId;
};
};