 SET NAMES utf8;
DELIMITER $$

/* ************************************************************************************************************************************************************************
	Narzędzia do `ng_e_rec`
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `_ng_e_rec_init`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_init`(
	IN _MODE VARCHAR(250),	--	_handle_oper -- INSERT, EDIT, DELETE',
	IN _handle_FROM VARCHAR(250),	-- OP lub ZM ...?
	IN _Key VARCHAR(38),
	IN _handle_UserGUID VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
/*
	CALL _ng_e_rec_init('INSERT', 'OP', 'x', 'jmam', '', ''); 
	CALL _ng_e_rec_init('EDIT', 'OP', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', 'jmam', '', '');
	CALL _ng_e_rec_init('Check.before.handle', 'OP', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', 'jmam', '', '');
	CALL _ng_e_rec_init('INSERT', 'ZM', 'x', 'jmam', '', '');
*/
S_ng_e_rec_init: BEGIN 
	DECLARE _Rec_Is_Locked BOOLEAN DEFAULT FALSE;
	DECLARE _Rec_Is_Locked_MSG TEXT;



	DO _Birth_System();
	/*
	set @session.globals.CALC.VAT.Ver = '2021';		-- jmam UWAGA	- dla KONKOLa już wgrałem 2021 nalezy ustawic w tabeli
	set @session.LOCK.Ver = '2021';					-- jmam UWAGA	- dla KONKOLa już wgrałem 2021 nalezy ustawic w tabeli
	*/
	set @session.globals.CALC.VAT.Ver = 
		IF(@session.globals.Owner IN ('INT', 'KONKOL', 'SIMEX','SECURITY'),
			'2021',		-- jmam UWAGA	- dla KONKOLa już wgrałem 2021 nalezy ustawic w tabeli
			@session.globals.CALC.VAT.Ver
		)
	;
	set @session.LOCK.Ver = 
		IF(@session.globals.Owner IN ('INT', 'KONKOL', 'SIMEX', 'PLISZKA'),
			'2021',		-- jmam UWAGA	- dla KONKOLa już wgrałem 2021 nalezy ustawic w tabeli
			@session.LOCK.Ver
		)
	;
	/*
	jaki s czas vat dla 2021 naliczal sie zle ale pwodem by kurs nie aktualny w pozycjach - ponownie ustawiam 2021
	set @session.globals.CALC.VAT.Ver = 
		IF(@session.globals.Owner IN ('SIMEX'),
			'2017',		-- jmam UWAGA	- dla KONKOLa już wgrałem 2021 nalezy ustawic w tabeli
			@session.globals.CALC.VAT.Ver
		)
	;
	*/

set @Deb.1 = "1.   CALL ht_init_const('');";
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&1.a', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
	CALL ht_init_const('');
	SET @_ng_e_rec_init.Msg = '';
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&1.b', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);

set @Deb.1 = "2.   CALL _ng_e_rec_msg_clear()";
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&2.a', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
	CALL _ng_e_rec_msg_clear('', _Key, 'handle.init', '');
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&2.b', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
	
set @Deb.1 = "3.   Check.before.handle";
	IF _MODE = 'Check.before.handle' THEN
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&3->Check.before.handle.1', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);

		IF _Param_B = 'Server' THEN
			LEAVE S_ng_e_rec_init;
		END IF;
	--	Czy zablokowany?
		IF @session.LOCK.Ver = '0' THEN
		--	stare blokady 
					Set @_lock_inf_tool = 'Jestem.Check.before.handle';
			CALL _lock_inf_tool('Check.before.lock', _Key, IF(_handle_FROM != 'ZM', 'opng', 'zmng'), _handle_UserGUID, _Rec_Is_Locked, _Rec_Is_Locked_MSG, '', '1');
		END IF;
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&3->Check.before.handle.2', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
		
		/*
		SELECT
			@t_Check_before_lock.LockUserGUID,
			@t_Check_before_lock.LockSession,
			@t_Check_before_lock.Inf,
			@t_Check_before_lock.IsSameUser,
			@t_Check_before_lock.IsSameSession,
			@t_Check_before_lock.LockSession_Exist,
			@t_Check_before_lock.LockUserFullName,
			@t_Check_before_lock._State,
			@t_Check_before_lock._StateMsg
		;
		*/
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&3->Check.before.handle.3', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
		IF NOT (@t_Check_before_lock._State IN ('0.OK', '2.JA/Ta sesja')) AND @session.LOCK.Ver = '0' THEN
			CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
			@t_Check_before_lock._StateMsg,
			CASE @t_Check_before_lock._State
			WHEN '1.Blokada' THEN 'Error'
			WHEN '3.JA/inna sesja' THEN 'Ask'
			WHEN '4.JA/zamknieta sesja' THEN 'Ask'
			END, 
			CASE @t_Check_before_lock._State
			WHEN '1.Blokada' THEN 'Stop'
			WHEN '3.JA/inna sesja' THEN 'Stop'
			WHEN '4.JA/zamknieta sesja' THEN 'Clear'
			END, 
			'', '');
	
		END IF;
		LEAVE S_ng_e_rec_init;
	END IF;
	
	IF _MODE != 'INSERT' THEN
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
		
set @Deb.1 = "4.   SET @_ng_e_rec_init._Rec_Is_Locked = 0, @_ng_e_rec_init.Msg = '';";
	--	Czy zablokowany?
		SET @_ng_e_rec_init._Rec_Is_Locked = 0, @_ng_e_rec_init.Msg = '';
		SET @ROW_COUNT = -1;

		IF _Param_B != 'Server' THEN
		--	NIE MA blokowania dla przetwarzania serwerowego
						Set @_lock_inf_tool = 'Jestem.Insert';
						set @Deb.1 = "5.   CALL _lock_inf_tool('LOCK'...";
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.b', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
			IF @session.LOCK.Ver >= '2021' THEN
			--	nowe blokady
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.c', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
				CALL _ng_E_Tools('LOCK', _Key, _handle_FROM, @_Param_A);
				SET _Rec_Is_Locked = (@.xxng.Lock.Rec = 0), _Rec_Is_Locked_MSG = @.LCK.Result.Msg;
			ELSE
			--	stare blokady 
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.d', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
				CALL _lock_inf_tool('LOCK', _Key, IF(_handle_FROM != 'ZM', 'opng', 'zmng'), _handle_UserGUID, _Rec_Is_Locked, _Rec_Is_Locked_MSG, '', '1');
			END IF;
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.e', 'CALL _ng_e_rec_init', @IdnOper, '', @.X.log);
		END IF;
	END IF;
	
	
	-- IF @_ng_e_rec_init._Rec_Is_Locked = 0 THEN
	IF NOT _Rec_Is_Locked THEN
	--	NIE zablokowany
set @Deb.1 = "6.   INSERT IGNORE INTO `ng_e_rec`...";
set @Deb.1 = concat("Teraz INSERT czyli trigger ...", ",", QUOTE(_Key), ",", QUOTE(_handle_FROM), ",", QUOTE(_MODE), ",", QUOTE(_handle_UserGUID));

	--	WAZNE!!!!!!!!!!!!!!
		IF  NULLIF(@SYSTEM.Client.Session.GUID, '') IS NULL THEN
			CALL _sessions('SESSION.SETUP.VAR', '', '', '', '', '', 'GO');
		ELSEIF (@session.Registration.UserGUID IS NULL) OR (@SYSTEM.Client.Session.log_USER_GUID IS NULL) THEN
			-- CALL _sessions('SESSION.CHECK', @SYSTEM.Client.Session.GUID, '', '', '', '', '');
			-- a jednak to samo
			CALL _sessions('SESSION.SETUP.VAR', '', '', '', '', '', 'GO');
			-- CALL _sessions('SESSION.SETUP.Variables<-Session.GUID', '', '', '', '', '', 'GO');				
		END IF;
		INSERT IGNORE INTO `ng_e_rec`
		(GUID, handle_FROM, handle_oper, handle_UserGUID)
		VALUES
		(_Key, _handle_FROM, _MODE, _handle_UserGUID)
		;
set @Deb.1 = "7.   UPDATE `ng_e_rec` r...";
		UPDATE `ng_e_rec` r
		SET
			r.Handle_Check = -1 --	sprawdz semafor
		WHERE
			r.GUID = _Key
		;
		
		/*
		IF _MODE != 'INSERT' THEN
		
			UPDATE `ng_e_rec` r, `opng` n
			SET
				r.Rodzaj = n.Rodzaj, 
				r.Rodzaj_Typ = n.Rodzaj_Typ, 
				r.i_Calc_Ver = n.Calc_Ver, 
				r.i_KontrGUID = n.KontrGUID, 
				r.i_Magazyn1_Kasa = n.Zmagazynu, 
				r.i_Magazyn2 = n.Domagazynu, 
				r.i_Tymczasowa = n.Tymczasowa, 
				r.i_Waluta = n.Waluta, 
				r.i_OsobaGUID = n.OsobaGUID, 
				r.i_AreaGUID = n.AreaGUID, 
				r.i_fvrudowz = n.fvrudowz 
			WHERE
				r.GUID = _Key
				AND
				n.GUID = _Key
			;	
		END IF;
		*/
		/*
		CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
			CONCAT(@ROW_COUNT, 
						' @JakiUpdate ', @JakiUpdate,
						' @JakiUser ', @JakiUser,
						' - ',

			@ROW_COUNT, ' / ', _Rec_Is_Locked, ' / ', _Key, ' / ', _Rec_Is_Locked_MSG, ' / ', _handle_FROM, ' / ', _handle_UserGUID), 
			'Msg', '', '', '');
		*/
	ELSE
set @Deb.1 = "8.   CALL _ng_e_rec_msg_ins()...";
		IF @session.LOCK.Ver = '0' THEN
		--	po staremu
			CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
				CONCAT(
					_Rec_Is_Locked_MSG
				),
				-- _res_str_get( 'Brak danych do zapisu - anuluj zmiany!!!', ''),
				'Error', 'Stop', '', '');
		END IF;
	END IF;

	IF _Param_A = 'select_Rec_Is_Locked' THEN
set @Deb.1 = "9.   SELECT _Rec_Is_Locked, _Rec_Is_Locked_MSG;...";

		-- SELECT @_ng_e_rec_init._Rec_Is_Locked AS _Rec_Is_Locked, (@_ng_e_rec_init.Msg) AS _Rec_Is_Locked_MSG;
		SELECT _Rec_Is_Locked, _Rec_Is_Locked_MSG;
	ELSEIF _Param_A = 'Return_Rec_Is_Locked' THEN

		-- SELECT @_ng_e_rec_init._Rec_Is_Locked AS _Rec_Is_Locked, (@_ng_e_rec_init.Msg) AS _Rec_Is_Locked_MSG;
