 SET NAMES utf8;

DELIMITER $$

/* ************************************************************************************************************************************************************************
	Konfiguracja
************************************************************************************************************************************************************************ */	

DROP PROCEDURE IF EXISTS `_user_accounts_sys_cfg`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_user_accounts_sys_cfg`(
	IN _MODE VARCHAR(150),
	IN _IDN INT,
	IN _OsobaGUID VARCHAR(38),
	IN _Value VARCHAR(200),
	IN _PARAM_A VARCHAR(250),
	IN _PARAM_B VARCHAR(250),
	IN _PARAM_C VARCHAR(250),
	IN _PARAM_D VARCHAR(250),
	IN _PARAM_E MEDIUMTEXT -- VARCHAR(200)

)
/*
	CALL _user_accounts_sys_cfg('XXXXX', _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
	CALL _user_accounts_sys_cfg('SELECT', 0, '', '', '', '', '', '', ''); --	
	CALL _user_accounts_sys_cfg('CSrchHRSQL', 0, 'osoba', 'szukany login', '', '', '', '', ''); --	
	CALL _user_accounts_sys_cfg('CMakeExistingNotUserAsUserSQL', 0, 'osoba', 'szukany login', '', '', '', '', ''); --	
	CALL _user_accounts_sys_cfg('CMakeExistingNotUserAsUserSQL', 0, 'osoba', 'szukany login', '', '', '', '', ''); --	
	
	CALL _user_accounts_sys_cfg('Change.Disable', 0, 'osoba', '0', '', '', '', '', ''); --	dezaktywuj uzytkownika
	CALL _user_accounts_sys_cfg('Change.Disable', 0, 'osoba', '1', '', '', '', '', ''); --	aktywuj uzytkownika
	
	CALL _user_accounts_sys_cfg('Change.pswd', 0, _OsobaGUID, 'haslo', '', '', '', '', ''); --	zmiana hasla
	CALL _user_accounts_sys_cfg('Change.pswd.check', 0, _OsobaGUID, 'haslo', 'starehaslo', '', '', '', ''); --	zmiana hasla ale ze sprawdzeniem starego UWAGA zwraca pole IsOK (1 - ok, 0 niezgadza sie stare haslo
	
	CALL _user_accounts_sys_cfg('Change.deleted', 0, _OsobaGUID, '1', '', '', '', '', ''); --	usun
	CALL _user_accounts_sys_cfg('Change.deleted', 0, _OsobaGUID, '0', '', '', '', '', ''); --	przywroc
	
	CALL _user_accounts_sys_cfg('Change.block', 0, _OsobaGUID, '1', '', '', '', '', ''); --	zablokuj
	CALL _user_accounts_sys_cfg('Change.block', 0, _OsobaGUID, '0', '', '', '', '', ''); --	odblokuj
	CALL _user_accounts_sys_cfg('Change.block', 0, _OsobaGUID, '0', '', '', '', '', ''); --	odblokuj_OsobaGUID

*/
S_user_accounts_sys_cfg: BEGIN

	DECLARE _GrupaGUID VARCHAR(38);
	
	SET @.accounts.3.0 = TRUE;	--	Jeśli tak to wytnij w końcu kod poza IF @.accounts.3.0 = 1 !!!
	SET @.accounts.create.exists = FALSE;

CALL _sys_app_logtxt('LOG.Session.Add', @SYSTEM.Client.Session.GUID, 'CMD', '', '', 'PHP', '', '', _MODE);				
	
	IF _MODE IN ('SetUp.New', 'SetUp.Reset') THEN
	--	Dolacz do przedrostka czyli: "confirm.passwd.SetUp.New" lub "confirm.passwd.SetUp.Reset"
		SET _MODE = CONCAT('confirm.passwd.', _MODE);
	END IF;
	
	IF @session.LOGON.user_accounts_Mode IS NULL THEN
		CALL _Globals_Get('LOGON.user_accounts_Mode', @session.LOGON.user_accounts_Mode, 0);
	END IF;
		
	IF _MODE = 'user_accounts_Mode' THEN
		SELECT @session.LOGON.user_accounts_Mode AS user_accounts_Mode;
	END IF;

	IF _MODE = 'user_accounts_Mode' THEN
		IF @session.LOGON.user_accounts_Mode THEN
			SELECT * FROM v_intnet_users WHERE IDN_account > 0;
		ELSE
		-- po staremu
			SELECT * FROM v_intnet_users;
		END IF;
	END IF;
	
	IF _MODE = 'SELECT' THEN
CALL _sys_app_logtxt('LOG.Session.Add', @SYSTEM.Client.Session.GUID, 'CMD', '', '', 'PHP', '', '', _MODE);				
		IF @session.LOGON.user_accounts_Mode THEN
			-- było SELECT * FROM `v_intnet_users` WHERE IDN_account > 0;
			IF IFNULL(_PARAM_A, '') = '' THEN
			--	zwyczajny select wszystkich userow
			--	dodaj tu `_sys_app_reg`
				SELECT 
					u.*, 
					CONCAT_WS(' ',
						u.Konto_Status_str,
						IF(u.User_type = 2, _VarStr('(typu gość)'), IF(u.User_type = 1, NULL, NULL))
					) AS Account_Inf,
					CONCAT_WS(', ',
						CONCAT('Grup: ', _VarStr(u.cc)),
						CONCAT(
							'Upraw.: ', 
							IFNULL((SELECT COUNT(*) FROM `uprawnienia` up WHERE up.osobaguid = u.GUID), 0)
						)
					) AS InclusInf,
					(
					SELECT
						IF(COUNT(*) = 0,
							'Nie aktywna',
							CONCAT_WS(', ',
								CONCAT('Logowań: ', COUNT(*)),
								CONCAT('aplikacji: ', COUNT(DISTINCT sdl.log_APP_ID)),
								CONCAT('ost.logow.: ', _Format_DT(MAX(sdl.Ping_AT), '%DZ%DW %dd %d %mmm %YH o %H:%N:%S'))
							)
						) AS Usage_last_1_month
						
					-- ,sdl.log_APP_ID,
					-- sdl.*,
					-- MIN(sdl.Ping_AT) AS Od, 
					-- MAX(sdl.Ping_AT) AS DO, 
					-- COUNT(*) AS CC,
					-- COUNT(DISTINCT sdl.Log_USER_GUID) AS CU
					FROM `_sys_db_logons` sdl
					WHERE
						-- sdl.log_APP_ID = 'M.MOB.Mobile.Seller'
						sdl.log_USER_GUID = u.GUID
						AND NOT (sdl.Status IN ('NEW', 'LOG.ERR'))
						AND sdl.CONNECT_AT > NOW() - INTERVAL 1 MONTH
					ORDER BY sdl.CONNECT_AT DESC 
					) AS Usage_last_1_month,
					'OK' AS Valid_STATUS,
					IFNULL((SELECT COUNT(*) FROM `uprawnienia` up WHERE up.osobaguid = u.GUID), 0) AS CC_SelfUpr
				FROM `v_user_accounts` u
				-- FROM `v_intnet_users` u 
				WHERE 
					u.IDN_account > 0
				ORDER BY u.idnuser
				;
			ELSE
			--	select userow nalezacych do grupy _Param
				SELECT 
					u.*,
					Get_Status_For_Valid_From_To('', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') AS Valid_STATUS,
					IFNULL((SELECT COUNT(*) FROM `uprawnienia` up WHERE up.osobaguid = u.GUID), 0) AS CC_SelfUpr
				FROM `v_user_accounts` u, `grupy_osob` go 
				-- FROM `v_intnet_users` u, `grupy_osob` go 
				WHERE 
					u.IDN_account > 0
					AND go.OsobaGUID = u.GUID
					AND go.GrupaGUID = _PARAM_A
					-- AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				GROUP BY u.GUID
				ORDER BY u.idnuser
				;
			END IF;
		ELSE
		-- po staremu
			SELECT * FROM `v_intnet_users`;
		END IF;
	END IF;

	IF _MODE = 'CSrchHRSQL' THEN
		IF @session.LOGON.user_accounts_Mode THEN
			SELECT 
				_VarInt(COUNT(*)) AS C 
			FROM `_user_accounts` 
			WHERE 
				login = _Value
				AND 
				typ = 'SYS'
				AND
				OsobaGUID != _OsobaGUID
			;	
		ELSE
		-- po staremu
			SELECT 
				_VarInt(COUNT(*)) AS C 
			FROM `osoby` 
			WHERE 
				idnuser = _Value
				AND
				GUID != _OsobaGUID
			;	
		END IF;
	END IF;
	
	IF _MODE = 'CMakeExistingNotUserAsUserSQL' THEN
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` SET user_type = 1, login = _Value WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS';
		ELSE
		-- po staremu
			UPDATE `osoby` SET user_type = 1, idnuser = _Value WHERE GUID = _OsobaGUID;
		END IF;
	END IF;
	
	IF _MODE = 'Change.Disable' THEN
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` SET user_type = _Value WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS';
		ELSE
		-- po staremu
			UPDATE `osoby` SET user_type = _Value WHERE GUID = _OsobaGUID;
		END IF;
	END IF;
	
	IF _MODE = 'Toggle.Admin' THEN
		IF NOT @session.LOGON.user_accounts_Mode THEN  -- robimy update by zachowac zgodnosc danych
			UPDATE `_user_accounts` u, `osoby` o 
			SET u.admin = o.administrator, u.user_type = o.user_type 
		    WHERE u.OsobaGUID = _OsobaGUID 
			AND u.OsobaGUID = o.GUID
			AND u.typ = 'SYS';		
		END IF;
	END IF;

	IF _MODE = 'Change.admin' THEN
	/* *************************************************************************************************************************************************************
		Zmiana loginu
		CALL _user_accounts_sys_cfg('Change.admin', 0, osoba, '0 lub 1', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		0/1
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` u, `osoby` o 
			SET 
				u.admin = (_Value = 1),
				o.administrator = (_Value = 1)
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
				AND u.OsobaGUID = o.GUID
			;		
			UPDATE `_user_accounts` u
			SET 
				u.user_type = IF(_Value IN (0, 1), 1, 2)
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
			;		
		END IF;
	END IF;
	
	IF _MODE = 'Change.User_account_Type' THEN
	/* *************************************************************************************************************************************************************
		Zmiana loginu
		CALL _user_accounts_sys_cfg('Change.User_account_Type', 0, osoba, '0 lub 1 lub 2', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		0/1/2
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` u
			SET 
				u.admin = (_Value = 1)
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
			;		
			UPDATE `osoby` o, `_user_accounts` u 
			SET 
				o.administrator = (_Value = 1)
		    WHERE 
				o.GUID = _OsobaGUID 
				AND u.OsobaGUID = o.GUID
				AND u.typ = 'SYS'
			;		
			UPDATE `_user_accounts` u
			SET 
				u.user_type = IF(_Value IN (0, 1), 1, 2)
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
			;		
		END IF;
	END IF;
	
	IF _MODE = 'Change.Ad_Mail' THEN
	/* *************************************************************************************************************************************************************
		Zmiana adresu mailowego konta...
		CALL _user_accounts_sys_cfg('Change.Ad_Mail', 0, osoba, 'abc.123@ymail.pl', '' lub '1', 'Modul', '', '', '');
		... wersja z poleceniem wyslij mail z linkiem aktywacyjnym
		CALL _user_accounts_sys_cfg('Change.Ad_Mail', 0, osoba, 'abc.123@ymail.pl', '', 'Modul', '1', '', '');
		_OsobaGUID	osoba
		_Value		adres Email
		_PARAM_A	Debug np.
		_PARAM_B	link do strony systemu np. Porta fide lub KEY do Rega do linka strony !!!!
		_PARAM_C	Czy wyslac aktywacje konta mailem na adres _Value ? Wysylamy gdy _PARAM_C <> ''

	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` u
			SET 
				u.Ad_Mail = _Value
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
			;		
			IF FALSE AND _PARAM_C = '1' THEN	-- dodałem ten false bo to było tu bez sensu
				CALL _user_accounts_sys_cfg('accounts.sent.aktywacja', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, '', '', '');
			END IF;
			
			INSERT IGNORE INTO kontakty (guid,osobaguid,typ_medium,adres,opis) 
				SELECT osobaguid, osobaguid, 3, ad_mail, 'e-mail' from _user_accounts where ad_mail<>'' and osobaguid=_OsobaGUID;	
					
			UPDATE kontakty SET adres = _Value WHERE guid=_OsobaGUID AND osobaguid=_OsobaGUID AND typ_medium=3;
		END IF;
	END IF;

	IF _MODE = 'Change.KD_Mail' THEN
	/* *************************************************************************************************************************************************************
		Zmiana prywatnego adresu mailowego konta...
		CALL _user_accounts_sys_cfg('Change.KD_Mail', 0, osoba, 'abc.123@ymail.pl', '' lub '1', 'Modul', '', '', '');
		_OsobaGUID	osoba
		_Value		adres Email
		_PARAM_A	Debug np.
		_PARAM_B	
		_PARAM_C	

	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` u
			SET 
				u.KD_Mail = _Value
		    WHERE 
				u.OsobaGUID = _OsobaGUID 
				AND u.typ = 'SYS'
			;		
			
--			INSERT IGNORE INTO kontakty (guid,osobaguid,typ_medium,adres,opis) 
--				SELECT osobaguid, osobaguid, 3, ad_mail, 'e-mail' from _user_accounts where ad_mail<>'' and osobaguid=_OsobaGUID;	
					
--			UPDATE kontakty SET adres = _Value WHERE guid=_OsobaGUID AND osobaguid=_OsobaGUID AND typ_medium=3;
		END IF;
	END IF;

	IF _MODE = 'Change.login' THEN
	/* *************************************************************************************************************************************************************
		Zmiana loginu
		CALL _user_accounts_sys_cfg('Change.login', 0, osoba, 'nowy login', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		nowy login
		UWAGA 
		zwraca kolumne isOK - 0 gdy istnieje taki login oraz osobe takiego konta
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			SELECT 
				_VarInt(COUNT(*)) AS C,
				GROUP_CONCAT(CONCAT('< ',o.Nazwisko, ' ', o.Imiona, ' >') SEPARATOR ', ') AS Osoby
			INTO @C, @Osoby
			FROM `_user_accounts` a
			INNER JOIN `osoby` o ON o.GUID = a.OsobaGUID
			WHERE 
				login = _Value
				AND 
				typ = 'SYS'
				AND
				OsobaGUID != _OsobaGUID
			;	
			IF @C = 0 THEN
				UPDATE `_user_accounts` SET login = _Value WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS';
			END IF;
			SELECT (@C = 0) AS isOK, _VarStr(CONCAT('Podany login istnieje w kontach: \n', @Osoby, '')) AS Osoby;
		END IF;
	END IF;
	
	IF _MODE = 'Change.pswd' THEN
	/* *************************************************************************************************************************************************************
		Zmiana hasła 
		CALL _user_accounts_sys_cfg('Change.pswd', 0, osoba, 'nowe hasło', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		nowe hasło
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` SET datas = _Value, err_logon_count = 0 WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS';
			-- aktualizacja hasla w tabeli osob (dla aplikacji dzialajacych w oparciu o ta tabele WebDOC, webCRM) 
			UPDATE `osoby` SET datas = _Value, err_logon_count = 0 WHERE GUID = _OsobaGUID AND deleted = 0 AND rodzaj = 1;
		ELSE
		-- po staremu
			
			UPDATE `osoby` SET datas = _Value, err_logon_count = 0 WHERE GUID = _OsobaGUID AND deleted = 0 AND rodzaj = 1; -- #036642 wylaczamy ten warunek (zezwalamy na zmianę hasła dla wszystkich trzech rodzajów uzytkownikow) AND user_type = 1;
		-- a dajmy jeszcze poprawke hasla w `_user_accounts`
			CALL _user_accounts_create_from_osoba('', _OsobaGUID, 0, '', '', 0, 0, '', ''); 
			UPDATE `_user_accounts` SET datas = _Value, err_logon_count = 0 WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS';
		END IF;
	END IF;
	
	IF _MODE = 'Change.pswd.check' THEN
	/* *************************************************************************************************************************************************************
		Zmiana hasła ale podając nowe i stare
		CALL _user_accounts_sys_cfg('Change.pswd.check', 0, osoba, 'nowe hasło', 'stare hasło', '', '', '', '');
		_OsobaGUID	osoba
		_Value		nowe hasło
		_PARAM_A	stare hasło
		UWAGA 
		zwraca kolumne isOK
	**************************************************************************************************************************************************************/
		IF @.accounts.3.0 THEN
			CALL _user_accounts_sys_cfg('accounts.3.0.confirm.passwd.SetUp.Change', _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
			SELECT 
				tui2.Oper_Status LIKE 'OK%' AS isOK,
				tui2.Oper_Status_Msg AS Msg
				-- ,tui2.* 
			FROM `t_ua_inf` tui2
			;
			-- SELECT @_IS_OK AS isOK, IF(@_IS_OK, 'Hasło zostało zmienione!', @_MSG) AS Msg; 

			LEAVE S_user_accounts_sys_cfg;
		END IF;

/*		DALEJ WON!!!!!!!!!!!!!!!!!!	*/		
		
		
		
		
		SET @_MSG = '';
		IF @session.LOGON.user_accounts_Mode THEN
	--	Nowe logowanie
		--	1. Warunek - stare <> nowe
			SET @_IS_OK = (_PARAM_A != _Value); 
			IF NOT @_IS_OK THEN
				SET @_MSG = 'Nowe hasło musi się różnić od aktualnego!';
			ELSE
			--	2. Warunek - stare w bazie <> nowe
				SET @_IS_OK = NOT EXISTS(SELECT a.idn FROM `_user_accounts` a WHERE a.OsobaGUID = _OsobaGUID AND a.typ = 'SYS' AND a.datas = _Value);
				IF NOT @_IS_OK THEN
					SET @_MSG = 'Nowe hasło musi się różnić od aktualnego!';
				ELSE
				--	3. Warunek - Nie ma w archiwum
					SET @_IS_OK = NOT EXISTS(SELECT a.idn FROM `_user_accounts_pswd_arch` a WHERE a.OsobaGUID = _OsobaGUID AND a.typ = 'SYS' AND a.datas = _Value);
					IF NOT @_IS_OK THEN
						SET @_MSG = 'Takie hasło już było wcześniej w użyciu!';
					ELSE
						UPDATE `_user_accounts` SET datas = _Value, err_logon_count = 0 WHERE OsobaGUID = _OsobaGUID AND typ = 'SYS' AND datas = _PARAM_A;
						SET @_IS_OK = _VarInt(ROW_COUNT() != 0);
						IF NOT @_IS_OK THEN
							SET @_MSG = 'Niewłaściwe hasło!';
						END IF;
					END IF;
				END IF;
			END IF;
		ELSE
	-- po staremu
			UPDATE `osoby` SET datas = _Value, err_logon_count = 0 WHERE GUID = _OsobaGUID AND deleted = 0 AND rodzaj = 1 AND user_type = 1 AND datas = _PARAM_A;
			SET @_IS_OK = _VarInt(ROW_COUNT() != 0);
		END IF;
		SELECT @_IS_OK AS isOK, IF(@_IS_OK, 'Hasło zostało zmienione!', @_MSG) AS Msg; 
	END IF;

	IF _MODE = 'Change.deleted' THEN
	/* *************************************************************************************************************************************************************
		Usuwanie - PATRZ Change.status
		CALL _user_accounts_sys_cfg('Change.deleted', 0, osoba, '0 lub 1', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		Usun = 1 , przywróć z ksza 0
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` a 
			SET 
				a.Status = IF(_Value != 0, 2, 0) 
			WHERE 
				OsobaGUID = _OsobaGUID 
				AND typ = 'SYS' 
			;	
		END IF;
	END IF;

	IF _MODE = 'Change.block' THEN
	/* *************************************************************************************************************************************************************
		Zmiana statusu - PATRZ Change.status
		CALL _user_accounts_sys_cfg('Change.block', 0, osoba, '0 lub 1', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		Status 0/1
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` a 
			SET 
				a.Status = IF(_Value != 0, 1, 0) 
			WHERE 
				OsobaGUID = _OsobaGUID 
				AND typ = 'SYS' 
			;	
		END IF;
	END IF;

	IF _MODE = 'Change.status' THEN
	/* *************************************************************************************************************************************************************
		Usuwanie i block razem 
		CALL _user_accounts_sys_cfg('Change.status', 0, osoba, '0 lub 1 lub 2', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		czyli
			0 - konto aktywne
			1 - konto zablokowane
			2 - usunięte		
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			UPDATE `_user_accounts` a 
			SET 
				a.Status = _Value
			WHERE 
				OsobaGUID = _OsobaGUID 
				AND typ = 'SYS' 
			;	
		END IF;
	END IF;

	IF _MODE = 'Change.Other' THEN
	/* *************************************************************************************************************************************************************
		Usuwanie i block razem 
		CALL _user_accounts_sys_cfg('Change.Other', 0, osobaGUID, '', '', '', '', '', PARAMS);
		_OsobaGUID	osoba
		PARAMS
			ugrpGuid=xxx&inne
			1 - konto zablokowane
			2 - usunięte		
	**************************************************************************************************************************************************************/
		IF @session.LOGON.user_accounts_Mode THEN
			SET
				@.IN.ugrpGuid = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'ugrpGuid', ''), ''),
				@.IN.paramXXX = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'paramXXX', ''), '')
			;
		--	zmiany w `osoby`	
			UPDATE `osoby` o
			SET 
				o.ugrpGuid = @.IN.ugrpGuid
			WHERE 
				o.GUID = _OsobaGUID 
			;	
		--	zmiany w `_user_accounts`	
			UPDATE `_user_accounts` ua 
			SET 
				ua.Status = 'bleble' 	-- fake bo na razie nie mamy czego zmieniac
			WHERE 
				ua.OsobaGUID = _OsobaGUID 
				AND FALSE  -- fake bo na razie nie mamy czego zmieniac
			;	
		END IF;
	END IF;

	IF _MODE = 'Change.Stanowisko' THEN
	/* *************************************************************************************************************************************************************
		Zmiana pola Stanowisko w `osoby`
		CALL _user_accounts_sys_cfg('Change.Stanowisko', 0, osoba, 'stanow.', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		Stanowisko
	**************************************************************************************************************************************************************/
		UPDATE `osoby` o
		SET 
			o.Stanowisko = IFNULL(_Value, o.Stanowisko) 
		WHERE 
			o.GUID = _OsobaGUID 
			AND o.Rodzaj = 1
		;	
	END IF;

	IF _MODE = 'Change.nazwa_dzialu' THEN
	/* *************************************************************************************************************************************************************
		Zmiana pola nazwa_dzialu w `osoby`
		CALL _user_accounts_sys_cfg('Change.nazwa_dzialu', 0, osoba, 'nazwa dzialu', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value		nazwa_dzialu
	**************************************************************************************************************************************************************/
		UPDATE `osoby` o
		SET 
			o.nazwa_dzialu = IFNULL(_Value, o.nazwa_dzialu) 
		WHERE 
			o.GUID = _OsobaGUID 
			AND o.Rodzaj = 1
		;	
	END IF;

	IF _MODE = 'SELECT.groups.for.this.user' THEN
	/* *************************************************************************************************************************************************************
		Grupy danego uzytkownika
		CALL _user_accounts_sys_cfg('SELECT.groups.for.this.user', 0, osoba, '0', '', '', '', '', '');
		_OsobaGUID	osoba
	**************************************************************************************************************************************************************/
	/* bylo	
		SELECT 
			g.* 
		FROM `v_grupy_hr` g
		WHERE 
			TRUE
			AND EXISTS(SELECT * FROM `grupy_osob` g WHERE g.GrupaGUID = g.GUID AND g.OsobaGUID = _OsobaGUID)
		;	
	*/
	--	pokaz grupu osoby
		SELECT 
			g.*,
			Get_Status_For_Valid_From_To('', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') AS Valid_STATUS,
			go.Valid_From, go.Valid_To, go.Deleted,
			go.param1,
			go.param2,
			go.param3,
			go.param4,
			go.param5
		FROM `grupy_osob` go, `v_grupy_hr` g
		WHERE 
			TRUE
			AND go.OsobaGUID = _OsobaGUID
			-- AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			AND g.GUID = go.GrupaGUID 
		;	
	
	END IF;

	IF _MODE = 'SELECT.groups.for.add.to.this.user' THEN
	/* *************************************************************************************************************************************************************
		Grupy do ktorych mozna dodac danego uzytkownika
		CALL _user_accounts_sys_cfg('SELECT.groups.for.add.to.this.user', 0, osoba, '0', '', '', '', '', '');
		_OsobaGUID	osoba
	**************************************************************************************************************************************************************/
		SELECT 
			g.* 
		FROM `v_grupy_hr` g
		WHERE 
			TRUE
			AND !EXISTS(SELECT * FROM `grupy_osob` go WHERE go.GrupaGUID = g.GUID AND go.GrupaGUID != 'ALL' AND go.OsobaGUID = _OsobaGUID)
			AND g.GUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND g.GUID <> _OsobaGUID			--	i bez grupy własnej
		;
	END IF;

	IF _MODE = 'SELECT.APPS.for.add.to.this.user' THEN
	/* *************************************************************************************************************************************************************
		Grupy do ktorych mozna dodac danego uzytkownika
		CALL _user_accounts_sys_cfg('SELECT.APPS.for.add.to.this.user', 0, osoba, '0', '', '', '', '', '');
		_OsobaGUID	osoba
	**************************************************************************************************************************************************************/
		SELECT 
			g.* 
		FROM `v_grupy_app` g
		WHERE 
			TRUE
			AND !EXISTS(SELECT * FROM `grupy_osob` go WHERE go.GrupaGUID = g.GUID AND go.GrupaGUID != 'ALL' AND go.OsobaGUID = _OsobaGUID)
			AND g.GUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND g.GUID <> _OsobaGUID			--	i bez grupy własnej
		;
	END IF;

	
	
	IF _MODE = 'SELECT.users.for.this.group' THEN
	/* *************************************************************************************************************************************************************
		Osoby z danej grupy
		CALL _user_accounts_sys_cfg('SELECT.users.for.this.group', 0, Grupa, '0', '', '', '', '', '');
		_OsobaGUID	grupa
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
	/* bylo	
		SELECT 
			_VarInt(IFNULL(A.`user_type`, O.`user_type`)) AS `User_Type`,
			_VarInt(IFNULL(A.`Admin`, O.`administrator`)) AS `Administrator`,
			_VarDouble(
			(
				SELECT COUNT(0)
				FROM `grupy_osob` `g`
				WHERE `g`.`grupaGUID` != `g`.`osobaGUID` AND `g`.`osobaGUID` = O.`GUID`
			)) AS `CC`,
			O.`GUID` AS `GUID`,
			K.`symbol` AS `symbol`,
			O.`pracownik` AS `pracownik`,
			_VarStr(IF(IFNULL(dg.Value, 0), IFNULL(A.`Login`, O.`idnuser`), O.`idnuser`)) AS `idnuser`,
			_VarInt(IF(IFNULL(dg.Value, 0), IFNULL(A.`Status`, O.`user_inactive`), O.`user_inactive` )) AS `user_inactive`,
			O.`niewidoczna_w_HR` AS `niewidoczna_w_HR`,
			O.`rodzaj` AS `rodzaj`,
			O.`Nazwisko` AS `nazwisko`,
			O.`Imiona` AS `imiona`,
			O.`stanowisko` AS `stanowisko`,
			IFNULL(D.`opis`, '') AS `dzial`,
			O.`nazwa_dzialu` AS `nazwa_dzialu`,
			IF(O.pracownik, 'pracow.', IFNULL(K.Nazwa, '-')) AS PracownikKontrahent,
			O.`plec` AS `plec`,
			O.`AZAM_KodPocztowy` AS `AZAM_kodpocztowy`,
			CONCAT(O.`Nazwisko`, ' ', O.`Imiona`) AS `NazwiskoImie`,
			SUBSTR(CONCAT(O.`AZAM_Ulica`, ' ', O.`AZAM_KodPocztowy`, ' ', O.`AZAM_Miejscowosc`), 1, 70) AS `Adres`,
			O.`AZAM_Adres` AS `AZAM_Adres`,
			O.`AZAM_Miejscowosc` AS `AZAM_miejscowosc`,
			O.`AZAM_Ulica` AS `AZAM_ulica`,
			O.`nieaktywny` AS `nieaktywny`,
			O.`korespondencja` AS `korespondencja`,
			O.`priorytet` AS `priorytet`,
			O.`kontrGUID` AS `kontrGUID`, 
			_VarInt(IFNULL(A.`IDN`, -1)) AS `IDN_account`
		FROM `osoby` O 
		LEFT JOIN `_db_globals` dg ON dg.Key = 'LOGON.user_accounts_Mode'
		LEFT JOIN `kontrah` K ON O.`kontrGUID` = K.`GUID`
		LEFT JOIN `dzialy` D ON O.`dzial` = D.`idn`
		LEFT JOIN `_user_accounts` A ON A.`OsobaGUID` = O.`GUID` AND A.`typ` = 'SYS'
		WHERE 
			TRUE
			AND O.`deleted` = 0 
			AND O.`rodzaj` = 1
			AND EXISTS(SELECT * FROM `grupy_osob` g WHERE g.GrupaGUID = _GrupaGUID AND g.OsobaGUID = O.GUID)
		;		
	*/	
	--	pokaz osoby w grupe
		SELECT 
			u.*,
			Get_Status_For_Valid_From_To('', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') AS Valid_STATUS,
			go.Valid_From, go.Valid_To, go.Deleted,
			go.param1,
			go.param2,
			go.param3,
			go.param4,
			go.param5
		FROM `grupy_osob` go, `v_intnet_users` u
		WHERE 
			TRUE
			AND go.GrupaGUID = _GrupaGUID
			AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			AND u.GUID = go.OsobaGUID 
		;		
	END IF;

	IF _MODE = 'SELECT.users.for.add.to.this.group' THEN
	/* *************************************************************************************************************************************************************
		Osoby ktore mozna dodac do danej grupy
		CALL _user_accounts_sys_cfg('XXXXX', _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
		CALL _user_accounts_sys_cfg('SELECT.users.for.add.to.this.group', 0, Grupa, '0', '', '', '', '', ''); -- wszystkie osoby
		CALL _user_accounts_sys_cfg('SELECT.users.for.add.to.this.group', 0, Grupa, '0', 'users', '', '', '', ''); -- tylko aktywni userzy

		_OsobaGUID	grupa
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
		SELECT 
			_VarInt(IFNULL(A.`user_type`, O.`user_type`)) AS `User_Type`,
			_VarInt(IFNULL(A.`Admin`, O.`administrator`)) AS `Administrator`,
			_VarDouble(
			(
				SELECT COUNT(0)
				FROM `grupy_osob` `g`
				WHERE `g`.`grupaGUID` != `g`.`osobaGUID` AND `g`.`osobaGUID` = O.`GUID`
			)) AS `CC`,
			O.`GUID` AS `GUID`,
			K.`symbol` AS `symbol`,
			O.`pracownik` AS `pracownik`,
			_VarStr(IF(IFNULL(dg.Value, 0), IFNULL(A.`Login`, O.`idnuser`), O.`idnuser`)) AS `idnuser`,
			_VarInt(IF(IFNULL(dg.Value, 0), IFNULL(A.`Status`, O.`user_inactive`), O.`user_inactive` )) AS `user_inactive`,
			O.`niewidoczna_w_HR` AS `niewidoczna_w_HR`,
			O.`rodzaj` AS `rodzaj`,
			O.`Nazwisko` AS `nazwisko`,
			O.`Imiona` AS `imiona`,
			O.`stanowisko` AS `stanowisko`,
			-- IFNULL(D.`opis`, '') AS `dzial`,
			IFNULL(NULLIF(`D`.`opis`, ''), `O`.`nazwa_dzialu`) AS `dzial`,
			O.`nazwa_dzialu` AS `nazwa_dzialu`,
			IF(O.pracownik, 'pracow.', IFNULL(K.Nazwa, '-')) AS PracownikKontrahent,
			O.`plec` AS `plec`,
			O.`AZAM_KodPocztowy` AS `AZAM_kodpocztowy`,
			CONCAT(O.`Nazwisko`, ' ', O.`Imiona`) AS `NazwiskoImie`,
			SUBSTR(CONCAT(O.`AZAM_Ulica`, ' ', O.`AZAM_KodPocztowy`, ' ', O.`AZAM_Miejscowosc`), 1, 70) AS `Adres`,
			O.`AZAM_Adres` AS `AZAM_Adres`,
			O.`AZAM_Miejscowosc` AS `AZAM_miejscowosc`,
			O.`AZAM_Ulica` AS `AZAM_ulica`,
			O.`nieaktywny` AS `nieaktywny`,
			O.`korespondencja` AS `korespondencja`,
			O.`priorytet` AS `priorytet`,
			O.`kontrGUID` AS `kontrGUID`, 
			_VarInt(IFNULL(A.`IDN`, -1)) AS `IDN_account`
		FROM `osoby` O 
		LEFT JOIN `_db_globals` dg ON dg.Key = 'LOGON.user_accounts_Mode'
		LEFT JOIN `kontrah` K ON O.`kontrGUID` = K.`GUID`
		LEFT JOIN `dzialy` D ON O.`dzial` = D.`idn`
		LEFT JOIN `_user_accounts` A ON A.`OsobaGUID` = O.`GUID` AND A.`typ` = 'SYS'
		WHERE 
			TRUE
			AND O.`deleted` = 0 
			AND O.`rodzaj` = 1
			AND ! EXISTS(SELECT * FROM `grupy_osob` g WHERE g.GrupaGUID = _GrupaGUID AND g.OsobaGUID = O.GUID)
			AND O.GUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND O.GUID <> _GrupaGUID			--	i bez grupy własnej
			AND (_Param_A = '' OR (_Param_A='users' AND A.status=0))
		;		
	END IF;


	IF _MODE = 'SELECT.users.for.this.APPS' THEN
	/* *************************************************************************************************************************************************************
		Osoby z danej grupy
		CALL _user_accounts_sys_cfg('SELECT.users.for.this.APPS', 0, Grupa, '0', '', '', '', '', '');
		_OsobaGUID	grupa
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
	--	pokaz osoby w grupe
		/* było
		SELECT 
			u.*,
			Get_Status_For_Valid_From_To('', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') AS Valid_STATUS,
			go.Valid_From, go.Valid_To, go.Deleted,
			go.param1,
			go.param2,
			go.param3,
			go.param4,
			go.param5
		FROM `grupy_osob` go, `v_user_accounts` u
		WHERE 
			TRUE
			AND go.GrupaGUID = _GrupaGUID
			AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			AND u.GUID = go.OsobaGUID 
		;		
		*/
		SELECT 
			(@.IsGrupa := (g.NazwaGrupy IS NOT NULL)) AS IsGrupa,
			IF(NOT @.IsGrupa, u.NazwiskoImie, CONCAT('Grupa ', g.NazwaGrupy)) AS FullName,
			IF(NOT @.IsGrupa,
				(CONCAT_WS(', ', 
					-- IFNULL(u.PracInfo, 'użytkownik'),
					u.PracInfo,
					u.Konto_Status_Str
				)),
				_VarStr(IF(g.Group_Cardinality > 0, CONCAT_WS('', 'Użytk.: ', g.Group_Cardinality), '(pusta)'))
			) AS Info1,
			u.Dost_do_App AS Info2,
			go.OsobaGUID,
			u.*,
			Get_Status_For_Valid_From_To('', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') AS Valid_STATUS,
			go.Valid_From, go.Valid_To, go.Deleted,
			go.param1,
			go.param2,
			go.param3,
			go.param4,
			go.param5
		FROM `grupy_osob` go
		LEFT JOIN `v_user_accounts` u ON u.GUID = go.OsobaGUID 
		LEFT JOIN `v_grupy_hr` g ON g.GUID = go.OsobaGUID
		WHERE 
			TRUE
			AND go.GrupaGUID = _GrupaGUID
			AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
			AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
		;		
		
		
	END IF;

	IF _MODE = 'SELECT.users.for.add.to.this.APPS' THEN
	/* *************************************************************************************************************************************************************
		Osoby ktore mozna dodac do danej grupy
		CALL _user_accounts_sys_cfg('SELECT.users.for.add.to.this.APPS', 0, Grupa, '0', '', '', '', '', '');
		_OsobaGUID	grupa
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
		SELECT
			u.NazwiskoImie AS FullName,
			CONCAT_WS(', ', 
				-- IFNULL(u.PracInfo, 'użytkownik'),
				u.PracInfo,
				u.Konto_Status_Str
			) AS Info1,
			u.Dost_do_App AS Info2,
			u.*
		FROM `v_user_accounts` u
		WHERE
			NOT EXISTS(SELECT * FROM `grupy_osob` go WHERE go.GrupaGUID = _GrupaGUID AND go.OsobaGUID = u.GUID)
		;
	END IF;
	
	IF _MODE = 'SELECT.grps.for.add.to.this.APPS' THEN
	/* *************************************************************************************************************************************************************
		Osoby ktore mozna dodac do danej grupy
		CALL _user_accounts_sys_cfg('SELECT.grps.for.add.to.this.APPS', 0, Grupa, '0', '', '', '', '', '');
		_OsobaGUID	grupa
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
		SELECT
			g.NazwaGrupy AS FullName,
			IF(g.Group_Cardinality > 0, CONCAT_WS('', 'Użytk.: ', g.Group_Cardinality), '(pusta)') AS Info1,
			NULL AS Info2,
			-- NULL AS Info3,
			g.*
		FROM `v_grupy_hr` g -- `v_user_accounts` u
		WHERE
			NOT EXISTS(SELECT * FROM `grupy_osob` go WHERE go.GrupaGUID = _GrupaGUID AND go.OsobaGUID = g.GUID)
		;
	END IF;
	
	IF _MODE = 'Grupy.Insert/Edit' THEN
	/* *************************************************************************************************************************************************************
		Osoby z danej grupy
		CALL _user_accounts_sys_cfg('Grupy.Insert/Edit', 0, GuidGrupy, 'Grupa nowa', 'group_type', 'Opis grupy', 'Idnuser', 'tytul (kod)', 'nieaktywny');
		IN _OsobaGUID VARCHAR(38) 	Grupa
		IN _Value 		Nazwa grupy
		IN _PARAM_A 	group_type
		IN _PARAM_B 	Opis grupy (stanowisko AS OpisGrupy)
	**************************************************************************************************************************************************************/
		IF IFNULL(_OsobaGUID, '') <> '' THEN
			INSERT IGNORE INTO `osoby`
			(GUID, Rodzaj, Nazwisko, idnuser, group_type, stanowisko, User_type, tytul, nieaktywny)
			VALUES
			(_OsobaGUID, 0, _Value, IF(_PARAM_C='',_Value,_Param_C), _PARAM_A, _PARAM_B, 1, _Param_D,_VarInt(_Param_E))
			ON DUPLICATE KEY 
			UPDATE
				Nazwisko = _Value,
				group_type = _PARAM_A,
				stanowisko = _PARAM_B,
				User_type = 1,
				idnuser = IF(_PARAM_C='',idnuser,_Param_C),
				tytul = IF(_PARAM_D='',tytul,_Param_D),
				nieaktywny = IF(_PARAM_E='',0,_VarINT(_Param_E))
			;
			INSERT IGNORE INTO `grupy_osob`
			(grupaGUID, OsobaGUID)
			VALUES
			(_OsobaGUID, _OsobaGUID)
			;
		END IF;
	END IF;

	IF _MODE LIKE 'Grupy.%Delete%' THEN
	/* *************************************************************************************************************************************************************
		Osoby z danej grupy
		CALL _user_accounts_sys_cfg('Grupy.Delete.Check', 0, GuidGrupy, '', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('Grupy.Delete', 0, GuidGrupy, '', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('Grupy.UnDelete', 0, GuidGrupy, '', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('Grupy.Delete.Hard', 0, GuidGrupy, '', '', '', '', '', '');
		IN _OsobaGUID VARCHAR(38) 	Grupa
		IN _Value VARCHAR(120)		Nazwa grupy
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _OsobaGUID;
		IF _MODE IN ('Grupy.Delete', 'Grupy.UnDelete') THEN
			UPDATE `osoby` o
			SET
				o.Deleted = (_MODE = 'Grupy.Delete')
			WHERE
				o.GUID = _GrupaGUID
			;
			SET @RC := ROW_COUNT();
			SELECT
				0 AS Err,
				IF(@RC > 0,
					IF(_MODE = 'Grupy.Delete',
						'Poprawnie usunięto grupę (do kosza)!',
						'Poprawnie przyrócono grupę z kosza!'
					),
					'OK'
				) AS Msg
			;
			
		END IF;
		
		IF _MODE = 'Grupy.Delete.Check' THEN
			SELECT
				COUNT(*) AS IleOsob
			INTO @.IleOsob
			FROM `grupy_osob` go
			WHERE 
				TRUE
				AND go.GrupaGUID = _GrupaGUID
			;
			IF @.IleOsob = 0 THEN
				SELECT
					COUNT(*) AS IleOsob
				INTO @.IleOsob
				FROM `uprawnienia` u
				WHERE 
					TRUE
					AND u.osobaguid = _GrupaGUID
				;
			END IF;
			SELECT
				@.IleOsob > 0 AS Err,
				IF(@.IleOsob > 0,
					'Nie można usunąć grupy zawierającej osoby lub uprawnienia!',
					'OK'
				) AS Msg
			;
		END IF;
		
		IF _MODE = 'Grupy.Delete.Hard' THEN
			SELECT
				COUNT(*) AS IleOsob
			INTO @.IleOsob
			FROM `grupy_osob` go
			WHERE 
				TRUE
				AND go.GrupaGUID = _GrupaGUID
			;
			IF @.IleOsob = 0 THEN
				SELECT
					COUNT(*) AS IleOsob
				INTO @.IleOsob
				FROM `uprawnienia` u
				WHERE 
					TRUE
					AND u.osobaguid = _GrupaGUID
				;
			END IF;
			SET @RC := 0;
			IF @.IleOsob = 0 THEN
				DELETE o FROM `osoby` o
				WHERE
					o.GUID = _GrupaGUID
				;
				SET @RC := ROW_COUNT();
			END IF;
			
			SELECT
				@.IleOsob > 0 AS Err,
				IF(@.IleOsob > 0,
					'Nie można usunąć grupy zawierającej osoby lub uprawnienia!',
					'Poprawnie usunięto grupę!'
				) AS Msg
			;
		
		END IF;
		
	END IF;

	IF _MODE LIKE 'grupy_osob.for.USER.%' THEN
	/* *************************************************************************************************************************************************************
		NOWE
		zamiast 
		'Users.grupy_osob.xxx'
		Inicjowanie tabeli tymcz.
		CALL _user_accounts_sys_cfg('grupy_osob.for.USER.INIT', 0, '', '', '', '', '', '', '');
		
		wstawianie do tabeli tymcz.
		CALL _user_accounts_sys_cfg('grupy_osob.for.USER.ADD', 0, GuidOsoby, GuidGrupy, Valid_From, Valid_To, Deleted, '', 'param1=xxx&param2=yyy');
		IN _OsobaGUID VARCHAR(38) 	Osoba
		IN _Value VARCHAR(120)		Grupa
		_PARAM_A	Valid_From / null 
		_PARAM_B	Valid_To / null 
		_PARAM_C	Deleted (0/1)
		_PARAM_D 
		_PARAM_E 
		
		Zapis tabeli tymcz. do bazy
		CALL _user_accounts_sys_cfg('grupy_osob.for.USER.APPLY', 0, GuidOsoby, '', '', '', '', '', '');
		IN _OsobaGUID VARCHAR(120)		Osoba
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _Value;
		IF _MODE = 'grupy_osob.for.USER.INIT' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` LIKE `grupy_osob`;
			/*
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` (
			  `osobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `grupaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `Valid_From` DATE DEFAULT NULL,
			  `Valid_To` DATE DEFAULT NULL,
			  `Deleted` INTEGER NOT NULL DEFAULT 0,
			  UNIQUE KEY `osoba_grupa` (`osobaGUID`,`grupaGUID`)
			)
			;
			*/
		END IF;

		IF _MODE = 'grupy_osob.for.USER.ADD' THEN
			SET
				@.IN.param1 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param1', ''), ''),
				@.IN.param2 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param2', ''), ''),
				@.IN.param3 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param3', ''), ''),
				@.IN.param4 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param4', ''), ''),
				@.IN.param5 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param5', ''), '')
			;
			INSERT IGNORE INTO `t_edit_grupy_osob`
			(
				grupaGUID, OsobaGUID, Valid_From, Valid_To, Deleted, 
				param1, param2, param3, param4, param5
			)
			VALUES
			(
				_GrupaGUID, _OsobaGUID, NULLIF(_PARAM_A, ''), NULLIF(_PARAM_B, ''), IFNULL(NULLIF(_PARAM_C, ''), 0),
				@.IN.param1, @.IN.param2, @.IN.param3, @.IN.param4, @.IN.param5
			)
			;
		END IF;
		
		IF _MODE = 'grupy_osob.for.USER.APPLY' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_curr_grupy_osob`;
			CREATE TEMPORARY TABLE `t_curr_grupy_osob` 
				SELECT 
					go.* 
				FROM `grupy_osob` go, `osoby` g 
				WHERE
					go.OsobaGUID = _OsobaGUID
					AND go.GrupaGUID <> 'ALL' 			--	ale bez grupy 'Wszyscy'
					AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
					AND g.GUID = go.GrupaGUID 
					AND IF(IFNULL(_PARAM_D, '') = '', g.group_type != 1, TRUE)
			;
		--	Ustaw na usuniete tylko te których nie przysłano lub które ustawiono jako Deleted	
			UPDATE `t_curr_grupy_osob` tgo
			LEFT JOIN `t_edit_grupy_osob` t ON tgo.OsobaGUID = t.OsobaGUID AND tgo.GrupaGUID = t.GrupaGUID
			SET
				tgo.Deleted = IFNULL(t.Deleted, 1)
			WHERE
				TRUE
				-- AND tgo.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				-- AND tgo.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
			INSERT IGNORE INTO `grupy_osob`
			(
				grupaGUID, OsobaGUID, Valid_From, Valid_To, Deleted, 
				param1, param2, param3, param4, param5
			)
			SELECT
				t.grupaGUID, t.OsobaGUID, t.Valid_From, t.Valid_To, t.Deleted,
				t.param1, t.param2, t.param3, t.param4, t.param5
			FROM `t_edit_grupy_osob` t
			ON DUPLICATE KEY 
			UPDATE
				Valid_From = t.Valid_From,
				Valid_To = t.Valid_To,
				Deleted = t.Deleted,
				param1 = t.param1,
				param2 = t.param2,
				param3 = t.param3,
				param4 = t.param4,
				param5 = t.param5
			;
			DELETE go FROM `grupy_osob` go, `t_curr_grupy_osob` tgo
			WHERE
				go.OsobaGUID = _OsobaGUID
				AND tgo.OsobaGUID = go.OsobaGUID AND tgo.GrupaGUID = go.GrupaGUID
				AND tgo.Deleted
				AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
		END IF;
		
	END IF;


	IF _MODE LIKE 'grupy_osob.for.GROUP.%' THEN
	/* *************************************************************************************************************************************************************
		NOWE
		zamiast 
		'Users.grupy_osob.xxx'
		Inicjowanie tabeli tymcz.
		CALL _user_accounts_sys_cfg('grupy_osob.for.GROUP.INIT', 0, '', '', '', '', '', '', '');
		
		wstawianie do tabeli tymcz.
		CALL _user_accounts_sys_cfg('grupy_osob.for.GROUP.ADD', 0, GuidOsoby, GuidGrupy, Valid_From, Valid_To, Deleted, '', 'param1=xxx&param2=yyy');
		IN _OsobaGUID VARCHAR(38) 	Osoba
		IN _Value VARCHAR(120)		Grupa
		_PARAM_A	Valid_From / null 
		_PARAM_B	Valid_To / null 
		_PARAM_C	Deleted (0/1)
		
		Zapis tabeli tymcz. do bazy
		CALL _user_accounts_sys_cfg('grupy_osob.for.GROUP.APPLY', 0, GuidOsoby, '', '', '', '', '', '');
		IN _OsobaGUID VARCHAR(120)		Osoba
	**************************************************************************************************************************************************************/
		SET _GrupaGUID = _Value;
		IF _MODE = 'grupy_osob.for.GROUP.INIT' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` LIKE `grupy_osob`;
			/*
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` (
			  `osobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `grupaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `Valid_From` DATE DEFAULT NULL,
			  `Valid_To` DATE DEFAULT NULL,
			  `Deleted` INTEGER NOT NULL DEFAULT 0,
			  UNIQUE KEY `osoba_grupa` (`osobaGUID`,`grupaGUID`)
			)
			;
			*/
		END IF;

		IF _MODE = 'grupy_osob.for.GROUP.ADD' THEN
			SET
				@.IN.param1 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param1', ''), ''),
				@.IN.param2 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param2', ''), ''),
				@.IN.param3 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param3', ''), ''),
				@.IN.param4 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param4', ''), ''),
				@.IN.param5 = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'param5', ''), '')
			;
			INSERT IGNORE INTO `t_edit_grupy_osob`
			(
				grupaGUID, OsobaGUID, Valid_From, Valid_To, Deleted, 
				param1, param2, param3, param4, param5
			)
			VALUES
			(
				_GrupaGUID, _OsobaGUID, NULLIF(_PARAM_A, ''), NULLIF(_PARAM_B, ''), IFNULL(NULLIF(_PARAM_C, ''), 0),
				@.IN.param1, @.IN.param2, @.IN.param3, @.IN.param4, @.IN.param5
			)
			;
		END IF;
		
		IF _MODE = 'grupy_osob.for.GROUP.APPLY' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_curr_grupy_osob`;
			CREATE TEMPORARY TABLE `t_curr_grupy_osob` 
				SELECT 
					go.* 
				FROM `grupy_osob` go
				WHERE
					go.GrupaGUID = _GrupaGUID
					AND go.GrupaGUID <> 'ALL' 			--	ale bez grupy 'Wszyscy'
					AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
		--	Ustaw na usuniete tylko te których nie przysłano lub które ustawiono jako Deleted	
			UPDATE `t_curr_grupy_osob` tgo
			LEFT JOIN `t_edit_grupy_osob` t ON tgo.OsobaGUID = t.OsobaGUID AND tgo.GrupaGUID = t.GrupaGUID
			SET
				tgo.Deleted = IFNULL(t.Deleted, 1)
			WHERE
				TRUE
				-- AND tgo.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				-- AND tgo.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
		
			/*
			UPDATE `grupy_osob` go
			SET
				go.Deleted = 1
			WHERE
				go.GrupaGUID = _GrupaGUID
				AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
			*/
			INSERT IGNORE INTO `grupy_osob`
			(
				grupaGUID, OsobaGUID, Valid_From, Valid_To, Deleted, 
				param1, param2, param3, param4, param5
			)
			SELECT
				t.grupaGUID, t.OsobaGUID, t.Valid_From, t.Valid_To, t.Deleted,
				t.param1, t.param2, t.param3, t.param4, t.param5
			FROM `t_edit_grupy_osob` t
			ON DUPLICATE KEY 
			UPDATE
				Valid_From = t.Valid_From,
				Valid_To = t.Valid_To,
				Deleted = t.Deleted,
				param1 = t.param1,
				param2 = t.param2,
				param3 = t.param3,
				param4 = t.param4,
				param5 = t.param5
			;
	--	UWAGA!!!!!!!!!!!! Potencjalny BUG!!!!! niestety uswa ludzi bez powodu - Sprawdz to 17 I 2024!!!		
			DELETE go FROM `grupy_osob` go, `t_curr_grupy_osob` tgo
			WHERE
				go.GrupaGUID = _GrupaGUID
				AND tgo.OsobaGUID = go.OsobaGUID AND tgo.GrupaGUID = go.GrupaGUID
				AND tgo.Deleted
				AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
			/*
			DELETE go FROM `grupy_osob` go
			WHERE
				go.GrupaGUID = _GrupaGUID
				AND go.Deleted
				AND go.GrupaGUID <> 'ALL' 				--	ale bez grupy 'Wszyscy'
				AND go.GrupaGUID <> go.OsobaGUID		--	i bez grupy własnej
			;
			*/
			select * from `t_edit_grupy_osob`;
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
		END IF;
		
	END IF;
	
	IF _MODE LIKE 'Users.grupy_osob.%' THEN
	/* *************************************************************************************************************************************************************
		Inicjowanie tabeli tymcz.
		CALL _user_accounts_sys_cfg('Users.grupy_osob.INIT', 0, '', '', '', '', '', '', '');
		wstawianie do tabeli tymcz.
		CALL _user_accounts_sys_cfg('Users.grupy_osob.ADD', 0, GuidOsoby, GuidGrupy, '', '', '', '', '');
		IN _OsobaGUID VARCHAR(38) 	Osoba
		IN _Value VARCHAR(120)		Grupa
		Zapis tabeli tymcz. do bazy
		CALL _user_accounts_sys_cfg('Users.grupy_osob.APPLY', 0, GuidOsoby, '', '', '', '', '', '');
		IN _OsobaGUID VARCHAR(120)		Osoba
	**************************************************************************************************************************************************************/
		IF _MODE = 'Users.grupy_osob.INIT' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` (
			  `osobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `grupaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `Deleted` INTEGER NOT NULL DEFAULT 0,
			  UNIQUE KEY `osoba_grupa` (`osobaGUID`,`grupaGUID`)
			)
			;
		END IF;

		IF _MODE = 'Users.grupy_osob.ADD' THEN
			INSERT IGNORE INTO `t_edit_grupy_osob`
			(grupaGUID, OsobaGUID)
			VALUES
			(_Value, _OsobaGUID)
			;
		END IF;
		
		IF _MODE = 'Users.grupy_osob.APPLY' THEN
			INSERT IGNORE INTO `grupy_osob`
			(grupaGUID, OsobaGUID)
			SELECT
				grupaGUID, OsobaGUID
			FROM `t_edit_grupy_osob`
			;
			INSERT IGNORE INTO `t_edit_grupy_osob`
			(grupaGUID, OsobaGUID, Deleted)
			SELECT
				grupaGUID, OsobaGUID, 1
			FROM `grupy_osob`
			WHERE
				OsobaGUID = _OsobaGUID
				AND
				grupaGUID != OsobaGUID
			;
			DELETE g FROM `grupy_osob` g, `t_edit_grupy_osob` t
			WHERE
				g.grupaGUID = t.grupaGUID
				AND
				g.OsobaGUID = t.OsobaGUID
				AND
				t.Deleted
			;
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
		END IF;
	END IF;
	
	IF _MODE LIKE 'Grupy.grupy_osob.%' THEN
	/* *************************************************************************************************************************************************************
		Inicjowanie tabeli tymcz.
		CALL _user_accounts_sys_cfg('Grupy.grupy_osob.INIT', 0, '', '', '', '', '', '', '');
		wstawianie do tabeli tymcz.
		CALL _user_accounts_sys_cfg('Grupy.grupy_osob.ADD', 0, GuidOsoby, GuidGrupy, '', '', '', '', '');
		IN _OsobaGUID VARCHAR(38) 	Osoba
		IN _Value VARCHAR(120)		Grupa
		Zapis tabeli tymcz. do bazy GRUPY
		CALL _user_accounts_sys_cfg('Grupy.grupy_osob.APPLY.grupa', 0, '', GuidGrupy, '', '', '', '', '');
		IN _Value VARCHAR(120)		Grupa
		Zapis tabeli tymcz. do bazy UZYTKOWNICY
		CALL _user_accounts_sys_cfg('Grupy.grupy_osob.APPLY.user', 0, 'GuidOsoby', '', '', '', '', '', '');
		IN _OsobaGUID VARCHAR(120)		Osoba
	**************************************************************************************************************************************************************/
		IF _MODE = 'Grupy.grupy_osob.INIT' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
			CREATE TEMPORARY TABLE `t_edit_grupy_osob` (
			  `osobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `grupaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `Deleted` INTEGER NOT NULL DEFAULT 0,
			  UNIQUE KEY `osoba_grupa` (`osobaGUID`,`grupaGUID`)
			)
			;
		END IF;

		IF _MODE = 'Grupy.grupy_osob.ADD' THEN
			SET _GrupaGUID = _Value;
			INSERT IGNORE INTO `t_edit_grupy_osob`
			(grupaGUID, OsobaGUID)
			VALUES
			(_Value, _OsobaGUID)
			;
		END IF;
		
		IF _MODE LIKE 'Grupy.grupy_osob.APPLY%' THEN
			INSERT IGNORE INTO `grupy_osob`
			(grupaGUID, OsobaGUID)
			SELECT
				grupaGUID, OsobaGUID
			FROM `t_edit_grupy_osob`
			WHERE
				IFNULL(osobaguid, '') <> ''
				AND
				IFNULL(grupaGUID, '') <> ''
			;
			IF _MODE = 'Grupy.grupy_osob.APPLY.grupa' THEN
			--	powrotny insert wszystkich dla danej grupy (z wyjatkiem sama z soba) - kazdy affected da deleted na 1 czyli ze go tam nie bylo i bedzie usuniety
				INSERT IGNORE INTO `t_edit_grupy_osob`
				(grupaGUID, OsobaGUID, Deleted)
				SELECT
					grupaGUID, OsobaGUID, 1
				FROM `grupy_osob`
				WHERE
					grupaGUID = _Value
					AND
					grupaGUID != OsobaGUID
				;
			ELSE
			--	powrotny insert wszystkich dla danego usera (z wyjatkiem sama z soba) - kazdy affected da deleted na 1 czyli ze go tam nie bylo i bedzie usuniety
				INSERT IGNORE INTO `t_edit_grupy_osob`
				(grupaGUID, OsobaGUID, Deleted)
				SELECT
					grupaGUID, OsobaGUID, 1
				FROM `grupy_osob`
				WHERE
					OsobaGUID = _OsobaGUID
					AND
					grupaGUID != OsobaGUID
				;
			END IF;
		--	usuwanie czyli wszystkie te co maja deleted na 1
			DELETE g FROM `grupy_osob` g, `t_edit_grupy_osob` t
			WHERE
				g.grupaGUID = t.grupaGUID
				AND
				g.OsobaGUID = t.OsobaGUID
				AND
				t.Deleted
			;
			DROP TEMPORARY TABLE IF EXISTS `t_edit_grupy_osob`;
		END IF;
	--	Klonowanie	
		IF _MODE LIKE 'Grupy.grupy_osob.Clone.from%' THEN
		/* *************************************************************************************************************************************************************
			Klonowanie żródłowej grupy _Value pod nazwą _PARAM_A
			CALL _user_accounts_sys_cfg('Grupy.grupy_osob.Clone.from', 0, NULL, GuidGrupy, 'Nowa nazwa grupy', '', '', '', '');
			IN _OsobaGUID VARCHAR(38) 	Grupa docelowa - zazwyczaj NULL/""
			IN _Value VARCHAR(120)		Grupa żródłowa
			IN _PARAM_A nazwa docelowa
		**************************************************************************************************************************************************************/
		--	Inicjowanie tabeli tymcz.
			SET
				@.Clone.Src.GRP.GUID = _Value,
				@.Clone.Dest.GRP.GUID = IFNULL(NULLIF(_OsobaGUID, ''), CONCAT('CLN:', UUID_SHORT())),
				-- @.Clone.Dest.GRP.Name = nullIF('Hanlowcowy', '')
				@.Clone.Dest.GRP.Name = NULLIF(_PARAM_A, '')
			;
			DROP TEMPORARY TABLE IF EXISTS `tclone_grupa`; 
			CREATE TEMPORARY TABLE `tclone_grupa` 
			SELECT * FROM  `osoby` WHERE GUID = @.Clone.Src.GRP.GUID
			; 
			UPDATE `tclone_grupa` tg
			SET
				tg.Idn = NULL,
				tg.GUID = @.Clone.Dest.GRP.GUID,
				tg.Nazwisko = (@.Clone.Dest.GRP.Name := IFNULL(@.Clone.Dest.GRP.Name, CONCAT_WS(' ', 'Kopia', tg.Nazwisko))),
				tg.IdnUser = @.Clone.Dest.GRP.Name
			;
			INSERT IGNORE INTO `osoby` SELECT * FROM `tclone_grupa` tg;
			
						--	SELECT tg.GUID, tg.Nazwisko, tg.IdnUser, tg.* FROM `tclone_grupa` tg;
			DROP TEMPORARY TABLE IF EXISTS `tclone_grupa_users`; 
			CREATE TEMPORARY TABLE `tclone_grupa_users` 
			SELECT 
				go.* 
			FROM `grupy_osob` go 
			WHERE 
				TRUE
				-- and go.grupaGUID <> 'ALL' AND go.osobaGUID <> go.grupaGUID 
				-- AND NOT go.grupaGUID LIKE  'M.%'
				AND go.grupaGUID  = @.Clone.Src.GRP.GUID
			; 
			UPDATE `tclone_grupa_users` tgo
			SET
				tgo.osobaguid = @.Clone.Dest.GRP.GUID
			WHERE
				tgo.osobaguid = @.Clone.Src.GRP.GUID
			;
			UPDATE `tclone_grupa_users` tgo
			SET
				tgo.grupaGUID = @.Clone.Dest.GRP.GUID
			;
			INSERT IGNORE INTO `grupy_osob` SELECT tgo.* FROM `tclone_grupa_users` tgo;
						--	SELECT tgo.* FROM `tclone_grupa_users` tgo;
			DROP TEMPORARY TABLE IF EXISTS `tclone_grupa_upr`; 
			CREATE TEMPORARY TABLE `tclone_grupa_upr`
			SELECT 
				u.* 
			FROM `uprawnienia` u 
			WHERE 
				TRUE
				-- and go.grupaGUID <> 'ALL' AND go.osobaGUID <> go.grupaGUID 
				-- AND NOT go.grupaGUID LIKE  'M.%'
				AND u.osobaGUID  = @.Clone.Src.GRP.GUID
			; 
			UPDATE `tclone_grupa_upr` tgu
			SET
				tgu.GUID = NULL,
				tgu.osobaGUID = @.Clone.Dest.GRP.GUID,
				tgu.login = @.Clone.Dest.GRP.Name
			;
			INSERT IGNORE INTO `uprawnienia` SELECT tgu.* FROM `tclone_grupa_upr` tgu;
						--	SELECT tgu.* FROM `tclone_grupa_upr` tgu;
			IF NOT IFNULL(@session.Delfinek, FALSE) THEN
				DROP TEMPORARY TABLE IF EXISTS `tclone_grupa`; 
				DROP TEMPORARY TABLE IF EXISTS `tclone_grupa_users`; 
				DROP TEMPORARY TABLE IF EXISTS `tclone_grupa_upr`; 
			END IF;
		END IF;
	END IF;

	IF _MODE = 'Dodaj.grupy.jakiejsc.osoby.do.danej.osoby' THEN
	/* *************************************************************************************************************************************************************
		Dodawanie grup innej osoby (_Value) do osoby _OsobaGUID
		CALL _user_accounts_sys_cfg('Dodaj.grupy.jakiejsc.osoby.do.danej.osoby', 0, 'Osoba', 'Osoba_Src', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value	osoba z ktorej pobieramy grupy
	**************************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_grupy_for_Osoba_Src`;
		CREATE TEMPORARY TABLE `t_grupy_for_Osoba_Src`
			SELECT 
				g.osobaguid,
				g.grupaGUID 
			FROM `grupy_osob` g
			WHERE
				g.osobaGUID = _Value
				AND
				IFNULL(g.osobaguid, '') <> ''
				AND
				IFNULL(g.grupaGUID, '') <> ''
		;
		UPDATE `t_grupy_for_Osoba_Src` SET osobaGUID = _OsobaGUID;
		INSERT IGNORE INTO `grupy_osob`
		(`osobaguid`,`grupaGUID`)
			SELECT 
				t.osobaguid,
				t.grupaGUID 
			FROM `t_grupy_for_Osoba_Src` t
			WHERE
				IFNULL(t.osobaguid, '') <> ''
				AND
				IFNULL(t.grupaGUID, '') <> ''
		;
		DROP TEMPORARY TABLE IF EXISTS `t_grupy_for_Osoba_Src`;
	END IF;
	

	IF _MODE LIKE 'SELECT.osoby.%' THEN
	/* *************************************************************************************************************************************************************
		Osoby ktore widzimy w Centrum.IntNet
		CALL _user_accounts_sys_cfg('SELECT.osoby.IntNet', 0, '', '0', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('SELECT.osoby.IntNet', 0, 'Osoba', '0', '', '', '', '', '');
		_OsobaGUID	osoba gdy <> '' to wszystkich userow
	**************************************************************************************************************************************************************/
		-- IF _MODE = 'SELECT.osoby.bedace.userami' THEN
		SELECT 
			_VarInt(IFNULL(A.`user_type`, O.`user_type`)) AS `User_Type`,
			_VarInt(IFNULL(A.`Admin`, O.`administrator`)) AS `Administrator`,
			O.`GUID` AS `GUID`, 
			O.ugrpGuid,
			K.`symbol` AS `symbol`,
			O.`pracownik` AS `pracownik`,
			_VarStr(IF(IFNULL(dg.Value, 0), IFNULL(A.`Login`, O.`idnuser`), O.`idnuser`)) AS `idnuser`,
			_VarInt(IF(IFNULL(dg.Value, 0), IFNULL(A.`Status`, O.`user_inactive`), O.`user_inactive` )) AS `user_inactive`,
			O.`niewidoczna_w_HR` AS `niewidoczna_w_HR`,
			O.`rodzaj` AS `rodzaj`, 
			O.`Nazwisko` AS `Nazwisko`,	O.`Imie1`,	O.`Imie2`,
			O.`NrPesel`,
			O.`ImieMatki`, O.`ImieOjca`,
			O.`MiejsceUrodzenia`,
			O.`NazwiskoPanienskie`,
			O.`NrSeriaDowoduOsobistego`,
			O.`ToPracownik`,
			O.`ToZleceniobiorca`,
			O.`serwis`,
			O.`Imiona` AS `imiona`,
			O.`stanowisko` AS `stanowisko`,
			IFNULL(D.`opis`, '') AS `dzial`,
			O.`nazwa_dzialu` AS `nazwa_dzialu`,
			IF(O.pracownik, 'pracow.', IFNULL(K.Nazwa, '-')) AS PracownikKontrahent,
			O.`plec` AS `plec`,
			O.DataUrodzenia,
			O.`AZAM_KodPocztowy` AS `AZAM_kodpocztowy`,
			CONCAT(O.`Nazwisko`, ' ', O.`Imiona`) AS `NazwiskoImie`,
			SUBSTR(CONCAT(O.`AZAM_Ulica`, ' ', O.`AZAM_KodPocztowy`, ' ', O.`AZAM_Miejscowosc`), 1, 70) AS `Adres`,
			O.`AZAM_Adres` AS `AZAM_Adres`,
			O.`AZAM_Miejscowosc` AS `AZAM_miejscowosc`,
			O.`AZAM_Ulica` AS `AZAM_ulica`,
			O.`nieaktywny` AS `nieaktywny`,
			O.`korespondencja` AS `korespondencja`,
			O.`priorytet` AS `priorytet`,
			O.`kontrGUID` AS `kontrGUID`, 
			_VarInt(IFNULL(A.`IDN`, -1)) AS `IDN_account`
		FROM `osoby` O 
		LEFT JOIN `_db_globals` dg ON dg.Key = 'LOGON.user_accounts_Mode'
		LEFT JOIN `kontrah` K ON O.`kontrGUID` = K.`GUID`
		LEFT JOIN `dzialy` D ON O.`dzial` = D.`idn`
		LEFT JOIN `_user_accounts` A ON A.`OsobaGUID` = O.`GUID` AND A.`typ` = 'SYS'
		WHERE 
			TRUE
			AND O.deleted = 0 
			AND O.rodzaj = 1
			AND IF(IFNULL(_OsobaGUID, '') != '', TRUE, (IFNULL(A.user_type, 0) != 0 OR O.user_type != 0))
			AND IF(IFNULL(_OsobaGUID, '') != '', O.GUID = _OsobaGUID, TRUE)
		;		
	END IF;

	IF 
		_MODE LIKE 'accounts.%.Access_Module' 
		AND
		NOT(_MODE LIKE 'accounts.2.0%')		-- zabezb. aby nie wołac dla nowych wywołań 2.0
		AND
		NOT(_MODE LIKE 'accounts.3.0%')		-- zabezb. aby nie wołac dla nowych wywołań 2.0
	THEN
	/* *************************************************************************************************************************************************************
		Dodawanie/odbieranie dostepu do modulu 
		CALL _user_accounts_sys_cfg('accounts.add.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('accounts.remove.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value	Access_Module
		jmam
	**************************************************************************************************************************************************************/
		SET @.Access_Module = IFNULL(_Value, '');
		
		IF _MODE LIKE 'accounts.remove.Access_Module' THEN
			DELETE FROM `uprawnienia` 
			WHERE  
				osobaGUID = _OsobaGUID
				AND miejsce = @.Access_Module 
			;
			SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
			UPDATE `grupy_osob` go
			SET
				go.Deleted = 1
			WHERE
				go.osobaGUID = _OsobaGUID
				AND go.grupaGUID = @.Access_Module 
			;
			SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
		END IF;
		
		IF _MODE LIKE 'accounts.add.Access_Module' THEN
			/* 
			było
			REPLACE `uprawnienia` 
			(login, miejsce, poziom, rodzaj, opis, ValueList, core_id, upr_type, osobaGUID)
			SELECT
				CONCAT(':', IFNULL(a.Login, o.IdnUser)) AS login,
				@.Access_Module AS miejsce, 
				1 AS poziom, 
				ud.rodzaj, 
				ud.opis,
				ud.ValueList,
				ud.core_id, 
				ud.upr_type,
				o.GUID AS osobaGUID
			FROM `osoby` o
			INNER JOIN `uprawnienia_dict` ud ON ud.miejsce  = @.Access_Module
			LEFT JOIN `_user_accounts` a ON a.osobaGUID = o.GUID AND typ = 'SYS'
			WHERE
				o.GUID = _OsobaGUID
			; 
			*/
			INSERT IGNORE INTO `uprawnienia`
			(login, miejsce, poziom, rodzaj, opis, ValueList, core_id, upr_type, osobaGUID)
			SELECT
				CONCAT(':', IFNULL(a.Login, o.IdnUser)) AS login,
				@.Access_Module AS miejsce, 
				1 AS poziom, 
				ud.rodzaj, 
				ud.opis,
				ud.ValueList,
				ud.core_id, 
				ud.upr_type,
				o.GUID AS osobaGUID
			FROM `osoby` o
			INNER JOIN `uprawnienia_dict` ud ON ud.miejsce  = @.Access_Module
			LEFT JOIN `_user_accounts` a ON a.osobaGUID = o.GUID AND typ = 'SYS'
			WHERE
				o.GUID = _OsobaGUID
				AND 
				IFNULL(o.GUID, '') <> ''
			ON DUPLICATE KEY UPDATE
				poziom = 1
			; 
			SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
			
			IF IFNULL(_OsobaGUID, '') <> '' AND IFNULL(@.Access_Module, '') <> '' THEN
				INSERT IGNORE INTO `grupy_osob`
				SET
					osobaGUID = _OsobaGUID,
					grupaGUID = @.Access_Module 
				ON DUPLICATE KEY UPDATE
					Deleted = 0
				;
				SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
			ELSE
				SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
			END IF;
		END IF;
	--	Wysłac powiadomienie ?
		IF 
			@.accounts.add.Access_Module.ROW_COUNT > 0
			AND _PARAM_A = 'SEND.MAIL' 
		THEN
			CALL _user_accounts_sys_cfg('Moduly.Send.Info.2.User.Dostep', 0, _OsobaGUID, @.Access_Module, '1', '', '', '', '');
		END IF;
	--	Select koncowy ?
		IF (_PARAM_E LIKE '%select%') THEN
			SELECT
				CONCAT_WS('',
					IF(@.accounts.add.Access_Module.ROW_COUNT + @.accounts.add.Access_Module.UPR.ROW_COUNT > 0,
						IF(_MODE LIKE 'accounts.add.Access_Module',
							'Pomyślnie dodano dostęp użytkownika do modułu/aplikacji: ',
							'Usunięto dostęp użytkownika do modułu/aplikacji: '
						),
						IF(_MODE LIKE 'accounts.add.Access_Module',
							'Użytkownik ma już dostęp do modułu/aplikacji: ',
							'Użytkownik nie ma dostępu do modułu/aplikacji: '
						)
					),
					'\n',
					IFNULL(c.Caption, @.Access_Module),
					'!'
				) AS Actv_Status_Msg,
				'OK' AS Actv_Status	
			FROM `sys_core` c 
			WHERE
				c.GUID = @.Access_Module 
			;
		END IF;
		
	END IF;
	
	
	IF 
		_MODE LIKE 'accounts.Kadry.%' 
		OR
		_MODE LIKE 'accounts.INTNET.%' 
	THEN
		-- SET _MODE = REPLACE(_MODE, '.Kadry.', '.INTNET.');
	/* *************************************************************************************************************************************************************
		
		Informacja wstepna czyli pobierz dane uzytkownika
		CALL _user_accounts_sys_cfg('accounts.Kadry.select.INF', 0, USER_GUID, Modul, '', '', '', '', '');
			np.
			CALL _user_accounts_sys_cfg('accounts.Kadry.select.INF', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
			W polach 
			Action_Create, Action_Reactivate i Action_Err_logon_count
			masz inf. czy dany przycisk jest aktywny np. 
				dla Aktywacji konta bedziesz miał 1, 0, 0
				a dla odblokowania konta: 0, 0, 1 itp
			
		CALL _user_accounts_sys_cfg('accounts.create.select', 0, '{0B8FA759-8126-4141-85DC-8E1CB21A4786}', 'M.WEB.PortaFide.www', '', '', '', '', ''); --	
		Kreowanie konta		
			CALL _user_accounts_sys_cfg('accounts.Kadry.Create.Konto', 0, USER_GUID, Modul, '', 'email', '', '', '');
		Reaktywacja konta		
			CALL _user_accounts_sys_cfg('accounts.Kadry.Reaktuwuj.Konto', 0, USER_GUID, Modul, '', 'email', '', '', '');
		Dodanie dostępu do modułu
			CALL _user_accounts_sys_cfg('accounts.Kadry.Dodaj.dostep.do.modulu', 0, USER_GUID, Modul, '', '', '', '', '');
		Odblokowanie konta
			CALL _user_accounts_sys_cfg('accounts.Kadry.Odblokuj.Konto', 0, USER_GUID, '', '', '', '', '', '');
			_OsobaGUID		osoba
			IN _Value 		modul
			IN _PARAM_A		login
			IN _PARAM_B 	email
			IN _PARAM_E 	zawiera ew. opcje 
				select 					-- zwracamy select
				<dont.send.activation>	-- nie wysylamy linka aktywacyjnego
				<dont.send.add.module>	-- nie wysylamy linka inf o dodaniu grupy dostepowej
		
	**************************************************************************************************************************************************************/
		IF _MODE IN ('accounts.Kadry.Prepare', 'accounts.INTNET.Prepare') THEN
			CALL _user_accounts_build_login('INIT', _OsobaGUID, @.blabla, '', '');  	
			CALL _user_accounts_build_login('FIND', '', @.tua.Login, 'idnuser(5);i1nX(5);i1.nX(5);iXr2;pesel;iXr4', ''); 
			CALL _user_accounts_build_login('Get.Free.Login', '', @.Free.Logins, 'idnuser(5);i1nX(5);i1.nX(5);iXr2;pesel;iXr4', ''); 

			
			-- SHOW CREATE TABLE `t_kadry_accounts_state`;
			SET 
				@.tua.Access_Module = IFNULL(_Value, ''),
				@_MAX_USER_err_logon_count = 3
			;
			DROP TEMPORARY TABLE IF EXISTS `t_kadry_accounts_state`;
		/*	było
			CREATE TEMPORARY TABLE `t_kadry_accounts_state` (
			  `GUID` VARCHAR(38) NOT NULL DEFAULT '',
			  `Imie_Nazwisko` VARCHAR(150) DEFAULT NULL,
			  `Nazwisko_Imiona` VARCHAR(150) DEFAULT NULL,
			  `accounts_exists` INT(11) NOT NULL,
			  `accounts_exists_not_activate` INT(11) NOT NULL,
			  `accounts_active` INT(11) NOT NULL COMMENT 'user_type > 0 i status = 0',
			  `Access_Module` VARCHAR(38) NOT NULL DEFAULT '',
			  `Access_Module_OK` INT(1) DEFAULT NULL,
			-- Akcje przycisków
			  `Action_Create` INT(1) NOT NULL,
			  `Action_Reactivate` INT(1) NOT NULL,
			  `Action_Add_to_Module` INT(1) NOT NULL,
			  `Action_Err_logon_count` INT(1) NOT NULL,
			  
			  `idn` INT(11) DEFAULT 0,
			  `osobaGUID` VARCHAR(38) DEFAULT '' COMMENT 'uzytkownik',
			  `typ` VARCHAR(38) COMMENT 'typ konta SYS, MAIL, etc',
			  `login` VARCHAR(50) DEFAULT NULL,
			  `datas` VARCHAR(50),
			  `user_type` INT(11) DEFAULT 1 COMMENT 'typ uzytkownika 0, 1 - normalne, 2 - gosc',
			  `admin` INT(11) DEFAULT 0 COMMENT '1 - administrator, 0 zwykly uzytkownik',
			  `date_from` DATE DEFAULT '2000-01-01' COMMENT 'konto wazne od',
			  `date_to` DATE DEFAULT '2100-01-01' COMMENT 'konto wazne do',
			  `Ad_mail` VARCHAR(200) DEFAULT NULL COMMENT 'mail',
			  `Ad_sms` VARCHAR(200) DEFAULT NULL COMMENT 'sms',
			  `Last_Change_Pswd` DATETIME DEFAULT '2018-05-23 00:00:00',
			  `err_logon_count` INT(11) DEFAULT 0 COMMENT 'ilosc blednych logowan',
			  `status` INT(11) DEFAULT NULL COMMENT '0 - normalne, 1 - zablokowane, 2 - usuniete',
			  `LastUpdate` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP(),
			  `ExtFlags` VARCHAR(250) DEFAULT NULL COMMENT 'Dodatkowe flagi (np. <Empty.PSWD>)',
			  `User_account_Type` INT(11) DEFAULT 1 COMMENT 'typ uzytkownika dla int net!!! 0 zwykły 1 admin, 2 gosc'
			) ENGINE=MYISAM DEFAULT CHARSET=UTF8
			;
			INSERT IGNORE INTO `t_kadry_accounts_state`
			SELECT
				o.GUID,
				CONCAT_WS(' ', o.Imie1, o.Nazwisko) AS Imie_Nazwisko,
				CONCAT_WS(' ', o.Nazwisko, o.Imiona) AS Nazwisko_Imiona,
				(@.accounts.create.exists := (ua.OsobaGUID IS NOT NULL)) AS accounts_exists, 
				(@.accounts.create.exists.not.activate := (@.accounts.create.exists AND IFNULL(ua.ExtFlags, '') LIKE '%<SetUp.New>%')) AS accounts_exists_not_activate,
				IFNULL(
					(ua.user_type > 0 AND ua.Status = 0) AND NOT @.accounts.create.exists.not.activate, 
					FALSE
				) AS accounts_active,
				@.tua.Access_Module AS Access_Module,
				IF(@.tua.Access_Module = '',
					FALSE,	--	zawsze wpuszczaj nieokreslona aplikacje czy modul (sytuacja typu np. stare programy)
					IFNULL(
						(SELECT SUM(u.poziom) FROM `uprawnienia` u WHERE u.miejsce LIKE CONCAT(@.tua.Access_Module, '%') AND u.OsobaGUID = o.GUID),
						IFNULL(
							(SELECT MAX(u.poziom) FROM `uprawnienia` u, `grupy_osob` go WHERE go.OsobaGUID = o.GUID AND u.miejsce = @.tua.Access_Module AND u.OsobaGUID = go.GrupaGUID AND NOT go.Deleted),
							FALSE
						)
					) > 0
				) AS Access_Module_OK, 
				TRUE AS Action_Create,
				TRUE AS Action_Reactivate,
				TRUE AS Action_Add_to_Module,
				TRUE AS Action_Err_logon_count,
				ua.*
				,
				_VarInt(IF(ua.Admin != 0, 1, IF(ua.user_type = 1, 0, 2))) AS User_account_Type -- typ uzytkownika dla int net!!! 0 zwykły 1 admin, 2 gosc
				
				
			FROM `osoby` o
			LEFT JOIN `_user_accounts` ua ON ua.OsobaGUID = o.GUID AND ua.typ = 'SYS'
			WHERE
				o.GUID = _OsobaGUID
			;
		... jest	*/
			CREATE TEMPORARY TABLE `t_kadry_accounts_state` 
			SELECT
				o.GUID,
				CONCAT_WS(' ', o.Imie1, o.Nazwisko) AS Imie_Nazwisko,
				CONCAT_WS(' ', o.Nazwisko, o.Imiona) AS Nazwisko_Imiona,
				(@.accounts.create.exists := (ua.OsobaGUID IS NOT NULL)) AS accounts_exists, 
				(@.accounts.create.exists.not.activate := (@.accounts.create.exists AND IFNULL(ua.ExtFlags, '') LIKE '%<SetUp.New>%')) AS accounts_exists_not_activate,
				IFNULL(
					(ua.user_type > 0 AND ua.Status = 0) AND NOT @.accounts.create.exists.not.activate, 
					FALSE
				) AS accounts_active,
				@.tua.Access_Module AS Access_Module,
				IF(@.tua.Access_Module = '',
					FALSE,	--	zawsze wpuszczaj nieokreslona aplikacje czy modul (sytuacja typu np. stare programy)
					IFNULL(
						(SELECT SUM(u.poziom) FROM `uprawnienia` u WHERE u.miejsce LIKE CONCAT(@.tua.Access_Module, '%') AND u.OsobaGUID = o.GUID),
						IFNULL(
							(SELECT MAX(u.poziom) FROM `uprawnienia` u, `grupy_osob` go WHERE go.OsobaGUID = o.GUID AND u.miejsce = @.tua.Access_Module AND u.OsobaGUID = go.GrupaGUID AND NOT go.Deleted),
							FALSE
						)
					) > 0
				) AS Access_Module_OK, 
				TRUE AS Action_Create,
				TRUE AS Action_Reactivate,
				TRUE AS Action_Add_to_Module,
				TRUE AS Action_Err_logon_count,
				ua.*
				,
				_VarInt(IF(ua.Admin != 0, 1, IF(ua.user_type = 1, 0, 2))) AS User_account_Type -- typ uzytkownika dla int net!!! 0 zwykły 1 admin, 2 gosc
				
				
			FROM `osoby` o
			LEFT JOIN `_user_accounts` ua ON ua.OsobaGUID = o.GUID AND ua.typ = 'SYS'
			WHERE
				o.GUID = _OsobaGUID
			;
			UPDATE `t_kadry_accounts_state` tua
			SET
				tua.Login = IFNULL(NULLIF(tua.Login, ''), @.tua.Login),
				tua.Ad_mail = 
					IFNULL(tua.Ad_mail,
						(
						SELECT 
							kk.adres 
						FROM `kontakty` kk 
						WHERE 
							kk.osobaGUID = tua.GUID 
							AND kk.typ_medium = 3 
							AND LOCATE('@', kk.`adres`) > 0 
							AND kk.nieaktywny = 0
						ORDER BY kk.priorytet 
						LIMIT 1
						)
					),
				tua.Action_Create = (@.tua.Action_Create := 
					NOT tua.accounts_exists
				),
				tua.Action_Reactivate = (@.tua.Action_Reactivate := 
					NOT @.tua.Action_Create AND NOT tua.accounts_active AND NOT tua.accounts_exists_not_activate
				),
				tua.Action_Add_to_Module = (@.tua.Action_Add_to_Module := 
					NOT @.tua.Action_Create AND NOT tua.Action_Reactivate AND tua.Access_Module_OK = 0
				),
				tua.Action_Err_logon_count = (@.tua.Action_Err_logon_count := 
					NOT @.tua.Action_Create AND NOT tua.Action_Reactivate AND NOT @.tua.Action_Add_to_Module AND IFNULL(tua.err_logon_count, 0) > 3
				)
			;
		END IF;
		
		IF _MODE IN ('accounts.Kadry.select.INF', 'accounts.INTNET.select.INF') THEN
			
			CALL _user_accounts_sys_cfg('accounts.Kadry.Prepare', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E); --	
			/*
			było
			SELECT 
				IF(tua.Action_Create,
					CONCAT_WS('', 'Osoba ', tua.Imie_Nazwisko, ' nie ma jeszcze konta!'),
				IF(tua.Action_Reactivate,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma konto nieaktywne!'),
				IF(tua.Action_Add_to_Module,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" nie ma dostępu do modułu/aplikacji: "', IFNULL(c.Caption, tua.Access_Module), '"!'),
				IF(tua.Action_Err_logon_count,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma zablokowane konto po nieudanych logowaniach!'),
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma już aktywne konto z dostępem do modułu/aplikacji: "', IFNULL(c.Caption, tua.Access_Module), '".')
				)))) AS Info,
				tua.* 
			FROM `t_kadry_accounts_state` tua
			LEFT JOIN `sys_core` c  ON c.GUID = tua.Access_Module
			;
			*/
			SELECT 
				IF(tua.Action_Create, 'Brak konta', CONCAT_WS('', 'Użytkownik ma konto', (@.tua.user_type_Str := IF(tua.user_type = 2, ' (typu "gość")', NULL)))) AS Info_Short,

				IF(tua.Action_Create,
					CONCAT_WS('', 'Osoba ', tua.Imie_Nazwisko, ' nie ma jeszcze konta!'),
				IF(tua.Action_Reactivate,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma konto nieaktywne', @.tua.user_type_Str, '!'),
				IF(tua.Action_Add_to_Module,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma konto', @.tua.user_type_Str, '.\nUWAGA! Nie ma dostępu do modułu/aplikacji: "', IFNULL(c.Caption, tua.Access_Module), '"!'),
				IF(tua.Action_Err_logon_count ,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma konto', @.tua.user_type_Str, '\nale ma zablokowane konto po nieudanych logowaniach!'),
				IF(tua.accounts_exists_not_activate,
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma konto', @.tua.user_type_Str, '\nale nie dokonał dotąd jego aktywacji!'),
					CONCAT_WS('', 'Użytkownik "', tua.Login, '" ma już aktywne konto', @.tua.user_type_Str, ' z dostępem do modułu/aplikacji: "', IFNULL(c.Caption, tua.Access_Module), '".')
				)))))
				AS Info,
				CONCAT_WS(';',
					IF(tua.Login IS NOT NULL AND LOCATE(tua.Login, IFNULL(@.Free.Logins, '')) = 0, tua.Login, NULL),
					@.Free.Logins 
				) AS Choice_Free_Logins,
				CONCAT_WS(';',
					@.Choice_Email := (
					SELECT 
						GROUP_CONCAT(DISTINCT kk.adres SEPARATOR ';') AS FMail
					FROM `kontakty` kk 
					WHERE 
						kk.osobaGUID = tua.GUID 
						AND kk.typ_medium = 3 
						AND LOCATE('@', kk.`adres`) > 0 
						AND kk.nieaktywny = 0
					ORDER BY kk.priorytet 
					-- LIMIT 1
					),
					IF(tua.AD_mail IS NOT NULL AND LOCATE(tua.AD_mail, IFNULL(@.Choice_Email, '')) = 0, tua.AD_mail, NULL)
					-- ,tua.AD_mail,
					-- ,NULL
				) AS Choice_Email,
				
				tua.* 
			FROM `t_kadry_accounts_state` tua
			LEFT JOIN `sys_core` c  ON c.GUID = tua.Access_Module
			;
			
			
		END IF;
		
		IF _MODE IN ('accounts.Kadry.Create.Konto', 'accounts.Kadry.Reaktuwuj.Konto', 'accounts.INTNET.Create.Konto', 'accounts.INTNET.Reaktuwuj.Konto') THEN
		/*
			_OsobaGUID		osoba
			IN _Value 		modul
			IN _PARAM_A		login
			IN _PARAM_B 	email
			IN _PARAM_C 	User_type
			IN _PARAM_E 	zawiera ew. opcje 
				select 					-- zwracamy select
				<dont.send.activation>	-- nie wysylamy linka aktywacyjnego
				<dont.send.add.module>	-- nie wysylamy linka inf o dodaniu grupy dostepowej
				<dont.add.activation>
		*/
			SET
				@.ua.Ad_Mail = NULLIF(_PARAM_B, ''),
				@.ua.User_type = IFNULL(NULLIF(_PARAM_C, ''), 1)
			;
set @.trace.act.X = concat_WS('/', @.trace.act.X, '1');
			CALL _user_accounts_build_login('INIT', _OsobaGUID, @.blabla, '', '');  	
set @.trace.act.X = concat_WS('/', @.trace.act.X, '2');
			CALL _user_accounts_build_login('FIND', '', @.ua.Login, 'idnuser(5);i1nX(5);i1.nX(5);iXr2;pesel;iXr4', ''); 
set @.trace.act.X = concat_WS('/', @.trace.act.X, '3');
		--	UWAGA w (_PARAM_A powinno byc pusto = "" bo wtedy nadamy domyslny nie powtarzalny login ze zmienne @.ua.Login jeśli 
		--	jednak w _PARAM_A bedzie cos to taki login nadamy
			SET @.ua.Login = IFNULL(NULLIF(_PARAM_A, ''), @.ua.Login);
		--	Wstawiamy	
		/*
			INSERT IGNORE INTO `_user_accounts` 
			(OsobaGUID, typ, login, User_type, Ad_Mail, STATUS)
			SELECT
				o.GUID AS OsobaGUID,
				'SYS' AS typ, 
				@.ua.Login AS Login,
				@.ua.User_type AS User_type,
				@.ua.Ad_Mail AS Ad_Mail,
				0 AS STATUS
			FROM `osoby` o
			WHERE
				o.GUID = _OsobaGUID
			ON DUPLICATE KEY UPDATE
				`_user_accounts`.User_type = ABS(`_user_accounts`.User_type),
				`_user_accounts`.Status = 0,
				`_user_accounts`.err_logon_count  = 0,
				`_user_accounts`.Ad_Mail = IFNULL(@.ua.Ad_Mail, (@.ua.Ad_Mail := `_user_accounts`.Ad_Mail))
			;
		*/	
set @.trace.act.X = concat_WS('/', @.trace.act.X, '3.INS');
			INSERT IGNORE INTO `_user_accounts` 
			(OsobaGUID, typ, login, User_type, Ad_Mail, STATUS)
			SELECT
				o.GUID AS OsobaGUID,
				'SYS' AS typ, 
				@.ua.Login AS Login,
				@.ua.User_type AS User_type,
				@.ua.Ad_Mail AS Ad_Mail,
				0 AS STATUS
			FROM `osoby` o
			WHERE
				o.GUID = _OsobaGUID
			;
set @.trace.act.X = concat_WS('/', @.trace.act.X, '3.UPDATE');
			UPDATE `_user_accounts` ua
			SET
				ua.User_type = ABS(ua.User_type),
				ua.Status = 0,
				ua.err_logon_count  = 0,
				ua.Ad_Mail = IFNULL(@.ua.Ad_Mail, (@.ua.Ad_Mail := ua.Ad_Mail))
			WHERE
				ua.OsobaGUID = _OsobaGUID
			;
set @.trace.act.X = concat_WS('/', @.trace.act.X, '3.OK');
set @.trace.act.X = concat_WS('/', @.trace.act.X, '4');
		--	Gdy w osobach IdnUser = IDN (cyfrowy) to wstaw do IdnUser login z `_user_accounts ...` 
		--	... a gdy był w postaci GUIDa (@.accounts.create.IdnUser.IS.AS.GUID = TRUE) ...
		--	to także wstaw do IdnUser login z `_user_accounts` 
			/*
			error mamy 
			UPDATE `_user_accounts` u, `osoby` o
			SET
				o.IdnUser = u.Login
			WHERE	
				o.GUID = _OsobaGUID
				AND 
				(
					o.IdnUser = o.IDN OR o.IdnUser = o.GUID
				)
				AND u.OsobaGUID = o.GUID
			;
			*/
			SET
				@.Access_Module = IFNULL(_Value, ''),
				@.create.send.activation = NOT (_PARAM_E LIKE '%dont.send.activation%'),
				@.create.send.add.module = NOT (_PARAM_E LIKE '%dont.add.module%'),
				@.create.select.After = (_PARAM_E LIKE '%select%')
			;
set @.trace.act.X = concat_WS('/', @.trace.act.X, '5');
			CALL _user_accounts_sys_cfg('accounts.3.0.add.Access_Module', 0, _OsobaGUID, _Value, '', '', '', '', '');
set @.trace.act.X = concat_WS('/', @.trace.act.X, '6');
			
			IF @.create.send.activation THEN
set @.trace.act.X = concat_WS('/', @.trace.act.X, '7');
				-- było CALL _user_accounts_sys_cfg('accounts.sent.aktywacja', 0, _OsobaGUID, @.Access_Module, '', '', '', '', '');
				CALL _user_accounts_sys_cfg('accounts.3.0.sent.aktywacja', 0, _OsobaGUID, @.Access_Module, '', '', '', '', '<select>');
			END IF;
			
		END IF;

		IF _MODE IN ('accounts.Kadry.Change.Ad_Mail', 'accounts.INTNET.Change.Ad_Mail') THEN
			SET
				@.ua.Ad_Mail = NULLIF(_PARAM_B, '')
			;
			IF NOT EXISTS(SELECT ua.OsobaGUID FROM `_user_accounts` ua WHERE ua.OsobaGUID = _OsobaGUID) THEN
			--	Brak Konta!!!
				SELECT 
					'Nie można jeszcze zapisać emaila bowiem użytkownik nie ma jeszcze konta! ' AS Actv_Status_Msg,
					'ERR' AS Actv_Status	
				;
			ELSE
			--	Zapis emaila
				UPDATE `_user_accounts` ua
				SET
					/* było 24 III 2021...  
					ua.Status = IF(ua.User_type < 0, 100, ua.Status),
					jest ... */
					ua.Status = ua.Status,
					ua.Ad_Mail = IFNULL(@.ua.Ad_Mail, (@.ua.Ad_Mail := ua.Ad_Mail)),
					-- ua.User_type = ABS(ua.User_type),
					ua.ExtFlags = NULLIF(REPLACE(REPLACE(ua.ExtFlags, '<SetUp.New>', ''), '<SetUp.Reset>', ''), '')
				WHERE
					ua.OsobaGUID = _OsobaGUID
				;
				SELECT 
					'Zmieniono domyślny email użytkownika! ' AS Actv_Status_Msg,
					'OK' AS Actv_Status	
				;
			END IF;
			
		END IF;
		
		IF _MODE IN ('accounts.Kadry.Dodaj.dostep.do.modulu', 'accounts.INTNET.Dodaj.dostep.do.modulu') THEN
			SET
				@.Access_Module = IFNULL(_Value, ''),
				@.create.send.add.module = NOT (_PARAM_E LIKE '%dont.add.module%')
				-- @.create.select.After = (_PARAM_E LIKE '%select%')
			;
			
			-- było CALL _user_accounts_sys_cfg('accounts.add.Access_Module', 0, _OsobaGUID, _Value, IF(@.create.send.add.module, 'SEND.MAIL', ''), '', '', '', 'select');
			CALL _user_accounts_sys_cfg('accounts.2.0.add.Access_Module', 0, _OsobaGUID, _Value, '', '', '', '', IF(@.create.send.add.module, '<SELECT><SEND.MAIL>', '<SELECT>'));
		END IF;
		
		IF _MODE IN ('accounts.Kadry.Odblokuj.Konto', 'accounts.INTNET.Odblokuj.Konto') THEN
			UPDATE `_user_accounts` ua
			SET
				ua.err_logon_count  = 0,
				ua.User_type = ABS(ua.User_type)	-- czy aby na pewno????
				-- ua.Status = 0
			WHERE	
				ua.OsobaGUID = _OsobaGUID
			;
			
			SELECT 
				'Konto użytkownika zostało odblokowane! ' AS Actv_Status_Msg,
				'OK' AS Actv_Status	
			;
			
		END IF;
		
	END IF;
	
	IF _MODE LIKE 'accounts.create.%' THEN
	/* *************************************************************************************************************************************************************
		
		CALL _user_accounts_sys_cfg('accounts.create.exists', 0, osoba, '0', '', '', '', '', '');
		pobierz dane uzytjkownika
		CALL _user_accounts_sys_cfg('accounts.create.select', 0, '{0B8FA759-8126-4141-85DC-8E1CB21A4786}', 'M.WEB.PortaFide.www', '', '', '', '', ''); --	
		_OsobaGUID	osoba
		jmam
		IN _OsobaGUID VARCHAR(38),
		IN _Value VARCHAR(120),
		IN _PARAM_A VARCHAR(200),
		IN _PARAM_B VARCHAR(200),
		IN _PARAM_C VARCHAR(200),
		IN _PARAM_D VARCHAR(200),
		IN _PARAM_E VARCHAR(200)
		
	**************************************************************************************************************************************************************/
		IF _MODE IN ('accounts.create.exists', 'accounts.create.exists.find.by.mail') THEN
			IF _MODE  = 'accounts.create.exists' THEN
			--	Dodaj email na wypadek gdyby nie był pusty 
				UPDATE `_user_accounts` a
				SET
					a.Ad_mail = 
						(
						SELECT 
							kk.adres 
						FROM `kontakty` kk 
						WHERE 
							kk.`osobaGUID` = a.OsobaGUID 
							AND kk.typ_medium = 3 
							AND LOCATE('@', kk.`adres`) > 0 
							AND kk.nieaktywny = 0
						ORDER BY kk.priorytet 
						LIMIT 1
						)
				WHERE
					a.OsobaGUID = _OsobaGUID
					AND
					IFNULL(a.Ad_mail, '') = ''
				;
			END IF;
			DROP TEMPORARY TABLE IF EXISTS `t_accounts_create`;
			CREATE TEMPORARY TABLE `t_accounts_create` (
				`GUID` VARCHAR(38) NOT NULL DEFAULT '',
				`Nazwisko_Imiona` VARCHAR(200) DEFAULT NULL,
				`accounts_exists` BOOLEAN DEFAULT FALSE,
				`Ad_mail` VARCHAR(200) DEFAULT NULL,
				`Access_Module` VARCHAR(200) DEFAULT NULL,
				`Access_Module_Verify` BOOLEAN DEFAULT FALSE,
				`CH_Imie` VARCHAR(200) DEFAULT NULL,
				`CH_Nazwisko` VARCHAR(200) DEFAULT NULL,
				`CH_Rok_Urodzenia` VARCHAR(200) DEFAULT NULL,
				`CH_IdnUser` VARCHAR(200) DEFAULT NULL,
				`CH_Login` VARCHAR(200) DEFAULT NULL,
				`CH_Login_OK` BOOLEAN DEFAULT FALSE,
				`CH_Login_ErrCOUNT` INTEGER DEFAULT 1,
				`CH_IDN` INTEGER DEFAULT 0,
				`CH_IdnUser_equ_Idn` BOOLEAN DEFAULT FALSE,
				PRIMARY KEY (`GUID`)
			)
			;
			--	np. M.WEB.PortaFide.www
			IF _MODE  = 'accounts.create.exists' THEN
			
				SET @.Access_Module = IFNULL(_Value, '');
				SET @.accounts.create.IdnUser.IS.AS.GUID := FALSE;
				INSERT INTO `t_accounts_create`
					(GUID, Nazwisko_Imiona, accounts_exists, Ad_mail, Access_Module, Access_Module_Verify, CH_Imie, CH_Nazwisko, CH_Rok_Urodzenia, CH_IdnUser, CH_IDN, CH_IdnUser_equ_Idn)
					SELECT
						o.GUID,
						CONCAT(o.Nazwisko, ' ', o.Imiona) AS Nazwisko_Imiona,
						(@.accounts.create.exists := EXISTS(SELECT a.idn FROM `_user_accounts` a WHERE a.OsobaGUID = o.GUID AND a.typ = 'SYS')) AS accounts_exists, 
						-- bylo (SELECT kk.adres FROM `kontakty` kk WHERE kk.`osobaGUID` = o.GUID AND kk.typ_medium = 3 AND LOCATE('@', kk.`adres`) > 0 LIMIT 1) AS Ad_mail,
						(@.accounts.create.Ad_mail := '') AS Ad_mail,
						@.Access_Module AS Access_Module,
						IF(@.Access_Module = '',
							TRUE,	--	zawsze wpuszczaj nieokreslona aplikacje czy modul (sytuacja typu np. stare programy)
							IFNULL(
								(SELECT SUM(u.poziom) FROM `uprawnienia` u WHERE u.miejsce LIKE CONCAT(@.Access_Module, '%') AND u.OsobaGUID = o.GUID),
								IFNULL(
									(SELECT MAX(u.poziom) FROM `uprawnienia` u, `grupy_osob` go WHERE go.OsobaGUID = o.GUID AND u.miejsce LIKE CONCAT(@.Access_Module, '%') AND u.OsobaGUID = go.GrupaGUID),
									FALSE
								)
							)
						) AS Access_Module_Verify, 
						o.Imie1 AS CH_Imie, 
						o.Nazwisko AS CH_Nazwisko, 
						IFNULL(YEAR(o.DataUrodzenia), 0) AS CH_Rok_Urodzenia, 
						-- bylo o.IdnUser AS CH_IdnUser,
						IF(@.accounts.create.IdnUser.IS.AS.GUID := ((LENGTH(o.IdnUser) > 36) AND (o.IdnUser LIKE '{%}')),
							o.IdnUser,
							o.IdnUser
						) AS CH_IdnUser,
						o.Idn AS CH_IDN,
						(@.accounts.create.IdnUser_equ_Idn := (o.Idn = o.IdnUser)) AS CH_IdnUser_equ_Idn 
						
					FROM `osoby` o
					WHERE
						o.GUID = _OsobaGUID
				;
				UPDATE `t_accounts_create` ta, `_user_accounts` a
				SET
					ta.Ad_mail = (@.accounts.create.Ad_mail := a.Ad_mail)
				WHERE	
					a.OsobaGUID = ta.GUID 
					AND
					a.typ = 'SYS'
				;
			-- ELSE
			--	Szukaj po mailu
			END IF;

		END IF;
		
		IF _MODE = 'accounts.create.SELECT' THEN
			CALL _user_accounts_sys_cfg('accounts.create.exists', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E); --	
			SELECT
				ta.*,
				a.`login`,
				IF(a.date_to >= '2100-01-01',
					'bez ograniczeń',
					-- było _DATE_FORMAT_Range('', GREATEST(a.date_from,  CURRENT_DATE()), a.date_to, 'MR')
					_Fmt_DateTime_Range(GREATEST(a.date_from,  CURRENT_DATE()), a.date_to, '<MR>')
				) AS DostepOkres,
				a.*
			FROM `t_accounts_create` ta
			LEFT JOIN `_user_accounts` a ON a.OsobaGUID = ta.GUID 
			;
			
		END IF;

		IF _MODE = 'accounts.create.NEW' THEN
			CALL _user_accounts_sys_cfg('accounts.create.exists', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E); --	
			CALL _user_accounts_sys_cfg('accounts.add.Access_Module', 0, _OsobaGUID, _Value, '', '', '', '', '');
			
			IF @.accounts.create.exists THEN
				LEAVE S_user_accounts_sys_cfg;
			END IF;
		--	Sprawdz LOGI powt.	
			IF @session.globals.Owner IN ('PLISZKA') THEN
				CALL _user_accounts_build_login('INIT', _OsobaGUID, @.blabla, '', '');  	
				CALL _user_accounts_build_login('FIND', '', @.t.CH_Login, 'idnuser(5);i1nX(5);i1.nX(5);iXr2;pesel;iXr4', ''); 
				UPDATE `t_accounts_create` t
				SET
					t.CH_Login = @.t.CH_Login,
					t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.t.CH_Login AND a.typ = 'SYS'))
				WHERE	
					NOT t.CH_Login_OK
					-- AND CH_IDN <> CH_IdnUser
				;
			ELSE
				IF _PARAM_A <> '' AND NOT @.accounts.create.IdnUser_equ_Idn AND NOT @.accounts.create.IdnUser.IS.AS.GUID THEN
				--	kilka prob dla Idnuser z osob
				--	1. proba - oczywiscie t.CH_Login_OK	jest FALSE
					UPDATE `t_accounts_create` t
					SET
						t.CH_Login = (@.CH_Login := CONCAT(CH_IdnUser)),
						t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.CH_Login AND a.typ = 'SYS'))
					WHERE	
						NOT t.CH_Login_OK
						AND CH_IDN <> CH_IdnUser
					;
				--	3.4.5.6 proba - z iteracja ale tylko gdy NOT t.CH_Login_OK	
					REPEAT
						UPDATE `t_accounts_create` t
						SET
							t.CH_Login = (@.CH_Login := CONCAT(CH_IdnUser, t.CH_Login_ErrCOUNT)),
							t.CH_Login_ErrCOUNT = (@.t.CH_Login_ErrCOUNT := t.CH_Login_ErrCOUNT + 1),
							t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.CH_Login AND a.typ = 'SYS'))
						WHERE	
							NOT t.CH_Login_OK
						AND CH_IDN <> CH_IdnUser
						;
					UNTIL @.t.CH_Login_OK OR @.t.CH_Login_ErrCOUNT > 6
					END REPEAT;
					
				END IF;
				
			--	1. proba - oczywiscie t.CH_Login_OK	jest FALSE
				UPDATE `t_accounts_create` t
				SET
					-- t.CH_Login = (@.CH_Login := CONCAT(SUBSTR(t.CH_Imie, 1,1), '.',  t.CH_Nazwisko)),
					t.CH_Login = (@.CH_Login := CONCAT_WS('.', NULLIF(SUBSTR(t.CH_Imie, 1, 1), ''), t.CH_Nazwisko)),
					t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.CH_Login AND a.typ = 'SYS'))
				WHERE	
					NOT t.CH_Login_OK
				;
			--	2. proba - z rokiem urodzenia ale tylko gdy NOT t.CH_Login_OK	
				UPDATE `t_accounts_create` t
				SET
					-- t.CH_Login = (@.CH_Login := CONCAT(SUBSTR(t.CH_Imie, 1,1), '.',  t.CH_Nazwisko, t.CH_Rok_Urodzenia)),
					t.CH_Login = (@.CH_Login := CONCAT_WS('.', NULLIF(SUBSTR(t.CH_Imie, 1, 1), ''), t.CH_Nazwisko, t.CH_Rok_Urodzenia)),
					t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.CH_Login AND a.typ = 'SYS')),
					t.CH_Login_ErrCOUNT = 1
				WHERE	
				NOT t.CH_Login_OK
				;
			--	3.4.5.6 proba - z iteracja ale tylko gdy NOT t.CH_Login_OK	
				REPEAT
					UPDATE `t_accounts_create` t
					SET
						-- t.CH_Login = (@.CH_Login := CONCAT(SUBSTR(t.CH_Imie, 1,1), '.',  t.CH_Nazwisko, t.CH_Rok_Urodzenia, t.CH_Login_ErrCOUNT)),
						t.CH_Login = (@.CH_Login := CONCAT_WS('.', NULLIF(SUBSTR(t.CH_Imie, 1, 1), ''), t.CH_Nazwisko, t.CH_Rok_Urodzenia, t.CH_Login_ErrCOUNT)),
						t.CH_Login_ErrCOUNT = (@.t.CH_Login_ErrCOUNT := t.CH_Login_ErrCOUNT + 1),
						t.CH_Login_OK = (@.t.CH_Login_OK := NOT EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = @.CH_Login AND a.typ = 'SYS'))
					WHERE	
						NOT t.CH_Login_OK
					;
				UNTIL @.t.CH_Login_OK OR @.t.CH_Login_ErrCOUNT > 6
				END REPEAT;
			
			END IF;
			
		--	Ten insert zadziala tylko gdy t.CH_Login_OK = TRUE
			INSERT IGNORE INTO `_user_accounts` 
			(OsobaGUID, typ, login, User_type, STATUS)
			SELECT
				t.GUID AS OsobaGUID,
				'SYS' AS typ, 
				t.CH_Login AS Login,
				1 AS User_type,
				0 AS STATUS
			FROM `t_accounts_create` t
			WHERE
				t.CH_Login_OK
			;
		--	Gdy w osobach IdnUser = IDN (cyfrowy) to wstaw do IdnUser login z `_user_accounts ...` 
			UPDATE `_user_accounts` u, `osoby` o
			SET
				o.IdnUser = u.Login
			WHERE	
				o.GUID = _OsobaGUID
				AND o.IdnUser = o.IDN
				AND u.OsobaGUID = o.GUID
			;
		--	... a gdy był w postaci GUIDa (@.accounts.create.IdnUser.IS.AS.GUID = TRUE) ...
		--	to wstaw do IdnUser login z `_user_accounts` 
			UPDATE `_user_accounts` u, `osoby` o
			SET
				o.IdnUser = u.Login
			WHERE	
				o.GUID = _OsobaGUID
				AND u.OsobaGUID = o.GUID
				AND @.accounts.create.IdnUser.IS.AS.GUID
			;
		END IF;
		
		
		
	END IF;

						IF _MODE IN ('t_account_spec.INIT', 't_account_spec.END') THEN
							IF _MODE IN ('t_account_spec.INIT') THEN
								DROP TEMPORARY TABLE IF EXISTS `t_account_spec`;
								CREATE TEMPORARY TABLE `t_account_spec` (
									`IN_Mode` VARCHAR(250),
									`Actv_Mode` VARCHAR(250),
									`Actv_Status` VARCHAR(50),
									`Actv_Status_Msg` MEDIUMTEXT,
									`Actv_IN_ID` VARCHAR(150),
									`Actv_IN_EMail` VARCHAR(150),
									`UserGUID` VARCHAR(250),	-- Przedsiebiorstwo (z Owner lub z Ireg-a)
									`Ad_mail` VARCHAR(200) DEFAULT NULL,
									`Token` VARCHAR(50),
									`Last_Change_Pswd` DATETIME,
									`Datas` VARCHAR(50),
									`Access_Module` VARCHAR(38),
									`Log_Czynnosc` INTEGER,
									-- `ExtFlagsExtFlags` VARCHAR(250),
									PRIMARY KEY (`UserGUID`)
								) ENGINE=MYISAM DEFAULT CHARSET=UTF8
								;
							ELSE
								DROP TEMPORARY TABLE IF EXISTS `t_account_spec`;
							END IF;
						END IF;
						
						IF _MODE IN ('t_account_spec.to.LOG') THEN
						/*
							np. Aktywacja
								CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
								zapomnialem hasla
								CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 404, '', '', '');
							_PARAM_A - miejsce		(100)
							_PARAM_B - czynność
								401, 'Kereowanie konta', 'Kreowanie
								402, 'Email - aktywacja mailowa konta
								403, 'Aktywacja konta i nadanie hasła
								404, 'Email - zapomniane hasło
								405, 'Zmiana hasła z emaila
								410, 'Zablokowanie konta
								411, 'Odblokowanie konta
						*/
							SET 
								@.account.Log.Miejsce = IFNULL(NULLIF(_PARAM_A, ''), 100), 	-- 100 to "Konto użytkownika")
								@.account.Log.Czynnosc = IFNULL(NULLIF(_PARAM_B, ''), 3)
							;
							CREATE TEMPORARY TABLE IF NOT EXISTS `t_log_guids` (guid VARCHAR(38), info TEXT) ENGINE=MYISAM DEFAULT CHARSET=UTF8;
							TRUNCATE `t_log_guids`; 
							INSERT INTO `t_log_guids` 
							SELECT 
								tsa.UserGUID, 
								-- CONCAT_WS('', 
									-- IF(tsa.Actv_Mode = 'Aktywacja', 'Wysłanie maila aktywującego konto - ', 'Zapomniałem hasła - '),
								--	taki MYK aby dostac do zmienne wart. pola Log_Czynnosc
								IF((@.account.Log.Czynnosc := tsa.Log_Czynnosc) IS NULL, 
									tsa.Actv_Status_Msg,
									tsa.Actv_Status_Msg
								)
								-- )
							FROM `t_account_spec` tsa
							;
							CALL log_Insert('INS.Session', @_Idn, '', @.account.Log.Miejsce, @.account.Log.Czynnosc, '', '', '', 'osoby'); -- 100 to "Konto użytkownika")
						END IF;
						
						
	IF _MODE LIKE 'accounts.3.0.%' THEN
	/* *************************************************************************************************************************************************************
		NOWE 3.0 od 1 IV 2021
		Dodawanie/odbieranie dostepu do modulu 
		Aktywacja i reset konta
		oraz
		potw. aktywacji i zmiany hasła
	**************************************************************************************************************************************************************/
		DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash
		IF _MODE LIKE '%zapomnialem%' THEN 
			CALL _Setting_Variables('CHECK', '', '');	-- musze bo w zapomniałem hasła nie mam sesji i małp
		END IF;

	--	Na wstępie podmien _MODE dla aktywacja i zapomnialem
		IF 
		_MODE IN ('accounts.3.0.sent.aktywacja', 'accounts.3.0.sent.zapomnialem') 
		AND NOT (@session.globals.user_accounts.Setup.Pswd.Mode IN ('', 'Token')) THEN
			SET _MODE = CONCAT(_MODE, '.', @session.globals.user_accounts.Setup.Pswd.Mode);
		END IF;
		
		SET 
			@.tui._Mode = _MODE
		;
