salix/modules/ticket/back/methods/ticket/canBeInvoiced.js

63 lines
2.1 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethodCtx('canBeInvoiced', {
description: 'Whether the ticket can or not be invoiced',
accessType: 'READ',
accepts: [
{
arg: 'ticketsIds',
description: 'The tickets id',
type: ['number'],
required: true
},
{
arg: 'isRectificative',
description: 'If it is rectificative',
type: 'boolean'
}
],
http: {
path: `/canBeInvoiced`,
verb: 'get'
}
});
Self.canBeInvoiced = async(ctx, ticketsIds, isRectificative, options) => {
const myOptions = {};
const $t = ctx.req.__; // $translate
if (typeof options == 'object')
Object.assign(myOptions, options);
const tickets = await Self.find({
where: {
id: {inq: ticketsIds}
},
fields: ['id', 'refFk', 'shipped', 'totalWithVat']
}, myOptions);
const taxBaseFunction = isRectificative ? 'hasAnyPositiveBase' : 'hasAnyNegativeBase';
const [hasAnyIncorrectBase] =
await Self.rawSql(`SELECT ${taxBaseFunction}() AS hasBasesProblem`, null, options);
if (hasAnyIncorrectBase?.hasBasesProblem)
throw new UserError($t(taxBaseFunction, {ticketsIds: ticketsIds}));
const today = Date.vnNew();
tickets.some(ticket => {
const shipped = new Date(ticket.shipped);
const shippingInFuture = shipped.getTime() > today.getTime();
if (shippingInFuture)
throw new UserError(`Can't invoice to future`);
const isInvoiced = ticket.refFk;
if (isInvoiced)
throw new UserError(`This ticket is already invoiced`);
const priceZero = ticket.totalWithVat == 0;
if (ticketsIds.length == 1 && priceZero)
throw new UserError(`A ticket with an amount of zero can't be invoiced`);
});
};
};