DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`itemCost_beforeUpdate`
	BEFORE UPDATE ON `itemCost`
	FOR EACH ROW
BEGIN
	IF NEW.itemFk IN (95, 98) THEN
		SET NEW.cm3 = 0;
    END IF;
    
	IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN
		INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
			SELECT r.id 
				FROM vn.itemCost ic
					JOIN vn.sale s ON s.itemFk = ic.itemFk
					JOIN vn.ticket t ON t.id = s.ticketFk  AND t.warehouseFk = ic.warehouseFk 
					JOIN vn.route r ON r.id = t.routeFk
				WHERE r.isOk = FALSE 
					AND ic.itemFk = NEW.itemFk
					AND r.created >= util.VN_CURDATE()
				GROUP BY r.id;
		IF NEW.cm3Delivery = 0 AND NEW.warehouseFk = 60 THEN
			CALL mail_insert(
				'jgallego@verdnatura.es',
    			NULL,
    			'update cm3Delivery',
    			CONCAT('articulo: ', NEW.itemFk));
		END IF;
	END IF;
END$$
DELIMITER ;