set @.acc.3.0 = '1';		
		IF _MODE LIKE 'accounts.3.0.%.Access_Module' THEN
			SET @.tui.Access_Module = (@.tui.M.ID := IFNULL(IF(_Value LIKE '%http%', NULL, _Value), ''));
			SET 
				@.tui.Params = CONCAT_WS('&',
					CONCAT('IN_Access_Module=', @.tui.Access_Module)
				)
			;
		END IF;
		--	było IF _MODE IN ('accounts.3.0.sent.aktywacja', 'accounts.3.0.sent.zapomnialem', 'accounts.3.0.sent.2024.aktywacja', 'accounts.3.0.sent.2024.zapomnialem', 'accounts.3.0.sent.') THEN
		IF _MODE LIKE 'accounts.3.0.sent.aktywacja%' OR _MODE LIKE 'accounts.3.0.sent.zapomnialem%' THEN
set @.acc.3.0 = '1.sent.1';
			SET @.tui.Access_Module = (@.tui.M.ID := IFNULL(_Value, ''));
			SET 
				@.tui.Params = CONCAT_WS('&',
					CONCAT('IN_ID=', _OsobaGUID),
					CONCAT('IN_EMail=', IFNULL(_PARAM_B, '')),
					CONCAT('IN_Access_Module=', @.tui.Access_Module)
				)
			;
		END IF;
		
		IF _MODE IN ('accounts.3.0.confirm.passwd.SetUp.New', 'accounts.3.0.confirm.passwd.SetUp.Reset', 'accounts.3.0.confirm.passwd.SetUp.Change') THEN
			/*
			SET 
				@.NEW.datas = NULL,
				@.OLD.user_type = NULL
			;
			SET 
				@.tsa.IN_Token = _OsobaGUID,
				@.tsa.IN_EMail = IFNULL(_PARAM_B, ''),
				@.tsa.IN_Datas = _Value,
				@.tsa.IN_Datas_Old = _PARAM_A,
				@.ta.Actv_Portal = IF(_PARAM_C LIKE '%http%', _PARAM_C, '')	-- po co ?
			;
			*/
			SET 
				@.tui.Params = CONCAT_WS('&',
					CONCAT('IN_Token=', (@.tui.IN_Token := _OsobaGUID)),
					CONCAT('IN_Datas=', (@.tui.IN_Datas := _Value)),
					CONCAT('IN_Datas_Old=', (@.tui.IN_Datas_Old := _PARAM_A))
				)
			;
            IF _MODE IN ('accounts.3.0.confirm.passwd.SetUp.Change') THEN
                set @bla ='';
            END IF;
		END IF;
	--	Inicjacja ....	
		CALL _user_accounts_inf(CONCAT('INSERT.', @.tui._Mode), '', '', @.tui.Params); 
		
		IF _MODE LIKE 'accounts.3.0.%.Access_Module' THEN
		/* *************************************************************************************************************************************************************
			NOWE 3.0
			Dodawanie/odbieranie dostepu do modulu 
			CALL _user_accounts_sys_cfg('accounts.3.0.add.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
			CALL _user_accounts_sys_cfg('accounts.3.0.remove.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
			_OsobaGUID	osoba
			_Value	Access_Module
			jmam
		**************************************************************************************************************************************************************/
			CALL _user_accounts_inf('Find.UserGUID', _OsobaGUID, '', @.tui.Params); 
			-- CALL _user_accounts_inf('<-_user_accounts', '', '', @.tui.Params); 
			

			IF _MODE LIKE '%.remove.%' THEN
				DELETE u FROM `uprawnienia` u, `t_ua_inf` tui2
				WHERE  
					osobaGUID = tui2.UserGUID
					AND miejsce = tui2.IN_Access_Module
				;
				SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
				UPDATE `grupy_osob` go, `t_ua_inf` tui2
				SET
					go.Deleted = 1
				WHERE
					go.osobaGUID = tui2.UserGUID
					AND go.grupaGUID = tui2.IN_Access_Module
				;
				SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
			END IF;
			
			IF _MODE LIKE '%.add.%' THEN
				CALL _sys_app_logtxt('LOG.Session.Add', @SYSTEM.Client.Session.GUID, 'CMD', '', '', 'PHP', '', '', 'Wchodzę do dodawania modułu ... ');			
				INSERT IGNORE INTO `uprawnienia`
				(login, miejsce, poziom, rodzaj, opis, ValueList, core_id, upr_type, osobaGUID)
				SELECT
					CONCAT(':', IFNULL(a.Login, o.IdnUser)) AS login,
					tui2.IN_Access_Module AS miejsce, 
					1 AS poziom, 
					ud.rodzaj, 
					ud.opis,
					ud.ValueList,
					ud.core_id, 
					ud.upr_type,
					o.GUID AS osobaGUID
				FROM `t_ua_inf` tui2
				INNER JOIN `osoby` o ON o.GUID = tui2.UserGUID
				INNER JOIN `uprawnienia_dict` ud ON ud.miejsce  = tui2.IN_Access_Module
				LEFT JOIN `_user_accounts` a ON a.osobaGUID = o.GUID AND typ = 'SYS'
				WHERE
					TRUE -- o.GUID = _OsobaGUID
				ON DUPLICATE KEY UPDATE
					poziom = 1
				; 
				SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
			--	Z upr. juz nie korzystamy zatem ... dla bezp. wstawiam 1 kę
				SET @.accounts.add.Access_Module.UPR.ROW_COUNT = 1;
				
				INSERT IGNORE INTO `grupy_osob`
				(OsobaGUID, grupaGUID)
				SELECT
					tui2.UserGUID AS OsobaGUID,
					tui2.IN_Access_Module AS grupaGUID
				FROM `t_ua_inf` tui2 
				ON DUPLICATE KEY UPDATE
					Deleted = 0
				;
				SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
			--	Dodatkowo na prośbę pośr. Grzesia 22 II 2023 ...
			--	ze względu na VIEW osób np. w SECURITY osoby nie są dodawan z samym sobą i z ALL
			--	User <-> ALL
				INSERT IGNORE INTO `grupy_osob`
				(OsobaGUID, grupaGUID)
				SELECT
					tui2.UserGUID AS OsobaGUID,
					'ALL' AS grupaGUID
				FROM `t_ua_inf` tui2 
				;
			--	User <-> User
				INSERT IGNORE INTO `grupy_osob`
				(OsobaGUID, grupaGUID)
				SELECT
					tui2.UserGUID AS OsobaGUID,
					tui2.UserGUID AS grupaGUID
				FROM `t_ua_inf` tui2 
				;
				
			END IF;
		--	Wysłac powiadomienie ?
			CALL _sys_app_logtxt('LOG.Session.Add', @SYSTEM.Client.Session.GUID, 'CMD', '', '', 'PHP', '', '', 
				CONCAT_WS(' / ',
					'Sprawdzam warunki do wysylki maila ...',
					CONCAT_WS('', 'RC.AcMod = ', @.accounts.add.Access_Module.ROW_COUNT), 
					CONCAT_WS('', 'RC.Upr = ', @.accounts.add.Access_Module.UPR.ROW_COUNT),
					CONCAT_WS('', '_PARAM_E = ', _PARAM_E),
					CONCAT_WS('', '_MODE = ', _MODE) 
				)
			);			
		
			IF 
				@.accounts.add.Access_Module.ROW_COUNT > 0
				-- AND (_PARAM_E LIKE '%<SEND.MAIL>%' OR _PARAM_E = 'mail')
				AND _PARAM_E LIKE '%<SEND.MAIL>%'
				AND _MODE LIKE '%.add.%'
				AND (@.accounts.add.Access_Module.ROW_COUNT + @.accounts.add.Access_Module.UPR.ROW_COUNT > 0)
			THEN
				CALL _sys_app_logtxt('LOG.Session.Add', @SYSTEM.Client.Session.GUID, 'CMD', '', '', 'PHP', '', '', 'Wchodzę do wysylki maila ... ');			
				CALL _user_accounts_sys_cfg('Moduly.Send.Info.2.User.Dostep', 0, _OsobaGUID, @.tui.Access_Module, '1', '', '', '', '');
			END IF;
			
			SELECT
				CONCAT_WS('&',
					CONCAT('Oper_Status=', IF(@.accounts.add.Access_Module.ROW_COUNT + @.accounts.add.Access_Module.UPR.ROW_COUNT > 0, 'OK', 'ERR')
					),
					CONCAT_WS('',
						'Oper_Status_Msg=',
						IF(@.accounts.add.Access_Module.ROW_COUNT + @.accounts.add.Access_Module.UPR.ROW_COUNT > 0,
						--	Udało się dodac/usunąć
							IF(tui2.Oper_Mode = '<Access_Module.ADD>',
								'Pomyślnie dodano dostęp użytkownika do modułu/aplikacji: ',
								'Usunięto dostęp użytkownika do modułu/aplikacji: '
							),
						--	Nie udało się dodac/usunąć
							IF(tui2.Oper_Mode = '<Access_Module.ADD>',
								'Użytkownik ma już dostęp do modułu/aplikacji: ',
								'Użytkownik nie ma dostępu do modułu/aplikacji: '
							)
						),
						'\n',
						IFNULL(_VarStr(c.Caption), _VarStr(tui2.IN_Access_Module)),
						'!',
						'\nAktualnie użytkownik ma dostęp do nast. aplikacji:\n',
						IFNULL(
						(
							SELECT GROUP_CONCAT(DISTINCT _VarStr(cN.Caption) SEPARATOR ' + ') AS Moduly 
							FROM `grupy_osob` go, `sys_core` cN
							WHERE
								go.OsobaGUID = tui2.UserGUID
								AND go.GrupaGUID LIKE 'M.%'
								AND go.Deleted = 0 
								AND (Get_Status_For_Valid_From_To('GET', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') = 'OK')
								AND cN.GUID = go.GrupaGUID
						), '(brak modułów)'
						)
					)
				) AS Access_MODULE_Params
			INTO
				@.Access_MODULE.Params	-- do ponizszego calla 
			FROM `t_ua_inf` tui2, `sys_core` c
			WHERE
				c.GUID = tui2.IN_Access_Module 
			;
		--	Statusy koncowe
			CALL _user_accounts_inf('Summary', '', '', @.Access_MODULE.Params); 
		--	Select koncowy ?
			set @._PARAM_E = _PARAM_E;
			IF (_PARAM_E LIKE '%<select>%') THEN
				CALL _user_accounts_inf('<select>', '', '', @.Nic); 
			END IF;
		--	LOG
			CALL _user_accounts_inf('to.LOG', '', '', @.tui.Params); 
			-- CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
		--	Drop	
			-- CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');

			LEAVE S_user_accounts_sys_cfg;
			
		END IF; -- IF _MODE LIKE 'accounts.3.0.%.Access_Module' 
		
		--	było IF _MODE IN ('accounts.3.0.sent.aktywacja', 'accounts.3.0.sent.zapomnialem', 'accounts.3.0.sent.2024.aktywacja', 'accounts.3.0.sent.2024.zapomnialem') THEN
		IF _MODE LIKE 'accounts.3.0.sent.aktywacja%' OR _MODE LIKE 'accounts.3.0.sent.zapomnialem%' THEN
		/* *************************************************************************************************************************************************************
			Gdy aktywujemy pierwszy raz konto lub
			gdy zapomnielismy hasla
			CALL _user_accounts_sys_cfg('accounts.2.0.sent.aktywacja', 0, osobaGUID, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
			CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, osobaGUID, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
			CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, login, '', '', '', '', '', '<select>');
			CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, email, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
			_OsobaGUID		osoba jako OsobaGUID (dla aktywacja) lub 
							(dla zapomnialem hasla)
							jako login - wtedy 
							jako email - jest mailem !!! - postaci: LIKE '%@%'
			IN _Value 		modul
			IN _PARAM_A		login	-- po co??
			IN _PARAM_B 	email
			IN _PARAM_C 	Actv_Portal
			IN _PARAM_E		Gdy zawiera Select to select
			
			
			_Value		email aktywacyjny
			_PARAM_A	Debug np.
			_PARAM_B	link do strony systemu np. Porta fide lub KEY do Rega do linka strony !!!!
			jmam
		**************************************************************************************************************************************************************/
set @.acc.3.0 = '1.sent.2';		
		--	Szukaj user wg...
			CALL _user_accounts_inf('Find.UserGUID', '', '', @.tui.Params); 
		--	Teraz ustaw param. konta o ile istnieje jesli nie istnieje to badzie tam nadal 'ERR.NO.USER'
			-- CALL _user_accounts_inf('<-_user_accounts', '', '', @.tui.Params); 
		--	Teraz pods. statusów
			-- CALL _user_accounts_inf('Summary', '', '', @.tui.Params); 
set @.acc.3.0 = '1.IF...1';		
			
			IF @.tuai.Oper_Status LIKE 'OK%' THEN
			--	OK moge zaczynać
				SET @.tui.Auto.Datas = NULL;
set @.acc.3.0 = '1.2. UPDA ua';		
				UPDATE `_user_accounts` ua, `t_ua_inf` tui2
				SET
					ua.user_type = 
						IF(tui2.Oper_Mode = '<SetUp.New>',
							-ABS(ua.user_type),
							ua.user_type
						),
					ua.datas = 
						IF(tui2.Oper_Mode LIKE '<Sent.%.Auto.%Pswd%', 
						--	9 znakowe nowe hasło	
							_VarStr(MD5(@.tui.Auto.Datas := _user_accountsF('GetPSWD', NULL, 9, '', '', '', ''))), 
							ua.datas
						),
					ua.ExtFlags	= 
						CONCAT_WS('', 
							NULLIF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ua.ExtFlags, 
								tui2.Oper_Mode, ''), 
								'<Sent.aktywacja.Auto.Pswd>', ''), 
								'<Sent.aktywacja.Auto.TmpPswd>', ''), 
								'<Sent.zapomnialem.Auto.Pswd>', ''), 
								'<Sent.zapomnialem.Auto.TmpPswd>', ''), 
								'<SetUp.New>', ''), 
								'<SetUp.Reset>', ''),
							''), 
							tui2.Oper_Mode
						)
				WHERE
					tui2.Oper_Status LIKE 'OK%'
					AND ua.OsobaGUID = tui2.UserGUID AND ua.typ = 'SYS'
				;	
			--	Pocz. maila ...	
			/*	było do VII 2024
				SET @_Params = 'Sender_Name=Dział kadr';
			--	19 II 2024 Na prosbe apro do param dodaje sendera (kadrowy)	
				SELECT 	
					CONCAT_WS('&',
						-- oi.MAIL_FROM_system,
						CONCAT('Sender_Mail=', oi.MAIL_FROM_accounts_system),
						IF(tui2.Oper_Mode = '<SetUp.PSWD.Init>', 
							_VarStr('Sender_Name=Dział kadr'),
							IF(tui2.Oper_Mode = '<SetUp.PSWD.Reset>', 
								_VarStr('Sender_Name=Dział techniczny'),
								IF(tui2.Oper_Mode = '<SetUp.New>', 
									_VarStr('Sender_Name=Dział kadr'),
									_VarStr('Sender_Name=Dział kadr')
						))),
						CONCAT('Param1=', @.tui.Datas)
					)
				INTO 
					@_Params
				FROM `owner_info` oi, `t_ua_inf` tui2
				;
				-- CALL send_mail('Init', 'Mail_aktywujacy', 'Firmowy', @.tsa.M.ID, '', '', '', @_Params);
				CALL send_mail('Init', 'Mail_aktywujacy', 'MAIL_FROM_system', @.tsa.M.ID, '', '', '', @_Params);
				UPDATE `t_send_mail_inf` ti, `t_ua_inf` tui2
				SET
					ti.IN_MODE = 
						IF(tui2.Oper_Mode = '<SetUp.PSWD.Init>', 
							'ua.Mail.pswd.Init', 
							IF(tui2.Oper_Mode = '<SetUp.PSWD.Reset>', 
								'ua.Mail.pswd.Reset',
								IF(tui2.Oper_Mode = '<SetUp.New>', 
									'Mail_aktywujacy', 
									'Mail_zapomnialem_hasla'
						))),
					-- bylo ti.Modul_ID = NULLIF(_Value, '')
					ti.Modul_ID = NULLIF(@.tui.Access_Module, '')
				;
			jest ...	*/
				SET @_Params = NULL; -- juz nie potrzebne @_Params w INIT
