﻿<?xml version="1.0" encoding="utf-8"?>
<ReportsExport>
  <Reports>
    <Report id="2fdc5ccc-af77-467d-8de4-46a357c9d0d9" codekey="UsersOrganisationRoles" categoryCodekey="UserStats" name="Benutzer mit zugeordneten Organisationsrollen" description="Auflistung der Benutzer mit zugeordneten Organisationsrollen. Achtung: lange Laufzeit!">
      <MetaData created="2013-11-12T09:42:14" createdBy="Administrator Debeka (Administrator)" createdBy_user_id="2" modified="2015-05-28T11:46:21" modifiedBy="Administrator Debeka" />
      <ExecutionDetails format="TableResult" commandType="SqlCommandOrQuery" exportHandler="" adminControl="" exportMultipleTablesToSheets="False" datesWithTime="False" extraParams="" />
      <Mandators mandatorMode="OnlyOwner" mandator_id="6279bb24-f218-49e0-9155-7c1cb1dba226" mandatorName="Debeka" isStandard="False" isUsedByMenu="False" />
      <Parameters>
        <Parameter id="a5485539-67e0-4912-8255-8081a54efb3c" isRequired="True" allowMultiSelect="True" name="Zielgruppe" contextName="Zielgruppe" defaultValue="" renderHint="Undefined" disableParameter="DontDisable" />
      </Parameters>
      <Roles>
        <Role id="60" />
        <Role id="90" />
      </Roles>
      <command>
        -- declare debug variables
        --DECLARE @current_mandator_id UNIQUEIDENTIFIER
        --DECLARE @targetGroup_id INT

        --SET @current_mandator_id = (SELECT id FROM tblMandators WHERE name = 'Debeka')
        --SET @targetGroup_id = NULL --2623

        -- aux variables for dynamic sql
        DECLARE @sql NVARCHAR(MAX)
        DECLARE @sqlFinal NVARCHAR(MAX)
        DECLARE @allRolesCursor CURSOR -- cursor for building dynamic columns in @tblCoreInfo
        -- variables for traversing the @allRolesCursor rows
        DECLARE @organisationRoleId UNIQUEIDENTIFIER
        DECLARE @organisationRoleName NVARCHAR(200)
        DECLARE @organisationRoleCodekey NVARCHAR(50)
        DECLARE @bosses NVARCHAR(256) -- string for all bosses of a user


        DECLARE @resultsCursor CURSOR -- delcare cursor for walking the results to add bosses
        DECLARE @bossesCursor CURSOR -- declare cursor for building a string with all bosses of a user
        DECLARE @user_Id INT
        DECLARE @organisationRole_id UNIQUEIDENTIFIER

        IF (EXISTS (SELECT *
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'dbo'
        AND  TABLE_NAME = '#tmpHelper'))
        drop table #tmpHelper


        IF (EXISTS (SELECT *
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = 'dbo'
        AND  TABLE_NAME = 'tmpCoreInfo'))
        drop table tmpCoreInfo

        -- declare @tmpCoreInfo table (userIs_id int not null,
        CREATE TABLE tmpCoreInfo(userIs_id INT NOT NULL,
        Name NVARCHAR(128),
        Vorname NVARCHAR(128),
        Kennung NVARCHAR(64),
        Titel NVARCHAR(64),
        Abteilung NVARCHAR(128),
        Dienststelle NVARCHAR(64),
        organisationRole_id UNIQUEIDENTIFIER,
        roleName NVARCHAR(50))

        DECLARE @tblBosses TABLE(Name NVARCHAR(128),
        Nachname NVARCHAR(128),
        Kennung NVARCHAR(64))
        DECLARE @bossNachname NVARCHAR(128)
        DECLARE @bossKennung NVARCHAR(64)

        -- declare "All Roles" table for holding all defined roles for the mandator
        DECLARE @tblAllRoles TABLE(organisationRoleId UNIQUEIDENTIFIER NOT NULL,
        organisationRoleName VARCHAR(50),
        organisationRoleCodekey VARCHAR(15))
        -- fill out table with all defined roles for the mandator
        INSERT INTO @tblAllRoles
        SELECT id,
        name,
        codekey
        FROM tblOrganisationRoles
        WHERE mandator_id = @current_mandator_id
        ORDER BY sortorder

        --select * from @tblAllRoles -- inbetween rsult to check!!! REMOVE!!

        -- add defined roles columns to @tblCoreInfo
        SET @allRolesCursor = CURSOR FORWARD_ONLY STATIC
        FOR SELECT organisationRoleId,
        organisationRoleName,
        organisationRoleCodekey
        FROM @tblAllRoles

        INSERT INTO tmpCoreInfo
        SELECT DISTINCT user_id, --userIs_id, 
                v_Users.Nachname AS Name, 
                v_Users.Vorname, 
                v_Users.descUserCn AS Kennung, 
                v_Users.title, 
                v_Users.division AS Abteilung, 
                v_Users.office AS Dienststelle, 
                organisationRole_id, 
                tblOrganisationRoles.name AS roleName --, userFor_id--, dense_rank() over (order by userIs_id) as rank
  FROM tblOrganisationRolesOfUsers --tblUsersOrganisationRolesUsers
       JOIN v_Users ON tblOrganisationRolesOfUsers.user_id = v_Users.intUserCn --tblUsersOrganisationRolesUsers.userIs_id = v_Users.intUserCn
                   AND v_Users.mandator_id = @current_mandator_id
       JOIN tblOrganisationRoles ON tblOrganisationRolesOfUsers.organisationRole_id = tblOrganisationRoles.id --tblUsersOrganisationRolesUsers.organisationRole_id = tblOrganisationRoles.id
       JOIN tblUsersTargetGroups ON tblUsersTargetGroups.UserCn = user_id --userIs_id
                                AND tblUsersTargetGroups.targetGroup_id IN (SELECT * FROM @targetGroup_id);


        -- select all users in groups without organisation roles
        WITH noRolesIds(id)
        AS (SELECT DISTINCT UserCn
        FROM tblUsersTargetGroups
        JOIN v_Users ON v_Users.intUserCn = tblUsersTargetGroups.UserCn AND mandator_id = @current_mandator_id
        WHERE tblUsersTargetGroups.targetGroup_id IN (SELECT * FROM @targetGroup_id)
        EXCEPT
        SELECT DISTINCT userIs_id
        FROM tmpCoreInfo) -- tblUsersOrganisationRolesUsers is already filtered after Mandator

        --now add these users to result table
        INSERT INTO tmpCoreInfo
        SELECT id,
        v_Users.Nachname AS Name,
        v_Users.Vorname,
        v_Users.descUserCn AS Kennung,
        v_Users.title,
        v_Users.division AS Abteilung,
        v_Users.office AS Dienststelle,
        NULL,
        NULL  -- neither roleId nor roleName
        FROM noRolesIds
        JOIN v_Users ON v_Users.intUserCn = noRolesIds.id ;


        WITH cte
        AS (SELECT tmpCoreInfo.*,
        tblUsersOrganisationRolesUsers.userIs_id AS boss_Id,
        tblUsersOrganisationRolesUsers.organisationRole_id AS bossRoleId,
        v_Users.Nachname AS bossName,
        v_Users.Vorname AS bossVorname,
        v_Users.descUserCn AS bossKennung
        FROM tmpCoreInfo
        LEFT OUTER JOIN tblUsersOrganisationRolesUsers ON userFor_id = tmpCoreInfo.userIs_id
        left JOIN v_Users ON intUserCn = tblUsersOrganisationRolesUsers.userIs_id),

        -- this is the prefinal presentation
        cteFinal
        AS (SELECT * --cte.*, bosses
        FROM cte
        left JOIN(
        SELECT c1.userIs_id AS c1UserIs_id,
        c1.bossRoleId AS c1BossRoleId,
        STUFF((
        SELECT '; ' + bossName + ', ' + bossVorName + ' (' + bossKennung + ')'
        FROM cte AS c2
        WHERE c2.userIs_id = c1.userIs_id AND c2.bossRoleId = c1.bossRoleId
        ORDER BY bossName
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)'), 1, 1, '') AS bosses
        FROM cte AS c1
        GROUP BY userIs_id,
        bossRoleId)AS #tmpWithBosses ON #tmpWithBosses.c1UserIs_id = cte.userIs_id
        AND #tmpWithBosses.c1BossRoleId = cte.bossRoleId)
        --  this is the prefinal presentation

        select *  INTO #tmpHelper from cteFinal
        --select * from #tmpHelper

        -- initialize final sql for output
        set @sqlFinal = 'select Name, Vorname, Kennung, Titel, Abteilung, Dienststelle, ISNULL(roleName, ''keine'') AS ''Organisationsrolle des Users'', '

        open @allRolesCursor
        fetch next from @allRolesCursor into @organisationRoleId, @organisationRoleName, @organisationRoleCodekey
        while(@@FETCH_STATUS = 0)
        begin
        -- first add the column
        set  @sql = 'alter table #tmpHelper add ' +  @organisationRoleCodekey +  ' varchar(MAX) '
        exec sp_executesql @sql
        -- now update values for the column
        set @sql = 'update #tmpHelper set ' + @organisationRoleCodekey + ' =  bosses where bossRoleId = ''' +  cast(@organisationRoleId as nvarchar(50)) + ''''
        --select @sql
        exec sp_executesql @sql
        -- add column for output in corret format
        set @sqlFinal = @sqlFinal + 'ISNULL(MAX(' + @organisationRoleCodekey + '), ''keine'')  as ''' + @organisationRoleName + ''' ,'

        fetch next from @allRolesCursor into @organisationRoleId, @organisationRoleName, @organisationRoleCodekey
        end
        close @allRolesCursor
        deallocate @allRolesCursor

        -- remove last comma
        set @sqlFinal = SUBSTRING(@sqlFinal, 1, len(@sqlFinal) - 1)
        ---- add last part of query
        set @sqlFinal = @sqlFinal + 'from #tmpHelper group by Name, Vorname, Kennung, Titel, Abteilung, Dienststelle, roleName order by Abteilung, Name, Vorname'
        --select @sqlFinal
        exec sp_executesql @sqlFinal


        drop table #tmpHelper
        DROP TABLE tmpCoreInfo -- DO NOT FORGET TO CLEAN UP!!!!


      </command>
    </Report>
  </Reports>
  <Parameters>
    <Parameter id="a5485539-67e0-4912-8255-8081a54efb3c" isSystem="True" name="Zielgruppe" reportParameterType_id="9ae252e1-18b4-4b71-982c-e27b2d3a5287" queryParameterName="@targetGroup_id" />
  </Parameters>
  <ParameterTypes>
    <ParameterType id="9ae252e1-18b4-4b71-982c-e27b2d3a5287" isSystem="True" name="TargetGroup" datatype="TargetGroup" dataValueField="" dataTextField="" />
  </ParameterTypes>
</ReportsExport>