--USE [sOffice8_AGVISER]--[SOffice8_BCCR] --[S-Office8_Test] --[TUDI_SEST]--[sOffice8_AGVISER_20241216]
--GO
--USE [S-Office8_Test]
--GO
--USE [Mosquito_TEST]
--GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
DROP PROCEDURE IF EXISTS [dbo].[usp_ssERP8_update_sys_acl_resources]
GO

/*
select * from stepsoft.dbo.PARAMETERS
where CallFrom=N'usp_ssERP8_update_sys_acl_resources'
  AND DBname=N'S-Office8_Test'
  AND cast(TimeStmp as date)=N'2025-06-19'
order by id desc

select * from sys_acl_resources where name like 'ReportController@get%'
select sys_acl_resources.name,sys_acl_resource_role_rel.* from sys_acl_resource_role_rel
	join sys_acl_resources ON sys_acl_resource_role_rel.id_resource=sys_acl_resources.id
where sys_acl_resources.name like 'ReportController@get%'
  and id_role=1

select	 sys_reports.*
		,sys_print_forms.id as id_sys_print_froms
		,sys_reports_settings.id as id_sys_reports_settings
from sys_reports
	join sys_reports_settings ON sys_reports_settings.id_object=sys_reports.id
	left join sys_print_forms ON sys_print_forms.id_object = sys_reports_settings.id AND sys_print_forms.objectType = 3
where sys_reports.id=97

EXEC [dbo].[usp_ssERP8_update_sys_acl_resources]	 @id_objectType=3
													,@id_object=24
													,@SP_MODE='TEST1'
--*/
CREATE PROCEDURE [dbo].[usp_ssERP8_update_sys_acl_resources]
-- Author		Щерю Щерев																									
-- Create date	16/01/2025
-- Version		
--				
-- Serever		MS SQL 2019
-- Description	Updating the [dbo].[sys_acl_resources] table
-- Returns		0 = fail, 1 = success
-- TempTables	
-- Constraint	
-- Parameters
		@id_objectType				 int		NULL=NULL				--	1. ID of object type. null=all objects types
	   ,@id_object					 int		NULL=NULL				--	2. ID of objects. null=all objects of this type
	   ,@id_resource				 int		NULL=NULL				--	3. ID of resource. null=all resources for this object
	   ,@only_insert				 bit		NULL=0					--	4. 1=Do NOT modify existing right 0=modify all rights
	  -------------------------------------- 
	   ,@Output_json				 nvarchar(MAX)	NULL=''	OUTPUT		--	5. Text of result
	   ,@ErrMessage					 nvarchar(MAX)	NULL=''	OUTPUT		--	6. Text of error
	   ,@Return						 nvarchar(2)   	NULL=''	OUTPUT		--	7. Exit code parameter
	   ,@SP_MODE		 			 nvarchar(30) 	NULL='EXECUTE'  	--	8. Execution mode / Дали е в работен или тестов режим
