salix/modules/invoiceIn/back/methods/invoice-in/clone.js

106 lines
3.5 KiB
JavaScript
Raw Permalink Normal View History

2021-07-23 12:06:48 +00:00
module.exports = Self => {
Self.remoteMethodCtx('clone', {
description: 'Clone the invoiceIn and as many invoiceInTax and invoiceInDueDay referencing it',
accessType: 'WRITE',
accepts: {
arg: 'id',
2021-07-23 13:17:30 +00:00
type: 'number',
2021-07-23 12:06:48 +00:00
required: true,
description: 'The invoiceIn id',
http: {source: 'path'}
},
returns: {
type: 'object',
root: true
},
http: {
path: '/:id/clone',
verb: 'POST'
}
});
Self.clone = async(ctx, id, 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;
}
try {
const sourceInvoiceIn = await Self.findById(id, {
fields: [
'id',
'serial',
'supplierRef',
'supplierFk',
'issued',
'currencyFk',
'companyFk',
'isVatDeductible',
'withholdingSageFk',
'deductibleExpenseFk',
]
}, myOptions);
const sourceInvoiceInTax = await models.InvoiceInTax.find({where: {invoiceInFk: id}}, myOptions);
const sourceInvoiceInDueDay = await models.InvoiceInDueDay.find({where: {invoiceInFk: id}}, myOptions);
const issued = new Date(sourceInvoiceIn.issued);
issued.setMonth(issued.getMonth() + 1);
const clonedRef = sourceInvoiceIn.supplierRef + '(2)';
2021-07-23 12:06:48 +00:00
const clone = await models.InvoiceIn.create({
serial: sourceInvoiceIn.serial,
supplierRef: clonedRef,
2021-07-23 12:06:48 +00:00
supplierFk: sourceInvoiceIn.supplierFk,
issued: issued,
currencyFk: sourceInvoiceIn.currencyFk,
companyFk: sourceInvoiceIn.companyFk,
isVatDeductible: sourceInvoiceIn.isVatDeductible,
withholdingSageFk: sourceInvoiceIn.withholdingSageFk,
deductibleExpenseFk: sourceInvoiceIn.deductibleExpenseFk,
}, myOptions);
const promises = [];
for (let tax of sourceInvoiceInTax) {
promises.push(models.InvoiceInTax.create({
invoiceInFk: clone.id,
taxableBase: tax.taxableBase,
2021-08-12 05:39:26 +00:00
expenseFk: tax.expenseFk,
2021-07-23 12:06:48 +00:00
foreignValue: tax.foreignValue,
taxTypeSageFk: tax.taxTypeSageFk,
transactionTypeSageFk: tax.transactionTypeSageFk
}, myOptions));
}
for (let dueDay of sourceInvoiceInDueDay) {
const dueDated = dueDay.dueDated;
dueDated.setMonth(dueDated.getMonth() + 1);
promises.push(models.InvoiceInDueDay.create({
invoiceInFk: clone.id,
dueDated: dueDated,
bankFk: dueDay.bankFk,
amount: dueDay.amount,
foreignValue: dueDated.foreignValue,
}, myOptions));
}
await Promise.all(promises);
if (tx) await tx.commit();
return clone;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};