set @.acc.3.0 = '1.2. send_mail Init';		
				CALL send_mail('Init', 'Mail_aktywujacy', 'MAIL_FROM_system', @.tsa.M.ID, '', '', '', @_Params);
set @.acc.3.0 = '1.2. update t_send_mail_inf';		
				UPDATE `t_send_mail_inf` ti, `owner_info` oi, `t_ua_inf` tui2
				SET
					ti.IN_MODE = 
						IF(tui2.Oper_Mode LIKE '<Sent.%.Auto.%Pswd%', 
							tui2.Oper_Mode,
							/*
						IF(tui2.Oper_Mode IN ('<Sent.aktywacja.Auto.Pswd>','<Sent.aktywacja.Auto.TmpPswd>'),
							'ua.Mail.pswd.Init', 
							IF(tui2.Oper_Mode IN ('<Sent.zapomnialem.Auto.Pswd>','<Sent.zapomnialem.Auto.TmpPswd>'), 
								'ua.Mail.pswd.Reset',
							*/
							IF(tui2.Oper_Mode = '<SetUp.New>', 
								'Mail_aktywujacy', 
								'Mail_zapomnialem_hasla'
							)
						),
					ti.Sender_Mail = oi.MAIL_FROM_accounts_system,
					ti.Sender_Name =
						IF(tui2.Oper_Mode IN ('<Sent.aktywacja.Auto.Pswd>','<Sent.aktywacja.Auto.TmpPswd>'),
							_VarStr('Dział kadr'),
							IF(tui2.Oper_Mode IN ('<Sent.zapomnialem.Auto.Pswd>','<Sent.zapomnialem.Auto.TmpPswd>'), 
								_VarStr('Dział techniczny'),
								IF(tui2.Oper_Mode = '<SetUp.New>', 
									_VarStr('Dział kadr'),
									_VarStr('Dział kadr')
						))),
					-- bylo ti.Modul_ID = NULLIF(_Value, '')
					ti.Modul_ID = NULLIF(@.tui.Access_Module, ''),
					ti.Param_Welcome = 'Dzień dobry',
					ti.Param1 = IF(tui2.Oper_Mode LIKE '<Sent.%.Auto.%Pswd%', @.tui.Auto.Datas, ti.Param1)
				;
			/* zanim nie dodasz pola Prog_HREF_cfg
				SET @.Prog_HREF_cfg = NULL;
				SELECT
					ar.Prog_HREF_cfg
				INTO 
					@.Prog_HREF_cfg
				FROM `_sys_app_reg` ar, `t_send_mail_inf` ti 
				WHERE 
					ar.ID = ti.Modul_ID
				;
			*/
				IF @.Prog_HREF_cfg IS NULL THEN	
				--	Starsze!!!
				CALL _IReg_Get('', 'URL_Link_Mail_aktywujacy', 0, 'MEMO', 
					@.DevelopStuff.CentrumIntNet.URL, 
					'https://intdevel.int.com.pl:56491/CentrumIntNet/confirm.php?#ACT=#&nsv=#TOKEN#');
			--	UWAGA do @.DevelopStuff.CentrumIntNet.URL doklej wstawkę z wersja obsł. okna aktywizacji (Ja+Grześ 24-02-2021)	
				-- SET @.DevelopStuff.CentrumIntNet.URL = CONCAT_WS('&', @.DevelopStuff.CentrumIntNet.URL, 'ver=2.0');
				SET @.DevelopStuff.CentrumIntNet.URL = 
					CONCAT_WS('&', @.DevelopStuff.CentrumIntNet.URL,
						IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&klient_id=%', NULL, CONCAT('klient_id=', @session.globals.Owner)),
						IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&db_name=%', NULL, CONCAT('db_name=', SCHEMA())),
						IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&ver=%', NULL, 'ver=2.0')
					)
				;	
				SET @.Prog_HREF_cfg = @.DevelopStuff.CentrumIntNet.URL;
				ELSE
					SET 
						@.Prog_HREF_cfg = 
							CONCAT_WS('&', 
								@.Prog_HREF_cfg,
								IF(@.Prog_HREF_cfg LIKE '%&klient_id=%', NULL, CONCAT('klient_id=', @session.globals.Owner)),
								IF(@.Prog_HREF_cfg LIKE '%&db_name=%', NULL, CONCAT('db_name=', SCHEMA())),
								IF(@.Prog_HREF_cfg LIKE '%&ver=%', NULL, 'ver=2.0')
							)
					;
				END IF;
				TRUNCATE `t_send_mail`;
				INSERT IGNORE INTO `t_send_mail`
				(Send_Mode, Recip_GUID, Msg_Title, Msg_Body_Link, Token, Param_Welcome, Param1)
				SELECT 
					-- SendGUID = _Get_ID_xxxxx('SHORT', 38, 'send_mail.', '', '', NULL, NULL, NULL),
					tui2.Oper_Mode AS Send_Mode,
					tui2.UserGUID AS Recip_GUID,
					IF(tui2.Oper_Mode IN ('<SetUp.New>','<Sent.aktywacja.Auto.Pswd>','<Sent.aktywacja.Auto.TmpPswd>'), 
						'Aktywacja konta do systemu Motława.', 
						'Zapomniałem hasła!') AS Msg_Title,
					REPLACE(REPLACE(REPLACE(REPLACE(@.Prog_HREF_cfg,
						'#ACT=#',
							IF(tui2.Oper_Mode = '<SetUp.New>', 
								'ACT=SetUp.New', 
								'ACT=SetUp.Reset'
							)
						),
						'#klient_id#', @session.globals.Owner),
						'#SCHEMA#', SCHEMA()),
						'#ver#', '2.0')
					AS Msg_Body_Link,
					-- MD5(CONCAT(tui.UserGUID, tsa.Ad_mail)) AS Token,
					tui2.IN_Token AS Token,
					-- było 'Dzień dobry' AS Param_Welcome,
					NULL AS Param_Welcome,
					NULL AS Param1
				FROM `t_ua_inf` tui2
				WHERE
					tui2.Oper_Status LIKE 'OK%'
				;
				
				-- CALL send_mail('Prepare', '', '', '', '', '', '', '');
				CALL send_mail('Send', '', '', '', '', '', '', '');
			END IF;
			/*
			UPDATE `t_ua_inf` tui2
			SET
				tui2.Oper_Status_Msg = 
					IF(tui2.Oper_Mode = '<SetUp.New>',
						CASE 
						WHEN tui2.Oper_Status = 'ERR.Empty.Email' THEN 
							'Brak takiego konta użytkownika'
						WHEN tui2.Oper_Status = 'ERR.Unknown.Email' THEN 
							'Próba aktywacji konta z nieznanego adresu mailowego!'
						WHEN tui2.Oper_Status LIKE 'ERR.%' THEN 
							tsa.Account_Status_Msg
						ELSE
							'Aktywacja konta - wysłany został mail do użytkownika w którym będzie link do okna ustawienia hasła.'
						END
					,
						CASE 
						WHEN tui2.Oper_Status = 'ERR.DISABLED.Zapomnialem' THEN 
							'Funkcja jest niedostępna w systemie!'
						WHEN tui2.Oper_Status = 'ERR.Empty.Email' THEN 
							'Niepoprawny login lub brak adresu e-mial na Twoim koncie. \nKoniecznie skontaktuj sie z administratorem w celu zmiany lub uzupełnienia danych.'
						WHEN tui2.Oper_Status = 'ERR.Unknown.Email' THEN 
							'Próba aktywacji konta z nieznanego adresu mailowego!'
						WHEN tui2.Oper_Status LIKE 'ERR.%' THEN 
							tsa.Account_Status_Msg
						ELSE
							'Odbierz mail wysłany na podany w systemie adres w którym będzie link do okna ustawienia hasła.\nUWAGA! Operacja zmiany hasła z danego maila jest jednorazowa!'
						END
					)
			;
			*/
			
		--	Select koncowy ?
			set @._PARAM_E = _PARAM_E;
			IF (_PARAM_E LIKE '%<select>%') THEN
				CALL _user_accounts_inf('<select>', '', '', @.Nic); 
			END IF;
		--	LOG
			CALL _user_accounts_inf('to.LOG', '', '', @.tui.Params); 
			-- CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
		--	Drop	
			-- CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');

			LEAVE S_user_accounts_sys_cfg;

			
			
		END IF;

		IF _MODE IN ('accounts.3.0.confirm.passwd.SetUp.New', 'accounts.3.0.confirm.passwd.SetUp.Reset', 'accounts.3.0.confirm.passwd.SetUp.Change') THEN
		/* *************************************************************************************************************************************************************
			Potwierdzenie hasla z Tokenem
			CALL _user_accounts_sys_cfg('confirm.2.0.passwd.SetUp.New', 0, Token, PSWD, '', '', '', '', '');
			CALL _user_accounts_sys_cfg('ssss', 0, Token, PSWD, '', '', '', '', '');
			_OsobaGUID	
						Token dla NIE 'confirm.2.0.passwd.SetUp.Change'
						UserGUID/Login ??????????  dla 'confirm.2.0.passwd.SetUp.Change'
			_Value		PSWD#
			_PARAM_A	stare PSWD#
			jmam
			CALL _user_accounts_sys_cfg('accounts.3.0.confirm.passwd.SetUp.Change', 0, UserGUID, PSWD, '', '', '', '', '');
		**************************************************************************************************************************************************************/
