DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`invoiceOut_getMaxIssued`(vSerial VARCHAR(2),
	vCompanyFk INT,
	vYear INT
)
	RETURNS date
	NOT DETERMINISTIC
	READS SQL DATA
BEGIN
/**
 * Retorna la fecha a partir de la cual es válido emitir una factura 
 *
 * @param vSerial Serie de facturación 
 * @param vCompanyFk Empresa factura emitida
 * @param vYear Año contable
 * @return vInvoiceOutIssued fecha factura válida
 */
	DECLARE vInvoiceOutIssued DATE;
	DECLARE vFirstDayOfYear DATE;
	
	SET vFirstDayOfYear := MAKEDATE(vYear, 1);

	SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued 
		FROM invoiceOut io
		WHERE io.serial = vSerial
			AND io.companyFk = vCompanyFk
			AND io.issued BETWEEN vFirstDayOfYear 
				AND util.lastDayOfYear(vFirstDayOfYear);

	RETURN vInvoiceOutIssued;
END$$
DELIMITER ;
