DELIMITER $$

DROP EVENT IF EXISTS `e_infoPiek_2_Int`$$
CREATE EVENT `e_infoPiek_2_Int`
	ON SCHEDULE EVERY 15 MINUTE 
	DO
	CALL infoPiek_2_Int('import', '', ''); 	-- Paragony
;	
$$

DROP EVENT IF EXISTS `e_POS_INT_2_POS`$$
CREATE EVENT `e_POS_INT_2_POS`
	ON SCHEDULE EVERY 30 MINUTE 
	DO
	--	PZki do POS-a
	CALL _POS_INT_2_POS('refresh.PZ', '', '3');		--	w _Param_A ile dni wstecz
;	
$$

DROP EVENT IF EXISTS `e_POS_POS_2_INT`$$
CREATE EVENT `e_POS_POS_2_INT`
	ON SCHEDULE EVERY 10 MINUTE 
	DO
	CALL _POS_POS_2_INT('refresh.ALL', '', '', '');
;	
$$


/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `oppo_e_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `oppo_e_bi` BEFORE INSERT ON `oppo_e` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;

	SET @transact.ISNewDoc = (IFNULL(NEW.IDN, 0) = 0);
	IF NOT @transact.ISNewDoc THEN
	/* *************************************************************************************************************************
		ładowany jako 'real.to.e' WYJDŹ
	************************************************************************************************************************* */
		LEAVE A;
	END IF;
	/* *************************************************************************************************************************
		Kreowany w swiecie 'e'
	************************************************************************************************************************* */
	IF IFNULL(NEW.IdnOper, '') != '' THEN
		SET @aDoIt = TRUE; -- @session.HT.IR.Wymus_przepisywanie_katcol_do_poz;
		UPDATE `opng_e` n
		SET
			n.IlePoz = @n.IlePoz := (n.IlePoz + 1),
			NEW.LP = @n.IlePoz,
			NEW.IdnOper_e = n.GUID,		--	tutaj docieramy tylko gdy tworzymy rekord (idn=0) - gdy wgrywamy z real to idn != 0 - jest to mozliwe w fvrudowz ale tylko gdy tworzymy wlasna pozycje uslugowa
			NEW.Tymczasowa = n.Tymczasowa,
			NEW.kontridn = n.kontridn,
			NEW.datawystaw = n.datawystaw,
			NEW.datasprzed = n.datasprzed,
			NEW.datawplywu = n.datawplywu,
			NEW.Ilosc = IFNULL(NEW.Ilosc, 1),
			NEW.rabat = IFNULL(NEW.rabat, 0),
			NEW.cenanet = IFNULL(NEW.cenanet, 0),
			-- NEW.IleOpakowan = 1,
			NEW.ilewopakowaniu = 1,
			NEW.rodzaj = n.rodzaj,
			NEW.rodzaj_typ = n.rodzaj_typ,
			NEW.kurs = n.kurs,
			NEW.ZMagazynu = n.ZMagazynu, 
			NEW.DoMagazynu = n.DoMagazynu,
			NEW.Calc_Ver = n.Calc_Ver,
			/*
			{$IFDEF MOSTOSTAL}
			  if (FieldByName('rodzaj').AsInteger in [CPzPZ, CMGZW, CPzPW, CRzRW, CRzKR]) then
			  begin
				if DBPlacesZlec.Shell.Locate('GUID',ShlNg.FieldByName('zlecenieGUID').asString, []) then
				  FieldByName('info').asString :=  DBPlacesZlec.Shell.FieldByName('nr_zlecenia').asString;
			  end;
			{$ENDIF}

			{$IFDEF NEW_CALC_OPPO}
			if ValidShlNg then
			  FieldByName('Rodzaj_Przeliczenia').AsInteger :=
				AskForRodzaj_Przeliczenia(ShlNg.CDS, DataSet) else
			  FieldByName('Rodzaj_Przeliczenia').AsInteger := CRodzaj_Przeliczenia_CenaNet_NettoWal;
			{$ELSE}
			FieldByName('Rodzaj_Przeliczenia').AsInteger := CRodzaj_Przeliczenia_CenaNet_NettoWal;
			{$ENDIF}

			*/
			NEW.TypSymbolow = IF(n.rodzaj = 73, 0, IFNULL(@transact.TypSymbolow, 0)), 	--	CZmZP = 73;      { Zamówienie - zlecenie produkcyjne }
			NEW.kat0 = IF(n.KatCol0 != -1 AND @aDoIt, n.KatCol0, NEW.kat0),
			NEW.kat1 = IF(n.KatCol1 != -1 AND @aDoIt, n.KatCol1, NEW.kat1),
			NEW.kat2 = IF(n.KatCol2 != -1 AND @aDoIt, n.KatCol2, NEW.kat2),
			NEW.kat3 = IF(n.KatCol3 != -1 AND @aDoIt, n.KatCol3, NEW.kat3),
			NEW.kat4 = IF(n.KatCol4 != -1 AND @aDoIt, n.KatCol4, NEW.kat4),
			NEW.cenanet = IF(NEW.opakowanie_zwrotne > 0, 0, NEW.cenanet)
			
		WHERE
			n.GUID = NEW.IdnOper
		;
	
		IF NEW.Rodzaj IN (@ht.CInwn, @ht.CInNW, @ht.CInND) AND
			((NEW.iloscbylo != 0) OR (NEW.iloscjest != 0)) THEN
			SET
				NEW.Ilosc = NEW.iloscjest - NEW.iloscbylo
			;
		END IF;
		
		SET
			@p.Rodzaj = NEW.Rodzaj,
			@p.ZMagazynu = NEW.ZMagazynu,
			@p.DoMagazynu = NEW.DoMagazynu
		;
		CALL e_oppo_ustal_magazyny_rodzaj('', @p.Rodzaj, @p.ZMagazynu, @p.DoMagazynu, NEW.Ilosc, NEW.WartNet);
		SET 
			NEW.Rodzaj = @p.Rodzaj, 
			NEW.ZMagazynu = @p.ZMagazynu, 
			NEW.DoMagazynu = @p.DoMagazynu
		;
		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);
	END IF;
	
	SET
		NEW.idnoperfin =  
			IF(IFNULL(NEW.idnwz, '') != '', 
				NEW.idnwz,
				NEW.idnoper
			)
	;	
	CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
	-- CALL ht_rodzaj_calc(NEW.Rodzaj);
	
	IF IFNULL(NEW.TowrSymb, '') = '' THEN
		UPDATE `TowrNg` t
		SET
			NEW.TowrSymb = t.Symbol, 
			NEW.TowrNazwa = t.Nazwa, 
			NEW.IdnVat = IFNULL(IF((t.VatPrevYear > 0) AND (@session.vat.edityear <= t.VatPrevYear), t.VatPrevId, t.Vat), 0),
			NEW.Jednostka = t.Jednostka,
			NEW.Usluga = t.Usluga,
			NEW.ilewopakowaniu = t.ilewopakowaniu,
			NEW.kat5 = t.katcol0,
			NEW.kat6 = t.katcol1,
			NEW.kat7 = t.katcol2,
			NEW.kat8 = t.katcol3,
			NEW.kat9 = t.katcol4,
			NEW.cena_minimalna = t.cena_minimalna,
			NEW.CenaNet = IF(NEW.Rodzaj IN (@ht.CInwn, @ht.CInNW, @ht.CInND), t.CenaZkpNet, NEW.CenaNet),
			NEW.pkwiu = t.pkwiu,
			NEW.termin_waznosci = DATE_ADD(CURRENT_DATE(), INTERVAL t.dni_waznosci DAY),
			NEW.opakowanie_zwrotne = t.opakowanie_zwrotne,
			NEW.waga_jedn = t.waga
		WHERE
			t.GUID = NEW.IdnTowr
		;
	END IF;
	SET NEW.GUIDzm = IFNULL(NEW.GUIDzm, '');
	
	SET NEW.wartNetWal = IFNULL(NEW.wartNetWal, 0);
	SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
	SET NEW.wartNet = IFNULL(NEW.wartNet, 0);
	SET NEW.wartBrt = IFNULL(NEW.wartBrt, 0);
	SET NEW.wartVat = IFNULL(NEW.wartVat, 0);
	
END;
$$

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

	IF NEW.Calc_Ver >= 3 THEN
		SELECT 
			n.Rodzaj, n.ZMagazynu, n.DoMagazynu, n.fvrudowz 
		FROM `opng_e` n 
		WHERE 
			n.GUID = NEW.IdnOper_e
		INTO 
			@n.Rodzaj, @n.ZMagazynu, @n.DoMagazynu, @n.fvrudowz
		;
		SET
			NEW.idnoperfin =  
				IF(IFNULL(NEW.idnwz, '') != '', 
					NEW.idnwz,
					NEW.idnoper
				),
			NEW.GUIDzm = IFNULL(NEW.GUIDzm, '')
		;	

		SET @transact.IS_Do_WZ = (@n.fvrudowz != 0) AND !(NEW.IdnOper <=> NEW.IdnOper_e);
		IF @transact.IS_Do_WZ THEN 
		/* *************************************************************************************************************************
			Jest to edycja podlaczonych WZ/PZ do FV
		**************************************************************************************************************************/
			IF 
				NOT(NEW.idnvat <=> OLD.idnvat)
				OR
				NOT(NEW.Rabat <=> OLD.Rabat)
				OR
				NOT(NEW.CenaNet <=> OLD.CenaNet)
				OR
				NOT(NEW.CenaNetWalzRab <=> OLD.CenaNetWalzRab)
				OR
				NOT(NEW.cenabrt <=> OLD.cenabrt)
				OR
				NOT(NEW.wartnetwal <=> OLD.wartnetwal)
				OR
				NOT(NEW.wartnet <=> OLD.wartnet)
				OR
				NOT(NEW.wartbrt <=> OLD.wartbrt)
				OR
				NOT(NEW.wartbrtwal <=> OLD.wartbrtwal)
			THEN
				CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
				IF NEW.IdnWZ = '' THEN
					SET
						NEW.idnvat = OLD.idnvat,
						NEW.Rabat = OLD.Rabat,
						NEW.CenaNet = OLD.CenaNet,
						NEW.CenaNetWalzRab = OLD.CenaNetWalzRab,
						NEW.cenabrt = OLD.cenabrt,
						NEW.wartnetwal = OLD.wartnetwal,
						NEW.wartnet = OLD.wartnet,
						NEW.wartbrt = OLD.wartbrt,
						NEW.wartbrtwal = OLD.wartbrtwal
					;
					LEAVE A; 
				ELSE
					CALL CalcXXPo('', 
						NEW.rodzaj_przeliczenia, NEW.IdnVat, NEW.Ilosc, NEW.Wspolplatnosc, NEW.Rabat, NEW.CenaNet, @.CenaNetPL, NEW.CenaNetWalzRab, NEW.CenaBrt, 
						NEW.WartNet, NEW.WartNetWal, @.StawkaVat, NEW.WartVat, NEW.WartBrt, NEW.WartBrtWal, @.WartBrtEdit, @.WartRabatNet, @.WartRabatBrt, 
						NEW.Kurs, NEW.Koszt_nabycia, NEW.StawkaCla, NEW.WartClo, @.WartNetWalEdit, NEW.Oplata_produktowa,
						NULL, NULL, -- było @ht.doc.IsKorekta, @ht.doc.IsWaluta,
						'', '', '', '')
					;
					SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
				END IF;
			END IF;
			
			LEAVE A; 
		END IF;
		
		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);

		SET @transact.IdnTowr.Change = NOT(IFNULL(NEW.IdnTowr, '') <=> IFNULL(OLD.IdnTowr, ''));
		SET @transact.Ilosc.Change = NOT(IFNULL(NEW.Ilosc, '') <=> IFNULL(OLD.Ilosc, ''));
		SET @transact.iloscjest.Change = NOT(IFNULL(NEW.iloscjest, '') <=> IFNULL(OLD.iloscjest, ''));
		SET @transact.iloscbylo.Change = NOT(IFNULL(NEW.iloscbylo, '') <=> IFNULL(OLD.iloscbylo, ''));
		
		SET @transact.WartNet.Change = NOT(IFNULL(NEW.WartNet, '') <=> IFNULL(OLD.WartNet, ''));

		
		/**************************************************************************************************************************
			Sprawdz `oppo_instancje_e` czy są egzemplarze
		**************************************************************************************************************************/
		IF NOT @ht.doc.IsKorekta AND NOT @transact.IS_Do_WZ THEN
			SET NEW.Ilosc = 
				IFNULL(
					(
						SELECT 
							SUM(Ilosc) AS Ilosc
						FROM `oppo_instancje_e`
						WHERE
							guid_oppo = NEW.GUID
					),
					NEW.Ilosc
			);
		END IF;
		
		
		/**************************************************************************************************************************
			Jeśli towar sie zmienił ...
		**************************************************************************************************************************/
		IF @transact.IdnTowr.Change THEN
			IF IFNULL(NEW.IdnTowr, '') != '' THEN 
				UPDATE `TowrNg` t
				SET
					NEW.TowrSymb = t.Symbol, 
					NEW.TowrNazwa = t.Nazwa, 
					NEW.IdnVat = IFNULL(IF((t.VatPrevYear > 0) AND (@session.vat.edityear <= t.VatPrevYear), t.VatPrevId, t.Vat), 0),
					NEW.Jednostka = t.Jednostka,
					NEW.Usluga = t.Usluga,
					NEW.ilewopakowaniu = t.ilewopakowaniu,
					NEW.kat5 = t.katcol0,
					NEW.kat6 = t.katcol1,
					NEW.kat7 = t.katcol2,
					NEW.kat8 = t.katcol3,
					NEW.kat9 = t.katcol4,
					NEW.cena_minimalna = t.cena_minimalna,
					NEW.CenaNet = IF(NEW.Rodzaj IN (@ht.CInwn, @ht.CInNW, @ht.CInND), t.CenaZkpNet, NEW.CenaNet),

					NEW.pkwiu = t.pkwiu,
					NEW.termin_waznosci = DATE_ADD(CURRENT_DATE(), INTERVAL t.dni_waznosci DAY),
					NEW.opakowanie_zwrotne = t.opakowanie_zwrotne,
					NEW.waga_jedn = t.waga
				WHERE
					t.GUID = NEW.IdnTowr
				;
			END IF;
		END IF;

		SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
		
		/**************************************************************************************************************************
			Sprawdz czy nie trzeba zmienic rodzaju!!!!!!!!!!!!!!!!!!
			Skoro zmieniono ilosc lub wart. netto	
		**************************************************************************************************************************/
		IF (@transact.Ilosc.Change OR @transact.iloscjest.Change OR @transact.iloscbylo.Change OR @transact.WartNet.Change) AND NOT @transact.IS_Do_WZ THEN

			IF @transact.iloscjest.Change OR @transact.iloscbylo.Change THEN
				SET
					NEW.Ilosc = NEW.iloscjest - NEW.iloscbylo
				;
			END IF;
			
			SET
				@p.Rodzaj = @n.Rodzaj,
				@p.ZMagazynu = @n.ZMagazynu,
				@p.DoMagazynu = @n.DoMagazynu
			;
			CALL e_oppo_ustal_magazyny_rodzaj('', @p.Rodzaj, @p.ZMagazynu, @p.DoMagazynu, NEW.Ilosc, NEW.WartNet);
			-- ??? CALL e_oppo_ustal_magazyny_rodzaj('', @_Rodzaj, @_ZMagazynu, @_DoMagazynu, NEW.Ilosc, NEW.WartNet);
			-- stare CALL e_oppo_rec_ustal_magazyny_rodzaj('', @p.Rodzaj, @p.ZMagazynu, @p.DoMagazynu, NEW.Ilosc, NEW.WartNet);
			SET 
				NEW.Rodzaj = @p.Rodzaj, 
				NEW.ZMagazynu = @p.ZMagazynu, 
				NEW.DoMagazynu = @p.DoMagazynu
			;
			-- CALL ht_rodzaj_calc(NEW.Rodzaj);
			-- CALL ht_rodzaj_calc(@n.Rodzaj);
			CALL ht_rodzaj_update_zmienne(@n.Rodzaj);
		END IF;
		
		SET NEW.waga = IF(IFNULL(NEW.Ilosc, 0) > 0, IFNULL(NEW.waga_jedn, 0) * IFNULL(NEW.Ilosc, 0), 0);
		
		/**************************************************************************************************************************
			Przelicz (calcOppo) jeśli to nie korekta
		**************************************************************************************************************************/
		IF NOT @ht.doc.IsKorekta AND NOT @transact.IS_Do_WZ THEN
			-- IF NOT @ht.doc.IsKorekta THEN
			CALL CalcXXPo('', 
				NEW.rodzaj_przeliczenia, NEW.IdnVat, NEW.Ilosc, NEW.Wspolplatnosc, NEW.Rabat, NEW.CenaNet, @.CenaNetPL, NEW.CenaNetWalzRab, NEW.CenaBrt, 
				NEW.WartNet, NEW.WartNetWal, @.StawkaVat, NEW.WartVat, NEW.WartBrt, NEW.WartBrtWal, @.WartBrtEdit, @.WartRabatNet, @.WartRabatBrt, 
				NEW.Kurs, NEW.Koszt_nabycia, NEW.StawkaCla, NEW.WartClo, @.WartNetWalEdit, NEW.Oplata_produktowa,
				NULL, NULL, -- było @ht.doc.IsKorekta, @ht.doc.IsWaluta,
				'', '', '', '')
			;
			SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
		END IF;
		
	ELSE
		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);

		-- SET @transact.IdnTowr.Change = IFNULL(NEW.IdnTowr, '') != IFNULL(OLD.IdnTowr, '');
		
		SET @transact.IdnTowr.Change = NOT(IFNULL(NEW.IdnTowr, '') <=> IFNULL(OLD.IdnTowr, ''));
		SET @transact.Ilosc.Change = NOT(IFNULL(NEW.Ilosc, '') <=> IFNULL(OLD.Ilosc, ''));
		
		SET @transact.WartNet.Change = NOT(IFNULL(NEW.WartNet, '') <=> IFNULL(OLD.WartNet, ''));

		SET
			NEW.idnoperfin =  
				IF(IFNULL(NEW.idnwz, '') != '', 
					NEW.idnwz,
					NEW.idnoper
				),
			NEW.GUIDzm = IFNULL(NEW.GUIDzm, '')
		;	
		
		--	Sprawdz `oppo_instancje_e` czy są egzemplarze
		
		IF NOT @ht.doc.IsKorekta THEN
			SET NEW.Ilosc = 
				IFNULL(
					(
						SELECT 
							SUM(Ilosc) AS Ilosc
						FROM `oppo_instancje_e`
						WHERE
							guid_oppo = NEW.GUID
					),
					NEW.Ilosc
			);
		END IF;
		
		
		IF @transact.IdnTowr.Change THEN
			IF IFNULL(NEW.IdnTowr, '') != '' THEN 
				UPDATE `TowrNg` t
				SET
					NEW.TowrSymb = t.Symbol, 
					NEW.TowrNazwa = t.Nazwa, 
					NEW.IdnVat = IFNULL(IF((t.VatPrevYear > 0) AND (@session.vat.edityear <= t.VatPrevYear), t.VatPrevId, t.Vat), 0),
					NEW.Jednostka = t.Jednostka,
					NEW.Usluga = t.Usluga,
					NEW.ilewopakowaniu = t.ilewopakowaniu,
					NEW.kat5 = t.katcol0,
					NEW.kat6 = t.katcol1,
					NEW.kat7 = t.katcol2,
					NEW.kat8 = t.katcol3,
					NEW.kat9 = t.katcol4,
					NEW.cena_minimalna = t.cena_minimalna,
					NEW.pkwiu = t.pkwiu,
					NEW.termin_waznosci = DATE_ADD(CURRENT_DATE(), INTERVAL t.dni_waznosci DAY),
					NEW.opakowanie_zwrotne = t.opakowanie_zwrotne,
					NEW.waga_jedn = t.waga
				WHERE
					t.GUID = NEW.IdnTowr
				;
			END IF;
		END IF;

		SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
		
		/**************************************************************************************************************************
		Sprawdz czy nie trzeba zmienic rodzaju!!!!!!!!!!!!!!!!!!
		Skoro zmieniono ilosc lub wart. netto	
		**************************************************************************************************************************/
		IF @transact.Ilosc.Change OR @transact.WartNet.Change THEN
			SELECT 
				n.Rodzaj, n.ZMagazynu, n.DoMagazynu 
			FROM `opng_e` n 
			WHERE 
				n.GUID = NEW.IdnOper 
			INTO 
				@n.Rodzaj, @n.ZMagazynu, @n.DoMagazynu
			;
			-- SET @n.Rodzaj = NEW.Rodzaj; -- , @n.ZMagazynu = NEW.ZMagazynu, @n.DoMagazynu = NEW.DoMagazynu;
			SET
				@p.Rodzaj = @n.Rodzaj,
				@p.ZMagazynu = @n.ZMagazynu,
				@p.DoMagazynu = @n.DoMagazynu
			;
			CALL e_oppo_rec_ustal_magazyny_rodzaj('', @p.Rodzaj, @p.ZMagazynu, @p.DoMagazynu, NEW.Ilosc, NEW.WartNet);
			SET 
				NEW.Rodzaj = @p.Rodzaj, 
				NEW.ZMagazynu = @p.ZMagazynu, 
				NEW.DoMagazynu = @p.DoMagazynu
			;
			-- CALL ht_rodzaj_calc(NEW.Rodzaj);
			-- CALL ht_rodzaj_calc(@n.Rodzaj);
			CALL ht_rodzaj_update_zmienne(@n.Rodzaj);
		END IF;
		
		SET NEW.waga = IF(IFNULL(NEW.Ilosc, 0) > 0, IFNULL(NEW.waga_jedn, 0) * IFNULL(NEW.Ilosc, 0), 0);
		
		IF NOT @ht.doc.IsKorekta THEN
			-- IF NOT @ht.doc.IsKorekta THEN
			SET @jmam = true;
			CALL CalcXXPo('', 
				NEW.rodzaj_przeliczenia, NEW.IdnVat, NEW.Ilosc, NEW.Wspolplatnosc, NEW.Rabat, NEW.CenaNet, @.CenaNetPL, NEW.CenaNetWalzRab, NEW.CenaBrt, 
				NEW.WartNet, NEW.WartNetWal, @.StawkaVat, NEW.WartVat, NEW.WartBrt, NEW.WartBrtWal, @.WartBrtEdit, @.WartRabatNet, @.WartRabatBrt, 
				NEW.Kurs, NEW.Koszt_nabycia, NEW.StawkaCla, NEW.WartClo, @.WartNetWalEdit, NEW.Oplata_produktowa,
				NULL, NULL, -- było @ht.doc.IsKorekta, @ht.doc.IsWaluta,
				'', '', '', '');
			SET NEW.wartBrtWal = IFNULL(NEW.wartBrtWal, 0);
			/*	
			CALL CalcPo('', 
				NEW.rodzaj_przeliczenia, NEW.IdnVat, NEW.Ilosc, NEW.Wspolplatnosc, NEW.Rabat, NEW.CenaNet, @.CenaNetPL, NEW.CenaNetWalzRab, NEW.CenaBrt, 
				NEW.WartNet, NEW.WartNetWal, @.StawkaVat, NEW.WartVat, NEW.WartBrt, @.WartBrtEdit, @.WartRabatNet, @.WartRabatBrt, 
				NEW.Kurs, NEW.Koszt_nabycia, NEW.StawkaCla, NEW.WartClo, @.WartNetWalEdit, NEW.Oplata_produktowa,
				@ht.doc.IsKorekta, @ht.doc.IsWaluta,
				'', '', '', '');
			*/	
		END IF;
		
		
	END IF;		--	PO Staremu NEW.Calc_Ver < 3
	SET @session.oppo_e = FALSE;
END;
$$


/* ************************************************************************************************************************************************************************
	Narzędzia  triggera `oppo_e`
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `e_oppo_ustal_magazyny_rodzaj`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `e_oppo_ustal_magazyny_rodzaj`(
	IN _MODE VARCHAR(250),
	INOUT _Rodzaj INTEGER,			--	rodzaj z nagłówka
	INOUT _ZMagazynu INTEGER,		--	ZMagazynu z nagłówka		
	INOUT _DoMagazynu INTEGER,		--	DoMagazynu z nagłówka
	IN _Ilosc DECIMAL(16,6),
	IN _WartNet DECIMAL(16,6)
)
/*
	CALL e_oppo_ustal_magazyny_rodzaj('', @_Rodzaj, @_ZMagazynu, @_DoMagazynu, @_Ilosc, @_WartNet);
*/
S_e_oppo_ustal_magazyny_rodzaj: BEGIN 
	DECLARE N_Rodzaj INTEGER;
	SET N_Rodzaj = _Rodzaj;
	
	SELECT
		IF(od.MA_Magzyny,
			IF(od.IsKorekta,
			--	Korekta
				IF((_Ilosc > 0.0) OR (_WartNet > 0),
					od.AntyRodzaj,
					_Rodzaj
				),
			--	NIE Korekta
				IF(_Rodzaj IN (@ht.CInwn, @ht.CInNW, @ht.CInND),
					IF(_Ilosc >= 0.0, @ht.CInNW, @ht.CInND),
					IF(_Rodzaj IN (@ht.CZmZP),
						@ht.CZM_ZP1,
						_Rodzaj
					)
				)
			),	
			_Rodzaj
		) AS Rodzaj	
	FROM `operdoc` od
	WHERE
		od.rodzaj = _Rodzaj
	INTO 
		N_Rodzaj
	;
	
	SET 
		@_ZMagazynu = _ZMagazynu, @_DoMagazynu = _DoMagazynu,
		_Rodzaj = N_Rodzaj
	;
	SELECT
		_VarInt(
			CASE 
		/*RZ*/	WHEN od.MagTyp = @ht.mtRZ THEN IF(@_ZMagazynu > 0, @_ZMagazynu, @_DoMagazynu) 
		/*PZ*/	WHEN od.MagTyp = @ht.mtPZ THEN 0
		/*MM*/	WHEN od.MagTyp = @ht.mtMM THEN IF(@_ZMagazynu > 0, @_ZMagazynu, @_DoMagazynu) 
		/*NN*/	ELSE 0
			END
		) AS _ZMagazynu,
		_VarInt(
			CASE 
		/*RZ*/	WHEN od.MagTyp = @ht.mtRZ THEN 0
		/*PZ*/	WHEN od.MagTyp = @ht.mtPZ THEN IF(@_DoMagazynu > 0, @_DoMagazynu, @_ZMagazynu) 
		/*MM*/	WHEN od.MagTyp = @ht.mtMM THEN IF(@_DoMagazynu > 0, @_DoMagazynu, @_ZMagazynu) 
		/*NN*/	ELSE 0
			END
		) AS _DoMagazynu
	FROM `operdoc` od
	WHERE
		od.rodzaj = N_Rodzaj
	INTO 
		_ZMagazynu, _DoMagazynu
	;
	
	LEAVE S_e_oppo_ustal_magazyny_rodzaj;
	
END$$


/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `opng_e_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `opng_e_bi` BEFORE INSERT ON `opng_e` FOR EACH ROW 
S_opng_e_bi: BEGIN
		IF _GetVer() = '5.1.30' THEN LEAVE S_opng_e_bi; END IF;
	--	wartosc @session.trigger_lock rowna TRUE blokuje wykonanie triggera
		IF IFNULL(@session.trigger_lock, FALSE) THEN LEAVE S_opng_e_bi; END IF;
		
	IF NEW.Calc_Ver >= 3 THEN
	
		DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_trigg_operdoc` LIKE `operdoc`;
		INSERT INTO `t_trigg_operdoc` SELECT * FROM `operdoc`;

		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);

		IF @ht.doc.MA_Magzyny THEN
			IF (@ht.doc.MagTyp = @ht.mtRZ) THEN
				SET NEW.DoMagazynu = 0;
			END IF;	
			IF (@ht.doc.MagTyp = @ht.mtPZ) THEN
				SET NEW.ZMagazynu = 0;
			END IF;	
		ELSE		
			SET 
				NEW.ZMagazynu = 0, 
				NEW.DoMagazynu = 0
			;
		END IF;
		
		--  CALL e_opng_rec_ustal_magazyny('', NEW.Rodzaj, NEW.ZMagazynu, NEW.DoMagazynu);
		
		SET
			@ng.f.Brutto = IFNULL(NEW.Brutto,	0),	
			
			-- @ng.f.CKwota,		
			-- @ng.f.CKwotaWal,		
			-- @ng.f.CWN,		
			-- @ng.f.CRozliczone,		
			-- @ng.f.Kurs_rozliczen,		
			-- @ng.f.gruparozrach,		
			@ng.f.gruparozrach_wymus = IFNULL(NEW.gruparozrach_wymus, 0),		
			@ng.f.Waluta = IFNULL(NEW.Waluta,	0)
		;	
		
		
		-- UPDATE `t_ht_ngcalc` t
		SET @transact.ISNewDoc = (IFNULL(NEW.IDN, 0) = 0);
		IF @transact.ISNewDoc THEN

			/*
			SELECT 
				d.IsRozrachunek,
				@ng.f.grupaoper := d.Grupa,	-- ??? 
				d.wzordekr,
				d.rv_id, 
				d.RodzajDowodu,
				d.ugrpGUID,
				IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0),
				IF(d.MagTyp = @ht.mtRZ, 0, NEW.DoMagazynu),
				IF(d.MagTyp = @ht.mtPZ, 0, NEW.ZMagazynu)
			FROM `operdoc` d
			WHERE
				d.Rodzaj = NEW.Rodzaj
			INTO
				NEW.rozrachunek,
				NEW.grupaoper,
				NEW.wzordekr,
				NEW.rv_id, 
				NEW.RodzajDowodu,
				NEW.ugrpGUID,
				NEW.gruparozrach,
				NEW.DoMagazynu,
				NEW.ZMagazynu
			;
			*/
			/**/
			UPDATE `t_trigg_operdoc` d
			SET
				NEW.rozrachunek = d.IsRozrachunek,
				NEW.grupaoper = @ng.f.grupaoper := d.Grupa,
				NEW.wzordekr = d.wzordekr,
				NEW.rv_id = d.rv_id, 
				NEW.RodzajDowodu = d.RodzajDowodu,
				NEW.ugrpGUID = d.ugrpGUID,
				NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0),
				
				NEW.DoMagazynu = IF(d.MagTyp = @ht.mtRZ, 0, NEW.DoMagazynu),
				NEW.ZMagazynu = IF(d.MagTyp = @ht.mtPZ, 0, NEW.ZMagazynu)
				
			WHERE
				d.Rodzaj = NEW.Rodzaj
			;
			/**/
			SET
				NEW.idnuser = IFNULL(@session.Registration.IdnUser, @session.CheckLogonUserLogin),
				NEW.ugrpGUID = IFNULL(@session.user.CurrugrpGUID, IFNULL(NEW.ugrpGUID, 'ALL')),
				NEW.Deleted = IFNULL(NEW.Deleted, 0),
				NEW.ilepoz = IFNULL(NEW.ilepoz, 0),
				--	Daty
				NEW.DataWystaw = IFNULL(NEW.DataWystaw, CURRENT_DATE()),
				NEW.DataSprzed = IFNULL(NEW.DataSprzed, CURRENT_DATE()),
				NEW.DataWplywu = IFNULL(NEW.DataWplywu, CURRENT_DATE()),
				NEW.data_vat = IFNULL(NEW.data_vat, CURRENT_DATE()),
				NEW.DataWaluty = IFNULL(NEW.DataWaluty, CURRENT_DATE()),
				NEW.DataPlatnosci = IFNULL(NEW.DataPlatnosci, CURRENT_DATE()),
				NEW.dataplatnosci_oczekiwana = IFNULL(NEW.dataplatnosci_oczekiwana, CURRENT_DATE()),
				
				NEW.kurs_rozliczen = IFNULL(NEW.kurs_rozliczen, 1),
				
				NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				
			;	
			
			SET	NEW.data_vat = IF(NEW.data_vat='0000-00-00',CURRENT_DATE(), NEW.data_vat);

			SET NEW.DataPlatnosci = _GetDataPlatnosci(NEW.datawystaw, NEW.sposobplatn);
			SET NEW.dataplatnosci_oczekiwana = _GetDataPlatnosci_oczekiwana(NEW.DataPlatnosci, NEW.datawplywu);
		
			SET NEW.rozrachunek = IFNULL(NEW.rozrachunek, 0);
			
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				Rozrachunki
			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			SET NEW.NettoDoRozrach = 0;  -- domyslnie od Brutto do rozrach
			/*
			1. uwaga inicjuj waluta_rozliczen na waluta !!!!!!!!!!!!
			2. Inicjacja nastepuje gdy wpiszemu w UPDATE `opng_e` SET Tag = -1; !!! wtedy w triggerze zosstanie zainicjowana na 0 lub 1
			PATRZ update i @transact.Is_Inicjacja
			*/
			IF NEW.rozrachunek THEN
				-- CALL rozrach_rodzaj_calc(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Brutto);
			CALL _Rozrach_Nalicz_Pola(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Netto, NEW.NettoWal, NEW.Brutto, NEW.BruttoWal, NEW.NettoDoRozrach,
				NEW.Zaplacono, 
				NEW.Kurs,
				NEW.Kurs_rozliczen,
				NEW.CWN,
				NEW.CKwota,
				NEW.CKwotaWal,
				NEW.CRozliczone,
				NEW.CRozliczoneWal,
				NEW.nierozliczony,
				'', '', '', '');
				
			END IF;	
			
			

		END IF;		--	NOWE czyli @transact.ISNewDoc

   
		SET NEW.akcept_platn_uwagi = IFNULL(NEW.akcept_platn_uwagi, 0);
		
		DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
	ELSE	--	PO NOWEMU
	--	po staremu
		
		DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_trigg_operdoc` LIKE `operdoc`;
		INSERT INTO `t_trigg_operdoc` SELECT * FROM `operdoc`;

		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);

		CALL e_opng_rec_ustal_magazyny('', NEW.Rodzaj, NEW.ZMagazynu, NEW.DoMagazynu);
		
		SET
			@ng.f.Brutto = IFNULL(NEW.Brutto,	0),	
			
			-- @ng.f.CKwota,		
			-- @ng.f.CKwotaWal,		
			-- @ng.f.CWN,		
			-- @ng.f.CRozliczone,		
			-- @ng.f.Kurs_rozliczen,		
			-- @ng.f.gruparozrach,		
			@ng.f.gruparozrach_wymus = IFNULL(NEW.gruparozrach_wymus, 0),		
			@ng.f.Waluta = IFNULL(NEW.Waluta,	0)
		;	
		
		
		-- UPDATE `t_ht_ngcalc` t
		SET @transact.ISNewDoc = (IFNULL(NEW.IDN, 0) = 0);
		IF @transact.ISNewDoc THEN

			UPDATE `t_trigg_operdoc` d
			SET
				NEW.rozrachunek = d.IsRozrachunek,
				NEW.grupaoper = @ng.f.grupaoper := d.Grupa,
				NEW.wzordekr = d.wzordekr,
				NEW.rv_id = d.rv_id, 
				NEW.RodzajDowodu = d.RodzajDowodu,
				NEW.ugrpGUID = d.ugrpGUID,
				NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				
			WHERE
				d.Rodzaj = NEW.Rodzaj
			;
			SET
				NEW.idnuser = IFNULL(@session.Registration.IdnUser, @session.CheckLogonUserLogin),
				NEW.ugrpGUID = IFNULL(@session.user.CurrugrpGUID, ''),
				NEW.Deleted = IFNULL(NEW.Deleted, 0),
				NEW.ilepoz = IFNULL(NEW.ilepoz, 0),
				--	Daty
				NEW.DataWystaw = IFNULL(NEW.DataWystaw, CURRENT_DATE()),
				NEW.DataSprzed = IFNULL(NEW.DataSprzed, CURRENT_DATE()),
				NEW.DataWplywu = IFNULL(NEW.DataWplywu, CURRENT_DATE()),
				NEW.data_vat = IFNULL(NEW.data_vat, CURRENT_DATE()),
				NEW.DataWaluty = IFNULL(NEW.DataWaluty, CURRENT_DATE()),
				NEW.DataPlatnosci = IFNULL(NEW.DataPlatnosci, CURRENT_DATE()),
				NEW.dataplatnosci_oczekiwana = IFNULL(NEW.dataplatnosci_oczekiwana, CURRENT_DATE()),
				
				NEW.kurs_rozliczen = IFNULL(NEW.kurs_rozliczen, 1),
				
				/*
-- jmam 				NEW.rozrachunek = @ht.doc.IsRozrachunek,
				NEW.grupaoper = @ng.f.grupaoper := @ht.doc.Optyp,
				NEW.wzordekr = @ht.doc.wzordekr,
				NEW.rv_id = @ht.doc.rv_id, 
				NEW.RodzajDowodu = @ht.doc.RodzajDowodu,
				NEW.ugrpGUID = @ht.doc.ugrpGUID,
				*/
				NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				
			;	
			SET	NEW.data_vat = IF(NEW.data_vat='0000-00-00',CURRENT_DATE(), NEW.data_vat);
			
		END IF;
		
		SET NEW.rozrachunek = IFNULL(NEW.rozrachunek, 0);
		SET NEW.akcept_platn_uwagi = IFNULL(NEW.akcept_platn_uwagi, 0);
	END IF;		--	PO Staremu
