DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaEntryValueUpdate`(vDuaFk INT)
BEGIN

	UPDATE duaEntry de
		JOIN 
			( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total
					FROM buy b
						JOIN duaEntry de ON de.entryFk = b.entryFk
                        WHERE duaFk = vDuaFk
					GROUP BY b.entryFk
        	 ) sub ON sub.entryFk = de.entryFk
             
        LEFT JOIN 
			(SELECT e.id, sum(iit.taxableBase) as euros
				FROM entry e
					JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk
                    JOIN duaEntry de ON de.entryFk = e.id
                    WHERE de.duaFk = vDuaFk
				GROUP BY e.id
			) sub2 ON sub2.id = de.entryFk
            
		SET de.value = sub.total,
			de.euroValue = sub2.euros
        WHERE duaFk = vDuaFk;
    
END$$
DELIMITER ;
