 DELIMITER $$

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

DROP PROCEDURE IF EXISTS `P_crm_workflow_n`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `P_crm_workflow_n`(
	IN _MODE VARCHAR(150),
	IN _GUID VARCHAR(255),	
	IN _cwIdn INTEGER,
	IN _IdnX INTEGER,		-- np cwcIdn
	IN _User VARCHAR(255),	
	IN _Param_A VARCHAR(255),
	IN _Param_B VARCHAR(255),
	IN _Param_C TEXT,	
	IN _Params TEXT	
)
L_EXIT: BEGIN 
	IF _MODE = 'NEW' THEN
			INSERT IGNORE INTO `crm_workflow_n`
			SET
				GUID = _GUID
			;
	END IF;
	IF _MODE = 'Insert.OR.UPDATE.from.@' THEN
	/*	Wstawia i uzupełnia rekord z danymi	
		CALL P_crm_workflow_n('INSERT.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);

	*/
		CALL P_crm_workflow_n('INSERT.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
			INSERT IGNORE INTO `crm_workflow_n`
			SET
				GUID = _GUID
			;
	END IF;
	IF _MODE = 'INSERT.from.@' THEN
	/*
		CALL P_crm_workflow_n('INSERT.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
	*/
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID),
			@.cwn.we.uOwner = IFNULL(NULLIF(_User, ''), @.cwn.we.uOwner)
		;
		
		INSERT IGNORE INTO `crm_workflow_n`
		(GUID, uOwner, Rodzaj, Podrodzaj, Def, Alg_Typ, cwStatus, D1, D2, dAbs, tAbs, DeadLine, Temat, Opis, ExtDescr, IsAbsencja, UpdateStatus)
		SELECT
			@.we.wGUID, 
			@.cwn.we.uOwner AS uOwner,	-- _User
			cr.Rodzaj, cr.Podrodzaj, cr.Def_confirm_statuses AS Def, cr.Alg_Typ,  
			'new' AS cwStatus, 
			@.cwn.we.D1 AS D1, @.cwn.we.D2 AS D2, 
			-- NULL AS dAbs,
			--	dAbs
			--	IF(cr.Alg_Typ = 'W.ABSENCJA',	
			IF((@.cwn.IsAbsencja := (IFNULL(ad.Idn, 0) > 0)),
				(
				SELECT
					SUM(kp.godziny > 0)	-- zliczamy dni z godz. pracy (pracujące)
				FROM `Pracownicy` p, `kalendpracy` k, `kalendpracy_po` kp
				WHERE
					p.GUID = @.cwn.we.uOwner
					AND k.Symbol = p.SymbolKalendarza
					AND k.rok = YEAR(@.cwn.we.D1)
					AND kp.GUIDNg = k.GUID
					AND kp.Data >= DATE(@.cwn.we.D1)
					AND kp.Data <= DATE(@.cwn.we.D2)
				),
				NULL
			) AS dAbs,
			@.cwn.we.tAbs,
			@.cwn.we.DeadLine, 
			-- @.cwn.we.Temat, @.cwn.we.Opis, 
			CONCAT('->', cr.Nazwa) AS Temat,
			CONCAT('->', cr.Opis) AS Opis,
			@.cwn.we.ExtDescr,
			-- IFNULL(ad.Idn, 0) > 0 AS IsAbsencja,	
			@.cwn.IsAbsencja AS IsAbsencja,
			'UPD.Temat.Opis' AS UpdateStatus
		FROM `crm_rodzaje` cr
		LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = cr.Rodzaj AND ad.Wniosek_podrodzaj = cr.Podrodzaj
		WHERE
			cr.Rodzaj = 16 
			AND cr.PodRodzaj = @.cwn.we.PodRodzaj
		;	
		CALL P_crm_workflow_n('USERS.Insert.from.cwdu', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);		
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'owner', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'creator', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'szef', NULL, _Param_C, '', _Params);
	END IF;
	
	IF _MODE = 'UPDATE.from.@' THEN
	/*
		CALL P_crm_workflow_n('UPDATE.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
	*/
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID),
			@.cwn.we.uOwner = IFNULL(NULLIF(_User, ''), @.cwn.we.uOwner)
		;
		UPDATE `crm_workflow_n` cwn
		SET
			cwn.uOwner = @.cwn.we.uOwner,
			cwn.D1 = @.cwn.we.D1,
			cwn.D2 = IFNULL(NULLIF(@.cwn.we.D2, '0000-00-00 00:00:00'), @.cwn.we.D1 + INTERVAL @.cwn.we.Duration HOUR),
			-- cwn.dAbs = @.cwn.we.dAbs,
			cwn.dAbs = 
				--	IF(cwn.Alg_Typ = 'W.ABSENCJA',
				IF(cwn.IsAbsencja,
					(
					SELECT
						SUM(kp.godziny > 0)	-- zliczamy dni z godz. pracy (pracujące)
					FROM `Pracownicy` p, `kalendpracy` k, `kalendpracy_po` kp
					WHERE
						p.GUID = @.cwn.we.uOwner
						AND k.Symbol = p.SymbolKalendarza
						AND k.rok = YEAR(@.cwn.we.D1)
						AND kp.GUIDNg = k.GUID
						AND kp.Data >= DATE(@.cwn.we.D1)
						AND kp.Data <= DATE(@.cwn.we.D2)
					),
					NULL
				),
			
			cwn.tAbs = @.cwn.we.tAbs,
	--	DODAĆ - dokleić !!! nie wiem jak> jescze @.cwn.we.ExtDescr - testowy komentarz
	--	może wyświetlając we VIEW? TAK zrobić!!!!!!!!!!!!!
			cwn.Temat = IFNULL(@.cwn.we.Temat, cwn.Temat),
			cwn.Opis = IFNULL(@.cwn.we.Opis, cwn.Opis),
			cwn.DeadLine = @.cwn.we.DeadLine,
			cwn.ExtDescr = @.cwn.we.ExtDescr,
			cwn.UpdateStatus = 'UPD.Temat.Opis'
		WHERE 
			GUID = @.we.wGUID
		;				
		CALL P_crm_workflow_n('USERS.Insert.from.cwdu', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);		
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'owner', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'owner', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'creator', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'szef', NULL, _Param_C, '', _Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, NULL, 'zastepca', NULL, @_Param_C, '', @_Params);
		-- CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', @.we.wGUID, @_cwIdn, @_IdnX, _User, 'DW', 'BBB', @_Param_C, '', @_Params);
	END IF;

	IF _MODE = 'UPDATE.from.ABS' THEN
	/*
        TODO
        Jeśli jest to absencja to nawet jeśli jeszcze nie ma absencji nalicz dAbs, tAbs etc
		CALL P_crm_workflow_n('UPDATE.from.ABS', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
	*/
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID),
			@.cwn.we.uOwner = IFNULL(NULLIF(_User, ''), @.cwn.we.uOwner)
		;
	END IF;

	IF _MODE LIKE 'USERS.%' THEN
		SET
			@.we.wGUID = NULLIF(_GUID, '')
		;
		IF _MODE = 'USERS.Insert.from.cwdu' THEN
		/*
			CALL P_crm_workflow_n('USERS.Insert.from.cwdu', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
		*/
			/*	Wstaw z cwdu 	*/
			INSERT IGNORE INTO `crm_workflow_confirm`
			(wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom)
			SELECT
				wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom
			FROM 
			(
				SELECT
					cwn.GUID AS wGUID, 
					0 AS IDN_workflow, 
					cwdu.uType AS UserGUID,
					@.uGUID := (
						IF(cwdu.uGUID = 'szef',
						--	szef
							(
							SELECT
								hl.OsobaGUID_B	--	szef
							FROM `hr_self_links` hl
							WHERE
								TRUE
								AND hl.OsobaGUID_A = cwn.uOwner
								AND hl.rel = 'szef'
							),
						IF(cwdu.uGUID = 'zastepca',
						--	zastepca
							(
							SELECT 
								hl.OsobaGUID_B
							FROM `hr_self_links` hl
							WHERE
								TRUE
								AND hl.OsobaGUID_A = cwn.uOwner
								AND hl.rel = '<-zastepca'
								AND hl.A_Rel_Unique = 1
							),
						cwdu.uGUID
						))
					) AS uGUID, 
					cwdu.uType,
					cwdu.Poziom
					-- ,cwn.*
				FROM crm_workflow_n cwn
				INNER JOIN `crm_workflow_def_users` cwdu ON cwdu.Podrodzaj = cwn.Podrodzaj AND cwdu.Deleted = 0
				WHERE
					TRUE
					AND cwn.GUID = @.we.wGUID
			) s
			/*
			ON DUPLICATE KEY UPDATE
				uGUID = s.uGUID,
				uType = s.uType,
				Poziom = s.Poziom
			*/
			;
		END IF;
		
		IF _MODE = 'USERS.Insert.Update' THEN
		/*
			CALL P_crm_workflow_n('USERS.Insert.Update', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
		*/
			SET
				-- juz u góry @.we.wGUID = NULLIF(_GUID, ''),
				@.cwu.we.uType := NULLIF(_Param_A, ''),
				@.cwu.we.Poziom := 
					IF(@.cwu.we.uType = 'creator', 
						0,
						IF(@.cwu.we.uType IN ('szef', 'zastepca'), 
							1,
							IF(@.cwu.we.uType = 'owner', 
								2,
								3
					))),
				-- @.cwu.we.UserGUID := NULLIF(_Param_B, '')
				@.cwu.we.UserGUID := NULLIF(_User, '')
			;
			IF @.we.wGUID IS NOT NULL AND @.cwu.we.uType IS NOT NULL THEN
				INSERT IGNORE INTO `crm_workflow_confirm`
				(wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom)
				SELECT
					wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom
				FROM 
				(
					SELECT
						cwn.GUID AS wGUID, 
						0 AS IDN_workflow,
						@.cwu.we.uType AS uType, 
						@.cwu.we.uType AS UserGUID,
						@.uGUID := (
							IF(@.cwu.we.uType = 'owner' OR @.cwu.we.UserGUID = 'owner', 
								cwn.uOwner,
							IF(@.cwu.we.uType = 'creator' OR @.cwu.we.UserGUID = 'creator', 
								cwn.uCreator,
							IF(@.cwu.we.UserGUID = 'szef' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'szef'),
							--	szef
								(
								SELECT
									hl.OsobaGUID_B	--	szef
								FROM `hr_self_links` hl
								WHERE
									TRUE
									AND hl.OsobaGUID_A = cwn.uOwner
									AND hl.rel = 'szef'
								),
							IF(@.cwu.we.UserGUID = 'zastepca' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'zastepca'),
							--	zastepca
								(
								SELECT 
									hl.OsobaGUID_B
								FROM `hr_self_links` hl
								WHERE
									TRUE
									AND hl.OsobaGUID_A = cwn.uOwner
									AND hl.rel = '<-zastepca'
									AND hl.A_Rel_Unique = 1
								),
								@.cwu.we.UserGUID
							))))
						) AS uGUID, 
						-- @.cwu.we.uTypeUserGUID AS uTypeUserGUID, 
						-- IF(@.cwu.we.uType = 'DW', @.UserGUID, '') AS uTypeUserGUID, 
						@.cwu.we.Poziom AS Poziom
					FROM `crm_workflow_n` cwn	-- , `crm_workflow` cw
					WHERE
						cwn.GUID = @.we.wGUID
						-- AND cw.wGUID = cwn.GUID
						-- AND cw.Prev_IDN_workflow IS NULL
					) s
				WHERE
					TRUE
					AND s.UserGUID IS NOT NULL
				ON DUPLICATE KEY UPDATE
					uGUID = s.uGUID,
					uType = s.uType,
					Poziom = s.Poziom
				;
			END IF;
		END IF;
	END IF;
	
					IF _MODE = 'INSERT.UPDATE.cwu.from.@' THEN
					/*
						CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
					*/
						SET
							@.we.wGUID = NULLIF(_GUID, ''),
							@.cwu.we.uType := NULLIF(_Param_A, ''),
							@.cwu.we.Poziom := 
								IF(@.cwu.we.uType = 'creator', 
									0,
									IF(@.cwu.we.uType IN ('szef', 'zastepca'), 
										1,
										IF(@.cwu.we.uType = 'owner', 
											2,
											3
								))),
							-- @.cwu.we.UserGUID := NULLIF(_Param_B, '')
							@.cwu.we.UserGUID := NULLIF(_User, '')
						;
						IF @.we.wGUID IS NOT NULL AND @.cwu.we.uType IS NOT NULL THEN
							INSERT IGNORE INTO `crm_workflow_confirm`
							(wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom)
							SELECT
								wGUID, IDN_workflow, UserGUID, uGUID, uType, Poziom
							FROM 
							(
								SELECT
									cwn.GUID AS wGUID, 
									0 AS IDN_workflow,
									@.cwu.we.uType AS uType, 
									@.cwu.we.uType AS UserGUID,
									@.uGUID := (
										IF(@.cwu.we.uType = 'owner' OR @.cwu.we.UserGUID = 'owner', 
											cwn.uOwner,
										IF(@.cwu.we.uType = 'creator' OR @.cwu.we.UserGUID = 'creator', 
											cwn.uCreator,
										IF(@.cwu.we.UserGUID = 'szef' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'szef'),
										--	szef
											(
											SELECT
												hl.OsobaGUID_B	--	szef
											FROM `hr_self_links` hl
											WHERE
												TRUE
												AND hl.OsobaGUID_A = cwn.uOwner
												AND hl.rel = 'szef'
											),
										IF(@.cwu.we.UserGUID = 'zastepca' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'zastepca'),
										--	zastepca
											(
											SELECT 
												hl.OsobaGUID_B
											FROM `hr_self_links` hl
											WHERE
												TRUE
												AND hl.OsobaGUID_A = cwn.uOwner
												AND hl.rel = '<-zastepca'
												AND hl.A_Rel_Unique = 1
											),
											@.cwu.we.UserGUID
										))))
									) AS uGUID, 
									-- @.cwu.we.uTypeUserGUID AS uTypeUserGUID, 
									-- IF(@.cwu.we.uType = 'DW', @.UserGUID, '') AS uTypeUserGUID, 
									@.cwu.we.Poziom AS Poziom
								FROM `crm_workflow_n` cwn	-- , `crm_workflow` cw
								WHERE
									cwn.GUID = @.we.wGUID
									-- AND cw.wGUID = cwn.GUID
									-- AND cw.Prev_IDN_workflow IS NULL
								) s
							WHERE
								TRUE
								AND s.UserGUID IS NOT NULL
							ON DUPLICATE KEY UPDATE
								uGUID = s.uGUID,
								uType = s.uType,
								Poziom = s.Poziom
							;
						END IF;
					END IF;
	
					IF _MODE = 'old.INSERT.UPDATE.cwu.from.@' THEN
					/*
						CALL P_crm_workflow_n('INSERT.UPDATE.cwu.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
					*/
						SET
							@.we.wGUID = NULLIF(_GUID, ''),
							@.cwu.we.uType := NULLIF(_Param_A, ''),
							@.cwu.we.Poziom := 
								IF(@.cwu.we.uType = 'creator', 
									0,
									IF(@.cwu.we.uType IN ('szef', 'zastepca'), 
										1,
										IF(@.cwu.we.uType = 'owner', 
											2,
											4
								))),
							-- @.cwu.we.UserGUID := NULLIF(_Param_B, '')
							@.cwu.we.UserGUID := NULLIF(_User, '')
						;
						IF @.we.wGUID IS NOT NULL AND @.cwu.we.uType IS NOT NULL THEN
							INSERT IGNORE INTO `crm_workflow_users`
							(wGUID, uType, UserGUID, uTypeUserGUID, Poziom)
							SELECT
								wGUID, uType, UserGUID, uTypeUserGUID, Poziom
							FROM 
							(
								SELECT
									cwn.GUID AS wGUID, 
									@.cwu.we.uType AS uType, 
									@.UserGUID := (
										IF(@.cwu.we.uType = 'owner' OR @.cwu.we.UserGUID = 'owner', 
											cwn.uOwner,
										IF(@.cwu.we.uType = 'creator' OR @.cwu.we.UserGUID = 'creator', 
											cwn.CreatorGUID,
										IF(@.cwu.we.UserGUID = 'szef' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'szef'),
										--	szef
											(
											SELECT
												hl.OsobaGUID_B	--	szef
											FROM `hr_self_links` hl
											WHERE
												TRUE
												AND hl.OsobaGUID_A = cwn.uOwner
												AND hl.rel = 'szef'
											),
										IF(@.cwu.we.UserGUID = 'zastepca' OR (@.cwu.we.UserGUID IS NULL AND @.cwu.we.uType = 'zastepca'),
										--	zastepca
											(
											SELECT 
												hl.OsobaGUID_B
											FROM `hr_self_links` hl
											WHERE
												TRUE
												AND hl.OsobaGUID_A = cwn.uOwner
												AND hl.rel = '<-zastepca'
												AND hl.A_Rel_Unique = 1
											),
											@.cwu.we.UserGUID
										))))
									) AS UserGUID, 
									-- @.cwu.we.uTypeUserGUID AS uTypeUserGUID, 
									IF(@.cwu.we.uType = 'DW', @.UserGUID, '') AS uTypeUserGUID, 
									@.cwu.we.Poziom AS Poziom
								FROM `crm_workflow_n` cwn	-- , `crm_workflow` cw
								WHERE
									cwn.GUID = @.we.wGUID
									-- AND cw.wGUID = cwn.GUID
									-- AND cw.Prev_IDN_workflow IS NULL
								) s
							WHERE
								TRUE
								AND s.UserGUID IS NOT NULL
							ON DUPLICATE KEY UPDATE
								UserGUID = s.UserGUID,
								uTypeUserGUID = s.uTypeUserGUID
							;
						END IF;
					END IF;
	
	IF _MODE = 'DELETE.from.@' THEN
	/*
		CALL P_crm_workflow_n('DELETE.from.@', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
	*/
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID)
		;
		DELETE cwn FROM `crm_workflow_n` cwn
		WHERE
			cwn.GUID = @.we.wGUID
		;
		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.02' THEN
			DELETE c FROM `crm_commisions` c
			WHERE
				c.GUID = @.we.wGUID
				AND 
				IF(_Params LIKE '%<crm.always>%',
					TRUE,
					c.deleted <> 0
				)
				-- AND c.Status < 2
			;
            DELETE a FROM absencje a 
            WHERE 
                a.GuidWniosku = @.we.wGUID 
                AND _Params LIKE '%<crm.always>%'
            ;
		END IF;
	END IF;
	
	IF _MODE LIKE 'cwn.%' THEN
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID)
		;
		IF _MODE = 'cwn.Update.wStatus' THEN
		/*
			Update po confirme / undo
			CALL P_crm_workflow_n('cwn.Update.wStatus', _GUID, '', '', '', '', '', '', '');
		*/
		--	Najpierw cwn ...
			UPDATE `crm_workflow_n` cwn,
				(
				SELECT 	
					-- cw.commisionGUID,
					cw.Idn,
					cw.Confirm_Status AS cwStatus,
					cwd.crm_Status AS crmStatus,
					IFNULL(cw.Is_Ending, 0) AS Is_Ending
				FROM `crm_workflow` cw, `crm_workflow_def` cwd
				WHERE 
					-- cw.wGUID = cwn.GUID
					cw.wGUID = @.we.wGUID
					AND cwd.Def = cw.Def 
					AND cwd.Status = cw.Confirm_Status
				ORDER BY cw.idn DESC 
				LIMIT 1
				) cwlast
			SET
				cwn.cwIdnLast = cwlast.Idn,
				cwn.cwStatus = cwlast.cwStatus,
				cwn.crmStatus = cwlast.crmStatus,
				cwn.IsEnding = cwlast.Is_Ending,
				cwn.IsCancel = cwlast.Is_Ending = 2
			WHERE
				cwn.GUID = @.we.wGUID
			;
		--	teraz crm
			UPDATE `crm_commisions` c, `crm_workflow_n` cwn
			SET
				c.Confirm_Status = cwn.cwStatus,
				c.status = cwn.crmStatus
			WHERE
				cwn.GUID = @.we.wGUID
				AND c.GUID = cwn.GUID
			;
		END IF;
	END IF;
	
	IF _MODE LIKE 'cw.%' THEN
		SET
			@.we.wGUID = IFNULL(NULLIF(_GUID, ''), @.we.wGUID),
			@.we.cwIdn = IFNULL(NULLIF(_cwIdn, ''), 0)
		;
		IF _MODE = 'cw.Update.node.and.crm' THEN
		/*
			Update po confirme / undo
			dawniej
				CALL crm_workflow_TOOLS('Confim.workflow.node.and.crm', '8', '', '', '', '', '');
			CALL P_crm_workflow_n('cw.Update.node.and.crm', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
		*/
			SET
				@.cwc.s.CC := 0,
				@.cwc.s.CDec := 0,
				@.cwc.s.Poziom := 999,
				-- @.cwc.s.Min := 999,
				@.cwc.s.Is_Ending := FALSE,
				@.cwc.s.Status := NULL
			;
			SELECT
				@.cwc.s.CC AS CC, 
					-- @.cwc.s.CDec as CDec, 
				@.cwc.s.CDec AS ResponseCount,
				IF(@.cwc.s.CC = 0,
					NULL,
					IF(@.cwc.s.CC = @.cwc.s.CDec,
						'RESPONSE_100',
						IF(@.cwc.s.CDec > 0,
							'RESPONSE_50',
							'RESPONSE_0'
						)
					)
				) AS Response, 
				@.cwc.s.Status AS confirm_status,
				@.cwc.s.Is_Ending
				-- po co ,@.cwc.s.Poziom as sPoziom
			INTO
				@.we.cw.CC,
				@.we.cw.ResponseCount,
				@.we.cw.Response,
				@.we.cw.confirm_status,
				@.we.cw.Is_Ending
				-- @.we.cw.Poziom	-- ale po co?
			FROM
			(
				SELECT
					cwc.IDN,
					(@.cwc.s.CC := @.cwc.s.CC + 1) AS sCC,
					(@.tIsLow := (cwd.Poziom < @.cwc.s.Poziom)) AS tIsLow,
						(@.cwc.s.Poziom := LEAST(cwd.Poziom, @.cwc.s.Poziom)) AS sPoziom, 
					(@.cwc.s.Status := IF(@.tIsLow, cwd.Status, @.cwc.s.Status)) AS AggStatus,
					(@.cwc.s.Is_Ending := IF(@.tIsLow, cwd.Is_Ending, @.cwc.s.Is_Ending)) AS Is_Ending,
					/*
					-- cwc.Start_Status,
					-- (@.confirm_status := IFNULL(NULLIF(cwc.confirm_status, ''), cwc.start_status)) AS confirm_status,
					-- (@.confirm_status := cwd.Status) AS confirm_status,
					-- (@.cwc.s.IsDec := (cwc.Start_Status <> @.confirm_status)) AS IsDec,
					*/
					(@.cwc.s.IsDec := (cwc.Start_Status <> cwd.Status)) AS IsDec,
					(@.cwc.s.cDec := @.cwc.s.cDec + @.cwc.s.IsDec) AS cDec,
					cwd.Poziom,
					cwc.IDN_workflow
					-- , cwc.
				FROM `crm_workflow_confirm` cwc
				INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = cwc.wGUID
				INNER JOIN `crm_workflow_def` cwd ON cwd.Status = IFNULL(NULLIF(cwc.confirm_status, ''), cwc.start_status) AND cwd.Def = cwn.Def
				WHERE
					cwc.IDN_workflow = @.we.cwIdn
			) s
			LIMIT 1
			;
		--	Teraz Update cw	
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'Teraz Update cw');
			UPDATE `crm_workflow` cw
			SET
				cw.ResponseCount = @.we.cw.ResponseCount,
				cw.confirm_status = @.we.cw.confirm_status,
				cw.Is_Ending = @.we.cw.Is_Ending,
				cw.Response = @.we.cw.Response,
				cw.WasDecision = cw.WasDecision OR (@.we.cw.ResponseCount > 0)
				--	 w triggerze , cw.UndoEnabled = (cw.ResponseCount > 0)
			WHERE
				cw.Idn = @.we.cwIdn
				AND @.we.cw.CC >= 0
			;
			SET @.cw.RC = ROW_COUNT();
			-- SET @.wf.inf.crm_workflow.RC = ROW_COUNT();

			IF @.cw.RC > 0 THEN
			--	Usun nastepnik o ile w ogole istnieje bo crm updatuje się wg ostatniego!!!
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'DELETE d FROM');
				DELETE d FROM `crm_workflow` d, `crm_workflow` cw 
				WHERE 
					cw.Idn = @.we.cwIdn
					AND cw.Is_Ending = 0
					AND d.Prev_IDN_workflow = cw.Idn
				;
			--	Wstaw nastepnik o ile w ogole to ma sens
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'INTO `crm_workflow`');
				INSERT IGNORE INTO `crm_workflow` 
				(Prev_IDN_workflow, wGUID, commisionGUID, Def, Start_Status, Confirm_Status)
				SELECT 
					cw.Idn AS Prev_IDN_workflow, cw.wGUID, cw.commisionGUID, cwn.Def, cw.Confirm_Status AS Start_Status, cw.Confirm_Status 
				FROM `crm_workflow` cw
				INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = cw.wGUID
				WHERE
					cw.Idn = @.we.cwIdn
					AND (cw.Response = 'RESPONSE_100')	--	tylko dla noda mającego juz pełną decyzję
					AND cw.Is_Ending = 0	--	nie zakładamy nastepnego dla końcowego noda
				;
			--	I jeszcze - nowe na razie (25 I 2024) nie wykorzystywane - Undo poprzednika!!! o ile istnieje
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'UPDATE `crm_workflow`');
				UPDATE `crm_workflow` cw_p, `crm_workflow` cw 
				SET
					cw_p.NextBlocksMe = (cw.ResponseCount > 0)
				WHERE 
					cw.Idn = @.we.cwIdn
					AND cw_p.Idn = cw.Prev_IDN_workflow
				;
			--	teraz update cwn i crm	
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '..1');
				CALL P_crm_workflow_n('cwn.Update.wStatus', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
			--	Na koniec ExtNotify
				IF 
					-- (@.wf.inf.Has_Decision OR @.wf.inf.UNDO) 
					--	po co ??? AND @session.globals.WORK.FLOW.Ver >= '2022'
					--	AND
						@.we.cwc.IsTechn = 0
				THEN
							set @.wf.inf.watch = concat_WS(' / ', concat_WS(',', _GUID, _cwIdn, _IdnX, @.we.cwc.cwStatus, @.we.cwc.uDecision, @.wf.inf.ProcExtNotify));				
				--	w @.wf.inf.ExtNotify mam inf. co mam po tej decyzji wykonać
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '..2.1');
					CALL P_crm_workflow_n('cw.ExtNotify.AFTER.confirm.Response', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, @.wf.inf.ProcExtNotify, _Params);
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '..2.1.end');
					SET @.we.cwc.IsTechn = 0;	--	muszę bo gdzieś się o to pytamy

				END IF;
				
				/*
				DELETE FROM `crm_workflow` WHERE Prev_IDN_workflow = _cwIdn;
			--	Update crm	dla wersji ...
					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 = 'cw.Insert.New' THEN
		/*
			Wstawianie noda cw przy nowym crm
			CALL P_crm_workflow_n('cw.Insert.New', _GUID,  NULL, NULL, NULL, 'new', '', '', @_Params);
			dawniej
				CALL crm_workflow_TOOLS('Insert.New', 'GUID', 'new', '', '', '', '');
			_ID 	GUID zdarzenia
			_ID_2 	Status
		*/
			SET
				@.we.wGUID = NULLIF(_GUID, ''),
				@.we.cw.cwStatus := _Param_A,	--	wej. confirm_status
				@.cwLog.IDN = NULL
			;
			INSERT IGNORE INTO `crm_workflow` 
			(commisionGUID, Def, Start_Status, Confirm_Status)
			SELECT 
				cwn.GUID, cwn.Def, @.we.cw.cwStatus, ''
			FROM `crm_workflow_n` cwn
			WHERE
				cwn.GUID = @.we.wGUID
			;
		--	Dla dalszych selectów musze ust. stara zmienną ...	
			SET @.crm_workflow.Last.IDN := LAST_INSERT_ID();
			CALL P_crm_workflow_n('cwn.Update.wStatus', @.we.wGUID, '', '', '', '', '', '', '');
			--	IF _Params LIKE '%<select>%' THEN
		END IF;
		
		IF _MODE = 'cw.confirm.Response' THEN
		/*
			Podejmij decyzje
			dawniej
				CALL crm_workflow_TOOLS('confirm.Response', 8, @UserGUID, 'decyzjastatus', '', '', 'koment');
			Update po confirme / undo
			CALL P_crm_workflow_n('cw.confirm.Response', _GUID, _cwIdn, _IdnX, @UserGUID, 'decyzjastatus', ''/'TECHN', 'koment', _Params);
				_Param_A	--	wej. confirm_status
			UWAGA!!! NIE MAMY TU GUID-A!!! Mamy tylko IDN cw
		*/
			SET
				@.we.cwc.uDecision = NULLIF(_User, ''),	--	user decydujący
				@.we.cwc.cwStatus := _Param_A,	--	wej. confirm_status
				@.we.cwc.IsUndo := (_Param_A = 'UNDO'),
				@.we.cwc.IsTechn = (_Param_B = 'TECHN'),
				@.we.cwc.Comment = NULLIF(_Param_C, ''),
				@.we.cwc.IsDisabled = TRUE,
				
				@.cw.NextBlocksMe = 0,	--	wazne
				@.cwLog.IDN = NULL
			;
                                                    SET @resp.watch = NULL;				
                                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, CONCAT_WS(',', @resp.ProcExtNotify));				
		--	Pobierz do @.we.cwc.IsDisabled inf. o zabronionej operacji confirm - gdy sa nastepniki
			SELECT
				cw.wGUID,	--	UWAGA!!! NIE MAMY TU GUID-A!!! Mamy tylko IDN cw stąd musimy go sobie wziąc
				((IFNULL(cwn.ResponseCount, 0) > 0) OR cwnn.Confirm_Status IS NOT NULL) AS IS_Disabled
			INTO 
				@.we.wGUID, @.we.confim.IS_Disabled
			FROM `crm_workflow` cw
			LEFT JOIN `crm_workflow` cwn ON cwn.Prev_IDN_workflow = cw.IDN 
			LEFT JOIN `crm_workflow` cwnn ON cwnn.Prev_IDN_workflow = cwn.IDN 
			WHERE
				cw.IDN = @.we.cwIdn
			;
			UPDATE `crm_workflow` cw 
			LEFT JOIN `crm_workflow` cw_n ON cw_n.Prev_IDN_workflow = cw.IDN 
			SET 
				cw.wGUID = cw.commisionGUID,
				cw.NextBlocksMe = (@.cw.NextBlocksMe := IFNULL(cw_n.ResponseCount > 0, 0))
			WHERE
				cw.IDN = @.we.cwIdn
			;
			-- IF NOT @.we.confim.IS_Disabled THEN	
			IF @.cw.NextBlocksMe = 0 THEN
		--	OK nie ma przeciwskazan ...	
			--	UWAGA!!! NIE MAMY TU GUID-A!!! Mamy tylko IDN cw stąd musimy go sobie wziąc	
				SET _GUID = @.we.wGUID;
			--	przygotuj log...
			--	ustaw confirm
                                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '@.cw.NextBlocksMe = 0');				
				UPDATE `crm_workflow_confirm` cwc
				SET
					cwc.Confirm_Status = IF(@.we.cwc.IsUndo, '', @.we.cwc.cwStatus),
					cwc.Decision_UserGUID = 
						IF(@.we.cwc.IsUndo, 
							'', 
							IF(@.we.cwc.IsTechn,
								cwc.UserGUID,
								@.we.cwc.uDecision
							)
						),
					cwc.Comment = IFNULL(@.we.cwc.Comment, cwc.Comment)
				WHERE
					cwc.IDN_workflow = @.we.cwIdn
					AND
					-- cwc.UserGUID = @.we.cwc.uDecision
					(
						@.we.cwc.IsTechn
						OR
						IF(@.we.cwc.IsUndo,
						--	dla Undo user musi być osobą która podjęła wczesniej decyzję
							cwc.Decision_UserGUID = @.we.cwc.uDecision,
						--	dla statusów pozwól osobie z grupy
							@.we.cwc.uDecision IN 
								(SELECT go.OsobaGUID FROM `grupy_osob` go WHERE go.grupaGUID = cwc.UserGUID AND go.Deleted = 0)
						)
					)
				;
				SET @.cwc.RC = ROW_COUNT();
                                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'OK!!!');				
				IF @.cwc.RC > 0 THEN
                                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'cw.Update.node.and.crm');				
					CALL P_crm_workflow_n('cw.Update.node.and.crm', _GUID, _cwIdn, _IdnX, _User, _Param_A, _Param_B, _Param_C, _Params);
                                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'OK');				
				END IF;
			END IF;
			SET @.cwLog.IDN = NULL;
		END IF;
		
		IF _MODE LIKE 'cw.ExtNotify.%' THEN
		/************************************************************************************************************************************************
			Te przy ktorych musze zadecydoweac
			CALL crm_workflow_TOOLS('ExtNotify.....', 
		************************************************************************************************************************************************/
			CALL P_crm_workflow_n('cw.Get.Info', '', _cwIdn, NULL, '', '', '', '', @_Params);
	set @.wf.inf.watch = concat_WS(' / ', concat_WS(',', _MODE));				
			IF _MODE = 'cw.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', '', '');
					_cwIdn			IDN_workflow
					_User		Decision_UserGUID
					_Param_A	confirm_status				 
					_Param_B	Owner_GUID
					_Param_C	ExtNotify			
			----------------------------------------------------------------------------------------------------------------------------------------------*/
				SET @.EN.ExtNotify = IFNULL(NULLIF(_Param_C, ''), @.wf.inf.ProcExtNotify);
												set @.wf.inf.watch = concat_WS(' / ', concat_WS(',', _GUID, _cwIdn, _Param_A, _Param_B, _Param_C));				
				IF @.EN.ExtNotify LIKE '<-zastepca.%' THEN
				/*----------------------------------------------------------------------------------------------------------------------------------------------
					Zastępstwa!!!
						_User		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, _User, _Param_B, '', '', '', '', '');
					ELSEIF @.EN.ExtNotify LIKE '<-zastepca.B->A.REJECT' THEN
					--	Odrzucony
						CALL _user_accounts_sys_cfg('Profil.GUI.Zastepstwa.Status<-REJECT', 0, _User, _Param_B, '', '', '', '', '');
					END IF;
				END IF;
				
				-- IF @.EN.ExtNotify LIKE '<%ABSENCJA>' THEN
				
				IF @.wf.inf.confirm_status_Is_Ending OR @.wf.inf.confirm_status_Is_Cancel THEN
				/*----------------------------------------------------------------------------------------------------------------------------------------------
					Zakonczone lub anulowane
				----------------------------------------------------------------------------------------------------------------------------------------------*/
					IF @.wf.inf.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 = @.wf.inf.wGUID
						;
					END IF;
				END IF;

                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '@.wf.inf.IsAbsencja');
				
				IF @.wf.inf.IsAbsencja THEN
				/*----------------------------------------------------------------------------------------------------------------------------------------------
					ABSENCJA!!!
				----------------------------------------------------------------------------------------------------------------------------------------------*/
					CALL absencje_tools('crm.Wniosek.Update.ABS', @.wf.inf.wGUID, '', '', '', '');
				END IF;
				
				-- IF @.wf.inf.confirm_status_Param1 = '<AUTONUM>' THEN
				IF @.EN.ExtNotify LIKE '%<AUTONUM>%' THEN
				--	Naliczanie numeracji dla crm-a
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '<AUTONUM>');
					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
					INTO
						@.wf.inf.autonum.c.NrWewn,
						@.wf.inf.autonum.c.Data,
						@.wf.inf.autonum.ObjType,
						@.wf.inf.autonum.Rodzaj, @.wf.inf.autonum.Podrodzaj, @.wf.inf.autonum.Res
					FROM `v_crm_workflow_coms2` c
					WHERE 
						c.GUID = @.wf.inf.wGUID
					;
					
					IF @.wf.inf.autonum.c.NrWewn = '' THEN
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '<AUTONUM>.1');
						CALL erp_obj_counters_GetNumber_and_build_number_text('', 
							@_Numer, @_NumerText, @.wf.inf.autonum.ObjType, @.wf.inf.autonum.Rodzaj, @.wf.inf.autonum.Podrodzaj, 
							0, 0, @.wf.inf.autonum.Res, 
							-- YEAR(CURRENT_DATE()), MONTH(CURRENT_DATE()), 
							YEAR(@.wf.inf.autonum.c.Data), MONTH(@.wf.inf.autonum.c.Data), 
							1, '', '', '', '', ''
						);		
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, '<AUTONUM>.2');
						UPDATE `crm_commisions` c
						SET
							c.NrWewn = @_NumerText
						WHERE 
							c.GUID = @.wf.inf.wGUID
							AND
							IFNULL(c.NrWewn, '') = ''
							AND
							IFNULL(@_NumerText, '') <> ''
						;
						IF @.wf.inf.Wniosek_Typ LIKE '%SZKOLENIE%' OR @.wf.inf.Wniosek_Typ LIKE '%DELEGACJA%' THEN
							UPDATE `delegacje` d
							SET
								d.NrDelegacji = @_NumerText
							WHERE 
								d.GUID = @.wf.inf.wGUID
								AND
								IFNULL(d.NrDelegacji, '') = ''
								AND
								IFNULL(@_NumerText, '') <> ''
							;
							IF @session.globals.Owner = 'SKOK' THEN
								SET @.Xyz = '';
							END IF;
						END IF;
					END IF;
				END IF;
                                    SET @resp.watch = CONCAT_WS(' / ', @resp.watch, 'oki');
			END IF;
		END IF;
		
		IF _MODE = 'cw.Get.Info' THEN
		/************************************************************************************************************************************************
			Pobieranie informacji
			CALL P_crm_workflow_n('cw.Get.Info', _GUID, _cwIdn, _IdnX, @UserGUID, 'decyzjastatus', ''/'TECHN', 'koment', _Params);
			dawniej
				CALL crm_workflow_TOOLS('cw.Get.Info', '8', '', '', '', '', '');
			_cwIdn IDN p.decyz.
		************************************************************************************************************************************************/
			SELECT
				-- cw.*, 
				cw.commisionGUID,
				cw.IDN,
				cw.Confirm_Status AS Confirm_Status,
				(cw.Response = 'RESPONSE_100') AS Has_Decision,
				((IFNULL(cw_n.ResponseCount, 0) > 0) OR cw_nn.Confirm_Status IS NOT NULL) AS IS_Disabled,
				--	cw_n.IDN AS Next_IDN,
				--	cw_n.Confirm_Status AS Next_Confirm_Status,
				--	(cw_n.Response = 'RESPONSE_100') AS Next_Has_Decision,
				--	(cw_nn.Confirm_Status IS NOT NULL OR IFNULL(cw_nn.ResponseCount, 0) > 0) AS Next_IS_Disabled,

				--	cw_nn.IDN AS Next_2_IDN,
				--	cw_nn.Confirm_Status AS Next_2_Confirm_Status,
				--	(cw_nn.Response = 'RESPONSE_100') AS Next_2_Has_Decision,
					--	IFNULL(wd.Is_Ending, 0) AS Is_Ending,
				cwn.IsEnding,
				cwn.IsCancel,
