IF OBJECT_ID('dbo.fn_fco_tarifa_FSP') IS NOT NULL
    DROP FUNCTION dbo.fn_fco_tarifa_FSP
GO
CREATE FUNCTION dbo.fn_fco_tarifa_FSP
(
    @pch_compania char(4), 
    @pch_trabajador char(10), 
    @psi_anio smallint,
    @pti_mes tinyint,
    @pdc_valor decimal(19,6), -- mesada para los pensionados
    @pbi_pensionado bit = 1
)
RETURNS decimal(6,5)
AS
BEGIN
    DECLARE 
        @vdc_tarifa decimal(6,5),
        @vdc_sal_min decimal(16,6),
        @vdc_salarios decimal(5,2) -- Cantidad de Salarios Mínimos
        
    SELECT @vdc_sal_min = real FROM parametros_rh
    WHERE compania = @pch_compania AND parametro_rh = 'Sal_Minimo' AND secuencia_parametro = 1
      AND Convert(char(6), fecha, 112) <= Rtrim(@psi_anio) + Right('00' + RTrim(@pti_mes), 2)

    IF @vdc_sal_min IS NULL
        SELECT TOP 1 @vdc_sal_min = salario_minimo FROM hist_sal_min_zona
        WHERE zona = 'A' AND Convert(char(6), fecha, 112) <= Rtrim(@psi_anio) + Right('00' + RTrim(@pti_mes), 2)
        ORDER BY fecha Desc
    
    IF IsNull(@vdc_sal_min, 0) = 0 
        SET @vdc_salarios = 0
    ELSE
        SET @vdc_salarios = @pdc_valor / @vdc_sal_min

    SELECT @vdc_tarifa = porcentaje FROM impuestos
    WHERE impuesto = 5
      AND @vdc_salarios BETWEEN limite_inferior AND limite_superior
    
    RETURN ISNULL(@vdc_tarifa / 100, 0)
END
GO
GRANT EXECUTE ON dbo.fn_fco_tarifa_FSP TO PUBLIC
GO

