DELIMITER $$

/* ************************************************************************************************************************************************************************
	ZOO tylko!!!
	PARAGONY
	infoPiek --> INT
	
`infpie_dok_ng`
oraz
`infpie_dok_ng_rec`
TYLKO w ZOO
	
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `infoPiek_par_import_PAR_WZ`$$


DROP PROCEDURE IF EXISTS `infoPiek_par_import_WZ_DO_PARAGONOW`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `infoPiek_par_import_WZ_DO_PARAGONOW`(
	IN _MODE VARCHAR(250),
	_IDOK_HEX VARCHAR(50),	
	_Param_A VARCHAR(50)	
	)
/*
ZAMIAST procedury `infoPiek_par_import_PAR_WZ`

	ZOO tylko!!!
	Import paragonow TYLKO `zoo`
	AKTUALNE
	
	CALL infoPiek_par_import_WZ_DO_PARAGONOW('import', '', '');
	CALL infoPiek_par_import_WZ_DO_PARAGONOW('import.one.rec', '222', '');
		CALL infoPiek_par_import_WZ_DO_PARAGONOW('Set.Status', IDOK_HEX, 'E');
	
*/

S_infoPiek_par_import_WZ_DO_PARAGONOW: BEGIN
	/********************************************************************************
	P A R A G O N Y   I   R A F I
	*********************************************************************************/	
	DECLARE _KontrGUID VARCHAR(38) DEFAULT '@ST_ZS';
	DECLARE _IdnOper VARCHAR(38);
	DECLARE _ZMagazynu INTEGER DEFAULT 0; --	IKON_HEX
	DECLARE _DoMagazynu INTEGER DEFAULT 0; --	IKON_HEX
	
	DECLARE _IS_USED_LOCK BOOLEAN DEFAULT FALSE;
	DECLARE _Process, _LOCK_infopiek VARCHAR(250);
	DECLARE _Ile_Dni_Wstecz INTEGER DEFAULT 5;
	DECLARE _Do_ROW_COUNT INTEGER DEFAULT 0;
	DECLARE _CONNECTION_ID VARCHAR(38);
	
	IF SCHEMA() != 'zoo' AND SCHEMA() != 'httest' AND SCHEMA() != 'zoo_kopia' THEN LEAVE S_infoPiek_par_import_WZ_DO_PARAGONOW; END IF;
	
	SET @A := '1';

	IF _MODE = 'Set.Status' THEN
		UPDATE `infpie_dok_ng` nd
		SET
			nd.INT_Status = _Param_A,
			nd.reserved_ID = IF(_Param_A = 'F', '', nd.reserved_ID),
			nd.Attempt = IF(_Param_A = '', 1, nd.Attempt)
		WHERE
			nd.IDOK_HEX = _IDOK_HEX
		;
	END IF;		--	_MODE = 'Set.Status'
	
	
	

	IF _MODE = 'import' THEN
		/* *******************************************************************************
		WZ-ki Paragonowej
		*********************************************************************************/	
		CALL _Session_Refresh_Variables('', '', '');
		
		SET 
			_Process = CONCAT('import.WZ.do.PAR', ''),
			_LOCK_infopiek = CONCAT('infopiek_', SCHEMA())
		;
		CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 'Start przetw', 0, '', '');
		-- CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 'GET_LOCK(...)', 0, '', '');
		
		CALL _Globals_Set(_Process, NOW());

	--	ustaw zmarle sesje `reserved_ID` na swoja
		SET _CONNECTION_ID = CONNECTION_ID();
		UPDATE `infpie_dok_ng` nd
		SET
			nd.reserved_ID = 
				IF(EXISTS(SELECT p.ID FROM information_schema.`PROCESSLIST` p WHERE p.ID = nd.reserved_ID),
					nd.reserved_ID,
					_CONNECTION_ID
				),
			nd.INT_localtime = nd.INT_localtime
		WHERE
			nd.reserved_ID != ''
		;		
	--	00.	Ustaw INT_Status na 'OLD' wszystkim ktorym sie nie udalo zrealizowac czyli majacym INT_Status = 'T' lub 'E' ALE sa starsze niz 60 dni
		UPDATE `infpie_dok_ng` rd
		SET
			rd.INT_Status = CONCAT(rd.INT_Status, '->ARCH'),
			rd.INT_localtime = rd.INT_localtime,
			rd.reserved_ID = ''
		WHERE
			rd.INT_Status IN ('', 'T', 'E')
			AND
			rd.INT_Create < DATE_ADD(NOW(), INTERVAL -60 DAY)
			AND
			rd.attempt <= 5
			AND
			reserved_ID IN ('', _CONNECTION_ID)
		;
	--	0.	Ustaw INT_Status na '' wszystkim ktorym sie nie udalo zrealizowac czyli majacym INT_Status = 'T' lub 'E' ALE UWAGA!!! maja attempt <= 5!! Gdy > 6 to juz nie obslugujemy
		UPDATE `infpie_dok_ng` rd
		SET
			rd.INT_Status = '',
			rd.INT_localtime = rd.INT_localtime
		WHERE
			rd.INT_Status IN ('T', 'E')
			AND
			rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
			AND
			rd.attempt <= 5
			AND
			reserved_ID IN ('', _CONNECTION_ID)
		;

		UPDATE `infpie_dok_ng` rd
		SET
			rd.reserved_ID = _CONNECTION_ID,
			rd.INT_Status = 'T',	--	Temporary czyli przetwarzam
			rd.attempt = rd.attempt + 1,
			rd.INT_localtime = rd.INT_localtime
		WHERE
			rd.INT_Status = ''
			AND
			rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
			AND 
			rd.reserved_ID IN ('', _CONNECTION_ID)
		;
		
	--	1.	kreuję tymcz.
		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_ng`;
		CREATE TEMPORARY TABLE `t_infpie_dok_ng`
			SELECT
				rd.*
			FROM `infpie_dok_ng` rd
			WHERE
				rd.reserved_ID = _CONNECTION_ID
				/* bylo
				AND rd.INT_Status = ''
				AND
				rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
				*/
		;
		/* bylo
		SELECT COUNT(*) FROM `t_infpie_dok_ng` INTO _Do_ROW_COUNT;
		*/
		SELECT COUNT(*) FROM `infpie_dok_ng` rd WHERE rd.reserved_ID = _CONNECTION_ID INTO _Do_ROW_COUNT;
		-- SELECT ROW_COUNT() INTO _Do_ROW_COUNT;
		IF IFNULL(@_POS_POS_2_INT.Select.ROW_COUNT, FALSE) THEN select _Do_ROW_COUNT; END IF;
		-- IF _Param_A != '' THEN select _Do_ROW_COUNT; END IF;
		IF _Do_ROW_COUNT <= 0 THEN
	--	B R A K rekordów do przetwarzania
			CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 'Brak rekordow do przetwarzania', 0, '', '');
			-- LEAVE S_infoPiek_par_import_RAFI;
		ELSE
	--	P E T L A	
			CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 
				CONCAT('Petla dok. w liczbie = ', _Do_ROW_COUNT), 
				0, '', '');

			
		/* bylo	
		--	2.	ustawiam status na 'T' temporary czyli przetwarzam
			UPDATE `infpie_dok_ng` r, `t_infpie_dok_ng` t
			SET
				r.INT_Status = 'T',	--	Temporary czyli przetwarzam
				r.attempt = r.attempt + 1
			WHERE
				r.IDOK_HEX = t.IDOK_HEX
			;
		*/	
		--	3.	Pętla przetwarzania
			SET @ROW_Curr = 0;
			BEGIN
			-- 	Operacje np. magazynowe
			
				DECLARE done BOOL DEFAULT FALSE;
				DECLARE _IDOK_HEX INTEGER DEFAULT 0;
			--	3.1 Kursor	
				DECLARE c_t_infpie_dok_ng CURSOR FOR
					SELECT
						rd.IDOK_HEX
						
					-- bylo FROM `t_infpie_dok_ng` t
					FROM `infpie_dok_ng` rd
					WHERE 
						rd.reserved_ID = _CONNECTION_ID
						AND
						rd.INT_Status = 'T'	-- przetwarzane
				;	
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				DECLARE EXIT HANDLER FOR SQLEXCEPTION 
				BEGIN
					GET DIAGNOSTICS CONDITION 1
						@h.p1 = RETURNED_SQLSTATE, @h.p2 = MESSAGE_TEXT
					;
					CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 
						REPLACE(REPLACE('ERROR (#SQLSTATE#): #MESSAGE_TEXT#', '#SQLSTATE#', IFNULL(@h.p1, '')), '#MESSAGE_TEXT#', IFNULL(@h.p2, '')), 
						1, '', '');
					CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 
						CONCAT('Blad systemu gdy przetwarzano rekord nr: ', @ROW_Curr), 
						1, '', '');
					SET @ROW_Curr = @ROW_Curr - 1;

					-- SET done_err = TRUE;
				END;
				
			--	3.2 Open Kursor	
				OPEN c_t_infpie_dok_ng;
				loop_c_t_infpie_dok_ng: LOOP
					SET done = FALSE;
					FETCH c_t_infpie_dok_ng INTO 
						_IDOK_HEX
					;
					IF done THEN
						LEAVE loop_c_t_infpie_dok_ng;
					END IF;
				--	Wykonaj naliczanie
					SET @ROW_Curr = @ROW_Curr + 1;
					CALL infoPiek_par_import_WZ_DO_PARAGONOW('import.one.rec', _IDOK_HEX, '');
				END LOOP;
				CLOSE c_t_infpie_dok_ng;
			
			END;
			
			CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 
				CONCAT('Przetwarzono = ', @ROW_Curr), 
				0, '', '');
			
		--	5.	przepisz status do infpie_dok_ng
		--	6.	usuń rekordy z `infpie_dok_ng_rec` ze statusem na 'F' czyli zakonczono 
		
			-- SET @_RELEASE_LOCK = RELEASE_LOCK(_LOCK_infopiek);
			-- CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 'RELEASE_LOCK(...)', 0, '', '');
		END IF;
		
	--	Wyczysc blokujaca sesje
		UPDATE `infpie_dok_ng` rd
		SET
			rd.reserved_ID = ''
		WHERE
			rd.reserved_ID = _CONNECTION_ID
		;
	--	10.	usuń tymczsowkę
		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_ng`;
	
		CALL _erp_external_process_log_tools('Insert', _Process, 'infpie_dok_ng', 'Koniec przetw', 0, '', '');
	END IF;		--	_MODE = 'import.RAFI'
		
		
	IF _MODE = 'import.one.rec' THEN
	-- S_import_one_rec_Exit: BEGIN
		/* *******************************************************************************
		WZ DO PARAGONOW
		*********************************************************************************/	
		
	--	1.	ustawiam status na 'E' czyli teraz przetwarzam (E ma znaczenie: error gdy zostanie nie zmieniony na F)
		CALL infoPiek_par_import_WZ_DO_PARAGONOW('Set.Status', _IDOK_HEX, 'Brak pozycji');
		
		
		SET
			@import.one.rec.Exist.Pozycje = 
			EXISTS(
				SELECT dp.INT_GUID AS GUID FROM `infpie_dok_po` dp WHERE dp.IDOK_HEX = _IDOK_HEX AND dp.ARTYK_PLU > 0
			)					
		;
		IF NOT @import.one.rec.Exist.Pozycje THEN
			LEAVE S_infoPiek_par_import_WZ_DO_PARAGONOW;
		END IF;

	--	1.	ustawiam status na 'E' czyli teraz przetwarzam (E ma znaczenie: error gdy zostanie nie zmieniony na F)
		CALL infoPiek_par_import_WZ_DO_PARAGONOW('Set.Status', _IDOK_HEX, 'E');
		SELECT 
			dn.INT_GUID,
			dn.IKON_HEX
		FROM `infpie_dok_ng` dn
		WHERE
			dn.IDOK_HEX = _IDOK_HEX
		INTO
			_IdnOper,
			_ZMagazynu
		;
		SET
			_KontrGUID = IFNULL((SELECT k.GUID FROM `kontrah` k WHERE k.sklep = _ZMagazynu LIMIT 1), _KontrGUID)
		;
		SET 
			@Rodzaj = 10,
			@IdnOper = _IdnOper,
			@KontrGUID = _KontrGUID,
			@_Tymczasowa = TRUE,
			@G = '',
			@ZMagazynu = _ZMagazynu
		;
