 SET NAMES utf8;
DELIMITER $$

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

	IF NEW.Start_Status != '' AND NEW.confirm_status = '' THEN
		SET NEW.confirm_status = NEW.Start_Status;
	ELSEIF NEW.Start_Status = '' AND NEW.confirm_status != '' THEN
		SET NEW.confirm_status = '';
	END IF;
	
	IF @session.globals.WORK.FLOW.Ver IS NULL THEN CALL _Globals_Get_2('WORK.FLOW.Ver', @session.globals.WORK.FLOW.Ver, '2015', '?'); END IF;
	
	IF !(NEW.commisionGUID <=> NEW.wGUID) THEN
		IF IFNULL(NEW.wGUID, '') <> '' THEN
			SET NEW.commisionGUID = NEW.wGUID;
		ELSE
			SET NEW.wGUID = NEW.commisionGUID;
		END IF;
	END IF;
    SELECT wd.Is_Ending INTO @.NEW.Is_Ending FROM `crm_workflow_def` wd WHERE wd.Def = NEW.Def AND wd.Status = NEW.Start_Status;
    SET NEW.Is_Ending = @.NEW.Is_Ending;
	-- IF IFNULL((SELECT wd.Is_Ending FROM `crm_workflow_def` wd WHERE wd.Def = NEW.Def AND wd.Status = NEW.Start_Status), FALSE) THEN
    IF IFNULL(NEW.Is_Ending, 0) THEN
		SET NEW.Response = 'RESPONSE_100';
	END IF;
END;
$$

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

--	zmienna: aktualny idn idn crm_workflow
	SET @.cw.NEW.IDN = NEW.IDN;
	IF IFNULL(@.cw.NEW.IDN, 0) = 0 THEN
		SET @.cw.NEW.IDN = LAST_INSERT_ID();
	END IF;
--	i jeszcze do starej zmiennej... potrzebne?	
	SET @.LAST_INSERT_ID = @.cw.NEW.IDN;
	/*	a to stare ... potrzebne?	
		SET @.LAST_INSERT_ID = NEW.IDN;
		IF IFNULL(@.LAST_INSERT_ID, 0) = 0 THEN
			SET @.LAST_INSERT_ID = LAST_INSERT_ID();
		END IF;
	*/	
	IF @session.globals.WORK.FLOW.Ver IS NULL THEN CALL _Globals_Get_2('WORK.FLOW.Ver', @session.globals.WORK.FLOW.Ver, '2015', '?'); END IF;
		IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			SELECT
				cwn.uOwner, cwn.uCreator
			INTO 
				@.cw.uOwner, @.cw.uCreator	-- nowe zmienne
			FROM `crm_workflow_n` cwn
			WHERE
				cwn.GUID = NEW.commisionGUID
			;
			SET
				@.cw.uCreator = IFNULL(NULLIF(@.cw.uCreator, ''), @.cw.uOwner)
			;
		--	do starych zmiennych	
			SET
				@.cw.Owner_GUID = @.cw.uOwner,
				@.cw.Creator_GUID = @.cw.uCreator
			;
		ELSE
		SET
			@.cw.Owner_GUID = (SELECT culowner.Osoba FROM `crm_usr_links` culowner WHERE culowner.commisionGUID = NEW.commisionGUID AND culowner.Poziom = 2),
			@.cw.Creator_GUID = (SELECT culowner.Osoba FROM `crm_usr_links` culowner WHERE culowner.commisionGUID = NEW.commisionGUID AND culowner.Poziom = 0)
		;
		END IF;
		SET @session.globals.crm_workflow.Ver = IFNULL(@session.globals.crm_workflow.Ver, '1.0');
		IF NEW.Start_Status IN ('new', 'amendment') THEN	-- nowy lub poprawka
		/******************************************************************************************
			Wstaw do `crm_workflow_confirm` odp. interesariuszy
		******************************************************************************************/
		
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
				IF @.cwLog.IDN IS NULL THEN
					INSERT IGNORE INTO `crm_workflow_log_n`
					SET
						wGUID = NEW.wGUID
					;
					SET @.cwLog.IDN = IFNULL(@.cwLog.IDN, LAST_INSERT_ID());
				END IF;
				INSERT IGNORE INTO `crm_workflow_log_p`
				(LogIdn, OP, cwIdn, uWe, uDec, cwStatus1, cwStatus2, uType)
				SELECT
					cwln.IDN AS LogIdn,
					'cwc.FIRST' AS OP,
					NEW.Idn AS cwIdn,
					IFNULL(@.cw.uCreator, @.cw.uOwner) AS uWe, 
					IFNULL(@.cw.uCreator, @.cw.uOwner) AS uDec, 
					'' AS cwStatus1, 
					'new' AS cwStatus2,
					'uCreator' AS uType
				FROM `crm_workflow_log_n` cwln
				WHERE
					cwln.IDN = @.cwLog.IDN
				;
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm`  
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			VALUES
			(@.cw.NEW.IDN, @.cw.uOwner, NEW.commisionGUID, 'new', 'uOwner')
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			VALUES
			(@.LAST_INSERT_ID, @.cw.Owner_GUID)
			;
			END IF;
		ELSEIF NEW.Response != 'RESPONSE_100' THEN
		/******************************************************************************************
		--	Wstaw do `crm_workflow_confirm` odp. interesariuszy 
		--	Osoby albo grupy zatem nie! 'szef','bryg','zastepca','owner',''
		******************************************************************************************/
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			SELECT 
				@.cw.NEW.IDN, cwdr.UserGUID, 
				NEW.commisionGUID, NEW.Start_Status, 
				'uDecd' AS uType
			FROM `crm_workflow_def_responsible` cwdr
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND (cwdr.UserGUID != 'szef')
				AND (cwdr.UserGUID != 'bryg')
				AND (cwdr.UserGUID != 'zastepca')
				AND (cwdr.UserGUID != 'owner')
				AND (cwdr.UserGUID != '')
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			SELECT 
				@.LAST_INSERT_ID, cwdr.UserGUID
			FROM `crm_workflow_def_responsible` cwdr
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND (cwdr.UserGUID != 'szef')
				AND (cwdr.UserGUID != 'bryg')
				AND (cwdr.UserGUID != 'zastepca')
				AND (cwdr.UserGUID != 'owner')
				AND (cwdr.UserGUID != '')
			;
			END IF;
		/******************************************************************************************
			OWNER - właściciel wniosku - 
			w UserGUID ma 'owner' lub ''
			Zazwyczaj jest tam '' ale to dotyczy głownie końcowych węzłów a wtedy tu 
			i tak nie wejdziemy
		******************************************************************************************/
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			SELECT 
				@.cw.NEW.IDN, @.cw.uOwner, 
				NEW.commisionGUID, NEW.Start_Status, 
				'uOwner' AS uType
			FROM `crm_workflow_def_responsible` cwdr
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND (cwdr.UserGUID IN ('', 'owner'))
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			SELECT 
				@.LAST_INSERT_ID, @.cw.Owner_GUID
			FROM `crm_workflow_def_responsible` cwdr
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND (cwdr.UserGUID IN ('', 'owner'))
			;
			END IF;
		/******************************************************************************************
			Szefowie
			Wstaw do `crm_workflow_confirm` szefow odp. interesariuszy 
		******************************************************************************************/
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			SELECT 
				@.cw.NEW.IDN, IFNULL(zast.OsobaGUID_B, hl.OsobaGUID_B),	-- gdy nie ma (NULL) zast. szefa to szef którey tez jest z linkowni od właściciela worflow
				NEW.commisionGUID, NEW.Start_Status, 
				'uSzef' AS uType
			FROM `crm_workflow_def_responsible` cwdr
			INNER JOIN `hr_self_links` hl ON hl.OsobaGUID_A = @.cw.Owner_GUID AND hl.rel = 'szef'
			LEFT JOIN  `hr_self_links` zast ON zast.OsobaGUID_A = hl.OsobaGUID_B 
				AND zast.Rel = '<-zastepca' AND zast.Status = 0 AND NOW() BETWEEN zast.DateFrom AND zast.DateTo
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'szef'
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			SELECT 
				@.LAST_INSERT_ID, IFNULL(zast.OsobaGUID_B, hl.OsobaGUID_B)	-- gdy nie ma (NULL) zast. szefa to szef którey tez jest z linkowni od właściciela worflow
			FROM `crm_workflow_def_responsible` cwdr
			INNER JOIN `hr_self_links` hl ON hl.OsobaGUID_A = @.cw.Owner_GUID AND hl.rel = 'szef'
			LEFT JOIN  `hr_self_links` zast ON zast.OsobaGUID_A = hl.OsobaGUID_B 
				AND zast.Rel = '<-zastepca' AND zast.Status = 0 AND NOW() BETWEEN zast.DateFrom AND zast.DateTo
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'szef'
			;
			END IF;
		/******************************************************************************************
			Brygadzisci czyli jakby kieronicy/opiekunowie
			Wstaw do `crm_workflow_confirm` brygadzistow odp. interesariuszy 
		******************************************************************************************/
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			SELECT 
				@.cw.NEW.IDN, hl.OsobaGUID_B, 
				NEW.commisionGUID, NEW.Start_Status, 
				'uBryg' AS uType
			FROM `crm_workflow_def_responsible` cwdr, `hr_self_links` hl
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'bryg'
				AND hl.OsobaGUID_A = @.cw.Owner_GUID
				AND hl.rel = 'bryg'
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			SELECT 
				@.LAST_INSERT_ID, hl.OsobaGUID_B
			FROM `crm_workflow_def_responsible` cwdr, `hr_self_links` hl
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'bryg'
				AND hl.OsobaGUID_A = @.cw.Owner_GUID
				AND hl.rel = 'bryg'
			;
			END IF;
		/******************************************************************************************
			Zastępujący
			Wstaw do `crm_workflow_confirm` zastepujacych
		******************************************************************************************/
			IF @session.globals.WORK.FLOW.Ver >= '2024' THEN
			-- IF @session.globals.crm_workflow.Ver = '2.0' THEN
			/******************************
			Nowy Workflow (I 2024)
			******************************/
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID, wGUID, Start_Status, uType)
			SELECT 
				@.cw.NEW.IDN, hl.OsobaGUID_B, 
				NEW.commisionGUID, NEW.Start_Status, 
				'uZast' AS uType
			FROM `crm_workflow_def_responsible` cwdr, `hr_self_links` hl
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'zastepca'
				AND hl.OsobaGUID_A = @.cw.Owner_GUID
				AND hl.rel = '<-zastepca'
				AND hl.A_Rel_Unique = 1
			;
			ELSE
			INSERT IGNORE INTO `crm_workflow_confirm` 
			(IDN_workflow, UserGUID)
			SELECT 
				@.LAST_INSERT_ID, hl.OsobaGUID_B
			FROM `crm_workflow_def_responsible` cwdr, `hr_self_links` hl
			WHERE
				cwdr.Def = NEW.Def
				AND cwdr.Status = NEW.Start_Status
				AND cwdr.UserGUID = 'zastepca'
				AND hl.OsobaGUID_A = @.cw.Owner_GUID
				AND hl.rel = '<-zastepca'
				AND hl.A_Rel_Unique = 1
			;
			END IF;
		END IF;
	--	Dodatkowo wstaw do wysyłki mailowej
	/*
		INSERT IGNORE INTO `crm_workflow_confirm` 
		(IDN_workflow, UserGUID)
		SELECT 
			@.LAST_INSERT_ID, cwdr.UserGUID
		FROM `crm_workflow_def_responsible` cwdr
		WHERE
			cwdr.Def = NEW.Def
			AND cwdr.Status = NEW.Start_Status
			AND cwdr.notification IS NOT NULL
		;
	*/	
	--	Dodatkowo wstaw do wysyłki smsowej
	/*
		INSERT IGNORE INTO `crm_workflow_confirm` 
		(IDN_workflow, UserGUID)
		SELECT 
			@.LAST_INSERT_ID, cwdr.UserGUID
		FROM `crm_workflow_def_responsible` cwdr
		WHERE
			cwdr.Def = NEW.Def
			AND cwdr.Status = NEW.Start_Status
			AND cwdr.notification IS NOT NULL
		;
	*/	
	
--	FINAL UnLock trigger zmienna @session.trigger.xxx
	--	SET @session.trigger.crm_workflow = FALSE;
END;
$$

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

	/*
	IF IFNULL((SELECT wd.Is_Ending FROM `crm_workflow_def` wd WHERE wd.Def = NEW.Def AND wd.Status = NEW.Start_Status), FALSE) THEN
		SET NEW.Response = 'RESPONSE_100';
	END IF;
	*/
	IF @session.globals.WORK.FLOW.Ver IS NULL THEN CALL _Globals_Get_2('WORK.FLOW.Ver', @session.globals.WORK.FLOW.Ver, '2015', '?'); END IF;
	
	SET NEW.confirm_status = IF(NEW.confirm_status IN ('', 'BACK'), NEW.Start_Status, NEW.confirm_status);
	
	IF NEW.Update_status != '' THEN
		SET @.crm_workflow.NEW.Update_status = NEW.Update_status;
		IF NEW.Update_status = 'CALC_FROM_crm_workflow_confirm' THEN
			IF IFNULL((SELECT wd.Is_Ending FROM `crm_workflow_def` wd WHERE wd.Def = NEW.Def AND wd.Status = NEW.Start_Status), FALSE) THEN
				SET NEW.Response = 'RESPONSE_100';
			ELSE
			
			set @.cw.debug = concat_WS('/', @.cw.debug, 'DROP, CREATE');
				DROP TEMPORARY TABLE IF EXISTS `t_trigg_sel_crm_workflow`;
				CREATE TEMPORARY TABLE `t_trigg_sel_crm_workflow`
				SELECT
					tcwc.MinStatus_Full,
					tcwc.MinStatus,
					tcwc.CC,
					tcwc.CResponse,
					cwd.Status AS confirm_status,
					cwd.Is_Ending
				FROM 
				(
					SELECT 
						MIN(
							CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status))
						) AS MinStatus_Full,
						SUBSTR(
							MIN(CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status))), 
						6,100) AS MinStatus,
						COUNT(*) AS CC,
						IFNULL(SUM(NEW.Start_Status != IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status)), 0) AS CResponse
						-- s.Is_Ending,
						-- NEW.confirm_status,
						-- NEW.Def
						-- _VarStr(CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status)))
					FROM `crm_workflow_confirm` cwc
					INNER JOIN `crm_workflow_def` s ON s.Status = IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status) AND s.Def = NEW.Def
					WHERE
						cwc.IDN_workflow = NEW.IDN
				) tcwc
				LEFT JOIN `crm_workflow_def` cwd ON 
					cwd.Def = NEW.Def 
					AND 
					cwd.Status = 
						IF(tcwc.CC > 0, 
							tcwc.MinStatus, 
							NEW.confirm_status
						)
				;
			
			
			
				-- IF @session.globals.Owner = 'KONKOL' AND SCHEMA() = 'zoo' THEN
			set @.cw.debug = concat_WS('/', @.cw.debug, 'SET NULL');
				SET
					@.crm_workflow.ResponseCount = NULL,  -- CResponse,
					@.crm_workflow.confirm_status = NULL,
					@.crm_workflow.Response = NULL,
					@.crm_workflow.Is_Ending = NULL,
					@.crm_workflow.WasDecision = NULL,
					
					@.crm_workflow.MinStatus_Full = NULL,
					@.crm_workflow.MinStatus = NULL,
					@.crm_workflow.CC = NULL
					
				;
				/*
				SELECT
					tcwc.MinStatus_Full,
					tcwc.MinStatus,
					tcwc.CC,
					tcwc.CResponse,
					cwd.Status AS confirm_status,
					cwd.Is_Ending
					
				FROM 
				(
					SELECT 
						MIN(
							CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status))
						) AS MinStatus_Full,
						SUBSTR(
							MIN(CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status))), 
						6,100) AS MinStatus,
						COUNT(*) AS CC,
						IFNULL(SUM(NEW.Start_Status != IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status)), 0) AS CResponse
						-- s.Is_Ending,
						-- NEW.confirm_status,
						-- NEW.Def
						-- _VarStr(CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status)))
					FROM `crm_workflow_confirm` cwc
					INNER JOIN `crm_workflow_def` s ON s.Status = IF(cwc.confirm_status = '', NEW.Start_Status, cwc.confirm_status) AND s.Def = NEW.Def
					WHERE
						cwc.IDN_workflow = NEW.IDN
				) tcwc
				LEFT JOIN `crm_workflow_def` cwd ON 
					cwd.Def = NEW.Def 
					AND 
					cwd.Status = 
						IF(tcwc.CC > 0, 
							tcwc.MinStatus, 
							NEW.confirm_status
						)
				INTO
					@.crm_workflow.MinStatus_Full,
					@.crm_workflow.MinStatus,
					@.crm_workflow.CC,
					@.crm_workflow.ResponseCount, -- CResponse,
					@.crm_workflow.confirm_status,
					@.crm_workflow.Is_Ending
				;
				SET
					@.crm_workflow.Response = 
						IF(@.crm_workflow.CC = @.crm_workflow.ResponseCount, 
							'RESPONSE_100',
							IF(@.crm_workflow.ResponseCount > 0,
								'RESPONSE_50',
								'RESPONSE_0'
							)
						),
					@.crm_workflow.WasDecision = (@.crm_workflow.ResponseCount > 0)
				;	
				*/
					/*
					SELECT 
						t.CResponse AS ResponseCount,
						t.confirm_status, 
						IF(t.CC > 0, t.Is_Ending, NULL) AS Is_Ending,
						IF(t.CC = t.CResponse, 
							'RESPONSE_100',
							IF(t.CResponse > 0,
								'RESPONSE_50',
								'RESPONSE_0'
							)
						) AS Response,
						t.CResponse > 0 AS WasDecision
					FROM `t_trigg_sel_crm_workflow` t 
					LIMIT 1
					INTO
						@.crm_workflow.ResponseCount,
						@.crm_workflow.confirm_status,
						@.crm_workflow.Is_Ending,
						@.crm_workflow.Response,
						@.crm_workflow.WasDecision
					;
					*/
				SELECT
					tcwc.CResponse AS ResponseCount,
					tcwc.confirm_status,
					IF(tcwc.CC = tcwc.CResponse, 
						'RESPONSE_100',
						IF(tcwc.CResponse > 0,
							'RESPONSE_50',
							'RESPONSE_0'
						)
					) AS Response,
					IF(tcwc.CC > 0, tcwc.Is_Ending, NULL) AS Is_Ending,
					tcwc.CResponse > 0 AS WasDecision
				INTO
					@.crm_workflow.ResponseCount, -- CResponse,
					@.crm_workflow.confirm_status,
					@.crm_workflow.Response,
					@.crm_workflow.Is_Ending,
					@.crm_workflow.WasDecision
				FROM `t_trigg_sel_crm_workflow` tcwc
				WHERE
					tcwc.CC >= 0
				LIMIT 1
				;
			set @.cw.debug = concat_WS('/', @.cw.debug, 'SET...');
				SET 
					NEW.ResponseCount = IFNULL(@.crm_workflow.ResponseCount, 0),
					NEW.confirm_status = IFNULL(@.crm_workflow.confirm_status, NEW.confirm_status),
					NEW.Is_Ending = IFNULL(IFNULL(@.crm_workflow.Is_Ending, NEW.Is_Ending), 0),
					NEW.Response = IFNULL(@.crm_workflow.Response, NEW.Response),
					-- NEW.WasDecision = NEW.WasDecision OR IFNULL(@.crm_workflow.WasDecision, FALSE)
					NEW.WasDecision = NEW.WasDecision + IFNULL(@.crm_workflow.WasDecision, 0)
				;
					
			END IF;

		END IF;
		
	END IF;
	
    -- SET NEW.Is_Ending = IFNULL(NEW.Is_Ending, 0);
	IF !(NEW.confirm_status <=> OLD.confirm_status) THEN
		SET NEW.DecisionAt = NOW();	-- 	od teraz nie wolno usunac tego rekordu z powodu anulowania decyzji punktu = Prev_IDN_workflow ()
	END IF;
	
	SET NEW.Update_status = '';	--	zawsze
	
END;
$$

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


	SET @.crm_workflow.NEW.Update_status = NEW.Update_status;
	SET @.cw.NEW.Change.Decision = !(NEW.Confirm_Status <=> OLD.Confirm_Status);
	IF @.cw.NEW.Change.Decision THEN
		IF @.cwLog.IDN IS NULL THEN
			INSERT IGNORE INTO `crm_workflow_log_n`
			SET
				wGUID = NEW.wGUID
			;
			SET @.cwLog.IDN = IFNULL(@.cwLog.IDN, LAST_INSERT_ID());
		END IF;
		INSERT IGNORE INTO `crm_workflow_log_p`
		(LogIdn, OP, cwIdn, uWe, uDec, cwStatus1, cwStatus2)
		SELECT
			cwln.IDN AS LogIdn,
			'cw.CHANGE' AS OP,
			NEW.Idn AS cwIdn,
			'' AS uWe, 
			'' AS uDec, 
			IFNULL(NULLIF(OLD.Confirm_Status, ''), NEW.Start_Status) AS cwStatus1,
			IFNULL(NULLIF(NEW.Confirm_Status, ''), NEW.Start_Status) AS cwStatus2
		FROM `crm_workflow_log_n` cwln
		WHERE
			cwln.IDN = @.cwLog.IDN
		;
	END IF;

--	FINAL UnLock trigger zmienna @session.trigger.xxx
	--	SET @session.trigger.crm_workflow = FALSE;
END;
$$

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


/* ************************************************************************************************************************************************************************
	AD
************************************************************************************************************************************************************************ */	
DROP TRIGGER IF EXISTS `crm_workflow_ad`$$
CREATE DEFINER = `root`@`localhost` TRIGGER `crm_workflow_ad` AFTER DELETE ON `crm_workflow` FOR EACH ROW 
A: BEGIN
	IF _TriggerDisabled() THEN LEAVE A; END IF;
--	INIT Lock trigger zmienna @session.trigger.xxx
	--	IF IFNULL(@session.trigger.crm_workflow, FALSE) THEN LEAVE A; END IF;
	--	SET @session.trigger.crm_workflow = TRUE;

	DELETE FROM `crm_workflow_confirm` WHERE IDN_workflow = OLD.IDN;

--	FINAL UnLock trigger zmienna @session.trigger.xxx
	--	SET @session.trigger.crm_workflow = FALSE;
END;
$$


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

DROP PROCEDURE IF EXISTS `crm_workflow_TOOLS`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `crm_workflow_TOOLS`(
	IN _MODE VARCHAR(250),	 --	_handle_oper INSERT, EDIT, DELETE,
	IN _ID VARCHAR(38),		-- 	Zdarzenie, IDN, etc
	IN _ID_2 VARCHAR(38),	-- 	Zdarzenie, IDN, etc
	IN _Param_A VARCHAR(250),	
	IN _Param_B VARCHAR(250),
	IN _Param_C VARCHAR(250),	
	IN _Param_D Text
)
/*
	CALL crm_workflow_TOOLS('', 'GUID', '', 'OsobaGUID', @Poziom, 0, NULL, NULL, '', '');
*/	
S_crm_workflow_TOOLS: BEGIN
	DECLARE _SQLText MEDIUMTEXT;
-- set  @session.globals.WORK.FLOW.Ver = 2022;
	IF @session.globals.WORK.FLOW.Ver IS NULL THEN CALL _Globals_Get_2('WORK.FLOW.Ver', @session.globals.WORK.FLOW.Ver, '2015', '?'); END IF;
				IF _MODE = 'TECH.confirm.Response' THEN
				/************************************************************************************************************************************************
					Proc. techniczna - specjalny confirme fabryczny/migracja danych etc.
					Ustaw status/decyzję dla danego workflow
					UWAGA nie bada zgodności ani tego czy nie ma dalszych IDNów
					CALL crm_workflow_TOOLS('TECH.confirm.Response', 8, 'status_przed', 'status_po', '', '', 'komentarz');
					_ID 	IDN p.decyz.
					_ID_2 	niejest konieczny UserGUID
					_Param_A	Decyzja (Status) inicjalny
					_Param_B	Decyzja (Status) finalny
					_Param_D	TEXT to adnotacja do pola `Comment`
				************************************************************************************************************************************************/
							set @.cw.Start_Status = _Param_A, @.cw.End_Status = _Param_B;
					UPDATE `crm_workflow` cw
					SET
						cw.Start_Status = _Param_A,
						cw.Confirm_Status = _Param_A
					WHERE
						cw.IDN = _ID
					;
					CALL crm_workflow_TOOLS('confirm.Response', _ID, '', _Param_B, 'TECHN', '', _Param_D);
				END IF;
				
	IF _MODE = 'confirm.Response' THEN
	/************************************************************************************************************************************************
		Podejmij decyzje
		CALL crm_workflow_TOOLS('confirm.Response', 8, @UserGUID, 'decyzjastatus', '', '', 'koment');
		_ID 	IDN p.decyz.
		_ID_2 	UserGUID
		_Param_A	Decyzja (Status)
		_Param_B	gdy "TECHN" to specjalny confirme fabryczny/migracja danych etc.
		_Param_D	TEXT to adnotacja do pola `Comment`
	************************************************************************************************************************************************/
		SET
			@.resp.IDN = _ID,
			@.resp.Confirm_Status = _Param_A,
			@.resp.Undo = _Param_A = 'UNDO',
			@resp.TECHN = (_Param_B = 'TECHN')
		;
		IF @session.globals.WORK.FLOW.Ver >= '2024.02' THEN
			CALL P_crm_workflow_n('cw.confirm.Response', '', @.resp.IDN, NULL, _ID_2, @.resp.Confirm_Status, @resp.TECHN, _Param_D, @_Params);
		--	zapytaj Darka czy nie potrzebuje select-a zwracanego - patrz nużej za else
			LEAVE S_crm_workflow_TOOLS;
		END IF;

		CALL crm_workflow_TOOLS('Get.Info', @.resp.IDN, '', '', '', '', '');
		SET @resp.TECHN = (_Param_B = 'TECHN');
		IF NOT IFNULL(@resp.IS_Disabled, TRUE) THEN
						set @._Param_A = _Param_A;
			SET 
				@resp.IDN_workflow = NULL, 
				@resp.Decision_UserGUID = NULL,
				@resp.UNDO = _Param_A = 'UNDO' 
			; 
			UPDATE `crm_workflow_confirm` cwc
			SET
				cwc.Confirm_Status = IF(@resp.UNDO, '', _Param_A),
				cwc.Decision_UserGUID = 
					IF(@resp.UNDO, 
						'', 
						IF(@resp.TECHN,
							cwc.UserGUID,
							_ID_2
						)
					),
				cwc.Comment = IF(IFNULL(_Param_D, '') != '', _Param_D, cwc.Comment)
			WHERE
				cwc.IDN_workflow = _ID
				AND
				-- cwc.UserGUID = _ID_2
				(
					@resp.TECHN
					OR
					_ID_2 IN (SELECT go.OsobaGUID FROM `grupy_osob` go WHERE go.grupaGUID = cwc.UserGUID)
				)
			;
			SET @resp.AU.RC = ROW_COUNT();
			IF @resp.AU.RC > 0 THEN
				SET @resp.AU.IDN_workflow = _ID, @resp.AU.Decision_UserGUID = _ID_2; 
				
				
				-- IF @session.globals.Owner = 'KONKOL' AND SCHEMA() = 'zoo' THEN
				IF TRUE THEN
				
					CALL crm_workflow_TOOLS('Confim.workflow.node.and.crm', _ID, '', '', '', '', '');
					CALL crm_workflow_TOOLS('Get.Info', _ID, '', '', '', '', '');
				--	Usun nastepnik o ile w ogole istnieje	
					DELETE FROM `crm_workflow` WHERE Prev_IDN_workflow = _ID;

				ELSE
				
					UPDATE `crm_workflow` cw
					SET
						cw.Update_status = 'CALC_FROM_crm_workflow_confirm'
					WHERE
						cw.IDN = _ID 
					;
					CALL crm_workflow_TOOLS('Get.Info', _ID, '', '', '', '', '');
				--	Usun nastepnik o ile w ogole istnieje	
					DELETE FROM `crm_workflow` WHERE Prev_IDN_workflow = _ID;
					IF @resp.Has_Decision OR (_Param_A = 'UNDO') THEN
					/*	było po staremu i NADAL TAK MOŻNA ale ...
						UPDATE `crm_commisions` c 
						SET 
							c.Update_status = 'check.crm_workflow'
						WHERE
							c.GUID = @resp.commisionGUID
						;
					*/
						UPDATE `crm_commisions` c,
							(
							SELECT 	
								cw.Confirm_Status,
								cwd.crm_Status
							FROM `crm_workflow` cw, `crm_workflow_def` cwd
							WHERE 
								cw.commisionGUID = @resp.commisionGUID
								AND cwd.Def = cw.Def AND cwd.Status = cw.Confirm_Status
							ORDER BY cw.idn DESC 
							LIMIT 1
							) cw
						SET
							c.Confirm_Status = cw.Confirm_Status,
							c.Status = cw.crm_Status
						WHERE
							c.GUID = @resp.commisionGUID
						;				
					--	Tutaj dodatkowo wyślij do zrobienia inne rzeczy	
					
					END IF;	
				END IF; -- owner <> KONKOL zoo`
