 SET	NAMES utf8;

DELIMITER $$
/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `ng_e_rec_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `ng_e_rec_bi` BEFORE INSERT ON `ng_e_rec` FOR EACH ROW 
A: BEGIN
-- set @Deb.1 = "ng_e_rec_bi _TriggerDisabled()";
-- 							INSERT INTO `_erp_external_process_log` (Process, TYPE, MSG, Err) VALUES ('ng_e_rec_bi', '_MODE', @Deb.1, 0);

	IF _TriggerDisabled() THEN LEAVE A; END IF;
	
	SET 
		NEW.handle_UserGUID = IFNULL(NEW.handle_UserGUID, ''),
		NEW.handle_Msg = '',
		NEW.handle_TableName = 
			IF(NEW.handle_FROM = 'OP', 
				'opng_e', 
				IF(NEW.handle_FROM = 'ZM', 
					'zmng_e',
					'opng_r_e'
				)
			)
	;	
	
	CALL _Get_Actual_handle_rec_User_Params('CHANGE', @SYSTEM.Client.Session.GUID, NEW.handle_UserGUID, NEW.handle_UserLogin, NEW.handle_UserUgrpGUID, NEW.handle_oper, '', '', '', '');
	
	IF NEW.handle_FROM IN ('OP', 'ZM') THEN
	/**********************************************************************************************************************************
		OPERACJE ZAMOWIENIA
	**********************************************************************************************************************************/
		IF (IFNULL(NEW.GUID, '') != '') AND (NEW.handle_oper IN ('EDIT', 'DELETE')) THEN
		--	EDYCJA lub DELETE
			IF NEW.handle_FROM = 'OP' THEN
				UPDATE `opng` n
				SET
					NEW.Rodzaj = n.Rodzaj,
					NEW.Rodzaj_typ = n.Rodzaj_typ,
					NEW.ui_idnuser = n.idnuser,	 	--	pole chyba nie uzywane
					NEW.ui_datawplywu = n.datawplywu,
					NEW.ui_status = n.status,
					NEW.i_KontrGUID = n.KontrGUID,
					NEW.i_Magazyn1_Kasa = n.ZMagazynu,
					NEW.i_Magazyn2 = n.DoMagazynu,
					NEW.i_calc_ver = n.calc_ver,
					NEW.i_fvrudowz = n.fvrudowz,
					NEW.r_UgrpGUID = n.UgrpGUID,
					NEW.u_ThisIsUserRecord = (NEW.handle_UserGUID = n.CreatorGUID)
				WHERE
					n.GUID = NEW.GUID
				;
			ELSE	
				UPDATE `zmng` n
				SET
					NEW.Rodzaj = n.Rodzaj,
					NEW.Rodzaj_typ = n.Rodzaj_typ,
					NEW.ui_idnuser = n.idnuser,	 	--	pole chyba nie uzywane
					NEW.ui_datawplywu = n.datawplywu,
					NEW.ui_status = n.status,
					NEW.i_KontrGUID = n.KontrGUID,
					NEW.i_Magazyn1_Kasa = n.idnmagazyn,
					NEW.i_Magazyn2 = n.MagazynWys,
					NEW.i_calc_ver = n.calc_ver,
					NEW.r_UgrpGUID = n.UgrpGUID
				WHERE
					n.GUID = NEW.GUID
				;
			END IF;
			
			UPDATE `operdoc` o
			SET
				NEW.u_optyp = o.upr_optyp,
				NEW.u_rodzaj = o.upr_rodzaj,
				NEW.OpTyp = o.grupa
			WHERE
				o.Rodzaj = NEW.Rodzaj
			;
			
		END IF;
	END IF; -- OPERACJE ZAMOWIENIA
	
	IF NEW.handle_FROM IN ('R', 'R') THEN
	/**********************************************************************************************************************************
		KASA BANK DOKUMENTY ROZRACHUNKOWE
	**********************************************************************************************************************************/
		UPDATE `operdoc` o
		SET
			NEW.u_optyp = o.upr_optyp,
			NEW.u_rodzaj = o.upr_rodzaj,
			NEW.OpTyp = o.grupa
		WHERE
			o.Rodzaj = NEW.Rodzaj
		;
		IF (NEW.handle_oper IN ('INSERT')) THEN
		--	INSERT
			SET 
				NEW.r_Family_GUID = NewGUID()
			;
			
		END IF;
		
		IF (NEW.handle_oper IN ('EDIT', 'DELETE')) THEN
		--	EDYCJA DELETE
			IF NEW.handle_FROM = 'R' AND NEW.i_IsFamily AND NEW.r_Family_GUID IS NOT NULL THEN
				SET
				--	Daj pierwszy z brzegu rekord z `opng` o takim Family_GUID jak r_Family_GUID
					NEW.GUID = (
						SELECT n.GUID FROM `opng` n WHERE n.Family_GUID = NEW.r_Family_GUID ORDER BY n.idn LIMIT 1
					)
				;
			END IF;
			
			IF NEW.GUID IS NOT NULL THEN
				UPDATE `opng` n
				SET
					NEW.Rodzaj = n.Rodzaj,
					NEW.Rodzaj_typ = n.Rodzaj_typ,
					NEW.ui_idnuser = n.idnuser,	 	--	pole chyba nie uzywane
					NEW.ui_datawplywu = n.datawplywu,
					NEW.ui_status = n.status,
					NEW.i_KontrGUID = n.KontrGUID,
					NEW.i_Magazyn1_Kasa = n.nrkasy,
					NEW.i_calc_ver = n.calc_ver,
					NEW.r_Family_GUID = n.Family_GUID,
					NEW.r_nrraportu = n.nrraportu,
					NEW.r_nrkasy = n.nrkasy,
					NEW.r_datawystaw = n.datawystaw,
					NEW.r_UgrpGUID = n.UgrpGUID,
					NEW.r_RodzajDowodu = n.RodzajDowodu
				WHERE
					n.GUID = NEW.GUID
				;
			END IF;
		END IF;
	END IF; -- KASA BANK DOKUMENTY ROZRACHUNKOWE
END;
$$

/* ************************************************************************************************************************************************************************
	AI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `ng_e_rec_ai`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `ng_e_rec_ai` AFTER INSERT ON `ng_e_rec` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	/*
	IF IFNULL(@session.trigger.ng_e_rec, FALSE) THEN 
		LEAVE A; 
	END IF;
	SET @session.trigger.ng_e_rec = TRUE;
	*/

	
	
	/*
	SET @session.trigger.ng_e_rec = FALSE;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `ng_e_rec_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `ng_e_rec_bu` BEFORE UPDATE ON `ng_e_rec` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	/*
	IF IFNULL(@session.trigger.ng_e_rec, FALSE) THEN 
		LEAVE A; 
	END IF;
	SET @session.trigger.ng_e_rec = TRUE;
	*/
	
	IF NOT (NEW.Rodzaj <=> OLD.Rodzaj) AND NEW.Rodzaj >= 0 THEN
		UPDATE `operdoc` o
		SET
			NEW.u_optyp = o.upr_optyp,
			NEW.u_rodzaj = o.upr_rodzaj,
			NEW.OpTyp = o.grupa,
			NEW.i_Tymczasowa = IF(o.DefaultTymczasowa < 0, 0, NEW.i_Tymczasowa)
		WHERE
			o.Rodzaj = NEW.Rodzaj
		;
	END IF;