CALL _WatchTimeLogs_Tools('start', "Opng_E_init", '-', '', '', '');
		
CALL _WatchTimeLogs_Tools('start', "CALL Opng_E_init('INSERT', _IdnOper, 'jmam_alg', '1', 'Server');", '-', '', '', '');
		CALL Opng_E_init('INSERT', _IdnOper, 'jmam_alg', '1', 'Server'); 	-- _Param_A jest tu != '' aby nie wywoływać selecta wewn. innej proc. _ng_e_rec_init
CALL _WatchTimeLogs_Tools('stop', "CALL Opng_E_init('INSERT', _IdnOper, 'jmam_alg', '1', 'Server');", '-', '', '', '');
		
CALL _WatchTimeLogs_Tools('start', "CALL Opng_E_init_set('', _IdnOper, @Rodzaj, 0, '', '3', _KontrGUID, _ZMagazynu, 0, 0, 0, '', '', '', 0, '', '', '');", '-', '', '', '');
		CALL Opng_E_init_set('', _IdnOper, @Rodzaj, 0, '', '3', _KontrGUID, _ZMagazynu, 0, 0, 0, '', '', '', 0, '', '', '');
CALL _WatchTimeLogs_Tools('stop', "CALL Opng_E_init_set('', _IdnOper, @Rodzaj, 0, '', '3', _KontrGUID, _ZMagazynu, 0, 0, 0, '', '', '', 0, '', '', '');", '-', '', '', '');