set @.acc.3.0 = '1.confirm.1';		
		set @._PARAM_E = _PARAM_E;
		--	Szukaj user wg...
			CALL _user_accounts_inf('Find.UserGUID', '', '', @.tui.Params); 
		--	Teraz ustaw param. konta o ile istnieje jesli nie istnieje to badzie tam nadal 'ERR.NO.USER'
			-- CALL _user_accounts_inf('<-_user_accounts', '', '', @.tui.Params); 
		--	Teraz pods. statusów
			-- CALL _user_accounts_inf('Summary', '', '', @.tui.Params); 
		
		--	... dla _MODE IN ('confirm.2.0.passwd.SetUp.Change') czyli Oper_Mode = '<Change>'	
			UPDATE `_user_accounts` ua, `t_ua_inf` tui2
			SET
			--	UWAGA gdy mamy w @.tsa.Actv_Status = 'ERR.PSWD' to traktujemy to jak błędne logowanie musimy zwiekszyć licznik błędnych logowań (err_logon_count)
				ua.err_logon_count = 
					IF(tui2.Oper_Status = 'ERR.PSWD', 
						ua.err_logon_count + 1, 
					--	zlokalizowano OK	
						ua.err_logon_count
					)
			WHERE	
				ua.OsobaGUID = tui2.UserGUID
				AND ua.typ = 'SYS'
				AND tui2.Oper_Mode = '<Change>'
			;
