 /* 
$Log: erp_obj_counters_tools.sql,v $
Revision 1.24  2025/02/25 20:43:09  jmam
$send$ Zmiany po TK

Revision 1.23  2025/02/20 11:44:48  waliant
Warningi $SEND$

Revision 1.22  2025/02/20 11:09:00  waliant
Warningi $SEND$

Revision 1.21  2024/07/02 07:57:41  jmam
$SEND$ - popr. zwracanych zmiennych (HYDROMEGA)

Revision 1.20  2023/10/12 10:04:13  jmam
no message

Revision 1.19  2023/01/10 11:55:29  apro
procka na potrzeby funkcji (bez select, bo się wywala)

Revision 1.18  2021/09/13 10:23:42  jmam
$SEND$

Revision 1.17  2020/06/22 16:26:34  jmam
$SEND$

Revision 1.16  2019/05/09 10:19:14  jmam
$SEND$

Revision 1.15  2017/08/18 07:42:51  jmam
$SEND$

Revision 1.14  2017/05/16 16:13:27  jmam
$SEND$

Revision 1.13  2016/09/14 13:36:37  jmam
$SEND$

Revision 1.12  2016/07/21 12:15:58  jmam
no message

Revision 1.11  2016/02/03 13:31:03  jmam
$SEND$ numeracja manualna

Revision 1.10  2015/12/29 09:08:10  jmam
$SEND$ Numeracja n = n + 1

Revision 1.9  2015/06/08 09:13:30  jmam
no message

Revision 1.8  2015/02/05 15:10:22  jmam
no message

Revision 1.7  2015/01/20 10:49:57  jmam
Inicjowanie info rewizji

*/

/*SQZ autogen*/
/*SQZ devel*/
/*SQZ */
DELIMITER $$

/* ***********************************************************************************************************************************************************
	Numewracja oparta na `erp_obj_counters`
********************************************************************************************************************************************************** */