CALL _WatchTimeLogs_Tools('start', "CALL Opng_E_Run('before.run', _IdnOper, '', '', ''); ...", '-', '', '', '');
		CALL Opng_E_Run('before.run', _IdnOper, '', '', '');
		CALL Opng_E_Run('', _IdnOper, '', '', '');
		CALL Opng_E_Run('after.run', _IdnOper, '', '', '');
CALL _WatchTimeLogs_Tools('stop', "CALL Opng_E_Run('before.run', _IdnOper, '', '', ''); ...", '-', '', '', '');
		
CALL _WatchTimeLogs_Tools('start', "Updaty...", '-', '', '', '');
		UPDATE	`opng_e` n, `infpie_dok_ng` dn
		SET
			n.NrDokFin = CONCAT('#', LPAD(_ZMagazynu, 3, '0'), '/', dn.IDOK_NUM, '/', YEAR(dn.IDOK_DAT)),
			n.NrWewn = IF(_IDOK_HEX = 999999, '', ''),
			n.przeliczenie_B_N = 1,
			n.paragon_printed = 1,
			-- BYLO kiedy by paragon teraz jest WZ  n.Rozrachunek = 1, 	-- p.Marek 2013-08-14 14:58 ZAWSZE 1 n.Rozrachunek = IF(dn.IDOK_PLA = 1, 0, 1),
			n.Rozrachunek = 0, 	-- Bo jest to WZ-ka
			n.Datawystaw = IF(dn.IDOK_DAT = '0000-00-00', CURRENT_DATE(), dn.IDOK_DAT),
			n.DataSprzed = IF(dn.IDOK_DAT = '0000-00-00', CURRENT_DATE(), dn.IDOK_DAT),
			n.DataWplywu = IF(dn.IDOK_DAT = '0000-00-00', CURRENT_DATE(), dn.IDOK_DAT),
			n.remotetime = dn.IDOK_TIM,
			n.id_kasy_fis = dn.IDOK_LIC,
			n.AreaGUID = (SELECT m.AreaGUID FROM Magazyny m WHERE m.IdnMagazynu = _ZMagazynu LIMIT 1),
			n.osobaGUID = (SELECT o.GUID FROM `osoby` o WHERE o.IDN = dn.IDOK_KTO LIMIT 1),
			n.wzordekr = 'K'
		WHERE
			dn.IDOK_HEX = _IDOK_HEX
			AND
			n.GUID = _IdnOper
		;
		UPDATE	`opng_e` n, `erp_area_nodes` an
		SET
			n.opis = CONCAT('Paragon fisk. z urz.: ', n.id_kasy_fis, ' w : ', an.Nazwa, ' (', n.remotetime, ')')
		WHERE
			n.GUID = _IdnOper
			AND
			an.GUID = n.AreaGUID
		;
		UPDATE	`opng_e` n, `osoby` o
		SET
			n.idnuser = o.idnuser,
			n.opis = CONCAT(n.opis, ' wyst.: ', o.Nazwisko, ' ', o.Imiona)
		WHERE
			n.GUID = _IdnOper
			AND
			o.GUID = n.osobaGUID
		;
		UPDATE `infpie_dok_po` dp
		SET 
			dp.ARTYK_GUID = RTRIM(dp.ARTYK_GUID)
		WHERE
			dp.IDOK_HEX = _IDOK_HEX 
		;		
		UPDATE `infpie_dok_po` dp
		SET
			dp.ARTYK_GUID = 
			IFNULL(
			(SELECT GUID FROM `TowrNg` t WHERE t.IDN = dp.ARTYK_HEX ORDER BY t.IDN LIMIT 1), ''
			)
		WHERE
			dp.ARTYK_GUID = ''
			AND
			dp.IDOK_HEX = _IDOK_HEX 
		;
CALL _WatchTimeLogs_Tools('stop', "Updaty...", '-', '', '', '');
		