set @.acc.3.0 = '1.confirm.2';		
			
			IF @.tuai.Oper_Status LIKE 'OK%' THEN
			--	OK moge zaczynać
				UPDATE `_user_accounts` ua, `t_ua_inf` tui2
				SET
					ua.Status = IF(ua.Status = 100, 0, ua.Status), 	-- 24 III 2021 - zabez. bo kiedys bo ło wstawiane 100 - za pół roku to zdejmij jesli nie ma kont z Status = 100
					ua.Last_Change_Pswd = IF(ua.datas <=> tui2.IN_datas, ua.Last_Change_Pswd, NOW()),
					ua.datas = tui2.IN_datas,
					ua.user_type = ABS(ua.user_type),
					ua.ExtFlags	= 
						NULLIF(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ua.ExtFlags, 
							'<Sent.aktywacja.Auto.Pswd>', ''), 
							'<Sent.aktywacja.Auto.TmpPswd>', ''), 
							'<Sent.zapomnialem.Auto.Pswd>', ''), 
							'<Sent.zapomnialem.Auto.TmpPswd>', ''), 
							'<SetUp.New>', ''), 
							'<SetUp.Reset>', ''),
							'<Empty.PSWD>', ''),
						''),
					
					-- ua.ExtFlags = NULLIF(REPLACE(REPLACE(REPLACE(ua.ExtFlags, '<SetUp.New>', ''), '<SetUp.Reset>', ''), '<Empty.PSWD>', ''), ''),
					ua.err_logon_count = 0 
				WHERE	
					ua.OsobaGUID = tui2.UserGUID
					AND ua.typ = 'SYS'
					AND tui2.Oper_Status LIKE 'OK%'
				;
			--	Dodatkowo wyślij wiszące maile ze statusem 'HOLD_FOR_ACTIVATION'	
			--	ALE tylko dla Inicjacja/po Zapomnialem hasla
				UPDATE `com_msg_ng` cn, `com_msg_po` cp, `_user_accounts` ua, `t_ua_inf` tui2
				SET
					cn.Status = 'NEW'
				WHERE
				--	Tylko dla Inicjacja/po Zapomnialem hasla
					tui2.Oper_Mode IN  ('<confirm.SetUp.New>', '<confirm.SetUp.Reset>')
					AND ua.OsobaGUID = tui2.UserGUID
					AND ua.typ = 'SYS'
					AND tui2.Oper_Status LIKE 'OK%'
					AND cp.Recipient = ua.Ad_mail AND cp.Medium_Type = 'mail' AND cp.Type = 'OUT'
					AND cn.GUID = cp.GUIDNg AND cn.Status = 'HOLD_FOR_ACTIVATION'
				;
			END IF;
			-- set @._PARAM_E1 = NULL;
		--	Select koncowy ?
			set @._PARAM_E = _PARAM_E;
			IF (_PARAM_E LIKE '%<select>%') THEN
				CALL _user_accounts_inf('<select>', '', '', @.Nic); 
			END IF;
			
			LEAVE S_user_accounts_sys_cfg;
		--	LOG
			CALL _user_accounts_inf('to.LOG', '', '', @.tui.Params); 
			-- CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
		--	Drop	
			-- CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');
			
			LEAVE S_user_accounts_sys_cfg;

		END IF;
		
	END IF; 	-- accounts.3.0.%
	
	
	IF _MODE LIKE 'accounts.2.0.%.Access_Module' THEN
	/* *************************************************************************************************************************************************************
		NOWE 2.0
		Dodawanie/odbieranie dostepu do modulu 
		CALL _user_accounts_sys_cfg('accounts.2.0.add.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('accounts.2.0.remove.Access_Module', 0, osoba, 'M.WEB.PortaFide.www', '', '', '', '', '');
		_OsobaGUID	osoba
		_Value	Access_Module
		jmam
	**************************************************************************************************************************************************************/
		IF @.accounts.3.0 THEN
			CALL _user_accounts_sys_cfg(REPLACE(_MODE, '2.0', '3.0'), _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
			LEAVE S_user_accounts_sys_cfg;
		END IF;

/*		DALEJ WON!!!!!!!!!!!!!!!!!!	*/		



		
		
		SET 
			@.tsa._Mode = _MODE,
			@.tsa.Access_Module = (@.tsa.M.ID := IFNULL(_Value, ''))
		;
		CALL _user_accounts_sys_cfg('t_account_spec.INIT', 0, '', '', '', '', '', '', '');
		TRUNCATE `t_account_spec`;
		INSERT IGNORE INTO `t_account_spec`
		SET
			IN_Mode = @.tsa._Mode,
			UserGUID = _OsobaGUID,
			Access_Module = @.tsa.Access_Module,
			Actv_Mode = IF(@.tsa._Mode LIKE '%.add.%', 'ADD', IF(@.tsa._Mode LIKE '%.remove.%', 'DEL', '???')),
			Actv_Status = (@.tsa.Actv_Status := 'OK')
		;
		IF _MODE LIKE '%.remove.%' THEN
			DELETE u FROM `uprawnienia` u, `t_account_spec` tsa
			WHERE  
				osobaGUID = tsa.USERGUID
				AND miejsce = tsa.Access_Module
			;
			SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
			UPDATE `grupy_osob` go, `t_account_spec` tsa
			SET
				go.Deleted = 1
			WHERE
				go.osobaGUID = tsa.USERGUID
				AND go.grupaGUID = tsa.Access_Module 
			;
			SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
		END IF;
		
		IF _MODE LIKE '%.add.%' THEN
			INSERT IGNORE INTO `uprawnienia`
			(login, miejsce, poziom, rodzaj, opis, ValueList, core_id, upr_type, osobaGUID)
			SELECT
				CONCAT(':', IFNULL(a.Login, o.IdnUser)) AS login,
				tsa.Access_Module AS miejsce, 
				1 AS poziom, 
				ud.rodzaj, 
				ud.opis,
				ud.ValueList,
				ud.core_id, 
				ud.upr_type,
				o.GUID AS osobaGUID
			FROM `t_account_spec` tsa
			INNER JOIN `osoby` o ON o.GUID = tsa.USERGUID
			INNER JOIN `uprawnienia_dict` ud ON ud.miejsce  = tsa.Access_Module
			LEFT JOIN `_user_accounts` a ON a.osobaGUID = o.GUID AND typ = 'SYS'
			WHERE
				TRUE -- o.GUID = _OsobaGUID
			ON DUPLICATE KEY UPDATE
				poziom = 1
			; 
			SET @.accounts.add.Access_Module.UPR.ROW_COUNT = ROW_COUNT();
			
			INSERT IGNORE INTO `grupy_osob`
			(OsobaGUID, grupaGUID)
			SELECT
				tsa.USERGUID AS OsobaGUID,
				tsa.Access_Module AS grupaGUID
			FROM `t_account_spec` tsa
			ON DUPLICATE KEY UPDATE
				Deleted = 0
			;
			SET @.accounts.add.Access_Module.ROW_COUNT = ROW_COUNT();
		END IF;
	--	Wysłac powiadomienie ?
		IF 
			@.accounts.add.Access_Module.ROW_COUNT > 0
			AND _PARAM_E LIKE '%<SEND.MAIL>%' 
		THEN
			CALL _user_accounts_sys_cfg('Moduly.Send.Info.2.User.Dostep', 0, _OsobaGUID, @.tsa.Access_Module, '1', '', '', '', '');
		END IF;
		
		UPDATE `t_account_spec` tsa, `sys_core` c
		SET
			tsa.Log_Czynnosc = 
				IF(tsa.Actv_Mode = 'ADD', 415, IF(tsa.Actv_Mode = 'DEL', 416, 3)),
			tsa.Actv_Status_Msg = 
				CONCAT_WS('',
					IF(@.accounts.add.Access_Module.ROW_COUNT + @.accounts.add.Access_Module.UPR.ROW_COUNT > 0,
					--	Udało się dodac/usunąć
						IF(Actv_Mode = 'ADD',
							'Pomyślnie dodano dostęp użytkownika do modułu/aplikacji: ',
							'Usunięto dostęp użytkownika do modułu/aplikacji: '
						),
					--	Nie udało się dodac/usunąć
						IF(Actv_Mode = 'ADD',
							'Użytkownik ma już dostęp do modułu/aplikacji: ',
							'Użytkownik nie ma dostępu do modułu/aplikacji: '
						)
					),
					'\n',
					IFNULL(c.Caption, tsa.Access_Module),
					'!',
					'\nAktualnie użytkownik ma dostęp do nast. aplikacji:\n',
					IFNULL(
					(
						SELECT GROUP_CONCAT(DISTINCT cN.Caption SEPARATOR ' + ') AS Moduly 
						FROM `grupy_osob` go, `sys_core` cN
						WHERE
							go.OsobaGUID = tsa.UserGUID
							AND go.GrupaGUID LIKE 'M.%'
							AND go.Deleted = 0 
							AND (Get_Status_For_Valid_From_To('GET', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, '', '', '') = 'OK')
							AND cN.GUID = go.GrupaGUID
					), '(brak modułów)'
					)
				)
			-- tsa.Actv_Status = 'OK'
		WHERE
			c.GUID = tsa.Access_Module 
		;
				
	--	Select koncowy ?
		IF (_PARAM_E LIKE '%<select>%') THEN
			SELECT * FROM `t_account_spec`;
		END IF;
	--	LOG
		CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
	--	Drop	
		-- CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');

		LEAVE S_user_accounts_sys_cfg;
		
	END IF;
	-- @.Access_Module 

	IF _MODE IN ('accounts.2.0.sent.aktywacja', 'accounts.2.0.sent.zapomnialem', 'accounts.2.0.sent.') THEN
	/* *************************************************************************************************************************************************************
		Gdy aktywujemy pierwszy raz konto lub
		gdy zapomnielismy hasla
		CALL _user_accounts_sys_cfg('accounts.2.0.sent.aktywacja', 0, osobaGUID, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
		CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, osobaGUID, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
		CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, login, '', '', '', '', '', '<select>');
		CALL _user_accounts_sys_cfg('accounts.2.0.sent.zapomnialem', 0, email, 'M.WEB.PortaFide.www', '', 'jmam68@gmail.com', '', '', '<select>');
		_OsobaGUID		osoba jako OsobaGUID (dla aktywacja) lub 
						(dla zapomnialem hasla)
						jako login - wtedy 
						jako email - jest mailem !!! - postaci: LIKE '%@%'
		IN _Value 		modul
		IN _PARAM_A		login	-- po co??
		IN _PARAM_B 	email
		IN _PARAM_C 	Actv_Portal
		IN _PARAM_E		Gdy zawiera Select to select
		
		
		_Value		email aktywacyjny
		_PARAM_A	Debug np.
		_PARAM_B	link do strony systemu np. Porta fide lub KEY do Rega do linka strony !!!!
		jmam
	**************************************************************************************************************************************************************/
	
		IF @.accounts.3.0 THEN
			CALL _user_accounts_sys_cfg(REPLACE(_MODE, '2.0', '3.0'), _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
			LEAVE S_user_accounts_sys_cfg;
		END IF;

/*		DALEJ WON!!!!!!!!!!!!!!!!!!	*/		



		
		
		SET 
			@.tui.Params = CONCAT_WS('&',
				CONCAT('IN_ID=', _OsobaGUID),
				CONCAT('IN_EMail=', IFNULL(_PARAM_B, '')),
				CONCAT('IN_Access_Module=', (@.Access_Module := IF(_Value LIKE '%http%', NULL, _Value)))
			)
		;
		
		SET 
			@.tsa._Mode = _MODE,
			@.tsa.AnyID = _OsobaGUID,
			@.tsa.IN_EMail = IFNULL(_PARAM_B, ''),
			@.tsa.M.ID = (@.Access_Module := IF(_Value LIKE '%http%', NULL, _Value)),
			-- @.tsa.Aktywacja = (_MODE = 'accounts.sent.aktywacja'),
			-- @.tsa.Zapomnialem.hasla = (_MODE = 'accounts.sent.zapomnialem'),
			@.ta.Actv_Portal = IF(_PARAM_C LIKE '%http%', _PARAM_C, '')	-- po co ??????????????
		;
		
		CALL _user_accounts_sys_cfg('t_account_spec.INIT', 0, '', '', '', '', '', '', '');

		TRUNCATE `t_account_spec`;
		INSERT IGNORE INTO `t_account_spec`
		SET
			IN_Mode = @.tsa._Mode,
			Actv_Mode = IF(@.tsa._Mode LIKE '%sent.aktywacja%', 'Aktywacja', IF(@.tsa._Mode LIKE '%sent.zapomnialem%', 'Zapomnialem', '???')),
			-- Actv_Mode = IF(@.tsa._Mode LIKE '%sent.aktywacja%', '<SetUp.New>', IF(@.tsa._Mode LIKE '%sent.zapomnialem%', '<SetUp.Reset>', '???')),
			Actv_Status = (@.tsa.Actv_Status := 'ERR.NO.USER'),
			Actv_IN_ID = @.tsa.AnyID,
			Actv_IN_EMail = IFNULL(@.tsa.IN_EMail, '')
		;
		UPDATE `t_account_spec` tsa
		SET
			tsa.Actv_Status = (@.tsa.Actv_Status := 
				IF(tsa.Actv_Mode = 'Zapomnialem' AND NOT (@session.globals.user_accounts.PrzypomnijHaslo.Acitve <> '0'), 'ERR.DISABLED.Zapomnialem', tsa.Actv_Status)),
			tsa.Log_Czynnosc = 
				IF(tsa.Actv_Mode = 'Aktywacja', 402, IF(tsa.Actv_Mode = 'Zapomnialem', 404, 3))
		;
		-- CALL _Session_Refresh_Variables('', '', '');
		-- select @session.globals.user_accounts.PrzypomnijHaslo.Acitve;
		
		
	--	Szukaj user wg
	--	GUID-a ... 
		UPDATE `t_account_spec` tsa
		LEFT JOIN `_user_accounts` ua ON ua.OsobaGUID = Actv_IN_ID AND ua.typ = 'SYS'
		SET
			tsa.UserGUID = ua.OsobaGUID,
			tsa.AD_Mail = ua.AD_Mail,
			tsa.Actv_Status = (@.tsa.Actv_Status := IF(ua.OsobaGUID IS NOT NULL, 'OK', tsa.Actv_Status))
		WHERE
			tsa.Actv_Status = 'ERR.NO.USER'
		;
	--	a gdy nie znaleziono to (ale tylko dla Actv_Mode = 'Zapomnialem')
	--	loginu
		UPDATE `t_account_spec` tsa
		LEFT JOIN `_user_accounts` ua ON ua.login = Actv_IN_ID AND ua.typ = 'SYS'
		SET
			tsa.UserGUID = ua.OsobaGUID,
			tsa.AD_Mail = ua.AD_Mail,
			tsa.Actv_Status = (@.tsa.Actv_Status := IF(ua.OsobaGUID IS NOT NULL, 'OK', tsa.Actv_Status))
		WHERE
			tsa.Actv_Status = 'ERR.NO.USER'
			AND tsa.Actv_Mode = 'Zapomnialem'
		;
	--	a gdy nie znaleziono to (ale tylko dla Actv_Mode = 'Zapomnialem')
	--	emaila
		UPDATE `t_account_spec` tsa
		LEFT JOIN `_user_accounts` ua ON ua.Ad_mail = Actv_IN_ID AND ua.typ = 'SYS'
		SET
			tsa.UserGUID = ua.OsobaGUID,
			tsa.AD_Mail = ua.AD_Mail,
			tsa.Actv_Status = (@.tsa.Actv_Status := IF(ua.OsobaGUID IS NOT NULL, 'OK', tsa.Actv_Status))
		WHERE
			tsa.Actv_Status = 'ERR.NO.USER'
			AND tsa.Actv_Mode = 'Zapomnialem'
		;
		UPDATE `t_account_spec` tsa
		INNER JOIN `_user_accounts` ua ON ua.OsobaGUID = tsa.UserGUID AND ua.typ = 'SYS'
		SET
			tsa.Actv_Status = (@.tsa.Actv_Status :=
				IF(ua.Status > 0, 'ERROR.Account.Inactive', 
					IF(IFNULL(tsa.AD_Mail, '') = '', 
						'ERR.Empty.Email', 
						IF(tsa.Actv_IN_EMail <> ''  AND tsa.AD_Mail <> tsa.Actv_IN_EMail, 
							'ERR.Unknown.Email', 
							tsa.Actv_Status
						)
					)
				)
			),
			tsa.Last_Change_Pswd = ua.Last_Change_Pswd
		WHERE
			tsa.Actv_Status LIKE 'OK%'
		;
		
		UPDATE `t_account_spec` tsa
		SET
			-- tsa.Token = _MD5_CHARSET('', tsa.UserGUID, tsa.Ad_mail, tsa.Last_Change_Pswd, '', '')
			tsa.Token = _MD5_CHARSET('', tsa.UserGUID, tsa.Ad_mail, '', '', '')
		WHERE
			tsa.Actv_Status LIKE 'OK%'
		;
		IF @.tsa.Actv_Status LIKE 'OK%' THEN
		--	OK moge zaczynać
			SET @_Params = 'Sender_Name=Dział kadr';
			UPDATE `_user_accounts` ua, `t_account_spec` tsa
			SET
				ua.user_type = -ABS(user_type),
				ua.ExtFlags	= 
					CONCAT_WS('', NULLIF(REPLACE(REPLACE(ua.ExtFlags, '<SetUp.New>', ''), '<SetUp.Reset>', ''), ''), 
						IF(tsa.Actv_Mode = 'Aktywacja', 
							'<SetUp.New>', 
							'<SetUp.Reset>'
						)
					)
			WHERE
				tsa.Actv_Status LIKE 'OK%'
				AND ua.OsobaGUID = tsa.UserGUID AND ua.typ = 'SYS'
			;	
			-- CALL send_mail('Init', 'Mail_aktywujacy', 'Firmowy', @.tsa.M.ID, '', '', '', @_Params);
			CALL send_mail('Init', 'Mail_aktywujacy', 'MAIL_FROM_system', @.tsa.M.ID, '', '', '', @_Params);
			UPDATE `t_send_mail_inf` ti, `t_account_spec` tsa
			SET
				ti.IN_MODE = IF(tsa.Actv_Mode = 'Aktywacja', 'Mail_aktywujacy', 'Mail_zapomnialem_hasla')
			;
				
			CALL _IReg_Get('', 'URL_Link_Mail_aktywujacy', 0, 'MEMO', 
				@.DevelopStuff.CentrumIntNet.URL, 
				'https://intdevel.int.com.pl:56491/CentrumIntNet/confirm.php?#ACT=#&nsv=#TOKEN#');
		--	UWAGA do @.DevelopStuff.CentrumIntNet.URL doklej wstawkę z wersja obsł. okna aktywizacji (Ja+Grześ 24-02-2021)	
			-- SET @.DevelopStuff.CentrumIntNet.URL = CONCAT_WS('&', @.DevelopStuff.CentrumIntNet.URL, 'ver=2.0');
			SET @.DevelopStuff.CentrumIntNet.URL = 
				CONCAT_WS('&', @.DevelopStuff.CentrumIntNet.URL,
					IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&klient_id=%', NULL, CONCAT('klient_id=', @session.globals.Owner)),
					IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&db_name=%', NULL, CONCAT('db_name=', SCHEMA())),
					IF(@.DevelopStuff.CentrumIntNet.URL LIKE '%&ver=%', NULL, 'ver=2.0')
				)
			;			
			TRUNCATE `t_send_mail`;
			INSERT IGNORE INTO `t_send_mail`
			(Send_Mode, Recip_GUID, Msg_Title, Msg_Body_Link, Token, Param_Welcome, Param1)
			SELECT 
				-- SendGUID = _Get_ID_xxxxx('SHORT', 38, 'send_mail.', '', '', NULL, NULL, NULL),
				tsa.Actv_Mode AS Send_Mode,
				tsa.UserGUID AS Recip_GUID,
				-- tsa.Ad_mail AS Recip_Ad_mail,
				IF(tsa.Actv_Mode = 'Aktywacja', 'Aktywacja konta do systemu Motława.', 'Zapomniałem hasła!') AS Msg_Title,
				-- 'DEFAULT' as Msg_Body_Template,
				-- Msg_Body_Content = @.Mail.content.HTML,
				REPLACE(@.DevelopStuff.CentrumIntNet.URL, '#ACT=#', 
					IF(tsa.Actv_Mode = 'Aktywacja', 
						'ACT=SetUp.New', 
						'ACT=SetUp.Reset'
					)
				) AS Msg_Body_Link,
				-- MD5(CONCAT(tsa.UserGUID, tsa.Ad_mail)) AS Token,
				tsa.Token AS Token,
				'Dzień dobry' AS Param_Welcome,
				NULL AS Param1
			FROM `t_account_spec` tsa
			WHERE
				tsa.Actv_Status LIKE 'OK%'
			;
			
			-- CALL send_mail('Prepare', '', '', '', '', '', '', '');
			CALL send_mail('Send', '', '', '', '', '', '', '');
 		END IF;
		
		UPDATE `t_account_spec` tsa
		SET
			tsa.Actv_Status_Msg = 
				IF(tsa.Actv_Mode = 'Aktywacja',
					CASE tsa.Actv_Status 
					WHEN 'ERR.NO.USER' THEN 
						'Brak takiego konta użytkownika'
					WHEN 'ERROR.Account.Inactive' THEN 
						'To konto jest nieaktywne!'
					WHEN 'ERR.Empty.Email' THEN 
						'Brak takiego konta użytkownika'
					WHEN 'ERR.Unknown.Email' THEN 
						'Próba aktywacji konta z nieznanego adresu mailowego!'
					ELSE
						'Aktywacja konta - wysłany został mail do użytkownika w którym będzie link do okna ustawienia hasła.'
					END
				,
					CASE tsa.Actv_Status 
					WHEN 'ERR.DISABLED.Zapomnialem' THEN 
						'Funkcja jest niedostepna w systemie!'
					WHEN 'ERR.NO.USER' THEN 
						'Brak takiego konta użytkownika'
					WHEN 'ERROR.Account.Inactive' THEN 
						'To konto jest nieaktywne!'
					WHEN 'ERR.Empty.Email' THEN 
						'Niepoprawny login lub brak adresu e-mial na Twoim koncie. \nKoniecznie skontaktuj sie z administratorem w celu zmiany lub uzupełnienia danych.'
					WHEN 'ERR.Unknown.Email' THEN 
						'Próba aktywacji konta z nieznanego adresu mailowego!'
					ELSE
						'Odbierz mail wysłany na podany w systemie adres w którym będzie link do okna ustawienia hasła.\nUWAGA! Operacja zmiany hasła z danego maila jest jednorazowa!'
					END
				)
		;
		IF (_PARAM_E LIKE '%<select>%') THEN
			SELECT * FROM `t_account_spec`;
		END IF;
	--	LOG
		CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
	--	Drop	
		-- CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');

		LEAVE S_user_accounts_sys_cfg;

		
		
	END IF;

	IF _MODE IN ('confirm.2.0.passwd.SetUp.New', 'confirm.2.0.passwd.SetUp.Reset') THEN
	/* *************************************************************************************************************************************************************
		Potwierdzenie hasla z Tokenem
		CALL _user_accounts_sys_cfg('confirm.2.0.passwd.SetUp.New', 0, Token, PSWD, '', '', '', '', '');
		CALL _user_accounts_sys_cfg('ssss', 0, Token, PSWD, '', '', '', '', '');
		_OsobaGUID	
					Token dla NIE 'confirm.2.0.passwd.SetUp.Change'
					UserGUID/Login ??????????  dla 'confirm.2.0.passwd.SetUp.Change'
		_Value		PSWD#
		_PARAM_A	stare PSWD#
		jmam
		CALL _user_accounts_sys_cfg('confirm.2.0.passwd.SetUp.Change', 0, UserGUID, PSWD, '', '', '', '', '');
	**************************************************************************************************************************************************************/
	
		IF @.accounts.3.0 THEN
			SET _MODE = CONCAT('accounts.3.0.', REPLACE(_MODE, '2.0.', ''));
			/*
			SET _MODE = REPLACE(REPLACE(REPLACE(_MODE, 
				'confirm.2.0.passwd.SetUp.New', 'confirm.2.0.passwd.SetUp.New'),
				'confirm.2.0.passwd.SetUp.Reset', 'confirm.2.0.passwd.SetUp.Reset'),
				'confirm.2.0.passwd.SetUp.Change', 'accounts.3.0.confirm.passwd.SetUp.Change')
			;
			*/
			CALL _user_accounts_sys_cfg(_MODE, _IDN, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
			LEAVE S_user_accounts_sys_cfg;
		END IF;

/*		DALEJ WON!!!!!!!!!!!!!!!!!!	*/		


		
		
		SET 
			@.NEW.datas = NULL,
			@.OLD.user_type = NULL
		;
		DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash
		SET 
			@.tsa._Mode = _MODE,
			@.tsa.IN_Token = _OsobaGUID,
			@.tsa.IN_EMail = IFNULL(_PARAM_B, ''),
			@.tsa.IN_Datas = _Value,
			@.tsa.IN_Datas_Old = _PARAM_A,
			-- @.tsa.Aktywacja = (_MODE = 'accounts.sent.aktywacja'),
			-- @.tsa.Zapomnialem.hasla = (_MODE = 'accounts.sent.zapomnialem'),
			@.ta.Actv_Portal = IF(_PARAM_C LIKE '%http%', _PARAM_C, '')	-- po co ?
		;
		CALL _user_accounts_sys_cfg('t_account_spec.INIT', 0, '', '', '', '', '', '', '');
		INSERT IGNORE INTO `t_account_spec`
		SET
			IN_Mode = @.tsa._Mode,
			Actv_Mode = IF(@.tsa._Mode LIKE '%confirm.2.0.passwd.SetUp.New%', '<SetUp.New>', IF(@.tsa._Mode LIKE '%confirm.2.0.passwd.SetUp.Reset%', '<SetUp.Reset>', '???')),
			Actv_Status = (@.tsa.Actv_Status := 'ERR.NO.USER'),
			Token = @.tsa.IN_Token,
			Datas = @.tsa.IN_Datas
		;
		UPDATE `t_account_spec` tsa, `_user_accounts` ua
		SET
			tsa.UserGUID = ua.OsobaGUID,
			tsa.AD_Mail = ua.AD_Mail,
			tsa.Actv_Status = (@.tsa.Actv_Status := 
				IF(tsa.Actv_Mode = '<SetUp.Reset>', 
				-- zmiana hasła a NIE nowo zakladane konto
					IF(ua.ExtFlags LIKE '%<SetUp.Reset>%',
						'OK', 	
						'ERR.1.raz'
					),
					IF(tsa.Actv_Mode = '<SetUp.New>', 
					-- nowo zakladane konto
						IF(ua.user_type < 0 AND ua.ExtFlags LIKE '%<SetUp.New>%', 
							'OK',
							'ERR.Bylo.Aktywowane' 	
						),
						tsa.Actv_Status
					)
				)
			)
		WHERE
			tsa.Actv_Status = 'ERR.NO.USER'
			-- and tsa.Token = _MD5_CHARSET('', ua.OsobaGUID, ua.Ad_mail, ua.Last_Change_Pswd, '', '')
			AND tsa.Token = _MD5_CHARSET('', ua.OsobaGUID, ua.Ad_mail, '', '', '')
			AND ua.typ = 'SYS'
		;
		IF @.tsa.Actv_Status LIKE 'OK%' THEN
		--	OK moge zaczynać
			UPDATE `_user_accounts` ua, `t_account_spec` tsa
			SET
				ua.Last_Change_Pswd = IF(ua.datas <=> tsa.datas, ua.Last_Change_Pswd, NOW()),
				ua.datas = tsa.datas,
				ua.user_type = ABS(ua.user_type),
				ua.ExtFlags = NULLIF(REPLACE(REPLACE(ua.ExtFlags, '<SetUp.New>', ''), '<SetUp.Reset>', ''), '')
			WHERE	
				ua.OsobaGUID = tsa.UserGUID
				AND ua.typ = 'SYS'
				AND tsa.Actv_Status LIKE 'OK%'
			;
		--	Dodatkowo wyślij wiszące maile ze statusem 'HOLD_FOR_ACTIVATION'	
		--	ALE tylko dla Inicjacja/po Zapomnialem hasla
			UPDATE `com_msg_ng` cn, `com_msg_po` cp, `_user_accounts` ua, `t_account_spec` tsa
			SET
				cn.Status = 'NEW'
			WHERE
				ua.OsobaGUID = tsa.USERGUID
				AND ua.typ = 'SYS'
				AND tsa.Actv_Status LIKE 'OK%'
				AND cp.Recipient = ua.Ad_mail AND cp.Medium_Type = 'mail' AND cp.Type = 'OUT'
				AND cn.GUID = cp.GUIDNg AND cn.Status = 'HOLD_FOR_ACTIVATION'
			;
		END IF;
		
		UPDATE `t_account_spec` tsa
		SET
			tsa.Log_Czynnosc = 
				IF(tsa.Actv_Mode = '<SetUp.New>', 403, IF(tsa.Actv_Mode = '<SetUp.Reset>', 405, 3)),
			tsa.Actv_Status_Msg = 
				CONCAT_WS('', 
					CASE tsa.Actv_Status 
					WHEN 'ERR.NO.USER' THEN 
						'Zmiana hasła nie powiodła się - błąd identyfikacji!'
					WHEN 'ERROR.Account.Inactive' THEN 
						'To konto jest nieaktywne!'
					WHEN 'ERR.Bylo.Aktywowane' THEN 
						'Konto było już aktywowane - i jest to operacja jednorazowa - dlatego zmiana hasła nie powiodła się!'
					WHEN 'ERR.1.raz' THEN 
						'Operacja zmiany hasła z maila jest jednorazowa - \npowtórne jej wykorzystanie jest niemożliwe -\ndlatego zmiana hasła nie powiodła się!!'
					ELSE
						'Zmiana hasła powiodła się!'
					END,
					'\nUWAGA!!! - link z maila umożliwiający ustawienie/zmianę hasła był JEDNORAZOWY!'
				)
		;
		
		IF (_PARAM_E LIKE '%<select>%') THEN
			SELECT tsa.* FROM `t_account_spec` tsa;
		END IF;
		
	--	LOG
		CALL _user_accounts_sys_cfg('t_account_spec.to.LOG', 0, '', '', '', 402, '', '', '');
	--	Drop	
		CALL _user_accounts_sys_cfg('t_account_spec.END', 0, '', '', '', '', '', '', '');
		
		LEAVE S_user_accounts_sys_cfg;

	END IF;

	
	
	IF _MODE IN ('accounts.sent.aktywacja', 'accounts.sent.zapomnialem', 'accounts.sent.') THEN
	/* *************************************************************************************************************************************************************
		Gdy aktywujemy pierwszy raz konto lub
		gdy zapomnielismy hasla
		CALL _user_accounts_sys_cfg('accounts.sent.aktywacja', 0, osobaGUID, 'jmam68@gmail.com', '', '', '', '', '');
		CALL _user_accounts_sys_cfg('accounts.sent.zapomnialem', 0, login, '', 'debug', 'www.link', '', '', '');
		_OsobaGUID	osoba jako OsobaGUID (dla aktywacja) lub login (dla zapomnialem hasla)
		_Value		email aktywacyjny
		_PARAM_A	Debug np.
		_PARAM_B	link do strony systemu np. Porta fide lub KEY do Rega do linka strony !!!!
		jmam
	**************************************************************************************************************************************************************/
		SET 
			@.ta.Aktywacja = (_MODE = 'accounts.sent.aktywacja'),
			@.ta.Zapomnialem.hasla = (_MODE = 'accounts.sent.zapomnialem'),
			@.ta.M.ID = IF(_PARAM_B LIKE '%http%', NULL, _PARAM_B),
			@.ta.Actv_Portal = IF(_PARAM_B LIKE '%http%', _PARAM_B, '')
		;
		IF @.ta.Aktywacja AND (@.ta.M.ID IS NOT NULL) THEN
			CALL _user_accounts_sys_cfg('accounts.add.Access_Module', 0, _OsobaGUID, @.ta.M.ID, '', '', '', '', '');
		END IF;
		
		IF @.ta.Zapomnialem.hasla THEN
			
			IF NOT (@session.globals.user_accounts.PrzypomnijHaslo.Acitve <> '0') THEN
			--	Nie obsluguj przycisku przypomnij haslo 
				LEAVE S_user_accounts_sys_cfg;
			END IF;
			IF _OsobaGUID LIKE '%@%' THEN
			--	przyponienie hasła - podano adre mailowy i po nim szukamy (to prawidlowe i najlepsze 
			-- 	podejscie bo czesto ludzie zapominaja nie tylko hasla ale i loginu a mail znają!!!
				SELECT 
					a.OsobaGUID, a.Ad_mail
				INTO 
					_OsobaGUID, _Value
				FROM `_user_accounts` a
				WHERE
					a.Ad_mail = _OsobaGUID
				;
			ELSE
			--	przyponienie hasła - podano login i po loginie szukamy
				SELECT 
					a.OsobaGUID, a.Ad_mail
				INTO 
					_OsobaGUID, _Value
				FROM `_user_accounts` a
				WHERE
					a.Login = _OsobaGUID
				;
			END IF;
		--	UWAGA! dla Zapomnialem.hasla gdy nie ma jeszce adresu mailowego nie wysylaj i nie zmieniaj stany konta czyli user_type na minus!! 
		END IF;
		
		UPDATE `_user_accounts` a
		SET
		--	UWAGA
		--	Zawsze przygotuj konto do zmiany hasla poprzez ustawienie UserType na -1 
		--	wejscie potem w link aktywacyjny i uzupenienie hasla przestawi UserType na 1 ALE tym samym zablokuje wejscie 
		--	ponowne (celowe, zlosliwe) w link i zmiane hasla gdyz zmiana ta odbywa sie tylko dla UserType < 0
			a.Ad_mail = 
				IF(_MODE = 'accounts.sent.aktywacja',
			--	dla 'accounts.sent.aktywacja'
					IF(IFNULL(a.Ad_mail, '') != '',
						a.Ad_mail,
						(
						SELECT 
							kk.adres 
						FROM `kontakty` kk 
						WHERE 
							kk.`osobaGUID` = a.OsobaGUID 
							AND kk.typ_medium = 3 
							AND LOCATE('@', kk.`adres`) > 0 
							AND kk.nieaktywny = 0
						ORDER BY kk.priorytet 
						LIMIT 1
						)
					),
				--	oczywiscie dla 'accounts.sent.zapomnialem' nie ruszamy w zaden sposob pola Ad_mail
					a.Ad_mail
				)
					
		WHERE
			a.OsobaGUID = _OsobaGUID
		;
		SET @X = 1;
				-- CALL _user_accounts_sys_cfg('accounts.add.Access_Module', 0, _OsobaGUID, 'M.WEB.PortaFide.www', '', '', '', '', '');		
				
		DROP TEMPORARY TABLE IF EXISTS `t_account_activate`;
		CREATE TEMPORARY TABLE `t_account_activate` (
			`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			`Nazwisko_Imiona` VARCHAR(200) DEFAULT NULL,
			`accounts_exists` BOOLEAN DEFAULT FALSE,
			`Ad_mail` VARCHAR(200) DEFAULT NULL,
			`Actv_LOGIN` VARCHAR(50),
			`Actv_Portal` VARCHAR(250),
			`Actv_Portal_Url` VARCHAR(250),
			`Actv_Portal_Descr` MEDIUMTEXT,
			`Actv_Status` VARCHAR(50),
			`Actv_Status_Msg` MEDIUMTEXT,
			`Actv_Msg_Title` VARCHAR(250),
			`Actv_Msg_Body` MEDIUMTEXT,
			`Actv_Token` VARCHAR(50),
			`Actv_Msg_Body_Link` VARCHAR(250),
			`Actv_Owner_Name` VARCHAR(250),
			`Actv_Owner_Adr` VARCHAR(250),
			PRIMARY KEY (`OsobaGUID`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8
		;




		
		INSERT INTO `t_account_activate` 
		SET 
			OsobaGUID = _OsobaGUID,
			Actv_Status_Msg = 'Funkcja tymczasowo zablokowana', Actv_Status = 'OK'
		;	
		SELECT * FROM `t_account_activate`;
		LEAVE S_user_accounts_sys_cfg;
		
		
		
		
		
	--	Zmien stan konta ALE TYLKO gdy jest w ogole adres mailowy - bo inaczej nie pojdzie mail a konto zablokowane :( !!!	
		UPDATE `_user_accounts` a
		SET
			a.user_type = -ABS(a.user_type)
		WHERE
			a.OsobaGUID = _OsobaGUID
			AND
			IFNULL(a.Ad_mail, '') != ''
		;
		
		
		
		
			
		INSERT INTO `_erp_external_process_log`  
					SET 
						TIME = NOW(), PROCESS = "CALL _user_accounts_sys_cfg('accounts.sent.aktywacja'...) START", 
						TYPE = 'Accounts', Msg = CONCAT('osoba: ', _VarStr(_OsobaGUID), ' mail', _VarStr(_Value))  
					;

		
		CALL _IReg_Get('', 'URL_Link_Mail_aktywujacy', 0, 'MEMO', 
			@.DevelopStuff.CentrumIntNet.URL, 
			'https://intdevel.int.com.pl:56491/CentrumIntNet/confirm.php?#ACT=#&nsv=#TOKEN#');
		-- 	np dla konkola
		--	https://intdevel.int.com.pl:56491/CentrumIntNet/confirm.php?#ACT=#&nsv=#TOKEN#&klient_id=KONKOL_PF&db_name=httest
		CALL _IReg_Get('DaneFirmy', 'OurMail', 0, 'STRING', @.mail_from, NULL);
		
		INSERT INTO `t_account_activate`
			(
			OsobaGUID, Nazwisko_Imiona, accounts_exists, Actv_Token, Ad_mail, 
			Actv_Msg_Title, Actv_Msg_Body, Actv_Msg_Body_Link, Actv_LOGIN, 
			Actv_Portal, Actv_Portal_Url, Actv_Portal_Descr, Actv_Owner_Name, Actv_Owner_Adr
			)
			SELECT
				a.OsobaGUID AS OsobaGUID,
				CONCAT(o.Nazwisko, ' ', o.Imiona) AS Nazwisko_Imiona,
				TRUE AS accounts_exists,
				MD5(CONCAT(a.OsobaGUID, a.Ad_mail)) AS Actv_Token,
				a.Ad_mail,
				'' AS Actv_Msg_Title,
				(
					SELECT 
						i.valuex -- , i.*
					FROM IReg i
					WHERE
						-- i.IdKey = 'Mail aktywujacy'
						i.IdKey = IF(@.ta.Aktywacja, 
							'Mail aktywujacy',
							'Mail zapomnialem hasla'
						)
						AND i.IdPath = 'INT\\SYSTEM\\MOTLAWA'
					LIMIT 1
				) AS Actv_Msg_Body,
				REPLACE(@.DevelopStuff.CentrumIntNet.URL, '#ACT=#', 
					IF(@.ta.Aktywacja, 
						'ACT=SetUp.New', 
						'ACT=SetUp.Reset'
					)
				) AS Actv_Msg_Body_Link,
				a.login AS Actv_LOGIN,
				IFNULL(c.Caption, @.ta.Actv_Portal) AS Actv_Portal,
				IFNULL(c.Prog_HREF, '') AS Actv_Portal_Url,
				IFNULL(c.Descr, '') AS Actv_Portal_Descr,
				IFNULL(k.Nazwa, '') AS Actv_Owner_Name,
				IFNULL(
				IF(@session.globals.DOC_with_AdrLink, 
					_varSTR(CONCAT(
						'', 
						(
							SELECT 
								_FetchParams_Quick('', al.adr_MASKS, '<ADR_P>', '&') 
							FROM `geo_int_adr_link` al 
							WHERE 
								al.ObjGUID = k.GUID 
								AND al.ObjTable = 'kontrah' 
								AND al.AdrTyp LIKE '%K%' 
							ORDER BY LENGTH(al.AdrTyp) 
							LIMIT 1
						)
					)), 
					CONCAT('', k.ulica, ', ', k.zipcode, ' ', k.NazwaMiasta)
				), '') AS  Actv_Owner_Adr
			FROM `_user_accounts` a
			INNER JOIN `osoby` o ON o.GUID = a.OsobaGUID
			LEFT JOIN `sys_core` c ON c.GUID = @.ta.M.ID
			LEFT JOIN `kontrah` k ON k.GUID = @session.globals.Owner_kontrguid
			WHERE
				IF(IFNULL(_OsobaGUID, '') != '', 
					a.OsobaGUID = _OsobaGUID,
					a.Ad_mail = _Value
				)
				AND a.typ = 'SYS'
				
			LIMIT 1
		;
		IF ROW_COUNT() = 0 THEN
			INSERT INTO `t_account_activate`
			SET
				accounts_exists = FALSE, 
				-- Actv_Status = ,
				Ad_mail = '',
				Actv_Status_Msg = '',
				Actv_Msg_Title = '', 
				Actv_Msg_Body = ''
			;
		END IF;
		
		UPDATE `t_account_activate` ta
		SET
			ta.Actv_Status = (@.ta.Actv_Status := 
				IF(NOT ta.accounts_exists,
					'account not exists',
					IF(IFNULL(ta.Ad_mail, '') = '',
						'empty email address',
						IF((ta.Ad_mail != _Value) OR _Value = '',
							'SEND: unknown email address',
							'SEND: OK'
						)
					)
				))
		WHERE	
			TRUE
		;		
		
		UPDATE `t_account_activate` ta
		SET
			ta.Actv_Status_Msg = (@.ta.Actv_Status_Msg :=
				IF(@.ta.Actv_Status = 'SEND: OK',
				--	OK
					IF(@.ta.Aktywacja, 
						'Aktywacja konta - odbierz mail w którym będzie link do okna ustawienia hasła.', 
						'Zmiana hasła będzie możliwa po odebraniu maila wysłanego na podany w systemie adres i wejściu w odpowiedni link.\nUWAGA! Operacja zmiany hasła z danego maila jest jednorazowa!'
					), 
				--	ERR
					IF(@.ta.Aktywacja,
					--	Aktywacja
						IF(@.ta.Actv_Status = 'SEND: unknown email address',
							'Próba aktywacji konta z nieznanego adresu mailowego!',
							''
						),
					--	zapomnialem hasla
						'Niepoprawny login lub brak adresu e-mial na Twoim koncie. \nKoniecznie skontaktuj sie z administratorem w celu zmiany lub uzupełnienia danych.'
					)
				)),
			ta.Actv_Msg_Title =
				IF(@.ta.Actv_Status = 'SEND: OK',
					IF(@.ta.Aktywacja, 
						'Aktywacja konta', 
						'Zmiana hasła'
					), 
					@.ta.Actv_Status_Msg
					/*
					IF(@.ta.Actv_Status = 'SEND: unknown email address',
					--	Gdy zapomnialem hasla to nie pobieram zadnego maila domyslnego z kontaktow tylko sprawdzam czy jest w polu `Ad_mail`
					--	Jesli brak takowego to EXIT z errorem i msg
						IF(@.ta.Aktywacja, 'Próba aktywacji konta z nieznanego adresu mailowego!', 'Brak adresu e-mial na koncie. \nSkontaktuj sie z administratorem w celu jego uzupełnienia.'), 
						''
					)
					*/
				),
			ta.Actv_Msg_Body =
				IF(@.ta.Actv_Status = 'SEND: OK',
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ta.Actv_Msg_Body, 
						'#N#', ta.Nazwisko_Imiona), 
						'#URL:LINK#', ta.Actv_Msg_Body_Link), 
						'#TOKEN#', ta.Actv_Token),
						'#LOGIN#', ta.Actv_LOGIN),
						'#WWW#', ta.Actv_Portal),
						'#WWW_URL#', ta.Actv_Portal_Url),
						'#WWW_DESCR#', ta.Actv_Portal_Descr),
						'#OWNER#', ta.Actv_Owner_Name),
						'#OWNER_ADR#', ta.Actv_Owner_Adr),
					
					IF(@.ta.Actv_Status = 'SEND: unknown email address',
						CONCAT(
							'Próbowano dokonać aktywacji podając nastepujący adres mailowy: \n', 
							_Value, '\n',
							'proszę sprawdzić ten adres.\n',
							''
						),
						''
					)
				)
		WHERE	
			TRUE
		;
		
		
		IF _PARAM_A = 'debug.jmam' THEN
			LEAVE S_user_accounts_sys_cfg;
		END IF;
		
		
		-- SELECT * FROM `t_account_activate`;
		-- LEAVE S_user_accounts_sys_cfg;
		CALL com_mailer('SET.Sender.MAIL', '', 'Firmowy', '', '', '');	-- ustawia zmienną @.Sender.MAIL jako np. Firmowy/MAIL_FROM_faktury/MAIL_FROM_zamowienia/MAIL_FROM_Place/MAIL_FROM_rozrach/ 
		REPLACE `com_msg_ng`
		(GUID, TYPE, OWNER, Msg_Title, Msg_Body, SrcGUID, SrcTable, STATUS, Msg_Mode, Notification_Start, Notification_Until, Sender)
		SELECT
			(@.accounts.com_msg_ng := MD5(CONCAT(ta.OsobaGUID, ta.Actv_Status, SUBSTR(CURRENT_DATE(), 1, 250)))) AS GUID,
			'OUT' AS `Type`,
			@session.INFO.User_GUID AS `Owner`,
			ta.Actv_Msg_Title AS Msg_Title, 
			REPLACE(REPLACE(REPLACE(ta.Actv_Msg_Body, '\n', ''), '\r', ''), '\t', '') AS Msg_Body,
			ta.OsobaGUID AS SrcGUID, 
			'_user_accounts' AS SrcTable, 
			'NEW' AS `Status`, 
			'MAIL.user_accounts' AS Msg_Mode,
			NOW() AS Notification_Start,
			DATE_ADD(NOW(), INTERVAL 1 DAY) AS Notification_Until,
			-- było @.mail_from AS Sender
			@.Sender.MAIL AS Sender
		FROM `t_account_activate` ta
		WHERE
			ta.Actv_Status LIKE 'SEND%'
			AND ta.Actv_Status = 'SEND: OK'	--	dodano - ostrzezen nie wysylamy
		;
		
		IF _PARAM_A != 'debug' THEN
			INSERT IGNORE INTO `com_msg_po`
			(GuidNg, TYPE, Medium_Type, Recipient, STATUS, Dispatch_ID)
			SELECT
				@.accounts.com_msg_ng AS GuidNg,
				'OUT' AS `Type`,
				'mail' AS Medium_Type,
				ta.Ad_mail AS Recipient,
				'NEW' AS `STATUS`,
				_Get_ID_xxxxx('', 38, 'Disp:', ta.Actv_Token, ':', _VarStr(NOW()), NULL, NULL) AS Dispatch_ID
			FROM `t_account_activate` ta
			WHERE
				ta.Actv_Status LIKE 'SEND%'
				AND ta.Actv_Status = 'SEND: OK'	--	dodano - ostrzezen nie wysylamy
			;
		ELSE

			INSERT IGNORE INTO `com_msg_po`
			(GuidNg, TYPE, Medium_Type, Recipient, STATUS, Dispatch_ID)
			SELECT
				@.accounts.com_msg_ng AS GuidNg,
				'OUT' AS `Type`,
				'mail' AS Medium_Type,
				-- ta.Ad_mail AS Recipient,
				'apro68@gmail.com' AS Recipient,
				'NEW' AS `STATUS`,
				_Get_ID_xxxxx('', 38, 'Disp:', ta.Actv_Token, ':', _VarStr(NOW()), NULL, NULL) AS Dispatch_ID
			FROM `t_account_activate` ta
			WHERE
				ta.Actv_Status LIKE 'SEND%'
				AND ta.Actv_Status = 'SEND: OK'	--	dodano - ostrzezen nie wysylamy
			;

			INSERT IGNORE INTO `com_msg_po`
			(GuidNg, TYPE, Medium_Type, Recipient, STATUS, Dispatch_ID)
			SELECT
				@.accounts.com_msg_ng AS GuidNg,
				'OUT' AS `Type`,
				'mail' AS Medium_Type,
				-- ta.Ad_mail AS Recipient,
				'int.grzegorz@gmail.com' AS Recipient,
				'NEW' AS `STATUS`,
				_Get_ID_xxxxx('', 38, 'Disp:', ta.Actv_Token, ':', _VarStr(NOW()), NULL, NULL) AS Dispatch_ID
			FROM `t_account_activate` ta
			WHERE
				ta.Actv_Status LIKE 'SEND%'
				AND ta.Actv_Status = 'SEND: OK'	--	dodano - ostrzezen nie wysylamy
			;
		END IF;
		
		INSERT INTO `_erp_external_process_log`  
					SET 
						TIME = NOW(), PROCESS = "CALL _user_accounts_sys_cfg('accounts.sent.aktywacja'...) END", 
						TYPE = 'Info_piek', Msg = CONCAT('osoba: ', _VarStr(_OsobaGUID), ' mail', _VarStr(_Value))  
					;
		
		
		SELECT * FROM `t_account_activate`;
		
		LEAVE S_user_accounts_sys_cfg;
		
		
	END IF;
	
	IF _MODE IN ('confirm.passwd.SetUp.New', 'confirm.passwd.SetUp.Reset') THEN
	/* *************************************************************************************************************************************************************
		Potwierdzenie hasla z Tokenem
		CALL _user_accounts_sys_cfg('confirm.passwd.SetUp.New', 0, Token, PSWD, '', '', '', '', '');
		CALL _user_accounts_sys_cfg('ssss', 0, Token, PSWD, '', '', '', '', '');
		_OsobaGUID	Token
		_Value		PSWD#
		jmam
	**************************************************************************************************************************************************************/
		DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash
		IF FALSE AND @session.globals.Owner IN ('PLISZKA') THEN
		--	nie potrzebne juz!!!!!!!!!!!!
			CALL _user_accounts_sys_cfg('confirm.2.0.passwd.SetUp.New', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, 'from.old.ver', _PARAM_E);
			LEAVE S_user_accounts_sys_cfg;
		END IF;
		
		SET 
			@.NEW.datas = NULL,
			@.OLD.user_type = NULL
		;
		UPDATE `_user_accounts` a
		SET
			-- bylo a.datas = (@.NEW.datas := IF(a.user_type < 0, _Value, 'Blokada')),
			a.datas = (@.NEW.datas := IF((@.OLD.user_type := a.user_type) < 0, _Value, a.datas)),
			a.user_type = ABS(a.user_type)
		WHERE
			-- MD5(CONCAT(a.OsobaGUID, a.Ad_mail)) = _OsobaGUID	--	 identyfikacja Tokena
			_MD5_CHARSET('', a.OsobaGUID, a.Ad_mail, '', '', '') = _OsobaGUID	--	 identyfikacja Tokena
		;
		SELECT 
			@.NEW.datas IS NULL AS Err,	 -- @.NEW.datas jest (pozostaje) NULL tylko gdy UPDATE w ogóle nie doszedł do skutku (błędna identyfikacja Tokena np. włamanie)
			IF(@.NEW.datas IS NULL, 
			--	Gdy błędna identyfikacja Tokena
				'Zmiana hasła nie powiodła się - błąd identyfikacji!', 	
			--	Identyfikacja Tokena OK ale ...
				CONCAT_WS('\n',
					IF(@.OLD.user_type >= 0, 
				--	Konto juz było aktywowane lub zmieniono juz raz hasło i user_type zmieniono na dodatnie	
						IF(_MODE = 'confirm.passwd.SetUp.New',
							'Konto było już aktywowane - i jest to operacja jednorazowa - dlatego zmiana hasła nie powiodła się!', 
							'Operacja zmiany hasła z maila jest jednorazowa - \npowtórne jej wykorzystanie jest niemożliwe -\ndlatego zmiana hasła nie powiodła się!!'
						),
						'Zmiana hasła powiodła się!'
					),
				--	Wszystko w porządku 	
					'UWAGA!!! - link z maila umożliwiający ustawienie/zmianę hasła był JEDNORAZOWY!'	
				)
			) AS Msg;
	END IF;


	IF _MODE LIKE ('Moduly.%') THEN
	/* *************************************************************************************************************************************************************
		Dodawanie kolejnego modulu
		CALL _user_accounts_sys_cfg('Moduly.ADD.Modul', 0, 'M.MOB.BakerDroid', '', 'Aplikacja mob. do kompletowania/pakowania zamówień', '', '', '', '');
		_OsobaGUID	Dodawany Modul
		_Value		--- brak 
		_PARAM_A	Opis
		_PARAM_B	Caption
		_PARAM_C	Prog name
		CALL _user_accounts_sys_cfg('Moduly.UPDATE', 0, '', '', '', '', '', '', '');
	**************************************************************************************************************************************************************/
		
					IF _MODE IN ('Moduly.Send.Info.2.User.Dostep') THEN
					/* *************************************************************************************************************************************************************
						Potwierdzenie hasla z Tokenem
						CALL _user_accounts_sys_cfg('Moduly.Send.Info.2.User.Dostep', 0, User, Modul, '', '', '', '', '');
						_OsobaGUID	User
						_Value		Grupa dostepowa
						_PARAM_A <> '' to wersja 1 
					**************************************************************************************************************************************************************/
						
						SET @_Params = 'Sender_Name=Dział kadr';
						CALL send_mail('Init', 'SEND.MAIL.for.USER', 'MAIL_FROM_Kadry', _Value, '', '', '', @_Params);
						SET
							@.Mail.content.HTML = 
'<p class="welcome">#Welcome#</p>
<p class="text-info">Szanowny Użytkowniku! - adresatem tej wiadomości jest <strong>#ImNa#.</strong><br>#SENDER#</p><p class="text-small-info">(<i>#OWNER#, #OWNER_ADR#</i>)<br></p>
<p class="text-info"><strong>informuje że otrzymałeś dostęp do aplikacji <I>#WWW#</I>.</strong></p>
<p class="text-small-info">#WWW_DESCR#</strong></p>
<p class="text-info">Możesz korzystać z aplikacji <strong>klikając poniższy przycisk i logując się tak jak do innych aplikacji </i>Motławy</i>.</strong></p>
<p class="p-button"> <a class="button" href="#WWW_URL#" target="_blank">Przejdź do portalu</a> </p>
';
					--	Dwie wersje ze sznurkiem i z insertem
						IF _PARAM_A <> '' THEN
						--	Wersja ze sznurkiem
							SET @_Params = 
								CONCAT_WS('&', 
									'Body_Template=DEFAULT&Param_Welcome=Dzień dobry&Msg_Title=Udzielono dostępu do aplikacji: #WWW#', 
									CONCAT('Body_Content=', @.Mail.content.HTML)
								)
							;
							CALL send_mail('Add', 'User.Powiadomienie1', _OsobaGUID, _Value, '', '', '', @_Params);
						ELSE
						--	Wersja z insertem
							INSERT IGNORE INTO `t_send_mail`
							SET
								-- SendGUID = _Get_ID_xxxxx('SHORT', 38, 'send_mail.', '', '', NULL, NULL, NULL),
								Send_Mode = 'Owner3',			-- Send_Mode
								Recip_GUID = _OsobaGUID,
								-- Recip_Ad_mail = 'andy@ha.pl',
								Msg_Title = 'Udzielono dostępu do aplikacji: #WWW#',
								Msg_Body_Template = 'DEFAULT',
								Msg_Body_Content = @.Mail.content.HTML,
								Param_Welcome = 'Dzień dobry'
								-- , Ctx_GUID = 'Prac51' -- 'POLPHARMA'
							;
						END IF;
					--	Wysyłka	
						-- CALL send_mail('Prepare', '', '', '', '', '', '', '');
						CALL send_mail('send', '', '', '', '', '', '', '');
	-- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
						LEAVE S_user_accounts_sys_cfg;
						
						SET
							@.Mail.Lead.HTML = 
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<title></title>
	<style TYPE="text/css">
		.welcome{margin:20px 10px 20px 10px;color:#0079c1;font-size: 2em;font-family: Helvetica, Arial, sans-serif;clear: both;}
		.text-info{line-height:1.5em;margin: 20px 10px 20px 10px;color:#000;font-size:1.2em;font-family: Helvetica, Arial, sans-serif;text-align: left;}
		.text-small-info{line-height:1.5em;margin: 20px 10px 20px 10px;color:#000;font-size:1em;font-family: Helvetica, Arial, sans-serif;text-align: left;}
		.activate-info{line-height:.9em;margin:40px 10px 40px 10px;color:#717074;font-size:1.1em;font-family: Helvetica, Arial, sans-serif;text-align: left;font-weight: 900;}
		.button{margin: 20px 10px 20px 10px; padding:10px 30px 10px 30px;background-color:blue;color:yellow; border-radius: 5px;text-decoration-line: none;}
		a:focus, a:hover { background-color:#DDD;color: #0079c1;}
		.p-button {margin: 40px 10px 40px 10px;}
		a {font-family: Helvetica, Arial, sans-serif;}		
	</style>
</head>'
						;
						SET
							@.Mail.Body.HTML = 
'<body lang="pl-PL">
<p class="welcome">Witamy</p>
<p class="text-info">Szanowny Użytkowniku! - adresatem tej wiadomości jest <strong>#ImNa#</strong></p>
<p class="text-small">- <br><i>#OWNER#, #OWNER_ADR#</i>-</p>
<p class="user-info"><br><strong>informuje że otrzymałeś dostęp do aplikacji <I>#WWW#</I>.</strong></p>
<p class="owner-info">#WWW_DESCR#</strong></p>
<p class="user-info">Możesz korzystać z aplikacji <strong>klikając poniższy przycisk.</strong></p>
<p class="p-button"> <a class="button" href="#WWW_URL#" target="_blank">Przejdź do portalu</a> </p>
-- <br><br><a style=''float:right;margin:0;padding:0;margin:0;padding:0;border-radius: 5px;font-family:Helvetica Neue,Helvetica,Helvetica,Arial,sans-serif;text-decoration:none;color:#fff;background-color:blue;padding:10px 16px;font-weight:bold;margin-right:10px;text-align:center;display:inline-block'' href=#WWW_URL#> Przejdź do portalu </a>
<p class="owner-info"><BR>Wiadomość ta wygenerowana została automatycznie z systemu <I>Motława</I>. Prosimy na nią nie odpowiadać.</strong></p>
</body>
</html>'
						;
						
						SET
							@Html.Go.to.Module.Button = 
								"<br><br><a style='float:right;margin:0;padding:0;margin:0;padding:0;font-family:Helvetica Neue,Helvetica,Helvetica,Arial,sans-serif;text-decoration:none;color:#fff;background-color:blue;padding:10px 16px;font-weight:bold;margin-right:10px;text-align:center;display:inline-block' href=#WWW_URL#> Przejdź do portalu </a>",
							@Html.Go.to.Module.href.default = 'https://webapp.konkol.pl/PortaFide/'
						;
						/*
						SET
						--	odczytaj z coresów link do Module - potrzebny do podmiany frazy #href_PortaFide#
							@Html.Go.to.Module.href = IFNULL(
								(SELECT c.Prog_HREF FROM `sys_core` c WHERE c.GUID = _Value),
								@Html.Go.to.Module.href.default
							)
						;
						SET	-- podmiana frazy #href_PortaFide# na link buttona
							@Html.Go.to.Module.Button = REPLACE(@Html.Go.to.Module.Button, '#WWW_URL#', @Html.Go.to.Module.href)
						;	
						*/
						SET
							@.Moduly.Send.Info.2.User.Title = 
								'Udzielono dostępu do aplikacji: #WWW#',
							@.Moduly.Send.Info.2.User.Body = 
							CONCAT_WS('',
								@.Mail.Lead.HTML,
								@.Mail.Body.HTML
								-- @Html.Go.to.Module.Button
							/*	
								'Dzień dobry!<br>Szanowny Użytkowniku! - adresatem tej wiadomości jest <strong>#N#</strong> ',
								'- <i>#OWNER#, #OWNER_ADR#</i> - informuje<BR>że otrzymałeś dostęp do aplikacji <I>#WWW#</I>.</strong><br><br>',
								'#WWW_DESCR#</strong>.<br>',
								'Możesz korzystać z aplikacji <strong>klikając poniższy przycisk.</strong><br><br>',
								@Html.Go.to.Module.Button,
								'<BR><BR>Wiadomość ta wygenerowana została automatycznie z systemu <I>Motława</I>. Prosimy na nią nie odpowiadać.</strong>'
							*/	
							)
						;
						CALL send_mail('Init', 'SEND.MAIL.for.USER', 'MAIL_FROM_Kadry', 'M.WEB.PortaFide.www', '', '', '', @_Params);
						
						LEAVE S_user_accounts_sys_cfg;
			
					END IF;		
		
		IF _MODE IN ('Moduly.ADD.Modul') THEN
			SET 
			--	_OsobaGUID											   APP_ID
			--	_PARAM_A											   Descr
				_PARAM_B = IFNULL(NULLIF(_PARAM_B, ''), _PARAM_A),	-- Caption
				_PARAM_C = IFNULL(NULLIF(_PARAM_C, ''), _PARAM_A),	-- Prog_Name
				_PARAM_D = NULLIF(_PARAM_D, '')						-- Prog_HREF
			;
			INSERT IGNORE INTO `sys_core`
			SET
				GUID = _OsobaGUID,
				Parent_GUID = 'SYS',
				Descr = _PARAM_A, 
				Caption = _PARAM_B, 
				Prog_Name = _PARAM_C,
				Prog_HREF = 
					IFNULL(_PARAM_D,
					CASE
					WHEN _PARAM_C LIKE 'M.EXE.%' THEN 'EXE'
					WHEN _PARAM_C LIKE 'M.WEB.%' THEN 'WWW'
					WHEN _PARAM_C LIKE 'M.WWW.%' THEN 'WWW'
					WHEN _PARAM_C LIKE 'M.MOB.%' THEN 'MOB'
					ELSE ''
					END
				)
			;-- Portal - Logistyka - nadzór nad sprzedażą mobilną

			INSERT IGNORE INTO `uprawnienia_dict`
			SET
				miejsce = _OsobaGUID, 
				core_id = _OsobaGUID, 
				opis = _PARAM_A, 
				rodzaj = 11, 
				poziom = 1
			;
		--	Uwaga może byc tak że w uprawnieniach są juz uprawnienia do modułów a generalnie odchodzimy od uprawnień na rzecz Grup dostepowych
		--	zaem przepisz z uprawnień do grup
			INSERT IGNORE INTO `grupy_osob`
			(osobaGUID, grupaGUID)
			SELECT 
				u.osobaGUID, u.Miejsce AS grupaGUID -- , o.Nazwisko, o.Rodzaj
			FROM `uprawnienia` u, `osoby` o 
			WHERE 
				-- u.miejsce LIKE 'M.EXE.HT2003%' 
				u.miejsce = _OsobaGUID
				AND o.GUID = u.OsobaGUID 
				-- AND o.Rodzaj = 1 
				AND u.osobaGUID != u.Miejsce 
				AND u.OsobaGUID <> 'ALL'
			;
		--	Update pozostałe zasoby
		--	16 V 2022 ... teaz _Moduly_Grupy
			CALL _Moduly_Grupy('APP.UPDATE.Moduly', '', '', '', '', '');
			--	16 V 2022	CALL _user_accounts_sys_cfg('Moduly.UPDATE', 0, '', '', '', '', '', '', '');
		END IF;
		
		IF _MODE IN ('Moduly.UPDATE') THEN
		--	16 V 2022 ... teaz _Moduly_Grupy
		--	jesli w ogóle wywołujemy to i tak wywołaj _Moduly_Grupy (zamień w PHP/i innych)
			CALL _Moduly_Grupy('APP.UPDATE.Moduly', '', '', '', '', '');
			/*
			wieczorem 16 V 2022
			... wychodzimy
			*/
			LEAVE S_user_accounts_sys_cfg;
			
			
		END IF;

		IF _MODE IN ('Moduly.DEL.Modul') THEN
			DELETE FROM `osoby` WHERE GUID = _OsobaGUID;
			DELETE FROM `osoby` WHERE GUID = _OsobaGUID;
			DELETE FROM `grupy_osob` WHERE OsobaGUID LIKE _OsobaGUID;
			DELETE FROM `sys_core` WHERE GUID LIKE _OsobaGUID;
			DELETE FROM `uprawnienia_dict` WHERE Miejsce LIKE _OsobaGUID;
			DELETE FROM `uprawnienia` WHERE Miejsce LIKE _OsobaGUID;			
		END IF;

		IF _MODE IN ('Moduly.REGISTER.Modul') THEN
			IF
				NOT EXISTS(
					SELECT 
						c.GUID 
					FROM `sys_core` c 
					INNER JOIN `osoby` o ON o.GUID = c.GUID
					INNER JOIN `grupy_osob` go ON go.OsobaGUID = c.GUID
					INNER JOIN `uprawnienia_dict` ud ON ud.Miejsce = c.GUID
					INNER JOIN `uprawnienia` u ON u.Miejsce = c.GUID
					WHERE 
						c.GUID = _OsobaGUID
				)
			THEN	
				CALL _user_accounts_sys_cfg('Moduly.ADD.Modul', 0, _OsobaGUID, _Value, _PARAM_A, _PARAM_B, _PARAM_C, _PARAM_D, _PARAM_E);
			END IF;
		END IF;

		IF _MODE LIKE 'Moduly.Dostep.%' THEN
			/****************************************************************************************
			Lista dostępów do modułu/modułow dla uzytkownia wraz z informacjami
			****************************************************************************************/
			IF _MODE IN ('Moduly.Dostep.Init') THEN
				DROP TEMPORARY TABLE IF EXISTS `t_dostep_auth_WE`;
				CREATE TEMPORARY TABLE `t_dostep_auth_WE` (
				  `User_GUID` VARCHAR(38) DEFAULT NULL COMMENT 'uzytkownik',
				  `APP_ID` VARCHAR(38)  COMMENT 'Modul',
				  `APP_Name` VARCHAR(250)  COMMENT 'Modul',
				  PRIMARY KEY `GrupaGUID`(`User_GUID`,`APP_ID`)
				) ENGINE=MYISAM -- DEFAULT CHARSET=UTF8
				;

				DROP TEMPORARY TABLE IF EXISTS `t_dostep_auth`;
				CREATE TEMPORARY TABLE `t_dostep_auth` (
				  `User_GUID` VARCHAR(38) DEFAULT NULL COMMENT 'uzytkownik',
				  `APP_ID` VARCHAR(38) DEFAULT NULL COMMENT 'grupa',
				  `Link_GrupaGUID` VARCHAR(38) DEFAULT NULL COMMENT 'grupa',
				  `Link_OsobaGUID` VARCHAR(38) DEFAULT NULL COMMENT 'grupa',
				  `Link_Kind` VARCHAR(20) DEFAULT NULL COMMENT '"Main"/"SUB"',
				  `Link_Exists` BOOLEAN,
				  `Link_Name` VARCHAR(150) COMMENT 'Nazwa Grupy/Uprawnienia',
				  `Link_Status_OK` INT(11) NOT NULL DEFAULT '1' COMMENT '1 OK 0 Nie',
				  `Link_Status` VARCHAR(150) NOT NULL DEFAULT '???' COMMENT 'status dla wryf. grupy: OK ERR etc',
				  `Link_Status_FULL` VARCHAR(255) COMMENT 'full status dla wryf. grupy',
				  `Link_Status_Descr` VARCHAR(255) NULL COMMENT 'Opis weryf.',
				  PRIMARY KEY `GrupaGUID`(`Link_GrupaGUID`,`Link_OsobaGUID`)
				) ENGINE=MYISAM -- DEFAULT CHARSET=UTF8
				;

			END IF;
			
			IF 
				_MODE LIKE 'Moduly.Dostep.Init<-%' 
				OR
				_MODE LIKE 'Moduly.Dostep.Prepare<-%' 
			THEN
				/****************************************************************************************
				Przygotowanie listy dostępów do modułu wraz z informacjami
				Moduly.Dostep.Prepare<-UserGUID+APP_ID
					CALL _user_accounts_sys_cfg('Moduly.Dostep.Prepare<-UserGUID+APP_ID', 0, '', '', '', '', '', '', ''); --	
					_OsobaGUID - UserGUID
				Moduly.Dostep.Prepare<-`t_authorization_rec`
					CALL _user_accounts_sys_cfg('Moduly.Dostep.Prepare<-`t_authorization_rec`', 0, '', '', '', '', '', '', ''); --	
					_OsobaGUID - UserGUID
					_Value - APP_ID
				Uwaga może byc także 
				Moduly.Dostep.Prepare<-UserGUID+APP_ID.and.Find
				Moduly.Dostep.Prepare<-`t_authorization_rec`.Find
				****************************************************************************************/
				CALL _user_accounts_sys_cfg('Moduly.Dostep.Init', 0, '', '', '', '', '', '', ''); --	
				IF _MODE LIKE 'Moduly.Dostep.%<-UserGUID+APP_ID%' THEN
					INSERT IGNORE INTO `t_dostep_auth_WE`
					SET
						User_GUID = _OsobaGUID,
						APP_ID = _Value
					;
				END IF;
				
				IF _MODE LIKE 'Moduly.Dostep.%<-`t_authorization_rec`%' THEN
				/*
					INSERT IGNORE INTO `t_dostep_auth_WE`
					(User_GUID, APP_ID)	
						SELECT
							ta.User_GUID,
							ta.APP_ID
						FROM `t_authorization_rec` ta
						WHERE
							ta._Verify_Status LIKE 'OK%'
							AND NOT ta._Verify_Access_available
					;
				*/
					SET @blabla = 0;
				END IF;
				
				IF _MODE LIKE 'Moduly.Dostep.Prepare<-%' THEN
				-- IF _MODE LIKE 'Moduly.Dostep.Prepare<-UserGUID+APP_ID%' THEN
					CALL _user_accounts_sys_cfg('Moduly.Dostep.Prepare', 0, '', '', '', '', '', '', ''); --	
				END IF;
			END IF;
			
			IF _MODE = 'Moduly.Dostep.Prepare' THEN
			-- IF _MODE IN ('Moduly.Dostep.Prepare') THEN
				/****************************************************************************************
				Naliczenie / przygotowanie listy dostępów do modułu wraz z informacjami
				****************************************************************************************/
				UPDATE `t_dostep_auth_WE` tdw
				LEFT JOIN `sys_core` c ON c.GUID = tdw.APP_ID
				LEFT JOIN `osoby` o ON o.GUID = tdw.APP_ID
				SET
					-- tdw.APP_Name = o.Nazwisko
					tdw.APP_Name = IFNULL(c.Caption, o.Nazwisko)
				;
				TRUNCATE `t_dostep_auth`;
			--	1. Wstaw główna grupę dostepu
			--	Sprawdz status przynaleznosci do grupy danego uzytkownika
			--	Pamietaj!!! 
			--		jesli jest w głównej grupie to własnie tu miozna mu zablokowac dostep (Daty!!!) a w innych grupach może miec dostep 
			--		dlatego jeśli w głównej grupie ma blokade to dalej nie sprawdzamy
			--	Przykład 
			--		Franek należy do grupy 'M.EXE.PL2003' - ta grupa ma także włączona inna grupe np. "Place_rozliczenia" w której Franek także jest 
			--		i teraz jesli chcę mu odciąć prace w 'M.EXE.PL2003' to w tej przynalezności odcinam i żądam by nie wchidził nawet jeśli w podgrupach 
			--		nie ma blokady!!!
				SET
					@.Fun.Get_SFVFT.Param_A = 'Dostęp do modułu/grupy "#Grupa#" #Text##Delete2##Date#',
					@.Fun.Get_SFVFT.Param_B = 'nastąpi dnia ',
					@.Fun.Get_SFVFT.Param_C = 'wygasł dnia '
				;
			
				SET @LP = 0;
				INSERT IGNORE INTO `t_dostep_auth`
				(User_GUID, APP_ID, Link_GrupaGUID, Link_OsobaGUID, Link_Kind, Link_Exists, Link_Status, Link_Status_FULL)	
					SELECT
						ta.User_GUID,
						ta.APP_ID,
						go.GrupaGUID AS Link_GrupaGUID,
						go.OsobaGUID AS Link_OsobaGUID,
						'USER' AS Link_Kind,
						(go.GrupaGUID IS NOT NULL) AS Link_Exists,
						-- ta.APP_Name AS Link_Name,
						'???' AS Link_Status,
						IF(go.GrupaGUID IS NULL,
							NULL,
							(@.A.S := Get_Status_For_Valid_From_To('GET.FULL', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, @.Fun.Get_SFVFT.Param_A, @.Fun.Get_SFVFT.Param_B, @.Fun.Get_SFVFT.Param_C))
						) AS Link_Status_FULL
					FROM `t_dostep_auth_WE` ta
					LEFT JOIN `grupy_osob` go ON go.GrupaGUID = ta.APP_ID AND go.OsobaGUID = ta.User_GUID
					-- LEFT JOIN `osoby` o ON o.GUID = ta.APP_ID
					WHERE
						TRUE
				;
			--	2. Wstaw pozstałe ewntulne podgrupy dostepu
				INSERT IGNORE INTO `t_dostep_auth`
				(User_GUID, APP_ID, Link_GrupaGUID, Link_OsobaGUID, Link_Kind, Link_Exists, Link_Status, Link_Status_FULL)	
					SELECT
						ta.User_GUID,
						ta.APP_ID,
						go.GrupaGUID AS Link_GrupaGUID,
						go.OsobaGUID AS Link_OsobaGUID,
						CONCAT('GRP->GRP.', @LP := @LP + 1) AS Link_Kind,
						(go.GrupaGUID IS NOT NULL) AS Link_Exists,
						-- ta.APP_Name AS Link_Name,
						'???' AS Link_Status,
						IF(go.GrupaGUID IS NULL,
							NULL,
							(@.A.S := Get_Status_For_Valid_From_To('GET.FULL', NULL, '', go.Deleted, go.Valid_From, go.Valid_To, @.Fun.Get_SFVFT.Param_A, @.Fun.Get_SFVFT.Param_B, @.Fun.Get_SFVFT.Param_C))
						) AS Link_Status_FULL
					FROM `t_dostep_auth_WE` ta
					INNER JOIN `grupy_osob` go_main ON go_main.GrupaGUID = ta.APP_ID 
					INNER JOIN `grupy_osob` go ON go.GrupaGUID = go_main.OsobaGUID AND go.OsobaGUID = ta.User_GUID AND go.OsobaGUID != go.GrupaGUID	--	wazne bo badamy uczestnictwo uzytkownika w tej grupie
					-- LEFT JOIN `osoby` o ON o.GUID = ta.APP_ID
					WHERE
						TRUE
				;
				UPDATE `t_dostep_auth` tdt
				INNER JOIN `t_dostep_auth_WE` ta ON ta.APP_ID = tdt.APP_ID
				LEFT JOIN `sys_core` c ON c.GUID = tdt.Link_GrupaGUID
				LEFT JOIN `osoby` o ON o.GUID = tdt.Link_GrupaGUID
				SET
					tdt.Link_Status = (@.td.Link_Status := 
						IF(NOT tdt.Link_Exists,
							'???',
							NULLIF(SUBSTRING_INDEX(tdt.Link_Status_FULL, '::', 1), '')
						)
					),
					tdt.Link_Status_Descr = 
						IF(NOT Link_Exists,
							CONCAT('brak dostępu do modułu/grupy "', IFNULL(IFNULL(c.Caption, o.Nazwisko), ta.APP_Name), '"'),
							IF(tdt.Link_Status_FULL LIKE 'OK%',
								CONCAT_WS('', 'Dostęp z modułu/grupy "', IFNULL(IFNULL(c.Caption, o.Nazwisko), tdt.Link_GrupaGUID), '"'),
								REPLACE(NULLIF(SUBSTRING_INDEX(tdt.Link_Status_FULL, '::', -1), ''), '#Grupa#', IFNULL(IFNULL(c.Caption, o.Nazwisko), tdt.Link_GrupaGUID))
							)
						),
					tdt.Link_Status_OK = (@.td.Link_Status LIKE 'OK%'),
					-- td.Link_Name = o.Nazwisko
					tdt.Link_Name = IFNULL(c.Caption, o.Nazwisko)
				WHERE
					TRUE
					-- AND tm.Link_Kind = 'M'
				;
				
				
			END IF;
			
			IF _MODE IN ('Moduly.Dostep.Select') THEN
				SELECT * FROM `t_dostep_auth`;
			END IF;
		END IF;
		
		
	END IF;

	IF _MODE = 'SEND.MAIL.for.USER' THEN
	/* *************************************************************************************************************************************************************
		Potwierdzenie hasla z Tokenem
		CALL _user_accounts_sys_cfg('SEND.MAIL.for.USER', 0, User, 'opcj.Grupa dost.', '', '', '', '', '');
		_OsobaGUID	User
		_Value		Grupa dostepowa
		jmam
	**************************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_account_2_send_mail`;
		CREATE TEMPORARY TABLE `t_account_2_send_mail` (
			`_MODE` VARCHAR(150) NOT NULL DEFAULT '',
			`OsobaGUID` VARCHAR(38) NOT NULL DEFAULT '',
			`Imie_Nazwisko` VARCHAR(200) DEFAULT NULL,
			`Nazwisko_Imiona` VARCHAR(200) DEFAULT NULL,
			`Login` VARCHAR(200) DEFAULT NULL,
			`Ad_mail` VARCHAR(200) DEFAULT NULL,
			`Msg_Title` VARCHAR(250),
			`Msg_Body` MEDIUMTEXT,
			`Msg_Body_Link` VARCHAR(250),
			`Portal` VARCHAR(250),
			`Portal_Url` VARCHAR(250),
			`Portal_Descr` MEDIUMTEXT,
			-- `Actv_Status` VARCHAR(50),
			-- `Actv_Status_Msg` MEDIUMTEXT,
			`Owner_Name` VARCHAR(250),
			`Owner_Adr` VARCHAR(250),
			PRIMARY KEY (`OsobaGUID`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8
		;
			CALL _Owner_KontrGUID_Tools('GET.Data.To.Var', '', '', '', '');
			-- SELECT @session.globals.Owner.Name, @session.globals.Owner.Addr;
			TRUNCATE `t_account_2_send_mail`;
			INSERT IGNORE INTO `t_account_2_send_mail`
			SELECT
				'xxx' AS _MODE,
				ua.OsobaGUID,
				CONCAT_WS(' ', o.Imie1, o.Nazwisko) AS Imie_Nazwisko,
				CONCAT_WS(' ', o.Nazwisko, o.Imiona) AS Nazwisko_Imiona,
				ua.Login,
				ua.Ad_mail,
				_PARAM_A AS Msg_Title,
				_PARAM_E AS Msg_Body,
				'' AS Msg_Body_Link,
				IFNULL(c.Caption, '?') AS Portal,
				IFNULL(c.Prog_HREF, '') AS Portal_Url,
				IFNULL(c.Descr, '') AS Portal_Descr,
				REPLACE(REPLACE(@session.globals.Owner.Name, 
					'ograniczoną odpowiedzialnością', 'o.o.'), 
					'OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ', 'O.O.') 
				AS Owner_Name,
				@session.globals.Owner.Addr Owner_Adr
				
			FROM `osoby` o
			INNER JOIN `_user_accounts` ua ON ua.OsobaGUID = o.GUID
			LEFT JOIN `sys_core` c ON c.GUID = _Value
			LEFT JOIN `kontrah` k ON k.GUID = @session.globals.Owner_kontrguid
			WHERE
				o.GUID = _OsobaGUID
			;
			UPDATE `t_account_2_send_mail` ts
			SET
				ts.Msg_Title =
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ts.Msg_Title, 
						'#ImNa#', ts.Imie_Nazwisko), 
						'#N#', ts.Nazwisko_Imiona), 
						'#URL:LINK#', ts.Msg_Body_Link), 
						'#TOKEN#', ''),
						'#LOGIN#', ts.LOGIN),
						'#WWW#', ts.Portal),
						'#WWW_URL#', ts.Portal_Url),
						'#WWW_DESCR#', ts.Portal_Descr),
						'#OWNER#', ts.Owner_Name),
						'#OWNER_ADR#', ts.Owner_Adr),
				ts.Msg_Body =
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ts.Msg_Body, 
						'#ImNa#', ts.Imie_Nazwisko), 
						'#N#', ts.Nazwisko_Imiona), 
						'#URL:LINK#', ts.Msg_Body_Link), 
						'#TOKEN#', ''),
						'#LOGIN#', ts.LOGIN),
						'#WWW#', ts.Portal),
						'#WWW_URL#', ts.Portal_Url),
						'#WWW_DESCR#', ts.Portal_Descr),
						'#OWNER#', ts.Owner_Name),
						'#OWNER_ADR#', ts.Owner_Adr)
						
			;
			SELECT * FROM `t_account_2_send_mail`;
			
	
	END IF;
	
	IF _MODE LIKE 'Profil.GUI%' THEN
	/* *************************************************************************************************************************************************************
		Profil usera w www
		CALL _user_accounts_sys_cfg('Profil.GUI.Main.SELECT', 0, User, 'opcj.Grupa dost.', '', '', '', '', '');
		_OsobaGUID	User
	**************************************************************************************************************************************************************/
		IF _MODE LIKE 'Profil.GUI.Main.Prepare%' THEN
		-- IF _MODE IN ('Profil.GUI.Prepare', 'Profil.GUI.SELECT', 'Profil.GUI.SELECT.Sekcje') THEN
			DROP TEMPORARY TABLE IF EXISTS `t_user_profil_we`;
			CREATE TEMPORARY TABLE `t_user_profil_we` (
				`_MODE` VARCHAR(150) NOT NULL DEFAULT '',
				`UserGUID` VARCHAR(38) NOT NULL DEFAULT '',
				PRIMARY KEY (`UserGUID`)
			)
			;
			INSERT IGNORE INTO `t_user_profil_we`
			(_MODE, UserGUID)
			SELECT
				'PortaFide' AS _MODE,
				ua.OsobaGUID AS UserGUID
			FROM `_user_accounts` ua
			WHERE
				-- ua.OsobaGUID = 'cf23fedf8f020ff365c0e164a6251d76'
				ua.OsobaGUID = _OsobaGUID -- ptest_prac
				-- ua.OsobaGUID = '{13A307C8-3C9E-4ECB-AFCB-BCC218116DBD}' -- ptest_zast
				-- ua.OsobaGUID = '{BB23C6A9-8E4C-430B-9480-29CDC50AB871}'	-- ptestkier
			
			;
			/*
			TRUNCATE `t_user_profil_inf`;
			INSERT IGNORE INTO `t_user_profil_inf`
			(_MODE, UserGUID)
			SELECT
				'PortaFide' AS _MODE,
				ua.OsobaGUID AS UserGUID
			FROM `_user_accounts` ua
			WHERE
				-- ua.OsobaGUID = 'cf23fedf8f020ff365c0e164a6251d76'
				ua.OsobaGUID = _OsobaGUID -- ptest_prac
				-- ua.OsobaGUID = '{13A307C8-3C9E-4ECB-AFCB-BCC218116DBD}' -- ptest_zast
				-- ua.OsobaGUID = '{BB23C6A9-8E4C-430B-9480-29CDC50AB871}'	-- ptestkier
			
			;
			
			SHOW CREATE TABLE `t_user_profil_inf`;
			SHOW CREATE TABLE `t_user_profil_inf_sec`;
			*/

			DROP TEMPORARY TABLE IF EXISTS `t_user_profil_inf_sec`;
			CREATE TEMPORARY TABLE `t_user_profil_inf_sec` (
				-- `_MODE` VARCHAR(150) NOT NULL DEFAULT '',
				`Sekcja` VARCHAR(100) NOT NULL DEFAULT '',
				`ID` VARCHAR(30) DEFAULT NULL,
				`Caption` VARCHAR(150) DEFAULT NULL,
				`Content` MEDIUMTEXT,
				`LP` VARCHAR(20) DEFAULT NULL,
				-- `Button_1` VARCHAR(200) DEFAULT NULL,	-- np "Zmień"/"Edytuj"
				-- `Button_2` VARCHAR(200) DEFAULT NULL,	-- np "Wstaw"
				-- `Button_3` VARCHAR(200) DEFAULT NULL,	-- np "Usuń"
				`json_Buttons` MEDIUMTEXT,
				-- `Buttons` MEDIUMTEXT,
				`CtxKey1` VARCHAR(38) DEFAULT NULL,
				`CtxKey2` VARCHAR(38) DEFAULT NULL,
				`Param1` VARCHAR(150) DEFAULT NULL,
				`Param2` VARCHAR(150) DEFAULT NULL,
				`Param3` VARCHAR(150) DEFAULT NULL,
				PRIMARY KEY (`ID`)
				-- UNIQUE KEY (`Sekcja`, `Caption`)
			)DEFAULT CHARSET=UTF8
			;
			
			DROP TEMPORARY TABLE IF EXISTS `t_user_profil_inf`;
			CREATE TEMPORARY TABLE `t_user_profil_inf` 
			SELECT
				'PortaFide' AS _MODE,
				ua.GUID AS UserGUID,
				ua.NazwiskoImie,
				ua.IdnUser AS Login, 
				ua.PracInfo, 
				-- ua.StanowiskoInfo, 
				IF(p.GUID IS NOT NULL,
					CONCAT_WS(', dz.: ', 
						stan.stanowisko,
						dz.Opis
					),
					ua.StanowiskoInfo
				) AS StanowiskoInfo, 
				ua.Konto_Status_Str, 
				_Format_DT(ua.LastUpdate, '%DZ%DW %D %mmm %YH %HH:%NN') AS LastUpdateStr, 
				ua.Ad_Mail, 
				_Format_DT(ua.Last_Change_Pswd, '%DZ%DW %D %mmm %YH %HH:%NN') AS Last_Change_PswdStr, 
				ua.dost_do_App, 
				CONCAT_WS(' ',
					ua.Konto_Status_str,
					IF(ua.User_type = 2, _VarStr('(typu gość)'), IF(ua.User_type = 1, NULL, NULL))
				) AS Account_Inf,
				CONCAT_WS(', ',
					CONCAT('Grup: ', _VarStr(ua.cc)),
					CONCAT(
						'Upraw.: ', 
						IFNULL((SELECT COUNT(*) FROM `uprawnienia` up WHERE up.osobaguid = ua.GUID), 0)
					)
				) AS InclusInf,
			--	Logowania skuteczne
			/*
				IF(sdlagg.CC = 0,
					'Nie aktywna',
					CONCAT_WS(',\n',
						_varStr(CONCAT('Logowań: ', sdlagg.CC)),
						_varStr(
							CONCAT_WS('',
								'aplikacji: ', 
								sdlagg.APP_CC,
								CONCAT(' (', sdlagg.APP_Names, ')')
							)
						),
						_varStr(
							CONCAT_WS('',
								'ost.logow.: ', 
								_Format_DT(MAX(sdlLast.Last_Use), '%DZ%DW %dd %d %mmm %YH o %H:%N:%S'),
								CONCAT(' (', sdlLast.Last_APP_Name, ')')
							)
						)
					)
					
				) AS Usage_last_1_month,
				*/
				IF(sdlagg.CC = 0,
					'Nie aktywna',
					CONCAT_WS(',\n',
						-- _varStr(CONCAT('Logowań: ', sdlagg.CC)),
						_varStr(CONCAT('Logowań: ', sdlagg.CC_LOG_OK)),
						_varStr(
							CONCAT_WS('',
								'aplikacji: ', 
								sdlagg.APP_CC_OK, -- sdlagg.APP_CC,
								CONCAT(' (', sdlagg.APP_Names_OK, ')') -- CONCAT(' (', sdlagg.APP_Names, ')')
							)
						),
						_varStr(
							CONCAT_WS('',
								'ost.logow.: ', 
								_Format_DT(MAX(sdlLastOK.Last_Use), '%DZ%DW %dd %d %mmm %YH o %H:%N:%S'),
								CONCAT(' (', sdlLastOK.Last_APP_Name, ')')
							)
						)
					)
					
				) AS Usage_last_1_month,
			--	Błedne logowania	
				IF(sdlagg.CC_LOG_Err = 0,
					NULL,
					CONCAT_WS(',\n',
						_varStr(CONCAT('Błędnych logowań: ', sdlagg.CC_LOG_Err)),
						_varStr(
							CONCAT_WS('',
								'aplikacji: ', 
								sdlagg.APP_CC_Err, -- sdlagg.APP_CC,
								CONCAT(' (', sdlagg.APP_Names_Err, ')') -- CONCAT(' (', sdlagg.APP_Names, ')')
							)
						),
						_varStr(
							CONCAT_WS('',
								'ost. błędne logow.: ', 
								_Format_DT(MAX(sdlLastErr.Last_Use), '%DZ%DW %dd %d %mmm %YH o %H:%N:%S'),
								CONCAT(' (', sdlLastErr.Last_APP_Name, ')')
							)
						)
					)
					
				) AS Usage_last_1_month_err,
			
				'OK' AS Valid_STATUS,
				IFNULL((SELECT COUNT(*) FROM `uprawnienia` up WHERE up.osobaguid = ua.GUID), 0) AS CC_SelfUpr
			FROM `v_user_accounts` ua, `t_user_profil_we` we
			LEFT JOIN `Pracownicy` p ON p.GUID = we.UserGUID
			LEFT JOIN `stanowiska` stan ON stan.GUID = p.stanowisko
			LEFT JOIN `dzialy` dz ON dz.Idn = p.Dzial
			LEFT JOIN (
				SELECT
					COUNT(*) AS CC,
					COUNT(DISTINCT IFNULL(sdl.log_APP_ID, sdl.log_APPNAME)) AS APP_CC,
					COUNT(DISTINCT IF(NOT (sdl.Status IN ('NEW', 'LOG.ERR')), IFNULL(sdl.log_APP_ID, sdl.log_APPNAME), NULL)) AS APP_CC_OK,
					COUNT(DISTINCT IF((sdl.Status IN ('NEW', 'LOG.ERR')), IFNULL(sdl.log_APP_ID, sdl.log_APPNAME), NULL)) AS APP_CC_Err,
					SUM(NOT (sdl.Status IN ('NEW', 'LOG.ERR'))) AS CC_LOG_OK,
					SUM((sdl.Status IN ('NEW', 'LOG.ERR'))) AS CC_LOG_Err,
					GROUP_CONCAT(
						DISTINCT IFNULL(sdl.log_APP_ID, sdl.log_APPNAME)
					) AS APP_Names,
					GROUP_CONCAT(
						DISTINCT IF(NOT (sdl.Status IN ('NEW', 'LOG.ERR')), IFNULL(sdl.log_APP_ID, sdl.log_APPNAME), NULL)
					) AS APP_Names_OK,
					GROUP_CONCAT(
						DISTINCT IF((sdl.Status IN ('NEW', 'LOG.ERR')), IFNULL(sdl.log_APP_ID, sdl.log_APPNAME), NULL)
					) AS APP_Names_Err,
					MAX(sdl.Ping_AT) AS Last_Ping
				FROM `t_user_profil_we` we, `_sys_db_logons` sdl
				WHERE
					sdl.log_USER_GUID = we.UserGUID --  _OsobaGUID
					-- AND NOT (sdl.Status IN ('NEW', 'LOG.ERR'))
					AND sdl.CONNECT_AT > NOW() - INTERVAL 1 MONTH
				ORDER BY sdl.CONNECT_AT DESC 
			) sdlagg ON TRUE
			LEFT JOIN (
				SELECT
					sdl.Ping_AT AS Last_Use,
					sdl.log_APPNAME AS Last_APP_Name
				FROM `t_user_profil_we` we, `_sys_db_logons` sdl
				WHERE
					sdl.log_USER_GUID = we.UserGUID --  _OsobaGUID
					AND NOT (sdl.Status IN ('NEW', 'LOG.ERR'))
					AND sdl.CONNECT_AT > NOW() - INTERVAL 1 MONTH
				ORDER BY sdl.CONNECT_AT DESC 
				LIMIT 1
			) sdlLastOK ON TRUE
			LEFT JOIN (
				SELECT
					sdl.Ping_AT AS Last_Use,
					sdl.log_APPNAME AS Last_APP_Name
				FROM `t_user_profil_we` we, `_sys_db_logons` sdl
				WHERE
					sdl.log_USER_GUID = we.UserGUID --  _OsobaGUID
					AND (sdl.Status IN ('NEW', 'LOG.ERR'))
					AND sdl.CONNECT_AT > NOW() - INTERVAL 1 MONTH
				ORDER BY sdl.CONNECT_AT DESC 
				LIMIT 1
			) sdlLastErr ON TRUE
			WHERE
				-- ua.GUID = 'IM_a746899861d876574e574c46058bdb2c'
				ua.GUID = we.UserGUID --  _OsobaGUID -- ptest_prac
				-- ua.GUID = '{13A307C8-3C9E-4ECB-AFCB-BCC218116DBD}' -- ptest_zast
				-- ua.GUID = '{BB23C6A9-8E4C-430B-9480-29CDC50AB871}'	-- ptestkier
			;
			
			
			SET @.LP = 0;
			TRUNCATE `t_user_profil_inf_sec`;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Ogólne' AS Sekcja, 
				'Użytkownik:' AS ID, 
				'Użytkownik:' AS Caption, 
				ti.NazwiskoImie AS Content,
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, json_Buttons, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Ogólne' AS Sekcja, 
				'Login:' AS ID, 
				'Login:' AS Caption, 
				ti.Login AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	'Zmień' AS Button_1,
			--	json_Buttons	
				IF(@session.globals.Owner IN ('SKOK'),
					NULL,
					CONCAT_WS('', 
						CONCAT('{"buttons":[{', '"ID":"EDIT.Login","Caption":"Zmień","Color":"primary","Href":"wywolaj"', '}]}')
					)
				) AS json_Buttons,
			--	Buttons	
			--	CONCAT_WS('&', 
			--		CONCAT('B1=', 'EDIT.Login#Zmień')
			--	) AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, json_Buttons, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Ogólne' AS Sekcja, 
				'eMail:' AS ID, 
				'eMail:' AS Caption, 
				ti.Ad_Mail AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	'Zmień' AS Button_1,
			--	json_Buttons	
				IF(@session.globals.Owner IN ('SKOK'),
					NULL,
					CONCAT_WS('', 
						CONCAT('{"buttons":[{', '"ID":"EDIT.eMail","Caption":"Zmień","Color":"primary","Href":"wywolaj"', '}]}')
					)
				) AS json_Buttons,
			--	Buttons	
			--	CONCAT_WS('&', 
			--		CONCAT('B1=', 'EDIT.eMail#Zmień')
			--	) AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Ogólne' AS Sekcja, 
				'Stanowisko użytkownika/osoby:' AS ID, 
				'Stanowisko użytkownika/osoby:' AS Caption, 
				ti.StanowiskoInfo AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			-- LEFT JOIN `Pracownicy` p ON p.GUID = ti.UserGUID
			-- LEFT JOIN `stanowiska` stan ON stan.GUID = p.stanowisko
			-- LEFT JOIN `dzialy` dz ON dz.Idn = p.Dzial
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Status użytkownika/osoby:' AS ID, 
				'Status użytkownika/osoby:' AS Caption, 
				ti.PracInfo AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Status konta:' AS ID, 
				'Status konta:' AS Caption, 
				ti.Account_Inf AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Ostatnia zmiana:' AS ID, 
				'Ostatnia zmiana:' AS Caption, 
				ti.LastUpdateStr AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		--	(Sekcja, ID, Caption, Content, LP, Button_1, json_Buttons, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Hasło zmieniane:' AS ID, 
				'Hasło zmieniane:' AS Caption, 
				ti.Last_Change_PswdStr AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	'Zmień hasło' AS Button_1,
			--	json_Buttons	
				CONCAT_WS('', 
					CONCAT('{"buttons":[{', '"ID":"EDIT.Pswd","Caption":"Zmień hasło","Color":"primary","Href":"wywolaj"', '}]}')
				) AS json_Buttons,
			--	Buttons	
			--	CONCAT_WS('&', 
			--		CONCAT('B1=', 'EDIT.Pswd#Zmień')
			--	) AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Dostęp do aplik.:' AS ID, 
				'Dostęp do aplik.:' AS Caption, 
				ti.dost_do_App AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				'Konto' AS Sekcja, 
				'Grupy, uprawnienia:' AS ID, 
				'Grupy, uprawnienia:' AS Caption, 
				ti.InclusInf AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				_VarStr('Konto') AS Sekcja, 
				'Logowania w ost. m-c:' AS ID, 
				'Logowania w ost. m-c:' AS Caption, 
				ti.Usage_last_1_month AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT
				_VarStr('Konto') AS Sekcja, 
				'Błędne logowania w ost. m-c:' AS ID, 
				'Błędne Logowania w ost. m-c:' AS Caption, 
				ti.Usage_last_1_month_err AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT 
				'PortaFide' AS Sekcja, 
				'Szef:' AS ID, 
				'Szef:' AS Caption, 
				CONCAT_WS(' ', o.Nazwisko, o.Imie1) AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			INNER JOIN `v_prac_szef` ps ON ps.PracGUID = ti.UserGUID
			INNER JOIN `osoby` o ON o.GUID = ps.SzefGUID
			LIMIT 1
			;
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		-- 	(Sekcja, ID, Caption, Content, LP, Button_1, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT 
				'PortaFide' AS Sekcja, 
				'Brygadzista:' AS ID, 
				'Brygadzista:' AS Caption, 
				CONCAT_WS(' ', o.Nazwisko, o.Imie1) AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				NULL AS json_Buttons,
			--	'' AS Button_1,
			--	Buttons	
			--	NULL AS Buttons,
				ti.UserGUID AS CtxKey1, NULL AS CtxKey2
			FROM `t_user_profil_inf` ti
			INNER JOIN `v_prac_bryg` ps ON ps.PracGUID = ti.UserGUID
			INNER JOIN `osoby` o ON o.GUID = ps.BrygGUID
			LIMIT 1
			;
			
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		--	(Sekcja, ID, Caption, Content, LP, json_Buttons, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT 
				'PortaFide' AS Sekcja, 
				'Domyślny zastępca:' AS ID, 
				'Domyślny zastępca:' AS Caption, 
				IF(o.Nazwisko IS NULL,
					'brak',
					CONCAT_WS(' ', o.Nazwisko, o.Imie1, '-', 
						Get_Status_For_From_To_Str('GET.Info.Zastepstwo.Full', NOW(), ps.DateFrom, ps.DateTo, ps.Status, 0, '', '')
					)
				) AS Content, 
				@.LP := @.LP + 1 AS LP, 
			--	json_Buttons	
				IF(ps.ZastepcaGUID IS NOT NULL,
					CONCAT('{"buttons":[{', '"ID":"EDIT.Zastepca","Caption":"Zmień","Color":"primary","Href":"wywolaj"', '}]}'),
					CONCAT('{"buttons":[{', '"ID":"ADD.Zastepca","Caption":"Dodaj zast.","Color":"primary","Href":"wywolaj"', '}]}')
				) AS json_Buttons,
			--	Buttons	
			--	CONCAT_WS('&', 
			--		CONCAT('B1=', 'CHOICE.Zastepca#Zmień')
			--	) AS Buttons,
				ti.UserGUID AS CtxKey1, 
				ps.ZastepcaGUID AS CtxKey2
			FROM `t_user_profil_inf` ti
			LEFT JOIN `v_prac_zastepca` ps ON ps.PracGUID = ti.UserGUID
			LEFT JOIN `osoby` o ON o.GUID = ps.ZastepcaGUID
			LIMIT 1
			;
			SET @.LP.zast = 0;
			
			INSERT IGNORE INTO `t_user_profil_inf_sec`
		--	(Sekcja, ID, Caption, Content, LP, Button_1, Button_2, Button_3, json_Buttons, Buttons, CtxKey1, CtxKey2)
		--	(Sekcja, ID, Caption, Content, LP, json_Buttons, Buttons, CtxKey1, CtxKey2)
			(Sekcja, ID, Caption, Content, LP, json_Buttons, CtxKey1, CtxKey2)
			SELECT 
				'PortaFide' AS Sekcja, 
				CONCAT('Zastępujesz:', (@.LP.zast := @.LP.zast + 1)) AS ID, 
				IF(@.LP.zast = 1, 'Zastępujesz pracownika:', '') AS Caption, 
				CONCAT_WS(' ', 
					-- CONCAT(@.LP.zast, '.'),
					tSub.OsobaZastepowana, '-', tSub.Status_Str
				) AS Content, 
				@.LP := @.LP + 1 AS LP, 
				/*
				IF(tSub.OUT_Status IS NULL, 
					'Dodaj',
					'Zmień'
				) AS Button_1,
				IF(tSub.OUT_Status IS NULL, 
					'',
					IF(tSub.OUT_Status IN ('Offer'), 
						'Zaakceptuj',
						IF(tSub.OUT_Status IN ('Canceled', 'Reject'), 
							'Zmień decyzję i zaakceptuj',
							IF(tSub.OUT_Status LIKE 'OK%',
								'Anuluj zast.',
								''
							)
						)
					)
				) AS Button_2,
				IF(tSub.OUT_Status IS NULL, 
					'',
					IF(tSub.OUT_Status IN ('Offer'), 
						'Odrzuć',
						IF(tSub.OUT_Status LIKE 'OK%',
							'Zmień decyzję i odrzuć',
							''
						)
					)
				) AS Button_3,
				*/
			--	json_Buttons	
				_Brackets('{"buttons":[',
					CONCAT_WS(',', 
					--	1 button	
						_Brackets('{',
						IF(tSub.OUT_Status IS NULL, 
							'"ID":"ADD.Zast","Caption":"Dodaj","Color":"primary","Href":"wywolaj"',
							'"ID":"ADD.Zast","Caption":"Dodaj kolejne","Color":"primary","Href":"wywolaj"'
						), '}'),
					--	1 Prim button	
						_Brackets('{',
						IF(tSub.OUT_Status IS NULL, 
							NULL,
							'"ID":"EDIT.Zast","Caption":"Zmień","Color":"primary","Href":"wywolaj"'
						), '}'),
					--	2 button	
						_Brackets('{',
						IF(tSub.OUT_Status IS NULL, 
							NULL,
							IF(tSub.OUT_Status IN ('Offer'), 
								'"ID":"ACCEPT.Zast","Caption":"Zaakceptuj","Color":"success","Href":"wywolaj"',
								IF(tSub.OUT_Status IN ('Canceled', 'Reject'), 
									'"ID":"ACCEPT.Zast","Caption":"Zmień decyzję i zaakceptuj","Color":"success","Href":"wywolaj"',
									/*
									IF(tSub.OUT_Status LIKE 'OK%',
										'"ID":"CANCEL.Zast","Caption":"Anuluj zast.","Color":"danger","Href":"wywolaj"',
										NULL
									)
									*/
									NULL
								)
							)
						),
						'}'),
					--	3 button	
						_Brackets('{',
						IF(tSub.OUT_Status IS NULL, 
							NULL,
							IF(tSub.OUT_Status IN ('Offer'), 
								'"ID":"REJECT.Zast","Caption":"Odrzuć","Color":"danger","Href":"wywolaj"',
								IF(tSub.OUT_Status LIKE 'OK%',
									'"ID":"REJECT.Zast","Caption":"Zmień decyzję i Odrzuć","Color":"danger","Href":"wywolaj"',
									NULL
								)
							)
						),
					'}')
					),
					']}'
				) AS json_Buttons,
				ti.UserGUID AS CtxKey1, 
				tSub.PracGUID AS CtxKey2
			FROM `t_user_profil_inf` ti 
			LEFT JOIN 
			(
				SELECT 
					CONCAT_WS(' ', o.Nazwisko, o.Imie1) AS OsobaZastepowana,
					Get_Status_For_From_To_Str('GET.Info.Zastepstwo.Full', NOW(), ps.DateFrom, ps.DateTo, ps.Status, 0, '', '') AS Status_Str,
					@.OUT.Status AS OUT_Status,
					ps.PracGUID, ps.ZastepcaGUID,
					ps.DateFrom, ps.DateTo, ps.Status
				FROM `t_user_profil_inf` ti
				INNER JOIN `v_prac_zastepca` ps ON ps.ZastepcaGUID = ti.UserGUID
				INNER JOIN `osoby` o ON o.GUID = ps.PracGUID
				-- where false
				ORDER BY ps.DateFrom
			) AS tSub ON TRUE
			;
		END IF;
						
		-- IF _MODE IN ('Profil.GUI.SELECT') THEN
		IF _MODE LIKE 'Profil.GUI.Main.%SELECT' THEN
			SELECT ti.* FROM `t_user_profil_inf_sec` ti;
		END IF;
		
		-- IF _MODE IN ('Profil.GUI.SELECT.Sekcje') THEN
		IF _MODE LIKE 'Profil.GUI.Main.%SELECT.Sekcje' THEN
			SELECT ti.Sekcja FROM `t_user_profil_inf_sec` ti GROUP BY ti.Sekcja;
		END IF;
		
		IF _MODE LIKE 'Profil.GUI.Zastepca%' THEN
		/* *************************************************************************************************************************************************************
			Zastepca - wskazanie osoby do zastępstwa
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepca.SELECT', 0, User, '', '', '', '', '', '');
			_OsobaGUID	User
		**************************************************************************************************************************************************************/
			IF _MODE LIKE 'Profil.GUI.Zastepca.Select%' THEN
				SET
					@.Profil.GUI.Zastepca.ZastepcaGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'ZastepcaGUID', ''), '')
						)
				;
				SELECT 
					CONCAT_WS(' ', ouser.Nazwisko, ouser.Imie1) AS OsobaZastepowana,
					CONCAT_WS(' ', zastepca.Nazwisko, zastepca.Imie1) AS OsobaZastepca,
					CONCAT_WS(' ', 'Osoba zastępowana:', ouser.Nazwisko, ouser.Imie1) AS DecrPre,
					CONCAT_WS(' ', 
						'Pracownika:', ouser.Nazwisko, ouser.Imie1, 
						_VarStr('zastępuje...'), 
						IF(ps.PracGUID IS NULL,
							_VarStr('???'),
							CONCAT_WS(' ',
								zastepca.Nazwisko, zastepca.Imie1, '-', 
								Get_Status_For_From_To_Str('GET.Info.Zastepstwo.Full', NOW(), ps.DateFrom, ps.DateTo, ps.Status, 0, '', '')
							)
						)
					) AS Descr, 
					
					-- ps.*
					ps.PracGUID,
					ps.ZastepcaGUID,
					ps.Rel,
					ps.A_Rel_Unique,
					DATE(ps.DateFrom) AS DateFrom, 
					-- ps.DateTo, 
					DATE(GREATEST(ps.DateTo, ps.DateFrom)) AS DateTo, 
					ps.Status
					
				FROM `osoby` ouser
				LEFT JOIN `v_prac_zastepca` ps ON ps.PracGUID = ouser.GUID AND IF(@.Profil.GUI.Zastepca.ZastepcaGUID IS NULL, TRUE, ps.ZastepcaGUID = @.Profil.GUI.Zastepca.ZastepcaGUID)
				LEFT JOIN `osoby` zastepca ON zastepca.GUID = ps.ZastepcaGUID
				WHERE
					ouser.GUID =_OsobaGUID
					-- ouser.GUID = '{E7F59AE5-D1B0-4428-99C7-6F9F7F40974E}'
					-- ps.PracGUID =_OsobaGUID
				LIMIT 1
				;
				
			END IF;
			
			IF _MODE LIKE 'Profil.GUI.Zastepca.Update%' THEN
				SET
					@.Profil.GUI.Zastepca.ZastepcaGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'ZastepcaGUID', ''), '')
						),
					@.Profil.GUI.Zastepca.ZastepcaGUID.OLD = NULL,
					@.Profil.GUI.Zastepca.Status = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'Status', ''), ''),
					@.Profil.GUI.Zastepca.Status.OLD = NULL,
					@.Profil.GUI.Zastepca.DateFrom = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'DateFrom', ''), ''),
					@.Profil.GUI.Zastepca.DateTo = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'DateTo', ''), '')
				;
				IF @.Profil.GUI.Zastepca.ZastepcaGUID IS NOT NULL THEN
					SET
						@.zast.Save.Time = NOW()
					;
					INSERT IGNORE INTO `v_prac_zastepca`
					SET
						Rel = '<-zastepca',
						-- PracGUID = '{30C0B310-6A73-4274-BEE7-96F2F068777E}',
						A_Rel_Unique = 1,
						PracGUID =_OsobaGUID,
						ZastepcaGUID = @.Profil.GUI.Zastepca.ZastepcaGUID,
						`Status` = IFNULL(@.Profil.GUI.Zastepca.Status, DEFAULT(`v_prac_zastepca`.`Status`)),
						DateFrom = IFNULL(NULLIF(@.Profil.GUI.Zastepca.DateFrom, ''), '0000-00-00 00:00:00'),
						DateTo = IFNULL(NULLIF(@.Profil.GUI.Zastepca.DateTo, ''), '2100-12-31 00:00:00')
					ON DUPLICATE KEY UPDATE
						A_Rel_Unique = 1,
						ZastepcaGUID = 
						--	teczniczny IF aby mieć @.Profil.GUI.Zastepca.ZastepcaGUID.OLD
							IF((@.Profil.GUI.Zastepca.ZastepcaGUID.OLD := ZastepcaGUID) IS NULL, 
								@.Profil.GUI.Zastepca.ZastepcaGUID,
								@.Profil.GUI.Zastepca.ZastepcaGUID
							),
						--	teczniczny IF aby mieć @.Profil.GUI.Zastepca.ZastepcaGUID.OLD
						`Status` = 
							IF((@.Profil.GUI.Zastepca.Status.OLD := Status) IS NULL, 
								IFNULL(@.Profil.GUI.Zastepca.Status, DEFAULT(`Status` )),
								IFNULL(@.Profil.GUI.Zastepca.Status, DEFAULT(`Status` ))
							),
						DateFrom = IFNULL(NULLIF(@.Profil.GUI.Zastepca.DateFrom, ''), DateFrom),
						DateTo = IFNULL(NULLIF(@.Profil.GUI.Zastepca.DateTo, ''), DateTo)
					;
					SET @.Profil.GUI.Zastepca.ROW_COUNT = ROW_COUNT();
