salix/modules/ticket/back/methods/sale/recalculatePrice.js

74 lines
2.2 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('recalculatePrice', {
description: 'Calculates the price of sales and its components',
accessType: 'WRITE',
accepts: [{
arg: 'sales',
description: 'The sales',
type: ['object'],
required: true,
http: {source: 'body'}
}],
returns: {
type: 'Number',
root: true
},
http: {
path: `/recalculatePrice`,
verb: 'post'
}
});
Self.recalculatePrice = async(ctx, sales, options) => {
const models = Self.app.models;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const salesIds = [];
const params = [];
sales.forEach(sale => {
salesIds.push(sale.id);
params.push('?');
});
const isEditable = await models.Ticket.isEditable(ctx, sales[0].ticketFk, myOptions);
if (!isEditable)
throw new UserError(`The sales of this ticket can't be modified`);
const canEditSale = await models.Sale.canEdit(ctx, sales, myOptions);
if (!canEditSale)
throw new UserError(`Sale(s) blocked, please contact production`);
const paramsString = params.join();
const query = `
DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;
CREATE TEMPORARY TABLE tmp.recalculateSales
SELECT s.id
FROM sale s
WHERE s.id IN (${paramsString});
CALL vn.sale_calculateComponentSalix();
DROP TEMPORARY TABLE tmp.recalculateSales;`;
const recalculation = await Self.rawSql(query, salesIds, myOptions);
if (tx) await tx.commit();
return recalculation;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};