DELIMITER $$

DROP PROCEDURE IF EXISTS `pr_kr_Wizard`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `pr_kr_Wizard`(
	IN _MODE VARCHAR(50),
	IN _Check_GUID VARCHAR(100),
	IN _Check_Value INT,
	IN _Param_A VARCHAR(50),	-- np. _krng_GUID, _DataOd
	IN _Param_B VARCHAR(50),	-- np. _DataDo
	IN _Param_C VARCHAR(50),	-- np. _OsobaGUID	
	IN _Param_D VARCHAR(50)	-- np. NOT Show?
	)
	READS SQL DATA
SPROC: BEGIN
/*
	CALL pr_kr_Wizard('INIT', @Case_GUID, 0, '', '', '', '');
	CALL pr_kr_Wizard('DZIALY', @Case_GUID, 1, '', '', '', '');
	-- CALL pr_kr_Wizard(2, @Case_GUID, 0, '', '', '', '');
	CALL pr_kr_Wizard('INFO', @Case_GUID, 0, '', '', '', '');

	SEt @ID = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}IdCK0';  -- CK
	CALL pr_kr_Wizard('CHECK_KARTY', @ID, 1, '', '', '', '');
	SEt @ID = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}IdCA0'; -- CA
	CALL pr_kr_Wizard('CHECK_KARTY', @ID, 1, '', '', '', '');

	_MODE:
	
	0, 
	'INIT':	
		Kreowanie tabel tymczasowych (Start) oraz  SELECT zleceń z okresu Od - Do  (z polem check)  lub dla Zlecenia z parametru _Check_GUID o ile _Check_GUID <> ''
		Parametry
			_Param_A (_DataOd), _Param_B (_DataDo) 
			LUB 
			_Check_GUID
		CALL pr_kr_Wizard('INIT', @Case_GUID, 0, '', '', '', '');
		LUB
		CALL pr_kr_Wizard('INIT', '', 0, '2009-08-01', '2009-09-01', '', '');
	
	1, 
	'CHECK_ZLEC':	
		Wstawianie zleceń zaznaczonych (Insert jeden rekord n-razy)
		Parametry
			_Check_GUID, 		zlecenie
			_Check_Value		0/1	
		CALL pr_kr_Wizard('INFO', _Check_GUID, _Check_Value, '', '', '', '');	
		
	2, 
	'DZIALY':	
		SELECT wydzialow z top-ow/gniaz/bez KaPr dla zlecen wybranych (z polem check)  - gdy pusty select to oznacza, ze wszystkie karty juz istnieja
		Parametry
			_Check_Value 		0/1 czyli zwraca wszystkie zaznaczone lub nie
		CALL pr_kr_Wizard('DZIALY', '', 0, '', '', '', '');  zwraca wszystkie NIE zaznaczone
		CALL pr_kr_Wizard('DZIALY', '', 1, '', '', '', '');  zwraca wszystkie zaznaczone
	
	3, 
	'CHECK_DZIALY':	
		Wstawianie wydzialow zaznaczonych (Insert jeden rekord n-razy)
		Parametry
			_Check_GUID, 		wydzial
			_Check_Value		0/1	
		CALL pr_kr_Wizard('CHECK_DZIALY', _Check_GUID, _Check_Value, '', '', '', '');	
		
	4, 
	'INFO':
		Przygotowanie kart (usuwam rekordy dla wydzialow niewybranych na koniec SELECT sumaryczny
		Parametry
			BRAK
		CALL pr_kr_Wizard('INFO', '', 0, '', '', '', '');
		
	5, 
	'CHECK_KARTY':
		Wstawianie Kart zaznaczonych (Insert jeden rekord n-razy)
		Parametry
			_Check_GUID, 		Klucz z pola ID dataset-a otrzymanego z CALL pr_kr_Wizard('INFO', ...)
			_Check_Value		0/1	
			_Param_A			(NIEWYMAGANY)	jako _krng_GUID - UWAGA mozemy dac pusty bo i tak wykonamy NewGUID()
		CALL pr_kr_Wizard('CHECK_KARTY', ID, _Check_Value, '', '', '', '');
			
	6, 
	'CREATE':
		Kreowanie kart rozliczen
		Parametry
			BRAK
			_Param_C			(NIEWYMAGANY)	GUID osoby, gdy _Param_C = '' wykorzystamy @session.CurrOsobaGUID
		CALL pr_kr_Wizard('CREATE', '', 0, '', '', '', '');	
			
	7, 
	'CLEAR':
		Sprzatanie
		Parametry
			BRAK
		CALL pr_kr_Wizard('CLEAR', '', 0, '', '', '', '');	
	
	
	'ROZLICZ_krpo_INIT'
		Przygotowuje rekord (rekordy) do rozliczania +/-
		Parametry
			Parametry takie jak przy FIND
			_Check_GUID, 		GUID lub IDN karty/pozycji
			_Param_A 		'krng' - szukam po krng, 'krpo' szukam po krpo, '*' szukam po krng gdy _GUID like 'KRZ-' lub po krpo 
			_Param_B 		'IDN' - szukam po IDN, 'GUID' szukam po GUID
			_Param_C 		'+' - zmiana puli, '-' - rozliczanie
			_Param_D			'Ng' - dotyczy naglowka, 'Po' - dotyczy pozycji (1 lub wielu, a  to zalezy od tego czy _KrPoIDN <> 0)				
				
	'ROZLICZ_krpo_APPLY'
		Zapisuje rekord (rekordy) do rozliczania +/- i przelicza
		Parametry
			_Param_C			(NIEWYMAGANY)	GUID osoby, gdy _Param_C = '' wykorzystamy @session.CurrOsobaGUID
				
	_Check_Value:
	0:	niezaznaczony
	1:	zaznaczony	
*/
	DECLARE _Case_GUID VARCHAR(38);
	DECLARE _Area_GUID VARCHAR(38);
	DECLARE _Area_Symbol VARCHAR(58);
	DECLARE _Workgroup_GUID VARCHAR(38);
	DECLARE _PodZlec_GUID VARCHAR(38); 
	DECLARE _Div_GUID VARCHAR(38);
	DECLARE _Div_Symbol VARCHAR(50);
	DECLARE _S1 VARCHAR(50);
	DECLARE _S2 VARCHAR(50);
	DECLARE _NrWewn VARCHAR(38);
	DECLARE _DataOd DATE;
	DECLARE _DataDo DATE;
	DECLARE _krng_GUID VARCHAR(38);
	DECLARE _OsobaGUID VARCHAR(38);
--	DECLARE _krpo_GUID VARCHAR(38);
	DECLARE _IsOBUN INT;

	DECLARE _NewGUID VARCHAR(38);
	DECLARE _KrNgGUID VARCHAR(38) DEFAULT _Check_GUID;
	DECLARE _KrPoGUID VARCHAR(38) DEFAULT _Check_GUID;
	DECLARE _KrNgIDN INT DEFAULT _Check_GUID;
	DECLARE _KrPoIDN INT DEFAULT _Check_GUID;
	
	DECLARE _LogType VARCHAR(20) DEFAULT '';
	DECLARE _RozliczOneRec INT DEFAULT 1;
	
	SET _Check_GUID = IFNULL(_Check_GUID, '');
	SET _krng_GUID = IF(IFNULL(_Param_A, '') = '', NewGUID(), _Param_A);
	SET _DataDo = IFNULL(_Param_B, CURRENT_DATE());
	SET _DataOd = IFNULL(_Param_A, DATE_ADD(_DataDo, INTERVAL -1 MONTH));
	
	IF (_MODE = 'INIT') OR (_MODE = '0') THEN