set @.X.Prof = concat_WS('/', @.X.Prof, concat_WS('', 'row:', @.Profil.GUI.Zastepca.ROW_COUNT));
					--	0 nic, 1 INSERT, 2 ON DUPLICATE...
					IF @.Profil.GUI.Zastepca.ROW_COUNT > 0 THEN
						SET @.Profil.GUI.Zastepstwa.ROW_COUNT = NULL;
					--	Wyslij powiadomiecie do zainteresowanego - ZastepcaGUID
						SET @.zast.Last.Updates = @.zast.Save.Time;
set @.X.Prof = concat_WS('/', @.X.Prof, concat_WS('', 'czas:', @.zast.Last.Updates));
set @.X.Prof = concat_WS('/', @.X.Prof, concat_WS('', 'SendMsg:', 'Start'));
						CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MSG', 0, @.Profil.GUI.Zastepca.ZastepcaGUID, '', '', '', '', '', '');
					--	Wyslij mail do zainteresowanego - ZastepcaGUID
						SET @.zast.Last.Updates = @.zast.Save.Time;
set @.X.Prof = concat_WS('/', @.X.Prof, concat_WS('', 'czas:', @.zast.Last.Updates));
set @.X.Prof = concat_WS('/', @.X.Prof, concat_WS('', 'SendMail:', 'Start'));
						CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MAIL', 0, @.Profil.GUI.Zastepca.ZastepcaGUID, '', '', '', '', '', '');
					END IF;
				END IF;
				IF _MODE LIKE 'Profil.GUI.Zastepca.Update%Select%' THEN
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepca.Select', 0, _OsobaGUID, _Value, '', '', '', '', _PARAM_E);
				END IF;
			END IF;
		END IF;
		
		IF _MODE LIKE 'Profil.GUI.Zastepstwa%' THEN
		/* *************************************************************************************************************************************************************
			Zastępstwo - wskazanie osoby do zastępstwa
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.SELECT', 0, User, 'opcj.Grupa dost.', '', '', '', '', '');
			_OsobaGUID	User
		**************************************************************************************************************************************************************/
			IF _MODE LIKE 'Profil.GUI.Zastepstwa.Select%' THEN
				SET
					@.Profil.GUI.Zastepstwa.PracGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'PracGUID', ''), '')
						)
				;
				SELECT 
					CONCAT_WS(' ', ouser.Nazwisko, ouser.Imie1) AS OsobaZastepujaca,
					CONCAT_WS(' ', 'Osoba zastępująca:', o.Nazwisko, o.Imie1) AS DecrPre,
					CONCAT_WS(' ', _VarStr('Zastępstwo za...'), o.Nazwisko, o.Imie1, '-', 
						IF(ps.ZastepcaGUID IS NULL,
							_VarStr('???'),
							Get_Status_For_From_To_Str('GET.Info.Zastepstwo.Full', NOW(), ps.DateFrom, ps.DateTo, ps.Status, 0, '', '')
						)
					) AS Descr, 
					-- ps.*
					ps.PracGUID,
					ps.ZastepcaGUID,
					ps.Rel,
					ps.A_Rel_Unique,
					DATE((@.ps.DateFrom := GREATEST(ps.DateFrom, CURRENT_DATE()))) AS DateFrom,
					DATE(GREATEST(ps.DateTo, @.ps.DateFrom)) AS DateTo, 
					ps.Status
				FROM `osoby` ouser
				LEFT JOIN `v_prac_zastepca` ps ON ps.ZastepcaGUID = ouser.GUID AND ps.PracGUID = @.Profil.GUI.Zastepstwa.PracGUID
				LEFT JOIN `osoby` o ON o.GUID = ps.PracGUID
				WHERE
					ouser.GUID =_OsobaGUID
					-- ps.PracGUID = '{30C0B310-6A73-4274-BEE7-96F2F068777E}'
					-- ps.PracGUID =_OsobaGUID
				LIMIT 1
				;
			/*
				SELECT 
					CONCAT_WS(' ', o.Nazwisko, o.Imie1) AS OsobaZastepowana,
					CONCAT_WS(' ', o.Nazwisko, o.Imie1, '-', 
						Get_Status_For_From_To_Str('GET.Info.Zastepstwo.Full', NOW(), ps.DateFrom, ps.DateTo, ps.Status, 0, '', '')
					) AS Descr, 
					ps.*
				FROM `v_prac_zastepca` ps 
				INNER JOIN `osoby` o ON o.GUID = ps.PracGUID
				WHERE
					-- ps.PracGUID = '{30C0B310-6A73-4274-BEE7-96F2F068777E}'
					ps.ZastepcaGUID =_OsobaGUID
				;
			*/
			END IF;
			
			IF _MODE LIKE 'Profil.GUI.Zastepstwa.Delete%' THEN
				SET
					@.Profil.GUI.Zastepstwa.PracGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'PracGUID', ''), '')
						)
				;
				IF @.Profil.GUI.Zastepstwa.PracGUID IS NOT NULL THEN
					DELETE FROM `v_prac_zastepca`
					WHERE
						Rel = '<-zastepca'
						AND PracGUID = @.Profil.GUI.Zastepstwa.PracGUID
						AND ZastepcaGUID = _OsobaGUID
					;
				END IF;
				IF _MODE LIKE 'Profil.GUI.Zastepstwa.Delete%Select%' THEN
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Select', 0, _OsobaGUID, _Value, '', '', '', '', '');
				END IF;
			END IF;
			
			IF _MODE LIKE 'Profil.GUI.Zastepstwa.Status<-%' THEN
		/* *************************************************************************************************************************************************************
			Ustawianie stanu zastepstwa
		--	Akceptacja  
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-ACCEPT+Select', 0, User, PracGUID, '', '', '', '', '');
		--	Propozycja - wstępny status 
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-Offer+Select', 0, User, PracGUID, '', '', '', '', '');
		--	Anulowany
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-CANCEL+Select', 0, User, PracGUID, '', '', '', '', '');
		--	Odrzucony
			CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-REJECT+Select', 0, User, PracGUID, '', '', '', '', '');
			_OsobaGUID	User - jako zastepca
			_Value		PracGUID	ale może byc w sznurku
		**************************************************************************************************************************************************************/
				SET
					@.Profil.GUI.Zastepstwa.PracGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'PracGUID', ''), '')
						)
				;
				IF @.Profil.GUI.Zastepstwa.PracGUID IS NOT NULL THEN
				/*------------------------------------------------------------------------------------
					0	- OK / Akceptuj
					-1	- Propozycja (Offer) - wstępny status 
					1	- Usuniety (Deleted) 
					2	- Anulowany (Canceled)
					3	- Odrzucony (Reject)
					Generalnie 0 OK ale też awaryjnie akcepujemy wszystkie NOT (Status > 0) 
				------------------------------------------------------------------------------------*/
					SET
						@.Params.Far = 
							CONCAT_WS('&',
								CONCAT('PracGUID=', @.Profil.GUI.Zastepstwa.PracGUID),
								CONCAT('Status=', 
									IF(_MODE LIKE 'Profil.GUI.Zastepstwa.Status<-Offer',
										-1,	-- Propozycja (Offer) - wstępny status 
										IF(_MODE LIKE 'Profil.GUI.Zastepstwa.Status<-ACCEPT',
											0,	-- Propozycja (Offer) - wstępny status 
											IF(_MODE LIKE 'Profil.GUI.Zastepstwa.Status<-CANCEL',
												2,	-- Anulowany (Canceled)
												IF(_MODE LIKE 'Profil.GUI.Zastepstwa.Status<-REJECT',
													3,	-- Odrzucony (Reject)
													0
												)
											)	
										)
									)
								)
							)
					;
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Update', 0, _OsobaGUID, '', '', '', '', '', @.Params.Far);		
				END IF;
				IF _MODE LIKE 'Profil.GUI.Zastepstwa.Status%Select%' THEN
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Select', 0, _OsobaGUID, _Value, '', '', '', '', '');
				END IF;
			END IF;
			
			IF _MODE LIKE 'Profil.GUI.Zastepstwa.Update%' THEN
				SET
					@.Profil.GUI.Zastepstwa.PracGUID = 
						IFNULL(NULLIF(_Value, ''),
							NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'PracGUID', ''), '')
						),
					-- @.Profil.GUI.Zastepstwa.ZastepcaGUID = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'ZastepcaGUID', ''), ''),
					@.Profil.GUI.Zastepstwa.Status = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'Status', ''), ''),
					@.Profil.GUI.Zastepstwa.DateFrom = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'DateFrom', ''), ''),
					@.Profil.GUI.Zastepstwa.DateTo = NULLIF(_Params2('_FetchParams', '', _PARAM_E, 'DateTo', ''), '')
				;
				IF @.Profil.GUI.Zastepstwa.PracGUID IS NOT NULL THEN
					SET
						@.zast.Save.Time = NOW()
					;
					INSERT IGNORE INTO `v_prac_zastepca`
					SET
						Rel = '<-zastepca',
						-- PracGUID = '{30C0B310-6A73-4274-BEE7-96F2F068777E}',
						PracGUID = @.Profil.GUI.Zastepstwa.PracGUID,
						ZastepcaGUID = _OsobaGUID,
						A_Rel_Unique = 1,
						`Status` = IFNULL(@.Profil.GUI.Zastepstwa.Status, DEFAULT(`Status` )),
						DateFrom = IFNULL(NULLIF(@.Profil.GUI.Zastepstwa.DateFrom, ''), '0000-00-00 00:00:00'),
						DateTo = IFNULL(NULLIF(@.Profil.GUI.Zastepstwa.DateTo, ''), '2100-12-31 00:00:00')
					ON DUPLICATE KEY UPDATE
						PracGUID = @.Profil.GUI.Zastepstwa.PracGUID,
						ZastepcaGUID = _OsobaGUID,
						A_Rel_Unique = 1,
						`Status` = IFNULL(@.Profil.GUI.Zastepstwa.Status, DEFAULT(`v_prac_zastepca`.`Status`)),
						DateFrom = IFNULL(NULLIF(@.Profil.GUI.Zastepstwa.DateFrom, ''), DateFrom),
						DateTo = IFNULL(NULLIF(@.Profil.GUI.Zastepstwa.DateTo, ''), DateTo)
					;
					SET @.Profil.GUI.Zastepstwa.ROW_COUNT = ROW_COUNT();
					--	0 nic, 1 INSERT, 2 ON DUPLICATE...
					IF @.Profil.GUI.Zastepstwa.ROW_COUNT > 0 THEN
						SET @.Profil.GUI.Zastepstwa.ROW_COUNT = NULL;
					--	Wyslij powiadomiecie do zainteresowanego - PracGUID	
						SET @.zast.Last.Updates = @.zast.Save.Time;
						CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MSG', 0, @.Profil.GUI.Zastepstwa.PracGUID, '', '', '', '', '', '');
					--	Wyslij mail do zainteresowanego - ZastepcaGUID
						SET @.zast.Last.Updates = @.zast.Save.Time;
						CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MAIL', 0, @.Profil.GUI.Zastepstwa.PracGUID, '', '', '', '', '', '');
					END IF;
				END IF;
				IF _MODE LIKE 'Profil.GUI.Zastepstwa.Update%Select%' THEN
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Select', 0, _OsobaGUID, _Value, '', '', '', '', '');
				END IF;
			END IF;
		END IF;
		
		IF _MODE LIKE 'Profil.GUI.Zast.SEND.%' THEN
		/* *************************************************************************************************************************************************************
			Wysłanie z LOG-u powiadomienia
			CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MSG', 0, Prac/Zast, '', '', '', '', '', '');
			CALL _user_accounts_sys_cfg('Profil.GUI.Zast.SEND.MAIL', 0, Prac/Zast, '', '', '', '', '', '');
			_OsobaGUID	User powiadamiany
		**************************************************************************************************************************************************************/
			SET
				@.zast.Last.Updates = IFNULL(@.zast.Last.Updates, NOW() - INTERVAL 5 SECOND),
				@.zast.Send.Mode = IF(_MODE = 'Profil.GUI.Zast.SEND.MSG', 'Notification', 'mail')
			;
			IF @.zast.Send.Mode = 'Notification' THEN
				CALL com_notifier('SEND.MSG.From.LOG', _OsobaGUID, '', 'hr_self_links', '1015, 1016', @.zast.Last.Updates, '');
			ELSE
				CALL com_notifier('SEND.MAIL.From.LOG', _OsobaGUID, '', 'hr_self_links', '1015, 1016', @.zast.Last.Updates, '');
			END IF;
			SET
				@.zast.Last.Updates = NULL
			;
			LEAVE S_user_accounts_sys_cfg;
						
		END IF;
		
	END IF;
	
