DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expedition_StateGet`(vExpeditionFk INT)
BEGIN
	
	/* Devuelve una "ficha" con todos los datos relativos a la expedición
	 * 
	 * param vExpeditionFk 
	 */
	
	DECLARE vTicketsPendientes INT;
	DECLARE vEtiquetasTotales INT;
	DECLARE vEtiquetasEscaneadas INT;
	DECLARE vEtiquetasLeidasSorter INT;
	DECLARE vRouteFk INT;

	SELECT t.routeFk INTO vRouteFk
		FROM vn.ticket t
			JOIN vn.expedition e ON e.ticketFk = t.id
		WHERE e.id = vExpeditionFk;
	
	SELECT COUNT(*) INTO vTicketsPendientes
		FROM vn.ticket t
			LEFT JOIN vn.expedition e ON e.ticketFk = t.id
		WHERE t.routeFk = vRouteFk
			AND ISNULL(e.id);
		
	SELECT COUNT(*) INTO vEtiquetasTotales
		FROM vn.expedition e 
			JOIN vn.ticket t ON t.id = e.ticketFk
		WHERE t.routeFk = vRouteFk;
	
	SELECT COUNT(*) INTO vEtiquetasEscaneadas
		FROM vn.expeditionScan es 
			JOIN vn.expedition e ON e.id = es.expeditionFk
			JOIN vn.ticket t ON t.id = e.ticketFk 
		WHERE t.routeFk = vRouteFk;
	
	SELECT COUNT(*) INTO vEtiquetasLeidasSorter
		FROM srt.expedition e 
			JOIN vn.expedition ve ON ve.id = e.id
			LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id
			JOIN vn.ticket t ON t.id = ve.ticketFk 
			WHERE t.routeFk = vRouteFk
				AND e.created != e.updated
				AND ISNULL(es.expeditionFk); 
			
		
	SELECT 	e.ticketFk ticket,
			t.nickname cliente,
			a.city ciudad,
			p.name provincia,
			z.name zonaTicket,
			am.name zonaRuta,
			t.routeFk ruta,
			rm.beachFk ubicacion,
			rs.eta ,
			rs.description camion,
			vTicketsPendientes AS ticketsPendientes,
			vEtiquetasTotales AS etiquetasTotales,
			vEtiquetasEscaneadas AS etiquetasEscaneadas,
			vEtiquetasLeidasSorter AS etiquetasSorter
		FROM vn.expedition e 
			JOIN vn.ticket t ON t.id = e.ticketFk 
			JOIN vn.address a ON a.id = t.addressFk 
			JOIN vn.province p ON p.id = a.provinceFk 
			JOIN vn.`zone`z ON z.id = t.zoneFk 
			LEFT JOIN vn.route r ON r.id = t.routeFk 
			LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk 
			LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id 
			LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk 
		WHERE e.id = vExpeditionFk;
	
END$$
DELIMITER ;