--	Kreowanie tabel tymczasowych (Start) oraz  SELECT zleceń z okresu Od - Do  (z polem check) 
	--	Tymczasowki
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_podzlec1`;
		IF _Check_GUID = '' THEN
			CREATE TEMPORARY TABLE `t_hurt_podzlec1`
				SELECT
					z.GUID,
					NAME_CONST('Checked', '1'),		--	Domyslnie Zaznaczony
					z.`nrwewn` AS `NrWewn`,
					SUBSTR(IF(z.`Temat` != '', z.`Temat`, `cr`.`nazwa`), 1, 250) AS `Temat`,
					_VarStr(z.StartTime) AS StartTime,
					_VarStr(IF(z.`Status` = 7, z.DeadLine, 'Otwarte')) AS CloseTime,
					z.Opis,
					z.`case_guid` AS `Case_GUID`
				FROM crm_commisions z
				LEFT JOIN `crm_rodzaje` `cr` ON `cr`.`rodzaj` = `z`.`rodzaj` AND `cr`.`podrodzaj` = `z`.`podrodzaj`
				WHERE
					(z.`rodzaj` = 12 AND z.`podrodzaj` = 1) AND
					z.StartTime < _DataDo AND z.DeadLine > _DataOd
				-- GROUP BY `C`.`GUID`
			;
		ELSE
			CREATE TEMPORARY TABLE `t_hurt_podzlec1`
				SELECT
					z.GUID,
					NAME_CONST('Checked', '1'),		--	Domyslnie Zaznaczony
					z.`nrwewn` AS `NrWewn`,
					SUBSTR(IF(z.`Temat` != '', z.`Temat`, `cr`.`nazwa`), 1, 250) AS `Temat`,
					_VarStr(z.StartTime) AS StartTime,
					_VarStr(IF(z.`Status` = 7, z.DeadLine, 'Otwarte')) AS CloseTime,
					z.Opis,
					z.`case_guid` AS `Case_GUID`
				FROM crm_commisions z
				LEFT JOIN `crm_rodzaje` `cr` ON `cr`.`rodzaj` = `z`.`rodzaj` AND `cr`.`podrodzaj` = `z`.`podrodzaj`
				WHERE
					z.GUID = _Check_GUID
				;
		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_top`;
		CREATE TEMPORARY TABLE `t_hurt_top`
			SELECT
				z.GUID AS Case_GUID,
				tob.Def_Obj,
				tob.Ilosc_Seria,
				tob.nr_zmiany AS tob_nr_zmiany,
				tob.Asortyment,
				tob.status_top,
				tob.Marszruta,
				((_VarStr_NotNull(top.pr_krpo_GUID) = '') AND (_VarStr_NotNull(top.commision_guid) = '')) AS IsValid, 
				IF(tob.Def_Obj = -4, 0, tob.status_top != 1) AS IsLock,
				top.*
			FROM `t_hurt_podzlec1` z
			INNER JOIN pr_tob tob ON `tob`.`Case_GUID` = `z`.`GUID` -- AND IF(_IsOBUN != 0, `tob`.`Def_Obj` = -4, `tob`.`Def_Obj` != -4)
			-- `tob`.`Def_Obj` = -4
			INNER JOIN `zmpo` top ON top.TobGUID = `tob`.`GUID` -- AND (IFNULL(top.pr_krpo_GUID, '') = '')
		;

		DROP TEMPORARY TABLE IF EXISTS `t_hurt_podzlec`;
		CREATE TEMPORARY TABLE `t_hurt_podzlec`
			SELECT
				z.*, _VarINT(COUNT(*)) AS IleOp
			FROM `t_hurt_podzlec1` z
			INNER JOIN `t_hurt_top` top ON top.Case_GUID = `z`.`GUID` AND top.IsValid
			GROUP BY `z`.`GUID`
		;
	--	SELECT gotowej tabeli (do zaznaczenia)	
		IF _Param_D = '' THEN
			SELECT
				z.*
			FROM `t_hurt_podzlec` z
			ORDER BY z.`NrWewn`
			;
		END IF;
	END IF;	-- (_MODE = 0) OR (_MODE = 'INIT')
	
	IF (_MODE = 1) OR (_MODE = 'CHECK_ZLEC') THEN
--	Wstawianie zleceń zaznaczonych (Insert jeden rekord n-razy)
		UPDATE `t_hurt_podzlec` z
			SET Checked = _Check_Value
		WHERE
			z.GUID = _Check_GUID
		;
	END IF;	-- (_MODE = 1) OR (_MODE = 'CHECK_ZLEC')
	
	IF (_MODE = 'DZIALY') OR (_MODE = 2) THEN
--	SELECT wydzialow z top-ow/gniaz/bez KaPr dla zlecen wybranych (z polem check)  - gdy pusty select to oznacza, ze wszystkie karty juz istnieja
	--	Przygotuj zestaw gniaz dla wybranych zlecen (checked) i IS_OBUN dla ktorych nie ma jeszcze kart pracy 
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_gniazda_dla_zazn_zlecen`;
		CREATE TEMPORARY TABLE `t_hurt_gniazda_dla_zazn_zlecen`
			SELECT
				z.GUID AS Case_GUID,
				top.AreaGUID, 
				n.Dzial,
				NAME_CONST('Checked', '0')		--	wydzial tego gniazda zaznaczono? Domyslnie NIEzaznaczony
			FROM `t_hurt_podzlec` z	
			INNER JOIN `t_hurt_top` top ON top.`Case_GUID` = `z`.`GUID` AND top.IsValid
			INNER JOIN erp_area_nodes n ON n.GUID = top.AreaGUID
			WHERE 
				z.Checked != 0 AND 
				IFNULL(top.AreaGUID, '') != ''
			GROUP BY top.AreaGUID
		;
	--	Selekcja gniazd z opisem operacji na gniazdach	
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_Gniazda_z_TOP`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_hurt_Gniazda_z_TOP`
			SELECT
				d.GUID AS Wydzial_GUID,
				d.Symbol AS Wydzial,
				d.Nazwa AS WydzialNazwa,
				top.AreaGUID AS AreaGUID,
				n.Symbol AS Gniazdo,
				GROUP_CONCAT(DISTINCT top.towrsymb ORDER BY top.towrsymb SEPARATOR '-') AS Operacje,
				COUNT(DISTINCT top.GUID) AS Ile_Op,
				SUM(top.IsValid) AS Ile_Op_BezKart,
				-- bylo SUM(_VarStr_NotNull(top.pr_krpo_GUID) = '') AS Ile_Op_BezKart,
				SUM(IF(top.IsValid AND IsLock, 1, 0)) AS Ile_Op_BezKart_StatusLock,
				-- bylo SUM(IF(_VarStr_NotNull(top.pr_krpo_GUID) = '' AND top.status_top != 1, 1, 0)) AS Ile_Op_BezKart_StatusLock,
				SUM(NOT top.IsValid) AS Ile_Op_ZKart
				-- bylo SUM(_VarStr_NotNull(top.pr_krpo_GUID) != '') AS Ile_Op_ZKart
			FROM t_hurt_gniazda_dla_zazn_zlecen g
			INNER JOIN `t_hurt_top` top ON top.AreaGUID = g.AreaGUID AND top.`Case_GUID` = g.Case_GUID
			INNER JOIN erp_area_nodes n ON n.GUID = g.AreaGUID
			INNER JOIN erp_division_schema d ON d.GUID = n.Dzial
			GROUP BY n.GUID
			ORDER BY Gniazdo
		;
			
	--	Przygotuj zestaw wydzialow
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_wydzialy_gniaz_bez_kart`;
		CREATE TEMPORARY TABLE `t_hurt_wydzialy_gniaz_bez_kart`
		    SELECT
				g.Wydzial_GUID AS GUID,
				-- NAME_CONST('Checked', '0'),		--	Domyslnie NIEzaznaczony/Zaznaczony?
				_VarINT(_Check_Value) AS Checked,		--	Domyslnie NIEzaznaczony/Zaznaczony?
				g.Wydzial_GUID AS Wydzial_GUID,
				g.Wydzial AS Wydzial,
				g.WydzialNazwa AS WydzialNazwa,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_BezKart > 0,g.Gniazdo, NULL) ORDER BY g.Gniazdo SEPARATOR '-'), '') AS Gniazda,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_ZKart > 0,g.Gniazdo, NULL) ORDER BY g.Gniazdo SEPARATOR '-'), '') AS GniazdaKarty,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_BezKart_StatusLock > 0, g.Gniazdo, NULL) ORDER BY g.Gniazdo SEPARATOR '-'), '') AS GniazdaStatusLock,
				COUNT(DISTINCT g.Gniazdo) AS Ile_Gniazd,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_BezKart > 0,g.Operacje, NULL) ORDER BY g.Operacje SEPARATOR '-'), '') AS Operacje,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_ZKart > 0,g.Operacje, NULL) ORDER BY g.Operacje SEPARATOR '-'), '') AS OperacjeKarty,
				IFNULL(GROUP_CONCAT(DISTINCT IF(Ile_Op_BezKart_StatusLock > 0,g.Operacje, NULL) ORDER BY g.Operacje SEPARATOR '-'), '') AS OperacjeStatusLock,
				SUM(g.Ile_Op) AS Ile_Op,
				SUM(g.Ile_Op_BezKart) AS Ile_Op_BezKart,
				SUM(g.Ile_Op_ZKart) AS Ile_Op_ZKart,
				SUM(g.Ile_Op_BezKart_StatusLock) AS Ile_Op_BezKart_StatusLock
			FROM `t_hurt_Gniazda_z_TOP` g
			GROUP BY GUID
			HAVING Ile_Op_BezKart > 0 OR TRUE
			ORDER BY g.Wydzial
			;
			
	--	SELECT	wydzialow	
		IF _Param_D = '' THEN
			SELECT 
				d.*, _VarINT(((d.Ile_Op - d.Ile_Op_BezKart_StatusLock) <= 0)) AS IsDisabled  
			FROM `t_hurt_wydzialy_gniaz_bez_kart` d
			ORDER BY Wydzial -- d.Symbol
			;
		END IF;
	END IF;	-- (_MODE = 2) OR (_MODE = 'DZIALY')
	
	IF (_MODE = 3) OR (_MODE = 'CHECK_DZIALY') THEN