END$$

DROP PROCEDURE IF EXISTS `_user_accounts_create_from_osoba`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_user_accounts_create_from_osoba`(
	IN _MODE VARCHAR(150),
	IN _OsobaGUID VARCHAR(38),
	IN _Osoba_IDN INT,
	IN _Osoba_IdnUser VARCHAR(120),
	IN _Osoba_Datas VARCHAR(120),
	IN _Osoba_user_type INTEGER,
	IN _Osoba_administrator INTEGER,
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200)

)
/*
	CALL _user_accounts_create_from_osoba('', 'OsobaGUID', '', '', '', '', '', '', ''); 
	CALL _user_accounts_create_from_osoba('PARAMS', 'OsobaGUID', 'IDN', 'IdnUser', 'Datas', 'user_type', 'administrator', '', ''); 
	CALL _user_accounts_create_from_osoba('ALL', '', '', '', '', '', '', '', ''); 

*/
S_user_accounts_create_from_osoba: BEGIN
		
	IF _MODE = 'ALL' THEN
		IF @session.LOGON.user_accounts_Mode IS NULL THEN
			CALL _Globals_Get('LOGON.user_accounts_Mode', @session.LOGON.user_accounts_Mode, 0);
		END IF;
		IF @session.LOGON.user_accounts_Mode THEN
			
			DROP TEMPORARY TABLE IF EXISTS `t_ins_user_accounts`;
			CREATE TEMPORARY TABLE `t_ins_user_accounts`
				SELECT
					o.GUID, 'SYS', o.IdnUser, o.datas, o.user_type, o.administrator, CURRENT_DATE(), 0
				FROM `osoby` o
				WHERE
					o.Rodzaj = 1
					AND 
					o.user_type > 0
			;
			-- SELECT * FROM `t_ins_user_accounts`;			
			INSERT IGNORE INTO `_user_accounts`
				(osobaGUID, typ, login, datas, user_type, admin, date_from, STATUS)
				SELECT * FROM `t_ins_user_accounts`	o
			ON DUPLICATE KEY
			UPDATE
				STATUS = IF(STATUS = 2, 0, STATUS), 
				login = o.IdnUser, 
				datas = o.datas,
				user_type = o.user_type, 
				admin = o.administrator
			;
		END IF;
	ELSEIF _MODE != '' THEN
		SET _Osoba_IdnUser = IF(IFNULL(_Osoba_IdnUser, '') = '', _Osoba_IDN, _Osoba_IdnUser);
		IF EXISTS(SELECT IDN FROM `_user_accounts` WHERE Typ = 'SYS' AND login = _Osoba_IdnUser) THEN
			SET _Osoba_IdnUser = CONCAT(_Osoba_IdnUser, _Osoba_IDN);
		END IF;
		INSERT IGNORE INTO `_user_accounts`
			(osobaGUID, typ, login, datas, user_type, admin, date_from, STATUS)
			VALUES
			(_OsobaGUID, 'SYS', _Osoba_IdnUser, _Osoba_Datas, _Osoba_user_type, _Osoba_administrator, CURRENT_DATE(), 0)
		ON DUPLICATE KEY
		UPDATE
			Status = IF(Status = 2, 0, Status) 
		;
	END IF;
	
	IF _MODE = '' THEN
	
		CALL _user_accounts_sys_cfg('accounts.create.NEW', 0, _OsobaGUID, '', '1', '', '', '', '');
		LEAVE S_user_accounts_create_from_osoba;
		
		
		
		
		SELECT
			IDN, IdnUser, Datas, user_type, administrator
		INTO
			_Osoba_IDN, _Osoba_IdnUser, _Osoba_Datas, _Osoba_user_type, _Osoba_administrator
		FROM `osoby`
		WHERE
			GUID = _OsobaGUID
		;	
		CALL _user_accounts_create_from_osoba('PARAMS', _OsobaGUID, _Osoba_IDN, _Osoba_IdnUser, _Osoba_Datas, _Osoba_user_type, _Osoba_administrator, '', ''); 
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_user_accounts_build_login`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_user_accounts_build_login`(
	IN _MODE VARCHAR(150),
	IN _OsobaGUID VARCHAR(38),
	OUT _Login VARCHAR(120),
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200)

)
/*
	CALL _user_accounts_build_login('FIND', 'OsobaGUID', @Login, 'Format', ''); 
	CALL _user_accounts_build_login('FIND', 'f50d4d7a-6216-11eb-9565-00155d000205*', @Login, 'i1.nX(15);iXr2;idnuser(5)', ''); 	
	CALL _user_accounts_build_login('FIND', 'f50d4d7a-6216-11eb-9565-00155d000205*', @Login, 'idnuser(5);i1.nX(15);iXr2', ''); 	
	CALL _user_accounts_build_login('SELECT.Free.Login', 'f50d4d7a-6216-11eb-9565-00155d000205*', @Login, 'idnuser(5);i1.nX(15);iXr2', ''); 	
*/
S_user_accounts_build_login: BEGIN
	IF _MODE IN ('INIT') THEN
		DROP TEMPORARY TABLE IF EXISTS `t_search_dupl_login_ua_inf`;
		CREATE TEMPORARY TABLE `t_search_dupl_login_ua_inf` (
			`GUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'osoba',
			`IDN` INT, 
			`Nazwisko` VARCHAR(38) NOT NULL DEFAULT '',
			`Imie1` VARCHAR(38) NOT NULL DEFAULT '',
			`Imie2` VARCHAR(38) NOT NULL DEFAULT '',
			`DataUrodzenia` DATE NULL,
			-- `YEAR_DataUrodzenia` INT NOT NULL DEFAULT 0,
			`NrPesel` VARCHAR(38) NOT NULL DEFAULT '',
			`IdnUser` VARCHAR(150) NOT NULL DEFAULT '',
			PRIMARY KEY (`GUID`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8;
		IF NULLIF(_OsobaGUID, '') IS NOT NULL THEN
			INSERT IGNORE INTO `t_search_dupl_login_ua_inf`
			SELECT
				o.GUID,
				o.IDN,
				o.Nazwisko,
				o.Imie1, 
				o.Imie2, 
				o.DataUrodzenia, 
				o.NrPesel,
				IF(o.IdnUser = GUID OR o.IdnUser = IDN OR o.IdnUser LIKE '{%-%',
					NULL,
					o.IdnUser
				) AS IdnUser
			FROM `osoby` o
			WHERE
				o.GUID = _OsobaGUID
			;
		END IF;
		DROP TEMPORARY TABLE IF EXISTS `t_search_dupl_login_ua_buf012`;
		CREATE TEMPORARY TABLE `t_search_dupl_login_ua_buf012` (
			`Sect` INT, 
			`Buff` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'osoba',
			`Fmt` VARCHAR(150) NOT NULL DEFAULT '',
			`Build_Login` VARCHAR(50) NOT NULL DEFAULT '',
			`Repeat` INT NOT NULL DEFAULT 1,
			PRIMARY KEY (`Sect`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8;
				
		
	END IF;
	
	IF _MODE = 'PREPARE.N.Sect' THEN
		-- _PARAM_A - zestaw znaków
		/*
		SET @.Sekc.0 = _PARAM_A;	-- 'i1.nX(15);iXr2';
		SET @.Buff.OUT = @.Sekc.0;
		SET @.Sekc.0 = _Buff_Stack('@.TakeOff.First+Delete', @.Buff.OUT, '');
		SET @.Sekc.1 = _Buff_Stack('@.TakeOff.First+Delete', @.Buff.OUT, '');
		SET @.Sekc.2 = _Buff_Stack('@.TakeOff.First+Delete', @.Buff.OUT, '');
		
		IF NULLIF(@.Sekc.0, '') IS NOT NULL THEN
			INSERT INTO `t_search_dupl_login_ua_buf012`
			SET Buff = @.Sekc.0, Sect = 0
			;
		END IF;
		IF NULLIF(@.Sekc.1, '') IS NOT NULL THEN
			INSERT INTO `t_search_dupl_login_ua_buf012`
			SET Buff = @.Sekc.1, Sect = 1
			;
		END IF;
		IF NULLIF(@.Sekc.2, '') IS NOT NULL THEN
			INSERT INTO `t_search_dupl_login_ua_buf012`
			SET Buff = @.Sekc.2, Sect = 2
			;
		END IF;
		*/
		SET @.Sekc.0 = _PARAM_A;	-- 'i1.nX(15);iXr2';
		SET @.Buff.OUT = @.Sekc.0;
		SET @.I = 0;
		REPEAT
			SET @.Sekc.X = _Buff_Stack('@.TakeOff.First+Delete', @.Buff.OUT, '');
			IF NULLIF(@.Sekc.X, '') IS NOT NULL THEN
				INSERT IGNORE INTO `t_search_dupl_login_ua_buf012`
				SET 
					Buff = LOWER(@.Sekc.X), 
					Sect = @.I
				;
			END IF;
			
			SET @.I = @.I + 1;
		UNTIL @.I >= 5 OR (NULLIF(@.Sekc.X, '') IS NULL)	-- dopoki nie ma juz nic lale nie wiecej niz 5
		END REPEAT;
		
		UPDATE `t_search_dupl_login_ua_buf012` tb
		SET
			tb.Repeat = (@.Repeat := IFNULL(NULLIF(_Midle_Two_Sep(tb.Buff, '(', ')'), ''), 10)),
			tb.Fmt = REPLACE(tb.Buff, CONCAT('(', @.Repeat, ')'), '')
		;
		UPDATE `t_search_dupl_login_ua_buf012` tb, `t_search_dupl_login_ua_inf` ti
		SET
			tb.Build_Login = 
			LOWER(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(tb.Fmt,
				'idnuser', IFNULL(SUBSTR(ti.IdnUser, 1, 15), '')),
				'i1', IFNULL(SUBSTR(ti.Imie1, 1, 1), '')),
				'ix', IFNULL(SUBSTR(ti.Imie1, 1, 15), '')),
				'nx', IFNULL(SUBSTR(ti.Nazwisko, 1, 15), '')),
				'r2', IFNULL(SUBSTR(YEAR(ti.DataUrodzenia), 3, 2), '')),
				'r4', IFNULL(SUBSTR(YEAR(ti.DataUrodzenia), 1, 4), '')),
				'pesel', IFNULL(SUBSTR(ti.NrPesel, 1, 11), ''))
			)
		;
		DROP TEMPORARY TABLE IF EXISTS `t_search_dupl_logins_check_012`;
		CREATE TEMPORARY TABLE `t_search_dupl_logins_check_012` (
			`Sect` INT, 
			`Build_Login` VARCHAR(50) NOT NULL DEFAULT '',
			PRIMARY KEY (`Build_Login`),
			`Repeat` INT NOT NULL DEFAULT 1,
			KEY (`Sect`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8;
		INSERT IGNORE INTO `t_search_dupl_logins_check_012` 
			SELECT 
				tb.Sect, tb.Build_Login, MAX(tb.Repeat)
			FROM `t_search_dupl_login_ua_buf012` tb
			WHERE
				IFNULL(tb.Build_Login, '') <> ''
			GROUP BY tb.Build_Login
		;
		DROP TEMPORARY TABLE IF EXISTS `t_search_dupl_logins_check_N`;
		CREATE TEMPORARY TABLE `t_search_dupl_logins_check_N` (
			`Sect` INT, 
			`LP` INT, 
			`Build_Login` VARCHAR(50) NOT NULL DEFAULT '',
			`EXISTS` BOOLEAN DEFAULT NULL,
			PRIMARY KEY (`Sect`, `LP`),
			`Repeat` INT NOT NULL DEFAULT 1,
			KEY (`LP`)
		) ENGINE=MYISAM DEFAULT CHARSET=UTF8;
	END IF;
	
	IF _MODE = 'PREPARE.1.Sect.Repeat' THEN
		-- _PARAM_A - sekcja
		SET @.tc.Repeat.X = 0;
		SELECT 
			tc.Repeat
		INTO @.tc.Repeat.X
		FROM `t_search_dupl_logins_check_012` tc
		WHERE	
			tc.Sect = _PARAM_A
		;
		IF @.tc.Repeat.X > 0 THEN
			SET @.I = 0;
			REPEAT
				INSERT IGNORE INTO `t_search_dupl_logins_check_N`
				(Sect, Build_Login, LP)
				SELECT	
					tc.Sect, 
					IF(@.I = 0, tc.Build_Login, CONCAT(tc.Build_Login, @.I)) AS Build_Login,
					(@.I := @.I + 1) AS LP
				FROM `t_search_dupl_logins_check_012` tc
				WHERE	
					tc.Sect = _PARAM_A
					-- AND IFNULL(tc.Build_Login, '') <> ''
				;
			UNTIL @.I >= @.tc.Repeat.X
			END REPEAT;
		END IF;
			
	END IF;
	
	IF _MODE IN ('FIND', 'SELECT.Free.Login', 'Get.Free.Login') THEN
		UPDATE `t_search_dupl_login_ua_inf` ti
		SET
			ti.IdnUser = _BezPolskich(ti.IdnUser),
			ti.Nazwisko = _BezPolskich(ti.Nazwisko),
			ti.Imie1 = _BezPolskich(ti.Imie1),
			ti.Imie2 = _BezPolskich(ti.Imie2)
		;
		CALL _user_accounts_build_login('PREPARE.N.Sect', '', @.self.Login, _PARAM_A, ''); 

		SET @.sect.I = 0;
		REPEAT
			CALL _user_accounts_build_login('PREPARE.1.Sect.Repeat', '', @.self.Login, @.sect.I, ''); 
			SET @.sect.I = @.sect.I + 1;
		UNTIL @.sect.I >= 5
		END REPEAT;
		/*
		CALL _user_accounts_build_login('.INS_X', '', @.self.Login, '0', ''); 
		CALL _user_accounts_build_login('.INS_X', '', @.self.Login, '1', ''); 
		CALL _user_accounts_build_login('.INS_X', '', @.self.Login, '2', ''); 
		*/
		UPDATE `t_search_dupl_logins_check_N` tn
		SET
			tn.Exists = EXISTS(SELECT idn FROM `_user_accounts` a WHERE a.login = tn.Build_Login AND a.typ = 'SYS')
		ORDER BY tn.Sect
		;
		SET
			@.Find.Login = (
				SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.Exists ORDER BY tn.Sect, tn.LP LIMIT 1
			)
		;
		IF _MODE = 'FIND' THEN
			SET _Login = @.Find.Login;
		END IF;
		
		IF _MODE = 'SELECT.Free.Login' THEN
			(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 0 LIMIT 1)
			UNION
			(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 1 LIMIT 1)
			UNION
			(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 2 LIMIT 1)
			UNION
			(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 3 LIMIT 1)
			UNION
			(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 4 LIMIT 1)
			;
		END IF;
		
		IF _MODE = 'Get.Free.Login' THEN
			SET @.Get.Free.Login = NULL;
			/*
			SET @.Get.Free.Login = CONCAT_WS(';',
				(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 0 LIMIT 1),
				(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 1 LIMIT 1),
				(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 2 LIMIT 1),
				(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 3 LIMIT 1),
				(SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 4 LIMIT 1)
				)
			;
			*/
			SET @.Get.Free.Login = 
				CONCAT_WS(';', @.Get.Free.Login, (SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 0 LIMIT 1))
			;
			SET @.Get.Free.Login = 
				CONCAT_WS(';', @.Get.Free.Login, (SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 1 LIMIT 1))
			;
			SET @.Get.Free.Login = 
				CONCAT_WS(';', @.Get.Free.Login, (SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 2 LIMIT 1))
			;
			SET @.Get.Free.Login = 
				CONCAT_WS(';', @.Get.Free.Login, (SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 3 LIMIT 1))
			;
			SET @.Get.Free.Login = 
				CONCAT_WS(';', @.Get.Free.Login, (SELECT tn.Build_Login FROM `t_search_dupl_logins_check_N` tn WHERE NOT tn.EXISTS AND SECT = 4 LIMIT 1))
			;
			
			SET _Login = @.Get.Free.Login;
		END IF;
	END IF;

END$$

DELIMITER ;

DELIMITER $$
DROP FUNCTION IF EXISTS `_user_accountsF`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_user_accountsF`(
	_MODE VARCHAR(250),
	_C1 VARCHAR(250),
	_C2 VARCHAR(250),
	_C3 VARCHAR(250),
	_C4 VARCHAR(250),
	_C5 VARCHAR(250),
	_M1 TEXT
	
) RETURNS VARCHAR(200)
	DETERMINISTIC
-- 	COMMENT 'narodziny swiata - ustawienie kilku kluczowych zmiennych'
BEGIN

	IF _MODE = 'GetPSWD' THEN
	/*	
		select _user_accountsF('GetPSWD', NULL, 12, '', '', '', '');	
		_user_accountsF('GetPSWD', '', '', '', '', '', '');
		_user_accountsF('GetPSWD', NULL, 14, '', '', '', '');
		_user_accountsF('GetPSWD', NULL, 10, '', '', '', '');
	*/
		SET
			@pLen := GREATEST(9, IFNULL(NULLIF(_C2, ''), 0)),	-- nie mniejsze niz 9
			@pSet20 := '$@sHb1v36!q7A#L8nTuw', -- SUBSTR(@pSet, FLOOR(1 + (RAND() * 8)), 1) as x,
			--	LENGTH(@pSet20) AS LpSet20,
			@pSet := '$@0B1c-3De$Fg7$9Jk@LmNo#pQ!rUwVxYz@!=a2Cd4#$f6Gh8!ijK@oPqR$stvXyZ', -- SUBSTR(@pSet, FLOOR(1 + (RAND() * 8)), 1) as x,
			@pSetL := LENGTH(@pSet),
			@pU := UUID_SHORT(),
			@pH := SUBSTR(SUBSTR(@pU, -@pLen, @pLen), 1, @pLen),	-- @pLen - 5 = 4 !!!
			@pHV := ROUND(@pH)
		;
		SET
			@.uaF.Pswd :=
			INSERT(INSERT(INSERT(INSERT(@pH, 
			1, 1, SUBSTR(@pSet, 1 + ((SUBSTR(@pH, 1, 1) + @pHV) MOD @pSetL), 1)),
			3, 1, SUBSTR(@pSet, 1 + ((SUBSTR(@pH, 3, 1) + @pHV) MOD @pSetL), 1)),
			@pLen - 2, 1, SUBSTR(@pSet20, 1+SUBSTR(@pH, @pLen - 2, 1), 1)),
			@pLen, 1, SUBSTR(@pSet20, 11+SUBSTR(@pH, @pLen, 1), 1))
		;
		SET @.uaF.Return = @.uaF.Pswd;
	--	Zwróć...
		RETURN @.uaF.Return;
	END IF;
END;
$$
DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
/*
$Log: _user_accounts_tools.sql,v $
Revision 1.69  2025/03/31 10:00:13  jmam
$send$ poprawki po Waliant + polskie znaki

Revision 1.68  2025/03/19 10:34:35  waliant
$SEND$ Warningi, strona kodowa i powalone literaly

Revision 1.67  2025/01/22 17:48:49  jmam
$send$ Aktywacja konta

Revision 1.66  2024/10/03 12:36:24  jmam
$SEND$ zwracanie nazwy działu

Revision 1.65  2024/10/03 10:54:27  jmam
$SEND$ dwa mody do zmiany ..Change.Stanowisko i Change.nazwa_dzialu

Revision 1.64  2024/09/27 13:21:46  jmam
$SEND$ klonowanie grup z uprawnieniami + poprawka

Revision 1.63  2024/09/27 11:18:46  jmam
$SEND$ klonowanie grup z uprawnieniami

Revision 1.62  2024/07/24 06:06:42  jmam
POprawki dot. inicjacji i resetu hasła + maile

Revision 1.61  2024/07/23 07:58:06  slon
$SEND$

Revision 1.60  2023/12/14 14:47:47  jmam
$SEND$ SQL zmiana 14 XII

Revision 1.59  2023/08/21 10:36:32  jmam
Synchronizacja kolejna po zmianach apro

Revision 1.58  2023/08/21 10:26:14  jmam
no message

Revision 1.57  2023/08/21 10:25:11  jmam
poprawki do ost. apro

Revision 1.56  2023/08/17 13:21:44  apro
rozszerzenia pod kątem intnetcenter
$SEND$

*/
