DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInsert`
	BEFORE INSERT ON `expedition`
	FOR EACH ROW
BEGIN
	DECLARE intcounter INT;
    DECLARE vShipFk INT;

	SET NEW.editorFk = account.myUser_getId();

	IF NEW.freightItemFk IS NOT NULL THEN 

		UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;

		SELECT IFNULL(MAX(counter),0) +1 INTO intcounter 
            FROM expedition e 
				INNER JOIN ticket t1 ON e.ticketFk = t1.id 
                LEFT JOIN ticketState ts ON ts.ticketFk = t1.id
				INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) 
                    AND t1.warehouseFk = t2.warehouseFk
			WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk 
                AND t1.agencyModeFk = t2.agencyModeFk;

		SET NEW.`counter` = intcounter;
	END IF;
END$$
DELIMITER ;