--	handle_UserGUID	
SET
@.X.EDIT = concat(NEW.handle_oper, ' - ', NEW.handle_FROM),
@.E.NEW.handle_UserLogin = NEW.handle_UserLogin,
@.E.OLD.handle_UserGUID = OLD.handle_UserGUID,
@.E.NEW.handle_UserGUID = NEW.handle_UserGUID,
@.E.handle_UserGUID.Changed = !(NEW.handle_UserGUID <=> OLD.handle_UserGUID)
;
	SET @.handle_UserGUID.Changed = !(NEW.handle_UserGUID <=> OLD.handle_UserGUID);
	IF NEW.handle_UserGUID = '?' THEN
		SET NEW.handle_UserGUID = '';
	END IF;
                SET @XXX = concat_WS('->', @XXX, 'TR:CHANGE');
	CALL _Get_Actual_handle_rec_User_Params('CHANGE', @SYSTEM.Client.Session.GUID, NEW.handle_UserGUID, NEW.handle_UserLogin, NEW.handle_UserUgrpGUID, NEW.handle_oper, '', '', '', '');
	/*
	IF @.handle_UserGUID.Changed AND NOT (NEW.handle_oper IN ('EDIT', 'DELETE')) THEN	--	DLACZEGO dla Edycji i Delete NIE MOZEMY ??????????????  -> patrz nizej NEW.handle_UserLogin =
	--	Dla Insert
		SET	
			-- NEW.r_UgrpGUID = IFNULL(
			NEW.handle_UserUgrpGUID = IFNULL(
				(SELECT o.UgrpGUID FROM `osoby` o WHERE o.GUID = NEW.handle_UserGUID)
			, 'ALL')
		;
	END IF;
	
	IF @.handle_UserGUID.Changed THEN	--	2016-05-11 Oddzieliłem i NEW.handle_UserLogin pozwlama dla EDIT i DELETE
		SET
			-- NEW.ui_idnuser = IFNULL(
			NEW.handle_UserLogin = IFNULL(
				(SELECT o.idnuser FROM `osoby` o WHERE o.GUID = NEW.handle_UserGUID)
			, '')
		;
	END IF;
	koniec zmian
	*/
	
	
	IF NEW.handle_oper = 'insert' THEN
		IF !(NEW.i_Magazyn1_Kasa <=> OLD.i_Magazyn1_Kasa) AND (@session.globals.Owner = 'IZOHAN') AND NEW.i_MODE = 'CLONE.AS.ZAM.FROM.OFERTA' THEN
		--	UWAGA dla Izohanu gdy robimy zam. z oferty to mag. wysylkowy <- idnmag.
			SET NEW.i_Magazyn2 =  NEW.i_Magazyn1_Kasa;
		END IF;
	END IF;
	
	IF NEW.handle_FROM IN ('R', 'R') THEN	--	Gdy rodzinna lub jedyncza ...
	/**********************************************************************************************************************************
		KASA BANK DOKUMENTY ROZRACHUNKOWE
	**********************************************************************************************************************************/
		IF NEW.handle_oper = 'Insert' AND NEW.i_Tymczasowa = 0 AND NEW.OpTyp = @ht.KS AND 	--	ale KASA i wstawianie
			(
			NOT (NEW.Rodzaj <=> OLD.Rodzaj) 
			OR 
			NOT (NEW.r_nrkasy <=> OLD.r_nrkasy)
			) 
		THEN
		/**********************************************************************************************************************************
			ustawiono w wizardzie rodzaj kasy i numer kasy ... zatem zmien  r_Family_GUID i nrraportu z ostatniego BO
		**********************************************************************************************************************************/
			SELECT 
				n.nrraportu,
				n.GUID 
			INTO 
				@NEW.r_nrraportu,
				@NEW.r_Family_GUID
			FROM `opng` n 
			WHERE 
				TRUE
				AND n.nrkasy = NEW.r_nrkasy
				AND n.rodzaj = @ht.CRKBO
				-- AND n.datawystaw  BETWEEN  DATE_SUB('2014-01-01',INTERVAL 3 DAY) AND CURRENT_DATE()
			ORDER BY n.datawystaw DESC 
			LIMIT 1
			;
			SET
				NEW.r_nrraportu = IFNULL(@NEW.r_nrraportu, ''),
				NEW.r_Family_GUID = IFNULL(@NEW.r_Family_GUID, '')
			;
		END IF;
	END IF;
SET @XXX = concat_WS('->', @XXX, 'TR:2');	
	IF NOT (NEW.i_Tymczasowa <=> OLD.i_Tymczasowa) AND OLD.i_Tymczasowa > NEW.i_Tymczasowa AND NEW.Rodzaj != 3 THEN
	--	gdy zmienia ktos z 1 na 0 (odtymczasowienie) i nie jest to korekta -> to sprawdz uprawnienie czyli pozwol gdy masz uprawnienie
		-- bylo SET NEW.i_Tymczasowa = _GetUprawnienieExpected('Wystawianie_Dokumentow_Nietymczasowych', '', 1);
		SET NEW.i_Tymczasowa = IF(_GetUprawnienie('Wystawianie_Dokumentow_Nietymczasowych', '') IN (1, 5), NEW.i_Tymczasowa, OLD.i_Tymczasowa);
	END IF;

SET @XXX = concat_WS('->', @XXX, 'TR:3');	
	IF NOT (NEW.handle_check <=> OLD.handle_check) AND NEW.handle_check != 0 THEN
set @jmam_1 = '1';	
		IF NEW.handle_check IN (102, 103) THEN	--	wolane z CALL _ng_e_rec_set_from_another_doc()
			SET 
				@.handle_check.Update.Self = 
					IF(NEW.handle_check = 103,
						TRUE,
						NEW.handle_oper = 'Insert' AND NEW.i_MODE = '' 
					)
			;
			SET 
				NEW.handle_check = -2 
			;
			/*
			IF NEW.handle_oper != 'Insert' THEN
				LEAVE A; 
			END IF;
			
			IF NEW.i_MODE != '' THEN
				LEAVE A; 
				
			ELSE	-- gdy NEW.i_MODE != ''
			*/
			IF NOT @.handle_check.Update.Self THEN
				set @jmam_1 = '888';	
				LEAVE A; 
				
			ELSE	-- gdy NEW.i_MODE != ''
				set @jmam_1 = '2';	
				IF NEW.handle_FROM != 'ZM' THEN
				--	Operacje
					UPDATE `opng` n
					SET
						NEW.Rodzaj = n.Rodzaj, 
						NEW.Rodzaj_Typ = n.Rodzaj_Typ, 
						NEW.i_Calc_Ver = n.Calc_Ver, 
						NEW.i_KontrGUID = n.KontrGUID, 
						NEW.i_Magazyn1_Kasa = n.Zmagazynu, 
						NEW.i_Magazyn2 = n.Domagazynu, 
						NEW.i_Tymczasowa = n.Tymczasowa, 
						NEW.i_Waluta = n.Waluta, 
						NEW.i_OsobaGUID = n.OsobaGUID, 
						NEW.i_AreaGUID = n.AreaGUID, 
						NEW.i_fvrudowz = n.fvrudowz, 
						NEW.r_UgrpGUID = n.UgrpGUID
					WHERE
						NEW.handle_oper = 'Insert'
						AND
						n.GUID = NEW.i_Input_GUID
					;	
				ELSE
				--	Zamowienia
					UPDATE `zmng` n
					SET
						NEW.Rodzaj = n.Rodzaj, 
						NEW.Rodzaj_Typ = n.Rodzaj_Typ, 
						NEW.i_Calc_Ver = n.Calc_Ver, 
						NEW.i_KontrGUID = n.KontrGUID, 
						NEW.i_Magazyn1_Kasa = n.idnmagazyn, 
						NEW.i_Magazyn2 = n.magazynwys, 
						NEW.i_Tymczasowa = n.Tymczasowa, 
						NEW.i_Waluta = n.Waluta, 
						NEW.i_OsobaGUID = n.OsobaGUID, 
						NEW.i_AreaGUID = n.AreaGUID, 
						NEW.r_UgrpGUID = n.UgrpGUID
					WHERE
						NEW.handle_oper = 'Insert'
						AND
						n.GUID = NEW.i_Input_GUID
					;	
				END IF;
			END IF;
			LEAVE A; 
		END IF;
	