set @resp.watch = concat_WS(' / ', concat_WS(',', @resp.ProcExtNotify));				
				-- było IF @resp.ProcExtNotify <> '' AND @session.globals.WORK.FLOW.Ver >= 2022 THEN
				IF 
					(@resp.Has_Decision OR @resp.UNDO) 
					AND @session.globals.WORK.FLOW.Ver >= 2022 
					AND NOT @resp.TECHN 
				THEN
set @resp.watch = concat_WS(' / ', concat_WS(',', _ID, _ID_2, _Param_A, @resp.Owner_GUID, @resp.ProcExtNotify));				
				--	w @resp.ExtNotify mam inf. co mam po tej decyzji wykonać
					CALL crm_workflow_TOOLS('ExtNotify.AFTER.confirm.Response', _ID, _ID_2, _Param_A, @resp.Owner_GUID, @resp.ProcExtNotify, '');
				END IF;
set @resp.watch = concat_WS(' / ', @resp.watch, 'Przed Insert.Next');				
				IF 
					@resp.Has_Decision 
				--	dodałem 18 II 2022 aby nie tworzył nastepnego - zbednego noda dla noda który jest końcowy!!!	
					AND NOT @resp.Is_Ending
				THEN
set @resp.watch = concat_WS(' / ', @resp.watch, 'Insert.Next');				
					CALL crm_workflow_TOOLS('Insert.Next', _ID, '', '', '', '', '');
				END IF;
			END IF;
		ELSE
			SELECT 'Nie mozna juz podejmowac decyzji';
		END IF;
	END IF;

	IF _MODE = 'confirm.UnDo' THEN
	/************************************************************************************************************************************************
		Cofnij decyzje
		CALL crm_workflow_TOOLS('confirm.UnDo', 8, @UserGUID, '', '', '', '');
		_ID 	IDN p.decyz.
		_ID_2 	UserGUID
	************************************************************************************************************************************************/
		CALL crm_workflow_TOOLS('confirm.Response', _ID, _ID_2, 'UNDO', '', '', '');
	END IF;

			IF _MODE = 'Confim.workflow.node.and.crm' THEN
			/************************************************************************************************************************************************
				Zwykle wstawianie następnika
				CALL crm_workflow_TOOLS('Confim.workflow.node.and.crm', '8', '', '', '', '', '');
				_ID IDN p.decyz.
			************************************************************************************************************************************************/
				SET
					@.resp.IDN = _ID
				;
				DROP TEMPORARY TABLE IF EXISTS `t_trigg_sel_crm_workflow`;
				CREATE TEMPORARY TABLE `t_trigg_sel_crm_workflow`
				SELECT
					tcwc.Idn,
					tcwc.Def,
					tcwc.commisionGUID,
					tcwc.MinStatus_Full,
					tcwc.MinStatus,
					tcwc.CC,
					tcwc.CResponse,
					cwd.Status AS confirm_status,
					cwd.Is_Ending
				FROM 
				(
					SELECT 
						cw.Idn,
						cw.Def,
						cw.commisionGUID,
						cw.confirm_status AS confirm_status_OLD,
						MIN(
							CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', cw.Start_Status, cwc.confirm_status))
						) AS MinStatus_Full,
						SUBSTR(
							MIN(CONCAT(LPAD(s.Poziom, 5, 0), IF(cwc.confirm_status = '', cw.Start_Status, cwc.confirm_status))
							), 
						6,100) AS MinStatus,
						COUNT(*) AS CC,
						IFNULL(SUM(cw.Start_Status != IF(cwc.confirm_status = '', cw.Start_Status, cwc.confirm_status)), 0) AS CResponse
					FROM `crm_workflow` cw
					INNER JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
					INNER JOIN `crm_workflow_def` s ON s.Status = IF(cwc.confirm_status = '', cw.Start_Status, cwc.confirm_status) AND s.Def = cw.Def
					WHERE
						cw.IDN = @.resp.IDN
						-- cwc.IDN_workflow = @.resp.IDN
				) tcwc
				LEFT JOIN `crm_workflow_def` cwd ON 
					cwd.Def = tcwc.Def 
					AND 
					cwd.Status = 
						IF(tcwc.CC > 0, 
							tcwc.MinStatus, 
							tcwc.confirm_status_OLD
						)
				;
				UPDATE `crm_workflow` cw, `t_trigg_sel_crm_workflow` t
				SET
					cw.ResponseCount = t.CResponse,
					cw.confirm_status = t.confirm_status,
					cw.Is_Ending = IF(t.CC > 0, t.Is_Ending, NULL),
					cw.Response =
						IF(t.CC = t.CResponse,
							'RESPONSE_100',
							IF(t.CResponse > 0,
								'RESPONSE_50',
								'RESPONSE_0'
							)
						),
					cw.WasDecision = cw.WasDecision OR (t.CResponse > 0)
				WHERE
					cw.IDN = t.IDN
					AND t.CC >= 0
				;

				SET @resp.crm_workflow.RC = ROW_COUNT();
				IF @resp.crm_workflow.RC > 0 THEN
				--	Usun nastepnik o ile w ogole istnieje BO crm updatuje się wg ostatniego!!!
					DELETE FROM `crm_workflow` WHERE Prev_IDN_workflow = _ID;
				--	Update crm	
					UPDATE `crm_commisions` c,
						(
						SELECT 	
							cw.commisionGUID,
							cw.Confirm_Status,
							cwd.crm_Status
						FROM `t_trigg_sel_crm_workflow` t, `crm_workflow` cw, `crm_workflow_def` cwd
						WHERE 
							cw.commisionGUID = t.commisionGUID
							AND cwd.Def = cw.Def AND cwd.Status = cw.Confirm_Status
						ORDER BY cw.idn DESC 
						LIMIT 1
						) cwlast
					SET
						c.Confirm_Status = cwlast.Confirm_Status,
						c.Status = cwlast.crm_Status
					WHERE
						c.GUID = cwlast.commisionGUID
					;				
				END IF;
			END IF;
	
			IF _MODE = 'Get.Info' THEN
			/************************************************************************************************************************************************
				Zwykle wstawianie następnika
				CALL crm_workflow_TOOLS('Get.Info', '8', '', '', '', '', '');
				_ID IDN p.decyz.
			************************************************************************************************************************************************/
				SELECT
					-- cw.*, 
					cw.commisionGUID,
					cw.IDN,
					cw.Confirm_Status AS Confirm_Status,
					(cw.Response = 'RESPONSE_100') AS Has_Decision,
					((IFNULL(cwn.ResponseCount, 0) > 0) OR cwnn.Confirm_Status IS NOT NULL) AS IS_Disabled,
					cwn.IDN AS Next_IDN,
					cwn.Confirm_Status AS Next_Confirm_Status,
					(cwn.Response = 'RESPONSE_100') AS Next_Has_Decision,
					(cwnn.Confirm_Status IS NOT NULL OR IFNULL(cwnn.ResponseCount, 0) > 0) AS Next_IS_Disabled,

					cwnn.IDN AS Next_2_IDN,
					cwnn.Confirm_Status AS Next_2_Confirm_Status,
					(cwnn.Response = 'RESPONSE_100') AS Next_2_Has_Decision,
					IFNULL(wd.Is_Ending, 0) AS Is_Ending,
