DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`agencia_descuadre`(vFrom DATE, vTo DATE, vAgencyModeFk INT, vWarehouseAlias INT)
BEGIN
    DECLARE vToDayEnd DATETIME;
    
    SET vToDayEnd = util.dayEnd(vTo);
	     
	SELECT t.id ticketFk,t.addressFk,
			v.amount AS VN, v.amount - shipping_charge AS Difer,
			e.shipping_charge AS teorico, t.packages, t.clientFk, t.zoneFk, a.provinceFk
		
		FROM  vn.ticket t 
			LEFT JOIN 
			(SELECT ticketFk, SUM(amount) amount,shipped 
				FROM vn.sale_freightComponent
				WHERE shipped BETWEEN vFrom AND vToDayEnd
						GROUP BY ticketFk) v ON t.id = v.ticketFk
			LEFT JOIN (SELECT t.id, SUM(t.zonePrice * ebv.ratio) shipping_charge
							FROM vn.ticket t
								LEFT JOIN vn.expedition e ON e.ticketFk = t.id
								JOIN vn.expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk
							WHERE t.shipped BETWEEN vFrom AND vToDayEnd
							GROUP BY t.id
					) e ON t.id = e.id
			JOIN vn.address a ON a.id = t.addressFk
			JOIN warehouse_group wg ON wg.warehouse_id = t.warehouseFk
		WHERE DATE(t.shipped) BETWEEN vFrom AND vToDayEnd 
			AND t.agencyModeFk = vAgencyModeFk 
			AND wg.warehouse_alias_id = vWarehouseAlias;

END$$
DELIMITER ;