SET @XXX = concat_WS('->', @XXX, 'TR:4');	
	
		SET @_extCaption = IF(NEW.handle_oper = 'Insert', 'Wstawianie danych ', IF(NEW.handle_oper = 'Edit', 'Edycja danych ', 'Usuwanie danych '));
		
		IF NEW.handle_check = 1 THEN
		/**********************************************************************************************************************************
			BEFORE	przed operacja
		**********************************************************************************************************************************/
			CALL _ng_e_rec_msg_clear('', NEW.GUID, 'handle.BEFORE', '');
			
			SET @aUp = GREATEST(_GetUprawnienie(NEW.u_optyp, ''), _GetUprawnienie(NEW.u_rodzaj, ''));
			SET @aUp0 = @aUp;
		
			CALL _sys_upr_DefaultUprIsOK('BEFORE', NEW.handle_oper, FALSE, FALSE, @aUp, NEW.u_rodzaj, @_extCaption, NEW.u_OK, NEW.u_Msg);		
			
			-- SET _OK = @ht.doc.UprOK;
			IF NOT NEW.u_OK THEN
				CALL _ng_e_rec_msg_ins('ng_msg_upr', 'B1', NEW.GUID, 'handle.BEFORE', 
					'',
					'Error', 
					'Stop', '', ''
				);
			END IF;
		
			/**********************************************************************************************************************************
				Czy kontrahent w ogole istnieje ?????
			**********************************************************************************************************************************/
			IF IFNULL((SELECT o.MA_Kontrahenta FROM `operdoc` o WHERE o.Rodzaj = NEW.Rodzaj), FALSE) THEN
			--	Operacja MA Kontrahenta
				IF IFNULL(NEW.i_KontrGUID, '') = '' THEN
					CALL _ng_e_rec_msg_ins('', '', NEW.GUID, 'handle.BEFORE', 
						'Nie wybrano kontrahenta !!!',
						'Warning', 
						'Msg', '', ''
					);
				ELSEIF NOT EXISTS(SELECT k.GUID FROM `kontrah` k WHERE k.GUID = NEW.i_KontrGUID) THEN
					CALL _ng_e_rec_msg_ins('', '', NEW.GUID, 'handle.BEFORE', 
						'Kontrahent taki nie istnieje !!!',
						'Error', 
						'Stop', '', ''
					);
				END IF;
			END IF;
			
		
		END IF;	--	IF NEW.handle_check = 1 THEN
SET @XXX = concat_WS('->', @XXX, 'TR:5');	
		
		IF NEW.handle_check = 2 THEN
			SET 
				NEW.handle_check = -2, 
				NEW.handle_Msg = '',
				NEW.handle_ReadOnly_Msg = ''
			;
			CALL _ng_e_rec_msg_clear('', NEW.GUID, 'handle.AFTER', '');
		/**********************************************************************************************************************************
			ON/AFTER	w trakcie operacji
		**********************************************************************************************************************************/
			SET @UpGREATEST = GREATEST(_GetUprawnienie(NEW.u_optyp, ''), _GetUprawnienie(NEW.u_rodzaj, ''));
			SET @aUp = @UpGREATEST;
			SET @aUp1 = @aUp;
			
			/**********************************************************************************************************************************
				INSERT
			**********************************************************************************************************************************/
			IF NEW.handle_oper = 'insert' THEN
				CALL _sys_upr_DefaultUprIsOK('AFTER', NEW.handle_oper, FALSE, FALSE, @UpGREATEST, NEW.u_rodzaj, @_extCaption, NEW.u_OK, NEW.u_Msg);
				IF NOT NEW.u_OK THEN
					SET @1NEW.u_OK_XXX =  NEW.u_OK;
				END IF;
				
			END IF;
			
			/**********************************************************************************************************************************
				EDIT
			**********************************************************************************************************************************/
			IF NEW.handle_oper = 'edit' THEN
				
				/**********************************************************************************************************************************
					Sprawdzam date zabr. operacji
				**********************************************************************************************************************************/
				IF NEW.handle_FROM IN ('OP')  
				--	Kontrola daty granicznej dok	
				AND (@session.HT.IR.Kontrola_daty_granicznej_dok)
				THEN -- _MODE = 'DataZabrOper' THEN
					SELECT 
						n.IDN, n.Rodzaj, n.grupaoper, -- IFNULL(n.nrdokfin, ''), IFNULL(n.NrWewn, ''), IFNULL(n.nrdokmag, ''), IFNULL(n.wzordekr, ''), 
						n.datawplywu, n.datawystaw, n.datasprzed,
						n.kancelaria_kierunek
						/*
						n.fvrudowz, n.brutto, n.Vat,
						-- NIE !!! bo NULL musi byc zbadana ponizej !!!!! IFNULL(n.ZMagazynu, 0), IFNULL(n.DoMagazynu, 0),
						n.ZMagazynu, n.DoMagazynu,
						op.MA_Kontrahenta,
						op.IsDostawa, op.IsKorekta, op.MA_Magzyny, op.MA_Detale,
						op.Grupa AS OpTyp,
						n.korektatytulem,
						n.kontrnip,
						n.split_payment
						*/
					INTO
						@n.IDN, @n.Rodzaj, @n.grupaoper, -- @n.nrdokfin, @n.NrWewn, @n.nrdokmag, @n.wzordekr, 
						@n.datawplywu, @n.datawystaw, @n.datasprzed,
						@KK_kier
					FROM `opng` n	-- , `operdoc` op
					WHERE
						n.GUID = NEW.GUID
						-- AND op.Rodzaj = n.Rodzaj
					;
					IF @n.grupaoper = 0 THEN
					--	Sprzedaż
						SET @.data.graniczna = DATE(@session.HT.IR.DataZabrOperSprzedaz);
						SET @.data.graniczna.OK =
							DATE(@n.datawystaw) > @.data.graniczna
							AND
							DATE(@n.datasprzed) > @.data.graniczna,
							@.data.graniczna.ng_msg_DataZabrOper_stop = 'ng_msg_DataZabrOperSprzed_stop',
							@.data.graniczna.ng_msg_DataZabrOper_warrning = 'ng_msg_DataZabrOperSprzed_warrning'
						;
					ELSE
						IF @n.grupaoper IN (1, 4) then
						--	Zakup i zak. pzost ZT, ZP
							SET @.data.graniczna = DATE(@session.HT.IR.DataZabrOperZakupy);
						ELSE
						--	dla wszystkich pozst. grup ...	
							SET @.data.graniczna = DATE(@session.HT.IR.cDataZabrOper);
						END IF;
						SET 
							@.data.graniczna.OK = DATE(@n.datawplywu) > @.data.graniczna,
							@.data.graniczna.ng_msg_DataZabrOper_stop = 'ng_msg_DataZabrOper_stop',
							@.data.graniczna.ng_msg_DataZabrOper_warrning = 'ng_msg_DataZabrOper_warrning'
						;
					END IF;
					IF NOT @.data.graniczna.OK THEN
						SET @aUp = _GetUprawnienie('opng|EditPoCzasie', '');
						SET @aUp_EditPoCzasie = @aUp;
						SET NEW.handle_ReadOnly = (@aUp < @uprDSView);
						
						CALL _ng_e_rec_msg_ins('', 'A1', NEW.GUID, 'handle.AFTER', 
							(@.data.graniczna.MSG :=
							IF(NEW.handle_ReadOnly, 
								REPLACE(_res_str_get(@.data.graniczna.ng_msg_DataZabrOper_stop, ''), '#D', _VarStr(@.data.graniczna)),
								REPLACE(_res_str_get(@.data.graniczna.ng_msg_DataZabrOper_warrning, ''), '#D', _VarStr(@.data.graniczna))
							)),
							IF(NEW.handle_ReadOnly, 
								'Warning', 
								'Msg'
							),
							IF(NEW.handle_ReadOnly, 
								'ReadOnly', 
								''
							),
							'', ''
						);
						SET 
							NEW.u_DataZabrOper_Status = IF(NEW.handle_ReadOnly, 'ReadOnly', 'Info'),
							NEW.u_DataZabrOper_Msg = @.data.graniczna.MSG,
						--	I dodaj jeszcze te sam komunikat do NEW.handle_Msg
							NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, @.data.graniczna.MSG)
						;	
					END IF;
				END IF;
				
				/**********************************************************************************************************************************
					WZ lub PZ gdy ma juz podczepione pozycje
				**********************************************************************************************************************************/
				IF NEW.Rodzaj IN (10, 12) THEN -- NEW.i_fvrudowz = 0 THEN
					SET
						@ExistAttachPoz = EXISTS(SELECT IDN FROM `oppo` WHERE IdnOper = NEW.GUID AND IFNULL(IDNWZ, '') != '')
					;
					IF @ExistAttachPoz THEN
						IF IFNULL(@session.HT.IR.ZakazEdycjiWZPZPodczepionych, TRUE) THEN
						--	NIE wolno edytowac dok. gdy jest podczepiony do finansowego
							SET NEW.handle_ReadOnly = TRUE; -- NEW.handle_ReadOnly OR @NEW.Status.handle_ReadOnly;
							CALL _ng_e_rec_msg_ins('', 'A2', NEW.GUID, 'handle.AFTER', 
								_res_str_get('ng_msg_Podczepione_poz_WZPZ__warrning', ''),
								'Warning', 
								'ReadOnly', '', ''
							);
						ELSE
						--	Wolno edytowac dok. gdy jest podczepiony do finansowego - ALE SPRAWDZ czy nie jest zafiskalizowany ????
							SET
								@ExistAttachPozFisk = EXISTS(SELECT nfin.GUID FROM `oppo` p, `opng` nfin WHERE p.IdnOper = NEW.GUID AND nfin.GUID = p.idnwz AND nfin.paragon_printed)
							;
							IF @ExistAttachPozFisk THEN
							--	NIE wolno edytowac dok. gdy jest podczepiony do ZAFISKALIZOWANEGO finansowego (paragon_printed)
								SET NEW.handle_ReadOnly = TRUE; -- NEW.handle_ReadOnly OR @NEW.Status.handle_ReadOnly;
								CALL _ng_e_rec_msg_ins('', 'A2', NEW.GUID, 'handle.AFTER', 
                                    _res_str_get('ng_msg_Podczepione_poz_WZPZ__warrning', ''),
									'Warning', 
									'ReadOnly', '', ''
								);
							END IF;
						END IF;
					END IF;
				END IF;