--====================================================================================================================================
AS BEGIN
/* manualUpdateFlag: No */
BEGIN TRY
/* DECLARE
		@id_objectType int=1			
	   ,@id_object int=46				
	   ,@id_resource int=NULL			
	   ,@only_insert bit=0				
	  -------------------------------------- 
	   ,@Output_json nvarchar(MAX)=N''			
	   ,@ErrMessage nvarchar(MAX)=N''	
	   ,@Return nvarchar(2)=N''		
	   ,@SP_MODE nvarchar(30)=N'TEST1'  
--*/
	SET NOCOUNT ON;
		DECLARE @ProcedureName sysname = ISNULL(OBJECT_NAME(@@PROCID),N'usp_ssERP8_update_sys_acl_resources')
		DECLARE @SQLstr nvarchar(MAX), @nRetValue int = 1, @Status nvarchar(1024) = N'0', @ExitCode int
		DECLARE @ParamDefinition nvarchar(MAX), @CommandString nvarchar(MAX)
		DECLARE @HOST nvarchar(255) = HOST_NAME()
			SET @ErrMessage = N''

	-- 1. Parameters sniffing
	DECLARE @object_type nvarchar(255), @object_name nvarchar(1024)

		SET @Status += ',1'
		--CREATE TABLE #Items ( [id] nvarchar(1024), [table_name] nvarchar(128), [id_object] int, [id_objectType] int )
		-- exec ( 'use tempdb; select * from sys.columns where object_id = OBJECT_ID(''tempdb.dbo.#Items'')')

		-- @SP_MODE
		--	SET @SP_MODE = case when @SP_MODE is null then N'EXECUTE' when @SP_MODE=N'TEST1' then N'TEST1' when @SP_MODE=N'TEST' then N'TEST' else N'EXECUTE' end
			DECLARE @MetaIndex nvarchar(2048) = case when LEFT(@SP_MODE,5)=N'TEST1' then TRIM(SUBSTRING(@SP_MODE,6,2000)) end
			SET @SP_MODE = case when LEFT(@SP_MODE,5)=N'TEST1'																				then N'TEST1' 
								when @SP_MODE=N'TEST'																						then N'TEST' 
								when exists ( select 1 from [dbo].[sys_global_settings] where [name]=N'SP_MODE' AND [value]=N'TEST')		then N'TEST'
								when exists ( select 1 from [dbo].[sys_global_settings] where [name]=N'SP_MODE' AND [value]=@ProcedureName)	then N'TEST'
								else																											 N'EXECUTE' 
							end
		-- @id_objectType
			IF @id_objectType is not null	BEGIN
				SET @id_objectType = (select [id] from [dbo].[sys_systemObjects] where [id]=@id_objectType)
				 IF @id_objectType is null begin SET @ErrMessage += 'Invalid @id_objectType parameter'; SET @nRetValue = 0 end
											END
			ELSE SET @id_object = null
		-- @id_object
			IF @id_object is not null AND @id_objectType is not null	BEGIN
			IF			 	@id_objectType = 1 
									begin -- select * from sys_translations where 
								select @id_object = [sys_objectReference].[objectable_id],@object_type=[sys_systemObjects].[description], @object_name=[sys_translations].[value]
								from [dbo].[sys_nmcl] 
									left join [dbo].[sys_objectReference] ON [sys_objectReference].[sys_systemObjects_id]=1 AND [sys_objectReference].[objectable_id]=[sys_nmcl].[id]
									left join [dbo].[sys_translations] ON [sys_translations].[label]=[sys_nmcl].[label] AND [sys_translations].[filename]='nomenclature' AND [sys_translations].[locale]=N'bg' AND [sys_translations].[device]=N'web'
									left join [dbo].[sys_systemObjects] ON [sys_systemObjects].[id]=[sys_objectReference].[sys_systemObjects_id]
								where [sys_nmcl].[id]=@id_object
									end	
			   ELSE	IF	    @id_objectType = 2
									begin -- select * from [dbo].[sys_objectReference] where sys_systemObjects_id=2 AND	objectable_id=69
								select	 @id_object = [sys_objectReference].[objectable_id]
										,@object_type=[sys_systemObjects].[description]
										,@object_name=[sys_translations].[value]
								from [dbo].[sys_doctype]
									left join [dbo].[sys_objectReference] ON [sys_objectReference].[sys_systemObjects_id]=2 AND [sys_objectReference].[objectable_id]=[sys_doctype].[id]
									left join [dbo].[sys_translations] ON [sys_translations].[label]=[sys_doctype].[label] AND [sys_translations].[filename]='document' AND [sys_translations].[locale]=N'bg' AND [sys_translations].[device]=N'web'
									left join [dbo].[sys_systemObjects] ON [sys_systemObjects].[id]=[sys_objectReference].[sys_systemObjects_id]
								where [sys_doctype].[id]=@id_object
									end
				    ELSE IF @id_objectType = 3 
									begin
								select @id_object = [sys_objectReference].[objectable_id],@object_type=[sys_systemObjects].[description], @object_name=[sys_translations].[value]
								from [dbo].[sys_reports]
									left join [dbo].[sys_objectReference] ON [sys_objectReference].[sys_systemObjects_id]=3 AND [sys_objectReference].[objectable_id]=[sys_reports].[id]
									left join [dbo].[sys_translations] ON [sys_translations].[label]=[sys_reports].[label] AND [sys_translations].[filename]='report' AND [sys_translations].[locale]=N'bg' AND [sys_translations].[device]=N'web'
									left join [dbo].[sys_systemObjects] ON [sys_systemObjects].[id]=[sys_objectReference].[sys_systemObjects_id]
								where [sys_reports].[id]=@id_object
									end	
						 ELSE				   SET @id_objectType = NULL
			 IF @id_object is null begin SET @ErrMessage += 'Invalid @id_object parameter'; SET @nRetValue = 0 end
																		END -- IF @id_object is not null AND @id_objectType is not null
		-- @id_resource
			IF @id_resource is not null	begin
				SET @id_resource = (select [id] from [dbo].[sys_acl_resources] where [id]=@id_resource)
										end	

	-----------------------------------------------------------------------------------------------------------------------------------------------------
	-- 2. Logging the data for analysis / Запазване на данни за анализ
		SET @Status += ',2'
		DECLARE @TestSaveParamID int = 0
	IF OBJECT_ID(N'stepsoft.dbo.PARAMETERS') is not null AND LEFT(@SP_MODE,4)=N'TEST'	BEGIN
		DECLARE @PrmString varchar(7168) = ISNULL(cast(@id_objectType as varchar(10)),'null')+','		--	1. ID of object type. null=all objects types
										 + ISNULL(cast(@id_object as varchar(10)),'null')+','			--	2. ID of objects. null=all objects of this type
										 + ISNULL(cast(@id_resource as varchar(10)),'null')+','			--	3. ID of resource. null=all resources for this object
										 + ISNULL(@SP_MODE,'null')
		DECLARE @PrmJson nvarchar(MAX) = (	SELECT	 @id_objectType as [@id_objectType]					--	1. ID of object type. null=all objects types	
													,@id_object		as [@id_object]						--	2. ID of objects. null=all objects of this type
													,@id_resource	as [@id_resource]					--	3. ID of resource. null=all resources for this object
													,@ErrMessage 	as [@ErrMessage]					--	7. Text of error
													,@Return		as [@Return]						--	8. Exit code parameter
													,@SP_MODE		as [@SP_MODE]						--	9. Execution mode / Дали е в работен или тестов режим
											FOR JSON PATH, WITHOUT_ARRAY_WRAPPER )
		DECLARE @DBName nvarchar(128) = DB_NAME()
			 EXEC [stepsoft].[dbo].[usp_ssTestSaveParam] @PrmMessage = @PrmString, @CallingModule = @ProcedureName, @XMLString = null
														,@Separator = ',', @DataBase = @DBName, @RecordID = @TestSaveParamID OUTPUT
														,@PrmJson = @PrmJson 
		print @ProcedureName+'->SP_MODE = ' + ISNULL(@SP_MODE,'NULL')+' '+@ProcedureName+'->TestSaveParamID = ' + ISNULL(cast(@TestSaveParamID as varchar(10)),'NULL')

																						END -- 	IF OBJECT_ID(N'stepsoft.dbo.PARAMETERS') is not null AND LEFT(@SP_MODE,4)=N'TEST'	BEGIN
	IF @SP_MODE=N'TEST1' select  @ProcedureName+N'('+@Status+N')' as [procedure], N'Parameters' as tbl
								,@id_objectType as '@id_objectType', @id_object as '@id_object',@id_resource as '@id_resource'
								,@object_type as '@object_type', @object_name as '@object_name'
								,@SP_MODE as '@SP_MODE',@MetaIndex as '@MetaIndex',@nRetValue as '@nRetValue', @ErrMessage as '@ErrMessage'
	
	-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- 3. Create pilot tables / Създаване на спомагателни таблици
	/************************************************************
	* В този раздел се създава таблицата #Resources съдържаща	*
	* ВСИЧКИ имена на ресурси за 8ма версия с включени			*
	* МЕТАПРОМЕНЛИВИ в името									*
	* ТАБЛИЦАТА ТРЯБВА ДА СЕ АКТУАЛИЗИРА при появата/промяната	*
	* или премахването на ресурс в системата					*
	************************************************************/
		SET @Status += ',3'
	DROP TABLE IF EXISTS #Resources
	CREATE TABLE #Resources 
		(	 id int identity	
		,resource_name			nvarchar(1024)
		,resource_type			tinyint			 
		,resource_description	nvarchar(512)	-- Calendar			─────┐	
												-- Configuration		 │	
												-- Dashboard			 ├	ресурси НЕСВЪРЗАНИ с обекти
												-- Widget				 │
												-- Navigation			 │
												-- Location				 │
												-- Home					 │
												-- Import				 │
												-- Profile			─────┘
												-- Nomenclature		─────┐
												-- Documents			 ├ ресурси СВЪРЗАНИ с обекти
												-- Reports				 │
												------					 │
												-- Form					 │
												-- Sections				 │
												-- Elements				 │
												-- Print			─────┘
		,resource_comment		nvarchar(500)
		,resource_default		tinyint
		,is_trackable			tinyint
		,default_id_object		int
		,default_id_objectType	int
		)
	INSERT INTO #Resources	( 	 resource_name, resource_type, resource_description, resource_comment, is_trackable, default_id_object, default_id_objectType ) 
	VALUES
		-- 3.1. Resources for controllers
			 (	N'AdminController@index'										,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за достъп до меню Администрация/Конфигуриране
			,(	N'RolesController@index'										,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за списък с роли
			,(	N'RolesController@getEditRolePermissions'						,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за права по роля
			,(	N'RolesController@getEditRolePermissions/<<id_sys_acl_roles>>'	,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер за редакция на права по конкретна роля
			,(	N'RolesController@storeRolePermissions'							,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за запис права по роли
			,(	N'RolesController@storeRolePermissions/<<id_sys_acl_roles>>'	,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер за запис на промени по права на конкретна роля
			,(	N'RolesController@store'										,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер (общ) за запис на роля
			,(	N'RolesController@getEditRole'									,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер (общ) за редакция на роля
			,(	N'RolesController@saveRolePermissions'							,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер (общ) за запис на права по роля
			,(	N'RolesController@deleteRole'									,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер (общ) за изтриване на роля (не деактивира, а изтрива!)
			,(	N'UsersController@index'										,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за списък с Потребители
			,(	N'UsersController@updateUserRoles'								,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер за даване/обновяване на роля на Потребител
			,(	N'UsersController@addNewPersonalPermission'						,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер за добавяне на персонално право за Потребител
			--,(	N'UsersController@saveUserPersonalPermissions'					,	1,	N'Configuration',	N'Route',	1,	0,	0	)	-- Контролер за запис на персонално правно за Потребител
			,(	N'UsersController@getUserRolesById'								,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за извличане на роли за Потребители
			,(	N'UsersController@getUserRolesById/<<id_sys_users>>'			,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер за извличане на роли за конкретен Потребител
			,(	N'UsersController@getUserPersonalPermissions'					,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер (общ) за извличане на персонални права за Потребители
			,(	N'UsersController@getUserPersonalPermissions/<<id_sys_users>>'	,	1,	N'Configuration',	N'Route',		1,	0,	0	)	-- Контролер за извличане на персонални права за конкретен Потребители
			,(	N'UserRolesPermissionsController@index'							,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер (общ) за списък с права на роли по потребители
			,(	N'UserRolesPermissionsController@getEditRolePermissions'		,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер за редакция/промяна права на роли по потребители
			,(	N'UserRolesPermissionsController@storeRolePermissions'			,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер за запис на права по роля на потребители
			,(	N'UsersController@deletePersonalPermission'						,	1,	N'Configuration',	N'Route',		0,	0,	0	)	-- Контролер за изтриване на персонални права по потребител
			--,(	N'ConfigController@updateAcl'									,	1,	N'Configuration',	N'Route',	0,	0,	0	)	-- Контролер за обновяване на права по всички роли, за да не се налага разлогване
			,(	N'CalendarController@index'										,	1,	N'Calendar',		N'Route',		1,	0,	0	)	-- Контролер (общ) за Календар
			,(	N'CalendarController@getEvents'									,	1,	N'Calendar',		N'Route',		1,	0,	0	)	-- Контролер (общ) за зареждане на събития в Календар
			,(	N'HomeController@index'											,	1,	N'Home',			N'Route',		1,	0,	0	)	-- Контролер (общ) за достъп до заглавната навигационна лента с менюта?
			,(	N'ImportController@index'										,	1,	N'Import',			N'Route',		1,	0,	0	)	-- Контролер (общ) за достъп до меню Импорт на файлове-- Контролер за конкретен работен плот
			,(	N'FormsController@getForm'										,	1,	N'Form',			N'Route',		1,	0,	0	)	-- Контролер (общ) за извличане на форми на документ?
			--,(	N'TranslationsController@publishTranslations'					,	1,	N'language',		N'Route',	1,	0,	0	)	-- Контролер (общ) за обновяване на права, преведени през Конфигуратора, така че да се налага разлогване в Клиента
			,(	N'FormsController@getOpenedObjects'								,	1,	N'Form',			N'Route',		1,	0,	0	)	-- Контролер (общ) за виждане на всички отворени обекти в десния панел?
			,(	N'ProfileController@edit'										,	1,	N'Profile',			N'Route',		1,	0,	0	)	-- Контролер (общ) за редакция на потребителски профил
			--,(	N'AuthController@logout'										,	1,	N'logout',			N'Route',	1,	0,	0	)	-- Контролер (общ) за излизане от системата
			,(	N'NavigationController@getNavigations'							,	1,	N'Navigation',	 	N'Route',		1,	0,	0	)	-- Контролер за навигация?
			,(	N'DashboardController@index'									,	1,	N'Dashboard',		N'Route',		0,	0,	0	)	-- Контролер (общ) за достъп до меню Дашборд
			,(	N'DashboardController@index/<<id_sys_dashboards>>'				,	1,	N'Dashboard',		N'Route',		0,	0,	0	)	-- Контролер за достъп до конкретен Дашборд
			,(	N'DashboardController@saveDashboardElement	'					,	1,	N'Dashboard',		N'Route',		0,	0,	0	)	-- Контролер за запис на елемент?
			,(	N'WidgetsController@getWidget/<<id_sys_widgets>>'				,	1,	N'Widget',			N'Route',		1,	0,	0	)	-- Контролер за конкретен работен плот
			,(	N'WidgetsController@modifyWidget/<<id_sys_widgets>>'			,	1,	N'Widget',			N'Route',		1,	0,	0	)	-- Контролер за конкретен работен плот
		-- 3.2. Resources for nomenclatures
			,(	N'NmclController@index'											,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер за активиране/деактивиране на меню Номенклатури
			,(	N'NmclController@show'											,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер (общ) за право на виждане на Номенклатури
			,(	N'NmclController@edit'											,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер (общ) за право на редакция на Номенклатури
			,(	N'NmclController@create'										,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер (общ) за право на създаване на запис в Номенклатури
			,(	N'NmclController@store'											,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер (общ) за право на запис на Номенклатури
			,(	N'NmclController@destroy'										,	1,	N'Nomenclature',	N'Route',		1,	0,	1	)	-- Контролер (общ) за право на триене на Номенклатури
			,(	N'NmclController@show/<<id_sys_nmcl>>'							,	1,	N'Nomenclature',	N'Route',		1,	1,	1	)	-- Контролер (общ) за право на виждане на конкретна номенклатура. След '@show/' се показва Id-то на номенклатурата
			,(	N'NmclController@edit/<<id_sys_nmcl>>'							,	1,	N'Nomenclature',	N'Route',		1,	1,	1	)	-- Контролер (общ) за право на редакция на конкретна номенклатура. След '@edit/' се показва Id-то на номенклатурата
			,(	N'NmclController@create/<<id_sys_nmcl>>'						,	1,	N'Nomenclature',	N'Route',		1,	1,	1	)	-- Контролер (общ) за право на създаване на запис в конкретна номенклатура. След '@create/' се показва Id-то на номенклатурата
			,(	N'NmclController@store/<<id_sys_nmcl>>'							,	1,	N'Nomenclature',	N'Route',		1,	1,	1	)	-- Контролер (общ) за право на запис в конкретна номенклатура. След '@store/' се показва Id-то на номенклатурата
			,(	N'NmclController@destroy/<<id_sys_nmcl>>'						,	1,	N'Nomenclature',	N'Route',		1,	1,	1	)	-- Контролер (общ) за право на изтриване на запис в конкретна номенклатура. След '@destroy/' се показва Id-то на номенклатурата
		-- 3.3. Resources for documents
			,(	N'DocumentController@index'										,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер за активиране/деактивиране на меню Документи
			,(	N'DocumentController@show'										,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на виждане на документи
			,(	N'DocumentController@edit'										,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на редакция на документи
			,(	N'DocumentController@store'										,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на запис на документи
			,(	N'DocumentController@search'									,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на търсене в документи
			,(	N'DocumentController@searchResult'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на виждане на резултат от търсене в документи
			,(	N'DocumentController@searchRows'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на търсене в редове на документи
			,(	N'DocumentController@addSearchRows'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на добавяне на редове от търсене в документи
			,(	N'DocumentController@searchConfig'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на филтри/стартиране на търсене в документи
			,(	N'DocumentController@createAndFillDocumentByReport'				,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на създаване/наследяване документи през справки
			,(	N'DocumentController@createAndFill'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контролер (общ) за право на създаване/наследяване документи през документна форма
			,(	N'DocumentController@show/<<id_sys_doctype>>'					,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- DocumentController@show/(document_id)Контролер за право на виждане на конкретен документ. След '@show/' се показва Id-то на документа
			,(	N'DocumentController@create/<<id_sys_doctype>>'					,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на създаване на конкретен документ. След '@create/' се показва Id-то на документа
			,(	N'DocumentController@edit/<<id_sys_doctype>>'					,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на редакция на конкретен документ. След '@edit/' се показва Id-то на документа
			,(	N'DocumentController@store/<<id_sys_doctype>>'					,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на запис на конкретен документ. След '@store/' се показва Id-то на документа
			,(	N'DocumentController@destroy/<<id_sys_doctype>>'				,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на анулиране на конкретен документ. След '@destroy/' се показва Id-то на документа
			,(	N'DocumentController@search/<<id_sys_doctype>>'					,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на търсене в конкретен документ. След '@search/' се показва Id-то на документа
			,(	N'DocumentController@docsearch/<<id_sys_docType/id_sys_reports_settings>>',1,N'Documents',	N'Route',		1,	1,	1	)	-- Контролер за право на търсене в конкретен документ. След '@docsearch/' се показва Id-то на документа
			,(	N'DocumentController@searchResult/<<id_sys_doctype>>'			,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на виждане на резултат от търсене в конкретен документ. След '@searchResult/' се показва Id-то на документа
			,(	N'DocumentController@searchRows/<<id_sys_doctype>>'				,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на търсене в редове на конкретен документ. След '@searchRows/' се показва Id-то на документа
			,(	N'DocumentController@searchConfig/<<id_sys_doctype>>'			,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на филтри/стартиране на търсене в конкретен документ. След '@searchConfig/' се показва Id-то на документа
			,(	N'DocumentController@createAndFill/<<id_sys_doctype>>'			,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право създаване и наследяване на данни към документ наследник през документната форма на документ родител. След '@createAndFill/' се показва Id-то на документа, който се създава като наследник.
			,(	N'DocumentController@createAndFillDocumentByReport/<<id_sys_doctype>>',1,N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за право на създаване/наследяване конкретен документи през справка.След '@createAndFillDocumentByReport/' се показва Id-то на документа
			,(	N'DocumentController@createAndFillDocumentByInheritance/<<id_sys_doctype>>',1,	N'Documents',N'Route',		1,	1,	1	)	-- Контролер за право създаване и наследяване на данни към документ наследник през документната форма на документ родител. След '@createAndFillDocumentByInheritance/' се показва Id-то на документа, който се създава като наследник. 
			,(	N'DocumentController@createAndFillDocumentByInheritance/<<id_sys_doctype>>/Prev',1,	N'Documents',N'Route',	1,	1,	1	)	-- Ресурс за управляване на бутон "Предишен док." в интерфейса за наследвяване.
			,(	N'DocumentController@createAndFillDocumentByInheritance/<<id_sys_doctype>>/Next',1,	N'Documents',N'Route',	1,	1,	1	)	-- Ресурс за управляване на бутон "Следващ док." в интерфейса за наследвяване.
		-- 3.4. Resources for reports
			,(	N'ReportController@index'										,	1,	N'Reports',	    	N'Route',		1,	0,	1	)	-- Контолер (общ) За достъп до меню справки
			,(	N'PrintController@printReport'									,	1,	N'Reports',	    	N'Route',		1,	0,	1	)	-- Контолер (общ) за печат през справки
			,(	N'ReportController@config'										,	1,	N'Reports',			N'Route',		1,	0,	1	)	-- Контолер (общ) за виждане на филтри или стартиране на справки
			,(	N'ReportController@show'										,	1,	N'Reports',			N'Route',		1,	0,	1	)	-- Контолер (общ) за виждане на справки в списък
		--,(	N'ReportController@discardcache'								,	1,	N'Documents',		N'Route',		1,	0,	1	)	-- Контолер (общ) за изчистване на кеш?
			,(	N'ReportController@show/<<id_sys_reports>>'						,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за виждане на конкретна справка. След '@show/' се показва id-то на справката
			,(	N'ReportController@view/<<id_sys_reports>>'						,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за преглед на резултат (tab) на конкретна справка. След '@view/' се показва id-то на справката
			,(	N'ReportController@config/<<id_sys_reports>>'					,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за виждане на филтри или стартиране на конкретна справка. След '@config/' се показва id-то на справката
			,(	N'ReportController@change/<<id_sys_reports>>'					,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за ..................конкретна справка. След '@change/' се показва id-то на справката
			,(	N'ReportController@index/<<id_sys_reports>>'					,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за виждане на конкретна справка в списъка със справки. След '@index/' се показва id-то на справката
			,(	N'ReportController@totalsum/<<id_sys_reports>>'					,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Ресурс за управляване на сумарният ред в дадена справка.
		--	,(	N'ReportController@discardcache/<<id_sys_reports>>'				,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за изчистване на кеш конкретна справка в списъка със справки? След '@discardcache/' се показва id-то на справката
		    ,(	N'ReportController@filter/<<id_sys_reports/id_sys_referenceMap_filter>>',1,	N'Reports',		N'Route',		1,	1,	1	)	-- Ресурс за управляване на филтър в дадена справка.
			,(	N'ReportController@column/<<id_sys_reports/id_sys_referenceMap_columns>>',1,N'Reports',		N'Route',		1,	1,	1	)	-- Ресурс за управляване на колона в дадена справка.
			,(	N'ReportController@exportAll/<<id_sys_reports>>'				,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Ресурс за управляване на експорт на данни в цялата справка.
			,(	N'ReportController@export/<<id_sys_reports/id_sys_reports_settings>>',1,N'Reports',			N'Route',		1,	1,	1	)	-- Ресурс за управляване на експорт на данни за даден таб/view в справката.
			,(	N'ReportController@tab/<<id_sys_reports/id_sys_reports_settings>>',	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Ресурс за управляване на таб/view в дадена справка
			,(	N'ReportController@CreateDocByReport/<<id_sys_reports>>'		,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- ресурс да се създава документ от цялата справка
			,(	N'ReportController@CreateDocByReport/<<id_sys_reports/id_sys_reports_settings>>',1,N'Reports',N'Route',		1,	1,	1	)	-- ресурс да се създава документ от изглед насправка	
		--	,(	N'ReportController@column/<<id_sys_reports/id_sys_element>>'	,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- ресурс да се ползва колона на справка
			,(	N'report/<<id_sys_reports_settings/name_column>>'				,	5,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер/ресурс показва типа на обекта (report)/id на изглед (tab) на справка/ име на колона в справка. 
			,(	N'ReportController@getReportsByGroup/<<id_sys_reports_groups>>'	,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за получаване на печатни форми за група справки. След '@getReportsByGroup/' се показва id-то на групата справки
		-- 3.5. Resources for print forms
			,(	N'PrintController@index'										,	1,	N'Print',			N'Route',		1,	0,	0	)	-- Контолер (общ) за списък на печатни форми
			,(	N'PrintController@show'											,	1,	N'Print',			N'Route',		1,	0,	0	)	-- Контолер (общ) за показване/виждане на печатни форми
			,(	N'PrintController@printDocument'								,	1,	N'Print',			N'Route',		1,	0,	1	)	-- Контолер (общ) за печатна форма на документ 
			,(	N'PrintController@index/<<id_sys_doctype>>'						,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за показване на списък с печатни форми за конкретен документ. След '@index/' се показва id-то на документа
			,(	N'PrintController@show/<<id_sys_doctype>>'						,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за виждане на печатни форми за конкретен документ. След '@show/' се показва id-то на документа
			,(	N'PrintController@printDocument/<<id_sys_doctype>>'				,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за печат на документ. След '@printDocument/' се показва id-то на документа
			,(	N'PrintController@printDocument/<<id_sys_doctype/id_sys_print_forms>>',	1,	N'Documents',	N'Route',		1,	1,	1	)	-- Контролер за печат на документ. След '@printDocument/' се показва id-то на документа
		--	,(	N'PrintController@printReport/<<id_sys_reports_settings>>'		,	1,	N'Documents',		N'Route',		1,	1,	1	)	-- Контролер за печат на бланка през конкретна справка. След '@printReport/' се показва id-то на справката, от която ще се отпечатва бланка
			,(	N'PrintController@printReport/<<id_sys_reports_settings/id_sys_print_forms>>',1,N'Documents',N'Route',		1,	1,	1	)	-- Контролер за печат на бланка през конкретна справка. След '@printReport/' се показва id-то на справката, след нея /id-то на бланката
			,(	N'PrintController@printReport/<<id_sys_reports>>'				,	1,	N'Reports',			N'Route',		1,	1,	1	)	-- Контролер за печат през конкретна справка. След '@printReport/' се показва id-то на справката
			,(	N'PrintController@getReportsByGroup/<<id_sys_reports_groups>>'	,	1,	N'Reports',			N'Route',		1,	0,	1	)	-- Контролер за получаване на печатни форми за група справки. След '@getReportsByGroup/' се показва id-то на групата справки
		-- 3.6. Resources for sections
			,(	N'section-<<id_sys_sections>>'									,	1,	N'Sections',		N'Route',		1,	1,	1	)	-- Контролер/ресурс за секция. След тирето се показва ид-то на секцията
			,(	N'section-<<id_sys_sections>>/AddRow'							,	1,	N'Sections',		N'Route',		1,	1,	1	)	-- Контролер/ресурс за секция. Добавяне на ред
			,(	N'section-<<id_sys_sections>>/DeleteRow'						,	1,	N'Sections',		N'Route',		1,	1,	1	)	-- Контролер/ресурс за секция. Изтриване на ред
		-- 3.7. Resources for elements
			,(	N'form-<<id_sys_form/name_sys_element>>'						,	2,	N'Elements',		N'Route',		1,	1,	1	)	-- Контролер/ресурс за секция. Изтриване на ред
		-- 3.8. Other resources
			--,(	N'bg'															,	3,	N'language',		N'Route',	1,	0,	0	)	-- Контролер (общ) за видимост на полета на български език
			--,(	N'en'															,	3,	N'language',		N'Route',	1,	0,	0	)	-- Контролер (общ) за видимост на полета на английски език
			--,(	N'tr'															,	3,	N'language',		N'Route',	1,	0,	0	)	-- Контролер (общ) за видимост на полета на турски език
			--,(	N'de'															,	3,	N'language',		N'Route',	1,	0,	0	)	-- Контролер (общ) за видимост на полета на немски език
			,(	N'loginLocation'												,	6,	N'Location',		N'location',	1,	0,	0	)	-- 
		--	,(	N'loginLocation/<<id_location>>'								,	6,	N'Location',		N'location',	1,	0,	0	)	-- 
		-- Премахване на ресурси които не са за @id_objectType параметъра(това включва ресурсите Nomenclature, Documents и Reports)
		IF @id_objectType is not null	begin
			IF @id_objectType=1			DELETE FROM #Resources WHERE [resource_description]=N'Documents' OR [resource_description]=N'Reports'		-- [resource_description]<>N'Nomenclature'
			IF @id_objectType=2			DELETE FROM #Resources WHERE [resource_description]=N'Nomenclature' OR [resource_description]=N'Reports'	-- [resource_description]<>N'Documents'	
			IF @id_objectType=3			DELETE FROM #Resources WHERE [resource_description]=N'Nomenclature' OR [resource_description]=N'Documents'	-- [resource_description]<>N'Reports'		
										end
	IF @SP_MODE=N'TEST1' AND EXISTS ( select 1 from #Resources ) begin
		select  @ProcedureName+N'('+@Status+N')' as [procedure], N'Table #Resources' as tbl,@nRetValue as '@nRetValue', @ErrMessage as '@ErrMessage',* from #Resources
		IF @MetaIndex is not null
			select N'proba #Resources' as tbl,* from #Resources where resource_name LIKE N'%'+@MetaIndex+N'%' 
																 end
		ELSE IF @SP_MODE=N'TEST1'
		select  @ProcedureName+N'('+@Status+N')' as [procedure], N'NO rows in table #Resources' as tbl,@nRetValue as '@nRetValue', @ErrMessage as '@ErrMessage'

	-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- 4. Collecting meta variable sets from system settings/ Събиране на стойностите на мета променливите от настройките на системата
	/************************************************************
	* В този раздел се създава таблицата #Items съдържаща		*
	* ВСИЧКИ използвани в настройките стойности на				*
	* МЕТАПРОМЕНЛИВИТЕ											*
	************************************************************/
		SET @Status += ',4'
	DROP TABLE IF EXISTS #Items
	select TOP(0)  
			 [name]							as [id]				-- идентификатор на метапроменливата(нй-често id, но понякога name,label...)
			,cast( null as nvarchar(128))	as [table_name]		-- таблица съдържаща идентификатора
			,cast( null as int )			as [id_objectType]	-- ID на тип обект (ако се метапроменливата е обвързана с тип)
			,cast( null as int )			as [id_object]		-- ID на обекта (ако метапроменливата е обвързана с обект)
		into #Items
	from sys_acl_resources
	  --------------------------------------  !!!!!!!!!!!!!!!!!!!!
	  --if the parameters below are equal to:
	  -- = 0			-- resources will be missed
	  -- = valid ID		-- include resources only for this ID
	  -- = NULL			-- include resources for ALL ID	
	  DECLARE
	    @id_sys_users				 int		--	4. ID of user. null= for all users
	   ,@id_sys_acl_roles			 int		--	5. ID of role. null= for all roles
	   ,@id_sys_dashboards			 int		--	6. ID of dashboard. null= for all dashboards
	   ,@id_sys_widgets				 int		--	7. ID of widget. null= for all widgets
	   ,@id_sys_nmcl				 int		--	8. ID of nomenclature. null= for all nomenclatures
	   ,@id_sys_doctype				 int		--	9. ID of document type. null= for all document types 
	   ,@id_sys_reports				 int		--	10.ID of report. null= for all reports 
	   ,@id_sys_reports_groups		 int		--	11. ID of reports_groups. null= for all reports_groups
	   ,@id_sys_sections			 int		--	12.ID of section. null= for all sections 
	   ,@id_sys_form				 int		--	13.ID of form. null= for all forms 	   
	   ,@id_sys_print_forms			 int		--	14.ID of printform. null= for all print forms

	IF @nRetValue = 1	BEGIN
	-- ПОТРЕБИТЕЛИ	
		SET @Status += ',a'
		-- @id_sys_users - филтриране ако e посочен конкретен потребител/всички потребители
		INSERT INTO  #Items ( [id], [table_name] ) SELECT DISTINCT [id], N'id_sys_users' as [table_name] FROM [dbo].[sys_users] WHERE [id]=ISNULL(@id_sys_users,[id])
	-- РОЛИ
		SET @Status += ',b'
		-- @id_sys_acl_roles - филтриране ако e посочена конкретна роля/всички роли
		INSERT INTO #Items ( [id], [table_name] ) SELECT DISTINCT [id], N'id_sys_acl_roles' as [table_name] FROM [dbo].[sys_acl_roles] WHERE [id]=ISNULL(@id_sys_acl_roles,[id])
	-- ТАБЛА
		SET @Status += ',c'
		-- @id_sys_dashboards  - филтриране ако e посочен конкретeн dashboard
		INSERT INTO #Items ( [id], [table_name] ) SELECT  DISTINCT [id], N'id_sys_dashboards' as [table_name] FROM [dbo].[sys_dashboards] WHERE [id]=ISNULL(@id_sys_dashboards,[id])
	-- СЪРВИСИ
		SET @Status += ',d'
		-- @id_sys_widgets - филтриране ако e посочен конкретeн widgets
		INSERT INTO #Items ( [id], [table_name] ) SELECT  DISTINCT [id], N'id_sys_widgets' as [table_name] FROM [dbo].[sys_widgets] WHERE [id]=ISNULL(@id_sys_widgets,[id])

		-- @id_location -- филтриране на локации
		-- INSERT INTO #Items SELECT [id] FROM [dbo].[sys_locations] WHERE [id]=ISNULL(@id_location,[id])


		-- МЕТАПРОМЕНЛИВИ СВЪРЗАНИ С ОБЕКТИ
		-- НОМЕНКЛАТУРИ
		-- @id_sys_nmcl -- филтриране по номенклатури
		SET @Status += ',e'
		  IF ISNULL(@id_objectType,1) = 1	begin -- определен е тип номенклатури
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] ) 
												  -- една или всички номенклатури	
				SELECT [id], N'id_sys_nmcl' as [table_name], [id] as [id_object], 1 as [id_objectType] 
				FROM [dbo].[sys_nmcl] 
				WHERE [id]=ISNULL(@id_object,[id])
											end
		-- ДОКУМЕНТИ
		-- @id_sys_doctype
		SET @Status += ',f'
		  IF ISNULL(@id_objectType,1) = 2	begin -- определен е тип документи
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] ) 
												  -- един или всички типове документи	
				SELECT [id], N'id_sys_doctype' as [table_name], [id] as [id_object], 2 as [id_objectType]  
				FROM [dbo].[sys_doctype] 
				WHERE [id]=ISNULL(@id_object,[id])
											end
		-- СПРАВКИ
		-- @id_sys_reports
		SET @Status += ',g'
		IF ISNULL(@id_objectType,1) = 3	begin -- определен е тип справки
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
												  -- една или всички справки	
				SELECT [sys_reports].[id], N'id_sys_reports' as [table_name], [sys_reports].[id] as [id_object], 3 as [id_objectType] 
				FROM [dbo].[sys_reports] 
					LEFT JOIN [dbo].[sys_reports_groups] ON	[sys_reports].[id_sys_reports_groups]=[sys_reports_groups].[id] 
				WHERE [sys_reports].[id]=ISNULL(@id_object,[sys_reports].[id])
				  AND [sys_reports].[id_sys_reports_groups]=ISNULL(@id_sys_reports_groups,[sys_reports].[id_sys_reports_groups])
										end

		-- ГРУПИ СПРАВКИ
		-- @id_sys_reports_groups - филтриране ако e посочена конкретна група справки
		SET @Status += ',h'
		IF ISNULL(@id_objectType,1) = 3	begin -- определен е тип справки
		INSERT INTO #Items ( [id], [table_name],[id_objectType]/*,[id_object]*/ )
			SELECT DISTINCT
						  [sys_reports_groups].[id]
						 ,N'id_sys_reports_groups' as [table_name]
						 ,3 as [id_objectType]
						 --,[sys_reports].[id] as [id_object]
			FROM [dbo].[sys_reports] 
				JOIN [dbo].[sys_reports_groups] ON	[sys_reports].[id_sys_reports_groups]=[sys_reports_groups].[id] 
			WHERE [sys_reports].[id]=ISNULL(@id_object,[sys_reports].[id])
			  AND [sys_reports_groups].[id]=ISNULL(@id_sys_reports_groups,[sys_reports_groups].[id])
					-- AND [active]=1
										end
		-- СЕКЦИИ
		-- @id_sys_sections
		SET @Status += ',i'
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  ) 
				SELECT	[sys_sections].[id]
					   ,N'id_sys_sections' as [table_name]
					   ,ISNULL(or1.objectable_id,or2.objectable_id)
					   ,ISNULL(or1.sys_systemObjects_id,or2.sys_systemObjects_id)
				FROM [dbo].[sys_sections]
					LEFT JOIN [dbo].[sys_referenceMap] ON [sys_sections].[id]=[sys_referenceMap].[sys_section_id]
					LEFT JOIN [dbo].[sys_referenceMap_dynamic] ON [sys_sections].[id]=[sys_referenceMap_dynamic].[sys_section_id]
					LEFT JOIN [dbo].[sys_objectReference] as or1 ON [or1].[sys_form_id]=[sys_referenceMap].[sys_form_id]
					LEFT JOIN [dbo].[sys_objectReference] as or2 ON [or2].[sys_form_id]=[sys_referenceMap_dynamic].[sys_form_id]
				WHERE [sys_sections].[id]=ISNULL(@id_sys_sections,[sys_sections].[id])
				  AND ([or1].[sys_systemObjects_id]=ISNULL(@id_objectType,[or1].[sys_systemObjects_id]) OR [or2].[sys_systemObjects_id]=ISNULL(@id_objectType,[or2].[sys_systemObjects_id]))
				  AND ([or1].[objectable_id]=ISNULL(@id_object,[or1].[objectable_id]) OR [or2].[objectable_id]=ISNULL(@id_object,[or2].[objectable_id]))

		-- @id_sys_referenceMap
		SET @Status += ',j'
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
				select  [sys_referenceMap].[id]			as [id]
					   ,N'id_sys_referenceMap'			as [table_name]
					   ,[or1].[objectable_id]		    as [id_object]	
					   ,[or1].[sys_systemObjects_id]    as [id_objectType]
				from [dbo].[sys_referenceMap]
					LEFT JOIN [dbo].[sys_objectReference] as or1 ON [or1].[sys_form_id]=[sys_referenceMap].[sys_form_id]
 				where or1.sys_systemObjects_id=ISNULL(@id_objectType,or1.sys_systemObjects_id)
				  AND or1.objectable_id=ISNULL(@id_object,or1.objectable_id) 
		-- @id_sys_referenceMap_dynamic
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
				select  [sys_referenceMap_dynamic].[id]	as [id]
					   ,N'id_sys_referenceMap'			as [table_name]
					   ,[or2].[objectable_id]		    as [id_object]	
					   ,[or2].[sys_systemObjects_id]    as [id_objectType]
				from [dbo].[sys_referenceMap_dynamic]
					LEFT JOIN [dbo].[sys_objectReference] as or2 ON [or2].[sys_form_id]=[sys_referenceMap_dynamic].[sys_form_id]
 				where or2.sys_systemObjects_id=ISNULL(@id_objectType,or2.sys_systemObjects_id)
				  AND or2.objectable_id=ISNULL(@id_object,or2.objectable_id) 
		---------------------------------------------------------------------------------------------------------------------------------------------------
		-- doubletes meta variables -----------------------------------------------------------------------------------------------------------------------
		-- ФОРМА-ИМЕ НА ЕЛЕМЕНТ
		-- @id_sys_form/name_sys_element
				-- form-21-element-placent_peculiarities_complications_notes
				-- select * from dbo.ufn_ssERP8_CollectObjects(	null,null,null,null,null,null,'bg')
		SET @Status += ',k'
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
				select DISTINCT  
						cast([object_interface_form_id] as nvarchar(20)) -- id form
					   + N'-element-'+ [element_name]					-- element_name	
					   ,N'id_sys_form/name_sys_element'
					   ,[objectable_id]
					   ,[object_type]
				from dbo.ufn_ssERP8_CollectObjects(	@id_objectType,		-- @sys_systemObjects_id
													@id_object,				-- @sys_objectable_id
													@id_sys_form,		-- @sys_form_id
													null,				-- @sys_section_id
													null,				-- @sys_element_id
													null,				-- @sys_table_id
													'bg'
												  )
				where [object_interface_form_id] is not null AND [element_name] is not null

		-- ИЗГЛЕД НА СПРАВКА-ПЕЧАТНА ФОРМА
		-- @id_sys_reports_settings/id_sys_print_forms
				-- select * from [dbo].[sys_reports_settings]; select * from [dbo].[sys_print_forms]
		SET @Status += ',l'
			IF ISNULL(@id_objectType,3)=3 begin
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
				-- declare @id_object int, @id_sys_print_forms int
				select DISTINCT 
						cast(srs.[id] as nvarchar(20))			-- id settings
					   + N'/'+ cast(pf.[id]	as nvarchar(20))	-- id print form
					   ,N'id_sys_reports_settings/id_sys_print_forms'
					   ,sr.[id]
					   ,3
				from [dbo].[sys_reports] as sr
					JOIN [dbo].[sys_reports_settings] as srs ON sr.[id]=srs.[id_object] AND srs.[objectType] = 3
					JOIN [dbo].[sys_print_forms]	  as pf ON srs.objectType=pf.objectType AND srs.id=pf.id_object
				where sr.id=ISNULL(@id_object,sr.id)
				  AND pf.[id]=ISNULL(@id_sys_print_forms,pf.[id])
				  AND srs.[id] is not null AND pf.[id] is not null
										  end -- IF ISNULL(@id_objectType,3)=3 

		-- СПРАВКА-ИЗГЛЕД НА СПРАВКА
		-- @id_sys_reports/id_sys_reports_settings
		SET @Status += ',m'
			IF ISNULL(@id_objectType,3)=3 begin
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
				-- declare @id_object int, @id_sys_print_forms int
				select DISTINCT  
						cast(sr.[id]		 as nvarchar(20))	-- id report
					   + N'/'+ cast(srs.[id] as nvarchar(20))	-- id reports setting
					   ,N'id_sys_reports/id_sys_reports_settings'
					   ,sr.[id]
					   ,3
				from [dbo].[sys_reports] as sr
					JOIN [dbo].[sys_reports_settings] as srs ON sr.[id]=srs.[id_object] AND srs.[objectType] = 3
					JOIN [dbo].[sys_print_forms]	  as pf ON srs.objectType=pf.objectType AND srs.id=pf.id_object
				where sr.id=ISNULL(@id_object,sr.id)
				  AND sr.[id] is not null AND srs.[id] is not null
										  end -- IF ISNULL(@id_objectType,3)=3 

		-- ИЗГЛЕД НА СПРАВКА-ИМЕ НА КОЛОНА
		-- @id_sys_reports_settings/name_column -- нормални справки
		SET @Status += ',n'
			IF ISNULL(@id_objectType,3)=3 begin
				-- select * from [dbo].[sys_reports_settings] where [id_object]=81; select * from [dbo].[sys_print_forms]
				-- select * from dbo.ufn_ssERP8_CollectObjects(	3,null,null,null,null,null,'bg')
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
				-- declare @id_object int = 81-- select * from 
					select DISTINCT  
							cast(srs.[id] as nvarchar(20))	-- id settings
						   + N'/'+ f.[element_name]			-- element name
																		   as [id]
						   ,N'id_sys_reports_settings/name_column'		   as [table_name]
						   ,sr.[id]										   as [id_object]	
						   ,3											   as [id_objectType]
					from sys_reports as sr
						JOIN [dbo].[sys_reports_settings] as srs ON sr.[id]=srs.[id_object] AND srs.[objectType] = 3
						cross apply dbo.ufn_ssERP8_CollectObjects(3,@id_object,null,null,null,null,'bg') as f
 					where (sr.id=@id_object OR @id_object is null)
					  AND f.[element_description] IN (N'Report column',N'Report filter')
					  AND srs.[id] is not null AND f.[element_name]	is not null
										  end -- IF ISNULL(@id_objectType,3)=3
								
		-- @id_sys_reports_settings/name_column -- вътрешнодокументни справки
			IF ISNULL(@id_objectType,2)=2 begin
		SET @Status += ',o'
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType] )
				-- declare @id_object int = 81; select * from cachereport151
					select DISTINCT  
							cast(srs.[id] as nvarchar(20))	-- id settings
						   + N'/'+ f.[name]					-- element name
																		   as [id]
						   ,N'id_sys_reports_settings/name_column'		   as [table_name]
						   ,sdt.[id]									   as [id_object]	
						   ,2											   as [id_objectType]
					from sys_doctype as sdt
						JOIN [dbo].[sys_reports_settings] as srs ON sdt.[id]=srs.[id_object] AND srs.[objectType] = 2
						cross apply OPENJSON(srs.settings,'$.colSettings') WITH ( [name] nvarchar(50) '$.name' ) as f
 					where (sdt.id=@id_object OR @id_object is null)
					  AND srs.[id] is not null AND f.[name] is not null
										  end -- IF ISNULL(@id_objectType,2)=2 

		-- СПРАВКА-КАРТА НА ЕЛЕМЕНТИ
		-- @id_sys_reports/id_sys_referenceMap
		SET @Status += ',p'
		/*
			IF ISNULL(@id_objectType,3)=3 begin
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
				--  select * from ufn_sdCollectReportElements(99,'bg'); declare @id_object int=99
				select DISTINCT  
						cast(obR.[objectable_id]	as nvarchar(20))	-- id report
					   + N'/'+ cast(rm.[id] as nvarchar(20))		-- id reports setting
					   ,N'id_sys_reports/id_sys_referenceMap'
					   ,obR.[objectable_id]
					   ,3
				from sys_referenceMap as rm 
					JOIN sys_objectReference as obR ON obR.[sys_form_id]=rm.[sys_form_id] AND obR.[sys_systemObjects_id]=3
				--	cross apply ufn_sdCollectReportElements(obR.objectable_id,'bg') as f
 				where obR.objectable_id=@id_object OR @id_object is null
				--  AND f.[type]=N'filters'
										  end -- IF ISNULL(@id_objectType,3)=3
		*/

		-- ДОКУМЕНТ-ИЗГЛЕД НА СПРАВКА
		-- @id_sys_docType_id/sys_reports_settings -- select * from sys_reports_settings
		SET @Status += ',q'
			IF ISNULL(@id_objectType,2)=2 begin
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
				-- declare @id_object int = 81
				select DISTINCT  
						cast(sdt.[id]		 as nvarchar(20))	-- id report
					   + N'/'+ cast(srs.[id] as nvarchar(20))	-- id reports setting
					   ,N'id_sys_docType/id_sys_reports_settings'
					   ,sdt.[id]
					   ,2
				from [dbo].[sys_docType] as sdt
					JOIN [dbo].[sys_reports_settings] as srs ON sdt.[id]=srs.[id_object] AND srs.[objectType] = 2
					-- LEFT JOIN [dbo].[sys_reports] as sr ON sr.[id]=srs.[reportID]
				where (sdt.id=@id_object OR @id_object is null)
				  AND sdt.[id] is not null AND srs.[id] is not null
										  end -- IF ISNULL(@id_objectType,2)=2

		-- ДОКУМЕНТ-ПЕЧАТНА ФОРМА
		-- @id_sys_doctype/id_sys_print_forms -- select * from sys_print_forms
		SET @Status += ',r'
			IF ISNULL(@id_objectType,2)=2 begin
				INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
				-- declare @id_object int = 81
				select DISTINCT 
						cast(sdt.[id]		 as nvarchar(20))	-- id report
					   + N'/'+ cast(spf.[id] as nvarchar(20))	-- id print form
					   ,N'id_sys_doctype/id_sys_print_forms'
					   ,sdt.[id]
					   ,2
				from [dbo].[sys_docType] as sdt
					JOIN [dbo].[sys_print_forms] as spf ON sdt.[id]=spf.[id_object] AND spf.[objectType] = 2
					-- LEFT JOIN [dbo].[sys_reports] as sr ON sr.[id]=srs.[reportID]
				where (sdt.id=@id_object OR @id_object is null)
				  AND sdt.[id] is not null AND spf.[id] is not null 
										  end -- IF ISNULL(@id_objectType,2)=2

		-- СПРАВКА-ЕЛЕМЕНТ (КОЛОНИ И ФИЛТРИ)
		-- @id_sys_reports/id_sys_element
		SET @Status += ',s'
			IF ISNULL(@id_objectType,3)=3 begin
			-- DECLARE @id_object int
			DROP TABLE IF EXISTS #ReportColumns
				select	 f.[object_type]				 as [id_objectType]
						,f.[objectable_id]				 as [id_object]
						,f.[rm_id]						 as [id_sys_referenceMap]
						,f.[element_id]					 as [id_sys_element]
						,f.[element_name]				 as [element_name]
						,f.[element_label]				 as [element_label]
						,f.[element_description]		 as [element_description]
					--	,sr.[label]+N'-'+js.[name]		 as [element_label]
						,f.[objectable_table_name]		 as [report_tableName]
			INTO #ReportColumns
				-- DECLARE @id_objectType int = 3, @id_object int =96; select  f.[object_type] as [id_objectType],f.[objectable_id] as [id_object],f.[element_name] as [element_name],f.[rm_id] as [id_sys_referenceMap],f.[objectable_table_name] as [report_tableName]
				from ufn_ssERP8_CollectObjects(  @id_objectType		-- 1. ID of object type		
												,@id_object			-- 2. ID of source object	
												,null				-- 3. ID of interface form	
												,null				-- 4. ID of section			
												,null				-- 5. ID of element			
												,null				-- 6. ID of table			
												,'bg'				-- 7. Current language		
											  ) as f

			INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
			select DISTINCT 
					 cast(ReportColumns.[id_object] as nvarchar(20))+N'/'
					+cast(ReportColumns.[id_sys_referenceMap] as nvarchar(20))	 as [id]
					,N'id_sys_reports/id_sys_referenceMap_columns'				 as [table_name]
					,ReportColumns.[id_object]									 as [id_object]	
					,ReportColumns.[id_objectType]								 as [id_objectType]
			from #ReportColumns		 as ReportColumns
			where ReportColumns.[element_description] = N'Report column'
			  and ReportColumns.[id_object] is not null 
			  and ReportColumns.[id_sys_referenceMap] is not null

			INSERT INTO #Items ( [id], [table_name], [id_object], [id_objectType]  )
			select DISTINCT 
					cast(ReportColumns.[id_object] as nvarchar(20))+N'/'
					+cast(ReportColumns.[id_sys_referenceMap] as nvarchar(20))	 as [id]
					,N'id_sys_reports/id_sys_referenceMap_filter'				 as [table_name]
					,ReportColumns.[id_object]									 as [id_object]	
					,ReportColumns.[id_objectType]								 as [id_objectType]
			from #ReportColumns		 as ReportColumns
			where [element_description] = N'Report filter' 
			  and ReportColumns.[id_object] is not null 
			  and ReportColumns.[id_sys_referenceMap] is not null
										  end	-- IF ISNULL(@id_objectType,3)=3 

						END -- IF @nRetValue = 1	

	
	IF @SP_MODE=N'TEST1' AND exists ( select 1 from #Items) begin
		select  @ProcedureName+N'('+@Status+N')' as [procedure], N'Table #Items' as tbl,* from #Items
		IF @MetaIndex is not null
			select N'proba #Items' as tbl,* from #Items where table_name=@MetaIndex order by [id_objectType], [id_object]
															end
		ELSE IF @SP_MODE=N'TEST1'
			select  @ProcedureName+N'('+@Status+N')' as [procedure], N'No rows in table #Items' as tbl

--======================================================================================================================================
	-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
	-- 5. Create table #sys_acl_resources/ Създаване на таблицата #sys_acl_resources
	/************************************************************
	* В този раздел се създава таблицата #sys_acl_resources		*
	* съдържаща ВСИЧКИ НЕОБХОДИМИ РЕСУРСИ						*
	* според параметрите @id_objectType и @id_object			*
	* и @id_resource											*
	************************************************************/
		SET @Status += ',5'
	DROP TABLE IF EXISTS #sys_acl_resources
	SELECT TOP(0) * INTO #sys_acl_resources FROM [dbo].[sys_acl_resources]
	ALTER TABLE #sys_acl_resources DROP COLUMN [id]
	IF COL_LENGTH(N'#sys_acl_resources',N'id_object') is null ALTER TABLE #sys_acl_resources ADD id_object int
	IF COL_LENGTH(N'#sys_acl_resources',N'id_objectType') is null ALTER TABLE #sys_acl_resources ADD id_objectType int

		DECLARE @Output_res TABLE ( [action] nvarchar(255), [name_resource] nvarchar(1024) )
		DECLARE @Output_del TABLE (	[action] nvarchar(255), [id_resource] int, [name_resource] nvarchar(1024), [id_objectType] int, [id_object] int )
	
	DECLARE  @id int
			,@resource_name			 nvarchar(1024)
				,@key_name1			 nvarchar(50), @p1 int, @p2 int, @l1 int	
				,@key_name2			 nvarchar(50), @p3 int, @p4 int, @l2 int	
			,@resource_type			 tinyint
			,@resource_description	 nvarchar(512)
			,@resource_comment		 nvarchar(500)
			,@resource_default 		 tinyint
			,@is_trackable	 		 tinyint
			,@default_id_object		 int
			,@default_id_objectType	 int

	IF @nRetValue = 1	BEGIN
	DECLARE @CNT_resources TABLE ( resource_name nvarchar(1024), [name] nvarchar(1024) )
	DECLARE @CNT_metaName TABLE  ( resource_name nvarchar(1024), [CNT] int )
	DECLARE @test_resources TABLE ( [resource_name] nvarchar(1024), [replaced_name] nvarchar(1024), [@key_name1] nvarchar(1024), [@l1] int )
	DECLARE resource_cursor CURSOR FOR SELECT  id,resource_name,resource_type,resource_description,resource_comment,resource_default,is_trackable,default_id_object,default_id_objectType
									   FROM #Resources	
	OPEN resource_cursor;	FETCH NEXT FROM resource_cursor INTO @id,@resource_name,@resource_type,@resource_description,@resource_comment,@resource_default,@is_trackable,@default_id_object,@default_id_objectType
		WHILE (@@FETCH_STATUS <> -1)   BEGIN
		   IF (@@FETCH_STATUS <> -2)   BEGIN   
			SET @p1 = CHARINDEX( N'<<', @resource_name) ; SET @p2 = CHARINDEX( N'>>', @resource_name)
			SET @l1 = 0; IF @p1 > 0 AND @p2 > @p1 begin SET @p1 += 2; SET @p2 -= 1; SET @l1 = @p2-@p1+1; SET @key_name1 = SUBSTRING(@resource_name,@p1,@l1) end
			--SET @p3 = CHARINDEX( N'<<', @resource_name,@p2+2) ; SET @p4 = CHARINDEX( N'>>', @resource_name,@p2+2)
			--SET @l2 = 0; IF @p3 > 0 AND @p4 > @p3 begin SET @p3 += 2; SET @p4 -= 1; SET @l2 = @p4-@p3+1; SET @key_name2 = SUBSTRING(@resource_name,@p3,@l2) end
	
	--	print @resource_name+N'--'+cast(@l as nvarchar(20))
	delete @CNT_resources
			IF @l1>0 --AND (@default_id_object=1 OR @default_id_objectType=1)	 
						begin
						 INSERT INTO #sys_acl_resources ( name, type, comment, is_trackable, flag, insert_date, id_object, id_objectType )
							OUTPUT @resource_name, inserted.[name] INTO @CNT_resources
						 SELECT replace(@resource_name, N'<<'+@key_name1+N'>>', cast([id] as nvarchar(1024)))
								--stuff(@resource_name, @p1, @l1, cast([id] as nvarchar(20)))
												  as [name]
							   ,@resource_type	  as [type]
							   ,@resource_comment as [comment]
							   ,@is_trackable	  as [is_trackable]
							   ,1				  as [flag]
							   ,GetDate()		  as [insert_date]
							   ,ISNULL([id_object],0)		as [id_object]		
							   ,ISNULL([id_objectType],0)	as [id_objectType]
						 FROM #Items 
						 WHERE [table_name]=@key_name1
						   AND (ISNULL([id_object],@id_object)=@id_object OR @id_object is null)
						   AND (ISNULL([id_objectType],@id_objectType)=@id_objectType OR @id_objectType is null)
					--	print @key_name
						end			
			ELSE		begin
						 INSERT INTO #sys_acl_resources ( name, type, comment, is_trackable, flag, insert_date, id_object, id_objectType )
							OUTPUT @resource_name, inserted.[name] INTO @CNT_resources
						 SELECT @resource_name														as [name]
							   ,@resource_type														as [type]
							   ,@resource_comment													as [comment]
							   ,@is_trackable														as [is_trackable]
							   ,0																	as [flag]
							   ,GetDate()															as [insert_date]
							   ,case when @default_id_object=1 then @id_object else 0 end			as [id_object]		
							   ,case when @default_id_objectType=1 then	@id_objectType else 0 end	as [id_objectType]
						end
	insert into @CNT_metaName ( [resource_name], [CNT] ) select [resource_name], COUNT(name) as CNT from @CNT_resources group by [resource_name]
		IF @MetaIndex is not null AND @resource_name LIKE N'%'+@MetaIndex+N'%' 
			insert into @test_resources ([resource_name], [replaced_name], [@key_name1], [@l1])
			select [resource_name], [name], @key_name1, @l1 from @CNT_resources 
									   END
							FETCH NEXT FROM resource_cursor INTO @id,@resource_name,@resource_type,@resource_description,@resource_comment,@resource_default,@is_trackable,@default_id_object,@default_id_objectType
									   END
	CLOSE resource_cursor; DEALLOCATE resource_cursor
							END
	IF @SP_MODE=N'TEST1' AND EXISTS ( select 1 from #sys_acl_resources ) begin	
		select  @ProcedureName+N'('+@Status+N')' as [procedure], N'Table #sys_acl_resources' as tbl,* from #sys_acl_resources order by [name]
		IF @MetaIndex is not null select 'proba @test_resources' as tbl,* from @test_resources 
																		 end
	  ELSE IF @SP_MODE=N'TEST1'												
		select  @ProcedureName+N'('+@Status+N')' as [procedure], N'NO rows in table #sys_acl_resources' as tbl,@nRetValue as '@nRetValue', @ErrMessage as '@ErrMessage'
	-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
	-- 5. Modify resources table ( sys_acl_resources ) / Модифициране на основната таблица с ресурси
		SET @Status += ',6'
		IF @nRetValue = 1 AND @SP_MODE <> N'TEST1'	BEGIN
		SET @Status += 'a'
	-- delate duplication
	;WITH CTE
	 AS	(  SELECT *, ROW_NUMBER() OVER (PARTITION BY [name] ORDER BY [name]) as Duplicate
				   FROM #sys_acl_resources
		)
	--SELECT * FROM CTE WHERE Duplicate > 1
	--/*
		DELETE FROM CTE 
			   -- [action], [id_resource], [name_resource], [id_objectType],	  [id_object] int
			OUTPUT N'DELETE', null,  deleted.[name],  deleted.[id_objectType], deleted.[id_object] INTO @Output_del 
		WHERE Duplicate > 1	
	--*/
	-- check structure
		SET @CommandString = N''
			IF COL_LENGTH(N'[dbo].[sys_acl_resources]',N'objectType') is null SET @CommandString += N'[objectType] INT'
			IF COL_LENGTH(N'[dbo].[sys_acl_resources]',N'objectID') is null SET @CommandString += case when @CommandString <> N'' then N',' else N'' end  +  N'[objectID] INT'
			IF @CommandString <> N'' /*	print N'ALTER TABLE [dbo].[sys_acl_resources] ADD '+@CommandString */ EXEC (N'ALTER TABLE [dbo].[sys_acl_resources] ADD '+@CommandString)

	-- merge temp table AND [dbo].[sys_acl_resources]
		SET @Status += 'b'
		-- select * from [dbo].[sys_acl_resources]
	MERGE [dbo].[sys_acl_resources]			AS tgt  
	USING (	SELECT	 [name]
					,[type]
					,[comment]
					,[is_trackable]
					,[flag]
					,[insert_date]
					,[id_objectType]	as [objectType]
					,[id_object]		as [objectID]
			FROM #sys_acl_resources	
			WHERE ( ISNULL([id_object],0)=@id_object OR @id_object is null )
			  AND ( ISNULL([id_objectType],0)=@id_objectType OR @id_objectType is null )	
									)		AS src
		ON ( tgt.[name] COLLATE database_default = src.[name] COLLATE database_default )
		
		WHEN MATCHED AND (tgt.id = @id_resource OR @id_resource is null ) 
					 AND (@only_insert =0)
						 THEN UPDATE 
								SET  [type] = src.[type]
									,[comment]=src.[comment]
									,[is_trackable]=src.[is_trackable]
									,[flag]=src.[flag]
									,[insert_date]=src.[insert_date]
									,[objectType]=ISNULL(src.[objectType],0)
									,[objectID]=ISNULL(src.[objectID],0)
		WHEN NOT MATCHED AND @id_resource is null
						THEN INSERT (	[name],[type],[comment],[is_trackable],[flag],[insert_date],[objectType],			[objectID] )
							  VALUES (	[name],[type],[comment],[is_trackable],[flag],[insert_date],ISNULL([objectType],0),	ISNULL([objectID],0)  )
		OUTPUT $action, inserted.[name] INTO @Output_res;
													END -- IF @nRetValue = 1 AND @SP_MODE <> N'TEST1'


--======================================================================================================================================
END TRY
BEGIN CATCH																																																	
-- Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
		--close opened cursors
		--DROP TABLE IF EXISTS #cursors
		--SELECT * INTO #cursors FROM sys.dm_exec_cursors(0) WHERE session_id = @@SPID
		--IF EXISTS (select 1 from #cursors WHERE [name] = 'Transferring_cursor' COLLATE database_default ) 	begin	CLOSE Transferring_cursor;	DEALLOCATE Transferring_cursor	end
		--WHILE @@TRANCOUNT > 0 ROLLBACK TRANSACTION
		DECLARE @ERROR_PROCEDURE nvarchar(128) = ISNULL(ERROR_PROCEDURE(),@ProcedureName)+ISNULL(N'-'+@Status,N'')
		DECLARE @ERROR_MESSAGE nvarchar(2048) = ISNULL(ERROR_MESSAGE(),N'n/a')
		SET @ErrMessage = isnull(@ErrMessage+N',',N'')	
							 +N'SQL Msg: ' + ISNULL(cast(ERROR_NUMBER() as nvarchar(20)),N'')	+N','
							 +N' Level ' + ISNULL(cast(ERROR_SEVERITY() as nvarchar(20)),N'')	+N','
							 +N' State ' + ISNULL(cast(ERROR_STATE() as nvarchar(20)),N'')		+N','
							 +N' Proc ' + @ERROR_PROCEDURE									
							 +N'('+ISNULL('Line: '+cast(ERROR_LINE() as nvarchar(20)),N'')		+N'),'
							 + @ERROR_MESSAGE		
		SET @nRetValue = 0 
END CATCH

	-- Запазване на данни за анализ на грешката
	IF @nRetValue = 0 AND @TestSaveParamID > 0 UPDATE [StepSoft].[dbo].[PARAMETERS] SET [ErrMessage] = @ErrMessage WHERE [ID] = @TestSaveParamID 
		DECLARE @Error TABLE ( [Error] nvarchar(2048) ); INSERT INTO @Error SELECT [Value] as Error FROM string_split(@ErrMessage,';')	WHERE ISNULL([Value],N'') <> N'' 
			SET @ErrMessage = (SELECT * FROM @Error FOR JSON AUTO , ROOT('Errors'))
	-- Определяне на перформънс
	IF @TestSaveParamID > 0 UPDATE [StepSoft].[dbo].[PARAMETERS] SET [EndTime] = GETDATE() WHERE [ID] = @TestSaveParamID 
	-- Връщане на резултат
	SET @Return = @nRetValue
	SET @Output_json = (SELECT 
							 ( select count(*) from @Output_res ) as [COUNT_sys_acl_resource] 	
							,( select * from @CNT_metaName FOR JSON PATH) as [COUNT_by meta names]
							,( select * from @Output_res FOR JSON PATH ) as [sys_acl_resource]
						    ,( select * from @Output_del FOR JSON PATH ) as [sys_acl_resource_duplicate]
						  FOR JSON PATH, WITHOUT_ARRAY_WRAPPER )
	IF @SP_MODE=N'TEST1' select @ProcedureName+N'('+@Status+N')' as  [procedure], N'Final @Output_json' as tbl, @Output_json
	SELECT @Return as [Return], @ErrMessage as [Error_json], @Output_json as [Output_json]
	   	
RETURN @Return
END

 