salix/modules/client/back/methods/client/createReceipt.js

145 lines
4.7 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self) {
Self.remoteMethodCtx('createReceipt', {
description: 'Creates receipt and its compensation if necessary',
accepts: [{
arg: 'clientFk',
type: 'number',
description: 'The client id',
http: {source: 'path'}
},
{
arg: 'payed',
type: 'Date',
required: true
},
{
arg: 'companyFk',
type: 'number',
required: true
},
{
arg: 'bankFk',
type: 'number',
required: true
},
{
arg: 'amountPaid',
type: 'number',
required: true
},
{
arg: 'description',
type: 'string',
required: true
},
{
arg: 'compensationAccount',
type: 'any'
}],
returns: {
root: true,
type: 'Object'
},
http: {
verb: 'post',
path: '/:clientFk/createReceipt'
}
});
Self.createReceipt = async ctx => {
const models = Self.app.models;
const args = ctx.args;
const tx = await models.Address.beginTransaction({});
try {
const options = {transaction: tx};
delete args.ctx; // Remove unwanted properties
const newReceipt = await models.Receipt.create(args, options);
const clientOriginal = await models.Client.findById(args.clientFk);
const bank = await models.Bank.findById(args.bankFk);
const accountingType = await models.AccountingType.findById(bank.accountingTypeFk);
if (accountingType.code == 'compensation') {
if (!args.compensationAccount)
throw new UserError('Compensation account is empty');
const supplierCompensation = await models.Supplier.findOne({
where: {
account: args.compensationAccount
}
});
let clientCompensation = {};
if (!supplierCompensation) {
clientCompensation = await models.Client.findOne({
where: {
accountingAccount: args.compensationAccount
}
});
}
if (!supplierCompensation && !clientCompensation)
throw new UserError('Invalid account');
await Self.rawSql(
`CALL vn.ledger_doCompensation(CURDATE(), ?, ?, ?, ?, ?, ?)`,
[
args.compensationAccount,
args.bankFk,
accountingType.receiptDescription + clientOriginal.accountingAccount,
args.amountPaid,
args.companyFk,
clientOriginal.accountingAccount
],
options);
} else if (accountingType.isAutoConciliated == true) {
const description = `${clientOriginal.id} : ${clientOriginal.socialName} - ${accountingType.receiptDescription}`;
const [xdiarioNew] = await Self.rawSql(
`SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ledger;`,
[
null,
bank.account,
clientOriginal.accountingAccount,
description,
args.amountPaid,
0,
0,
'',
'',
null,
null,
false,
args.companyFk
],
options);
await Self.rawSql(
`SELECT xdiario_new(?, CURDATE(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`,
[
xdiarioNew.ledger,
clientOriginal.accountingAccount,
bank.account,
description,
0,
args.amountPaid,
0,
'',
'',
null,
null,
false,
args.companyFk
],
options);
}
await tx.commit();
return newReceipt;
} catch (e) {
await tx.rollback();
throw e;
}
};
};