SET @XXX = concat_WS('->', @XXX, 'TR:6');	

				IF NEW.handle_FROM IN ('ZM') AND NEW.Rodzaj = 27 AND (@session.globals.Owner = 'IZOHAN')  THEN 
				/**********************************************************************************************************************************
					Gdy w ZAM oo WyjazdGUID <> ''
				**********************************************************************************************************************************/
					SET
						@.n.wyjazdGUID = IFNULL((SELECT CONCAT('Wyj: ', w.nrwewn) FROM `zmng` n, `v_crm_spedycje` w WHERE n.GUID = NEW.GUID AND w.GUID = n.wyjazdGUID) 
						, '') -- INTO @.n.wyjazdGUID
					;
					IF @.n.wyjazdGUID <> '' THEN
						CALL _ng_e_rec_msg_ins('', 'A2', NEW.GUID, 'handle.AFTER', 
							-- _res_str_get('ng_msg_Podczepione_poz_WZPZ__warrning', ''),
							CONCAT('Zamowienie w czesci lub cale jest podlaczone do wyjazdu ', @.n.wyjazdGUID),
							'Warning', 
							'', '', ''
						);
				
					END IF;
					
					SET
						@Exist_pakowana_pozycja_zm = EXISTS(SELECT IDN FROM `zmpo` WHERE IdnNg = NEW.GUID AND Status = 32)
					;
					IF @Exist_pakowana_pozycja_zm THEN
						-- JEDNAK NIE!!! SET NEW.handle_ReadOnly = TRUE; -- NEW.handle_ReadOnly OR @NEW.Status.handle_ReadOnly;
						CALL _ng_e_rec_msg_ins('', 'A2.A', NEW.GUID, 'handle.AFTER', 
							-- _res_str_get('ng_msg_Podczepione_poz_WZPZ__warrning', ''),
							CONCAT('Przynajmniej niektore pozycje sa juz pakowane (realizowane) i nie powinny podlegac edycji!'),
							'Warning', 
							'', '', ''
						);
				
					END IF;
				END IF;

SET @XXX = concat_WS('->', @XXX, 'TR:7');	
				
				/**********************************************************************************************************************************
					Czy paragon zafiskalizowany ?
				**********************************************************************************************************************************/
				IF NEW.Rodzaj IN (0, 2) THEN -- czy paragon
					SET
						@Exist_paragon_zafiskalizowany = EXISTS(SELECT IDN FROM `opng` WHERE GUID = NEW.GUID AND paragon_printed != 0)
					;
					IF @Exist_paragon_zafiskalizowany THEN
						SET NEW.handle_ReadOnly = TRUE; -- NEW.handle_ReadOnly OR @NEW.Status.handle_ReadOnly;
						CALL _ng_e_rec_msg_ins('', 'A2', NEW.GUID, 'handle.AFTER', 
                            _res_str_get('ng_msg_Exist_paragon_zafiskalizowany', ''),
							-- 'Dokument ten został już zafiskalizowany i nie podlega edycji!',
							'Warning', 
							'ReadOnly', '', ''
						);
					END IF;
				END IF;

SET @XXX = concat_WS('->', @XXX, 'TR:8');	
				/**********************************************************************************************************************************
					Zadekretowana operacja
				**********************************************************************************************************************************/
				IF NEW.handle_FROM IN ('OP') THEN
					SELECT n.zaksiegowana INTO @n.zaksiegowana FROM `opng_e` n WHERE n.GUID = NEW.GUID;
				ELSEIF NEW.handle_FROM IN ('R') THEN
					SELECT MAX(n.zaksiegowana) INTO @n.zaksiegowana FROM `opng_r_e` n WHERE n.Family_GUID = NEW.r_Family_GUID;
				ELSE
					SET @n.zaksiegowana = FALSE;
				END IF;
				
				IF @n.zaksiegowana != 0 THEN 
SET @XXX = concat_WS('->', @XXX, 'TR:8.1');	
					SET
                        NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, _res_str_get('ng_msg_Zadekretowana_operacja_warrning', ''))
						/*NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
							'Dokument ten został już zadekretowany i nie powinien być modyfikowany!', 
							'\n'
						)*/
					;