DROP PROCEDURE IF EXISTS `erp_obj_counters_Get_INC_Number`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_Get_INC_Number`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Inkrementowanie licznika
		CALL erp_obj_counters_Get_INC_Number('', @_Numer, 'PASS', '0', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_Get_INC_Number('', @_Numer, 'oper', '1', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_Get_INC_Number('from.erp_obj_counters_masks', @_Numer, 'oper', '1', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_Get_INC_Number('from.erp_obj_counters_masks', @_Numer, 'oper', '1', '0', '4', '0', '', 2012, 6, 0);		-- dla przepustek
		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_GetNumber: BEGIN

	SET _Numer = 0;
	
	SET @erp_obj_counters.Number = _Numer;
	
	INSERT INTO `erp_obj_counters`
	(
		`Nr`,
		`ObjType`,
		`Rodzaj`,
		`Podrodzaj`,
		`Res1`,
		`Res2`,
		`ResGUID`,
		`Y`,
		`M`,
		`D`
	)
		SELECT
			@erp_obj_counters.Number := @erp_obj_counters.Number + 1, 
			_ObjType,
			m.Rodzaj,
			m.Podrodzaj,
			IF(m.Grp_Res1 = 1, _Res1, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
			IF(m.Grp_Res2 = 1, _Res2, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
			IF(m.Grp_ResGUID, _ResGUID, ''),
			IF(m.Grp_Y, _NumYear, 0),
			IF(m.Grp_M, _NumMonth, 0),
			IF(m.Grp_D, _NumDay, 0)
			
			-- m.Rodzaj, m.Podrodzaj, 
			-- m.grp_Res1, m.grp_Res2, m.grp_ResGUID, m.grp_Y, m.grp_M, m.grp_D, m.Disabled
		FROM `erp_obj_counters_masks` m1
		INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji -- JUZ nie AND NOT m.Disabled
		WHERE
			m1.ObjType = _ObjType
			AND m1.Rodzaj = _Rodzaj
			AND m1.Podrodzaj = _Podrodzaj
		
	ON DUPLICATE KEY
	UPDATE
		`Nr` = @erp_obj_counters.Number := (`Nr` + 1)
	;
	
	SET _Numer = IFNULL(@erp_obj_counters.Number, 0);

END$$


DROP PROCEDURE IF EXISTS `erp_obj_counters_GetNumber`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_GetNumber`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Inkrementowanie licznika
		CALL erp_obj_counters_GetNumber('', @_Numer, 'PASS', '0', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_GetNumber('', @_Numer, 'oper', '1', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_GetNumber('from.erp_obj_counters_masks', @_Numer, 'oper', '1', '0', '0', '0', '', 2012, 6, 0);		-- dla przepustek
		CALL erp_obj_counters_GetNumber('from.erp_obj_counters_masks', @_Numer, 'oper', '1', '0', '4', '0', '', 2012, 6, 0);		-- dla przepustek
		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_GetNumber: BEGIN

	-- DECLARE _Rodzaj_op_numeracji, _Podrodzaj_op_numeracji INTEGER;
	DECLARE _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
	DECLARE _grp_ResGUID VARCHAR(100);
	
	SET _PodRodzaj = IFNULL(_PodRodzaj, 0);
	SET 
		@_Rodzaj = _Rodzaj, 
		@_Podrodzaj = _PodRodzaj,
		@_Numer = 1
	;
SET @.X = '1';
	SET _ObjType = IF(_ObjType = 'Nrwewn', 'oper_wewn', _ObjType);
	
	IF _MODE = 'from.erp_obj_counters_masks' THEN
SET @.X = '2';
		CALL erp_obj_counters_Get_Props_For_Oper('', _ObjType, _Rodzaj, _PodRodzaj, _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, @_NumMask, _Disabled);
		-- CALL erp_obj_counters_Get_Props_For_Oper('', _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, @_NumMask, _Disabled);
SET @.X = '3';
		
		IF _Disabled THEN
			SET _Numer = 0;
			LEAVE S_erp_obj_counters_GetNumber;
		END IF;
		SET 
			_Rodzaj = _Rodzaj_N, 
			_Podrodzaj = _PodRodzaj_N,
			_Res1 = IF(_grp_Res1 = 1, _Res1, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
			_Res2 = IF(_grp_Res2 = 1, _Res2, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
			_ResGUID = IF(_grp_ResGUID, _ResGUID, ''),
			_NumYear = IF(_grp_Y, _NumYear, 0),
			_NumMonth = IF(_grp_M, _NumMonth, 0),
			_NumDay = IF(_grp_D, _NumDay, 0)
		;
SET @.X = '4';
	END IF;

	
SET @.X = '5';
	IF _Rodzaj IS NOT NULL THEN
		INSERT INTO `erp_obj_counters`
		(
			`Nr`,
			`ObjType`,
			`Rodzaj`,
			`Podrodzaj`,
			`Res1`,
			`Res2`,
			`ResGUID`,
			`Y`,
			`M`,
			`D`
		)
		VALUES
		(
			@_Numer,
			_ObjType,
			_Rodzaj,
			_Podrodzaj,
			_Res1,
			_Res2,
			_ResGUID,
			_NumYear,
			_NumMonth,
			_NumDay
		)
		ON DUPLICATE KEY
		UPDATE
			`Nr` = (@_Numer := `Nr` + 1)
		;
	/*
	SELECT
		Nr INTO _Numer
	FROM `erp_obj_counters`
	WHERE
		ObjType = _ObjType AND
		Rodzaj = _Rodzaj AND
		Podrodzaj = _Podrodzaj AND
		Res1 = _Res1 AND
		Res2 = _Res2 AND
		ResGUID = _ResGUID AND
		Y = _NumYear AND
		M = _NumMonth AND
		D = _NumDay
	;
	SET _Numer = IFNULL(_Numer, 0);
	*/
		SET _Numer = IFNULL(@_Numer, 0);
	ELSE
		SET _Numer = NULL;
	END IF;

END$$

DROP PROCEDURE IF EXISTS `erp_obj_counters_Get_Props_For_Oper`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_Get_Props_For_Oper`(
	IN _MODE VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	INOUT _Rodzaj_N INTEGER,
	INOUT _PodRodzaj_N INTEGER,
	INOUT _grp_Res1 INTEGER,
	INOUT _grp_Res2 INTEGER,
	INOUT _grp_ResGUID VARCHAR(38),
	INOUT _grp_Y INTEGER,
	INOUT _grp_M INTEGER,
	INOUT _grp_D INTEGER,
	INOUT _NumMask VARCHAR(250),
	INOUT _Disabled INTEGER
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Zwraca prametry z ustawien
		CALL erp_obj_counters_Get_Props_For_Oper('', _ObjType, _Rodzaj, _PodRodzaj, _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, _NumMask, _Disabled);
		CALL erp_obj_counters_Get_Props_For_Oper('', 'PASS', _Rodzaj, _PodRodzaj, _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, _NumMask, _Disabled);
		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_Get_Props_For_Oper: BEGIN
	-- DECLARE _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D INTEGER;
	-- DECLARE _grp_ResGUID VARCHAR(100);
	SET _ObjType = IF(_ObjType = 'Nrwewn', 'oper_wewn', _ObjType);
	SELECT
		m.Mask, 
		m.Rodzaj, m.Podrodzaj, 
		m.grp_Res1, m.grp_Res2, m.grp_ResGUID, m.grp_Y, m.grp_M, m.grp_D, m.Disabled
	INTO
		_NumMask,
		_Rodzaj_N, _Podrodzaj_N,
		_grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, _Disabled
	FROM `erp_obj_counters_masks` m1
	INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji
	WHERE
		m1.ObjType = _ObjType
		AND m1.Rodzaj = _Rodzaj
		AND m1.Podrodzaj = _Podrodzaj
	;
	IF _Disabled THEN
		LEAVE S_erp_obj_counters_Get_Props_For_Oper;
	END IF;
	/*
	SET 
		_Rodzaj = @_Rodzaj, 
		_Podrodzaj = @_Podrodzaj,
		_Res1 = IF(_grp_Res1 = 1, _Res1, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
		_Res2 = IF(_grp_Res2 = 1, _Res2, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
		_ResGUID = IF(_grp_ResGUID, _ResGUID, ''),
		_NumYear = IF(_grp_Y, _NumYear, 0),
		_NumMonth = IF(_grp_M, _NumMonth, 0),
		_NumDay = IF(_grp_D, _NumDay, 0)
	;
	*/
END$$



-- te ponize won


DROP PROCEDURE IF EXISTS `AutoNum_GetFmtNumberText`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `AutoNum_GetFmtNumberText`(
	IN _MODE VARCHAR(150),
	INOUT _NumerText VARCHAR(150),
	IN _Numer INTEGER,
	IN _NumMask VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER,
	IN _NumSymbolRes1 VARCHAR(50),
	IN _NumSymbolRes2 VARCHAR(50),
	IN _NumSymbolResGUID VARCHAR(50)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Inkrementowanie licznika
		CALL AutoNum_GetFmtNumberText('', @_NumerText, 45, 'Przepustka Nr:%NNNN/%DYDY/%MHMH/%YYYY', 'PASS', 0, 0, 0, 0, '', 2012, 6, 19, 'x', 'y', 'z');		-- dla przepustek
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_AutoNum_GetFmtNumberText:BEGIN
		SET _NumMask = IFNULL(_NumMask, '');
		IF _NumMask = ''  THEN
			SET _NumerText = '';
			LEAVE S_AutoNum_GetFmtNumberText;
		END IF;
		
		SET @_NumText = IFNULL(_NumMask, '');
		
		-- SET @_NumText = CONCAT(@_NumText, ' Mies:%MH / Symbol: %SASA');
		IF _NumYear = 0 THEN
			SET _NumYear = YEAR(Now());
		END IF;
		IF _NumMonth = 0 THEN
			SET _NumMonth = MONTH(Now());
		END IF;
		IF _NumDay = 0 THEN
			SET _NumDay = DAY(Now());
		END IF;
	--	Miesiac
		SET @_NumText = _MaskTool('', @_NumText, '%', 'MH', _NumMonth, '0', 6);
	--	Miesiac znakowy
		SET @_NumText = _MaskTool('', @_NumText, '%', 'MHC', _NumMonth, 'CHAR', 6);
	--	Dzien
		SET @_NumText = _MaskTool('', @_NumText, '%', 'DY', _NumDay, '0', 6);

		
	--	Numer
		SET @_NumText = _MaskTool('', @_NumText, '%', 'N', _Numer, '0', 6);
	--	Magazyn
		SET @_NumText = _MaskTool('', @_NumText, '%', 'M', _Res1, '0', 6);
	--	Rok
		SET @_NumText = _MaskTool('', @_NumText, '%', 'Y', _NumYear, '0', 6);

	--	_NumSymbolResGUID
		SET @_NumText = _MaskTool('', @_NumText, '%', 'RES', _NumSymbolResGUID, 'CHAR', 20);
		
		SET @_NumText = _MaskTool('', @_NumText, '%', 'SA', 'RURA', 'CHAR', 6);
		
		SET _NumerText = _VarStr(@_NumText);
		SELECT _NumerText;
END$$

DROP PROCEDURE IF EXISTS `AutoNum_GetNumberText`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `AutoNum_GetNumberText`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	INOUT _NumerText VARCHAR(150),
	IN _NumMask VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER,
	IN _NumSymbolRes1 VARCHAR(50),
	IN _NumSymbolRes2 VARCHAR(50),
	IN _NumSymbolResGUID VARCHAR(50)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		Inkrementowanie licznika + Zwrot formatowanego tekstu
		CALL AutoNum_GetNumberText('', @_Numer, @_NumerText, 'Przepustka Nr:%NNNN/%DYDY/%MHMH/%YYYY', 'PASS', 0, 0, 0, 0, '', 2012, 6, 19, 'x', 'y', 'z');		-- dla przepustek
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_AutoNum_GetNumberText:BEGIN
	CALL AutoNum_GetNumber('', _Numer, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay);		-- 
	CALL AutoNum_GetFmtNumberText('', _NumerText, _Numer, _NumMask, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _NumSymbolRes1, _NumSymbolRes2, _NumSymbolResGUID);		
END$$



DROP PROCEDURE IF EXISTS `AutoNum_GetNumberText_OperDoc`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `AutoNum_GetNumberText_OperDoc`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	INOUT _NumerText VARCHAR(150),
	IN _NumMask VARCHAR(150),
	
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	
	IN _Res1 INTEGER,	--	Magazyn/Kasa
	IN _Res2 INTEGER,	--	DoMagazynu/Kasa
	IN _DataOper DATE,
	IN _RodzajDowodu VARCHAR(150),
	IN _Rv_id INTEGER,
	IN _UGrpGUID VARCHAR(38)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
CALL AutoNum_GetNumberText_OperDoc('', @_Numer, @_NumerText, '', 'nrdokfin', Rodzaj, 0, ZMagazynu, DoMagazynu, DataWystaw, RodzajDowodu, Rv_id, UGrpGUID);		
		
		CALL AutoNum_GetNumberText_OperDoc('', @_Numer, @_NumerText, '', 'nrdokfin', 1, 0, 8, 0, '2013-10-21', 6, 1020, '');		
		CALL AutoNum_GetNumberText_OperDoc('WEWN', @_Numer, @_NumerText, '', 'nrwewn', 1, 0, 8, 0, '2013-10-21', 6, 1020, '');		

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_AutoNum_GetNumberText_OperDoc: BEGIN
	DECLARE _Params TEXT;
	DECLARE _ResGUID VARCHAR(38) DEFAULT '';
	DECLARE _NumYear, _NumMonth, _NumDay INTEGER;
	/**************************************************************************************************************************************************************
		PObierz wlasciwy rodzaj z pola `rodzaj_op_numeracji`
	**************************************************************************************************************************************************************/
	IF _MODE != 'WEWN' THEN
		SELECT 
			od.mask, od.wspolna, od.numdok_automat, od2.rodzaj_op_numeracji		--	od.mask_wewn, od.wspolna_wewn, od.numwewn_automat
		INTO
			@_Mask, @od.wspolna, @_numdok_automat, @_Rodzaj_op_numeracji
		FROM `operdoc` od2
		LEFT JOIN `operdoc` od ON od.Rodzaj = od2.rodzaj_op_numeracji
		WHERE
			od2.Rodzaj = _Rodzaj
		;
	ELSE
		SELECT 
			od.mask_wewn, od.wspolna_wewn, od.numwewn_automat, od.rodzaj		--	od.mask_wewn, od.wspolna_wewn, od.numwewn_automat
		INTO
			@_Mask, @od.wspolna, @_numdok_automat, @_Rodzaj_op_numeracji
		FROM `operdoc` od
		WHERE
			od.Rodzaj = _Rodzaj
		;
	END IF;
	
	IF _Rodzaj != IFNULL(@_Rodzaj_op_numeracji, _Rodzaj) THEN
		SET 
			_Rodzaj = @_Rodzaj_op_numeracji,
			_PodRodzaj = 0
		;
	END IF;
	SET
		_NumYear = YEAR(_DataOper),
		_NumMonth = MONTH(_DataOper),
		_NumDay = 0 -- NA RAZIE ZAWSZE DAY(_DataOper)
	;
	SELECT wspolna INTO @wspolna FROM `operdoc` WHERE rodzaj = _Rodzaj;
	
	SET 
		_Res1 = IF(@wspolna, 0, _Res1),
		_Res2 = IF(@wspolna, 0, _Res2)
	;
	
	SET
		_Params = CONCAT(_Res1,';',_Res2,';',_DataOper,';',_RodzajDowodu,';',_Rv_id,';', _UGrpGUID, ';')
	;
	-- CALL AutoNum_GetNumber(_MODE, _Numer, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _RodzajDowodu, _UGrpGUID, _NumYear, _NumMonth, _NumDay);		-- 
	CALL AutoNum_GetNumber(_MODE, _Numer, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Rv_id, _RodzajDowodu, _NumYear, _NumMonth, _NumDay);		-- 
	
	CALL GetUniqNrForFieldAndUpdate(_MODE, _Numer, _Rodzaj, _Res1, _Params, _NumerText);

	/*
	CALL AutoNum_GetNumber('', @_Numer, 'nrdokfin', Rodzaj, 0, '0', RodzajDowodu, '', YEAR(DataWystaw), MONTH(DataWystaw), 0);
	CALL AutoNum_GetFmtNumberText('', _NumerText, _Numer, _NumMask, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _NumSymbolRes1, _NumSymbolRes2, _NumSymbolResGUID);		
	*/
END$$



/* ************************************************************************************************************************************************************************
	Narzędzia 
************************************************************************************************************************************************************************ */	

DROP FUNCTION IF EXISTS `_Trigger_OldNum_AfterUpdate`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_Trigger_OldNum_AfterUpdate`(
	_Nr INTEGER,
	_ObjType VARCHAR(200),
	_Rodzaj INTEGER,	
	_Res1 INTEGER	--	Magazyn
) 
RETURNS INTEGER
	DETERMINISTIC
	COMMENT 'Zwraca numer dodany do  `erp_obj_counters`'
BEGIN
	SET @num.NEW.Nr = _Nr;
	IF @session.globals.Autonumeracja_NOWA THEN
	-- 	numeracja w `erp_obj_counters`
		IF NOT IFNULL(@session.trigger.erp_obj_counters, FALSE) THEN
		-- 	Na pewno wartosc nie pochodzi z triggera `erp_obj_counters`
			-- 	KLUCZ na `erp_obj_counters` to ObjType`,`Rodzaj`,`Podrodzaj`,`Res1`,`Res2`,`ResGUID`,`Y`,`M`,`D`
			INSERT IGNORE INTO `erp_obj_counters`
			(`Nr`, `ObjType`, `Rodzaj`, `Podrodzaj`, `Res1`, `Res2`) 
			VALUES
				(
				_Nr, _ObjType, _Rodzaj, 0, _Res1, 0
				)
			ON DUPLICATE KEY UPDATE
				`erp_obj_counters`.Nr = (@num.NEW.Nr := (`erp_obj_counters`.Nr + 1))
			;		
		END IF;
	END IF;
	
	RETURN @num.NEW.Nr;
END
$$

DROP FUNCTION IF EXISTS `_Conv_OldMaskTool`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_Conv_OldMaskTool`(
	_MODE VARCHAR(255),
	_InputStr VARCHAR(255),
	_Mask_Prefix VARCHAR(5),
	_Mask_Char VARCHAR(5),
	_Value VARCHAR(50),
	_Mask_Prefix_Value VARCHAR(5)
) 
RETURNS VARCHAR(256)
    NO SQL
    DETERMINISTIC
SPROC: BEGIN
/*
	_MODE 
	_InputStr 			Wejsciowy string np '%NNNN/%YYYY-%A'
	_Mask_Prefix 		domyslnie '%'
	_Mask_Char 			np 'N' lub 'M' etc.
	_Value 				co bedziemy wstawiac w maske np. 
							dla _Value = 2345 za %NNNNNNN mamy 002345
							dla _Value = 2010 za %YY mamy 10
	_Mask_Prefix_Value	Poprzedzajaca wartosc (domyslnie 0 wstawiamy przed numer gdy za krotki 
						przykladowo dla _Value = 2345 za %NNNNNNN mamy 002345

*/


	SET @OutStr = IFNULL(_InputStr, '');
	IF @OutStr = '' THEN
		RETURN @OutStr;
		LEAVE SPROC;
	END IF;
	SET _Mask_Prefix_Value = IFNULL(_Mask_Prefix_Value, '');
	IF _Mask_Prefix_Value = ' ' THEN
		SET _Mask_Prefix_Value = '. .';
	END IF;	
	IF _Mask_Prefix_Value = '' THEN
		SET _Mask_Prefix_Value = '0';
	END IF;	
	SET _Mask_Prefix_Value = REPLACE(_Mask_Prefix_Value, '. .', ' ');
	SET @I = 6;
	WHILE @I >= 1 DO
		-- SET @SubMask = RPAD(_Mask_Prefix, @I + 1, _Mask_Char);
		SET @SubMask = CONCAT(_Mask_Prefix, REPEAT(_Mask_Char, @I));
		IF LOCATE(@SubMask, @OutStr) > 0 THEN
			IF _Mask_Prefix_Value = 'CHAR' THEN
				SET @_Value = _Value;
			ELSE	
				-- SET @_Value = LPAD(RIGHT(_Value, @I), @I, _Mask_Prefix_Value);
				SET @_Value = CONCAT(_Value, IF(@I = 1, '', @I));
			END IF;	
			SET @OutStr = REPLACE(@OutStr, @SubMask, CONCAT('<', @_Value, '>'));
			-- SET @I := 1;
		END IF;
		SET @I := @I - 1;
	END WHILE;
	
	RETURN @OutStr;
END$$

DROP FUNCTION IF EXISTS `_Conv_OldMaskToNew`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_Conv_OldMaskToNew`(
	_MODE VARCHAR(255),
	_InputStr VARCHAR(255)
) 
RETURNS VARCHAR(256)
    NO SQL
    DETERMINISTIC
SPROC: BEGIN
/*
	_MODE 
	_InputStr 			Wejsciowy string np '%NNNN/%YYYY-%A'

*/


	SET @OutStr = IFNULL(_InputStr, '');
	IF @OutStr = '' THEN
		RETURN @OutStr;
		LEAVE SPROC;
	END IF;
	
	-- N	Numer (%N)
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'N', 'N', '0');
	-- Y	Rok %Y
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'Y', 'Y', '0');
	-- M	Miesiąc %W
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'W', 'M', '0');
	-- D	dzien
	-- nie bylo SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'Y', 'Y', '0');

	-- MG	Nr Magazynu %M
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'M', 'MG', '0');
	-- MGS	symbol magazynu %A
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'A', 'MGS', '0');
	-- MD	Nr Magazynu docelowego %G
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'G', 'MD', '0');
	-- MDS	symbol Magazynu docelowego symbol %F
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'F', 'MDS', '0');

	-- RD	Rodzaj dowodu %O
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'O', 'RD', '0');
	-- RV	Symbol rejestru vat %V
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'V', 'RV', '0');
	-- U	Ugrp %U
	SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'U', 'U', '0');

	RETURN @OutStr;
END$$


			DROP FUNCTION IF EXISTS `_MaskTool_NEW`$$
			CREATE DEFINER=`root`@`localhost` FUNCTION `_MaskTool_NEW`(
				_MODE VARCHAR(255),
				_InputStr VARCHAR(255),
				_Mask_Chars VARCHAR(5),
				_Value VARCHAR(50),
				_LPad_Value VARCHAR(5)
			) 
			RETURNS VARCHAR(256)
				NO SQL
				DETERMINISTIC
			SPROC: BEGIN
			/*
				_MODE 
				_InputStr 			Wejsciowy string np '%NNNN/%YYYY-%A'
				_Mask_Chars 			np 'N' lub 'M' etc.
				_Value 				co bedziemy wstawiac w maske np. 
										dla _Value = 2345 za %NNNNNNN mamy 002345
										dla _Value = 2010 za %YY mamy 10
				_LPad_Value			Poprzedzajaca wartosc (domyslnie 0 wstawiamy przed numer gdy za krotki 
									przykladowo dla _Value = 2345 za %NNNNNNN mamy 002345
			*/

				SET @OutStr = IFNULL(_InputStr, '');
				IF @OutStr = '' THEN
					RETURN @OutStr;
					LEAVE SPROC;
				END IF;
				SET 
					@Begin = CONCAT('<', _Mask_Chars),
					@I = 1	--	6 razy szukaj podmaski - bo moze rok jest kilka razy?
				;
				WHILE @I >= 1 DO
					SET	@Pocz = LOCATE(@Begin, @OutStr);
					IF @Pocz < 1 THEN
					--	juz nie ma albo w ogole nie ma takiej podmaski
						RETURN @OutStr;
						LEAVE SPROC;
					END IF;
					
					SET @Internal = CONCAT(_Mask_Chars, _Midle_Two_Sep(SUBSTR(@OutStr, @Pocz, 255), @Begin, '>'));
					SET @InternalPad = REPLACE(@Internal, _Mask_Chars, '');
					SET @InternalPadINT = _VarInt(@InternalPad);
					
					IF @InternalPadINT = 0 OR _LPad_Value = 'CHAR' THEN
						SET @_Value = _Value;
					ELSE	
						SET @_Value = LPAD(RIGHT(_Value, @InternalPadINT), @InternalPadINT, _LPad_Value);
					END IF;	

					SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Internal, '>'), @_Value);
					SET @I := @I - 1;
				END WHILE;
					
				
				-- SET @OutStr = _MaskTool_NEW('', @OutStr, _Mask_Chars, _Value, _LPad_Value);
				
				RETURN @OutStr;
			END$$

			DROP FUNCTION IF EXISTS `erp_obj_counters_build_number_text_one_atom`$$
			CREATE DEFINER=`root`@`localhost` FUNCTION `erp_obj_counters_build_number_text_one_atom`(
				_MODE VARCHAR(255),
				_NumMask VARCHAR(250),
				_SectionMask VARCHAR(250),
				_Params VARCHAR(250),
				_LPad_Value VARCHAR(5),
				_Param_A VARCHAR(50),	
				_Param_B VARCHAR(50)	
			) 
			RETURNS VARCHAR(256)
				NO SQL
				DETERMINISTIC
			/*
				SELECT erp_obj_counters_build_number_text_one_atom('', '<N6>/MAG:<MG4>/Rok:<Y4>/<M2>/KOR/<MGS1>-<MD1>', 'N', '<N=112><Y=2014><MG=6><MGS=daleki>', '', '');
			*/
			SPROC: BEGIN
				DECLARE _SectionMaskVALUE, _OUT_NumMask VARCHAR(250);
				SET _SectionMaskVALUE = _Midle_Two_Sep(_Params, CONCAT('<', _SectionMask, '='), '>');
				-- set @_SectionMaskVALUE = _SectionMaskVALUE;
				SET _OUT_NumMask := _MaskTool_NEW('', _NumMask, _SectionMask, _SectionMaskVALUE, _LPad_Value);
				
				RETURN _OUT_NumMask;
			END$$

			
DROP FUNCTION IF EXISTS `erp_obj_counters_build_and_get_number_text`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `erp_obj_counters_build_and_get_number_text`(
	_MODE VARCHAR(255),
	_NumMask VARCHAR(250),
	_Params VARCHAR(250),
	_Param_A VARCHAR(50)	
) 
RETURNS VARCHAR(256)
	NO SQL
	DETERMINISTIC
/*
	erp_obj_counters_build_and_get_number_text('', maska, params, '')
*/
SPROC: BEGIN
	DECLARE _NumerText VARCHAR(250);

	SET _NumerText = IFNULL(_NumMask, '');
	IF _NumerText = '' THEN
		SET _NumerText = _Midle_Two_Sep(_Params, '<N=', '>');
	ELSE
	
		-- MGS	symbol magazynu %A
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MGS', _Params, 'char', '', '');
		-- MDS	symbol Magazynu docelowego symbol %F
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MDS', _Params, 'char', '', '');
		-- MG	Nr Magazynu %M
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MG', _Params, '0', '', '');
		-- MD	Nr Magazynu docelowego %G
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MD', _Params, '0', '', '');

		-- RD	Rodzaj dowodu %O
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RD', _Params, 'char', '', '');
		-- RV	Symbol rejestru vat %V
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RV', _Params, 'char', '', '');
		-- U	Ugrp %U
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'U', _Params, 'char', '', '');
		-- RES	Res GUID
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RES', _Params, 'char', '', '');
		
		-- N	Numer (%N)
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'N', _Params, '0', '', '');
		-- Y	Rok %Y
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'Y', _Params, '0', '', '');
		-- M	Miesiąc %W
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'M', _Params, '0', '', '');
		-- D	dzien
		-- nie bylo SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'Y', 'Y', '0');
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'D', _Params, '0', '', '');

		-- R	rodzaj
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'R', _Params, 'char', '', '');
		-- PR	Podrodzaj - typ z `operdoc_typy` jako INTEGER
		SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'PR', _Params, '0', '', '');

		
	END IF;
	
	RETURN _NumerText;
END$$
			
DROP PROCEDURE IF EXISTS `erp_obj_counters_build_number_text`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_build_number_text`(
	IN _MODE VARCHAR(150),
	INOUT _NumerText VARCHAR(150),
	-- IN _Numer INTEGER,
	IN _NumMask VARCHAR(250),
	IN _Params VARCHAR(250),
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	Glowna procedura budujaca numer tekstowy z paramsow
	CALL erp_obj_counters_build_number_text('', @_NumerText, '<N=112><Y=2014><MG=6><MGS=daleki>', params, '', '');		
	_NumMask	maska
	_Params		zawiera wartosci dla maski UWAGA numer zawarty w parametrze _Params
				UWAGA:
				aby dostac parametry mozna posluzyc sie metoda: `_MaskTool_Fill_Params`
				W _MaskTool_Fill_Params gdy _MODE = 'sofist' to system sam pobierze symbole magazynow etc.

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_build_number_text: BEGIN
	-- DECLARE _SectionMask  VARCHAR(250);
	
	SET _NumerText = IFNULL(_NumMask, '');
	IF _NumerText = '' THEN
		SET _NumerText = _Midle_Two_Sep(_Params, '<N=', '>');
		LEAVE S_erp_obj_counters_build_number_text;
	END IF;
	

	-- MGS	symbol magazynu %A
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MGS', _Params, 'char', '', '');
	-- MDS	symbol Magazynu docelowego symbol %F
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MDS', _Params, 'char', '', '');
	-- MG	Nr Magazynu %M
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MG', _Params, '0', '', '');
	-- MD	Nr Magazynu docelowego %G
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'MD', _Params, '0', '', '');

	-- RD	Rodzaj dowodu %O
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RD', _Params, 'char', '', '');
	-- RV	Symbol rejestru vat %V
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RV', _Params, 'char', '', '');
	-- U	Ugrp %U
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'U', _Params, 'char', '', '');
	-- RES	Res GUID
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'RES', _Params, 'char', '', '');
	
	-- N	Numer (%N)
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'N', _Params, '0', '', '');
	-- Y	Rok %Y
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'Y', _Params, '0', '', '');
	-- M	Miesiąc %W
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'M', _Params, '0', '', '');
	-- D	dzien
	-- nie bylo SET @OutStr = _Conv_OldMaskTool('', @OutStr, '%', 'Y', 'Y', '0');
	SET _NumerText = erp_obj_counters_build_number_text_one_atom('', _NumerText, 'D', _Params, '0', '', '');
	
	
END$$

			DROP FUNCTION IF EXISTS `_MaskTool_Fill_Params`$$
			CREATE DEFINER=`root`@`localhost` FUNCTION `_MaskTool_Fill_Params`(
				_MODE VARCHAR(255),
				_ObjType VARCHAR(200),
				
				_Rodzaj INTEGER,
				_PodRodzaj INTEGER,
				
				_Numer INTEGER,
				_Res1 INTEGER,
				_Res2 INTEGER,
				_ResGUID VARCHAR(38),
				_NumYear INTEGER,
				_NumMonth INTEGER,
				_NumDay INTEGER,
				
				_RodzajDowodu VARCHAR(150),
				_Rv_id VARCHAR(250),
				_UGrpGUID VARCHAR(250),
				_MGS VARCHAR(250),
				_MDS VARCHAR(250)
			) 
			RETURNS VARCHAR(1000)
				NO SQL
				DETERMINISTIC
			SPROC: BEGIN
				
				IF _MODE = 'sofist' THEN
					IF _ObjType  IN ('oper', 'oper_wewn', 'xyz') THEN
						SET @X = '1';
						SELECT Grupa INTO @_GRP FROM `operdoc` WHERE rodzaj = _Rodzaj;
						IF @_GRP IN (@ht.ST, @ht.ZT, @ht.MG, @ht.SI, @ht.ZP, @ht.WE, @ht.ZM, @ht.PR) THEN
						SET @X = '2';
							IF IFNULL(_MGS, '') = '' THEN
						SET @X = '3';
								SET _MGS = IFNULL((SELECT symbol FROM Magazyny WHERE IdnMagazynu = _Res1), '');
								SET @_MGS = _MGS;
							END IF;
							IF IFNULL(_MDS, '') = '' THEN
								SET _MDS = IFNULL((SELECT symbol FROM Magazyny WHERE IdnMagazynu = _Res2), '');
							END IF;
						ELSEIF @_GRP IN (@ht.KS) THEN
							IF IFNULL(_MGS, '') = '' THEN
								SET _MGS = IFNULL((SELECT NazwaKasy FROM kasy WHERE Idn = _Res1), '');
							END IF;
							IF IFNULL(_MDS, '') = '' THEN
								SET _MDS = IFNULL((SELECT NazwaKasy FROM kasy WHERE Idn = _Res2), '');
							END IF;
						ELSEIF @_GRP IN (@ht.BN) THEN
							IF IFNULL(_MGS, '') = '' THEN
								SET _MGS = IFNULL((SELECT NazwaKonta FROM banki WHERE Idn = _Res1), '');
							END IF;
							IF IFNULL(_MDS, '') = '' THEN
								SET _MDS = IFNULL((SELECT NazwaKonta FROM banki WHERE Idn = _Res2), '');
							END IF;
						END IF;
						
						IF IFNULL(_UGrpGUID, '') = '' THEN
							SET _UGrpGUID = IFNULL((SELECT Nazwisko FROM `osoby` WHERE guid= @CCurrUgrpGUID), '');
						END IF;
					END IF;
