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

82 lines
2.7 KiB
JavaScript
Raw Normal View History

let UserError = require('../../helpers').UserError;
module.exports = Self => {
2018-11-27 12:28:15 +00:00
Self.remoteMethodCtx('new', {
description: 'Create a newticket and returns the new ID',
accessType: 'WRITE',
accepts: [{
arg: 'params',
type: 'object',
required: true,
description: 'ClientFk, Shipped, WharehouseFk, CompanyFk, AddressFk, AgencyModeFk, RouteFk, Landed, userId',
http: {source: 'body'}
}],
returns: {
type: 'number',
root: true
},
http: {
path: `/new`,
verb: 'post'
}
});
2018-11-27 12:28:15 +00:00
Self.new = async (ctx, params, transaction) => {
let address = await Self.app.models.Address.findOne({
where: {id: params.addressFk},
fields: ['clientFk'],
include: [
{relation: 'client'}
]
2018-10-10 07:59:42 +00:00
});
2018-11-27 12:28:15 +00:00
if (!address)
throw new UserError(`This address doesn't exist`);
2018-11-27 12:28:15 +00:00
if (address.client().isFreezed)
2018-11-29 15:27:27 +00:00
throw new UserError(`You can't create a ticket for a frozen client`);
2018-11-27 12:28:15 +00:00
if (!address.client().isActive)
2018-11-29 15:27:27 +00:00
throw new UserError(`You can't create a ticket for a inactive client`);
2018-11-27 12:28:15 +00:00
if (!address.client().isTaxDataChecked)
2018-11-29 15:27:27 +00:00
throw new UserError(`You can't create a ticket for a client that doesn't has tax data verified`);
2018-11-27 12:28:15 +00:00
let clientFk = address.clientFk;
2018-11-29 10:06:15 +00:00
let agency;
if (params.agency)
agency = await Self.app.models.AgencyMode.findById(params.agencyModeFk);
else
agency = {code: null};
2018-11-27 12:28:15 +00:00
2018-11-28 11:03:48 +00:00
if (agency.code != 'refund') {
let query = `SELECT vn.clientGetDebt(?, CURDATE()) AS debt`;
let clientDebt = await Self.rawSql(query, [clientFk]);
2018-11-27 12:28:15 +00:00
if (address.client().credit - clientDebt[0].debt <= 0)
2018-11-29 15:27:27 +00:00
throw new UserError(`You can't create a ticket for a client that has a debt`);
2018-11-28 11:03:48 +00:00
}
2018-11-27 12:28:15 +00:00
if (!params.userId && ctx.req && ctx.req.accessToken.userId)
params.userId = ctx.req.accessToken.userId;
query = `CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result);
SELECT @result newTicketId;`;
let result = await Self.rawSql(query, [
params.clientFk,
params.shipped,
params.warehouseFk,
params.companyFk | 442,
params.addressFk,
2018-10-03 12:05:25 +00:00
params.agencyModeFk | null,
params.routeFk | null,
params.landed,
params.userId
2018-11-27 12:28:15 +00:00
], {options: transaction});
2018-10-10 07:59:42 +00:00
return await Self.findOne({
where: {id: result[1][0].newTicketId}
2018-11-27 12:28:15 +00:00
}, {options: transaction});
};
};