SET @XXX = concat_WS('->', @XXX, 'TR:8.2');	
					IF NOT NEW.handle_ReadOnly THEN
						SET @aUp = _GetUprawnienie('Mozliwosc_edycji_po_zadekr', '');
						SET @aUp_Mozliwosc_edycji_po_zadekr = @aUp;
					/*********************************************************************************************************
						Z ustaleń z ok. 16 Xi 2021
						@session.FK.IR.MozliwoscEdycjiDokZadekretowanego
						ma znaczenie "wykluczające" czyli 
						gdy = 0 to TYLKO DO ODCZYTU!!!!
						a gdy = 1 to sprawdzamy uprawnienia etc.
					*********************************************************************************************************/
						/* było SET NEW.handle_ReadOnly = (@aUp = 0); */
						SET 
							NEW.handle_ReadOnly = 
							--	gdy = 0 to TYLKO DO ODCZYTU!!!!
								NOT @session.FK.IR.MozliwoscEdycjiDokZadekretowanego
							--	gdy = 1 to decyduje  uprawnienie
								OR (@aUp = 0) 
						; 
						CALL _ng_e_rec_msg_ins('', 'A2', NEW.GUID, 'handle.AFTER', 
							IF(NEW.handle_ReadOnly, 
								CONCAT(
									-- patrz nizej _res_str_get('ng_msg_doc_ReadOnly', ''),
									_res_str_get('ng_msg_Zadekretowana_operacja_warrning', '')
								),
								CONCAT_WS('\n',
                                    _res_str_get('ng_msg_Zadekretowana_operacja_warrning', ''),
                                    _res_str_get('ng_msg_Zadekretowana_operacja_warrning2', '')
								)
							),
							IF(NEW.handle_ReadOnly, 
								'Warning', 
								'Msg'
							),
							IF(NEW.handle_ReadOnly, 
								'ReadOnly', 
								''
							),
							'', ''
						);
						
		-- {$IFDEF MozliwoscEdycjiDokZadekretowanego}
						IF NOT NEW.handle_ReadOnly THEN
							IF @session.FK.IR.MozliwoscEdycjiDokZadekretowanego THEN
								SET
                                    NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, _res_str_get('ng_msg_Zadekretowana_operacja_warrning2', ''))
									/*NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
										CONCAT(
											'Zmiany nie mogą dotyczyć:                        \n'
											' - wartość dokumentu \n',
											' - numeru dokumentu \n',
											' - numeru wewnętrznego \n',
											' - daty wpływu \n'
										), 
										'\n'
									)*/
								;
							END IF;
						END IF;
					ELSE
						CALL _ng_e_rec_msg_ins('', 'A2.1', NEW.GUID, 'handle.AFTER', 
							_res_str_get('ng_msg_Zadekretowana_operacja_warrning', ''),
							'Msg',
							'', 
							'', ''
						);
					END IF;
					
				END IF;
SET @XXX = concat_WS('->', @XXX, 'TR:8.3');	
				
				/**********************************************************************************************************************************
					Status dokumentu
				**********************************************************************************************************************************/
				IF TRUE THEN -- 
					/*
					IF (NEW.ui_status = @COpngStatus_PAKOWANA) AND
						(_GetUprawnienie('HT_opng_edycja_status_pakowanie') > 0) THEN   -- ToDo: sprawdzic czy to jest aktualne i kto tego uzywa
					*/
					-- IF NOT NEW.handle_ReadOnly THEN
SET @XXX = concat_WS('->', @XXX, 'TR:8.3.1');	
					IF TRUE THEN
						-- if (DataSet.FieldByName('Rodzaj').AsInteger in [CZmZP]) then -- nie ZM tylko Oper ((DataSet.FieldByName('status').AsInteger <> COPNG_Status_NONE) and (DataSet.FieldByName('status').AsInteger <> 18)) then//seba: 18 to przekazana [crm:25114]
						IF NEW.Rodzaj IN (@ht.CZmZP) THEN
							-- NEW.handle_ReadOnly = (not DBPlacesStatusZlecProd.CzyStatusEdycja(DataSet.FieldByName('status').AsInteger));//True;
							SELECT 
                                (s.ParamExtra = 'NoEdit') 
                            INTO 
                                @NEW.Status.handle_ReadOnly
							FROM `slowniki_pierwotne` s 
							WHERE s.Slownik_GUID = 'ZmZPStatus' AND s.VALUE = NEW.ui_status;
							/*
							UPDATE `slowniki_pierwotne` s
							SET
								NEW.handle_ReadOnly = (s.ParamExtra = 'NoEdit')
							WHERE Slownik_GUID = 'ZmZPStatus' AND s.VALUE = NEW.ui_status 
							;
							*/
						ELSEIF (NEW.optyp IN (@ht.ZM)) then
						  -- NEW.handle_ReadOnly = (not DBPlacesStatusZM.CzyStatusEdycja(DataSet.FieldByName('status').AsInteger));
							SELECT 
                                (s.ParamExtra = 'NoEdit') 
                            INTO 
                                @NEW.Status.handle_ReadOnly
							FROM `slowniki_pierwotne` s
							WHERE s.Slownik_GUID = 'zamwstatus' AND s.VALUE = NEW.ui_status;
							/*
							UPDATE `slowniki_pierwotne` s
							SET
								NEW.handle_ReadOnly = (s.ParamExtra = 'NoEdit')
							WHERE Slownik_GUID = 'zamwstatus' AND VALUE = NEW.ui_status 
							;
							*/
						ELSE
						  -- NEW.handle_ReadOnly = (not DBPlacesStatusOper.CzyStatusEdycja(DataSet.FieldByName('status').AsInteger));//True;
							SELECT 
                                (s.ParamExtra = 'NoEdit') 
                            INTO 
                                @NEW.Status.handle_ReadOnly
							FROM `slowniki_pierwotne` s
							WHERE s.Slownik_GUID = 'OperStatus' AND s.VALUE = NEW.ui_status;
							/*
							UPDATE `slowniki_pierwotne` s
							SET
								NEW.handle_ReadOnly = (s.ParamExtra = 'NoEdit')
							WHERE Slownik_GUID = 'OperStatus' AND VALUE = NEW.ui_status 
							;
							*/
						END IF;
						
						SET NEW.handle_ReadOnly = NEW.handle_ReadOnly OR @NEW.Status.handle_ReadOnly;
						

						/*
							if ReadOnly and not(____PrintNOW____) then -- slon
							  FormSupport.ShowMessage('UWAGA'+#13+'Ten dokument ma już status uniemożliwiający edycję');
						  end;
						*/
						IF @NEW.Status.handle_ReadOnly THEN
							CALL _ng_e_rec_msg_ins('', 'A4', NEW.GUID, 'handle.AFTER', 
								_res_str_get('ng_msg_Status_ReadOnly', ''),
								'Warning',
								'ReadOnly', 
								'', ''
							);
							SET
                                NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, _res_str_get('ng_msg_Status_ReadOnly', '')),
								/*NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
									'Ten dokument ma już status uniemożliwiający edycję', 
									'\n'
								),*/
                                NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_Status_ReadOnly', ''))
								/*(NEW.handle_ReadOnly_Msg = 'UWAGA\n Ten dokument ma już status uniemożliwiający edycję'*/
							;
						END IF;	
					END IF;
-- SET @XXX = concat_WS('->', @XXX, 'TR:8.3.2');	
				END IF;	--	Status dokumentu
			
				/**********************************************************************************************************************************
					Czy mam pozycje korygowane
				**********************************************************************************************************************************/
SET @XXX = concat_WS('->', @XXX, 'TR:8.4');	
				IF NEW.handle_FROM IN ('OP') THEN
-- SET @XXX = concat_WS('->', @XXX, 'TR:8.4.1');	
					SELECT 
						COUNT(*) AS C
					INTO 
                        @Ile_Korygowanych
					FROM `oppo` o
					INNER JOIN `oppo` k ON o.guid = k.guidkorpo
					WHERE 
						NOT(k.rodzaj IN (64, 65, 66, 70)) AND 
						o.idnoperfin = NEW.GUID
					;
-- SET @XXX = concat_WS('->', @XXX, 'TR:8.4.2');	
					SET @Ile_Korygowanych = IFNULL(@Ile_Korygowanych, 0);
					IF (@Ile_Korygowanych > 0) 
					THEN