--	Wstawianie wydzialow zaznaczonych (Insert jeden rekord n-razy)
		UPDATE `t_hurt_wydzialy_gniaz_bez_kart` d
			SET Checked = _Check_Value
		WHERE
			d.GUID = _Check_GUID
		;
		UPDATE `t_hurt_gniazda_dla_zazn_zlecen` g
			SET g.Checked = (SELECT d.Checked FROM `t_hurt_wydzialy_gniaz_bez_kart` d WHERE g.Dzial = d.GUID )
		WHERE g.Dzial = _Check_GUID	
		;
	END IF;	-- (_MODE = 3) OR (_MODE = 'CHECK_DZIALY')
	
	IF (_MODE = 4) OR (_MODE = 'INFO') THEN
--	Przygotowanie kart (usuwam rekordy dla wydzialow niewybranych na koniec SELECT sumaryczny
	--	Przygotuj liste gniaz - checked z wydzialow odznacz w gniazdach tych wydzialow (te niezaznaczone beda ignorowane)
		UPDATE `t_hurt_gniazda_dla_zazn_zlecen` g
			SET g.Checked = (SELECT d.Checked FROM `t_hurt_wydzialy_gniaz_bez_kart` d WHERE g.Dzial = d.GUID)
		;
	--	Kreuj `temp_karty_pracy` ale nie wypelniaj w CALL	
		--	kiedys bylo CALL pr_KartyPracy_CreateTemp_karty_pracy('');
		DROP TEMPORARY TABLE IF EXISTS `temp_karty_pracy`;
		CREATE TEMPORARY TABLE `temp_karty_pracy`(
			`GUID` VARCHAR(38) NOT NULL DEFAULT '',		-- Klucz glowny z tabeli zmpo
			`Ilosc` DOUBLE (16,4) DEFAULT 0,			-- Ilosc z zmpo
			`Ilosc_Seria` DOUBLE (16,4) DEFAULT 0,		-- Ilosc_Seria z tob
			`pr_ilosc_seria` DOUBLE (16,4) DEFAULT 0,	-- pr_ilosc_seria z zmpo
			`cenanet` DOUBLE (16,4) DEFAULT 0,			-- cenanet z zmpo
			`wartnet` DOUBLE (16,4) DEFAULT 0,			-- wartnet z zmpo
			`rcpoGUID` VARCHAR(38) DEFAULT NULL,		-- Pole do listy operacji, stawek etc.
			`pr_krng_GUID` VARCHAR(38) DEFAULT NULL,	-- Pole karty rozliczen
			`pr_krpo_GUID` VARCHAR(38) DEFAULT NULL,	-- Pole do sprawdzenia czy juz podpieta jest karta rozliczen
			`tobGUID` VARCHAR(38) DEFAULT NULL,
			`case_GUID` VARCHAR(38) DEFAULT NULL,
			`SymbAsortyment` VARCHAR(50) DEFAULT '',	-- Symbol asortymentu
			`SymbZmpo` VARCHAR(38) DEFAULT '',			-- Symbol z pozycji zamowien
			`Symbol` VARCHAR(150) DEFAULT '',			-- Symbol polaczenie symbolu z zamowien z symbolm asortymentu
			`Res_type` VARCHAR(20) DEFAULT '',			-- Typ zasobu
			`areaGUID` VARCHAR(38) DEFAULT NULL,
			`dzial` VARCHAR(38) DEFAULT NULL,
			`wydzial` VARCHAR(38) DEFAULT NULL,
			`Symboldzialu` VARCHAR(150) DEFAULT NULL,
			`SymbolMiejsca` VARCHAR(150) DEFAULT NULL,
			`Asortyment` VARCHAR(38) DEFAULT NULL,
			`status_top` INT DEFAULT 0,
			`EnabledAsortyment` INT DEFAULT 0,
			`IsOBUN` INT DEFAULT 0,
			`extra_nr_karty` VARCHAR(50) DEFAULT NULL,
			`Nr_Zlec` VARCHAR(100) DEFAULT NULL,
			`Marszruta` VARCHAR(255) DEFAULT NULL,
			PRIMARY KEY (`GUID`),
			KEY `case_GUID` (`case_GUID`)
		);
	
	--	Uzupelnij `temp_karty_pracy` 	
		INSERT INTO `temp_karty_pracy`
		SELECT
			top.GUID,
			top.ilosc,
			top.Ilosc_Seria,
			top.pr_ilosc_seria,
			top.cenanet,
			top.wartnet,
			top.rcpoGUID,
			top.pr_krpo_GUID,								-- na razie jako pr_krng_GUID 
			top.pr_krpo_GUID,
			top.tobGUID,
			top.case_GUID,
			a.symbol AS symbAsortyment,
			top.towrsymb AS symbZmpo,
			CONCAT(IFNULL(top.towrsymb, ''), ' ', IFNULL(a.symbol, '')) AS symbol,
			top.Res_type,
			top.areaGUID,
			n.dzial,
			vd1.GUID_wydzialu,
			d.symbol AS Symboldzialu,
			n.symbol AS SymbolMiejsca,
			top.Asortyment,
			top.status,		--	top.status_top,
			_VarINT(0),
			_VarINT(IF(top.Def_Obj = -4, 1, 0)),
			_VarSTR(IF(top.Def_Obj = -4, top.tob_nr_zmiany, '')),
			z.NrWewn,
			top.Marszruta
		FROM `t_hurt_podzlec` z	
		INNER JOIN `t_hurt_top` top ON top.`Case_GUID` = `z`.`GUID` AND top.IsValid AND top.IsLock = 0
		INNER JOIN `t_hurt_gniazda_dla_zazn_zlecen` g ON g.AreaGUID = top.areaGUID AND g.Checked != 0 	
		LEFT JOIN `erp_asort_types` a ON a.guid = top.Asortyment
		LEFT JOIN `erp_area_nodes` n ON n.guid = top.areaGUID
		LEFT JOIN v_pr_division vd1 on vd1.GUID = n.dzial
		LEFT JOIN `erp_division_schema` d ON d.guid = vd1.GUID_Wydzialu
		WHERE
			z.Checked != 0 -- AND 
		--	(top.status_top = 1 OR top.Def_Obj = -4) AND
		-- 	(top.Status = 1 OR top.Def_Obj = -4)
		GROUP BY top.GUID	
		;
		UPDATE `temp_karty_pracy` tkp, `rcpo` r
		SET
			tkp.cenanet = r.cena_kalulacyjna,
			tkp.wartnet = r.cena_kalulacyjna * tkp.ilosc
		WHERE
			tkp.rcpoGUID = r.GUID
		;
		
	--	SELECT	zagregowanych kart	
		SELECT DISTINCT
			kp.`Nr_Zlec` As NrPodzelc, z.`Temat`,
			-- kp.Symbol,
			kp.Symboldzialu As Wydzial,
			kp.SymbolMiejsca As Miejsce,
			_varDOUBLE(ROUND(SUM(kp.Ilosc),2)) AS Pula_Karty,
			_varDOUBLE(ROUND(SUM(kp.wartnet),2)) AS Wartosc_Karty,
			kp.IsOBUN,
			_varINT(COUNT(*)) AS IleOperacji,
			GROUP_CONCAT(kp.symbZmpo, '') As Operacje,
			kp.areaGUID,
			kp.pr_krng_GUID,
			kp.pr_krpo_GUID,
			kp.extra_nr_karty,
			NAME_CONST('Checked', '1'),
			-- Bylo _VarStr(CONCAT(kp.case_GUID, kp.`areaGUID`, `IsOBUN`)) As ID
			_VarStr(CONCAT(kp.case_GUID, kp.`areaGUID`)) AS ID
		FROM `temp_karty_pracy` kp
		LEFT JOIN `t_hurt_podzlec` z ON z.GUID = kp.case_GUID	
		WHERE
			IFNULL(kp.pr_krpo_GUID, '') = '' AND
			kp.Res_type = 'W'
			# AND kp.EnabledAsortyment
		GROUP BY kp.`case_GUID`, kp.`areaGUID`	-- NIE!!!!, kp.`IsOBUN`
		ORDER BY NrPodzelc, Wydzial, Miejsce
		;
	END IF;	-- (_MODE = 4) OR (_MODE = 'INFO')
	
	IF (_MODE = 5) OR (_MODE = 'CHECK_KARTY') THEN
--	Wstawianie Kart zaznaczonych (Insert jeden rekord n-razy)
	--	_krng_GUID gdy pusty to wstaw wlasny GUID
	--	wstaw przyszle GUIDy Kapr do tabeli `temp_karty_pracy` wedle agregatu karty czyli case_GUID, areaGUID, IsOBUN
		UPDATE `temp_karty_pracy` kp
		SET 
			kp.pr_krng_GUID = IF(_Check_Value != 0, _krng_GUID, '')
		WHERE
			-- Bylo CONCAT(kp.case_GUID, kp.`areaGUID`, `IsOBUN`) = _Check_GUID
			CONCAT(kp.case_GUID, kp.`areaGUID`) = _Check_GUID
		;
		UPDATE `temp_karty_pracy` kp
		SET 
			-- Bylo kp.pr_krpo_GUID = IF(_Check_Value != 0, Md5(CONCAT(_krng_GUID, kp.case_GUID, kp.`areaGUID`, kp.`TobGUID`, `IsOBUN`)), '')
			kp.pr_krpo_GUID = IF(_Check_Value != 0, Md5(CONCAT(_krng_GUID, kp.case_GUID, kp.`areaGUID`, kp.`TobGUID`)), '')
		WHERE
			-- Bylo CONCAT(kp.case_GUID, kp.`areaGUID`, `IsOBUN`) = _Check_GUID
			CONCAT(kp.case_GUID, kp.`areaGUID`) = _Check_GUID
		;
		
	END IF;	-- (_MODE = 5) OR (_MODE = 'CHECK_KARTY')
	
	IF (_MODE = 6) OR (_MODE = 'CREATE') THEN
--	Kreowanie kart
	-- 	Wstaw do zmpo GUIDy kart (do pola `pr_krpo_GUID`)	UWAGA tylko niepuste GUIDY do topow majacych puste pole `pr_krpo_GUID`
		/* NA RAZIE
		UPDATE `zmpo` z, `temp_karty_pracy` tkp, `rcpo` r
		SET
			z.pr_krpo_GUID = tkp.pr_krpo_GUID,
			z.cenanet = r.cena_kalulacyjna,
			z.wartnet = r.cena_kalulacyjna * z.ilosc
		WHERE
			tkp.GUID = z.GUID AND	
			IFNULL(tkp.pr_krpo_GUID, '') != '' AND	
			IFNULL(z.pr_krpo_GUID, '') = '' AND
			z.rcpoGUID = r.GUID
		;
		*/
		-- ODBLOKOWUJE	LEAVE SPROC;	-- Na razie (23-09-2009) w Mostostalu nie kreujemy do 5-10-2009
		
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_KaPr`;
		CREATE TEMPORARY TABLE `t_hurt_KaPr`
			SELECT 
				_VarINT(0) AS `IsCreated`, 
				kp.`pr_krng_GUID`, 
				-- kp.`pr_krpo_GUID`, 
				kp.`Case_GUID`, kp.`areaGUID`, kp.`IsOBUN`, 
				_ConcatSTR(kp.`Nr_Zlec`, _ConcatSTR(kp.SymbolMiejsca, IF(kp.`IsOBUN` != 0, 'OBUN', ''), ' - '), ' - ') As NrWewn,
				d.GUID_Wydzialu AS Div_GUID,
				d.Symbol AS Div_Symbol,
				n.Symbol AS Area_Symbol
			FROM `temp_karty_pracy` kp
			LEFT JOIN `erp_area_nodes` n ON n.GUID = kp.`AreaGUID`
			LEFT JOIN `v_pr_division` d ON d.GUID = n.Dzial
			WHERE 
				IFNULL(kp.`pr_krng_GUID`, '') != ''
			GROUP BY kp.`pr_krng_GUID`	
		;
		
	--	Petla z GUID-ami KaPr - w petli dla kazdego GUIDa wolamy kreowanie czyli CALL pr_kr_Wizard(100, ...
		BEGIN
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE _LOCAL_krng_GUID VARCHAR(38);
			DECLARE c_proc CURSOR FOR
				SELECT 
					kp.`pr_krng_GUID`
				FROM `t_hurt_KaPr` kp
				;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			OPEN c_proc;
			loop1: LOOP
				FETCH c_proc INTO _LOCAL_krng_GUID;
				IF done THEN
					LEAVE loop1;
				END IF;
				CALL pr_kr_Wizard('CREATE_ONE', '', 0, _LOCAL_krng_GUID, '', _Param_C, '');
			END LOOP;
			CLOSE c_proc;
		END;
		
	END IF;	-- (_MODE = 6) OR (_MODE = 'CREATE')
	
	IF (_MODE = 100) OR (_MODE = 'CREATE_ONE') THEN
--	Atomiczne Kreowanie karty
	--	Ustaw zmienne		
	--	Ustaw _Case_GUID, _Area_GUID, _IsOBUN, _NrWewn, _Div_GUID 
			LEAVE SPROC;	-- Na razie (23-09-2009) w Mostostalu nie kreujemy do 5-10-2009
	
		SELECT
			`Case_GUID`, `areaGUID`, `IsOBUN`, `NrWewn`, `Div_GUID`, `Div_Symbol`, `Area_Symbol` 
		INTO
			_Case_GUID, _Area_GUID, _IsOBUN, _NrWewn, _Div_GUID, _Div_Symbol, _Area_Symbol 
		FROM `t_hurt_KaPr` tkp
		WHERE
			pr_krng_GUID = _krng_GUID
		LIMIT 1
		;
		SET _Div_Symbol = IFNULL(_Div_Symbol, '');
		SET _Area_Symbol = IFNULL(_Area_Symbol, ''); 
	--	Ustaw _Workgroup_GUID
		SELECT
			GUID 
		INTO
			_Workgroup_GUID 
		FROM `erp_workgroups` wg
		WHERE
			wg.areaGUID = _Area_GUID
		LIMIT 1
		;
		SET _Workgroup_GUID = IFNULL(_Workgroup_GUID, '');
		
	--	Kreuj zdarzenie karta rozliczen oraz uzupelnij gniazdo w KaPr			
		INSERT INTO `pr_krng`
			(GUID, PodzlecGUID, AreaGUID, WorkgroupGUID, Opis)
			VALUES
			(_krng_GUID, _Case_GUID, _Area_GUID, _Workgroup_GUID, CONCAT('Karta rozliczeń: ', _NrWewn, ' GN: ', _Area_Symbol))
		;
		UPDATE `pr_krng`
		SET
			NrWewn = CONCAT('KRZ-', IDN),
			DataWyst = aLocalTime
		WHERE
			GUID = _krng_GUID
		;
-- INNER JOIN `t_hurt_top` top ON top.`Case_GUID` = `z`.`GUID` AND top.IsValid
		DROP TEMPORARY TABLE IF EXISTS `t_kr_po`;
		CREATE TEMPORARY TABLE `t_kr_po`
			SELECT 
				-- _VarINT(0) AS `IsCreated`, 
				_VarStr(top.pr_krpo_GUID) AS GUID_kr_po, 
				_VarINT(COUNT(*)) AS Top_C,
				_VarDouble(SUM(top.Ilosc_Seria)) AS Tob_Seria,
				_VarDouble(SUM(top.pr_ilosc_seria)) AS Top_Seria,
				_VarDouble(SUM(top.Ilosc)) AS Top_h,
				top.Marszruta AS Marszruta_G,
				_VarDouble(SUM(top.wartnet)) AS Wartosc,
				top.TobGUID,
				_ConcatSTR_NotEqu(def.Nazwa, _ConcatSTR_NotEqu(tob.Symbol, tob.Nazwa, ' - '), ': ') AS Tob_SymbolNazwa,
				tob.ParentGUID AS Rysunek_GUID,
				tob.ParentGUID AS Element_GUID,
				_VarStr('???????????????????????????????????????????') AS Rys_SymbolNazwa,
				_VarStr('???????????????????????????????????????????') AS Elem_SymbolNazwa,
				tob.Ilosc_J AS Ilosc_J,
				top.IsOBUN,
				top.extra_nr_karty
			FROM `temp_karty_pracy` top
			INNER JOIN `pr_tob` tob ON tob.GUID = top.TobGUID
			LEFT JOIN `pr_techn_def_obj` def ON def.IDN = tob.Def_Obj
			WHERE 
				top.pr_krng_GUID = _krng_GUID
				-- Bylo top.Case_GUID = _Case_GUID
				-- Bylo AND top.AreaGUID = _Area_GUID
			GROUP BY top.TobGUID	
		;
	-- 	Wstaw GUIDy rysunku i elementu
		UPDATE `t_kr_po`
		SET
			`Rys_SymbolNazwa` = '',
			`Elem_SymbolNazwa` = '',
			`Rysunek_GUID` = (@Rysunek_GUID := pr_GetPersistantTOB(`TobGUID`, 1, FALSE)),
			`Element_GUID` = (@Element_GUID := pr_GetPersistantTOB(`TobGUID`, 2, FALSE))
		;
	-- 	Uzupelnij dane rysunku
		UPDATE `t_kr_po` t, `pr_tob` tob
		SET
			t.Rys_SymbolNazwa = _ConcatSTR_NotEqu(tob.Symbol, tob.Nazwa, ' - ')
		WHERE
			t.Rysunek_GUID = tob.GUID
		;
	-- 	Uzupelnij dane elementu
		UPDATE `t_kr_po` t, `pr_tob` tob
		SET
			t.Elem_SymbolNazwa = _ConcatSTR_NotEqu(tob.Symbol, tob.Nazwa, ' - ')
		WHERE
			t.Element_GUID = tob.GUID
		;
		
		UPDATE `t_kr_po` krpo
		SET
			Marszruta_G = (
				SELECT
					_VarStr(GROUP_CONCAT(DISTINCT g.Symbol ORDER BY top.lp_vc SEPARATOR ' > '))
				FROM zmpo top
				LEFT JOIN `erp_area_nodes` g ON g.GUID = top.AreaGUID
				WHERE
					top.TobGUID = krpo.TobGUID
			)
		;
		IF _Area_Symbol != '' THEN
			SET _S1 = CONCAT('> ', _Area_Symbol);			--	np. '> CG'   dla gniazda IdCG
			SET _S2 = CONCAT('> |', _Area_Symbol, '|');		--	np. '> |CG|' dla gniazda IdCG
			UPDATE `t_kr_po` krpo
			SET
				Marszruta_G = _VarStr(IF(IFNULL(Marszruta_G, '') = '', '', CONCAT('> ', Marszruta_G))),
				Marszruta_G = _VarStr(Replace(Marszruta_G, _S1, _S2))
			;
		END IF;
		
	--	Kreuj pozycje karty rozliczen `pr_krpo`
		INSERT INTO `pr_krpo`
			(GUID,krngGUID,PodzlecGUID,TobGUID,AreaGUID,WorkgroupGUID,lp_int,lp_vc,Rodzaj,Progress,TimeCaps,Seria,IsOBUN,-- uwagi,
				Marszruta_G,Wartosc,
				Tob_SymbolNazwa,
				Rys_SymbolNazwa,
				Elem_SymbolNazwa,
				Masa_J
				)
			SELECT
				GUID_kr_po,
				_krng_GUID,	
				_Case_GUID, 				
				TobGUID,
				_Area_GUID, 
				_Workgroup_GUID, 
				0, '0',
				1,
				0,
				Top_h,
				Tob_Seria,
				IsOBUN,
				-- extra_nr_karty,
				Marszruta_G,
				Wartosc,
				Tob_SymbolNazwa,
				Rys_SymbolNazwa,
				Elem_SymbolNazwa,
				Ilosc_J
			FROM t_kr_po
		;
	-- 	Wstaw do zmpo (operacje czyli TOP-y) pr_krpo_GUID  bedacymi guidami pozycji kart realizacji
		UPDATE `zmpo` z, `temp_karty_pracy` top
		SET
			z.pr_krpo_GUID = top.pr_krpo_GUID
		WHERE
			z.GUID = top.GUID
		;

		
	--	Kreuj pozycje karty rozliczen `pr_krpo_r`
		SET _OsobaGUID = IFNULL(_Param_C, '');
		IF _OsobaGUID = '' THEN
			SET _OsobaGUID = @session.CurrOsobaGUID;
		END IF;
	--	Wstawianie	
		INSERT INTO `pr_krpo_r`
			(GUID,PodzlecGUID,krngGUID,krpoGUID,AreaGUID,WorkgroupGUID,LogType,Rodzaj,Progress,TimeCaps,TimeDone,Seria,SeriaDone,IsOBUN,OsobaGUID)
			SELECT
				NewGUID(),
				_Case_GUID, 				
				_krng_GUID,	
				GUID_kr_po,
				_Area_GUID, 
				_Workgroup_GUID, 
				'+',
				0, 0,
				Top_h, 0,
				Tob_Seria, 0,
				_IsOBUN, 
				_OsobaGUID
			FROM t_kr_po
		;
		UPDATE `pr_krpo_r`
		SET
			DateDone = aLocalTime
		WHERE
			krngGUID = _krng_GUID
		;
		
	--	Przelicz w KRz - Ustala ogolny progress karty `pr_krng` z wszystkich `pr_krpo` - parametrem jest _GUID (GUID z `pr_krng`)
		CALL pr_kr_Tool('NALICZ_krng', _krng_GUID, '', 0, '', '', '', '');		
/*		
	--	Przelicz w KaPr dodaj LOG do KaPr 
		CALL pr_KartaPracy_Log_Resume(_krng_GUID, FALSE);
		
		UPDATE `t_hurt_KaPr` kp
			SET kp.`IsCreated` = 1
		WHERE	
			kp.`pr_krpo_GUID` = _krpo_GUID
		;	
*/		
	END IF;	-- (_MODE = 100) OR (_MODE = 'CREATE_ONE') 
	
	IF (_MODE = 7) OR (_MODE = 'CLEAR') THEN
--	Sprzatanie
	--	Wyczysc ewentualne sieroty w zmpo (podczepione do zmpo KaPr, ktore nie istnieja 
/*	NA RAZIE 		
		UPDATE zmpo top, `t_hurt_KaPr` kp
			SET top.pr_krpo_GUID = '' 
		WHERE 
			kp.pr_krpo_GUID = top.pr_krpo_GUID 
			AND kp.IsCreated = 0 
		;
*/		
	--	Zwracaj karty ale tylko zalozone !!!!!!!
		SELECT * 
		FROM `t_hurt_KaPr` kp
		WHERE
			kp.`IsCreated` = 1
		;
	--	Drop tabeli 
		DROP TEMPORARY TABLE IF EXISTS `t_hurt_KaPr`;
		
	END IF;	-- (_MODE = 7) OR (_MODE = 'CLEAR') 

	IF _MODE = 'ROZLICZ_krpo_INIT' THEN
	--	Przygotowuje rekord (rekordy) do rozliczania +/-
	--	Parametry takie jak przy FIND
	--	_Param_C 		'+' - zmiana puli, '-' - rozliczanie
	--	_Param_D			'Ng' - dotyczy naglowka, 'Po' - dotyczy pozycji (1 lub wielu, ato zalezy od tego czy _KrPoIDN <> 0)
		SET _LogType = IFNULL(_Param_C, '-');
		SET _KrNgGUID = '';
		SET _KrNgIDN = 0;
		SET _KrPoGUID = '';
		SET _KrPoIDN = 0;
	-- Szukaj
		CALL pr_kr_Tool('FIND', _Check_GUID, '', _Check_Value, _Param_A,	_Param_B, '', '');
		SELECT 
			KrPoIDN, KrPoGUID, KrNgIDN, KrNgGUID
		INTO 
			_KrPoIDN, _KrPoGUID, _KrNgIDN, _KrNgGUID
		FROM `t_pr_kr_id`	
		;
		
		-- SET _RozliczOneRec = IF((_LogType = '-') AND (_KrPoIDN != 0), 1, 
		DROP TEMPORARY TABLE IF EXISTS `t_edit_pr_krpo_r_header`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_edit_pr_krpo_r_header`	
			SELECT
				_VarInt(_KrPoIDN) AS KrPoIDN, 
				_VarStr(_KrPoGUID) AS KrPoGUID, 
				_VarInt(_KrNgIDN) AS KrNgIDN, 
				_VarStr(_KrNgGUID) AS KrNgGUID,
				_VarStr(_LogType) AS LogType
		; 

		IF (_LogType = '-') AND (_KrPoIDN != 0) THEN
		--	Rozliczanie 
			IF _KrPoGUID != '' THEN
				CALL pr_kr_Tool('NALICZ_krpo', _KrPoGUID, '', 0, '', '', '', '');
			ELSE
				CALL pr_kr_Tool('NALICZ_krpo', _KrNgGUID, '', 0, 'x', '', '', '');
			END IF;
		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS `t_edit_pr_krpo_r`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_edit_pr_krpo_r`(
			`ID` VARCHAR(38) NOT NULL DEFAULT '',    	-- Klucz glowny z tabeli `t_edit_pr_krpo_r`
			`KrNgGUID` VARCHAR(38) NOT NULL DEFAULT '',
			`KrPoGUID` VARCHAR(38) NOT NULL DEFAULT '',
			`PodzlecGUID` VARCHAR(38) NOT NULL DEFAULT '', 
			`AreaGUID` VARCHAR(38) NOT NULL DEFAULT '', 
			`WorkgroupGUID` VARCHAR(38) NOT NULL DEFAULT '', 
			`kp_TobGUID` VARCHAR(38) NOT NULL DEFAULT '', 
			`kp_Progress` DOUBLE (16,4) DEFAULT 0, 
			`kp_Progress100` DOUBLE (16,4) DEFAULT 0, 
			`DateDone` DATE,
			`kp_TimeCaps` DOUBLE (16,4) DEFAULT 0, 
			`kp_TimeDone` DOUBLE (16,4) DEFAULT 0, 
			`kp_TimeDoneProc` DOUBLE (16,4) DEFAULT 0, 
			`kp_Seria` DOUBLE (16,4) DEFAULT 0, 
			`kp_SeriaDone` DOUBLE (16,4) DEFAULT 0, 
			`kp_Status` INT DEFAULT 0, 
			`kp_StatusStr` VARCHAR(50) NOT NULL DEFAULT '', 
			`kp_Marszruta_G` VARCHAR(255) NOT NULL DEFAULT '',
			`kp_Tob_SymbolNazwa` VARCHAR(255) NOT NULL DEFAULT '',
			`kp_Rys_SymbolNazwa` VARCHAR(255) NOT NULL DEFAULT '',
			`kp_Elem_SymbolNazwa` VARCHAR(255) NOT NULL DEFAULT '',			
			`AsortymentNazwa` VARCHAR(200) NOT NULL DEFAULT '',		
			`gat_stali` VARCHAR(200) NOT NULL DEFAULT '',		
			`atest` VARCHAR(200) NOT NULL DEFAULT '',		
			`LogType` VARCHAR(20) NOT NULL DEFAULT '-',
			`Checked` INT DEFAULT 0, 
			`ModifyStatus` INT DEFAULT 0, 
			`TimeCapsALL` DOUBLE (16,4) DEFAULT 0, 
			`TimeCapsALLTob` DOUBLE (16,4) DEFAULT 0, 
			`TimeDoneALL` DOUBLE (16,4) DEFAULT 0, 
			`TimeDoneALLTob` DOUBLE (16,4) DEFAULT 0, 
			`Waga` DOUBLE (16,4) DEFAULT 0, 
			`TimeToDo` DOUBLE (16,4) DEFAULT 0, 
			`TimeToDoRest` DOUBLE (16,4) DEFAULT 0, 
			`SeriaToDo` DOUBLE (16,4) DEFAULT 0, 
			`New_TimeDone` DOUBLE (16,4) DEFAULT 0, 
			`New_SeriaDone` DOUBLE (16,4) DEFAULT 0, 
			`New_TimeCaps` DOUBLE (16,4) DEFAULT 0, 
			`New_AreaGUID` VARCHAR(38) NOT NULL DEFAULT '',  
			`New_WorkgroupGUID` VARCHAR(38) NOT NULL DEFAULT '',  
			PRIMARY KEY (`ID`)
		);
		DELETE FROM `t_edit_pr_krpo_r`;
		
		--	Jaki _Param_D		???		
		IF _Param_D = 'Ng' THEN
		--	dotyczy naglowka
			INSERT INTO `t_edit_pr_krpo_r`	
				SELECT
					NewGUID(),
					_KrNgGUID,
					_KrPoGUID,
					kp.PodzlecGUID, 
					kp.AreaGUID, 
					kp.WorkgroupGUID, 
					kp.TobGUID, 
					kn.Progress, 
					_VarDouble(kn.Progress*100), 
					CURRENT_DATE() AS DateDone,
					SUM(kp.TimeCaps) AS TimeCaps,  
					SUM(kp.TimeDone) AS TimeDone,  
					AVG(kp.TimeDoneProc) AS TimeDoneProc,  
					SUM(kp.Seria) AS Seria, 
					SUM(kp.SeriaDone) AS SeriaDone, 
					kn.Status, 
					sp.DisplayValue,		-- as StatusStr,
					kp.Marszruta_G,
					kp.Tob_SymbolNazwa,
					kp.Rys_SymbolNazwa,
					kp.Elem_SymbolNazwa,

					_VarStr(_ConcatSTR_NotEqu(aso.Symbol, aso.Nazwa,  ' - ')), 
					_VarStr_NotNull(sp1.DisplayValue),
					_VarStr_NotNull(sp2.DisplayValue),
					
					_VarStr(_LogType),	--  AS LogType,
					_VarInt(0),	-- AS Checked,
					_VarInt(0),	--  AS ModifyStatus, 
					_VarDouble(0),	--  As TimeCapsALL,
					_VarDouble(0),	--  As TimeCapsALLTob,
					_VarDouble(0),	--  As TimeDoneALL, 
					_VarDouble(0),	--  As TimeDoneALLTob, 
					_VarDouble(1),	--  As Waga,
					_VarDouble(0),	--  AS TimeToDo,
					_VarDouble(0),	--  As TimeToDoRest,
					_VarDouble(0),	--  AS SeriaToDo,
					_VarDouble(0),	--  As New_TimeDone,
					_VarDouble(0),	--  As New_SeriaDone,
					_VarDouble(0),	--  As New_TimeCaps,
					kp.AreaGUID,	--  AS New_AreaGUID, 
					kp.WorkgroupGUID	--  AS New_WorkgroupGUID 
				FROM `pr_krpo` kp	
				LEFT JOIN `pr_krng` kn ON kn.GUID = kp.KrNgGUID
				LEFT JOIN `pr_tob` tob ON tob.GUID = kp.tobGUID
				LEFT JOIN `erp_asort_types` aso ON aso.GUID = tob.Asortyment
				LEFT JOIN `slowniki_pierwotne` sp1 ON tob.ParamA = sp1.value AND sp1.slownik_guid = "G_STALI"
				LEFT JOIN `slowniki_pierwotne` sp2 ON tob.atest_id = sp2.value AND sp2.slownik_guid = "ATESTY_STALI"
				LEFT JOIN `slowniki_pierwotne` sp ON sp.Value = kn.status AND sp.Slownik_GUID = 'PR_STATUS_KRz'
				WHERE
					kp.KrNgGUID = _KrNgGUID
				GROUP BY kp.KrNgGUID		
				-- LIMIT 1		
			; 
		ELSE
		--	dotyczy pozycji (1 lub wielu, ato zalezy od tego czy _KrPoIDN <> 0)
			INSERT INTO `t_edit_pr_krpo_r`	
				SELECT
					NewGUID(),
					_KrNgGUID,
					kp.GUID,
					kp.PodzlecGUID, 
					kp.AreaGUID, 
					kp.WorkgroupGUID, 
					kp.TobGUID, 
					kp.Progress, 
					_VarDouble(kp.Progress*100), 
					CURRENT_DATE() AS DateDone,
					kp.TimeCaps, 
					kp.TimeDone, 
					kp.TimeDoneProc, 
					kp.Seria, 
					kp.SeriaDone, 
					kp.Status, 
					sp.DisplayValue,		-- as StatusStr,
					kp.Marszruta_G,
					kp.Tob_SymbolNazwa,
					kp.Rys_SymbolNazwa,
					kp.Elem_SymbolNazwa,

					_VarStr(_ConcatSTR_NotEqu(aso.Symbol, aso.Nazwa,  ' - ')), 
					_VarStr_NotNull(sp1.DisplayValue),
					_VarStr_NotNull(sp2.DisplayValue),
					
					_VarStr(_LogType),	--  AS LogType,
					_VarInt(0),	--  AS Checked,
					_VarINT(0),	--  AS ModifyStatus, 
					_VarDouble(0),	--  As TimeCapsALL,
					_VarDouble(0),	--  As TimeCapsALLTob,
					_VarDouble(0),	--  As TimeDoneALL, 
					_VarDouble(0),	--  As TimeDoneALLTob, 
					_VarDouble(1),	--  As Waga,
					_VarDouble(kp.TimeCaps - kp.TimeDone),	--  AS TimeToDo,
					_VarDouble(0),	--  As TimeToDoRest,
					_VarDouble(kp.Seria - kp.SeriaDone),	--  AS SeriaToDo,
					_VarDouble(0),	--  As New_TimeDone,
					_VarDouble(0),	--  As New_SeriaDone,
					_VarDouble(0),	--  As New_TimeCaps,
					kp.AreaGUID,	--  AS New_AreaGUID, 
					kp.WorkgroupGUID	--  AS New_WorkgroupGUID 
				FROM `pr_krpo` kp	
				LEFT JOIN `pr_tob` tob ON tob.GUID = kp.tobGUID
				LEFT JOIN `erp_asort_types` aso ON aso.GUID = tob.Asortyment
				LEFT JOIN `slowniki_pierwotne` sp1 ON tob.ParamA = sp1.value AND sp1.slownik_guid = "G_STALI"
				LEFT JOIN `slowniki_pierwotne` sp2 ON tob.atest_id = sp2.value AND sp2.slownik_guid = "ATESTY_STALI"
				LEFT JOIN `slowniki_pierwotne` sp ON sp.Value = kp.status AND sp.Slownik_GUID = 'PR_STATUS_KRz'
				WHERE
						IF(_KrPoGUID != '', kp.GUID = _KrPoGUID, kp.KrNgGUID = _KrNgGUID)
			; 
		END IF;	--	_Param_D
		
	--	Rozliczenie
		SELECT
			_VarDouble(SUM(TimeCaps)),
			_VarDouble(SUM(IF(KrPoGUID != '', TimeCaps, 0))),
			_VarDouble(SUM(TimeDone)),
			_VarDouble(SUM(IF(KrPoGUID != '', TimeDone, 0)))
		INTO	
			@_TimeCapsALL, @_TimeCapsALLTob, @_TimeDoneALL, @_TimeDoneALLTob
			FROM `pr_krpo_r` kr	
			WHERE
				kr.KrNgGUID = _KrNgGUID
		; 
		UPDATE `t_edit_pr_krpo_r`
		SET
			TimeCapsALL = ROUND(@_TimeCapsALL, 4),
			TimeCapsALLTob = ROUND(@_TimeCapsALLTob, 4),
			TimeDoneALL = ROUND(@_TimeDoneALL, 4), 
			TimeDoneALLTob = ROUND(@_TimeDoneALLTob, 4),
			Waga = _VarDouble(ROUND(IF(TimeCapsALLTob = 0, 0, (kp_TimeCaps - kp_TimeDone)/(TimeCapsALLTob - TimeDoneALLTob)),5)),
			TimeToDoRest = ROUND(TimeCapsALL*Waga, 4)
		;
		
		IF _LogType = '+' THEN
		--	Pula czasowa
			SET _LogType = '+';
		ELSE
			SET _LogType = '+';
		END IF;	--	LogType

		
		IF (_LogType = '+') AND (_KrPoIDN != 0) THEN
		--	+ PULA Naglowka	
			SET _LogType = '+';
		END IF;
		IF (_LogType = '+') AND (_KrPoIDN = 0) THEN
		--	+ PULA Pozycji
			SET _LogType = '+';
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `t_edit_pr_krpo_r_select`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_edit_pr_krpo_r_select`	
			SELECT
				
				r.*
			FROM `t_edit_pr_krpo_r` r	
		; 
		
		select 	* FROM `t_edit_pr_krpo_r`;
		/*
		IF _KrPoIDN != 0 THEN
		--	Rozliczaj jedna pozycje karty
			CALL pr_kr_Tool('EDIT_krng', _KrNgIDN, '', 0, '', '', '', '');
		
		END IF;
		*/
	END IF; 	-- _MODE = 'ROZLICZ_krpo_INIT' 
	
	IF _MODE = 'ROZLICZ_krpo_APPLY' THEN
	--	Zapisuje rekord (rekordy) do rozliczania +/- i przelicza
	--	Bez parametrow
		SET _KrNgGUID = '';
		SET _KrNgIDN = 0;
		SET _KrPoGUID = '';
		SET _KrPoIDN = 0;
	-- Pobierz zmienne
		SELECT 
			KrPoIDN, KrPoGUID, KrNgIDN, KrNgGUID, LogType
		INTO 
			_KrPoIDN, _KrPoGUID, _KrNgIDN, _KrNgGUID, _LogType
		FROM `t_edit_pr_krpo_r_header`	
		;
	--	Kreuj pozycje karty rozliczen `pr_krpo_r`
		SET _OsobaGUID = IFNULL(_Param_C, '');
		IF _OsobaGUID = '' THEN
			SET _OsobaGUID = @session.CurrOsobaGUID;
		END IF;
		
		UPDATE `t_edit_pr_krpo_r`
		SET
			New_TimeCaps = IF(_LogType = '+', New_TimeCaps, 0),
			New_TimeDone = IF(_LogType = '+', 0, New_TimeDone),
			New_SeriaDone = IF(_LogType = '+', 0, New_SeriaDone)
		;
	--	Wstawianie	
		INSERT INTO `pr_krpo_r`
			(
				GUID,
				PodzlecGUID,krngGUID,krpoGUID,
				AreaGUID,WorkgroupGUID,
				LogType,Rodzaj,Progress,
				DateDone,
				TimeCaps,TimeDone,
				Seria,SeriaDone,
				IsOBUN,OsobaGUID
			)
			SELECT
				ID,
				PodzlecGUID,krngGUID,krpoGUID, 				
				New_AreaGUID,New_WorkgroupGUID, 
				_LogType,0, 0,
				DateDone,
				New_TimeCaps, New_TimeDone,
				0, New_SeriaDone, 
				0, _OsobaGUID
			FROM `t_edit_pr_krpo_r`
			WHERE
				ModifyStatus != 0		--	Tylko zmodyfikowane
		;
		/*
		IF _LogType = '+' THEN
		-- Pula czasowa (+)
		ELSE
		-- Rozliczenie (-)
		END IF;
		*/
	
	--	Przelicz w KRz - Ustala ogolny progress karty `pr_krng` z wszystkich `pr_krpo` - parametrem jest _GUID (GUID z `pr_krng`)
		CALL pr_kr_Tool('NALICZ_krng', _KrNgGUID, '', 0, '', '', '', '');		
	END IF; 	-- _MODE = 'ROZLICZ_krpo_APPLY' 
	
	
END$$



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

SET @CASEguid = '{F1A79CB6-2C12-4950-8C98-57D8A0C688DA}'; #17500 Zlec
SET @CASEguid = '{871CB62C-4846-49C2-9881-80719747BAC5}'; #17500/01 Podzlec
SET @CASEguid = '{453C2091-2AD8-4881-98E4-BEBD6BE5EA1A}'; #17500/02 Podzlec
SET @CASEguid = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}'; #17500/03 Podzlec
SET @CASEguid = '{1EE560C8-F23E-46EF-AFE2-E306F5592708}'; #17500/Sloniasty
SET @CASEguid = '{DD496100-9357-44A8-8629-916584C0271E}'; #17500/Klon
SET @Case_GUID = @CASEguid;

