DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(15))
	RETURNS char(2) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
	DETERMINISTIC
BEGIN
	/**
	* Obtiene la serie de una factura
	* dependiendo del area del cliente.
	*
	* @param vClientFk Id del cliente
	* @param vCompanyFk Id de la empresa
	* @param vType Tipo de factura ['global','multiple','quick']
	* @return vSerie de la factura
	*/
	DECLARE vTaxArea VARCHAR(25) COLLATE utf8mb3_general_ci;
	DECLARE vSerie CHAR(2);

	IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN
		RETURN 'S';
	END IF;

	SELECT addressTaxArea(defaultAddressFk, vCompanyFk) INTO vTaxArea
		FROM client
		WHERE id = vClientFk;

	SELECT code INTO vSerie
		FROM invoiceOutSerial
		WHERE `type` = vType AND taxAreaFk = vTaxArea;

	RETURN vSerie;
END$$
DELIMITER ;