/*					
dokoncz z tego co ponizej >>>>>>>>>>>>>					
	SET @_NumText = REPLACE(@_NumText, '%V', IFNULL((SELECT IFNULL(symbol, idn) FROM rejestry_vat WHERE idn = _Rv_id), ''));
--	Nr Magazynu docelowego %G
	SET @_NumText = _MaskTool('', @_NumText, '%', 'G', _Res2, '0', 6);
--	Magazyn docelowy symbol	%F
	SET @_NumText = REPLACE(@_NumText, '%F', IFNULL((SELECT symbol FROM Magazyny WHERE IdnMagazynu = _Res2), ''));
--	Ugrp	%U
	SET @_NumText = REPLACE(@_NumText, '%U', IFNULL((SELECT Nazwisko FROM `osoby` WHERE guid= @CCurrUgrpGUID), ''));
<<<<<<<<<<<<<<<<<<					
*/
				END IF;
				
				set @JestemTutaj = '1';
				SET @OutStr = '<N=><R=><PR=><Y=><M=><D=><MG=><MGS=><MD=><MDS=><RES=><RD=><RV=><U=>';
				SET @OutStr = 
					IFNULL(
						(
						SELECT 
							REPLACE(REPLACE(@OutStr, CONCAT('<', 'R', '=>'), CONCAT('<', 'R', '=', odt.Nazwa, '>')), CONCAT('<', 'PR', '=>'), CONCAT('<', 'PR', '=', odt.Typ, '>'))
						 
						FROM `operdoc_typy` odt
						WHERE
							odt.Rodzaj = _Rodzaj
							AND odt.Typ = _PodRodzaj
						LIMIT 1
						), @OutStr
					)
				;
				/*
				bylo
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));	
				SET @Sec = 'R', @Val = ''; -- na razie ''
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));	
				SET @Sec = 'PR', @Val = ''; -- na razie ''
				*/
				
				
				SET @Sec = 'N', @Val = _Numer;
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));	
				SET @Sec = 'Y', @Val = _NumYear;
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'M', @Val = _NumMonth;
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'D', @Val = _NumDay;
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'MG', @Val = IFNULL(_Res1, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'MGS', @Val = IFNULL(_MGS, ''); -- na razie ''
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));	
				SET @Sec = 'MD', @Val = IFNULL(_Res2, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'MDS', @Val = IFNULL(_MDS, ''); -- na razie ''
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'RES', @Val = IFNULL(_ResGUID, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));				

				SET @Sec = 'RD', @Val = IFNULL(_RodzajDowodu, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'RV', @Val = IFNULL(_Rv_id, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				SET @Sec = 'U', @Val = IFNULL(_UGrpGUID, '');
				SET @OutStr = REPLACE(@OutStr, CONCAT('<', @Sec, '=>'), CONCAT('<', @Sec, '=', @Val, '>'));
				
				RETURN @OutStr;
			END$$


			
DROP PROCEDURE IF EXISTS `erp_obj_counters_GetNumber_and_build_number_text`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_GetNumber_and_build_number_text`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	INOUT _NumerText VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER,
	IN _RodzajDowodu VARCHAR(150),
	IN _Rv_id VARCHAR(250),
	IN _UGrpGUID VARCHAR(250),
	IN _MGS VARCHAR(250),
	IN _MDS VARCHAR(250)
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	Glowna procedura budujaca numer tekstowy z paramsow
	DZIAŁA !!!!! 
	np. w zapisach ksiegowych dla KONKOLA aby pobrac numer dok. z ksiazki podawczej :
	CALL erp_obj_counters_GetNumber_and_build_number_text('select', @_Numer, @_NumerText, 'opng.lp_ks_podawcza_str', 104, 0, 0, 0, '', YEAR(%data_dowodu), MONTH(%data_dowodu), DAY(%data_dowodu), '', '', '', '', '');
	_NumMask	maska
	_Params		zawiera wartosci dla maski UWAGA numer zawarty w parametrze _Params
				UWAGA:
				aby dostac parametry mozna posluzyc sie metoda: `_MaskTool_Fill_Params`
				W _MaskTool_Fill_Params gdy _MODE = 'sofist' to system sam pobierze symbole magazynow etc.

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_GetNumber_and_build_number_text: BEGIN
	DECLARE _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
	DECLARE _grp_ResGUID VARCHAR(100);
	DECLARE
		_NumMask,
		_Params VARCHAR(250)
	;	
--	Pobierz numer
					SET @Ycc = '1';
	CALL erp_obj_counters_Get_Props_For_Oper('', _ObjType, _Rodzaj, _PodRodzaj, _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, _NumMask, _Disabled);
					SET @Ycc = '2';
	CALL erp_obj_counters_GetNumber('from.erp_obj_counters_masks', _Numer, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay);
					SET @Ycc = '3';
	SET _Params = _MaskTool_Fill_Params('sofist', _ObjType, _Rodzaj, _PodRodzaj, _Numer, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _RodzajDowodu, _Rv_id, _UGrpGUID, _MGS, _MDS);
					SET @Ycc = '4';
	CALL erp_obj_counters_build_number_text('', _NumerText, _NumMask, _Params, '', '');		
					SET @Ycc = '999';
	
	IF _MODE = 'select' THEN
		SELECT _Numer, _NumerText, _Params, _NumMask, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `erp_obj_counters_GetNumber_simple`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_GetNumber_simple`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	INOUT _NumerText VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER,
	IN _RodzajDowodu VARCHAR(150),
	IN _Rv_id VARCHAR(250),
	IN _UGrpGUID VARCHAR(250),
	IN _MGS VARCHAR(250),
	IN _MDS VARCHAR(250)
)

BEGIN
	DECLARE _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
	DECLARE _grp_ResGUID VARCHAR(100);
	DECLARE _NumMask,_Params VARCHAR(250);	
	CALL erp_obj_counters_Get_Props_For_Oper('', _ObjType, _Rodzaj, _PodRodzaj, _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_ResGUID, _grp_Y, _grp_M, _grp_D, _NumMask, _Disabled);
	CALL erp_obj_counters_GetNumber('from.erp_obj_counters_masks', _Numer, _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay);
	SET _Params = _MaskTool_Fill_Params('sofist', _ObjType, _Rodzaj, _PodRodzaj, _Numer, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _RodzajDowodu, _Rv_id, _UGrpGUID, _MGS, _MDS);
	CALL erp_obj_counters_build_number_text('', _NumerText, _NumMask, _Params, '', '');		
END$$

DROP PROCEDURE IF EXISTS `erp_obj_counters_values_SetNumber`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_values_SetNumber`(
	IN _MODE VARCHAR(150),
	INOUT _Numer INTEGER,
	INOUT _NumerText VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _ID VARCHAR(200),
	IN _TableName VARCHAR(200),
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
			
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	
	CALL erp_obj_counters_values_SetNumber('', @_Numer, @_NumerText, 'opng.nrdokfin', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '', '');
	CALL erp_obj_counters_values_SetNumber('', @_Numer, @_NumerText, 'zmng.nrzamw', '1', '0', '{49C168AE-F889-402B-B834-06122669DE2F}', 'zmng', '', '');

------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_values_SetNumber: BEGIN
	DECLARE _SQLText, _SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum MEDIUMTEXT;
	DECLARE _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
	DECLARE _Result, _NumerText_OLD, _grp_ResGUID VARCHAR(200);
	DECLARE
		_NumMask,
		_Params VARCHAR(250)
	;	
	
	IF _MODE IN ('ponumeruj.mnie', 'get.number.for.ID.and.all.Rodzaj.Podrodzaj') THEN
	/* *************************************************************************************************************************************************************
		Ponumeruj mnie czyli moj rekord 
		1 Sprawdza ile numeratorow istnieje dla mojego rodzaju (podrodzaju) i .. 
		2 dla kazdego wola w petli 
				CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', @_Numer, @_NumerText, 'opng.nrdokfin', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '', '');
		CALL erp_obj_counters_values_SetNumber('get.number.for.ID.and.all.Rodzaj.Podrodzaj', @_Numer, @_NumerText, 'opng', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', '', '', '');
		lub
		CALL erp_obj_counters_values_SetNumber('ponumeruj.mnie', @_Numer, @_NumerText, 'opng', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', '', '', '');
		UWAGA
		_ObjType traktowany bedzie jako like
		ALE
		moze byc ze gdy _Rodzaj = -1 to
			_Param_A musi byc pelny _ObjType i WTEDY moge sobie pozwolic na ponumerowanie bez podawania _Rodzaj 
	**************************************************************************************************************************************************************/
		SET 	
			_Rodzaj = IFNULL(_Rodzaj, -1)
		;
		IF _Rodzaj = -1 AND _Param_A != '' THEN
		--	UWAGA w _Param_A musi byc pelny _ObjType 
		--	WTEDY moge sobie pozwolic na ponumerowanie bez podawania _Rodzaj
			CALL erp_obj_counters_Load_Params('get.params.for.ID.and.ObjType', _Param_A, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');
		END IF;
		--	Pętla przetwarzania
			BEGIN
			-- pozycje receptury
			
				DECLARE done BOOL DEFAULT FALSE;
			--	3.1 Kursor	
				DECLARE c_get_number_for_id_atom CURSOR FOR
					SELECT
						ObjType -- , Rodzaj, PodRodzaj
					FROM `erp_obj_counters_masks` m
					WHERE
						ObjType LIKE CONCAT(_ObjType, '%')
						AND
						Rodzaj = _Rodzaj
						AND
						PodRodzaj = _PodRodzaj
					;	
				
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			--	3.2 Open Kursor	
				OPEN c_get_number_for_id_atom;
				loop_c_get_number_for_id_atom: LOOP
					FETCH c_get_number_for_id_atom INTO 
						_ObjType
					;
					IF done THEN
						LEAVE loop_c_get_number_for_id_atom;
					END IF;
				--	Wykonaj nadawanie numeru
					CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, _ID, _TableName, _Param_A, _Param_B);
					SET @Xcc = '999';
				END LOOP;
				CLOSE c_get_number_for_id_atom;
			
			END;
		
	END IF;
	
	IF _MODE = 'get.number.for.ID.Rodzaj.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca numer i numer tekstowy wraz z 1. sprawdzeniem czy istnieje numer, 2. wstawia numeru
		CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', @_Numer, @_NumerText, 'opng.nrdokfin', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '', '');
		_Param_B	gdy zawiera 'clear.before' to czysci i nalicza ponownie
	**************************************************************************************************************************************************************/
	
		SET 
			_Numer = 0,
			_NumerText = '',
			_NumerText_OLD = NULL,
			@.clear.before = (_Param_B LIKE '%clear.before%'),
			@.update.src.table = (_Param_B LIKE '%update.src.table%')
		;
			SET @X = '1';
		SELECT 
			v.Number_Text
		INTO _NumerText_OLD
		FROM `erp_obj_counters_values` v
		WHERE
			v.ObjType = _ObjType
			AND 
			v.ID = _ID
		;
		SET _NumerText_OLD = IF(@.clear.before, '', IFNULL(_NumerText_OLD, ''));
					SET @Xcc = '2';
		/*
		IF NOT (_NumerText_OLD IN ('', '?')) AND NOT @.clear.before AND NOT @.update.src.table THEN
			SET @X = 'end1';
			LEAVE S_erp_obj_counters_values_SetNumber;
		END IF;
		*/
		IF _NumerText_OLD IN ('', '?') THEN
					SET @Xcc = '3';
			CALL erp_obj_counters_values_SetNumber('make.number.for.ID', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, _ID, _TableName, _Param_A, _Param_B);
					SET @Xcc = '4';
			IF _Numer > 0 THEN

					SET @Xcc = '5';
				INSERT IGNORE INTO `erp_obj_counters_values` 
				SET
					ObjType = _ObjType,
					ID = _ID,
					Number_Text = _NumerText,
					Input_Number = _Numer
				ON DUPLICATE KEY
				UPDATE
					Number_Text = _NumerText,
					Input_Number = _Numer
				;			
				SET _NumerText_OLD = _NumerText;
			END IF;
		END IF;
		
		IF @.update.src.table THEN
					SET @Xcc = '6';
			CALL erp_obj_counters_values_SQL_UpdateNum('', _NumerText_OLD, _ObjType, _ID, _TableName, _Numer, '');
		END IF;
		
					SET @Xcc = '7';
	END IF;

	IF _MODE = 'make.number.for.ID' THEN
	/* *************************************************************************************************************************************************************
		Zwraca numer i numer tekstowy (ale ... 1. nie sprawdza czy istnieje numer, 2. nie wstawia numeru
		CALL erp_obj_counters_values_SetNumber('make.number.for.ID', @_Numer, @_NumerText, 'opng.nrdokfin', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '', '');
		
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters_Load_Params('get.params.for.ID.and.ObjType', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');
		SET @X = _Result;
		IF _Result != '' THEN
			SET @X = _Result;
			LEAVE S_erp_obj_counters_values_SetNumber;
		END IF;
		
		/*
		SET 	
			_Rodzaj = IFNULL(_Rodzaj, -1),
			_PodRodzaj = IFNULL(_PodRodzaj, -1),
			_Numer = 0,
			_NumerText = '',
			_SQLText_SQL_GetParams = '', 
			_SQLText_SQL_UpdateNum = '',
			@erp_obj_counters._Rodzaj = NULL
		;
					SET @X = '1';
		IF _Rodzaj = -1 THEN
			set _PodRodzaj = IFNULL(_PodRodzaj, -1);
		END IF;
		
		SELECT
			m.Mask, 
			m.Rodzaj, m.Podrodzaj, 
			IFNULL(m.SQL_GetParams, d.SQL_GetParams) AS SQL_GetParams,
			IFNULL(m.SQL_UpdateNum, d.SQL_UpdateNum) AS SQL_UpdateNum,
			IFNULL(m.TableName, d.TableName) AS TableName,
			m.Disabled
		FROM `erp_obj_counters_masks` m1
		INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji
		INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m1.ObjType
		WHERE
			m1.ObjType = _ObjType
			AND m1.Rodzaj = _Rodzaj
			AND m1.Podrodzaj = _Podrodzaj
		INTO
			_NumMask,
			_Rodzaj_N, _Podrodzaj_N, 
			_SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum, @TableName,
			_Disabled
		;
		IF _Disabled THEN
			SET @X = 'end2';
			LEAVE S_erp_obj_counters_values_SetNumber;
		END IF;
		
			SET @X = '2';
		
		SET _TableName = IF(IFNULL(_TableName, '') = '', @TableName, _TableName);
		
		IF _SQLText_SQL_GetParams = '' THEN
			SET @X = 'end3';
			LEAVE S_erp_obj_counters_values_SetNumber;
		END IF;
		
		SET _SQLText = _SQLText_SQL_GetParams;
		SET _SQLText = REPLACE(_SQLText, '#TABLENAME#', _TableName);
		SET _SQLText = REPLACE(_SQLText, '#ID#', _ID);
		SET @_SQLText = _SQLText;
		
		SET @_SQLText1111 = _SQLText;
		SET @__SQLText_SQL_GetParams = _SQLText_SQL_GetParams;
		
		*/
		
		/*
		Teraz Execute Query  aby wstawic dane do zmiennych:
				@erp_obj_counters._Rodzaj,
				@erp_obj_counters._Podrodzaj,
				@erp_obj_counters._Res1,
				@erp_obj_counters._Res2,
				@erp_obj_counters._ResGUID,
				@erp_obj_counters._NumYear,
				@erp_obj_counters._NumMonth,
				@erp_obj_counters._NumDay
		*/

		/*
		CALL _ExecuteCmd(_SQLText, @Error);

		IF @erp_obj_counters._Rodzaj IS NULL THEN
			SET @X = 'end4';
			LEAVE S_erp_obj_counters_values_SetNumber;
		END IF;
		*/
		
		CALL erp_obj_counters_Get_INC_Number('', 
				@_Numer, _ObjType, 
				@erp_obj_counters._Rodzaj,
				@erp_obj_counters._Podrodzaj,
				@erp_obj_counters._Res1,
				@erp_obj_counters._Res2,
				@erp_obj_counters._ResGUID,
				@erp_obj_counters._NumYear,
				@erp_obj_counters._NumMonth,
				@erp_obj_counters._NumDay
		);		

		
		IF @_Numer > 0 THEN
			SET _Numer = @_Numer;
			SET _Params = 
				_MaskTool_Fill_Params('', _ObjType, _Rodzaj_N, _Podrodzaj_N, _Numer, 
				@erp_obj_counters._Res1, @erp_obj_counters._Res2, @erp_obj_counters._ResGUID, 
				@erp_obj_counters._NumYear, @erp_obj_counters._NumMonth, @erp_obj_counters._NumDay, 
				@erp_obj_counters._RodzajDowodu, @erp_obj_counters._Rv_id, @erp_obj_counters._UGrpGUID, @erp_obj_counters._MGS, @erp_obj_counters._MDS)
			;
			CALL erp_obj_counters_build_number_text('', _NumerText, _NumMask, _Params, '', '');		

		END IF;
	END IF;


				IF _MODE = 'prepare.t_erp_obj_counters_inputs' THEN
					SET 
						_Numer = 0,
						_NumerText = ''
					;
				
					SET @X = 'prepare.t_erp_obj_counters_inputs';
					DROP TEMPORARY TABLE IF EXISTS `t_erp_obj_counters_inputs`;
					CREATE TEMPORARY TABLE `t_erp_obj_counters_inputs` (
					  `in_ObjType` VARCHAR(200) NOT NULL DEFAULT 'opng.nrdokfin' COMMENT 'ID numeratora - Klasa obiektow numeracji ("oper", "oper_wewn", "crm", etc.)',
					  `in_Rodzaj` INTEGER,
					  `in_PodRodzaj` INTEGER,
					  `in_Rodzaj_N` INTEGER,
					  `in_PodRodzaj_N` INTEGER,
					  `in_SrcObjType` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'zrodlo - Klasa obiektow numeracji ("oper", "oper_wewn", "crm", etc.)',
					  `in_ID` VARCHAR(250) DEFAULT '' COMMENT 'Identyfikator np. dokumentu',
					  `in_Manual_Set` INTEGER NOT NULL DEFAULT 0 COMMENT 'gdy 1 to wstawiane reczne',
					  `in_Clear_Before` INTEGER NOT NULL DEFAULT 0 COMMENT 'gdy 1 to zawsze nadajemy numer od nowa',
					  `in_Update_Src_Table` INTEGER NOT NULL DEFAULT 0 COMMENT 'gdy 1 to przepisujemy numer sql-ka z pola `inf_SQL_UpdateNum` ',
					  `out_Numer` INTEGER NOT NULL DEFAULT 0 COMMENT 'zapamietany sam numer',
					  `out_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'numer tekstowy',
					  `inf_prev_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'stary numer tekstowy z `erp_obj_counters_values`',
					  `inf_old_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'stary numer tekstowy dokumentu',
					  `inf_TableName` VARCHAR(250) DEFAULT '' COMMENT 'Nazwa tabeli',
					  `inf_Disabled` INTEGER NOT NULL DEFAULT 0 COMMENT 'czy automatyczna',
					  `inf_Update_Old_Field` VARCHAR(250) DEFAULT '' COMMENT 'Czy robic update sqlka z pola SQL_UpdateNum',
					  `inf_SQL_GetParams` MEDIUMTEXT COMMENT 'SQL dla pobierania danych',
					  `inf_SQL_UpdateNum` MEDIUMTEXT COMMENT 'SQL dla wstawienie numeru do jakiejs tabeli ',
					  `inf_NumMask` VARCHAR(250) DEFAULT '',
					  `inf_GUI_Ctrl_option` SET('AutoNum','ManualNum','EditedNum') DEFAULT 'AutoNum,ManualNum,EditedNum',
					  `p_Res1` INTEGER,
					  `p_Res2` INTEGER,
					  `p_ResGUID` VARCHAR(38),
					  `p_NumYear` INTEGER,
					  `p_NumMonth` INTEGER,
					  `p_NumDay` INTEGER,
					  `p_RodzajDowodu` VARCHAR(250) DEFAULT '',
					  `p_Rv_id` VARCHAR(250) DEFAULT '',
					  `p_UGrpGUID` VARCHAR(250) DEFAULT '',
					  `p_MGS` VARCHAR(250) DEFAULT '',
					  `p_MDS` VARCHAR(250) DEFAULT '',
					  `p_Params` VARCHAR(250) DEFAULT '',
					  PRIMARY KEY (`in_ObjType`,`in_ID`)
					)
					;
			-- @.clear.before = (_Param_B LIKE '%clear.before%'),
			-- @.update.src.table = (_Param_B LIKE '%update.src.table%')
