DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` PROCEDURE `vn`.`supplierExpenses`(vEnded DATE)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS openingBalance;

	CREATE TEMPORARY TABLE openingBalance(
		dueDated DATE
		, supplierFk INT NOT NULL
		, companyFk INT NOT NULL
		, eurAmount DOUBLE NOT NULL
		, foreignAmount DOUBLE NOT NULL
		, PRIMARY KEY(supplierFk, companyFk))
	ENGINE =  MEMORY;

	-- Calcula el balance inicial y final de cada proveedor
	INSERT INTO openingBalance
		SELECT MAX(dueDated),
				supplierFk, 
                companyFk, 
				sum(amount) eurAmount,
				sum(divisa) foreignAmount
		FROM (
			SELECT p.dueDated,
				p.supplierFk, 
				p.companyFk,
				p.amount,
                p.divisa
			FROM payment p
				JOIN currency c ON c.id = p.currencyFk
                JOIN company co ON co.id = p.companyFk
			WHERE p.dueDated > '2014-12-31'
				AND p.dueDated <= vEnded
				AND co.`code` = 'VNL'
				AND c.`code` <> 'EUR'
		UNION ALL

			SELECT iidd.dueDated,
					ii.supplierFk,
					ii.companyFk,
					- iidd.amount, 
                    - iidd.foreignValue
			FROM invoiceIn ii
				JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk
				JOIN currency c ON c.id = ii.currencyFk
                JOIN company co ON co.id = ii.companyFk
			WHERE  iidd.dueDated > '2014-12-31'
				AND iidd.dueDated <= vEnded
				AND ii.isBooked AND co.`code` = 'VNL' 
                AND c.`code` <> 'EUR'
		UNION ALL

			SELECT se.dueDated,
					se.supplierFk,
					se.companyFk,
					- se.amount, 
                    0
			FROM supplierExpense se
				JOIN currency c ON c.id = se.currencyFk
                JOIN company co ON co.id = se.companyFk
			WHERE se.dueDated > '2014-12-31'
				AND se.dueDated <= vEnded
				AND co.`code` = 'VNL' AND c.`code` <> 'EUR'
		) sub
		GROUP BY companyFk, supplierFk;
  
    SELECT ob.dueDated
			, ob.supplierFk
			, ob.companyFk
			, ob.eurAmount
            , s.`name`
		FROM openingBalance ob
			LEFT JOIN supplier s ON s.id = ob.supplierFk
		WHERE ob.eurAmount <> 0 AND ob.foreignAmount = 0;

    DROP TEMPORARY TABLE openingBalance;

END$$
DELIMITER ;