END;
$$

/* ************************************************************************************************************************************************************************
	AI
************************************************************************************************************************************************************************ */	

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `opng_e_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `opng_e_bu` BEFORE UPDATE ON `opng_e` FOR EACH ROW 
S_opng_e_bu: BEGIN

	IF _TriggerDisabled() THEN LEAVE S_opng_e_bu; END IF;
	

	IF NEW.Calc_Ver >= 3 THEN
	
		DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_trigg_operdoc` LIKE `operdoc`;
		INSERT INTO `t_trigg_operdoc` SELECT * FROM `operdoc`;
		CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
		SET
			@transact.Is_Inicjacja = !(NEW.tag <=> NEW.tag) AND (NEW.tag < 0),
			@transact.Rodzaj.Change = !(NEW.Rodzaj <=> OLD.Rodzaj),
			@transact.Mag1.Change = !(NEW.ZMagazynu <=> OLD.ZMagazynu),
			@transact.Mag2.Change = !(NEW.DoMagazynu <=> OLD.DoMagazynu)
		;
		
		
		-- CALL ht_rodzaj_calc(NEW.Rodzaj);
		IF @transact.Mag1.Change OR @transact.Mag2.Change THEN
			/*
			SELECT
				IF(d.MagTyp = @ht.mtRZ, 0, NEW.DoMagazynu),
				IF(d.MagTyp = @ht.mtPZ, 0, NEW.ZMagazynu)
			FROM `operdoc` d
			WHERE
				d.Rodzaj = NEW.Rodzaj
			INTO
				NEW.DoMagazynu,
				NEW.ZMagazynu
			;
			*/
			/**/
			UPDATE `t_trigg_operdoc` d
			SET
				NEW.DoMagazynu = IF(d.MagTyp = @ht.mtRZ, 0, NEW.DoMagazynu),
				NEW.ZMagazynu = IF(d.MagTyp = @ht.mtPZ, 0, NEW.ZMagazynu)
			WHERE
				d.Rodzaj = NEW.Rodzaj
			;
			/**/
		END IF;
		
		SET @NEW.DoMagazynu = NEW.DoMagazynu;
		SET @NEW.ZMagazynu = NEW.ZMagazynu;
		SET @ng.f.tag = NEW.tag;
		
		SET @transact.ISNewDoc = (IFNULL(NEW.IDN, 0) = 0);
		IF @transact.ISNewDoc THEN

			IF NEW.Rodzaj_typ = -1 THEN
				SET NEW.Rodzaj_typ = 0;
			END IF;
			
			IF @transact.Rodzaj.Change THEN
				/*
				SELECT 
					d.IsRozrachunek,
					@ng.f.grupaoper := d.Grupa,	-- ??? 
					d.wzordekr,
					d.rv_id, 
					d.RodzajDowodu,
					d.ugrpGUID,
					IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				FROM `operdoc` d
				WHERE
					d.Rodzaj = NEW.Rodzaj
				INTO
					NEW.rozrachunek,
					NEW.grupaoper,
					NEW.wzordekr,
					NEW.rv_id, 
					NEW.RodzajDowodu,
					NEW.ugrpGUID,
					NEW.gruparozrach
				;
				*/
				/**/
				UPDATE `t_trigg_operdoc` d
				SET
					NEW.rozrachunek = d.IsRozrachunek,
					NEW.grupaoper = @ng.f.grupaoper := d.Grupa,
					NEW.wzordekr = d.wzordekr,
					NEW.rv_id = d.rv_id, 
					NEW.RodzajDowodu = d.RodzajDowodu,
					NEW.ugrpGUID = d.ugrpGUID,
					NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				WHERE
					d.Rodzaj = NEW.Rodzaj
				;
				SET @Watch = 'UPDATE `t_trigg_operdoc` d';
				/**/
			END IF;
			
			SET
				NEW.idnuser = IFNULL(@session.Registration.IdnUser, @session.CheckLogonUserLogin),
				NEW.ugrpGUID = IFNULL(@session.user.CurrugrpGUID, ''),
				NEW.Deleted = IFNULL(NEW.Deleted, 0),
				NEW.ilepoz = IFNULL(NEW.ilepoz, 0),
				--	Daty
				NEW.DataWystaw = IFNULL(NEW.DataWystaw, CURRENT_DATE()),
				NEW.DataSprzed = IFNULL(NEW.DataSprzed, CURRENT_DATE()),
				NEW.DataWplywu = IFNULL(NEW.DataWplywu, CURRENT_DATE()),
				NEW.data_vat = IFNULL(NEW.data_vat, CURRENT_DATE()),
				NEW.DataWaluty = IFNULL(NEW.DataWaluty, CURRENT_DATE()),
				NEW.DataPlatnosci = IFNULL(NEW.DataPlatnosci, CURRENT_DATE()),
				NEW.dataplatnosci_oczekiwana = IFNULL(NEW.dataplatnosci_oczekiwana, CURRENT_DATE()),
				
				NEW.kurs_rozliczen = IFNULL(NEW.kurs_rozliczen, 1),
				/*
	-- jmam			NEW.rozrachunek = @ht.doc.IsRozrachunek,
				NEW.grupaoper = @ng.f.grupaoper := @ht.doc.Optyp,
				NEW.wzordekr = @ht.doc.wzordekr,
				NEW.rv_id = @ht.doc.rv_id, 
				NEW.RodzajDowodu = @ht.doc.RodzajDowodu,
				NEW.ugrpGUID = @ht.doc.ugrpGUID,
				*/
				NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
				
			;	
			SET	NEW.data_vat = IF(NEW.data_vat='0000-00-00',CURRENT_DATE(), NEW.data_vat);

		END IF;
		--	Daty
		SET
			NEW.dataplatnosci_oczekiwana = 
				IF(@session.globals.Owner = 'RELACOM',
					DATE_ADD(NEW.datawplywu, INTERVAL @session.HT.IR.DniPowiekszeniaDatyPlatnosciOczekiwanej DAY),
					NEW.dataplatnosci
				)	
			
		;	
		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
			NEW.Waluta
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		SET @transact.WalutaChanged = !(NEW.Waluta <=> OLD.Waluta);
		IF @transact.WalutaChanged OR @transact.Is_Inicjacja THEN
			IF (NEW.Kurs <=> OLD.Kurs) THEN	--	skoro kurs sie nie zmienia to w JEDNYM Update mamy tylko zmiane waluty (bez kursu) a to oznacza że musimy pobrać Kurs
				SELECT Kurs FROM `kursy_calc` WHERE idnwaluty1 = NEW.Waluta AND idnwaluty2 = 0 LIMIT 1 INTO @NEW.Kurs;
				SET NEW.Kurs = IFNULL(@NEW.Kurs, 1);
			END IF;
			IF NEW.Waluta_Rozliczen < 0 THEN
				SET NEW.Waluta_Rozliczen = NEW.Waluta;
			END IF;
		END IF;

		SET @transact.Waluta_RozliczenChanged = !(NEW.Waluta_Rozliczen <=> OLD.Waluta_Rozliczen);
		IF @transact.Waluta_RozliczenChanged OR @transact.Is_Inicjacja THEN
			IF (NEW.Kurs_Rozliczen <=> OLD.Kurs_Rozliczen) THEN	--	skoro Kurs_Rozliczen sie nie zmienia to w JEDNYM Update mamy tylko zmiane Waluta_Rozliczen (bez Kurs_Rozliczen) a to oznacza że musimy pobrać Kurs
				SELECT Kurs FROM `kursy_calc` WHERE idnwaluty1 = NEW.Waluta_Rozliczen AND idnwaluty2 = 0 LIMIT 1 INTO @NEW.Kurs;
				SET NEW.Kurs_Rozliczen = IFNULL(@NEW.Kurs, 1);
			END IF;
		END IF;
		

		IF @transact.Is_Inicjacja THEN
			SET NEW.NettoDoRozrach = 0;
			-- UWAGA Dorobic rowniez dla PLN
			-- do zatwierdzenia przez jmam po powrocie z wkacji
			IF NEW.waluta_rozliczen > 0 THEN	--	Dla dokumentow w walucie obcej
				SELECT NettoDoRozrachWal FROM `operdoc` WHERE rodzaj = NEW.Rodzaj INTO @NEW.NettoDoRozrachWal;
				SET NEW.NettoDoRozrach = IFNULL(@NEW.NettoDoRozrachWal, 0);

				
			/*
				 IF NOT (((@ht.doc.Optyp IN (@ht.ST, IF(@session.globals.Owner = 'Stanpol', @ht.ZP, @ht.ST))) AND @session.HT.IR.Sprzedaz_export_BruttoWal_do_rozrach)
						   OR ((_Rodzaj IN (@ht.CZkFV,@ht.CZkRU,@ht.CZkKF,@ht.CZkKR)) AND @session.HT.IR.Zakup_krajowy_walucie_Brutto_do_rozrach) ) THEN
						   -- APRO: rowniez dodac zakupy pozostale
			
					SET NEW.NettoDoRozrach = 1;
				-- 	
				-- if not (((crdzOper[cdsEOpNg.FieldByName('Rodzaj').AsInteger].OpTyp IN [ST{$IFDEF Stanpol},ZP{$ENDIF}]) AND @session.HT.IR.Sprzedaz_export_BruttoWal_do_rozrach)
				--		   OR ((cdsEOpNg.FieldByName('Rodzaj').AsInteger IN [CZkFV,CZkRU,CZkKF,CZkKR]) AND @session.HT.IR.Zakup_krajowy_walucie_Brutto_do_rozrach) ) then
				-- 
				END IF; 
			*/
			END IF; -- NettoDoRozrach
		
		END IF;
		SET NEW.CWN = IFNULL(NEW.CWN, 0); 
		
		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
			NEW.KontrGUID
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		-- SET @transact.KontrGUIDChanged = IFNULL(NEW.KontrGUID, '') != IFNULL(OLD.KontrGUID, '');
		SET @transact.KontrGUIDChanged = !(NEW.KontrGUID <=> OLD.KontrGUID);
		IF @transact.KontrGUIDChanged THEN
			IF IFNULL(NEW.KontrGUID, '') != '' THEN 
		
				UPDATE `kontrah` k
				SET
					NEW.kontridn = k.Idn,
					NEW.kontrnazwa = k.nazwa, 
					NEW.kontrsymbol = k.symbol,
					NEW.kontradres = CONCAT(k.ulica,', ',k.zipcode, ' ', k.nazwamiasta),
					NEW.kontrklasacenowa = k.klasacenowa, 
					NEW.kontrnip = k.nip, 
					NEW.kontrpodzialnip = k.podzialnip, 
					NEW.kontrupowaznienie = k.Upowaznienie,
					NEW.spedycja = k.spedycja,
					NEW.platnikguid = k.platnikguid, 
					NEW.akwizytorguid = k.akwizytorguid, 
					NEW.rodzaj2 = k.rodzaj2, 
					NEW.kontrrabat = k.rabat,
					NEW.idn_tab_kurs = k.idn_tab_kurs,
					NEW.Odbierajacy = IF(@session.HT.IR.PrzenosOdbierajacegoZKartyKontrahenta AND k.Upowaznienie = 0, k.Odbierajacy, NEW.Odbierajacy),
			-- 		NEW.Przeliczenie_B_N = IF(@session.HT.IR.Przeliczenie_B_N_z_klasy_cen, kc.czy_ceny_brt, NEW.Przeliczenie_B_N),
					NEW.lang_id = k.lang_id,
					NEW.KatCol0 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol0, NEW.KatCol0),
					NEW.KatCol1 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol1, NEW.KatCol1),
					NEW.KatCol2 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol2, NEW.KatCol2),
					NEW.KatCol3 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol3, NEW.KatCol3),
					NEW.KatCol4 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol4, NEW.KatCol4),
					NEW.sposobplatn = IF(@session.HT.IR.Zakup_nie_inicjuj_sposobu_platnosci_z_karty_kontra, k.sposplat, NEW.sposobplatn),
					NEW.kontofk = 
						IF(@session.globals.Owner != 'ASEKURACJA', 
							IF(@ht.doc.Rztyp IN (@ht.Rz_NL, @ht.RzSNL, @ht.Rz_SN, @ht.RzSSN), -- aRzTyp in [Rz_NL, RzSNL, Rz_SN, RzSSN],
								k.kontofk,
								IF(@ht.doc.Rztyp IN (@ht.Rz_ZB, @ht.RzSZB, @ht.Rz_SZ, @ht.RzSSZ), -- aRzTyp in [Rz_ZB, RzSZB, Rz_SZ, RzSSZ],
									k.kontofk2,
									NEW.kontofk
								)	
							),	
							NEW.kontofk
						),
					NEW.uwagi = IF(@session.HT.IR.przepisz_uwagi_kontrah_do_oper, _CONCATStr(k.Uwagi, k.UwagiNaFV, '\n'), NEW.uwagi),
					NEW.dotyczy = IF(@session.globals.Owner = 'STANPOL', k.opis_dzialalnosci, NEW.dotyczy),
					k.TypSymbolow = (@transact.TypSymbolow := k.TypSymbolow),
					NEW.ugrpGUID = IF(@session.HT.IR.przepisz_ugrpGUID_z_kontrah, k.ugrpGUID, NEW.ugrpGUID)
					
				/*					
					  {$IFDEF UprawnieniaDoZapisow}
					  if RegistryInt.GetRegIntValueBoolean('przepisz_ugrpGUID_z_kontrah', False, 'OPNGINFOPATH') then
						aNaglowek.FieldByName('ugrpGUID').AsString := aDSTempKontrah.FieldByName('ugrpGUID').AsString;
					  {$ENDIF UprawnieniaDoZapisow}
				*/
				WHERE 
					k.guid = NEW.KontrGUID
				;

				/* 
				I JESZCZE !!!!!!!!!!!!!
				  if INgPoCOM.EditorMode and (cdsEOpNg.FieldByName('kontrGUID').asString <> '') then
				  begin
					JDB.LetEdit(cdsEOpNg);n
					PrepareAreaGUID;
					if JDB.DataSetIsNotEmpty(cdsAreaGUID) and (cdsAreaGUID.RecordCount = 1) then
						cdsEOpNg.FieldByName('areaGUID').asString := cdsAreaGUID.FieldByName('GUID').asString
					else
						cdsEOpNg.FieldByName('areaGUID').asString := '';

				  end;
				*/
				
				UPDATE `klasycen` kc 
				SET
					NEW.Przeliczenie_B_N = IF(@session.HT.IR.Przeliczenie_B_N_z_klasy_cen, kc.czy_ceny_brt, NEW.Przeliczenie_B_N)
				WHERE 
					kc.idn = NEW.kontrklasacenowa
				;
				
			ELSE
			--	WYCZYŚĆ
				-- UPDATE `t_ht_ngpo_transact` t
				SET
					NEW.kontridn = 0,
					@transact.TypSymbolow := 0,
					NEW.kontrnazwa = '', 
					NEW.kontrsymbol = '',
					NEW.kontradres = '',
					NEW.kontrklasacenowa = 0, 
					NEW.kontrnip = '', 
					NEW.kontrpodzialnip = 0, 
					NEW.kontrupowaznienie = 0,
					NEW.spedycja = 0,
					NEW.platnikguid = '', 
					NEW.akwizytorguid = '', 
					NEW.rodzaj2 = 0, 
					NEW.kontrrabat = 0,
					NEW.idn_tab_kurs = 0,
					NEW.Odbierajacy = NULL,
					NEW.Przeliczenie_B_N = 0,
					NEW.lang_id = NULL,
					NEW.KatCol0 = -1,
					NEW.KatCol1 = -1,
					NEW.KatCol2 = -1,
					NEW.KatCol3 = -1,
					NEW.KatCol4 = -1,
					NEW.sposobplatn = 0,
					NEW.kontofk = '',	
					NEW.uwagi = '',
					NEW.dotyczy = ''
				;
			END IF;
			
		END IF;
		
		IF (IFNULL(NEW.PlatnikGUID, '') = '') AND (IFNULL(NEW.KontrGUID, '') != '') THEN
			SET NEW.PlatnikGUID = NEW.KontrGUID;
		END IF;
		SET NEW.CWN = IFNULL(NEW.CWN, 0); 

		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
			NEW.sposobplatn
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		SET @transact.sposobplatn.Change = !(NEW.sposobplatn <=> OLD.sposobplatn);
		SET @transact.sposobplatn.Change = @transact.sposobplatn.Change or !(NEW.datawystaw <=> OLD.datawystaw);
		SET @transact.sposobplatn.Change = @transact.sposobplatn.Change or !(NEW.datawplywu <=> OLD.datawplywu);
		
		IF @transact.sposobplatn.Change THEN
			SET NEW.DataPlatnosci = _GetDataPlatnosci(NEW.datawystaw, NEW.sposobplatn);
			SET NEW.dataplatnosci_oczekiwana = _GetDataPlatnosci_oczekiwana(NEW.DataPlatnosci, NEW.datawplywu);
		END IF;
		
		SET NEW.rozrachunek = IFNULL(NEW.rozrachunek, 0);
		
		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
			Rozrachunki
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		IF NEW.rozrachunek THEN
			-- CALL rozrach_rodzaj_calc(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Brutto);
			-- CALL rozrach_nalicz_pola(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Netto, NEW.NettoWal, NEW.Brutto, 
			CALL _Rozrach_Nalicz_Pola(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Netto, NEW.NettoWal, NEW.Brutto, NEW.BruttoWal, NEW.NettoDoRozrach,
				NEW.Zaplacono, 
				NEW.Kurs,
				NEW.Kurs_rozliczen,
				NEW.CWN,
				NEW.CKwota,
				NEW.CKwotaWal,
				NEW.CRozliczone,
				NEW.CRozliczoneWal,
				NEW.nierozliczony,
				'', '', '', '');
		END IF;	

		SET NEW.CWN = IFNULL(NEW.CWN, 0); 
		
		/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
			Koniec
		------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
		IF NEW.tag = -1 THEN
			SET NEW.tag = OLD.tag;
		END IF;
		
		IF NEW.tag = 1 THEN
			SET NEW.tag = 0;
		END IF;
		
		IF NEW.tag = 2 THEN
			SET NEW.tag = 1;
		END IF;
		
		IF NEW.tag = 3 THEN
			SET NEW.tag = 2;
		END IF;
		
		IF NEW.tag = 4 THEN
			SET NEW.tag = 3;
		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
		
	
	ELSE	--	PO NOWEMU
	-- Po staremu
			DROP TEMPORARY TABLE IF EXISTS `t_trigg_operdoc`;
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_trigg_operdoc` LIKE `operdoc`;
			INSERT INTO `t_trigg_operdoc` SELECT * FROM `operdoc`;
			
			SET @session.opng_e = FALSE;	--	CELOWO!!!!!!!!
			IF IFNULL(@session.opng_e, FALSE) THEN 
				LEAVE S_opng_e_bu; 
			END IF;
			-- SET @session.opng_e = FALSE;
			
			
			CALL ht_rodzaj_update_zmienne(NEW.Rodzaj);
			-- CALL ht_rodzaj_calc(NEW.Rodzaj);
			
			CALL e_opng_rec_ustal_magazyny('', NEW.Rodzaj, NEW.ZMagazynu, NEW.DoMagazynu);
				  -- [FieldByName('WalutaSymbol').AsString, FieldByName('datawaluty').AsString, FieldByName('kurs').DisplayText]);
			SET @NEW.DoMagazynu = NEW.DoMagazynu;
			SET @NEW.ZMagazynu = NEW.ZMagazynu;
			SET @ng.f.tag = NEW.tag;
			
			SET @transact.ISNewDoc = (IFNULL(NEW.IDN, 0) = 0);
			IF @transact.ISNewDoc THEN
			
				UPDATE `t_trigg_operdoc` d
				SET
					NEW.rozrachunek = d.IsRozrachunek,
					NEW.grupaoper = @ng.f.grupaoper := d.Grupa,
					NEW.wzordekr = d.wzordekr,
					NEW.rv_id = d.rv_id, 
					NEW.RodzajDowodu = d.RodzajDowodu,
					NEW.ugrpGUID = d.ugrpGUID,
					NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
					
				WHERE
					d.Rodzaj = NEW.Rodzaj
				;
				SET
					NEW.idnuser = IFNULL(@session.Registration.IdnUser, @session.CheckLogonUserLogin),
					NEW.ugrpGUID = IFNULL(@session.user.CurrugrpGUID, ''),
					NEW.Deleted = IFNULL(NEW.Deleted, 0),
					NEW.ilepoz = IFNULL(NEW.ilepoz, 0),
					--	Daty
					NEW.DataWystaw = IFNULL(NEW.DataWystaw, CURRENT_DATE()),
					NEW.DataSprzed = IFNULL(NEW.DataSprzed, CURRENT_DATE()),
					NEW.DataWplywu = IFNULL(NEW.DataWplywu, CURRENT_DATE()),
					NEW.data_vat = IFNULL(NEW.data_vat, CURRENT_DATE()),
					NEW.DataWaluty = IFNULL(NEW.DataWaluty, CURRENT_DATE()),
					NEW.DataPlatnosci = IFNULL(NEW.DataPlatnosci, CURRENT_DATE()),
					NEW.dataplatnosci_oczekiwana = IFNULL(NEW.dataplatnosci_oczekiwana, CURRENT_DATE()),
					
					NEW.kurs_rozliczen = IFNULL(NEW.kurs_rozliczen, 1),
					/*
		-- jmam			NEW.rozrachunek = @ht.doc.IsRozrachunek,
					NEW.grupaoper = @ng.f.grupaoper := @ht.doc.Optyp,
					NEW.wzordekr = @ht.doc.wzordekr,
					NEW.rv_id = @ht.doc.rv_id, 
					NEW.RodzajDowodu = @ht.doc.RodzajDowodu,
					NEW.ugrpGUID = @ht.doc.ugrpGUID,
					*/
					NEW.gruparozrach = IFNULL(@ng.f.gruparozrach := @ht.doc.RzTypRozrach, 0)
					
				;	
				SET	NEW.data_vat = IF(NEW.data_vat='0000-00-00',CURRENT_DATE(), NEW.data_vat);
		
			END IF;
		--	Daty
			SET
				NEW.dataplatnosci_oczekiwana = 
					IF(@session.globals.Owner = 'RELACOM',
						DATE_ADD(NEW.datawplywu, INTERVAL @session.HT.IR.DniPowiekszeniaDatyPlatnosciOczekiwanej DAY),
						NEW.dataplatnosci
					)	
				
			;	
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				NEW.Waluta
			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			SET @transact.WalutaChanged = IFNULL(NEW.Waluta, '') != IFNULL(OLD.Waluta, '');
			IF @transact.WalutaChanged THEN
				SELECT Kurs FROM `kursy_calc` WHERE idnwaluty1 = NEW.Waluta AND idnwaluty2 = 0 LIMIT 1 INTO @NEW.Kurs;
				SET NEW.Kurs = IFNULL(@NEW.Kurs, 1);
			END IF;
			
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				NEW.KontrGUID
			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			-- SET @transact.KontrGUIDChanged = IFNULL(NEW.KontrGUID, '') != IFNULL(OLD.KontrGUID, '');
			SET @transact.KontrGUIDChanged = !(NEW.KontrGUID <=> OLD.KontrGUID);
			IF @transact.KontrGUIDChanged THEN
				IF IFNULL(NEW.KontrGUID, '') != '' THEN 
			
					UPDATE `kontrah` k
					SET
						NEW.kontridn = k.Idn,
						NEW.kontrnazwa = k.nazwa, 
						NEW.kontrsymbol = k.symbol,
						NEW.kontradres = CONCAT(k.ulica,', ',k.zipcode, ' ', k.nazwamiasta),
						NEW.kontrklasacenowa = k.klasacenowa, 
						NEW.kontrnip = k.nip, 
						NEW.kontrpodzialnip = k.podzialnip, 
						NEW.kontrupowaznienie = k.Upowaznienie,
						NEW.spedycja = k.spedycja,
						NEW.platnikguid = k.platnikguid, 
						NEW.akwizytorguid = k.akwizytorguid, 
						NEW.rodzaj2 = k.rodzaj2, 
						NEW.kontrrabat = k.rabat,
						NEW.idn_tab_kurs = k.idn_tab_kurs,
						NEW.Odbierajacy = IF(@session.HT.IR.PrzenosOdbierajacegoZKartyKontrahenta AND k.Upowaznienie = 0, k.Odbierajacy, NEW.Odbierajacy),
				-- 		NEW.Przeliczenie_B_N = IF(@session.HT.IR.Przeliczenie_B_N_z_klasy_cen, kc.czy_ceny_brt, NEW.Przeliczenie_B_N),
						NEW.lang_id = k.lang_id,
						NEW.KatCol0 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol0, NEW.KatCol0),
						NEW.KatCol1 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol1, NEW.KatCol1),
						NEW.KatCol2 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol2, NEW.KatCol2),
						NEW.KatCol3 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol3, NEW.KatCol3),
						NEW.KatCol4 = IF(@session.HT.IR.Przepisz_katcol_kontrah_do_opng, k.KatCol4, NEW.KatCol4),
						NEW.sposobplatn = IF(@session.HT.IR.Zakup_nie_inicjuj_sposobu_platnosci_z_karty_kontra, k.sposplat, NEW.sposobplatn),
						NEW.kontofk = 
							IF(@session.globals.Owner != 'ASEKURACJA', 
								IF(TRUE, -- aRzTyp in [Rz_NL, RzSNL, Rz_SN, RzSSN],
									k.kontofk,
									IF(TRUE, -- aRzTyp in [Rz_ZB, RzSZB, Rz_SZ, RzSSZ],
										k.kontofk2,
										NEW.kontofk
									)	
								),	
								NEW.kontofk
							),
						NEW.uwagi = IF(@session.HT.IR.przepisz_uwagi_kontrah_do_oper, _CONCATStr(k.Uwagi, k.UwagiNaFV, '\n'), NEW.uwagi),
						NEW.dotyczy = IF(@session.globals.Owner = 'STANPOL', k.opis_dzialalnosci, NEW.dotyczy),
						k.TypSymbolow = (@transact.TypSymbolow := k.TypSymbolow)
					WHERE 
						k.guid = NEW.KontrGUID
					;
					
					UPDATE `klasycen` kc 
					SET
						NEW.Przeliczenie_B_N = IF(@session.HT.IR.Przeliczenie_B_N_z_klasy_cen, kc.czy_ceny_brt, NEW.Przeliczenie_B_N)
					WHERE 
						kc.idn = NEW.kontrklasacenowa
					;
					
				ELSE
				--	WYCZYŚĆ
					-- UPDATE `t_ht_ngpo_transact` t
					SET
						NEW.kontridn = 0,
						@transact.TypSymbolow := 0,
						NEW.kontrnazwa = '', 
						NEW.kontrsymbol = '',
						NEW.kontradres = '',
						NEW.kontrklasacenowa = 0, 
						NEW.kontrnip = '', 
						NEW.kontrpodzialnip = 0, 
						NEW.kontrupowaznienie = 0,
						NEW.spedycja = 0,
						NEW.platnikguid = '', 
						NEW.akwizytorguid = '', 
						NEW.rodzaj2 = 0, 
						NEW.kontrrabat = 0,
						NEW.idn_tab_kurs = 0,
						NEW.Odbierajacy = NULL,
						NEW.Przeliczenie_B_N = 0,
						NEW.lang_id = NULL,
						NEW.KatCol0 = -1,
						NEW.KatCol1 = -1,
						NEW.KatCol2 = -1,
						NEW.KatCol3 = -1,
						NEW.KatCol4 = -1,
						NEW.sposobplatn = 0,
						NEW.kontofk = '',	
						NEW.uwagi = '',
						NEW.dotyczy = ''
					;
				END IF;
				
			END IF;
	
			IF (IFNULL(NEW.PlatnikGUID, '') = '') AND (IFNULL(NEW.KontrGUID, '') != '') THEN
				SET NEW.PlatnikGUID = NEW.KontrGUID;
			END IF;

	
			SET NEW.rozrachunek = IFNULL(NEW.rozrachunek, 0);
	
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				Rozrachunki
			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			IF NEW.rozrachunek THEN
				-- CALL rozrach_rodzaj_calc(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Brutto);
				CALL rozrach_nalicz_pola(NEW.Rodzaj, NEW.gruparozrach_wymus, NEW.Netto, NEW.NettoWal, NEW.Brutto, NEW.Zaplacono, 
					NEW.Kurs,
					NEW.Kurs_rozliczen,
					NEW.CWN,
					NEW.CKwota,
					NEW.CKwotaWal,
					NEW.CRozliczone,
					NEW.CRozliczoneWal,
					NEW.nierozliczony,
					'', '', '', '');
				
			END IF;	
			
			/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
				Koniec
			------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
			IF NEW.tag = 1 THEN
				SET NEW.tag = 0;
			END IF;
			
			IF NEW.tag = 2 THEN
				SET NEW.tag = 1;
			END IF;
	
			IF NEW.tag = 3 THEN
				SET NEW.tag = 2;
			END IF;
			
			IF NEW.tag = 4 THEN
				SET NEW.tag = 3;
			END IF;
			
			
			
			SET @session.opng_e = FALSE;
	
	END IF;		--	PO Staremu NEW.Calc_Ver < 3

END;
$$


/* ************************************************************************************************************************************************************************
	AU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `opng_e_au`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `opng_e_au` AFTER UPDATE ON `opng_e` FOR EACH ROW 
S_opng_e_au: BEGIN
	IF _GetVer() = '5.1.30' THEN LEAVE S_opng_e_au; END IF;
	-- wartosc @session.trigger_lock rowna TRUE blokuje wykonanie triggera
	IF IFNULL(@session.trigger_lock, FALSE) THEN LEAVE S_opng_e_au; END IF;
	--
	/*
	SET @rec.oppo.Need.Update.from.opng = (
		IFNULL(NEW.Rodzaj, -1) != IFNULL(OLD.Rodzaj, -1) OR
		IFNULL(NEW.ZMagazynu, -1) != IFNULL(OLD.ZMagazynu, -1) OR
		IFNULL(NEW.DoMagazynu, -1) != IFNULL(OLD.DoMagazynu, -1) OR
		IFNULL(NEW.tymczasowa, '') != IFNULL(OLD.tymczasowa, '') OR
		IFNULL(NEW.DataWystaw, '2100-01-01') != IFNULL(OLD.DataWystaw, '2100-01-01') OR
		IFNULL(NEW.DataWplywu, '2100-01-01') != IFNULL(OLD.DataWplywu, '2100-01-01') OR
		IFNULL(NEW.DataSprzed, '2100-01-01') != IFNULL(OLD.DataSprzed, '2100-01-01') OR
		IFNULL(NEW.KontrGUID, '') != IFNULL(OLD.KontrGUID, '') OR
		IFNULL(NEW.katcol0, -1) != IFNULL(OLD.katcol0, -1) OR
		IFNULL(NEW.katcol1, -1) != IFNULL(OLD.katcol1, -1) OR
		IFNULL(NEW.katcol2, -1) != IFNULL(OLD.katcol2, -1) OR
		IFNULL(NEW.katcol3, -1) != IFNULL(OLD.katcol3, -1) OR
		IFNULL(NEW.katcol4, -1) != IFNULL(OLD.katcol4, -1) OR
		IFNULL(NEW.Waluta, -1) != IFNULL(OLD.Waluta, -1) OR
		IFNULL(NEW.Kurs, -1) != IFNULL(OLD.Kurs, -1) OR
		False
		
	)
	;
	IF @rec.oppo.Need.Update.from.opng THEN
		CALL stztmg_e_update_oppo_e_from_epng_e('', NEW.GUID);
	END IF;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	Narzędzia 
************************************************************************************************************************************************************************ */	
DROP FUNCTION IF EXISTS `_GetDataPlatnosci`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_GetDataPlatnosci`(
	_datawystaw DATE,
	_sposobplatn INTEGER
	) RETURNS DATE
    NO SQL
    DETERMINISTIC
/*
*/	
BEGIN
	SELECT plat.dni FROM `platnosc` plat WHERE plat.IDN = _sposobplatn LIMIT 1 INTO @plat.dni;
	RETURN DATE_ADD(_datawystaw, INTERVAL @plat.dni DAY);
END$$

DROP FUNCTION IF EXISTS `_GetDataPlatnosci_oczekiwana`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_GetDataPlatnosci_oczekiwana`(
	_Dataplatnosci DATE,
	_Datawplywu DATE
	) RETURNS DATE
    NO SQL
    DETERMINISTIC
/*
*/	
BEGIN
	SET
		@NEW.dataplatnosci_oczekiwana = 
			IF(@session.globals.Owner = 'RELACOM',
				DATE_ADD(_Datawplywu, INTERVAL @session.HT.IR.DniPowiekszeniaDatyPlatnosciOczekiwanej DAY),
				_Dataplatnosci
			)	
		
	;	
	SET
		@NEW.DataPlatnosci_oczekiwana = 
			IF(@session.globals.Owner = 'Laczpol',
				_Dataplatnosci,
				@NEW.DataPlatnosci_oczekiwana
			)	
	;

	RETURN DATE(@NEW.DataPlatnosci_oczekiwana);
END$$

/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `_lock_inf_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `_lock_inf_bi` BEFORE INSERT ON `_lock_inf` FOR EACH ROW 
S__lock_inf_bi: BEGIN
	IF _GetVer() = '5.1.30' THEN LEAVE S__lock_inf_bi; END IF;
--	wartosc @session.trigger_lock rowna TRUE blokuje wykonanie triggera
	IF IFNULL(@session.trigger_lock, FALSE) THEN LEAVE S__lock_inf_bi; END IF;

	SET NEW.LockUserGUID = IFNULL(NEW.LockUserGUID, '');
	SET
		NEW.LockSession = CONNECTION_ID(),
		NEW.LockUserGUID = IF(NEW.LockUserGUID = '', IFNULL(@session.CurrOsobaGUID, ''), NEW.LockUserGUID),
		NEW.LockTime = CURRENT_TIMESTAMP(),
		NEW.LockMsg = IF(IFNULL(NEW.`LockMsg`, '')  = '', 'Dokument jest edytowany', NEW.`LockMsg`)
	;	
/*
	SELECT 
		EXISTS(
			SELECT p.ID FROM information_schema.PROCESSLIST p WHERE p.ID = _LockSession AND p.DB = DATABASE()
		) AS LockSession_Exist
	INTO
		@_LockSession_Exist
	;
	
	SET
	--	Wstaw 1 gdy rekord zablokowany umarłą sesją
		_Status = IF(@_LockSession_Exist, 0, 1),
		@Hours = TIMESTAMPDIFF(HOUR, _alocaltime, CURRENT_TIMESTAMP()),
		@Minutes = TIMESTAMPDIFF(MINUTE, _alocaltime, CURRENT_TIMESTAMP())
	;
	SET
	--	Wstaw 2 gdy rekord zablokowany umarłą sesją dłużej niż 24h
		_Status = IF((_Status = 1) AND (@Hours >= 24), 2, _Status)
	;
	
*/	
	SET 
		NEW.LockUserFullName = 
			IFNULL(
			(SELECT CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr FROM `osoby` o WHERE o.GUID = NEW.LockUserGUID),
			'nieznany'
			)
	;
	SET NEW.LockUserFullName = IFNULL(NEW.LockUserFullName, 'nieznany');
	CALL _lock_inf_getInf('', NEW.LockSession, NEW.LockUserGUID, CURRENT_TIMESTAMP(), @trigger._lock_inf._LockUserFullName, NEW.Inf, '', '');
		
END;
$$

/* ************************************************************************************************************************************************************************
	AI
************************************************************************************************************************************************************************ */	

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `_lock_inf_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `_lock_inf_bu` BEFORE UPDATE ON `_lock_inf` FOR EACH ROW 
S__lock_inf_bu: BEGIN

	IF _GetVer() = '5.1.30' THEN LEAVE S__lock_inf_bu; END IF;
--	wartosc @session.trigger_lock rowna TRUE blokuje wykonanie triggera
	IF IFNULL(@session.trigger_lock, FALSE) THEN LEAVE S__lock_inf_bu; END IF;
	
	IF IFNULL(@session._lock_inf, FALSE) THEN 
		LEAVE S__lock_inf_bu; 
	END IF;
	
	SET NEW.Set_1_To_Calc = 0;	--	 zawsze gaś na ZERO
	
	SET NEW.LockMsg = IF(IFNULL(NEW.`LockMsg`, '')  = '', 'Dokument jest edytowany', NEW.`LockMsg`);
	
	/******************************************************************************************************************************************************
		LockUserFullName
	******************************************************************************************************************************************************/
	IF IFNULL(NEW.LockUserFullName, '') = '' THEN
		SET 
			NEW.LockUserFullName = 
				IFNULL(
				(SELECT CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr FROM `osoby` o WHERE o.GUID = NEW.LockUserGUID),
				'nieznany'
				)
		;
	END IF;
	
	IF (NEW.LockSession = -1) THEN
		SET
			NEW.LockSession = CONNECTION_ID(),
			NEW.Number_of_Trials = 0
		;	
		
	END IF;
	
	IF !(NEW.LockSession <=> OLD.LockSession) THEN
		SET
			NEW.LockTime = CURRENT_TIMESTAMP(),
			NEW.alocaltime = CURRENT_TIMESTAMP()
		;	
	END IF;

	/******************************************************************************************************************************************************
		Czas
	******************************************************************************************************************************************************/
	SET
		@_lock_inf_bu.Hours = TIMESTAMPDIFF(HOUR, NEW.LockTime, CURRENT_TIMESTAMP()),
		@_lock_inf_bu.Minutes = TIMESTAMPDIFF(MINUTE, NEW.LockTime, CURRENT_TIMESTAMP())
	;
	SET 
		NEW.LockSessionState = IF(@_LockSession_Exist, 0, 1)
	;
	SET 
		@_lock_inf_bu.Trwa = IF(@_lock_inf_bu.Hours > 1, CONCAT(@_lock_inf_bu.Hours, ' godz. (', @_lock_inf_bu.Minutes, ' min.)'), CONCAT(@_lock_inf_bu.Minutes, ' min.'))
	;
	/******************************************************************************************************************************************************
		Informacje o Sesji
	******************************************************************************************************************************************************/
	SELECT 
		EXISTS(
			SELECT p.ID FROM information_schema.PROCESSLIST p WHERE _VarStr(p.ID) <=> NEW.LockSession AND p.DB = DATABASE()
		) AS LockSession_Exist
	INTO
		@_LockSession_Exist
	;
	
	SET
		@_lock_inf_bu.Override = (@_lock_inf_bu.Hours >= NEW.TimeHourLimit)
	;
	IF @_lock_inf_bu.Override THEN
		SET	NEW.LockSessionState = 
			IF(NEW.LockSessionState = 0, 2, 3);
	END IF;
	
	/******************************************************************************************************************************************************
		Msg
	******************************************************************************************************************************************************/
	SET
		@_lock_inf_bu.Msg =
			CASE 	-- 0-normalna sesji, 1-umarla sesja, 2-przekroczony czas (TimeHourLimit), 3 - umarla przekroczona
				WHEN NEW.LockSessionState = 0 THEN ''
				WHEN NEW.LockSessionState IN (1, 3) THEN 
					CONCAT(
						'********************************************************\n',
						-- 'UWAGA \nSESJA NIEAKTYWNA \nskontaktuj się z administratorem w celu \nodblokowania dokumentu!!!\n',
						_res_str_get('_lock_inf.Sesja_Nieaktywana_1', ''),
						'********************************************************'
					)
				WHEN NEW.LockSessionState = 2 THEN 
					CONCAT(
						'********************************************************\n',
						-- 'UWAGA \nPRZEKROCZONY CZAS \nskontaktuj się z użytkownikiem blokującym dokument lub \nz administratorem w celu odblokowania dokumentu!!!\n',
						_res_str_get('_lock_inf.Sesja_Nieaktywana_2', ''),
						'********************************************************'
					)
				ELSE
				''
			END
	;
	/******************************************************************************************************************************************************
		LockSessionStateInf
	******************************************************************************************************************************************************/
	SET
		
		@LockSessionStateInf = 
			_res_str_get('_lock_inf.LockSessionStateInf', '')
			-- '#LockMsg#\nprzez użytkownika: #LockUserFullName#\nBlokada z dnia: #LockTime#\nTrwa ponad #Trwa#\nSesja nr: #LockSession#\n#Msg#'
	;
	SET
		NEW.LockSessionStateInf = 
			REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@LockSessionStateInf,
				'#LockMsg#', NEW.LockMsg),
				'#LockUserFullName#', NEW.LockUserFullName),
				'#LockTime#', NEW.LockTime),
				'#Trwa#', @_lock_inf_bu.Trwa),
				'#LockSession#', NEW.LockSession),
				'#Msg#', @_lock_inf_bu.Msg)
	;
	
-- ????	CALL _lock_inf_getInf('', NEW.LockSession, NEW.LockUserGUID, NEW.alocaltime, @trigger._lock_inf._LockUserFullName, NEW.Inf, '', '');

	
	IF !(NEW.LockSession <=> OLD.LockSession) AND (NEW.LockSession IN ('0', '')) AND FALSE THEN
		SET
			NEW.LockSession = CONNECTION_ID(),
			NEW.alocaltime = CURRENT_TIMESTAMP(),
			NEW.Number_of_Trials = 0
		;	
		CALL _lock_inf_getInf('', NEW.LockSession, NEW.LockUserGUID, NEW.alocaltime, @trigger._lock_inf._LockUserFullName, NEW.Inf, '', '');
	END IF;
	
	IF !(NEW.Number_of_Trials <=> OLD.Number_of_Trials) AND (NEW.Number_of_Trials != 0) THEN
		SET NEW.Number_of_Trials = OLD.Number_of_Trials + 1;
-- ????		CALL _lock_inf_getInf('', NEW.LockSession, NEW.LockUserGUID, NEW.alocaltime, @trigger._lock_inf._LockUserFullName, NEW.Inf, '', '');
	END IF;
	
	--	CALL _lock_inf_getInf('', 194532, NEW.LockUserGUID, NEW.alocaltime, @trigger._lock_inf._LockUserFullName, @trigger._lock_inf._Status, NEW.Inf, '', '');
	--	SET NEW.Status = @trigger._lock_inf._Status;
	
	SET @session._lock_inf = FALSE;
END;
$$


/* ************************************************************************************************************************************************************************
	AU
************************************************************************************************************************************************************************ */	





/* ************************************************************************************************************************************************************************
	narzędzia 
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `_lock_inf_getInf`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_lock_inf_getInf`(
	IN _MODE VARCHAR(250), 
	IN _LockSession INTEGER,
	IN _LockUserGUID VARCHAR(38),
	IN _alocaltime DATETIME,
	INOUT _LockUserFullName VARCHAR(150),
	-- INOUT _Status INTEGER,
	INOUT _Inf TEXT,
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200)
)
BEGIN
	DECLARE _Status INTEGER;
	SELECT 
		EXISTS(
			SELECT p.ID FROM information_schema.PROCESSLIST p WHERE p.ID = _LockSession AND p.DB = DATABASE()
		) AS LockSession_Exist
	INTO
		@_LockSession_Exist
	;
	
	SET
	--	Wstaw 1 gdy rekord zablokowany umarłą sesją
		_Status = IF(@_LockSession_Exist, 0, 1),
		@Hours = TIMESTAMPDIFF(HOUR, _alocaltime, CURRENT_TIMESTAMP()),
		@Minutes = TIMESTAMPDIFF(MINUTE, _alocaltime, CURRENT_TIMESTAMP())
	;
	SET
	--	Wstaw 2 gdy rekord zablokowany umarłą sesją dłużej niż 24h
		_Status = IF((_Status = 1) AND (@Hours >= 24), 2, _Status)
	;
	
	
	SET _LockUserGUID = IFNULL(_LockUserGUID, '');
	IF (_LockUserGUID != '') THEN
		SET 
			_LockUserFullName = (
				SELECT CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr FROM `osoby` o WHERE o.GUID = _LockUserGUID
		);
	ELSE	
		SET _LockUserFullName = '';
	END IF;
	IF IFNULL(_LockUserFullName, '')  = '' THEN
		SET _LockUserFullName = '(nieznany)';
	END IF;
	

	SET
		@Msg = 
		CONCAT(
			CASE _Status
				WHEN 0 THEN 'Dokument jest używany ...'
				WHEN 1 THEN 'Dokument jest zablokowany (ale nieużywany) ...' 
				WHEN 2 THEN 'Dokument jest zablokowany (ale nieużywany ponad limit czasowy) ...' 
			END,
	
			'\n',
			--	IF(@DF DIV 100 < 5, 'Od 5 min', _VarStr(CONCAT('od ', @H, ' ', @M))),
			--	'\n',
			'przez użytkownika: ',  _LockUserFullName,
			'\n',
			'Blokada z dnia: ', _alocaltime,
			'\n',
			'Trwa ponad ', IF(@Hours > 1, CONCAT(@Hours, ' godz. (', @Minutes, ' min.)'), CONCAT(@Minutes, ' min.')),
			'\n',
			'Sesja nr: ', _LockSession,
			'\n'
			-- 'Status: ', _Status
		)
	;
	SET _Inf = @Msg;