SET @XXX = concat_WS('->', @XXX, 'TR:8.4.3');	
						IF (@session.globals.Owner IN ('BALTIMA')) AND (IFNULL(@session.Registration.Admin, IFNULL(@session.user.Admin, 0)))  --	gdy NIE ADMIN (dla Baltimy - tymczasowo bo docelowo musimy dać edycję i zapisywać wybiórczo kilka pól
						THEN
							SET 
								NEW.handle_ReadOnly = FALSE,
								NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_dokument_korygowany_Admin', ''))
							;						
							CALL _ng_e_rec_msg_ins('', 'A5', NEW.GUID, 'handle.AFTER', 
								_res_str_get('ng_msg_dokument_korygowany_Admin', ''),
								'Warning',
								'',  -- ReadOnly
								'', ''
							);												
						ELSE	
SET @XXX = concat_WS('->', @XXX, 'TR:8.4.4');	
							SET 
								NEW.handle_ReadOnly = TRUE,
								NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_dokument_korygowany_ReadOnly', ''))
							;
							
SET @XXX = concat_WS('->', @XXX, 'TR:8.4.5');	
							CALL _ng_e_rec_msg_ins('', 'A5', NEW.GUID, 'handle.AFTER', 
								_res_str_get('ng_msg_dokument_korygowany_ReadOnly', ''),
								'Warning',
								'ReadOnly',  
								'', ''
							);
SET @XXX = concat_WS('->', @XXX, 'TR:8.4.6');	
						END IF;
					END IF;
SET @XXX = concat_WS('->', @XXX, 'TR:8.4.9');	
				END IF;	--	Czy mam pozycje korygowane
			
				/**********************************************************************************************************************************
					Gdy jestem korekta - czy mam mlodsze pozycje korygujace ten sam oryginal?
				**********************************************************************************************************************************/
				SELECT IsKorekta INTO @_IsKorekta FROM `operdoc` WHERE rodzaj = NEW.Rodzaj;
				IF NEW.handle_FROM IN ('OP') AND @_IsKorekta != 0 THEN
					SELECT 
						COUNT(cprev.idn) AS cPosLater 
					INTO 
                        @cPosLater
					FROM `oppo_corr` c 
					LEFT JOIN `oppo_corr` cprev ON cprev.GUID_corr_prev = c.guid 
					WHERE  
						c.IdnOper_corr = NEW.GUID
					;
					SET @cPosLater = IFNULL(@cPosLater, 0);
					IF (@cPosLater > 0) 
					THEN
						IF (IFNULL(@session.Registration.Admin, IFNULL(@session.user.Admin, 0)))  --	gdy NIE ADMIN (dla Baltimy - tymczasowo bo docelowo musimy dać edycję i zapisywać wybiórczo kilka pól
						THEN
							SET 
								NEW.handle_ReadOnly = FALSE,
								NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_moj_oryginal_korygowany_Admin', ''))
							;						
							CALL _ng_e_rec_msg_ins('', 'A5', NEW.GUID, 'handle.AFTER', 
								-- na razie _res_str_get('ng_msg_dokument_korygowany_Admin', ''),
								NEW.handle_ReadOnly_Msg,
								'Warning',
								'',  -- ReadOnly
								'', ''
							);												
						ELSE	
							SET 
								NEW.handle_ReadOnly = TRUE,
								NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_moj_oryginal_korygowany_ReadOnly', ''))
							;
							
							CALL _ng_e_rec_msg_ins('', 'A5', NEW.GUID, 'handle.AFTER', 
								-- na razie _res_str_get('ng_msg_dokument_korygowany_ReadOnly', ''),
								NEW.handle_ReadOnly_Msg,
								'Warning',
								'ReadOnly',  
								'', ''
							);
						END IF;
					END IF;
				END IF;	--	Czy mam pozycje korygowane
			
SET @XXX = concat_WS('->', @XXX, 'TR:8.5');	
				
				/**********************************************************************************************************************************
					Sprawdz UPR
				**********************************************************************************************************************************/
				IF TRUE THEN -- _MODE = 'UPR' THEN
					SET 
						@NEW.handle_ReadOnly = NEW.handle_ReadOnly, 
						@NEW.u_ThisIsUserRecord = NEW.u_ThisIsUserRecord, 
						@NEW.u_rodzaj = NEW.u_rodzaj,
						@NEW.u_Msg = NEW.u_Msg
					;
					CALL _sys_upr_DefaultUprIsOK('AFTER', NEW.handle_oper, NEW.handle_ReadOnly, NEW.u_ThisIsUserRecord, @UpGREATEST, NEW.u_rodzaj, @_extCaption, NEW.u_OK, NEW.u_Msg);
					SET
						@1NEW.u_OK_XXX =  NEW.u_OK, 
						@1NEW.u_OK = NEW.u_OK, 
						@1NEW.u_Msg = NEW.u_Msg,
						@1Params = concat(NEW.handle_oper, ', ', NEW.handle_ReadOnly, ', ', NEW.u_ThisIsUserRecord, ', ', @UpGREATEST, ', ', NEW.u_rodzaj, ', ', @_extCaption, ', ', NEW.u_OK, ', ', NEW.u_Msg)
					;
					IF NOT NEW.u_OK AND NEW.handle_oper = 'EDIT' THEN
					--	nie wpuszcza w Edycje - SPRAWDZ czy moze wpusci na ReadOnly
						SET 
							NEW.handle_ReadOnly = 1,
							@NEW.handle_ReadOnly = 1
						;
						CALL _sys_upr_DefaultUprIsOK('AFTER', NEW.handle_oper, NEW.handle_ReadOnly, NEW.u_ThisIsUserRecord, @UpGREATEST, NEW.u_rodzaj, @_extCaption, NEW.u_OK, NEW.u_Msg);		
						IF NEW.u_OK THEN
							SET
								NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, _res_str_get('ng_msg_upr_edit', ''))
								/*NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
								'Uprawnienie nie pozwala zmieniac dokumentu (tylko ogladanie).', 
								'\n'
								)*/
							;
							CALL _ng_e_rec_msg_ins('', 'A6', NEW.GUID, 'handle.AFTER', 
								_res_str_get('ng_msg_upr_edit', ''),
								'Warning',
								'ReadOnly', 
								'', ''
							);
						END IF;
					END IF;
					-- 	@ht.doc.UprOK AS UprOK,
					-- 	@ht.doc.Upr_Msg AS Upr_Msg,
					
				END IF;	--	Sprawdz UPR

				IF NEW.handle_ReadOnly THEN
					SET
                        NEW.handle_Msg = CONCAT_WS('\n', NEW.handle_Msg, _res_str_get('ng_msg_doc_ReadOnly', '')),
                        NEW.handle_ReadOnly_Msg = CONCAT_WS('\n', NEW.handle_ReadOnly_Msg, _res_str_get('ng_msg_doc_ReadOnly', ''))
						/*NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
							'UWAGA !!!\n Dokument tylko do odczytu', 
							'\n'
						),
						NEW.handle_ReadOnly_Msg = CONCAT(NEW.handle_ReadOnly_Msg, '\n',
							'UWAGA\n Dokument tylko do odczytu'
						)*/
					;
					CALL _ng_e_rec_msg_ins('', 'A7', NEW.GUID, 'handle.AFTER', 
						_res_str_get('ng_msg_doc_ReadOnly', ''),
						'Warning',
						'ReadOnly', 
						'', ''
					);
				END IF;	
				
				-- SET _OK = @ht.doc.UprOK;
SET @XXX = concat_WS('->', @XXX, 'TR:8.6');	
			
			END IF;	--	EDIT
			
SET @XXX = concat_WS('->', @XXX, 'TR:9');	
			IF NOT NEW.u_OK THEN
				SET @X := '';
				CALL _ng_e_rec_msg_ins('ng_msg_upr', 'A8', NEW.GUID, 'handle.AFTER', 
					'',
					'Error', 
					'Stop', '', ''
				);

			END IF;
			
		END IF;	--	IF NEW.handle_check = 2 THEN
		
	
	END IF;	--	Gdy zmienil sie handle_check

	/*
	SET @session.trigger.ng_e_rec = FALSE;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	AU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `ng_e_rec_au`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `ng_e_rec_au` AFTER UPDATE ON `ng_e_rec` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	/*
	IF IFNULL(@session.trigger.ng_e_rec, FALSE) THEN 
		LEAVE A; 
	END IF;
	SET @session.trigger.ng_e_rec = TRUE;
	*/

	IF NEW.handle_FROM IN ('R', 'R') THEN
	/**********************************************************************************************************************************
		KASA BANK DOKUMENTY ROZRACHUNKOWE
	**********************************************************************************************************************************/
	
		IF NOT (NEW.r_nrraportu <=> OLD.r_nrraportu) OR  
			NOT (NEW.r_nrkasy <=> OLD.r_nrkasy) OR 
			NOT (NEW.r_datawystaw <=> OLD.r_datawystaw) OR 
			NOT (NEW.r_UgrpGUID <=> OLD.r_UgrpGUID) OR 
			NOT (NEW.r_RodzajDowodu <=> OLD.r_RodzajDowodu) 
		THEN
		/**********************************************************************************************************************************
			AFTER POST rodzinnej i pojedynczej - zapis/rozrzucenie danych naglowkowych do wszystkich dokumentow 
		**********************************************************************************************************************************/
			IF NEW.i_IsFamily AND IFNULL(NEW.r_Family_GUID, '') != '' THEN
				UPDATE `opng_r_e` n
				SET
					n.nrraportu = NEW.r_nrraportu,
					n.nrkasy = NEW.r_nrkasy,
					n.datawystaw = NEW.r_datawystaw,
					n.UgrpGUID = NEW.r_UgrpGUID,
					n.RodzajDowodu = NEW.r_RodzajDowodu
				WHERE
					n.Family_GUID = NEW.r_Family_GUID
				;
			END IF;
		END IF;
	END IF;
	
	/*
	SET @session.trigger.ng_e_rec = FALSE;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	BD
************************************************************************************************************************************************************************ */	


/* ************************************************************************************************************************************************************************
	AD
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `ng_e_rec_ad`$$
CREATE DEFINER = `root`@`localhost` TRIGGER `ng_e_rec_ad` AFTER DELETE ON `ng_e_rec` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;

	-- CALL _lock_inf_tool('UNLOCK', OLD.GUID, IF(OLD.handle_FROM != 'ZM', 'opng', 'zmng'), OLD.handle_UserGUID, @_ng_e_rec_init._Rec_Is_Locked, @_ng_e_rec_init.Msg, '', '1');
	/********************************************************
		Przy usuwaniu rekordu ze swiata E zawolaj to !!!
	*********************************************************/
	INSERT IGNORE INTO `_sys_msg` 
	(Src, Dest, DestCtx, DestCtxID, Msg, SendAt, con_ID, MsgDlg, MsgEffect)
	SELECT
		@SYSTEM.Client.Session.GUID AS Src,
		lck.LockSession AS Dest,
		IF(OLD.handle_FROM = 'ZM', 'EDIT.zmng_e', 'EDIT.opng_e') AS DestCtx, 
		lck.ID AS DestCtxID,
		(@.MSG := 'Operacja którą edytujesz nie jest już dostępna do edycji - została prawdopodobnie zamknięta z innego komputera.\nAby edytować tę oparację, ponownie wejdź w jej edycję.') AS Msg, 
		NOW() AS SendAt, CONNECTION_ID() AS con_ID,
		'Error' AS MsgDlg,
		'CLOSE' AS MsgEffect
	FROM `_locks` lck
	WHERE
		lck.Ctx = 'EDIT'
		AND lck.TableName = OLD.handle_TableName
		AND lck.ID = OLD.GUID
		AND lck.LockSession != @SYSTEM.Client.Session.GUID
	ON DUPLICATE KEY UPDATE 
		Msg = @.MSG, SendAt = NOW(), con_ID = CONNECTION_ID(), SendStatusInf = CONCAT_WS('->', SendStatusInf, IF(SendStatus = 'SEND', NULL, 'SEND')), SendStatus = 'SEND'
	;
	
	
END;
$$


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

DROP PROCEDURE IF EXISTS `_ng_e_rec_check`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_check`(
	IN _MODE VARCHAR(250),
	IN _FROM VARCHAR(250),
	IN _Key VARCHAR(38),
	IN _Rodzaj INTEGER,
	IN _Rodzaj_typ INTEGER,		
	INOUT _OK BOOLEAN,
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255)
)
/*
	przed edycją
	CALL doc_ng_check('before.edit', 'OP', _Key, _Rodzaj, _Rodzaj_typ, @_OK, '', '');
*/
S_doc_ng_check: BEGIN 

END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_msg_ins`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_msg_ins`(
	IN _MODE VARCHAR(250),	 --	PUSTY ale moze oznacza RES_ID stringu
	IN _ID VARCHAR(255),			--	ID komunikatu
	IN _GUID VARCHAR(38),			--	GUID dokumentu
	IN _Kind VARCHAR(255),			--	np. "Init", "BeforeApply"
	IN _Msg TEXT,
	IN _MsgDlg VARCHAR(255), 		--	np. "Msg", "Warning", "Error", "Ask"',
	IN _Effect VARCHAR(255),		--	np. "", "ReadOnly", "Stop", "?"',
	IN _Lang VARCHAR(255),		--	Lang
	IN _Param_A VARCHAR(255)
)
/*
	CALL _ng_e_rec_msg_ins('', '15', 'xxx', '', 'A teraz 3', NULL, NULL, '', '');
	CALL _ng_e_rec_msg_ins('', '55', 'xxx', '', 'A teraz 3', '', '', '', '');
	CALL _ng_e_rec_msg_ins('ng_msg_Zadekretowana_operacja_warrning2', '255', 'xxx', '', '', '', '', '', '');

*/
BEGIN 
	IF _ID = '' THEN
		SELECT COUNT(*) INTO _ID FROM `ng_e_rec_msg` WHERE GUID = _GUID AND Kind = _Kind;
	END IF;
	
	IF _MODE = '' THEN
		INSERT IGNORE INTO `ng_e_rec_msg`
		(`ID`, `GUID`, `Kind`, `Msg`, `MsgDlg`, `Effect`) 
		VALUES 
		(_ID, _GUID, IFNULL(_Kind, ''), _Msg, IF(IFNULL(_MsgDlg, '') = '', Default(`MsgDlg`), IFNULL(_MsgDlg, '')), _Effect) 
		;
	END IF;
	
	IF _MODE != '' THEN
		INSERT IGNORE INTO `ng_e_rec_msg`
		(`ID`, `GUID`, `Kind`, `Msg`, `MsgDlg`, `Effect`) 
		VALUES 
		(_ID, _GUID, IFNULL(_Kind, ''), _res_str_get(_MODE, _Lang), IF(IFNULL(_MsgDlg, '') = '', Default(`MsgDlg`), IFNULL(_MsgDlg, '')), _Effect) 
		;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_msg_clear`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_msg_clear`(
	IN _MODE VARCHAR(250),	 --	PUSTY ale moze oznacza RES_ID stringu
	IN _GUID VARCHAR(38),			--	GUID dokumentu
	IN _Kind VARCHAR(255),			--	np. "Init", "BeforeApply"
	IN _Param_A VARCHAR(255)
)
/*
	CALL _ng_e_rec_msg_clear('', 'xxx', 'Init', '');
	CALL _ng_e_rec_msg_clear('', 'xxx', 'BeforeApply', '');

*/
BEGIN 
	IF _MODE = 'ALL' THEN
		DELETE FROM `ng_e_rec_msg`
		WHERE
			GUID = _GUID
		;
	ELSE
		DELETE FROM `ng_e_rec_msg`
		WHERE
			GUID = _GUID AND Kind = _Kind
		;
	END IF;
--	usun z `_sys_msg` wszystkie dot. tego rekordu
	DELETE FROM `_sys_msg`
	WHERE
		DestLevel = 'SESSION'
		AND Dest = @SYSTEM.Client.Session.GUID
		AND DestCtx IN (_Kind, 'EDIT.zmng_e', 'EDIT.opng_e')
		AND DestCtxID = _GUID
	;
	-- select * from `_sys_msg`;
	
END$$

DROP PROCEDURE IF EXISTS `_ng_e_rec_msg_select`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_ng_e_rec_msg_select`(
	IN _MODE VARCHAR(250),	 --	PUSTY ale moze oznacza RES_ID stringu
	IN _GUID VARCHAR(38),			--	GUID dokumentu
	IN _Kind VARCHAR(255),			--	np. "Init", "BeforeApply"
	IN _Param_A VARCHAR(255)
)
/*
	CALL _ng_e_rec_msg_select('', 'xxx', 'Init', '');
	CALL _ng_e_rec_msg_select('', 'xxx', 'BeforeApply', '');

*/
BEGIN 
	IF _MODE LIKE '_sys_msg->%' THEN
		SET @.sm.SendStatus = IF(_MODE = '_sys_msg->CHECK', 'CHECK', 'READ');
		UPDATE `_sys_msg` sm, `ng_e_rec` ngr 
		SET 
			-- sm.SendStatusInf = CONCAT_WS('->', sm.SendStatusInf, IF(sm.SendStatusInf LIKE @.sm.SendStatus.LIKE, NULL, @.sm.SendStatus))
			sm.SendStatusInf = CONCAT_WS('->', sm.SendStatusInf, IF(sm.SendStatus = @.sm.SendStatus, NULL, @.sm.SendStatus)), 
			sm.SendStatus = @.sm.SendStatus,
			sm.ReadAt = IF(@.sm.SendStatus = 'READ', NOW(), sm.ReadAt)
		WHERE
			ngr.GUID = _GUID
			AND sm.DestLevel = 'SESSION'
			AND sm.Dest = @SYSTEM.Client.Session.GUID
			AND sm.DestCtx = IF(ngr.handle_FROM = 'ZM', 'EDIT.zmng_e', 'EDIT.opng_e')
			AND sm.DestCtxID = ngr.GUID
			AND sm.SendStatus != 'READ'
		;
	END IF;

	IF _MODE IN ('', 'ALL') THEN
	/* 
	było
	IF _MODE = 'ALL' THEN
		SELECT 
			nrm.* 
		FROM `ng_e_rec_msg` nrm
		WHERE
			nrm.GUID = _GUID
		;
	ELSE
		SELECT * FROM `ng_e_rec_msg`
		WHERE
			GUID = _GUID AND Kind = _Kind
		;
	END IF;
	*/
		CALL _ng_e_rec_msg_select('_sys_msg->CHECK', _GUID, '', '');
		SELECT 
			nrm.ID, nrm.GUID, nrm.Kind, nrm.Msg, nrm.MsgDlg, nrm.Effect, nrm.Response
		FROM `ng_e_rec_msg` nrm
		WHERE
			nrm.GUID = _GUID
			AND IF(_MODE != 'ALL', nrm.Kind = _Kind, TRUE)
		UNION
		SELECT 
			sm.ID AS ID, sm.DestCtxID AS GUID, 'INFO' AS Kind, sm.Msg, sm.MsgDlg, sm.MsgEffect, sm.Response
		FROM `_sys_msg` sm, `ng_e_rec` ngr 
		WHERE
			ngr.GUID = _GUID
			AND sm.DestLevel = 'SESSION'
			AND sm.Dest = @SYSTEM.Client.Session.GUID
			AND 
				IF(_MODE != 'ALL', 
					sm.DestCtx = _Kind,
					sm.DestCtx = IF(ngr.handle_FROM = 'ZM', 'EDIT.zmng_e', 'EDIT.opng_e')
				)
			-- AND sm.DestCtx = IF(ngr.handle_FROM = 'ZM', 'EDIT.zmng_e', 'EDIT.opng_e')
			AND sm.DestCtxID = ngr.GUID
			AND sm.SendStatus != 'READ'
		;
		CALL _ng_e_rec_msg_select('_sys_msg->READ', _GUID, '', '');
	END IF;
	
END$$


DELIMITER ;


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

SHOW CREATE TABLE `ng_e_rec_msg`;
DROP TABLE `ng_e_rec_msg`;
CREATE TABLE `ng_e_rec_msg` (
  `ID` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'ID komunikatu',
  `GUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'GUID dokumentu',
  `Kind` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'np. "Init", "BeforeApply"',
  `Msg` TEXT,
  `MsgDlg` VARCHAR(255) NOT NULL DEFAULT 'Msg' COMMENT 'np. "Msg", "Warning", "Error", "Ask"',
  `Effect` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'np. "", "ReadOnly", "Stop", "?"',
  `Response` VARCHAR(255) DEFAULT '',
  PRIMARY KEY (`GUID`,`ID`,`Kind`)
) DEFAULT CHARSET=cp1250
;

CALL _ng_e_rec_msg_ins('', '15', 'xxx', '', 'A teraz 3', NULL, NULL, '', '');
CALL _ng_e_rec_msg_ins('', '55', 'yyy', '', 'A teraz 3', '', '', '', '');
CALL _ng_e_rec_msg_ins('ng_msg_Zadekretowana_operacja_warrning2', '255', 'yyy', '', '', '', '', '', '');

CALL _ng_e_rec_msg_clear('', 'xxx', '', '');

CALL _ng_e_rec_msg_select('all', 'yyy', '', '');

SELECT * FROM `ng_e_rec_msg`;
SELECT COUNT(*) FROM `ng_e_rec_msg` WHERE IdnOper = 'xxx' AND Kind = 'z' INTO @_ID;
SELECT @_ID;

ALTER TABLE `ng_e_rec`   
  ADD COLUMN `i_IsFamily` INT(11) NOT NULL  COMMENT '0 pojedynczy, 1 rodzinny' AFTER `Need_Update`,
  ADD COLUMN `r_Family_GUID` VARCHAR(38) NOT NULL  COMMENT 'GUID spinajacy raporty, wyciagi, etc. Dla rap. kas. to bedzie GUID ost.BO' AFTER `i_IsFamily`,
  ADD COLUMN `r_nrraportu` VARCHAR(50) DEFAULT ''  NOT NULL  COMMENT 'wstawiany do nrraportu - wspolny dla rodziny' AFTER `r_Family_GUID`,
  ADD COLUMN `r_nrkasy` INT(11) NOT NULL  COMMENT 'jaka kasa, bank' AFTER `r_nrraportu`,
  ADD COLUMN `r_datawystaw` DATE NULL AFTER `r_nrkasy`,
  ADD COLUMN `r_UgrpGUID` VARCHAR(38) DEFAULT 'ALL'   NOT NULL AFTER `r_datawystaw`,
  ADD COLUMN `r_RodzajDowodu` VARCHAR(50) DEFAULT ''  NOT NULL  COMMENT 'wstawiany do nrraportu - wspolny do rodzaju dowodu' AFTER `r_UgrpGUID`
;


ALTER TABLE `ng_e_rec`   
  ADD COLUMN `handle_UserLogin` VARCHAR(100) NULL   COMMENT 'login usera/operatora' AFTER `handle_UserGUID`,
  ADD COLUMN `handle_UserUgrpGUID` VARCHAR(38) NULL   COMMENT 'ugrpGUID usera/operatora' AFTER `handle_UserLogin`
;

*/
