﻿<?xml version="1.0" encoding="utf-8"?>
<ReportsExport>
	<Reports>
		<Report id="faa12b72-94d6-4364-b20e-8c45f3b9b082" codekey="glc_theme_per_tg" categoryCodekey="UserStats" name="GCL Gesamtübersicht SI" description="Stati der Lerner bei der Rezertifizierung einzelner Programme, ausgewertet nach Zielgruppe.">
			<MetaData created="2020-06-12T15:39:52" createdBy="62483_LastName, 62483_FirstName (62483)" createdBy_user_id="62483" modified="2024-09-03T12:45:06" modifiedBy="Administrator_LastName, Administrator_FirstName (Administrator)" modifiedBy_user_id="2" />
			<ExecutionDetails format="TableResult" commandType="SqlCommandOrQuery" exportHandler="" adminControl="" exportMultipleTablesToSheets="False" datesWithTime="False" extraParams="" />
			<Mandators mandatorMode="OnlyOwner" mandator_id="B4FBE551-EE3C-4528-BEAD-422E88FA689D" mandatorName="munichre-anticorruption" isStandard="False" isUsedByMenu="False" />
			<Parameters>
				<Parameter id="d8e4595f-8bdd-4a54-9298-8f378450e6a0" isRequired="False" allowMultiSelect="False" name="Zeitraum" contextName="Selected period" defaultValue="" renderHint="Undefined" disableParameter="DontDisable" />
				<Parameter id="38955e82-7018-4542-83e5-2c08d6d24560" isRequired="True" allowMultiSelect="False" name="Lernprogramm" contextName="Selected program" defaultValue="" renderHint="Undefined" disableParameter="DontDisable" />
			</Parameters>
			<Roles>
				<Role id="90" />
			</Roles>
			<command>
				--      declare @theme_id uniqueidentifier
				--SET @theme_id = 'AC43585C-7542-4021-91E1-6020CE4620E1'

				--      declare @current_mandator_id uniqueidentifier
				--      select @current_mandator_id = id from tblMandators where name = 'ELECT'

				--      declare @dateRange_start datetime
				--      set @dateRange_start = '2020-01-01'

				--      declare @dateRange_end datetime
				--      set @dateRange_end = '2020-06-14'
				-- The report without debugging information starts here
				--APA4
				-- The report without debugging information starts here
				DECLARE @recertificationInterval INT
				DECLARE @MinUsers INT = 2
				DECLARE @todayDay DATETIME

				SET @todayDay = GETDATE()
				SELECT @recertificationInterval = overrideSpanMonths FROM tblItems WHERE id = @theme_id

				if (@dateRange_start is not null)
					set @dateRange_start = cast(convert(NVARCHAR(32), @dateRange_start, 112) as datetime)

				if ( @dateRange_end is not null )
				begin
					set @dateRange_end  = cast(convert(NVARCHAR(32), @dateRange_end, 112) as datetime)
					set @dateRange_end = dateadd(day, 1, @dateRange_end)
					set @dateRange_end = dateadd(second, -1, @dateRange_end)
				end

				CREATE TABLE #result
				(
					user_id INT,
					targetGroupId INT,
					activeLearner INT,
					greenStatus INT,
					yellowStatus INT,
					greyStatus INT,
					overrideDate DATETIME NULL,
					firstMailNotification INT,
					finalMailNotificiation INT,
					overrideMailNotificiation INT,
					lastGreenStatusInPeriode INT
				)
				
				DECLARE @Bibliothek INT = (select id from tbltargetgroups where title like 'Bibliothek%' and mandator_id = @current_mandator_id)

				-- select all users, which had the WBT assigned in the given time range and which have a "non empty" department set and calculate theme status and activity
				INSERT INTO #result
				SELECT
					intUserCn,
					
					(select top 1 targetGroup_id 
					   from tblUsersTargetGroups join tblTargetGroups on tblTargetGroups.id = tblUsersTargetGroups.targetGroup_id
					  where UserCn = intUserCn and targetGroup_id &lt;&gt; @Bibliothek and left(title,1) &lt;&gt; '_'
					) as targetGroupId,
					
					-- we have to check tblStatsThemeSessions and tblStatusUserItemHistory as there are some statuses without entry in tblStatsThemeSessions
					CASE
					WHEN EXISTS 
						(SELECT * FROM tblStatsThemeSessions
						  WHERE tblStatsThemeSessions.theme_id = @theme_id
							AND tblStatsThemeSessions.durationSeconds IS NOT NULL
							AND tblStatsThemeSessions.user_id = v_users.intUserCn
							AND (tblStatsThemeSessions.startTime BETWEEN @dateRange_start AND @dateRange_end)
						)
					OR EXISTS 
						(SELECT * FROM tblStatusUserItemHistory
						  WHERE tblStatusUserItemHistory.item_id = @theme_id
							AND tblStatusUserItemHistory.user_id = v_users.intUserCn
							AND (tblStatusUserItemHistory.startDate BETWEEN @dateRange_start AND @dateRange_end)
						)
					THEN 1 ELSE 0 END AS [ActiveLearner], -- active learner provided some status information
					
					CASE WHEN (
						(SELECT TOP 1 ISNULL(status,0) FROM tblStatusUserItemHistory UIH
						  WHERE user_id = v_users.intUserCn
							AND UIH.item_id = @theme_id
							AND
							(
								(UIH.startDate BETWEEN @dateRange_start AND @dateRange_end)
							OR
								(UIH.startDate &lt; @dateRange_end AND UIH.endDate IS NULL)
							) 
						ORDER BY endDate
						) = 2)
					THEN 1 ELSE 0 END AS [GreenStatus],
					
					CASE WHEN (
						(SELECT TOP 1 ISNULL(status,0) FROM tblStatusUserItemHistory UIH
						  WHERE user_id = v_users.intUserCn
							AND UIH.item_id = @theme_id
							AND
							(
								(UIH.startDate BETWEEN @dateRange_start AND @dateRange_end)
							OR
								(UIH.startDate &lt; @dateRange_end AND UIH.endDate IS NULL)
							) 
						ORDER BY endDate
						) = 1)
					THEN 1 ELSE 0 END AS [YellowStatus],
					
					CASE WHEN (
						(SELECT TOP 1 ISNULL(status,0) FROM tblStatusUserItemHistory UIH
						  WHERE user_id = v_users.intUserCn
							AND UIH.item_id = @theme_id
							AND
							(
								(UIH.startDate BETWEEN @dateRange_start AND @dateRange_end)
							OR
								(UIH.startDate &lt; @dateRange_end AND UIH.endDate IS NULL)
							) 
						ORDER BY endDate
						) = 0)
					THEN 1 ELSE 0 END AS [GreyStatus],
					
					NULL, --overrideDate
					0,
					0,
					0,
					CASE WHEN 
					EXISTS
					(
						(SELECT TOP 1 id FROM tblStatusUserItemHistory UIH
						  WHERE user_id = v_users.intUserCn
							AND UIH.item_id = @theme_id
							AND ((UIH.startDate BETWEEN @dateRange_start AND @dateRange_end))
							AND status = 2
						)
					) THEN 1 ELSE 0 END
				FROM v_users
				WHERE
					EXISTS (SELECT * FROM tblStatusUserItemOverride
						WHERE tblStatusUserItemOverride.item_id = @theme_id
						AND tblStatusUserItemOverride.user_id = v_users.intUserCn
						AND (@dateRange_end IS NULL OR tblStatusUserItemOverride.assignedDate &lt; @dateRange_end)
						)
					AND NOT EXISTS (SELECT * FROM tblRecertificationExcludedTargetGroups AS excluded
						INNER JOIN tblUsersTargetGroups AS utg ON excluded.targetGroup_id = utg.targetGroup_id
						AND excluded.item_id = @theme_id
						WHERE utg.UserCn = v_users.intUserCn)
					AND v_Users.userStatus NOT IN (2,3)

				-- getting override information for the item
				UPDATE #result
					SET overrideDate = ISNULL(tblStatusUserItemOverride.overrideDate,dbo.fn_GetUserItemStatusWillOverrideDate(#result.user_id, @theme_id))
				FROM #result INNER JOIN tblStatusUserItemOverride
					ON #result.user_id = tblStatusUserItemOverride.user_id AND tblStatusUserItemOverride.item_id = @theme_id

				UPDATE #result
					SET greyStatus = 1
				WHERE greenStatus + yellowStatus + greyStatus = 0

				-- getting further information regarding the first mail notification
				UPDATE #result
					SET firstMailNotification = 1
				WHERE
					EXISTS
					(
					SELECT *
					FROM
					tblMails
					WHERE
						(
							tblMails.codekey = 'ModuleItemStatusOverride.FirstAlert.Theme'
						OR
							-- Look for a variant of this template, at the time of writing no content variant was allowed for this template
							-- so the only possible variant is an OU variant whose "parent" is the base template (so no need to check parent
							-- of parent which is the case for an OU variant of a content variant).
							EXISTS
							(
							SELECT
							*
							FROM
							tblMailTemplates mt
							JOIN tblMailTemplateVariant mtv
							ON  mtv.id = mt.variant_id
							WHERE
							mt.mandator_id = @current_mandator_id
							AND mt.codekey = tblMails.codekey
							AND mtv.parentCodekey = 'ModuleItemStatusOverride.FirstAlert.Theme'
							)
						)
						AND tblMails.user_id = #result.user_id
						AND tblMails.context_id = @theme_id
						AND
						(
							(
								@dateRange_start IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_start)
							)
						OR
							(
								@dateRange_end IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_end)
							)
						)
					)

				UPDATE #result
					SET finalMailNotificiation = 1
				WHERE
					EXISTS
					(
					SELECT  *
					FROM
						tblMails
					WHERE
						(
							tblMails.codekey = 'ModuleItemStatusOverride.FinalAlert.Theme'
						OR
							-- Look for a variant of this template, at the time of writing no content variant was allowed for this template
							-- so the only possible variant is an OU variant whose "parent" is the base template (so no need to check parent
							-- of parent which is the case for an OU variant of a content variant).
							EXISTS
							(
							SELECT
							*
							FROM
							tblMailTemplates mt
							JOIN tblMailTemplateVariant mtv
							ON  mtv.id = mt.variant_id
							WHERE
							mt.mandator_id = @current_mandator_id
							AND mt.codekey = tblMails.codekey
							AND mtv.parentCodekey = 'ModuleItemStatusOverride.FinalAlert.Theme'
							)
						)
						AND tblMails.user_id = #result.user_id
						AND tblMails.context_id = @theme_id
						AND
						(
							(
								@dateRange_start IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_start)
							)
						OR
							(
								@dateRange_end IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_end)
							)
						)
					)

				UPDATE #result
					SET overrideMailNotificiation = 1
				WHERE
					EXISTS
					(SELECT  *
					   FROM tblMails
					  WHERE
						(
							tblMails.codekey = 'ModuleItemStatusOverride.OverrideAlert.Theme'
						OR
							-- Look for a variant of this template, at the time of writing no content variant was allowed for this template
							-- so the only possible variant is an OU variant whose "parent" is the base template (so no need to check parent
							-- of parent which is the case for an OU variant of a content variant).
							EXISTS
							(SELECT *
							   FROM
								tblMailTemplates mt
								JOIN tblMailTemplateVariant mtv
								ON  mtv.id = mt.variant_id
							 WHERE
								mt.mandator_id = @current_mandator_id
								AND mt.codekey = tblMails.codekey
								AND mtv.parentCodekey = 'ModuleItemStatusOverride.OverrideAlert.Theme'
							)
						)
						AND tblMails.user_id = #result.user_id
						AND tblMails.context_id = @theme_id
						AND
						(
							(
								@dateRange_start IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_start)
							)
						OR
							(
								@dateRange_end IS NULL
							OR
								tblMails.created &gt; DATEADD(MONTH,-1 * @recertificationInterval,@dateRange_end)
							)
						)
						)

				--SELECT * FROM #result
				--SELECT * FROM tblStatusUserItemHistory AS suih
				--INNER JOIN #result AS r ON r.user_id = suih.user_id AND suih.item_id = @theme_id
				--ORDER BY suih.user_id , status


				-- get the desired result
				;WITH CTE
				AS(SELECT
					targetGroupId AS [Zielgruppe],

					-- counting the users per department company
					COUNT(*) AS 'totalLearners',
					SUM(lastGreenStatusInPeriode) AS lastGreenStatusInPeriode,
					
					-- users with override date in the past or received on of the mails for resetting the status
					SUM(CASE WHEN overrideDate &lt; @todayDay OR (finalMailNotificiation + overrideMailNotificiation &gt; 0) THEN 1 ELSE 0 END) AS 'dueLearnersInPeriode',
					
					-- expired users due of override
					SUM(CASE WHEN overrideDate &lt; @todayDay THEN 1 ELSE 0 END) AS 'expiredLearnersInPeriode',
					
					-- users with green status in the given periode
					SUM(greenStatus) AS 'Learners completed in selected period abs',
					
					-- users with override date in the future
					SUM(CASE WHEN overrideDate &gt; @todayDay THEN 1 ELSE 0 END) AS 'validLeanersWithCertificate',
					
					-- users with override date in the future and received at least one of the mails
					SUM(CASE WHEN finalMailNotificiation &gt; 0 THEN 1 ELSE 0 END) AS 'learnersInNotification'
					
				FROM #result
				GROUP BY targetGroupId)
				
				SELECT
					[Zielgruppe],
					
					-- counting the users per department company
					totalLearners,
					
					-- users with override date in the past or received on of the mails
					dueLearnersInPeriode AS 'Due learners in selected time period',
					
					-- users with green status in the given periode
					lastGreenStatusInPeriode AS 'Learners completed in selected period abs',
					
					CASE WHEN ISNULL(lastGreenStatusInPeriode,0) &gt; 0 AND ISNULL(dueLearnersInPeriode,0) &gt; 0
					THEN ROUND(CAST(lastGreenStatusInPeriode * 100 AS FLOAT) / dueLearnersInPeriode,2)
					ELSE NULL
					END AS 'Learners completed in selected period in %',
					
					-- users with override date in the future
					validLeanersWithCertificate AS 'Learners with valid certificate abs',
					
					CASE WHEN ISNULL(totalLearners,0) &gt; 0
					THEN ROUND(CAST((validLeanersWithCertificate) * 100 AS FLOAT) / totalLearners,2)
					ELSE NULL
					END AS 'Learners with valid certificate in %',
					
					-- users with override date in the past
					expiredLearnersInPeriode AS 'Leaners still expired / defaulting abs',
					
					CASE WHEN ISNULL(totalLearners,0) &gt; 0
					THEN ROUND(CAST((expiredLearnersInPeriode) * 100 AS FLOAT) / totalLearners,2)
					ELSE NULL
					END AS 'Learners still expired / defaulting in %',
					
					-- users with override date in the future and received at least one of the mails
					learnersInNotification AS 'Learners in notification abs',
					
					CASE WHEN ISNULL(dueLearnersInPeriode,0) &gt; 0 AND ISNULL(totalLearners,0) &gt; 0
					THEN ROUND(CAST(learnersInNotification * 100 AS FLOAT) / totalLearners,2)
					ELSE NULL
					END AS 'Learners in notification in %'
					
				INTO #tmpResult
				FROM CTE

				SELECT *
				FROM
				(
				SELECT
					tblTargetGroups.title as [Zielgruppe],
					
					-- counting the users per department company
					totalLearners AS [Learners in recertification],
					
					-- users with override date in the past or received on of the mails
					CASE WHEN (totalLearners &gt; @MinUsers) THEN
					[Due learners in selected time period]
					ELSE NULL END AS 'Due learners in selected time period',
					
					-- users with green status in the given periode
					CASE WHEN (totalLearners &gt; @MinUsers) THEN
					[Learners completed in selected period abs]
					ELSE NULL END AS 'Learners completed in selected period abs',
					
					CASE WHEN (totalLearners &gt; @MinUsers) AND ISNULL([Learners completed in selected period abs],0) &gt; 0 AND ISNULL([Due learners in selected time period],0) &gt; 0
					THEN [Learners completed in selected period in %]
					ELSE NULL
					END AS 'Learners completed in selected period in %',
					
					-- users with override date in the future
					CASE WHEN (totalLearners &gt; @MinUsers) THEN
					[Learners with valid certificate abs]
					ELSE NULL END AS 'Learners with valid certificate abs',
					
					CASE WHEN (totalLearners &gt; @MinUsers) AND ISNULL(totalLearners,0) &gt; 0
					THEN [Learners with valid certificate in %]
					ELSE NULL
					END AS 'Learners with valid certificate in %',
					
					-- users with override date in the past
					CASE WHEN (totalLearners &gt; @MinUsers) THEN
					[Leaners still expired / defaulting abs]
					ELSE NULL END AS 'Leaners still expired / defaulting abs',
					
					CASE WHEN (totalLearners &gt; @MinUsers) AND ISNULL(totalLearners,0) &gt; 0
					THEN [Learners still expired / defaulting in %]
					ELSE NULL
					END AS 'Learners still expired / defaulting in %',
					
					-- users with override date in the future and received at least one of the mails
					CASE WHEN (totalLearners &gt; @MinUsers) THEN
					[Learners in notification abs]
					ELSE NULL END AS 'Learners in notification abs',
					
					CASE WHEN (totalLearners &gt; @MinUsers) AND ISNULL([Due learners in selected time period],0) &gt; 0 AND ISNULL(totalLearners,0) &gt; 0
					THEN [Learners in notification in %]
					ELSE NULL
					END AS 'Learners in notification in %'
					
				FROM #tmpResult join tblTargetGroups on #tmpResult.[Zielgruppe] = tblTargetGroups.id
				
				UNION ALL
				
				SELECT
					NULL,
					
					-- counting the users per department company
					SUM(totalLearners),
					
					-- users with override date in the past or received on of the mails
					SUM([Due learners in selected time period]) AS 'Due learners in selected time period',
					
					-- users with green status in the given periode
					SUM([Learners completed in selected period abs]) AS 'Learners completed in selected period abs',
					
					CASE WHEN ISNULL(SUM(totalLearners),0) &gt; 0 THEN 
						ROUND(CAST((SUM([Learners completed in selected period in %])) * 100 AS FLOAT) / SUM(totalLearners),2)
					ELSE NULL
					END AS 'Learners completed in selected period in %',
					
					-- users with override date in the future
					SUM([Learners with valid certificate abs]) AS 'Learners with valid certificate abs',
					
					CASE WHEN ISNULL(SUM(totalLearners),0) &gt; 0 THEN 
						ROUND(CAST((SUM([Learners with valid certificate in %])) * 100 AS FLOAT) / SUM(totalLearners),2)
					ELSE NULL
					END AS 'Learners with valid certificate in %',
					
					-- users with override date in the past
					SUM([Leaners still expired / defaulting abs]) AS 'Leaners still expired / defaulting abs',
					
					CASE WHEN ISNULL(SUM(totalLearners),0) &gt; 0 THEN 
						ROUND(CAST((SUM([Learners still expired / defaulting in %])) * 100 AS FLOAT) / SUM(totalLearners),2)
					ELSE NULL
					END AS 'Learners still expired / defaulting in %',
					
					-- users with override date in the future and received at least one of the mails
					SUM([Learners in notification abs]) AS 'Learners in notification abs',
					
					CASE WHEN ISNULL(SUM(totalLearners),0) &gt; 0 THEN 
						ROUND(CAST((SUM([Learners in notification in %])) * 100 AS FLOAT) / SUM(totalLearners),2)
					ELSE NULL
					END AS 'Learners in notification in %'
					
				FROM #tmpResult
				) AS A 
				ORDER BY ISNULL([Zielgruppe],'ZZZZZZZZ')
				
				DROP TABLE #tmpResult
				DROP TABLE #result
			</command>
		</Report>
	</Reports>
	<Parameters>
		<Parameter id="d8e4595f-8bdd-4a54-9298-8f378450e6a0" isSystem="True" name="Zeitraum" reportParameterType_id="abff13be-91c3-4ee1-93a3-7292f8e013ba" queryParameterName="@dateRange" />
		<Parameter id="38955e82-7018-4542-83e5-2c08d6d24560" mandator_id="d5a90a49-e697-4aeb-8a5b-298782815490" isSystem="False" name="WBTs assigned to module GCL Auswertung" reportParameterType_id="86dbdace-73ac-4dc4-adfa-70c3ccbb8ad1" queryParameterName="@theme_id" />
	</Parameters>
	<ParameterTypes>
		<ParameterType id="abff13be-91c3-4ee1-93a3-7292f8e013ba" isSystem="True" name="DateRange" datatype="DateRange" dataValueField="" dataTextField="" />
		<ParameterType id="86dbdace-73ac-4dc4-adfa-70c3ccbb8ad1" mandator_id="d5a90a49-e697-4aeb-8a5b-298782815490" isSystem="False" name="WBTs assigned to module GCL Auswertung" datatype="GuidDDL" dataValueField="id" dataTextField="title">
			<query>
				declare @module_id uniqueidentifier = (select top 1 id from tblItems where title like 'GCL Auswertung')
				SELECT DISTINCT tblItems.id, tblItems.title
				FROM tblItems
					JOIN tblModuleItems ON tblModuleItems.item_id = tblItems.id
				WHERE tblModuleItems.module_id = @module_id
					AND itemType_id = 1 --theme
					AND tblItems.certificationType = 1 -- FixInterval
					AND tblItems.deleted is null
				ORDER BY title
			</query>
		</ParameterType>
	</ParameterTypes>
</ReportsExport>