DROP TRIGGER IF EXISTS `vn2008`.`expeditionsBeforeInsert`;

DELIMITER $$
CREATE DEFINER=`root`@`%` TRIGGER `vn2008`.`expeditionsBeforeInsert`
BEFORE INSERT ON `expeditions` FOR EACH ROW
-- Edit trigger body code below this line. Do not edit lines above this one
BEGIN
	DECLARE intcounter INT;
    DECLARE vShipFk INT;

	IF NEW.EsBulto > 0 THEN 

		UPDATE Tickets SET Bultos = nz(Bultos) + 1 WHERE Id_Ticket = NEW.ticket_id;
		SELECT IFNULL(MAX(counter),0) +1 INTO intcounter FROM expeditions e 
				INNER JOIN Tickets t1 ON e.ticket_id = t1.Id_Ticket 
                LEFT JOIN vn.ticketState ts ON ts.ticket = t1.Id_Ticket
				INNER JOIN Tickets t2 ON t2.Id_Consigna = t1.Id_Consigna AND DATE(t2.Fecha) = DATE(t1.Fecha) AND t1.warehouse_id = t2.warehouse_id
			WHERE t2.Id_Ticket = NEW.ticket_id AND ts.alertLevel < 3 AND t1.empresa_id = t2.empresa_id AND t1.Id_Agencia = t2.Id_Agencia;
		SET NEW.`counter` = intcounter;
	END IF;
    
    -- JGF 14/01/19 si existe un polizon queda anulado
    SELECT shipFk INTO vShipFk FROM vn.stowaway WHERE id = NEW.ticket_id;
    IF vShipFk THEN
		CALL vn.stowawayUnBoarding(vShipFk, NEW.ticket_id);
    END IF;
END$$
DELIMITER ;
