 /*!40101 SET NAMES cp1250 */;
DELIMITER $$

DROP PROCEDURE IF EXISTS `ht_pres_zestdowodow`$$
	
CREATE DEFINER=`root`@`localhost` PROCEDURE `ht_pres_zestdowodow`(
		IN _MODE VARCHAR(38), 
		IN _GUID VARCHAR(38),
		IN _WHERE_SQL TEXT, 
		IN _Param_A VARCHAR(50),
		IN _Param_B VARCHAR(50)
)
SPROC: BEGIN

/*
CALL ht_pres_zestdowodow('GETData','','','','');
*/
	IF (_MODE='GETData') THEN
		SELECT distinct 
			(select idn from zapisy limit 0 ) as Techniczne , 
			'0' as Checked, Z.idn, Z.GUID,
			Z.status, Z.localtime, Z.idnoper, Z.data_dowodu, Z.konto, Z.ID_Bazy,
			_varDOUBLE(0.0) as StworzoneRO, O.nrdokfin, O.uwagi, P.symbol_fmt,
			P.Nazwa as NazwaKonta, IF(O.pozycjawyciagu <> 0, Concat(LPAD(O.pozycjawyciagu,4, ' '), '/',LPAD(O.podpozycja, 3, ' ')), '') as pozycja,
			O.kontrsymbol as kontrsymbol, O.data_vat as data_vat, DATE(IFNULL(O.datawystaw,Z.data_dowodu)) as datawystaw, 
			if(O.CKwota=Z.kwota, ifnull(if(Z.StronaWN,O.CKwotaWal,-O.CKWotaWal), 0.00), 0.00) as Wartosc, 
			if(O.CKwota=Z.kwota,ifnull(W.Symbol, ' '), ' ') as waluta, Z.katcol0, Z.opis, Z.kwota, Z.stronaWN,
			Z.nr_dekretu, Z.nr_pozycji, Z.rodzaj_fk, Z.numer_dok, Z.data_oper, Z.uid, Z.lp,
			Z.Id_Obcy, Z.idnwaluty, Z.kurs_waluty, Z.data_ksiegowania, Z.data_korekty,
			Z.pozabilans, Z.wzordekr, RD.nazwa as RodzajDowodu, if(Z.stronaWn = 1,Z.kwota,0) as WN, 
			if(Z.stronaWn = 0,Z.kwota,0) as MA, 
			(select valuex from v_kpk0 KC where Z.katcol0=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK0,
			(select valuex from v_kpk1 KC where Z.katcol1=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK1,
			(select valuex from v_kpk2 KC where Z.katcol2=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK2,
			(select valuex from v_kpk3 KC where Z.katcol3=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK3,
			(select valuex from v_kpk4 KC where Z.katcol4=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK4,
			(select valuex from v_kza0 KC where Z.katcol5=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK5,
			(select valuex from v_kza1 KC where Z.katcol6=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK6,
			(select valuex from v_kza2 KC where Z.katcol7=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK7,
			(select valuex from v_kza3 KC where Z.katcol8=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK8,
			(select valuex from v_kza4 KC where Z.katcol9=KC.klucz AND KC.rok IN(0, Z.Rok) ) as katLK9 
		FROM
			zapisy Z 
		LEFT JOIN plankont P ON P.symbol=Z.konto AND P.Rok = Z.Rok 
		LEFT JOIN rodzaje_dowodow RD ON RD.symbol=Z.RodzajDowodu 
		LEFT JOIN opng O ON O.GUID=Z.IdnOper 
		LEFT JOIN waluty W ON W.idn=O.waluta 
		WHERE
			Z.idnoper in (select distinct idnoper from	t_zestdowod)
		ORDER BY Z.numer_dok, Z.lp
		;
	
	END IF;
		
END$$

