DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_getTotal`()
BEGIN
/**
 * Calcula el total con IVA para un conjunto de orders.
 *
 * @table tmp.order(orderFk) Identificadores de las ordenes a calcular
 * @return tmp.orderTotal Total para cada orden
 */
	CALL order_getTax;

	DROP TEMPORARY TABLE IF EXISTS tmp.orderTotal;
	CREATE TEMPORARY TABLE tmp.orderTotal
		(INDEX (orderFk))
		ENGINE = MEMORY
		SELECT o.orderFk, 
				IFNULL(SUM(ot.taxableBase + ot.tax), 0.0) total,
				IFNULL(SUM(ot.taxableBase + ot.tax) * ot.currencyFk, 0.0) foreignTotal
			FROM tmp.`order` o
				LEFT JOIN tmp.orderAmount ot ON o.orderFk = ot.orderFk
			GROUP BY orderFk;

	DROP TEMPORARY TABLE
		tmp.orderTax,
        tmp.orderAmount;
END$$
DELIMITER ;