set @Deb.1 = "10.   SET @_Rec_Is_Locked = _Rec_Is_Locked, @_Rec_Is_Locked_MSG = _Rec_Is_Locked_MSG;...";
		SET @_Rec_Is_Locked = _Rec_Is_Locked, @_Rec_Is_Locked_MSG = _Rec_Is_Locked_MSG;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_init_r`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_init_r`(
	IN _MODE VARCHAR(250),	--	_handle_oper -- INSERT, EDIT, DELETE',
	IN _handle_FROM VARCHAR(250),	-- OP lub ZM ...?
	IN _Key VARCHAR(38),
	IN _IsFamily INTEGER,
	IN _Family_GUID VARCHAR(38),
	IN _handle_UserGUID VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
/*
	CALL _ng_e_rec_init_r('INSERT', 'OP', 'x', 'jmam', '', '');
	CALL _ng_e_rec_init_r('EDIT', 'OP', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', 'jmam', '', '');
	CALL _ng_e_rec_init_r('Check.before.handle', 'OP', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', 'jmam', '', '');
	CALL _ng_e_rec_init_r('INSERT', 'ZM', 'x', 'jmam', '', '');
*/
S_ng_e_rec_init_r: BEGIN 
	DECLARE _Rec_Is_Locked BOOLEAN DEFAULT FALSE;
	DECLARE _Rec_Is_Locked_MSG TEXT;
	
	CALL ht_init_const('');
	SET @_ng_e_rec_init.Msg = '?';

	CALL _ng_e_rec_msg_clear('', _Key, 'handle.init', '');
	
	IF _MODE = 'Check.before.handle' THEN
	
		IF _Param_B = 'Server' THEN
			LEAVE S_ng_e_rec_init_r;
		END IF;
	--	Czy zablokowany?
		Set @_lock_inf_tool = 'Jestem.Check.before.handle';
		CALL _lock_inf_tool('Check.before.lock', _Key, IF(_handle_FROM != 'ZM', 'opng', 'zmng'), _handle_UserGUID, _Rec_Is_Locked, _Rec_Is_Locked_MSG, '', '1');
		
		/*
		SELECT
			@t_Check_before_lock.LockUserGUID,
			@t_Check_before_lock.LockSession,
			@t_Check_before_lock.Inf,
			@t_Check_before_lock.IsSameUser,
			@t_Check_before_lock.IsSameSession,
			@t_Check_before_lock.LockSession_Exist,
			@t_Check_before_lock.LockUserFullName,
			@t_Check_before_lock._State,
			@t_Check_before_lock._StateMsg
		;
		*/
		IF NOT (@t_Check_before_lock._State IN ('0.OK', '2.JA/Ta sesja')) THEN
		CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
			@t_Check_before_lock._StateMsg,
			CASE @t_Check_before_lock._State
			WHEN '1.Blokada' THEN 'Error'
			WHEN '3.JA/inna sesja' THEN 'Ask'
			WHEN '4.JA/zamknieta sesja' THEN 'Ask'
			END, 
			CASE @t_Check_before_lock._State
			WHEN '1.Blokada' THEN 'Stop'
			WHEN '3.JA/inna sesja' THEN 'Stop'
			WHEN '4.JA/zamknieta sesja' THEN 'Clear'
			END, 
			'', '');
	
		END IF;
		LEAVE S_ng_e_rec_init_r;
	END IF;
	
	IF _MODE != 'INSERT' THEN
		
	--	Czy zablokowany?
		SET @_ng_e_rec_init._Rec_Is_Locked = 0, @_ng_e_rec_init.Msg = '';
		SET @ROW_COUNT = -1;

		IF _Param_B != 'Server' THEN
		--	NIE MA blokowania dla przetwarzania serwerowego
		Set @_lock_inf_tool = 'Jestem.Insert';
			CALL _lock_inf_tool('LOCK', _Key, IF(_handle_FROM != 'ZM', 'opng', 'zmng'), _handle_UserGUID, _Rec_Is_Locked, _Rec_Is_Locked_MSG, '', '1');
		END IF;
	END IF;
	
	
	-- IF @_ng_e_rec_init._Rec_Is_Locked = 0 THEN
	IF NOT _Rec_Is_Locked THEN
	--	NIE zablokowany
	--	WAZNE!!!!!!!!!!!!!!
		IF  NULLIF(@SYSTEM.Client.Session.GUID, '') IS NULL THEN
			CALL _sessions('SESSION.SETUP.VAR', '', '', '', '', '', 'GO');
		ELSEIF (@session.Registration.UserGUID IS NULL) OR (@SYSTEM.Client.Session.log_USER_GUID IS NULL) THEN
			CALL _sessions('SESSION.CHECK', @SYSTEM.Client.Session.GUID, '', '', '', '', '');
			-- CALL _sessions('SESSION.SETUP.Variables<-Session.GUID', '', '', '', '', '', 'GO');				
		END IF;
		INSERT IGNORE INTO `ng_e_rec`
		(GUID, i_IsFamily, r_Family_GUID, handle_FROM, handle_oper, handle_UserGUID)
		VALUES
		(_Key, IFNULL(_IsFamily, FALSE), _Family_GUID, _handle_FROM, _MODE, _handle_UserGUID)
		;
		UPDATE `ng_e_rec` r
		SET
			r.Handle_Check = -1 --	sprawdz semafor
		WHERE
			r.GUID = _Key
		;
		
	ELSE
	--	BLOKADA
		CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
			CONCAT(
				_Rec_Is_Locked_MSG
			),
			-- _res_str_get( 'Brak danych do zapisu - anuluj zmiany!!!', ''),
			'Error', 'Stop', '', '');
		
	END IF;

	IF _Param_A = 'select_Rec_Is_Locked' THEN

		-- SELECT @_ng_e_rec_init._Rec_Is_Locked AS _Rec_Is_Locked, (@_ng_e_rec_init.Msg) AS _Rec_Is_Locked_MSG;
		SELECT _Rec_Is_Locked, _Rec_Is_Locked_MSG;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_do`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_do`(
	IN _MODE VARCHAR(250),	-- 'check.semafor' semafor/ 'check.upr.1' sprawdz uprawnienie BEFORE	przed operacja/	'check.upr.2' sprawdz uprawnienie ON/AFTER	w trakcie operacji
	IN _Key VARCHAR(38),
	-- IN _handle_Check INTEGER,	-- -1 semafor/ 1 sprawdz uprawnienie BEFORE	przed operacja/	2 sprawdz uprawnienie ON/AFTER	w trakcie operacji
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
/*
	CALL _ng_e_rec_do('check.semafor', 'x', '', '');	-- sprawdz semafor
	CALL _ng_e_rec_do('check.upr.1', 'x', '', '');		-- sprawdz uprawnienie BEFORE	przed operacja
	CALL _ng_e_rec_do('check.upr.2', 'x', '', '');		-- sprawdz uprawnienie ON/AFTER	w trakcie operacji
	
	CALL _ng_e_rec_do('create', 'x', '', '');	-- stworz rekord opng_e lub zmng_e (o ile jest to handle_oper = 'INSERT'

	CALL _ng_e_rec_do('select', '_Key', '', '');	-- zwróć wszystkie ustawienia (kolumny `ng_e_rec`, `operdoc` i `operdoc`
	CALL _ng_e_rec_do('select.into', _Key, '', '');	

	CALL _ng_e_rec_do('check.kontrahent.new', _Key, _KontrGUID, '');	--	zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	CALL _ng_e_rec_do('check.kontrahent.new', @IdnOper, '{9F42245E-6AEB-4852-8E79-C52F186E01B6}', '');	--	zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	CALL _ng_e_rec_do('check.kontrahent.new', @IdnOper, 'ABC', '');	--	zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	
*/
S_ng_e_rec_do: BEGIN 
	DO _Birth_System();
	IF _MODE LIKE 'check.%' THEN
	/**********************************************************************************************************************************
	Sprawdzanie: semafora, uprawnienia  (w triggerze `ng_e_rec`
	**********************************************************************************************************************************/
		IF _MODE = 'check.semafor' THEN
			UPDATE `ng_e_rec`
			SET
				Handle_Check = -1 --	sprawdz semafor (w triggerze `ng_e_rec`
			WHERE
				GUID = _Key
			;	
		END IF;	
		
		IF _MODE = 'check.upr.1' THEN
			UPDATE `ng_e_rec`
			SET
				Handle_Check = 1 --	sprawdz uprawnienie BEFORE	przed operacja (w triggerze `ng_e_rec`
			WHERE
				GUID = _Key
			;	
		END IF;	
		
		IF _MODE = 'check.upr.2' THEN
                        SET @XXX = concat_WS('->', @XXX, _MODE);
                        SET @XXX = concat_WS('->', @XXX, '...');

			UPDATE `ng_e_rec`
			SET
				Handle_Check = 2 --	sprawdz uprawnienie ON/AFTER	w trakcie operacji (w triggerze `ng_e_rec`
			WHERE
				GUID = _Key
			;	
                        SET @XXX = concat_WS('->', @XXX, 'po upd');
		END IF;	
	END IF;	

	
	IF _MODE = 'select.into' THEN
	/**********************************************************************************************************************************
	zwróć wszystkie ustawienia w zmiennych
	**********************************************************************************************************************************/
		SELECT
			r.OpTyp, 
			r.i_KontrGUID,
			r.i_Calc_Ver, 
			r.i_fvrudowz,
			r.handle_oper,
			r.handle_FROM,
			i_MODE,
			i_Input_GUID,
			r.i_Magazyn1_Kasa, 
			r.i_Magazyn2,
			r.i_IsFamily,
			IFNULL(r.r_Family_GUID, ''),
			r.handle_UserGUID,
			r.handle_UserLogin
		INTO
			@OpTyp,
			@i_KontrGUID,
			@i_Calc_Ver,
			@i_fvrudowz,
			@handle_oper,
			@handle_FROM,
			@i_MODE,
			@i_Input_GUID,
			@i_Magazyn1_Kasa,
			@i_Magazyn2,
			@i_IsFamily,
			@r_Family_GUID,
			@i.handle_UserGUID,
			@i.handle_UserLogin
		FROM `ng_e_rec` r
		WHERE
			r.GUID = _Key
		;	
	END IF;	
	
	IF _MODE = 'select' THEN
	/**********************************************************************************************************************************
	zwróć wszystkie ustawienia (kolumny `ng_e_rec`, `operdoc` i `operdoc`
	**********************************************************************************************************************************/
		CALL _ng_e_rec_do('select.into', _Key, '', '');	
		
		IF @handle_FROM = 'OP' OR @handle_FROM = 'R' THEN
			SELECT
				n.Idn,
				n.Rodzaj,
				IFNULL(n.Rodzaj_Typ, u.Rodzaj_Typ) AS Rodzaj_Typ,
				o.MagTyp,
				_VarStr_NotNull(
				IF(u.Rodzaj IN (@ht.CKPKP, @ht.CKWKW, @ht.CRKBO), 
					n.nrdokkas,
					IF(u.Rodzaj IN (@ht.CBNWN, @ht.CBNMA),
						n.nrraportu,
						IF(u.Optyp = @ht.MG,
							n.NrDokMag,
							n.NrDokFin
						)
					)
				)) AS NrDok,
				n.NrDokMag,
				n.nrwewn,
				n.NrFvWewn,
				IF(IFNULL(u.i_Magazyn1_Kasa, 0) = 0, n.ZMagazynu, u.i_Magazyn1_Kasa) AS i_Magazyn1_Kasa,
				IF(IFNULL(u.i_Magazyn2, 0) = 0, n.DoMagazynu, u.i_Magazyn2) AS i_Magazyn2,
				IFNULL(m1.Opis, '') AS i_Magazyn1_Kasa_Str,
				IFNULL(m2.Opis, '') AS i_Magazyn2_Str,
				n.KontrGUID,
				n.Waluta,
				n.Kurs
			INTO
				@n.Idn,
				@n.Rodzaj,
				@n.Rodzaj_Typ,
				@o.MagTyp,
				@n.NrDok,
				@n.NrDokMag,
				@n.nrwewn,
				@n.NrFvWewn,
				@.i_Magazyn1_Kasa,
				@.i_Magazyn2,
				@.i_Magazyn1_Kasa_Str,
				@.i_Magazyn2_Str,
				@n.KontrGUID,
				@n.Waluta,
				@n.Kurs
			FROM `ng_e_rec` u
			LEFT JOIN `opng_e` n ON n.GUID = u.GUID
			LEFT JOIN `operdoc` o ON o.Rodzaj = IFNULL(n.Rodzaj, u.Rodzaj)
			-- LEFT JOIN `operdoc_typy` p ON p.Rodzaj = o.Rodzaj AND p.Typ = IFNULL(n.Rodzaj_Typ, u.Rodzaj_Typ)
			-- LEFT JOIN `kontrah` k ON k.GUID = n.KontrGUID
			-- LEFT JOIN `waluty` w ON w.Idn = n.Waluta
			LEFT JOIN `Magazyny` m1 ON m1.IdnMagazynu = IF(IFNULL(u.i_Magazyn1_Kasa, 0) = 0, n.ZMagazynu, u.i_Magazyn1_Kasa) 
			LEFT JOIN `Magazyny` m2 ON m2.IdnMagazynu = IF(IFNULL(u.i_Magazyn2, 0) = 0, n.DoMagazynu, u.i_Magazyn2) 
			WHERE
				u.GUID = _Key
			;
			SET @.FMagCommentC = '';
SET @Deb.1 = '1';
			IF @handle_FROM = 'OP' THEN
				IF @o.MagTyp IN (@ht.mtPZ, @ht.mtPlanPZ) THEN
					SET 
						@.FMagCommentA := _VarStr(REPLACE('Do magazynu "%s"', '%s', _VarStr(@.i_Magazyn2_Str))),
						@.FMagCommentB := _VarStr(REPLACE('-> %d', '%d', _VarStr(@.i_Magazyn2)))
					;
				ELSEIF @o.MagTyp IN (@ht.mtRZ, @ht.mtPlanRZ) THEN
					SET 
						@.FMagCommentA := _VarStr(REPLACE('Z magazynu "%s"', '%s', _VarStr(@.i_Magazyn1_Kasa_Str))),
						@.FMagCommentB := _VarStr(REPLACE('%d ->', '%d', _VarStr(@.i_Magazyn1_Kasa)))
					;
				ELSE
					SET 
						@.FMagCommentA := _VarStr(REPLACE(REPLACE('Z magazynu "%s1" do magazynu "%s2"', '%s1', _VarStr(@.i_Magazyn1_Kasa_Str)), '%s2', _VarStr(@.i_Magazyn2_Str))),
						@.FMagCommentB := _VarStr(REPLACE(REPLACE('%d1 -> %d2', '%d1', _VarStr(@.i_Magazyn1_Kasa)), '%d2', _VarStr(@.i_Magazyn2)))
					;
				END IF;
				
				IF @session.globals.Owner = 'SKOK' THEN
					SET @.FMagCommentA := REPLACE(_VarStr(@.FMagCommentA), 'magazynu', 'zestawu');
				END IF;
				
			END IF;

SET @Deb.1 = '2';
			IF @handle_FROM = 'R' THEN
					SET @.FMagCommentA := REPLACE(_VarStr(@.FMagCommentA), 'magazynu', 'zestawu');
			END IF;
SET @Deb.1 = '3';
		ELSEIF @handle_FROM = 'ZM' THEN		--	ZM
-- TODO: zrobić po bożemu z operdoc
			IF (@session.globals.Owner IN ('PARAQUA', 'IZOHAN')) THEN
			      UPDATE ng_e_rec u, zmng_e n SET u.i_Magazyn2=u.i_Magazyn1_Kasa, n.magazynwys=n.idnmagazyn
			      WHERE u.guid=n.guid and n.Rodzaj IN (@ht.CZMOO, @ht.CZMDD, @ht.CZMEX, @ht.CZMIM) and n.guid=_Key;
			END IF;
			
		
			SELECT
				n.Idn,
				n.Rodzaj,
				IFNULL(n.Rodzaj_Typ, u.Rodzaj_Typ) AS Rodzaj_Typ,
				o.MagTyp,
				_VarStr_NotNull(n.nrzamw) AS NrDok,
				'' AS NrDokMag,
				'' AS nrwewn,
				'' AS NrFvWewn,
				IF(IFNULL(u.i_Magazyn1_Kasa, 0) = 0, n.idnmagazyn, u.i_Magazyn1_Kasa) AS i_Magazyn1_Kasa,
				IF(IFNULL(u.i_Magazyn2, 0) = 0, n.MagazynWys, u.i_Magazyn2) AS i_Magazyn2,
				IFNULL(m1.Opis, '') AS i_Magazyn1_Kasa_Str,
				IFNULL(m2.Opis, '') AS i_Magazyn2_Str,
				n.KontrGUID,
				n.Waluta,
				n.Kurs
			INTO
				@n.Idn,
				@n.Rodzaj,
				@n.Rodzaj_Typ,
				@o.MagTyp,
				@n.NrDok,
				@n.NrDokMag,
				@n.nrwewn,
				@n.NrFvWewn,
				@.i_Magazyn1_Kasa,
				@.i_Magazyn2,
				@.i_Magazyn1_Kasa_Str,
				@.i_Magazyn2_Str,
				@n.KontrGUID,
				@n.Waluta,
				@n.Kurs
			FROM `ng_e_rec` u
			LEFT JOIN `zmng_e` n ON n.GUID = u.GUID
			LEFT JOIN `operdoc` o ON o.Rodzaj = IFNULL(n.Rodzaj, u.Rodzaj)
			-- LEFT JOIN `operdoc_typy` p ON p.Rodzaj = o.Rodzaj AND p.Typ = IFNULL(n.Rodzaj_Typ, u.Rodzaj_Typ)
			-- LEFT JOIN `kontrah` k ON k.GUID = n.KontrGUID
			-- LEFT JOIN `waluty` w ON w.Idn = n.Waluta
			LEFT JOIN `Magazyny` m1 ON m1.IdnMagazynu = IF(IFNULL(u.i_Magazyn1_Kasa, 0) = 0, n.idnmagazyn, u.i_Magazyn1_Kasa) 
			LEFT JOIN `Magazyny` m2 ON m2.IdnMagazynu = IF(IFNULL(u.i_Magazyn2, 0) = 0, n.MagazynWys, u.i_Magazyn2) 
			WHERE
				u.GUID = _Key
			;
			--			@OpTyp,
			SET @.FMagCommentA := _VarStr(REPLACE('Na magazyn "%s"', '%s', _VarStr(@.i_Magazyn1_Kasa_Str)));
			IF @n.Rodzaj IN (@ht.CZmOO, @ht.CZmEx, @ht.CZmZP, @ht.CZMWE) THEN
				IF @.i_Magazyn1_Kasa != @.i_Magazyn2 THEN
					CASE @n.Rodzaj
						WHEN @ht.CZmZP THEN 
							SET @.FMagCommentA = _VarStr(REPLACE(REPLACE('Materiały i surowce z "%s1", produkowany na "%s1"', '%s1', _VarStr(@.i_Magazyn1_Kasa_Str)), '%s2', _VarStr(@.i_Magazyn2_Str)));
						WHEN @ht.CZMWE THEN 
							SET @.FMagCommentA = _VarStr(REPLACE(REPLACE('Z magazynu "%s1", wysyłany na "%s2"', '%s1', _VarStr(@.i_Magazyn1_Kasa_Str)), '%s2', _VarStr(@.i_Magazyn2_Str)));
						ELSE
							SET @.FMagCommentA = _VarStr(REPLACE(REPLACE('Na magazyn "%s1", wysyłany z "%s2"', '%s1', _VarStr(@.i_Magazyn1_Kasa_Str)), '%s2', _VarStr(@.i_Magazyn2_Str)));
					END CASE;
				
				END IF;
				SET 
					@.FMagCommentB = _VarStr(REPLACE('%d ->', '%d', _VarStr(@.i_Magazyn2))),
					@.FMagCommentC = IF(@n.Rodzaj != @ht.CZmZP, 'Zam. od ', '')
				;
			ELSE
				SET 
					@.FMagCommentB = _VarStr(REPLACE('-> %d', '%d', _VarStr(@.i_Magazyn2))),
					@.FMagCommentC = 'Zam. do '
				;
			END IF;
			
		END IF;	--	ZM
		
		
		
		SELECT 
			u.*,
			o.antyrodzaj, o.grupa, o.Twtyp, o.MagTyp, o.Rztyp, o.Fntyp, IFNULL(o.wzordekr, '') AS wzordekr, o.rv_id, o.RodzajDowodu, o.ugrpGUID, 
			o.Nazwa, o.Opis, o.upr_optyp, o.upr_rodzaj,
			o.IsWaluta, o.IsRozrachunek, o.IsPozycjeVisible, o.MA_Magzyny, o.MA_Detale, o.MA_Kontrahenta, o.IsKorekta, o.IsPodlegaVAT, o.IsTabelkaVatEditable, o.IsSprzedazNieKrajowa, o.IsDostawa, o.IsWlasny,
			
			-- o.*,
			p.*,
			(status_before = -1 AND status_after = 0) AS Instancje_Kreowanie, 
			(status_before = 0 AND status_after = -1) AS Instancje_Likwidacja,
			IF(o.TwTyp = @ht.TwZm,
				u.i_Magazyn1_Kasa,
				IF(o.TwTyp = @ht.TwRZ,
					u.i_Magazyn1_Kasa,
					u.i_Magazyn2
				)
			) AS IdnMagazynuByTwTyp,
			IF(o.TwTyp = @ht.TwZm,
				_varInt(1),
				IF(o.TwTyp IN (@ht.TwRZ, @ht.TwMM),
					_varInt(1),
					_varInt(0)
				)
			) AS IsMag_1,
			IF(o.TwTyp = @ht.TwZm,
				_varInt(1),
				IF(o.TwTyp IN (@ht.TwPZ, @ht.TwMM),
					_varInt(1),
					_varInt(0)
				)
			) AS IsMag_2,
			o.FVdoWZPZ AND
				IF(o.TwTyp = @ht.TwPZ,
					IFNULL(@session.HT.IR.PytajoFVdoPZ, FALSE),
					IFNULL(@session.HT.IR.PytajoFVdoWZ, FALSE)
				)
			AS IsFVdoWZPZ,
			o.DefaultTymczasowa,
			
			IFNULL(m1.Opis, '') AS i_Magazyn1_Kasa_Str,
			IFNULL(m2.Opis, '') AS i_Magazyn2_Str,
			
			_VarStr(CONCAT(
				'Dok: ', o.Nazwa, ' (', o.Opis, ')',
				IF(@n.NrDok != '', CONCAT(' - Nr: ', @n.NrDok), '')
			)) AS LabelInfo1,
			
			_VarStr(CONCAT(
				@.FMagCommentA, ' (', @.FMagCommentB, ')'
			)) AS LabelInfo2,
			
			_VarStr(CONCAT('Id: ', 
				IF(@n.Idn = 0, '?', @n.Idn) 
			)) AS LabelInfo3,
			
			_VarStr(CONCAT(
				IF(k.GUID IS NOT NULL,
					CONCAT(
						@.FMagCommentC,
						_ConcatSTR(
							IF(IFNULL(k.dostawca, 0) != 0, 'dostawca', ''),
							IF(IFNULL(k.odbiorca, 0) != 0, 'odbiorca', ''),
							', '
						),
						'(', k.Symbol, ') ', k.Nazwa
					),
					''
				)
			)) AS LabelInfo4,
			
			_VarStr(
				IF(o.IsWaluta AND (IFNULL(w.IDN, 0) != 0),
					CONCAT(
						w.NazwaWaluty,
						' (', 
						IF(NOT o.IsSprzedazNieKrajowa, 'kurs', 'rate'), 
						': ', _VarStr(@n.Kurs), ')'
					),
					''
				)
			) AS LabelInfo5,
			o.ZezwalajNaGrupowaniePozycji,
			u.Need_Update
			
			-- o.Ma_detale AS DefaultTymczasowa
/*			
(CRdzOper[FCRdzOperIdx{slon to co u gory FNgTransact.FRodzaj}].FVdoWZPZ=1) and
    ((FFVdoPZ and (CRdzOper[FCRdzOperIdx{slon to co u gory FNgTransact.FRodzaj}].twtyp=twPZ)) or
    (FFVdoWZ and (CRdzOper[FCRdzOperIdx{slon to co u gory FNgTransact.FRodzaj}].twtyp=twRZ))
    )
*/
		FROM `ng_e_rec` u
		-- LEFT JOIN `opng_e` n ON n.GUID = u.GUID
		LEFT JOIN `operdoc` o ON o.Rodzaj = @n.Rodzaj
		LEFT JOIN `operdoc_typy` p ON p.Rodzaj = o.Rodzaj AND p.Typ = @n.Rodzaj_Typ
		LEFT JOIN `kontrah` k ON k.GUID = @n.KontrGUID
		LEFT JOIN `waluty` w ON w.Idn = @n.Waluta
		LEFT JOIN `Magazyny` m1 ON m1.IdnMagazynu = u.i_Magazyn1_Kasa 
		LEFT JOIN `Magazyny` m2 ON m2.IdnMagazynu = u.i_Magazyn2 
		WHERE
			u.GUID = _Key
		;
SET @Deb.1 = '9';
	END IF;	
	
	IF _MODE = 'update.from.xxng_e' THEN
	/**********************************************************************************************************************************
		np. po zmianie Magazynu, AreaGUID etc
		CALL _ng_e_rec_do('update.from.xxng_e', _Key, '', '');	-- update ng_rec_e
	**********************************************************************************************************************************/
		CALL _ng_e_rec_do('select.into', _Key, '', '');	
		
		IF @handle_FROM = 'OP' THEN
			UPDATE `ng_e_rec` r, `opng_e` n
			SET
				r.Rodzaj = n.Rodzaj, 
				r.Rodzaj_Typ = n.Rodzaj_Typ, 
				r.i_Calc_Ver = n.Calc_Ver, 
				r.i_KontrGUID = n.KontrGUID, 
				r.i_Magazyn1_Kasa = n.Zmagazynu, 
				r.i_Magazyn2 = n.Domagazynu, 
				r.i_Tymczasowa = n.Tymczasowa, 
				r.i_Waluta = n.Waluta, 
				r.i_OsobaGUID = n.OsobaGUID, 
				r.i_AreaGUID = n.AreaGUID, 
				r.i_fvrudowz = n.fvrudowz 
			WHERE
				r.GUID = _Key
				AND
				n.GUID = _Key
			;	
		ELSEIF @handle_FROM = 'ZM' THEN		--	ZM
			UPDATE `ng_e_rec` r, `zmng_e` n
			SET
				r.Rodzaj = n.Rodzaj, 
				r.Rodzaj_Typ = n.Rodzaj_Typ, 
				r.i_Calc_Ver = n.Calc_Ver, 
				r.i_KontrGUID = n.KontrGUID, 
				r.i_Magazyn1_Kasa = n.idnmagazyn,
				r.i_Magazyn2 = n.MagazynWys,
				r.i_Tymczasowa = n.Tymczasowa, 
				r.i_Waluta = n.Waluta, 
				r.i_OsobaGUID = n.OsobaGUID, 
				r.i_AreaGUID = n.AreaGUID 
			WHERE
				r.GUID = _Key
				AND
				n.GUID = _Key
			;	
		END IF;	
	END IF;	

	IF _MODE = 'create' THEN
	/**********************************************************************************************************************************
	Kreowanie
	**********************************************************************************************************************************/
			SET @XXX = 'create...';
			SET @.X = 'create...';
			SET @YYY = '10.1.1';

											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.1.a', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
		SELECT
			r.handle_FROM,
			r.handle_oper,
			r.handle_UserLogin,
			r.handle_status
		INTO
			@_ng_e_rec_do.create.handle_FROM,
			@_ng_e_rec_do.create.handle_oper,
			@_ng_e_rec_do.create.handle_UserLogin,
			@_ng_e_rec_do.create.handle_status
		FROM `ng_e_rec` r
		WHERE
			r.GUID = _Key
		;
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.1.b', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			SET @YYY = '10.1.2';
		IF (@_ng_e_rec_do.create.handle_status != 0) OR (@_ng_e_rec_do.create.handle_oper != 'INSERT') THEN 
			LEAVE S_ng_e_rec_do;
		END IF;
		
			SET @YYY = '10.1.3';
		SET 
			@_ng_e_rec_do.create.handle_UserLogin = 
				IF(IFNULL(@_ng_e_rec_do.create.handle_UserLogin, '') = '',
					IFNULL(@session.Registration.IdnUser, IFNULL(@session.CheckLogonUserLogin, '')),
					@_ng_e_rec_do.create.handle_UserLogin
				)
		;
		-- SET @IdnUser = IFNULL(@session.Registration.IdnUser, IFNULL(@session.CheckLogonUserLogin, ''));
			SET @YYY = '10.1.4';
		IF @_ng_e_rec_do.create.handle_UserLogin = '' AND (@SYSTEM.Client.Session.log_USER_GUID != '') THEN
		--	gdy @SYSTEM.Client.Session.log_USER_GUID <> '' to oznacza ze @SYSTEM.Client.Session.log_USER takze jest <> ''  UWAGA @SYSTEM.Client.xxxx to zmienne ustawiana via www
			SET @_ng_e_rec_do.create.handle_UserLogin = @SYSTEM.Client.Session.log_USER;
		END IF;
		
			SET @YYY = '10.1.5';
		IF @_ng_e_rec_do.create.handle_FROM = 'OP' THEN
		/**********************************************************************************************************************************
			opng_e
		**********************************************************************************************************************************/
			SET @XXX = concat_WS('->', @XXX, 'create.200');
			SET @.X = concat_WS('->', @XXX, 'create.200');

											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.5', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			INSERT IGNORE INTO `opng_e`
				(
				GUID, tag, Rodzaj, Rodzaj_typ, DataWystaw, idnuser, -- CreatorGUID,
				Calc_Ver,
				fvrudowz,
				rozrachunek
				)
			SELECT
				r.GUID, -1, r.Rodzaj, r.Rodzaj_typ, CURRENT_DATE(), @_ng_e_rec_do.create.handle_UserLogin, -- @SYSTEM.Client.Session.log_USER_GUID,
				r.i_Calc_Ver, 
				r.i_fvrudowz,
				0
			FROM `ng_e_rec` r
			WHERE
				r.GUID = _Key
			;
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.6', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			IF @session.globals.Owner IN ('TRANSBUD') THEN			
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.6.transbud', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
				UPDATE `opng_e` n, `ng_e_rec` r
				SET
					n.Tag = -1,	 -- Inicjowanie rekordu (potem Tag wraca na stara wartosc
					n.zmagazynu = r.i_Magazyn1_Kasa, 
					n.domagazynu = r.i_Magazyn2
				WHERE
					r.GUID = _Key
					AND
					n.GUID = r.GUID
				;	
			END IF;
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.6....', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			
			SET @XXX = concat_WS('->', @XXX, 'create.200.1');
			SET @.X = concat_WS('->', @XXX, 'create.200.1');
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.7', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			UPDATE `opng_e` n, `ng_e_rec` r
			SET
				n.Tag = -1,	 -- Inicjowanie rekordu (potem Tag wraca na stara wartosc
				n.KontrGUID = r.i_KontrGUID, 
				n.zmagazynu = r.i_Magazyn1_Kasa, 
				n.domagazynu = r.i_Magazyn2, 
				n.tymczasowa = r.i_Tymczasowa,
				n.Waluta = r.i_Waluta, 
				n.Waluta_Rozliczen = r.i_Waluta, 
				n.OsobaGUID = IFNULL(r.i_OsobaGUID, ''),
				n.AreaGUID = IFNULL(r.i_AreaGUID, ''),
				n.IdnUser = r.handle_UserLogin,
				n.UgrpGUID = r.handle_UserUgrpGUID,
				n.CreatorGUID = r.handle_UserGUID
			WHERE
				r.GUID = _Key
				AND
				n.GUID = r.GUID
			;	
			SET @XXX = concat_WS('->', @XXX, 'create.200.2');
			SET @.X = concat_WS('->', @XXX, 'create.200.2');
			
			-- slon dodal to zeby ustawiac flage nettodorozrach nie wiem czy slusznie i czy tu chcesz miec to ustawiane
			-- mozesz odrazu w pozniejszym terminie dorobic dla nie walutowych 
			
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.8', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			UPDATE `opng_e` oe, `operdoc` od 
			SET 
				oe.NettoDoRozrach = od.NettoDoRozrachWal 
			WHERE 
				oe.rodzaj = od.rodzaj 
				AND 
				oe.waluta_rozliczen > 0 
				AND 
				oe.guid = _Key
			;
	
			SET @XXX = concat_WS('->', @XXX, 'create.200.3');
			SET @.X = concat_WS('->', @XXX, 'create.200.3');
			
		ELSEIF @_ng_e_rec_do.create.handle_FROM = 'ZM' THEN
		/**********************************************************************************************************************************
			zmng_e
		**********************************************************************************************************************************/
			SET @YYY = '10.1.6';
            SET @XXX = 'INS INTO `zmng_e`';
			INSERT IGNORE INTO `zmng_e`
				(
				GUID, Rodzaj, Rodzaj_typ, DataWystaw, idnuser, 
				Calc_Ver
				)
			SELECT
				r.GUID, r.Rodzaj, r.Rodzaj_typ, CURRENT_DATE(), @_ng_e_rec_do.create.handle_UserLogin, 
				r.i_Calc_Ver 
			FROM `ng_e_rec` r
			WHERE
				r.GUID = _Key
			;
			SET @YYY = '10.1.7';
            SET @XXX = 'UPDATE `zmng_e` n, `ng_e_rec` r';
			UPDATE `zmng_e` n, `ng_e_rec` r
			SET
				n.KontrGUID = r.i_KontrGUID, 
				n.IDNMagazyn = r.i_Magazyn1_Kasa, 
				n.MagazynWys = r.i_Magazyn2, 
				n.tymczasowa = r.i_Tymczasowa,
				n.Waluta = r.i_Waluta, 
				n.OsobaGUID = IFNULL(r.i_OsobaGUID, ''),
				n.AreaGUID = IFNULL(r.i_AreaGUID, ''),
				n.IdnUser = r.handle_UserLogin,
				n.UgrpGUID = r.handle_UserUgrpGUID,
				n.CreatorGUID = r.handle_UserGUID
			WHERE
				r.GUID = _Key
				AND
				n.GUID = r.GUID
			;	
			SET @YYY = '10.1.8';
			SET @XXX = 'adasdf';
		ELSE	
		/**********************************************************************************************************************************
			opng_r_e	KS, BN, RR
		**********************************************************************************************************************************/
			INSERT IGNORE INTO `opng_r_e`
				(
				GUID, tag, Rodzaj, Rodzaj_typ, DataWystaw, idnuser, 
				KontrGUID,
				Calc_Ver,
				fvrudowz,
				rozrachunek,
				Family_GUID,
				nrraportu,
				nrkasy,
				UgrpGUID,
				RodzajDowodu
				)
			SELECT
				r.GUID, -1, r.Rodzaj, r.Rodzaj_typ, r_datawystaw, @_ng_e_rec_do.create.handle_UserLogin, 
				'',
				r.i_Calc_Ver, 
				r.i_fvrudowz,
				1,
				r_Family_GUID,
				r_nrraportu,
				r_nrkasy,
				r_UgrpGUID,
				r_RodzajDowodu
			FROM `ng_e_rec` r
			WHERE
				r.GUID = _Key
			;
			SET @XXX = 'afterrun.1';
			UPDATE `opng_r_e` n, `ng_e_rec` r
			SET
				n.Tag = -1,	 -- Inicjowanie rekordu (potem Tag wraca na stara wartosc
				n.KontrGUID = r.i_KontrGUID, 
				n.tymczasowa = r.i_Tymczasowa,
				n.Waluta = r.i_Waluta, 
				n.Waluta_Rozliczen = r.i_Waluta, 
				n.OsobaGUID = IFNULL(r.i_OsobaGUID, ''),
				n.AreaGUID = IFNULL(r.i_AreaGUID, ''),
				n.IdnUser = r.handle_UserLogin,
				n.UgrpGUID = r.handle_UserUgrpGUID
			WHERE
				r.GUID = _Key
				AND
				n.GUID = r.GUID
			;	
			
			SET @XXX = 'afterrun.2';
			-- slon dodal to zeby ustawiac flage nettodorozrach nie wiem czy slusznie i czy tu chcesz miec to ustawiane
			-- mozesz odrazu w pozniejszym terminie dorobic dla nie walutowych 
			
		END IF;
		SET @XXX = concat_WS('->', @XXX, 'afterrun.200.3');
		SET @.X = concat_WS('->', @XXX, 'create.200.3');
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a.create.9', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
	END IF;	
	
	IF _MODE = 'check.kontrahent' OR _MODE = 'check.kontrahent.new' THEN
	/**********************************************************************************************************************************
	Kontrahent - zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	**********************************************************************************************************************************/
		CALL _ng_e_rec_msg_clear('', _Key, 'check.kontrahent', '');
		SET
			@Kontrah_Invalid_Msg = '',
			-- @Kontrah_Msg = ''
			@Kontrah_Msg = NULL
		;
		SET @k.KontrGUID := NULL, @k.PlatnikGUID := NULL;
		SELECT 
			_VarInt(0) AS Kontrah_Is_not_OK,
			-- k.GUID,
			k.GUID AS KontrGUID,
            kplat.GUID AS PlatnikGUID,
			k.Blokujsprzedaz, 
			kplat.Blokujsprzedaz AS BlokujsprzedazPlatnik, 
			k.blokada_zwrotow,
			k.Nazwa,
			k.Symbol,
			r.Rodzaj,
			o.TwTyp,
			o.magtyp,
			k.kredyt
		INTO
			@Kontrah_Is_not_OK,
			-- było @k.GUID,
            @k.KontrGUID,
            @k.PlatnikGUID,
			@k.Blokujsprzedaz, 
			@k.BlokujsprzedazPlatnik,
			@k.blokada_zwrotow,
			@k.Nazwa,
			@k.Symbol,
			@r.Rodzaj,
			@o.TwTyp,
			@o.magtyp,
			@k.kredyt
		-- było FROM `kontrah` k, `ng_e_rec` r, `operdoc` o
		FROM `ng_e_rec` r 
		INNER JOIN `kontrah` k ON k.GUID = _Param_A
		INNER JOIN `operdoc` o ON o.Rodzaj = r.Rodzaj
		LEFT JOIN `kontrah` kplat ON kplat.GUID = k.PlatnikGUID
		WHERE
			r.GUID = _Key
		/*było	AND
			o.Rodzaj = r.Rodzaj
			AND
			k.GUID = _Param_A   */
		;
        SET @k.GUID := @k.KontrGUID;    -- dla kompat.
		/**********************************************************************************************************************************
			Blokujsprzedaz
		**********************************************************************************************************************************/
		-- bylo do 25 VI 2024 IF (@o.TwTyp = @ht.TwRZ) AND (@k.Blokujsprzedaz <> 0) THEN
		IF @session.globals.Owner = 'PARAQUA' THEN
        --  PŁATNIK!!!!
            SET @K.Czy.Spr := 
                !(@k.PlatnikGUID <=> @k.KontrGUID) AND  -- gdy płatnik <> kontrah i ...
                @o.magtyp = 2 AND   -- rozchodowy i ...
                (
                    @o.TwTyp IN (@ht.TwRZ) OR   -- op. rozchodowa lub ...
                    (@o.TwTyp IN (@ht.TwZm) AND @session.HT.IR.Blokuj_kontrahenta_przy_zam_i_zlecprod) -- zam. i badamy
                )
            ;
            IF @K.Czy.Spr AND (@k.BlokujsprzedazPlatnik <> 0) THEN
                SET
                    @Kontrah_Is_not_OK = @Kontrah_Is_not_OK OR 1,
                    @Kontrah_Invalid_Msg = 
                        _ConcatSTR(@Kontrah_Invalid_Msg,
                            CONCAT(
                                'Kontrahent: ', @k.Nazwa, '\n',
                                'Symbol: "', @k.Symbol, '"\n',
                                'Ma zablokowaną sprzedaż w systemie!\n',
                                'W celu umożliwienia sprzedaży należy zdjąć blokadę w karcie tego kontrahenta.\n'
                            ),
                            '\n ------------------------------------------------------------------\n'
                        )
                    ;
                    CALL _ng_e_rec_msg_ins('', '', _Key, 'check.kontrahent', 
                        REPLACE(REPLACE(_res_str_get('ng_msg_check.kontrahent.Blokujsprzedaz', ''), '#KontrNazwa#', _VarStr(@k.Nazwa)), '#KontrSymbol#', _VarStr(@k.Symbol)),
                        'Error', 
                        'Stop', '', ''
                    );
            END IF;
		END IF;
			
		IF (@k.Blokujsprzedaz <> 0) AND @o.TwTyp IN (@ht.TwRZ, @ht.TwZm) AND @o.magtyp = 2 THEN
			SET
				@Kontrah_Is_not_OK = @Kontrah_Is_not_OK OR 1,
				@Kontrah_Invalid_Msg = 
					_ConcatSTR(@Kontrah_Invalid_Msg,
						CONCAT(
							'Kontrahent: ', @k.Nazwa, '\n',
							'Symbol: "', @k.Symbol, '"\n',
							'Ma zablokowaną sprzedaż w systemie!\n',
							'W celu umożliwienia sprzedaży należy zdjąć blokadę w karcie tego kontrahenta.\n'
						),
						'\n ------------------------------------------------------------------\n'
					)
				;
				CALL _ng_e_rec_msg_ins('', '', _Key, 'check.kontrahent', 
					REPLACE(REPLACE(_res_str_get('ng_msg_check.kontrahent.Blokujsprzedaz', ''), '#KontrNazwa#', _VarStr(@k.Nazwa)), '#KontrSymbol#', _VarStr(@k.Symbol)),
					'Error', 
					'Stop', '', ''
				);
		END IF;
		/**********************************************************************************************************************************
			blokada_zwrotow / JARZEBINSCY
		**********************************************************************************************************************************/
		IF (@session.globals.Owner = 'JARZEBINSCY') 
			AND (@r.Rodzaj = @ht.CMGZW) AND (@k.blokada_zwrotow <> 0) THEN
			SET
				@Kontrah_Is_not_OK = @Kontrah_Is_not_OK OR 1,
				@Kontrah_Invalid_Msg = 
					_ConcatSTR(@Kontrah_Invalid_Msg,
						CONCAT(
							'Kontrahent: ', @k.Nazwa, '\n',
							'Symbol: "', @k.Symbol, '"\n',
							'Wybrany kontrahent ma włączoną blokadę zwrotów!\n',
							'Proszę wybrać innego lub anulować operację.\n'
						),
						'\n ------------------------------------------------------------------\n'
					)
				;
				CALL _ng_e_rec_msg_ins('', '', _Key, 'check.kontrahent', 
					REPLACE(REPLACE(_res_str_get('ng_msg_check.kontrahent.blokada_zwrotow', ''), '#KontrNazwa#', _VarStr(@k.Nazwa)), '#KontrSymbol#', _VarStr(@k.Symbol)),
					'Error', 
					'Stop', '', ''
				);
		END IF;
		
		/**********************************************************************************************************************************
			Ostrz. brak ostatnio operacji / IZOHAN
		**********************************************************************************************************************************/
		IF (@session.globals.Owner IN ('PARAQUA', 'IZOHAN')) AND (@r.Rodzaj = @ht.CZmOO) THEN
			SET @przelewowy = 
				IFNULL(
				(
				SELECT 
					IF (p.rodzaj = 1 AND p.dni > 0, 1, 0) AS przelewowy -- , k.sposplat, p.rodzaj
				FROM `kontrah` k 
				LEFT JOIN `platnosc` p ON k.sposplat = p.idn  
				WHERE 
					k.GUID = @k.GUID
					AND k.deleted = 0
				), 0)
			;
			IF @przelewowy = 1 THEN
			
				SET @przelewowy.Ile = 
					IFNULL(
					(
						SELECT 
							COUNT(*) AS ile 
						FROM `opng` n, `rozrach` r, `opng` n2  
						WHERE 
							n.rodzaj IN (0,1,2,50) 
							AND n.guid = r.idnoper 
							AND n2.guid = r.idnoper2 
							AND n2.rodzaj IN (20, 36) 
							AND n.nierozliczony = 0 
							AND n.datawystaw >= DATE_SUB(CURRENT_DATE,INTERVAL 1 YEAR) 
							AND n.brutto >= 200 
							AND (TO_DAYS(n.datarozliczenia) - TO_DAYS(n.dataplatnosci) < 60) 
							AND n.platnikGUID = @k.GUID
					), 0)
				;
				IF @przelewowy.Ile = 0 THEN
					SET
						@przelewowy.Kontrah_Invalid_Msg = 
							CONCAT(
								'Kontrahent: ', @k.Nazwa, '\n',
								'Symbol: "', @k.Symbol, '"\n',
								'Brak przynajmniej 2 operacji wystawionych dla wskazanego kontrahenta w ciągu ostatnich 12 miesięcy\n',
								'na kwotę minimum 200 zł brutto, zapłaconych do 60 dni po terminie płatności!\n',
								'Proszę wybrać innego lub anulować operację.\n'
							)
						;
					CALL _ng_e_rec_msg_ins('', '', _Key, 'check.kontrahent', 
						@przelewowy.Kontrah_Invalid_Msg,
						-- REPLACE(REPLACE(_res_str_get('ng_msg_check.kontrahent.blokada_zwrotow', ''), '#KontrNazwa#', _VarStr(@k.Nazwa)), '#KontrSymbol#', _VarStr(@k.Symbol)),
						'Warning', 
						'', '', ''
					);
				END IF;
			END IF;
		END IF;
		
		/**********************************************************************************************************************************
			Uwagi-Komunikat / Popraw uwagi kontrahenta
		**********************************************************************************************************************************/
		IF @session.HT.IR.KontrahAlert_ZMSTZTMG THEN
			SET @komunikat = NULL;
		/*	było		
			SELECT
				IF(k.wysylacFVviaMail = 1,
					_ConcatSTR2('Zgoda na wysyłkę faktury elektronicznej',
						k.uwagi,
						'\n------------------------------------------------------------------\n'
					),
					k.uwagi
				) AS Komunikat
			FROM `kontrah` k
			WHERE 
				k.GUID = _Param_A
			INTO
				@komunikat
			;
		*/
			SELECT
				CONCAT_WS('\n------------------------------------------------------------------\n',
					IF(k.wysylacFVviaMail = 1, _VarStr('Zgoda na wysyłkę faktury elektronicznej'), NULL),
					k.uwagi
				) AS Komunikat
			INTO
				@komunikat
			FROM `kontrah` k
			WHERE 
				k.GUID = _Param_A
			;
			
		/*	było
			gdy nie było kolunikatów to zwracał bez sensu komunikat "Popraw uwagi kontrahenta"
			ale 8 V 2022 uzgodniliśmy TL,GP,JG że temat może powrócić na inny klucz i w walidatorach
			SET @komunikat = IF(IFNULL(@komunikat, '') != '', @komunikat, _res_str_get('ng_msg_check.kontrahent.Uwagi-Komunikat', ''));
			SET
				@Kontrah_Msg = 
					_ConcatSTR2(@Kontrah_Msg,
						@komunikat,
						'\n ------------------------------------------------------------------\n'
					)
			;
			...
		*/
			SET
				@Kontrah_Msg = 
					CONCAT_WS('\n------------------------------------------------------------------\n',
						NULLIF(_VarStr(@Kontrah_Msg), ''),
						NULLIF(_VarStr(@komunikat), '')
					)
			;
		END IF;
		
		/**********************************************************************************************************************************
			Informuj_o_materialach_propagandowych
		**********************************************************************************************************************************/
		IF @session.HT.IR.Informuj_o_materialach_propagandowych THEN
			SET @komunikat = NULL, @wydaj = NULL;
			SELECT
				_VarStr('Należy wydać materialy propagandowe') AS Komunikat,
				IFNULL(max(o.datawystaw),'wcale') AS data_ost_wydania,
				to_days(current_date)-to_days(IFNULL(max(o.datawystaw),'2000-01-01'))>180 AS wydaj 
			INTO
				@komunikat, @data_ost_wydania, @wydaj
			FROM `oppo` o, `opng` n 
			WHERE 
				o.idnoper = n.guid 
				AND n.zmagazynu <> 0 
				AND n.kontrguid= _Param_A
			;
			IF IFNULL(@wydaj, FALSE) THEN
			/*	było
				SET
					@Kontrah_Msg = 
						_ConcatSTR2(@Kontrah_Msg,
							@komunikat,
							'\n------------------------------------------------------------------\n'
						)
				;
			*/	
				SET
					@Kontrah_Msg = 
						CONCAT_WS('\n------------------------------------------------------------------\n',
							NULLIF(_VarStr(@Kontrah_Msg), ''),
							NULLIF(_VarStr(@komunikat), '')
						)
				;
			END IF;
		END IF;
		
		IF IFNULL(@Kontrah_Msg, '') != '' THEN
			CALL _ng_e_rec_msg_ins('', '', _Key, 'check.kontrahent', 
				CONCAT_WS('\n------------------------------------------------------------------\n',
					_VarStr('Uwagi kontrahenta:\n'),
					_VarStr(@Kontrah_Msg)
				),
				'Msg', 
				'', '', ''
			);
		END IF;

		CALL _ng_e_rec_msg_select('', _Key, 'check.kontrahent', '');
		
		/*
		SELECT
			_VarInt(@Kontrah_Is_not_OK) AS Kontrah_Is_not_OK,
			_VarStr(@Kontrah_Invalid_Msg) AS Kontrah_Invalid_Msg,
			_VarStr(@Kontrah_Msg) AS Kontrah_Msg,
			_VarStr('') AS Kontrah_Ask_Msg,
			_VarDouble(@k.kredyt) AS Kredyt
		FROM `kontrah` k
		WHERE
			k.GUID = _Param_A
		;
		*/
		
	END IF;	
	
	IF _MODE = 'Need.Update' THEN
	/**********************************************************************************************************************************
	wolany po kazdym post w celu informacji ze nalezy rekord zapisac (apply e->r) - wstawiamy Need_Update = 1
	**********************************************************************************************************************************/
		UPDATE `ng_e_rec` r
		SET
			r.Need_Update = 1 
		WHERE
			r.GUID = _Key
		;
	END IF;	
	
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_set`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_set`(
	IN _MODE VARCHAR(250),	--	
	IN _Key VARCHAR(38),	
	IN _Rodzaj INTEGER,
	IN _Rodzaj_Typ INTEGER,
	IN i_MODE VARCHAR(255),
	IN i_Calc_Ver INTEGER,
	IN i_KontrGUID VARCHAR(38),
	IN i_Magazyn1_Kasa INTEGER,
	IN i_Magazyn2 INTEGER,
	IN i_Tymczasowa INTEGER,
	IN i_Waluta INTEGER,
	IN i_OsobaGUID VARCHAR(38),
	IN i_AreaGUID VARCHAR(38),
	IN i_Input_GUID VARCHAR(255),
	IN i_fvrudowz INTEGER,
	IN i_Param_A VARCHAR(255),
	IN i_Param_B VARCHAR(255),
	IN i_Param_C VARCHAR(255)
	
)
/*
	CALL _ng_e_rec_set('', 'x', 1, 0, '', 0, 'kontrGUID', 1, 0, 0, 0, 'OsobaGUID', 'AreaGUID', '', 0, '', '', '');
	CALL _ng_e_rec_set('', 'x', 10, 0, '', 0, 'kontrGUID', 1, 3, 0, 0, 'OsobaGUID', 'AreaGUID', '', 0, '', '', '');
*/
S_ng_e_rec_set: BEGIN 
	DECLARE _SQLText, _SQLText_NG_statement TEXT;
						set @.ng_e_rec.test = '1';
						set @.2.i_Tymczasowa = i_Tymczasowa;

		UPDATE `ng_e_rec` r
		SET
			r.Rodzaj = _Rodzaj, 
			r.Rodzaj_Typ = _Rodzaj_Typ, 
			r.i_MODE = i_MODE, 
			r.i_Calc_Ver = i_Calc_Ver, 
			r.i_KontrGUID = IFNULL(i_KontrGUID, ''), 
			r.i_Magazyn1_Kasa = i_Magazyn1_Kasa, 
			r.r_nrkasy = IF(handle_FROM = 'R', i_Magazyn1_Kasa, r.r_nrkasy),
			r.i_Magazyn2 = i_Magazyn2, 
			r.i_Tymczasowa = i_Tymczasowa, 
			r.i_Waluta = i_Waluta, 
			r.i_OsobaGUID = IFNULL(i_OsobaGUID, ''), 
			r.i_AreaGUID = IFNULL(i_AreaGUID, ''), 
			r.i_Input_GUID = IFNULL(i_Input_GUID, ''), 
			r.i_fvrudowz = i_fvrudowz, 
			r.i_Param_A = i_Param_A, 
			r.i_Param_B = i_Param_B, 
			r.i_Param_C = i_Param_C
		WHERE
			r.GUID = _Key
		;	
						set @.ng_e_rec.test = '2';
	
	
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_set_from_another_doc`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_set_from_another_doc`(
	IN i_MODE VARCHAR(250),	--	
	IN _Key VARCHAR(38),	
	IN _OtherKey VARCHAR(38),	
	IN i_Param_A VARCHAR(255),
	IN i_Param_B VARCHAR(255),
	IN i_Param_C VARCHAR(255)
	
)
/*
	CALL _ng_e_rec_set_from_another_doc('', 'Key', '_OtherKey', '', '', '');
*/
BEGIN 
	DECLARE _SQLText, _SQLText_NG_statement TEXT;
	
	UPDATE `ng_e_rec` r -- , `opng` n
	SET
		r.i_MODE = i_MODE,
	--	TU JEST CLUE sprawy -> (102) reszta w triggerze czyli zapoczatkowanie zmiennych z rekordu z opng dla opng_e i zmng dla zmng_e. Ale!!! dla opng_e z zmng (czyli realizacji zam. TO JUZ NIE!!!!)
		r.handle_check = 102,	
		r.i_Input_GUID = _OtherKey,
		r.i_Param_A = i_Param_A, 
		r.i_Param_B = i_Param_B, 
		r.i_Param_C = i_Param_C
	WHERE
		r.GUID = _Key
		AND
		r.handle_oper = 'Insert'
	;	
	
	set @watch = 'ccc';
	
/*
		UPDATE `ng_e_rec` r, `opng` n
		SET
			r.Rodzaj = n.Rodzaj, 
			r.Rodzaj_Typ = n.Rodzaj_Typ, 
			r.i_Calc_Ver = n.Calc_Ver, 
			r.i_KontrGUID = n.KontrGUID, 
			r.i_Magazyn1_Kasa = n.Zmagazynu, 
			r.i_Magazyn2 = n.Domagazynu, 
			r.i_Tymczasowa = n.Tymczasowa, 
			r.i_Waluta = n.Waluta, 
			r.i_OsobaGUID = n.OsobaGUID, 
			r.i_AreaGUID = n.AreaGUID, 
			r.i_fvrudowz = n.fvrudowz, 
			r.i_Param_A = i_Param_A, 
			r.i_Param_B = i_Param_B, 
			r.i_Param_C = i_Param_C
		WHERE
			r.GUID = _Key
			AND
			r.handle_oper = 'Insert'
			AND
			n.GUID = _OtherKey
		;	
*/	
	
END$$

DROP PROCEDURE IF EXISTS `_ng_E_Run`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_Run`(
	IN _MODE VARCHAR(250),	 --	'before.run' 'after.run' ''
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255),
	IN _Param_C VARCHAR(255)
)
/*
	CALL _ng_E_Run('before.run', 'x', '', '', '');
	CALL _ng_E_Run('', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', '', '', '');
	CALL _ng_E_Run('after.run', 'x', '', '', '');
	CALL _ng_E_Run('after.print', 'x', '', '', '');
*/
BEGIN 
    SET @.eID.EXE := IFNULL(@.eID.EXE, @SYSTEM.Client.Session.GUID);

	IF _MODE = 'before.run' THEN
	/**********************************************************************************************************************************
		przed operacją (Edit lub Insert)
	**********************************************************************************************************************************/
	
		CALL _ng_e_rec_do('check.semafor', _Key, '', '');	-- sprawdz semafor
		CALL _ng_e_rec_do('check.upr.1', _Key, '', '');	-- sprawdz uprawnienie BEFORE	przed operacja
		IF _Param_C != '' THEN
			CALL _ng_e_rec_do('select', _Key, '', '');	-- zwróć wszystkie ustawienia (kolumny `ng_e_rec`, `operdoc` i `operdoc`
		END IF;	
	END IF;	
	
	IF _MODE = '' THEN
	/**********************************************************************************************************************************
		RUN Czyli mamy juz załadowany lub skreowany rekord
	**********************************************************************************************************************************/
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'pusty', null), '_ng_E_Run', '', '', @.jmam.GP.log);
		
		SELECT
			handle_oper,
			handle_FROM,
			i_MODE,
			i_Input_GUID,
			i_param_A,
			i_param_B,
			i_param_C
		INTO
			@handle_oper,
			@handle_FROM,
			@i_MODE,
			@i_Input_GUID,
			@i_param_A,
			@i_param_B,
			@i_param_C
		FROM `ng_e_rec` r
		WHERE
			r.GUID = _Key
		;	
set @rozrach_Change_Tymczasowa = '11';		
                SET @ng_E_Run.dubug = '..""..';
		IF (@handle_oper = 'Insert') THEN
		/**********************************************************************************************************************************
			INSERT
		**********************************************************************************************************************************/
			SET @YYY = '10.1';
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&3', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			CALL _ng_E_Tools('update.LP', _Key, @handle_FROM, '');
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.a', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			CALL _ng_e_rec_do('create', _Key, '', '');	-- stworz rekord opng_e lub zmng_e lub opng_r_e (o ile jest to handle_oper = 'INSERT'
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&4.b', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			SET @XXX = 'afterrun.3';
			
			SET @YYY = '10.2';
			
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&5', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			CALL _ng_e_rec_do('select.into', _Key, '', '');	
			/**************************************************************************************************************************
				CZY FV do WZ/PZ
			**************************************************************************************************************************/
			IF @i_fvrudowz THEN
			
			--	Edycja podlaczonych WZ/PZ
				CALL _ng_E_Tools('real.WZPZ.to.e', _Key, @handle_FROM, '');
			END IF;
			SET @XXX = 'afterrun.4';
			SET @YYY = '10.3';
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&6.a', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			CALL _ng_E_Tools('update.LP', _Key, @handle_FROM, '');
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&6.b', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
			SET @YYY = '10.4';
		END IF;
		
		IF (@handle_oper IN ('Edit', 'DELETE')) THEN
		/**********************************************************************************************************************************
			Edycja
		**********************************************************************************************************************************/
			SET @zmpo.real.to.e = 0;
			SET @opng_r.real.to.e = 0;
			set @X = '1';
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'delete.e', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			CALL _ng_E_Tools('delete.e', _Key, @handle_FROM, '');
			set @X = '2'; set @delkor = 'real.to.e';
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			CALL _ng_E_Tools('real.to.e', _Key, @handle_FROM, '');
			set @X = '3';
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'update.LP', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			CALL _ng_E_Tools('update.LP', _Key, @handle_FROM, '');
			set @X = '4';
            IF @handle_FROM = 'ZM' THEN
                IF @session.globals.Owner IN ('PLISZKA') THEN
                --   zmpo instancje
                    CALL zmpo_instancjeE_P('E.EDIT', @.eID.EXE, _Key, '', '', '', '', '', '', '');
                END IF; 
            END IF;
			-- czyli CALL ng_E_LetEdit(_MODE, 'OP', _Key, _Param_A, _Param_B, _Param_C, _Param_D);
		END IF;
		
		
											-- tylko testy!!!	CALL _exproc_LOG('LOG', 'test&7', 'CALL _ng_E_Run', @IdnOper, '', @.X.log);
		IF @session.globals.HT.erp_obj_counters_values_e_1_rec IS NULL THEN
			CALL _Globals_Get('erp_obj_counters_values_e_1_rec', @session.globals.HT.erp_obj_counters_values_e_1_rec, FALSE);		
		END IF;
		IF @session.globals.HT.erp_obj_counters_values_e_1_rec THEN
			-- CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.INIT', @_Numer, @_NumerText, '', , 'podrodzaj', GUID, '', '', '');
			-- xxxxxxxxxxxxxxxxx
			CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', @handle_FROM, _Key, '', '', '', '');
		END IF;
		
		
		
	END IF;	
	
	IF _MODE = 'after.run' THEN
	/**********************************************************************************************************************************
		ustala ReadOnly etc.
	**********************************************************************************************************************************/
		SET @XXX = concat_WS('->', @XXX, _MODE);
		CALL _ng_e_rec_do('check.upr.2', _Key, '', '');	-- sprawdz uprawnienie ON/AFTER	w trakcie operacji
		SET @XXX = concat_WS('->', @XXX, '...');
		IF _Param_C != '' THEN
			CALL _ng_e_rec_do('select', _Key, '', '');	-- zwróć wszystkie ustawienia (kolumny `ng_e_rec`, `operdoc` i `operdoc`
		END IF;	
		SET @XXX = concat_WS('->', @XXX, 'wych');
	END IF;	
	
	IF _MODE = 'after.print' THEN
	/**********************************************************************************************************************************
		po wydruku
	**********************************************************************************************************************************/
		CALL _ng_e_rec_do('select.into', _Key, '', '');	
		IF @session.HT.IR.ZamknijWydrukowanaOperacje THEN
			CALL _ng_DoChangeStatusOnServer('', _Key, @COpngStatus_Zamknieta, @handle_FROM, '');
		ELSEIF @session.HT.IR.UstawPakowaniePoWydrukuOperacji THEN
			CALL _ng_DoChangeStatusOnServer('', _Key, @COpngStatus_PAKOWANA, @handle_FROM, '');
		END IF;
	END IF;	

END$$

DROP PROCEDURE IF EXISTS `_ng_E_LetPost`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_LetPost`(
	IN _MODE VARCHAR(250),	 
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
/*
	CALL _ng_E_LetPost('', 'OP', @IdnOper, '', '');
*/
BEGIN 
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.1&1 _ng_E_LetPost', 'SLON', _Key, '', @._ng_E_LetPost.log);
	IF @session.globals.NEW.CALC.VAT.VI.2017 IS NULL THEN
		CALL _Globals_Get('NEW.CALC.VAT.VI.2017', @session.globals.NEW.CALC.VAT.VI.2017, FALSE);
	END IF;
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.2&2 _ng_E_LetPost', 'SLON', _Key, '', @._ng_E_LetPost.log);
	
	IF _MODE = '' THEN
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3& _ng_E_LetPost', 'SLON', _Key, '', @._ng_E_LetPost.log);
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&1. vat.to.ng', 'SLON', _Key, '', @._ng_E_LetPost.log);
		CALL _ng_E_LetPost('vat.to.ng', _handle_FROM, _Key, '', '');
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&2. ng.to.po', 'SLON', _Key, '', @._ng_E_LetPost.log);
		CALL _ng_E_LetPost('ng.to.po', _handle_FROM, _Key, '', '');
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&3. po.to.ng', 'SLON', _Key, '', @._ng_E_LetPost.log);
		CALL _ng_E_LetPost('po.to.ng', _handle_FROM, _Key, '', '');
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&4. _ng_E_LetPost', 'SLON', _Key, '', @._ng_E_LetPost.log);
		CALL _ng_e_rec_do('update.from.xxng_e', _Key, '', '');	-- update ng_rec_e
	-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&6. _ng_E_LetPost', 'SLON', _Key, '', @._ng_E_LetPost.log);
	--	Uwaga zmienna @_ng_E_LetPost.DONE okresla czy byl POST i sprawdzana jest w _ng_E_LetApply
		SET @_ng_E_LetPost.DONE = TRUE;
	END IF; --  _MODE = '' 
	
	IF (_MODE = 'vat.to.ng') AND _handle_FROM != 'R' /* apro rzekl aby jednak bylo wypelniane AND @ht.doc.IsPodlegaVAT */ THEN
					-- CALL _exproc_LOG('LOG', CONCAT_WS('', '_ng_E_LetPost.3&', 'CALC.VAT.VI.2017=', @session.globals.NEW.CALC.VAT.VI.2017), 'SLON', _Key, '', @._ng_E_LetPost.log);
		IF 
            @session.globals.CALC.VAT.Ver >= '2021' 
            OR (_Key LIKE 'KSEF_%')
        THEN
		/********************************************************
			Nowe od 2021 r. 
		********************************************************/
			CALL C_HT_xxng_vat('Oper.Nalicz.Tabelke+`xxng`+prepare.do.Edycji', _handle_FROM, 'E', _Key, '', '', '', '', '');
		ELSE
		/********************************************************
			Przed 2021 r.   2017, 1999
		********************************************************/
			IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
						/*
						CALL _exproc_LOG('LOG', 
							CONCAT_WS('', '_ng_E_LetPost.3&', 
							'Session.GUID=', @SYSTEM.Client.Session.GUID,
							'Registration.UserGUID=', @session.Registration.UserGUID,
							'log_USER_GUID=', @SYSTEM.Client.Session.log_USER_GUID
							), 
							'SLON', _Key, '', @._ng_E_LetPost.log);
						CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&UPDATE `xxng_vat` and `xxng`', 'SLON', _Key, '', @._ng_E_LetPost.log);
						*/

				CALL xxng_vat_TOOLS('UPDATE `xxng_vat` and `xxng`', _handle_FROM, 'E', _Key, '', '', '', ''); 
				REPLACE INTO `_db_globals` SET `key` = 'xxng_vat_TOOLS', `value` = NOW();
						-- CALL _exproc_LOG('LOG', '_ng_E_LetPost.3&REPLACE INTO `_db_globals`', 'SLON', _Key, '', @._ng_E_LetPost.log);
			ELSE
				CALL ng_vat_e_build_from_po('', _handle_FROM, _Key, '', '');
				CALL ng_vat_e_TO_ng_e('', _handle_FROM, _Key);
			END IF;
		END IF;
	END IF; --  _MODE = '' 
	
	IF (_MODE = 'ng.to.po') AND _handle_FROM != 'R' AND (@ht.doc.Twtyp != @ht.TwNN) THEN
	--	nagłówek do pozycji: rozrzucanie/ l.p. etc
		IF _handle_FROM != 'ZM' THEN
		--	Operacje
			CALL oppo_E_Let_Update('from_opng_e', '', _Key, '', '');
			CALL oppo_E_Let_Update('lp', '', _Key, '', '');
			CALL oppo_E_Let_Update('rozrzucanie', '', _Key, '', '');
		ELSE
		--	Zamowienia
			CALL zmpo_E_Let_Update('from_zmng_e', '', _Key, '', '');
			CALL zmpo_E_Let_Update('lp', '', _Key, '', '');
		END IF;
	END IF; --  _MODE = '' 
	
	IF (_MODE = 'po.to.ng') AND _handle_FROM != 'R' AND (@ht.doc.Twtyp != @ht.TwNN) THEN
	--	pozycje do nagłówka: liczba pozycji i inne agregaty
		IF _handle_FROM != 'ZM' THEN
		--	Operacje
			UPDATE `opng_e` n, `operdoc` od
			SET
				n.tag = 2,	--	faza oppo to nbg
				n.ilepoz = (SELECT COUNT(*) FROM `oppo_e` p WHERE p.IdnOper = n.GUID),
				n.waga = IFNULL((SELECT SUM(IFNULL(p.waga, 0)) FROM `oppo_e` p WHERE p.IdnOper = n.GUID), 0),
				n.netto_bez_zaliczki = IFNULL((SELECT SUM(IFNULL(p.wartnet, 0)) FROM `oppo_e` p WHERE p.idnoperfin = n.GUID AND p.usluga <> 8), 0),
				/* było !!!
				n.jpkgtu = 
					IF(od.Grupa IN (@ht.ST, @ht.SI),
						(SELECT GROUP_CONCAT(DISTINCT t.jpkgtu) AS jpkgtu FROM `oppo_e` p LEFT JOIN `TowrNg` t ON p.idntowr = t.guid WHERE p.idnoperfin = n.GUID ORDER BY t.jpkgtu),
						n.jpkgtu
					)
				.. jest ...
				*/
				n.jpkgtu = 
					IF(od.Grupa IN (@ht.ST, @ht.SI),
						IF(IFNULL(@session.HT.IR.Ustaw_jpkgtu_na_podstawie_pozycji, FALSE),	
						-- tylko z pozycji !!!!
							(
							SELECT 
								GROUP_CONCAT(DISTINCT jpkgtu SEPARATOR ';') AS jpkgtu 
							FROM `oppo_e` p 
							LEFT JOIN `TowrNg` t ON p.idntowr = t.guid 
							WHERE 
								p.idnoperfin = n.GUID 
							ORDER BY t.jpkgtu
							),
						-- Kombinacja z nagl. i pozycji.	
							(
							SELECT
								GROUP_CONCAT(DISTINCT jpkgtu SEPARATOR ';') AS jpkgtu
							FROM
							(
								SELECT
									g.Value AS jpkgtu 
								FROM `v_jpk_gtu` g, `opng_e` nn
								WHERE
									g.Value <> ''
									AND nn.GUID = _Key
									AND LOCATE(g.Value, nn.JpkGTU) > 0
								UNION
								SELECT
									g.Value AS jpkgtu 
								FROM `oppo_e` p 
								INNER JOIN `TowrNg` t ON p.idntowr = t.guid 
								INNER JOIN `v_jpk_gtu` g ON g.Value = t.jpkgtu AND g.Value <> ''
								WHERE
									p.idnoperfin = _Key
								ORDER BY jpkgtu
							) AS t_jpkgtu
							)
						
						),
						n.jpkgtu
					)					
			WHERE
				n.GUID = _Key
				AND od.Rodzaj = n.Rodzaj
			;	
		ELSE
		--	Zamowienia
			UPDATE `zmng_e` n
			SET
				-- n.tag = 2,	--	faza zmpo to nbg
				n.ilepoz = (SELECT COUNT(*) FROM `zmpo_e` p WHERE idnNg = n.GUID AND p.wersja = n.wersja),
				n.IlepozZreal = IFNULL((SELECT SUM(IFNULL(p.zrealizowano >= p.ilosc, 0)) FROM `zmpo_e` p WHERE p.IdnNg = n.GUID AND p.wersja = n.wersja), 0),
				n.waga = IFNULL((SELECT SUM(IFNULL(waga, 0)) FROM `zmpo_e` WHERE idnNg = n.GUID), 0)
			WHERE
				n.GUID = _Key
			;	
			UPDATE `zmng_e` n
			SET
				-- było n.Status = IF(n.ilepoz = n.IlepozZreal, 2, n.Status),
				n.Status =
					IF((@session.globals.Owner = 'COMEX' OR NOT @session.HT.IR.Zmiana_statusu_zm_po_zrealizowaniu_pozycji),
					--	nie zmieniamy statusu !!!
						n.Status,
						-- ?? IF(n.IlepozZreal > 0 AND n.ilepoz <= n.IlepozZreal, 2, n.Status)
						IF(n.ilepoz = n.IlepozZreal, 2, n.Status)
					),
				-- ?? n.zrealizowane = (n.ilepoz = n.IlepozZreal),
                -- ?? n.Update_status = '<SET.Status.po.to.ng>'
				n.zrealizowane = (n.ilepoz = n.IlepozZreal)
			WHERE
				n.GUID = _Key
				AND n.zamwpermn = 0
			;	
		END IF;
	END IF; --  _MODE = '' 
	
	IF _MODE = 'vat.to.?' THEN
	--	?
		SET @X = '';
	END IF; --  _MODE = '' 
	
END$$

DROP PROCEDURE IF EXISTS `_ng_E_LetApply`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_LetApply`(
	IN _MODE VARCHAR(250),	 
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
S_ng_E_LetApply: BEGIN 
	set @jmam_inf = concat_ws('>', null, 'Wej');
	SET @.C_HT_ng_e.Process = 'WEJ';
	IF _handle_FROM = 'OP' THEN
		IF NOT EXISTS (SELECT GUID FROM `opng_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	ELSEIF _handle_FROM = 'ZM' THEN
		IF NOT EXISTS (SELECT GUID FROM `zmng_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	ELSEIF _handle_FROM = 'R' THEN
		IF NOT EXISTS (SELECT GUID FROM `opng_r_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	END IF;
	
	set @jmam_inf = concat_ws('>', @jmam_inf, 'jestem');
	
	
--	Uwaga zmienna @_ng_E_LetPost.DONE okresla czy byl POST czyli _ng_E_LetPost. Gdy  @_ng_E_LetPost.DONE IS NULL to przyjmujemy @_ng_E_LetPost.DONE = FALSE
	IF NOT IFNULL(@_ng_E_LetPost.DONE, FALSE) THEN
		CALL _ng_E_LetPost('', _handle_FROM, _Key, '', '');
	END IF;
	
	SET @.C_HT_ng_e.Process = CONCAT('APPLY po: ', @handle_oper, ': `#ng_e#`');
	SET @.C_HT_ng_e.Process = REPLACE(@.C_HT_ng_e.Process, '#ng_e#', IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e'));
	SET 
		@.C_HT_ng_e.Process.Type = _Key
	;
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Start', 0, '', '');
	END IF;
	BEGIN

			-- IF @session.globals.Owner = 'AMICUS!' THEN
				DECLARE EXIT HANDLER FOR SQLEXCEPTION 
				BEGIN
				/*
					GET DIAGNOSTICS CONDITION 1
						@h.p1 = RETURNED_SQLSTATE, @h.p2 = MESSAGE_TEXT
					;
				*/
					-- @err.RETURNED_SQLSTATE = RETURNED_SQLSTATE, @err.MESSAGE_TEXT = MESSAGE_TEXT
					IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, 
							-- REPLACE(REPLACE('ERROR (#SQLSTATE#): #MESSAGE_TEXT#', '#SQLSTATE#', IFNULL(@err.RETURNED_SQLSTATE, '')), '#MESSAGE_TEXT#', IFNULL(@err.MESSAGE_TEXT, '')), 
							@.C_HT_ng_e.Process.Msg,
							1, '', '');
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, CONCAT('Ostatni etap:', @.C_HT_ng_e.Process.Msg), 0, '', '');
						/* CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, 
							CONCAT('Blad systemu gdy przetwarzano rekord nr: ', @ROW_Curr), 
							1, '', '');
						SET @ROW_Curr = @ROW_Curr - 1;
						*/
					END IF;
				END;
			-- END IF;
	--	sprawdz deltę czy można
	--	delta
				SET @.C_HT_ng_e.Process.Msg = "CALL oper_Delta_Update('', _handle_FROM, _Key, '', '', '');";		

-- JUZ NIE	CALL _ng_e_Numeracja_przed_Apply('Before.Apply', _Key, _handle_FROM, _Param_A, _Param_B);

	SET @session.globals.NEW.oper_delta.2018 := NULL;
	CALL _Globals_Get('NEW.oper_delta.2018', @session.globals.NEW.oper_delta.2018, FALSE);

	IF _handle_FROM IN ('OP','ZM') THEN

		IF @session.globals.NEW.oper_delta.2018  THEN
		--	PO NOWEMU !!!!!!!!!!!!
			IF _handle_FROM IN ('OP') THEN
			--	inicjuj i wpisz z oppo przed
				CALL oper_Delta_Tools('OP.BEFORE.Apply', _Key, '', '', '', '', '');
			ELSE
			--	inicjuj i wpisz z oppo przed
				CALL oper_Delta_Tools('ZM.BEFORE.Apply', _Key, '', '', '', '', '');
			END IF;
		ELSE
			CALL oper_Delta_Update('', _handle_FROM, _Key, '', '', '');		
			CALL oper_Delta_Dostawy_Update('init', _handle_FROM, _Key, '', '', '');
		--	Przygotowanie `t_zmpo_update_status` do upodate zam powiazanych 	
			IF _handle_FROM IN ('OP') THEN
				CALL _zmng_Update_zrealizowane('Apply.E.insert.into.t_zmpo_update_status.BEFORE.Apply', _Key, '', '');
			END IF;
		END IF;
	END IF;

	set @jmam_inf = concat_ws('>', @jmam_inf, '2');

	
	
							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.przed.mumer.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	
	--	jesli tak to ...
	--	numeracja
	set @jmam_inf = concat_ws('>', @jmam_inf, '2.1');
	
	IF _Param_B != '' THEN
		CALL _ng_e_Numeracja_przed_Apply('Do.Apply', _Key, _handle_FROM, _Param_A, _Param_B);
	END IF;
	set @jmam_inf = concat_ws('>', @jmam_inf, '2.2');
	
							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.po.mumer.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	
	
	-- ZAPIS DO LOG
	set @apro = '1';
	set @jmam_inf = concat_ws('>', @jmam_inf, '2.3');
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_SaveToLogBeforeApply('', _Key, _handle_FROM, '');";		
	CALL _ng_E_SaveToLogBeforeApply('', _Key, _handle_FROM, '');
	
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_Tools('delete.real', _Key, _handle_FROM, '');";		
	set @apro = '2';
	set @jmam_inf = concat_ws('>', @jmam_inf, '2.4');

						set @jmam_inf = concat_ws('>', @jmam_inf, '3');
	
	IF @session.globals.Owner = 'AMICUS' THEN
	--	SPECJALNY nietypowy LOG
		DROP TEMPORARY TABLE IF EXISTS `t_zmpo_log_apply`;
		CREATE TEMPORARY TABLE `t_zmpo_log_apply` (
		  `GUID` VARCHAR(38) NOT NULL DEFAULT '',
		  `Write_at` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
		  `IdnNg` VARCHAR(38) NOT NULL DEFAULT '',
		  `Idn` INT(11) DEFAULT '0',
		  `Idn_e` INT(11) DEFAULT '0',
		  `IdnTowr` VARCHAR(38) DEFAULT NULL,
		  `IdnTowr_e` VARCHAR(38) DEFAULT NULL,
		  `Ilosc` DOUBLE(18,6) DEFAULT NULL,
		  `Ilosc_e` DOUBLE(18,6) DEFAULT NULL,
		--   PRIMARY KEY (`GUID`,`Write_at`),
		  PRIMARY KEY PKey (`GUID`),
		--   KEY `GUID` (`GUID`),
		  KEY `IdnNg` (`IdnNg`)
		)
		;
		INSERT INTO `t_zmpo_log_apply`
		(GUID, Write_at, IdnNg, Idn_e, IdnTowr_e, Ilosc_e)
			SELECT
				p.GUID,
				LOCALTIME() AS Write_at,
				p.IdnNg,
				-- p.IDN AS Idn,
				p.IDN AS Idn_e,
				-- p.IdnTowr, 
				p.IdnTowr AS IdnTowr_e,
				-- p.Ilosc, 
				p.Ilosc AS Ilosc_e
			FROM `zmpo_e` p
			WHERE
				p.IdnNg = _Key
		;
		INSERT INTO `t_zmpo_log_apply`
		(GUID, Write_at, IdnNg, Idn, IdnTowr, Ilosc)
			SELECT
				p.GUID,
				LOCALTIME() AS Write_at,
				p.IdnNg,
				-- p.IDN AS Idn,
				p.IDN,
				-- p.IdnTowr, 
				p.IdnTowr,
				-- p.Ilosc, 
				p.Ilosc
			FROM `zmpo` p
			WHERE
				p.IdnNg = _Key
			ON DUPLICATE KEY 
			UPDATE
				`t_zmpo_log_apply`.Idn = p.Idn,
				`t_zmpo_log_apply`.IdnTowr = p.IdnTowr,
				`t_zmpo_log_apply`.Ilosc = p.Ilosc
		;
		SET @LOG.Info = '';
		SELECT
			CONCAT(t.Write_at, '\n',
			GROUP_CONCAT(
				CONCAT(
					IF(t.Idn = 0, 
						'INSERT: ',
						IF(t.Idn != 0 AND t.Idn_e = 0, 
							'DELETE: ',
							'EDIT:   '
						)
					),
					'IDN: ', t.Idn, '/IDN E: ', t.Idn_e, '  ',
					'Ilosc: ', IFNULL(t.Ilosc, 'NULL'), '/Ilosc E: ', IFNULL(t.Ilosc_e, 'NULL'), '  ',
					'IdnTowr: ', IFNULL(t.IdnTowr, 'NULL'), '/IdnTowr E: ', IFNULL(t.IdnTowr_e, 'NULL'), '  '
				)
				SEPARATOR '\n'
			)) AS Info
		INTO
			@LOG.Info
		FROM `t_zmpo_log_apply` t
		;
		IF IFNULL(@LOG.Info, '') != '' THEN
			CALL _log_tools('INSERT', @session.Registration.UserLogin, '4', '3', _Key, '127.0.0.1', @LOG.Info, 'zmng');	
		END IF;
		
	END IF;
	
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Usuwanie real', 0, '', '');	
	END IF;
	
							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.przed.delete.real.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	set @jmam_inf = concat_ws('>', @jmam_inf, 'Before.Apply');
	CALL _ng_E_ON('Before.Apply', _Key, _handle_FROM, '');
	/*================================================================
		USUWANIE real
		delete.real
	================================================================*/
	set @apro = 'delete.real';
	set @jmam_inf = concat_ws('>', @jmam_inf, 'delete.real');
		IF @session.globals.Owner IN ('SIMEX') THEN
			CALL _ng_E_ToolsP('LOG.Add.logtxt', @apro, 'before', _handle_FROM, _Key, '', '', '', @.loginf);	
		END IF;
	CALL _ng_E_Tools('delete.real', _Key, _handle_FROM, '');
		IF @session.globals.Owner IN ('SIMEX') THEN
			CALL _ng_E_ToolsP('LOG.Add.logtxt', @apro, 'after', _handle_FROM, _Key, '', '', '', @.loginf);	
		END IF;
	set @jmam_inf = concat_ws('>', @jmam_inf, ' i po delete.real');
	set @apro = concat(@apro, ' i po delete.real');
	
							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.po.delete.real.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	
	
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_Tools('e.to.real', _Key, _handle_FROM, '');";		
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'zapis z e to real', 0, '', '');	
	END IF;
		
							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.przed.e.to.real.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	
	/*================================================================
		WSTAWIANIE do  real
		e.to.real
	================================================================*/
	set @jmam_inf = concat_ws('>', @jmam_inf, 'e.to.real');
		IF @session.globals.Owner IN ('SIMEX') THEN
			CALL _ng_E_ToolsP('LOG.Add.logtxt', 'e.to.real', 'before', _handle_FROM, _Key, '', '', '', @.loginf);	
		END IF;
	CALL _ng_E_Tools('e.to.real', _Key, _handle_FROM, '');
		IF @session.globals.Owner IN ('SIMEX') THEN
			CALL _ng_E_ToolsP('LOG.Add.logtxt', 'e.to.real', 'after', _handle_FROM, _Key, 'CC.P.R', '', '', @.loginf);	
		END IF;

    IF _handle_FROM = 'ZM' THEN
        IF @session.globals.Owner IN ('PLISZKA') THEN
        --   zmpo instancje
            CALL zmpo_instancjeE_P('E.APPLY', @.eID.EXE, _Key, '', '', '', '', '', '', '');
        END IF; 
    END IF; 

	set @jmam_inf = concat_ws('>', @jmam_inf, 'e.to.real');
	CALL _ng_E_ON('After.Apply', _Key, _handle_FROM, '');						

	
	IF _handle_FROM = 'OP' 
	AND (@session.globals.Owner IN ('PARAQUA', 'IZOHAN'))
	THEN
	--	Dla FV do WZ ustaw nrdokFin w WZ-kach
		SET @.n.IDN = NULL, @.n.Nrdokfin = NULL, @.n.fvrudowz = NULL, @.n.Rodzaj = NULL;
		SELECT
			n.IDN, n.Nrdokfin, n.fvrudowz, n.Rodzaj, ng.Handle_oper, n.info2, n.nrdokmag
		INTO
			@.n.IDN, @.n.Nrdokfin, @.n.fvrudowz, @.n.Rodzaj, @.n.Handle_oper, @.n.info2, @.n.nrdokmag
		FROM `opng` n, `ng_e_rec` ng 
		WHERE 
			n.GUID = _Key
			AND
			ng.GUID = _Key
		;
	set @.malpka = 2;
		-- SELECT @.n.IDN, @.n.Nrdokfin, @.n.fvrudowz, @.n.Rodzaj;
		-- SET @.n.Rodzaj = 0;
	--	Ustaw wszystkim WZ-kom (`opng` n) numerdokfin z biezacego dokumentu (_Key) o ile!! : 
	--	jest numer <> '', jest to nowy dokument FV (idn=0) i WZ-ki maja pusty numer
		UPDATE `opng` n, `oppo` p
		SET
			n.Nrdokfin = @.n.Nrdokfin
		WHERE
			TRUE
			-- AND IFNULL(@.n.Handle_oper, '') = 'INSERT'	-- Jest to nowa ...
			AND IFNULL(@.n.Rodzaj, 0) IN (@ht.CSpBR, @ht.CSpFV, @ht.CSpRU, @ht.CSTUE, @ht.CSpFE)		-- FV ...  0, 1, 80, 50 
			AND IFNULL(@.n.fvrudowz, 0) = 1		-- ... do WZ
			AND IFNULL(@.n.Nrdokfin, '') != ''	-- z numerem <> ''
			AND p.IdnWZ = _Key
			AND n.GUID = p.IdnOper
			AND IFNULL(n.Nrdokfin, '') = ''	-- a same WZki nie maja numery
		;
	--	A teraz w druga strone do info2 wstaw nrdokmag własny lub serię z WZ
	set @.malpka = 3;
		-- IF TRUE OR IFNULL(@.n.info2, '') != '' THEN
		IF IFNULL(@.n.Rodzaj, 0) IN (@ht.CSpBR, @ht.CSpFV, @ht.CSpRU, @ht.CSTUE, @ht.CSpFE)		-- FV ...  0, 1, 80, 50 
		THEN
	set @.malpka = 4;
			SET
				@.n.info2 = 
				IFNULL(
					CONCAT(
					-- 'Nr mag: ', 
					IF(@.n.fvrudowz = 0,
							NULLIF(@.n.nrdokmag, ''),
							(
								SELECT 
									GROUP_CONCAT(DISTINCT nwz.nrdokmag ORDER BY nwz.nrdokmag SEPARATOR ', ') 
								FROM `oppo` pwz, `opng` nwz 
								WHERE 
									pwz.IdnWZ = _Key AND 
									nwz.GUID = pwz.IdnOper
							)
					)
					)
				,''
				)	
			;
			UPDATE `opng` n SET n.info2 = @.n.info2 WHERE n.GUID = _Key;
			UPDATE `opng_e` n SET n.info2 = @.n.info2 WHERE n.GUID = _Key;
		END IF;
	END IF;	
	
	

							IF _handle_FROM IN ('R') THEN
							--	testy dla Transbudu - problemy z kasa zad = 44541  - potem usunac ten kod
								SET @_Kasa_Bank = CONCAT(
									'Apply.po.e.to.real.  ', 
									IFNULL((SELECT CONCAT('r_nrkasy = ', r_nrkasy, ', i_Magazyn1_Kasa = ', i_Magazyn1_Kasa) FROM `ng_e_rec` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng_r_e.nrkasy = ', nrkasy) FROM `opng_r_e` WHERE GUID = _Key), ''),
									IFNULL((SELECT CONCAT(', opng.nrkasy = ', nrkasy) FROM `opng` WHERE GUID = _Key), '')
								);
								CALL log_Insert('INSERT', @Idn, '', 6, 2, _Key, @session.Registration.IP, @_Kasa_Bank, 'opng_r_e');
							END IF;
	
	
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Po zapisie', 0, '', '');	
	END IF;

	
	IF _handle_FROM IN ('OP', 'ZM') THEN

					SET @.C_HT_ng_e.Process.Msg = 'CALL oper_Delta_Dostawy_Update...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;

		IF @session.globals.NEW.oper_delta.2018 THEN
		--	PO NOWEMU !!!!!!!!!!!!
			IF _handle_FROM IN ('OP') THEN
			--	Update po
				CALL oper_Delta_Tools('OP.After.Apply', _Key, '', '', '', '', '');
			ELSE
			--	Update po
				CALL oper_Delta_Tools('ZM.After.Apply', _Key, '', '', '', '', '');
			END IF;
		ELSE
					
			CALL oper_Delta_Dostawy_Update('update', _handle_FROM, _Key, '', '', '');

			IF _handle_FROM IN ('OP') THEN
			--	Po apply uzupelnienie `t_zmpo_update_status` do upodate zam powiazanych 	
				CALL _zmng_Update_zrealizowane('Apply.E.insert.into.t_zmpo_update_status.AFTER.Apply', _Key, '', '');
			END IF;
		END IF;
	END IF;

	
	IF _handle_FROM IN ('ZM') THEN

					SET @.C_HT_ng_e.Process.Msg = 'CALL oper_Delta_Oferty_Update...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
SET  @.JMAM.o.co.chodzi = 'czy jestem 1';
		CALL oper_Delta_Oferty_Update('update', _handle_FROM, _Key, '', '', '');
SET  @.JMAM.o.co.chodzi = 'czy jestem 2';
		CALL _zmng_Update_zrealizowane('?', _Key, '1', '');
SET  @.JMAM.o.co.chodzi = concat('czy jestem 3 ', _Key);
	END IF;

	
	IF _handle_FROM IN ('OP') THEN
		IF @i_MODE = 'Realizacja.ZM.Edit' AND IFNULL(@i_Input_GUID, '') != '' THEN
					SET @.C_HT_ng_e.Process.Msg = 'CALL _zmng_Update_zrealizowane...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
	
			CALL _zmng_Update_zrealizowane('', @i_Input_GUID, '1', '');
		END IF;
		
	END IF;

SET  @.Grzesiu.o.co.chodzi = concat(@.Grzesiu.o.co.chodzi, ' PO');
	
						SET @.C_HT_ng_e.Process.Msg = "Koniec";		
	-- Znies flage `Need_Update` w `ng_e_rec`
	SET @_ng_E_LetPost.DONE = TRUE;
	UPDATE `ng_e_rec` r
	SET
		r.Need_Update = 0
	WHERE
		r.GUID = _Key
	;
	
	IF _handle_FROM != 'ZM' THEN
					SET @.C_HT_ng_e.Process.Msg = 'CALL oppo_mag...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
		-- koszt sprzedazy dla axisa 			
		IF @session.globals.Owner = 'AXIS' THEN
			UPDATE oppo o,rcpo r, TowrNg t 
			SET o.koszt_sprzedazy=_rnd2(IFNULL(r.cena_kalulacyjna,t.cenazkpnet)) * o.Ilosc
			WHERE r.idntowr=o.idntowr AND r.przychod=1 AND r.priorytet='-1' AND t.guid=o.idntowr
			AND t.wyroznik<>'U' AND o.rodzaj IN (0,1,2,80,50,10)  AND o.idnoperfin=_Key;	
		END IF;
	
		--	oppo_mag
		CALL oppo_mag('UPDATE_OPNG_REC', _Key);
		--	rozlicz
		CALL ht_rozrach_rozlicz('ROZLICZ.CALC.OPNG', _Key, '', '', '', '');
		CALL ht_rozrach_rozlicz('ROZLICZ.CALC.OPNG.RELATED', _Key, '', '', '', '');

	END IF;

	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'End', 0, '', '');
	END IF;
	END;
	
END$$

DROP PROCEDURE IF EXISTS `_ng_E_LetCancel`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_LetCancel`(
	IN _MODE VARCHAR(250),
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(255),	
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
BEGIN 
	CALL _ng_E_LetEnd('', _handle_FROM, _Key, _Param_A, _Param_B);
END$$

DROP PROCEDURE IF EXISTS `_ng_E_LetEnd`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_LetEnd`(
	IN _MODE VARCHAR(250),
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(255),	
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
S_ng_E_LetEnd: BEGIN 
--	pobierz @_ng_e_rec_init.handle_UserGUID z `ng_e_rec` aby zdjąć Locka
--	wstepna flaga robocza!!!
	SET @.CLEAR.E.WORLD = TRUE;	--	wstepna flaga robocza!!!
					set @X.L = '_ng_E_LetEnd';	
	DO _counters_tools('SET', '_ng_E_LetEnd', '', '');		-- to tylko Licznik!!!!
	IF @session.LOCK.Ver >= '2021' THEN
	/******************************************************************************************************************
		Uwaga
		Jeśli sa wdrozone nowe locki i gdy lock na tym rekordzie
		należy do innej - żywej - sesji (NIE koniecznie do innego usera !!!)
		to zabraniamy usuwania takiego rekordu ze świata E
		Jeśli w locku sesja jest martwa to możemy usuwać
		Czyli usuwamy gdy 
		-	nie ma blokady	- @.LCK.OTHER_LOCK = 0
		-	jest blokada mojej sesji 	- @.LCK.OTHER_LOCK = 0
		-	jest blokada nie mojej sesji i ta sesja juz umarła	- @.LCK.OTHER_LOCK = 1	@.LCK.Current.Session.IS_INACTIVE = 1
		
		w SQL-zmianach poszło
			INSERT IGNORE INTO `_db_globals` SET `key` = 'LOCK.Ver', `Value` = 0, descr = 'wersja blokad - domyslnie 0 gdy nowsze z 2021 to 2021.0 2021.1 2022.0 itd ', VariableName = '@session.LOCK.Ver';

	******************************************************************************************************************/
		DO _lck('CHECK', '', _Key, 'EDIT', IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e'), '', '', '', '') ;
	--	sesja jest - spr. czy martwa?
					set @X.L = concat_WS('/', @X.L, @.LCK.EXISTS, @.LCK.Current.Session, @.LCK.Current.Session.IS_INACTIVE, @.LCK.Current.Session.Msg, @.LCK.OTHER_LOCK, @.CLEAR.E.WORLD);
		SET @.CLEAR.E.WORLD = 
		--	gdy nie ma innej blokady lub gdy nawet jest to jej sesja już umarła
			NOT @.LCK.OTHER_LOCK OR @.LCK.Current.Session.IS_INACTIVE
		;
					set @X.L = concat_WS('/', @X.L, @.CLEAR.E.WORLD);
	END IF;
	
	IF @.CLEAR.E.WORLD THEN
	--	CZYSCIMY!!!!!!!!!!!!
					set @X = '1';
		SET @_ng_e_rec_init.handle_UserGUID = NULL;
					set @X = '2';
		SELECT handle_UserGUID INTO @_ng_e_rec_init.handle_UserGUID FROM `ng_e_rec` WHERE GUID = _Key;	-- UWAGA moze byc ze rekord nie istnieje (row aff. = 0) wtedy pozostanie NULL - patrz nizej
		CALL _ng_E_Tools('delete.e', _Key, _handle_FROM, 'LetEnd');
        
        IF _handle_FROM = 'ZM' THEN
            IF @session.globals.Owner IN ('PLISZKA') THEN
            --   zmpo instancje
                CALL zmpo_instancjeE_P('E.CLEAR', @.eID.EXE, _Key, '', '', '', '', '', '', '');
            END IF; 
        END IF; 
        
	END IF;
	
	IF @session.LOCK.Ver >= '2021' THEN
	--	nowe blokady
					set @X = concat_WS('/', @X, 'UNLOCK');
		CALL _ng_E_Tools('UNLOCK', _Key, _handle_FROM, @_Param_A);
	END IF;
	
	IF @session.LOCK.Ver = '0' THEN
	--	stare blokady 
						set @X = concat_WS('/', @X, '3');
	--	teraz - na koniec - trzeba zdjąć Locka - ALE ZA NIM to zrobie spr czy masz @_ng_e_rec_init.handle_UserGUID ?
		IF (@_ng_e_rec_init.handle_UserGUID IS NULL) THEN
						set @X = concat_WS('/', @X, '4');
		--	UWAGA!!! @_ng_e_rec_init.handle_UserGUID jest null bo rekordy w swiecie E nie istnialy Pobiez zatem usera z innych zmiennych
			IF IFNULL(@SYSTEM.Client.Session.log_USER_GUID, '') != '' THEN
						set @X = concat_WS('/', @X, '5.1');
				SET @_ng_e_rec_init.handle_UserGUID = @SYSTEM.Client.Session.log_USER_GUID;
			ELSE
						set @X = concat_WS('/', @X, '5.2');
				SET @_ng_e_rec_init.handle_UserGUID = IFNULL(@session.Registration.UserGUID, '');
			END IF;
		
		END IF;
		
		IF IFNULL(@_ng_e_rec_init.handle_UserGUID, '') != '' THEN 
						set @X = concat_WS('/', @X, '6');
			CALL _lock_inf_tool('UNLOCK', _Key, IF(_handle_FROM != 'ZM', 'opng', 'zmng'), @_ng_e_rec_init.handle_UserGUID, @_ng_e_rec_init._Rec_Is_Locked, @_ng_e_rec_init.Msg, '', '1');
		END IF;
						set @X = concat_WS('/', @X, 'End');
	END IF;

END$$

	
DROP PROCEDURE IF EXISTS `_ng_e_Numeracja_przed_Apply`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_Numeracja_przed_Apply`(
	IN _MODE VARCHAR(150),
	IN _Key VARCHAR(255),	
	IN _handle_FROM VARCHAR(255),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
S_ng_e_Numeracja_przed_Apply: BEGIN 
	DECLARE _Is_Obj_Counters BOOLEAN;
	
	SET _Is_Obj_Counters = @session.globals.HT.erp_obj_counters_values_e_1_rec;
	
	/*
	IF _MODE = 'Before.Apply' THEN
	*/
		/* *************************************************************************************************************************************************************
			Przed zapisem
			CALL _ng_e_Numeracja_przed_Apply('Before.Apply', _Key, _handle_FROM, _Param_A, _Param_B);
		**************************************************************************************************************************************************************/
	/*
		IF @session.globals.HT.erp_obj_counters_values_e_1_rec THEN
			-- xxxxxxxxxxxxxxxxx
			CALL erp_obj_counters_values_e_1_rec_tools('APPLY.from.e', _handle_FROM, _Key, '', '', '', '');
		END IF;
	END IF;
	*/
	
	IF _MODE = 'Do.Apply' THEN
SET @_Is_Obj_Counters_X = _Mode;
		/* *************************************************************************************************************************************************************
			Zapis 
			CALL _ng_e_Numeracja_przed_Apply('Do.Apply', _Key, _handle_FROM, _Param_A, _Param_B);
		**************************************************************************************************************************************************************/
	
		IF _Is_Obj_Counters THEN
set @Transbud = '1.1';
			-- xxxxxxxxxxxxxxxxx
			SELECT Is_Obj_Counters INTO _Is_Obj_Counters FROM `erp_obj_counters_values_e_1_rec` WHERE ID = _Key;
			SET @_Is_Obj_Counters_X = concat(_Mode, ', ', _Is_Obj_Counters);
		END IF;
		
		IF _Is_Obj_Counters THEN
set @Transbud = '1.2';
SET @_Is_Obj_Counters_X = 'HAHA';
			CALL erp_obj_counters_values_e_1_rec_tools('Set.auto.number', _handle_FROM, _Key, '', '', '', '');
		
		ELSE
set @Transbud = '2';
			IF _handle_FROM = 'OP' THEN
			
			-- IF _handle_FROM IN ('OP','ZM') THEN
				-- CALL erp_obj_counters_values_SetNumber('ponumeruj.mnie', @_Numer, @_NumerText, 'opng', '-1', '0', _Key, 'opng_e', 'opng.nrdokfin', '');
				-- CALL erp_obj_counters_values_SetNumber('ponumeruj.mnie', @_Numer, @_NumerText, 'opng', '-1', '0', '{C249ED5B-2E97-43BB-BA31-0855B55AC302}', 'opng_e', 'opng.nrdokfin', '');
                    set @Transbud = '2.a1';
				CALL opng_e_Numeracja_po_Apply('', _Key, '', '', '');
                    set @Transbud = '2.a2';
			ELSEIF _handle_FROM = 'ZM' THEN
				CALL zmng_e_Numeracja_po_Apply('', _Key, '', '', '');
			ELSEIF _handle_FROM = 'R' THEN
				CALL opng_r_e_Numeracja_po_Apply('', _Key, '', '', '');
			END IF;
			/*
			to nie ma sensu bo jesli @session.globals.HT.erp_obj_counters_values_e_1_rec True to nie ma nas w tym elsie !!
			IF @session.globals.HT.erp_obj_counters_values_e_1_rec THEN
				-- xxxxxxxxxxxxxxxxx
				CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', _handle_FROM, _Key, '', '', '', '');
			END IF;
			*/
		END IF;
	END IF;
	
	
END$$


/* ************************************************************************************************************************************************************************
	Narzędzia 
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `_ng_E_SaveToLogBeforeApply`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_SaveToLogBeforeApply`(
	IN _MODE VARCHAR(150),
	IN _Key VARCHAR(255),	
	IN _handle_FROM VARCHAR(255),
	IN _Param_A VARCHAR(255)
)
/*
	CALL _ng_E_SaveToLogBeforeApply('', _Key, _handle_FROM, '');
*/
S_ng_E_SaveToLogBeforeApply: BEGIN 
	CALL _ng_e_rec_do('select.into', _Key, '', '');
	SET @Miejsce = 
		CASE @OpTyp
			WHEN @ht.ZM THEN 4
			WHEN @ht.RO THEN 5
			WHEN @ht.KS THEN 6
			WHEN @ht.BN THEN 7
			ELSE 3
		END
	;
	
	SET @.Info = IF(@handle_oper = 'INSERT', 'wstawianie z `#ng_e#`', IF(@handle_oper = 'DELETE', 'usuwanie  w `#ng_e#`', 'edycja w `#ng_e#`'));
	SET @.Info = REPLACE(@.Info, '#ng_e#', IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e'));
	
	IF @handle_oper != 'DELETE' THEN
		CALL log_Insert_from_ng_e(
			'INSERT', @_IDN,
			IF(IFNULL(@i.handle_UserLogin, '') = '', @session.Registration.UserLogin, @i.handle_UserLogin),
			@Miejsce,
			IF(@handle_oper = 'INSERT', 2, 3), 
			_Key, 
			IFNULL(@session.INFO.INSERT.LOG.ip, @session.Registration.IP), 
			@.Info, 
			IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e'),
			IF(_handle_FROM != 'ZM', 'opng', 'zmng'),
			'GUID', 
			''
		);		
	ELSE
		CALL log_Insert('INSERT', @Idn, 
			'', 
			@Miejsce,
			IF(@handle_oper = 'INSERT', 2, IF(@handle_oper = 'DELETE', 4, 3)), 
			_Key, 
			IFNULL(@session.INFO.INSERT.LOG.ip, @session.Registration.IP), 
			@.Info, 
			IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e')
		);
	END IF;
	SET @.C_HT_ng_e.Process = @.Info;
END$$


DROP PROCEDURE IF EXISTS `_ng_DoChangeStatusOnServer`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_DoChangeStatusOnServer`(
	IN _MODE VARCHAR(150),
	IN _Key VARCHAR(255),	
	IN _Status INTEGER,
	IN _handle_FROM VARCHAR(255),
	IN _Param_A VARCHAR(255)
)
/*
	CALL _ng_DoChangeStatusOnServer('', IdnOper, 1, 'op', '')
*/
S_ng_DoChangeStatusOnServer: BEGIN 
	IF _handle_FROM IN ('', 'op') THEN
		UPDATE `opng` n SET n.status = _Status WHERE n.GUID = _Key;
		UPDATE `opng_e` n SET n.status = _Status WHERE n.GUID = _Key;
	ELSE
		UPDATE `zmng` n 
        SET 
            n.status = _Status,
            n.Update_status = '<SET.Status.OnServer>'
        WHERE 
            n.GUID = _Key
        ;
		UPDATE `zmng_e` n 
        SET 
            n.status = _Status,
            n.Update_status = '<SET.Status.OnServer>'
        WHERE 
            n.GUID = _Key
        ;
	END IF;
END$$
-- set @session.globals.Owner='IZOHAN';
-- call _ng_E_ON('Before.Apply','{4978D77C-69C9-4B3E-8833-F5C9E1B99AA7}','ZM','');
-- set @session.globals.Owner='AXIS';
-- call _ng_E_ON('After.Apply','{CD5C79EF-D408-471F-8FAA-08EEAF3DEAD5}','OP','');

DROP PROCEDURE IF EXISTS `_ng_E_ON`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_ON`(
	IN _MODE VARCHAR(150),
	IN _Key VARCHAR(255),	
	IN _handle_FROM VARCHAR(255),
	IN _Param_A VARCHAR(255)
)
S_ng_E_ON: BEGIN 
	IF NOT(@session.globals.Owner IN ('PARAQUA', 'IZOHAN', 'AXIS')) THEN
	    LEAVE S_ng_E_ON;
	END IF;
	IF _MODE = 'Before.Apply' THEN
		IF _handle_FROM = 'OP' THEN
		SET @aaaaaaaaaaaaaaaaaa='a';
			UPDATE opng_e n, oppo_e p, TowrNg t 
			SET n.ugrpguid='IZOLEX'
			WHERE @session.globals.Owner='IZOHAN' AND (n.guid=p.idnoper OR n.guid=p.idnwz) AND p.idntowr=t.guid AND 
			  t.treenode like '*|IZOLEX%' AND (n.rozrachunek OR n.rodzaj in (1,2,3,4,50,80,10));

			UPDATE opng_e n
			SET
--				n.ubezpieczyciel=IF(n.ugrpGUID = 'IZOLEX',2,1),
				-- n.ubezpieczyciel=2,
				n.sposobplatn=IFNULL(
				  (SELECT s.sposplat FROM oppo_e p,TowrNg t,sposobyplatn_kontrah s
				   WHERE p.idnoperfin=n.guid AND s.kontrguid=n.platnikguid AND t.guid=p.idntowr AND t.treenode LIKE concat(s.treenode,'%')
				  ORDER BY s.priorytet LIMIT 1
				  ),n.sposobplatn)
			WHERE
				n.GUID = _Key
			;/**/
			
		END IF;
		
		IF _handle_FROM = 'ZM' THEN
--			SET @aaaaaaaaaaaaaaaaaa='a';
			UPDATE zmng_e n, zmpo_e p, TowrNg t 
			SET n.ugrpguid='IZOLEX'
			WHERE @session.globals.Owner='IZOHAN' AND n.guid=p.idnng AND p.idntowr=t.guid AND t.treenode like '*|IZOLEX%' and n.rodzaj<>73;
			
			UPDATE zmng_e n
			SET
--				n.ubezpieczyciel=IF(n.ugrpGUID = 'IZOLEX',2,1), 2- atriadus, 1 - hermes
				-- n.ubezpieczyciel=2,
				n.sposobplatn=IFNULL(
				  (SELECT s.sposplat FROM zmpo_e p,TowrNg t,sposobyplatn_kontrah s
				   WHERE p.idnng=n.guid AND s.kontrguid=n.platnikguid AND t.guid=p.idntowr AND t.treenode LIKE concat(s.treenode,'%')
				  ORDER BY s.priorytet LIMIT 1
				  ),n.sposobplatn)
			WHERE
				n.GUID = _Key and n.rodzaj<>73
			;/**/
			
		END IF;
	END IF;

	IF _MODE = 'After.Apply' THEN
		IF _handle_FROM = 'OP' THEN
		-- korekta zaokraglen dla dok ST walutowych - suma netto nagłówka koryguje pozycję o najwyższej wartości 
		-- korekta zaokraglen dal ZT w kluczu 2
			SELECT n.netto,n.nettowal,n.kurs,/*d.iskorekta=0 and */
			IF(IFNULL((SELECT ValueB FROM IReg WHERE IdKey LIKE 'rozrzucenie_odchylen_wal_opng_oppo'),0)=2,d.grupa IN (0,1),d.grupa=0 )AS issprzedaz,
			(SELECT sum(wartnet) FROM oppo o WHERE n.guid=o.idnoperfin) as wartnet
			INTO @a.a.netto,@a.a.nettowal,@a.a.kurs,@a.a.issprzedaz,@a.a.wartnet
			FROM opng n,operdoc d WHERE d.rodzaj=n.rodzaj AND n.guid=_Key 
			;
			SET @a.a.diff=_Rnd2(@a.a.netto-@a.a.wartnet);
			IF @a.a.issprzedaz AND @a.a.kurs<>1 AND abs(@a.a.diff)>0 THEN
			      SELECT idn,wartnet,wartbrt
			      INTO @a.a.idn,@a.a.wartnetj,@a.a.wartbrtj
			      FROM oppo WHERE idnoperfin=_Key ORDER BY abs(wartnet) DESC LIMIT 1
			      ;
			      UPDATE oppo SET wartnet=_Rnd2(@a.a.wartnetj+@a.a.diff),wartbrt=_Rnd2(@a.a.wartbrtj+@a.a.diff) 
			      WHERE idn=@a.a.idn;
			END IF;
		END IF;
	END IF;
	
	IF _MODE = 'Before.e.to.real' THEN
		SET _MODE = '';
	END IF;
	
	IF _MODE = 'Before.Post' THEN
		SET _MODE = '';
	END IF;
	
	IF _MODE = 'After.Post' THEN
		SET _MODE = '';
	END IF;

	IF _MODE = 'PO.After.Post' THEN
	--	pozycja After Post
		SET _MODE = '';
	END IF;

	LEAVE S_ng_E_ON;
END$$

DROP PROCEDURE IF EXISTS `_ng_E_Tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_Tools`(
	IN _MODE VARCHAR(150),
	IN _Key VARCHAR(255),	
	IN _handle_FROM VARCHAR(255),
	IN _Param_A VARCHAR(255)
)
S_ng_E_Tools: BEGIN 
	DECLARE _SQLText TEXT;
	
	IF @session.globals.NEW.CALC.VAT.VI.2017 IS NULL THEN
		CALL _Globals_Get('NEW.CALC.VAT.VI.2017', @session.globals.NEW.CALC.VAT.VI.2017, FALSE);
	END IF;
	
	IF _MODE = 'LOCK' THEN
	set @.X1 = 'jestem';
		DO _counters_tools('SET', 'LOCK.Ver.2021', '', '');		-- to tylko Licznik!!!!
		/*	Nie bedziemy tego wdrażali
		SET @.xxng.Lock.Rec.Params = 
			IF(@session.globals.Owner IN ('COMEX'),
				'<MSG><ReadOnly>',
				'<MSG>'
			)
		;
		CALL _lcks('LOCK', @.xxng.Lock.Rec, '', _Key, 'EDIT', IF(_handle_FROM = 'ZM', 'zmng_e', 'opng_e'), 3600*8, '', 0, @.xxng.Lock.Rec.Params);
		*/
		CALL _lcks('LOCK', @.xxng.Lock.Rec, '', _Key, 'EDIT', IF(_handle_FROM = 'ZM', 'zmng_e', 'opng_e'), 3600*8, '', 0, '<MSG>');
		IF NOT @.xxng.Lock.Rec THEN
			/*	Nie bedziemy tego wdrażali
		--	gdy zablokowany !!!
		--	Czy tylko jako readonly (1) czy blokada całkowita 
						--	SET @.xxng.Lock.Rec.ReadOnly = @session.globals.Owner IN ('COMEX');
			CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
				CONCAT(
					@.LCK.Result.Msg
				),
				@.LCK.Result.Msg.MsgDlg,	--	do komunikatów 'Warning'/'Error'
				@.LCK.Result.Msg.Effect,	-- 'ReadOnly'/NULL, NULL ozn.'Stop'
				'', ''
			)
			;
			*/
			CALL _ng_e_rec_msg_ins('', '', _Key, 'handle.init', 
				CONCAT(
					@.LCK.Result.Msg
				),
				'Error', 'Stop', '', '')
			;
		ELSE
		--	jest OK nie zablokowany ALE !!! może byc to sesja przejeta przez tego samego uzytkownika
			IF IFNULL(@.Prev.LockSession, @SYSTEM.Client.Session.GUID) != @SYSTEM.Client.Session.GUID THEN
			/******************************************************************************************
				Przy przechwyceniu sesji w lck 
				wyslij wiadomośc do sesji @.Prev.LockSession że ten rekord przejęła inna sesja
			******************************************************************************************/
				INSERT IGNORE INTO `_sys_msg` 
				-- (Src, Dest, DestCtx, DestCtxID, Msg, SendAt, con_ID)
				SET 
					Src = @SYSTEM.Client.Session.GUID, 
					Dest = @.Prev.LockSession, 
					DestCtx = IF(_handle_FROM = 'ZM', 'EDIT.zmng_e', 'EDIT.opng_e'),
					DestCtxID = _Key, 
					Msg = (@.MSG := 'Rekord który edytujesz jest już edytowany w innej sesji (np. na innym urządzeniu).\nOkno edycji zostanie zamknięte!'), 
					SendAt = NOW(), con_ID = CONNECTION_ID(),
					MsgDlg = 'Error',
					MsgEffect = 'CLOSE'
				ON DUPLICATE KEY UPDATE Msg = @.MSG.1, SendAt = NOW(), con_ID = CONNECTION_ID(), SendStatusInf = CONCAT_WS('->', SendStatusInf, IF(SendStatus = 'SEND', NULL, 'SEND')), SendStatus = 'SEND'
				;
			END IF;
		END IF;
	END IF;
	
	IF _MODE = 'UNLOCK' THEN
		CALL _lcks('FREE', @.xxng.Lock.Rec, '', _Key, 'EDIT', IF(_handle_FROM = 'ZM', 'zmng_e', 'opng_e'), '', '', '', '');
	END IF;
	
	IF _MODE = 'CHECK.E.Exists' THEN
		SELECT 
			EXISTS(SELECT nr.GUID FROM `ng_e_rec` nr WHERE nr.GUID = _Key) AS ng_e_rec_Exists,
			IF(_handle_FROM = 'ZM',
				EXISTS(SELECT n.GUID FROM `zmng_e` n WHERE n.GUID = _Key),
				EXISTS(SELECT n.GUID FROM `opng_e` n WHERE n.GUID = _Key)
			) AS xxng_e_rec_Exists
		INTO 
			@.ng_e_rec_Exists, @.xxng_e_rec_Exists
		;
		-- SET @.CHECK.E.Exists.ERR = (!@.ng_e_rec_Exists OR !@.xxng_e_rec_Exists);
		SELECT
			(@.CHECK.E.Exists.ERR := (!@.ng_e_rec_Exists OR !@.xxng_e_rec_Exists))AS C_Err,
			IF(@.CHECK.E.Exists.ERR, 'ERR', 'OK') AS C_Status,
			IF(@.CHECK.E.Exists.ERR, 'Nieoczekiwana awaria - operacja którą edytujesz nie jest już dostępna do edycji - została prawdopodobnie zamknięta z innego komputera.\nAby edytować tę oparację, ponownie wejdź w jej edycję.', '') AS C_Msg
		;

		-- CALL _lcks('Is.FREE.or.MINE', @LR, @.Session.Obca, 'X1', 'EDIT', 'opng_e', '', '', '', '<MSG>');
		
	END IF;
	
	IF _MODE = 'E.MSG.CHECK' THEN
		SELECT 
			EXISTS(SELECT nr.GUID FROM `ng_e_rec` nr WHERE nr.GUID = _Key) AS ng_e_rec_Exists,
			IF(_handle_FROM = 'ZM',
				EXISTS(SELECT n.GUID FROM `zmng_e` n WHERE n.GUID = _Key),
				EXISTS(SELECT n.GUID FROM `opng_e` n WHERE n.GUID = _Key)
			) AS xxng_e_rec_Exists
		INTO 
			@.ng_e_rec_Exists, @.xxng_e_rec_Exists
		;
		-- SET @.CHECK.E.Exists.ERR = (!@.ng_e_rec_Exists OR !@.xxng_e_rec_Exists);
		SELECT
			(@.CHECK.E.Exists.ERR := (!@.ng_e_rec_Exists OR !@.xxng_e_rec_Exists))AS C_Err,
			IF(@.CHECK.E.Exists.ERR, 'ERR', 'OK') AS C_Status,
			IF(@.CHECK.E.Exists.ERR, 'Nieoczekiwana awaria - operacja którą edytujesz nie jest już dostępna do edycji - została prawdopodobnie zamknięta z innego komputera.\nAby edytować tę oparację, ponownie wejdź w jej edycję.', '') AS C_Msg
		;

	END IF;
	IF _MODE = 'E.MSG.CHECK' THEN
		select * from `_sys_msg`;
	END IF;
	IF _handle_FROM IN ('', 'op') THEN
	--	OPERACJE
		IF _MODE = 'IS_need_Apply' THEN
			SET 
				@IS_need_Apply = 
				EXISTS(
				SELECT GUID FROM `opng_e` ne  WHERE ne.GUID = _Key
				)
			;
			IF @IS_need_Apply THEN
				SELECT
					(IFNULL(n.LocalTime, '0000-00-00 00:00:00') < IFNULL(ne.LocalTime, '0000-00-00 00:00:00')) AS IS_need_Apply
				FROM `opng_e` ne 
				LEFT JOIN `opng` n ON n.GUID = ne.GUID
				WHERE
					ne.GUID = _Key
				;
			ELSE
				SELECT @IS_need_Apply AS IS_need_Apply;
			END IF;
		END IF; 
		
		IF _MODE = 'delete.e' THEN
			CALL _ng_e_rec_do('select.into', _Key, '', '');
			SET @n.IsNewDoc = ((@n.Idn := IFNULL((SELECT ne.IDN FROM `opng_e` ne WHERE ne.GUID = _Key), 0)) = 0);
			-- SELECT @n.IsNewDoc, @n.Idn;
			IF @n.IsNewDoc THEN
			--	dla nowego usuwaj 
				DELETE FROM `opng_e` WHERE GUID = _Key;
				DELETE FROM `opng_vat_e` WHERE IdnOper = _Key;
				
				CALL erp_obj_counters_values_e_1_rec_tools('DELETE.from.e', _handle_FROM, _Key, '', '', '', '');
				IF NOT @i_fvrudowz THEN
				--	byla normalna edycja - usun zwyczajnie
					DELETE FROM `oppo_e` WHERE IdnOper = _Key;
					/* Nie ma juz `oppo_instancje`
					DELETE FROM `oppo_instancje_e` WHERE IdnOper = _Key;
					*/
					DELETE FROM `oppo_corr_e` WHERE IdnOper_corr = _Key;
				ELSE
				--	byla edycja podlaczonych WZ/PZ - usun laczac z oppo_e i pole IdnOper_e
					DELETE pe FROM `oppo_e` pe  WHERE pe.IdnOper_e = _Key AND IFNULL(pe.IdnOper_e, '') != '';
				END IF;
			ELSE
			--	ale dla edytowanego - usuwaj tyloko gdy jest rekord w Real
				DELETE ne FROM `opng_e` ne, `opng` n WHERE n.GUID = _Key AND ne.GUID = n.GUID;
				DELETE ve FROM `opng_vat_e` ve, `opng` n WHERE n.GUID = _Key AND ve.IdnOper = n.GUID;

				CALL erp_obj_counters_values_e_1_rec_tools('DELETE.from.e', _handle_FROM, _Key, '', '', '', '');
				IF NOT @i_fvrudowz THEN
				--	byla normalna edycja - usun zwyczajnie
					DELETE pe FROM `oppo_e` pe, `opng` n WHERE n.GUID = _Key AND pe.IdnOper = n.GUID;
					/* Nie ma juz `oppo_instancje`
					DELETE FROM `oppo_instancje_e` WHERE IdnOper = _Key;
					*/
					DELETE pe FROM `oppo_corr_e` pe, `opng` n WHERE n.GUID = _Key AND pe.IdnOper_corr = n.GUID;
				ELSE
				--	byla edycja podlaczonych WZ/PZ - usun laczac z oppo_e i pole IdnOper_e
					-- DELETE pe FROM `oppo_e` pe  WHERE pe.IdnOper_e = _Key AND IFNULL(pe.IdnOper_e, '') != '';
					DELETE pe FROM `oppo_e` pe, `opng` n WHERE n.GUID = _Key AND pe.IdnOper_e = n.GUID AND IFNULL(pe.IdnOper_e, '') != '';
				END IF;
				
			END IF;
			
			IF _Param_A = 'LetEnd' THEN	-- Wolane w _ng_E_LetEnd
		set @X = concat_WS('/', @X, 'DELETE FROM `ng_e_rec`');
				DELETE FROM `ng_e_rec` WHERE GUID = _Key;
		set @X = concat_WS('/', @X, 'CALL _ng_e_rec_msg_clear');
				CALL _ng_e_rec_msg_clear('ALL', _Key, '', '');
			END IF;
		END IF; 
		
		IF _MODE = 'delete.real' THEN
			CALL _ng_e_rec_do('select.into', _Key, '', '');
			DELETE n FROM `opng` n, `opng_e` ne WHERE ne.GUID = _Key AND n.GUID = ne.GUID;
			DELETE v FROM `opng_vat` v, `opng_e` ne WHERE ne.GUID = _Key AND v.IdnOper = ne.GUID;
			-- bylo DELETE FROM `oppo` WHERE IdnOper = _Key;
			DELETE p FROM `oppo` p, `opng_e` ne WHERE ne.GUID = _Key AND p.IdnOper = ne.GUID;
			IF NOT @i_fvrudowz THEN
			--	byla normalna edycja - usun zwyczajnie
			--		dla poczepianych WZ/PZ nie usuwamy bo będzie update
				/* Nie ma juz `oppo_instancje`
				DELETE FROM `oppo_instancje` WHERE IdnOper = _Key;
				*/
				-- bylo DELETE FROM `oppo_corr` WHERE IdnOper_corr = _Key;
				DELETE p FROM `oppo_corr` p, `opng_e` ne WHERE ne.GUID = _Key AND p.IdnOper_corr = ne.GUID;
			END IF;
		END IF; 

		IF _MODE = 'refresh.real.to.e' THEN
		--	Gdy zrobilem Apply i rozliczylem w swiecie r ale nie wyszedlem z e to musze zaladowac calosc pol do e
			DELETE FROM `opng_e` WHERE GUID = _Key;
			INSERT INTO `opng_e` SELECT * FROM `opng` WHERE GUID = _Key;
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 
		
		IF _MODE = 'real.to.e' THEN
set @delkor = '1';		
					-- CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e.1', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			INSERT INTO `opng_e` SELECT * FROM `opng` WHERE GUID = _Key;
					-- CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e.2', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			IF 
                @session.globals.CALC.VAT.Ver >= '2021' 
                OR (_Key LIKE 'KSEF_%')
            THEN
			/********************************************************
				Nowe od 2021 r. 
			********************************************************/
					DO _counters_tools('SET', 'CALC.VAT.Ver.2021', '', '');		-- to tylko Licznik!!!!
					-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> R.vat->clear->E.vat', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			--	Uwaga zawiera juz w sobie dodawanie stawek do edycji i fixed dla bezpozycyjnych
				CALL C_HT_xxNgPo_DO('R.vat->clear->E.vat', _handle_FROM, '', _Key, '', '', '', '', '', @P);
					-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> R.vat->clear->E.vat OK', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			ELSE
			/********************************************************
				Przed 2021 r.   2017, 1999
			********************************************************/
				INSERT INTO `opng_vat_e` SELECT * FROM `opng_vat` WHERE IdnOper = _Key;
			--	...	przywroc wszystkie brakujace stawki
				IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
					CALL xxng_vat_TOOLS('`xxng_vat`.make.fixed.bezpozycyjne.niezerowe', _handle_FROM, 'E', _Key, '', '', '', ''); 
					CALL xxng_vat_TOOLS('`xxng_vat`.fill.brakujace.stawki', _handle_FROM, 'E', _Key, '', 'nie sprawdzaj', '', ''); 
				ELSE
					CALL ng_vat_e_fill_delete('fill.brakujace.stawki', _handle_FROM, _Key);
				END IF;
			END IF;
			
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> select.into', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			CALL _ng_e_rec_do('select.into', _Key, '', '');	

			/**************************************************************************************************************************
				CZY FV do WZ/PZ
			**************************************************************************************************************************/
			IF NOT @i_fvrudowz THEN
			--	Normalna edycja
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> IF NOT @i_fvrudowz THEN...', null), '_ng_E_Run', '', '', @.jmam.GP.log);
				INSERT IGNORE INTO `oppo_e` SELECT * FROM `oppo` WHERE IdnOper = _Key;
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> UPDATE `oppo_e` p, `opng_e` n', null), '_ng_E_Run', '', '', @.jmam.GP.log);
				UPDATE `oppo_e` p, `opng_e` n
				SET
					p.IdnOper_e = p.IdnOper
				WHERE
					n.GUID = _Key
					AND
					p.IdnOper = n.GUID
				;
				/* Nie ma juz `oppo_instancje`
				INSERT INTO `oppo_instancje_e` SELECT * FROM `oppo_instancje` WHERE IdnOper = _Key;
				*/
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> UPDATE `oppo_e` p END, `opng_e` n', null), '_ng_E_Run', '', '', @.jmam.GP.log);
				INSERT INTO `oppo_corr_e` SELECT * FROM `oppo_corr` WHERE IdnOper_corr = _Key;
				UPDATE `oppo_corr_e` c
				SET
					`Temporary` = 0
				WHERE
					c.IdnOper_corr = _Key
				;
			ELSE
			--	Edycja podlaczonych WZ/PZ
				CALL _ng_E_Tools('real.WZPZ.to.e', _Key, _handle_FROM, _Param_A);
			END IF;
						-- 	CALL _exproc_LOG('LOG', CONCAT_WS('', 'real.to.e >> After.real.to.e', null), '_ng_E_Run', '', '', @.jmam.GP.log);
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 

		IF _MODE = 'update.LP' THEN
			--	CALL _ng_E_Tools('update.LP', _Key, _handle_FROM, _Param_A);
			SELECT
				IFNULL(MAX(p.LP), 0) AS MaxLP
			INTO @tr.oppo_e.oppo_e.LP
			FROM `oppo_e` p
			WHERE
				p.IdnOper = _Key
			;
			SET @transact.oppo_e.LP = @tr.oppo_e.oppo_e.LP; -- na chwile potem usun
		END IF;
		
		IF _MODE = 'real.WZPZ.to.e' THEN
			CALL _ng_e_rec_do('select.into', _Key, '', '');	
			/**************************************************************************************************************************
				CZY FV do WZ/PZ
			**************************************************************************************************************************/
			IF NOT @i_fvrudowz THEN
				LEAVE S_ng_E_Tools;
			END IF;

			IF @OpTyp = @ht.ST THEN
				SET
					@MagSQL = @i_Magazyn1_Kasa, 
					@aRodzaj = @ht.CRzWZ, -- sprzedaz zatem WZ-ka
					@aRodzaj2 = IF(@session.HT.IR.Lista_FV_z_dokmag_bez_zwrotow, @ht.CRzWZ, @ht.CMGZW)
				;
			ELSE
				SET
					@MagSQL = @i_Magazyn2, 
					@aRodzaj = @ht.CPzPZ, -- zakup zatem PZ-ka
					@aRodzaj2 = @ht.CPzPZ
				;
			END IF;
			
			DROP TEMPORARY TABLE IF EXISTS `t_real_to_e_oppo_Attach_WZPZ`;
			CREATE TEMPORARY TABLE `t_real_to_e_oppo_Attach_WZPZ`(
				GUID VARCHAR(38) NOT NULL DEFAULT '',
				IdnOper VARCHAR(38) NOT NULL DEFAULT '',
				IdnOperFin VARCHAR(38) NOT NULL DEFAULT '',
				IdnWZ VARCHAR(38) NOT NULL DEFAULT '',
				PRIMARY KEY (`GUID`),
				KEY IdnOper(IdnOper),
				KEY IdnOperFin(IdnOperFin),
				KEY IdnWZ(IdnWZ)
			)
			;

			INSERT IGNORE INTO `t_real_to_e_oppo_Attach_WZPZ`
			(GUID, IdnOper, IdnOperFin, IdnWZ)
				SELECT
					p.GUID, p.IdnOper, p.IdnOperFin, p.IdnWZ
				FROM `oppo` p
				INNER JOIN `TowrNg` t ON p.idntowr = t.GUID AND (t.opakowanie_zwrotne = 0)
				WHERE
					(p.rodzaj IN (@aRodzaj, @aRodzaj2)) 
					AND 
					(p.idnWZ = _Key)
					
					
			;
			--	dodaj pozycje wlasne nie atachmentowe czyli te z idnoper - np. gdy do FV do WZ dodajemy jeszcze usluge
			INSERT IGNORE INTO `t_real_to_e_oppo_Attach_WZPZ`
			(GUID, IdnOper, IdnOperFin, IdnWZ)
				SELECT
					p.GUID, p.IdnOper, p.IdnOperFin, p.IdnWZ
				FROM `oppo` p
				INNER JOIN `TowrNg` t ON p.idntowr = t.GUID AND (t.opakowanie_zwrotne = 0)
				WHERE
					(p.IdnOper = _Key)
					
					
			;
			INSERT IGNORE INTO `oppo_e` SELECT * FROM `oppo` WHERE IdnOper = _Key;
			SET _SQLText =
			"
			INSERT IGNORE INTO `t_real_to_e_oppo_Attach_WZPZ`
			(GUID, IdnOper, IdnOperFin, IdnWZ)
				SELECT
					p.GUID, p.IdnOper, p.IdnOperFin, p.IdnWZ
				FROM `oppo` p
				INNER JOIN `opng` n ON p.IdnOper = n.GUID
				-- INNER JOIN `TowrNg` t ON p.idntowr = t.GUID AND (t.opakowanie_zwrotne = 0)
				LEFT JOIN `oppo_e` pe ON pe.GUID = p.GUID
				WHERE
					(p.rodzaj IN (@aRodzaj, @aRodzaj2)) 
					AND IFNULL(p.idnWZ, '') = ''
					AND p.opakowanie_zwrotne = 0
					AND (pe.GUID IS NULL)
					AND #PlatnikKontrGUID#
					AND #Magazyn#
					AND #CDG#
			;
			";
			
			SET _SQLText = REPLACE(_SQLText, '@aRodzaj', _VarStr(@aRodzaj));
			SET _SQLText = REPLACE(_SQLText, '@aRodzaj2', _VarStr(@aRodzaj2));
			
			IF @session.HT.IR.FV_z_WZ_dla_Platnika THEN
				SET _SQLText = REPLACE(_SQLText, '#PlatnikKontrGUID#', "(n.PlatnikGUID = '@i_KontrGUID') AND (n.PlatnikGUID != '')");
			ELSE
				SET _SQLText = REPLACE(_SQLText, '#PlatnikKontrGUID#', "(n.KontrGUID  = '@i_KontrGUID') AND (n.KontrGUID  != '')");
			END IF;
			SET _SQLText = REPLACE(_SQLText, '@i_KontrGUID', _VarStr(@i_KontrGUID));
			
			IF @session.HT.IR.FVdoWZtylkoWybranyMag THEN
				SET _SQLText = REPLACE(_SQLText, '#Magazyn#', "(n.zmagazynu + n.domagazynu = @MagSQL)");
			ELSE
				SET _SQLText = REPLACE(_SQLText, '#Magazyn#', "TRUE");
			END IF;

			IF @session.globals.Owner = 'CDG' THEN
				SET _SQLText = REPLACE(_SQLText, '#CDG#', "n.RodzajDowodu <> 'BP'");
			ELSE
				SET _SQLText = REPLACE(_SQLText, '#CDG#', "TRUE");
			END IF;
			
			
			SET _SQLText = REPLACE(_SQLText, '@MagSQL', _VarStr(@MagSQL));
			
			SET @_SQLText = _SQLText;
			SET @_SQLTextXXX = _SQLText;
			set @A.X = 'real.WZPZ.to.e.xxxxxxxxx';
			-- 	LEAVE S_ng_E_Tools;
			CALL _ExecuteCmd(_SQLText, @Error);

			-- LEAVE S_ng_E_Tools;
			--	Na koniec wstaw wreszcie pozycje z `t_real_to_e_oppo_Attach_WZPZ` 
			INSERT IGNORE INTO `oppo_e` 
				SELECT p.* FROM `oppo` p, `t_real_to_e_oppo_Attach_WZPZ` t
				WHERE
					p.GUID = t.GUID
			;
			
set @A = 'oj3';			
			UPDATE `oppo_e` p, `t_real_to_e_oppo_Attach_WZPZ` t, `ng_e_rec` ng
			SET
				p.IdnOper_e = _Key,
				p.calc_ver = ng.I_calc_ver
			WHERE
				p.GUID = t.GUID
				AND
				ng.GUID = _Key
			;
set @A = 'oj4';			
			-- DROP TEMPORARY TABLE IF EXISTS `t_real_to_e_oppo_Attach_WZPZ`;
			
		END IF; 
		
		IF _MODE = 'e.to.real' THEN	--	OPERACJE
						--	UWAGA dla konkola spr. PPT
							IF @session.globals.Owner = 'KONKOL' AND _Key LIKE 'WZ_z_PPT_%' AND DATABASE() = 'ht' THEN
								INSERT IGNORE INTO `oppo_konkol_WZ_z_PPT_1`
								(GUID, IdnOper, IDN, IdnTowr, ilosc, GUIDzm, Create_At, t_before_apply)
								SELECT
									p.GUID, p.IdnOper, p.IDN, p.IdnTowr, p.ilosc, p.GUIDzm, p.Create_At, 
									NOW()
								FROM `oppo_e` p
								WHERE
									p.IdnOper = _Key
								ON DUPLICATE KEY 
								UPDATE
									t_before_apply = NOW()
								;
								
							END IF;
					
		--	1. Naglowek
			UPDATE `opng_e` n SET n.tag = 0 WHERE n.GUID = _Key;	
			
			CALL _ng_E_ON('Before.e.to.real', _Key, _handle_FROM, '');
			
			INSERT IGNORE INTO `opng` SELECT * FROM `opng_e` WHERE GUID = _Key;
			--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
			UPDATE `opng_e` e, `opng` n SET e.Idn = n.Idn WHERE e.GUID = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			
						--	UWAGA dla konkola spr. PPT
							IF @session.globals.Owner = 'KONKOL' AND _Key LIKE 'WZ_z_PPT_%' AND DATABASE() = 'ht' THEN
								INSERT IGNORE INTO `oppo_konkol_WZ_z_PPT_1`
								(GUID, IdnOper, IDN, IdnTowr, ilosc, GUIDzm, Create_At, t_before_apply, t_after_insert_opng)
								SELECT
									p.GUID, p.IdnOper, p.IDN, p.IdnTowr, p.ilosc, p.GUIDzm, p.Create_At, 
									NOW(), NOW()
								FROM `oppo_e` p
								WHERE
									p.IdnOper = _Key
								ON DUPLICATE KEY 
								UPDATE
									t_after_insert_opng = NOW()
								;
								
							END IF;
			
		--	2. Vat	
		--	...	Usun niepotrzebne zerowe stawki
			IF 
                @session.globals.CALC.VAT.Ver >= '2021' 
                OR (_Key LIKE 'KSEF_%')
            THEN
			/********************************************************
				Nowe od 2021 r. 
			********************************************************/
				CALL C_HT_xxNgPo_DO('R.vat<-clear<-E.vat', _handle_FROM, '', _Key, '', '', '', '', '', @P);
			ELSE
			/********************************************************
				Przed 2021 r.   2017, 1999
			********************************************************/
				IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
					CALL xxng_vat_TOOLS('`xxng_vat`.delete.zerowe', _handle_FROM, 'E', _Key, '', '', '', ''); 
				ELSE
					CALL ng_vat_e_fill_delete('delete.zerowe', _handle_FROM, _Key);
				END IF;
			--	...	przepisz do real
				INSERT INTO `opng_vat` 
					SELECT * FROM `opng_vat_e` WHERE IdnOper = _Key
				;
						--	UWAGA dla konkola spr. PPT
							IF @session.globals.Owner = 'KONKOL' AND _Key LIKE 'WZ_z_PPT_%' AND DATABASE() = 'ht' THEN
								INSERT IGNORE INTO `oppo_konkol_WZ_z_PPT_1`
								(GUID, IdnOper, IDN, IdnTowr, ilosc, GUIDzm, Create_At, t_before_apply, t_after_insert_opng, t_after_insert_opng_vat)
								SELECT
									p.GUID, p.IdnOper, p.IDN, p.IdnTowr, p.ilosc, p.GUIDzm, p.Create_At, 
									NOW(), NOW(), NOW()
								FROM `oppo_e` p
								WHERE
									p.IdnOper = _Key
								ON DUPLICATE KEY 
								UPDATE
									t_after_insert_opng_vat = NOW()
								;
								
							END IF;
			--	...	przywroc wszystkie brakujace stawki
				IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
					CALL xxng_vat_TOOLS('`xxng_vat`.fill.brakujace.stawki', _handle_FROM, 'E', _Key, '', '', '', ''); 
				ELSE
					CALL ng_vat_e_fill_delete('fill.brakujace.stawki', _handle_FROM, _Key);
				END IF;
			END IF;

					IF @session.globals.Owner IN ('SIMEX') THEN
						CALL _ng_E_ToolsP('LOG.Add.logtxt', 'e.to.real', 'before.P.Ungroup.Zombie', _handle_FROM, _Key, '', '', '', @.loginf);	
					END IF;
			CALL C_HT_xxNgPo_GRP('P.Ungroup.Zombie', 'OP', 'E', _Key, '', '', '', '', '');		

					IF @session.globals.Owner IN ('SIMEX') THEN
						CALL _ng_E_ToolsP('LOG.Add.logtxt', 'e.to.real', 'before.INSERT IGNORE INTO `oppo`', _handle_FROM, _Key, '', '', '', @.loginf);	
					END IF;
		--	3. pozycje dodaj zwyczajnie (I TYLKO ZWYCZAJNE GDY JEST fvrudowz)
			INSERT IGNORE INTO `oppo` SELECT * FROM `oppo_e` WHERE IdnOper = _Key;
					IF @session.globals.Owner IN ('SIMEX') THEN
						CALL _ng_E_ToolsP('LOG.Add.logtxt', 'e.to.real', 'after.INSERT IGNORE INTO `oppo`', _handle_FROM, _Key, 'CC.P.R', '', '', @.loginf);	
					END IF;
			
			
						--	UWAGA dla konkola spr. PPT
							IF @session.globals.Owner = 'KONKOL' AND _Key LIKE 'WZ_z_PPT_%' AND DATABASE() = 'ht' THEN
								INSERT IGNORE INTO `oppo_konkol_WZ_z_PPT_1`
								(GUID, IdnOper, IDN, IdnTowr, ilosc, GUIDzm, Create_At, t_before_apply, t_after_insert_opng, t_after_insert_opng_vat, t_after_insert_oppo)
								SELECT
									p.GUID, p.IdnOper, p.IDN, p.IdnTowr, p.ilosc, p.GUIDzm, p.Create_At, 
									NOW(), NOW(), NOW(), NOW()
								FROM `oppo` p
								WHERE
									p.IdnOper = _Key
								ON DUPLICATE KEY 
								UPDATE
									t_after_insert_oppo = NOW()
								;
								
							END IF;
			
			
			
			--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
			UPDATE `oppo_e` e, `oppo` n SET e.Idn = n.Idn WHERE e.IdnOper = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			
			CALL _ng_e_rec_do('select.into', _Key, '', '');
			IF NOT @i_fvrudowz THEN
			--	5. korekty
				INSERT INTO `oppo_corr` SELECT * FROM `oppo_corr_e` WHERE IdnOper_corr = _Key;
				--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
				UPDATE `oppo_corr_e` e, `oppo_corr` n SET e.Idn = n.Idn WHERE e.IdnOper_corr = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			ELSE
			--	byla edycja podlaczonych WZ/PZ - usun laczac z oppo_e i pole IdnOper_e 
				UPDATE `oppo` p, `oppo_e` pe 
				SET
					p.IdnWZ = pe.IdnWZ,
					p.IdnOperFin = pe.IdnOperFin,
					p.idnvat = IF(pe.IdnOperFin = _key, pe.idnvat, p.idnvat),
					p.Rabat = IF(pe.IdnOperFin = _key, pe.Rabat, p.Rabat),
					p.idncennik = IF(pe.IdnOperFin = _key, pe.idncennik, p.idncennik),
				--	jmam 10 XII 2021
					p.Kurs = IF(pe.IdnOperFin = _key, pe.Kurs, p.Kurs),
					
					p.CenaNet = IF(pe.IdnOperFin = _key, pe.CenaNet, p.CenaNet),
					p.CenaNetWalzRab = IF(pe.IdnOperFin = _key, pe.CenaNetWalzRab, p.CenaNetWalzRab),
					p.cenabrt = IF(pe.IdnOperFin = _key, pe.cenabrt, p.cenabrt),
					
					p.wartnetwal = IF(pe.IdnOperFin = _key, pe.wartnetwal, p.wartnetwal),
					p.wartnet = IF(pe.IdnOperFin = _key, pe.wartnet, p.wartnet),
					p.wartvat = IF(pe.IdnOperFin = _key, pe.wartvat, p.wartvat),
					p.wartbrt = IF(pe.IdnOperFin = _key, pe.wartbrt, p.wartbrt), 
					p.wartbrtwal = IF(pe.IdnOperFin = _key, pe.wartbrtwal, p.wartbrtwal),
					
					p.koszt_nabycia = IF(pe.IdnOperFin = _key, pe.koszt_nabycia, p.koszt_nabycia),
					
					p.grp_GUID = IF(pe.IdnOperFin = _key, pe.grp_GUID, DEFAULT(p.grp_GUID)),
					p.grp_TowrSymb = IF(pe.IdnOperFin = _key, pe.grp_TowrSymb, DEFAULT(p.grp_TowrSymb)),
					p.grp_TowrNazwa = IF(pe.IdnOperFin = _key, pe.grp_TowrNazwa, DEFAULT(p.grp_TowrNazwa)),
					p.grp_Ilosc = IF(pe.IdnOperFin = _key, pe.grp_Ilosc, DEFAULT(p.grp_Ilosc)),
					p.grp_IdnTowr = IF(pe.IdnOperFin = _key, pe.grp_IdnTowr, DEFAULT(p.grp_IdnTowr)),
					p.grp_Jednostka = IF(pe.IdnOperFin = _key, pe.grp_Jednostka, DEFAULT(p.grp_Jednostka)),
					
					p.TowrNazwa2 = IF(pe.IdnOperFin = _key, pe.TowrNazwa2, p.TowrNazwa2),
					
					p.LP = IF(pe.IdnOperFin = _key, pe.LP, p.LP),
					
					p.Calc_ver = pe.Calc_ver
				WHERE
					pe.IdnOper_e = _key
					AND
					p.GUID = pe.GUID
				;
			END IF;
			
		END IF; 

	ELSEIF _handle_FROM = 'ZM' THEN
	/**********************************************************************************************************************************
		ZAMOWIENIA
	**********************************************************************************************************************************/
		IF _MODE = 'IS_need_Apply' THEN
			SET 
				@IS_need_Apply = 
				EXISTS(
				SELECT GUID FROM `zmng_e` ne WHERE ne.GUID = _Key
				)
			;
			IF @IS_need_Apply THEN
				SELECT
					(IFNULL(n.LocalTime, '0000-00-00 00:00:00') < IFNULL(ne.LocalTime, '0000-00-00 00:00:00')) AS IS_need_Apply
				FROM `zmng_e` ne 
				LEFT JOIN `zmng` n ON n.GUID = ne.GUID
				WHERE
					ne.GUID = _Key
				;
			ELSE
				SELECT @IS_need_Apply AS IS_need_Apply;
			END IF;
		END IF; 
		
		IF _MODE = 'delete.e' THEN
			DELETE FROM `zmng_e` WHERE GUID = _Key;
			CALL erp_obj_counters_values_e_1_rec_tools('DELETE.from.e', _handle_FROM, _Key, '', '', '', '');
			DELETE FROM `zmng_vat_e` WHERE IdnOper = _Key;
			DELETE FROM `zmpo_e` WHERE IdnNg = _Key;
			IF _Param_A = 'LetEnd' THEN	-- Wolane w _ng_E_LetEnd
				DELETE FROM `ng_e_rec` WHERE GUID = _Key;
			END IF;
		END IF; 
		
		IF _MODE = 'delete.real' THEN
		
			IF @session.globals.Owner = 'AMICUS' THEN
			--	UWAGA dla Amicusa - zapisz bezpiecznie pozycje zamowienia 
				DELETE FROM `zmpo_e_saved` WHERE IdnNg = _Key;
				INSERT IGNORE INTO `zmpo_e_saved` SELECT * FROM `zmpo_e` WHERE IdnNg = _Key;
			END IF;
			
			IF @session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX') THEN
			--	UWAGA dla SIMEX - zapisz bezpiecznie pozycje zamowienia 
				DELETE FROM `zmpo_e_saved` WHERE IdnNg = _Key;
				INSERT IGNORE INTO `zmpo_e_saved` SELECT * FROM `zmpo_e` WHERE IdnNg = _Key;
				DELETE FROM `zmng_e_saved` WHERE GUID = _Key;
				INSERT IGNORE INTO `zmng_e_saved` SELECT * FROM `zmng_e` WHERE GUID = _Key;
			END IF;
			
					SET @.C_HT_ng_e.Process.Msg = 'delete.real.1'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			-- bylo DELETE FROM `zmng` WHERE GUID = _Key;
			DELETE n FROM `zmng` n, `zmng_e` ne WHERE ne.GUID = _Key AND n.GUID = ne.GUID;
			
			
					SET @.C_HT_ng_e.Process.Msg = 'delete.real.2'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			-- bylo	DELETE FROM `zmng_vat` WHERE IdnOper = _Key;
			DELETE v FROM `zmng_vat` v, `zmng_e` ne WHERE ne.GUID = _Key AND v.IdnOper = ne.GUID;
					SET @.C_HT_ng_e.Process.Msg = 'delete.real.3'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			-- bylo DELETE FROM `zmpo` WHERE IdnNg = _Key;
			DELETE p FROM `zmpo` p, `zmng_e` ne WHERE ne.GUID = _Key AND p.IdnNg = ne.GUID;
					SET @.C_HT_ng_e.Process.Msg = 'delete.real.4'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
		END IF; 

		IF _MODE = 'refresh.real.to.e' THEN
		--	Gdy zrobilem Apply i rozliczylem w swiecie r ale nie wyszedlem z e to musze zaladowac calosc pol do e
			DELETE FROM `zmng_e` WHERE GUID = _Key;
			INSERT INTO `zmng_e` SELECT * FROM `zmng` WHERE GUID = _Key;
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 
		
		IF _MODE = 'real.to.e' THEN
			SET @zmpo.real.to.e = 1;
			
					SET @.C_HT_ng_e.Process.Msg = 'real.to.e.1 :   INSERT INTO `zmng_e` SELECT * FROM `zmng` WHERE GUID = _Key'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
			INSERT INTO `zmng_e` SELECT * FROM `zmng` WHERE GUID = _Key;
					SET @.C_HT_ng_e.Process.Msg = 'real.to.e.2 :   INSERT INTO `zmng_vat_e` SELECT * FROM `zmng_vat` WHERE IdnOper = _Key;'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
			INSERT INTO `zmng_vat_e` SELECT * FROM `zmng_vat` WHERE IdnOper = _Key;
		--	...	przywroc wszystkie brakujace stawki
			IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
				CALL xxng_vat_TOOLS('`xxng_vat`.make.fixed.bezpozycyjne.niezerowe', _handle_FROM, 'E', _Key, '', '', '', ''); 
				CALL xxng_vat_TOOLS('`xxng_vat`.fill.brakujace.stawki', _handle_FROM, 'E', _Key, '', 'nie sprawdzaj', '', ''); 
			ELSE
				CALL ng_vat_e_fill_delete('fill.brakujace.stawki', _handle_FROM, _Key);
			END IF;
					SET @.C_HT_ng_e.Process.Msg = 'real.to.e.3 :   INSERT INTO `zmpo_e` SELECT * FROM `zmpo` WHERE IdnNg = _Key;'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
			INSERT INTO `zmpo_e` SELECT * FROM `zmpo` WHERE IdnNg = _Key;
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 
		
		IF _MODE = 'e.to.real' THEN	--	ZAMOWIENIA
		--	1. Naglowek
			-- UPDATE `zmng_e` n SET n.tag = 0 WHERE n.GUID = _Key;	
			
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.1'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			CALL _ng_E_ON('Before.e.to.real', _Key, _handle_FROM, '');

			IF @session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX') THEN
			--	UWAGA dla SIMEX - zapisz bezpiecznie pozycje zamowienia 
				INSERT IGNORE INTO `zmpo_e_saved` SELECT * FROM `zmpo_e` WHERE IdnNg = _Key;
				INSERT IGNORE INTO `zmng_e_saved` SELECT * FROM `zmng_e` WHERE GUID = _Key;
			END IF;
			
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.1 .... INSERT IGNORE INTO `zmng` SELECT * FROM `zmng_e` WHERE GUID = _Key;'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			INSERT IGNORE INTO `zmng` SELECT * FROM `zmng_e` WHERE GUID = _Key;
			
			IF @session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX') THEN
			--	UWAGA dla SIMEX - zapisz bezpiecznie pozycje zamowienia 
				UPDATE `zmng_e_saved` e, `zmng` n SET e.Idn = n.Idn WHERE e.GUID = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			END IF;
			
			/* Chyba tak nie bedzie
			INSERT IGNORE INTO `zmng`
			(`GUID`)
			SELECT e.GUID FROM `zmng_e` WHERE GUID = _Key
			;
			UPDATE `zmng` n, `zmng_e` e
				SET
				n.rodzaj = e.rodzaj,
				n.zrealizowane = e.zrealizowane,
				n.datawystaw = e.datawystaw,
				n.datawplywu = e.datawplywu,
				n.grupaoper = e.grupaoper,
				n.symboper = e.symboper,
				n.idn_kontrah = e.idn_kontrah,
				n.kontrsymbol = e.kontrsymbol,
				n.netto = e.netto,
				n.sposobplatn = e.sposobplatn,
				n.uwagi = e.uwagi,
				n.zamawiajacy = e.zamawiajacy,
				n.useridn = e.useridn,
				n.nrzamw = e.nrzamw,
				n.zamwpermn = e.zamwpermn,
				n.rezerwacja = e.rezerwacja,
				n.idnmagazyn = e.idnmagazyn,
				n.nrzamwkontr = e.nrzamwkontr,
				n.terminrealizacji = e.terminrealizacji,
				n.GUID = e.GUID,
				n.klasacenowa = e.klasacenowa,
				n.rabat = e.rabat,
				n.waluta = e.waluta,
				n.kurs = e.kurs,
				n.status = e.status,
				n.lockflag = e.lockflag,
				n.kontrGUID = e.kontrGUID,
				n.localtime = e.localtime,
				n.remotetime = e.remotetime,
				n.ilepoz = e.ilepoz,
				n.ilepozzreal = e.ilepozzreal,
				n.lockGUID = e.lockGUID,
				n.nettowal = e.nettowal,
				n.MagazynWys = e.MagazynWys,
				n.tymczasowa = e.tymczasowa,
				n.spedycja = e.spedycja,
				n.akwizytorGUID = e.akwizytorGUID,
				n.rodzaj2 = e.rodzaj2,
				n.deleted = e.deleted,
				n.idnuser = e.idnuser,
				n.katcol0 = e.katcol0,
				n.katcol1 = e.katcol1,
				n.katcol2 = e.katcol2,
				n.katcol3 = e.katcol3,
				n.katcol4 = e.katcol4,
				n.warunki_dostawy = e.warunki_dostawy,
				n.waga = e.waga,
				n.wydzial = e.wydzial,
				n.permanentne_cykl = e.permanentne_cykl,
				n.analityka = e.analityka,
				n.wersja = e.wersja,
				n.lang_id = e.lang_id,
				n.przeliczenie_B_N = e.przeliczenie_B_N,
				n.ugrpguid = e.ugrpguid,
				n.DataZakonczUmowy = e.DataZakonczUmowy,
				n.idn_tab_kurs = e.idn_tab_kurs,
				n.osobaGUID = e.osobaGUID,
				n.warunki_dostawy_2 = e.warunki_dostawy_2,
				n.rodzaj_typ = e.rodzaj_typ,
				n.zlecenieGUID = e.zlecenieGUID,
				n.ogk_GUID = e.ogk_GUID,
				n.dataplatnosci = e.dataplatnosci,
				n.info1 = e.info1,
				n.info2 = e.info2,
				n.waga_brutto = e.waga_brutto,
				n.transza_zamow = e.transza_zamow,
				n.wyjazdGUID = e.wyjazdGUID,
				n.numer_na_trasie_zm = e.numer_na_trasie_zm,
				n.czasrealizacji = e.czasrealizacji,
				n.powod_niezrealizowania = e.powod_niezrealizowania,
				n.createdfrom_GUID = e.createdfrom_GUID,
				n.info3 = e.info3,
				n.info4 = e.info4,
				n.brutto = e.brutto,
				n.BruttoWal = e.BruttoWal,
				n.terminrealizacji_plan = e.terminrealizacji_plan,
				n.RodzajDowodu = e.RodzajDowodu,
				n.info5 = e.info5,
				n.info6 = e.info6,
				n.areaGUID = e.areaGUID,
				n.Calc_Ver = e.Calc_Ver,
				n.status_obieg = e.status_obieg,
				n.Create_At = e.Create_At,
				n.status_powiadomien = e.status_powiadomien

				WHERE
					e.GUID = _Key
					AND
					n.GUID = e.GUID
			;
			*/

			
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.2'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
			--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
			UPDATE `zmng_e` e, `zmng` n SET e.Idn = n.Idn WHERE e.GUID = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.3'	;
					IF (@session.globals.APPLY.LOG.Active = 'ON 2') OR (@session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX')) THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, _Key, '');
					END IF;
					
			CALL C_HT_xxNgPo_GRP('P.Ungroup.Zombie', 'ZM', 'E', _Key, '', '', '', '', '');		

		--	3. pozycje dodaj zwyczajnie
			INSERT IGNORE INTO `zmpo` SELECT * FROM `zmpo_e` WHERE IdnNg = _Key;
			--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
			IF @session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX') THEN
			--	UWAGA dla SIMEX - zapisz bezpiecznie pozycje zamowienia 
				UPDATE `zmpo_e_saved` e, `zmpo` n SET e.Idn = n.Idn WHERE e.IdnNg = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			END IF;
			
			UPDATE `zmpo_e` e, `zmpo` n SET e.Idn = n.Idn WHERE e.IdnNg = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	

		--	2. Vat	
		--	...	Usun niepotrzebne zerowe stawki
			IF 
                @session.globals.CALC.VAT.Ver >= '2021' 
                OR (_Key LIKE 'KSEF_%')
            THEN
			/********************************************************
				Nowe od 2021 r. 
			********************************************************/
				CALL C_HT_xxNgPo_DO('R.vat<-clear<-E.vat', _handle_FROM, '', _Key, '', '', '', '', '', @P);
			ELSE
			/********************************************************
				Przed 2021 r.   2017, 1999
			********************************************************/
				IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
					CALL xxng_vat_TOOLS('`xxng_vat`.delete.zerowe', _handle_FROM, 'E', _Key, '', '', '', ''); 
				ELSE
					CALL ng_vat_e_fill_delete('delete.zerowe', _handle_FROM, _Key);
				END IF;
					/*
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.4'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
					*/
		--	...	przepisz do real vat
				INSERT INTO `zmng_vat` SELECT * FROM `zmng_vat_e` WHERE IdnOper = _Key;
					/*
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.5'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
					*/
		--	...	przywroc wszystkie brakujace stawki
				IF @session.globals.NEW.CALC.VAT.VI.2017 THEN
					CALL xxng_vat_TOOLS('`xxng_vat`.fill.brakujace.stawki', _handle_FROM, 'E', _Key, '', '', '', ''); 
				ELSE
					CALL ng_vat_e_fill_delete('fill.brakujace.stawki', _handle_FROM, _Key);
				END IF;
			END IF;
					-- ERROR!!!!!!!!!!!! celowy	
					-- select sdf from zmpo_e where GUID = 'qqqq' into @WWWW;
					/*
					SET @.C_HT_ng_e.Process.Msg = 'e.to.real.6'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
					*/
		/*	było do 14 II 2023 - teraz wyżej przed VAT-em
		
		--	3. pozycje dodaj zwyczajnie
			INSERT IGNORE INTO `zmpo` SELECT * FROM `zmpo_e` WHERE IdnNg = _Key;
			--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
			IF @session.globals.Owner IN ('SIMEX', 'POLAM', 'COMEX') THEN
			--	UWAGA dla SIMEX - zapisz bezpiecznie pozycje zamowienia 
				UPDATE `zmpo_e_saved` e, `zmpo` n SET e.Idn = n.Idn WHERE e.IdnNg = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			END IF;
			
			UPDATE `zmpo_e` e, `zmpo` n SET e.Idn = n.Idn WHERE e.IdnNg = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
		*/
		END IF; 
		
		IF _MODE = 'update.LP' THEN
			--	CALL _ng_E_Tools('update.LP', _Key, _handle_FROM, _Param_A);
			SELECT
				IFNULL(MAX(p.LP), 0) AS MaxLP
				INTO @tr.zmpo_e.zmpo_e.LP
			FROM `zmpo_e` p
			WHERE
				p.IdnNG = _Key
			;
			SET @transact.zmpo_e.LP = @tr.zmpo_e.zmpo_e.LP; -- na chwile potem usun
		END IF;
		
		
	ELSE
	/**********************************************************************************************************************************
		KS, BN, RR
	**********************************************************************************************************************************/
		CALL _ng_e_rec_do('select.into', _Key, '', '');	
		
		IF _MODE = 'IS_need_Apply' THEN
			SELECT
				(IFNULL(n.LocalTime, '0000-00-00 00:00:00') < IFNULL(ne.LocalTime, '0000-00-00 00:00:00')) AS IS_need_Apply
			FROM `opng_e` ne 
			LEFT JOIN `opng` n ON n.GUID = ne.GUID
			WHERE
				ne.GUID = _Key
			;
		END IF; 
		
		IF _MODE = 'delete.e' THEN
			IF @i_IsFamily AND @r_Family_GUID != '' THEN
				DELETE FROM `opng_r_e` WHERE Family_GUID = @r_Family_GUID;
			ELSE
				DELETE FROM `opng_r_e` WHERE GUID = _Key;
			END IF;
			IF _Param_A = 'LetEnd' THEN	-- Wolane w _ng_E_LetEnd
				DELETE FROM `ng_e_rec` WHERE GUID = _Key;
			END IF;
		END IF; 
		
		IF _MODE = 'delete.real' THEN
			IF @i_IsFamily AND @r_Family_GUID != '' THEN
				DELETE FROM `opng` WHERE Family_GUID = @r_Family_GUID;
			ELSE
				DELETE FROM `opng` WHERE GUID = _Key;
			END IF;
			
		END IF; 

		IF _MODE = 'refresh.real.to.e' THEN
		--	Gdy zrobilem Apply i rozliczylem w swiecie r ale nie wyszedlem z e to musze zaladowac calosc pol do e
			IF @i_IsFamily AND @r_Family_GUID != '' THEN
				DELETE FROM `opng_r_e` WHERE Family_GUID = @r_Family_GUID;
				INSERT INTO `opng_r_e` SELECT * FROM `opng` WHERE Family_GUID = @r_Family_GUID;
			ELSE
				DELETE FROM `opng_r_e` WHERE GUID = _Key;
				INSERT INTO `opng_r_e` SELECT * FROM `opng` WHERE GUID = _Key;
			END IF;
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 
		
		IF _MODE = 'real.to.e' THEN
			SET @opng_r.real.to.e = 1;
			
			IF @i_IsFamily AND @r_Family_GUID != '' THEN
				INSERT INTO `opng_r_e` SELECT * FROM `opng` WHERE Family_GUID = @r_Family_GUID;
			ELSE
				INSERT INTO `opng_r_e` SELECT * FROM `opng` WHERE GUID = _Key;
			END IF;
			CALL _ng_E_ON('After.real.to.e', _Key, _handle_FROM, '');
		END IF; 
		
		IF _MODE = 'e.to.real' THEN
        	set @jmam_inf = concat_ws('>', @jmam_inf, 'jestem w "R"');

			CALL _ng_E_ON('Before.e.to.real', _Key, _handle_FROM, '');
        	set @jmam_inf = concat_ws('>', @jmam_inf, 'j.1');
		--	1. Naglowek
			IF @i_IsFamily AND @r_Family_GUID != '' THEN
				INSERT IGNORE INTO `opng` SELECT * FROM `opng_r_e` WHERE Family_GUID = @r_Family_GUID;
				--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
				UPDATE `opng_r_e` e, `opng` n SET e.Idn = n.Idn WHERE e.Family_GUID = @r_Family_GUID AND e.Idn = 0 AND n.GUID = e.GUID;	
			ELSE
                        set @jmam_inf = concat_ws('>', @jmam_inf, 'j.2');
                        set @jmam_inf = concat_ws('>', @jmam_inf, _Key);
				-- UPDATE `zmng_e` n SET n.tag = 0 WHERE n.GUID = _Key;	
				INSERT IGNORE INTO `opng` SELECT * FROM `opng_r_e` WHERE GUID = _Key;
				--	zwrotnie nadaj IDN w E -> jesli kreowalismy dokument to po pierwszym apply swiat E juz powinien miec idn-y
				UPDATE `opng_r_e` e, `opng` n SET e.Idn = n.Idn WHERE e.GUID = _Key AND e.Idn = 0 AND n.GUID = e.GUID;	
			END IF;
		
		END IF; 
-- ?????Tutaj dalej poprawiuaj		
	END IF; 
	
END$$


DROP PROCEDURE IF EXISTS `_ng_E_Wizard`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_Wizard`(
	IN _MODE VARCHAR(250),
	IN _Key VARCHAR(255),	
	IN _Param_WE INTEGER,
	IN _Context VARCHAR(255),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255),
	IN _Param_C VARCHAR(255)
)
/*
	CALL _ng_E_Wizard('Init.wizard', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.optypy', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.rodzaje', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.rodzaje_typ', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.magazyny', @IdnOper, 0, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.magazyny', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.kasy', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('select.waluty', @IdnOper, 1, 'STZTMG', '', '', '');
	CALL _ng_E_Wizard('Init.wizard', @IdnOper, 0, 'Short.Paragon', '', '', '');
*/
S__ng_E_Wizard: BEGIN 
	IF _MODE = 'Init.wizard' THEN
		CALL _sys_upr_init('');
		/*********************************************************************
		Typy
		*********************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Optypy`;
		CREATE TEMPORARY TABLE `t_ng_E_Wizard_Optypy`
			SELECT 
				nr.Handle_UserGUID, 
				_VarInt(sp.Value) AS OpTyp,
				sp.DisplayValue AS Opis,
				_VarStr('') AS upr_optyp,
				_VarInt(0) AS u_optyp,
				_VarInt(1) AS Visible
			FROM `slowniki_pierwotne` sp, `ng_e_rec` nr
			WHERE 
				sp.slownik_GUID = 'optyp'
				AND
				nr.GUID = _Key
			ORDER BY OpTyp
		;
		UPDATE `t_ng_E_Wizard_Optypy` t
		SET 
			t.upr_optyp = 
				IFNULL((SELECT od.upr_optyp FROM `operdoc` od WHERE od.Grupa = t.OpTyp LIMIT 1), '')
		;
		UPDATE `t_ng_E_Wizard_Optypy` t
		SET 
			t.u_optyp = 
				_GetUprawnienie(t.upr_optyp, t.Handle_UserGUID)
		;
		UPDATE `t_ng_E_Wizard_Optypy` t
		SET 
			t.Visible = (t.u_optyp >= @uprDSInsert)
		;
		
		IF _Context = 'STZTMG' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = FALSE
			WHERE
				NOT(t.OpTyp IN (@ht.ST, @ht.ZT, @ht.MG, @ht.SI, @ht.ZP, @ht.WE)) 
			;
		ELSEIF _Context = 'KOREKTA' THEN
			SET @Xccccc = '';	--	nic nie rob tutaj
		ELSEIF _Context = 'KANCELARIA' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = (t.OpTyp = 4 or t.OpTyp = 17)
			WHERE
				TRUE -- t.OpTyp = 4
			;
		ELSEIF _Context = 'ZM' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = FALSE
			WHERE
				NOT(t.OpTyp IN (@ht.ZM)) 
			;
		ELSEIF _Context = 'KS' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = FALSE
			WHERE
				NOT(t.OpTyp IN (@ht.KS)) 
			;
		ELSEIF _Context = 'BN' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = FALSE
			WHERE
				NOT(t.OpTyp IN (@ht.BN)) 
			;
		ELSEIF _Context = 'R' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = FALSE
			WHERE
				NOT(t.OpTyp IN (@ht.RO, @ht.KS, @ht.BN)) 
			;
		ELSEIF _Context = 'Short.Paragon' THEN
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = (t.OpTyp = 0)
			;
		END IF;
		/*********************************************************************
		Rodzaje
		*********************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Rodzaje`;
		CREATE TEMPORARY TABLE `t_ng_E_Wizard_Rodzaje`
			SELECT
				nr.Handle_UserGUID, 
				od.*,
				_VarInt(0) AS u_optyp,
				_VarInt(0) AS u_rodzaj,
				_VarInt(1) AS Visible,
				-- _VarInt(0) AS WP_GrupaOperacji,
				_VarInt(0) AS WP_RodzajTyp,
				_VarInt(0) AS WP_International,
				_VarInt(0) AS WP_Zalacznik,
				_VarInt(0) AS WP_MagFrom,
				_VarInt(0) AS WP_MagTo,
				_VarInt(0) AS WP_Kasy,
				_VarInt(0) AS WP_Kontrahent,
				_VarInt(0) AS Ile_RodzajTyp,
				_VarInt(0) AS Ile_MagFrom,
				_VarInt(0) AS Ile_MagTo,
				_VarInt(0) AS Ile_Kasy
				
			FROM `ng_e_rec` nr, `operdoc` od
			WHERE
				nr.GUID = _Key 
				AND od.valid 
			ORDER BY od.Grupa, od.Rodzaj
		;
		UPDATE `t_ng_E_Wizard_Rodzaje` tr
		SET 
			tr.WP_International = tr.IsWaluta,	--	IFNULL(@session.HT.IR.PytajoWalutePrzyDokKrajowym, FALSE) !!!!!!!!!!!!! i co z tym
			tr.WP_Zalacznik = 
				tr.FVdoWZPZ AND
					IF(tr.TwTyp = @ht.TwPZ,
						IFNULL(@session.HT.IR.PytajoFVdoPZ, FALSE),
						IFNULL(@session.HT.IR.PytajoFVdoWZ, FALSE)
					),
			tr.WP_MagFrom = 
				IF(tr.TwTyp = @ht.TwZm,
					_varInt(1),
					IF(tr.TwTyp IN (@ht.TwRZ, @ht.TwMM),
						_varInt(1),
						_varInt(0)
					)
				),
			tr.WP_MagTo =
				IF(tr.TwTyp = @ht.TwZm,
					IF(NOT @session.globals.Owner IN ('COMEX'),
						_varInt(1),
						_varInt(0)
					),
--					_varInt(2),
					IF(tr.TwTyp IN (@ht.TwPZ, @ht.TwMM),
						_varInt(1),
						_varInt(0)
					)
				),
			tr.WP_Kasy = 
				tr.Grupa = @ht.KS,
			tr.WP_Kontrahent = 
				MA_Kontrahenta,
			tr.u_optyp = 
				_GetUprawnienie(tr.upr_optyp, tr.Handle_UserGUID),
			tr.u_rodzaj =
				_GetUprawnienie(tr.upr_rodzaj, tr.Handle_UserGUID)
		;
		UPDATE `t_ng_E_Wizard_Rodzaje` tr
		SET 
			-- tr.Visible = tr.Visible AND(GREATEST(tr.u_optyp, tr.u_rodzaj) >= @uprDSInsert)
			tr.Visible = tr.Visible AND(tr.u_rodzaj >= @uprDSInsert)
		;

		IF _Context = 'KOREKTA' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr, `ng_e_rec` nr
			SET 
				tr.Visible = (tr.Rodzaj = nr.Rodzaj)	--	na razie bo powinno sie dac wybor 
			WHERE
				nr.GUID = _Key
			;
			UPDATE `t_ng_E_Wizard_Optypy` t, `t_ng_E_Wizard_Rodzaje` tr
			SET 
				t.Visible = tr.Visible
			WHERE
				tr.grupa = t.OpTyp
			;
		ELSE
		--	Gdy NIE KOREKTA w ogóle nie dawaj korekt do wyboru jako samodzielnie tworzonych dokumentów - zawsze opcją korekta do dok. na którym stoisz!
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET
				tr.Visible = NOT tr.IsKorekta
			WHERE
				tr.Visible
			;
			-- IF @session.globals.Owner IN ('GLENBROOK', 'TRANSBUD', 'LACZPOL', 'SEVENET', 'PROBIER','CDG') THEN  apro - dla wszystkich powinny być widoczne te korekty - sa niemagazynowe
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET
				tr.Visible = tr.Rodzaj IN (@ht.CKsKF, @ht.CSiKF, @ht.CWeDK)	-- 25	Korekta ZP (kosztowe) 31 Sprzedaż inna - korekta faktury VAT, Dowód wewn korygujący
			WHERE
				NOT tr.Visible
			;
			--	END IF;
			IF @session.globals.Owner IN ('PROBIER') THEN
				UPDATE `t_ng_E_Wizard_Rodzaje` tr
				SET
					tr.Visible = tr.Rodzaj IN (@ht.CWeKF)			--		84	Korekta SW-FV
				WHERE
					NOT tr.Visible
				;								
			END IF;
		END IF;
		
		IF _Context = 'KANCELARIA' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr SET tr.Visible = tr.Visible AND (tr.Rodzaj in (104, 111));
		END IF;
		
		IF _Context LIKE 'Realizacja.ZM.%' THEN
			IF _Context = 'Realizacja.ZM.cTRANS_MM_FROMZamowienia' THEN
			--	TYLKO MM
				UPDATE `t_ng_E_Wizard_Rodzaje` tr
				SET 
					tr.Visible = (tr.Rodzaj = @ht.CMMMM)
				;
			ELSE
				UPDATE `t_ng_E_Wizard_Rodzaje` tr, `ng_e_rec` nr, `zmng` z, `operdoc` od 
				SET
					tr.Visible = 
						--  tr.Visible 
						--  AND
						(tr.MagTyp = od.MagTyp) 
						AND
						(tr.Grupa != od.Grupa) 
						AND
						(tr.IsPozycjeVisible) 
						AND 
						(tr.Grupa IN (0,1,2)) 
						AND
						(tr.MA_Kontrahenta) 
						AND
						NOT(tr.ISKorekta) 
				WHERE
					nr.GUID = _Key
				AND
					IFNULL(nr.i_Input_GUID, '') != ''
				AND
					z.GUID = nr.i_Input_GUID
				AND
					od.Rodzaj = z.Rodzaj
					AND TRUE
				;
			END IF;
			--	Teraz jeszcze sztucznie schowaj grupy Optyp z wyjatkiem 1 ej
			UPDATE `t_ng_E_Wizard_Optypy` t SET t.Visible = FALSE;
			UPDATE `t_ng_E_Wizard_Optypy` t, `t_ng_E_Wizard_Rodzaje` tr
			SET 
				t.Visible = 1
			WHERE
				t.OpTyp = tr.Grupa
				AND
				tr.Visible
				AND FALSE
			;

		--	UWAGA przy realizacji zamowien - niektorzy jak Transbud nie chcą by przy MagazynWys = 0  chowac magazyny -
		--	chca miec wtedy WYBÓR!!!!
			SET 
			--	Na razie tylko dla transbudu
				@.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0 = 
					@session.globals.Owner IN ('TRANSBUD', 'COMEX')		-- COMEX dodany z zad.56466 X 2022
			;
		--	Realizacja zam. i uwzgl. czy magazynwys = 0 - wtedy pokaz magazyny
			UPDATE `t_ng_E_Wizard_Rodzaje` tr, `ng_e_rec` nr, `zmng` z, `operdoc` od 
			SET 
				tr.WP_MagFrom = 
					IF(@.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0 AND _Context != 'Realizacja.ZM.cTRANS_MM_FROMZamowienia',
						tr.WP_MagFrom AND (z.MagazynWys = 0),
						FALSE
					),
				tr.WP_MagTo =
					IF(@.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0,
						tr.WP_MagTo AND (z.MagazynWys = 0),
						FALSE
					)
			WHERE
				tr.Visible
				AND
				nr.GUID = _Key
				AND
				IFNULL(nr.i_Input_GUID, '') != ''
				AND
				z.GUID = nr.i_Input_GUID
			;
		END IF;
		
		IF _Context LIKE 'CLONE.AS.ZAM.FROM.%' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr SET tr.Visible = FALSE;
			IF _Context = 'CLONE.AS.ZAM.FROM.ZAPOTRZEBOWANIE' THEN
			--	TYLKO MM
				UPDATE `t_ng_E_Wizard_Rodzaje` tr
				SET 
					tr.Visible = (tr.Rodzaj = @ht.CZmDD)
				;
			ELSE
				UPDATE `t_ng_E_Wizard_Rodzaje` tr
				SET 
					tr.Visible = (tr.Rodzaj IN (@ht.CZmOO, @ht.CZmEX))
				;
			END IF;
			
			UPDATE `t_ng_E_Wizard_Rodzaje` tr, `ng_e_rec` nr
			SET 
				tr.Visible = tr.Visible
				--	zad 57084
					AND (tr.IsPozycjeVisible) 
					AND (tr.MA_Kontrahenta) 
					AND NOT(tr.ISKorekta) 
					-- było AND IF(nr.i_Waluta != 0, tr.Rodzaj = @ht.CZmEX, TRUE)	--	gdy Jest waluta (przeszla z dok. zrodlowego) TO LICZY SIE TYLKO @ht.CZmEX
					AND
					IF(@session.globals.Owner IN ('COMEX'), 	 	-- zad 57084
						tr.Rodzaj = nr.rodzaj, 
						IF(nr.i_Waluta != 0, tr.Rodzaj = @ht.CZmEX, TRUE)	--	gdy Jest waluta (przeszla z dok. zrodlowego) TO LICZY SIE TYLKO @ht.CZmEX
					) 	-- zad 57084
					AND IFNULL(nr.i_Input_GUID, '') != ''
			WHERE
				tr.Visible
				AND nr.GUID = _Key
			;
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.WP_International = 0,
				-- tr.WP_MagFrom = FALSE, -- tr.WP_MagFrom AND @upr.Korekta_z_innego_magazynu > 0,
				-- tr.WP_MagTo = FALSE, -- tr.WP_MagTo AND @upr.Korekta_z_innego_magazynu > 0,
				tr.WP_Kontrahent = FALSE -- MA_Kontrahenta AND (@session.globals.Owner = 'JARZEBINSCY' OR TRUE)
			;
			--	Teraz jeszcze sztucznie schowaj grupy Optyp z wyjatkiem 1 ej
			UPDATE `t_ng_E_Wizard_Optypy` t SET t.Visible = FALSE;
			UPDATE `t_ng_E_Wizard_Optypy` t, `t_ng_E_Wizard_Rodzaje` tr
			SET 
				t.Visible = 1
			WHERE
				t.OpTyp = tr.Grupa
				AND
				tr.Visible
				AND FALSE	-- !!!!!!!!!!!!!!!!!!
			;
		END IF;		--	IF _Context LIKE 'CLONE.AS.ZAM.FROM.%' THEN
		
		IF _Context = 'REALIZUJ.WZ' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr, `operdoc` od
			SET 
				tr.Visible = 
					tr.Visible 
					AND
					(tr.grupa IN (@ht.ST, @ht.MG)) 
					AND
					(od.MagTyp = @ht.mtRZ) 
			WHERE
				od.Rodzaj = tr.Rodzaj
			;
			--	Teraz jeszcze sztucznie schowaj grupy Optyp z wyjatkiem 0 ej
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = (t.OpTyp = 0)
			;
		ELSEIF _Context = 'REALIZUJ.PZ' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr, `operdoc` od
			SET 
				tr.Visible = 
					tr.Visible 
					AND
					(tr.grupa IN (@ht.ZT, @ht.MG)) 
					AND
					(od.MagTyp = @ht.mtPZ) 
			WHERE
				od.Rodzaj = tr.Rodzaj
			;
			--	Teraz jeszcze sztucznie schowaj grupy Optyp z wyjatkiem 1 ej
			UPDATE `t_ng_E_Wizard_Optypy` t
			SET 
				t.Visible = (t.OpTyp = 1)
			;
		ELSEIF _Context = 'Short.Paragon' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.Visible = (tr.Rodzaj = @ht.CSpBR)	--	Paragon
			;
		END IF;
		
		/*********************************************************************
		Magazyny
		*********************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Magazyny`;
		CREATE TEMPORARY TABLE `t_ng_E_Wizard_Magazyny`
			SELECT 
				nr.Handle_UserGUID, 
				m.*,
				_VarInt(0) AS u_przychod,
				_VarInt(0) AS u_rozchod,
				_VarInt(1) AS Visible
			FROM `Magazyny` m, `ng_e_rec` nr
			WHERE
				nr.GUID = _Key AND 
			--	TODO kons. z GP VII 2024 musimy dac badanie wszystki z wyj. uprawnienia "Dostep_do_mag_nieakt"
				IF(@session.globals.Owner IN ('COMEX'),
					m.Status = 0,	-- zad.56466 (COMEX) X 2022
					TRUE
				) 
				/*
				(
					m.Status = 0
					OR
					_GetUpr2024('Dostep_do_mag_nieakt', nr.Handle_UserGUID, NULL, 1) > 0
				)
				*/
				AND 	
				(@session.Registration.Admin OR 
				 m.ugrpguid IN (SELECT grp.grupaguid FROM grupy_osob grp WHERE grp.osobaGUID=nr.Handle_UserGUID)
				)
		;
		UPDATE `t_ng_E_Wizard_Magazyny` tm
		SET 
			tm.u_przychod = 
				_GetUprawnienie(CONCAT('magazyny|', tm.IdnMagazynu, '|przychod'), tm.Handle_UserGUID),
			tm.u_rozchod =
				_GetUprawnienie(CONCAT('magazyny|', tm.IdnMagazynu, '|rozchod'), tm.Handle_UserGUID)
		;
				
		IF _Context = 'KOREKTA' THEN
			SET @upr.Korekta_z_innego_magazynu = NULL;
			/*
			TODO:
			Niech GP dorobi sprawdzenie tego uprawnienia na zmiane magazynu gdy jest to korekta
			w Delphi bylo kiedys
			
				  if (User60.GetUprawnienie('Korekta_z_innego_magazynu') > 0) and
					 (SubOper_Operacje.MA_Magzyny) and (self.TrybAutomatyczny = 0) then
				  begin
					if (cds.FieldByName('ZMagazynu').AsInteger <> 0) and Assigned(DBPlacesMagazyny) then
					  DBPlacesMagazyny.GUI_ChoiceForField(cds.FieldByName('ZMagazynu'), 'Wybierz magazyn pobrania');
					if (cds.FieldByName('DoMagazynu').AsInteger <> 0) and Assigned(DBPlacesMagazyny) then
					  DBPlacesMagazyny.GUI_ChoiceForField(cds.FieldByName('DoMagazynu'), 'Wybierz magazyn docelowy-');
				  end;
			
			*/
			SELECT 
				_GetUprawnienie('Korekta_z_innego_magazynu', nr.Handle_UserGUID)
			INTO
				@upr.Korekta_z_innego_magazynu
			FROM `ng_e_rec` nr
			WHERE
				nr.GUID = _Key
			;
			SET @upr.Korekta_z_innego_magazynu = IFNULL(@upr.Korekta_z_innego_magazynu, 0);
			
			-- SET @upr.Korekta_z_innego_magazynu = 1;
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.WP_International = 0,
				tr.WP_MagFrom = tr.WP_MagFrom AND @upr.Korekta_z_innego_magazynu > 0,
				tr.WP_MagTo = tr.WP_MagTo AND @upr.Korekta_z_innego_magazynu > 0,
				tr.WP_Kontrahent = 
					MA_Kontrahenta AND (@session.globals.Owner = 'JARZEBINSCY')
			;
			
		/*
			  if (User60.GetUprawnienie('Korekta_z_innego_magazynu') > 0) and
				 (SubOper_Operacje.MA_Magzyny) and (self.TrybAutomatyczny = 0) then
			  begin
				if (cds.FieldByName('ZMagazynu').AsInteger <> 0) and Assigned(DBPlacesMagazyny) then
				  DBPlacesMagazyny.GUI_ChoiceForField(cds.FieldByName('ZMagazynu'), 'Wybierz magazyn pobrania');
				if (cds.FieldByName('DoMagazynu').AsInteger <> 0) and Assigned(DBPlacesMagazyny) then
				  DBPlacesMagazyny.GUI_ChoiceForField(cds.FieldByName('DoMagazynu'), 'Wybierz magazyn docelowy-');
			  end;
		*/		
		
		END IF;
		
		IF _Context = 'Realizacja.ZM.cTRANS_MM_FROMZamowienia' THEN		
		/*	było po prostu
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.WP_MagFrom = FALSE,
				tr.WP_MagTo = FALSE,
				tr.WP_International = FALSE
			;
			UPDATE `ng_e_rec` nr, `t_ng_E_Wizard_Magazyny` tm
			SET 
				tm.Visible = (tm.IdnMagazynu IN (nr.i_Magazyn1_Kasa, i_Magazyn2))
			WHERE
				nr.GUID = _Key
			
			;
			ale teraz trzeba uwzgl. że że dla niektórych np. Transbud (flaga: @.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0)
			gdy MagazynWys=0 musimy mieć mozliwośc wyboru magazynu a to wiąże się z tym że musimy...
			1 tr.WP_MagFrom tr.WP_MagTo ustawić na 1
			2 pokazywac wszystkie magazyny a nie tylko te z nr.i_Magazyn1_Kasa, i_Magazyn2
			Ad.1 - pola tr.WP_MagFrom tr.WP_MagTo są juz wyżej ustawione - odblokowane!!! - wystarczy ich nie zerować
			Ad.2 - to ustawiamy poniżej
			
		*/
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.WP_MagFrom = IF(NOT @.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0, FALSE, tr.WP_MagFrom),
				tr.WP_MagTo = IF(NOT @.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0, FALSE, tr.WP_MagTo),
				tr.WP_International = FALSE
			;
			UPDATE `ng_e_rec` nr, `t_ng_E_Wizard_Magazyny` tm, `zmng` z
			SET 
				tm.Visible = 
					IF(NOT @.WIZ.Realizacja.ZM.MAG.Visible.IF.Magazyn.Wys.0, 
						(tm.IdnMagazynu IN (nr.i_Magazyn1_Kasa, i_Magazyn2)),
						(z.MagazynWys = 0)
					)
			WHERE
				nr.GUID = _Key
				AND
				IFNULL(nr.i_Input_GUID, '') != ''
				AND
				z.GUID = nr.i_Input_GUID
			;
			/*
			*/
		END IF;
		
		/*********************************************************************
		Kasy
		*********************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Kasy`;
		CREATE TEMPORARY TABLE `t_ng_E_Wizard_Kasy`
			SELECT 
				nr.Handle_UserGUID, 
				m.*,
				_VarInt(0) AS u_KP,
				_VarInt(0) AS u_KW,
				_VarInt(1) AS Visible
			FROM `kasy` m, `ng_e_rec` nr
			WHERE
				nr.GUID = _Key
		;
		UPDATE `t_ng_E_Wizard_Kasy` tk
		SET 
			tk.u_KP = 
				_GetUprawnienie(CONCAT('kasy|', tk.Idn, '|KP'), tk.Handle_UserGUID),
			tk.u_KW =
				_GetUprawnienie(CONCAT('kasy|', tk.Idn, '|KW'), tk.Handle_UserGUID)
		;
		
		/*********************************************************************
		Na koniec w rodzajach ustaw widocznosc magazynow i kas (gdy 1 rekord to zakladna niewidoczna
		*********************************************************************/
		UPDATE `t_ng_E_Wizard_Rodzaje` tr
		SET 
			tr.Ile_RodzajTyp = _VarInt(
				(SELECT COUNT(*) FROM `operdoc_typy` ot WHERE ot.Rodzaj = tr.Rodzaj AND NOT ot.Disabled AND NOT ot.Is_Instancje)
			), 
			tr.Ile_MagFrom = _VarInt(
				(SELECT COUNT(*) FROM `t_ng_E_Wizard_Magazyny` m WHERE m.Visible AND m.u_rozchod >= @uprDSInsert)
			)
		;
		UPDATE `t_ng_E_Wizard_Rodzaje` tr
		SET 
			tr.Ile_MagTo = _VarInt(
				(SELECT COUNT(*) FROM `t_ng_E_Wizard_Magazyny` m WHERE m.Visible AND m.u_przychod >= @uprDSInsert)
			),
			tr.Ile_Kasy = _VarInt(
				(
				SELECT COUNT(*) FROM `t_ng_E_Wizard_Kasy` k 
				WHERE 
					IF(tr.Rodzaj IN (@ht.CKPKP, @ht.CRKBO),
						k.u_KP >= @uprDSInsert,
						IF(tr.Rodzaj IN (@ht.CKWKW),
							k.u_KW >= @uprDSInsert,
							FALSE
						)
					)
					
				)
			
			)
		;
		UPDATE `t_ng_E_Wizard_Rodzaje` tr
		SET 
			tr.WP_RodzajTyp = IF(tr.Ile_RodzajTyp > 0, IF(tr.Ile_RodzajTyp > 1, 1, 2), 0),
			tr.WP_MagFrom = IF(tr.WP_MagFrom AND (tr.Ile_MagFrom > 0), IF(tr.Ile_MagFrom > 1, 1, 2), 0),
			tr.WP_MagTo = IF(tr.WP_MagTo AND (tr.Ile_MagTo > 0), IF(tr.Ile_MagTo > 1, 1, 2), 0),
			tr.WP_Kasy = IF(tr.WP_Kasy AND (tr.Ile_Kasy > 0), IF(tr.Ile_Kasy > 1, 1, 2), 0)
		;
-- TODO: zrobić to w operdoc - decyzja o tym, czy jest używany mag.wysyłkowy
		IF (@session.globals.Owner IN ('PARAQUA', 'IZOHAN')) THEN
			IF _Context = 'CLONE.AS.ZAM.FROM.OFERTA' THEN
				UPDATE t_ng_E_Wizard_Rodzaje SET WP_MagTo = 0;
			ELSE
				UPDATE t_ng_E_Wizard_Rodzaje SET WP_MagTo = 2 WHERE Rodzaj IN (@ht.CZMOO, @ht.CZMDD, @ht.CZMEX, @ht.CZMIM);
			END IF;
		END IF;

		--	NA KONIEC ...	
	
		IF _Context = 'Short.Paragon' THEN
			UPDATE `t_ng_E_Wizard_Rodzaje` tr
			SET 
				tr.WP_Kontrahent = FALSE,
				tr.WP_RodzajTyp = FALSE,
				tr.WP_Zalacznik = FALSE,
				tr.WP_International = FALSE,
				tr.Ile_MagFrom = 1,
				tr.Ile_MagTo = 0
			WHERE
				(tr.Rodzaj = @ht.CSpBR)
			;
		END IF;
		
	END IF; 
	
	IF _MODE = 'Clear.wizard' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Optypy`;
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Rodzaje`;
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Magazyny`;
		DROP TEMPORARY TABLE IF EXISTS `t_ng_E_Wizard_Kasy`;
	END IF; 
	
	IF _MODE = 'select.optypy' THEN
		
		IF _Context LIKE 'Realizacja.ZM.%' THEN
			SELECT 
				`to`.*
			FROM `t_ng_E_Wizard_Optypy` `to`
			WHERE
				`to`.Visible
			;
		ELSE
			SELECT 
				`to`.*
			FROM `t_ng_E_Wizard_Optypy` `to`
			WHERE
				`to`.Visible
			;
		END IF;
	END IF; 
	
	IF _MODE = 'select.rodzaje' THEN
		IF _Context IN ('REALIZUJ.WZ', 'REALIZUJ.PZ') OR
			_Context LIKE 'KANCELARIA' OR
			_Context LIKE 'KOREKTA' OR
			_Context LIKE 'Realizacja.ZM.%' OR
			_Context LIKE 'CLONE.AS.ZAM.FROM.OFERTA%' OR
			_Context = 'Short.Paragon'
			THEN
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
			;
		/*
		ELSEIF _Context LIKE 'KANCELARIA' THEN
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
			;
		ELSEIF _Context LIKE 'KOREKTA' THEN
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
			;
		ELSEIF _Context LIKE 'Realizacja.ZM.%' THEN
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
			;
		ELSEIF _Context LIKE 'CLONE.AS.ZAM.FROM.OFERTA%' THEN
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
			;
		*/
		ELSE
			SELECT 
				tr.* 
			FROM `t_ng_E_Wizard_Rodzaje` tr
			WHERE
				tr.Visible
				AND
				tr.grupa = _Param_WE
			;
		END IF; 
	END IF; 
	
	IF _MODE = 'select.rodzaje_typ' THEN
		SELECT 
			ot.* 
		FROM `t_ng_E_Wizard_Rodzaje` tr, `operdoc_typy` ot
		WHERE
			tr.Visible
			AND
			tr.Rodzaj = _Param_WE
			AND
			ot.Rodzaj = tr.Rodzaj
			AND 
			NOT ot.Disabled
			AND
			NOT ot.Is_Instancje
		;
	END IF; 
	
	IF _MODE = 'select.magazyny' THEN
		/*
		_Param_WE:
		0 zmagazynu
		1 do magazynu
		inne zawsze FALSE
		*/
		SELECT 
			m.* 
		FROM `t_ng_E_Wizard_Magazyny` m, `ng_e_rec` nr
		WHERE
			nr.GUID = _Key
			AND
			m.Visible
			AND
			/*	Mag typ	
				@ht.mtPZ = 0, 
				@ht.mtMM = 1, 
				@ht.mtRZ = 2, 
			*/	
			IF(_Param_WE = 0,
				m.u_przychod >= @uprDSInsert,
				IF(_Param_WE = 1,
					m.u_rozchod >= @uprDSInsert,
					FALSE
				)
			)
		;
	END IF; 
	
	IF _MODE = 'select.kasy' THEN
		/*
		*/
		SELECT 
			k.* 
		FROM `t_ng_E_Wizard_Kasy` k, `ng_e_rec` nr
		WHERE
			nr.GUID = _Key
			AND
			IF(nr.Rodzaj IN (@ht.CKPKP, @ht.CRKBO),
				k.u_KP >= @uprDSInsert,
				IF(nr.Rodzaj IN (@ht.CKWKW),
					k.u_KW >= @uprDSInsert,
					FALSE
				)
			)
		;
	END IF; 
	
	IF _MODE = 'select.Waluty' THEN
		SELECT 
			w.*,
			c.Name, Flag 
		FROM `waluty` w
		LEFT JOIN `geo_country` c ON c.Code = SUBSTR(w.Symbol, 1, 2)
		ORDER BY w.Idn
		;	
	END IF; 
	
	IF _MODE = 'Fill.ng_e_rec' THEN
		UPDATE `ng_e_rec` nr
		SET	
			nr.i_Calc_Ver = 4,
			nr.Rodzaj = IFNULL(
				(SELECT tr.rodzaj FROM `t_ng_E_Wizard_Rodzaje` tr WHERE tr.Visible LIMIT 1)
			, -1)		
		WHERE
			nr.GUID = _Key

		;
		UPDATE `ng_e_rec` nr, `t_ng_E_Wizard_Rodzaje` tr
		SET	
			nr.OpTyp = tr.grupa
		WHERE
			nr.GUID = _Key
			AND
			tr.Rodzaj = nr.Rodzaj
		;
	--	Mag From	
		UPDATE `ng_e_rec` nr, `t_ng_E_Wizard_Rodzaje` tr
		SET	
			nr.i_Magazyn1_Kasa = 
				IF(tr.WP_MagFrom,
					IFNULL(
						(SELECT tm.IdnMagazynu FROM `t_ng_E_Wizard_Magazyny` tm WHERE tm.Visible AND tm.u_rozchod >= @uprDSInsert LIMIT 1)
					, -1),
					0
				)
		WHERE
			nr.GUID = _Key
			AND
			tr.Rodzaj = nr.Rodzaj
		;
	--	Mag To	
		UPDATE `ng_e_rec` nr, `t_ng_E_Wizard_Rodzaje` tr
		SET	
			nr.i_Magazyn2 = 
				IF(tr.WP_MagTo,
					IFNULL(
						(SELECT tm.IdnMagazynu FROM `t_ng_E_Wizard_Magazyny` tm WHERE tm.Visible AND tm.u_przychod >= @uprDSInsert LIMIT 1)
					, -1),
					0
				)
		WHERE
			nr.GUID = _Key
			AND
			tr.Rodzaj = nr.Rodzaj
		;
		IF _Context = 'Short.Paragon' THEN
			/*
			handle_UserUgrpGUID
			r_UgrpGUID 1.
			*/
			UPDATE `ng_e_rec` nr
			SET	
				nr.handle_UserUgrpGUID = IFNULL(
					(SELECT o.UgrpGUID FROM `osoby` o WHERE o.GUID = handle_UserGUID)
				, 'ALL')
			WHERE
				nr.GUID = _Key
				AND IFNULL(nr.handle_UserUgrpGUID, '') IN ('', 'ALL')
			;
			/*
			handle_UserUgrpGUID
			r_UgrpGUID 2.
			*/
			UPDATE `ng_e_rec` nr
			SET	
				nr.handle_UserUgrpGUID = IFNULL(
					(SELECT m.UgrpGUID FROM `Magazyny` m WHERE m.IdnMagazynu = nr.i_Magazyn1_Kasa)
				, 'ALL')
			WHERE
				nr.GUID = _Key
				AND IFNULL(nr.handle_UserUgrpGUID, '') IN ('', 'ALL')
			;
			/*
			i_KontrGUID
			*/
			UPDATE `ng_e_rec` nr
			SET	
				nr.i_KontrGUID = 
					IF(_Context = 'Short.Paragon',
						CONCAT('@STZS', IF(IFNULL(nr.handle_UserUgrpGUID, '') IN ('', 'ALL'), '', nr.handle_UserUgrpGUID)),
						nr.i_KontrGUID
					)
			WHERE
				nr.GUID = _Key
			;
		END IF; -- IF _Context = 'Short.Paragon' THEN
	END IF; 
	
END$$

DROP PROCEDURE IF EXISTS `ng_E_CheckNotRepeatedNumber`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `ng_E_CheckNotRepeatedNumber`(
	IN _MODE VARCHAR(150),		-- 1 lub 0
	IN _Key VARCHAR(255),	
	IN _TableName VARCHAR(255),
	IN _NrFieldName VARCHAR(255),
	IN _DataFieldName VARCHAR(255),
	IN _Is_ZT_ZP BOOLEAN,
	IN _Year_All BOOLEAN,	--	 Year All
	INOUT _Nr_Ile INTEGER,
	IN _Param_A VARCHAR(255)	--	 dodatkowy
)
/*
	CALL ng_E_CheckNotRepeatedNumber('', _Key, 'opng', 'NrDokFin', 'DataWystaw', @_Is_ZT_ZP, FALSE, @Nr_ile, '');				
	



function TINgPoCOMSprzed.Ostrzeganie_o_powtorzeniu_nrdokfin: Boolean;
begin
  Result := true;
  if (RegistryInt.GetRegIntValueBoolean('Ostrzeganie o powtorzeniu numeru dokfin', False, 'OPNGINFOPATH')) then
  begin
    //aOT := OpTypForRdzOper(cds.FieldByName('rodzaj').AsInteger);
    if (not (OpTypForRdzOper(cds.FieldByName('rodzaj').AsInteger) in [MG])) {$IFDEF PBUCH} or
      (RdzOperOpis(cds.FieldByName('rodzaj').AsInteger) = 'PZ') {$ENDIF PBUCH} then
    begin
      if not (OpTypForRdzOper(cds.FieldByName('rodzaj').AsInteger) in [ZT, ZP]) {$IFDEF PBUCH} and
             (RdzOperOpis(cds.FieldByName('rodzaj').AsInteger) <> 'PZ') {$ENDIF PBUCH} then
        Result := CheckNotRepeatedNumber(
           'opng', 'nrdokfin',
            cds.FieldByName('nrdokfin').AsString,
            cds.FieldByName('rodzaj').AsInteger,
            cds.FieldByName('grupaoper').AsInteger,
            cds.FieldByName('GUID').AsString,
            ExtractYear(cds.FieldByName('DataWystaw').AsDateTime)
            )
      else
        Result := CheckNotRepeatedNumberZTZP(
          'opng', 'nrdokfin',
           cds.FieldByName('nrdokfin').AsString,
           cds.FieldByName('rodzaj').AsInteger,
           cds.FieldByName('grupaoper').AsInteger,
           cds.FieldByName('GUID').AsString,
           ExtractYear(cds.FieldByName('DataWystaw').AsDateTime),
            cds.FieldByName('KontrGUID').AsString);
    end;
  end;

end;


    // maks #09163 wprowadzenie dwóch rodzajów kontroli nr wewn. (ostrzeżenie, blokada zapisu)
    if (RegistryInt.GetRegIntValueBoolean('Ostrzeganie o powtorzeniu numeru wewnetrznego', False, 'OPNGINFOPATH')) then
    begin
      if not (OpTypForRdzOper(cds.FieldByName('rodzaj').AsInteger) in [ZT, ZP]) then
       {Result}aIsOk := CheckNotRepeatedNumber(
         'opng', 'nrwewn',
         cds.FieldByName('nrwewn').AsString,
         cds.FieldByName('rodzaj').AsInteger,
         cds.FieldByName('grupaoper').AsInteger,
         cds.FieldByName('GUID').AsString,
         ExtractYear(cds.FieldByName('DataWystaw').AsDateTime)
         )
      else
       {Result} aIsOk := CheckNotRepeatedNumber(
         'opng', 'nrwewn',
         cds.FieldByName('nrwewn').AsString,
         cds.FieldByName('rodzaj').AsInteger,
         cds.FieldByName('grupaoper').AsInteger,
         cds.FieldByName('GUID').AsString,
         ExtractYear(cds.FieldByName('datawplywu').AsDateTime)
         );

      if (RegistryInt.GetRegIntValueBoolean('Ostrzeganie restrykcyjne o powtorzeniu numeru wewn', True, 'OPNGINFOPATH')) then
        Result := aIsOk;
      // CheckNotRepeatedNumber wyświetla komunikat o powtórzeniu numeru  
     { else if not aIsOk then
        FormSupport.ShowMessageWar('Wprowadzony numer wewnętrzny już istnieje'); }
    end; // 'Ostrzeganie o powtorzeniu numeru wewnetrznego'
//end slon
    if not Result then exit;

    {maks #13933 - Ostrzeżenie o powtórzeniu numeru dokumentu magazynowego }
    if (RegistryInt.GetRegIntValueBoolean('Ostrzeganie o powtorzeniu numeru magazynowego', False, 'OPNGINFOPATH')) then
    begin
      {$IFDEF CDG}
      if (cds.FieldByName('Rodzaj').AsInteger <> CZkFV) then
        exit;
      {$ENDIF CDG}
      Result := CheckNotRepeatedNumberAllYears('opng', 'nrdokmag', cds.FieldByName('nrdokmag').AsString,
         cds.FieldByName('rodzaj').AsInteger,
         cds.FieldByName('GUID').AsString);
    end;
    if not Result then exit;
	
	
	
  cCheckNumberSQL = 'SELECT COUNT(*) as ile FROM %s 
    'WHERE %s =''%s'' AND deleted = 0 AND   // 03.06.2013 wylaczamy ogolny warunek na grupeoper: AND grupaoper = %d '+ // #032360 wlaczamy warunek na grupe operacji (w miejsce wyłaczonego warunku na rodzaj)
    {$IFDEF KONTROLA_NUMERACJI_ZTZP}  // 03.06.2013 na razie dajemy to dla Crista, ale docelowo prawdopodobnie dla wszystkich:
    ' IF(%d IN (1, 4), grupaoper IN (1, 4), rodzaj = %d)    // 1 = ZT, 4 = ZP
    {$ELSE}
    ' rodzaj = %d 
    {$ENDIF KONTROLA_NUMERACJI_ZTZP}
    'AND GUID <> ''%s'' AND Year(DataWystaw)=%d;
	
	
	
function TINgPoCOMSprzed.CheckNotRepeatedNumber(aTable, aName, aNumber: String;
  aRodzaj, aGrupaOper : Integer; aGUID: String; aRok: Integer): Boolean;
var
  aC : Integer;
  VSQL, aRodz : String;
begin
    Result := True;
    if (aNumber = '') or (aNumber = 'LOCKED') then exit;
    aC := 0;
    VSQL := Format(cCheckNumberSQL, // AND rodzaj=%d  - bylo ale wywalone 2013-04-17 #032360 28-05-2013: zamiast tego dajemy warunek na "grupaoper"
            [aTable, aName, aNumber, {$IFDEF KONTROLA_NUMERACJI_ZTZP} aGrupaOper, {$ENDIF} aRodzaj,  aGUID, aRok]);
    if not ConnectSupport.GetQueryInteger(VSQL, 'ile', nil, aC) then exit;
    if (aC > 0) then
    begin
      Result := False;
      if aName = 'nrdokfin' then
        aRodz := 'finansowy'
      else
        aRodz := '';
      if EditorMode then
        FormSupport.ShowMessage(Format('Dokument %s o numerze "%s" już istnieje', [aRodz, aNumber]));
    end
end;

function TINgPoCOMSprzed.CheckNotRepeatedNumberZTZP(aTable, aName, aNumber: String;
  aRodzaj, aGrupaOper : Integer; aGUID: String; aRok: Integer; aKontrGUID: String): Boolean;
var
  aC : Integer;
  VSQL, aRodz : String;
begin
    Result := True;
    if (aNumber = '') or (aNumber = 'LOCKED') then exit;
    aC := 0;
    VSQL := cCheckNumberSQL + ' and KontrGUID = ''%s'' ';
    VSQL := Format(VSQL, ///  AND rodzaj=%d  - bylo ale wywalone 2013-04-17  #032360 28-05-2013: zamiast tego dajemy warunek na "grupaoper"
            [aTable, aName, aNumber, {$IFDEF KONTROLA_NUMERACJI_ZTZP} aGrupaOper, {$ENDIF} aRodzaj, aGUID, aRok, aKontrGUID]);
    if not ConnectSupport.GetQueryInteger(VSQL, 'ile', nil, aC) then exit;
    if (aC > 0) then
    begin
      Result := True;
      if aName = 'nrdokfin' then
        aRodz := 'finansowy'
      else
        aRodz := '';
      if EditorMode then
      begin
        Result := FormSupport.Ask(Format('Dokument %s o numerze "%s" już istnieje. Czy na pewno zapisać dokument ?', [aRodz, aNumber]));
        if Result and Assigned(ShellLog) then
        // dajemy info do loga, że zarejestrowano dokument o istniejącym już numerze
        begin
          ShellLog.AddToLogS(Self.SysId, CLOG_M_Apply, aGUID,
            'Zapisanie dokumentu ze zdublowanym numerem (po akceptacji użytkownika)');
        end;
      end;
    end
end;

function TINgPoCOMSprzed.CheckNotRepeatedNumberAllYears(aTable, aName,
  aNumber: String; aRodzaj: Integer; aGUID: String): Boolean;
var
  ac : Integer;
  VSQL : String;
begin
    Result := True;
    if (aNumber = '') or (aNumber = 'LOCKED') then exit;
    aC := 0;
    VSQL := Format('SELECT COUNT(*) as ile FROM %s WHERE %s =''%s'' AND deleted = 0 AND rodzaj=%d AND GUID<>''%s'' ',
            [aTable, aName, aNumber, aRodzaj, aGUID]);
    if not ConnectSupport.GetQueryInteger(VSQL, 'ile', nil, aC) then exit;
    if (aC > 0) then
    begin
    {$IFDEF PBUCH}
      Result := False;
      if EditorMode then
        FormSupport.ShowMessageWar(Format('Dokument magazynowy o numerze "%s" już istnieje',[aNumber]));
    {$ELSE}
      Result := True;
      if EditorMode then
        Result := FormSupport.Ask(Format('Dokument magazynowy o numerze "%s" już istnieje. Czy napewno zapisać dokument ?',[aNumber]));
    {$ENDIF}
    end
end;	

*/


S_ng_E_CheckNotRepeatedNumber: BEGIN 
	DECLARE _SQLText TEXT;
		SET 
			_Param_A = IFNULL(_Param_A, ''),
			_Nr_Ile = 0
		;
		IF (_Param_A LIKE '***%***') OR (_Param_A LIKE '%TYMCZAS%') THEN
		--	Takie numeru nie sprawdzaj
			LEAVE S_ng_E_CheckNotRepeatedNumber;
		END IF;
		SET 
			@Nr_Ile = NULL,
			_SQLText = 
			"
				SELECT
					COUNT(*) AS ILE
				INTO @Nr_Ile
				FROM `#table#` n, `#table#_e` ne
				WHERE
					ne.GUID = '#_Key#'
					AND IFNULL(#IN_Number#, '') != ''
					AND n.GUID <> ne.GUID 
					AND n.#FN_Number# = #IN_Number#
					AND #Year#
					AND #KontrGUID#
					AND n.deleted = 0 
					AND #GrupaOper# 
				;
			"
		;
		SET _SQLText = REPLACE(_SQLText, '#table#', _VarStr(_TableName));
		SET _SQLText = REPLACE(_SQLText, '#_Key#', _VarStr(_Key));
		SET _SQLText = REPLACE(_SQLText, '#IN_Number#', _VarStr(IF(NOT @session.globals.HT.erp_obj_counters_values_e_1_rec, 'ne.#FN_Number#', QUOTE(_Param_A))));
		SET _SQLText = REPLACE(_SQLText, '#FN_Number#', _VarStr(_NrFieldName));
		SET _SQLText = REPLACE(_SQLText, '#Year#', IF(_Year_All, 'TRUE', 'Year(n.#DataWystaw#) = Year(ne.#DataWystaw#)'));
		SET _SQLText = REPLACE(_SQLText, '#DataWystaw#', _DataFieldName);
	--	było
		-- SET _SQLText = REPLACE(_SQLText, '#GrupaOper#', IF(@session.globals.Owner != 'CRIST', 'n.rodzaj = ne.rodzaj', 'IF(ne.GrupaOper IN (1, 4), n.grupaoper IN (1, 4), n.rodzaj = ne.rodzaj)'));
	--	jest -> jmam + apro : warunek CRISTA jest uniwaersalny (zakupy brać wszystkie po uwage) 	
		SET _SQLText = REPLACE(_SQLText, '#GrupaOper#', 'IF(ne.GrupaOper IN (1, 4), n.grupaoper IN (1, 4), n.rodzaj = ne.rodzaj)');
		SET _SQLText = REPLACE(_SQLText, '#KontrGUID#', IF(NOT _Is_ZT_ZP, 'TRUE', 'n.KontrGUID = ne.KontrGUID'));
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		SET _Nr_Ile = IFNULL(@Nr_Ile, 0);

END$$

DROP PROCEDURE IF EXISTS `ng_E_InsertNumbers`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `ng_E_InsertNumbers`(
	IN _MODE VARCHAR(150),		-- 1 lub 0
	IN _handle_FROM VARCHAR(250),	-- OP lub ZM ...?
	IN _Key VARCHAR(38),
	IN _Nr_1 VARCHAR(255),
	IN _Nr_2 VARCHAR(255),
	IN _Nr_3 VARCHAR(255),
	IN _Param_A VARCHAR(255)	--	 dodatkowy
)
BEGIN 
	DECLARE _SQLText TEXT;
	
	IF _handle_FROM = 'OP' THEN
	/* *************************************************************************************************************************************************************
		CALL ng_E_InsertNumbers('', 'OP', 'sss', 'N1', 'N2', 'N3', '');
		IDN zdarzenia
	**************************************************************************************************************************************************************/
		
		UPDATE `opng_e` n
		SET
			n.nrdokfin = IFNULL(_Nr_1, n.nrdokfin), 
			n.nrwewn = IFNULL(_Nr_2, n.nrwewn), 
			n.nrdokmag = IFNULL(_Nr_3, n.nrdokmag)
		WHERE
			n.GUID = _Key
		;
		SET @NEW.counter = '', @NEW.counter2 = '';
		SELECT 
			ot.counter,
			ot2.counter
		INTO @NEW.counter, @NEW.counter2
		FROM `opng_e` n
		LEFT JOIN `operdoc_typy` ot ON ot.Rodzaj = n.Rodzaj AND ot.Typ = n.rodzaj_typ 
		INNER JOIN `operdoc_typy` ot2 ON ot2.Rodzaj = n.Rodzaj AND ot2.Typ = 0
		WHERE 
			n.GUID = _Key
		;
		SET @NEW.counter = IF(IFNULL(@NEW.counter, '') = '', @NEW.counter2, @NEW.counter);
		SET @NEW.Is_Obj_Counters = (@NEW.counter = 'OBJ_COUNTERS');
		
		IF @NEW.Is_Obj_Counters THEN
		--	Nowa numeracja
			IF _Nr_1 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, 'opng.nrdokfin', _Nr_1
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_1
				;			
			END IF;
			IF _Nr_2 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, 'opng.nrwewn', _Nr_2
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_2
				;			
			END IF;
			IF _Nr_3 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, 'opng.nrdokmag', _Nr_3
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_3
				;			
			END IF;
		END IF;
		
	END IF;

	IF _handle_FROM = 'ZM' THEN
	/* *************************************************************************************************************************************************************
		CALL ng_E_InsertNumbers('', 'ZM', 'sss', 'N1', 'N2', 'N3', '');
		IDN zdarzenia
	**************************************************************************************************************************************************************/
		
		UPDATE `zmng_e` n
		SET
			n.nrzamw = IFNULL(_Nr_1, n.nrzamw)
		WHERE
			n.GUID = _Key
		;
		SET @NEW.counter = '', @NEW.counter2 = '';
		SELECT 
			ot.counter,
			ot2.counter
		INTO @NEW.counter, @NEW.counter2
		FROM `zmng_e` n
		LEFT JOIN `operdoc_typy` ot ON ot.Rodzaj = n.Rodzaj AND ot.Typ = n.rodzaj_typ 
		INNER JOIN `operdoc_typy` ot2 ON ot2.Rodzaj = n.Rodzaj AND ot2.Typ = 0
		WHERE 
			n.GUID = _Key
		;
		SET @NEW.counter = IF(IFNULL(@NEW.counter, '') = '', @NEW.counter2, @NEW.counter);
		SET @NEW.Is_Obj_Counters = (@NEW.counter = 'OBJ_COUNTERS');
		
		IF @NEW.Is_Obj_Counters THEN
		--	Nowa numeracja
			IF _Nr_1 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, 'zmng.nrzamw', _Nr_1
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_1
				;			
			END IF;
			/*
			IF _Nr_2 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, '????', _Nr_2
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_2
				;			
			END IF;
			IF _Nr_3 IS NOT NULL THEN
				INSERT IGNORE INTO `erp_obj_counters_values` 
				(ID, ObjType, Number_Text)
				SELECT
					_Key, '????', _Nr_3
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _Nr_3
				;			
			END IF;
			*/
		END IF;
		
	END IF;
	
END$$

DROP PROCEDURE IF EXISTS `erp_obj_counters_values_e_1_rec_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_values_e_1_rec_tools`(
	IN _MODE VARCHAR(150),		-- 1 lub 0
	IN _handle_FROM VARCHAR(250),	-- OP lub ZM ...?
	IN _Key VARCHAR(38),
	IN _Nr_1 VARCHAR(255),	
	IN _Nr_2 VARCHAR(255),
	IN _Nr_3 VARCHAR(255),
	IN _Param_A VARCHAR(255)	--	 dodatkowy
)
BEGIN 
	DECLARE _SQLText MEDIUMTEXT;

	IF _MODE = 'INIT.from.e.SET.@' THEN
		SET @NEW.counter = '', @NEW.counter2 = '';
		IF _handle_FROM = 'OP' THEN
			SELECT 
				ot.counter,
				ot2.counter,
				IFNULL(ot.Rodzaj, ot2.Rodzaj) AS Rodzaj,
				IFNULL(ot.Typ, ot2.Typ) AS PodRodzaj
			INTO
				@NEW.counter, @NEW.counter2,
				@NEW.Rodzaj, @NEW.PodRodzaj
			FROM `opng_e` n
			LEFT JOIN `operdoc_typy` ot ON ot.Rodzaj = n.Rodzaj AND ot.Typ = n.rodzaj_typ 
			INNER JOIN `operdoc_typy` ot2 ON ot2.Rodzaj = n.Rodzaj AND ot2.Typ = 0
			WHERE 
				n.GUID = _Key
			;
		ELSEIF _handle_FROM = 'ZM' THEN
			SELECT 
				ot.counter,
				ot2.counter,
				IFNULL(ot.Rodzaj, ot2.Rodzaj) AS Rodzaj,
				IFNULL(ot.Typ, ot2.Typ) AS PodRodzaj
			INTO
				@NEW.counter, @NEW.counter2,
				@NEW.Rodzaj, @NEW.PodRodzaj
			FROM `zmng_e` n
			LEFT JOIN `operdoc_typy` ot ON ot.Rodzaj = n.Rodzaj AND ot.Typ = n.rodzaj_typ 
			INNER JOIN `operdoc_typy` ot2 ON ot2.Rodzaj = n.Rodzaj AND ot2.Typ = 0
			WHERE 
				n.GUID = _Key
			;
		END IF;
		
		SET @NEW.counter = IF(IFNULL(@NEW.counter, '') = '', @NEW.counter2, @NEW.counter);
		SET @NEW.Is_Obj_Counters = (@NEW.counter = 'OBJ_COUNTERS');

	END IF;
	
	IF _MODE = 'INIT.from.e' THEN
		/* *************************************************************************************************************************************************************
			4. pobranie info o crm
			CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', 'OP', '_Key', '', '', '', '');
			CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', 'ZM', '_Key', '', '', '', '');
			IDN zdarzenia
		**************************************************************************************************************************************************************/
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e.SET.@', _handle_FROM, _Key, '', '', '', '');
		-- mam juz @NEW.Rodzaj, @NEW.PodRodzaj
set @A = "po CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e.SET.@', _handle_FROM, _Key, '', '', '', '');"		;
		INSERT IGNORE INTO `erp_obj_counters_values_e_1_rec`
		(ID, Is_Obj_Counters, Update_Mode)
		VALUES
		(_Key, @NEW.Is_Obj_Counters, 'INIT')
		ON DUPLICATE KEY
		UPDATE
			Update_Mode = 'INIT'
		;
set @A = "po INSERT IGNORE INTO `erp_obj_counters_values_e_1_rec`;";		

		DROP TEMPORARY TABLE IF EXISTS `t_erp_obj_counters_values_e_1_rec`;
		SET @LP = 0;
		
		IF @NEW.counter = 'NUMDOK' THEN
		/*
			Stara numeracja
		*/
			IF _handle_FROM = 'OP' THEN
			--	OPERACJE
				CREATE TEMPORARY TABLE `t_erp_obj_counters_values_e_1_rec`
				SELECT
					_VarInt(0) AS LP, 
					d.ObjType, d.Descr,
					IF(d.ObjType = 'opng.nrdokfin', n.Nrdokfin, 
						IF(d.ObjType = 'opng.nrwewn', n.nrwewn, 
						  IF(d.ObjType = 'opng.nrdokmag', n.nrdokmag, NULL)
						) 
					) AS Number_Text,		
					m.GUI_Ctrl_option,
					m.LP AS m_LP
				FROM `opng_e` n
				INNER JOIN `erp_obj_counters_masks` m ON m.Rodzaj = @NEW.Rodzaj AND m.PodRodzaj = @NEW.PodRodzaj
				INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m.ObjType
				-- INNER JOIN `opng` v ON v.GUID = @IdnOper
				WHERE
					n.GUID = _Key
					AND d.ObjType IN ('opng.nrdokfin', 'opng.nrwewn', 'opng.nrdokmag')
				ORDER BY 
					m_LP
					/*
					IF(d.ObjType = 'opng.nrdokfin', 0, 
						IF(d.ObjType = 'opng.nrwewn', 1, 
						  IF(d.ObjType = 'opng.nrdokmag', 2, 3)
						) 
					)		
					*/
				; 
			ELSEIF _handle_FROM = 'ZM' THEN
			--	ZAM
				CREATE TEMPORARY TABLE `t_erp_obj_counters_values_e_1_rec`
				SELECT
					_VarInt(0) AS LP, 
					d.ObjType, d.Descr,
					IF(d.ObjType = 'zmng.nrzamw', n.nrzamw, NULL)
						 
					AS Number_Text,		
					m.GUI_Ctrl_option,
					m.LP AS m_LP
				FROM `zmng_e` n
				INNER JOIN `erp_obj_counters_masks` m ON m.Rodzaj = @NEW.Rodzaj AND m.PodRodzaj = @NEW.PodRodzaj
				INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m.ObjType
				-- INNER JOIN `opng` v ON v.GUID = @IdnOper
				WHERE
					n.GUID = _Key
					AND d.ObjType IN ('zmng.nrzamw')
				ORDER BY 
					m_LP
					/*
					IF(d.ObjType = 'opng.nrdokfin', 0, 
						IF(d.ObjType = 'opng.nrwewn', 1, 
						  IF(d.ObjType = 'opng.nrdokmag', 2, 3)
						) 
					)		
					*/
				; 
			END IF;
		ELSE
		/*
			Nowa numeracja czyli @NEW.counter IN ('OBJ_COUNTERS_VALUES', 'OBJ_COUNTERS')
			'OBJ_COUNTERS'			Nowa ale oparta nadal na polach wewnetrznych (nrdokfin, nrdokmag etc)
			'OBJ_COUNTERS_VALUES'	Nowa oparta wylacznie na `erp_obj_counters_values` PRZYSZLOSC
		*/
			CREATE TEMPORARY TABLE `t_erp_obj_counters_values_e_1_rec`
			SELECT
				_VarInt(0) AS LP, 
				d.ObjType, d.Descr,
				v.Number_Text,
				m.GUI_Ctrl_option,
				m.LP AS m_LP
			FROM `erp_obj_counters_masks` m 
			INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m.ObjType
			LEFT JOIN `erp_obj_counters_values` v ON v.ID = _Key AND v.ObjType = m.ObjType
			WHERE
				m.Rodzaj = @NEW.Rodzaj AND m.PodRodzaj = @NEW.PodRodzaj
			ORDER BY 
				m_LP
				/*
				IF(d.ObjType = 'opng.nrdokfin', 0, 
					IF(d.ObjType = 'opng.nrwewn', 1, 
					  IF(d.ObjType = 'opng.nrdokmag', 2, 
						IF(d.ObjType = 'zmng.nrzamw', 3, 4)
						)
					) 
				)
				*/
			; 
			DELETE FROM `t_erp_obj_counters_values_e_1_rec` WHERE GUI_Ctrl_option = '';
			
			IF @NEW.counter = 'OBJ_COUNTERS' THEN
			--	Nowa ale oparta nadal na polach wewnetrznych (nrdokfin, nrdokmag etc)
			--	1.	Pobierz z pol wewnetrznych (nrdokfin, nrdokmag etc)
			
				IF _handle_FROM = 'OP' THEN
					UPDATE `t_erp_obj_counters_values_e_1_rec` v, `opng_e` n
					SET
						Number_Text = 
							IF(v.ObjType = 'opng.nrdokfin', n.Nrdokfin, 
								IF(v.ObjType = 'opng.nrwewn', n.nrwewn, 
									IF(v.ObjType = 'opng.nrdokmag', n.nrdokmag, 
										IF(v.ObjType = 'opng.lp_ks_podawcza_str', n.lp_ks_podawcza_str, 
											NULL
										)
									)
								) 
							)
					WHERE
						n.GUID = _Key
					;
				ELSEIF _handle_FROM = 'ZM' THEN
					UPDATE `t_erp_obj_counters_values_e_1_rec` v, `zmng_e` n
					SET
						Number_Text = 
							IF(v.ObjType = 'zmng.nrzamw', 
								n.nrzamw, 
								NULL
							)
					WHERE
						n.GUID = _Key
					;
				END IF;
			--	2.	Utworz odpowiedniki w `erp_obj_counters_values` BO MOZE ICH NIE BYC
				INSERT IGNORE INTO `erp_obj_counters_values`
				(ObjType, ID, Number_Text)
				SELECT
					r.ObjType, _Key, r.Number_Text
				FROM `t_erp_obj_counters_values_e_1_rec` r
				;
			END IF;
			
		END IF;
		
		SET @LP = 0;
		UPDATE `t_erp_obj_counters_values_e_1_rec`
		SET
			LP = @LP := @LP + 1
		ORDER BY m_LP
		;
		
		SELECT
			GROUP_CONCAT(IF(t.LP = 1, t.ObjType, NULL)) AS ObjType_1,
			GROUP_CONCAT(IF(t.LP = 1, t.Descr, NULL)) AS Label_1,
			GROUP_CONCAT(IF(t.LP = 1, t.Number_Text, NULL)) AS Number_Text_1,
			GROUP_CONCAT(IF(t.LP = 1, t.GUI_Ctrl_option, NULL)) AS GUI_Ctrl_option_1,
			GROUP_CONCAT(IF(t.LP = 2, t.ObjType, NULL)) AS ObjType_2,
			GROUP_CONCAT(IF(t.LP = 2, t.Descr, NULL)) AS Label_2,
			GROUP_CONCAT(IF(t.LP = 2, t.Number_Text, NULL)) AS Number_Text_2,
			GROUP_CONCAT(IF(t.LP = 2, t.GUI_Ctrl_option, NULL)) AS GUI_Ctrl_option_2,
			GROUP_CONCAT(IF(t.LP = 3, t.ObjType, NULL)) AS ObjType_3,
			GROUP_CONCAT(IF(t.LP = 3, t.Descr, NULL)) AS Label_3,
			GROUP_CONCAT(IF(t.LP = 3, t.Number_Text, NULL)) AS Number_Text_3,
			GROUP_CONCAT(IF(t.LP = 3, t.GUI_Ctrl_option, NULL)) AS GUI_Ctrl_option_3,
			GROUP_CONCAT(IF(t.LP = 4, t.ObjType, NULL)) AS ObjType_4,
			GROUP_CONCAT(IF(t.LP = 4, t.Descr, NULL)) AS Label_4,
			GROUP_CONCAT(IF(t.LP = 4, t.Number_Text, NULL)) AS Number_Text_4,
			GROUP_CONCAT(IF(t.LP = 4, t.GUI_Ctrl_option, NULL)) AS GUI_Ctrl_option_4,
			GROUP_CONCAT(IF(t.LP = 5, t.ObjType, NULL)) AS ObjType_5,
			GROUP_CONCAT(IF(t.LP = 5, t.Descr, NULL)) AS Label_5,
			GROUP_CONCAT(IF(t.LP = 5, t.Number_Text, NULL)) AS Number_Text_5,
			GROUP_CONCAT(IF(t.LP = 5, t.GUI_Ctrl_option, NULL)) AS GUI_Ctrl_option_5
		INTO
			@NEW.ObjType_1, @NEW.Label_1, @NEW.Number_Text_1, @NEW.GUI_Ctrl_option_1,
			@NEW.ObjType_2, @NEW.Label_2, @NEW.Number_Text_2, @NEW.GUI_Ctrl_option_2,
			@NEW.ObjType_3, @NEW.Label_3, @NEW.Number_Text_3, @NEW.GUI_Ctrl_option_3,
			@NEW.ObjType_4, @NEW.Label_4, @NEW.Number_Text_4, @NEW.GUI_Ctrl_option_4,
			@NEW.ObjType_5, @NEW.Label_5, @NEW.Number_Text_5, @NEW.GUI_Ctrl_option_5
		FROM `t_erp_obj_counters_values_e_1_rec` t
		ORDER BY m_LP
		; 
		UPDATE `erp_obj_counters_values_e_1_rec` aNEW
		SET
			aNEW.ObjType_1 = @NEW.ObjType_1, aNEW.Label_1 = IFNULL(@NEW.Label_1, ''), aNEW.Number_Text_1 = IFNULL(@NEW.Number_Text_1, ''), aNEW.GUI_Ctrl_option_1 = IFNULL(@NEW.GUI_Ctrl_option_1, ''),  
			aNEW.ObjType_2 = @NEW.ObjType_2, aNEW.Label_2 = IFNULL(@NEW.Label_2, ''), aNEW.Number_Text_2 = IFNULL(@NEW.Number_Text_2, ''), aNEW.GUI_Ctrl_option_2 = IFNULL(@NEW.GUI_Ctrl_option_2, ''), 
			aNEW.ObjType_3 = @NEW.ObjType_3, aNEW.Label_3 = IFNULL(@NEW.Label_3, ''), aNEW.Number_Text_3 = IFNULL(@NEW.Number_Text_3, ''), aNEW.GUI_Ctrl_option_3 = IFNULL(@NEW.GUI_Ctrl_option_3, ''),
			aNEW.ObjType_4 = @NEW.ObjType_4, aNEW.Label_4 = IFNULL(@NEW.Label_4, ''), aNEW.Number_Text_4 = IFNULL(@NEW.Number_Text_4, ''), aNEW.GUI_Ctrl_option_4 = IFNULL(@NEW.GUI_Ctrl_option_4, ''),
			aNEW.ObjType_5 = @NEW.ObjType_5, aNEW.Label_5 = IFNULL(@NEW.Label_5, ''), aNEW.Number_Text_5 = IFNULL(@NEW.Number_Text_5, ''), aNEW.GUI_Ctrl_option_5 = IFNULL(@NEW.GUI_Ctrl_option_5, '') 
		WHERE 
			aNEW.ID = _Key
		;
			
	END IF; --	_MODE = 'INIT.from.e' 
	
	IF _MODE = 'DELETE.from.e' THEN
		/* *************************************************************************************************************************************************************
			Usuwanie
			CALL erp_obj_counters_values_e_1_rec_tools('DELETE.from.e', 'OP', @IdnOper, '', '', '', '');
		**************************************************************************************************************************************************************/
		DELETE FROM `erp_obj_counters_values_e_1_rec` WHERE ID = _Key;	
	END IF; --	_MODE = 'DELETE.from.e' 

	/*
	IF _MODE = 'APPLY.from.e' THEN */
		/* *************************************************************************************************************************************************************
			Zapis do `erp_obj_counters_values` lub `opng_e`
			CALL erp_obj_counters_values_e_1_rec_tools('APPLY.from.e', 'OP', @IdnOper, '', '', '', '');
		**************************************************************************************************************************************************************/
	/*
		UPDATE `erp_obj_counters_values_e_1_rec` r1
		SET
			r1.Update_Mode = 'LetAPPLY'
		WHERE
			ID = _Key
		;
		po co to ponizej
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', 'OP', _Key, '', '', '', '');
		
	END IF; --	_MODE = 'APPLY.from.e' 
	*/
	IF _MODE = 'Set.semi.auto.number' THEN
		/* *************************************************************************************************************************************************************
			Zapis do `erp_obj_counters_values` lub `opng_e`
			CALL erp_obj_counters_values_e_1_rec_tools('Set.semi.auto.number', 'OP', @IdnOper, '', '', '', '');
			IN _Nr_1 	Numer kontrolki
			IN _Nr_2 	Rodzaj
			IN _Nr_3 	Podrodzaj
			IN _Param_A VARCHAR(255)	--	 dodatkowy
		**************************************************************************************************************************************************************/
		UPDATE `erp_obj_counters_values_e_1_rec` r1
		SET
			r1.Update_Mode = CONCAT('BEFORE.', _MODE, '.', _handle_FROM)	--	 'Set.semi.auto.number.OP'
		WHERE
			r1.ID = _Key
		;
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e.SET.@', _handle_FROM, _Key, '', '', '', '');
		-- mam juz @NEW.Rodzaj, @NEW.PodRodzaj
		SET _SQLText = 
		"SELECT r.ObjType_#ObjType_# FROM `erp_obj_counters_values_e_1_rec` r WHERE ID = '#_ID#' INTO @ObjType;"
		;
		SET _SQLText = REPLACE(REPLACE(_SQLText, '#ObjType_#', _Nr_1), '#_ID#', _Key);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		-- IF(_handle_FROM = 'OP', 'opng_e', 'zmng_e')
		-- JUZ NIE CALL erp_obj_counters_values_SetNumber('prepare.t_erp_obj_counters_inputs', @_Numer, @_NumerText, @ObjType, @NEW.Rodzaj, @NEW.PodRodzaj, _Key, IF(_handle_FROM = 'OP', 'opng_e', 'zmng_e'), '', 'clear.before');
		CALL erp_obj_counters_values_tools('EXECUTE', @ObjType, @NEW.Rodzaj, @NEW.PodRodzaj, _Key, IF(_handle_FROM = 'OP', 'opng_e', 'zmng_e'), 'clear.before;ManualNum', '', '');		
		
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', _handle_FROM, _Key, '', '', '', '');
		
	END IF; --	_MODE = 'Set.semi.auto.number' 
	
	IF _MODE = 'Set.auto.number' THEN
		/* *************************************************************************************************************************************************************
			Zapis do `erp_obj_counters_values` lub `opng_e`
			CALL erp_obj_counters_values_e_1_rec_tools('Set.auto.number', 'OP', @IdnOper, '', '', '', '');
			CALL erp_obj_counters_values_e_1_rec_tools('Set.auto.number', 'ZM', @IdnOper, '', '', '', '');
		**************************************************************************************************************************************************************/
		UPDATE `erp_obj_counters_values_e_1_rec` r1
		SET
			r1.Update_Mode = CONCAT('BEFORE.', _MODE, '.', _handle_FROM)	--	 'Set.auto.number.OP'
		WHERE
			r1.ID = _Key
		;
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e.SET.@', _handle_FROM, _Key, '', '', '', '');
		-- mam juz @NEW.Rodzaj, @NEW.PodRodzaj
		-- JUZ NIE CALL erp_obj_counters_values_SetNumber('prepare.t_erp_obj_counters_inputs', @_Numer, @_NumerText, 'opng.', @NEW.Rodzaj, @NEW.PodRodzaj, _Key, IF(_handle_FROM = 'OP', 'opng_e', 'zmng_e'), '', '');
set @coto = 'aa';		

		CALL erp_obj_counters_values_tools('EXECUTE', IF(_handle_FROM = 'OP', 'opng.', 'zmng.'), @NEW.Rodzaj, @NEW.PodRodzaj, _Key, IF(_handle_FROM = 'OP', 'opng_e', 'zmng_e'), '', '', '');
		
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e', _handle_FROM, _Key, '', '', '', '');
		
	END IF; --	_MODE = 'Set.semi.auto.number' 
	
	
	IF _MODE = 'ng_E_InsertNumbers' THEN
		CALL erp_obj_counters_values_e_1_rec_tools('INIT.from.e.SET.@', _handle_FROM, _Key, '', '', '', '');
		-- mam juz @NEW.counter, @NEW.counter2, @NEW.Rodzaj, @NEW.PodRodzaj
		
		IF _handle_FROM = 'OP' THEN
		/* *************************************************************************************************************************************************************
			CALL erp_obj_counters_values_e_1_rec_tools('ng_E_InsertNumbers', 'OP', @IdnOper,  'N1', 'N2', 'N3', '');
		**************************************************************************************************************************************************************/
			
			UPDATE `opng_e` n
			SET
				n.nrdokfin = IFNULL(_Nr_1, n.nrdokfin), 
				n.nrwewn = IFNULL(_Nr_2, n.nrwewn), 
				n.nrdokmag = IFNULL(_Nr_3, n.nrdokmag)
			WHERE
				n.GUID = _Key
			;
			
			IF @NEW.Is_Obj_Counters THEN
			--	Nowa numeracja
				IF _Nr_1 IS NOT NULL THEN
					INSERT IGNORE INTO `erp_obj_counters_values` 
					(ID, ObjType, Number_Text)
					SELECT
						_Key, 'opng.nrdokfin', _Nr_1
					ON DUPLICATE KEY
					UPDATE
						Number_Text = _Nr_1
					;			
				END IF;
				IF _Nr_2 IS NOT NULL THEN
					INSERT IGNORE INTO `erp_obj_counters_values` 
					(ID, ObjType, Number_Text)
					SELECT
						_Key, 'opng.nrwewn', _Nr_2
					ON DUPLICATE KEY
					UPDATE
						Number_Text = _Nr_2
					;			
				END IF;
				IF _Nr_3 IS NOT NULL THEN
					INSERT IGNORE INTO `erp_obj_counters_values` 
					(ID, ObjType, Number_Text)
					SELECT
						_Key, 'opng.nrdokmag', _Nr_3
					ON DUPLICATE KEY
					UPDATE
						Number_Text = _Nr_3
					;			
				END IF;
			END IF;
			
		END IF;

		IF _handle_FROM = 'ZM' THEN
		/* *************************************************************************************************************************************************************
			CALL erp_obj_counters_values_e_1_rec_tools('ng_E_InsertNumbers', 'ZM', @IdnOper,  'N1', 'N2', 'N3', '');
		**************************************************************************************************************************************************************/
			
			UPDATE `zmng_e` n
			SET
				n.nrzamw = IFNULL(_Nr_1, n.nrzamw)
			WHERE
				n.GUID = _Key
			;
			
			IF @NEW.Is_Obj_Counters THEN
			--	Nowa numeracja
				IF _Nr_1 IS NOT NULL THEN
					INSERT IGNORE INTO `erp_obj_counters_values` 
					(ID, ObjType, Number_Text)
					SELECT
						_Key, 'zmng.nrzamw', _Nr_1
					ON DUPLICATE KEY
					UPDATE
						Number_Text = _Nr_1
					;			
				END IF;
			END IF;
			
		END IF;

	END IF;
	
END$$












DROP PROCEDURE IF EXISTS `_ng_E_LetApply_2`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_LetApply_2`(
	IN _MODE VARCHAR(250),	 
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
S_ng_E_LetApply: BEGIN 
	SET @.C_HT_ng_e.Process = 'WEJ';
	IF _handle_FROM = 'OP' THEN
		IF NOT EXISTS (SELECT GUID FROM `opng_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	ELSEIF _handle_FROM = 'ZM' THEN
		IF NOT EXISTS (SELECT GUID FROM `zmng_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	ELSEIF _handle_FROM = 'R' THEN
		IF NOT EXISTS (SELECT GUID FROM `opng_r_e` WHERE GUID = _Key) THEN
			LEAVE S_ng_E_LetApply;
		END IF;
	END IF;
	
	
--	Uwaga zmienna @_ng_E_LetPost.DONE okresla czy byl POST czyli _ng_E_LetPost. Gdy  @_ng_E_LetPost.DONE IS NULL to przyjmujemy @_ng_E_LetPost.DONE = FALSE
CALL _WatchTimeLogs_Tools('start', "APPLY", "POST", '', '', '');
	IF NOT IFNULL(@_ng_E_LetPost.DONE, FALSE) THEN
		CALL _OP_ET_Let('POST', '', '', _handle_FROM, _Key, '', '', '', '', '');
	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "POST", '', '', '');
	
	
CALL _WatchTimeLogs_Tools('start', "APPLY", "EXEPTION", '', '', '');
	SET @.C_HT_ng_e.Process = CONCAT('APPLY po: ', @handle_oper, ': `#ng_e#`');
	SET @.C_HT_ng_e.Process = REPLACE(@.C_HT_ng_e.Process, '#ng_e#', IF(_handle_FROM != 'ZM', 'opng_e', 'zmng_e'));
	SET 
		@.C_HT_ng_e.Process.Type = _Key
	;
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Start', 0, '', '');
	END IF;
	BEGIN

			-- IF @session.globals.Owner = 'AMICUS!' THEN
				DECLARE EXIT HANDLER FOR SQLEXCEPTION 
				BEGIN
				/*
					GET DIAGNOSTICS CONDITION 1
						@h.p1 = RETURNED_SQLSTATE, @h.p2 = MESSAGE_TEXT
					;
				*/
					-- @err.RETURNED_SQLSTATE = RETURNED_SQLSTATE, @err.MESSAGE_TEXT = MESSAGE_TEXT
					IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, 
							-- REPLACE(REPLACE('ERROR (#SQLSTATE#): #MESSAGE_TEXT#', '#SQLSTATE#', IFNULL(@err.RETURNED_SQLSTATE, '')), '#MESSAGE_TEXT#', IFNULL(@err.MESSAGE_TEXT, '')), 
							@.C_HT_ng_e.Process.Msg,
							1, '', '');
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, CONCAT('Ostatni etap:', @.C_HT_ng_e.Process.Msg), 0, '', '');
						/* CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, 
							CONCAT('Blad systemu gdy przetwarzano rekord nr: ', @ROW_Curr), 
							1, '', '');
						SET @ROW_Curr = @ROW_Curr - 1;
						*/
					END IF;
				END;
			-- END IF;
	--	sprawdz deltę czy można
	--	delta
				SET @.C_HT_ng_e.Process.Msg = "CALL oper_Delta_Update('', _handle_FROM, _Key, '', '', '');";		

-- JUZ NIE	CALL _ng_e_Numeracja_przed_Apply('Before.Apply', _Key, _handle_FROM, _Param_A, _Param_B);

	-- IF @session.globals.NEW.oper_delta.2018 IS NULL THEN
	-- 	CALL _Globals_Get('NEW.oper_delta.2018', @session.globals.NEW.oper_delta.2018, FALSE);
	-- END IF;

CALL _WatchTimeLogs_Tools('stop', "APPLY", "EXEPTION", '', '', '');

CALL _WatchTimeLogs_Tools('start', "APPLY", "OPER_DELTA BEGIN", '', '', '');
	
	IF _handle_FROM IN ('OP','ZM') THEN
	--	PO NOWEMU !!!!!!!!!!!!
		IF _handle_FROM IN ('OP') THEN
		--	OP inicjuj i wpisz z oppo przed
			CALL oper_Delta_Tools('OP.BEFORE.Apply', _Key, '', '', '', '', '');
		ELSE
		--	ZM inicjuj i wpisz z oppo przed
			CALL oper_Delta_Tools('ZM.BEFORE.Apply', _Key, '', '', '', '', '');
		END IF;
	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "OPER_DELTA BEGIN", '', '', '');

	
	
	
CALL _WatchTimeLogs_Tools('start', "APPLY", "_ng_e_Numeracja_przed_Apply", '', '', '');
	--	jesli tak to ...
	--	numeracja
	IF _Param_B != '' THEN
		CALL _ng_e_Numeracja_przed_Apply('Do.Apply', _Key, _handle_FROM, _Param_A, _Param_B);
	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "_ng_e_Numeracja_przed_Apply", '', '', '');
	
	
	
CALL _WatchTimeLogs_Tools('start', "APPLY", "ZAPIS DO LOG", '', '', '');
	-- ZAPIS DO LOG
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_SaveToLogBeforeApply('', _Key, _handle_FROM, '');";		
	CALL _ng_E_SaveToLogBeforeApply('', _Key, _handle_FROM, '');
	
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_Tools('delete.real', _Key, _handle_FROM, '');";		

						
	
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Usuwanie real', 0, '', '');	
	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "ZAPIS DO LOG", '', '', '');

	CALL _ng_E_ON('Before.Apply', _Key, _handle_FROM, '');
	/*================================================================
		USUWANIE real
		delete.real
	================================================================*/
						CALL _WatchTimeLogs_Tools('start', "APPLY", "delete.real", '', '', '');
	CALL _ng_E_Tools('delete.real', _Key, _handle_FROM, '');
						CALL _WatchTimeLogs_Tools('stop', "APPLY", "delete.real", '', '', '');
	
						SET @.C_HT_ng_e.Process.Msg = "CALL _ng_E_Tools('e.to.real', _Key, _handle_FROM, '');";		
						IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
							CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'zapis z e to real', 0, '', '');	
						END IF;
	
	/*================================================================
		WSTAWIANIE do  real
		e.to.real
	================================================================*/
						CALL _WatchTimeLogs_Tools('start', "APPLY", "e.to.real", '', '', '');
	CALL _ng_E_Tools('e.to.real', _Key, _handle_FROM, '');
						CALL _WatchTimeLogs_Tools('stop', "APPLY", "e.to.real", '', '', '');
    IF _handle_FROM = 'ZM' THEN
        IF @session.globals.Owner IN ('PLISZKA') THEN
        --   zmpo instancje
            CALL zmpo_instancjeE_P('E.APPLY', @.eID.EXE, _Key, '', '', '', '', '', '', '');
        END IF; 
    END IF; 

	CALL _ng_E_ON('After.Apply', _Key, _handle_FROM, '');						
	
	IF _handle_FROM = 'OP' 
	AND (@session.globals.Owner IN ('PARAQUA', 'IZOHAN'))
	THEN
	set @.malpka = 1;
	--	Dla FV do WZ ustaw nrdokFin w WZ-kach
		SET @.n.IDN = NULL, @.n.Nrdokfin = NULL, @.n.fvrudowz = NULL, @.n.Rodzaj = NULL;
		SELECT
			n.IDN, n.Nrdokfin, n.fvrudowz, n.Rodzaj, ng.Handle_oper, n.info2, n.nrdokmag
		FROM `opng` n, `ng_e_rec` ng 
		WHERE 
			n.GUID = _Key
			AND
			ng.GUID = _Key
		INTO 
			@.n.IDN, @.n.Nrdokfin, @.n.fvrudowz, @.n.Rodzaj, @.n.Handle_oper, @.n.info2, @.n.nrdokmag
		;
	set @.malpka = 2;
		-- SELECT @.n.IDN, @.n.Nrdokfin, @.n.fvrudowz, @.n.Rodzaj;
		-- SET @.n.Rodzaj = 0;
	--	Ustaw wszystkim WZ-kom (`opng` n) numerdokfin z biezacego dokumentu (_Key) o ile!! : 
	--	jest numer <> '', jest to nowy dokument FV (idn=0) i WZ-ki maja pusty numer
		UPDATE `opng` n, `oppo` p
		SET
			n.Nrdokfin = @.n.Nrdokfin
		WHERE
			TRUE
			-- AND IFNULL(@.n.Handle_oper, '') = 'INSERT'	-- Jest to nowa ...
			AND IFNULL(@.n.Rodzaj, 0) = 1		-- FV ...
			AND IFNULL(@.n.fvrudowz, 0) = 1		-- ... do WZ
			AND IFNULL(@.n.Nrdokfin, '') != ''	-- z numerem <> ''
			AND p.IdnWZ = _Key
			AND n.GUID = p.IdnOper
			AND IFNULL(n.Nrdokfin, '') = ''	-- a same WZki nie maja numery
		;
	--	A teraz w druga strone do info2 wstaw nrdokmag własny lub serię z WZ
	set @.malpka = 3;
		IF TRUE OR IFNULL(@.n.info2, '') != '' THEN
	set @.malpka = 4;
			SET
				@.n.info2 = 
				IFNULL(
					CONCAT(
					'Nr mag: ', 
					IF(@.n.fvrudowz = 0,
							NULLIF(@.n.nrdokmag, ''),
							(
								SELECT 
									GROUP_CONCAT(DISTINCT nwz.nrdokmag SEPARATOR ', ') 
								FROM `oppo` pwz, `opng` nwz 
								WHERE 
									pwz.IdnWZ = _Key AND 
									nwz.GUID = pwz.IdnOper
							)
					)
					)
				,''
				)	
			;
			UPDATE `opng` n SET n.info2 = @.n.info2 WHERE n.GUID = _Key;
			UPDATE `opng_e` n SET n.info2 = @.n.info2 WHERE n.GUID = _Key;
		END IF;
	END IF;
	

	
	
	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'Po zapisie', 0, '', '');	
	END IF;

	
CALL _WatchTimeLogs_Tools('start', "APPLY", "OPER_DELTA END", '', '', '');
	IF _handle_FROM IN ('OP', 'ZM') THEN

					SET @.C_HT_ng_e.Process.Msg = 'CALL oper_Delta_Dostawy_Update...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;

	--	PO NOWEMU !!!!!!!!!!!!
		IF _handle_FROM IN ('OP') THEN
		--	Update po
			CALL oper_Delta_Tools('OP.After.Apply', _Key, '', '', '', '', '');
		ELSE
		--	Update po
			CALL oper_Delta_Tools('ZM.After.Apply', _Key, '', '', '', '', '');
		END IF;
	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "OPER_DELTA END", '', '', '');

	
	IF _handle_FROM IN ('ZM') THEN

					SET @.C_HT_ng_e.Process.Msg = 'CALL oper_Delta_Oferty_Update...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
	
		CALL oper_Delta_Oferty_Update('update', _handle_FROM, _Key, '', '', '');
		-- dawne CALL _zmng_Update_zrealizowane('?', _Key, '1', '');
		CALL _ZM_Update_Realizacja('UPDATE.for.zmng', _Key, '', '');
	END IF;

	
	IF _handle_FROM IN ('OP') THEN
		IF @i_MODE = 'Realizacja.ZM.Edit' AND IFNULL(@i_Input_GUID, '') != '' THEN
					SET @.C_HT_ng_e.Process.Msg = 'CALL _zmng_Update_zrealizowane...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
	
CALL _WatchTimeLogs_Tools('start', "APPLY", "OP -> Realizacja.ZM.Edit", '', '', '');
			CALL _ZM_Update_Realizacja('UPDATE.for.zmng', @i_Input_GUID, '', '');
CALL _WatchTimeLogs_Tools('stop', "APPLY", "OP -> Realizacja.ZM.Edit", '', '', '');
		END IF;
		
	END IF;

SET  @.Grzesiu.o.co.chodzi = concat(@.Grzesiu.o.co.chodzi, ' PO');
	
						SET @.C_HT_ng_e.Process.Msg = "Koniec";		
	-- Znies flage `Need_Update` w `ng_e_rec`
CALL _WatchTimeLogs_Tools('start', "APPLY", "Koncowka", '', '', '');
	SET @_ng_E_LetPost.DONE = TRUE;
	UPDATE `ng_e_rec` r
	SET
		r.Need_Update = 0
	WHERE
		r.GUID = _Key
	;
	
	IF _handle_FROM != 'ZM' THEN
					SET @.C_HT_ng_e.Process.Msg = 'CALL oppo_mag...'	;
					IF @session.globals.APPLY.LOG.Active = 'ON 2' THEN
						CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, _MODE, @.C_HT_ng_e.Process.Msg, 0, '', '');
					END IF;
	
		--	oppo_mag
		CALL oppo_mag('UPDATE_OPNG_REC', _Key);
		--	rozlicz
		CALL ht_rozrach_rozlicz('ROZLICZ.CALC.OPNG', _Key, '', '', '', '');
		CALL ht_rozrach_rozlicz('ROZLICZ.CALC.OPNG.RELATED', _Key, '', '', '', '');

	END IF;
CALL _WatchTimeLogs_Tools('stop', "APPLY", "Koncowka", '', '', '');

	IF @session.globals.APPLY.LOG.Active != 'OFF' THEN
		CALL _erp_external_process_log_tools('Insert', @.C_HT_ng_e.Process, @.C_HT_ng_e.Process.Type, @.C_HT_ng_e.Process.Msg := 'End', 0, '', '');
	END IF;
	END;
	
END$$



DROP PROCEDURE IF EXISTS `_OP_ET_Let`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_OP_ET_Let`(
	IN _MODE VARCHAR(250),	 
	IN _Opt VARCHAR(255),
	IN _Opt_NEG VARCHAR(255),
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255),
	IN _Param_C VARCHAR(255),
	IN _Param_D VARCHAR(255),
	IN _Param_E VARCHAR(255)
)
S_OP_ET_Let: BEGIN 
	IF _MODE LIKE 'POST%' THEN
		SET @._OP_ET_Let.POST.each = (_MODE = 'POST') AND (_Opt = '');	--	gdy true to kazda czesc POST wykonuj
		IF NOT @._OP_ET_Let.POST.each AND _Opt = '' THEN
		--	UWAGA gdy dodatki wstawiamy w MODE a w _Opt jest pusto to przenosimy je do _Opt
			SET _Opt = REPLACE(_MODE, 'POST', '');
		END IF;
		/*
		IF _MODE = 'POST' THEN
			CALL xxng_vat_TOOLS('UPDATE `xxng_vat` and `xxng`', _handle_FROM, 'E', _Key, '', '', '', ''); 
			-- CALL _ng_E_LetPost('vat.to.ng', _handle_FROM, _Key, '', '');
			CALL _ng_E_LetPost('ng.to.po', _handle_FROM, _Key, '', '');
			CALL _ng_E_LetPost('po.to.ng', _handle_FROM, _Key, '', '');
			CALL _ng_e_rec_do('update.from.xxng_e', _Key, '', '');	-- update ng_rec_e
		....
		*/
		IF (_Opt LIKE '%UPDATE `xxng_vat` and `xxng`%' OR _Opt LIKE '%NG<-VAT<-PO%' OR @._OP_ET_Let.POST.each)
		AND NOT _Opt_NEG LIKE '%NG<-VAT<-PO%' THEN
			CALL xxng_vat_TOOLS('UPDATE `xxng_vat` and `xxng`', _handle_FROM, 'E', _Key, '', '', '', ''); 
			set @.VAT = 1;
		END IF;
		
		IF (_Opt LIKE '%NG->PO%' OR @._OP_ET_Let.POST.each)
		AND NOT _Opt_NEG LIKE '%NG->PO%' THEN
		--	na razie wolamy po staremu ale z czasem trzeba by to zmienic
			CALL oppo_E_Let_Update('from_opng_e', '', _Key, '', '');
			CALL oppo_E_Let_Update('lp', '', _Key, '', '');
			CALL oppo_E_Let_Update('rozrzucanie', '', _Key, '', '');
			set @.PO.z.NG = 1;
		END IF;
		
		IF (_Opt LIKE '%NG<-PO%' AND _handle_FROM != 'R' AND (@ht.doc.Twtyp != @ht.TwNN) OR @._OP_ET_Let.POST.each )
		AND NOT _Opt_NEG LIKE '%NG<-PO%' THEN
		--	na razie wolamy po staremu ale z czasem trzeba by to zmienic
			
		--	pozycje do nagłówka: liczba pozycji i inne agregaty
			CALL _po_e_NDE('UPDATE.NG<-PO', _handle_FROM, '', _Key, '', '', '', '', '');
			set @.NG.z.PO = 1;
			/* stare ************************************************************************
			IF _handle_FROM != 'ZM' THEN
			--	Operacje

				UPDATE `opng_e` n
				SET
					n.tag = 2,	--	faza oppo to nbg
					n.ilepoz = (SELECT COUNT(*) FROM `oppo_e` p WHERE p.IdnOper = n.GUID),
					n.waga = IFNULL((SELECT SUM(IFNULL(p.waga, 0)) FROM `oppo_e` p WHERE p.IdnOper = n.GUID), 0),
					n.netto_bez_zaliczki = IFNULL((SELECT SUM(IFNULL(p.wartnet, 0)) FROM `oppo_e` p WHERE p.idnoperfin = n.GUID AND p.usluga <> 8), 0)
				WHERE
					n.GUID = _Key
				;	
			ELSE
			--	Zamowienia
				UPDATE `zmng_e` n
				SET
					-- n.tag = 2,	--	faza zmpo to nbg
					n.ilepoz = (SELECT COUNT(*) FROM `zmpo_e` p WHERE idnNg = n.GUID AND p.wersja = n.wersja),
					n.IlepozZreal = IFNULL((SELECT SUM(IFNULL(p.zrealizowano >= p.ilosc, 0)) FROM `zmpo_e` p WHERE p.IdnNg = n.GUID AND p.wersja = n.wersja), 0),
					n.waga = IFNULL((SELECT SUM(IFNULL(waga, 0)) FROM `zmpo_e` WHERE idnNg = n.GUID), 0)
				WHERE
					n.GUID = _Key
				;	
				UPDATE `zmng_e` n
				SET
					n.Status = IF(n.ilepoz = n.IlepozZreal, 2, n.Status),
					n.zrealizowane = (n.ilepoz = n.IlepozZreal)
				WHERE
					n.GUID = _Key
					AND n.zamwpermn = 0
				;	
			END IF;
			*/
		END IF;
				
		IF (_Opt LIKE '%update.from.xxng_e%' OR @._OP_ET_Let.POST.each)
		AND NOT _Opt_NEG LIKE '%update.from.xxng_e%' THEN

			CALL _ng_e_rec_do('update.from.xxng_e', _Key, '', '');	-- update ng_rec_e
				set @.xxng_e = 1;
		END IF;
		SET @_ng_E_LetPost.DONE = TRUE;
	END IF;	--	IF _MODE = 'POST' 
END$$


DROP PROCEDURE IF EXISTS `OP_DELPHI_DO`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `OP_DELPHI_DO`(
	IN _MODE VARCHAR(250),	 
	IN _handle_FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255),
	IN _Param_C VARCHAR(255),
	IN _Param_D VARCHAR(255)
)
S_OP_DELPHI_DO: BEGIN 
	IF _MODE = 'Before.Apply' THEN
		SET _MODE = '';
	END IF;

	IF _MODE = 'After.Apply' THEN
	/***********************************************************************************************************************************************************
		CALL OP_DELPHI_DO('After.Apply', 'OP', IdnOper, '', '', '', '');
		CALL OP_DELPHI_DO('After.Apply', 'ZM', IdnNG, '', '', '', '');
	***********************************************************************************************************************************************************/
		IF _handle_FROM = 'OP' THEN
			SET @aaaaaaaaaaaaaaaaaa='a';
		END IF;
		
		IF _handle_FROM = 'ZM' THEN
		
			IF (@session.globals.Owner = 'KONKOL') THEN
			--	Dla KONKOL-a
				-- na razie CALL oper_Delta_Tools('ZM.Before.Apply', _Key, '', '', '', '', '');
				-- było CALL m_zmng_Tools('Reset.`zmng`.for.GUID', _Key, '', '', '', '');
				-- bylo session jako KEY
				-- CALL m_zmng_Tools('Manage.Wyjazd.SET.Default.WyjazdGUID.For.1.ZM', _Key, _Key, '', '', '');
				CALL m_zmng_Tools('Manage.Wyjazd.SET.Default.WyjazdGUID.For.1.ZM', _Key, IFNULL(NULLIF(@SYSTEM.Client.Session.GUID, ''), CONNECTION_ID()), '', '', '');
				-- na razie CALL oper_Delta_Tools('ZM.After.Apply', _Key, '', '', '', '', '');
			END IF;
		END IF;
	END IF;
	
	IF _MODE = 'Before.e.to.real' THEN
		SET _MODE = '';
	END IF;
	
	IF _MODE = 'Before.Post' THEN
		SET _MODE = '';
	END IF;
	
	IF _MODE = 'After.Post' THEN
		SET _MODE = '';
	END IF;

	LEAVE S_OP_DELPHI_DO;
END$$

DROP PROCEDURE IF EXISTS `_ng_E_ToolsP`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_E_ToolsP`(
	_MODE VARCHAR(250),
	_C1 VARCHAR(250),
	_C2 VARCHAR(250),
	_C3 VARCHAR(250),
	_C4 VARCHAR(250),
	_C5 VARCHAR(250),
	_F1 DOUBLE(16,6),
	_F2 DOUBLE(16,6),
	INOUT _M1 TEXT
)
L_EXIT: BEGIN 

	IF _MODE LIKE 'LOG.%' THEN
	--	'LOG.GET' / 'LOG.Add.logtxt'
		SET 
			@.l.MODE = _C1,	--	_MODE
			@.l.LogEx = _C2,	--	Extra etap do logu
			@.l.OpZm = _C3,	--	_handle_FROM
			@.l.Key = _C4,	--	_Key
			-- @.l.NP = _C5	--	n/p nagł. poz.	
			@.l.Check.Alert = _C5	--	badanie alertu
			
		;
			
		IF TRUE THEN 	-- @.l.MODE LIKE 'e.to.real%' THEN

			IF TRUE THEN
			--	pozycje
				IF @.l.OpZm = 'OP' THEN
					SET @.SQL.CC.p = "SET @.CC = IFNULL((SELECT COUNT(*) AS CC FROM `#xxpo#` p WHERE p.IdnOperFin = #_IdnOper# OR p.IdnOper = #_IdnOper#), 0);";
				ELSE
					SET @.SQL.CC.p = "SET @.CC = IFNULL((SELECT COUNT(*) AS CC FROM `#xxpo#` p WHERE p.IdnNg = #_IdnOper#), 0);";
				END IF;
			--	R...																			 
				SET @.SQL.CC.p.R = @.SQL.CC.p;
				CALL _ExecuteCmd_xxNgPo('', @.l.OpZm, 'R', @.l.Key, '', '', '', '', '', @.SQL.CC.p.R);
				SET @.CC.P.R = @.CC;
						SET @.CC.R = @.CC;
			--	E...	
				SET @.SQL.CC.p.E = @.SQL.CC.p;
				CALL _ExecuteCmd_xxNgPo('', @.l.OpZm, 'E', @.l.Key, '', '', '', '', '', @.SQL.CC.p.E);
				SET @.CC.P.E = @.CC;
						SET @.CC.E = @.CC;
			END IF;
			IF TRUE THEN
			--	naglowek
				SET 
					@.CC = 0, @.N.MA_Detale = 0,
					@.SQL.CC.n = "
					SELECT 
						COUNT(*) AS CC, IFNULL(od.MA_Detale, 0)
					INTO
						@.CC, @.N.MA_Detale
					FROM `#xxng#` n 
					left join `operdoc` od ON od.Rodzaj = n.Rodzaj
					WHERE 
						n.GUID  = #_IdnOper#
					;
					"
				;
			
				-- SET @.SQL.CC.n = "SET @.CC = IFNULL((SELECT COUNT(*) AS CC FROM `#xxng#` n WHERE n.GUID  = #_IdnOper#), 0);";
			--	R...	
				SET @.SQL.CC.n.R = @.SQL.CC.n;
				CALL _ExecuteCmd_xxNgPo('', @.l.OpZm, 'R', @.l.Key, '', '', '', '', '', @.SQL.CC.n.R);
				SET @.CC.N.R = @.CC;
				SET @.N.R.MA_Detale = @.N.MA_Detale;
						SET @.CC.R = @.CC;
			--	E...	
				SET @.SQL.CC.n.E = @.SQL.CC.n;
				CALL _ExecuteCmd_xxNgPo('', @.l.OpZm, 'E', @.l.Key, '', '', '', '', '', @.SQL.CC.n.E);
				SET @.CC.N.E = @.CC;
				SET @.N.E.MA_Detale = @.N.MA_Detale;
						SET @.CC.E = @.CC;
			END IF;
		
			SET
				@.logInf =
				CONCAT_WS('',
					/* wersja osobno nag. i poz.
					CONCAT(IF(@.l.NP = 'P', 'pozycje ', ' nagl. '), @.l.OpZm),
					CONCAT_WS(', ',
						CONCAT('CC.R = ', IF(IFNULL(@.CC.R, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.R))),
						CONCAT('CC.E = ', IF(IFNULL(@.CC.E, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.E))),
						null
					),
						wersja wsztskie nag/poz/E/R	... */
					CONCAT('(', @.l.OpZm, ') '),
					'"R": ',
					CONCAT_WS(', ',
						CONCAT('Ng.CC = ', IF(IFNULL(@.CC.N.R, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.N.R))),
						CONCAT('Po.CC = ', IF(IFNULL(@.CC.P.R, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.P.R)))
					),
					', "E": ',
					CONCAT_WS(', ',
						CONCAT('Ng.CC = ', IF(IFNULL(@.CC.N.E, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.N.E))),
						CONCAT('Po.CC = ', IF(IFNULL(@.CC.P.E, 0) = 0, 'brak rekord.!!!', _VarStr(@.CC.P.E))),
						NULL
					),
					NULL
				)
			;
		END IF;
	--	do logu -- 
	--	@.l.MODE
	--	Zwróć...
		SET _M1 = @.logInf;
		SET @.l.Log_ID = CONCAT_WS('.', @.l.MODE, @.l.OpZm, @.l.LogEx);
		IF _MODE LIKE 'LOG.Add.logtxt%' THEN
			-- SET @.log.inf = (SELECT CONCAT_WS('/', n.Idn, n.GUID) AS inf FROM `opng` n WHERE n.GUID = '_GUID');
			CALL _sys_app_logtxt('LOG.Session.Add', NULL, @.l.Log_ID, '', '', '', '', @.l.Key, 
				@.logInf
			);
			IF @.l.Check.Alert  <> '' --	 na razie tylko czy <> ""
			AND 	
			@.N.R.MA_Detale 
			AND
			(
				@.CC.P.R = 0	--	na razie 
			)
			THEN 
			-- w @.al.LastIdn jest LAST_INSERT_ID();
				UPDATE `_sys_app_logtxt` al 
				SET
					al.Param2 = 'ALERT'
				WHERE
					al.Idn = @.al.LastIdn
				;
			END IF;
		END IF;
	END IF;
END;
$$

DELIMITER ;
/*
$Log: C_HT_ng_e.sql,v $
Revision 1.138  2025/11/06 10:02:45  waliant
$SEND$ poprawka koment (bledy backupu)

Revision 1.137  2025/09/09 11:05:55  jmam
dodano obsluge zmpo_instancje

Revision 1.136  2025/07/10 11:44:28  jmam
Blokada sprzed. rowniez na platniku

Revision 1.135  2025/03/31 08:26:15  jmam
$send$ poprawki po Waliant + polskie znaki

Revision 1.134  2025/02/14 12:18:31  waliant
Warningi, ale jest problem z komentarzami

Revision 1.133  2024/11/20 18:14:18  jmam
$SEND$ koszt_sprzedazy dla AXIS

Revision 1.132  2024/07/22 14:20:21  jmam
$SEND$ na razie tylko dla COMEX spr. statusu w widocz. mag.

Revision 1.131  2024/07/19 08:24:27  jmam
$SEND$ poprawka w poprawkach dla SIMEX (chodzi log by? b??d dla zam.)

Revision 1.130  2024/07/18 16:08:19  jmam
$SEND$ dopisanie proc. LOG-u dla SIMEX

Revision 1.129  2024/07/02 08:08:06  jmam
$SEND$ - masowe zmiany po d?ugim czasie

Revision 1.128  2023/02/09 14:53:28  jmam
$SEND$ ost. poprawki

Revision 1.127  2022/11/23 09:24:39  rafalg
zmiany dla AXIS

Revision 1.126  2022/08/25 06:52:08  jmam
$SEND$ - komink. np. Uwagi kontrahenta

Revision 1.125  2022/02/10 11:57:07  jmam
$SEND$ - zmiany II 2022

Revision 1.124  2021/12/01 15:56:02  jmam
$SEND$

Revision 1.123  2021/12/01 11:29:47  jmam
$SEND$

Revision 1.122  2021/09/13 10:33:19  jmam
$SEND$

Revision 1.121  2021/04/19 07:14:06  jmam
$SEND$

Revision 1.120  2021/04/07 13:06:32  jmam
$SEND$

Revision 1.119  2021/03/25 12:38:13  apro
$SEND$

Revision 1.118  2021/03/24 11:43:34  apro
*** empty log message ***

Revision 1.117  2021/03/22 11:41:10  jmam
$SEND$

Revision 1.116  2021/02/10 07:44:52  apro
$SEND$
wizard - widoczność korekt ZP, SI i DW

Revision 1.115  2021/01/25 12:40:42  jmam
$SEND$

Revision 1.114  2020/11/04 19:56:18  jmam
$SEND$

Revision 1.113  2020/11/02 15:42:21  jmam
$SEND$

Revision 1.112  2020/11/02 15:34:52  jmam
$SEND$

Revision 1.111  2020/10/20 11:01:10  jmam
$SEND$

Revision 1.110  2020/10/12 12:21:56  jmam
$SEND$

Revision 1.109  2020/09/18 16:12:52  jmam
no message

Revision 1.108  2020/09/18 15:57:08  jmam
no message

Revision 1.107  2020/05/08 11:26:37  rafalg
rozrzucanie zaokraglen ZT + wysylka mailowa

Revision 1.106  2020/01/08 08:30:00  jmam
$SEND$

Revision 1.105  2019/11/12 09:53:28  jmam
$SEND$

Revision 1.104  2019/10/28 12:28:10  apro
jednak korekty

Revision 1.103  2019/10/28 12:03:10  apro
Korekta zaokrągleń wart netto w eSwiat dla dok. ST w walucie- na razie testowo dla AXIS-a, docelowo wyłączyć ograniczenie

Revision 1.102  2019/10/22 11:51:13  rafalg
zp-fv dla cdg

Revision 1.101  2019/10/04 07:46:38  jmam
$SEND$

Revision 1.100  2019/10/03 07:33:28  slon
dodanie kolejnego dokumentu w kancelarii
$SEND$

Revision 1.99  2019/07/24 08:32:31  jmam
$SEND$

Revision 1.98  2019/05/09 09:40:19  jmam
$SEND$

Revision 1.97  2019/04/01 12:59:10  jmam
no message

Revision 1.96  2018/11/14 12:04:41  jmam
$SEND$

Revision 1.95  2018/09/11 08:10:35  jmam
no message

Revision 1.94  2018/09/05 11:43:56  jmam
no message

Revision 1.93  2018/09/04 07:33:31  apro
literówka

Revision 1.92  2018/09/04 06:05:56  apro
zmiana Izohan - jeden ubezpieczyciel - Atriadus

Revision 1.91  2018/07/30 12:01:21  jmam
$SEND$

Revision 1.90  2018/07/12 05:05:19  apro
log

*/

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

CALL C_HT_VAT('', '', '', '');

SELECT * FROM `ng_e_rec`;
CALL ng_Check_real_to_E('Before.Handle', 'OP', 'Edit', '{4367FDA9-1EF9-4117-B768-BCD4D91C6DE1}', 3, 0, '', 0, 0, 0, 0, '', '', @G_orig, '', '', '');


CALL _Session_Refresh_Variables('', '', ''); 
SET @NEW.handle_UserGUID = 'Prac2';
SET @IdnOper = 'GXYZ';
CALL Opng_E_init('INSERT', @IdnOper, @NEW.handle_UserGUID, '', ''); 
CALL _ng_e_rec_do(, @IdnOper, '', ''); -- zwróć wszystkie ustawienia (kolumny `ng_e_rec`, `operdoc` i `operdoc`

CALL _ng_E_Wizard('Init.wizard', @IdnOper, 1, '', '', '', '');
CALL _ng_E_Wizard('Init.wizard', @IdnOper, 1, 'STZTMG', '', '', '');
CALL _ng_E_Wizard('select.optypy', @IdnOper, 1, 'STZTMG', '', '', '');
CALL _ng_E_Wizard('select.rodzaje', @IdnOper, 1, 'STZTMG', '', '', '');
CALL _ng_E_Wizard('select.rodzaje', @IdnOper, 2, '', '', '', '');
CALL _ng_E_Wizard('select.rodzaje_typ', @IdnOper, 1, 'STZTMG', '', '', '');

CALL _ng_E_Wizard('select.magazyny', @IdnOper, 0, '', '', '', '');
CALL _ng_E_Wizard('select.magazyny', @IdnOper, 1, '', '', '', '');
CALL _ng_E_Wizard('select.kasy', @IdnOper, 1, '', '', '', '');
CALL _ng_E_Wizard('select.waluty', @IdnOper, 1, '', '', '', '');

PAMIETAJ w triggerze opng_e zamień @ małpy na oper_doc !!!!!!!!!!!!!!!!

	CALL _ng_e_rec_do('check.kontrahent', @IdnOper, '{9F42245E-6AEB-4852-8E79-C52F186E01B6}', '');	--	zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	CALL _ng_e_rec_do('check.kontrahent', @IdnOper, 'ABC', '');	--	zwraca informacje nt kontrahenta w tym także czy nie jest zablokowany
	
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
