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

105 lines
3.4 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethodCtx('invoiceTickets', {
description: 'Make out an invoice from one or more tickets',
accessType: 'WRITE',
accepts: [
{
arg: 'ticketsIds',
description: 'The tickets id',
type: ['number'],
required: true
}
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/invoiceTickets`,
verb: 'POST'
}
});
Self.invoiceTickets = async(ctx, ticketsIds, options) => {
const models = Self.app.models;
const date = Date.vnNew();
date.setHours(0, 0, 0, 0);
const myOptions = {userId: ctx.req.accessToken.userId};
let tx;
if (typeof options === 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
let invoicesIds = [];
try {
const tickets = await models.Ticket.find({
where: {
id: {inq: ticketsIds}
},
fields: ['id', 'clientFk', 'companyFk']
}, myOptions);
const [firstTicket] = tickets;
const clientId = firstTicket.clientFk;
const companyId = firstTicket.companyFk;
const isSameClient = tickets.every(ticket => ticket.clientFk === clientId);
if (!isSameClient)
throw new UserError(`You can't invoice tickets from multiple clients`);
const client = await models.Client.findById(clientId, {
fields: ['id', 'hasToInvoiceByAddress']
}, myOptions);
if (client.hasToInvoiceByAddress) {
const query = `
SELECT DISTINCT addressFk
FROM ticket t
WHERE id IN (?)`;
const result = await Self.rawSql(query, [ticketsIds], myOptions);
const addressIds = result.map(address => address.addressFk);
for (const address of addressIds)
await createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, myOptions);
} else
await createInvoice(ctx, companyId, ticketsIds, null, invoicesIds, myOptions);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
for (const invoiceId of invoicesIds)
await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null);
return invoicesIds;
};
async function createInvoice(ctx, companyId, ticketsIds, address, invoicesIds, myOptions) {
const models = Self.app.models;
await models.Ticket.rawSql(`
CREATE OR REPLACE TEMPORARY TABLE tmp.ticketToInvoice
(PRIMARY KEY (id))
ENGINE = MEMORY
SELECT id
FROM vn.ticket
WHERE id IN (?)
${address ? `AND addressFk = ${address}` : ''}
`, [ticketsIds], myOptions);
const invoiceId = await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), myOptions);
invoicesIds.push(invoiceId);
}
};