CALL _WatchTimeLogs_Tools('start', "`t_infpie_dok_po_insert`...", '-', '', '', '');

		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_po_insert`;
		IF FALSE THEN	--	Wartosc Brutto
			CREATE TEMPORARY TABLE `t_infpie_dok_po_insert`
				SELECT
					dp.INT_GUID AS GUID, -- 	CONCAT('Infpie_', dp.IPOZ_HEX) AS GUID,
					_IdnOper AS IdnOper,
					-- (SELECT GUID FROM `TowrNg` t WHERE t.kod_fiskalny = dp.ARTYK_PLU ORDER BY t.IDN LIMIT 1) AS IdnTowr,
					dp.ARTYK_GUID AS IdnTowr,
					-- było (SELECT GUID FROM `TowrNg` t WHERE t.IDN = dp.ARTYK_HEX ORDER BY t.IDN LIMIT 1) AS IdnTowr,
					-- t.GUID AS IdnTowr,
					IFNULL(dp.IPOZ_ILE, 0.0) AS Ilosc,
					IFNULL(dp.IPOZ_WAB, 0.0) AS WartBrt,	--	bylo IFNULL(dp.IPOZ_CEB, 0.0) AS CenaBrt,
					IFNULL(0*dp.IPOZ_RAB, 0.0) AS rabat,	--	UWAGA TERAZ Rabat daje juz na 0
					4 AS rodzaj_przeliczenia, -- z wart. brutto do ceny brt itd	a bylo 5 	-- Brutto z ceny brutto  BYŁO 7 (_BN_CB_WN_POS) jest 5 
					dp.INT_IDNVAT AS IdnVat
				FROM `infpie_dok_po` dp
				-- INNER JOIN `TowrNg` t ON t.IDN = dp.ARTYK_HEX 	-- Bylo ale uznaliśmy że lepiej gdy będzie to kod_fiskalny czyli ARTYK_PLU
				-- INNER JOIN `TowrNg` t ON t.kod_fiskalny = dp.ARTYK_PLU
				WHERE
					dp.IDOK_HEX = _IDOK_HEX 
					AND
					dp.ARTYK_PLU > 0
			;
			INSERT IGNORE INTO `oppo_e` 
			(GUID, IdnOper, IdnTowr, Ilosc, WartBrt, rabat, rodzaj_przeliczenia, IdnVat)
				SELECT
					dp.GUID,
					dp.IdnOper,
					dp.IdnTowr,
					dp.Ilosc,
					dp.WartBrt,
					dp.rabat,
					dp.rodzaj_przeliczenia, 	-- Brutto z ceny brutto
					dp.IdnVat
				FROM `t_infpie_dok_po_insert` dp
			ON DUPLICATE KEY UPDATE
				`oppo_e`.IdnTowr = dp.IdnTowr,
				`oppo_e`.Ilosc = dp.Ilosc
			;
		ELSE	--	Cena Brutto
			CREATE TEMPORARY TABLE `t_infpie_dok_po_insert`
				SELECT
					dp.INT_GUID AS GUID, -- 	CONCAT('Infpie_', dp.IPOZ_HEX) AS GUID,
					_IdnOper AS IdnOper,
					-- (SELECT GUID FROM `TowrNg` t WHERE t.kod_fiskalny = dp.ARTYK_PLU ORDER BY t.IDN LIMIT 1) AS IdnTowr,
					dp.ARTYK_GUID AS IdnTowr,
					-- było (SELECT GUID FROM `TowrNg` t WHERE t.IDN = dp.ARTYK_HEX ORDER BY t.IDN LIMIT 1) AS IdnTowr,
					-- t.GUID AS IdnTowr,
					IFNULL(dp.IPOZ_ILE, 0.0) AS Ilosc,
					IFNULL(dp.IPOZ_WAB, 0.0) AS CenaBrt,	--	bylo IFNULL(dp.IPOZ_CEB, 0.0) AS CenaBrt,
					IFNULL(0*dp.IPOZ_RAB, 0.0) AS rabat,	--	UWAGA TERAZ Rabat daje juz na 0
					5 AS rodzaj_przeliczenia, -- Brutto z ceny brutto  BYŁO 7 (_BN_CB_WN_POS) jest 5 
					dp.INT_IDNVAT AS IdnVat
				FROM `infpie_dok_po` dp
				-- INNER JOIN `TowrNg` t ON t.IDN = dp.ARTYK_HEX 	-- Bylo ale uznaliśmy że lepiej gdy będzie to kod_fiskalny czyli ARTYK_PLU
				-- INNER JOIN `TowrNg` t ON t.kod_fiskalny = dp.ARTYK_PLU
				WHERE
					dp.IDOK_HEX = _IDOK_HEX 
					AND
					dp.ARTYK_PLU > 0
			;
			INSERT IGNORE INTO `oppo_e` 
			(GUID, tag, IdnOper, IdnTowr, Ilosc, CenaBrt, rabat, rodzaj_przeliczenia, IdnVat)
				SELECT
					dp.GUID,
					1,
					dp.IdnOper,
					dp.IdnTowr,
					dp.Ilosc,
					dp.CenaBrt,
					dp.rabat,
					dp.rodzaj_przeliczenia, 	-- Brutto z ceny brutto
					dp.IdnVat
				FROM `t_infpie_dok_po_insert` dp
			ON DUPLICATE KEY UPDATE
				`oppo_e`.IdnTowr = dp.IdnTowr,
				`oppo_e`.Ilosc = dp.Ilosc
			;
			UPDATE `oppo_e` p, `t_infpie_dok_po_insert` dp
			SET
				p.IdnVat = dp.IdnVat
			WHERE
				p.GUID = dp.GUID
			;
		END IF;
		
CALL _WatchTimeLogs_Tools('stop', "`t_infpie_dok_po_insert`...", '-', '', '', '');

CALL _WatchTimeLogs_Tools('start', "CALL oppo_E_Let_Update('from_opng_e', '', _IdnOper, '', ''); i update...", '-', '', '', '');
		CALL oppo_E_Let_Update('from_opng_e.after.insert', '', _IdnOper, '', '');
		UPDATE `oppo_e` p
		SET
			p.Tag = 0
		WHERE
			p.IdnOper = _IdnOper
		;
		-- BYLO CALL oppo_E_Let_Update('from_opng_e', '', _IdnOper, '', '');
		--	IdnVat TRACĘ w triggerze `oppo_e` po wstawieniu IdnTowr - zatem raz jeszcze go wstawiam
		

		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_po_insert`;
			-- CALL oppo_E_Let_Update('one_rec', _GUID, '', '', '');
CALL _WatchTimeLogs_Tools('stop', "CALL oppo_E_Let_Update('from_opng_e', '', _IdnOper, '', ''); i update...", '-', '', '', '');
		
CALL _WatchTimeLogs_Tools('start', "Post...", '-', '', '', '');
		CALL opng_E_Let('Post', _IdnOper, '', '');