END$$

DROP PROCEDURE IF EXISTS `_lock_inf_do`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_lock_inf_do`(
	IN _MODE VARCHAR(250), 
	IN _RecID VARCHAR(250),
	IN _TableName VARCHAR(250),
	IN _LockUserGUID VARCHAR(38),
	OUT _Result BOOLEAN
)
/*
	CALL _lock_inf_do('LOCK', 'X', 'tabX', 'jmam', @R);
	SELECT  @R;
	CALL _lock_inf_do('UNLOCK', 'X', 'tabX', 'jmam', @R);
	SELECT  @R;
*/
BEGIN
	IF _MODE = 'LOCK' THEN
		SET 
			_LockUserGUID = IF(_LockUserGUID = '', IFNULL(@session.CurrOsobaGUID, '<???>'), _LockUserGUID)
		;
		SET @_LockUserGUID = _LockUserGUID;
		/*
		INSERT IGNORE INTO `_lock_inf` 
		SET
			RecID = _RecID,
			TableName = _TableName,
			LockUserGUID = _LockUserGUID
		;
		*/
		SET
			@JakiUpdate = '0'
		;
		INSERT IGNORE INTO `_lock_inf` 
		SET
			RecID = _RecID,
			TableName = _TableName,
			LockUserGUID = _LockUserGUID 
		ON DUPLICATE KEY UPDATE
			LockSession = IF(LockUserGUID = _LockUserGUID, @JakiUpdate := '-1', @JakiUpdate := LockSession),
			Set_1_To_Calc = 1
			
		;
		SET @ROW_COUNT = ROW_COUNT();
		IF @JakiUpdate = '0' THEN
			SET @ROW_COUNT = 1;
		ELSEIF @JakiUpdate = '-1' THEN
			SET @ROW_COUNT = 2;
		ELSE
			SET @ROW_COUNT = 0;
		END IF;
		SET _Result = (@ROW_COUNT > 0);
		-- SELECT _Result;
	END IF;
	
	IF _MODE = 'RELOCK' THEN
		INSERT INTO `_lock_inf` 
		SET
			RecID = _RecID,
			TableName = _TableName,
			LockUserGUID = _LockUserGUID
		ON DUPLICATE KEY UPDATE
			LockSession = IF(LockUserGUID = _LockUserGUID, '', LockSession)
		;
		SET _Result = (ROW_COUNT() > 0);
		-- SELECT _Result;
	END IF;
	
	IF _MODE = 'UNLOCK' THEN
		SET 
			_LockUserGUID = IF(_LockUserGUID = '', IFNULL(@session.CurrOsobaGUID, '<???>'), _LockUserGUID)
		;
		DELETE FROM `_lock_inf` 
		WHERE	
			RecID = _RecID
			AND
			TableName = _TableName
			AND
			LockUserGUID = _LockUserGUID
		;
		SET _Result = (ROW_COUNT() > 0);
		-- SELECT _Result;
	END IF;
		
END$$

DROP PROCEDURE IF EXISTS `_lock_inf_tool`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_lock_inf_tool`(
	IN _MODE VARCHAR(250), 
	IN _RecID VARCHAR(250), 
	IN _TableName VARCHAR(250),
	IN _LockUserGUID VARCHAR(38),
	INOUT _Rec_Is_Locked BOOLEAN,
	INOUT _LockInf TEXT,
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200)
)
/*
	SET _LockUser = IF(_LockUser = '', IFNULL(@session.CurrOsobaGUID, '<AutoID>'), _LockUser);
	CALL ht_test2._lock_inf_tool('LOCK', 'AutoID_CheckBuffOsob_LOCK', 'AutoID_CheckBuffOsob_LOCK', _LockUser, _Rec_Is_Locked, @R2, '', '');
	-- UPDATE `_db_globals` SET `value` = NOW() WHERE Key = 'AutoID_CheckBuffOsob_LOCK' AND `value` = '';
	SET @_Rec_Is_Locked = _Rec_Is_Locked;
	IF _Rec_Is_Locked THEN		--	zablokowany?

	CALL ht_test2._lock_inf_tool('UNLOCK', 'AutoID_CheckBuffOsob_LOCK', 'AutoID_CheckBuffOsob_LOCK', 'event', _Rec_Is_Locked, @R2, '', '');	
*/
S_lock_inf_tool: BEGIN
	DECLARE _Is_Same_Session, _Result BOOLEAN DEFAULT FALSE;

	IF _MODE = 'DELETE_OLD' THEN
		UPDATE `_lock_inf` 
		SET
			Status = -1
		;	
		DELETE FROM `_lock_inf` 
		WHERE	
			Status = 2
		;
	END IF;
	
	IF _MODE = 'LOCK' THEN
		SET 
			_LockInf = '',
			@_Rec_Is_Locked = FALSE,
			@_Is_Same_Session = FALSE,
			_LockUserGUID = IF(_LockUserGUID = '', IFNULL(@session.CurrOsobaGUID, '<???>'), _LockUserGUID)
		;
		CALL _lock_inf_do('LOCK', _RecID, _TableName, _LockUserGUID, _Result);

		SET _Rec_Is_Locked = NOT _Result;
		IF _Result THEN
			SET _LockInf = '';
			-- LEAVE S_lock_inf_tool;
		ELSE	
		/*
			UPDATE `_lock_inf`  
			SET
				Number_of_Trials = -1
			WHERE	
				RecID = _RecID
				AND
				TableName = _TableName
			;
		*/	
			SELECT
				LockSessionStateInf -- Inf
			FROM `_lock_inf` 
			WHERE	
				RecID = _RecID
				AND
				TableName = _TableName
			INTO 
				@Inf1
			;
			SET _LockInf = @Inf1;



			-- LEAVE S_lock_inf_tool;
		END IF;
		
			IF _Param_B = '' THEN
				SELECT _Rec_Is_Locked, (_LockInf) AS _Rec_Is_Locked_MSG;
			END IF;
		
	END IF;
	
	IF _MODE = 'UNLOCK' THEN
		SET _LockInf = '';
		CALL _lock_inf_do('UNLOCK', _RecID, _TableName, _LockUserGUID, _Result);
		/*
		DELETE FROM `_lock_inf` 
		WHERE	
			RecID = _RecID
			AND
			TableName = _TableName
			AND
			LockUserGUID = IF(_LockUserGUID = '', IFNULL(@session.CurrOsobaGUID, '<?>'), _LockUserGUID)
		;
		*/
	END IF;
	
	IF _MODE = 'LOCK_UNLOCK' THEN
		CALL _lock_inf_tool('LOCK', 'JMAM_TEST', 'JMAM_TEST_TABLE', @_LockUser, @_Rec_Is_Locked, @_Rec_Is_Locked_Msg, '', '');
		CALL _lock_inf_tool('UNLOCK', 'JMAM_TEST', 'JMAM_TEST_TABLE', @_LockUser, @_Rec_Is_Locked, @_Rec_Is_Locked_Msg, '', '');
	
	END IF;

	IF _MODE = 'LOCK_Err_UNLOCK' THEN
		CALL _lock_inf_tool('LOCK', 'JMAM_TEST', 'JMAM_TEST_TABLE', @_LockUser, @_Rec_Is_Locked, @_Rec_Is_Locked_Msg, '', '');
		select Costam from `tabela` INTO @Costam;
		CALL _lock_inf_tool('UNLOCK', 'JMAM_TEST', 'JMAM_TEST_TABLE', @_LockUser, @_Rec_Is_Locked, @_Rec_Is_Locked_Msg, '', '');
	
	END IF;


	IF _MODE = 'Check.before.lock' THEN
		
		UPDATE `_lock_inf` l
		SET
			l.Set_1_To_Calc = 1
		WHERE
			l.RecID = _RecID
			AND
			l.TableName = _TableName
		;
		DROP TEMPORARY TABLE IF EXISTS `t_Check_before_lock`;
		CREATE TEMPORARY TABLE `t_Check_before_lock`
			SELECT 
				l.*,
				@IsSameUser := (l.LockUserGUID <=> _LockUserGUID) AS IsSameUser,
				@IsSameSession := (l.LockSession <=> CONNECTION_ID()) AS IsSameSession,
				@LockSession_Exist := EXISTS(
					SELECT p.ID FROM information_schema.PROCESSLIST p WHERE _VarStr(p.ID) <=> l.LockSession AND p.DB = DATABASE()
					-- SELECT p.ID FROM information_schema.PROCESSLIST p WHERE p.ID <=> 'asdads' AND p.DB = DATABASE()
				) AS LockSession_Exist,
				@Hours := TIMESTAMPDIFF(HOUR, l.alocaltime, CURRENT_TIMESTAMP()) AS Hours,
				@Minutes := TIMESTAMPDIFF(MINUTE, l.alocaltime, CURRENT_TIMESTAMP()) AS Minutes,
				@Trwa := IF(@Hours > 1, CONCAT(@Hours, ' godz. (', @Minutes, ' min.)'), CONCAT(@Minutes, ' min.')) AS Trwa,
				-- @_LockUserFullName := (SELECT CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr FROM `osoby` o WHERE o.GUID = l.LockUserGUID) AS LockUserFullName,
				@_State := 
					IF(@IsSameUser,
						IF(@IsSameSession,
							'2.JA/Ta sesja',
							IF(@LockSession_Exist,
								'3.JA/inna sesja',
								'4.JA/zamknieta sesja'
							)
						),
						'1.Blokada'
					) AS _State,
				CASE @_State
				WHEN '1.Blokada' THEN 
					LockSessionStateInf
					/*
					CONCAT(
					REPLACE(REPLACE(
					'Dokument jest zablokowany przez użytkownika: #N#!\n\rSesja ta trwa ponad #T#\n\rSpróbuj później', 
					'#N#', l.LockUserFullName
					),
					'#T#', @Trwa
					)	
					)
					*/
				WHEN '2.JA/Ta sesja' THEN 
					CONCAT('Wznowienie edycji'
					)
				WHEN '3.JA/inna sesja' THEN 
					CONCAT(
					REPLACE(
					-- 'Prawdopodobnie ten dokument jest przez Ciebie edytowany w innej sesji (by może w innej aplikacji)!\n\rSesja ta trwa od ponad #T#\n\rKontunuacja edycji spowoduje zapis zmian dokonanych na innym stanowisku!\n\rCzy chcesz kontynuowac edycję?', 
					_res_str_get('_lock_inf.3.JA/inna sesja', ''),
					'#T#', @Trwa
					)	
					)
				WHEN '4.JA/zamknieta sesja' THEN 
					CONCAT(
					REPLACE(
					-- 'Prawdopodobnie ten dokument był przez Ciebie edytowany i edycja ta nie została prawidłowo zakończona!\n\rSesja ta trwa od ponad #T#\n\rCzy anulowac tamte zmiany?', 
					_res_str_get('_lock_inf.4.JA/zamknieta sesja', ''),
					'#T#', @Trwa
					)	
					)
				ELSE
					'  '
				END AS _StateMsg	
					
			FROM `_lock_inf` l
			WHERE
				l.RecID = _RecID
				AND
				l.TableName = _TableName
				-- _LockUserGUID
		
		;
		ALTER TABLE `t_Check_before_lock` ADD PRIMARY KEY RecID (RecId);
		
		INSERT IGNORE INTO `t_Check_before_lock` 
		(RecId, _State)
		VALUES
		(_RecID, '0.OK')
		;
		
		SELECT
			LockUserGUID,
			LockSession,
			Inf,
			IsSameUser,
			IsSameSession,
			LockSession_Exist,
			LockUserFullName,
			_State,
			IFNULL(_StateMsg, '')
		FROM `t_Check_before_lock`
		LIMIT 1
		INTO
			@t_Check_before_lock.LockUserGUID,
			@t_Check_before_lock.LockSession,
			@t_Check_before_lock.Inf,
			@t_Check_before_lock.IsSameUser,
			@t_Check_before_lock.IsSameSession,
			@t_Check_before_lock.LockSession_Exist,
			@t_Check_before_lock.LockUserFullName,
			@t_Check_before_lock._State,
			@t_Check_before_lock._StateMsg
		;
		DROP TEMPORARY TABLE IF EXISTS `t_Check_before_lock`;

	
	END IF;


	
