DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_next`(
	IN vFiscalYear INT,
	OUT vLastBookEntry INT
)
BEGIN
	DECLARE vHasStartTransaction BOOLEAN;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
		BEGIN

		IF vHasStartTransaction THEN
			ROLLBACK TO sp;
			RESIGNAL;
		ELSE
			ROLLBACK;
			CALL util.throw ('It has not been possible to generate a new ledger');
		END IF;
	END;

	IF vFiscalYear IS NULL THEN
		CALL util.throw('Fiscal year is required');
	END IF;

	SELECT @@in_transaction INTO vHasStartTransaction;
	
	IF NOT vHasStartTransaction THEN
		START TRANSACTION;
	ELSE
		SAVEPOINT sp;
	END IF;

	SELECT bookEntry + 1 INTO vLastBookEntry
		FROM ledgerCompany
		WHERE fiscalYear = vFiscalYear
		FOR UPDATE;

	IF vLastBookEntry IS NULL THEN 
		INSERT INTO ledgerCompany
			SET fiscalYear = vFiscalYear,
				bookEntry = 1;
		SET vLastBookEntry = 1;
	END IF;

	UPDATE ledgerCompany
		SET bookEntry = vLastBookEntry 
		WHERE fiscalYear = vFiscalYear;

	IF vHasStartTransaction THEN
		RELEASE SAVEPOINT sp;	
	ELSE
		COMMIT;
    END IF;
END$$
DELIMITER ;