﻿

-- =============================================
-- Author:		Dr. Stefan Ott
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[fis_getModuleAuth]
(
	@module varchar(50),
	@useraccount_id varchar(10)  -- length is 5; content would be cut to 5 is variable-length is 5 also
)
RETURNS int
AS
BEGIN
	DECLARE @RET int,  @TMP int, @module_base varchar(50), @module_qualifier varchar(50);
	SET @module = ISNULL(@module,'');
	SET @module_base = CASE WHEN CHARINDEX('-', @module) = 0 THEN @module ELSE LEFT(@module, CHARINDEX('-', @module) -1) END;
	SET @module_qualifier = CASE WHEN CHARINDEX('-', @module) = 0 THEN '' ELSE RIGHT(@module, LEN(@module) - CHARINDEX('-', @module)) END;

	SET @RET = CASE WHEN @module = '' OR LEFT(@module,1) ='-'  -- OR ISNULL(@account, '') IN ('','*'))
						THEN -3
					WHEN @useraccount_id = 'sa'
						THEN 10
					WHEN NOT EXISTS (SELECT 0 FROM [dbo].[fis_useraccounts] as u WHERE u.[useraccount_id] = @useraccount_id and u.[DateDeleted] is null)
						THEN -2
					WHEN EXISTS (SELECT 0 FROM [dbo].[fis_useraccounts] as u WHERE u.[useraccount_id] = @useraccount_id and u.[DateDeleted] is null AND u.[DateDisabled] is not null)
						THEN -1
					WHEN @module <> 'fds-admin' AND NOT EXISTS (SELECT 0 from [dbo].[fis_module_auth] as a WHERE a.[module] = @module)
						THEN 0
				ELSE NULL END;


	IF @RET is null
		BEGIN
			WITH maCTE as (
				SELECT * FROM [dbo].[fis_module_auth] as a_ 
			)
			SELECT @RET = Max(a.[auth]) 
				FROM maCTE as a
					WHERE (
							((@module LIKE (a.[module] + '%') OR @module = a.[module]) AND @module <> '') 
						  OR a.[module] = 'admin'
						)
					AND ( 
							   (a.[isgroup] = 0 AND a.[group_or_user] = @useraccount_id)
							OR (a.[isgroup] = 1 AND [dbo].[fis_admin_testGroupMembership](@useraccount_id, a.[group_or_user]) = 1)
						);
		END

	
	IF @module_qualifier not in ('manage','admin') AND @RET between -1 and 9 AND @RET between -1 and 9
		SET @RET = [dbo].[ott_max](@RET, [dbo].[fis_getModuleAuth](@module_base + '-manage', @useraccount_id ));  

	IF @module <> 'fds-admin' AND ISNULL(@RET, -1) between -1 and 9
		SET @RET = [dbo].[ott_max](@RET, [dbo].[fis_getModuleAuth]('fds-admin', @useraccount_id ));  

	--SET @RET = CASE WHEN @module = 'fds_inv' and @useraccount_id = 'J5KL8' THEN 1 ELSE @RET END;

	SET @RET = ISNULL(@RET, -3);

	RETURN @RET

END