CALL _WatchTimeLogs_Tools('stop', "Post...", '-', '', '', '');
		-- CALL ng_vat_e_build_from_po('', 'OP', _IdnOper, '', '');              Niepotrzebne wolane juz w opng_E_Let('Post', ...
		
CALL _WatchTimeLogs_Tools('start', "Apply...", '-', '', '', '');
		CALL opng_E_Let('ApplyAndClear', _IdnOper, '', '1');		--	 Wraz z numeracja
CALL _WatchTimeLogs_Tools('stop', "Apply...", '-', '', '', '');

CALL _WatchTimeLogs_Tools('stop', "Opng_E_init", '-', '', '', '');

		/*
		
		SELECT n.rozrachunek, n.grupaoper, n.wzordekr, n.ugrpGUID, n.* FROM opng_e n WHERE GUID = @IdnOper;
		SELECT p.* FROM oppo_e p WHERE IdnOper = @IdnOper;
			CALL opng_E_Let('Post', _IdnOper, '', '');
			-- CALL opng_E_Let('Apply', _IdnOper, '', '');
			CALL opng_E_Let('ApplyAndClear', _IdnOper, '', '');
			-- CALL opng_E_Let('End', _IdnOper, '', '');
		*/
		
		
	--	3.	ustawiam status na 'F' czyli zakonczono 
		CALL infoPiek_par_import_WZ_DO_PARAGONOW('Set.Status', _IDOK_HEX, 'F'); 	-- 'F' czyli zakonczono 
	-- END;
	END IF;		--	_MODE = 'import.one.rec'

END$$


DROP PROCEDURE IF EXISTS `infoPiek_par_import_RAFI`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `infoPiek_par_import_RAFI`(
	IN _MODE VARCHAR(250),
	_RAFI_HEX VARCHAR(50),	
	_Param_A VARCHAR(50)	
	)
/*
	ZOO tylko!!!
	Import paragonow TYLKO `zoo`
	AKTUALNE
	
	CALL infoPiek_par_import_RAFI('import.RAFI', '', '');
	CALL infoPiek_par_import_RAFI('import.RAFI.one.rec', '222', '');
		CALL infoPiek_par_import_RAFI('Set.Status', _RAFI_HEX, 'E');
	
*/

S_infoPiek_par_import_RAFI: BEGIN
	/********************************************************************************
	P A R A G O N Y   I   R A F I
	*********************************************************************************/	
	DECLARE _KontrGUID VARCHAR(38) DEFAULT '@ST_ZS';
	DECLARE _IdnOper VARCHAR(38);
	DECLARE _ZMagazynu INTEGER DEFAULT 0; --	IKON_HEX
	DECLARE _DoMagazynu INTEGER DEFAULT 0; --	IKON_HEX
	
	DECLARE _IS_USED_LOCK BOOLEAN DEFAULT FALSE;
	DECLARE _Process, _LOCK_infopiek VARCHAR(250);
	DECLARE _Ile_Dni_Wstecz INTEGER DEFAULT 14;
	DECLARE _Do_ROW_COUNT INTEGER DEFAULT 0;
	DECLARE _SQLText TEXT;
	DECLARE _CONNECTION_ID VARCHAR(38);
	
	IF SCHEMA() != 'zoo' AND SCHEMA() != 'httest' AND SCHEMA() != 'zoo_kopia' THEN LEAVE S_infoPiek_par_import_RAFI; END IF;
	
	
	IF _MODE = 'Set.Status' THEN
		UPDATE `infpie_dok_ng_dobowe` nd
		SET
			nd.INT_Status = _Param_A,
			nd.reserved_ID = IF(_Param_A = 'F', '', nd.reserved_ID),
			nd.Attempt = IF(_Param_A = '', 1, nd.Attempt)
		WHERE
			nd.RAFI_HEX = _RAFI_HEX
		;
	END IF;		--	_MODE = 'Set.Status'
	
	
	IF _MODE = 'import.RAFI' THEN
		/* *******************************************************************************
		R A F I
		*********************************************************************************/	
		CALL _Session_Refresh_Variables('', '', '');
		
		SET 
			_Process = CONCAT('import.RAFI', ''),
			_LOCK_infopiek = CONCAT('infopiek_', SCHEMA())
		;
		CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 'Start przetw', 0, '', '');
		-- CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 'GET_LOCK(...)', 0, '', '');
		
		CALL _Globals_Set(_Process, NOW());

	--	ustaw zmarle sesje `reserved_ID` na swoja
		SET _CONNECTION_ID = CONNECTION_ID();
		UPDATE `infpie_dok_ng_dobowe` nd
		SET
			nd.reserved_ID = 
				IF(EXISTS(SELECT p.ID FROM information_schema.`PROCESSLIST` p WHERE p.ID = nd.reserved_ID),
					nd.reserved_ID,
					_CONNECTION_ID
				),
			nd.INT_localtime = nd.INT_localtime
		WHERE
			nd.reserved_ID != ''
		;		
	--	00.	Ustaw INT_Status na 'OLD' wszystkim ktorym sie nie udalo zrealizowac czyli majacym INT_Status = 'T' lub 'E' ALE sa starsze niz 60 dni
		UPDATE `infpie_dok_ng_dobowe` rd
		SET
			rd.INT_Status = CONCAT(rd.INT_Status, '->ARCH'),
			rd.INT_localtime = rd.INT_localtime,
			rd.reserved_ID = ''
		WHERE
			rd.INT_Status IN ('', 'T', 'E')
			AND
			rd.INT_Create < DATE_ADD(NOW(), INTERVAL -60 DAY)
			AND
			rd.attempt <= 5
			AND
			reserved_ID IN ('', _CONNECTION_ID)
		;
	--	0.	Ustaw INT_Status na '' wszystkim ktorym sie nie udalo zrealizowac czyli majacym INT_Status = 'T' lub 'E' ALE UWAGA!!! maja attempt <= 5!! Gdy > 6 to juz nie obslugujemy
		UPDATE `infpie_dok_ng_dobowe` rd
		SET
			rd.INT_Status = '',
			rd.INT_localtime = rd.INT_localtime
		WHERE
			rd.INT_Status IN ('T', 'E')
			AND
			rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
			AND
			rd.attempt <= 5
			AND
			reserved_ID IN ('', _CONNECTION_ID)
		;

		UPDATE `infpie_dok_ng_dobowe` rd
		SET
			rd.reserved_ID = _CONNECTION_ID,
			rd.INT_Status = 'T',	--	Temporary czyli przetwarzam
			rd.attempt = rd.attempt + 1,
			rd.INT_localtime = rd.INT_localtime
		WHERE
			rd.INT_Status = ''
			AND
			rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
			AND 
			rd.reserved_ID IN ('', _CONNECTION_ID)
		;
		
	--	1.	kreuję tymcz.
		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_ng_dobowe`;
		CREATE TEMPORARY TABLE `t_infpie_dok_ng_dobowe`
			SELECT
				rd.*
			FROM `infpie_dok_ng_dobowe` rd
			WHERE
				rd.reserved_ID = _CONNECTION_ID
				/* bylo
				AND rd.INT_Status = ''
				AND
				rd.INT_localtime > DATE_ADD(NOW(), INTERVAL -_Ile_Dni_Wstecz DAY)
				*/
		;
		/* bylo
		SELECT COUNT(*) FROM `t_infpie_dok_ng_dobowe` INTO _Do_ROW_COUNT;
		*/
		SELECT COUNT(*) FROM `infpie_dok_ng_dobowe` rd WHERE rd.reserved_ID = _CONNECTION_ID INTO _Do_ROW_COUNT;
		-- SELECT ROW_COUNT() INTO _Do_ROW_COUNT;
		IF IFNULL(@_POS_POS_2_INT.Select.ROW_COUNT, FALSE) THEN select _Do_ROW_COUNT; END IF;
		-- IF _Param_A != '' THEN select _Do_ROW_COUNT; END IF;
		IF _Do_ROW_COUNT <= 0 THEN
	--	B R A K rekordów do przetwarzania
			CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 'Brak rekordow do przetwarzania', 0, '', '');
			-- LEAVE S_infoPiek_par_import_RAFI;
		ELSE
	--	P E T L A	
			CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 
				CONCAT('Petla dok. w liczbie = ', _Do_ROW_COUNT), 
				0, '', '');

			
		/* bylo	
		--	2.	ustawiam status na 'T' temporary czyli przetwarzam
			UPDATE `infpie_dok_ng_dobowe` r, `t_infpie_dok_ng_dobowe` t
			SET
				r.INT_Status = 'T',	--	Temporary czyli przetwarzam
				r.attempt = r.attempt + 1
			WHERE
				r.RAFI_HEX = t.RAFI_HEX
			;
		*/	
		--	3.	Pętla przetwarzania
			SET @ROW_Curr = 0;
			BEGIN
			-- 	Operacje np. magazynowe
			
				DECLARE done BOOL DEFAULT FALSE;
				DECLARE _RAFI_HEX INTEGER DEFAULT 0;
			--	3.1 Kursor	
				DECLARE c_t_infpie_dok_ng_dobowe CURSOR FOR
					SELECT
						rd.RAFI_HEX
						
					-- bylo FROM `t_infpie_dok_ng_dobowe` t
					FROM `infpie_dok_ng_dobowe` rd
					WHERE 
						rd.reserved_ID = _CONNECTION_ID
						AND
						rd.INT_Status = 'T'	-- przetwarzane
				;	
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				DECLARE EXIT HANDLER FOR SQLEXCEPTION 
				BEGIN
					GET DIAGNOSTICS CONDITION 1
						@h.p1 = RETURNED_SQLSTATE, @h.p2 = MESSAGE_TEXT
					;
					CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 
						REPLACE(REPLACE('ERROR (#SQLSTATE#): #MESSAGE_TEXT#', '#SQLSTATE#', IFNULL(@h.p1, '')), '#MESSAGE_TEXT#', IFNULL(@h.p2, '')), 
						1, '', '');
					CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 
						CONCAT('Blad systemu gdy przetwarzano rekord nr: ', @ROW_Curr), 
						1, '', '');
					SET @ROW_Curr = @ROW_Curr - 1;

					-- SET done_err = TRUE;
				END;
				
			--	3.2 Open Kursor	
				OPEN c_t_infpie_dok_ng_dobowe;
				loop_c_t_infpie_dok_ng_dobowe: LOOP
					SET done = FALSE;
					FETCH c_t_infpie_dok_ng_dobowe INTO 
						_RAFI_HEX
					;
					IF done THEN
						LEAVE loop_c_t_infpie_dok_ng_dobowe;
					END IF;
				--	Wykonaj naliczanie
					SET @ROW_Curr = @ROW_Curr + 1;
					CALL infoPiek_par_import_RAFI('import.RAFI.one.rec', _RAFI_HEX, '');
				END LOOP;
				CLOSE c_t_infpie_dok_ng_dobowe;
			
			END;
			
			CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 
				CONCAT('Przetwarzono = ', @ROW_Curr), 
				0, '', '');
			
		--	5.	przepisz status do infpie_dok_ng
		--	6.	usuń rekordy z `infpie_dok_ng_rec` ze statusem na 'F' czyli zakonczono 
		
			-- SET @_RELEASE_LOCK = RELEASE_LOCK(_LOCK_infopiek);
			-- CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 'RELEASE_LOCK(...)', 0, '', '');
		END IF;
		
	--	Wyczysc blokujaca sesje
		UPDATE `infpie_dok_ng_dobowe` rd
		SET
			rd.reserved_ID = ''
		WHERE
			rd.reserved_ID = _CONNECTION_ID
		;
	--	10.	usuń tymczsowkę
		DROP TEMPORARY TABLE IF EXISTS `t_infpie_dok_ng_dobowe`;
	
		CALL _erp_external_process_log_tools('Insert', _Process, 'Info_piek', 'Koniec przetw', 0, '', '');
	END IF;		--	_MODE = 'import.RAFI'
		
		
	IF _MODE = 'import.RAFI.one.rec' THEN
	S_import_RAFI_one_rec_Exit: BEGIN
		/* *******************************************************************************
		R A F I
		*********************************************************************************/	
		
	--	1.	ustawiam status na 'E' czyli teraz przetwarzam (E ma znaczenie: error gdy zostanie nie zmieniony na F)
		CALL infoPiek_par_import_RAFI('Set.Status', _RAFI_HEX, 'E');
		
		SELECT 
			dn.INT_GUID,
			dn.KONT_HEX
		FROM `infpie_dok_ng_dobowe` dn
		WHERE
			dn.RAFI_HEX = _RAFI_HEX
		INTO
			_IdnOper,
			_ZMagazynu
		;
		SET @A = '0';
		SET
			_KontrGUID = IFNULL((SELECT k.GUID FROM `kontrah` k WHERE k.sklep = _ZMagazynu LIMIT 1), _KontrGUID)
		;
		SET 
			@Rodzaj = 0,
			@IdnOper = _IdnOper,
			@KontrGUID = _KontrGUID,
			@_Tymczasowa = TRUE,
			@G = '',
			@ZMagazynu = _ZMagazynu,
			@i_fvrudowz = 0		--	KONIECZNIE bo jak daje 1 to laduje milion wierszy potencjalnych poz. WZ. ALE fvrudowz = 1 daj nizej w osobnym UPDATE 
		;
		SET @A = '1';
		CALL Opng_E_init('INSERT', _IdnOper, 'jmam_alg', '1', 'Server'); 	-- _Param_A jest tu != '' aby nie wywoływać selecta wewn. innej proc. _ng_e_rec_init
		SET @A = '2';
		CALL Opng_E_init_set('', _IdnOper, @Rodzaj, 0, '', '3', _KontrGUID, _ZMagazynu, 0, 0, 0, '', '', '', @i_fvrudowz, '', '', '');
		SET @A = '3';

		CALL Opng_E_Run('before.run', _IdnOper, '', '', '');
		SET @A = '4';
		CALL Opng_E_Run('', _IdnOper, '', '', '');
		SET @A = '5';
		CALL Opng_E_Run('after.run', _IdnOper, '', '', '');
		SET @A = '6';


		/*
		UPDATE `ng_e_rec` ng
		SET
			ng.i_fvrudowz = 1
		WHERE
			ng.GUID = _IdnOper
		;
		*/
		UPDATE	`opng_e` n, `infpie_dok_ng_dobowe` dn
		SET
			-- n.fvrudowz = 1,
			n.NrDokFin = CONCAT('#', dn.INT_NrdokFin, ''),
			n.NrWewn = IF(_RAFI_HEX = 999999, '', ''),
			n.przeliczenie_B_N = 1,
			n.paragon_printed = 1,
			n.Rozrachunek = 1, 	-- p.Marek 2013-08-14 14:58 ZAWSZE 1 n.Rozrachunek = IF(dn.IDOK_PLA = 1, 0, 1),
			n.Datawystaw = IF(dn.RAFI_DAT = '0000-00-00', CURRENT_DATE(), dn.RAFI_DAT),
			n.DataSprzed = IF(dn.RAFI_DAT = '0000-00-00', CURRENT_DATE(), dn.RAFI_DAT),
			n.DataWplywu = IF(dn.RAFI_DAT = '0000-00-00', CURRENT_DATE(), dn.RAFI_DAT),
			n.data_vat = IF(dn.RAFI_DAT = '0000-00-00', CURRENT_DATE(), dn.RAFI_DAT),
			n.remotetime = dn.RAFI_DTT,
			n.id_kasy_fis = dn.RAFI_IUF,
			n.AreaGUID = (SELECT m.AreaGUID FROM Magazyny m WHERE m.IdnMagazynu = _ZMagazynu LIMIT 1),
			-- n.osobaGUID = (SELECT o.GUID FROM `osoby` o WHERE o.IDN = dn.IDOK_KTO LIMIT 1),
			n.wzordekr = 'K'
		WHERE
			dn.RAFI_HEX = _RAFI_HEX
			AND
			n.GUID = _IdnOper
		;
		SET @A = '7';
		UPDATE	`opng_e` n, `erp_area_nodes` an
		SET
			n.opis = CONCAT('Paragon fisk. z urz.: ', n.id_kasy_fis, ' w : ', an.Nazwa, ' (', n.remotetime, ')')
		WHERE
			n.GUID = _IdnOper
			AND
			an.GUID = n.AreaGUID
		;
		/*
		UPDATE	`opng_e` n, `osoby` o
		SET
			n.idnuser = o.idnuser,
			n.opis = CONCAT(n.opis, ' wyst.: ', o.Nazwisko, ' ', o.Imiona)
		WHERE
			n.GUID = _IdnOper
			AND
			o.GUID = n.osobaGUID
		;
		*/
		SET 
			@import.RAFI.one.rec._FULL_ALG = TRUE, -- FALSE,
			@import.RAFI.one.rec._Nie_Zapisuj = FALSE -- TRUE
		;
		
		SET @A = '8';
		
		IF @import.RAFI.one.rec._FULL_ALG THEN
		--	Ustaw fvrudowz
			UPDATE	`opng_e` n
			SET
				n.fvrudowz = 1
			WHERE
				n.GUID = _IdnOper
			;
		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS `t_opng_WZ_do_Paragonu`;
		CREATE TEMPORARY TABLE `t_opng_WZ_do_Paragonu`
		SELECT
			np.INT_GUID
		FROM `infpie_dok_ng_dobowe` dn, `infpie_dok_ng` np 
		WHERE
			dn.RAFI_HEX = _RAFI_HEX
			AND np.IDOK_DAT = dn.RAFI_DAT 
			AND IF(SUBSTR(np.IDOK_NUM, 1, 1) = 'P', 1, 2) = dn.RAFI_TYU 
			AND np.IDOK_LIC = dn.RAFI_IUF 
			AND np.IKON_HEX = dn.KONT_HEX 
		;

		DROP TEMPORARY TABLE IF EXISTS `t_oppo_WZ_do_Paragonu`;
		CREATE TEMPORARY TABLE `t_oppo_WZ_do_Paragonu` LIKE `oppo_e`;
		INSERT IGNORE INTO `t_oppo_WZ_do_Paragonu`
			SELECT
				p.*
			FROM `oppo` p, `t_opng_WZ_do_Paragonu` n
			WHERE
				p.IdnOper = n.INT_GUID
		;
		
		SET
			@import.RAFI.one.rec.oppo.Count = IFNULL((SELECT COUNT(*) FROM `t_oppo_WZ_do_Paragonu`), 0)
		;
		
		IF @import.RAFI.one.rec.oppo.Count = 0 THEN
		--	brak pozycji wychodzimy
			CALL opng_E_Let('Clear', _IdnOper, '', '1');		--	 Wraz z numeracja
			CALL infoPiek_par_import_RAFI('Set.Status', _RAFI_HEX, '');
			LEAVE S_import_RAFI_one_rec_Exit;
		END IF;
		
		UPDATE `t_oppo_WZ_do_Paragonu` tp
		SET
			tp.IdnWZ = _IdnOper,
			-- tp.Tag = 0,
			tp.IdnOperFin = _IdnOper,
			tp.IdnOper_e = _IdnOper
		;
		
		IF @import.RAFI.one.rec._FULL_ALG THEN
			INSERT IGNORE INTO `oppo_e`
				SELECT * FROM `t_oppo_WZ_do_Paragonu`
			;
		END IF;
		SET @A = '9';
	--	Teraz `opng_vat_e`
		DELETE FROM `opng_vat_e` WHERE IdnOper = _IdnOper;
	--	od 1..6
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '1'); 	
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '2'); 	
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '3'); 	
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '4'); 	
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '5'); 	
		CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '6'); 	
		
		SET @A = '10';
		UPDATE `opng_vat_e` v
		SET
			v.OperCount = (SELECT COUNT(*) FROM `t_oppo_WZ_do_Paragonu` WHERE IdnVat = v.IdVat)
		WHERE
			v.IdnOper = _IdnOper
		;
		IF @import.RAFI.one.rec._FULL_ALG THEN
		--	POST
			SET @A = '11';
			CALL opng_E_Let('Post', _IdnOper, '', '');
		ELSE
		-- 	ZAMIAST POST	
			CALL ng_vat_e_TO_ng_e('', 'OP', _IdnOper);
			CALL _ng_E_LetPost('ng.to.po', 'OP', _IdnOper, '', '');
			CALL _ng_E_LetPost('po.to.ng', 'OP', _IdnOper, '', '');
		END IF;
		
		
		IF NOT @import.RAFI.one.rec._Nie_Zapisuj THEN
			SET @A = '12';
			CALL opng_E_Let('ApplyAndClear', _IdnOper, '', '1');		--	 Wraz z numeracja
			SET @A = '12.a';
		--	Ustaw pozycje WZ-ek
		
			IF @import.RAFI.one.rec._FULL_ALG THEN
					SET @A = '13';
					SET @S = 'UPDATE `oppo` p, `t_oppo_WZ_do_Paragonu` tp';
				UPDATE `oppo` p, `t_oppo_WZ_do_Paragonu` tp
				SET
					p.IdnWZ = _IdnOper,
					p.IdnOperFin = _IdnOper
				WHERE
					p.GUID = tp.GUID
				;
			--	Ustaw fvrudowz
			
				UPDATE	`opng` n
				SET
					n.fvrudowz = 1
				WHERE
					n.GUID = _IdnOper
				;
			END IF;
		END IF;
		
		-- DROP TEMPORARY TABLE IF EXISTS `t_oppo_WZ_do_Paragonu`;
		DROP TEMPORARY TABLE IF EXISTS `t_opng_WZ_do_Paragonu`;
		
	--	13.	ustawiam status na 'F' czyli zakonczono 
		CALL infoPiek_par_import_RAFI('Set.Status', _RAFI_HEX, 'F'); 	-- 'F' czyli zakonczono 
	END;
	END IF;		--	_MODE = 'import.RAFI.one.rec'

	IF _MODE = 'insert.opng_vat_e' THEN
		/* *******************************************************************************
		Wstawianie do `opng_vat_e`
			_RAFI_HEX VARCHAR(50),	
			_Param_A = 1 2 3 .. 6  - doklejka do kolumn np. RAFI_NN1 RAFI_NN2 ... itd 
			CALL infoPiek_par_import_RAFI('insert.opng_vat_e', _RAFI_HEX, '1'); 	-- 'F' czyli zakonczono 
		*********************************************************************************/	
		
		SET _SQLText = 
			'
			INSERT INTO `opng_vat_e`
			(IdnOper, IdVat, Netto, Vat, Brutto, NettoWal, VatWal, BruttoWal, FIXED)
			SELECT
				dn.INT_GUID, s.IdnVat, RAFI_NN#N#, RAFI_VN#N#, RAFI_BB#N#, RAFI_NN#N#, RAFI_VN#N#, RAFI_BB#N#, 1
			FROM `infpie_dok_ng_dobowe` dn 
			LEFT JOIN `infpie_stawki` s ON s.VAT_CHAR = dn.RAFI_VC#N#
			-- LEFT JOIN `v_erp_vat` v ON v.ID = s.IdnVat
			WHERE
				dn.RAFI_HEX = #RAFI_HEX#
			;
			'
		;	-- wstawiam zawsze z FIXED na 1
		SET _SQLText = REPLACE(_SQLText, '#N#', _Param_A);
		SET _SQLText = REPLACE(_SQLText, '#RAFI_HEX#', _RAFI_HEX);
		SET @_SQLTextVat = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
	END IF;		--	_MODE = 'insert.opng_vat_e'
	
END$$


-- DROP USER pos $$
-- CREATE USER pos IDENTIFIED BY 'pos98sql' $$
GRANT SELECT ON TowrNg TO pos $$
GRANT SELECT ON cennik TO pos $$
GRANT SELECT ON Jednostki TO pos $$
GRANT SELECT ON katcols TO pos $$
GRANT ALL ON infpie_dok_ng TO pos $$
GRANT ALL ON infpie_dok_po TO pos $$
GRANT ALL ON infpiek_int_ng TO pos $$
GRANT ALL ON infpiek_int_po TO pos $$
GRANT ALL ON infpie_dok_ng_dobowe TO pos $$
GRANT ALL ON infpie_dok_kasowe TO pos $$

GRANT EXECUTE ON PROCEDURE _WELT_GET_GRUPY_ART TO pos $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_ARTYKULY TO pos $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_USERS TO pos $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_Sklepy TO pos $$

GRANT EXECUTE ON PROCEDURE _WELT_GET_GRUPY_ART TO pos@'%' $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_ARTYKULY TO pos@'%' $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_USERS TO pos@'%' $$
GRANT EXECUTE ON PROCEDURE _WELT_GET_Sklepy TO pos@'%' $$

GRANT ALL ON `infpie_rcp` TO pos@'%' $$

DELIMITER ;

/*
====================================================================================================================================================================================
	NOTArdIK
====================================================================================================================================================================================
`reserved_ID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT '"" nie zajety lub numer sesji ktora przetwarza rekord',


