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

82 lines
2.7 KiB
JavaScript

let UserError = require('../../helpers').UserError;
module.exports = Self => {
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'
}
});
Self.new = async (ctx, params, transaction) => {
let address = await Self.app.models.Address.findOne({
where: {id: params.addressFk},
fields: ['clientFk'],
include: [
{relation: 'client'}
]
});
if (!address)
throw new UserError(`This address doesn't exist`);
if (address.client().isFreezed)
throw new UserError(`You can't create a ticket for a frozen client`);
if (!address.client().isActive)
throw new UserError(`You can't create a ticket for a inactive client`);
if (!address.client().isTaxDataChecked)
throw new UserError(`You can't create a ticket for a client that doesn't has tax data verified`);
let clientFk = address.clientFk;
let agency;
if (params.agency)
agency = await Self.app.models.AgencyMode.findById(params.agencyModeFk);
else
agency = {code: null};
if (agency.code != 'refund') {
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 a ticket for a client that has a debt`);
}
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,
params.agencyModeFk | null,
params.routeFk | null,
params.landed,
params.userId
], {options: transaction});
return await Self.findOne({
where: {id: result[1][0].newTicketId}
}, {options: transaction});
};
};