CALL pr_kr_Wizard('INIT', @Case_GUID, 0, '', '', '', '');
CALL pr_kr_Wizard('DZIALY', @Case_GUID, 1, '', '', '', '');
-- CALL pr_kr_Wizard(2, @Case_GUID, 0, '', '', '', '');
CALL pr_kr_Wizard('INFO', @Case_GUID, 0, '', '', '', '');

SEt @ID = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}IdCK0';  -- CK
CALL pr_kr_Wizard('CHECK_KARTY', @ID, 1, '', '', '', '');
SEt @ID = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}IdCA0'; -- CA
CALL pr_kr_Wizard('CHECK_KARTY', @ID, 1, '', '', '', '');

SELECT 
tob.Symbol,tob.Def_obj,kp.areaGUID,kp.symbol,kp.pr_krpo_GUID,kp.* 
FROM `temp_karty_pracy` kp
LEFT JOIN `pr_tob` tob ON tob.GUID = kp.tobGUID

;
SELECT * FROM `temp_karty_pracy`
WHERE pr_krpo_GUID != '';

CALL pr_kr_Wizard('CREATE', '', 0, '', '', '', '');

-- erp_workgroups
-- areaGUID
WorkgroupGUID
Wskazanie na GUID tabeli `erp_workgroups`