-- 					cw.ExtNotify,
				cwdl.ExtNotify,
				--	dawniej c.Owner_GUID,
				cwn.uOwner, cwn.uCreator,
			--	doatk. zmienne
					--	wd.Is_Ending AS confirm_status_Is_Ending,
				cwn.IsEnding AS confirm_status_Is_Ending,
					--	wd.Is_Ending = 2 AS confirm_status_Is_Cancel,
				cwn.IsCancel AS confirm_status_Is_Cancel,
					--	wd.param1 AS confirm_status_Param1,
			--	z crm-a	
				cwn.IsAbsencja,
					--	c.Absencja_Rodzaj,
				-- c.Wniosek_Typ,
				cwn.Alg_Typ AS Wniosek_Typ
					-- c.okres_typ
			INTO
				@.wf.inf.wGUID,
				@.wf.inf.IDN,
				@.wf.inf.Confirm_Status,
				@.wf.inf.Has_Decision,
				@.wf.inf.IS_Disabled,

				--	@.wf.inf.Next_IDN,
				--	@.wf.inf.Next_Confirm_Status,
				--	@.wf.inf.Next_Has_Decision,
				--	@.wf.inf.Next_IS_Disabled,

				--	@.wf.inf.Next_2_IDN,
				--	@.wf.inf.Next_2_Confirm_Status,
				--	@.wf.inf.Next_2_Has_Decision,
				@.wf.inf.IsEnding,
				@.wf.inf.IsCancel,
				@.wf.inf.ExtNotify,
				--	dawniej @.wf.inf.Owner_GUID,
				@.wf.inf.uOwner,
				@.wf.inf.uCreator,
			--	doatk. zmienne
				@.wf.inf.confirm_status_Is_Ending,
				@.wf.inf.confirm_status_Is_Cancel,
			--	@.wf.inf.confirm_status_Param1,
			--	z crm-a	
				--	było @.wf.inf.IS_Absencja,
				@.wf.inf.IsAbsencja,
			--	@.wf.inf.Absencja_Rodzaj,
				@.wf.inf.Wniosek_Typ
				-- @.wf.inf.okres_typ
			FROM `crm_workflow` cw
			INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = cw.wGUID
			-- 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` cw_n ON cw_n.Prev_IDN_workflow = cw.IDN 
			LEFT JOIN `crm_workflow` cw_nn ON cw_nn.Prev_IDN_workflow = cw_n.IDN 
-- 		LEFT JOIN `absencje_dict` ad ON ad.Wniosek_rodzaj = c.Rodzaj AND ad.Wniosek_podrodzaj = c.Podrodzaj
			WHERE
				cw.idn = @.we.cwIdn
			;
			SET
				@.wf.inf.ProcExtNotify = IF(@.wf.inf.Has_Decision AND IFNULL(@.wf.inf.ExtNotify, '') <> '', @.wf.inf.ExtNotify, '')
			;
		END IF;
		
		
	END IF;
	
	IF _MODE LIKE 'log.%' THEN
		IF _MODE LIKE 'log.Create%' THEN
			SET
				@.we.LogIdn = _IdnX,
				@.we.wGUID = NULLIF(_GUID, '')
			;
			DROP TEMPORARY TABLE IF EXISTS `t_log_we`;
			SET @.F := 0;
			CREATE TEMPORARY TABLE `t_log_we`
			SELECT
				IF((@.F := @.F + 1) = 1, TRUE, FALSE) AS fFirst, 
				FALSE AS fLast, 
				FALSE AS fLastBrakDec,
				-- @.F := 0 as x,
				wlp.Idn, wlp.LogIdn, wln.LogAt, wln.wGUID, 
				DATE_FORMAT(wln.LogAt, '%a %e %b %H:%i') AS tAt,
				-- wln.*,
				wlp.Comment,
				IF(wlp.OP = 'cw.CHANGE', NULL, IF(wlp.uWe = cwn.uOwner, 'JA', 'KTOS')) AS Kto,
				wlp.OP,
				-- cwd1.*,
				cwdu.uAs AS uAsDec, 
				cwdu.uAsDw AS uAsDwDec,
				wlp.cwStatus1, wlp.cwStatus2,
				(@.IsKtos := (wlp.uType != 'uOwner')) AS IsKtos,
				NOT(@.IsKtos) AS IsOwner,
				(@.OpTxt :=
				IF(wlp.OP = 'cwc.DONE', 
					cwd2.OpTxtDone,	--	cwd2.TxtOnDone, 
					IF(wlp.OP = 'cwc.UNDO', 
						cwd1.OpTxtUndone, --	cwd1.TxtOnUndone, 
						IF(wlp.OP = 'cwc.NEW', 
							cwd2.OpTxtDone,	--	cwd2.TxtOnDone, 
							IF(wlp.OP = 'cwc.FIRST',
								cwmN.Txt,
								NULL
							)
						)
					)
				)) AS OpTxt,
				cwd2.Descr_status AS StatusCurrTxt,
				cwd1.Descr_status AS StatusTxt1,
				cwd2.Descr_status AS StatusTxt2,
				cwd2.msgExt,
				-- cwd1.TxtOnDone AS TxtOnDone,
				-- cwd1.TxtOnUndone AS TxtOnUndone,
				cwdl.Descr_Item_Past AS cwStatusTxt,
				IFNULL(NULLIF(cwd2.msgDWFlags, ''), cwd2.Param2) AS DWFlags, 	-- msgDWFlags
				cwn.uOwner,
				wlp.uWe,
				wlp.uDec,
				(@.nOwner := CONCAT_WS(' ' , oOwner.Imie1, oOwner.Nazwisko)) AS nOwner,
				(@.nCreator := CONCAT_WS(' ' , oCreator.Imie1, oCreator.Nazwisko)) AS nCreator,
				(@.nWe := CONCAT_WS(' ' , IF(oWe.Rodzaj = 0, 'grupa', oWe.Imie1), oWe.Nazwisko)) AS nWe,
				(@.nDec := CONCAT_WS(' ' , oDec.Imie1, oDec.Nazwisko)) AS nDec,
				oAbsZast.GUID AS uAbsZast,
				(@.nAbsZast := CONCAT_WS(' ' , oAbsZast.Imie1, oAbsZast.Nazwisko)) AS nAbsZast,
				wlp.cwIdn, wlp.cwcIdn,
				cwn.Podrodzaj, wlp.uType

				-- ,wlp.*
			FROM `crm_workflow_log_n` wln
			INNER JOIN `crm_workflow_log_p` wlp ON wlp.LogIdn = wln.Idn
			INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = wln.wGUID
			LEFT JOIN `v_cwd` cwd1 ON cwd1.Def = cwn.Def AND cwd1.Status = wlp.cwStatus1
			LEFT JOIN `v_cwd` cwd2 ON cwd2.Def = cwn.Def AND cwd2.Status = wlp.cwStatus2
			LEFT JOIN `crm_workflow_def_links` cwdl ON cwdl.Def = cwn.Def AND cwdl.Status_Start = wlp.cwStatus1 AND cwdl.Status_End = wlp.cwStatus2
			-- LEFT JOIN `crm_workflow_def_users` cwdu ON cwdu.Def IN (cwn.Def, '') AND cwdu.uType = wlp.uType
			LEFT JOIN `v_cwdu` cwdu ON cwdu.Podrodzaj = cwn.Podrodzaj AND cwdu.uType = wlp.uType -- IN (cwn.Def, '') AND cwdu.uType = cwdr.uType
			LEFT JOIN `osoby` oOwner ON oOwner.GUID = cwn.uOwner
			LEFT JOIN `osoby` oCreator ON oCreator.GUID = cwn.uCreator
			LEFT JOIN `osoby` oDec ON oDec.GUID = wlp.uDec
			LEFT JOIN `osoby` oWe ON oWe.GUID = wlp.uWe
			LEFT JOIN `crm_workflow_msgs` cwmN ON cwmN.ID = 'NOWY' AND TRUE
			LEFT JOIN  `crm_workflow_confirm` cwcAbsZast ON cwcAbsZast.wGUID = cwn.GUID AND cwcAbsZast.Idn_workflow = 0 AND cwcAbsZast.uType = 'uAbsZast'
			LEFT JOIN `osoby` oAbsZast ON oAbsZast.GUID = cwcAbsZast.uGUID
			WHERE 
				TRUE
				AND wln.wGUID = @.we.wGUID
				-- AND @.we.LogIdn IN (0, wln.Idn)
				
				-- and wlp.OP IN ('cwc.DONE', 'cwc.UNDO')
			ORDER BY wln.IDN, wlp.Idn
			;
			SET @.twe.last.Idn = IFNULL((SELECT MAX(twe.Idn) FROM `t_log_we` twe), 0);
			--	SELECT @.twe.last.Idn;
			UPDATE `t_log_we` twe SET twe.fLastBrakDec = FALSE;
			UPDATE `t_log_we` twe 
			SET
				twe.fLastBrakDec = twe.OP IN ('cwc.NEW')
			WHERE
				twe.Idn = @.twe.last.Idn
			;
			SET @.twe.last.Idn = IFNULL((SELECT MAX(twe.Idn) FROM `t_log_we` twe WHERE (twe.OP IN ('cwc.FIRST', 'cwc.DONE', 'cwc.UNDO')) OR twe.fLastBrakDec), 0);
			UPDATE `t_log_we` twe 
			SET
                fLast := TRUE
			WHERE
				twe.Idn = @.twe.last.Idn
			;
			/*
			SET @.fLastBrakDec = FALSE;		
			UPDATE `t_log_we` twe SET twe.fLastBrakDec = FALSE;
			UPDATE `t_log_we` twe 
			SET
				twe.fLastBrakDec = 
					IF(@.fLastBrakDec,
						twe.fLastBrakDec,
						(@.fLastBrakDec := (NOT @.fLastBrakDec AND twe.OP IN ('cwc.NEW')))
					)
			ORDER BY idn DESC
			;
					-- SELECT * FROM `t_log_we` twe;
			*/
		END IF;

		IF _MODE LIKE 'log.Prepare.HIST.Tabela.from.t_log_we%' THEN
		--	Historia do html
			SET @Html.HIST.Tabela.New = IFNULL(
				(
				SELECT 
					CONCAT(
					'<br><br><hr><br><center><b> HISTORIA WNIOSKU </b><br><table style="border:1px solid black;border-collapse: collapse;"> <tr> <th style="background-color:gray;color:white;padding:5px;border:1px solid black ;">Data</th><th style="background-color:gray;color:white;padding:5px;border:1px solid black;">Osoba</th><th style="background-color:gray;color:white;padding:5px;border:1px solid black;">Status</th></tr>',
					GROUP_CONCAT(DISTINCT 
						CONCAT(
							_VarStr('<tr><td style="padding:5px;border:1px solid black;">'),
							IF(NOT twe.fLastBrakDec,
								sLogAt,
								_VarStr('Następny krok...')
							),
							_VarStr('</td><td style="padding:5px;border:1px solid black;">'),
							IF(NOT twe.fLastBrakDec,
								twe.nDec,
								twe.nWe
							),
							_VarStr('</td><td style="padding:5px;border:1px solid black;">'),
							LogInf,	--	_VarStr(t.Status_Current),
							_VarStr('</td></tr>')
						)
						ORDER BY twe.Idn SEPARATOR ''
					),
					'</table></center>'
					)
					 AS tabela
				FROM 
				(
				SELECT 
					twe.Idn,
					twe.LogAt,
					_Fmt_DateTime(twe.LogAt, 'ddd d mmm yyyy hh:nn @Y') AS sLogAt,
					twe.uDec AS Users_Nazwiska_Log,
					twe.nWe,
					CONCAT_WS('',
						-- twe.tAt, ' ',
						REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
								-- IF(NOT twe.IsKtos, @workflow.mail.MSG.Ja.Ja, @workflow.mail.MSG.Ktos), 
							IF(NOT twe.fLastBrakDec,
								CONCAT_WS(' ',
									twe.OpTxt,	
									NULLIF(twe.msgExt, '')
								),
								CONCAT('brak decyzji - (', NULLIF(twe.StatusCurrTxt, ''), ')')
							),
							'#CHANGE#', twe.OpTxt),
							'#STATUS_BEFORE#', twe.StatusCurrTxt),
							'#msgExt#', IFNULL(twe.msgExt, '')),
							'#uAs#', twe.uAsDec),
							'#uAsDw#', twe.uAsDec),
							'#owner#', twe.nOwner),
							'#creator#', twe.nCreator),
							'#dec#', twe.nDec),
							'#AbsZast#', twe.nAbsZast),
							'#WNIOSEK#', cwn.Opis),
							'#TIME#', tAt),
							'#STATUS_?#', ''),
							'#(nGrupa)#', ''),
							CONCAT(' z adnotacją: "', NULLIF(twe.Comment, ''), '"')
					) AS LogInf,
					StatusTxt1 AS Status_Before,
					StatusTxt2 AS Status_Current,
					
					'????' AS Confirm_log,
					-- cwIDN AS Idn,
					cw.Prev_Idn_workflow,
					cwn.GUID AS commisionGUID,
					cwn.Def,
					cw.Start_Status,
					cw.Confirm_Status,
					555 AS `X`,
					333 AS `Y`,
					
					twe.uDec,
					twe.nDec,
					tAt,
					twe.OpTxt,
					twe.fLastBrakDec
					--	,twe.*
				FROM `t_log_we` twe
				INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
				LEFT JOIN `crm_workflow` cw ON cw.IDN = cwIdn
				WHERE
					(twe.OP IN ('cwc.FIRST', 'cwc.DONE', 'cwc.UNDO'))
					OR
					twe.fLastBrakDec
				ORDER BY twe.Idn
				) twe
				ORDER BY Idn
				), ''
			)
			;
		END IF;
			
		IF _MODE = 'log.Prepare.HIST.html' THEN
        --  UWAGA @.we.LogIdn CHYBA NIEPOTRZEBNY!!!!!!!!!!!!!!!!!!!!!!!!
		--	do `t_log_we` wpisz log wf
			CALL P_crm_workflow_n('log.Create', @.we.wGUID, null, @.we.LogIdn, '', '', '', '', _Params);
        --	Historia do html z `t_log_we`
            CALL P_crm_workflow_n('log.Prepare.HIST.Tabela.from.t_log_we', null, null, null, '', '', '', '', _Params);
            IF _Params LIKE '%<select>%' THEN
                SELECT @Html.HIST.Tabela.New AS Hist_HTML;
            END IF;
		END IF;

		IF _MODE LIKE 'log.Prepare.Mail.by.LogIdn%' THEN
		/*
			Przygoduj maile z loga
			CALL P_crm_workflow_n('log.Prepare.Mail.by.LogIdn', _GUID, null, LogIdn, @UserGUID, '', '', '', _Params);
				_Param_A	--	wej. confirm_status
			UWAGA!!! NIE MAMY TU GUID-A!!! Mamy tylko IDN cw
		*/
			SET
				@.we.LogIdn = IFNULL(_IdnX, 0),
				@.we.wGUID = NULLIF(_GUID, '')
			;
			IF @.we.LogIdn = 0 THEN
				SET @.we.LogIdn = (SELECT MAX(IDN) FROM `crm_workflow_log_n` wln WHERE wln.wGUID = @.we.wGUID);
			END IF;
		--	do `t_log_we` wpisz log wf
			CALL P_crm_workflow_n('log.Create', @.we.wGUID, null, @.we.LogIdn, '', '', '', '', _Params);
		--	Historia do html z `t_log_we`
			CALL P_crm_workflow_n('log.Prepare.HIST.Tabela.from.t_log_we', null, null, null, '', '', '', '', _Params);
		--	Adresaci ...	
			DROP TEMPORARY TABLE IF EXISTS `twflog_recip`;
			CREATE TEMPORARY TABLE `twflog_recip` (
			  `msgTyp` VARCHAR(20) NOT NULL DEFAULT 'DEC' COMMENT 'DEC/DW ...',
			  `uRecip` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'user/grupa decyzyjna',
			  `nRecip` VARCHAR(61) DEFAULT NULL,
			  `uAs` VARCHAR(200) DEFAULT NULL,
			  `uType` VARCHAR(50) NOT NULL DEFAULT '' COMMENT 'typ rekordu decyzji "" normalny ale <> "" to specjalny user links typu cul',
			  `IsOwner` INTEGER DEFAULT 0,
			  `IsCreator` INTEGER DEFAULT 0,
			  `IsDec` INTEGER DEFAULT 0,	--	PO CO?????
			  `Adres` VARCHAR(250) DEFAULT NULL,
			  `isGrupa` INTEGER DEFAULT 0,
			  `Deleted` INTEGER DEFAULT 1,
			  PRIMARY KEY (`msgTyp`, `uRecip`)
			)
			;
				TRUNCATE `twflog_recip`;
		/*	Do decyzji recipientami sa tylko uWe !!!	*/
			INSERT IGNORE INTO `twflog_recip`
			(msgTyp, uRecip, nRecip, uAs, uType, IsOwner, IsCreator, isGrupa)
				SELECT
					DISTINCT
					'DEC' AS msgTyp,
					twe.uWe AS uRecip,
					twe.nWe AS nRecip,
					twe.uAsDec AS uAs,
					twe.uType,
					(cwn.uOwner = twe.uWe) AS IsOwner,
					(cwn.uCreator = twe.uWe) AS IsCreator,		
					oDD.Rodzaj = 0 AS isGrupa
					-- , twe.*
				FROM `t_log_we` twe
				INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
				INNER JOIN `v_cwdu` cwdu ON cwdu.Podrodzaj = twe.Podrodzaj AND cwdu.uType = twe.uType -- IN (cwn.Def, '') AND cwdu.uType = cwdr.uType
				INNER JOIN `osoby` oDD ON oDD.GUID = twe.uWe
				-- inner join 
				WHERE
					twe.OP = 'cwc.NEW'
			;
		/*	o zmianach w wf !!! DW	*/
		/*
		UWAGA w ...
			@workflow.mail.Adr.DW = IFNULL((SELECT ValueA AS maile FROM IReg i WHERE IdKey = 'PF_emaile_DW' AND IdPath = 'INT\\SYSTEM\\MOTLAWA\\DaneFirmy'), '')	
		sa adresy DW - przenieś je do tabel !
			zrób select-a np. dla 'web_crm'
					SELECT 
						cr.Nazwa,
						cwdu.* 
					FROM `crm_workflow_def_users` cwdu
					LEFT JOIN `crm_rodzaje` cr ON cr.Rodzaj = 16 AND cr.Podrodzaj = cwdu.Podrodzaj
					WHERE
						cwdu.Def = 'web_crm'
					ORDER BY cwdu.uType, cwdu.Podrodzaj, cwdu.uType
					;			
				w kolumnie uType = uDW1 dla wszystkich aktualnie uzywanych podrodzajów ustaw
				Deleted = 0
				uGUID = xxxx  np. KADRY_Decyzje/AUDYTORZY_SZKOLEN etc.
		*/

			INSERT IGNORE INTO `twflog_recip`
			(msgTyp, uRecip, nRecip, uAs, uType, IsOwner, IsCreator, isGrupa)
				SELECT
					DISTINCT
					'DW' AS msgTyp,
					oDW.GUID AS uRecip,
					(@.nDW := TRIM(CONCAT_WS(' ' , oDW.Imie1, oDW.Nazwisko))) AS nRecip,
					cwdu.uAs AS uAs,
					cwdr.uType,
					(cwn.uOwner = oDW.GUID) AS IsOwner,
					(cwn.uCreator = oDW.GUID) AS IsCreator,		
					oDW.Rodzaj = 0 AS isGrupa
					-- , twe.*
				FROM `t_log_we` twe
				INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
				INNER JOIN `crm_workflow_confirm` cwdr ON cwdr.wGUID = twe.wGUID AND cwdr.Idn_WorkFlow = 0 AND twe.DWFlags LIKE CONCAT('%', cwdr.uType, '%')	-- cwdr.uType IN ('uOdp', 'uAbsZast')
				LEFT JOIN `v_cwdu` cwdu ON cwdu.Podrodzaj = cwn.Podrodzaj AND cwdu.uType = cwdr.uType -- IN (cwn.Def, '') AND cwdu.uType = cwdr.uType
				LEFT JOIN `osoby` oDW ON oDW.GUID = cwdr.uGUID
				WHERE
					twe.OP IN ('cwc.DONE', 'cwc.UNDO')
			;		
			UPDATE `twflog_recip` twla
			SET
				twla.Adres = 
					NULLIF(
					IFNULL(
						(
						SELECT ua.Ad_mail FROM `_user_accounts` ua WHERE ua.OsobaGUID = twla.uRecip
						),
						IFNULL(
							(
							SELECT 
								k.Adres 
							FROM `kontakty` k 
							WHERE 
								k.osobaGUID = twla.uRecip
								AND k.typ_medium = 3 
								AND IFNULL(k.KontrGUID, '') != '' 				--	KontrGUID !!!
							ORDER BY k.newsletter DESC, k.priorytet DESC 
							LIMIT 1
							),
							''
						)
					), '')
			;
		--	Tabela maili ...
			-- SHOW CREATE TABLE `t_log_we_mail`;		
			DROP TEMPORARY TABLE IF EXISTS `t_log_we_mail`;
			CREATE TEMPORARY TABLE `t_log_we_mail` (
			  `ID` VARCHAR(38) DEFAULT NULL,
			  `mType` VARCHAR(20) DEFAULT 'DW',
			  `wGUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'powtorzenie commisionGUID',
			  `uRecip` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'user/grupa decyzyjna',
			  `nRecip` VARCHAR(61) DEFAULT NULL,
			  `msgTitle` VARCHAR(250) DEFAULT NULL,
			  `msgBody` MEDIUMTEXT,
			  `msgBodyContent` MEDIUMTEXT,
			  `msgBodyA` MEDIUMTEXT,
			  `msgBodyB` MEDIUMTEXT,
			  `msgBodyC` MEDIUMTEXT,
			  `msgMailWhy` VARCHAR(250) DEFAULT '',
			  `Idn` INT(11) NOT NULL DEFAULT 0,
			  `LogIdn` INT(11) NOT NULL COMMENT 'ng logu',
			  `adres` VARCHAR(250) DEFAULT NULL,	--	PO CO???
			  `cRecip` INTEGER DEFAULT 0,
			  `Deleted` INTEGER DEFAULT 1,
			PRIMARY KEY `ID`(`ID`)
			)
			;
		--	Button - takie rzeczy przenieś potem do send mail	
			SET 
				@Html.Go.to.PortaFide.Button = "<br><br><a style='float:right;margin:0;padding:0;margin:0;padding:0;font-family:Helvetica Neue,Helvetica,Helvetica,Arial,sans-serif;text-decoration:none;color:#fff;background-color:blue;padding:10px 16px;font-weight:bold;margin-right:10px;text-align:center;display:inline-block' href=#href_PortaFide#> Przejdź do portalu </a>"
			;
			SET
			--	odczytaj z coresów link do PortaFide - potrzebny do podmiany frazy #href_PortaFide#
				@Html.Go.to.PortaFide.href = 
					IFNULL(
						(SELECT a.Prog_HREF FROM `_sys_app_reg` a WHERE a.ID LIKE 'M.WEB.PortaFide.www%' AND a.Prog_HREF <> '' LIMIT 1),
						IFNULL(
							(SELECT c.Prog_HREF FROM `sys_core` c WHERE c.GUID LIKE 'M.WEB.PortaFide.www%'),
							@Html.Go.to.PortaFide.href.default
						)
				)
			;
			SET	-- podmiana frazy #href_PortaFide# na link buttona
				@Html.Go.to.PortaFide.Button = 
					REPLACE(REPLACE(@Html.Go.to.PortaFide.Button, 
					'#href_PortaFide#', @Html.Go.to.PortaFide.href),
					'#URL:LINK#', @Html.Go.to.PortaFide.href)
			;	
		--	Wstawianie Do decyzji i DW	
			TRUNCATE `t_log_we_mail`;
		--	Do decyzji (DD)
			INSERT IGNORE INTO `t_log_we_mail`
			SELECT 
				_Get_ID_xxxxx('SHORT', 38, 'WF.DD.Log=', twe.LogIdn, ':', NULL, NULL, NULL) AS ID,
				'DD' AS mType,
				twe.wGUID,
			-- cwm.Txt,
			--	cwmp.Txt,
				twla.uRecip,
				twla.nRecip,
				cwn.Temat AS msgTitle,
				NULL AS msgBody,
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
						-- IF(NOT twe.IsKtos, @workflow.mail.MSG.Ja.Ja, @workflow.mail.MSG.Ktos), 
					cwm.Txt,	
					'#CHANGE#', twe.OpTxt),
					'#STATUS_BEFORE#', twe.StatusCurrTxt),
					'#STATUS_END#', IF(cwn.IsEnding, cwmE.Txt, '')),
					'#msgExt#', IFNULL(twe.msgExt, '')),
					'#uAs#', twe.uAsDec),
					'#uAsDw#', twe.uAsDwDec),
					'#owner#', twe.nOwner),
					'#creator#', twe.nCreator),
					'#dec#', twe.nDec),
					'#AbsZast#', twe.nAbsZast),
					'#WNIOSEK#', cwn.Opis),
					'#TIME#', tAt),
					'#(nGrupa)#', ''),
					'#STATUS_?#', '')
				AS msgBodyContent,
				NULL AS msgBodyA,
				@Html.Go.to.PortaFide.Button AS msgBodyB,
				@Html.HIST.Tabela.NEW AS msgBodyC,
				/*	w do decyzji msgMailWhy pomijamy (przynajmniej na razie)
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
					twe.uAsDwDec,
					'#uAs#', twe.uAsDec),
					'#uAsDw#', twe.uAsDwDec),
					'#owner#', twe.nOwner),
					'#creator#', twe.nCreator),
					'#dec#', twe.nDec),
					'#WNIOSEK#', cwn.Opis)
				*/
				'' AS msgMailWhy,
				twe.Idn, 
				twe.LogIdn,
				twla.adres,
				0 AS cRecip, 1 AS Deleted
				-- twe.*
			FROM `t_log_we` twe
			INNER JOIN `twflog_recip` twla ON twla.uRecip = twe.uWe AND twla.msgTyp = 'DEC'
			INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
			LEFT JOIN `crm_workflow_msgs` cwm ON cwm.ID = 'DoDecyzji' AND cwm.TwojWniosek = (twe.uWe = twe.uOwner)
			LEFT JOIN `crm_workflow_msgs` cwmp ON cwmp.ID = 'Prolog' AND cwmp.TwojWniosek = (twe.uWe = twe.uOwner)
			LEFT JOIN `crm_workflow_msgs` cwmE ON cwmE.ID = 'Wniosek.End' AND cwmE.TwojWniosek = -1
			WHERE
				twe.OP = 'cwc.NEW'
				AND twe.LogIdn = @.we.LogIdn
			;
		--	DW	
			INSERT IGNORE INTO `t_log_we_mail`
			SELECT 
				_Get_ID_xxxxx('SHORT', 38, 'WF.DW.Log=', twe.LogIdn, ':', NULL, NULL, NULL) AS ID,
				'DW' AS mType,
				twe.wGUID,
			--	twe.idn,
			-- cwm.Txt,
			--	cwm.Txt,
			-- cwdu.uAsDw,
				twla.uRecip,
				twla.nRecip,
				cwn.Temat AS msgTitle,
				NULL AS msgBody,
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
						-- IF(NOT twe.IsKtos, @workflow.mail.MSG.Ja.Ja, @workflow.mail.MSG.Ktos), 
					/*	
					CONCAT_WS('',
						IF((twla.uRecip = twe.uDec), NULL, cwmp.Txt),
						cwm.Txt
					),
					*/
					cwm.Txt,
					'#CHANGE#', twe.OpTxt),
					'#STATUS_BEFORE#', twe.StatusCurrTxt),
					'#STATUS_END#', IF(cwn.IsEnding, cwmE.Txt, '')),
					'#msgExt#', IFNULL(twe.msgExt, '')),
					'#uAs#', twe.uAsDec),
					'#uAsDw#', cwdu.uAsDw),
					'#owner#', twe.nOwner),
					'#creator#', twe.nCreator),
					'#dec#', twe.nDec),
					'#AbsZast#', twe.nAbsZast),
					'#WNIOSEK#', cwn.Opis),
					'#TIME#', tAt),
					'#(nGrupa)#', ''),
					'#STATUS_?#', '')
				AS msgBodyContent,
				NULL AS msgBodyA,
				@Html.Go.to.PortaFide.Button AS msgBodyB,
				@Html.HIST.Tabela.NEW AS msgBodyC,
				REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
					IF((twla.uRecip = twe.uDec), '', cwmp.Txt),
					'#uAs#', twe.uAsDec),
					'#uAsDw#', cwdu.uAsDw),
					'#owner#', twe.nOwner),
					'#creator#', twe.nCreator),
					'#dec#', twe.nDec),
					'#AbsZast#', twe.nAbsZast),
					'#(nGrupa)#', IF(twla.isGrupa, CONCAT_WS('', ' ("', twla.nRecip, '")'),'')),
					'#WNIOSEK#', cwn.Opis)
				AS msgMailWhy,
				twe.Idn, 
				twe.LogIdn,
				twla.adres,
				0 AS cRecip, 1 AS Deleted 
				-- twe.*
			FROM `t_log_we` twe
			INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
			INNER JOIN `twflog_recip` twla ON twla.msgTyp = 'DW' AND twe.DWFlags LIKE CONCAT('%', twla.uType, '%')

			-- INNER JOIN `crm_workflow_confirm` cwdr ON cwdr.wGUID = twe.wGUID AND cwdr.Idn_WorkFlow = 0 AND twe.DWFlags LIKE CONCAT('%', cwdr.uType, '%')-- cwdr.uType IN ('uOdp', 'uAbsZast')
			LEFT JOIN `crm_workflow_msgs` cwm ON cwm.ID = 'ChangeDW' AND cwm.TwojWniosek = (twla.IsOwner) AND cwm.CtxTy = (twla.uRecip = twe.uDec)
			LEFT JOIN `crm_workflow_msgs` cwmp ON cwmp.ID = 'Prolog' AND cwmp.TwojWniosek = (twla.IsOwner)
			LEFT JOIN `v_cwdu` cwdu ON cwdu.Podrodzaj = cwn.Podrodzaj AND cwdu.uType = twla.uType -- IN (cwn.Def, '') AND cwdu.uType = cwdr.uType
			LEFT JOIN `crm_workflow_msgs` cwmE ON cwmE.ID = 'Wniosek.End' AND cwmE.TwojWniosek = -1
			-- LEFT JOIN `osoby` oDW ON oDW.GUID = cwdr.uGUID
			WHERE
				twe.OP IN ('cwc.DONE', 'cwc.UNDO')
				AND twe.LogIdn = @.we.LogIdn
			ORDER BY idn
			;
	SET	
		@.MSG.Templ = 