set @JestemTutaj = null;
			
set @JestemTutaj = concat_WS('>', @JestemTutaj, '1');					
					INSERT IGNORE INTO `t_erp_obj_counters_inputs`	
					(in_ObjType, in_Rodzaj, in_PodRodzaj, in_Rodzaj_N, in_PodRodzaj_N, in_ID, in_Manual_Set, in_Clear_Before, in_Update_Src_Table, out_Numer, out_NumerText, inf_prev_NumerText, inf_TableName, inf_Disabled, inf_Update_Old_Field, inf_SQL_GetParams, inf_SQL_UpdateNum, inf_NumMask, inf_GUI_Ctrl_option)
						SELECT
							m.ObjType AS in_ObjType,
							m1.Rodzaj AS in_Rodzaj, 
							m1.Podrodzaj AS in_Podrodzaj, 
							m.Rodzaj AS in_Rodzaj_N, 
							m.Podrodzaj AS in_Podrodzaj_N, 
							_ID AS in_ID,
							(_Param_B LIKE '%manual.set%') AS in_Manual_Set,
							IF(IFNULL(v.Number_Text, '') IN ('','?'), 
								TRUE, 
								(_Param_B LIKE '%clear.before%')
							) AS in_Clear_Before,
							(_Param_B LIKE '%update.src.table%') OR (m.Update_Old_Field != 'NO') AS in_Update_Src_Table,
							0 AS out_Numer,
							'' AS out_NumerText,
							IFNULL(v.Number_Text, '') AS inf_prev_NumerText,
							IF(IFNULL(_TableName, '') != '', 
								_TableName,
								IFNULL(m.TableName, d.TableName)
							) AS inf_TableName,
							m.Disabled AS inf_Disabled,
							m.Update_Old_Field AS inf_Update_Old_Field,
							IF(IFNULL(m.SQL_GetParams, '') != '', m.SQL_GetParams, d.SQL_GetParams) AS inf_SQL_GetParams,
							IF(IFNULL(m.SQL_UpdateNum, '') != '', m.SQL_UpdateNum, d.SQL_UpdateNum) AS inf_SQL_UpdateNum,
							m.Mask AS inf_NumMask,
							m.GUI_Ctrl_option
						FROM `erp_obj_counters_masks` m1
						INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji
						INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m1.ObjType
						LEFT JOIN `erp_obj_counters_values` v ON v.ID = _ID AND v.ObjType = m.ObjType
						WHERE
							-- m1.ObjType LIKE _ObjType
							m1.ObjType LIKE CONCAT(_ObjType, '%')
							AND m1.Rodzaj = _Rodzaj
							AND m1.Podrodzaj = _Podrodzaj
					;
set @JestemTutaj = concat_WS('>', @JestemTutaj, '2');
					
UPDATE `t_erp_obj_counters_inputs` t
set in_SrcObjType = 'opng.lp_ks_podawcza_str'
where in_ObjType = 'opng.nrwewn' and in_Rodzaj_N = 104;

					UPDATE `t_erp_obj_counters_inputs` t
					SET
						t.inf_Disabled = t.inf_Disabled AND NOT t.in_Manual_Set,	--	 Disabled tylko gdy Disabled w ustawieniach i automatyczne nadawanie
						t.inf_SQL_GetParams = 
							REPLACE(REPLACE(t.inf_SQL_GetParams, '#TABLENAME#', t.inf_TableName), '#ID#', t.in_ID),
						t.inf_SQL_UpdateNum = 
							REPLACE(REPLACE(t.inf_SQL_UpdateNum, '#TABLENAME#', t.inf_TableName), '#ID#', t.in_ID)
					;

set @JestemTutaj = concat_WS('>', @JestemTutaj, '3');


				--	Nadawanie numerow - Pętla przetwarzania
					BEGIN
					
						DECLARE done BOOL DEFAULT FALSE;
					--	Kursor	
						DECLARE c_t_erp_obj_counters_inputs_1 CURSOR FOR
							SELECT
								in_ObjType, in_Rodzaj_N, in_PodRodzaj_N,
								inf_SQL_GetParams, inf_SQL_UpdateNum
							FROM `t_erp_obj_counters_inputs` t
							WHERE
								NOT t.inf_Disabled
								AND
								t.in_Clear_Before
								AND
								(t.in_SrcObjType = '')
						;	
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
					--	Open Kursor	
						OPEN c_t_erp_obj_counters_inputs_1;
						loop_c_t_erp_obj_counters_inputs_1: LOOP
							FETCH c_t_erp_obj_counters_inputs_1 INTO 
								_ObjType, _Rodzaj_N, _PodRodzaj_N,
								_SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum
							;
							IF done THEN
								LEAVE loop_c_t_erp_obj_counters_inputs_1;
							END IF;
						--	Wykonaj nadawanie numeru
							SET _SQLText = _SQLText_SQL_GetParams;
							SET @_SQLText = _SQLText;
							SET @erp_obj_counters.exit = NULL;
							CALL _ExecuteCmd(_SQLText, @Error);
							
							UPDATE `t_erp_obj_counters_inputs` t
							SET
								inf_old_NumerText = @erp_obj_counters._Number,
								p_Res1 = @erp_obj_counters._Res1,
								p_Res2 = @erp_obj_counters._Res2,
								p_ResGUID = @erp_obj_counters._ResGUID,
								p_NumYear = @erp_obj_counters._NumYear,
								p_NumMonth = @erp_obj_counters._NumMonth,
								p_NumDay = @erp_obj_counters._NumDay,
								p_RodzajDowodu = @erp_obj_counters._RodzajDowodu,
								p_Rv_id = @erp_obj_counters._Rv_id,
								p_UGrpGUID = @erp_obj_counters._UGrpGUID,
								p_MGS = @erp_obj_counters._MGS,
								p_MDS = @erp_obj_counters._MDS
							WHERE
								t.in_ObjType = _ObjType AND t.in_Rodzaj_N = _Rodzaj_N AND t.in_PodRodzaj_N = _PodRodzaj_N
							;
							SET @erp_obj_counters.exit = IFNULL(@erp_obj_counters.exit, FALSE);
							IF _Param_B LIKE '%exit.if.old.field.not.empty%' OR @erp_obj_counters.exit THEN
							--	UWAGA TUTAJ chcemy by nie nadawac W OGOLE numeru gdy 
							--	1. przerzucamy wartosci (inf_Update_Old_Field != 'NO')
							--	2. a wartosci starych pol (np nrdokfin etc) sa nie puste (inf_old_NumerText <> '')
								UPDATE `t_erp_obj_counters_inputs` t
								SET
									t.inf_Disabled = (IFNULL(t.inf_old_NumerText, '') != '') OR @erp_obj_counters.exit
								WHERE
									t.in_ObjType = _ObjType AND t.in_Rodzaj_N = _Rodzaj_N AND t.in_PodRodzaj_N = _PodRodzaj_N
									AND
									t.in_Clear_Before
									AND
									inf_Update_Old_Field != 'NO'
								;
							END IF;
							
							/* 
							NADAWANIE NUMERU
							*/