CALL pr_kr_Wizard('ROZLICZ_krpo_INIT', 'KRZ-66', 0, '*', '', '-', 'Po');

CALL pr_kr_Wizard('ROZLICZ_krpo_INIT', 'KRZ-66', 0, '*', '', '-', 'Po');
CALL pr_kr_Wizard('ROZLICZ_krpo_INIT', 'KRZ-66', 0, '*', '', '+', 'Po');
CALL pr_kr_Wizard('ROZLICZ_krpo_APPLY', '', 0, '', '', '', '');
CALL pr_kr_Tool('NALICZ_krng', '{7E6CB6D2-9EA8-11DE-A5B6-00065BF0376E}', '', 0, '', '', '', '');		

SET @CASEguid = '{2B254A41-69F8-4A45-BDD3-CF770A3A58E3}'; #17500/03 Podzlec
SET @CASEguid = '{DD496100-9357-44A8-8629-916584C0271E}'; #17500/Klon
CALL pr_ZlecWToku_Update(0, zlecGUID, divGUID, '', '');
-- 'Nawa1'
SET @W3 = '{5CA680FC-DFE2-448C-B997-2673440084C7}';
SET @W1 = '{8022922F-1712-49CD-A531-F7958180B305}';

SELECT d.Symbol,dl.* 
FROM crm_div_links dl
LEFT JOIN erp_division_schema d ON d.GUID = dl.DivGUID
WHERE
dl.commisionGUID = @CASEguid;

