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

64 lines
1.8 KiB
JavaScript
Raw Normal View History

const UserError = require('vn-loopback/util/user-error');
2022-10-04 11:22:11 +00:00
module.exports = Self => {
2019-11-21 11:00:56 +00:00
Self.remoteMethodCtx('recalculatePrice', {
2021-11-30 12:47:16 +00:00
description: 'Calculates the price of sales and its components',
accessType: 'WRITE',
accepts: [{
2021-11-30 12:47:16 +00:00
arg: 'sales',
description: 'The sales',
type: ['object'],
required: true,
2021-11-30 12:47:16 +00:00
http: {source: 'body'}
}],
returns: {
2021-12-01 10:39:48 +00:00
type: 'number',
root: true
},
http: {
2021-11-30 12:47:16 +00:00
path: `/recalculatePrice`,
verb: 'post'
}
});
2021-11-30 12:47:16 +00:00
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 {
2022-10-04 11:22:11 +00:00
const salesIds = sales.map(sale => sale.id);
2022-10-04 11:22:11 +00:00
const canEditSale = await models.Sale.canEdit(ctx, salesIds, myOptions);
if (!canEditSale)
throw new UserError(`Sale(s) blocked, please contact production`);
2021-11-30 12:47:16 +00:00
const query = `
DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;
CREATE TEMPORARY TABLE tmp.recalculateSales
SELECT s.id
FROM sale s
2022-03-07 09:10:45 +00:00
WHERE s.id IN (?);
2021-11-30 14:13:20 +00:00
CALL vn.sale_recalcComponent(null);
2021-11-30 12:47:16 +00:00
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;
}
};
};