salix/modules/invoiceOut/back/methods/invoiceOut/transfer.js

124 lines
3.8 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('transfer', {
description: 'Transfer an issued invoice to another client',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
type: 'number',
required: true,
description: 'Issued invoice id'
},
{
arg: 'newClientFk',
type: 'number',
required: true
},
{
arg: 'cplusRectificationTypeFk',
type: 'number',
required: true
},
{
arg: 'siiTypeInvoiceOutFk',
type: 'number',
required: true
},
{
arg: 'invoiceCorrectionTypeFk',
type: 'number',
required: true
},
{
arg: 'makeInvoice',
type: 'boolean',
required: true
},
],
returns: {type: 'object', root: true},
http: {path: '/transfer', verb: 'post'}
});
Self.transfer = async(
ctx,
id,
newClientFk,
cplusRectificationTypeFk,
siiTypeInvoiceOutFk,
invoiceCorrectionTypeFk,
makeInvoice,
options
) => {
const models = Self.app.models;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const originalInvoice = await models.InvoiceOut.findById(id);
if (!originalInvoice)
throw new UserError('Original invoice not found');
if (originalInvoice.clientFk === newClientFk)
throw new UserError('Select a different client');
let transferredInvoiceId;
try {
await Self.refundAndInvoice(
ctx,
id,
false,
cplusRectificationTypeFk,
siiTypeInvoiceOutFk,
invoiceCorrectionTypeFk,
myOptions
);
const tickets = await models.Ticket.find({where: {refFk: originalInvoice.ref}}, myOptions);
const ticketIds = tickets.map(ticket => ticket.id);
const transferredTickets = await models.Ticket.cloneAll(ctx, ticketIds, false, false, myOptions);
const client = await models.Client.findById(newClientFk,
{fields: ['id', 'defaultAddressFk']}, myOptions);
const address = await models.Address.findById(client.defaultAddressFk,
{fields: ['id', 'nickname']}, myOptions);
const transferredTicketIds = transferredTickets.map(ticket => ticket.id);
await models.Ticket.updateAll(
{id: {inq: transferredTicketIds}},
{
clientFk: newClientFk,
addressFk: client.defaultAddressFk,
nickname: address.nickname
},
myOptions
);
if (makeInvoice)
transferredInvoiceId = await models.Ticket.invoiceTickets(ctx, transferredTicketIds, null, myOptions);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
if (transferredInvoiceId) {
try {
await models.InvoiceOut.makePdfList(ctx, transferredInvoiceId);
} catch (e) {
throw new UserError('The invoices have been created but the PDFs could not be generatedd');
}
}
return transferredInvoiceId;
};
};