DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_recalc`(vSelf INT)
BEGIN
/**
 * Recalculates the order total.
 *
 * @param vSelf The order id
 */
	DECLARE vTaxableBase DECIMAL(10,2);
	DECLARE vTax DECIMAL(10,2);
	DECLARE vForeignTaxableBase DECIMAL(10,2);
	DECLARE vForeignTax DECIMAL(10,2);

	DROP TEMPORARY TABLE IF EXISTS tmp.`order`;
	CREATE TEMPORARY TABLE tmp.`order`
		ENGINE = MEMORY
		SELECT vSelf orderFk;
		
	CALL order_getTax;

	SELECT IFNULL(SUM(taxableBase), 0.0), 
			IFNULL(SUM(tax), 0.0),
			IFNULL(SUM(foreignTaxableBase), 0.0), 
			IFNULL(SUM(foreignTax), 0.0)
		INTO vTaxableBase, 
			vTax, 
			vForeignTaxableBase, 
			vForeignTax
		FROM tmp.orderAmount;

	UPDATE `order`
		SET taxableBase = vTaxableBase,
			tax = vTax,
			total = vTaxableBase + vTax,
			foreignTaxableBase = vForeignTaxableBase,
			foreignTax = vForeignTax,
			foreignTotal = vForeignTaxableBase + vForeignTax
		WHERE id = vSelf;

	DROP TEMPORARY TABLE
		tmp.`order`,
		tmp.orderTax;
END$$
DELIMITER ;
