DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`dms_beforeInsert`
	BEFORE INSERT ON `dms`
	FOR EACH ROW
BEGIN
	DECLARE vHardCopyNumber INT;
	DECLARE vDmsTypeCode INT;
    	               
	IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN
		CALL util.throw('this warehouse has not dms');
	END IF;

	IF NEW.hasFile THEN
		SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber 
            FROM dms 
            WHERE warehouseFk = NEW.warehouseFk;
	
		SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1);
    END IF;
    
	SELECT code INTO vDmsTypeCode 
		FROM dmsType WHERE NEW.dmsTypeFk = id;
	 IF (vDmsTypeCode ='ticket')  THEN
	  UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference;
	 END IF;
END$$
DELIMITER ;