SELECT * FROM v_pr_division;

CALL pr_div_links_Tool('INIT', @CASEguid, 'Nawa1', '', '', '', '');

CALL pr_div_links_Tool('INIT_NEW', '', '', '0', '', '', '');
INSERT IGNORE INTO `t_Init_zlec_div`
(commisionGUID, divGUID)
VALUES (@CASEguid, 'Nawa1');
INSERT IGNORE INTO `t_Init_zlec_div`
(commisionGUID, divGUID)
VALUES (@CASEguid, @W3);

CALL pr_div_links_Tool('INIT_NEW', '', '', 'CREATE', '', '', '');

CALL pr_div_links_Tool('UPDATE', '', '', '', '', 'P', '');			
CALL pr_div_links_Tool('UPDATE_EXECUTE', @CASEguid, @W1, '', '', '', '');	-- nalicz

SELECT @_NeedUpdate;
SELECT  * FROM `t_PodZelcOkres_Agg`;

				explain
					SELECT
						@CASEguid AS PodzlecGUID,
						_VarInt(SUM(pw.GUID IS NOT NULL)) As C_MW,
						Date(MIN(pw.Data)) AS MinDate,
						Date(MAX(pw.Data)) AS MaxDate,
						_VarDouble(SUM(pmw.masa)) AS ilosc_work
					FROM `crm_div_links` dl 
					LEFT JOIN crm_commisions pw ON pw.Case_GUID = dl.commisionGUID AND pw.Rodzaj = 14 AND pw.PodRodzaj in (4,8,9)  
					LEFT JOIN pr_przesuniecie_mw pmw ON pmw.GUID_Ng = pw.GUID -- AND pmw.DivisionGUIDFrom = @W1 
					LEFT JOIN v_pr_division d ON d.GUID = pmw.DivisionGUIDFrom
					WHERE
						dl.commisionGUID = @CASEguid AND
						-- pmw.DivisionGUIDFrom = @W1 AND
						d.GUID_Wydzialu = @W1 AND
						dl.divGUID = @W1 
					GROUP BY PodzlecGUID
				;
				
				
				explain
					SELECT
						@CASEguid AS PodzlecGUID,
						_VarInt(SUM(pw.GUID IS NOT NULL)) As C_MW,
						Date(MIN(pw.Data)) AS MinDate,
						Date(MAX(pw.Data)) AS MaxDate,
						_VarDouble(SUM(pmw.masa)) AS ilosc_work
					FROM `crm_div_links` dl 
					LEFT JOIN pr_przesuniecie_mw pmw ON pmw.caseguid = dl.commisionGUID
					LEFT JOIN crm_commisions pw ON pw.GUID = pmw.GUID_Ng -- AND pw.Rodzaj = 14 AND pw.PodRodzaj in (4,8,9)  
					LEFT JOIN v_pr_division d ON d.GUID = pmw.DivisionGUIDFrom
					WHERE
						dl.commisionGUID = @CASEguid AND
						-- pmw.DivisionGUIDFrom = @W1 AND
						d.GUID_Wydzialu = @W1 AND
						dl.divGUID = @W1 
					GROUP BY PodzlecGUID
				;
				
				explain
					SELECT
						@CASEguid AS PodzlecGUID,d.GUID_Wydzialu
					FROM `crm_div_links` dl 
					LEFT JOIN crm_commisions pw ON pw.Case_GUID = dl.commisionGUID AND pw.Rodzaj = 14 AND pw.PodRodzaj in (4,8,9)  
					LEFT JOIN pr_przesuniecie_mw pmw ON pmw.GUID_Ng = pw.GUID -- AND pmw.DivisionGUIDFrom = @W1 
					LEFT JOIN v_pr_division d ON d.GUID = pmw.DivisionGUIDFrom
					WHERE
						dl.commisionGUID = @CASEguid AND
						-- pmw.DivisionGUIDFrom = @W1 AND
						d.GUID_Wydzialu = @W1 AND
						dl.divGUID = @W1 
					GROUP BY PodzlecGUID
;				
select * 
from pr_przesuniecie_mw pmw 
WHERE pmw.caseguid = @CASEguid
;


SELECT 
pw.GUID, pw.case_guid, pmw.caseguid, pmw.*
FROM pr_przesuniecie_mw pmw
LEFT JOIN crm_commisions pw ON pw.GUID = pmw.GUID_Ng AND pw.Rodzaj = 14 AND pw.PodRodzaj in (4,8,9)  
WHERE 
pw.case_guid <> pmw.caseguid
;

*/

DELIMITER ;