DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`travel_beforeUpdate`
	BEFORE UPDATE ON `travel`
	FOR EACH ROW
BEGIN
	DECLARE vHasAnyInvoiceBooked BOOL;

	SET NEW.editorFk = account.myUser_getId();

	IF NOT (NEW.landed <=> OLD.landed) 
	OR NOT (NEW.shipped <=> OLD.shipped) THEN
		CALL travel_checkDates(NEW.shipped, NEW.landed);
	END IF;

	IF NOT (NEW.isReceived <=> OLD.isReceived) THEN
		CALL travel_checkPackaging(NEW.id);
	END IF;

	IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN
		CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk);
	END IF;

	IF NOT (NEW.awbFk <=> OLD.awbFk)THEN
		SELECT COUNT(*) INTO vHasAnyInvoiceBooked 
			FROM travel t
				JOIN entry e ON e.travelFk = t.id 
				JOIN invoiceIn ii ON ii.id = e.invoiceInFk 
			WHERE t.id = NEW.id
				AND ii.isBooked; 
				
		IF vHasAnyInvoiceBooked THEN
			CALL util.throw('The travel has entries with booked invoices');
		END IF;
	END IF;	
	
	IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN
		CALL travel_throwAwb(NEW.id);
	END IF;
END$$
DELIMITER ;