'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<title></title>
	<style type="text/css">
		.welcome{margin:20px 10px 20px 10px;color:#0079c1;font-size: 1.5em;font-family: Helvetica, Arial, sans-serif;clear: both;}
		.user-info{line-height:1.5em;margin: 20px 10px 20px 10px;color:#000;font-size:1em;font-family: Helvetica, Arial, sans-serif;text-align: left;}
		.owner-info{line-height:1.5em;margin: 20px 10px 20px 10px;color:#000;font-size:1em;font-family: Helvetica, Arial, sans-serif;text-align: left;}
		.small-info{line-height:1.5em;margin: 20px 10px 20px 10px;color:#000;font-size:0.8em;font-family: Helvetica, Arial, sans-serif;text-align: left;}
		.activate-info{line-height:.9em;margin:40px 10px 40px 10px;color:#717074;font-size:1.1em;font-family: Helvetica, Arial, sans-serif;text-align: left;font-weight: 900;}
		.button{margin: 20px 10px 20px 10px; padding:10px 30px 10px 30px;background-color:#0079c1;color: #F3F3F3; border-radius: 5px;text-decoration-line: none;}
		a:focus, a:hover { background-color:#DDD;color: #0079c1;}
		.p-button {margin: 40px 10px 40px 10px;}
		a {font-family: Helvetica, Arial, sans-serif;}		
	</style>
</head>
<body lang="pl-PL">
<p class="welcome">Witamy</p>
<p class="user-info"><#BODY#></p>
<p class="p-button"> <a class="button" href="#URL:LINK#" target="_blank"> Przejdź do portalu </a> </p></body></html>
<p class="user-info"><#TABELA#></p>
<p class="owner-info"><BR>Wiadomość ta wygenerowana została automatycznie z systemu <I>Motława</I>. Prosimy na nią nie odpowiadać.</strong></p>
<p class="small-info">Jednocześnie - mając na uwadze wymogi Rozporządzenia Parlamentu Europejskiego i Rady (UE) 2016/679 z dnia 27 kwietnia 2016 r. w sprawie ochrony osób fizycznych w związku z przetwarzaniem danych osobowych i w sprawie swobodnego przepływu takich danych oraz uchylenia dyrektywy 95/46/WE (tzw."RODO") - <strong>informujemy że administratorem Pani/Pana danych osobowych jest:<BR>#OWNER#, #OWNER_ADR#.</strong></p>
</body>
</html>'
;		

			UPDATE `t_log_we_mail` t
			SET
				t.msgBody = CONCAT_WS('',
					REPLACE(REPLACE(t.msgBodyContent,
					'\n', '<br>'),
					'\t', '<li>'),
					-- t.msgBodyA,
					-- t.msgBodyB,
					-- t.msgBodyC,
					NULL
				)
			;
			UPDATE `t_log_we_mail` t, `_txt_templ` tt, `owner_info` oi
			SET
				t.msgBody = 
					REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(tt.txt,
					'<#BODY#>', t.msgBody),
					'#MAIL.WHY#', t.msgMailWhy),
					'<#TABELA#>', t.msgBodyC),
					'#URL:LINK#', @Html.Go.to.PortaFide.href),
					'#OWNER_ADR#', IFNULL(oi.oAddr, '')),
					'#OWNER#', IFNULL(
						REPLACE(REPLACE(oi.oName,  
							'ograniczoną odpowiedzialnością', 'o.o.'), 
							'OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ', 'O.O.'), 
						''))
					
			WHERE
				tt.ID =
					IF(t.mType = 'DD', 'PF.Mail.Do.Decyzji', IF(t.mType = 'DW', 'PF.Mail.DW', 'PF.Mail.DW'))
			;
				--	SELECT * FROM t_log_we_mail;
		--	Adresy mailowe także z grup
			DROP TEMPORARY TABLE IF EXISTS `t_log_we_mail_recip`;
			CREATE TEMPORARY TABLE `t_log_we_mail_recip`
			SELECT 
				sn.ID, sn.mType,
				sn.uRecip AS uRecipWe,
				o.GUID AS uRecip,
					NULLIF(
					IFNULL(
						(
						SELECT ua.Ad_mail FROM `_user_accounts` ua WHERE ua.OsobaGUID = o.GUID
						),
						IFNULL(
							(
							SELECT 
								k.Adres 
							FROM `kontakty` k 
							WHERE 
								k.osobaGUID = o.GUID
								AND k.typ_medium = 3 
								AND IFNULL(k.KontrGUID, '') != '' 				--	KontrGUID !!!
							ORDER BY k.newsletter DESC, k.priorytet DESC 
							LIMIT 1
							),
							''
						)
					), '') AS Adres
				
			FROM `t_log_we_mail` sn
			INNER JOIN `grupy_osob` go ON go.grupaGUID = sn.uRecip AND go.Deleted = 0
			INNER JOIN `osoby` o ON o.GUID = go.osobaGUID AND o.Rodzaj != 0
			GROUP BY sn.ID, o.GUID
			HAVING Adres IS NOT NULL
			;
		--	Na koniec usun te które nie mają adresów (może tak być)	
			UPDATE `t_log_we_mail` sn
			SET
				sn.cRecip = (@.cRecip := (SELECT COUNT(*) FROM `t_log_we_mail_recip` snr WHERE snr.ID = sn.ID)),
				sn.Deleted = (@.cRecip = 0)
			;
		--	inicjacja	ALE PO CO??? skoro i tak sam ślesz do `com_msg_ng` i `com_msg_po`!!!!
			CALL send_mail('Init', 'crm_porta_fide_tools', 'MAIL_FROM_Kadry', 'M.WEB.PortaFide.www', '', '', '', NULL);
			IF NOT(IFNULL(_Params, '') LIKE '<No.Send>') THEN
			--	Nagłówki mailowe - Recipient
				INSERT IGNORE INTO `com_msg_ng`
					(
					GUID, 
					CreateAt, 
					OWNER, Msg_Title, Msg_Body,SrcGUID, SrcTable, 
					Notification_Start, Notification_Hour_Before, Notification_Until, Msg_Mode, Msg_SubMode, Sender
					, SrcCtxID
					)
					SELECT 
						sn.ID AS GUID,
						NOW() AS CreateAt, 
						-- NULL AS GUID_crm_notification,
						
						'System' AS OWNER, 
						sn.msgTitle AS Msg_Title, 
						sn.msgBody AS Msg_Body,
						sn.wGUID,
						'crm_commisions' AS SrcTable,
						NOW() AS Notification_Start, 
						0 AS Notification_Hour_Before, 
						DATE_ADD(NOW(), INTERVAL 1 DAY) AS Notification_Until,
						'MAIL' AS Msg_Mode, 
						'NEW' AS Msg_SubMode,
						@.Sender.MAIL AS Sender	--	było 'biuro@konkol.pl' AS Sender
						
						,sn.msgMailWhy AS SrcCtxID
					FROM `t_log_we_mail` sn
					-- FROM `t_prepare_mail_by_workflow_confirm_2` sn
					-- INNER JOIN `crm_commisions` c ON c.GUID = sn.crm_GUID
					WHERE
						TRUE -- sn.Adr_Mail <> ''
						AND sn.Deleted = 0
						-- AND ID = 'WF.DW.Log=52:100684787949240397'
				;
			--	Adresy mailowe - Recipient
				INSERT IGNORE INTO `com_msg_po`
					(GUIDNg, Medium_Type, Recipient, STATUS, Dispatch_ID, RecipientRole, Param1)
					SELECT
						sna.ID AS GUIDNg,
						'MAIL' AS Medium_Type,
				/*	Odblokuj (adr. mailowe)	*/
						sna.adres AS Recipient,
				/*	Testowe (adr. mailowe)	*/
					--	'jmam68@gmail.com,andrzej.semrau@gmail.com' AS Recipient,
						'NEW' AS STATUS,
						UUID_SHORT() AS Dispatch_ID, --  sn.GUID_Mail AS Dispatch_ID,
						'To' AS RecipientRole,
						CONCAT_WS('/', sna.mType, sna.Adres) AS Param1 
					FROM `t_log_we_mail_recip` sna
					WHERE
						sna.adres <> ''
						-- AND ID = 'WF.DW.Log=52:100684787949240397'
				;
			END IF;
		END IF;

		IF _MODE LIKE 'log.HIST%' THEN
            CALL P_crm_workflow_n('log.Create', _GUID, null, '', '', '', '', '', _Params);
            IF _MODE LIKE 'log.HIST.SELECT' OR _Params LIKE '%<select>%' THEN
                SET @.tStart := NULL;
                SELECT
                    (@.tStart := IF(@.tStart IS NULL, 1, 0)) AS isFirst,
                    h.Idn,
                    h.sLogAt AS LogAt,
                    -- h.sLogAt AS Time_log2,
                        --	h.LogAt AS Time_log2,
                    h.nDec AS DecUsersN,
                    h.logInf AS logInf, -- Status_log,
                    h.Status_Before,
                    h.Status_Current,
                    h.fFirst, h.fLast, h.OP,
                    IF(h.fLast AND h.OP = 'cwc.DONE' AND h.IsEnding <> 0,
                        h.IsEnding,
                        0
                    ) AS IsEND,
                    h.IsEnding,
                    h.fLastBrakDec,
                    h.IsOwner
                    -- h.*
                FROM (
                    SELECT 
                        twe.Idn,
                        twe.LogAt,
                        _Fmt_DateTime(twe.LogAt, 'ddd d mmm yyyy hh:nn @Y') AS sLogAt,
                        twe.uDec AS Users_Nazwiska_Log,
                        twe.nWe,
                        CONCAT_WS('',
                            -- twe.tAt, ' ',
                            REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
                                    -- IF(NOT twe.IsKtos, @workflow.mail.MSG.Ja.Ja, @workflow.mail.MSG.Ktos), 
                                IF(NOT twe.fLastBrakDec,
                                    CONCAT_WS(' ',
                                        twe.OpTxt,	
                                        NULLIF(twe.msgExt, '')
                                    ),
                                    CONCAT('brak decyzji - (', NULLIF(twe.StatusCurrTxt, ''), ')')
                                ),
                                '#CHANGE#', twe.OpTxt),
                                '#STATUS_BEFORE#', twe.StatusCurrTxt),
                                '#msgExt#', IFNULL(twe.msgExt, '')),
                                '#uAs#', twe.uAsDec),
                                '#uAsDw#', twe.uAsDec),
                                '#owner#', twe.nOwner),
                                '#creator#', twe.nCreator),
                                '#dec#', twe.nDec),
                                '#AbsZast#', twe.nAbsZast),
                                '#WNIOSEK#', cwn.Opis),
                                '#TIME#', tAt),
                                '#STATUS_?#', ''),
                                '#(nGrupa)#', ''),
                                CONCAT(' z adnotacją: "', NULLIF(twe.Comment, ''), '"')
                        ) AS LogInf,
                        StatusTxt1 AS Status_Before,
                        StatusTxt2 AS Status_Current,
                        
                        '????' AS Confirm_log,
                        -- cwIDN AS Idn,
                        cw.Prev_Idn_workflow,
                        cwn.GUID AS commisionGUID,
                        cwn.Def,
                        cw.Start_Status,
                        cw.Confirm_Status,
                        555 AS `X`,
                        333 AS `Y`,
                        
                        twe.uDec,
                        twe.nDec,
                        tAt,
                        twe.OpTxt,
                        twe.fLastBrakDec,
                        twe.fLast, twe.fFirst, twe.OP, twe.IsOwner,
                        cwn.IsEnding
                            -- ,twe.*
                    FROM `t_log_we` twe
                    INNER JOIN `crm_workflow_n` cwn ON cwn.GUID = twe.wGUID
                    LEFT JOIN `crm_workflow` cw ON cw.IDN = cwIdn
                    WHERE
                        (twe.OP IN ('cwc.FIRST', 'cwc.DONE', 'cwc.UNDO'))
                        OR
                        twe.fLastBrakDec
                    ORDER BY twe.Idn
                ) h 	
                ;                
            END IF;
		END IF;
			
	END IF;
END$$

DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
UWAGA
w tekstach w tabeli `crm_workflow_msgs`
gdy chcemy miec zawartość pola msgExt z `crm_workflow_def`
musimy dodać 
...#msgExt#... 
Dla SKOK dodałem dla ID = 'DoDecyzji' i TwojWniosek = 0 
*/

/*
$Log: P_crm_workflow_n.sql,v $
Revision 1.5  2025/02/25 20:45:43  jmam
$send$ Warningi

Revision 1.4  2024/11/20 18:00:52  jmam
$SEND$ Poprawka do mode "crm.Wniosek.CANCEL"

Revision 1.3  2024/07/02 08:11:57  jmam
$SEND$ - uwzgl. null-i

Revision 1.2  2024/05/13 18:00:28  jmam
SQL zmiana V 2024 $SEND$

Revision 1.1  2024/04/27 09:14:05  jmam
Inicjacja WORK.FLOW.Ver = 2024.04 $SEND$

*/
