DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`agencyModeImbalance`(vStarted DATE, vEnded DATE)
BEGIN
/**
 * Devuelve el valor de los precios teorico, practico de las agencias
 * y si ademas es de mrw lo compara con su fichero previamente procesado
 *
 * @param vEktFk Identificador de edi.ekt
 */
	DECLARE vEndedDayEnd DATETIME;

	SET vEndedDayEnd = util.dayEnd(vEnded);

	SELECT t.id ticketFk,t.addressFk,
			CAST(v.amount AS DECIMAL (10,2)) AS VN,
			CAST(v.amount - e.shipping_charge AS DECIMAL (10,2)) AS Difer,
			CAST(mrwPrice AS DECIMAL (10,2)) mrwPrice,
			CAST(e.shipping_charge - mrwPrice AS DECIMAL (10,2)) mrwDifference,
			CAST(e.shipping_charge AS DECIMAL (10,2)) AS teorico,
			CAST(e.extraCharge AS DECIMAL (10,2)) AS extraCharge,
			t.packages, t.clientFk,
			t.zoneFk, a.provinceFk, mrwCount
		FROM  vn.ticket t
			LEFT JOIN
			(SELECT ticketFk, SUM(amount) amount, fc.shipped
				FROM vn.sale_freightComponent fc
					JOIN vn.ticket t ON t.id = fc.ticketFk
					JOIN tmp.agencyMode am ON am.agencyModeFk = t.agencyModeFk
				WHERE fc.shipped BETWEEN vStarted AND vEndedDayEnd
						GROUP BY ticketFk) v ON t.id = v.ticketFk
			LEFT JOIN (SELECT t.id,
								SUM(t.zonePrice) shipping_charge,
								SUM(IFNULL(aex.price,0)) extraCharge
							FROM vn.ticket t
								LEFT JOIN vn.expedition e ON e.ticketFk = t.id
								LEFT JOIN vn.packaging p ON p.id = e.packagingFk
								JOIN tmp.agencyMode amc ON amc.agencyModeFk = t.agencyModeFk
								JOIN vn.agencyMode am ON am.id = amc.agencyModeFk
								LEFT JOIN vn.agencyExtraCharge aex ON p.width+p.depth+p.height BETWEEN aex.sizeMin AND aex.sizeMax AND aex.agencyFk = am.agencyFk
							WHERE t.shipped BETWEEN vStarted AND vEndedDayEnd
							GROUP BY t.id
					) e ON t.id = e.id
			LEFT JOIN (SELECT ticketFk, SUM(price) mrwPrice, COUNT(*) mrwCount
							FROM vn.mrw
							GROUP BY ticketFk) mrw ON mrw.ticketFk = t.id
			JOIN vn.address a ON a.id = t.addressFk
			JOIN tmp.agencyMode am ON am.agencyModeFk = t.agencyModeFk
		WHERE t.shipped BETWEEN vStarted AND vEndedDayEnd;
END$$
DELIMITER ;
