96 lines
2.6 KiB
JavaScript
96 lines
2.6 KiB
JavaScript
module.exports = Self => {
|
|
Self.remoteMethodCtx('refundAndInvoice', {
|
|
description: 'Refund an invoice and create a new one',
|
|
accessType: 'WRITE',
|
|
accepts: [
|
|
{
|
|
arg: 'id',
|
|
type: 'number',
|
|
required: true,
|
|
description: 'Issued invoice id'
|
|
},
|
|
{
|
|
arg: 'withWarehouse',
|
|
type: 'boolean',
|
|
required: true
|
|
},
|
|
{
|
|
arg: 'cplusRectificationTypeFk',
|
|
type: 'number',
|
|
required: true
|
|
},
|
|
{
|
|
arg: 'siiTypeInvoiceOutFk',
|
|
type: 'number',
|
|
required: true
|
|
},
|
|
{
|
|
arg: 'invoiceCorrectionTypeFk',
|
|
type: 'number',
|
|
required: true
|
|
},
|
|
],
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: '/refundAndInvoice',
|
|
verb: 'post'
|
|
}
|
|
});
|
|
|
|
Self.refundAndInvoice = async(
|
|
ctx,
|
|
id,
|
|
withWarehouse,
|
|
cplusRectificationTypeFk,
|
|
siiTypeInvoiceOutFk,
|
|
invoiceCorrectionTypeFk,
|
|
options
|
|
) => {
|
|
const models = Self.app.models;
|
|
const myOptions = {userId: ctx.req.accessToken.userId};
|
|
let refundId;
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
let tx;
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
}
|
|
|
|
try {
|
|
const originalInvoice = await models.InvoiceOut.findById(id, myOptions);
|
|
|
|
const refundedTickets = await Self.refund(ctx, originalInvoice.ref, withWarehouse, myOptions);
|
|
|
|
const invoiceCorrection = {
|
|
correctedFk: id,
|
|
cplusRectificationTypeFk,
|
|
siiTypeInvoiceOutFk,
|
|
invoiceCorrectionTypeFk
|
|
};
|
|
const ticketIds = refundedTickets.map(ticket => ticket.id);
|
|
refundId = await models.Ticket.invoiceTickets(ctx, ticketIds, invoiceCorrection, myOptions);
|
|
|
|
tx && await tx.commit();
|
|
} catch (e) {
|
|
if (tx) await tx.rollback();
|
|
throw e;
|
|
}
|
|
|
|
if (tx) {
|
|
try {
|
|
await models.InvoiceOut.makePdfList(ctx, refundId);
|
|
} catch (e) {
|
|
throw new UserError('The invoices have been created but the PDFs could not be generated');
|
|
}
|
|
}
|
|
|
|
return {refundId};
|
|
};
|
|
};
|