END$$




/* ************************************************************************************************************************************************************************
	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

	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', 'zmng_e')
	;	
	IF NEW.handle_UserGUID = '' THEN
		SET NEW.handle_UserGUID = IFNULL(@session.Registration.UserGUID, '');
	END IF;
	SET @NEW.handle_UserGUID = NEW.handle_UserGUID;
	IF (IFNULL(NEW.GUID, '') != '') AND (NEW.handle_oper IN ('EDIT', 'DELETE')) THEN
		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,
				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
			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,
				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
			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;
$$

/* ************************************************************************************************************************************************************************
	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;
	
	IF NOT (NEW.i_Tymczasowa <=> OLD.i_Tymczasowa) AND NEW.i_Tymczasowa > 0 AND NEW.Rodzaj != 3 THEN
	--	gdy tymczasowie (1) i nie jest to korekta to pozwol gdy masz uprawnienie
		SET NEW.i_Tymczasowa = _GetUprawnienieExpected('Wystawianie_Dokumentow_Nietymczasowych', '', 1);
	END IF;
	

	IF NOT (NEW.handle_check <=> OLD.handle_check) AND NEW.handle_check != 0 THEN

		IF NEW.handle_check = 102 THEN	--	wolane z CALL _ng_e_rec_set_from_another_doc()
			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 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 
					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 
					WHERE
						NEW.handle_oper = 'Insert'
						AND
						n.GUID = NEW.i_Input_GUID
					;	
				END IF;
			END IF;
			LEAVE A; 
		END IF;
	
	
		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;
			
			
		END IF;
		
		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 TRUE THEN -- _MODE = 'DataZabrOper' THEN
					IF (NEW.ui_datawplywu <= @session.HT.IR.cDataZabrOper) AND NOT (NEW.optyp IN (@ht.ZM)) 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', 
							IF(NEW.handle_ReadOnly, 
								REPLACE(_res_str_get('ng_msg_DataZabrOper_stop', ''), '#D', @session.HT.IR.cDataZabrOper),
								REPLACE(_res_str_get('nng_msg_DataZabrOper_warrning', ''), '#D', @session.HT.IR.cDataZabrOper)
							),
							IF(NEW.handle_ReadOnly, 
								'Warning', 
								'Msg'
							),
							IF(NEW.handle_ReadOnly, 
								'ReadOnly', 
								''
							),
							'', ''
						);
						
						IF NEW.handle_ReadOnly THEN
							SET 
								NEW.u_DataZabrOper_Status = 'ReadOnly',
								NEW.u_DataZabrOper_Msg = 	CONCAT(
									'Nie można edytować dokumentów o dacie wpływu mniejszej lub równej : ', @session.HT.IR.cDataZabrOper, '\n',
									'Możesz tylko przeglądać dane!'
								)	
							;	
						ELSE
							SET 
								NEW.u_DataZabrOper_Status = 'Info',
								NEW.u_DataZabrOper_Msg = 	CONCAT(
									'Uwaga! Edytujesz dokument o dacie wpływu mniejszej lub równej ustawionej dacie granicznej : ', @session.HT.IR.cDataZabrOper
								)	
							;	
							
						END IF;
						SET
						--	I dodaj jeszcze te sam komunikat do NEW.handle_Msg
							NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
								NEW.u_DataZabrOper_Msg, 
								'\n'
							)
						;
					END IF;
				END IF;
				

				SELECT n.zaksiegowana FROM `opng_e` n WHERE n.GUID = NEW.GUID INTO @n.zaksiegowana;
				
				/**********************************************************************************************************************************
					Zadekretowana operacja
				**********************************************************************************************************************************/
				IF @n.zaksiegowana != 0 THEN -- _MODE = 'Status' THEN
					SET
						NEW.handle_Msg = _ConcatSTR(NEW.handle_Msg,
							'Dokument ten został już zadekretowany i nie powinien być modyfikowany!', 
							'\n'
						)
					;
					IF NOT NEW.handle_ReadOnly THEN
						SET @aUp = _GetUprawnienie('Mozliwosc_edycji_po_zadekr', '');
						SET @aUp_Mozliwosc_edycji_po_zadekr = @aUp;

						SET NEW.handle_ReadOnly = (@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', '')
								),
								IF(@session.FK.IR.MozliwoscEdycjiDokZadekretowanego, 
									_res_str_get('ng_msg_Zadekretowana_operacja_warrning2', ''),
									_res_str_get('ng_msg_Zadekretowana_operacja_warrning', '')
								)
							),
							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 = _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;
				
				/**********************************************************************************************************************************
					Status dokumentu
				**********************************************************************************************************************************/
				IF TRUE THEN -- _MODE = 'Status' 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
					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') 
							FROM `slowniki_pierwotne` s 
							WHERE s.Slownik_GUID = 'ZmZPStatus' AND s.VALUE = NEW.ui_status INTO @NEW.Status.handle_ReadOnly;
							/*
							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') 
							FROM `slowniki_pierwotne` s
							WHERE s.Slownik_GUID = 'zamwstatus' AND s.VALUE = NEW.ui_status INTO @NEW.Status.handle_ReadOnly;
							/*
							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') 
							FROM `slowniki_pierwotne` s
							WHERE s.Slownik_GUID = 'OperStatus' AND s.VALUE = NEW.ui_status INTO @NEW.Status.handle_ReadOnly;
							/*
							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 = _ConcatSTR(NEW.handle_Msg,
									'Ten dokument ma już status uniemożliwiający edycję', 
									'\n'
								),
								NEW.handle_ReadOnly_Msg = 'UWAGA\n Ten dokument ma już status uniemożliwiający edycję'
							;
						END IF;	
					END IF;
				END IF;
			
				/**********************************************************************************************************************************
					Czy mam pozycje korygowane
				**********************************************************************************************************************************/
				IF TRUE THEN -- _MODE = 'Status' THEN
					SELECT 
						COUNT(*) AS C
					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
					INTO @Ile_Korygowanych
					;
					SET @Ile_Korygowanych = IFNULL(@Ile_Korygowanych, 0);
					IF (@Ile_Korygowanych > 0) 
						AND NOT(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 = TRUE,
							NEW.handle_ReadOnly_Msg = CONCAT(NEW.handle_ReadOnly_Msg, '\n',
								'UWAGA\n ',
								'Dokument ten posiada pozycje, które były już korygowane.\n ',
								'Edycja pozycji takiego dokumentu nie jest możliwa.\n ',
								'Niektóre funkcje okna edycji również nie będą dostępne.'
							)
						;
						CALL _ng_e_rec_msg_ins('', 'A5', NEW.GUID, 'handle.AFTER', 
							_res_str_get('ng_msg_dokument_korygowany_ReadOnly', ''),
							'Warning',
							'ReadOnly', 
							'', ''
						);
					END IF;
				END IF;
			
				
				/**********************************************************************************************************************************
					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 = _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;

				IF NEW.handle_ReadOnly THEN
					SET
						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;
			
			END IF;
			
			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;
	END IF;
	
	/*
	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;
	*/
	

	
	/*
	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');
	
	
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(*) FROM `ng_e_rec_msg` WHERE GUID = _GUID AND Kind = _Kind INTO _ID;
	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;
	
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 = 'ALL' THEN
		SELECT * FROM `ng_e_rec_msg`
		WHERE
			GUID = _GUID
		;
	ELSE
		SELECT * FROM `ng_e_rec_msg`
		WHERE
			GUID = _GUID AND Kind = _Kind
		;
	END IF;
	
END$$

/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `oppo_corr_e_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `oppo_corr_e_bi` BEFORE INSERT ON `oppo_corr_e` FOR EACH ROW 
S_oppo_corr_e_bi: BEGIN
	IF _TriggerDisabled() THEN LEAVE S_oppo_corr_e_bi; END IF;
	
	SET 
		NEW.b_idnTowr = IFNULL(NEW.b_idnTowr, ''),
		NEW.GUID = IF(IFNULL(NEW.GUID, '') = '', NewGUID(), NEW.GUID)
	;
	
END;
$$

/* ************************************************************************************************************************************************************************
	AI
************************************************************************************************************************************************************************ */	

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `oppo_corr_e_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `oppo_corr_e_bu` BEFORE UPDATE ON `oppo_corr_e` FOR EACH ROW 
S_oppo_corr_e_bu: BEGIN
	IF _TriggerDisabled() THEN LEAVE S_oppo_corr_e_bu; END IF;

	SET
		@oppo_corr_e_bu_IS_Temporary = IFNULL(OLD.Temporary, FALSE) OR IFNULL(NEW.Temporary, FALSE),
		NEW.j_uwagi = IFNULL(NEW.j_uwagi, ''),
		NEW.j_uwagi2 = IFNULL(NEW.j_uwagi2, ''),
		NEW.b_uwagi = IFNULL(NEW.b_uwagi, ''),
		NEW.b_uwagi2 = IFNULL(NEW.b_uwagi2, '')
	;	
	IF NOT @oppo_corr_e_bu_IS_Temporary THEN
		CALL CalcXXPo('', 
		-- CALL CalcPo('', 
			NEW.j_rodzaj_przeliczenia, NEW.j_idnvat, NEW.j_ilosc, @.Wspolplatnosc, NEW.j_Rabat, NEW.j_CenaNet, @.CenaNetPL, @.CenaNetWalzRab, NEW.j_CenaBrt,  -- 9
			NEW.j_WartNet, NEW.j_WartNetWal, @.StawkaVat, NEW.j_WartVat, NEW.j_WartBrt, @.WartBrtWal, @.WartBrtEdit, @.WartRabatNet, @.WartRabatBrt, 
			NEW.j_Kurs, @.Koszt_nabycia, @.StawkaCla, @.WartClo, @.WartNetWalEdit, @.Oplata_produktowa,
			TRUE, @ht.doc.IsWaluta,
			'', '', '', '');
	
		SET
			NEW.Changed = NOT(
				NEW.j_idnTowr = NEW.b_idnTowr AND 
				NEW.j_rodzaj_przeliczenia = NEW.b_rodzaj_przeliczenia AND
				NEW.j_ilosc = NEW.b_ilosc AND 
				NEW.j_cenanet = NEW.b_cenanet AND
				NEW.j_cenabrt = NEW.b_cenabrt AND
				NEW.j_rabat = NEW.b_rabat AND
				NEW.j_idnvat = NEW.b_idnvat AND
				NEW.j_wartnet = NEW.b_wartnet AND 
				NEW.j_kurs = NEW.b_kurs AND 
				NEW.j_wartnetWal = NEW.b_wartnetWal AND 
				NEW.j_wartvat = NEW.b_wartvat AND 
				NEW.j_wartbrt = NEW.b_wartbrt
			)	
		;
		IF NOT NEW.Changed THEN
			SET
				NEW.Changed = IF( NOT(
					NEW.j_pkwiu = NEW.b_pkwiu AND 
					NEW.j_uwagi = NEW.b_uwagi AND 
					NEW.j_uwagi2 = NEW.b_uwagi2 AND 
					NEW.j_towrsymb = NEW.b_towrsymb AND
					NEW.j_towrnazwa = NEW.b_towrnazwa AND
					NEW.j_towrnazwa2 = NEW.b_towrnazwa2 AND
					NEW.j_Jednostka = NEW.b_Jednostka
					),
						2,
						NEW.Changed
				)		
			;
		END IF;
	
	END IF;
	
END;
$$

/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `infpiek_int_ng_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `infpiek_int_ng_bi` BEFORE INSERT ON `infpiek_int_ng` FOR EACH ROW 
A: BEGIN

	IF _TriggerDisabled() THEN LEAVE A; END IF;

	IF (NEW.INT_Dir_Status != 'zINT') AND IFNULL(NEW.INT_GUID, '') = '' THEN
	
		SET NEW.INT_GUID = MD5(CONCAT(NEW.DOWN_NUM, NEW.DOWN_HEX, ''));
	END IF;
	
	SET NEW.DOWN_TER = IFNULL(NEW.DOWN_TER, NEW.DOWN_DAT);
	-- SET NEW.INT_GUID = IF(NEW.DOWN_HEX < 1, UUID(), CONCAT('Infpie_', NEW.DOWN_HEX));	

	IF (NEW.DOWN_TYP = '0') THEN
		SET NEW.INT_Dir_Status = 'PPT';
	END IF;
	
END;
$$

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

	/*
	W partagonach a tutaj NIE
	IF NEW.INT_Dir_Status != 'zINT' THEN
		INSERT IGNORE INTO `infpiek_int_ng_rec`
			(DOWN_HEX, INT_Status)
		VALUES
			(NEW.DOWN_HEX, '')
		;
	END IF;
	*/
	
	/*
	SET @session.trigger.infpiek_int_ng = FALSE;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `infpiek_int_ng_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `infpiek_int_ng_bu` BEFORE UPDATE ON `infpiek_int_ng` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	/*
	IF IFNULL(@session.trigger.infpiek_int_ng, FALSE) THEN 
		LEAVE A; 
	END IF;
	SET @session.trigger.infpiek_int_ng = TRUE;
	*/
	
	IF NEW.INT_Dir_Status != 'zINT' THEN
		SET NEW.INT_GUID = IF(NEW.INT_GUID != '', NEW.INT_GUID, MD5(CONCAT(NEW.DOWN_NUM, NEW.DOWN_HEX)));
	END IF;
	
	IF (NEW.DOWN_TYP = '0') AND (OLD.DOWN_TYP = '1') THEN
		SET NEW.INT_Dir_Status = 'PPT';
		IF OLD.INT_Status = 'F' THEN
			SET NEW.INT_Status = '';
		END IF;
	END IF;
	
	SET NEW.DOWN_TER = IFNULL(NEW.DOWN_TER, NEW.DOWN_DAT);
	/*
	SET @session.trigger.infpiek_int_ng = FALSE;
	*/
END;
$$

/* ************************************************************************************************************************************************************************
	AU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `infpiek_int_ng_au`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `infpiek_int_ng_au` AFTER UPDATE ON `infpiek_int_ng` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	
	IF NEW.INT_Dir_Status = 'zINT' AND NEW.INT_Status = 'F' THEN
	/*******************************************************************************************************************************
		dla np. PZ-ki gdy POS przeczytał i wstawia "F" do INT_Status to zamknij PZ-ke
	*******************************************************************************************************************************/
		UPDATE `opng` n
		SET
			n.Status = 2 	-- @COPNG_Status_ZREALIZOWANA = 2
		WHERE
			n.GUID = NEW.INT_GUID
		;
	END IF;
	
	/*
	IF IFNULL(@session.trigger.infpiek_int_ng, FALSE) THEN 
		LEAVE A; 
	END IF;
	SET @session.trigger.infpiek_int_ng = TRUE;
	*/
	

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

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


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

	
END;
$$

/* ************************************************************************************************************************************************************************
	BI
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `infpiek_int_po_bi`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `infpiek_int_po_bi` BEFORE INSERT ON `infpiek_int_po` FOR EACH ROW 
A: BEGIN

	IF _TriggerDisabled() THEN LEAVE A; END IF;
	
	SET NEW.ARTYK_GUID = RTRIM(NEW.ARTYK_GUID);
END;
$$

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

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

/* ************************************************************************************************************************************************************************
	BU
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `infpiek_int_po_bu`$$
CREATE DEFINER=`root`@`localhost` TRIGGER `infpiek_int_po_bu` BEFORE UPDATE ON `infpiek_int_po` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
	
	SET NEW.ARTYK_GUID = RTRIM(NEW.ARTYK_GUID);
	
END;
$$

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

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

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


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

	
END;
$$


DELIMITER ;