set @JestemTutaj = concat_WS('>', @JestemTutaj, 'ins');
							INSERT INTO `erp_obj_counters`
							(
								`Nr`,
								`ObjType`,
								`Rodzaj`,
								`Podrodzaj`,
								`Res1`,
								`Res2`,
								`ResGUID`,
								`Y`,
								`M`,
								`D`
							)
								SELECT
									@erp_obj_counters.Number := t.out_Numer + 1, 
									t.in_ObjType,
									t.in_Rodzaj_N,
									t.in_Podrodzaj_N,
									IF(m.Grp_Res1 = 1, t.p_Res1, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
									IF(m.Grp_Res2 = 1, t.p_Res2, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy	
									IF(m.Grp_ResGUID, t.p_ResGUID, ''),	
									IF(m.Grp_Y, t.p_NumYear, 0),
									IF(m.Grp_M, t.p_NumMonth, 0),
									IF(m.Grp_D, t.p_NumDay, 0)
									
									-- m.Rodzaj, m.Podrodzaj, 
									-- m.grp_Res1, m.grp_Res2, m.grp_ResGUID, m.grp_Y, m.grp_M, m.grp_D, m.Disabled
								FROM `t_erp_obj_counters_inputs` t
								INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = t.in_ObjType AND m.Rodzaj = t.in_Rodzaj_N AND m.Podrodzaj = t.in_Podrodzaj_N
								WHERE
									t.in_ObjType = _ObjType AND t.in_Rodzaj_N = _Rodzaj_N AND t.in_PodRodzaj_N = _PodRodzaj_N
									AND
									NOT t.inf_Disabled
							ON DUPLICATE KEY
							UPDATE
								`Nr` = @erp_obj_counters.Number := (`Nr` + 1)
							;
							SET _Numer = IFNULL(@erp_obj_counters.Number, 0);
							/* */
							
set @JestemTutaj = concat_WS('>', @JestemTutaj, 'upd');
							UPDATE `t_erp_obj_counters_inputs` t
							SET 
								out_Numer = IFNULL(@erp_obj_counters.Number, 0),
								p_Params = 
									_MaskTool_Fill_Params('', in_ObjType, in_Rodzaj, in_PodRodzaj, IFNULL(@erp_obj_counters.Number, 0), 
									p_Res1, p_Res2, p_ResGUID, 
									p_NumYear, p_NumMonth, p_NumDay, 
									p_RodzajDowodu, p_Rv_id, p_UGrpGUID, p_MGS, p_MDS)
							WHERE
								t.in_ObjType = _ObjType AND t.in_Rodzaj_N = _Rodzaj_N AND t.in_PodRodzaj_N = _PodRodzaj_N
								AND
								NOT t.inf_Disabled
							;
							-- CALL erp_obj_counters_build_number_text('', _NumerText, _NumMask, _Params, '', '');		
						END LOOP;
						CLOSE c_t_erp_obj_counters_inputs_1;
					
					END;
					SET @out_NumerText = NULL;
					UPDATE `t_erp_obj_counters_inputs` t
					SET 
						out_NumerText = @out_NumerText := 
							erp_obj_counters_build_and_get_number_text('', t.inf_NumMask, t.p_Params, '')
					WHERE
						NOT t.inf_Disabled
						AND
						t.in_Clear_Before
						AND
						(t.in_SrcObjType = '')
					;
					SET _NumerText = @out_NumerText;

				--	WSTAW juz numery i numeryteksty do `erp_obj_counters_values` 
					INSERT IGNORE INTO `erp_obj_counters_values` 
					(ObjType, ID, Number_Text, Input_Number)
						SELECT	
							t.in_ObjType,
							t.in_ID,
							t.out_NumerText,
							t.out_Numer
						FROM `t_erp_obj_counters_inputs` t
						WHERE
							NOT t.inf_Disabled
							AND
							t.in_Clear_Before
							AND
							(t.in_SrcObjType = '')
					ON DUPLICATE KEY
					UPDATE
						Number_Text = IF(t.in_Clear_Before, t.out_NumerText, Number_Text),
						Input_Number = IF(t.in_Clear_Before, t.out_Numer, Input_Number)
					;			
	--	Teraz ustaw te krore biora zrodlo z innych czyli maj t.in_SrcObjType != ''
		UPDATE `t_erp_obj_counters_inputs` t, `erp_obj_counters_values` v
		SET 
			t.out_NumerText = v.Number_Text,
			t.out_Numer = v.Input_Number
		WHERE
			NOT t.inf_Disabled
			AND
			t.in_Clear_Before
			AND
			(t.in_SrcObjType != '')
			AND
			v.ID = t.in_ID
			AND
			v.ObjType = t.in_SrcObjType
		;
	--	WSTAW juz numery i numeryteksty do `erp_obj_counters_values` 
		INSERT IGNORE INTO `erp_obj_counters_values` 
		(ObjType, ID, Number_Text, Input_Number)
			SELECT	
				t.in_ObjType,
				t.in_ID,
				t.out_NumerText,
				t.out_Numer
			FROM `t_erp_obj_counters_inputs` t
			WHERE
				NOT t.inf_Disabled
				AND
				t.in_Clear_Before
				AND
				(t.in_SrcObjType != '')
		ON DUPLICATE KEY
		UPDATE
			Number_Text = IF(t.in_Clear_Before, t.out_NumerText, Number_Text),
			Input_Number = IF(t.in_Clear_Before, t.out_Numer, Input_Number)
		;			

					
				--	Teraz ustaw UPDATE Sql jesli bedzie update np. opng
					UPDATE `t_erp_obj_counters_inputs` t
					SET 
						t.inf_SQL_UpdateNum = 
							REPLACE(
								REPLACE(
								t.inf_SQL_UpdateNum, '#NUMBER#', 
									IF(t.in_Clear_Before,
										out_NumerText,
										inf_prev_NumerText
									)
								),
								'#ALWAYS#',
								IF(t.inf_Update_Old_Field = 'IF_EMPTY',
									'FALSE',
									'TRUE'
								)
							)
					WHERE
						t.in_Update_Src_Table
						-- AND NOT t.inf_Disabled
					;

					
				--	Zapis do pol np opng_e i innych Pętla przetwarzania
					BEGIN
						DECLARE done BOOL DEFAULT FALSE;
						DECLARE c_t_erp_obj_counters_inputs_2 CURSOR FOR
							SELECT
								inf_SQL_UpdateNum
							FROM `t_erp_obj_counters_inputs` t
							WHERE
								t.in_Update_Src_Table
								-- AND NOT t.inf_Disabled
							;	
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
					--	3.2 Open Kursor	
						OPEN c_t_erp_obj_counters_inputs_2;
						loop_c_t_erp_obj_counters_inputs_2: LOOP
							FETCH c_t_erp_obj_counters_inputs_2 INTO 
								_SQLText_SQL_UpdateNum
							;
							IF done THEN
								LEAVE loop_c_t_erp_obj_counters_inputs_2;
							END IF;
						--	Wykonaj nadawanie numeru
							SET _SQLText = _SQLText_SQL_UpdateNum;
							SET @_SQLText = _SQLText;
							
							CALL _ExecuteCmd(_SQLText, @Error);
							
						END LOOP;
						CLOSE c_t_erp_obj_counters_inputs_2;
					
					END;
					
				END IF;
				

				
				IF _MODE LIKE 'opng_e.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, '', 'rodzaj', 'podrodzaj', GUID, '', '', '');
					_ID  GUID 
					CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.APPLY', @_Numer, @_NumerText, '', '', '', GUID, '', '', '');
					_ID  GUID 
					CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.CLEAR', @_Numer, @_NumerText, '', '', '', GUID, '', '', '');
					_ID  GUID 
					CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.Set.AutoNum', @_Numer, @_NumerText, '', '', '', GUID, '', '', '');
					_ID  GUID 
					_ObjType	TO Numer pola 1 to ObjType_1 , 2 to ObjType_2 itd
					etc
					
ALTER TABLE `operdoc_typy`   
  ADD COLUMN `counter` ENUM('NUMDOK','OBJ_COUNTERS') DEFAULT 'NUMDOK' NOT NULL  COMMENT 'Typ numeratora' AFTER `substatus_after`
;
					

				**************************************************************************************************************************************************************/
					IF _MODE = 'opng_e.erp_obj_counters_values_e_1_rec.INIT' THEN
						SELECT counter INTO @NEW.counter FROM `operdoc_typy` ot WHERE ot.Rodzaj = _Rodzaj AND ot.Typ = _PodRodzaj;
						SET @NEW.Is_Obj_Counters = (@NEW.counter = 'OBJ_COUNTERS');
						
						INSERT IGNORE INTO `erp_obj_counters_values_e_1_rec`
						(ID, Is_Obj_Counters, Update_Mode)
						VALUES
						(_ID, @NEW.Is_Obj_Counters, '')
						ON DUPLICATE KEY
						UPDATE
							Update_Mode = ''
						;
						
						
						DROP TEMPORARY TABLE IF EXISTS `t_erp_obj_counters_values_e_1_rec`;
						SET @LP = 0;
						
						IF @NEW.Is_Obj_Counters THEN
						--	Nowa numeracja
							CREATE TEMPORARY TABLE `t_erp_obj_counters_values_e_1_rec`
							SELECT
								@LP := @LP + 1 AS LP, 
								d.ObjType, d.Descr,
								v.Number_Text,
								m.GUI_Ctrl_option
							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 = _ID AND v.ObjType = m.ObjType
							WHERE
								m.Rodzaj = _Rodzaj AND m.PodRodzaj = _PodRodzaj
							ORDER BY 
								IF(d.ObjType = 'opng.nrdokfin', 0, 
									IF(d.ObjType = 'opng.nrwewn', 1, 
									  IF(d.ObjType = 'opng.nrdokmag', 2, 3)
									) 
								)		
							; 
						ELSE
						--	Stara numeracja
							CREATE TEMPORARY TABLE `t_erp_obj_counters_values_e_1_rec`
							SELECT
								@LP := @LP + 1 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
							FROM `opng_e` n
							INNER JOIN `erp_obj_counters_masks` m ON m.Rodzaj = n.Rodzaj AND m.PodRodzaj = 0
							INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m.ObjType
							-- INNER JOIN `opng` v ON v.GUID = @IdnOper
							WHERE
								n.GUID = _ID
								
								AND d.ObjType IN ('opng.nrdokfin', 'opng.nrwewn', 'opng.nrdokmag')
							ORDER BY 
								IF(d.ObjType = 'opng.nrdokfin', 0, 
									IF(d.ObjType = 'opng.nrwewn', 1, 
									  IF(d.ObjType = 'opng.nrdokmag', 2, 3)
									) 
								)		
							; 
						
						
						END IF;
							
						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
						; 
						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 = _ID
				
						;
						
					END IF;
					
					IF _MODE = 'opng_e.erp_obj_counters_values_e_1_rec.APPLY' THEN
					
						
						SET @NEW.ObjType_1 = NULL, @NEW.ObjType_2 = NULL, @NEW.ObjType_3 = NULL, @NEW.ObjType_4 = NULL, @NEW.ObjType_5 = NULL; 
						SELECT 
							Is_Obj_Counters, ObjType_1, ObjType_2, ObjType_3, ObjType_4, ObjType_5
						INTO
							@NEW.Is_Obj_Counters,
							@NEW.ObjType_1, @NEW.ObjType_2, @NEW.ObjType_3, @NEW.ObjType_4, @NEW.ObjType_5
						FROM `erp_obj_counters_values_e_1_rec`
						WHERE
							ID = _ID
						;
						IF @NEW.Is_Obj_Counters THEN
						--	Nowa numeracja
							SET @I = 1;
							WHILE @I <= 5 DO
								SET _SQLText = "
								INSERT IGNORE INTO `erp_obj_counters_values` 
								(ID, ObjType, Number_Text)
								SELECT
									aNEW.ID, aNEW.ObjType_#@I#, aNEW.Number_Text_#@I#
								FROM `erp_obj_counters_values_e_1_rec` aNEW
								WHERE
									aNEW.ID = '#_ID#'
									AND
									aNEW.ObjType_#@I# IS NOT NULL
								ON DUPLICATE KEY
								UPDATE
									Number_Text = aNEW.Number_Text_#@I#
								;			
								";
								SET _SQLText = REPLACE(REPLACE(_SQLText, '#@I#', @I), '#_ID#', _ID);
								SET @_SQLText = _SQLText;
								CALL _ExecuteCmd(_SQLText, @Error);
							
								SET @I := @I + 1;
							END WHILE;
						ELSE
						--	Stara numeracja
							UPDATE `opng_e` n, `erp_obj_counters_values_e_1_rec` r1
							SET
								n.nrdokfin = r1.Number_Text_1, 
								n.nrwewn = r1.Number_Text_2, 
								n.nrdokmag = r1.Number_Text_3
							WHERE
								n.GUID = _ID
								AND
								r1.ID = _ID
								
							;
						END IF;
						/*
						UPDATE `erp_obj_counters_values_e_1_rec`
						SET
							Update_Mode = 'editor'
						WHERE
							ID = _ID
						;
						*/
						CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.INIT', @_Numer, @_NumerText, _ObjType, _Rodzaj, _Podrodzaj, _ID, _TableName, _Param_A, _Param_B);
					END IF;

					IF _MODE = 'opng_e.erp_obj_counters_values_e_1_rec.Set.AutoNum' THEN
						SET _SQLText = 
						"SELECT ObjType_#ObjType_# INTO @ObjType FROM `erp_obj_counters_values_e_1_rec` WHERE ID = '#_ID#';"
						;
						SET _SQLText = REPLACE(REPLACE(_SQLText, '#ObjType_#', _ObjType), '#_ID#', _ID);
						SET @_SQLText = _SQLText;
						CALL _ExecuteCmd(_SQLText, @Error);
						
						CALL erp_obj_counters_values_SetNumber('prepare.t_erp_obj_counters_inputs', @_Numer, @_NumerText, @ObjType, _Rodzaj, _Podrodzaj, _ID, _TableName, _Param_A, 'clear.before');
						CALL erp_obj_counters_values_SetNumber('opng_e.erp_obj_counters_values_e_1_rec.INIT', @_Numer, @_NumerText, @ObjType, _Rodzaj, _Podrodzaj, _ID, _TableName, _Param_A, _Param_B);
					END IF;
					
					IF _MODE = 'opng_e.erp_obj_counters_values_e_1_rec.CLEAR' THEN
						DELETE FROM `erp_obj_counters_values_e_1_rec`
						WHERE
							ID = _ID
						;
					END IF;
				END IF;
				
				
	IF _MODE LIKE 'dokumenty.z.t_guidy_do_numeracji.%' THEN
	/* *************************************************************************************************************************************************************
		CALL erp_obj_counters_values_SetNumber('dokumenty.z.t_guidy_do_numeracji.create', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, '', _TableName, _Param_A, _Param_B);
		CALL erp_obj_counters_values_SetNumber('dokumenty.z.t_guidy_do_numeracji.ponumeruj.mnie', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, '', _TableName, _Param_A, _Param_B);
		lub
		CALL erp_obj_counters_values_SetNumber('dokumenty.z.t_guidy_do_numeracji.ponumeruj.by.ObjType', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, '', _TableName, _Param_A, _Param_B);
		CALL erp_obj_counters_values_SetNumber('dokumenty.z.t_guidy_do_numeracji.drop', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, '', _TableName, _Param_A, _Param_B);
	**************************************************************************************************************************************************************/
		IF _MODE = 'dokumenty.z.t_guidy_do_numeracji.create' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_guidy_do_numeracji`;
			CREATE TEMPORARY TABLE `t_guidy_do_numeracji` (
			  `ID` VARCHAR(250) DEFAULT '' COMMENT 'Identyfikator np. dokumentu',
			  PRIMARY KEY (`ID`)
			)
			;
		ELSEIF _MODE = 'dokumenty.z.t_guidy_do_numeracji.drop' THEN
			DROP TEMPORARY TABLE IF EXISTS `t_guidy_do_numeracji`;
		ELSE
		
		--	Pętla przetwarzania
			BEGIN
			-- pozycje receptury
			
				DECLARE done BOOL DEFAULT FALSE;
				DECLARE _ID_TMP VARCHAR(38);
			--	3.1 Kursor	
				DECLARE c_t_guidy_do_numeracji CURSOR FOR
					SELECT
						ID -- , Rodzaj, PodRodzaj
					FROM `t_guidy_do_numeracji`
					;	
				
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			--	3.2 Open Kursor	
				OPEN c_t_guidy_do_numeracji;
				loop_c_t_guidy_do_numeracji: LOOP
					FETCH c_t_guidy_do_numeracji INTO 
						_ID_TMP
					;
					IF done THEN
						LEAVE loop_c_t_guidy_do_numeracji;
					END IF;
				--	Wykonaj nadawanie numeru
					IF _MODE = 'dokumenty.z.t_guidy_do_numeracji.ponumeruj.mnie' THEN
						CALL erp_obj_counters_values_SetNumber('ponumeruj.mnie', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, _ID_TMP, _TableName, _Param_A, _Param_B);
					ELSEIF _MODE = 'dokumenty.z.t_guidy_do_numeracji.ponumeruj.by.ObjType' THEN
						CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', _Numer, _NumerText, _ObjType, _Rodzaj, _Podrodzaj, _ID_TMP, _TableName, _Param_A, _Param_B);
					END IF;
				END LOOP;
				CLOSE c_t_guidy_do_numeracji;
			
			END;
		END IF;
	END IF;
	
	
END$$



			DROP PROCEDURE IF EXISTS `erp_obj_counters_Load_Params`$$
			CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_Load_Params`(
				IN _MODE VARCHAR(150),
				IN _ObjType VARCHAR(200),
				INOUT _Rodzaj INTEGER,
				INOUT _PodRodzaj INTEGER,
				IN _ID VARCHAR(200),
				INOUT _TableName VARCHAR(200),
				INOUT _NumMask VARCHAR(250),
				INOUT _Result VARCHAR(200),
				IN _Input_SQLText MEDIUMTEXT,
				IN _Param_A VARCHAR(50),	
				IN _Param_B VARCHAR(50)	
			)
						
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				
				CALL erp_obj_counters_Load_Params('load.params.by._Input_SQLText', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');

			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			S_erp_obj_counters_Load_Params: BEGIN
				DECLARE _ParamsLoaded BOOLEAN DEFAULT FALSE;
				DECLARE _SQLText, _SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum MEDIUMTEXT;
				DECLARE _Rodzaj_N, _PodRodzaj_N, _Disabled INTEGER;
				IF _MODE = 'load.params.by._Input_SQLText' THEN
				/* *************************************************************************************************************************************************************
					Laduje @erp_obj_counters.xxxx z sqlki zawartej w _Input_SQLText (wstawiamy tam  _SQLText_SQL_GetParams
					CALL erp_obj_counters_Load_Params('load.params.by._Input_SQLText', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');
					
				**************************************************************************************************************************************************************/
					IF IFNULL(_Input_SQLText, '') = '' THEN
						SET _Result = 'Brak _SQLText_SQL_GetParams';
						LEAVE S_erp_obj_counters_Load_Params;
					END IF;
					
					SET @erp_obj_counters._Rodzaj = NULL;
					
					SET _SQLText = _Input_SQLText;											SET @__SQLText_SQL_GetParams = _Input_SQLText;
					SET _SQLText = REPLACE(_SQLText, '#TABLENAME#', _TableName);
					SET _SQLText = REPLACE(_SQLText, '#ID#', _ID);
					/*
					Teraz Execute Query  aby wstawic dane do zmiennych:
							@erp_obj_counters._Rodzaj,
							@erp_obj_counters._Podrodzaj,
							@erp_obj_counters._Res1,
							@erp_obj_counters._Res2,
							@erp_obj_counters._ResGUID,
							@erp_obj_counters._NumYear,
							@erp_obj_counters._NumMonth,
							@erp_obj_counters._NumDay
					*/
					SET @_SQLText = _SQLText;
					SET @_SQLText1111 = _SQLText;
					CALL _ExecuteCmd(_SQLText, @Error);

					IF @erp_obj_counters._Rodzaj IS NULL THEN
						SET _Result = 'Brak parametrow';
						LEAVE S_erp_obj_counters_Load_Params;
					END IF;
				
				END IF;
				
				IF _MODE = 'get.params.for.ID.and.ObjType' THEN
				/* *************************************************************************************************************************************************************
					Zwraca numer i numer tekstowy (ale ... 1. nie sprawdza czy istnieje numer, 2. nie wstawia numeru
					CALL erp_obj_counters_values_SetNumber('get.params.for.ID.and.ObjType', @_Numer, @_NumerText, 'opng.nrdokfin', '1', '0', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '', '');
					
				**************************************************************************************************************************************************************/
					SET 	
						_Result = '',
						_Rodzaj = IFNULL(_Rodzaj, -1),
						_PodRodzaj = IFNULL(_PodRodzaj, -1),
						_SQLText_SQL_GetParams = '', 
						_SQLText_SQL_UpdateNum = '',
						_ParamsLoaded = FALSE,
						@erp_obj_counters._Rodzaj = NULL
					;
					IF _Rodzaj = -1 THEN
					--	Ustal Rodzaj bo jest -1/null
						SELECT
							d.SQL_GetParams AS SQL_GetParams,
							d.SQL_UpdateNum AS SQL_UpdateNum,
							d.TableName AS TableName
						INTO
							_SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum, @TableName
						FROM `erp_obj_counters_def` d 
						WHERE
							d.ObjType = _ObjType
						;
						SET _TableName = IF(IFNULL(_TableName, '') = '', @TableName, _TableName);
						
						CALL erp_obj_counters_Load_Params('load.params.by._Input_SQLText', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');
						IF _Result != '' THEN
							LEAVE S_erp_obj_counters_Load_Params;
						END IF;
						SET
							_Rodzaj = @erp_obj_counters._Rodzaj,
							_Podrodzaj = @erp_obj_counters._Podrodzaj,
							_ParamsLoaded = True
						;
					
					END IF;
					
					
					SELECT
						m.Mask, 
						m.Rodzaj, m.Podrodzaj, 
						IFNULL(m.SQL_GetParams, d.SQL_GetParams) AS SQL_GetParams,
						IFNULL(m.SQL_UpdateNum, d.SQL_UpdateNum) AS SQL_UpdateNum,
						IFNULL(m.TableName, d.TableName) AS TableName,
						IF(m.SQL_GetParams IS NOT NULL, FALSE, _ParamsLoaded),
						m.Disabled
					INTO
						_NumMask,
						_Rodzaj, _Podrodzaj,
						_SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum, @TableName,
						_ParamsLoaded,
						_Disabled
					FROM `erp_obj_counters_masks` m1
					INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji
					INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m1.ObjType
					WHERE
						m1.ObjType = _ObjType
						AND m1.Rodzaj = _Rodzaj
						AND m1.Podrodzaj = _Podrodzaj
					;
					/* JUZ nie bo _Disabled oznacza tylko blokade automatycznego naliczania a co z manualnym?? Dlatego musz jednak nie blokowac
					IF _Disabled THEN
						SET _Result = 'Brak aktywnej numeracji';
						LEAVE S_erp_obj_counters_Load_Params;
					END IF;
					*/
					
					IF NOT _ParamsLoaded THEN
							SET @X = '2';
						
						SET _TableName = IF(IFNULL(_TableName, '') = '', @TableName, _TableName);
						
						CALL erp_obj_counters_Load_Params('load.params.by._Input_SQLText', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _NumMask, _Result, _SQLText_SQL_GetParams, '', '');
						IF _Result != '' THEN
							LEAVE S_erp_obj_counters_Load_Params;
						END IF;
						
					END IF;
				END IF;
			END$$

			
			DROP PROCEDURE IF EXISTS `erp_obj_counters_values_SQL_UpdateNum`$$
			CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_values_SQL_UpdateNum`(
				IN _MODE VARCHAR(150),
				IN _NumerText VARCHAR(150),
				IN _ObjType VARCHAR(200),
				IN _ID VARCHAR(200),
				IN _TableName VARCHAR(200),
				IN _Input_Numer VARCHAR(50),	
				IN _Param_A VARCHAR(50)	
			)
						
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				
				CALL erp_obj_counters_values_SQL_UpdateNum('', @_NumerText, 'opng.nrdokfin', '{4C47B62C-9B7E-4E90-A2E3-340BF50B28C7}', 'opng', '123456', '');

			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			S_erp_obj_counters_values_SQL_UpdateNum: BEGIN
				DECLARE _SQLText, _SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum MEDIUMTEXT;
				DECLARE _Rodzaj_N, _PodRodzaj_N, _grp_Res1, _grp_Res2, _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
				DECLARE _Result, _NumerText_OLD, _grp_ResGUID VARCHAR(200);
				DECLARE
					_NumMask,
					_Params VARCHAR(250)
				;	

				SELECT
					d.SQL_UpdateNum AS SQL_UpdateNum,
					IF(IFNULL(_TableName, '') = '', d.TableName, _TableName) AS TableName
				INTO
					_SQLText_SQL_UpdateNum, _TableName
				FROM `erp_obj_counters_def` d 
				WHERE
					d.ObjType = _ObjType
				;
				SET
				@_SQLText_SQL_UpdateNum = _SQLText_SQL_UpdateNum
				;
				
				IF IFNULL(_SQLText_SQL_UpdateNum, '') = '' THEN
					LEAVE S_erp_obj_counters_values_SQL_UpdateNum;
				END IF;
								
				SET @erp_obj_counters._Rodzaj = NULL;
								
				SET _SQLText = _SQLText_SQL_UpdateNum;		
				SET @_SQLText_SQL_UpdateNum = _SQLText_SQL_UpdateNum;
				
				SET _SQLText = REPLACE(_SQLText, '#TABLENAME#', _TableName);
				SET _SQLText = REPLACE(_SQLText, '#ID#', _ID);
				SET _SQLText = REPLACE(_SQLText, '#NUMBER#', _NumerText);
				SET _SQLText = REPLACE(_SQLText, '#INPUT_NUMBER#', _Input_Numer);
				SET @_SQLText = _SQLText;
				CALL _ExecuteCmd(_SQLText, @Error);
				
			END$$


DROP PROCEDURE IF EXISTS `erp_obj_counters_values_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters_values_tools`(
	IN _MODE VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	
	IN _ID VARCHAR(200),
	IN _TableName VARCHAR(200),
	
	IN _Param_WE VARCHAR(250),	
	
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		
	Wołana z E	-	('EXECUTE')
	SPÓJNA i krótka i działa!!!!!!!!!!!!!!
		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters_values_tools: BEGIN
	DECLARE _SQLText, _SQLText_SQL_GetParams, _SQLText_SQL_UpdateNum MEDIUMTEXT;
	-- DECLARE _grp_Y, _grp_M, _grp_D, _Disabled INTEGER;
	DECLARE _clear_before BOOLEAN;
	DECLARE _Rec_ID VARCHAR(200);

	IF _MODE = 'EXECUTE' THEN
	/* *************************************************************************************************************************************************************
		przygotowuje
		CALL erp_obj_counters_values_tools('EXECUTE', 'opng.%', '104', '0', @IdnOper, 'opng_e', '', '', '');		
		CALL erp_obj_counters_values_tools('EXECUTE', 'opng.%', '104', '0', @IdnOper, 'opng_e', 'clear.before', '', '');		
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters_values_tools('t_erp_obj_counters_inputs.init', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _Param_WE, _Param_A, _Param_B);		
		CALL erp_obj_counters_values_tools('loop.1.INC', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _Param_WE, _Param_A, _Param_B);		
		CALL erp_obj_counters_values_tools('loop.2.inf_SQL_UpdateNum', _ObjType, _Rodzaj, _PodRodzaj, _ID, _TableName, _Param_WE, _Param_A, _Param_B);		
		IF (_Param_WE LIKE '%select.NUM%') THEN
			SELECT Number_Text FROM `erp_obj_counters_values` WHERE ObjType = _ObjType AND ID = _ID;
		END IF;
		
		-- DROP TEMPORARY TABLE IF EXISTS `t_erp_obj_counters_inputs`;
	END IF;
	
	IF _MODE = 't_erp_obj_counters_inputs.init' THEN
	/* *************************************************************************************************************************************************************
		przygotowuje
		CALL erp_obj_counters_values_tools('t_erp_obj_counters_inputs.init', 'opng.%', '104', '0', @IdnOper, 'opng_e', '', '', '');		
		CALL erp_obj_counters_values_tools('t_erp_obj_counters_inputs.init', 'opng.%', '104', '0', @IdnOper, 'opng_e', 'clear.before', '', '');		
	**************************************************************************************************************************************************************/
		SET @X = 'prepare.t_erp_obj_counters_inputs';
		SET
			_clear_before = (_Param_WE LIKE '%clear.before%')
		;
		DROP TEMPORARY TABLE IF EXISTS `t_erp_obj_counters_inputs`;
		CREATE TEMPORARY TABLE `t_erp_obj_counters_inputs` (
		  `Rec_ID` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'Klucz lokalny tej tabeli',
		  `in_ObjType` VARCHAR(200) NOT NULL DEFAULT 'opng.nrdokfin' COMMENT 'ID numeratora - Klasa obiektow numeracji ("oper", "oper_wewn", "crm", etc.)',
		  `in_Rodzaj` INTEGER,
		  `in_PodRodzaj` INTEGER,
		  `in_Rodzaj_N` INTEGER,
		  `in_PodRodzaj_N` INTEGER,
		  `in_ID` VARCHAR(250) DEFAULT '' COMMENT 'Identyfikator np. dokumentu',
		  `in_Clear_Before` INTEGER NOT NULL DEFAULT 0 COMMENT 'gdy 1 to zawsze nadajemy numer od nowa',
		  `in_Update_Src_Table` INTEGER NOT NULL DEFAULT 0 COMMENT 'gdy 1 to przepisujemy numer sql-ka z pola `inf_SQL_UpdateNum` ',
		  `out_Numer` INTEGER NOT NULL DEFAULT 0 COMMENT 'zapamietany sam numer',
		  `out_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'numer tekstowy',
		  `inf_prev_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'stary numer tekstowy z `erp_obj_counters_values`',
		  `inf_old_NumerText` VARCHAR(250) DEFAULT '' COMMENT 'stary numer tekstowy dokumentu',
		  `inf_TableName` VARCHAR(250) DEFAULT '' COMMENT 'Nazwa tabeli',
		  `inf_IncNum_Enabled` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'czy automatyczna jest mozliwa',
		  -- `inf_Disabled` INTEGER NOT NULL DEFAULT 0 COMMENT 'czy automatyczna',
		  `inf_Update_Old_Field` VARCHAR(250) DEFAULT '' COMMENT 'Czy robic update sqlka z pola SQL_UpdateNum',
		  `inf_SQL_GetParams` MEDIUMTEXT COMMENT 'SQL dla pobierania danych',
		  `inf_SQL_UpdateNum` MEDIUMTEXT COMMENT 'SQL dla wstawienie numeru do jakiejs tabeli ',
		  `inf_NumMask` VARCHAR(250) DEFAULT '',
		  `inf_GUI_Ctrl_option` SET('AutoNum','ManualNum','EditedNum') DEFAULT 'AutoNum,ManualNum,EditedNum',
		  `inf_LP` INT DEFAULT 0 NOT NULL COMMENT 'kolejnosc',
		  `inf_SrcObjType` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'zrodlowe ObjType skad brany bedzie numer - Klasa obiektow numeracji ("oper", "oper_wewn", "crm", etc.)',
		  `p_Res1` INTEGER,
		  `p_Res2` INTEGER,
		  `p_ResGUID` VARCHAR(38),
		  `p_NumYear` INTEGER,
		  `p_NumMonth` INTEGER,
		  `p_NumDay` INTEGER,
		  `p_RodzajDowodu` VARCHAR(250) DEFAULT '',
		  `p_Rv_id` VARCHAR(250) DEFAULT '',
		  `p_UGrpGUID` VARCHAR(250) DEFAULT '',
		  `p_MGS` VARCHAR(250) DEFAULT '',
		  `p_MDS` VARCHAR(250) DEFAULT '',
		  `p_Params` VARCHAR(250) DEFAULT '',
		  PRIMARY KEY (`in_ObjType`,`in_ID`),
		  UNIQUE KEY (`Rec_ID`)
		)
		;
-- @.update.src.table = (_Param_WE LIKE '%update.src.table%')
		
		SET @X = 'INSERT IGNORE INTO `t_erp_obj_counters_inputs';
		IF (_Param_WE LIKE '%ManualNum%') THEN
			SET @GUI_Ctrl_option = '%ManualNum%';
		ELSE
			SET @GUI_Ctrl_option = '%AutoNum%';
		END IF;
		
		INSERT IGNORE INTO `t_erp_obj_counters_inputs`	
		(
		Rec_ID, in_ObjType, in_Rodzaj, in_PodRodzaj, in_Rodzaj_N, in_PodRodzaj_N, in_ID, in_Clear_Before, in_Update_Src_Table, out_Numer, out_NumerText, 
		inf_prev_NumerText, inf_TableName, inf_IncNum_Enabled, inf_Update_Old_Field, inf_SQL_GetParams, inf_SQL_UpdateNum, inf_NumMask, inf_GUI_Ctrl_option, inf_SrcObjType, inf_LP
		)
			SELECT
				CONCAT(m.ObjType, '.', m.Rodzaj, '.', m.Podrodzaj) AS Rec_ID,
				m.ObjType AS in_ObjType,
				m1.Rodzaj AS in_Rodzaj, 
				m1.Podrodzaj AS in_Podrodzaj, 
				m.Rodzaj AS in_Rodzaj_N, 
				m.Podrodzaj AS in_Podrodzaj_N, 
				_ID AS in_ID,
				(_clear_before OR (IFNULL(v.Number_Text, '') IN ('','?'))) AS in_Clear_Before,
				(_Param_WE LIKE '%update.src.table%') OR (m.Update_Old_Field != 'NO') AS in_Update_Src_Table,
				0 AS out_Numer,
				'' AS out_NumerText,
				IFNULL(v.Number_Text, '') AS inf_prev_NumerText,
				IF(IFNULL(_TableName, '') != '', 
					_TableName,
					IFNULL(m.TableName, d.TableName)
				) AS inf_TableName,
				-- (m.GUI_Ctrl_option LIKE '%AutoNum%') OR (m.GUI_Ctrl_option LIKE '%ManualNum%') AS inf_IncNum_Enabled,
				(m.GUI_Ctrl_option LIKE @GUI_Ctrl_option) AS inf_IncNum_Enabled,
				-- m.Disabled AS inf_Disabled,
				m.Update_Old_Field AS inf_Update_Old_Field,
				IF(IFNULL(m.SQL_GetParams, '') != '', m.SQL_GetParams, d.SQL_GetParams) AS inf_SQL_GetParams,
				IF(IFNULL(m.SQL_UpdateNum, '') != '', m.SQL_UpdateNum, d.SQL_UpdateNum) AS inf_SQL_UpdateNum,
				m.Mask AS inf_NumMask,
				m.GUI_Ctrl_option,
				m.SrcObjType AS inf_SrcObjType,
				m.LP AS inf_LP
			FROM `erp_obj_counters_masks` m1
			INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = m1.ObjType AND m.Rodzaj = m1.Rodzaj_op_numeracji AND m.Podrodzaj = m1.Podrodzaj_op_numeracji
			INNER JOIN `erp_obj_counters_def` d ON d.ObjType = m1.ObjType
			LEFT JOIN `erp_obj_counters_values` v ON v.ID = _ID AND v.ObjType = m.ObjType
			WHERE
				-- m1.ObjType LIKE _ObjType
				m1.ObjType LIKE CONCAT(_ObjType, '%')
				AND m1.Rodzaj = _Rodzaj
				AND m1.Podrodzaj = _Podrodzaj
			ORDER BY m.LP
		;
		
			/*		
			UPDATE `t_erp_obj_counters_inputs` t
			set inf_SrcObjType = 'opng.lp_ks_podawcza_str'
			where in_ObjType = 'opng.nrwewn' and in_Rodzaj_N = 104;
			*/

		SET @X = concat('UPDATE `t_erp_obj_counters_inputs` t : ', ROW_COUNT()); SET @Y = @X;
		UPDATE `t_erp_obj_counters_inputs` t
		SET
			t.inf_IncNum_Enabled = t.inf_IncNum_Enabled,
			t.inf_SQL_GetParams = 
				REPLACE(REPLACE(t.inf_SQL_GetParams, '#TABLENAME#', t.inf_TableName), '#ID#', t.in_ID),
			t.inf_SQL_UpdateNum = 
				REPLACE(REPLACE(t.inf_SQL_UpdateNum, '#TABLENAME#', t.inf_TableName), '#ID#', t.in_ID)
		;


	END IF;
	
	IF _MODE = 'loop.1.INC' THEN
	/* *************************************************************************************************************************************************************
		przygotowuje
		CALL erp_obj_counters_values_tools('loop.1.INC', 'opng.%', '104', '0', @IdnOper, 'opng_e', '', '', '');		
	**************************************************************************************************************************************************************/
	
		
	/************** POCZATEK PĘTLI **************/
	--	Nadawanie numerow - Pętla przetwarzania
		SET @X = 'loop.1.INC';
		BEGIN
		
			DECLARE done BOOL DEFAULT FALSE;
		--	Kursor	
			DECLARE c_t_erp_obj_counters_inputs_1 CURSOR FOR
				SELECT
					Rec_ID,
					inf_SQL_GetParams
				FROM `t_erp_obj_counters_inputs` t
				WHERE
					t.inf_IncNum_Enabled
					AND
					t.in_Clear_Before
					AND
					(t.inf_SrcObjType = '')
				ORDER BY t.inf_LP
			;	
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
		--	Open Kursor	
			OPEN c_t_erp_obj_counters_inputs_1;
			loop_c_t_erp_obj_counters_inputs_1: LOOP
				FETCH c_t_erp_obj_counters_inputs_1 INTO 
					_Rec_ID,
					_SQLText_SQL_GetParams
				;
				IF done THEN
					LEAVE loop_c_t_erp_obj_counters_inputs_1;
				END IF;
			--	Wykonaj nadawanie numeru
				SET _SQLText = _SQLText_SQL_GetParams;
				SET @_SQLText = _SQLText;
				SET @erp_obj_counters.exit = NULL;
				CALL _ExecuteCmd(_SQLText, @Error);
				
		SET @X = 'UPDATE `t_erp_obj_counters_inputs` t';
				UPDATE `t_erp_obj_counters_inputs` t
				SET
					inf_old_NumerText = @erp_obj_counters._Number,
					p_Res1 = @erp_obj_counters._Res1,
					p_Res2 = @erp_obj_counters._Res2,
					p_ResGUID = @erp_obj_counters._ResGUID,
					p_NumYear = @erp_obj_counters._NumYear,
					p_NumMonth = @erp_obj_counters._NumMonth,
					p_NumDay = @erp_obj_counters._NumDay,
					p_RodzajDowodu = @erp_obj_counters._RodzajDowodu,
					p_Rv_id = @erp_obj_counters._Rv_id,
					p_UGrpGUID = @erp_obj_counters._UGrpGUID,
					p_MGS = @erp_obj_counters._MGS,
					p_MDS = @erp_obj_counters._MDS
				WHERE
					t.Rec_ID = _Rec_ID
					-- t.in_ObjType = _ObjType AND t.in_Rodzaj_N = _Rodzaj_N AND t.in_PodRodzaj_N = _PodRodzaj_N
				;
			--		
				SET @erp_obj_counters.exit = IFNULL(@erp_obj_counters.exit, FALSE);
				
				IF @erp_obj_counters.exit THEN
					UPDATE `t_erp_obj_counters_inputs` t
					SET
						t.inf_IncNum_Enabled = FALSE
					WHERE
						t.Rec_ID = _Rec_ID
					;
				
				ELSEIF _Param_WE LIKE '%exit.if.old.field.not.empty%' THEN
				--	UWAGA TUTAJ chcemy by nie nadawac W OGOLE numeru gdy :
				--	1. chcemy przerzucac wartosci (czyli inf_Update_Old_Field != 'NO')
				--	2. ale wartosci starych pol (np nrdokfin etc) sa nie puste (inf_old_NumerText <> '')
				--	>>>> Nie chodzi aby nie przepisywac do `opng_e` ale zeby jesli w `opng_e` sa wartosci to wogole nie zwiekszac countera 
					UPDATE `t_erp_obj_counters_inputs` t
					SET
						t.inf_IncNum_Enabled = (IFNULL(t.inf_old_NumerText, '') = '')
					WHERE
						t.Rec_ID = _Rec_ID
						AND
						inf_Update_Old_Field != 'NO'
					;
				END IF;
				/* 
				NADAWANIE NUMERU
				*/
				INSERT INTO `erp_obj_counters`
				(
					`Nr`,
					`ObjType`,
					`Rodzaj`,
					`Podrodzaj`,
					`Res1`,
					`Res2`,
					`ResGUID`,
					`Y`,
					`M`,
					`D`
				)
					SELECT
						@erp_obj_counters.Number := t.out_Numer + 1, 
						t.in_ObjType,
						t.in_Rodzaj_N,
						t.in_Podrodzaj_N,
						IF(m.Grp_Res1 = 1, t.p_Res1, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
						IF(m.Grp_Res2 = 1, t.p_Res2, 0),	-- musi byc = 1 bo = -1 też jest RUE a nam chodzi o 1 a -1 to niedotyczy
						IF(m.Grp_ResGUID, t.p_ResGUID, ''),
						IF(m.Grp_Y, t.p_NumYear, 0),
						IF(m.Grp_M, t.p_NumMonth, 0),
						IF(m.Grp_D, t.p_NumDay, 0)
						
						-- m.Rodzaj, m.Podrodzaj, 
						-- m.grp_Res1, m.grp_Res2, m.grp_ResGUID, m.grp_Y, m.grp_M, m.grp_D, m.Disabled
					FROM `t_erp_obj_counters_inputs` t
					INNER JOIN `erp_obj_counters_masks` m ON m.ObjType = t.in_ObjType AND m.Rodzaj = t.in_Rodzaj_N AND m.Podrodzaj = t.in_Podrodzaj_N
					WHERE
						t.Rec_ID = _Rec_ID
						AND
						t.inf_IncNum_Enabled
						AND
						t.in_Clear_Before
						AND
						(t.inf_SrcObjType = '')
				ON DUPLICATE KEY
				UPDATE
					`Nr` = @erp_obj_counters.Number := (`Nr` + 1)
				;
				-- SET _Numer = IFNULL(@erp_obj_counters.Number, 0);
				/* */
				
				UPDATE `t_erp_obj_counters_inputs` t
				SET 
					out_Numer = IFNULL(@erp_obj_counters.Number, 0),
					p_Params = 
						_MaskTool_Fill_Params('', in_ObjType, in_Rodzaj, in_PodRodzaj, IFNULL(@erp_obj_counters.Number, 0), 
						p_Res1, p_Res2, p_ResGUID, 
						p_NumYear, p_NumMonth, p_NumDay, 
						p_RodzajDowodu, p_Rv_id, p_UGrpGUID, p_MGS, p_MDS)
				WHERE
					t.Rec_ID = _Rec_ID
					AND
					t.inf_IncNum_Enabled
					AND
					t.in_Clear_Before
					AND
					(t.inf_SrcObjType = '')
				;
				-- CALL erp_obj_counters_build_number_text('', _NumerText, _NumMask, _Params, '', '');		
			END LOOP;
			CLOSE c_t_erp_obj_counters_inputs_1;
		
		END;	--	
	/************** KONIEC PĘTLI **************/
		
		UPDATE `t_erp_obj_counters_inputs` t
		SET 
			out_NumerText = @out_NumerText := 
				erp_obj_counters_build_and_get_number_text('', t.inf_NumMask, t.p_Params, '')
		WHERE
			t.inf_IncNum_Enabled
			AND
			t.in_Clear_Before
			AND
			(t.inf_SrcObjType = '')
		;
		-- SET _NumerText = @out_NumerText;

	--	WSTAW juz numery i numeryteksty do `erp_obj_counters_values` 
		INSERT IGNORE INTO `erp_obj_counters_values` 
		(ObjType, ID, Number_Text, Input_Number)
			SELECT	
				t.in_ObjType,
				t.in_ID,
				t.out_NumerText,
				t.out_Numer
			FROM `t_erp_obj_counters_inputs` t
			WHERE
				t.inf_IncNum_Enabled
				AND
				t.in_Clear_Before
				AND
				(t.inf_SrcObjType = '')
		ON DUPLICATE KEY
		UPDATE
			Number_Text = IF(t.in_Clear_Before, t.out_NumerText, Number_Text),
			Input_Number = IF(t.in_Clear_Before, t.out_Numer, Input_Number)
		;			
	--	Teraz ustaw te ktore biora zrodlo z innych czyli maj t.inf_SrcObjType != ''
		UPDATE `t_erp_obj_counters_inputs` t, `erp_obj_counters_values` v
		SET 
			t.out_NumerText = v.Number_Text,
			t.out_Numer = v.Input_Number
		WHERE
			t.inf_IncNum_Enabled	-- Tak ma byc!! Bo gdy tylko EditedNum to nie inicjujemy z niczego (czysty tekscik i nic wiecej) - MUSI BYĆ AutoNum albo ManualNum 
			AND
			t.in_Clear_Before
			AND
			(t.inf_SrcObjType != '')
			AND
			v.ID = t.in_ID
			AND
			v.ObjType = t.inf_SrcObjType
		;
	--	WSTAW juz numery i numeryteksty do `erp_obj_counters_values` 
		INSERT IGNORE INTO `erp_obj_counters_values` 
		(ObjType, ID, Number_Text, Input_Number)
			SELECT	
				t.in_ObjType,
				t.in_ID,
				t.out_NumerText,
				t.out_Numer
			FROM `t_erp_obj_counters_inputs` t
			WHERE
				t.inf_IncNum_Enabled	-- Tak ma byc!! Bo gdy tylko EditedNum to nie inicjujemy z niczego (czysty tekscik i nic wiecej) - MUSI BYĆ AutoNum albo ManualNum 
				AND
				t.in_Clear_Before
				AND
				(t.inf_SrcObjType != '')
		ON DUPLICATE KEY
		UPDATE
			Number_Text = IF(t.in_Clear_Before, t.out_NumerText, Number_Text),
			Input_Number = IF(t.in_Clear_Before, t.out_Numer, Input_Number)
		;			
					
	END IF;
							
	IF _MODE = 'loop.2.inf_SQL_UpdateNum' THEN
	/* *************************************************************************************************************************************************************
		Update np. `opng_e`
		CALL erp_obj_counters_values_tools('loop.2.inf_SQL_UpdateNum', 'opng.%', '104', '0', @IdnOper, 'opng_e', '', '', '');		
	**************************************************************************************************************************************************************/
					
	--	Teraz ustaw UPDATE Sql jesli bedzie update np. opng
		UPDATE `t_erp_obj_counters_inputs` t
		SET 
			t.inf_SQL_UpdateNum = 
				REPLACE(REPLACE(REPLACE(
					t.inf_SQL_UpdateNum, '#NUMBER#', 
						IF(t.in_Clear_Before,
							out_NumerText,
							inf_prev_NumerText
						)
					),
					'#INPUT_NUMBER#',
					t.out_Numer
					),
					'#ALWAYS#',
					IF(t.inf_Update_Old_Field = 'IF_EMPTY',
						'FALSE',
						'TRUE'
					)
				)
		WHERE
			t.in_Update_Src_Table
		;

		
	/************** POCZATEK PĘTLI **************/
	--	Zapis do pol np opng_e i innych Pętla przetwarzania
		BEGIN
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE c_t_erp_obj_counters_inputs_2 CURSOR FOR
				SELECT
					inf_SQL_UpdateNum
				FROM `t_erp_obj_counters_inputs` t
				WHERE
					t.in_Update_Src_Table
				;	
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
		--	3.2 Open Kursor	
			OPEN c_t_erp_obj_counters_inputs_2;
			loop_c_t_erp_obj_counters_inputs_2: LOOP
				FETCH c_t_erp_obj_counters_inputs_2 INTO 
					_SQLText_SQL_UpdateNum
				;
				IF done THEN
					LEAVE loop_c_t_erp_obj_counters_inputs_2;
				END IF;
			--	Wykonaj nadawanie numeru
				SET _SQLText = _SQLText_SQL_UpdateNum;
				SET @_SQLText = _SQLText;
				
				CALL _ExecuteCmd(_SQLText, @Error);
				
			END LOOP;
			CLOSE c_t_erp_obj_counters_inputs_2;
		
		END;
	/************** KONIEC PĘTLI **************/
		
	END IF;
END$$
			
			
DROP PROCEDURE IF EXISTS `erp_obj_counters__INTNET`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `erp_obj_counters__INTNET`(
	IN _MODE VARCHAR(150),
	IN _ObjType VARCHAR(200),
	IN _Rodzaj INTEGER,
	IN _PodRodzaj INTEGER,
	IN _Res1 INTEGER,
	IN _Res2 INTEGER,
	IN _ResGUID VARCHAR(38),
	IN _NumYear INTEGER,
	IN _NumMonth INTEGER,
	IN _NumDay INTEGER,
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
		
		
		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
S_erp_obj_counters__INTNET: BEGIN
	IF _MODE = 'select.distinct.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca lewy panel do definicji masek
		CALL erp_obj_counters__INTNET('select.distinct.ObjType', '', '0', '0', '0', '0', '', 0, 0, 0, '', '');		
	**************************************************************************************************************************************************************/
		/*
		SELECT
			cm.ObjType,
			_VarStr(
				CASE 
				WHEN cm.ObjType IN ('oper', 'opng') THEN 'Operacje'
				WHEN cm.ObjType IN ('oper_wewn', 'opng_wewn') THEN 'Operacje nr. wewn.'
				WHEN cm.ObjType IN ('crm') THEN 'Zdarzenia, CRM'
				WHEN cm.ObjType IN ('webdoc') THEN 'Numeracja WebDoc'
				ELSE '?'
				END
			) AS ObjType_Str
		FROM `erp_obj_counters_masks` cm
		GROUP BY ObjType
		;	
		*/
		SELECT
			d.ObjType,
			d.Descr AS ObjType_Str
		FROM `erp_obj_counters_def` d
		;
		
	END IF;

	IF _MODE = 'prepare.edited.for.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Przygotowuje juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('prepare.edited.for.ObjType', 'oper_wewn', '0', '0', '0', '0', '', 2012, 6, 0, '', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
	**************************************************************************************************************************************************************/
		SET @.ObjType.SELECT.Type := 
            IF(_ObjType LIKE 'zapisy.%', 'PK',
            IF((_ObjType = 'CRM') OR (_ObjType LIKE 'web_delegacja'), 'CRM',
            'OPERDOC'
        ));
        DROP TEMPORARY TABLE IF EXISTS `t_select_edited_for_ObjType`;
		-- IF _ObjType IN ('oper', 'oper_wewn') OR (_ObjType LIKE 'opng%') OR (_ObjType LIKE 'zmng%') THEN
		Set @_ObjType = _ObjType;
		IF @.ObjType.SELECT.Type = 'PK' THEN
			CREATE TEMPORARY TABLE `t_select_edited_for_ObjType`
			SELECT
				_VarStr('') AS ID,
				_VarInt(0) AS NumCount,
				-- odt.nazwa AS Nazwa,
				d.Descr AS Nazwa,
				-- odtn.nazwa AS Nazwa_Num,
				d.Descr AS Nazwa_Num,
				_VarStr('') AS grp_Res1_Str,
				_VarStr('') AS grp_Res2_Str,
				_VarStr(
				'np. Rodz.?.'
				) AS grp_ResGUID_Str,
				_VarStr('Rok') AS grp_Y_Str,
				_VarStr('Miesiące') AS grp_M_Str,
				_VarStr('Dni') AS grp_D_Str,
				cm.*,
				0 AS Grupa
			FROM `erp_obj_counters_masks` cm
			INNER JOIN `erp_obj_counters_def` d ON d.ObjType = cm.ObjType
			WHERE
				cm.ObjType = _ObjType
			;		
        -- ELSEIF (_ObjType = 'CRM') OR (_ObjType LIKE 'web_delegacja') THEN
        ELSEIF @.ObjType.SELECT.Type = 'CRM' THEN
			CREATE TEMPORARY TABLE `t_select_edited_for_ObjType`
			SELECT
				_VarStr('') AS ID,
				_VarInt(0) AS NumCount,
				-- odt.nazwa AS Nazwa,
				odt.Opis AS Nazwa,
				-- odtn.nazwa AS Nazwa_Num,
				odtn.Opis AS Nazwa_Num,
				_VarStr('') AS grp_Res1_Str,
				_VarStr('') AS grp_Res2_Str,
				_VarStr(
				'np. Rodz.?.'
				) AS grp_ResGUID_Str,
				_VarStr('Rok') AS grp_Y_Str,
				_VarStr('Miesiac') AS grp_M_Str,
				_VarStr('Dni') AS grp_D_Str,
				cm.*,
				16 AS Grupa
			FROM `erp_obj_counters_masks` cm
			INNER JOIN `crm_rodzaje` odt ON odt.Rodzaj = cm.Rodzaj AND odt.PodRodzaj = cm.PodRodzaj
			INNER JOIN `crm_rodzaje` odtn ON odtn.Rodzaj = cm.Rodzaj_op_numeracji AND odtn.PodRodzaj = cm.PodRodzaj_op_numeracji
			WHERE
				cm.ObjType = _ObjType
			;		
		-- IF _ObjType != 'CRM' THEN
        ELSE
            Set @_ObjType = 'xxx';
		/*
            KONIECZNIE do SQL zmian dodaj
			UPDATE `erp_obj_counters_masks` cm
			INNER JOIN `operdoc_typy` odt ON odt.Rodzaj = cm.Rodzaj AND odt.Typ = cm.PodRodzaj
			INNER JOIN `operdoc` od ON od.Rodzaj = odt.Rodzaj -- and od.PodRodzaj = cm.PodRodzaj
			SET
				cm.grp_Res1 =
					IF(od.Grupa IN (0,1,2,3,4,5,6,7,9,12), cm.grp_Res1, -1),
				cm.grp_Res2 =
					IF(od.Grupa IN (0,1,2,3,4,5,6,7,9,12), cm.grp_Res2, -1)
			;		
			-1 oznaczać ma że fistaszek(ki) sa niewidoczne i przez to niezaznaczalne
		*/	
			CREATE TEMPORARY TABLE `t_select_edited_for_ObjType`
			SELECT
				_VarStr('') AS ID,
				_VarInt(0) AS NumCount,
				CONCAT_WS(' - ',
					IF(LOCATE(odt.nazwa, od.nazwa) > 0, 
						od.nazwa,
						odt.nazwa
					), 
					IF(LOCATE(odt.Opis, od.Opis) > 0, 
						od.Opis,
						odt.Opis
					)
				) AS Nazwa,
				CONCAT(
					IF(LOCATE(odtn.nazwa, odn.nazwa) > 0, 
						odn.nazwa,
						odtn.nazwa
					), ' - ',
					IF(LOCATE(odtn.Opis, odn.Opis) > 0, 
						odn.Opis,
						odtn.Opis
					)
				) AS Nazwa_Num,
				_VarStr(
				CASE 
				WHEN od.Grupa = 6 THEN 'Nr kasy'
				WHEN od.Grupa = 9 THEN 'Bank'
				WHEN od.Grupa IN (0,1,2,3,4,5,12) THEN 'Magazyn do lub z'
				WHEN od.Grupa = 7 THEN 'Magazyn zam.'
				ELSE '?'
				END
				) AS grp_Res1_Str,
				_VarStr(
				CASE 
				WHEN od.Grupa = 6 THEN 'Nr kasy'
				WHEN od.Grupa = 9 THEN 'Bank'
				WHEN od.Grupa IN (0,1,2,3,4,5,12) THEN 'Magazyn do'
				WHEN od.Grupa = 7 THEN 'Magazyn wys.'
				ELSE '?'
				END
				) AS grp_Res2_Str,
				_VarStr(
				'Opcja indywidualna' 	-- 'np. Rodz.Dow.'
				) AS grp_ResGUID_Str,
				_VarStr('Rok') AS grp_Y_Str,
				_VarStr('Miesiac') AS grp_M_Str,
				_VarStr('Dni') AS grp_D_Str,
				d.Descr AS ObjType_Str,
				cm.*,
				od.Grupa
			FROM `erp_obj_counters_masks` cm
			INNER JOIN `erp_obj_counters_def` d ON d.ObjType = cm.ObjType
			INNER JOIN `operdoc_typy` odt ON odt.Rodzaj = cm.Rodzaj AND odt.Typ = cm.PodRodzaj
			INNER JOIN `operdoc` od ON od.Rodzaj = odt.Rodzaj -- and od.PodRodzaj = cm.PodRodzaj
			INNER JOIN `operdoc_typy` odtn ON odtn.Rodzaj = cm.Rodzaj_op_numeracji AND odtn.Typ = cm.PodRodzaj_op_numeracji
			INNER JOIN `operdoc` odn ON odn.Rodzaj = odtn.Rodzaj 
			WHERE
				IF(_ObjType != '',
					cm.ObjType = _ObjType,
					(cm.ObjType LIKE 'opng%' OR cm.ObjType LIKE 'zmng%')
					AND
					cm.Rodzaj = _Rodzaj
					AND
					cm.PodRodzaj = _PodRodzaj
				)
					
			;		
		END IF;
		
		UPDATE `t_select_edited_for_ObjType` t
		SET
			Nazwa_Num = IF(t.Nazwa = t.Nazwa_Num, 'ten sam', t.Nazwa_Num),
			ID = Md5(CONCAT(t.ObjType,t.Rodzaj,t.PodRodzaj)),
			NumCount = IFNULL(
				(SELECT COUNT(*) FROM `erp_obj_counters` c WHERE t.Rodzaj = c.Rodzaj AND t.PodRodzaj = c.PodRodzaj AND t.ObjType = c.ObjType)
			, 0)
		;
	END IF;
	
	IF _MODE = 'select.edited.for.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('select.edited.for.ObjType', 'oper_wewn', '0', '0', '0', '0', '', 2012, 6, 0, '', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters__INTNET('prepare.edited.for.ObjType', _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _Param_A,	_Param_B	);		
		SELECT * FROM `t_select_edited_for_ObjType`;
        IF NOT @session.Delfinek THEN
            DROP TEMPORARY TABLE IF EXISTS `t_select_edited_for_ObjType`;
        END IF;
	END IF;
	
	IF _MODE = 'select.edited.for.Rodzaj.PodRodzaj.opng.zmng' THEN
	/* *************************************************************************************************************************************************************
		Zwraca juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('select.edited.for.Rodzaj.PodRodzaj.opng.zmng', '', '1', '0', '0', '0', '', 2012, 6, 0, '', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters__INTNET('prepare.edited.for.ObjType', '', _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _Param_A,	_Param_B	);		
		SELECT * FROM `t_select_edited_for_ObjType`;
        IF NOT @session.Delfinek THEN
            DROP TEMPORARY TABLE IF EXISTS `t_select_edited_for_ObjType`;
        END IF;
	END IF;
	
	IF _MODE = 'select.numbers.master.for.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('select.numbers.master.for.ObjType', 'oper_wewn', '0', '0', '0', '0', '', 2012, 6, 0, '', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters__INTNET('select.edited.for.ObjType', _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _Param_A,	_Param_B);		
	END IF;
	
	IF _MODE = 'select.numbers.detail.for.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('select.numbers.detail.for.ObjType', 'oper_wewn', '0', '0', '0', '0', '', 2012, 6, 0, '', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
	**************************************************************************************************************************************************************/
		CALL erp_obj_counters__INTNET('prepare.edited.for.ObjType', _ObjType, _Rodzaj, _PodRodzaj, _Res1, _Res2, _ResGUID, _NumYear, _NumMonth, _NumDay, _Param_A,	_Param_B);		
		SET @.ObjType.SELECT.Type := 
            IF(_ObjType LIKE 'zapisy.%', 'PK',
            IF((_ObjType = 'CRM') OR (_ObjType LIKE 'web_delegacja'), 'CRM',
            'OPERDOC'
        ));
		DROP TEMPORARY TABLE IF EXISTS `t_select_numbers_detail_for_ObjType`;
		IF @.ObjType.SELECT.Type = 'PK' THEN
		-- ELSEIF (_ObjType = 'CRM') OR (_ObjType LIKE 'web_delegacja') THEN
			CREATE TEMPORARY TABLE `t_select_numbers_detail_for_ObjType`
			SELECT
				cm.ID AS ParentID,
				-- _VarStr('') AS ParentID,
				cm.Rodzaj, cm.PodRodzaj, cm.ObjType,
				cm.grp_Res1_Str, cm.grp_Res2_Str, cm.grp_ResGUID_Str, cm.grp_Y_Str, cm.grp_M_Str, cm.grp_D_Str,
				c.Res1, c.Res2, c.ResGUID, c.Y, c.M, c.D,
				c.Nr,
			--	teraz lookupy do Res1...
				_VarStr('') AS Res1_Str,
				_VarStr('') AS Res2_Str,
				_VarStr('') AS ResGUID_Str
			FROM `erp_obj_counters` c
			INNER JOIN `t_select_edited_for_ObjType` cm ON cm.Rodzaj = c.Rodzaj AND cm.PodRodzaj = c.PodRodzaj AND cm.ObjType = c.ObjType
			WHERE
				c.ObjType = _ObjType
			;		
        ELSEIF @.ObjType.SELECT.Type = 'CRM' THEN
			CREATE TEMPORARY TABLE `t_select_numbers_detail_for_ObjType`
			SELECT
				cm.ID AS ParentID,
				-- _VarStr('') AS ParentID,
				cm.Rodzaj, cm.PodRodzaj, cm.ObjType,
				cm.grp_Res1_Str, cm.grp_Res2_Str, cm.grp_ResGUID_Str, cm.grp_Y_Str, cm.grp_M_Str, cm.grp_D_Str,
				c.Res1, c.Res2, c.ResGUID, c.Y, c.M, c.D,
				c.Nr,
			--	teraz lookupy do Res1...
				_VarStr('') AS Res1_Str,
				_VarStr('') AS Res2_Str,
				_VarStr('') AS ResGUID_Str
			FROM `erp_obj_counters` c
			INNER JOIN `t_select_edited_for_ObjType` cm ON cm.Rodzaj = c.Rodzaj AND cm.PodRodzaj = c.PodRodzaj AND cm.ObjType = c.ObjType
			WHERE
				c.ObjType = _ObjType
			;		
            /*
			CREATE TEMPORARY TABLE `t_select_numbers_detail_for_ObjType`
			SELECT
				_VarStr('') AS ParentID,
				-- odt.nazwa AS Nazwa,
				odt.Opis AS Nazwa,
				-- odtn.nazwa AS Nazwa_Num,
				_VarStr('') AS grp_Res1_Str,
				_VarStr('') AS grp_Res2_Str,
				_VarStr(
				'np. Rodz.?.'
				) AS grp_ResGUID_Str,
				_VarStr('Rok') AS grp_Y_Str,
				_VarStr('Miesiąc') AS grp_M_Str,
				_VarStr('Dni') AS grp_D_Str,
				cm.*,
			--	teraz lookupy do Res1...
				_VarStr('') AS Res1_Str
			
				
			FROM `erp_obj_counters` cm
			INNER JOIN `crm_rodzaje` odt ON odt.Rodzaj = cm.Rodzaj AND odt.PodRodzaj = cm.PodRodzaj
			WHERE
				cm.ObjType = _ObjType
			;		
            */
		-- IF _ObjType IN ('oper', 'oper_wewn') OR (_ObjType LIKE 'opng.%') OR (_ObjType LIKE 'zmng.%') THEN
        ELSE    -- @.ObjType.SELECT.Type = 'OPERDOC'
			CREATE TEMPORARY TABLE `t_select_numbers_detail_for_ObjType`
			SELECT
				-- cm.ID, 
				_VarStr('') AS ParentID,
				cm.Rodzaj, cm.PodRodzaj, cm.ObjType,
				cm.grp_Res1_Str, cm.grp_Res2_Str, cm.grp_ResGUID_Str, cm.grp_Y_Str, cm.grp_M_Str, cm.grp_D_Str,
				c.Res1, c.Res2, c.ResGUID, c.Y, c.M, c.D,
				c.Nr,
			--	teraz lookupy do Res1...
				_VarStr(IFNULL(
					CASE 
					WHEN cm.Grupa = 6 THEN (SELECT CONCAT(k.Symbol, ' - ', k.NazwaKasy) FROM `kasy` k WHERE k.Idn = c.Res1)
					WHEN cm.Grupa = 9 THEN ''
					WHEN cm.Grupa IN (0,1,2,3,4,5) THEN (SELECT CONCAT(m.Opis, ' - ', m.Symbol) FROM `Magazyny` m WHERE m.IdnMagazynu = c.Res1) -- 'Magazyn'
					WHEN cm.Grupa = 7 THEN (SELECT CONCAT(m.Opis, ' - ', m.Symbol) FROM `Magazyny` m WHERE m.IdnMagazynu = c.Res1) -- 'Magazyn wys.'
					ELSE '?'
					END
				, '')) AS Res1_Str,
				_VarStr(IFNULL(
					CASE 
					WHEN cm.Grupa = 6 THEN (SELECT CONCAT(k.Symbol, ' - ', k.NazwaKasy) FROM `kasy` k WHERE k.Idn = c.Res2)
					WHEN cm.Grupa = 9 THEN ''
					WHEN cm.Grupa IN (0,1,2,3,4,5) THEN (SELECT CONCAT(m.Opis, ' - ', m.Symbol) FROM `Magazyny` m WHERE m.IdnMagazynu = c.Res2) -- 'Magazyn'
					WHEN cm.Grupa = 7 THEN (SELECT CONCAT(m.Opis, ' - ', m.Symbol) FROM `Magazyny` m WHERE m.IdnMagazynu = c.Res2) -- 'Magazyn wys.'
					ELSE '?'
					END
				, '')) AS Res2_Str,
				_VarStr(IFNULL(
					CASE 
					WHEN cm.Grupa = 6 THEN ''
					WHEN cm.Grupa = 9 THEN ''
					WHEN cm.Grupa IN (0,1,2,3,4,5) THEN (SELECT CONCAT(r.Nazwa, ' - ', r.Symbol) FROM `rodzaje_dowodow` r WHERE r.Idn = c.ResGUID) -- 'Rodzaj dow.'
					WHEN cm.Grupa = 7 THEN ''
					ELSE '?'
					END
				, '')) AS ResGUID_Str
			FROM `erp_obj_counters` c
			INNER JOIN `t_select_edited_for_ObjType` cm ON cm.Rodzaj = c.Rodzaj AND cm.PodRodzaj = c.PodRodzaj AND cm.ObjType = c.ObjType
			WHERE
				c.ObjType = _ObjType
			;		
		END IF;
		
		UPDATE `t_select_numbers_detail_for_ObjType` t
		SET
			ParentID = Md5(CONCAT(t.ObjType,t.Rodzaj,t.PodRodzaj))
		;
		SELECT * FROM `t_select_numbers_detail_for_ObjType`;
		-- SELECT * FROM `t_select_edited_for_ObjType`;
        IF NOT @session.Delfinek THEN
            DROP TEMPORARY TABLE IF EXISTS `t_select_edited_for_ObjType`;
            DROP TEMPORARY TABLE IF EXISTS `t_select_numbers_detail_for_ObjType`;
        END IF;
	END IF;

	IF _MODE = 'select.Res.lookup.for.ObjType' THEN
	/* *************************************************************************************************************************************************************
		Zwraca lookupy np. do magazynów, kas, etc
		CALL erp_obj_counters__INTNET('select.Res.lookup.for.ObjType', 'oper_wewn', '2', '0', '0', '0', '', 2012, 6, 0, 'Res1', '');		
		_ObjType		zawiera typ wierszy ktore mamy zwrocic
		_Rodzaj
		_PodRodzaj
		_Param_A		tutaj podawane jest pole np. `Res1`
	**************************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_select_edited_for_ObjType`;
		IF _ObjType IN ('oper', 'oper_wewn') OR (_ObjType LIKE 'opng.%') OR (_ObjType LIKE 'zmng.%') THEN
			SELECT od.Grupa INTO @od.Grupa FROM `operdoc` od WHERE od.Rodzaj = _Rodzaj;
			/*
				WHEN od.Grupa = 6 THEN 'Kasa'
				WHEN od.Grupa = 9 THEN 'Bank'
				WHEN od.Grupa IN (0,1,2,3,4,5) THEN 'Magazyn'
				WHEN od.Grupa = 7 THEN 'Magazyn zam.'
			*/
			IF _Param_A IN ('Res1', 'Res2') THEN
				IF @od.Grupa = 6 THEN -- 'Kasa'
					SELECT Idn AS ID, NazwaKasy AS Nazwa, Symbol AS Symbol FROM `kasy`;
				ELSE
					SELECT IdnMagazynu AS ID, Opis AS Nazwa, Symbol AS Symbol FROM `Magazyny`;
				END IF;
			END IF;
			
			IF _Param_A IN ('ResGUID') THEN
				IF @od.Grupa = 6 THEN -- 'Kasa'
					SELECT IdnMagazynu AS ID, Opis AS Nazwa, Symbol AS Symbol FROM `Magazyny` WHERE FALSE;
				ELSE
					SELECT Symbol AS ID, Nazwa AS Nazwa, Symbol AS Symbol FROM `rodzaje_dowodow`;
				END IF;
			END IF;
			
			
		ELSEIF _Param_A IN ('crm') THEN
			SELECT IdnMagazynu AS ID, Opis AS Nazwa, Symbol AS Symbol FROM `Magazyny` WHERE FALSE;
		ELSEIF _Param_A IN ('webdoc') THEN
			SELECT IdnMagazynu AS ID, Opis AS Nazwa, Symbol AS Symbol FROM `Magazyny` WHERE FALSE;
		ELSE
			SELECT IdnMagazynu AS ID, Opis AS Nazwa, Symbol AS Symbol FROM `Magazyny` WHERE FALSE;
		END IF;
	END IF;
	
	
	IF _MODE = 'select.edited.for.Rodzaj.PodRodzaj.opng.zmng.USTAWIANIE.STARYCH.NUMEROW' THEN
	/* *************************************************************************************************************************************************************
		Zwraca juz gotowe rekordy dla edycji 
		CALL erp_obj_counters__INTNET('select.edited.for.Rodzaj.PodRodzaj.opng.zmng.USTAWIANIE.STARYCH.NUMEROW', 'numdok', '1', '0', '0', '0', '', 0, 0, 0, '', '');		
		CALL erp_obj_counters__INTNET('select.edited.for.Rodzaj.PodRodzaj.opng.zmng.USTAWIANIE.STARYCH.NUMEROW', 'numwewn', '1', '0', '0', '0', '', 0, 0, 0, '', '');		
		_ObjType		UWAGA tutaj albo "numdok" albo "numwewn"
		_Rodzaj
		_PodRodzaj
	**************************************************************************************************************************************************************/
		IF _ObjType = 'numdok' THEN
			SELECT 
				n.*,
				_VarStr(IFNULL(m.Opis, '(brak)')) AS MagazynStr
			FROM `numdok` n
			LEFT JOIN `Magazyny` m ON m.IdnMagazynu = n.Magazyn
			WHERE
				n.Rodzaj = _Rodzaj
			;
		ELSEIF _ObjType = 'numwewn' THEN
			SELECT 
				n.*,
				_VarStr(IFNULL(m.Opis, '(brak)')) AS MagazynStr
			FROM `numwewn` n
			LEFT JOIN `Magazyny` m ON m.IdnMagazynu = n.Magazyn
			WHERE
				n.Rodzaj = _Rodzaj
			;
		END IF;
	END IF;
	
	

END$$


DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
CALL _Session_Refresh_Variables('', '', '');


CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', 
  @_Numer, @_NumerText, 'opng.nrdokfin', '-1', '0', '{DB293D87-FF8F-4947-BD05-86AB808D99D3}', 'opng', '', '');
CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', 
  @_Numer, @_NumerText, 'opng.nrdokfin', '-1', '0', '{DB293D87-FF8F-4947-BD05-86AB808D99D3}', 'opng', '', 'clear.before;update.src.table');
CALL erp_obj_counters_values_SetNumber('get.number.for.ID.Rodzaj.ObjType', 
  @_Numer, @_NumerText, 'opng.nrdokfin', '-1', '0', '{DB293D87-FF8F-4947-BD05-86AB808D99D3}', 'opng', '', 'update.src.table');  
  
--	a sprawdzam tutaj
SELECT
n.GUID, n.NrDokFin, v.*
FROM `erp_obj_counters_values` v
INNER JOIN `opng` n ON n.GUID = v.ID
WHERE
v.ID = '{DB293D87-FF8F-4947-BD05-86AB808D99D3}'
;

21 II 2025 w tym dniu nie było na sambie tego pliku po wgraniu bylo juz bez error-u  
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