DROP TABLE `infpie_rcp`;
CREATE TABLE `infpie_rcp` (
  `rpcp_hex` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'identyf. rcp',
  `rpcp_typ` INT(11) NOT NULL DEFAULT 1 COMMENT 'wartosci 1 = przyjscie do pracy 2= wyjscie z pracy 3= wyjscie na przerwe 4= powrot z przerwy',
  `rpcp_dat` DATETIME NOT NULL DEFAULT '0000-00-00 00:00' COMMENT 'Datetime data i czas zdarzenia',
  `rpcp_idc` INTEGER NOT NULL DEFAULT 0 COMMENT 'numer karty',
  `rpcp_key` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'c(50,0) zastepczy numer karty jako string',
  `rpcp_reader` VARCHAR(30) NOT NULL DEFAULT '' COMMENT 'NUMER  cZYTNIKA',
  `Create_At` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data,czas kreowania',
  `Modify_At` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Data,czas modyfikacji',
  `INT_Status` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'Status dokumentu "" domyslnie, "T" czasowy (przetwarzanie, "F" przetworzony/zaimportowany',
  `INT_ID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'MD5(Numer karty + czas)',
  `attempt` INT(11) DEFAULT '0' COMMENT 'Ilosc prob',
  `reserved_ID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT '"" nie zajety lub numer sesji ktora przetwarza rekord',
  PRIMARY KEY (`rpcp_hex`),
  UNIQUE KEY `INT_ID` (`INT_ID`),
  KEY `INT_Status` (`INT_Status`)
)COMMENT='rejestr we/wy osob'
;

ALTER TABLE `zoo`.`infpie_dok_ng`   
  ADD COLUMN `attempt` INT(11) DEFAULT 0  NULL   COMMENT 'Ilosc prob' AFTER `INT_GUID`,
  ADD COLUMN `reserved_ID` VARCHAR(38) DEFAULT ''  NOT NULL   COMMENT '\"\" nie zajety lub numer sesji ktora przetwarza rekord' AFTER `attempt`
  ;
ALTER TABLE `zoo`.`infpie_dok_ng`   
  ADD COLUMN `INT_Create` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'data i czas powstania rekordu' AFTER IDOK_TIM
  ;

*/
