DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`route_beforeUpdate`
	BEFORE UPDATE ON `route`
	FOR EACH ROW
BEGIN
	DECLARE vKmMax INT;
	
	SET NEW.editorFk = account.myUser_getId();
	
	IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN
			SET NEW.m3 = ( SELECT SUM(litros)/1000 
								FROM  vn.saleVolume s 
									JOIN vn.ticket t ON s.ticketFk = t.id 
								WHERE t.routeFk = NEW.id);
	END IF;
   
    IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN
        CALL util.throw ('KmEnd menor que kmStart');
    END IF;

	SELECT kmMax INTO vKmMax
		FROM routeConfig rc;

	IF ((NEW.kmEnd - NEW.kmStart) > vKmMax) AND NEW.kmEnd <> 0 THEN
		CALL util.throw (CONCAT('The km can not exceed ', vKmMax));
	END IF;

END$$
DELIMITER ;
