DELIMITER $$

DROP PROCEDURE IF EXISTS `qs_get_wyjazdy`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `qs_get_wyjazdy`(
	IN _MODE VARCHAR(50),
	  _nadzien DATE,
	  _kontrGUID VARCHAR(38)
	)
	
BEGIN
/*
	Procedura zwracajaca wyjazdy na podstawie daty i ewentualnie guidu kontrahenta
*/

DECLARE _ugrpGUID VARCHAR(38);
DECLARE _areaGUID VARCHAR(38);

IF _MODE IN ('0','1') THEN
	SET _areaGUID='',_ugrpGUID='';
	IF _kontrGUID<>'' THEN
	  SELECT ifnull(ugrpGUID,''),ifnull(areaguid,'') FROM kontrah WHERE GUID=_kontrGUID INTO _ugrpGUID,_areaGUID;
	END IF;

	IF IFNULL(_nadzien,'0000-00-00')='0000-00-00' THEN
	  SET _nadzien=CURRENT_DATE;
	END IF;

	SELECT 
	ean.nazwa AS trasa,
	DATE(crm.starttime) AS dzien,
	crm.temat, crm.opis, crm.nrwewn,
	crm.GUID AS wyjazdGUID,
	ean.dzial as oddzial
	FROM crm_commisions crm
	LEFT JOIN erp_area_nodes ean ON ean.GUID=crm.areaGUID
	WHERE crm.rodzaj=5 AND crm.podrodzaj=1 AND crm.deleted=0 
	AND DATE(crm.starttime)=_nadzien 
/*
	AND (
	IF(IFNULL(_ugrpGUID,'') NOT IN ('','ALL'), ean.dzial=_ugrpGUID, TRUE) OR
	IF(IFNULL(_ugrpGUID,'') IN ('WL','GD'), ean.dzial IN ('WL','GD'), FALSE)
	)
	AND IF(_areaGUID<>'', ean.GUID=_areaGUID or _MODE='1', TRUE);
do 2014-06-05
*/
	AND (_ugrpGUID in ('','ALL') or ean.dzial=_ugrpGUID)
	AND (_areaGUID='' or _MODE='1' or ean.GUID=_areaGUID);
	
	SET @nadzien:=_nadzien;
	SET @areaguid:=_areaguid;
	SET @ugrpguid:=_ugrpguid;
	
END IF;  -- MODE 0

-- testy
-- CALL qs_get_wyjazdy('0','2013-06-04','{3DF8A211-93B2-4023-AC30-E63EB6BA48BD}');select @ugrpguid,@areaguid;
-- CALL qs_get_wyjazdy('0','2013-06-04','{BFBC4FAA-DF40-4AEB-A55F-48A6911A0280}');select @ugrpguid,@areaguid;

END$$

DELIMITER ;
