USE `hedera`;
DROP procedure IF EXISTS `orderGetTax`;

DELIMITER $$
USE `hedera`$$

CREATE DEFINER=`root`@`%` PROCEDURE `orderGetTax`()
READS SQL DATA
BEGIN
/**
* Calcula el IVA, y el recargo de equivalencia de un pedido
* desglosados por tipos.
*
* @tabla tmp.order Contiene los identificadores de los pedidos
* @treturn tmp.orderTax Bases imponibles, IVA y recargo de equivalencia
*/
CALL vn.taxGetRates (NULL);

-- Calcula el IVA y el recargo desglosado.

DROP TEMPORARY TABLE IF EXISTS tmp.orderTax;
CREATE TEMPORARY TABLE tmp.orderTax
(INDEX (orderFk))
ENGINE = MEMORY
SELECT id orderFk, t.type, t.taxBase,
CAST(IF(t.hasTax, t.taxBase * x.rate, 0) AS DECIMAL(10,2)) tax,
CAST(IF(t.hasEqualizationTax, t.taxBase * x.equalizationTax, 0) AS DECIMAL(10,2)) equalizationTax
FROM (
SELECT o.id, g.countryFk, g.type
,SUM(CAST(m.amount * m.price AS DECIMAL(10,2))) taxBase
,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax
,c.isEqualizated != FALSE AS hasEqualizationTax
FROM `order` o
JOIN tmp.order tmpo ON tmpo.orderFk = o.id
JOIN orderRow m ON m.orderFk = o.id
JOIN vn.item a ON a.id = m.itemFk
JOIN vn.client c ON c.id = o.customer_id
JOIN vn.supplier p ON p.id = o.company_id
JOIN tmp.taxClass g
ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk
GROUP BY o.id, g.type
) t
JOIN tmp.taxType x
ON x.countryFk = t.countryFk AND x.type = t.type;

DROP TEMPORARY TABLE
tmp.taxClass,
tmp.taxType;
END$$

DELIMITER;