
DELIMITER $$

DROP TRIGGER IF EXISTS `opng_crist_nrdokfin_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `opng_crist_nrdokfin_bu` BEFORE UPDATE
	ON `opng`
	FOR EACH ROW A: BEGIN

-- wartosc @session.trigger_lock rowna TRUE blokuje wykonanie triggera

		IF IFNULL(@session.trigger_lock, FALSE) THEN LEAVE A; END IF;
-- 
		SET @session.opng = TRUE;
		IF (NEW.deleted=0 and NEW.nrdokfin='' and NEW.rodzaj in (5,6) and NEW.kontrguid<>'') THEN BEGIN
			update kontrah set upowaznienie=upowaznienie+1 where guid=NEW.kontrguid;
			select concat(if(NEW.rodzaj=5,'FV ','F '),lpad(upowaznienie,3,'0'),'/',year(NEW.datawystaw)) into @nrdokfin from kontrah where guid=NEW.kontrguid;
			SET NEW.nrdokfin = @nrdokfin;
		END;	
		END IF;
		SET @session.opng = FALSE;
		
    END;
$$

DELIMITER ;