-- 					cw.ExtNotify,
					cwdl.ExtNotify,
					c.Owner_GUID,
				--	doatk. zmienne
					wd.Is_Ending AS confirm_status_Is_Ending,
					wd.Is_Ending = 2 AS confirm_status_Is_Cancel,
					wd.param1 AS confirm_status_Param1,
				--	z crm-a	
					c.IS_Absencja,
					c.Absencja_Rodzaj,
					c.Wniosek_Typ,
					c.okres_typ
				FROM `crm_workflow` cw
				INNER JOIN `v_crm_workflow_coms2` c ON c.GUID = cw.commisionGUID
				LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_Start = cw.Start_Status AND cwdl.Status_End = cw.Confirm_Status
			--	dodałem 18 II 2022 aby mieć zmienna Is_Ending -> patrz: 'Insert.Next' czyli aby nie tworzył nastepnego - zbednego noda dla noda który jest końcowy!!!	
				LEFT JOIN `crm_workflow_def` wd ON wd.Def = cw.Def AND wd.Status = cw.Confirm_Status -- do spr. czy END
				LEFT JOIN `crm_workflow` cwn ON cwn.Prev_IDN_workflow = cw.IDN 
				LEFT JOIN `crm_workflow` cwnn ON cwnn.Prev_IDN_workflow = cwn.IDN 
				/* było
				SELECT
					-- cw.*, 
					cw.commisionGUID,
					cw.IDN,
					cw.Confirm_Status AS Confirm_Status,
					(cw.Response = 'RESPONSE_100') AS Has_Decision,
					((IFNULL(cwn.ResponseCount, 0) > 0) OR cwnn.Confirm_Status IS NOT NULL) AS IS_Disabled,
					cwn.IDN AS Next_IDN,
					cwn.Confirm_Status AS Next_Confirm_Status,
					(cwn.Response = 'RESPONSE_100') AS Next_Has_Decision,
					(cwnn.Confirm_Status IS NOT NULL OR IFNULL(cwnn.ResponseCount, 0) > 0) AS Next_IS_Disabled,

					cwnn.IDN AS Next_2_IDN,
					cwnn.Confirm_Status AS Next_2_Confirm_Status,
					(cwnn.Response = 'RESPONSE_100') AS Next_2_Has_Decision,
					IFNULL(wd.Is_Ending, 0) AS Is_Ending,
					cw.ExtNotify,
					cw.Owner_GUID,
				--	doatk. zmienne
					wd.Is_Ending AS confirm_status_Is_Ending,
					wd.Is_Ending = 2 AS confirm_status_Is_Cancel,
					wd.param1 AS confirm_status_Param1,
				--	z crm-a	
					c.IS_Absencja,
					c.Absencja_Rodzaj,
					c.Wniosek_Typ,
					c.okres_typ
				FROM `v_crm_workflow` cw
			--	dodałem 18 II 2022 aby mieć zmienna Is_Ending -> patrz: 'Insert.Next' czyli aby nie tworzył nastepnego - zbednego noda dla noda który jest końcowy!!!	
				LEFT JOIN `crm_workflow_def` wd ON wd.Def = cw.Def AND wd.Status = cw.Confirm_Status -- do spr. czy END
				LEFT JOIN `v_crm_workflow` cwn ON cwn.Prev_IDN_workflow = cw.IDN 
				LEFT JOIN `v_crm_workflow` cwnn ON cwnn.Prev_IDN_workflow = cwn.IDN 
				LEFT JOIN `v_crm_workflow_coms` c ON c.GUID = cw.commisionGUID
				*/
				WHERE
					cw.idn = _ID
				INTO
					@resp.commisionGUID,
					@resp.IDN,
					@resp.Confirm_Status,			--	po co
					@resp.Has_Decision,
					@resp.IS_Disabled,

					@resp.Next_IDN,					--	po co
					@resp.Next_Confirm_Status,		--	po co
					@resp.Next_Has_Decision,		--	po co	
					@resp.Next_IS_Disabled,			--	po co

					@resp.Next_2_IDN,				--	po co
					@resp.Next_2_Confirm_Status,	--	po co
					@resp.Next_2_Has_Decision,		--	po co
					@resp.Is_Ending,
					@resp.ExtNotify,
					@resp.Owner_GUID,
				--	doatk. zmienne
					@resp.confirm_status_Is_Ending,
					@resp.confirm_status_Is_Cancel,
					@resp.confirm_status_Param1,
				--	z crm-a	
					@resp.IS_Absencja,
					@resp.Absencja_Rodzaj,
					@resp.Wniosek_Typ,
					@resp.okres_typ
				;
				SET
					@resp.ProcExtNotify = IF(@resp.Has_Decision AND IFNULL(@resp.ExtNotify, '') <> '', @resp.ExtNotify, '')
				;
			END IF;

			IF _MODE = 'Insert.New' THEN
			/************************************************************************************************************************************************
				Wstawianie przy nowym crm
				CALL crm_workflow_TOOLS('Insert.New', 'GUID', 'new', '', '', '', '');
				_ID 	GUID zdarzenia
				_ID_2 	Status
			************************************************************************************************************************************************/
				IF @session.globals.WORK.FLOW.Ver >= '2024.02' THEN
					CALL P_crm_workflow_n('cw.Insert.New', _ID, NULL, NULL, NULL, _ID_2, '', '', @_Params);
				--	zapytaj Darka czy nie potrzebuje select-a zwracanego - patrz nużej za else
					LEAVE S_crm_workflow_TOOLS;
				END IF;

				INSERT IGNORE INTO `crm_workflow` 
				(commisionGUID, Def, Start_Status, Confirm_Status)
				SELECT 
					c.GUID, cr.Def_confirm_statuses, _ID_2, ''
				FROM `crm_commisions` c, `crm_rodzaje` cr
				WHERE
					c.GUID = _ID
					AND	cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
					
				;
				SET @.crm_workflow.Last.IDN := LAST_INSERT_ID();
			END IF;

			IF _MODE = 'Insert.New.2.0' THEN
			/************************************************************************************************************************************************
				Wstawianie przy nowym crm WERSJA 2.0!!!
				UWAGA poprzednio w Insert.New 
				w _ID_2 był Status!!!!
				teraz 
				w _ID_2 jest UserGUID a status
				w _Param_A	(Status)
				CALL crm_workflow_TOOLS('Insert.New.2.0', 'GUID', 'new', '', '', '', '');
				_ID 	GUID zdarzenia
				_ID_2 	UserGUID
				_Param_A	Decyzja (Status)
			************************************************************************************************************************************************/
				INSERT IGNORE INTO `crm_workflow` 
				(commisionGUID, Def, Owner, Start_Status, Confirm_Status)
				SELECT 
					c.GUID, cr.Def_confirm_statuses, _ID_2 AS Owner, _Param_A AS Start_Status, '' AS Confirm_Status
				FROM `crm_commisions` c, `crm_rodzaje` cr
				WHERE
					c.GUID = _ID
					AND	cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
					
				;
				SET @.crm_workflow.Last.IDN := LAST_INSERT_ID();
			END IF;

			
			IF _MODE = 'Insert.Next.2.0' THEN
			/************************************************************************************************************************************************
				Zwykle wstawianie następnika WERSJA 2.0!!!
				CALL crm_workflow_TOOLS('Insert.Next.2.0', '8', '', '', '', '', '');
				_ID IDN p.decyz.
				-- _ID_2 	UserGUID - niepotrzebny bo klonowany z poprzedniego 
			************************************************************************************************************************************************/
				DROP TEMPORARY TABLE IF EXISTS `t_next_crm_workflow`;
				CREATE TEMPORARY TABLE `t_next_crm_workflow` SELECT * FROM `crm_workflow` WHERE idn = _ID;
				UPDATE `t_next_crm_workflow` t 
					SET t.Prev_IDN_workflow = t.IDN, t.IDN = NULL, t.Start_Status = t.Confirm_Status
				;
				-- SELECT * FROM `t_next_crm_workflow`;
				INSERT IGNORE INTO `crm_workflow` 
				(Prev_IDN_workflow, commisionGUID, Def, Start_Status, Confirm_Status, Owner)
				SELECT 
					t.Prev_IDN_workflow, t.commisionGUID, t.Def, t.Start_Status, t.Confirm_Status, t.Owner 
				FROM `t_next_crm_workflow` t
				;
			END IF;
			
			IF _MODE = 'Insert.Next' THEN
			/************************************************************************************************************************************************
				Zwykle wstawianie następnika
				CALL crm_workflow_TOOLS('Insert.Next', '8', '', '', '', '', '');
				_ID IDN p.decyz.
			************************************************************************************************************************************************/
				DROP TEMPORARY TABLE IF EXISTS `t_next_crm_workflow`;
				CREATE TEMPORARY TABLE `t_next_crm_workflow` 
				SELECT 
					cw.* 
				FROM `crm_workflow` cw
				WHERE 
					cw.idn = _ID
				;
				UPDATE `t_next_crm_workflow` t 
					SET t.Prev_IDN_workflow = t.IDN, t.IDN = NULL, t.Start_Status = t.Confirm_Status
				;
				-- SELECT * FROM `t_next_crm_workflow`;
				INSERT IGNORE INTO `crm_workflow` 
				(Prev_IDN_workflow, commisionGUID, Def, Start_Status, Confirm_Status)
				SELECT 
					t.Prev_IDN_workflow, t.commisionGUID, t.Def, t.Start_Status, t.Confirm_Status 
				FROM `t_next_crm_workflow` t
				;
			END IF;

	IF _MODE = 'Select.all.do.decyzji' THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		1. bez decyzji i 
		2. te ktore moge cofnac
		CALL crm_workflow_TOOLS('Select.all.do.decyzji', 'def', @UserGUID, '', '', '', '');
		_ID_2	UserGUID
		_ID		Definicja
	************************************************************************************************************************************************/
		SELECT
			(cwc.confirm_status IN ('', cwc.Start_Status)) AS Decision_Enabled,
			NOT (cwc.confirm_status IN ('', cwc.Start_Status)) AS Undo_Enabled,
			_VarInt(0) AS Edit_Enabled,
			cwc.*,
			c.Temat,
			cwc.Status_Before,
			cwc.Status_Current,
			c.GUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.AreaGUID AS Oddzial,
			CONCAT(d.Symbol, ' ', d.Nazwa) AS Oddzial_Str,
			CONCAT(owner.Nazwisko, ' ', owner.Imiona) AS Hadlowiec_Nazw,
			CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			cr.nazwa AS typ_nazwa, -- c.GUID, c.data, c.temat, c.opis, c.startTime, c.endTIme, c.status, c.duration, 
			_VarStr(CONCAT(st.statusName, ': "', cwc.Status_Current, '"')) AS Status_Info
		
			
 
		FROM `v_crm_workflow_confirm` cwc
		LEFT JOIN `crm_commisions` c ON c.GUID = cwc.commisionGUID
		LEFT JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		LEFT JOIN `status` st ON st.statusID = c.status
		LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		WHERE
			cwc.UserGUID = _ID_2
			AND c.Rodzaj = 0
			AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND IF(_ID != '', cwc.Def = _ID, TRUE)
			AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) 
		;
	END IF;
	
	IF _MODE = 'Select.all.do.decyzji.menu.decyzji' THEN
	/************************************************************************************************************************************************
		Poprawiana w 2022 r. Wydajnosciowo jest OK!!!!
		Te przy ktorych musze zadecydowac
		1. bez decyzji i 
		2. te ktore moge cofnac
		CALL crm_workflow_TOOLS('Select.all.do.decyzji.menu.decyzji', '1234', @UserGUID, '', '', '', '');
		_ID		IDN_workflow
		_ID_2	UserGUID
	************************************************************************************************************************************************/
		SET 
			@_IDN_workflow = _ID,
			@_USER = _ID_2
		;
		
		-- CALL crm_workflow_SELECT('SELECT.Lista.Statusy.do.decyzji', @.SQL, NULL, USER, IdnWorkFLow, '', '', '', '');		
		
		DROP TEMPORARY TABLE IF EXISTS `t_do_decyzji_1`;
		CREATE TEMPORARY TABLE `t_do_decyzji_1` 
		SELECT 
			-- cwc.Decision_Enabled,
			-- cwc.Undo_Enabled_For_Decision_UserGUID,
			commisionGUID, 
			-- OsobaGUID,
			IDN_workflow,
			Def,
			Start_Status, Confirm_Status,
			-- Next_Idn_WorkFlow, Has_Decision, Next_Has_Decision,
			-- nie!!! Is_Ending,
			-- confirm_status_Param1, Is_Archiwum, 
			Decision_Enabled, 
			-- Do_decyzji, Undo_Enabled_For_Decision_UserGUID, Decision_UserGUID
			-- cwc.* 
			cwc.Undo_Enabled_For_Decision_UserGUID AND cwc.Decision_UserGUID = @_USER AS Undo_Enabled
		FROM `v_wfc_osoby_cwc` cwc
		WHERE
			TRUE
			AND cwc.IDN_workflow = @_IDN_workflow
			AND cwc.OsobaGUID  = @_USER 
		;

		-- SELECT * FROM `t_do_decyzji_1`;

		DROP TEMPORARY TABLE IF EXISTS `t_do_decyzji`;
		CREATE TEMPORARY TABLE `t_do_decyzji` 
			SELECT	-- cwdl.Status_1, cwdl.Status_2,
				cwdl.Status_Start AS Current_Status,
				cwdl.Status_End AS Decision_Status,
				cwdl.Descr_Item AS Decision_Str,
				cwdl.LP,
				cwc.*,
				_VarInt(0) AS Is_Ending
			FROM `t_do_decyzji_1` cwc
			LEFT JOIN `crm_workflow_def_links` cwdl ON FALSE
			WHERE
				FALSE
		;
		ALTER TABLE `t_do_decyzji` ADD PRIMARY KEY `Decision_Status`(`Decision_Status`);
	-- 1. Do decyzji
		TRUNCATE `t_do_decyzji`;
		INSERT IGNORE INTO `t_do_decyzji`
			SELECT	
				cwc.Start_Status AS Current_Status,
				cwdl.Status_End AS Decision_Status,
				cwdl.Descr_Item AS Decision_Str,
				cwdl.LP,
				cwc.*,
				cwd.Is_Ending
			FROM `t_do_decyzji_1` cwc
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cwc.Def AND cwdl.Status_Start = cwc.Start_Status
			INNER JOIN `crm_workflow_def` cwd ON cwd.Def = cwdl.Def AND cwd.Status = cwdl.Status_End AND cwd.Deleted = 0
			WHERE
				cwc.Decision_Enabled
		;
	-- 2. Cofnij
		INSERT IGNORE INTO `t_do_decyzji`
			SELECT	-- cwdl.Status_1, cwdl.Status_2,
				cwc.Confirm_Status AS Current_Status,
				cwc.Start_Status AS Decision_Status,
				CONCAT('Cofnij', ' do ... "', cwd.Descr_Status, '"') AS Decision_Str,
				100 AS LP,
				cwc.*,
				cwd.Is_Ending
			FROM `t_do_decyzji_1` cwc
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cwc.Def AND cwd.Status = cwc.Start_Status
			WHERE
				NOT cwc.Decision_Enabled
		;
		-- DROP TEMPORARY TABLE IF EXISTS `t_do_decyzji_1`;
	-- było	SELECT * FROM `t_do_decyzji` cwc ORDER BY LP;
		SELECT 
			cwc.*,
			cwd.Poziom
			-- ,cwd.Is_Ending
		FROM `t_do_decyzji` cwc 
		LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cwc.Def AND cwd.Status = cwc.Current_Status
		ORDER BY cwc.LP, cwd.Poziom
		;
		-- DROP TEMPORARY TABLE IF EXISTS `t_do_decyzji`;
	END IF;
	
	IF _MODE = 'Select.crm_workflow_def_responsible.graph' THEN
	/************************************************************************************************************************************************
		Zwroc Graf definicji
		CALL crm_workflow_TOOLS('Select.crm_workflow_def_responsible.graph', 'cdg_plan_cen', '', '', '', '', '');
		_ID		Definicja
	************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_crm_workflow_def_responsible.graph`;
		CREATE TEMPORARY TABLE `t_crm_workflow_def_responsible.graph` 
			SELECT
				cwdl.*,
				GROUP_CONCAT(CONCAT(o.IdnUser, IFNULL(CONCAT(' (', cwdr.notification, ')'), '')) SEPARATOR ' / ') AS IdnUser,
				GROUP_CONCAT(CONCAT(o.Nazwisko, ' ', o.Imie1, IFNULL(CONCAT(' (', cwdr.notification, ')'), '')) SEPARATOR ' / ') AS Persons,
				cwd.Descr_status, 
				cwd.Poziom,
				_VarINT(0) AS x,
				_VarINT(0) AS y

			FROM `crm_workflow_def_links` cwdl
			INNER JOIN `crm_workflow_def` cwd ON cwd.Def = cwdl.Def AND cwd.Status = cwdl.Status_Start
			LEFT JOIN `crm_workflow_def_responsible` cwdr ON cwdr.Def = cwdl.Def AND cwdr.Status = cwdl.Status_Start
			LEFT JOIN `osoby` o ON o.GUID = cwdr.UserGUID
			WHERE
				cwdl.Def = _ID
			GROUP BY cwdl.Def, cwdl.Status_Start, cwdl.Status_End 
			ORDER BY LP
		;
		
		SELECT 
			t.* 
		FROM `t_crm_workflow_def_responsible.graph` t
		GROUP BY t.Status_Start
		ORDER BY IF(t.Status_Start = 'new', -200, t.Poziom)
		;
		DROP TEMPORARY TABLE IF EXISTS `t_crm_workflow_def_responsible.graph`;
	END IF;
	
	IF _MODE = 'Select.workflow.history' THEN
	/************************************************************************************************************************************************
		ODCHODZIMY!!!! Patrz Select.2022.workflow.history
		Zwroc Graf historii zmian
		CALL crm_workflow_TOOLS('Select.workflow.history', 'crmGUID', '', '', '', '', '');
		CALL crm_workflow_TOOLS('Select.workflow.history', 'crmGUID', '', '1', '', '', '');	--	bez select i dropa
		_ID			GUID zdarzenia
		_Param_A	'' lub <> ''
	************************************************************************************************************************************************/
		SET @Y = 0;
		DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		CREATE TEMPORARY TABLE `v_crm_workflow.history` 
			SELECT
				FALSE AS IS_NEW, 
				cw.DecisionAt AS Time_Log,
				cw.User_Nazwiska AS Users_Nazwiska_Log,
				cw.IdnUser AS IdnUser_Nazwiska_Log,
				cw.Status_log,
				cw.Status_Before,
				cw.Status_Current,
				cw.Confirm_log AS Confirm_log,
				cw.idn,
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				_VarINT(0) AS X,
				_VarINT(0) AS Y

			FROM `v_crm_workflow` cw
			WHERE
				FALSE
			;
		TRUNCATE `v_crm_workflow.history`;
		SET @Y = 0;
		INSERT IGNORE INTO `v_crm_workflow.history` 
			SELECT
				FALSE,
				cw.DecisionAt AS Time_Log,
				IFNULL(cw.Decision_User_Nazwiska, cw.User_Nazwiska) AS Users_Nazwiska_Log,
				cw.IdnUser AS IdnUser_Nazwiska_Log,
				IFNULL(CONCAT('Zmiana statusu na: "', cw.Status_log, '"'), cw.Status_Current) AS Status_log,
				cw.Status_Before,
				-- było ale bez comment cw.Status_Current,
				cw.Status_Hist AS Status_Current,
				cw.Confirm_log AS Confirm_log,
				cw.idn,
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				_VarINT(100*cw.Poziom) AS X,
				-- _VarINT(@Y := @Y + 30) AS Y
				cw.IDN AS Y

			FROM `v_crm_workflow` cw
			WHERE
				cw.commisionGUID = _ID
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		;
		INSERT IGNORE INTO `v_crm_workflow.history` 
			SELECT
				TRUE,
				cw.CreateAt AS Time_Log,
				IFNULL(cw.Decision_User_Nazwiska, cw.User_Nazwiska) AS Users_Nazwiska_Log,
				cw.IdnUser AS IdnUser_Nazwiska_Log,
				CONCAT('Utworzenie wniosku - status pocz.: "', cw.Status_Before, '"') AS Status_log,
				cw.Status_Before,
				'Utworzenie wniosku' AS Status_Current, 	-- cw.Status_Current,
				cw.Confirm_log AS Confirm_log,
				cw.idn,
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				-- _VarINT(100*cw.Poziom) AS X,
				_VarINT(0) AS X,
				_VarINT(0) AS Y

			FROM `v_crm_workflow` cw
			WHERE
				cw.commisionGUID = _ID
				AND
				cw.Start_Status = 'new'
			GROUP BY cw.IDN
			LIMIT 1
		;
		
		IF _Param_A = '' THEN
			SELECT 
				t.* 
			FROM `v_crm_workflow.history` t
			-- ORDER BY Y
			ORDER BY t.IS_NEW DESC, t.idn
			;

			
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
		
		LEAVE S_crm_workflow_TOOLS;
		
		
		
		DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		CREATE TEMPORARY TABLE `v_crm_workflow.history` 
			SELECT
				cw.*,
				_VarINT(100*cw.Poziom) AS X,
				_VarINT(@Y := @Y + 30) AS Y

			FROM `v_crm_workflow` cw
			WHERE
				cw.commisionGUID = _ID
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		;
		
		SELECT 
			t.* 
		FROM `v_crm_workflow.history` t
		ORDER BY Y
		;
		DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
	END IF;
	

	IF _MODE = 'Select.2022.workflow.history' THEN
	/************************************************************************************************************************************************
		Zwroc Graf historii zmian
		CALL crm_workflow_TOOLS('Select.2022.workflow.history', 'crmGUID', 'User', '', '', '', '<select>');
		CALL crm_workflow_TOOLS('Select.2022.workflow.history', 'crmGUID', 'User', '', '', '', '');	--	bez select i dropa
		_ID			GUID zdarzenia
		_ID_2		UserGUID
		_Param_D	'<select>' lub <> ''
	************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_crm_workflow.history`;

		SET _SQLText = 
		"
		CREATE TEMPORARY TABLE `t_crm_workflow.history` 
		(
			SELECT
				0 AS tStart,
				cw.IDN,
				cw.DecisionAt AS Time_Log,
				GROUP_CONCAT(TRIM(CONCAT(ouser.Imie1, ' ', ouser.Nazwisko))) AS User_Nazwiska,
				GROUP_CONCAT(TRIM(CONCAT(odec.Imie1, ' ', odec.Nazwisko))) AS Decision_User_Nazwiska,
				@.cw_Status_Str := CONCAT_WS(' ',
					IF(cwdl.Descr_Item_Past IS NULL, 
						CONCAT('', cwd.Descr_Status),
						cwdl.Descr_Item_Past
					),
					NULL
				) AS cw_Status_Str,
				IFNULL(cwdl_prev.Descr_Item_Past, cwd_before.Descr_Status) AS Status_Before,
				GROUP_CONCAT(
					CONCAT(
						cwd.Descr_Status,
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					)
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Status_log,
				GROUP_CONCAT(
					CONCAT(
						cwc.ModifyAt, ' - ', odec.IdnUser, ' - > ', cwd.Descr_Status, 
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					) 
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Confirm_log,
				
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				_VarINT(100*cwd_before.Poziom) AS X,
				cw.IDN AS Y
			FROM `v_wf_osoby_cul_1` vinit
			INNER JOIN `crm_workflow` cw ON cw.commisionGUID = vinit.commisionGUID
			LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
			LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw.Prev_IDN_workflow
		--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_start = cw.Start_Status AND cwdl.Status_end = cw.confirm_status
		--	aktualny status noda workflow	
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
		--	poprzedni status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
			LEFT JOIN `crm_workflow_def` cwd_before ON cwd_before.Def = cw.Def AND cwd_before.Status = cw.Start_Status
			LEFT JOIN `osoby` ouser ON ouser.GUID = cwc.UserGUID
			LEFT JOIN `osoby` odec ON odec.GUID = cwc.Decision_UserGUID
			WHERE
				vinit.commisionGUID = #GUID# 
				AND vinit.OsobaGUID = #UserGUID#
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		)
		UNION
		(
			SELECT
				1 AS tStart,
				cw.IDN,
				cw.CreateAt AS Time_Log,
				GROUP_CONCAT(TRIM(CONCAT(ouser.Imie1, ' ', ouser.Nazwisko))) AS User_Nazwiska,
				GROUP_CONCAT(TRIM(CONCAT(odec.Imie1, ' ', odec.Nazwisko))) AS Decision_User_Nazwiska,
				@.cw_Status_Str := CONCAT_WS(' ',
					IF(cwdl.Descr_Item_Past IS NULL, 
						CONCAT('', cwd.Descr_Status),
						cwdl.Descr_Item_Past
					),
					NULL
				) AS cw_Status_Str,
				cwd_before.Descr_Status AS Status_Before,
				CONCAT('Utworzenie wniosku - status pocz.: \"', cwd_before.Descr_Status, '\"') AS Status_log,
				GROUP_CONCAT(
					CONCAT(
						cw.CreateAt, ' - ', odec.IdnUser, ' - > ', cwd.Descr_Status, 
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					) 
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Confirm_log,
				
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				-- _VarINT(100*cwd_before.Poziom) AS X,
				-- cw.IDN AS Y
				_VarINT(0) AS X,
				_VarINT(0) AS Y
			FROM `v_wf_osoby_cul_1` vinit
			INNER JOIN `crm_workflow` cw ON cw.commisionGUID = vinit.commisionGUID
			LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
			-- LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw.Prev_IDN_workflow
		--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_start = cw.Start_Status AND cwdl.Status_end = cw.confirm_status
		--	aktualny status noda workflow	
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
		--	poprzedni status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			-- LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
			LEFT JOIN `crm_workflow_def` cwd_before ON cwd_before.Def = cw.Def AND cwd_before.Status = cw.Start_Status
			LEFT JOIN `osoby` ouser ON ouser.GUID = cwc.UserGUID
			LEFT JOIN `osoby` odec ON odec.GUID = cwc.Decision_UserGUID
			WHERE
				vinit.commisionGUID = #GUID# 
				AND vinit.OsobaGUID = #UserGUID#
				AND cw.Start_Status = 'new'
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		)
		ORDER BY tStart DESC, Y
		;
		"
		;
		SET @SQLText = _SQLText;
		SET _SQLText = REPLACE(_SQLText, '#GUID#', QUOTE(_ID));
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
		SET @.Select.2022.workflow.history.SQL = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		IF _Param_D LIKE '%Select%' THEN
			SELECT * FROM `t_crm_workflow.history`;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
	END IF;
	
	IF _MODE IN ('Select.all.moje', 'Select.1') THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		CALL crm_workflow_TOOLS('Select.all.moje', 'cdg_plan_cen', @UserGUID, '', '', '', '');
		CALL crm_workflow_TOOLS('Select.1', 'crmGUID', @UserGUID, '', '', '', '');
		_ID		GUID CRM dla 'Select.1'
		_ID_2	UserGUID
		_Param_A	Rodzaj ???
		_Param_B	PodRodzaj ???
	************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_select.zdarzenia.workflow.dla.osoby`;
		CREATE TEMPORARY TABLE `t_select.zdarzenia.workflow.dla.osoby`
		SELECT
			c.Temat,
			-- cwc.Status_Before,
			-- cwc.Status_Current,
			c.GUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.AreaGUID AS Oddzial,
			CONCAT(d.Symbol, ' ', d.Nazwa) AS Oddzial_Str,
			CONCAT(owner.Nazwisko, ' ', owner.Imiona) AS Hadlowiec_Nazw,
			CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			cr.nazwa AS typ_nazwa, -- c.GUID, c.data, c.temat, c.opis, c.startTime, c.endTIme, c.status, c.duration, 
			_VarStr(CONCAT(st.statusName, ': "', cw.Status_Current, '"')) AS Status_Info,
		
			-- _VarInt(cul.Idn) AS Cul_Idn,
			-- _VarInt(cul.Poziom) AS Cul_Poziom,
			/*
			_VarStr('') AS Cul_confirm_status_init,
			_VarStr('') AS Cul_confirm_status,
			_VarStr('') AS Cul_Twoja_Decyzja_str,
			_VarStr('') AS Cul_Twoje_Opcje_Zmien,
			_VarStr('') AS Cul_Twoje_Opcje_Cofnij,
			_VarStr('') AS Cul_Twoje_Opcje_Edytuj,
			_VarStr('') AS Cul_Twoje_Opcje_Wycofaj,
			_VarStr('') AS Cul_Twoje_Opcje_Wznow,
			*/
			_VarInt(0) AS workflow_idn,
			
			s_c.Descr_status,
			_VarINT(0) AS IsArchiwum,
			c.Data, 
			c.DeadLine, 
			c.confirm_status,
			c.StartTime,
			c.EndTime,
			c.Work_EndTime,
			c.Status
			-- ,c.*
		FROM `crm_commisions` c 
		INNER JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		INNER JOIN `v_crm_usr_links` cul ON cul.commisionGUID = c.GUID AND cul.poziom = 2
		INNER JOIN `grupy_osob` go ON go.grupaGUID = cul.Osoba
		LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		LEFT JOIN `crm_confirm_statuses` s_c ON s_c.Def = cul.Def_confirm_statuses AND s_c.Status = c.confirm_status
		LEFT JOIN `status` st ON st.statusID = c.status
		LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		LEFT JOIN `v_crm_workflow` cw ON cw.IDN = (SELECT cw.IDN FROM `v_crm_workflow` cw WHERE cw.commisionGUID = 'x' ORDER BY idn LIMIT 1)
		WHERE 
			TRUE
			AND c.Rodzaj = 0
			AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND go.OsobaGUID = _ID_2
			AND IF(_MODE = 'Select.1', c.GUID = _ID, TRUE)
			
		GROUP BY c.GUID
		ORDER BY c.data DESC 
		LIMIT 530
		;
		UPDATE `t_select.zdarzenia.workflow.dla.osoby` c
		SET
			c.IsArchiwum = 
				-- (c.STATUS IN (3, 4, 8, 11, 13, 14)) BEZ 13 ki !!!
				(c.STATUS IN (3, 4, 8, 11, 14))
				AND (CURRENT_DATE() > c.Data)
		;
		
		
		select * from `t_select.zdarzenia.workflow.dla.osoby` c;
			
		
	END IF;


	IF _MODE = 'Select.all.nodes.do.decyzji.old' THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		1. bez decyzji i 
		2. te ktore moge cofnac
		CALL crm_workflow_TOOLS('Select.all.nodes.do.decyzji', 'def', @UserGUID, '0', '0', '', '');
		_ID_2	UserGUID
		_ID		Definicja
		_Param_A	Rodzaj ???
		_Param_B	PodRodzaj ???
		_Param_C	gdy != '' to archiwum
	************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_select.all.nodes.do.decyzji`;
		SET _SQLText = 
		"
		CREATE TEMPORARY TABLE `t_select.all.nodes.do.decyzji`
		SELECT
			cwc.idn_workflow AS workflow_idn,
			-- (cwc.confirm_status IN ('', cwc.Start_Status)) AS Decision_Enabled,
			-- NOT (cwc.confirm_status IN ('', cwc.Start_Status)) AS Undo_Enabled,
			-- NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#) AS Undo_Enabled,
			(
				NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#)
				-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = c.workflow_idn AND n.ResponseCount > 0) 
				AND cwc.Next_ResponseCount = 0
			) AS Undo_Enabled,
			_VarInt(0) AS Edit_Enabled,
			cwc.*,
			IF(c.Temat LIKE '%(%)%', 
				c.Temat, 
				CONCAT_WS(' ', 
					c.Temat, --	stare
					IF(IFNULL(ad.Idn, 0) > 0,
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
					)
				)
			) AS Temat,
			-- jmam c.Temat,
			
			-- c.Opis,
			IF(owner.GUID = #UserGUID#, 
				c.Opis, 
				IF(c.Temat LIKE '%(%)%', 
					c.Temat, 
					CONCAT_WS(' ', 
						c.Temat, --	stare
						IF(IFNULL(ad.Idn, 0) > 0,
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
						)
					)
				)
			) AS Opis,
			c.typ,
			-- cwc.Status_Before,
			-- cwc.Status_Current,
			c.GUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.Data,
			c.AreaGUID AS Oddzial,
			-- ((c.STATUS IN (3, 4, 8, 11, 13, 14))   BEZ 13 ki !!!
			((c.STATUS IN (3, 4, 8, 11, 14)) 
			AND (NOW() > c.Data)
			) AS IsArchiwum,
			
			CONCAT(d.Symbol, ' ', d.Nazwa) AS Oddzial_Str,
			CONCAT(owner.Nazwisko, ' ', owner.Imiona) AS Hadlowiec_Nazw,
			CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			cr.nazwa AS typ_nazwa, 
			-- c.GUID, c.data, c.temat, c.opis, c.startTime, c.endTIme, c.status, c.duration, 
			_VarStr(CONCAT(st.statusName, ': ""', cwc.Status_Current, '""')) AS Status_Info,
			c.Rodzaj, c.Podrodzaj
		FROM `v_crm_workflow_confirm` cwc
		INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID
		LEFT JOIN `crm_commisions` c ON c.GUID = cwc.commisionGUID
		LEFT JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		LEFT JOIN `status` st ON st.statusID = c.status
		LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
		WHERE
			-- cwc.UserGUID = #UserGUID#
			go.OsobaGUID = #UserGUID#
			AND c.Rodzaj = #Rodzaj#
			-- AND c.PodRodzaj = #PodRodzaj#
			AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND IF(#Def# != '', cwc.Def = #Def#, TRUE)
			AND #ARCHIWUM#
			-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) 
			#HAVING#
		;
		"
		;
		SET @SQLText = _SQLText;
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
		SET _SQLText = REPLACE(_SQLText, '#Rodzaj#', _Param_A);
		SET _SQLText = REPLACE(_SQLText, '#PodRodzaj#', _Param_B);
		SET _SQLText = REPLACE(_SQLText, '#Def#', QUOTE(_ID));
		SET _SQLText = REPLACE(_SQLText, '#ARCHIWUM#', 
			'TRUE'
			/*
			IF(_Param_C != '', 
				'(EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) OR c.Status = 3)',
				'NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND (n.ResponseCount > 0 OR n.Response = ''RESPONSE_100'')) '
			)
			*/
		);
		SET _SQLText = REPLACE(_SQLText, '#HAVING#', 
			IF(_Param_C != '', 
				'HAVING IsArchiwum',
				'HAVING ! IsArchiwum AND (Decision_Enabled OR Undo_Enabled)'
			)
		);
		SET @SQLText = _SQLText;
		SET @.Select.all.nodes.do.decyzji.SQL = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		SELECT 
			t.*,
			_VarInt((SELECT COUNT(*) FROM `dokumenty` d WHERE d.Klucz = t.GUID AND d.Tabela = 'crm_commisions')) AS IleDoc  
		FROM `t_select.all.nodes.do.decyzji` t
		/*
		WHERE
			IF(_Param_C != '', 
				t.IsArchiwum,
				NOT t.IsArchiwum
			)
		*/
		;
	END IF;
	
	IF _MODE = 'Select.all.nodes.do.decyzji' THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		1. bez decyzji i 
		2. te ktore moge cofnac
		CALL crm_workflow_TOOLS('Select.all.nodes.do.decyzji', 'def', @UserGUID, '0', '0', '', '');
		_ID_2	UserGUID
		_ID		Definicja
		_Param_A	Rodzaj ???
		_Param_B	PodRodzaj ???
		_Param_C	gdy != '' to archiwum
	************************************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `t_select.all.nodes.do.decyzji`;
		SET _SQLText = 
		"
		CREATE TEMPORARY TABLE `t_select.all.nodes.do.decyzji`
		SELECT
			cwc.idn_workflow AS workflow_idn,
			-- (cwc.confirm_status IN ('', cwc.Start_Status)) AS Decision_Enabled,
			-- NOT (cwc.confirm_status IN ('', cwc.Start_Status)) AS Undo_Enabled,
			-- NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#) AS Undo_Enabled,
			(
				NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#)
				-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = c.workflow_idn AND n.ResponseCount > 0) 
				AND cwc.Next_ResponseCount = 0
			) AS Undo_Enabled,
			_VarInt(0) AS Edit_Enabled,
			cwc.*,
			IF(c.Temat LIKE '%(%)%', 
				c.Temat, 
				CONCAT_WS(' ', 
					c.Temat, --	stare
					IF(IFNULL(ad.Idn, 0) > 0,
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
					)
				)
			) AS Temat,
			-- jmam c.Temat,
			
			-- c.Opis,
			IF(c.Owner_GUID = #UserGUID#, 
				c.Opis, 
				IF(c.Temat LIKE '%(%)%', 
					c.Temat, 
					CONCAT_WS(' ', 
						c.Temat, --	stare
						IF(IFNULL(ad.Idn, 0) > 0,
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
						)
					)
				)
			) AS Opis,
			c.typ,
			-- cwc.Status_Before,
			-- cwc.Status_Current,
			c.GUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.Data,
			c.AreaGUID AS Oddzial,
			c.Status_IsArchiwum AS IsArchiwum,
			
			c.Oddzial_Str,
			c.Owner_Kto AS Hadlowiec_Nazw,
			-- CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			'' AS Hadlowiec_IdnUser,
			c.typ_nazwa,
			c.Status_Info,
			c.Rodzaj, c.Podrodzaj,
			c.Wniosek_Typ,
			c.Owner_GUID = go.OsobaGUID AS Moj
		FROM `v_crm_workflow_confirm` cwc
		INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID
		LEFT JOIN `v_crm_workflow_coms` c ON c.GUID = cwc.commisionGUID
		-- LEFT JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		-- LEFT JOIN `status` st ON st.statusID = c.status
		-- LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		-- LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		-- LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
		WHERE
			-- cwc.UserGUID = #UserGUID#
			go.OsobaGUID = #UserGUID#
			AND c.Rodzaj = #Rodzaj#
			-- AND c.PodRodzaj = #PodRodzaj#
			-- AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND IF(#Def# != '', cwc.Def = #Def#, TRUE)
			AND #ARCHIWUM#
			-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) 
			#HAVING#
		;
		"
		;
		SET @SQLText = _SQLText;
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
		SET _SQLText = REPLACE(_SQLText, '#Rodzaj#', _Param_A);
		SET _SQLText = REPLACE(_SQLText, '#PodRodzaj#', _Param_B);
		SET _SQLText = REPLACE(_SQLText, '#Def#', QUOTE(_ID));
		SET _SQLText = REPLACE(_SQLText, '#ARCHIWUM#', 
			'TRUE'
			/*
			IF(_Param_C != '', 
				'(EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) OR c.Status = 3)',
				'NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND (n.ResponseCount > 0 OR n.Response = ''RESPONSE_100'')) '
			)
			*/
		);
		SET _SQLText = REPLACE(_SQLText, '#HAVING#', 
			IF(_Param_C != '', 
				'HAVING IsArchiwum',
				'HAVING ! IsArchiwum AND (Decision_Enabled OR Undo_Enabled)'
			)
		);
		SET @SQLText = _SQLText;
		SET @.Select.all.nodes.do.decyzji.SQL = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		SELECT 
			t.*,
			_VarInt((SELECT COUNT(*) FROM `dokumenty` d WHERE d.Klucz = t.GUID AND d.Tabela = 'crm_commisions')) AS IleDoc  
		FROM `t_select.all.nodes.do.decyzji` t
		/*
		WHERE
			IF(_Param_C != '', 
				t.IsArchiwum,
				NOT t.IsArchiwum
			)
		*/
		;
	END IF;


					IF _MODE = 'Select.2022.nodes' THEN
					/************************************************************************************************************************************************
						Te przy ktorych musze zadecydoweac
							CALL crm_workflow_TOOLS('Select.2022.nodes', '', @User, '', '', 'MOJE', '');
							CALL crm_workflow_TOOLS('Select.2022.nodes', '', @User, '', 'END', 'MOJE', '');
							CALL crm_workflow_TOOLS('Select.2022.nodes', '', @User, '', '', 'ALL', '');
							CALL crm_workflow_TOOLS('Select.2022.nodes', '', @User, '', 'END', 'ALL', '');
						UWAGA teraz UserGUID nie w _ID_2 ale w _ID
						_ID			nie używane to ale ??? GUID CRM ???
						_ID_2		UserGUID
						_Param_A	Definicja gdy "" to wszystkie ale możemy podać np.'web_delegacja'
						_Param_B	Statut wniosku (nie stan) czyli "": bieżące, "END": zakończone, "END_ARCH": Archiwum(0: bieżące, 1: zakończone, 2: Archiwum)
						_Param_C	Czy tylko moje czyli "MOJE": tylko moje, "ALL/"": wszystkie
					************************************************************************************************************************************************/
						LEAVE S_crm_workflow_TOOLS;
					
						DROP TEMPORARY TABLE IF EXISTS `t_nodes_2022`;
						SET _SQLText = 
						"
						CREATE TEMPORARY TABLE `t_nodes_2022`
						SELECT
							-- wfcwc.*,
							c.GUID,
							c.Temat,
							c.Opis,
							c.Data,
							c.AreaGUID AS Oddzial,
							c.Oddzial_Str,
							-- PO CO??? c.Owner_Kto AS Hadlowiec_Nazw,
							-- PO CO??? '' AS Hadlowiec_IdnUser,
							-- PO CO??? c.typ_nazwa,
							c.Status_Info,
							c.Rodzaj, c.Podrodzaj,
							c.Wniosek_Typ,
							-- PO CO??? c.Owner_GUID = go.OsobaGUID AS Moj
							
							wfcwc.commisionGUID, wfcwc.OsobaGUID AS UserGUID,
							wfcwc.UserIsOwner,
							wfcwc.UserLast_cwIDN, wfcwc.UserLast_cwIDN_Decyzja,
							cw_last.Response = 'RESPONSE_100' AS Has_Decision,
							@.Decyzja_Status :=
							IF(cw_last.Response = 'RESPONSE_100',
							--	jest Decyzja
								IF(cw_last.IDN = wfcwc.UserLast_cwIDN_Decyzja,
								--	ost. cw JEST cw usera i JEST JEGO DECYZJA
									'USER_DECYZJA',
									'OTHER_USER_DECYZJA'
								),
							--	nie ma w ogóle lub pełnej decyzji
								IF(cw_last.IDN = wfcwc.UserLast_cwIDN,
								--	ost. cw JEST cw usera i CZEKA NA jego DECYZJĘ
									'USER_BRAK_DECYZJI',
								--	ost. cw NIE JEST cw usera
									'OTHER_USER_BRAK_DECYZJI'
								)
							) AS Decyzja_Status,
							IF(cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
							--	gdy nie podjeto jeszcze decyzji a usera decyzja poprzedzala ten cw to
								'USER_UNDO_ENABLED',
								'USER_UNDO_DISABLED'
							) AS Undo_Status,
							@.Decyzja_Status_Str :=
							IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI',
								-- 'oczek. na Twoją decyzję',
								'czeka na Ciebie',
								IF(@.Decyzja_Status = 'OTHER_USER_BRAK_DECYZJI',
									'brak decyzji',
									'zakończono'
								)
							) AS Decyzja_Status_Str,
							@.cw_Status_Str := CONCAT_WS(' ',
								IF(cwdl.Descr_Item_Past IS NULL, 
									CONCAT('', cwd.Descr_Status),
									cwdl.Descr_Item_Past
								),
								NULL
							) AS cw_Status_Str,
							@.cw_Status_Str2 := CONCAT_WS(' ',
								@.cw_Status_Str,
								CONCAT('(', @.Decyzja_Status_Str, ')')
							) AS cw_Status_Str2,
										cwd.Is_Ending > 0 AS Is_Ending,
										cwd.Is_Ending = 2 AS Is_Cancel,
										cwd.param1 AS confirm_status_Param1,
										(cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH < CURRENT_DATE()) ) AS Is_Archiwum,
										cw_last.DecisionAT,
							
							/*
							(@.Undo_Enabled := 
								-- NOT (cwc.confirm_status IN ('', cw.Start_Status)) 
								cw_last.Response = 'RESPONSE_100'
								-- AND cwc.Decision_UserGUID = #UserGUID#
								AND cwc.Decision_UserGUID = '{5943D8B9-31E3-491C-B516-6E98B661BFE4}'
								AND IFNULL(cw_next.ResponseCount, 0) = 0
								AND cwc.ModifyAT > CURRENT_DATE() - INTERVAL 42 DAY
							) AS Undo_Enabled,
							*/
							cw_last.Response
							-- ,cw_last.*
						FROM `v_wf_osoby_cwc` wfcwc
						LEFT JOIN `crm_workflow` cw_last ON cw_last.IDN = (SELECT MAX(cw1.IDN) FROM `crm_workflow` cw1 WHERE cw1.commisionGUID = wfcwc.commisionGUID)
						LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw_last.Prev_IDN_workflow
						LEFT JOIN `crm_workflow` cw_next ON cw_next.Prev_Idn_WorkFlow = cw_last.Idn	-- node nastepne
						-- LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw_last.Prev_IDN_workflow
					--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
						LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw_last.Def AND cwdl.Status_start = cw_last.Start_Status AND cwdl.Status_end = cw_last.confirm_status
					--	aktualny status noda workflow	
						LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw_last.Def AND cwd.Status = cw_last.confirm_status
						
						INNER JOIN `v_crm_workflow_coms2` c ON c.GUID = wfcwc.commisionGUID
						WHERE
						--	zalogoweany
							wfcwc.OsobaGUID = #UserGUID#
						--	aktualne/bieżące
							#Statut#	-- AND cwd.Is_Ending = 0
							#DEF#		-- AND IF(#Def# != '', cwc.Def = #Def#, TRUE)
							#MOJE#
							
						--	zakończone
							-- AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) 
						--	archiwum
							-- AND IF(@_Archiwum = '1', cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 2 MONTH < CURRENT_DATE()) , TRUE)
						--	dla moje nalezy podac
							-- AND wfcwc.UserIsOwner
						--	dla czekające na moja decyzje
							-- AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < 'RESPONSE_100'
							-- having cw_last.IDN = 1876 
						-- GROUP BY wfcwc.OsobaGUID, wfcwc.commisionGUID
						-- #HAVING#
						;
						"
						;
						SET @SQLText = _SQLText;
						SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
					--	_Param_A		Definicja gdy "" to wszystkie
						SET _SQLText = REPLACE(_SQLText, '#DEF#', 
							IF(IFNULL(_Param_A, '') != '', CONCAT('AND wfcwc.Def = ', QUOTE(_Param_A)), '')
						)
						;
					--	_Param_B	Statut wniosku (nie stan) czyli "": bieżące, "END": zakończone, "END_ARCH": Archiwum(0: bieżące, 1: zakończone, 2: Archiwum)
						SET _SQLText = REPLACE(_SQLText, '#Statut#', 
							IF(_Param_B = '', 
							--	bieżące
								'AND cwd.Is_Ending = 0', 
								IF(_Param_B = 'END', 
								--	zakończone
									'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) ',
									IF(_Param_B = 'END_ARCH', 
									--	archiwum
										'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 2 MONTH < CURRENT_DATE())',
										''
									)
								)
							)
						)
						;
					/*	_Param_C	Czy tylko moje czyli "MOJE": tylko moje, "ALL / "": wszystkie */
						SET _SQLText = REPLACE(_SQLText, '#MOJE#', 
							IF(IFNULL(_Param_C, '') = 'MOJE', 	
								'AND wfcwc.UserIsOwner', 
								''
							)
						);
						SET @SQLText = _SQLText;
						SET @.Select.all.nodes.do.decyzji.SQL = _SQLText;
						CALL _ExecuteCmd(_SQLText, @Error);
						SELECT t.* FROM `t_nodes_2022` t;
					END IF;

	IF _MODE = 'Select.all.nodes.moje' THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		CALL crm_workflow_TOOLS('Select.all.nodes.moje', 'cdg_plan_cen', @UserGUID, '0', '0', '', '');
		CALL crm_workflow_TOOLS('Select.all.nodes.moje', 'cdg_plan_cen', @UserGUID, '0', '0', '1', '');	--	IsArchiwum
		_ID		Definicja
		_ID_2	UserGUID
		_Param_A	Rodzaj ???
		_Param_B	PodRodzaj ???
		_Param_C	gdy != '' to archiwum

	************************************************************************************************************************************************/
		SET 
			@_USER = _ID_2,		-- '{147D628E-5AE9-48FB-AE9E-C621E994AFFF}'
			@_IsArchiwum = (IFNULL(_Param_C, '') != '')
		;
		DROP TEMPORARY TABLE IF EXISTS `t_select.zdarzenia.workflow.moje`;
		CREATE TEMPORARY TABLE `t_select.zdarzenia.workflow.moje`
		SELECT
			cwc_moje_ost.USERGUID,
			(cwc_moje_ost.Decision_UserGUID = '') AS Do_decyzji,
			(cwc_moje_ost.Decision_UserGUID = '') AS Decision_Enabled,
			(@.Undo_Enabled := 
				NOT (cwc_moje_ost.confirm_status IN ('', cw.Start_Status)) 
				-- AND cwc_moje_ost.Decision_UserGUID = #UserGUID#
				AND cwc_moje_ost.Decision_UserGUID = @_USER
				AND IFNULL(cw_next.ResponseCount, 0) = 0
				AND cwc_moje_ost.ModifyAT > CURRENT_DATE() - INTERVAL 42 DAY
			) AS Undo_Enabled,
			(c.confirm_status IN ('new')) AS Edit_Enabled,
			
			c.confirm_status_Is_Ending > 0 AS IsArchiwum,
			c.*
		FROM
		--	sekcja wyszukania tabeli ct zawierająca GUID wniosku i ost. confirm uzytkownika (z decyzja lub bez)
		--	sekcja zwróci zawsze wniosek jeśli tylko był w decyzjach (właściciel który załozył widzi zawsze inni 
		--	dopiero jak powstanie odpowiedni confirm
			(
			SELECT
				cw.commisionGUID, MAX(cwc.IDN) AS IDN_confirm_last
		--	decyzje		
			FROM `crm_workflow_confirm` cwc
		--	grupa/osoba decyzyjna - zalogowany zarówno w widoku "moje" jak i "do decyzji" - moje i innych osób
			INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID AND go.OsobaGUID  = @_USER 
		--	decyzja dotyczy: node workflow	
			INNER JOIN `crm_workflow` cw ON cw.IDN = cwc.IDN_workflow
			GROUP BY cw.commisionGUID
			) ct
		INNER JOIN `v_crm_workflow_coms2` c ON c.GUID = ct.commisionGUID AND c.Rodzaj = 16
		INNER JOIN `crm_workflow_confirm` cwc_moje_ost ON cwc_moje_ost.IDN = ct.IDN_confirm_last
	--	decyzja dotyczy: node workflow	
		INNER JOIN `crm_workflow` cw ON cw.IDN = cwc_moje_ost.IDN_workflow
	--	nast. node workflow	
		LEFT JOIN `crm_workflow` cw_next ON cw_next.Prev_Idn_WorkFlow = cw.Idn	-- node nastepne
	--	aktualny status noda workflow	
		-- LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
	--	status dot. decyzji jako para status start -> status end
		-- LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_Start = cw.Start_Status AND cwdl.Status_End = cw.confirm_status 
	--	zapasowy status dot. decyzji jesli ten wyżej link zwróci null - wtedy decyzja jako stan wybranej decyzji
		-- LEFT JOIN `crm_workflow_def` cwddec ON cwddec.Def = cw.Def AND cwddec.Status = cwc_moje_ost.confirm_status
		
		--	LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		--	LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
		--	LEFT JOIN `crm_confirm_statuses` s_c ON s_c.Def = cul.Def_confirm_statuses AND s_c.Status = c.confirm_status
		--	LEFT JOIN `status` st ON st.statusID = c.status
		--	LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		-- LEFT JOIN `v_crm_workflow` cw ON cw.IDN = (SELECT cw.IDN FROM `v_crm_workflow` cw WHERE cw.commisionGUID = c.GUID ORDER BY idn DESC LIMIT 1)
		WHERE 
			TRUE
			AND c.confirm_status != '' 
		--	Gdy mamy widok "moje" to koniecznie dodaj osoba do zdarzeń jako kreatora - bo chodzi o "moje wnioski"!!!
			AND c.Owner_GUID = @_USER 
		--	Gdy mamy widok "Archiwum" to ...
			-- AND c.confirm_status_Is_Ending != 0
			AND c.confirm_status_Is_Ending = @_IsArchiwum
		;

		SELECT 
			-- c.*,
			c.Decision_Enabled,
			c.Undo_Enabled,
			c.Edit_Enabled,
			c.GUID,
			c.Temat,
			c.Opis,
			c.typ,	-- ???
			c.UserGUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.AreaGUID AS Oddzial,
			-- CONCAT(d.Symbol, ' ', d.Nazwa) AS Oddzial_Str,
			c.Oddzial_Str,
			-- CONCAT(owner.Nazwisko, ' ', owner.Imiona) AS Hadlowiec_Nazw,
			c.Owner_Kto AS Hadlowiec_Nazw,
			-- CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			'' AS Hadlowiec_IdnUser,
			-- cr.nazwa AS typ_nazwa, 
			c.typ_nazwa,
			c.Status_Info,
			-- s_c.Descr_status,
			c.Descr_status,
			c.IsArchiwum,
			c.Data, c.DeadLine, 
			c.confirm_status,
			c.StartTime,
			c.EndTime,
			-- c.Work_EndTime,
			c.Status,
			c.Rodzaj, c.Podrodzaj, 
			c.Wniosek_Typ,
			_VarInt((SELECT COUNT(*) FROM `dokumenty` d WHERE d.Klucz = c.GUID AND d.Tabela = 'crm_commisions')) AS IleDoc 
		FROM `t_select.zdarzenia.workflow.moje` c
		WHERE
			TRUE
			/*
			and
			IF(_Param_C != '', 
				c.IsArchiwum,
				NOT c.IsArchiwum
			)
			*/
		;
	
		LEAVE S_crm_workflow_TOOLS;
		
		
		
		DROP TEMPORARY TABLE IF EXISTS `t_select.zdarzenia.workflow.dla.osoby`;
		SET _SQLText = 
		"
		CREATE TEMPORARY TABLE `t_select.zdarzenia.workflow.dla.osoby`
		SELECT
			_VarInt(0) AS workflow_idn,
			_VarInt(0) AS Decision_Enabled,
			_VarInt(0) AS Undo_Enabled,
			_VarInt(0) AS Edit_Enabled,
			IF(c.Temat LIKE '%(%)%', 
				c.Temat, 
				CONCAT_WS(' ', 
					c.Temat, 
					IF(IFNULL(c.Absencja_Rodzaj, 0) > 0,
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
					)
				)
			) AS Temat,
			-- jmam c.Temat,
			c.Opis,
			c.typ,
			-- cwc.Status_Before,
			-- cwc.Status_Current,
			c.GUID,
			#UserGUID# AS UserGUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.AreaGUID AS Oddzial,
			-- CONCAT(d.Symbol, ' ', d.Nazwa) AS Oddzial_Str,
			c.Oddzial_Str,
			-- CONCAT(owner.Nazwisko, ' ', owner.Imiona) AS Hadlowiec_Nazw,
			c.Owner_Kto AS Hadlowiec_Nazw,
			-- CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			'' AS Hadlowiec_IdnUser,
			-- cr.nazwa AS typ_nazwa, 
			c.typ_nazwa,
			
			
			-- c.GUID, c.data, c.temat, c.opis, c.startTime, c.endTIme, c.status, c.duration, 
			-- bylo _VarStr(CONCAT(st.statusName, IFNULL(CONCAT(': "', cw.Status_Current, '"'), ''))) AS Status_Info,
			/*
			teraz patrz nizej 
			_VarStr(CONCAT_WS(': ', 
				c.Status_Info, 
				-- _Brackets('"', cw.Status_Current, '"')
				cw.Status_Current
			)) AS Status_Info,
			*/
			-- cw.Status_Current_Str AS Status_Info,
			c.Status_Info,
		
			-- _VarInt(cul.Idn) AS Cul_Idn,
			-- _VarInt(cul.Poziom) AS Cul_Poziom,
			/*
			_VarStr('') AS Cul_confirm_status_init,
			_VarStr('') AS Cul_confirm_status,
			_VarStr('') AS Cul_Twoja_Decyzja_str,
			_VarStr('') AS Cul_Twoje_Opcje_Zmien,
			_VarStr('') AS Cul_Twoje_Opcje_Cofnij,
			_VarStr('') AS Cul_Twoje_Opcje_Edytuj,
			_VarStr('') AS Cul_Twoje_Opcje_Wycofaj,
			_VarStr('') AS Cul_Twoje_Opcje_Wznow,
			*/
			
			-- s_c.Descr_status,
			c.Descr_status,
			_VarINT(0) AS IsArchiwum,
			c.Data, c.DeadLine, 
			c.confirm_status,
			c.StartTime,
			c.EndTime,
			-- c.Work_EndTime,
			c.Status,
			c.Rodzaj, c.Podrodzaj, 
			c.Wniosek_Typ
			-- ,c.*
		-- FROM `crm_commisions` c 
		FROM `v_crm_workflow_coms2` c
		--	INNER JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		--	LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		--	INNER JOIN `v_crm_usr_links` cul ON cul.commisionGUID = c.GUID AND cul.poziom = 2
		INNER JOIN `grupy_osob` go ON go.grupaGUID = c.Owner_GUID -- cul.Osoba
		--	LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		--	LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
		--	LEFT JOIN `crm_confirm_statuses` s_c ON s_c.Def = cul.Def_confirm_statuses AND s_c.Status = c.confirm_status
		--	LEFT JOIN `status` st ON st.statusID = c.status
		--	LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		-- LEFT JOIN `v_crm_workflow` cw ON cw.IDN = (SELECT cw.IDN FROM `v_crm_workflow` cw WHERE cw.commisionGUID = c.GUID ORDER BY idn DESC LIMIT 1)
		WHERE 
			TRUE
			AND c.Rodzaj = #Rodzaj#
			-- AND c.PodRodzaj = #PodRodzaj#
			-- AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND go.OsobaGUID = #UserGUID#
			-- AND IF(_Key != '', c.GUID = _Key, TRUE)
		GROUP BY c.GUID
		ORDER BY c.data DESC 
		LIMIT 530
		;
		"
		;
		

		SET @SQLText = _SQLText;
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
		SET _SQLText = REPLACE(_SQLText, '#Rodzaj#', _Param_A);
		SET _SQLText = REPLACE(_SQLText, '#PodRodzaj#', _Param_B);
		SET _SQLText = REPLACE(_SQLText, '#Def#', QUOTE(_ID));
		
		SET @SQLText = _SQLText;
		SET @.Select.all.nodes.moje.SQL = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		UPDATE `t_select.zdarzenia.workflow.dla.osoby` c
		SET
			c.workflow_idn = (
				SELECT cwc.IDN_workflow 
				FROM `v_crm_workflow_confirm` cwc 
				INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID
				WHERE 
					cwc.commisionGUID = c.GUID 
					AND go.OsobaGUID = c.UserGUID 
				ORDER BY IDN_workflow DESC 
				LIMIT 1
			),
			c.IsArchiwum = 
				-- (c.STATUS IN (3, 4, 8, 11, 13, 14)) BEZ 13 ki !!!
				(c.STATUS IN (3, 4, 8, 11, 14))
				AND 
				IF(c.Rodzaj = _Param_A, -- było 16,  a w _Param_A jest podawany dla portafide 16!!
					TRUE,
					(CURRENT_DATE() > c.Data)
				)
		;
		UPDATE `t_select.zdarzenia.workflow.dla.osoby` c
		-- LEFT JOIN `v_crm_workflow` cw_moje ON cw_moje.IDN = c.workflow_idn
		LEFT JOIN `v_crm_workflow_confirm` cw_moje ON cw_moje.IDN_workflow = c.workflow_idn
		SET
			c.Decision_Enabled = 
				(cw_moje.confirm_status IN ('', cw_moje.Start_Status)),
			c.Undo_Enabled = 
				NOT (cw_moje.confirm_status IN ('', Start_Status)) AND (cw_moje.Decision_UserGUID = c.UserGUID ),
			c.Edit_Enabled = (c.confirm_status IN ('new'))
				-- NOT (cw_moje.confirm_status IN ('', cw_moje.Start_Status))
		WHERE
			NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = c.workflow_idn AND n.ResponseCount > 0) 
		;
		
		SELECT 
			t.*,
			_VarInt((SELECT COUNT(*) FROM `dokumenty` d WHERE d.Klucz = t.GUID AND d.Tabela = 'crm_commisions')) AS IleDoc 
		FROM `t_select.zdarzenia.workflow.dla.osoby` t
		WHERE
			IF(_Param_C != '', 
				t.IsArchiwum,
				NOT t.IsArchiwum
			)
		;
		
	END IF;

	IF _MODE LIKE 'ExtNotify.%' THEN
	/************************************************************************************************************************************************
		Te przy ktorych musze zadecydoweac
		CALL crm_workflow_TOOLS('ExtNotify.....', 
	************************************************************************************************************************************************/
set @resp.watch = concat_WS(' / ', concat_WS(',', _MODE));				
		IF _MODE = 'ExtNotify.AFTER.confirm.Response' THEN
		/*----------------------------------------------------------------------------------------------------------------------------------------------
			Te przy ktorych musze zadecydoweac
			CALL crm_workflow_TOOLS('ExtNotify.....', 
			CALL crm_workflow_TOOLS('ExtNotify.AFTER.confirm.Response', 449, '{13A307C8-3C9E-4ECB-AFCB-BCC218116DBD}', 'rejected', '<-zastepca.B->A.REJECT', '', '');
				_ID			IDN_workflow
				_ID_2		Decision_UserGUID
				_Param_A	confirm_status				 
				_Param_B	Owner_GUID
				_Param_C	ExtNotify			
		----------------------------------------------------------------------------------------------------------------------------------------------*/
			SET @.EN.ExtNotify = _Param_C;
set @resp.watch = concat_WS(' / ', concat_WS(',', _ID, _ID_2, _Param_A, _Param_B, _Param_C));				
			IF @.EN.ExtNotify LIKE '<-zastepca.%' THEN
			/*----------------------------------------------------------------------------------------------------------------------------------------------
				Zastępstwa!!!
					_ID_2		Decision_UserGUID / UserGUID - zastępca akcepuje/odrzuca
					_Param_B	Owner_GUID - pracownik dostaje decyzję od zastępcy
			----------------------------------------------------------------------------------------------------------------------------------------------*/
				IF @.EN.ExtNotify LIKE '<-zastepca.B->A.ACCEPT' THEN
				--	Akceptacja  
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-ACCEPT', 0, _ID_2, _Param_B, '', '', '', '', '');
				ELSEIF @.EN.ExtNotify LIKE '<-zastepca.B->A.REJECT' THEN
				--	Odrzucony
					CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-REJECT', 0, _ID_2, _Param_B, '', '', '', '', '');
				END IF;
			END IF;
			
			-- IF @.EN.ExtNotify LIKE '<%ABSENCJA>' THEN
			
			IF @resp.confirm_status_Is_Ending OR @resp.confirm_status_Is_Cancel THEN
			/*----------------------------------------------------------------------------------------------------------------------------------------------
				Zakonczone lub anulowane
			----------------------------------------------------------------------------------------------------------------------------------------------*/
				IF @resp.Wniosek_Typ = 'W.DELEGACJA.W.ABSENCJA' THEN
			--	Dla delgacji ... powinna mieć ustawione pole <zamkniety> na 1 - to decyduje o kolorowaniu wiersza z tą delegacją	
					UPDATE `delegacje` d
					SET
						d.zamkniety = 1
					WHERE 
						d.GUID = @resp.commisionGUID
					;
				END IF;
			END IF;
			
			IF @resp.IS_Absencja THEN
			/*----------------------------------------------------------------------------------------------------------------------------------------------
				ABSENCJA!!!
					_ID_2		Decision_UserGUID / UserGUID - zastępca akcepuje/odrzuca
					_Param_B	Owner_GUID - pracownik dostaje decyzję od zastępcy
			----------------------------------------------------------------------------------------------------------------------------------------------*/
				CALL absencje_tools('crm.Wniosek.Update.ABS', @resp.commisionGUID, '', '', '', '');
			END IF;
			
			-- IF @resp.confirm_status_Param1 = '<AUTONUM>' THEN
			IF @.EN.ExtNotify LIKE '%<AUTONUM>%' THEN
			--	Naliczanie numeracji dla crm-a
				SELECT
					IFNULL(c.NrWewn, '') AS NrWewn,
					c.Data,
					c.Def_confirm_statuses AS ObjType,
					c.Rodzaj, c.PodRodzaj,
					IF(@session.globals.Owner = 'SKOK',
					--	dla skoku numeracja osoban dla zarzadu (katcol0 w tabeli `pracownicy`
						-- było przez chwilę EXISTS(SELECT go.osobaGUID FROM `grupy_osob` go WHERE go.GrupaGUID = 'DEL_KIEROWNICY' AND go.osobaGUID = c.Owner_GUID),
						IF((SELECT p.katcol0 FROM `Pracownicy` p WHERE p.GUID = c.Owner_GUID),	-- _Param_B),
							'Z/',
							''
						),
						''
					) AS Res
				FROM `v_crm_workflow_coms2` c
				WHERE 
					c.GUID = @resp.commisionGUID
				INTO
					@resp.autonum.c.NrWewn,
					@resp.autonum.c.Data,
					@resp.autonum.ObjType,
					@resp.autonum.Rodzaj, @resp.autonum.Podrodzaj, @resp.autonum.Res
				;
				
				IF @resp.autonum.c.NrWewn = '' THEN
					CALL erp_obj_counters_GetNumber_and_build_number_text('', 
						@_Numer, @_NumerText, @resp.autonum.ObjType, @resp.autonum.Rodzaj, @resp.autonum.Podrodzaj, 
						0, 0, @resp.autonum.Res, 
						-- YEAR(CURRENT_DATE()), MONTH(CURRENT_DATE()), 
						YEAR(@resp.autonum.c.Data), MONTH(@resp.autonum.c.Data), 
						1, '', '', '', '', ''
					);		
					UPDATE `crm_commisions` c
					SET
						c.NrWewn = @_NumerText
					WHERE 
						c.GUID = @resp.commisionGUID
						AND
						IFNULL(c.NrWewn, '') = ''
						AND
						IFNULL(@_NumerText, '') <> ''
					;
					IF @resp.Wniosek_Typ LIKE '%SZKOLENIE%' OR @resp.Wniosek_Typ LIKE '%DELEGACJA%' THEN
						UPDATE `delegacje` d
						SET
							d.NrDelegacji = @_NumerText
						WHERE 
							d.GUID = @resp.commisionGUID
							AND
							IFNULL(d.NrDelegacji, '') = ''
							AND
							IFNULL(@_NumerText, '') <> ''
						;
						IF @session.globals.Owner = 'SKOK' THEN
							SET @.Xyz = '';
						END IF;
					END IF;
				END IF;
			END IF;
		END IF;
	END IF;
	
	
END;
$$

DROP PROCEDURE IF EXISTS `crm_workflow_SELECT`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `crm_workflow_SELECT`(
	IN _MODE VARCHAR(250),	 --	_handle_oper INSERT, EDIT, DELETE,
	INOUT _SQL MEDIUMTEXT,
	IN _ID VARCHAR(38),		-- 	Zdarzenie, IDN, etc
	IN _ID_2 VARCHAR(38),	-- 	Zdarzenie, IDN, etc
	IN _Param_A VARCHAR(250),	
	IN _Param_B VARCHAR(250),
	IN _Param_C VARCHAR(250),	
	IN _Param_D VARCHAR(250),	
	IN _Params Text
)
/*
	CALL crm_workflow_SELECT('', 'GUID', '', 'OsobaGUID', @Poziom, 0, NULL, NULL, '', '', '');
	CALL crm_workflow_SELECT('Select.2022.nodes', @SQL, '', @User, '', '', '', '', '');
*/	
S_crm_workflow_SELECT: BEGIN
	DECLARE _SQLText MEDIUMTEXT;
	IF _MODE LIKE 'WorkFlow.Moje%' THEN
		SET _SQLText = '';
	END IF;
SET @.debug = concat_WS('/', @.debug, 'WE');
	
	SET 
		@.cw.IDN = _ID,
		@.cw.crmGUID = _ID,
		@.cw.IDN_WorkFlow = _Param_A,
		@.cw.USERGUID = _ID_2
	;	
	/*
	SET
		@.Buttons.wf.HISTORY = IFNULL(@.Buttons.wf.HISTORY, '"ID":"HISTORY","Caption":"Historia","Color":"info","Href":"CALL"'),
		@.Buttons.wf.DECISION = IFNULL(@.Buttons.wf.DECISION, '"ID":"DECISION","Caption":"Decyduj","Color":"primary","Href":"CALL"'),
		@.Buttons.wf.UNDO = IFNULL(@.Buttons.wf.UNDO, '"ID":"UNDO","Caption":"Cofnij","Color":"primary","Href":"CALL"'),
		@.Buttons.wf.EDIT = IFNULL(@.Buttons.wf.EDIT, '"ID":"EDIT","Caption":"Edytuj","Color":"warning","Href":"CALL"'),
		@.Buttons.wf.VIEW = IFNULL(@.Buttons.wf.VIEW, '"ID":"VIEW","Caption":"Podgląd","Color":"warning","Href":"CALL"'),
		@.Buttons.wf.PROPS = IFNULL(@.Buttons.wf.PROPS, '"ID":"PROPS","Caption":"Szczegóły","Color":"primary","Href":"CALL"'),
		@.Buttons.wf.PRINT = IFNULL(@.Buttons.wf.PRINT, '"ID":"PRINT","Caption":"glyphicon glyphicon-print","Color":"primary","Href":"ICON.CALL"'),
		@.Buttons.wf.DELETE = IFNULL(@.Buttons.wf.DELETE, '"ID":"DELETE","Caption":"Usuń","Color":"danger","Href":"CALL"')
	;
	*/
	IF _MODE LIKE 'Buttons%' THEN
		LEAVE S_crm_workflow_SELECT;
	END IF;
	
	IF _MODE LIKE 'SELECT%' THEN
		SET @.Params = IFNULL(_Params, '');
		SET @.Params = _VarStr(REPLACE(@.Params, '=END_ARCH', '=END.ARCH'));
		SET
			@.BTN.Ctx = 'PF:DEL_SZKOL',
			@.BTN.Style = 'bootstrap',
			@.BTN.Ver = ''
		;
	
		IF @.Params <> '' THEN
SET @.debug = concat_WS('/', @.debug, '1.1');
			SET
			--	Def:	
				@.cw.SELECT.Def = NULLIF(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'Def', ''), ''), ''''),
			--	Tab:	ARCH', ''
			--	@.cw.SELECT.Tab = NULLIF(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'Tab', ''), ''), ''''),
			--	StanWF:	stan workflow - "" / "CURR": bieżące, "END": zakończone, "END.ARCH": Archiwum  (dawniej 0: bieżące, 1: zakończone, 2: Archiwum)
				@.cw.SELECT.StanWF = NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'StanWF', ''), ''),
			--	Czyje spr. ogladamy - "ALL" / "": wszystkie, "MOJE": tylko moje
				@.cw.SELECT.Czyje = NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'Czyje', ''), ''),
			--	StanDecyzji - czy tylko te do decyzji czyli "ALL" / "": wszystkie, "DO.DECYZJI", "DO.MOJEJ.DECYZJI" 
				@.cw.SELECT.StanDecyzji = NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'StanDecyzji', ''), ''),
			--	Confirm_status:	"ALL" znaczy wszystkie, pozostałe to typowe ... new, sent, approved_1, accepted
				@.cw.SELECT.Confirm_status = NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'Confirm_status', ''), ''),
			--	Data Od i Do - gdy NULL to odp. od 1 dnia zeszłego roku do ot. dnia przyszłego roku
				@.cw.SELECT.DataOd = DATE(IFNULL(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'DataOd', ''), ''), _VarStr(_FirstDayYYYY(YEAR(CURRENT_DATE()) - 1)))),
				@.cw.SELECT.DataDo = DATE(IFNULL(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'DataDo', ''), ''), _VarStr(_LastDayYYYY(YEAR(CURRENT_DATE()) + 1)))),
				@.BTN.Ctx = IFNULL(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'BTN.Ctx', ''), ''), @.BTN.Ctx),
				@.BTN.Style = IFNULL(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'BTN.Style', ''), ''), @.BTN.Style),
				@.BTN.Ver = IFNULL(NULLIF(_Params2('_FetchParams', @_ModeParam, @.Params, 'BTN.Ver', ''), ''), @.BTN.Ver)
				
			;
		ELSE
			SET
			--	ARCH', ''
				@.cw.SELECT.Def = NULL,
				@.cw.SELECT.StanWF = NULL,
				@.cw.SELECT.Czyje = NULL,
				@.cw.SELECT.StanDecyzji = NULL,
				@.cw.SELECT.DataOd = NULL,
				@.cw.SELECT.DataDo = NULL
			;
		END IF;
SET @.debug = concat_WS('/', @.debug, '1.2');
	--	Buttons temp. `t_wf_buttons`
		DROP TEMPORARY TABLE IF EXISTS `t_wf_buttons`;
		CREATE TEMPORARY TABLE `t_wf_buttons`
		SELECT
			MAX(IF(btn.ID = 'EDIT', btn.buttons, '')) AS btn_EDIT,
			MAX(IF(btn.ID = 'VIEW', btn.buttons, '')) AS btn_VIEW,
			MAX(IF(btn.ID = 'PROPS', btn.buttons, '')) AS btn_PROPS,
			MAX(IF(btn.ID = 'PRINT', btn.buttons, '')) AS btn_PRINT,
			MAX(IF(btn.ID = 'DELETE', btn.buttons, '')) AS btn_DELETE,
			MAX(IF(btn.ID = 'HISTORY', btn.buttons, '')) AS btn_HISTORY,
			MAX(IF(btn.ID = 'DECISION', btn.buttons, '')) AS btn_DECISION,
			MAX(IF(btn.ID = 'UNDO', btn.buttons, '')) AS btn_UNDO
		FROM (
			SELECT  
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('"ID":"#ID","Caption":"#Caption","Hint":"#Hint","Glyph":"#Glyph","Color":"#Color","Href":"#Href"',	
					'#ID', btn.ID), '#Caption', btn.Caption), '#Hint', btn.Hint), '#Glyph', btn.Glyph), '#Color', btn.Color), '#Href', btn.Href) AS buttons, 
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('"ID":"#ID","Caption":"#Caption","Hint":"#Hint","Color":"#Color","Href":"#Href"',	
					'#ID', btn.ID), '#Caption', btn.Caption), '#Hint', btn.Hint), '#Color', btn.Color), '#Href', btn.Href) AS buttons2, 
				btn.*	
			FROM `gui_buttons` btn
			WHERE
				btn.Ctx = @.BTN.Ctx AND btn.Style = @.BTN.Style AND btn.Ver = @.BTN.Ver
			) btn
		;
SET @.debug = concat_WS('/', @.debug, '1.3');
		SELECT  
			btn_EDIT, btn_VIEW, btn_PROPS, btn_PRINT, btn_DELETE, btn_HISTORY, btn_DECISION, btn_UNDO
		FROM `t_wf_buttons` 
		INTO
			@.Buttons.wf.EDIT,
			@.Buttons.wf.VIEW,
			@.Buttons.wf.PROPS,
			@.Buttons.wf.PRINT,
			@.Buttons.wf.DELETE,
			@.Buttons.wf.HISTORY,
			@.Buttons.wf.DECISION,
			@.Buttons.wf.UNDO
		;
SET @.debug = concat_WS('/', @.debug, '1.4');

	END IF;
	
	IF _MODE LIKE 'WorkFlow.Decyzja%' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_select.WorkFlow.Decyzja`;
		SET _SQLText = 
		"Decision_UserGUID
		CREATE TEMPORARY TABLE `t_select.all.nodes.do.decyzji`
		SELECT
			cwc.idn_workflow AS workflow_idn,
			-- (cwc.confirm_status IN ('', cwc.Start_Status)) AS Decision_Enabled,
			-- NOT (cwc.confirm_status IN ('', cwc.Start_Status)) AS Undo_Enabled,
			-- NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#) AS Undo_Enabled,
			(
				NOT (cwc.confirm_status IN ('', Start_Status)) AND (cwc.Decision_UserGUID = #UserGUID#)
				-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = c.workflow_idn AND n.ResponseCount > 0) 
				AND cwc.Next_ResponseCount = 0
			) AS Undo_Enabled,
			_VarInt(0) AS Edit_Enabled,
			cwc.*,
			IF(c.Temat LIKE '%(%)%', 
				c.Temat, 
				CONCAT_WS(' ', 
					c.Temat, --	stare
					IF(IFNULL(ad.Idn, 0) > 0,
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
						_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
					)
				)
			) AS Temat,
			-- jmam c.Temat,
			
			-- c.Opis,
			IF(c.Owner_GUID = #UserGUID#, 
				c.Opis, 
				IF(c.Temat LIKE '%(%)%', 
					c.Temat, 
					CONCAT_WS(' ', 
						c.Temat, --	stare
						IF(IFNULL(ad.Idn, 0) > 0,
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] [#hour#] ([od][#from#][do][#to#])'),
							_Format_DT_Range_Mask(c.StartTime, c.EndTime, '%D %mmm %YH;%D %mmm %YH;',  '[#dni#] ([od][#from#][do][#to#])')
						)
					)
				)
			) AS Opis,
			c.typ,
			-- cwc.Status_Before,
			-- cwc.Status_Current,
			c.GUID,
			MONTH(c.Data) AS Plan_Month,
			YEAR(c.Data) AS Plan_Year,
			c.Data,
			c.AreaGUID AS Oddzial,
			c.Status_IsArchiwum AS IsArchiwum,
			
			c.Oddzial_Str,
			c.Owner_Kto AS Hadlowiec_Nazw,
			-- CONCAT(owner.idnuser) AS Hadlowiec_IdnUser,
			'' AS Hadlowiec_IdnUser,
			c.typ_nazwa,
			c.Status_Info,
			c.Rodzaj, c.Podrodzaj,
			c.Wniosek_Typ,
			c.Owner_GUID = go.OsobaGUID AS Moj
		FROM `v_crm_workflow_confirm` cwc
		INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID
		LEFT JOIN `v_crm_workflow_coms` c ON c.GUID = cwc.commisionGUID
		-- LEFT JOIN `v_crm_usr_links` cul0 ON cul0.commisionGUID = c.GUID AND cul0.Poziom = 0
		-- LEFT JOIN `status` st ON st.statusID = c.status
		-- LEFT JOIN `erp_division_schema` d ON d.GUID = c.AreaGUID
		-- LEFT JOIN `osoby` owner ON owner.GUID = cul0.Osoba
		-- LEFT JOIN `crm_rodzaje` cr ON cr.rodzaj = c.rodzaj AND cr.podrodzaj = c.podrodzaj
		LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
		WHERE
			-- cwc.UserGUID = #UserGUID#
			go.OsobaGUID = #UserGUID#
			AND c.Rodzaj = #Rodzaj#
			-- AND c.PodRodzaj = #PodRodzaj#
			-- AND c.Template_Osoba = '' 
			AND c.confirm_status != '' 
			AND IF(#Def# != '', cwc.Def = #Def#, TRUE)
			AND #ARCHIWUM#
			-- AND NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) 
			#HAVING#
		;
		"
		;
		SET @SQLText = _SQLText;
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', QUOTE(_ID_2));
		SET _SQLText = REPLACE(_SQLText, '#Rodzaj#', _Param_A);
		SET _SQLText = REPLACE(_SQLText, '#PodRodzaj#', _Param_B);
		SET _SQLText = REPLACE(_SQLText, '#Def#', QUOTE(_ID));
		SET _SQLText = REPLACE(_SQLText, '#ARCHIWUM#', 
			'TRUE'
			/*
			IF(_Param_C != '', 
				'(EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND n.ResponseCount > 0) OR c.Status = 3)',
				'NOT EXISTS(SELECT n.IDN FROM `v_crm_workflow` n WHERE n.Prev_IDN_workflow = cwc.IDN AND (n.ResponseCount > 0 OR n.Response = ''RESPONSE_100'')) '
			)
			*/
		);
		SET _SQLText = REPLACE(_SQLText, '#HAVING#', 
			IF(_Param_C != '', 
				'HAVING IsArchiwum',
				'HAVING ! IsArchiwum AND (Decision_Enabled OR Undo_Enabled)'
			)
		);
		SET @SQLText = _SQLText;
		SET @.Select.all.nodes.do.decyzji.SQL = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		SELECT 
			t.*,
			_VarInt((SELECT COUNT(*) FROM `dokumenty` d WHERE d.Klucz = t.GUID AND d.Tabela = 'crm_commisions')) AS IleDoc  
		FROM `t_select.all.nodes.do.decyzji` t
		/*
		WHERE
			IF(_Param_C != '', 
				t.IsArchiwum,
				NOT t.IsArchiwum
			)
		*/
		;
		
	END IF;

		IF _MODE LIKE 'SET.#VAR#' THEN
			SET _SQL = REPLACE(REPLACE(_SQL, 
				'#WHERE cw.commisionGUID#', IF(IFNULL(@.cw.crmGUID, '') <> '', 'AND cw.commisionGUID = #GUID#', '')),
				'#WHERE cw.IDN#', IF(IFNULL(@.cw.IDN_WorkFlow, '') <> '', 'AND cw.IDN = #cwIDN#', ''))
			;
			SET _SQL = REPLACE(_SQL, '#cwIDN#', @.cw.IDN_WorkFlow);
			SET _SQL = REPLACE(_SQL, '#GUID#', QUOTE(@.cw.crmGUID));
			SET _SQL = REPLACE(_SQL, '#UserGUID#', QUOTE(@.cw.USERGUID));
		END IF;
		
		IF _MODE LIKE 'SQL.sub.for.User.by.%' THEN
			IF _MODE LIKE 'SQL.sub.for.User.by.Confirm->Nodes.old%' THEN
				SET @.SQL.SUB.select.User.by.Confirm.Nodes = 
				"\n
				--	sub table
				(
					SELECT
						csub.commisionGUID, csub.UserGUID -- AS UserGUID
						, cw.Def
						, EXISTS(SELECT cul.Idn FROM `crm_usr_links` cul WHERE cul.commisionGUID = csub.commisionGUID AND cul.Osoba = csub.USERGUID AND cul.Poziom = 2) AS UserIsOwner
						-- , MAX(cwc.IDN) AS UserLast_cwcIDN
						, MAX(cw.IDN) AS Last_cwIDN
						, MAX(cw.IDN) AS UserLast_cwIDN
						, null AS UserCC_cwIDN
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cwc.IDN, 0)) AS UserLast_cwcIDN_Decyzja
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cw.IDN, 0)) AS UserLast_cwIDN_Decyzja
						
					FROM
					(
						SELECT
							cw.commisionGUID, go.OsobaGUID AS UserGUID -- AS UserGUID
							,cw.IDN AS cwIDN_User
							,cwc.IDN AS cwcIDN_User
							,cw.Def
						FROM `crm_workflow_confirm` cwc
						INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID AND go.OsobaGUID  = #UserGUID#
						INNER JOIN `_user_accounts` ua ON ua.osobaGUID = go.osobaGUID
						INNER JOIN `crm_workflow` cw ON cw.Idn = cwc.IDN_workflow AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					) csub
					INNER JOIN `crm_workflow_confirm` cwc ON cwc.IDN = cwcIDN_User
					-- todo INNER JOIN `crm_workflow` cw ON cw.Idn = cwc.IDN_workflow AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					INNER JOIN `crm_workflow` cw ON cw.Idn = csub.cwIDN_User
					WHERE
						TRUE
						#WHERE cw.commisionGUID#
					GROUP BY commisionGUID, UserGUID
				) 
				"	-- AS wfcwc
				;
				CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.SUB.select.User.by.Confirm.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
				SET _SQL = REPLACE(_SQL, '#Sub.Table.User#', @.SQL.SUB.select.User.by.Confirm.Nodes);
			END IF;
			
			IF _MODE LIKE 'SQL.sub.for.User.by.Confirm->Nodes%' THEN
				SET @.SQL.SUB.select.User.by.Confirm.Nodes = 
				"\n
				--	sub table
				(
					SELECT
						csub.commisionGUID, csub.UserGUID -- AS UserGUID
						, cw.Def
						, EXISTS(SELECT cul.Idn FROM `crm_usr_links` cul WHERE cul.commisionGUID = csub.commisionGUID AND cul.Osoba = csub.USERGUID AND cul.Poziom = 2) AS UserIsOwner
						, MAX(cw.IDN) AS Last_cwIDN
						, MAX(IF(gouser.OsobaGUID IS NOT NULL, cw.IDN, 0)) AS UserLast_cwIDN
						, SUM((gouser.OsobaGUID IS NOT NULL)) AS UserCC_cwIDN
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cwc.IDN, 0)) AS UserLast_cwcIDN_Decyzja
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cw.IDN, 0)) AS UserLast_cwIDN_Decyzja
						
					FROM
					(
						SELECT
							cw.commisionGUID, go.OsobaGUID AS UserGUID -- AS UserGUID
							,cw.IDN AS cwIDN_User
							,cwc.IDN AS cwcIDN_User
							,cw.Def
						FROM `crm_workflow_confirm` cwc
						INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID AND go.OsobaGUID  = #UserGUID#
						INNER JOIN `_user_accounts` ua ON ua.osobaGUID = go.osobaGUID
						INNER JOIN `crm_workflow` cw ON cw.Idn = cwc.IDN_workflow #WHERE cw.commisionGUID# #WHERE cw.IDN# 		-- AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					) csub
					INNER JOIN `crm_workflow` cw ON cw.commisionGUID = csub.commisionGUID	-- cw.Idn = csub.cwIDN_User
					LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow  = cw.Idn -- AND cwc.Decision_UserGUID = csub.UserGUID
					LEFT JOIN `grupy_osob` gouser ON gouser.grupaGUID = cwc.UserGUID AND gouser.OsobaGUID  = csub.UserGUID
					WHERE
						TRUE
						#WHERE cw.commisionGUID#
					GROUP BY commisionGUID, UserGUID
				) 
				"	-- AS wfcwc
				;
				CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.SUB.select.User.by.Confirm.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
				SET _SQL = REPLACE(_SQL, '#Sub.Table.User#', @.SQL.SUB.select.User.by.Confirm.Nodes);
			END IF;
			
			IF _MODE LIKE 'SQL.sub.for.User.by.Cul->Nodes%' THEN
				SET @.SQL.SUB.select.User.by.Cul.Nodes = 
				"\n
				--	sub table
				(
					SELECT
						csub.commisionGUID, csub.UserGUID -- AS UserGUID
						-- cul.commisionGUID, go.OsobaGUID 
						, cw.Def
						, MAX(csub.IsOwner) AS UserIsOwner
						, MAX(cw.IDN) AS Last_cwIDN
						, MAX(IF(gouser.OsobaGUID IS NOT NULL, cw.IDN, 0)) AS UserLast_cwIDN
						, SUM((gouser.OsobaGUID IS NOT NULL)) AS UserCC_cwIDN
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cwc.IDN, 0)) AS UserLast_cwcIDN_Decyzja
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cw.IDN, 0)) AS UserLast_cwIDN_Decyzja
					FROM
					(
					/*	od 27 II 2025 rezygn z cul
						SELECT
							cw.commisionGUID, go.OsobaGUID AS UserGUID -- AS UserGUID
							,cw.IDN AS cwIDN_User
							-- ,cwc.IDN AS cwcIDN_User
							,cw.Def
							,(cul.Poziom = 2 AND cul.Osoba = go.OsobaGUID) AS IsOwner
						FROM `crm_workflow` cw 
						INNER JOIN `crm_usr_links` cul ON cul.commisionGUID = cw.commisionGUID
						INNER JOIN `grupy_osob` go ON go.grupaGUID = cul.Osoba AND go.OsobaGUID  = #UserGUID#
						INNER JOIN `_user_accounts` ua ON ua.osobaGUID = go.osobaGUID
						WHERE
							TRUE
							#WHERE cw.commisionGUID#
							#WHERE cw.IDN#
					*/		
						SELECT
							cwn.GUID AS commisionGUID, go.OsobaGUID AS UserGUID -- AS UserGUID
							,cw.IDN AS cwIDN_User
							-- ,cwc.IDN AS cwcIDN_User
							,cw.Def
							-- ,(cul.Poziom = 2 AND cul.Osoba = go.OsobaGUID) AS IsOwner
							, go.OsobaGUID = cwn.uOwner AS IsOwner
						FROM `crm_workflow_n` cwn 
						INNER JOIN `crm_workflow` cw ON cw.wGUID = cwn.GUID
						INNER JOIN `crm_workflow_confirm` cul ON cul.wGUID = cwn.GUID
						-- INNER JOIN `crm_usr_links` cul ON cul.commisionGUID = cw.commisionGUID
						INNER JOIN `grupy_osob` go ON go.grupaGUID = cul.UserGUID AND go.OsobaGUID  = #UserGUID#
						INNER JOIN `_user_accounts` ua ON ua.osobaGUID = go.osobaGUID
						WHERE
							TRUE
							#WHERE cw.commisionGUID#
							#WHERE cw.IDN#
					) csub
					-- INNER JOIN `crm_workflow` cw ON cw.Idn = csub.cwIDN_User
					INNER JOIN `crm_workflow` cw ON cw.commisionGUID = csub.commisionGUID	-- cw.Idn = csub.cwIDN_User
					LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow  = cw.Idn -- AND cwc.Decision_UserGUID = csub.UserGUID
					LEFT JOIN `grupy_osob` gouser ON gouser.grupaGUID = cwc.UserGUID AND gouser.OsobaGUID  = csub.UserGUID
					WHERE
						TRUE
						#WHERE cw.commisionGUID#
						-- AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					GROUP BY commisionGUID, UserGUID
				) 
				"	-- AS wfcwc
				;
				CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.SUB.select.User.by.Cul.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
				SET _SQL = REPLACE(_SQL, '#Sub.Table.User#', @.SQL.SUB.select.User.by.Cul.Nodes);
			END IF;
			
			IF _MODE LIKE 'SQL.sub.for.User.by.Decision->Nodes%' THEN
				SET @.SQL.SUB.select.User.by.Confirm.Nodes = 
				"\n
				--	sub table
				(
					SELECT
						csub.commisionGUID, csub.UserGUID -- AS UserGUID
						, cw.Def
						, EXISTS(SELECT cul.Idn FROM `crm_usr_links` cul WHERE cul.commisionGUID = csub.commisionGUID AND cul.Osoba = csub.USERGUID AND cul.Poziom = 2) AS UserIsOwner
						, MAX(cw.IDN) AS Last_cwIDN
						, MAX(IF(gouser.OsobaGUID IS NOT NULL, cw.IDN, 0)) AS UserLast_cwIDN
						, SUM((gouser.OsobaGUID IS NOT NULL)) AS UserCC_cwIDN
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cwc.IDN, 0)) AS UserLast_cwcIDN_Decyzja
						, MAX(IF(cwc.Decision_UserGUID = csub.UserGUID, cw.IDN, 0)) AS UserLast_cwIDN_Decyzja
						
					FROM
					(
						SELECT
							cw.commisionGUID, go.OsobaGUID AS UserGUID -- AS UserGUID
							,cw.IDN AS cwIDN_User
							,cwc.IDN AS cwcIDN_User
							,cw.Def
						FROM `crm_workflow_confirm` cwc
						INNER JOIN `crm_workflow` cw ON cw.Idn = cwc.IDN_workflow #WHERE cw.IDN# 		
						INNER JOIN `grupy_osob` go ON go.grupaGUID = cwc.UserGUID AND go.OsobaGUID  = #UserGUID#
						INNER JOIN `_user_accounts` ua ON ua.osobaGUID = go.osobaGUID
					) csub
					INNER JOIN `crm_workflow` cw ON cw.commisionGUID = csub.commisionGUID	-- cw.Idn = csub.cwIDN_User
					LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow  = cw.Idn -- AND cwc.Decision_UserGUID = csub.UserGUID
					LEFT JOIN `grupy_osob` gouser ON gouser.grupaGUID = cwc.UserGUID AND gouser.OsobaGUID  = csub.UserGUID
					WHERE
						TRUE
					GROUP BY commisionGUID, UserGUID
				) 
				"	-- AS wfcwc
				;
				CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.SUB.select.User.by.Confirm.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
				SET _SQL = REPLACE(_SQL, '#Sub.Table.User#', @.SQL.SUB.select.User.by.Confirm.Nodes);
			END IF;
		END IF;
					
	IF _MODE LIKE 'User.by.Confirm->Nodes%' THEN
	/*
		`v_wf_osoby_cwc`
	*/
		SET @.SQL.User.by.Confirm.Nodes = 
		"\n
		--	sub table
		(
				SELECT
					cw.commisionGUID, go.OsobaGUID -- AS UserGUID
					,cw.Def
					,EXISTS(SELECT cul.Idn FROM `crm_usr_links` cul WHERE cul.commisionGUID = cw.commisionGUID AND cul.Osoba = go.OsobaGUID AND cul.Poziom = 2) AS UserIsOwner
					, MAX(cwc.IDN) AS UserLast_cwcIDN
					, MAX(cw.IDN) AS UserLast_cwIDN
					, MAX(IF(cwc.Decision_UserGUID = go.OsobaGUID, cwc.IDN, 0)) AS UserLast_cwcIDN_Decyzja
					, MAX(IF(cwc.Decision_UserGUID = go.OsobaGUID, cw.IDN, 0)) AS UserLast_cwIDN_Decyzja
					-- , MAX(cwc.IDN) AS OsobaLastConfIdn
				FROM `crm_workflow_confirm` cwc, `grupy_osob` go, `crm_workflow` cw
				, `_user_accounts` ua 
				WHERE
					TRUE
					AND go.grupaGUID = cwc.UserGUID 
					AND go.OsobaGUID  = #UserGUID#
					AND cw.Idn = cwc.IDN_workflow
					AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					AND ua.osobaGUID = go.osobaGUID
					#WHERE cw.commisionGUID#
				GROUP BY commisionGUID, OsobaGUID
		) 
		"	-- AS wfcwc
		;
		CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.User.by.Confirm.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		SET _SQL = REPLACE(_SQL, '#User.by.Confirm.Nodes#', @.SQL.User.by.Confirm.Nodes);
	END IF;
	
	IF _MODE LIKE 'User.by.Cul->Nodes%' THEN
	/*
		`v_wf_osoby_cul_1`
	*/
		SET @.SQL.User.by.Cul.Nodes = 
		"\n
		--	sub table
		(
				SELECT
					cul.commisionGUID, go.OsobaGUID 
				FROM `crm_workflow` cw, `crm_usr_links` cul, `grupy_osob` go
				WHERE
					TRUE
					AND cw.CreateAt > NOW() - INTERVAL 1 YEAR
					AND cul.commisionGUID = cw.commisionGUID
					AND go.grupaGUID = cul.Osoba 
					AND go.OsobaGUID  = #UserGUID#
					#WHERE cw.commisionGUID#
				GROUP BY commisionGUID, OsobaGUID
		) 
		"	-- AS vinit
		;
		CALL crm_workflow_SELECT('SET.#VAR#', @.SQL.User.by.Cul.Nodes, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		SET _SQL = REPLACE(_SQL, '#User.by.Cul.Nodes#', @.SQL.User.by.Cul.Nodes);
	END IF;
			
	IF _MODE LIKE 'User->Crm->Node.test%' THEN
		SET @.cw.SQL.user.coms.test = 
		"
			SELECT
				0 AS tStart,
				cw.IDN,
				cw.DecisionAt AS Time_Log,
				GROUP_CONCAT(TRIM(CONCAT(ouser.Imie1, ' ', ouser.Nazwisko))) AS User_Nazwiska,
				GROUP_CONCAT(TRIM(CONCAT(odec.Imie1, ' ', odec.Nazwisko))) AS Decision_User_Nazwiska,
				@.cw_Status_Str := CONCAT_WS(' ',
					IF(cwdl.Descr_Item_Past IS NULL, 
						CONCAT('', cwd.Descr_Status),
						cwdl.Descr_Item_Past
					),
					NULL
				) AS cw_Status_Str,
				IFNULL(cwdl_prev.Descr_Item_Past, cwd_before.Descr_Status) AS Status_Before,
				GROUP_CONCAT(
					CONCAT(
						cwd.Descr_Status,
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					)
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Status_log,
				GROUP_CONCAT(
					CONCAT(
						cwc.ModifyAt, ' - ', odec.IdnUser, ' - > ', cwd.Descr_Status, 
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					) 
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Confirm_log,
				
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				_VarINT(100*cwd_before.Poziom) AS X,
				cw.IDN AS Y
			FROM #User.by.Cul.Nodes# vinit
			INNER JOIN `crm_workflow` cw ON cw.commisionGUID = vinit.commisionGUID
			LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
			LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw.Prev_IDN_workflow
		--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_start = cw.Start_Status AND cwdl.Status_end = cw.confirm_status
		--	aktualny status noda workflow	
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
		--	poprzedni status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
			LEFT JOIN `crm_workflow_def` cwd_before ON cwd_before.Def = cw.Def AND cwd_before.Status = cw.Start_Status
			LEFT JOIN `osoby` ouser ON ouser.GUID = cwc.UserGUID
			LEFT JOIN `osoby` odec ON odec.GUID = cwc.Decision_UserGUID
			WHERE
				vinit.commisionGUID = #GUID# 
				AND vinit.OsobaGUID = #UserGUID#
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		;
		"
		;
		CALL crm_workflow_SELECT('User.by.Cul->Nodes', @.cw.SQL.user.coms.test, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		CALL crm_workflow_SELECT('SET.#VAR#', @.cw.SQL.user.coms.test, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		
	END IF;
	
	IF _MODE LIKE 'Select.2022.nodes%' THEN
	/*
		workflow nodes
		CALL crm_workflow_SELECT('Select.2022.nodes', @SQL, '', @User, [DEF], [""|"CURR""END"|"END.ARCH"], '[""|"ALL"|"MOJE"]', '[""|"ALL"|"DO.DECYZJI"]', 'select');
		_Param_A	Definicja crm (np. wniosku) 
					gdy "" to wszystkie
		_Param_B	Statut wniosku (nie stan) czyli 
					""/"CURR": bieżące, "END": zakończone, "END.ARCH": Archiwum  (dawniej 0: bieżące, 1: zakończone, 2: Archiwum)
		_Param_C	Czy tylko moje czyli 
					"MOJE": tylko moje, "ALL"/"": wszystkie 
		_Param_D	Czy tylko te do decyzji czyli 
					"DO.DECYZJI" albo "ALL"/"": wszystkie 
		_Params		gdy "select" to zwracamy dane		
	*/
		DROP TEMPORARY TABLE IF EXISTS `t_nodes_2022`;
		SET @.cw.SQL.t_nodes_2022 = 
		"
		CREATE TEMPORARY TABLE `t_nodes_2022`
		SELECT
			-- wfcwc.*,
			c.GUID,
			c.Temat,
			c.Opis,
			c.Data,
			c.AreaGUID AS Oddzial,
			c.Oddzial_Str,
			-- PO CO??? c.Owner_Kto AS Hadlowiec_Nazw,
			-- PO CO??? '' AS Hadlowiec_IdnUser,
			-- PO CO??? c.typ_nazwa,
			c.status,
			c.confirm_status,
			c.Status_Info,
			c.Wniosek_Typ AS WFContext,
			c.Rodzaj, c.Podrodzaj,
			c.Wniosek_Typ,
			c.Owner_Kto,
			c.Owner_GUID,
			-- PO CO??? c.Owner_GUID = go.OsobaGUID AS Moj
			
			wfcwc.commisionGUID, wfcwc.OsobaGUID AS UserGUID,
			wfcwc.UserIsOwner,
			wfcwc.Last_cwIDN,
			wfcwc.UserLast_cwIDN,
			wfcwc.UserCC_cwIDN,
			wfcwc.UserLast_cwcIDN_Decyzja,
			wfcwc.UserLast_cwIDN_Decyzja,
			
			cw_last.Response = 'RESPONSE_100' AS Has_Decision,
			@.Decyzja_Status :=
			IF(cw_last.Response = 'RESPONSE_100',
			--	jest Decyzja
				IF(cw_last.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				--	ost. cw JEST cw usera i JEST JEGO DECYZJA
					'USER_DECYZJA',
					'OTHER_USER_DECYZJA'
				),
			--	nie ma w ogóle lub pełnej decyzji
				IF(cw_last.IDN = wfcwc.UserLast_cwIDN,
				--	ost. cw JEST cw usera i CZEKA NA jego DECYZJĘ
					'USER_BRAK_DECYZJI',
				--	ost. cw NIE JEST cw usera
					'OTHER_USER_BRAK_DECYZJI'
				)
			) AS Decyzja_Status,
			(@.Undo_info :=
			IF(cw_last.Is_Ending = 1 AND (cw_last.DecisionAT + INTERVAL c.Undo_After_End_Active_By MINUTE < NOW()),
			--	Dla zakonczonych jest spr. czy jeszcze moge cofac ...
				'No',
			--	Dla trwających lub zakonczonych ale jeszcze możliwych ...
				-- IF(cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				IF(cw_last.WasDecision = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				--	gdy nie podjeto jeszcze decyzji a usera decyzja poprzedzala ten cw to
					'Yes.Prev',	-- 'USER_UNDO_ENABLED',
					IF(@.Decyzja_Status = 'USER_DECYZJA' AND cw_next.IDN IS NULL, --  cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
						'Yes.Curr',	-- 'USER_UNDO_ENABLED',
						'No'	-- 'USER_UNDO_DISABLED'
					)
				)
			)) AS Undo_info,
			IF(@.Undo_info = 'Yes.Prev', cw_prev.IDN, IF(@.Undo_info = 'Yes.Curr', cw_last.Idn, NULL)) AS Undo_IdnWorkFlow,
		/*	było do 10 XI 2022
			IF(cw_last.Is_Ending = 1 AND (cw_last.DecisionAT + INTERVAL c.Undo_After_End_Active_By MINUTE < NOW()),
			--	Dla zakonczonych jest spr. czy jeszcze moge cofac ...
				'No',
			--	Dla trwających lub zakonczonych ale jeszcze możliwych ...
				-- było 	IF(cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				IF(cw_last.WasDecision = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				--	gdy nie podjeto jeszcze decyzji a usera decyzja poprzedzala ten cw to
					'Yes',	-- 'USER_UNDO_ENABLED',
					IF(@.Decyzja_Status = 'USER_DECYZJA' AND cw_next.IDN IS NULL, --  cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
						'Yes',	-- 'USER_UNDO_ENABLED',
						'No'	-- 'USER_UNDO_DISABLED'
					)
				)
			) AS Undo_Status,
		*/
			IF(@.Undo_info = 'No', 'No', 'Yes') AS Undo_Status,
			@.Decyzja_Status_Str :=
			IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI',
				-- 'oczek. na Twoją decyzję',
				'czeka na Ciebie',
				IF(@.Decyzja_Status = 'OTHER_USER_BRAK_DECYZJI',
					'brak decyzji',
					'zakończono'
				)
			) AS Decyzja_Status_Str,
			@.cw_Status_Str := CONCAT_WS(' ',
				IF(cwdl.Descr_Item_Past IS NULL, 
					CONCAT('', cwd.Descr_Status),
					cwdl.Descr_Item_Past
				),
				NULL
			) AS cw_Status_Str,
			@.cw_Status_Str2 := CONCAT_WS(' ',
				@.cw_Status_Str,
				CONCAT('(', @.Decyzja_Status_Str, ')')
			) AS cw_Status_Str2,
		--	Zakonczenie
						-- cwd.Is_Ending > 0 AS Is_Ending,
			cw_last.Is_Ending > 0 AS Is_Ending,
						-- cwd.Is_Ending = 2 AS Is_Cancel,
			cw_last.Is_Ending = 2 AS Is_Cancel,
			cwd.param1 AS confirm_status_Param1,
						-- (cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH < CURRENT_DATE()) ) AS Is_Archiwum,
			(cw_last.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH < CURRENT_DATE()) ) AS Is_Archiwum,
			cw_last.DecisionAT,
			
			/*
			(@.Undo_Enabled := 
				-- NOT (cwc.confirm_status IN ('', cw.Start_Status)) 
				cw_last.Response = 'RESPONSE_100'
				-- AND cwc.Decision_UserGUID = #UserGUID#
				AND cwc.Decision_UserGUID = '{5943D8B9-31E3-491C-B516-6E98B661BFE4}'
				AND IFNULL(cw_next.ResponseCount, 0) = 0
				AND cwc.ModifyAT > CURRENT_DATE() - INTERVAL 42 DAY
			) AS Undo_Enabled,
			*/
			cw_last.Response,
			cw_last.IDN AS Idn_WorkFlow_Curr,
			cw_prev.IDN AS Idn_WorkFlow_Prev,
			c.StartTime,
			c.EndTime,
			Date(c.StartTime) AS DataOd,
			Date(c.EndTime) AS DataDo,
			c.Undo_After_End_Active_By
			-- ,cw_last.*
		-- FROM `v_wf_osoby_cwc` wfcwc
		FROM #User.by.Confirm.Nodes# wfcwc
		LEFT JOIN `crm_workflow` cw_last ON cw_last.IDN = (SELECT MAX(cw1.IDN) FROM `crm_workflow` cw1 WHERE cw1.commisionGUID = wfcwc.commisionGUID)
		LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw_last.Prev_IDN_workflow
		LEFT JOIN `crm_workflow` cw_next ON cw_next.Prev_Idn_WorkFlow = cw_last.Idn	-- node nastepne
		-- LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw_last.Prev_IDN_workflow
	--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
		LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw_last.Def AND cwdl.Status_start = cw_last.Start_Status AND cwdl.Status_end = cw_last.confirm_status
	--	aktualny status noda workflow	
		LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw_last.Def AND cwd.Status = cw_last.confirm_status
		
		INNER JOIN `v_crm_workflow_coms2` c ON c.GUID = wfcwc.commisionGUID
		WHERE
		/*	zalogoweany ...	*/
			wfcwc.OsobaGUID = #UserGUID#
		/*	Statut (bieżące, zakończone, archiwum) ...	*/
			#Statut#	
		/*	Def wniosku	...*/
			#DEF#		
		/*	Moje/wszystkie ...	*/
			#MOJE#
		/*	Czy tylko do decyzji ...	*/
			#DO.DECYZJI#
			
		--	zakończone
			-- AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) 
		--	archiwum
			-- AND IF(@_Archiwum = '1', cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 2 MONTH < CURRENT_DATE()) , TRUE)
		--	dla moje nalezy podac
			-- AND wfcwc.UserIsOwner
		--	dla czekające na moja decyzje
			-- AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < 'RESPONSE_100'
			-- having cw_last.IDN = 1876 
		-- GROUP BY wfcwc.OsobaGUID, wfcwc.commisionGUID
		-- #HAVING#
		;
		"
		;
		CALL crm_workflow_SELECT('User.by.Confirm->Nodes', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		CALL crm_workflow_SELECT('SET.#VAR#', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');

		IF _Param_B <> '' THEN
		--	dla zgod. z wersja pocz. gdy w _Param_A, _Param_AB, ... były param. 
			SET
			--	ARCH', ''
				@.cw.SELECT.Def = _Param_A,
				@.cw.SELECT.StanWF = _Param_B,
				@.cw.SELECT.Czyje = _Param_C,
				@.cw.SELECT.StanDecyzji = _Param_D,
				@.cw.SELECT.DataOd = NULL,
				@.cw.SELECT.DataDo = NULL
			;
		END IF;
		SET @SQLText = @.cw.SQL.t_nodes_2022;
		-- SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#UserGUID#', QUOTE(_ID_2));
	--	@.cw.SELECT.Def	(_Param_A)
	--	Definicja gdy "" to wszystkie
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#DEF#', 
			IF(IFNULL(@.cw.SELECT.Def, '') != '', CONCAT('AND wfcwc.Def = ', QUOTE(@.cw.SELECT.Def)), '/* brak okr. def. wniosku */')
		)
		;
	--	@.cw.SELECT.StanWF	(_Param_B)
	--	Statut wniosku (nie stan) czyli "": bieżące, "END": zakończone, "END_ARCH": Archiwum(0: bieżące, 1: zakończone, 2: Archiwum)
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#Statut#', 
			IF(@.cw.SELECT.StanWF IN ('', 'CURR'),
			--	bieżące
				-- 'AND cwd.Is_Ending = 0	 /* bieżące */', 
				'AND IFNULL(cw_last.Is_Ending, 0) = 0	 /* bieżące */', 
				IF(@.cw.SELECT.StanWF = 'END', 
				--	zakończone
					-- 'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) 	/* zakończone */',
					'AND IFNULL(cw_last.Is_Ending, 0) > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) 	/* zakończone */',
					IF(@.cw.SELECT.StanWF = 'END_ARCH', 
					--	archiwum
						-- 'AND IFNULL(cw_last.Is_Ending, 0) > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH < CURRENT_DATE())	 /* archiwum */',
						'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH < CURRENT_DATE())	 /* archiwum */',
						'/* brak okr. statutu - pokaż wszyskie */'
					)
				)
			)
		)
		;
	/*	@.cw.SELECT.Czyje	(_Param_C)	
		Czy tylko moje czyli "MOJE": tylko moje, "ALL / "": wszystkie 
	*/
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#MOJE#', 
			IF(IFNULL(@.cw.SELECT.Czyje, '') = 'MOJE', 	
				'AND wfcwc.UserIsOwner', 
				'/* pokaż wszystkie */'
			)
		);
	/*	@.cw.SELECT.StanDecyzji	(_Param_D)	
		Czy tylko te do decyzji czyli "DO.DECYZJI" albo "ALL / "": wszystkie 
	*/
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, 
			'#DO.DECYZJI#', 
				IF(IFNULL(@.cw.SELECT.StanDecyzji, '') = 'DO.DECYZJI', 	
					'AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < ''RESPONSE_100''  /* pokaż tylko te do decyzji zalogowanego */', 
					IF(IFNULL(@.cw.SELECT.StanDecyzji, '') = 'DO.MOJEJ.DECYZJI', 	
						'AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < ''RESPONSE_100'' AND cw_last.IDN = wfcwc.UserLast_cwIDN	/* pokaż tylko te do decyzji zalogowanego */', 
						'/* pokaż wszystkie */'
					)
				)
			
		);
		SET @SQLText = @.cw.SQL.t_nodes_2022;
		SET @.Select.all.nodes.do.decyzji.SQL = @.cw.SQL.t_nodes_2022;
		CALL _ExecuteCmd(@.cw.SQL.t_nodes_2022, @Error);
		IF _Params LIKE '%Select%' THEN
			SELECT 
			-- c.Edit_Enabled = (c.confirm_status IN ('new'))
				t.*, 
				(@.vButtons := 
				CONCAT_WS(',',
					IF(TRUE, 'HISTORY', NULL),
					IF(t.Decyzja_Status = 'USER_BRAK_DECYZJI', 'DECISION', NULL),
					--	UWAGA na szybko robie tu wstawke by dla zakładek END i END ARCH nie było przycisku Cofnij ...
					-- 	potem usun to i zróc to w oparciu o absencje_dict i czas na cofnięcie!!!
					IF(t.Undo_Status = 'YES', 'UNDO', NULL),
					IF(t.Status < 2, 'EDIT', NULL),
					IF(t.Status < 2, 'DELETE', NULL),
					NULL
				)) AS vButtons,
				IF(@.vButtons LIKE '%DECISION%', t.Idn_WorkFlow_Curr, NULL) AS Idn_WorkFlow_DECISION,
				-- IF(@.vButtons LIKE '%UNDO%', t.Idn_WorkFlow_Prev, NULL) AS Idn_WorkFlow_UNDO,
				IF(@.vButtons LIKE '%UNDO%', t.Undo_IdnWorkFlow, NULL) AS Idn_WorkFlow_UNDO,
			--	json_Buttons	
				-- _Brackets('{"buttons":[',
				CONCAT(
					-- open Brackets
					'{"buttons":[',
					CONCAT_WS(',', 
					--	Historia
						_Brackets('{',
						IF(TRUE, 
							'"ID":"HISTORY","Caption":"Historia","Color":"info","Href":"CALL"',		-- info
							NULL
						), '}'),
					--	Decision button	
						_Brackets('{',
						-- IF(t.Decyzja_Status = 'USER_BRAK_DECYZJI', 
						IF(@.vButtons LIKE '%DECISION%',
							'"ID":"DECISION","Caption":"Decyduj","Color":"primary","Href":"CALL"',
							NULL
						), '}'),
					--	Undo button	
						_Brackets('{',
						-- IF(t.Undo_Status = 'USER_UNDO_ENABLED', 
						IF(@.vButtons LIKE '%UNDO%',
							'"ID":"UNDO","Caption":"Cofnij","Color":"primary","Href":"CALL"',
							NULL
						), '}'),
					--	Edit	
						_Brackets('{',
						IF(@.vButtons LIKE '%EDIT%',
							'"ID":"EDIT","Caption":"Edytuj","Color":"warning","Href":"CALL"',
							NULL
						), '}'),
					--	Usuń	
						_Brackets('{',
						IF(@.vButtons LIKE '%DELETE%',
							'"ID":"DELETE","Caption":"Usuń","Color":"danger","Href":"CALL"',
							NULL
						), '}')
					),
					-- close Brackets
					']}'
				) AS json_Buttons

				
			FROM `t_nodes_2022` t
			ORDER BY t.Data
			;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;

		
		IF _Params LIKE '%SQL%' THEN
			SELECT @.cw.SQL.t_nodes_2022;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
		
	END IF;

	IF _MODE LIKE 'Select.2022.workflow.history%' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_crm_workflow.history`;

		SET @.Select.2022.workflow.history.SQL = 
		"
		CREATE TEMPORARY TABLE `t_crm_workflow.history` 
		(
			SELECT
				0 AS tStart,
				cw.IDN,
				cw.DecisionAt AS Time_Log,
				GROUP_CONCAT(TRIM(CONCAT(ouser.Imie1, ' ', ouser.Nazwisko))) AS User_Nazwiska,
				GROUP_CONCAT(TRIM(CONCAT(odec.Imie1, ' ', odec.Nazwisko))) AS Decision_User_Nazwiska,
				@.cw_Status_Str := CONCAT_WS(' ',
					IF(cwdl.Descr_Item_Past IS NULL, 
						CONCAT('', cwd.Descr_Status),
						cwdl.Descr_Item_Past
					),
					NULL
				) AS cw_Status_Str,
				IFNULL(cwdl_prev.Descr_Item_Past, cwd_before.Descr_Status) AS Status_Before,
				GROUP_CONCAT(
					CONCAT(
						cwd.Descr_Status,
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					)
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Status_log,
				GROUP_CONCAT(
					CONCAT(
						cwc.ModifyAt, ' - ', odec.IdnUser, ' - > ', cwd.Descr_Status, 
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					) 
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Confirm_log,
				
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				_VarINT(100*cwd_before.Poziom) AS X,
				cw.IDN AS Y
			FROM #User.by.Cul.Nodes# vinit
			-- FROM `v_wf_osoby_cul_1` vinit
			INNER JOIN `crm_workflow` cw ON cw.commisionGUID = vinit.commisionGUID
			LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
			LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw.Prev_IDN_workflow
		--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_start = cw.Start_Status AND cwdl.Status_end = cw.confirm_status
		--	aktualny status noda workflow	
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
		--	poprzedni status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
			LEFT JOIN `crm_workflow_def` cwd_before ON cwd_before.Def = cw.Def AND cwd_before.Status = cw.Start_Status
			LEFT JOIN `osoby` ouser ON ouser.GUID = cwc.UserGUID
			LEFT JOIN `osoby` odec ON odec.GUID = cwc.Decision_UserGUID
			WHERE
				vinit.commisionGUID = #GUID# 
				AND vinit.OsobaGUID = #UserGUID#
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		)
		UNION
		(
			SELECT
				1 AS tStart,
				cw.IDN,
				cw.CreateAt AS Time_Log,
				GROUP_CONCAT(TRIM(CONCAT(ouser.Imie1, ' ', ouser.Nazwisko))) AS User_Nazwiska,
				GROUP_CONCAT(TRIM(CONCAT(odec.Imie1, ' ', odec.Nazwisko))) AS Decision_User_Nazwiska,
				@.cw_Status_Str := CONCAT_WS(' ',
					IF(cwdl.Descr_Item_Past IS NULL, 
						CONCAT('', cwd.Descr_Status),
						cwdl.Descr_Item_Past
					),
					NULL
				) AS cw_Status_Str,
				cwd_before.Descr_Status AS Status_Before,
				CONCAT('Utworzenie wniosku - status pocz.: \"', cwd_before.Descr_Status, '\"') AS Status_log,
				GROUP_CONCAT(
					CONCAT(
						cw.CreateAt, ' - ', odec.IdnUser, ' - > ', cwd.Descr_Status, 
						IFNULL(_Brackets(_VarStr('.\nZ adnotacją: \"'), _VarStr(cwc.Comment), '\"'), '')
					) 
					ORDER BY cwc.ModifyAt SEPARATOR '\n'
				) AS Confirm_log,
				
				cw.Prev_Idn_workflow,
				cw.commisionGUID,
				cw.Def,
				cw.Start_Status,
				cw.Confirm_Status,
				-- _VarINT(100*cwd_before.Poziom) AS X,
				-- cw.IDN AS Y
				_VarINT(0) AS X,
				_VarINT(0) AS Y
			FROM #User.by.Cul.Nodes# vinit
			-- FROM `v_wf_osoby_cul_1` vinit
			INNER JOIN `crm_workflow` cw ON cw.commisionGUID = vinit.commisionGUID
			LEFT JOIN `crm_workflow_confirm` cwc ON cwc.IDN_workflow = cw.IDN
			-- LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw.Prev_IDN_workflow
		--	aktualny status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw.Def AND cwdl.Status_start = cw.Start_Status AND cwdl.Status_end = cw.confirm_status
		--	aktualny status noda workflow	
			LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw.Def AND cwd.Status = cw.confirm_status
		--	poprzedni status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
			-- LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
			LEFT JOIN `crm_workflow_def` cwd_before ON cwd_before.Def = cw.Def AND cwd_before.Status = cw.Start_Status
			LEFT JOIN `osoby` ouser ON ouser.GUID = cwc.UserGUID
			LEFT JOIN `osoby` odec ON odec.GUID = cwc.Decision_UserGUID
			WHERE
				vinit.commisionGUID = #GUID# 
				AND vinit.OsobaGUID = #UserGUID#
				AND cw.Start_Status = 'new'
			GROUP BY cw.IDN
			ORDER BY cw.IDN
		)
		ORDER BY tStart DESC, Y
		;
		"
		;
		CALL crm_workflow_SELECT('User.by.Cul->Nodes', @.Select.2022.workflow.history.SQL, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		CALL crm_workflow_SELECT('SET.#VAR#', @.Select.2022.workflow.history.SQL, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		SET @SQLText = @.Select.2022.workflow.history.SQL;
		/*
		SET @.Select.2022.workflow.history.SQL = REPLACE(@.Select.2022.workflow.history.SQL, '#GUID#', QUOTE(_ID));
		SET @.Select.2022.workflow.history.SQL = REPLACE(@.Select.2022.workflow.history.SQL, '#UserGUID#', QUOTE(_ID_2));
		SET @.Select.2022.workflow.history.SQL = @.Select.2022.workflow.history.SQL;
		*/
		CALL _ExecuteCmd(@.Select.2022.workflow.history.SQL, @Error);
		
		IF _Params LIKE '%Select%' THEN
			SELECT * FROM `t_crm_workflow.history`;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
		
		IF _Params LIKE '%SQL%' THEN
			SELECT @.Select.2022.workflow.history.SQL;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
		
	END IF;

	IF _MODE LIKE 'Select.User->%' THEN
	/************************************************************************************************************************
		NOWE!!!
		Dwa tryby wywołań:
			Select.User->nodes->crm
				Dla wniosków bo wychodzimy od workflow nodes do crm-a
				Czyli ograniczamy zestaw tylko do węzłów w którym user był w procesie decyzyjnym w szczególności jest to jego wniosek
				
			Select.User->crm->nodes	
				Dla Szkoleń, Delegacji bo wychodzimy od crm-a do workflow nodes
				Bo może ktoś byc związany z crm (cul) ale nie brać udziału w proc. decyzyjnym (workflow nodes)
	************************************************************************************************************************/
SET @.debug = concat_WS('/', @.debug, '2');
		IF _MODE LIKE 'Select.User->nodes%->crm%' THEN
SET @.debug = concat_WS('/', @.debug, '2.a');
		/*
			NOWE!!!
			Dla wniosków bo wychodzimy od workflow nodes do crm-a
			Czyli ograniczamy zestaw tylko do węzłów w którym user był w procesie decyzyjnym w szczególności jest to jego wniosek
		*/
			SET 
				@.cw.SELECT.User.Is.By.CUL = FALSE,
				@.cw.SELECT.User.Is.By.NODES = TRUE
			;
		END IF;
		
		IF _MODE LIKE 'Select.User->crm->nodes%' THEN
SET @.debug = concat_WS('/', @.debug, '2.b');
		/*
			NOWE!!!
			Dla Szkoleń, Delegacji bo wychodzimy od crm-a do workflow nodes
			Bo może ktoś byc związany z crm (cul) ale nie brać udziału w proc. decyzyjnym (workflow nodes)
		*/
			SET 
				@.cw.SELECT.User.Is.By.CUL = TRUE,
				@.cw.SELECT.User.Is.By.NODES = FALSE
			;
		END IF;
SET @.debug = concat_WS('/', @.debug, '3');
		
		DROP TEMPORARY TABLE IF EXISTS `t_nodes_2022`;
		SET @.cw.SQL.t_nodes_2022 = 
		"
		CREATE TEMPORARY TABLE `t_nodes_2022`
		SELECT
			c.GUID,
			c.Temat,
			c.Opis,
			c.Data,
			c.AreaGUID AS Oddzial,
			c.Oddzial_Str,
			-- PO CO??? c.Owner_Kto AS Hadlowiec_Nazw,
			-- PO CO??? '' AS Hadlowiec_IdnUser,
			-- PO CO??? c.typ_nazwa,
			c.status,
			c.confirm_status,
			cw_last.Start_Status AS Start_Status_last,
			cw_last.confirm_status AS confirm_status_last,
			c.Status_Info,
			c.Wniosek_Typ AS WFContext,
			c.Rodzaj, c.Podrodzaj,
			c.Wniosek_Typ,
			c.Owner_Kto,
			c.Owner_GUID,
			-- PO CO??? c.Owner_GUID = go.OsobaGUID AS Moj
			
			wfcwc.commisionGUID, wfcwc.UserGUID,

			wfcwc.UserIsOwner,
			wfcwc.Last_cwIDN,
			wfcwc.UserLast_cwIDN,
			wfcwc.UserCC_cwIDN,
			wfcwc.UserLast_cwcIDN_Decyzja,
			wfcwc.UserLast_cwIDN_Decyzja,
			
			cw_last.Response = 'RESPONSE_100' AS Has_Decision,
			@.Decyzja_Status :=
			IF(cw_last.Response = 'RESPONSE_100',
			--	jest Decyzja
				IF(cw_last.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				--	ost. cw JEST cw usera i JEST JEGO DECYZJA
					'USER_DECYZJA',
					'OTHER_USER_DECYZJA'
				),
			--	nie ma w ogóle lub pełnej decyzji
				IF(cw_last.IDN = wfcwc.UserLast_cwIDN,
				--	ost. cw JEST cw usera i CZEKA NA jego DECYZJĘ
					'USER_BRAK_DECYZJI',
				--	ost. cw NIE JEST cw usera
					'OTHER_USER_BRAK_DECYZJI'
				)
			) AS Decyzja_Status,
			(@.Undo_info :=
			IF(cw_last.Is_Ending = 1 AND (cw_last.DecisionAT + INTERVAL c.Undo_After_End_Active_By MINUTE < NOW()),
			--	Dla zakonczonych jest spr. czy jeszcze moge cofac ...
				'No',
			--	Dla trwających lub zakonczonych ale jeszcze możliwych ...
				-- IF(cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				IF(cw_last.WasDecision = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
				--	gdy nie podjeto jeszcze decyzji a usera decyzja poprzedzala ten cw to
					'Yes.Prev',	-- 'USER_UNDO_ENABLED',
					IF(@.Decyzja_Status = 'USER_DECYZJA' AND cw_next.IDN IS NULL, --  cw_last.ResponseCount = 0 AND cw_prev.IDN = wfcwc.UserLast_cwIDN_Decyzja,
						'Yes.Curr',	-- 'USER_UNDO_ENABLED',
						'No'	-- 'USER_UNDO_DISABLED'
					)
				)
			)) AS Undo_info,
			IF(@.Undo_info = 'Yes.Prev', cw_prev.IDN, IF(@.Undo_info = 'Yes.Curr', cw_last.Idn, NULL)) AS Undo_IdnWorkFlow,
			IF(@.Undo_info = 'No', 'No', 'Yes') AS Undo_Status,
			@.Decyzja_Status_Str :=
			IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI',
				-- 'oczek. na Twoją decyzję',
				'czeka na Ciebie',
				IF(@.Decyzja_Status = 'OTHER_USER_BRAK_DECYZJI',
					'brak decyzji',
					'zakończono'
				)
			) AS Decyzja_Status_Str,
			@.cw_Status_Str := CONCAT_WS(' ',
				IF(cwdl.Descr_Item_Past IS NULL, 
					CONCAT('', cwd.Descr_Status),
					cwdl.Descr_Item_Past
				),
				NULL
			) AS cw_Status_Str,
			@.cw_Status_Str2 := CONCAT_WS(' ',
				@.cw_Status_Str,
				CONCAT('(', @.Decyzja_Status_Str, ')')
			) AS cw_Status_Str2,
			CONCAT_WS(' - ', 
				IF(cw_last.Is_Ending = 1, 'Koniec', NULL), 
				IFNULL(cwdl.Descr_Item_Past, cwdl_prev.Descr_Item_Past),
				IF(cwd.Descr_status = cwdl.Descr_Item_Past, NULL, cwd.Descr_status)
			) AS Status_Current_Str,
		--	Zakonczenie
						-- cwd.Is_Ending > 0 AS Is_Ending,
			cw_last.Is_Ending > 0 AS Is_Ending,
						-- cwd.Is_Ending = 2 AS Is_Cancel,
			cw_last.Is_Ending = 2 AS Is_Cancel,
			cwd.param1 AS confirm_status_Param1,
						-- (cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH < CURRENT_DATE()) ) AS Is_Archiwum,
			(cw_last.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH < CURRENT_DATE()) ) AS Is_Archiwum,
			cw_last.DecisionAT,
			cw_last.Response,
			cw_last.IDN AS Idn_WorkFlow_Curr,
			cw_prev.IDN AS Idn_WorkFlow_Prev,
			c.StartTime,
			c.EndTime,
                c.IsEnding,
			Date(c.StartTime) AS DataOd,
			Date(c.EndTime) AS DataDo,
			c.Undo_After_End_Active_By,
			cwd.Poziom AS Last_Poziom,
			cwd.Status AS cwd_Status,
			cwd.Def,
			cwd.Buttons,	-- buttony
			REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(cwd.Buttons,
				'DECISION?', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI', 'DECISION', '-')),
				'EDIT.USER.Confirm.Owner?', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI' AND wfcwc.UserIsOwner, 'EDIT', '-')),
				'VIEW.USER.Confirm.Owner?', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI' AND NOT wfcwc.UserIsOwner, 'VIEW', '-')),
				'EDIT.USER.Poniom=0.Confirm?', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI' AND cwd.Poziom = 0, 'EDIT', '-')),
				'EDIT.USER.Confirm?', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI', 'EDIT', '-')),
				'DELETE', IF(@.Decyzja_Status = 'USER_BRAK_DECYZJI' AND wfcwc.UserIsOwner AND cwd.Poziom = 0, 'DELETE', '-')),
				'UNDO?', IF(@.Undo_info = 'No', '-', 'UNDO'))
			AS wfButtons

			
			
			-- ,cw_last.*
		-- FROM `v_wf_osoby_cwc` wfcwc
		FROM #Sub.Table.User# wfcwc
		LEFT JOIN `crm_workflow` cw_last ON cw_last.IDN = (SELECT MAX(cw1.IDN) FROM `crm_workflow` cw1 WHERE cw1.commisionGUID = wfcwc.commisionGUID)
		LEFT JOIN `crm_workflow` cw_prev ON cw_prev.IDN = cw_last.Prev_IDN_workflow
		LEFT JOIN `crm_workflow` cw_next ON cw_next.Prev_Idn_WorkFlow = cw_last.Idn	-- node nastepne
	--	aktualny węzeł - status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
		LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cw_last.Def AND cwdl.Status_start = cw_last.Start_Status AND cwdl.Status_end = cw_last.confirm_status
	--	aktualny status noda workflow	
		LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cw_last.Def AND cwd.Status = cw_last.confirm_status
	--	poprzedni węzeł - status z crm_workflow_def_links a gdy null (bo nie ma decyzji) to z crm_workflow_def
		LEFT JOIN `crm_workflow_def_links` cwdl_prev ON cwdl_prev.Def = cw_prev.Def AND cwdl_prev.Status_start = cw_prev.Start_Status AND cwdl_prev.Status_end = cw_prev.confirm_status
		
		-- INNER JOIN `v_crm_workflow_coms2` c ON c.GUID = wfcwc.commisionGUID
		--	UWAGA jmam zmienił to w PLISZKA 12 IV 2024
		INNER JOIN `v_crm_workflow_n_coms2` c ON c.GUID = wfcwc.commisionGUID
		WHERE
		/*	zalogoweany ...	*/
			wfcwc.UserGUID = #UserGUID#
		/*	Statut (bieżące, zakończone, archiwum) ...	*/
			#Statut#	
		/*	Def wniosku	...*/
			#DEF#		
		/*	Moje/wszystkie ...	*/
			#MOJE#
		/*	Czy tylko do decyzji ...	*/
			#DO.DECYZJI#
		/*	Confirm_status	*/
			#Confirm_status#
		;
		"
		;		
	--	Sub Table ...	
SET @.debug = concat_WS('/', @.debug, '4');
				--	SQL.sub.for.User.by.Confirm->Nodes.old
					IF _MODE LIKE 'Select.User->nodes.old->crm%' THEN
						CALL crm_workflow_SELECT('SQL.sub.for.User.by.Confirm->Nodes.old', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
					END IF;	
	
		IF _MODE LIKE 'Select.User->nodes->crm%' THEN
SET @.debug = concat_WS('/', @.debug, '4.a');
			CALL crm_workflow_SELECT('SQL.sub.for.User.by.Confirm->Nodes', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		END IF;
		IF _MODE LIKE 'Select.User->crm->nodes%' THEN
SET @.debug = concat_WS('/', @.debug, '4.b');
			CALL crm_workflow_SELECT('SQL.sub.for.User.by.Cul->Nodes', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');
		END IF;
		
	--	Set VAR
		CALL crm_workflow_SELECT('SET.#VAR#', @.cw.SQL.t_nodes_2022, _ID, _ID_2, _Param_A, _Param_B, _Param_C, '', '');

		SET @SQLText = @.cw.SQL.t_nodes_2022;
		-- SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#UserGUID#', QUOTE(_ID_2));
	--	@.cw.SELECT.Def	(_Param_A)
	--	Definicja gdy "" to wszystkie
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#DEF#', 
			IF(IFNULL(@.cw.SELECT.Def, '') != '', CONCAT('AND wfcwc.Def = ', QUOTE(@.cw.SELECT.Def)), '/* brak okr. def. wniosku */')
		)
		;
	--	@.cw.SELECT.StanWF	(_Param_B)
	--	Statut wniosku (nie stan) czyli "CURR"|"": bieżące, "END": zakończone, "END.ARCH": Archiwum(0: bieżące, 1: zakończone, 2: Archiwum)
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#Statut#', 
			IF(@.cw.SELECT.StanWF IN ('', 'CURR'),
			--	bieżące
				-- 'AND cwd.Is_Ending = 0	 /* bieżące */', 
				'AND IFNULL(cw_last.Is_Ending, 0) = 0	 /* bieżące */', 
				IF(@.cw.SELECT.StanWF = 'END', 
				--	zakończone
					-- 'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH >= CURRENT_DATE()) 	/* zakończone */',
					'AND IFNULL(cw_last.Is_Ending, 0) > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH >= CURRENT_DATE()) 	/* zakończone */',
					IF(@.cw.SELECT.StanWF = 'END.ARCH', 
					--	archiwum
						'AND (cw_last.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 5 MONTH < CURRENT_DATE()) )	 /* archiwum */',
						-- 'AND cwd.Is_Ending > 0 AND (cw_last.DecisionAT + INTERVAL 4 MONTH < CURRENT_DATE())	 /* archiwum */',
						'/* brak okr. statutu - pokaż wszyskie */'
					)
				)
			)
		)
		;
	--	Confirm_status		
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#Confirm_status#', 
			IF(NULLIF(@.cw.SELECT.Confirm_status, 'ALL') IS NULL, 
				'/* brak okr. Confirm_status */',
				'AND cw_last.Confirm_status = IFNULL(@.cw.SELECT.Confirm_status, cw_last.Confirm_status)'
			)
		)
		;
	/*	@.cw.SELECT.Czyje	(_Param_C)	
		Czy tylko moje czyli czyje  - "ALL" / "" : wszystkie, "MOJE": tylko moje, "NIE.MOJE": NIE moje
	*/
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, '#MOJE#', 
			IF(IFNULL(@.cw.SELECT.Czyje, '') = 'MOJE', 	
				'AND wfcwc.UserIsOwner', 
				IF(IFNULL(@.cw.SELECT.Czyje, '') = 'NIE.MOJE', 	
					'AND NOT wfcwc.UserIsOwner', 
					'/* pokaż wszystkie */'
				)
			)
		);
	/*	@.cw.SELECT.StanDecyzji	(_Param_D)	
		Czy tylko te do decyzji czyli "DO.DECYZJI" albo "ALL / "": wszystkie 
	*/
		SET @.cw.SQL.t_nodes_2022 = REPLACE(@.cw.SQL.t_nodes_2022, 
			'#DO.DECYZJI#', 
				IF(IFNULL(@.cw.SELECT.StanDecyzji, '') = 'DO.DECYZJI', 	
					'AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < ''RESPONSE_100''  /* pokaż tylko te do decyzji zalogowanego */', 
					IF(IFNULL(@.cw.SELECT.StanDecyzji, '') = 'DO.MOJEJ.DECYZJI', 	
						'AND cw_last.IDN = wfcwc.UserLast_cwIDN and cw_last.Response < ''RESPONSE_100'' AND cw_last.IDN = wfcwc.UserLast_cwIDN	/* pokaż tylko te do decyzji zalogowanego */', 
						'/* pokaż wszystkie */'
					)
				)
			
		);
			
		SET @SQLText = @.cw.SQL.t_nodes_2022;
		SET @.Select.all.nodes.do.decyzji.SQL = @.cw.SQL.t_nodes_2022;
		CALL _ExecuteCmd(@.cw.SQL.t_nodes_2022, @Error);
		IF _Params LIKE '%Select%' THEN
			SELECT 
			-- c.Edit_Enabled = (c.confirm_status IN ('new'))
				t.*, 
				(@.vButtons := 
				CONCAT_WS(',',
					IF(TRUE, 'HISTORY', NULL),
					IF(t.Decyzja_Status = 'USER_BRAK_DECYZJI', 'DECISION', NULL),
					--	UWAGA na szybko robie tu wstawke by dla zakładek END i END ARCH nie było przycisku Cofnij ...
					-- 	potem usun to i zróc to w oparciu o absencje_dict i czas na cofnięcie!!!
					IF(t.Undo_Status = 'YES', 'UNDO', NULL),
					IF(t.Status < 2, 'EDIT', NULL),
					IF(t.Status < 2, 'DELETE', NULL),
					NULL
				)) AS vButtonsOLD,
				(@.vButtons := (t.wfButtons)) AS vButtons,
				IF(@.vButtons LIKE '%DECISION%', t.Idn_WorkFlow_Curr, NULL) AS Idn_WorkFlow_DECISION,
				-- IF(@.vButtons LIKE '%UNDO%', t.Idn_WorkFlow_Prev, NULL) AS Idn_WorkFlow_UNDO,
				IF(@.vButtons LIKE '%UNDO%', t.Undo_IdnWorkFlow, NULL) AS Idn_WorkFlow_UNDO,
				
			--	json_Buttons	
				CONCAT(
				-- open Brackets
					'{"buttons":[',
				-- buttons 1..n
					CONCAT_WS(',', 
					--	Decision button	
						_Brackets('{',
						IF(@.vButtons LIKE '%DECISION%',
							@.Buttons.wf.DECISION,
							NULL
						), '}'),
					--	Undo button	
						_Brackets('{',
						IF(@.vButtons LIKE '%UNDO%',
							@.Buttons.wf.UNDO,
							NULL
						), '}'),
					--	Edit	
						_Brackets('{',
						IF(@.vButtons LIKE '%EDIT%',
							@.Buttons.wf.EDIT,
							NULL
						), '}'),
					--	View - Podgląd
						_Brackets('{',
						IF(@.vButtons LIKE '%VIEW%',
							btn.btn_VIEW,	-- @.Buttons.wf.VIEW,
							NULL
						), '}'),
					--	Print
						_Brackets('{',
						IF(@.vButtons LIKE '%PRINT%',
							@.Buttons.wf.PRINT,
							NULL
						), '}'),
					--	Szczegóły
						_Brackets('{',
						IF(@.vButtons LIKE '%PROPS%',
							-- btn.btn_PROPS,	-- @.Buttons.wf.PROPS,
							@.Buttons.wf.PROPS,
							NULL
						), '}'),
					--	Usuń	
						_Brackets('{',
						IF(@.vButtons LIKE '%DELETE%', --  AND FALSE,
							@.Buttons.wf.DELETE,
							NULL
						), '}'),
					--	Historia
						_Brackets('{',
						IF(@.vButtons LIKE '%HISTORY%',
							btn.btn_HISTORY,	-- @.Buttons.wf.HISTORY,
							NULL
						), '}'),
						NULL
					),
				-- close Brackets
					']}'
				) AS json_Buttons
				
			FROM `t_nodes_2022` t
			LEFT JOIN `t_wf_buttons` btn ON TRUE
			ORDER BY t.Data
			;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;

		
		IF _Params LIKE '%SQL%' THEN
			SELECT @.cw.SQL.t_nodes_2022;
			-- DROP TEMPORARY TABLE IF EXISTS `v_crm_workflow.history`;
		END IF;
			
	END IF;
	
	IF _MODE LIKE 'SELECT.Lista.%' THEN
		IF _MODE LIKE 'SELECT.Lista.Statusy.worflow%' THEN
		/********************************************************************************************************
			CALL crm_workflow_SELECT('SELECT.Lista.Statusy.worflow', @.SQL, '', '', @_PodRodzaj, @_Def, '', '', '');		
			CALL crm_workflow_SELECT('SELECT.Lista.Statusy.worflow.DELEGACJE', @.SQL, '', '', @_PodRodzaj, @_Def, '', '', '');		
			CALL crm_workflow_SELECT('SELECT.Lista.Statusy.worflow.SZKOLENIA', @.SQL, '', '', @_PodRodzaj, @_Def, '', '', '');		
			_Param_A	rodzaj crm
			_Param_B	def
		********************************************************************************************************/
			SET @.Like.PodRodzaj = 
				CONCAT(
					'%(', 
					IF(_MODE LIKE 'SELECT.Lista.Statusy.worflow.DELEGACJE', 
						6, 
						IF(_MODE LIKE 'SELECT.Lista.Statusy.worflow.SZKOLENIA', 
							5,
							_Param_A
						)
					),  -- Wniosek o deleagacje, szkolenie
			
				')%');
			SET @.Like.Def = NULLIF(_Param_B, '');
			SELECT
				'ALL' AS STATUS, 'Pokaz wszystkie' AS Descr_status, -1 AS LP
			UNION
			SELECT 
				s.Status, s.Descr_status, s.LP_2 AS LP
			FROM `v_crm_workflow_def_active` s
			WHERE
				TRUE
				AND 
				IF(@.Like.Def IS NOT NULL,
					s.Def = @.Like.Def,
					s.Podrodzaje LIKE @.Like.PodRodzaj
				)
			ORDER BY LP
			;
		END IF;
		
		IF _MODE LIKE 'SELECT.Lista.Statusy.do.decyzji%' THEN
		/********************************************************************************************************
			Nowa XII 2022 r. Wydajnosciowo jest OK!!!!
			Te przy ktorych musze zadecydowac
			1. bez decyzji i 
			2. te ktore moge cofnac
			CALL crm_workflow_SELECT('SELECT.Lista.Statusy.do.decyzji', @.SQL, NULL, user, IdnWorkFLow, '', '', '', '');		
			_ID			nie istotny
			_ID_2		@.cw.USERGUID = UserGUID
			_Param_A	@.cw.IDN
		********************************************************************************************************/
			-- CALL crm_workflow_SELECT('Select.User->nodes->crm', @SQL, '', @.cw.USERGUID, @.cw.IDN, '', '', '', '&Czyje=&StanDecyzji=');		
			CALL crm_workflow_SELECT('Select.User->nodes->crm', @SQL, '', _ID_2, _Param_A, '', '', '', '&Czyje=&StanDecyzji=');		
			SELECT
				d.*
			FROM
			(
				SELECT	
					cwc.Start_Status_last AS Current_Status,
					cwdl.Status_End AS Decision_Status,
					cwdl.Descr_Item AS Decision_Str,
					cwdl.LP,
					cwd.Is_Ending,
					-- (cwc.Undo_Status = 'YES') AS Undo_Enabled,
					cwc.Last_Poziom AS Poziom
					-- ,cwc.*
				FROM `t_nodes_2022` cwc
				LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cwc.Def AND cwdl.Status_Start = cwc.Start_Status_last
				INNER JOIN `crm_workflow_def` cwd ON cwd.Def = cwdl.Def AND cwd.Status = cwdl.Status_End AND cwd.Deleted = 0
				WHERE
					cwc.Decyzja_Status = 'USER_BRAK_DECYZJI'
				UNION
				SELECT	
					cwc.confirm_status_last AS Current_Status,
					cwc.Start_Status_last AS Decision_Status,
					CONCAT('Cofnij', ' do ... "', cwd.Descr_Status, '"') AS Decision_Str,
					100 AS LP,
					cwd.Is_Ending,
					-- (cwc.Undo_Status = 'YES') AS Undo_Enabled,
					cwc.Last_Poziom AS Poziom
					-- ,cwc.*
				FROM `t_nodes_2022` cwc
				LEFT JOIN `crm_workflow_def` cwd ON cwd.Def = cwc.Def AND cwd.Status = cwc.Start_Status_last
				WHERE
					(cwc.Undo_Status = 'YES')
			) d
			ORDER BY lp, Poziom
			;
		END IF;
	END IF;
END;
$$

DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
wył. na 
ochr internetu antyvirus
IPLA - darmo na 2m-ce potem 10,- / m-c ale można wyłączyc potem	
Czasoumilacz
Gdzie jest bliski

*/

/*
$Log: crm_workflow.sql,v $
Revision 1.11  2024/05/13 18:03:41  jmam
SQL zmiana V 2024 $SEND$

Revision 1.10  2024/04/27 09:13:24  jmam
Inicjacja WORK.FLOW.Ver = 2024.04 $SEND$

*/
