/*
	DIESE SKRIPT MUSS VOR DEM ERSTEN START VON THEASOFT V4 AUSGEFÜHRT WERDEN.
    Das Script aktualisiert die Datenstruktur der theasoft Datenbank.
	
	- Bitte achten Sie darauf das die richtige (theasoft) Datenbank ausgewählt ist. -

	VOR DEM AUSFÜHEN DIESE SKRIPTES SOLLTEN ALLE ANWENDER THEASOFT V4 GESCHLOSSEN HABEN!
	Andernfalls kann es bei dem betreffenden Anwender zu einem Fehler kommen.

	Um zu prüfen ob Anwender theasoft V4 geöffnet haben, markieren Sie die acht folgenden Zeilen
	(von "SELECT" bis "'Theasoft%'") und klicken auf "Ausführen" (oder Taste "F5")
	Zur anschließenden Ausführung des gesamten Skriptes die Markierung entfernen.

	SELECT KeyName AS NAME, LOGINAME, HOSTNAME, LAST_BATCH, LastLoginDate, PROGRAM_NAME, 
	(SELECT TOP 1 DataValue FROM PersonContactData AS pcd INNER JOIN CommunicationTypes AS ct ON pcd.CommunicationTypeId = ct.CommunicationTypeId WHERE pcd.PersonId = users.PersonId AND Medium = 0  AND IsSecret = 0 AND NOT DataValue IS NULL AND DataValue <> '' ORDER BY ct.IsCommercial DESC, ct.Sort, pcd.Sort) AS Fon,
	(SELECT TOP 1 DataValue FROM PersonContactData AS pcd INNER JOIN CommunicationTypes AS ct ON pcd.CommunicationTypeId = ct.CommunicationTypeId WHERE pcd.PersonId = users.PersonId AND Medium = 10 AND IsSecret = 0 AND NOT DataValue IS NULL AND DataValue <> '' ORDER BY ct.IsCommercial DESC, ct.Sort, pcd.Sort) AS Mobil,
	(SELECT TOP 1 DataValue FROM PersonContactData AS pcd INNER JOIN CommunicationTypes AS ct ON pcd.CommunicationTypeId = ct.CommunicationTypeId WHERE pcd.PersonId = users.PersonId AND Medium = 50 AND IsSecret = 0 AND NOT DataValue IS NULL AND DataValue <> '' ORDER BY ct.IsCommercial DESC, ct.Sort, pcd.Sort) AS Email
	FROM sys.sysprocesses INNER	JOIN master.dbo.sysdatabases ON sysprocesses.DBID = sysdatabases.DBID
		LEFT JOIN Users ON LOGINAME = Users.UserName
		LEFT JOIN persons ON users.PersonId = persons.PersonId
	WHERE sysdatabases.name IN (SELECT db_name()) AND PROGRAM_NAME LIKE 'Theasoft%'

*/

--#region --------------------- Versions und Datenbankprüfungen ---------

--#region Prüfung auf Theasoft Datenbank
IF NOT EXISTS 
	(SELECT * 
	 FROM sys.objects 
	 WHERE  object_id = OBJECT_ID('dbo.NVData') AND OBJECTPROPERTY(object_id, 'IsUserTable') = 1)
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
		
																																															Print ''
																																															Print '		Keine theasoft V4 Datenbank!!!'	
																																															Print '		Bitte wechseln Sie die Datenbank'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
																																															Print ''
																																															Print ''
																																															RAISERROR('Keine Theasoft Datenbank!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region Berechtigungsprüfung
 if ((SELECT IS_SRVROLEMEMBER('sysadmin'))+(SELECT IS_ROLEMEMBER('db_Owner'))= 0)
 BEGIN
																																															Print ''
																																															Print ''
																																															Print '=================================================================='
		
																																															Print ''
																																															Print '		Keine ausreichenden Berechtigungen auf der Datenbank!!!'	
																																															Print '		Bitte führen Sie das Skript als SysAdmin oder db_owner aus'
																																															Print ''
																																															Print '=================================================================='
																																															Print ''
																																															Print ''	
																																															Print ''
																																															Print ''
																																															RAISERROR('Nicht genügend Berechtigungen!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion Berechtigungsprüfung

--#region SQL-Server Versionsprüfung
DECLARE @serverVersion INT
SELECT @serverVersion = CONVERT(INTEGER, CONVERT(FLOAT, CONVERT(VARCHAR(3), SERVERPROPERTY('productversion'))))
	IF @serverVersion < 10
	
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print '		Die SQL-Server-Version 2005 u. älter wird nicht mehr unterstützt!!!'	
																																															Print '		Bitte migrieren Sie auf eine aktuelle Version'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
																																															Print ''
																																															Print ''
																																															RAISERROR('Nicht unterstützte SQL-Server-Version!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region Datenbankmodel Versionsprüfung 206 (letzte Version 2020)
IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 206 OR (Minor=206 AND Build < 100)))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Der Versionsunterschied ist zu groß!!!'	
																																															Print '		Bitte führen Sie DbScript_2020.sql aus dem Unterordner OptionalScripts aus '
																																															Print '		bevor Sie DBScript.sql ausführen      '
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''																																															Print''
																																															Print''
																																															RAISERROR(N'Datenbankversion zu alt!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#region Datenbankmodel Versionsprüfung 211
--#region Datenbankmodel Versionsprüfung 221
IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major > 4 OR (Major = 4 AND (Minor >= 221))))
BEGIN
																																															Print ''
																																															Print ''
																																															Print '=============================================='		
																																															Print ''
																																															Print '		Veraltete Skriptversion!!!'	
																																															Print '		Bitte führen Sie DbScript_2022.sql bzw. DbScript.sql aus.'
																																															Print ''
																																															Print '=============================================='
																																															Print ''
																																															Print ''																																															Print''
																																															Print''
																																															RAISERROR(N'Skriptversion veraltet!!!', 20, -1) WITH LOG
																																															SET NOEXEC ON
END
GO
--#endregion

--#endregion --------------------- Ende Versions und Datenbankprüfungen ----

--#region --------------------- HilfsProzeduren -------------------------

--#region Standards setzen
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
--#endregion

--#region DropIndexByTable
IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropIndexByTable'))
BEGIN
	DROP PROCEDURE dbo.DropIndexByTable
END
go
CREATE PROCEDURE dbo.DropIndexByTable 
	@tablename varchar(100)
AS
BEGIN

DECLARE @ConstraintName VARCHAR(100) 
DECLARE cview_cursor CURSOR FOR 
	SELECT so.name FROM sysobjects so JOIN sysconstraints sc
		ON so.id = sc.constid  
		WHERE object_name(so.parent_obj) = @tablename
		AND so.xtype = 'UQ'

OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @ConstraintName 
	WHILE @@FETCH_STATUS = 0 
	BEGIN  
		Print 'Dropping Constraint ' + @ConstraintName + '...'
		declare @ccmd varchar(100)
	
		select @ccmd='ALTER TABLE '+@tablename+' DROP CONSTRAINT '+@ConstraintName
		exec (@ccmd)

		FETCH NEXT FROM cview_cursor 
		INTO @ConstraintName 
	END 
CLOSE cview_cursor 
DEALLOCATE cview_cursor 


DECLARE @IndexName VARCHAR(100) 
DECLARE view_cursor CURSOR FOR
		SELECT  i.name AS IndexName 
		FROM sysindexes AS i 
		WHERE OBJECT_NAME( i.id ) = @tablename AND NOT ([Status]&0x800)=0x800 AND  not i.name LIKE '_WA_Sys%' AND impid = 0
	
OPEN view_cursor 
	FETCH NEXT FROM view_cursor 
	INTO @IndexName 
	WHILE @@FETCH_STATUS = 0 
	BEGIN  
		Print @IndexName
		declare @cmd varchar(100)
		select @cmd='DROP INDEX ' +@tablename+ '.'+ @IndexName
		exec (@cmd)

		FETCH NEXT FROM view_cursor 
		INTO @IndexName 
	END 
CLOSE view_cursor 
DEALLOCATE view_cursor 


END
GO
--#endregion

--#region PrepareUniqueColumnIndex
IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].PrepareUniqueColumnIndex'))
BEGIN
	DROP PROCEDURE dbo.PrepareUniqueColumnIndex 
END
Go
CREATE PROCEDURE dbo.PrepareUniqueColumnIndex 
	(@tablename varchar(100),
	@columnname varchar(100),
	@primarykey varchar(100),
	@type varchar(100))
AS
BEGIN
	DECLARE @cmd NVARCHAR(MAX);
	SELECT @cmd='UPDATE '+@tablename+' SET '+@columnname+' = b.Neu 
		FROM '+ 
		@tablename+' as a inner join (
				SELECT 
					CAST
					(
					(CAST(ROW_NUMBER() OVER 
						(PARTITION BY '+ 
		@columnname+' ORDER BY LM) 
					AS NVARCHAR(2)) +COALESCE('+ 
		@columnname+',''#NAME#'')) AS '+@type+') AS neu
					,ROW_NUMBER() OVER (PARTITION BY 
		'+@columnname+' ORDER BY lm) AS nummer,
		'+@primarykey+'
				FROM 
		'+@tablename+'
				) AS b 
	ON 
		a.'+@primarykey+'=b.'+@primarykey+'
	WHERE b.nummer>1';
	EXECUTE SP_EXECUTESQL @cmd
END
GO
--#endregion

--#region DropDefaultConstraint
IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'DropDefaultConstraint'))
	DROP PROCEDURE dbo.DropDefaultConstraint 
GO
CREATE PROCEDURE dbo.DropDefaultConstraint
	@tablename varchar(100),
	@columnname varchar(100)
AS
BEGIN
	DECLARE @defname VARCHAR(100)
	DECLARE @cmd VARCHAR(200)

	SELECT @defname = Name
	FROM sys.default_constraints dc
	WHERE	OBJECT_NAME(parent_object_id) = @tablename
	AND		COL_NAME(parent_object_id, parent_column_id) = @columnname
	
	IF (NOT @defname IS NULL)
	BEGIN
			SELECT @cmd='ALTER TABLE '+ @tablename + ' DROP CONSTRAINT ' + @defname
			EXEC (@cmd)
			PRINT @defname + ' dropped'
	END

	IF EXISTS (SELECT TOP 1 S.NAME FROM SYS.SYSOBJECTS S JOIN SYS.SYSCOLUMNS C ON S.ID = C.CDEFAULT
				WHERE C.ID = OBJECT_ID( @tablename) AND C.NAME =  @columnname)
	BEGIN
		SELECT @cmd ='sp_unbindefault ''' +  @tablename + '.' + @columnname + ''''
		EXEC (@cmd)
		PRINT @columnname + ' unbound'
	END
END
GO
--#endregion

--#region DropColumn
IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropColumn'))
BEGIN
	DROP PROCEDURE dbo.DropColumn 
END
GO
CREATE PROCEDURE dbo.DropColumn 
	@tablename varchar(100),
	@columnname varchar(100)
AS
BEGIN

IF EXISTS (SELECT * FROM sysColumns c INNER JOIN sysobjects o on c.id = o.id 
	WHERE c.name = @columnname AND o.id = OBJECT_ID(N'[dbo].[' + @tablename + ']'))	

	BEGIN
		--TODO: Ggf. Index entf.
		declare @defname varchar(100)
		declare @cmd varchar(100)
		SELECT @defname = name 

		FROM sysobjects so JOIN sysconstraints sc ON so.id = sc.constid 
			WHERE object_name(so.parent_obj) =  @tablename
				AND so.xtype = 'D'
				AND sc.colid = 	(SELECT colid FROM syscolumns 
								WHERE id = OBJECT_ID(N'[dbo].[' + @tablename + ']') AND name = @columnname)

		SELECT @cmd='alter table ['+ @tablename + '] drop constraint ' + @defname
		EXEC (@cmd)
			
		IF EXISTS (SELECT TOP 1 S.NAME FROM SYS.SYSOBJECTS S JOIN SYS.SYSCOLUMNS C ON S.ID = C.CDEFAULT
			WHERE C.ID = OBJECT_ID(N'[dbo].[' + @tablename + ']') AND C.NAME =  @columnname)
		BEGIN

			SELECT @cmd ='sp_unbindefault ''[' +  @tablename + '].' + @columnname + ''''
			EXEC (@cmd)
		END
		
		SELECT @cmd='alter table ['+@tablename+ '] drop COLUMN [' + @columnname + ']'
		EXEC (@cmd)
		print('Column '+@columnname+' dropped!')
	END
END
GO

--#endregion

--Stored Procedure zum Löschen von Rollen, die vorher allerdings alle Member aus de Rolle entfernt
--#region DropRoleWithDropRoleMember

IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))
BEGIN
	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
END
GO
CREATE PROCEDURE dbo.DropRoleWithDropRoleMember 
	@role varchar(100)
AS 

BEGIN
	DECLARE @RoleName sysname
	set @RoleName = @role
	IF  EXISTS (SELECT * FROM dbo.sysusers WHERE  name = @RoleName AND issqlrole = 1)
	Begin
 
      DECLARE @RoleMemberName sysname
      /* Cursor to Loop in for Each Member have the Role Privilege AND Drop RoleMember */
      DECLARE Member_Cursor CURSOR FOR
      select [name]
      from dbo.sysusers
      WHERE  uid in (
            select memberuid
            from dbo.sysmembers
            WHERE  groupuid in (
                  select uid
                  FROM dbo.sysusers WHERE  [name] = @RoleName AND issqlrole = 1))
 
      OPEN Member_Cursor;
 
      FETCH NEXT FROM Member_Cursor
      into @RoleMemberName
 
      WHILE @@FETCH_STATUS = 0
      BEGIN
 
            exec sp_droprolemember @rolename=@RoleName, @membername= @RoleMemberName
 
            FETCH NEXT FROM Member_Cursor
            into @RoleMemberName
      END;
 
      CLOSE Member_Cursor;
      DEALLOCATE Member_Cursor;
      /* End Of Cursor */
 
	END
	
	/* Checking If Role Name Exists In Database */
	IF  EXISTS (SELECT * FROM dbo.sysusers WHERE  name = @RoleName)
		EXEC sp_droprole @rolename = @RoleName
	
END
go
--#endregion


--#endregion --------------------- Ende HilfsProzeduren --------------------

--------------------- Begin Änderungsblock --------------------
--------------------- Scripterstelldatum : 30.12.2020 ---------
--------------------- Datenbankänderungen ab hier -------------
--------------------- möglichst mit regions umschließen -------

--#region ----------- 4.206.x Release Übertrag ----------------

-- Platzhalter für 4.206.x Release Übertrag aus CreateDB_2020.sql

--#region 2020-01-05
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.fn_GetNeededBasicCastByProduction') AND xtype = 'IF') DROP Function dbo.fn_GetNeededBasicCastByProduction
GO
CREATE FUNCTION dbo.fn_GetNeededBasicCastByProduction (
		@productionId AS INT, 
		@date AS DATE,
		@activityTypeId AS INT,
		@understudyPosition AS INT, 
		@personIds IdFilterTable READONLY,
		@rolePermissions IdFilterTable READONLY)
RETURNS TABLE
AS
  RETURN
  (
  
  SELECT
    bc.RoleId, bc.PersonId, need.IsMandatory
  FROM Roles r
	 INNER JOIN (SELECT ChildProductionId FROM ProductionTimeFlow WHERE ProductionId = @productionId AND ChildProductionId IS NOT NULL UNION SELECT @productionId ) AS p
		 ON r.ProductionId = p.ChildProductionId
	INNER JOIN BasicCast bc ON r.RoleId = bc.RoleId
	INNER JOIN CastRules AS need ON r.RoleTypeId = need.RoleTypeId 
 WHERE 
	bc.UnderstudyPosition < @understudyPosition 
	AND (bc.StartDate <= @date OR bc.StartDate IS NULL) AND (bc.EndDate >= @date OR bc.EndDate IS NULL)
	AND bc.PersonId IN (SELECT Id FROM @personIds)
	AND need.ActivityTypeId = @activityTypeId
	AND r.OwnerGroupId IN (SELECT Id FROM @rolePermissions)
  )
GO
--#endregion (2020-01-05)


--#endregion (SH 2021-01-18 [MergeDoubletten] - Update PersonFieldData entfernt, da dies jetzt im Code gemacht wird)

--#region 2021-02-10
GRANT SELECT, UPDATE, INSERT, DELETE ON AbProjectTaskDependencies_Update TO public
GRANT SELECT, UPDATE, INSERT, DELETE ON AbProjectTasks_Update TO public
GRANT SELECT, UPDATE, INSERT, DELETE ON AbProjectTaskMembers_Update TO PUBLIC
GO
--#endregion

--#endregion--------- (4.206.x Release Übertrag) --------------

--#region ----------- 4.211.x ---------------------------------

--#region DH 2020-12-18 Gesprächsnotizenberechtigungen

--#region AbPersonalNotizen
ALTER VIEW [dbo].[AbPersonalNotizen]
AS
	SELECT
		pm.*
	FROM
		PersonMemo pm
		WHERE EXISTS (
			SELECT *
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId = p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				    p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&1024 = 1024 
				AND Username = CURRENT_USER
				AND pm.OwnerGroupId = pp.OwnerGroupId 
				AND pm.PersonId = pp.PersonId
					)
GO
--#endregion AbPersonalNotizen
--#region AbPersonalNotizen_Update
ALTER VIEW [dbo].[AbPersonalNotizen_Update]
AS
	SELECT *
	FROM PersonMemo pm	
		WHERE EXISTS (
			SELECT *
			FROM
				PersonPermissions AS pp
				INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				    p.PermissionArea = 0
				AND p.OptionsFlag&pp.OptionsFlag&1024 = 1024 
				AND pp.HasWritePermission&p.HasWritePermission&1=1
				AND Username = CURRENT_USER
				AND pm.OwnerGroupId=p.OwnerGroupId
				AND pm.PersonId = pp.PersonId
					)
WITH CHECK OPTION
GO
--#endregion AbPersonalNotizen_Update

--#region Permission ergänzen
IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 211 OR (Minor=211 AND Build < 3)))))
BEGIN
UPDATE P
SET Optionsflag=Optionsflag+1024 FROM Permissions p WHERE p.PermissionArea=0;
UPDATE P
SET Optionsflag=Optionsflag+1024 FROM PersonPermissions p;	
END
GO 
--#endregion Permission ergänzen

--#endregion DH 2020-12-18 Gesprächsnotizenberechtigungen

--#region SH 2020-12-31 Tabelle ActivityStatuses anlegen, mit Daten befüllen und FK zu Activities

IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='ActivityStatuses')
BEGIN

	PRINT 'Creating ActivityStatuses...'
    
	CREATE TABLE dbo.ActivityStatuses(
		ActivityStatusId INT IDENTITY(1,1) NOT NULL,
		[Name] VARCHAR(25) NOT NULL,
		[PrintName] VARCHAR(25) NULL,
		[Sort] SMALLINT NOT NULL CONSTRAINT DF_ActivityStatuses_Sort DEFAULT 0,
		[StatusType] SMALLINT NOT NULL CONSTRAINT DF_ActivityStatuses_StatusType DEFAULT 10, --normal
		[ForeColor] INT NULL,
		[LM] SMALLDATETIME NOT NULL CONSTRAINT DF_ActivityStatuses_LM DEFAULT GETDATE(),
		[UM] INT NULL,
		[LC] SMALLDATETIME NOT NULL CONSTRAINT DF_ActivityStatuses_LC DEFAULT GETDATE(),
		[UC] INT NULL,
		CONSTRAINT PK_ActivityStatuses PRIMARY KEY CLUSTERED (ActivityStatusId) ON [PRIMARY]
    ) ON [PRIMARY]
	GRANT SELECT ON ActivityStatuses TO [public]
	GRANT INSERT, UPDATE, DELETE ON ActivityStatuses TO [DispoAdmin]

	PRINT 'Adding default ActivityStatuses...'

	DECLARE @country VARCHAR(20)
	SELECT @country = DataValue FROM Settings WHERE Section = 'Adresse' AND KeyName = 'Country'
	IF @country = 'FI'
		BEGIN--Finnisch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor, Sort)
			VALUES
				(-3, 'cancelled (external)', -3, -7667712, 35), --canceledExtern
				(-1, 'peruutettu', -1, -65536, 25), --canceled
				( 4, 'vapaaehtoinen', 4, NULL, 5), --optional
				( 6, 'vahvistamaton', 6, NULL, 10), --unconfirmed
				(10, 'normaali', 10, NULL, 15), --normal
				(15, 'kiinteä', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
					(-2, ''cancelled request'', -2, -47872, 30), --canceledrequest
					( 2, ''request'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END
	ELSE IF @country = 'EN'
		BEGIN--Englisch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor, Sort)
			VALUES
				(-3, 'cancelled (external)', -3, -7667712, 35), --canceledExtern
				(-1, 'canceled', -1, -65536, 25), --canceled
				( 4, 'optional', 4, NULL, 5), --optional
				( 6, 'unconfirmed', 6, NULL, 10), --unconfirmed
				(10, 'regular', 10, NULL, 15), --normal
				(15, 'fixed', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
					(-2, ''cancelled request'', -2, -47872, 30), --canceledrequest
					( 2, ''request'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END
	ELSE IF @country = 'F' OR @country = 'BE'
		BEGIN --Französisch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor, Sort)
			VALUES
				(-3, 'annulé (externe)', -3, -7667712, 35), --canceledExtern
				(-1, 'ausgefallen', -1, -65536, 25), --canceled

				( 4, 'en option', 4, NULL, 5), --optional
				( 6, 'non confirmé', 6, NULL, 10), --unconfirmed
				(10, 'normal', 10, NULL, 15), --normal
				(15, 'fixe', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
						(-2, ''demande annulée'', -2, -47872, 30), --canceledrequest
						( 2, ''demande'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END
	ELSE IF @country = 'NL'
		BEGIN --Niederländisch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor, Sort)
			VALUES
				(-3, 'afgezegd (extern)', -3, -7667712, 35), --canceledExtern
				(-1, 'ausgefallen', -1, -65536, 25), --canceled
				( 4, 'optioneel', 4, NULL, 5), --optional
				( 6, 'onbevestigd', 6, NULL, 10), --unconfirmed
				(10, 'normaal', 10, NULL, 15), --normal
				(15, 'vaststaand', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
						(-2, ''geannuleerde aanvraag'', -2, -47872, 30), --canceledrequest
						( 2, ''aanvraag'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END
	ELSE IF @country = 'CZ'
		BEGIN --Tschechisch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor, Sort)
			VALUES
				(-3, 'od?eknuto (extern?)', -3, -7667712, 35), --canceledExtern
				(-1, 'vypadnout', -1, -65536, 25), --canceled
				( 4, 'na výb?r', 4, NULL, 5), --optional
				( 6, 'zamýšleno', 6, NULL, 10), --unconfirmed
				(10, 'jistý', 10, NULL, 15), --normal
				(15, 'na pevno', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
						(-2, ''stornované dotazy'', -2, -47872, 30), --canceledrequest
						( 2, ''dotaz'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END
	ELSE
		BEGIN --Deutsch
			SET IDENTITY_INSERT ActivityStatuses ON
			INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
			VALUES
				(-3, 'abgesagt (extern)', -3, -7667712, 35), --canceledExtern
				(-1, 'ausgefallen', -1, -65536, 25), --canceled
				( 4, 'optional', 4, NULL, 5), --optional
				( 6, 'unbestätigt', 6, NULL, 10), --unconfirmed
				(10, 'normal', 10, NULL, 15), --normal
				(15, 'feststehend', 15, NULL, 20)  --fixed
			EXEC('IF EXISTS (SELECT * FROM Activities WHERE Status IN (-2, 2)) 
				BEGIN
					INSERT INTO ActivityStatuses (ActivityStatusId, Name, StatusType, ForeColor,Sort)
					VALUES
						(-2, ''stornierte Anfrage'', -2, -47872, 30), --canceledrequest
						( 2, ''Anfrage'', 2, NULL, 0) --request
				END')
			SET IDENTITY_INSERT ActivityStatuses OFF
		END

	EXEC('UPDATE Activities SET Status = 10 WHERE Status = 0')

	ALTER TABLE Activities DROP CONSTRAINT DF_Activities_Status
	DROP INDEX [IX_Activities_RehearsalCount] ON Activities

	EXEC sp_rename 'Activities.Status', 'ActivityStatusId', 'COLUMN';

	ALTER TABLE Activities ALTER COLUMN [ActivityStatusId] INT NOT NULL

	CREATE NONCLUSTERED INDEX [IX_Activities_RehearsalCount] ON [dbo].[Activities] (
		[VariantId] ASC,
		[ProductionId] ASC,
		[ActivityTypeId] ASC,
		[Date] ASC, [StartTime]
	) INCLUDE ([ActivityStatusId]) ON [PRIMARY]
	

	ALTER TABLE Activities WITH CHECK ADD CONSTRAINT FK_Activities_ActivityStatuses FOREIGN KEY([ActivityStatusId])
	REFERENCES ActivityStatuses (ActivityStatusId)
	ALTER TABLE Activities CHECK CONSTRAINT FK_Activities_ActivityStatuses

	UPDATE ActivityStatuses SET PrintName = Name
END
GO

--#endregion SH 2020-12-31 Tabelle ActivityStatuses anlegen, mit Daten befüllen und FK zu Activities

--#region SH 2021-01-04 Views und Procedures aktualisieren die Status verwenden

--
-- Alter Procedure: dbo.GetCastCountByContract
--

ALTER PROCEDURE [dbo].[GetCastCountByContract]
		@ContractId INT, @ActivityStart DATE = NULL, @ActivityEnd DATE = NULL
AS
BEGIN
	SELECT COUNT(B.RoleId) FROM Cast AS B
	INNER JOIN Activities AS A ON A.ActivityId = B.ActivityId
	INNER JOIN ActivityStatuses [as] ON A.ActivityStatusId = [as].ActivityStatusId
	AND B.IsCanceled = 0
	AND [as].[StatusType] >= 0
	AND B.ContractId = @ContractId
	AND (@ActivityStart IS NULL OR a.Date >= @ActivityStart)
	AND (@ActivityEnd IS NULL OR a.Date <= @ActivityEnd)
END
GO

--
-- Alter Procedure: dbo.GetCastCountByContractAndProduction
--

ALTER PROCEDURE dbo.GetCastCountByContractAndProduction
		 @contractId INT, @productionId INT, @untilDate DATE, @activityTypeIds IdFilterTable READONLY 
AS
BEGIN
	SELECT
		Count(DISTINCT a.ActivityId)
	FROM
		Cast AS c
		INNER JOIN Activities AS A ON A.ActivityId = c.ActivityId
		INNER JOIN ActivityStatuses [as] ON A.ActivityStatusId = [as].ActivityStatusId
		INNER JOIN @activityTypeIds AS atFilter ON A.ActivityTypeId = atFilter.Id
	WHERE
		a.Date <= @untilDate
		AND a.ProductionId = @productionId
		AND c.IsCanceled = 0
		AND a.VariantId = 0
		AND c.ContractId = @ContractId
		AND (c.Creditable > 0 OR (c.Creditable IS NULL AND [as].[StatusType] >= 0))
END
GO

--
-- Alter View: dbo.CastActiveties
--

ALTER VIEW [dbo].[CastActiveties] 
AS
	SELECT	ac.Date, ac.StartTime, ac.EndTime, ac.ProductionId, ac.LocationId, ac.ActivityTypeId, ac.ArtisticNote, at.KatNr, ac.ActivityStatusId, ac.VariantId, ca.*, st.IsInactive
	FROM	Activities				AS ac
			INNER JOIN ActivityTypes		AS at	ON ac.ActivityTypeId = at.ActivityTypeId
			INNER JOIN Seasons AS s	ON ac.Date <= s.EndDate AND ac.Date >= s.StartDate
			INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
			INNER JOIN Users			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Productions			AS p	ON ac.ProductionId = p.ProductionId
			LEFT JOIN Permissions		AS uga	ON p.OwnerGroupId = uga.OwnerGroupId AND ua.UserID = uga.UserID AND uga.PermissionArea = 2
			INNER JOIN Cast	AS ca	ON ac.ActivityId = ca.ActivityId
			LEFT  JOIN Roles		AS ro	ON ca.RoleId = ro.RoleId
			INNER  JOIN OwnerGroups			AS g	ON g.OwnerGroupId = ro.OwnerGroupId	
			INNER  JOIN Permissions		AS ugc	ON G.OwnerGroupId = ugc.OwnerGroupId AND ugc.UserID = ua.UserID AND ugc.PermissionArea = 4
			LEFT JOIN Productions			AS st	ON ac.ProductionId=st.ProductionId 
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.IsSecret = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.IsSecret = 0 OR (Ugc.OptionsFlag & 1 = 1)))
GO

--
-- Alter Procedure: dbo.GetPossibleCastByPeriodInternal
--

ALTER PROCEDURE [dbo].[GetPossibleCastByPeriodInternal]
	@start DATE,
	@end DATE,
	@personIds IdFilterTable READONLY,
	@activityTypeIds IdFilterTable READONLY,
	@variantIds IdFilterTable READONLY,
	@understudyPosition TINYINT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @permissionPeriodStart DATE
	DECLARE @permissionPeriodEnd DATE

	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId 

	IF (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	DECLARE @rolePermissions IdFilterTable 
	INSERT INTO @rolePermissions SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 4 

	IF EXISTS(SELECT * FROM @activityTypeIds)
		BEGIN
		--Mit Activitytype Filter
		SELECT DISTINCT d.PersonId, d.ActivityId, c.CastId, d.RoleId, IsMandatory
			FROM (
					SELECT DISTINCT a.ActivityId, b.RoleId, b.IsMandatory, b.PersonId
					FROM Activities AS a 
						INNER JOIN ActivityStatuses [as] ON a.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN Productions AS p ON a.ProductionId = p.ProductionId
						CROSS APPLY dbo.fn_GetNeededBasicCastByProduction(a.ProductionId, a.Date, a.ActivityTypeId, @understudyPosition, @personIds, @rolePermissions) AS b
					WHERE Date BETWEEN @start AND @end AND VariantId IN (SELECT id FROM @variantIds) AND [as].StatusType >= 0
						AND a.ActivityTypeId IN (SELECT Id FROM @activityTypeIds)
						AND p.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 2)
				) AS d
				LEFT JOIN ( SELECT * 
							FROM Cast
							WHERE IsCanceled = 0 AND IsCover = 0) AS c 
					ON d.ActivityId = c.ActivityId AND d.RoleId = c.RoleId
				WHERE c.CastId IS NULL OR c.PersonId <> d.PersonId
				ORDER BY d.PersonId, d.ActivityId
		END 
	ELSE
		BEGIN
		--Ohne Activitytype Filter
			SELECT DISTINCT d.PersonId, d.ActivityId, c.CastId, d.RoleId, IsMandatory
			FROM (
					SELECT DISTINCT a.ActivityId, b.RoleId, b.IsMandatory, b.PersonId
					FROM Activities AS a 
						INNER JOIN ActivityStatuses [as] ON a.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN Productions AS p ON a.ProductionId = p.ProductionId
						CROSS APPLY dbo.fn_GetNeededBasicCastByProduction(a.ProductionId, a.Date, a.ActivityTypeId, @understudyPosition, @personIds, @rolePermissions) as b
					WHERE Date BETWEEN @start AND @end AND VariantId IN (SELECT id FROM @variantIds) AND [as].StatusType >= 0
						AND p.OwnerGroupId IN (SELECT OwnerGroupId FROM Permissions WHERE UserId = @userId AND PermissionArea = 2)
				) AS d
				LEFT JOIN ( SELECT * 
							FROM Cast
							WHERE IsCanceled = 0 AND IsCover = 0) AS c 
					ON d.ActivityId = c.ActivityId AND d.RoleId = c.RoleId
				WHERE c.CastId IS NULL OR c.PersonId <> d.PersonId
				ORDER BY d.PersonId, d.ActivityId
		END
END
GO

--
-- Alter View: dbo.AbActivities_Update
--

ALTER VIEW dbo.AbActivities_Update
	AS
	SELECT      a.*
	FROM        Activities AS a
	WHERE dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.ActivityStatusId, a.UC) = 1
WITH CHECK OPTION
GO

--
-- Alter View: dbo.AbActivitiesSubscriptions_Update
--

ALTER VIEW dbo.AbActivitiesSubscriptions_Update
	AS
	SELECT      *
	FROM       ActivitySubscriptions
	WHERE ActivitySubscriptions.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.ActivityStatusId, a.UC) = 1 OR IS_MEMBER('Vorverkauf ändern') = 1)
WITH CHECK OPTION
GO

--
-- Alter View: dbo.AbActivityScenes_Update
--

ALTER VIEW dbo.AbActivityScenes_Update
	AS
	SELECT     *
	FROM       ActivityScenes
	WHERE ActivityScenes.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.ActivityStatusId, a.UC) = 1)
WITH CHECK OPTION
GO

--
-- Alter View: dbo.AbActivityDetails_Update
--

ALTER VIEW dbo.AbActivityDetails_Update
	AS
	SELECT      *
	FROM       ActivityDetails AS AD 
	WHERE ad.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.ActivityStatusId, a.UC) = 1 OR IS_MEMBER('Vorverkauf ändern') = 1 OR IS_MEMBER('CostsWrite') = 1)
WITH CHECK OPTION
GO

--
-- Alter View: dbo.AbJourneyTimetabl_Update
--

ALTER VIEW dbo.AbJourneyTimetabl_Update
	AS
	SELECT      *
	FROM       JourneyTimetables AS AD 
	WHERE ad.ActivityId IN (SELECT ActivityId FROM Activities AS a WHERE  dbo.IsActivityWritable(a.Date, a.ProductionId, a.ActivityTypeId, a.ActivityStatusId, a.UC) = 1)

	WITH CHECK OPTION
GO

--
-- Alter Procedure: dbo.AbBuenenProbenNr
--

ALTER PROCEDURE [dbo].[AbBuenenProbenNr]
@lSnr int,
@DDatum  Datetime, 
@dVon  Datetime, 
@dspzStart  Datetime, 
@lZrNr As int
As

SELECT
	Count(*) AS [Anz]
FROM
	Activities a
	INNER JOIN ActivityTypes at ON a.ActivityTypeId = at.ActivityTypeId
	INNER JOIN ActivityStatuses [as] ON a.ActivityStatusId = [as].ActivityStatusId
WHERE
	a.ProductionId= @lSnr
	AND [as].[StatusType] >= 0
	AND a.[VariantId] = 0
	AND a.LocationId= @lZrNr
	AND at.Category = 800 --Proben
	AND (
		(a.Date < @DDatum  and a.Date>= @dspzStart)
		OR (a.Date= @DDatum AND  CONVERT(varchar(5), a.StartTime, 8)<= CONVERT(varchar(5), @dvon, 8))
	)
GO

--
-- Alter TableValuedFunction: dbo.GetActivityTypeRehearsalNumbers
--

ALTER FUNCTION [dbo].[GetActivityTypeRehearsalNumbers](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT Row_Number() OVER (PARTITION BY a.ActivityTypeId, ProductionId ORDER BY Date, StartTime) AS RowNum, ActivityId, Date 
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId 
				INNER JOIN ActivityStatuses [as] ON A.ActivityStatusId = [as].ActivityStatusId
		WHERE AT.LfdNr = 1 AND Date BETWEEN @start AND @end AND [as].[StatusType] >= 3 AND VariantId = 0)
GO

--
-- Alter Procedure: dbo.GetActivityPerformanceNumber
--

ALTER PROCEDURE dbo.GetActivityPerformanceNumber(
		@productionId INT,
		@seasonStart DATE,
		@date DATE,
		@startTime SMALLDATETIME)
	AS
		SELECT COUNT(*) AS Anz
		FROM Activities AS a
			INNER JOIN ActivityTypes AS At ON a.ActivityTypeId = At.ActivityTypeId
			INNER JOIN ActivityStatuses [as] ON a.ActivityStatusId = [as].ActivityStatusId
		WHERE a.ProductionId = @productionId 
			AND Category >= 2000
			AND ((a.Date < @date AND a.Date >= @seasonStart) OR (a.Date = @date AND StartTime <= @startTime))
			AND [as].[StatusType] >= 3
			AND VariantId = 0
GO

--
-- Alter View: dbo.Extern_Activities
--

ALTER VIEW dbo.Extern_Activities
AS
	SELECT	
	ActivityId,
	Date,
	CAST(Date AS DATETIME) + CAST(StartTime AS DATETIME) AS [Start],
	PrintStartTime,
	CASE WHEN StartTime <= EndTime THEN CAST(Date AS DATETIME) + CAST(EndTime AS DATETIME) 
		ELSE DATEADD(DAY,1 , CAST(Date AS DATETIME)) + CAST(EndTime AS DATETIME) END AS [End],
	PrintEndTime, 
	act.ProductionId,
	CASE WHEN LEFT(ISNULL(p.Title,''),1) = '*' THEN ArtisticNote ELSE p.Title END AS Title,
	act.LocationId AS StageId,
	lo.Name AS StageName,
	lo.ShortName AS StageShortName,
	act.ActivityTypeId,
	att.Name AS ActivityTypeName,
	att.ShortName AS ActivityTypeShortName,
	CASE WHEN att.Category >= 2000 THEN 1 ELSE 0 END AS IsPerformance,
	CASE WHEN att.Category >= 1000 THEN 1 ELSE 0 END AS IsPublicEvent,
	CASE WHEN [as].StatusType < 0 THEN 1 ELSE 0 END AS IsCanceled,
	CASE WHEN [as].StatusType = 4 THEN 1 ELSE 0 END AS IsOptional,
	CASE WHEN [as].StatusType IN (2, 6) THEN 1 ELSE 0 END AS IsUnconfirmed,
	CASE WHEN LEFT(ISNULL(p.Title,''),1) = '*' THEN NULL ELSE ArtisticNote END AS Note,
	TechnicalNote,
	LinkedActivityId,
	act.LM AS LastModified
	FROM			Activities act
		INNER JOIN	Seasons				AS s    ON act.Date <= s.EndDate AND act.Date >= s.StartDate
		INNER JOIN	SeasonPermissions   AS us   ON s.SeasonId   = us.SeasonId
		INNER JOIN	Users				AS u    ON us.UserId = u.UserID
		INNER JOIN	Productions         AS p    ON act.ProductionId = p.ProductionId
		INNER JOIN	ActivityTypes       AS att  ON act.ActivityTypeId = att.ActivityTypeId
		INNER JOIN  ActivityStatuses    AS [as] ON act.ActivityStatusId = [as].ActivityStatusId
		INNER JOIN	Locations           AS lo   ON act.LocationId = lo.LocationId
	WHERE
		u.UserName  = CURRENT_USER AND act.IsSecret = 0 AND VariantId = 0
GO

--
-- Alter Procedure: dbo.AbProbenNr
--

ALTER PROCEDURE [dbo].[AbProbenNr]
	@lSnr INT,
	@DDatum DATE,
	@dVon  SMALLDATETIME,
	@dspzStart DATE,
	@lArt As INT
AS
	SELECT Count(*) AS Anz
	FROM Activities
	INNER JOIN ActivityStatuses [as] ON Activities.ActivityStatusId = [as].ActivityStatusId
	WHERE ProductionId = @lSnr
		AND [as].[StatusType] >= 0
		AND VariantId = 0
		AND ActivityTypeId = @lArt 
		AND Date >= @dspzStart
		AND (Date < @DDatum OR  (Date = @DDatum AND StartTime <= @dvon))
GO

--
-- Alter TableValuedFunction: dbo.GetActivityPerformanceNumbers
--

ALTER FUNCTION [dbo].[GetActivityPerformanceNumbers](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT Row_Number() OVER (PARTITION BY a.ProductionId ORDER BY Date, StartTime) AS RowNum, ActivityId, Date 
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId
				INNER JOIN ActivityStatuses [as] ON A.ActivityStatusId = [as].ActivityStatusId
			WHERE Category >= 2000 
				AND Date BETWEEN @start AND @end 
				AND [as].[StatusType] >= 3
				AND VariantId = 0)
GO

--
-- Alter TableValuedFunction: dbo.GetActivityPerformanceNumbersAllSeasons
--

ALTER FUNCTION [dbo].[GetActivityPerformanceNumbersAllSeasons](
		@start DATE,
		@end DATE)
RETURNS TABLE
AS
	RETURN (SELECT * FROM (SELECT Row_Number() OVER (PARTITION BY a.ProductionId ORDER BY Date, StartTime)  + ISNULL(pd.NumberOfPerformancesBefore, 0)  AS RowNum, ActivityId, Date
			FROM Activities AS A
				INNER JOIN ActivityTypes AS AT ON AT.ActivityTypeId = A.ActivityTypeId
				INNER JOIN ActivityStatuses [as] ON A.ActivityStatusId = [as].ActivityStatusId
				LEFT JOIN ProductionDetails AS PD ON Pd.ProductionId = A.ProductionId
			WHERE Category >= 2000
				AND Date <= @end
				AND [as].[StatusType] >= 3
				AND VariantId = 0
			) AS subA WHERE Date BETWEEN @start AND @end)
GO

--
-- Alter View: dbo.AbCastActiveties
--

ALTER VIEW [dbo].[AbCastActiveties]
AS
	SELECT	ac.Date, ac.StartTime, ac.EndTime, ac.ProductionId, ac.LocationId, ac.ActivityTypeId, ac.ArtisticNote, ac.[ActivityStatusId], ca.*,
	        ro.RoleId AS Role_RoleId, ro.RoleTypeId AS Role_TaskAreaId,
	        ro.RoleCategoryId AS Role_RoleCategoryId, ro.OwnerGroupId AS Role_OwnerId, ro.PresseSort AS Role_PressSort, p.IsInactive AS IsInactive, ac.VariantId
	FROM	Activities				AS ac
			INNER JOIN Seasons AS s	ON ac.Date <= s.EndDate AND ac.Date >= s.StartDate
			INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
			INNER JOIN Users			AS ua	ON us.UserId = ua.UserID
			INNER JOIN Productions			AS p	ON ac.ProductionId = p.ProductionId
			INNER JOIN Permissions		AS uga	ON p.OwnerGroupId = uga.OwnerGroupId AND ua.UserID = uga.UserID AND uga.PermissionArea = 2
			INNER JOIN Cast	AS ca	ON ac.ActivityId = ca.ActivityId
			INNER JOIN Roles		AS ro	ON ca.RoleId = ro.RoleId
			INNER JOIN Permissions		AS ugc	ON ro.OwnerGroupId = ugc.OwnerGroupId AND ugc.UserID = ua.UserID AND ugc.PermissionArea = 4
	WHERE
			ua.UserName = CURRENT_USER
			AND  (ac.IsSecret = 0 OR uga.OptionsFlag IS NULL OR uga.OptionsFlag & 1 = 1)
			AND ((ca.IsSecret = 0 OR (Ugc.OptionsFlag & 1 = 1)))
GO


--#endregion SH 2021-01-04 Views und Procedures aktualisieren die Status verwenden

--#region SH 2021-01-05 Spalte Status in ActivityHistory umbenennen

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ActivityHistory') AND [name] = 'ActivityStatusId')
BEGIN
	PRINT('Renaming ActivityHistory.Status to ActivityStatusId...')
	EXEC sp_rename 'ActivityHistory.Status', 'ActivityStatusId', 'COLUMN';
END
GO

--#endregion SH 2021-01-05 Status in ActivityHistory umbenennen

--#region SH 2021-01-06 Spalte ActivityStatus in OwnerGroups umbenennen

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OwnerGroups') AND [name] = 'DefaultActivityStatusId')
BEGIN

	ALTER TABLE OwnerGroups DROP CONSTRAINT DF_OwnerGroups_DefaultActivityStatus

	PRINT('Renaming OwnerGroups.DefaultActivityStatus to DefaultActivityStatusId...')
	EXEC sp_rename 'OwnerGroups.DefaultActivityStatus', 'DefaultActivityStatusId', 'COLUMN';

	EXEC('UPDATE OwnerGroups SET DefaultActivityStatusId = 10 WHERE DefaultActivityStatusId NOT IN (SELECT ActivityStatusId FROM  ActivityStatuses)')

	ALTER TABLE OwnerGroups WITH CHECK ADD CONSTRAINT FK_OwnerGroups_ActivityStatuses FOREIGN KEY([DefaultActivityStatusId])
	REFERENCES ActivityStatuses (ActivityStatusId)
	ALTER TABLE OwnerGroups CHECK CONSTRAINT FK_OwnerGroups_ActivityStatuses	
END
GO


--#endregion SH 2021-01-05 Status in ActivityHistory umbenennen

--#region 2021-01-21 Kontaktbereiche
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='PersonInCategories')
BEGIN

	PRINT 'Creating PersonInCategories...'
    
	CREATE TABLE dbo.PersonInCategories(
		PersonInCategoryId INT IDENTITY(1,1) NOT NULL,
		PersonId INT NOT NULL,
		PersonCategoryId INT NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_PersonInCategories_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_PersonInCategories_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_PersonInCategories PRIMARY KEY CLUSTERED (PersonInCategoryId) ON [PRIMARY]
    ) ON [PRIMARY]
	GRANT SELECT, INSERT, UPDATE, DELETE ON PersonInCategories TO [public]

	CREATE UNIQUE NONCLUSTERED INDEX IX_PersonInCategories_Person_Category ON PersonInCategories (PersonId, PersonCategoryId) ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED INDEX IX_PersonInCategories_Category_Person  ON PersonInCategories (PersonCategoryId, PersonId) ON [PRIMARY]

	ALTER TABLE PersonInCategories WITH CHECK ADD CONSTRAINT FK_PersonInCategories_Persons FOREIGN KEY (PersonId) 
	REFERENCES Persons (PersonId)  ON DELETE CASCADE
	ALTER TABLE PersonInCategories CHECK CONSTRAINT FK_PersonInCategories_Persons
		
	ALTER TABLE PersonInCategories WITH CHECK ADD CONSTRAINT FK_PersonInCategories_PersonCategories FOREIGN KEY (PersonCategoryId) 
	REFERENCES PersonCategories (PersonCategoryId)
	ALTER TABLE PersonInCategories CHECK CONSTRAINT FK_PersonInCategories_PersonCategories


	EXEC('INSERT INTO PersonInCategories (PersonId, PersonCategoryId, LM, UM, LC, UC) SELECT PersonId, PersonCategoryId, LM, UM, LC, UC FROM Persons')
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_Persons_PersonCategories') AND type = 'F') ALTER TABLE dbo.Persons DROP CONSTRAINT FK_Persons_PersonCategories
	ALTER TABLE Persons ALTER COLUMN PersonCategoryId INT NULL
	EXEC sp_rename 'Persons.PersonCategoryId', 'X_PersonCategoryId', 'COLUMN';
END
GO

ALTER VIEW [dbo].[AbPersStatus]
AS 
SELECT PersonStatusId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.Note  ELSE NULL END AS Note,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,

	CASE WHEN z.Formel IN (1, 2) THEN 2  WHEN z.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
	CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
	sr.ApprovalStatus, sr.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, sr.LM, sr.UM, sr.LC, sr.UC,
	p.KeyName, p.OwnerGroupId
FROM PersonStatus AS sr
	INNER JOIN Persons AS p ON sr.PersonId = p.PersonId 
	INNER JOIN PersonStatusTypes AS st ON sr.PersonStatusTypeId = st.PersonStatusTypeId 
	INNER JOIN TimeAccounts AS z ON st.TimeAccountId = z.TimeAccountId
	INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users ON ug.Userid = Users.Userid
WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 
GO

ALTER VIEW [dbo].[AbPersStatusNameList]
AS 
SELECT 
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
	CASE WHEN z.Formel = 1 THEN 2  WHEN z.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
	sr.ApprovalStatus, st.StartDate, st.EndDate, st.StartTime, st.EndTime,
	p.KeyName, p.OwnerGroupId, sr.PersonId
FROM PersonStatus AS sr
	INNER JOIN Persons AS p ON sr.PersonId = p.PersonId 
	INNER JOIN PersonStatus AS st ON sr.PersonStatusId =st.PersonStatusId 
	INNER JOIN PersonStatusTypes AS stt ON sr.PersonStatusTypeId =stt.PersonStatusTypeId 
	INNER JOIN TimeAccounts AS z ON stt.TimeAccountId = z.TimeAccountId
	INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users ON ug.Userid = Users.Userid
WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 
GO

ALTER PROCEDURE [dbo].[GetPersonsInternal]
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowPersonsWithoutRights BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  PersonIds erstellen ***
	IF (@include <> 0) 
	BEGIN
	 CREATE TABLE #PersonsNP (PersonId INT NOT NULL)
	End
	-- *** Berechtigungen des Users für Personen (0) in Temp Tabelle ***
	CREATE TABLE #UserGroupPermissions (OwnerGroupId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #UserGroupPermissions SELECT OwnerGroupId, PermissionArea, OptionsFlag FROM Permissions WHERE  UserId = @userId AND PermissionArea IN (0,1,6)
		
	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten PersonIds in Temp
	
	if (@include <> 0 OR @ShowPersonsWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #PersonsNP SELECT Persons.PersonId FROM Persons '
			IF (@ShowPersonsWithoutRights = 0) 
			BEGIN
				SET @SQLQuery =  @SQLQuery + ' INNER JOIN #UserGroupPermissions AS UG ON UG.OwnerGroupId = Persons.OwnerGroupId AND ug.PermissionArea = 0'
			END
		END								
	ELSE		
		BEGIN
			SET @SQLQuery = 'SELECT persons.* FROM Persons  ' 
		END			
	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
		
		IF (@joins&2 = 2) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN PersonDetails ON Persons.PersonId = PersonDetails.PersonId '

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' WHERE ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + ' ORDER BY ' + @order 

		print @sqlquery
		EXECUTE sp_Executesql @SQLQuery 		
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT persons.* 
								FROM Persons INNER JOIN  #PersonsNP ON Persons.PersonId = #PersonsNP.PersonId'
				
			If (@order IS NOT NULL)
			BEGIN
			IF (@joins&1 = 1)
				SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
				SET @SQLQuery = @SQLQuery  + ' ORDER BY ' + @order 
			END
			print @sqlquery
			EXECUTE sp_Executesql  @SQLQuery
		END

	IF(@include<>0)
	BEGIN
		WITH CTE AS(
			SELECT PP.PersonId
					,MIN(p.OwnerGroupId)  AS BASEOWNER
                    ,MAX(CONVERT(TINYINT,PP.HASWRITEPERMISSION)) AS WRITE
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&1) AS READSECRET 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&2) AS WRITEQUALIFICATIONS
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&4) AS READPERSONDETAILS
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&8) AS WRITEPERSONDETAILS 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&16) AS READPERSONBANKDATA
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&32) AS WRITEPERSONBANKDATA
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&64) AS READPERSONFEENOTES
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&128) AS WRITEPERSONFEENOTES
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&256) AS WRITEPERSONEMPLOYEE
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&512) AS SHOWLINKEDCONTACTS
                    FROM PERSONPERMISSIONS PP  
                           INNER JOIN #UserGroupPermissions P ON PP.OWNERGROUPID=P.OwnerGroupId AND P.PERMISSIONAREA = 0                            
                    WHERE pp.PersonId IN (SELECT PersonId from #PersonsNP)
					GROUP BY pp.PersonId
					
		) SELECT * INTO #includePermissions from cte 
	END 

	if (@include&1024 = 1024)   --An den Anfang verschoben um preloading zu optimieren
			SELECT NULL as [#1024],PP.* 
			FROM PersonPermissions PP INNER JOIN #PersonsNP PNP on PNP.PersonId = pp.PersonId

	IF (@include&1 = 1)
			SELECT NULL AS [#1], 
				pk.PersonContactDataId, 
				pk.CommunicationTypeId, 
				pk.PersonId, 
				pk.Sort, 
				pk.IsSecret,
				CASE WHEN IsSecret = 1 AND readSecret=0 THEN '**********' ELSE  pk.DataValue	   END AS DataValue,
				CASE WHEN IsSecret = 1 AND readSecret=0 THEN '**********' ELSE  pk.Note END AS Note,
				pk.ContactPersonConnectionID,
				pk.LM, pk.UM, pk.LC, pk.UC
			FROM PersonContactData AS pk
				INNER JOIN (
				SELECT  pp.PersonId,pp.readSecret 
				FROM #includePermissions AS PP		
					) AS sub ON pk.PersonId = sub.PersonId

	IF (@include&2 = 2)
		SELECT NULL AS [#2], PersonAddress.*
		FROM PersonAddress
			INNER JOIN #includePermissions ON PersonAddress.PersonId = #includePermissions.PersonId WHERE PersonAddress.IsSecret = 0 OR readSecret > 0
					
	IF (@include&4 = 4)
		SELECT NULL AS [#4], PersonDetails.*
		FROM PersonDetails 			
			INNER JOIN #includePermissions ON PersonDetails.PersonId = #includePermissions.PersonId WHERE ReadPersonDetails > 0 OR WRITEPERSONDETAILS>0
		
	IF (@include&8 = 8)
		SELECT NULL AS [#8],PersonEmployee.*
		FROM PersonEmployee
			INNER JOIN #includePermissions ON PersonEmployee.PersonId = #includePermissions.PersonId
			
	IF (@include&16 = 16) 
		SELECT NULL AS [#16], zd.*
		FROM PersonAdditionalData zd 
		WHERE zd.PersonAdditionalDataId IN 
		(SELECT PersonAdditionalDataId FROM PersonAdditionalData
			INNER JOIN	PersonAdditionalDataTypes	AS zdt	ON zd.PersonAdditionalDataTypeId = zdt.PersonAdditionalDataTypeId
			INNER JOIN	#includePermissions			AS gp	ON zd.PersonId = gp.PersonId
			INNER JOIN  #UserGroupPermissions		AS ug	ON zdt.OwnerGroupId = ug.OwnerGroupId			 
		WHERE 
			zdt.IsSecret = 0 OR ug.PermissionArea = 0)
	
	IF (@include&32 = 32) 
		SELECT NULL AS [#32], PersonRelations.*
		FROM PersonRelations
			INNER JOIN #includePermissions ON PersonRelations.PersonId = #includePermissions.PersonId AND ShowLinkedContacts > 0

	IF (@include&64 = 64) 
		SELECT NULL AS [#64], PersonRelations.*
		FROM PersonRelations 
			INNER JOIN #includePermissions ON PersonRelations.ChildPersonId = #includePermissions.PersonId

	IF (@include&128 = 128) 
		SELECT NULL AS [#128], Qualification_Person.*
		FROM Qualification_Person 
			INNER JOIN #includePermissions ON Qualification_Person.PersonId = #includePermissions.PersonId
	
	IF (@include&256 = 256) 
		SELECT NULL AS [#256], BodyMeasurements.*
		FROM BodyMeasurements 
			INNER JOIN #includePermissions ON BodyMeasurements.PersonId = #includePermissions.PersonId
			INNER JOIN #UserGroupPermissions prp ON prp.OwnerGroupId = #includePermissions.baseOwner AND prp.PermissionArea=6
	
	IF (@include&512 = 512) 
		SELECT NULL AS [#512], BankAccounts.*
		FROM BankAccounts 
			INNER JOIN #includePermissions ON BankAccounts.PersonId = #includePermissions.PersonId 
				AND (#includePermissions.ReadPersonBankdata>0 OR #includePermissions.WritePersonBankdata > 0)

	IF (@include&2048 = 2048) 
		SELECT NULL AS [#2048], PersonAttachments.PersonId, Count(*) AS CountAttachments
		FROM PersonAttachments 
			INNER JOIN #includePermissions ON PersonAttachments.PersonId = #includePermissions.PersonId
		GROUP BY PersonAttachments.PersonId
	IF (@include&4096 = 4096) 
		SELECT NULL AS [#4096], Birthdays.*
		FROM Birthdays 
			INNER JOIN #includePermissions ON Birthdays.PersonId = #includePermissions.PersonId		
	IF (@include&8192 = 8192 OR @include&16384 = 16384) 
		SELECT NULL AS [#8192], Contracts.*
		FROM Contracts 
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	and contracts.OwnerGroupId in (select OwnerGroupId  from #UserGroupPermissions where PermissionArea=1)		
	IF (@include&16384 = 16384) 
		SELECT NULL AS [#16384], ContractDepartments.*
		FROM ContractDepartments 
			inner join Contracts on ContractDepartments.ContractId=Contracts.ContractId
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	and contracts.OwnerGroupId in (select OwnerGroupId  from #UserGroupPermissions where PermissionArea in (1,5))		
	IF (@include&32768 = 32768) 
		SELECT NULL AS [32768], PersonInCategories.*
		FROM PersonInCategories 
			INNER JOIN #PersonsNP ON PersonInCategories.PersonId = #PersonsNP.PersonId	
	IF (@include<>0) 
	BEGIN	
		DROP TABLE #includePermissions
		DROP TABLE #PersonsNP
	END
	DROP TABLE #UserGroupPermissions
END
GO

ALTER PROCEDURE [dbo].[GetPersons]
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowPersonsWithoutRights BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetPersonsInternal @condition, @order, @joins, @include, @ShowPersonsWithoutRights, @userId
END
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.CollectiveStatus') AND type <> 'U') DROP VIEW dbo.CollectiveStatus
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.PublicStatus') AND type <> 'U') DROP VIEW dbo.PublicStatus
GO

ALTER PROCEDURE [dbo].[GetPersonStatusInternal]
	@condition VARCHAR(MAX),
	@collectives BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	IF (@collectives = 0)
		BEGIN
			 SET @SQLQuery ='SELECT PersonStatusId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.Note  ELSE NULL END AS Note,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,
				CASE WHEN TimeAccounts.Formel IN (1, 2) THEN 2 WHEN TimeAccounts.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
				CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
				ps.ApprovalStatus, ps.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, ps.LM, ps.UM, ps.LC, ps.UC
			FROM PersonStatus AS ps
				INNER JOIN Persons AS p ON ps.PersonId = p.PersonId 
				INNER JOIN PersonStatusTypes AS st ON ps.PersonStatusTypeId = st.PersonStatusTypeId 
				INNER JOIN TimeAccounts  ON st.TimeAccountId = TimeAccounts.TimeAccountId
				INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
			WHERE ug.Userid = '+ CAST(@userId AS VARCHAR(10))+ 'AND PermissionArea = 8'
		END
	ELSE
		BEGIN
			 SET @SQLQuery =' SELECT ps.*, 
						st.TimeAccountId,
						1 AS AvailableStatus,
						CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1 ELSE 0 END AS IsHalfDayType
			FROM		   PersonStatus		 AS ps
				INNER JOIN PersonStatusTypes AS st	ON ps.PersonStatusTypeId = st.PersonStatusTypeId
				INNER JOIN TimeAccounts				ON st.TimeAccountId = TimeAccounts.TimeAccountId
			WHERE EXISTS (SELECT PersonId
							FROM PersonInCategories AS pic
								INNER JOIN PersonCategories AS cat ON pic.PersonCategoryId = cat.PersonCategoryId
							WHERE cat.PersonCategoryType BETWEEN 10 AND 200 AND  pic.PersonId = ps.PersonId)'
		END

	SET @SQLQuery = @SQLQuery + ' AND ' + @condition
	EXECUTE sp_Executesql @SQLQuery
END
GO
--#endregion 2021-01-21 Kontaktbereiche

--#region WorkVersionTimeFlow
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='WorkVersionTimeFlow')
BEGIN

	PRINT 'Creating WorkVersionTimeFlow...'
 
	CREATE TABLE dbo.WorkVersionTimeFlow (
		WorkVersionTimeFlowId INT IDENTITY(1,1) NOT NULL,
		WorkVersionId INT NOT NULL,
		[Name] VARCHAR(80) NOT NULL, 
		Position SMALLINT NOT NULL CONSTRAINT DF_WorkVersionTimeFlow_Position DEFAULT 0,
		Duration SMALLINT NOT NULL CONSTRAINT DF_WorkVersionTimeFlow_Duration DEFAULT 0,
		NOTE VARCHAR(1024),
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_WorkVersionTimeFlow_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_WorkVersionTimeFlow_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_WorkVersionTimeFlow PRIMARY KEY NONCLUSTERED (WorkVersionTimeFlowId) ON [PRIMARY]
    ) ON [PRIMARY]
	GRANT SELECT, INSERT, UPDATE, DELETE ON WorkVersionTimeFlow TO WorksWrite

	CREATE UNIQUE CLUSTERED INDEX IX_WorkVersionTimeFlow_WorkVersionId ON WorkVersionTimeFlow (WorkVersionId, Position) ON [PRIMARY]
	
	ALTER TABLE WorkVersionTimeFlow WITH CHECK ADD CONSTRAINT FK_WorkVersionTimeFlow_WorkVersion FOREIGN KEY(WorkVersionId)
	REFERENCES WorkVersions (WorkVersionId)
	ALTER TABLE WorkVersionTimeFlow CHECK CONSTRAINT FK_WorkVersionTimeFlow_WorkVersion	
END
GO
--#endregion WorkVersionTimeFlow

--#region SH 2021-02-01 TransferSettings ProxyUSage in ProxyType ändern

UPDATE ExportProfiles SET
Transfersettings = CAST(REPLACE(CAST(Transfersettings AS NVARCHAR(MAX)), '<UseProxy>None</UseProxy>','<ProxyType>None</ProxyType>') AS XML) WHERE CAST(Transfersettings AS NVARCHAR(MAX)) LIKE '%<UseProxy>None</UseProxy>%'
GO

UPDATE ExportProfiles SET
Transfersettings = CAST(REPLACE(CAST(Transfersettings AS NVARCHAR(MAX)), '<UseProxy>Custom</UseProxy>','<ProxyType>UserAtHost</ProxyType>') AS XML) WHERE CAST(Transfersettings AS NVARCHAR(MAX)) LIKE '%<UseProxy>Custom</UseProxy>%'
GO

--#endregion

--#region SH 2021-02-05 Settings.Context vergrößern auf 50 Zeichen

IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('Settings') AND c.Name = 'Context' AND c.max_length = 15) 
BEGIN
	PRINT 'Changing max length of Settings.Context to 50...'
	ALTER TABLE [Settings] ALTER COLUMN [Context] VARCHAR(50) NULL
END
GO

--#endregion (SH 2021-02-05 Settings.Context vergrößern auf 50 Zeichen)

--#region 2021-02-11
GRANT UPDATE, INSERT, DELETE ON CountDownTypes TO DispoAdmin
GO
--#endregion

--#region DH 2021-02-11 Fremdschlüssel für diverse Projekttabellen
IF NOT EXISTS ( SELECT * FROM SYS.FOREIGN_KEYS WHERE [name] ='FK_ResourceblockPeriods_Tours' )
BEGIN
Update ResourceBlockPeriods set TourId= null where TourId not in (select TourId from Tours);

ALTER TABLE Resourceblockperiods
   ADD CONSTRAINT FK_ResourceblockPeriods_Tours FOREIGN KEY (TourId)
      REFERENCES Tours (TourID)
END

GO
IF NOT EXISTS ( SELECT * FROM SYS.FOREIGN_KEYS WHERE [name] ='FK_ProductionTaskTemplates_Workareas' )
BEGIN
Update ProductionTaskTemplates set WorkAreaId= null where WorkAreaId not in (select WorkAreaId from WorkAreas);

ALTER TABLE ProductionTaskTemplates
   ADD CONSTRAINT FK_ProductionTaskTemplates_Workareas FOREIGN KEY (Workareaid)
      REFERENCES Workareas (Workareaid)
END
GO
IF NOT EXISTS ( SELECT * FROM SYS.FOREIGN_KEYS WHERE [name] ='FK_ProductionTaskTemplates_ProductionTemplates' )
BEGIN
ALTER TABLE ProductionTaskTemplates
   ADD CONSTRAINT FK_ProductionTaskTemplates_ProductionTemplates FOREIGN KEY (ProductionTemplateId)
      REFERENCES ProductionTemplates (ProductionTemplateId)
END
GO
IF NOT EXISTS ( SELECT * FROM SYS.FOREIGN_KEYS WHERE [name] ='FK_ProjectTasks_ProductionTaskTemplates' )
BEGIN
UPDATE ProjectTasks SET ProductionTaskTemplateid = NULL FROM ProjectTasks WHERE NOT EXISTS (SELECT * FROM ProductionTaskTemplates as pt WHERE pt.ProductionTaskTemplateid = ProjectTasks.ProductionTaskTemplateid )
ALTER TABLE ProjectTasks
   ADD CONSTRAINT FK_ProjectTasks_ProductionTaskTemplates FOREIGN KEY (ProductionTaskTemplateid)
      REFERENCES ProductionTaskTemplates (ProductionTaskTemplateid)
	  ON DELETE SET NULL
END
GO
IF NOT EXISTS ( SELECT * FROM SYS.FOREIGN_KEYS WHERE [name] ='FK_ProductionTemplates_Ownergroups' )
BEGIN
ALTER TABLE ProductionTemplates
   ADD CONSTRAINT FK_ProductionTemplates_Ownergroups FOREIGN KEY (OwnergroupId)
      REFERENCES Ownergroups (Ownergroupid)
END
GO
--#endregion DH 2021-02-11 Fremdschlüssel für diverse Projekttabellen

--#region
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[ContractFieldTypes]') AND o.Name = '[IX_CategoryCode]') DROP INDEX [IX_CategoryCode] ON [dbo].[ContractFieldTypes]
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[JourneyGroups]') AND o.Name = '[_1CA61189_BD03_11D2_BA7D_00400]') DROP INDEX [_1CA61189_BD03_11D2_BA7D_00400] ON [dbo].[JourneyGroups]
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[PlanColumns]') AND o.Name = '[_1CA6119D_BD03_11D2_BA7D_00400]') DROP INDEX [_1CA6119D_BD03_11D2_BA7D_00400] ON [dbo].[PlanColumns]
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[Cast]') AND o.Name = '[IX_AuffNr]') DROP INDEX [IX_AuffNr] ON [dbo].[Cast]
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[CastRepertoire]') AND o.Name = '[IX_PersNr_RolleId]') DROP INDEX [IX_PersNr_RolleId] ON [dbo].[CastRepertoire] 
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.[Roles]') AND o.Name = '[IX_Snr]') DROP INDEX [IX_Snr] ON [dbo].[Roles]
GO
--#endregion

--#region 2021-02-24 DutyRoster

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BonusDutyRosterData') AND [name] = 'Date')
BEGIN
	ALTER TABLE BonusDutyRosterData ADD Date DATE NULL
	ALTER TABLE BonusDutyRosterData ADD ContractId INT NULL
	
END
GO

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BonusDutyRosterData') AND [name] = 'DutyRosterId')
BEGIN
	EXEC('UPDATE BonusDutyRosterData SET Date = dp.Date, ContractId = dp.ContractId FROM DutyRoster AS DP INNER JOIN BonusDutyRosterData ON dp.DutyRosterId = BonusDutyRosterData.DutyRosterId WHERE dp.DutyRosterTypeId = 0')
	DELETE FROM BonusDutyRosterData WHERE Date IS NULL
	ALTER TABLE BonusDutyRosterData ALTER COLUMN Date DATE NOT NULL
	ALTER TABLE BonusDutyRosterData ALTER COLUMN ContractId INT NOT NULL
	ALTER TABLE BonusDutyRosterData ALTER COLUMN  DutyRosterId INT NULL

	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.BonusDutyRosterData') AND o.Name = 'IX_DienstplanID') DROP INDEX IX_DienstplanID ON dbo.BonusDutyRosterData
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_BonusDutyRosterData_DutyRoster') AND type = 'F') ALTER TABLE dbo.BonusDutyRosterData DROP CONSTRAINT FK_BonusDutyRosterData_DutyRoster
	ALTER TABLE dbo.BonusDutyRosterData DROP CONSTRAINT PK_BonusDutyRosterData
	CREATE CLUSTERED INDEX IX_BonusDutyRosterData_ContractId_Data  ON BonusDutyRosterData (ContractId, Date) ON [PRIMARY]
	ALTER TABLE dbo.BonusDutyRosterData ADD CONSTRAINT PK_BonusDutyRosterDataId PRIMARY KEY NONCLUSTERED (BonusDutyRosterDataId) ON [PRIMARY]

	ALTER TABLE BonusDutyRosterData
	ADD CONSTRAINT FK_BonusDutyRosterData_Contracts FOREIGN KEY (ContractId)
     REFERENCES Contracts (ContractId)
	 EXEC sp_rename 'BonusDutyRosterData.DutyRosterId', 'x_DutyRosterId', 'COLUMN';
END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.DutyRosterPeriodPermissionByDepartments')) DROP FUNCTION dbo.DutyRosterPeriodPermissionByDepartments
GO

CREATE FUNCTION [dbo].[DutyRosterPeriodPermissionByDepartments] (
		@start DATE,
		@end DATE,
		@departmentIds [dbo].[IdFilterTable] READONLY,
		@userId INT)
RETURNS
@resultTable TABLE (
	DepartmentId INT,
	StartDate DATE,
	EndDate DATE
)
AS
BEGIN
	DECLARE @departmentsWithPermissions TABLE(DepartmentId INT, OptionsFlag INT)
	
	INSERT INTO @departmentsWithPermissions
	SELECT
		DepartmentId, OptionsFlag 
	FROM
		[Permissions] AS P 
		INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
	WHERE
		UserId = @userId AND 
		PermissionArea = 5 AND 
		d.DepartmentId IN (SELECT Id FROM @departmentIds)
			

	INSERT INTO @resultTable
	SELECT
		DepartmentId,
		CASE WHEN OptionsFlag&128 = 128 OR @start >= GETDATE() THEN @start ELSE CAST(GETDATE() AS DATE) END, 
		@end AS EndDate
	FROM
		@departmentsWithPermissions
	WHERE
		OptionsFlag&64 = 64 
		
	INSERT INTO @resultTable
	SELECT
		dwp.DepartmentId,
		CASE WHEN OptionsFlag&128 = 128 OR @start >= GETDATE() THEN CASE WHEN drp.[start] > @start THEN drp.[start] ELSE @start END ELSE CAST(GETDATE() AS DATE) END, 
		CASE WHEN drp.[End] < @end THEN drp.[End] ELSE @end END
	FROM
		@departmentsWithPermissions AS dwp
		INNER JOIN DutyRosterPeriods AS drp ON dwp.DepartmentId = drp.DepartmentId
		INNER JOIN DutyRosterPeriodStatus AS srps ON drp.DutyRosterPeriodStatusId = srps.DutyRosterPeriodStatusId
	WHERE
		NOT OptionsFlag&64 = 64
		AND srps.IsReleasedStatus = 1
		AND drp.[Start] <= @end
		AND drp.[End] >= @Start
RETURN
END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.DutyRosterPeriodPermissionByContracts')) DROP FUNCTION dbo.DutyRosterPeriodPermissionByContracts
GO

CREATE FUNCTION [dbo].[DutyRosterPeriodPermissionByContracts] (
		@start DATE,
		@end DATE,
		@contractids[dbo].[IdFilterTable] READONLY,
		@userId INT)
RETURNS
@resultTable TABLE (
	ContractId INT,
	StartDate DATE,
	EndDate DATE
)
AS
BEGIN
	DECLARE @workAreasWithPermissions TABLE(ContractId INT, DepartmentId INT, OptionsFlag INT)
	INSERT INTO @workAreasWithPermissions
	SELECT
		ContractId, w.DepartmentId, OptionsFlag 
	FROM
		[Permissions]  AS P 
		INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
		INNER JOIN WorkAreas AS w ON d.DepartmentId = w.DepartmentId
		INNER JOIN ContractDepartments AS cd ON cd.WorkAreaId = w.WorkAreaId 
	WHERE
		UserId = @userId AND 
		cd.IsMainWorkArea = 1 AND 
		PermissionArea = 5 AND 
		cd.ContractId IN (SELECT Id FROM @contractids)
	
	INSERT INTO @resultTable
	SELECT
		ContractId,
		CASE WHEN OptionsFlag&128 = 128 OR @start >= GETDATE() THEN @start ELSE CAST(GETDATE() AS DATE) END, 
		@end AS EndDate
	FROM
		@workAreasWithPermissions
	WHERE
		OptionsFlag&64 = 64

	INSERT INTO @resultTable
	SELECT
		dwp.ContractId,
		CASE WHEN OptionsFlag&128 = 128 OR @start >= GETDATE() THEN CASE WHEN drp.[start] > @start THEN drp.[start] ELSE @start END ELSE CAST(GETDATE() AS DATE) END, 
		CASE WHEN drp.[End] < @end THEN drp.[End] ELSE @end END
	FROM
		@workAreasWithPermissions AS dwp
		INNER JOIN DutyRosterPeriods AS drp ON dwp.DepartmentId = drp.DepartmentId
		INNER JOIN DutyRosterPeriodStatus AS srps ON drp.DutyRosterPeriodStatusId = srps.DutyRosterPeriodStatusId
	WHERE
		NOT OptionsFlag&64 = 64
		AND srps.IsReleasedStatus = 1
		AND drp.[Start] <= @end
		AND drp.[End] >= @Start

RETURN
END
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByContractsInternal')) DROP PROCEDURE dbo.GetDutyRosterByContractsInternal
GO

CREATE PROCEDURE [dbo].[GetDutyRosterByContractsInternal]
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT,
	@topFromEnd INT,
	@userId INT,
	@personId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	DECLARE @e NVARCHAR(MAX)
	SET NOCOUNT ON
	
	CREATE TABLE #Permissions (ContractId INT NOT NULL, StartDate DATE NOT NULL, EndDate DATE NOT NULL)

	IF (NOT @personId IS NULL)
		BEGIN
			CREATE TABLE #OwnContracts (ContractId INT NOT NULL)
			INSERT INTO #OwnContracts SELECT ci.Id FROM @contractids AS ci INNER JOIN Contracts AS c ON ci.Id = c.ContractId WHERE c.PersonId = @personId

			IF ((SELECT COUNT(*) FROM #OwnContracts) > 0)
				BEGIN
					INSERT INTO #Permissions (ContractId, StartDate, EndDate) SELECT ContractId, @start, @end FROM #OwnContracts
					DECLARE @otherContractids IdFilterTable
					INSERT INTO @otherContractids SELECT c.Id FROM @contractids AS c WHERE NOT EXISTS (SELECT * FROM #OwnContracts AS oc WHERE oc.ContractId = c.Id)
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @otherContractids, @userId)
				END
			ELSE
				BEGIN
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
				END
		END
	ELSE
		BEGIN
			INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
		END
	
	
	SET @SQLQuery =	N'SELECT '
	IF (@topFromEnd > 0)  SET @SQLQuery = @SQLQuery + N' TOP ' + CAST(@topFromEnd AS VARCHAR(10))
	SET @SQLQuery = @SQLQuery + N' dp.* '

	SET @SQLQuery =@SQLQuery + N' FROM DutyRoster AS dp
						INNER JOIN #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate '
	
	 IF (ISNULL(@where, '') <> '' )  SET @SQLQuery = @SQLQuery + ' AND ' + @where
	 IF (@topFromEnd > 0)  SET @SQLQuery = @SQLQuery + ' ORDER BY dp.Date DESC'

	 EXECUTE sp_Executesql @SQLQuery
	--Weiteres Where wird aus Performancegründen ignoriert 	
	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate 
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 
END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByDepartmentInternal')) DROP PROCEDURE dbo.GetDutyRosterByDepartmentInternal
GO

CREATE PROCEDURE dbo.GetDutyRosterByDepartmentInternal
	@start DATE,
	@end DATE,
	@Departmentids IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	SET NOCOUNT ON
	
	CREATE TABLE #Permissions (DepartmentId INT NOT NULL,  StartDate DATE NOT NULL, EndDate DATE NOT NULL)
	INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByDepartments (@start,  @end, @Departmentids, @userId)

	SET @SQLQuery = 'SELECT dp.* 
					FROM DutyRoster AS dp 
						INNER JOIN ContractDepartments AS cd ON dp.ContractId = cd.ContractId 
						INNER JOIN WorkAreas AS w ON cd.WorkAreaId = w.WorkAreaId
						INNER JOIN #Permissions AS p ON w.DepartmentId = p.DepartmentId
					WHERE dp.[Date] BETWEEN p.StartDate AND p.EndDate'

	  IF (ISNULL(@where, '') <> '' )  SET @SQLQuery = @SQLQuery + ' AND ' + @where
	 EXECUTE sp_Executesql @SQLQuery

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate 
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 
END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterSickReturns')) DROP PROCEDURE dbo.GetDutyRosterSickReturns
GO

CREATE PROCEDURE dbo.GetDutyRosterSickReturns
	@date DATE,
	@contractids IdFilterTable READONLY,
	@shiftTypes IdFilterTable READONLY
AS
BEGIN

	SET NOCOUNT ON
	DECLARE @userId INT, @pdate DATE
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	SET @pdate = DATEADD (d, -1, @date)
	CREATE TABLE #Permissions (DepartmentId INT NOT NULL)
	
	INSERT INTO #Permissions SELECT d.DepartmentId
				FROM [Permissions]  AS P 
				INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
				WHERE UserId = @userId AND 
					PermissionArea = 5 
	SELECT dpk.*
					FROM DutyRoster AS dpk 
					INNER JOIN ContractDepartments AS cd ON dpk.ContractId = cd.ContractId 
					INNER JOIN WorkAreas AS w ON cd.WorkAreaId = w.WorkAreaId
					INNER JOIN #Permissions AS p ON w.DepartmentId = p.DepartmentId
					LEFT JOIN DutyRoster AS dpg ON dpk.Date = DATEADD (d, -1, dpg.[Date]) AND dpk.ContractId = dpg.ContractId 
			WHERE dpk.[Date]  = @pdate
				AND dpk.ContractId IN (SELECT id FROM @contractids)
				AND dpk.DutyRosterTypeId = 0
				AND dpk.ShiftTypeId1 IN (SELECT id FROM @shiftTypes)
				AND (dpg.DutyRosterId IS NULL OR (
					dpg.ShiftTypeId1 NOT IN (SELECT id FROM @shiftTypes)
					AND dpg.[Date] = @date
					AND dpg.DutyRosterTypeId = 0
					)
				)

END
GO

GRANT EXECUTE ON GetDutyRosterSickReturns TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetGroupedDutyRosterByContractsInternal')) DROP PROCEDURE dbo.GetGroupedDutyRosterByContractsInternal
GO

CREATE PROCEDURE dbo.GetGroupedDutyRosterByContractsInternal
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@select NVARCHAR(MAX),
	@from NVARCHAR(MAX),
	@where NVARCHAR(MAX),
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	SET NOCOUNT ON
	
	CREATE TABLE #Permissions (ContractId INT NOT NULL)
	INSERT INTO #Permissions SELECT DISTINCT ContractId
					FROM [Permissions]  AS P 
					INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
					INNER JOIN WorkAreas AS w ON d.DepartmentId = w.DepartmentId
					INNER JOIN ContractDepartments AS cd ON cd.WorkAreaId = w.WorkAreaId 
					WHERE UserId = @userId AND 
						PermissionArea = 5 AND 
						cd.ContractId IN (SELECT Id FROM @contractids)

	IF (ISNULL(@select, '') = '') SET @select = 'Count(*)'

	SET @SQLQuery =	'SELECT dp.ContractId, ' + @select + ' AS Value FROM '

	IF (ISNULL(@from, '') = '') SET @from = ' DutyRoster AS dp '
	SET @SQLQuery =  @SQLQuery + @from
	SET @SQLQuery =  @SQLQuery + ' INNER JOIN #Permissions AS p ON dp.ContractId = p.ContractId '

	SET @SQLQuery = @SQLQuery + ' WHERE dp.DutyRosterTypeId = 0 AND dp.[Date] BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''

	IF (ISNULL(@where, '') <> '') SET @SQLQuery = @SQLQuery + ' AND ' + @where

	SET @SQLQuery = @SQLQuery + ' GROUP BY dp.ContractId'

	EXECUTE sp_Executesql  @SQLQuery


END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByContracts')) DROP PROCEDURE dbo.GetDutyRosterByContracts
GO

CREATE PROCEDURE dbo.GetDutyRosterByContracts
	@start DATE,
	@end DATE,
	@contractIds IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT,
	@topFromEnd INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	DECLARE @personId INT
	SELECT @userId = UserId, @personId = PersonId FROM Users WHERE UserName  = CURRENT_USER

	IF (NOT @personId IS NULL) 
	BEGIN
		IF (IS_MEMBER('PersoWriteOwnRoster') = 0 AND IS_MEMBER('PersoWriteOwnRegularRoster') = 0)
		SET @personId = NULL
	END
	
	EXECUTE GetDutyRosterByContractsInternal @start, @end, @contractIds, @where,  @include, @topFromEnd, @userId, @personId
END
GO

GRANT EXECUTE ON GetDutyRosterByContracts TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByDepartment')) DROP PROCEDURE dbo.GetDutyRosterByDepartment
GO

CREATE PROCEDURE dbo.GetDutyRosterByDepartment
	@start DATE,
	@end DATE,
	@departmentIds IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetDutyRosterByDepartmentInternal @start, @end, @departmentIds, @where, @include, @userId
END
GO

GRANT EXECUTE ON GetDutyRosterByDepartment TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetGroupedDutyRosterByContracts')) DROP PROCEDURE dbo.GetGroupedDutyRosterByContracts
GO

CREATE PROCEDURE dbo.GetGroupedDutyRosterByContracts
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@select NVARCHAR(MAX),
	@from NVARCHAR(MAX),
	@where VARCHAR(MAX)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetGroupedDutyRosterByContractsInternal  @start, @end, @contractids, @select, @from, @where, @userId
END
GO

GRANT EXECUTE ON GetGroupedDutyRosterByContracts TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterById')) DROP PROCEDURE dbo.GetDutyRosterById
GO

CREATE PROCEDURE dbo.GetDutyRosterById
	@Id INT
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM DutyRoster WHERE DutyRosterId = @Id
END
GO

GRANT EXECUTE ON GetDutyRosterById TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByIds')) DROP PROCEDURE dbo.GetDutyRosterByIds
GO

CREATE PROCEDURE dbo.GetDutyRosterByIds
	@Ids IdFilterTable READONLY
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM DutyRoster WHERE DutyRosterId IN (SELECT Id FROM @Ids )
END
GO

GRANT EXECUTE ON GetDutyRosterByIds TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByContractsCore')) DROP PROCEDURE dbo.GetDutyRosterByContractsCore
GO

CREATE PROCEDURE dbo.GetDutyRosterByContractsCore
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@include INT
AS
BEGIN
	
	SET NOCOUNT ON
	DECLARE @userId INT
	DECLARE @personId INT
	SELECT @userId = UserId, @personId = PersonId FROM Users WHERE UserName  = CURRENT_USER

	IF (NOT @personId IS NULL) 
	BEGIN
		IF (IS_MEMBER('PersoWriteOwnRoster') = 0 AND IS_MEMBER('PersoWriteOwnRegularRoster') = 0)
		SET @personId = NULL
	END
	
	CREATE TABLE #Permissions (ContractId INT NOT NULL, StartDate DATE NOT NULL, EndDate DATE NOT NULL)
	
	IF (NOT @personId IS NULL)
		BEGIN
			CREATE TABLE #OwnContracts (ContractId INT NOT NULL)
			INSERT INTO #OwnContracts SELECT ci.Id FROM @contractids AS ci INNER JOIN Contracts AS c ON ci.Id = c.ContractId WHERE c.PersonId = @personId

			IF ((SELECT COUNT(*) FROM #OwnContracts) > 0)
				BEGIN
					INSERT INTO #Permissions (ContractId, StartDate, EndDate) SELECT ContractId, @start, @end FROM #OwnContracts
					DECLARE @otherContractids IdFilterTable
					INSERT INTO @otherContractids SELECT c.Id FROM @contractids AS c WHERE NOT EXISTS (SELECT * FROM #OwnContracts AS oc WHERE oc.ContractId = c.Id)
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @otherContractids, @userId)
				END
			ELSE
				BEGIN
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
				END
		END
	ELSE
		BEGIN
			INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
		END
		
	SELECT dp.* FROM DutyRoster AS dp
		INNER JOIN #Permissions AS p ON dp.ContractId = p.ContractId AND [Date] BETWEEN p.StartDate AND p.EndDate 
	WHERE dp.DutyRosterTypeId = 0

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 

END
GO

GRANT EXECUTE ON GetDutyRosterByContractsCore TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.DeleteDutyRosterByContractId')) DROP PROCEDURE dbo.DeleteDutyRosterByContractId
GO

CREATE PROCEDURE dbo.DeleteDutyRosterByContractId
	@contractIds INT
AS
BEGIN
	
	SET NOCOUNT ON
	
	IF EXISTS (	SELECT *
				FROM [Permissions]  AS P 
				INNER JOIN Users AS u ON p.UserID = u.UserID 
				INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
				INNER JOIN WorkAreas AS w ON d.DepartmentId = w.DepartmentId
				INNER JOIN ContractDepartments AS cd ON cd.WorkAreaId = w.WorkAreaId 
				WHERE u.UserName = CURRENT_USER AND 
					PermissionArea IN (1, 5) AND 
					p.HasWritePermission = 1 AND
					cd.ContractId = @contractids)
	BEGIN
		DELETE FROM DutyRoster WHERE ContractId = @contractids
	END
END
GO

GRANT EXECUTE ON DeleteDutyRosterByContractId TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.CountDutyRosterByContractId')) DROP PROCEDURE dbo.CountDutyRosterByContractId
GO

CREATE PROCEDURE dbo.CountDutyRosterByContractId
	@contractids INT
AS
BEGIN

	SET NOCOUNT ON

	SELECT COUNT(*) 
	FROM DutyRoster 
	WHERE ContractId = @contractids
END
GO

GRANT EXECUTE ON CountDutyRosterByContractId TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.CountDutyRosterInPeriodByContractId')) DROP PROCEDURE dbo.CountDutyRosterInPeriodByContractId
GO

CREATE PROCEDURE dbo.CountDutyRosterInPeriodByContractId
	@start DATE,
	@end DATE,
	@contractId INT,
	@dutyRosterTypeId INT
AS
BEGIN

	SET NOCOUNT ON

	SELECT COUNT(*) 
	FROM DutyRoster
	WHERE 
		DutyRosterTypeId = @dutyRosterTypeId AND 
		ContractId = @contractId AND 
		[Date] BETWEEN @start AND @end
END
GO

GRANT EXECUTE ON CountDutyRosterInPeriodByContractId TO Public
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbDutyRoster_Update') AND type <> 'U') DROP VIEW dbo.AbDutyRoster_Update
GO

CREATE VIEW dbo.AbDutyRoster_Update
AS
SELECT *
	FROM DutyRoster dp	
		WHERE EXISTS (SELECT *
				FROM [Permissions] AS P 
				INNER JOIN Users AS u ON p.UserId = u.UserId
				INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
				INNER JOIN WorkAreas AS w ON d.DepartmentId = w.DepartmentId
				INNER JOIN ContractDepartments AS cd ON cd.WorkAreaId = w.WorkAreaId 
				INNER JOIN Contracts AS c ON cd.ContractId = c.ContractId 
				WHERE u.UserName = CURRENT_USER 
					AND PermissionArea = 5 
					AND p.HasWritePermission = 1
					AND cd.ContractId = dp.ContractId)	
		OR ((IS_MEMBER('PersoWriteOwnRoster') = 1 OR IS_MEMBER('PersoWriteOwnRegularRoster') = 1) AND EXISTS (SELECT * FROM Contracts AS c 
							INNER JOIN Users AS u ON c.PersonId = u.PersonId 
					WHERE  u.UserName = CURRENT_USER
						AND c.ContractId = dp.ContractId))
WITH CHECK OPTION
GO

GRANT SELECT, UPDATE, INSERT, DELETE ON AbDutyRoster_Update TO PUBLIC
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterHistoryByIds')) DROP PROCEDURE dbo.GetDutyRosterHistoryByIds
GO

CREATE PROCEDURE dbo.GetDutyRosterHistoryByIds
	@Id INT
AS
BEGIN
	SET NOCOUNT ON
	SELECT * FROM updateLog WHERE LogTable = 'DutyRoster' AND PKValue = @Id
END
GO

GRANT EXECUTE ON GetDutyRosterHistoryByIds TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterConsecutiveFreeDays')) DROP PROCEDURE dbo.GetDutyRosterConsecutiveFreeDays
GO

CREATE PROCEDURE dbo.GetDutyRosterConsecutiveFreeDays
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@consecutiveDays INT, 
	@weekdays IdFilterTable READONLY
AS
BEGIN
	
	SET NOCOUNT ON
	IF EXISTS (SELECT * FROM @weekdays )
	BEGIN
		WITH GroupableData AS (
			SELECT 
				ContractId,
				[Date],
				DayOffCount,
				DATEADD(DAY,-ROW_NUMBER() OVER (
					PARTITION BY ContractId, DutyRosterTypeId, Dayoffcount 
					ORDER BY [Date]),[Date]) AS GroupingSet
			FROM DutyRoster  
			WHERE
				DutyRosterTypeId  = 0
				AND DutyRoster.ContractId IN (SELECT Id FROM @contractids)
				AND [Date] BETWEEN @start AND @end
				AND DayOffCount = 1
				AND (((@@datefirst-1) + datepart(weekday, [Date])) % 7) IN (SELECT Id FROM @weekdays)					
			) 
			SELECT n.ContractId,SUM(n.result) from (
				SELECT 
				ContractId,
				count(DayOffCount)/@consecutiveDays AS result 
				FROM GroupableData
				GROUP BY ContractId,GroupingSet 		
				) AS n GROUP BY n.ContractId 
	END
	ELSE
	BEGIN
		WITH GroupableData AS (
			SELECT 
				ContractId,
				[Date],
				DayOffCount,
				DATEADD(DAY,-ROW_NUMBER() OVER (
					PARTITION BY ContractId, DutyRosterTypeId, Dayoffcount 
					ORDER BY [Date]),[Date]) AS GroupingSet
			FROM DutyRoster  
			WHERE
				DutyRosterTypeId  = 0
				AND DutyRoster.ContractId IN (SELECT Id FROM @contractids)
				AND [Date] BETWEEN @start AND @end
				AND DayOffCount = 1
			) 
			SELECT n.ContractId,SUM(n.result) from (
				SELECT 
				ContractId,
				count(DayOffCount)/@consecutiveDays AS result 
				FROM GroupableData
				GROUP BY ContractId,GroupingSet 		
				) AS n GROUP BY n.ContractId 
	END
END
GO

GRANT EXECUTE ON GetDutyRosterConsecutiveFreeDays TO Public
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterActualDebitHours')) DROP PROCEDURE dbo.GetDutyRosterActualDebitHours
GO

CREATE PROCEDURE dbo.GetDutyRosterActualDebitHours
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY
AS
BEGIN
	
SET NOCOUNT ON
SELECT ContractId, SUM(MiscWorkingMinutes+WorkingMinutes1+WorkingMinutes2+WorkingMinutes3-PaidOffWorkingMinutes) AS Actual, SUM(DebitWorkingMinutes) AS Debit
			FROM DutyRoster
			WHERE  DutyRosterTypeId = 0
					AND ContractId IN (SELECT Id FROM @contractids)
					AND Date BETWEEN @start AND @end
			GROUP BY ContractId
END
GO

GRANT EXECUTE ON GetDutyRosterActualDebitHours TO Public
GO

--#endregion

--#region

IF NOT EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('Persons') AND c.Name = 'CompanyName') 
BEGIN
	PRINT 'Persons Add CompanyName'
	ALTER TABLE Persons ADD CompanyName VARCHAR(100) SPARSE NULL
END
GO

IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('ProductionDetails') AND c.Name = 'MemoIntern') 
BEGIN
	PRINT 'ProductionFieldTypes Add Entry Note'
	INSERT INTO ProductionFieldTypes ([Name], Code, SortInSection, IsVisibleIn, DataType, LM, LC, UM, UC, IsExportable, ShowOnPage, Settings)
	VALUES ('Notiz', 'MemoIntern', 1, 1, 1, GETDATE(), GETDATE(),-1, -1, 0, 1, '<MultiLineTextFieldSettings><ValidationAttributes /><LookupValues /><MinimumVisibleLines>7</MinimumVisibleLines></MultiLineTextFieldSettings>')

	EXEC ('DECLARE @id INT
	SELECT @id = ProductionFieldTypeId  FROM ProductionFieldTypes WHERE Code = ''MemoIntern'' AND [Name] = ''Notiz'' AND UM = -1

	INSERT INTO ProductionFieldData (ProductionId, ProductionFieldTypeId, TextValue, LM, LC, UM, UC)

	SELECT ProductionId, @id, MemoIntern, ISNULL(LM,''19000101''), ISNULL(LC,''19000101''), ISNULL(UM,-1), ISNULL(UC,-1)
	FROM ProductionDetails WHERE NOT MemoIntern IS NULL')

	EXEC sp_rename 'ProductionDetails.MemoIntern', 'x_MemoIntern', 'COLUMN';
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('CastRules') AND c.Name = 'PreparationMinutes') 
BEGIN
	ALTER TABLE CastRules ADD PreparationMinutes SMALLINT NOT NULL CONSTRAINT DF_CastRules_PreparationMinutes DEFAULT 0
	ALTER TABLE CastRules ADD PostProcessingMinutes SMALLINT NOT NULL CONSTRAINT DF_CastRules_PostProcessingMinutes DEFAULT 0
	EXEC ('UPDATE CastRules SET PreparationMinutes = rt.PreparationDuration FROM CastRules AS cs INNER JOIN RoleTypes AS rt ON cs.RoleTypeId = rt.RoleTypeId WHERE rt.PreparationDuration <> 0')
	EXEC sp_rename 'RoleTypes.PreparationDuration', 'x_PreparationDuration', 'COLUMN';
END
GO
--#endregion

--#region
IF NOT EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('ProductionAttachments') AND c.Name = 'OwnerGroupId') 
BEGIN
	PRINT 'Persons Add ProductionAttachments.OwnerGroupId'
	ALTER TABLE ProductionAttachments ADD OwnerGroupId INT NULL
	EXEC ('UPDATE ProductionAttachments SET OwnerGroupId = p.OwnerGroupId FROM ProductionAttachments AS pa INNER JOIN Productions AS p ON pa.ProductionId = p.ProductionId')
	ALTER TABLE ProductionAttachments ALTER COLUMN OwnerGroupId INT NOT NULL 
	ALTER TABLE ProductionAttachments WITH CHECK ADD CONSTRAINT FK_ProductionAttachments_OwnerGroups FOREIGN KEY(OwnerGroupId)
		REFERENCES  OwnerGroups	(OwnerGroupId)
	ALTER TABLE ProductionAttachments CHECK CONSTRAINT FK_ProductionAttachments_OwnerGroups
	
	INSERT INTO [Permissions] (OwnerGroupId, UserId, HasWritePermission, LM, UM, LC, UC, PermissionArea, OptionsFlag, IsInherited)
	SELECT OwnerGroupId, UserId, HasWritePermission, LM, UM, LC, UC, 21, OptionsFlag, IsInherited FROM [Permissions]  WHERE PermissionArea = 3
    
	CREATE TABLE dbo.ProductionAttachmentCategories(
		ProductionAttachmentCategoryId INT IDENTITY(1,1) NOT NULL,
		[Name] VARCHAR(30) NOT NULL,
		Code VARCHAR(15) NOT NULL,
		[Description] VARCHAR(1000) NULL,
		Sort SMALLINT NOT NULL CONSTRAINT DF_ProductionAttachmentCategories_Sort DEFAULT 0,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_PersonsOrganigramEnties_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_PersonsOrganigramEnties_LC DEFAULT GETDATE(),
		UC INT NULL
		CONSTRAINT PK_ProductionAttachmentCategoryId PRIMARY KEY CLUSTERED (ProductionAttachmentCategoryId) ON [PRIMARY])

	CREATE UNIQUE INDEX IX_ProductionAttachmentCategories_Name ON dbo.ProductionAttachmentCategories ([Name]) 
	CREATE UNIQUE INDEX IX_ProductionAttachmentCategories_Coe ON dbo.ProductionAttachmentCategories (Code) 
	GRANT SELECT ON ProductionAttachmentCategories TO [public]
	GRANT INSERT, UPDATE, DELETE ON ProductionAttachmentCategories TO DispoAdmin

	ALTER TABLE ProductionAttachments ADD ProductionAttachmentCategoryId INT NULL

	ALTER TABLE ProductionAttachments WITH CHECK ADD CONSTRAINT FK_ProductionAttachments_ProductionAttachmentCategories FOREIGN KEY(ProductionAttachmentCategoryId)
		REFERENCES  ProductionAttachmentCategories	(ProductionAttachmentCategoryId)
	ALTER TABLE ProductionAttachments CHECK CONSTRAINT FK_ProductionAttachments_ProductionAttachmentCategories

	PRINT('Add DataService...')
	EXEC sp_addrole @rolename = N'DataService'
	
	GRANT INSERT, UPDATE, DELETE ON ProductionAttachments TO DataService
	REVOKE INSERT, UPDATE, DELETE ON ProductionAttachments TO Public

	GRANT INSERT, UPDATE, DELETE ON PersonAttachments TO DataService
	REVOKE INSERT, UPDATE, DELETE ON PersonAttachments TO Public

	DECLARE @userName VARCHAR(128)
	SELECT @userName = UserName FROM Users WHERE Users.KnownUserType = 1 ORDER BY Users.IsInactive
	IF (NOT @userName IS NULL AND @userName <> 'dbo') EXEC sp_addrolemember N'DataService', @userName;  

END
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='TourAttachments')
BEGIN
	PRINT('Add TourAttachments...')
	CREATE TABLE dbo.TourAttachments(
		TourAttachmentId INT IDENTITY(1,1) NOT NULL,
		TourId INT NOT NULL,
		AttachmentId INT NOT NULL,
		Note VARCHAR(1024) NULL,
		Sort INT NOT NULL CONSTRAINT DF_TourAttachments_Sort  DEFAULT (0),
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_TourAttachments_LC DEFAULT GETDATE(),
		UC INT NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_TourAttachments_LM DEFAULT GETDATE(),
		UM INT NOT NULL,
	 CONSTRAINT PK_TourAttachments PRIMARY KEY NONCLUSTERED (TourAttachmentId ASC)  ON [PRIMARY]
	) ON [PRIMARY]

	CREATE  CLUSTERED INDEX IX_TourAttachments_TourId  ON TourAttachments (TourId) ON [PRIMARY]

	ALTER TABLE dbo.TourAttachments  WITH CHECK ADD  CONSTRAINT FK_TourAttachments_Attachments FOREIGN KEY(AttachmentId)
	REFERENCES dbo.Attachments (AttachmentId)
	ALTER TABLE dbo.TourAttachments CHECK CONSTRAINT FK_TourAttachments_Attachments
	
	ALTER TABLE dbo.TourAttachments  WITH CHECK ADD  CONSTRAINT FK_TourAttachments_Tours FOREIGN KEY(TourId)
	REFERENCES dbo.Tours (TourId)
	ALTER TABLE dbo.TourAttachments CHECK CONSTRAINT FK_TourAttachments_Tours
	GRANT INSERT, UPDATE, DELETE ON PersonAttachments TO DataService

	ALTER TABLE Tours_Contracts ADD StartDate DATE NULL
	ALTER TABLE Tours_Contracts ADD EndDate DATE NULL
	ALTER TABLE Tours_Contracts ADD Note VARCHAR(1024) NULL
	EXEC('ALTER TABLE Tours_Contracts WITH CHECK ADD  CONSTRAINT [CK_Tours_Contracts_PeriodCheck] CHECK  (StartDate <= EndDate OR StartDate IS NULL OR EndDate IS NULL)')
	EXEC('ALTER TABLE Tours_Contracts CHECK CONSTRAINT [CK_Tours_Contracts_PeriodCheck]')
END
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbPersonAttachments') AND type <> 'U') DROP VIEW dbo.AbPersonAttachments
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbPersonAttachments_Update') AND type <> 'U') DROP VIEW dbo.AbPersonAttachments_Update
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='ProductionPartners')
BEGIN
	PRINT('Add ProductionPartners...')
	CREATE TABLE dbo.ProductionPartners(
		ProductionPartnerId INT IDENTITY(1,1) NOT NULL,
		ProductionId INT NOT NULL,
		PersonId INT NOT NULL,
		Note VARCHAR(1024) NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ProductionPartners_LC DEFAULT GETDATE(),
		UC INT NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ProductionPartners_LM DEFAULT GETDATE(),
		UM INT NOT NULL,
	 CONSTRAINT PK_ProductionPartners PRIMARY KEY NONCLUSTERED (ProductionPartnerId)  ON [PRIMARY]
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_ProductionPartnersProductionId ON ProductionPartners (ProductionId) ON [PRIMARY]
	CREATE INDEX IX_ProductionPartnersPersobnId ON ProductionPartners (PersonId) ON [PRIMARY]

	ALTER TABLE dbo.ProductionPartners  WITH CHECK ADD CONSTRAINT FK_ProductionPartners_Productions FOREIGN KEY(ProductionId)
	REFERENCES dbo.Productions (ProductionId) ON DELETE CASCADE
	ALTER TABLE dbo.ProductionPartners CHECK CONSTRAINT FK_ProductionPartners_Productions

	ALTER TABLE dbo.ProductionPartners  WITH CHECK ADD CONSTRAINT FK_ProductionPartners_Persons FOREIGN KEY(PersonId)
	REFERENCES dbo.Persons (PersonId) ON DELETE CASCADE
	ALTER TABLE dbo.ProductionPartners CHECK CONSTRAINT FK_ProductionPartners_Persons

	GRANT SELECT ON ProductionPartners TO [Public]
END
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbProductionPartners_Update') AND type <> 'U') DROP VIEW dbo.AbProductionPartners_Update
GO

CREATE VIEW dbo.AbProductionPartners_Update
AS
	SELECT *
	FROM ProductionPartners AS pp
		WHERE pp.ProductionId IN (
				SELECT p.ProductionId
				FROM [Permissions] ug
					INNER JOIN Users u ON ug.Userid = u.Userid
					INNER JOIN Productions p ON p.OwnerGroupId = ug.OwnerGroupId
				WHERE u.Username = CURRENT_USER
					AND ug.PermissionArea = 3
					AND ug.HasWritePermission = 1
			)		
WITH CHECK OPTION
GO

GRANT SELECT, INSERT, UPDATE, DELETE ON AbProductionPartners_Update TO Public
GO

--#endregion

--#region

--CREATE TABLE dbo.PersonsOrganigramEnties(
--	PersonsOrganigramEntryId INT IDENTITY(1,1) NOT NULL,
--	PersonId INT NOT NULL,
--	ContractId INT NULL,
--	StartDate DATE NULL,
--	EndDate DATE NULL,
--	OrganigramJobId INT NOT NULL,
--	OrderNumerInJob SMALLINT NOT NULL CONSTRAINT DF_PersonsOrganigramEnties_OrderNumerInJob DEFAULT 0,
--	JobDescription VARCHAR(256),
--	LM SMALLDATETIME NOT NULL CONSTRAINT DF_PersonsOrganigramEnties_LM DEFAULT GETDATE(),
--	UM INT NULL,
--	LC SMALLDATETIME NOT NULL CONSTRAINT DF_PersonsOrganigramEnties_LC DEFAULT GETDATE(),
--	UC INT NULL
--CONSTRAINT PK_PersonsOrganigramId PRIMARY KEY CLUSTERED (PersonsOrganigramEntryId) ON [PRIMARY])
--CREATE INDEX IX_PersonId ON dbo.PersonsOrganigramEnties (PersonId) 
--CREATE INDEX IX_ContractId ON dbo.PersonsOrganigramEnties (ContractId) 

--ALTER TABLE PersonsOrganigramEnties WITH CHECK ADD CONSTRAINT FK_PersonsOrganigramEnties_Persons FOREIGN KEY(PersonId)
--REFERENCES  Persons	(PersonId)
--ALTER TABLE PersonsOrganigramEnties CHECK CONSTRAINT FK_PersonsOrganigramEnties_Persons	

--ALTER TABLE PersonsOrganigramEnties WITH CHECK ADD CONSTRAINT FK_PersonsOrganigramEnties_Contracts FOREIGN KEY(ContractId)
--REFERENCES Contracts (ContractId)
--ALTER TABLE PersonsOrganigramEnties CHECK CONSTRAINT FK_PersonsOrganigramEnties_Contracts	

--ALTER TABLE PersonsOrganigramEnties WITH CHECK ADD CONSTRAINT FK_PersonsOrganigramEnties_OrganigramJobs FOREIGN KEY(OrganigramJobId)
--REFERENCES Aufgabe (AufgabeNr)
--ALTER TABLE PersonsOrganigramEnties CHECK CONSTRAINT FK_PersonsOrganigramEnties_OrganigramJobs	

--INSERT INTO PersonsOrganigramEnties (PersonId,ContractId,OrganigramJobId,OrderNumerInJob,JobDescription, LM, UM, LC, UC)
--SELECT PersonId, ContractId ,Contracts.AufgabeNr, ISNULL(BJBSort, 0), BJBGenPos, ISNULL(Contracts.lm,'19000100'), Contracts.um, ISNULL(Contracts.LC,'19000100'), Contracts.uc FROM Contracts INNER JOIN Aufgabe ON Contracts.AufgabeNr = Aufgabe.AufgabeNr
--GO
--#endregion

--#endregion ------- (4.211.x) --------------------------------

--#region ----------- 4.211.x Release Übertrag ----------------

--#region Schicht mit ID 0 auf Arbeitszeit setzen

IF NOT EXISTS (SELECT * FROM ShiftTypes INNER JOIN TimeAccounts ON ShiftTypes.TimeAccountId = TimeAccounts.TimeAccountId WHERE ShiftTypeId = 0 AND TimeAccounts.Formel = 1)
BEGIN
	IF NOT EXISTS (SELECT * FROM TimeAccounts WHERE TimeAccounts.Formel = 1)
	BEGIN
		IF EXISTS (SELECT * FROM TimeAccounts WHERE TimeAccounts.Name = 'Arbeitszeit' AND Formel = 0) 
		BEGIN
			Print 'Konto korrigiert'
			UPDATE TimeAccounts SET Formel = 1 WHERE TimeAccounts.Name = 'Arbeitszeit' AND Formel = 0 
		END
	END


	IF EXISTS (SELECT * FROM TimeAccounts WHERE TimeAccounts.Formel = 1)
		BEGIN
		Print 'Schicht korrigiert'
			UPDATE ShiftTypes SET TimeAccountId = (SELECT TOP 1 TimeAccountId FROM TimeAccounts WHERE TimeAccounts.Formel = 1) WHERE ShiftTypeId = 0 
			UPDATE ShiftTypes SET [Name] = LEFT(TimeAccounts.[Name], 15) FROM ShiftTypes INNER JOIN TimeAccounts ON ShiftTypes.TimeAccountId = TimeAccounts.TimeAccountId WHERE ShiftTypeId = 0
		END
	ELSE
		BEGIN
			IF EXISTS (SELECT * FROM UserLicenses WHERE LicenseType = 2)
				BEGIN
					RAISERROR('In thea.perso ist ein Konto mit der Formel Arbeitszeit erforderlich', 20, -1) WITH LOG
					SET NOEXEC ON
				END
		END
END
GO

--#endregion
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('Tours_Contracts') AND [name] = 'PersonId')
BEGIN
PRINT('Tours_Contracts->PersonId...')
	ALTER TABLE Tours_Contracts ADD PersonId INT NULL
	EXEC('UPDATE Tours_Contracts SET Tours_Contracts.PersonId = Contracts.PersonId FROM Tours_Contracts INNER JOIN Contracts ON Tours_Contracts.ContractId=Contracts.ContractId')
	ALTER TABLE Tours_Contracts ALTER COLUMN PersonId INT NOT NULL
	ALTER TABLE Tours_Contracts ALTER COLUMN ContractId INT NULL	
	

END
GO
--#region 2021-03-11 PersonInCategories zusammenführen

ALTER PROCEDURE [dbo].[MergeDoubletten]
	@PersonId INT, 
	@DoubletteId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	BEGIN TRY
		BEGIN TRAN
			UPDATE Auditions			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId 
			UPDATE BankAccounts			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE BasicCast			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE [Cast]				SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonInCategories	SET PersonId = @PersonId WHERE  PersonId = @DoubletteId AND PersonCategoryId NOT IN (SELECT PersonCategoryId FROM PersonInCategories WHERE  PersonId = @PersonId)
			UPDATE BodyMeasurements		SET PersonId = @PersonId, MeasuredAt = DATEADD(minute, 1, MeasuredAt) WHERE  PersonId = @DoubletteId
			UPDATE CashCommands			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE CashCommands			SET AgencyId = @PersonId WHERE  AgencyId = @DoubletteId
			UPDATE CheckListItem		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE CheckListItemTemplate SET PersonId= @PersonId WHERE  PersonId = @DoubletteId
	
			UPDATE dc SET PersonId = @PersonId FROM DepartmentCollectives dc 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM DepartmentCollectives d2 WHERE d2.DepartmentId = dc.DepartmentId AND d2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM MeasureParticipations mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM MeasureParticipations mp2 WHERE mp2.MeasureTypeId = mp.MeasureTypeId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM PersonRequiredMeasureTypes mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes mp2 WHERE mp2.MeasureTypeId = mp.MeasureTypeId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM Tours_Contracts mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM Tours_Contracts mp2 WHERE mp2.TourContractId = mp.TourContractId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM ProductionPartners mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM ProductionPartners mp2 WHERE mp2.ProductionId = mp.ProductionId AND mp2.PersonId = @PersonId);
				

			UPDATE Departments			SET HeadOfDepartmentId = @PersonId 
																 WHERE  HeadOfDepartmentId = @DoubletteId
			UPDATE MailingListEntries	SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Orders				SET SupplierId = @PersonId WHERE  SupplierId = @DoubletteId
			UPDATE OrderTravelers		SET TravelerId = @PersonId WHERE  TravelerId = @DoubletteId
			--Verweise zwischen Dublette und Zielperson werden gelöscht
			DELETE FROM PersonRelations WHERE PersonId = @PersonId AND ChildPersonId = @DoubletteId
			DELETE FROM PersonRelations WHERE PersonId = @DoubletteId AND ChildPersonId = @PersonId
	
			UPDATE PersonRelations		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId 
			UPDATE PersonRelations		SET ChildPersonId = @PersonId WHERE  ChildPersonId = @DoubletteId
	
			IF NOT EXISTS (SELECT * FROM PersonEmployee WHERE  PersonId=@PersonId)
				BEGIN
					UPDATE PersonEmployee SET PersonId=@PersonId WHERE  PersonId= @DoubletteId
				END
			ELSE
				BEGIN
					DELETE FROM PersonEmployee WHERE  PersonId = @DoubletteId
				END
			UPDATE PersonMemo					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonAdditionalData			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Qualification_Person			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE ResourceObjectBorrows		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE ResourceObjectInsurances		SET InsuredPersonId = @PersonId 
																 WHERE  InsuredPersonId = @DoubletteId
			UPDATE ResourceObjects				SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonStatus					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Travels						SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Contracts					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkCreators					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkVersionRoles_Repertoire  SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkVersionRoles_Repertoire  SET TheaterId = @PersonId WHERE  TheaterId = @DoubletteId
			UPDATE WorkVersions					SET PublisherId = @PersonId WHERE  PublisherId = @DoubletteId
			UPDATE Locations					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE BasicCastHistory				SET PersonNewId = @PersonId	WHERE PersonNewId = @DoubletteId
			UPDATE MeasureParticipations		SET PersonId = @PersonId	WHERE PersonId = @DoubletteId 
				AND MeasureParticipationId NOT IN (SELECT MeasureParticipationId FROM MeasureParticipations AS a WHERE  PersonId = @PersonId AND a.MeasureTypeId = MeasureParticipations.MeasureTypeId AND a.ParticipationDate = MeasureParticipations.ParticipationDate  )
			UPDATE PersonRequiredMeasureTypes		SET PersonId = @PersonId	WHERE PersonId = @DoubletteId
				AND PersonRequiredMeasureTypeId NOT IN (SELECT PersonRequiredMeasureTypeId FROM PersonRequiredMeasureTypes AS a WHERE  PersonId = @PersonId AND a.MeasureTypeId = PersonRequiredMeasureTypes.MeasureTypeId)
			DELETE From MeasureParticipations	WHERE PersonId = @DoubletteId
			DELETE FROM PersonRequiredMeasureTypes	WHERE  PersonId = @DoubletteId
			
			DELETE From DepartmentCollectives WHERE PersonId = @DoubletteId
			DELETE From MeasureParticipations WHERE PersonId = @DoubletteId
			DELETE From PersonRequiredMeasureTypes WHERE PersonId = @DoubletteId
			DELETE From Tours_Contracts WHERE PersonId = @DoubletteId
			DELETE From ProductionPartners WHERE PersonId = @DoubletteId

			DELETE FROM PersonInCategories	WHERE  PersonId = @DoubletteId
			DELETE FROM Qualification_Person WHERE  PersonId = @DoubletteId AND Qualification_Person.QualificationId IN (SELECT QualificationId FROM Qualification_Person WHERE  PersonId = @PersonId)
			DELETE FROM PersonPermissions	WHERE PersonId = @DoubletteId
			DELETE FROM PersonContactData	WHERE PersonId = @DoubletteId
			DELETE FROM PersonAddress		WHERE PersonId = @DoubletteId
			DELETE FROM PersonDetails		WHERE PersonId = @DoubletteId
			DELETE FROM PersonFeeNotes		WHERE PersonId = @DoubletteId
			DELETE FROM Persons				WHERE PersonId = @DoubletteId
		COMMIT TRAN
	END TRY

	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK TRAN

		DECLARE @ErrorMessage NVARCHAR(4000);  
		DECLARE @ErrorSeverity INT;  
		DECLARE @ErrorState INT;  
  
		SELECT   
			@ErrorMessage = ERROR_MESSAGE(),  
			@ErrorSeverity = ERROR_SEVERITY(),  
			@ErrorState = ERROR_STATE();  

		RAISERROR (@ErrorMessage, -- Message text.  
				   @ErrorSeverity, -- Severity.  
				   @ErrorState -- State.  
				   );
	END CATCH
END 
GO

--#endregion (2021-03-11 PersonInCategories zusammenführen)

--#region SH 2021-03-11 Berechtigungen korrigieren

REVOKE SELECT, INSERT, UPDATE, DELETE FROM [public], [DispoAdmin], [WorksWrite]
GRANT SELECT ON [ActivityStatuses] TO [public]
GRANT INSERT, UPDATE, DELETE ON [ActivityStatuses] TO [DispoAdmin]
GRANT SELECT, INSERT, UPDATE, DELETE ON [PersonInCategories] TO [public]
GRANT SELECT, INSERT, UPDATE, DELETE ON [WorkVersionTimeFlow] TO [WorksWrite]
GO
--#endregion

--#region TK 2021-03-16
UPDATE Roles SET PersonCount = 1 FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId =OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND  PersonCount = 0
GO
--#endregion

--#region DH 2021-03-16
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkingTimeModels') AND [name] = 'AllowDebitRecalculate')
BEGIN
	PRINT('Adding AllowDebitRecalculate to WorkingTimeModels')
	ALTER TABLE WorkingTimeModels ADD AllowDebitRecalculate BIT NOT NULL Constraint DF_WorkingTimeModels_AllowDebitRecalculate DEFAULT 0
END
GO

--#endregion DH 2021-03-16

--#region SH 2021-03-18 Gespeicherte Suchfilter korrigieren
UPDATE OwnerGroupSettings SET SettingsXML = CONVERT(XML,REPLACE(CONVERT(nvarchar(MAX),SettingsXml),'PersZDTypID','PersonAdditionalDataTypeId'))
WHERE SettingSection = 'frmPersSuche' AND PermissionAreaId=11 AND CONVERT(nvarchar(MAX),SettingsXml) LIKE '%<TraitsWhere>%PersZDTypID%</TraitsWhere>%'
GO

UPDATE OwnerGroupSettings SET SettingsXML = CONVERT(XML,REPLACE(CONVERT(nvarchar(MAX),SettingsXml),'PersH.PersNr','Persons.PersonId'))
WHERE SettingSection = 'frmPersSuche' AND PermissionAreaId=11 AND CONVERT(nvarchar(MAX),SettingsXml) LIKE '%<TraitsWhere>%PersH.PersNr%</TraitsWhere>%'
GO

UPDATE OwnerGroupSettings SET SettingsXML = CONVERT(XML,REPLACE(CONVERT(nvarchar(MAX),SettingsXml),'ABPersZusatzDaten.PersNr','PersonAdditionalData.PersonId'))
WHERE SettingSection = 'frmPersSuche' AND PermissionAreaId=11  AND CONVERT(nvarchar(MAX),SettingsXml) LIKE '%<TraitsWhere>%ABPersZusatzDaten.PersNr%</TraitsWhere>%'
GO

UPDATE OwnerGroupSettings SET SettingsXML = CONVERT(XML,REPLACE(CONVERT(nvarchar(MAX),SettingsXml),'FROM ABPersZusatzDaten','FROM PersonAdditionalData'))
WHERE SettingSection = 'frmPersSuche' AND PermissionAreaId=11  AND CONVERT(nvarchar(MAX),SettingsXml) LIKE '%<TraitsWhere>%FROM ABPersZusatzDaten%</TraitsWhere>%'
GO
--#endregion (SH 2021-03-18 Gepsicherte Suchfilter korrigieren)

--#region //Spalten haben in einigen DBs gefehlt
IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('ProjectTaskTypes') AND [name] = 'DayExceptionRules')
BEGIN
	PRINT('Adding column ProjectTaskTypes.DayExceptionRules ...')
	ALTER TABLE dbo.ProjectTaskTypes ADD DayExceptionRules XML NULL
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('ProjectTaskTypes') AND [name] = 'ActivityTypeId')
BEGIN
	PRINT('Adding column ProjectTaskTypes.ActivityTypeId ...')
	ALTER TABLE ProjectTaskTypes ADD ActivityTypeId INT NULL
	ALTER TABLE dbo.ProjectTaskTypes ADD CONSTRAINT FK_ProjectTaskTypes_ActivityTypes FOREIGN KEY (ActivityTypeId) REFERENCES dbo.ActivityTypes (ActivityTypeId) ON DELETE SET NULL
END
GO
--#endregion
--#endregion -------- (4.211.x Release Übertrag) --------------

--#region ----------- 4.212.x ---------------------------------

--#region SH 2021-03-11 Standard BodyFormat Setzen, wenn keins vorhanden ist

UPDATE WebCalendarProfiles
	SET WebCalendarDataProviderSettings = CAST(
		REPLACE(
			CAST(WebCalendarDataProviderSettings AS NVARCHAR(MAX)),
			'</PublicActivityWebCalendarSettings>',
			'<BodyFormat>[note§f_\\n][noteTechnical§f_\\n][noteLong§f_\\n][statusName][lastModifiedOn§b_ //]</BodyFormat></PublicActivityWebCalendarSettings>')
		AS XML)
WHERE
	WebCalendarDataProvider = 'PublicActivityWebCalendarDataProvider'
	AND CAST(WebCalendarDataProviderSettings AS NVARCHAR(MAX)) NOT LIKE '%<BodyFormat>%'

--#endregion (SH 2021-03-11 Standard BodyFormat Setzen, wenn keins vorhanden ist)

--#region SH 2021-03-24 Addon Lizenzen zuweisen, da diese nicht mehr automatisch aktiv sind

IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 212 OR (Minor=212 AND Build < 1)))))
BEGIN
	PRINT('Assigning addon licenses...')
	DECLARE @license VARCHAR(MAX);
	SELECT @license = s.DataValue FROM Settings s WHERE s.Section='Application' AND s.KeyName='License' AND s.IsGlobalSetting = 1
	IF @license LIKE '%<Product>theaWorks</Product>%'  AND NOT EXISTS (SELECT * FROM UserLicenses WHERE Product = 10)
	BEGIN
		PRINT('Assigning theaWorks licenses...')
		INSERT INTO UserLicenses (UserId, Product, LicenseType, LM, UM, LC, UC)
		SELECT u.UserId, 10, 2, GETDATE(), -1, GETDATE(), -1
		FROM (
			SELECT DISTINCT ul.UserId 
			FROM UserLicenses ul WHERE ul.Product = 2
		) AS u
		WHERE NOT EXISTS (
			SELECT * FROM UserLicenses ul WHERE ul.UserId = u.UserId AND ul.Product = 10
		)
    END
	IF (@license LIKE '%<Product>PaymentOrders</Product>%' OR @license LIKE '%<Product>theaTransfer</Product>%') AND NOT EXISTS (SELECT * FROM UserLicenses WHERE Product = 11)
	BEGIN
		PRINT('Assigning theaTransfer licenses...')
    	INSERT INTO UserLicenses (UserId, Product, LicenseType, LM, UM, LC, UC)
		SELECT u.UserId, 11, 2, GETDATE(), -1, GETDATE(), -1
		FROM (
			SELECT DISTINCT ul.UserId 
			FROM UserLicenses ul WHERE ul.Product IN (1,2,3,8,9,20)
		) AS u
		WHERE NOT EXISTS (
			SELECT * FROM UserLicenses ul WHERE ul.UserId = u.UserId AND ul.Product = 11
		)
    END
	IF @license LIKE '%<Product>theaContract</Product>%' AND NOT EXISTS (SELECT * FROM UserLicenses WHERE Product = 5)
	BEGIN
		PRINT('Assigning theaContract licenses...')
		INSERT INTO UserLicenses (UserId, Product, LicenseType, LM, UM, LC, UC)
		SELECT u.UserId, 5, 2, GETDATE(), -1, GETDATE(), -1
		FROM (
			SELECT DISTINCT ul.UserId 
			FROM UserLicenses ul WHERE ul.Product IN (1,2,3,8,9,20)
		) AS u
		WHERE NOT EXISTS (
			SELECT * FROM UserLicenses ul WHERE ul.UserId = u.UserId AND ul.Product = 5
		)
    END
	IF @license LIKE '%<Product>ProductionChart</Product>%' AND NOT EXISTS (SELECT * FROM UserLicenses WHERE Product = 12)
	BEGIN
		PRINT('Assigning ProductionChart licenses...')
	    INSERT INTO UserLicenses (UserId, Product, LicenseType, LM, UM, LC, UC)
		SELECT u.UserId, 12, 2, GETDATE(), -1, GETDATE(), -1
		FROM (
			SELECT DISTINCT ul.UserId 
			FROM UserLicenses ul WHERE ul.Product IN (1,2)
		) AS u
		WHERE NOT EXISTS (
			SELECT * FROM UserLicenses ul WHERE ul.UserId = u.UserId AND ul.Product = 12
		)
    END
END
GO

--#endregion (SH 2021-03-24 Addon Lizenzen zuweisen, da diese nicht mehr automatisch aktiv sind)

--#region SH 2021-03-25 Schreibrechte für Dienstplan erweitern um Flag für Sollstundenbearbeitung

IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 212 OR (Minor=212 AND Build < 2)))))
BEGIN
	PRINT('Updating user permissions for DutyRoster...')
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|1024 WHERE HasWritePermission = 1 AND PermissionArea = 5
END
GO

--#endregion (SH 2021-03-25 Schreibrechte für Dienstplan erweitern um Flag für Sollstundenbearbeitung)

--#region DH 2020-03-24
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='MeasureTypes')
BEGIN

PRINT 'Create MeasureTypes'
CREATE TABLE dbo.MeasureTypes(
	MeasureTypeId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeCategory TINYINT NOT NULL CONSTRAINT DF_MeasureTypes_MeasureTypeCategory DEFAULT 0,
	[Name] VARCHAR(50) NOT NULL,
	[Description] VARCHAR(MAX) NULL,
	Sort SMALLINT NOT NULL  CONSTRAINT DF_MeasureTypes_Sort DEFAULT 0,
	ReoccurenceSettings XML NULL,
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypes_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypes_LC DEFAULT GETDATE(),
    UC INT NULL,
    CONSTRAINT PK_MeasureTypes PRIMARY KEY CLUSTERED (MeasureTypeId) ON [PRIMARY]
	) ON [PRIMARY]			
END
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='MeasureParticipations')
BEGIN

PRINT 'Create MeasureParticipations'
CREATE TABLE dbo.MeasureParticipations(
	MeasureParticipationId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeId INT NOT NULL,
	PersonId INT NOT NULL,
	ParticipationDate DATE NOT NULL CONSTRAINT DF_MeasureParticipations_ParticipationDate DEFAULT GETDATE(),
	[Description] VARCHAR(MAX) NULL,
	[Location] VARCHAR(200) NULL,
	CastId INT NULL, 
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureParticipations_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureParticipations_LC DEFAULT GETDATE(),
    UC INT NULL,
	CONSTRAINT FK_MeasureParticipations_Persons FOREIGN KEY(PersonId)
		REFERENCES Persons (PersonId) ON DELETE CASCADE,
	CONSTRAINT FK_MeasureParticipations_MeasureTypes FOREIGN KEY (MeasureTypeId)
		REFERENCES MeasureTypes (MeasureTypeId),
	CONSTRAINT FK_MeasureParticipations_Casts FOREIGN KEY(CastId)
		REFERENCES [Cast] (CastId) ON DELETE SET NULL, 
    CONSTRAINT PK_MeasureParticipations PRIMARY KEY NONCLUSTERED (MeasureParticipationId) ON [PRIMARY]
	) ON [PRIMARY];
	
	CREATE UNIQUE CLUSTERED INDEX IX_MeasureParticipations_PersonId_ParticipationDate_MeasureTypeId ON MeasureParticipations (PersonId, ParticipationDate, MeasureTypeId) ON [PRIMARY]
	CREATE INDEX IX_MeasureParticipations_MeasureTypeId ON MeasureParticipations (MeasureTypeId) ON [PRIMARY]
	CREATE INDEX IX_MeasureParticipations_CastId ON MeasureParticipations (CastId) ON [PRIMARY]
	CREATE INDEX IX_MeasureParticipations_ParticipationDate ON MeasureParticipations (ParticipationDate) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='PersonRequiredMeasureTypes')
BEGIN

PRINT 'Create PersonRequiredMeasureTypes'
CREATE TABLE dbo.PersonRequiredMeasureTypes(
	PersonRequiredMeasureTypeId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeId INT NOT NULL,
	PersonId INT NOT NULL,
	[Description] VARCHAR(MAX) NULL,
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_PersonRequiredMeasureTypes_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_PersonRequiredMeasureTypes_LC DEFAULT GETDATE(),
    UC INT NULL,
	CONSTRAINT FK_PersonRequiredMeasureTypes_MeasureTypes FOREIGN KEY(MeasureTypeId)
		REFERENCES MeasureTypes (MeasureTypeId),
	CONSTRAINT FK_PersonRequiredMeasureTypes_Persons FOREIGN KEY(PersonId)
		REFERENCES Persons (PersonId) ON DELETE CASCADE,
    CONSTRAINT PK_PersonRequiredMeasureTypes PRIMARY KEY NONCLUSTERED (PersonRequiredMeasureTypeId) ON [PRIMARY]
	) ON [PRIMARY]
	CREATE UNIQUE CLUSTERED INDEX IX_PersonRequiredMeasureTypes_PersonId_MeasureTypeID ON PersonRequiredMeasureTypes(PersonId, MeasureTypeId)
	CREATE INDEX IX_PersonRequiredMeasureTypes_MeasureTypeId ON PersonRequiredMeasureTypes (MeasureTypeId) ON [PRIMARY]
END


IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='DepartmentRequiredMeasureTypes')
BEGIN

PRINT 'Create DepartmentRequiredMeasureTypes'
CREATE TABLE dbo.DepartmentRequiredMeasureTypes(
	DepartmentRequiredMeasureTypeId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeId INT NOT NULL,
	DepartmentId INT NOT NULL,
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_DepartmentRequiredMeasureTypes_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_DepartmentRequiredMeasureTypes_LC DEFAULT GETDATE(),
    UC INT NULL,
	CONSTRAINT FK_DepartmentRequiredMeasureTypes_MeasureTypes FOREIGN KEY(MeasureTypeId)
		REFERENCES MeasureTypes (MeasureTypeId) ON DELETE CASCADE,
	CONSTRAINT FK_DepartmentRequiredMeasureTypes_Departments FOREIGN KEY(DepartmentId	)
		REFERENCES Departments (DepartmentId) ON DELETE CASCADE,
    CONSTRAINT PK_DepartmentRequiredMeasureTypes PRIMARY KEY NONCLUSTERED (DepartmentRequiredMeasureTypeId) ON [PRIMARY]
	) ON [PRIMARY];
	CREATE UNIQUE CLUSTERED INDEX IX_DepartmentRequiredMeasureTypes_DepartmentId ON DepartmentRequiredMeasureTypes(Departmentid, MeasuretypeId) ON [PRIMARY]
	CREATE INDEX IX_DepartmentRequiredMeasureTypes_MeasureTypeId ON DepartmentRequiredMeasureTypes (MeasureTypeId) ON [PRIMARY]
END
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='QualificationRequiredMeasureTypes')
BEGIN

PRINT 'Create QualificationRequiredMeasureTypes'
CREATE TABLE dbo.QualificationRequiredMeasureTypes(
	QualificationRequiredMeasureTypeId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeId INT NOT NULL,
	QualificationId INT NOT NULL,
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_QualificationRequiredMeasureTypes_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_QualificationRequiredMeasureTypes_LC DEFAULT GETDATE(),
    UC INT NULL,
	CONSTRAINT FK_QualificationRequiredMeasureTypes_Qualifications FOREIGN KEY(QualificationId)
		REFERENCES Qualification (QualificationId),
	CONSTRAINT FK_QualificationRequiredMeasureTypes_MeasureTypes FOREIGN KEY(MeasureTypeId)
		REFERENCES MeasureTypes (MeasureTypeId),
    CONSTRAINT PK_QualificationRequiredMeasureTypes PRIMARY KEY NONCLUSTERED (QualificationRequiredMeasureTypeId) ON [PRIMARY]
	) ON [PRIMARY];
	CREATE UNIQUE CLUSTERED INDEX IX_QualificationRequiredMeasureTypes_QualificationId_MeasureTypeId ON QualificationRequiredMeasureTypes (QualificationId, MeasureTypeId) ON [PRIMARY]
	CREATE INDEX IX_QualificationRequiredMeasureTypes_MeasureTypeId ON QualificationRequiredMeasureTypes (MeasureTypeId) ON [PRIMARY]
END

IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='MeasureTypesInActivities')
BEGIN
PRINT 'Create MeasureTypesInActivities'
CREATE TABLE dbo.MeasureTypesInActivities(
	MeasureTypesInActivityId INT IDENTITY(1,1) NOT NULL,
	MeasureTypeId INT NOT NULL,
	ActivityId INT NOT NULL,
	LM SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypesInActivities_LM DEFAULT GETDATE(),
    UM INT NULL,
    LC SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypesInActivities_LC DEFAULT GETDATE(),
    UC INT NULL,
	CONSTRAINT FK_MeasureTypesInActivities_Activities FOREIGN KEY(ActivityId)
		REFERENCES Activities (ActivityId) ON DELETE CASCADE,
	CONSTRAINT FK_MeasureTypesInActivities_MeasureTypes FOREIGN KEY(MeasureTypeId)
		REFERENCES MeasureTypes (MeasureTypeId),
    CONSTRAINT PK_MeasureTypesInActivities PRIMARY KEY NONCLUSTERED (MeasureTypesInActivityId) ON [PRIMARY]
	) ON [PRIMARY];
	CREATE UNIQUE CLUSTERED INDEX IX_MeasureTypesInActivities_ActivityId_MeasureTypeId ON MeasureTypesInActivities (ActivityId, MeasureTypeId) ON [PRIMARY]
	CREATE INDEX IX_MeasureTypesInActivities_MeasureTypeId ON MeasureTypesInActivities (MeasureTypeId) ON [PRIMARY]
END
GO
--#endregion 2020-03-24
--#region 2020-04-09 
if NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = 'StaffAdmin')
BEGIN
	EXEC sp_addrole @rolename = N'StaffAdmin'
END
GO

GRANT SELECT ON [QualificationRequiredMeasureTypes] TO [public]
GRANT INSERT, UPDATE, DELETE ON [QualificationRequiredMeasureTypes] TO [StaffAdmin]

GRANT SELECT ON [DepartmentRequiredMeasureTypes] TO [public]
GRANT INSERT, UPDATE, DELETE ON [DepartmentRequiredMeasureTypes] TO [StaffAdmin]

GRANT SELECT ON [MeasureTypes] TO [public]
GRANT INSERT, UPDATE, DELETE ON [MeasureTypes] TO [StaffAdmin]

GRANT SELECT, INSERT, UPDATE, DELETE ON [MeasureParticipations] TO [public]
GRANT SELECT, INSERT, UPDATE, DELETE ON [PersonRequiredMeasureTypes] TO [public]
GRANT SELECT, INSERT, UPDATE, DELETE ON [MeasureTypesInActivities] TO [public]
GO

--#endregion 2020-04-09

--#region SH 2021-03-25 Umbenennen der Spalte [DutyRoster].[IsHolidayCountManual] nach [CalculateHolidayCount]
IF EXISTS (SELECT * FROM sys.columns c WHERE c.object_id = OBJECT_ID('DutyRoster') AND c.Name = 'IsHolidayCountManual')
BEGIN
	PRINT('Renaming [DutyRoster].[IsHolidayCountManual] to [CalculateHolidayCount]...')
	ALTER TABLE [dbo].[DutyRoster] DROP CONSTRAINT [DF_DutyRoster_IsHolidayCountManual]
	EXEC sp_rename '[DutyRoster].[IsHolidayCountManual]' , 'CalculateHolidayCount', 'COLUMN'
	EXEC('ALTER TABLE [dbo].[DutyRoster] ADD  CONSTRAINT [DF_DutyRoster_CalculateHolidayCount]  DEFAULT 1 FOR [CalculateHolidayCount]')
END
GO

--#region CopyDutyRoster aktualisieren, da Spalte umbenannt wurde

-- verschoben, da Bugfix notwendig war

--#endregion (CopyDutyRoster aktualisieren, da Spalte umbenannt wurde)

--#endregion (SH 2021-03-25 Umbenennen der Spalte [DutyRoster].[IsHolidayCountManual] nach [CalculateHolidayCount])

--#region SH 2021-03-29 Spalten für Dienste pro Monat in Vertragsart und Dienste pro Woche/Monat/Spielzeit in Abw. Arbeitszeiten

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractTypes') AND [name] = 'DebitServicesCountPerMonth')
BEGIN
	PRINT('Adding ContractTypes.DebitServicesCountPerMonth ...')
	ALTER TABLE dbo.ContractTypes ADD DebitServicesCountPerMonth FLOAT NOT NULL
	CONSTRAINT DF_ContractTypes_DebitServicesCountPerMonth DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractPartTimePeriods') AND [name] = 'DebitServicesCountPerWeek')
BEGIN
	PRINT('Adding ContractPartTimePeriods.DebitServicesCountPerWeek ...')
	ALTER TABLE dbo.ContractPartTimePeriods ADD DebitServicesCountPerWeek FLOAT NOT NULL 
	CONSTRAINT DF_ContractPartTimePeriods_DebitServicesCountPerWeek DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractPartTimePeriods') AND [name] = 'DebitServicesCountPerMonth')
BEGIN
	PRINT('Adding ContractPartTimePeriods.DebitServicesCountPerMonth ...')
	ALTER TABLE dbo.ContractPartTimePeriods ADD DebitServicesCountPerMonth FLOAT NOT NULL
	CONSTRAINT DF_ContractPartTimePeriods_DebitServicesCountPerMonth DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractPartTimePeriods') AND [name] = 'DebitServicesCountPerSeason')
BEGIN
	PRINT('Adding ContractPartTimePeriods.DebitServicesCountPerSeason ...')
	ALTER TABLE dbo.ContractPartTimePeriods ADD DebitServicesCountPerSeason FLOAT NOT NULL 
	CONSTRAINT DF_ContractPartTimePeriods_DebitServicesCountPerSeason DEFAULT 0
END
GO
	
--#endregion (SH 2021-03-29 Spalten für Dienste pro Monat in Vertragsart und Dienste pro Woche/Monat/Spielzeit in Abw. Arbeitszeiten)

--#region 2021-04-09
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Salutations') AND [name] = 'SalutationType')
BEGIN
	PRINT('Adding Salutations.SalutationType ...')
	ALTER TABLE Salutations ADD SalutationType TINYINT NOT NULL CONSTRAINT DF_Salutations_SalutationType DEFAULT 0
	EXEC('UPDATE Salutations SET SalutationType = IsMale+1 WHERE NOT IsMale IS NULL')
	EXEC('UPDATE Salutations SET SalutationType = 5 WHERE Name LIKE ''Firma%'' OR Name = ''Perhe'' OR Name = ''Company''' )
	EXEC('UPDATE Salutations SET SalutationType = 4 WHERE Name = ''Familie'' OR Name = ''Family''')
	ALTER TABLE Salutations DROP COLUMN IsMale
	ALTER TABLE Salutations ADD IsMale AS CAST((CASE WHEN SalutationType BETWEEN 1 AND 2 THEN SalutationType-1 ELSE NULL END) AS BIT)
	UPDATE Roles SET Roles.CalculationSalaryLevelId = RoleTypes.CalculationSalaryLevelId FROM Roles INNER JOIN RoleTypes ON Roles.RoleTypeId = RoleTypes.RoleTypeId
		WHERE Roles.CalculationSalaryLevelId IS NULL AND NOT RoleTypes.CalculationSalaryLevelId IS NULL
END
GO
--#endregion

--#region SH 2021-04-14 PrintMode in Cast, RoleType und Role anpassen

PRINT('Fixing wrong PrintMode values in RoleTypes, Roles and Cast...')
UPDATE RoleTypes SET PrintMode = 2 WHERE PrintMode IS NULL OR PrintMode = 0
UPDATE Roles SET PrintMode = 2 WHERE PrintMode IS NULL OR PrintMode = 0
UPDATE [Cast] SET PrintMode = NULL WHERE PrintMode = 0
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleTypes') AND [name] = 'PrintMode' AND is_nullable = 0)
BEGIN
	PRINT('Changing RoleTypes.PrintMode to NOT NULL...')
	ALTER TABLE [RoleTypes] ALTER COLUMN PrintMode TINYINT NOT NULL
END
GO

IF NOT EXISTS(SELECT * FROM sys.default_constraints dc WHERE dc.Name = 'DF_RoleTypes_PrintMode')
BEGIN
	PRINT('Adding DF_RoleTypes_PrintMode...')
	ALTER TABLE [RoleTypes] ADD CONSTRAINT [DF_RoleTypes_PrintMode] DEFAULT 2 FOR [PrintMode]
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Roles') AND [name] = 'PrintMode' AND is_nullable = 0)
BEGIN
	PRINT('Changing Roles.PrintMode to NOT NULL...')
	ALTER TABLE [Roles] ALTER COLUMN PrintMode TINYINT NOT NULL
END
GO

IF NOT EXISTS(SELECT * FROM sys.default_constraints dc WHERE dc.Name = 'DF_Roles_PrintMode')
BEGIN
	PRINT('Adding DF_Roles_PrintMode...')
	ALTER TABLE [Roles] ADD CONSTRAINT [DF_Roles_PrintMode] DEFAULT 2 FOR [PrintMode]
END
GO

--#endregion (SH 2021-04-14 PrintMode in Cast, RoleType und Role anpassen)

--#region
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Auditions') AND [name] = 'CastId')
BEGIN
	PRINT('Adding Auditions.CastId ...')
	ALTER TABLE dbo.Auditions ADD CastId INT NULL
	ALTER TABLE dbo.Auditions ADD CONSTRAINT FK_Auditions_Cast FOREIGN KEY (CastId) REFERENCES [Cast] (CastId) ON DELETE CASCADE
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_Auditions_Activities') AND type = 'F') ALTER TABLE dbo.Auditions DROP CONSTRAINT FK_Auditions_Activities
	ALTER TABLE Auditions DROP COLUMN ActivityId

END
GO
--#endregion 

--#endregion ------- (4.212.x) --------------------------------

--#region ----------- 4.212.x Release Übertrag ----------------

--#region SH 2021-04-20 ScheduleRuleSettings reparieren

UPDATE Departments
SET ScheduleRuleSettings = CAST(REPLACE(CAST(ScheduleRuleSettings AS NVARCHAR(MAX)), 'DutyRosterLayotSettings','DutyRosterScheduleRuleSettings') AS XML)
WHERE ScheduleRuleSettings IS NOT NULL AND CAST(ScheduleRuleSettings AS NVARCHAR(MAX)) LIKE '%DutyRosterLayotSettings%'
GO

--#endregion

--#region 2021-04-29

  DELETE FROM ActivitySubscriptions WHERE SubscriptionId IN (
	 SELECT SubscriptionId FROM Subscriptions WHERE [Seasonid] = 0)
  DELETE FROM Subscriptions WHERE Seasonid = 0
  DELETE FROM ProductionInSeasons WHERE Seasonid = 0
  DELETE FROM Seasons WHERE Seasonid = 0
  GO

  --#endregion
 
 --#region SH 2021-05-06 Bugfix CopyDutyRoster, Berechtigung für Freigabe
 IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.CopyDutyRoster')) DROP PROCEDURE dbo.CopyDutyRoster
GO

CREATE PROCEDURE dbo.CopyDutyRoster
	@start DATE,
	@end DATE,
	@departemntId INT,
	@source INT,
	@target INT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER

	DECLARE @hasPermission BIT
	SET @hasPermission = 0

	-- wenn ziel kopie oder sollplan ist, reicht wochenabschluss, sonst schreibberechtigung
	IF EXISTS (SELECT * FROM DutyRosterTypes drt WHERE drt.DutyRosterTypeId = @target AND drt.DutyRosterTypeCategory IN (1, 2))
		SET @hasPermission =
			CASE
				WHEN  EXISTS (
					SELECT * FROM [Permissions]  AS P 
					INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
					WHERE UserId = @userId
						AND PermissionArea = 5
						AND p.OptionsFlag&32 = 32
						AND d.DepartmentId = @departemntId )
				THEN 1
				ELSE 0
			END
	ELSE		
		SET @hasPermission =
			CASE
				WHEN  EXISTS (
					SELECT * FROM [Permissions]  AS P 
					INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
					WHERE UserId = @userId
						AND PermissionArea = 5
						AND p.HasWritePermission = 1
						AND d.DepartmentId = @departemntId )
				THEN 1
				ELSE 0
			END


	IF @hasPermission = 1
	BEGIN
	   	DELETE FROM DutyRoster 
		WHERE DutyRosterId IN (SELECT DutyRosterId FROM  DutyRoster as d 
									INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId
									INNER JOIN  WorkAreas AS ab ON vp.WorkAreaId = ab.WorkAreaId
								WHERE d.DutyRosterTypeId = @target AND ab.DepartmentId = @departemntId AND d.[Date] BETWEEN  @start AND @end)
		INSERT INTO DutyRoster 
		      (  Date,  ContractId,  StartTime1,  EndTime1,  StartTime2,  EndTime2,  StartTime3,  EndTime3,  MiscWorkingMinutes,  WorkingMinutes1,  WorkingMinutes2,  WorkingMinutes3,  ShiftTypeId1,  ShiftTypeId2,  ShiftTypeId3,  ShiftNote1,  Note,  HolidayCount,  LM,  UM,  LC,  UC,  CalculateTimes,  DebitWorkingMinutes, DutyRosterTypeId,              BackColor1,  BackColor2,  BackColor3,  CalculateHolidayCount,  ExemptionStatus1,  ExemptionStatus2,  ExemptionStatus3,  HasNoBreak,  ShiftNote2,  ShiftNote3,  ForeColor1,  ForeColor2,  ForeColor3,  IsPostedHealthy,  DayOffCredit,  RegularWorkingTimeIsManual,  IsDayOffCreditManual,  BreakCorridorSettings,  WorkBreakSettings,  NoteBackColor1,  NoteBackColor2,  NoteBackColor3,  IsDayOffCountManual,  DayOffCount,  PaidOffWorkingMinutes)
		SELECT d.Date,d.ContractId,d.StartTime1,d.EndTime1,d.StartTime2,d.EndTime2,d.StartTime3,d.EndTime3,d.MiscWorkingMinutes,d.WorkingMinutes1,d.WorkingMinutes2,d.WorkingMinutes3,d.ShiftTypeId1,d.ShiftTypeId2,d.ShiftTypeId3,d.ShiftNote1,d.Note,d.HolidayCount,d.LM,d.UM,d.LC,d.UC,d.CalculateTimes, d.DebitWorkingMinutes, @target ,d.BackColor1,d.BackColor2,d.BackColor3,d.CalculateHolidayCount,d.ExemptionStatus1,d.ExemptionStatus2,d.ExemptionStatus3,d.HasNoBreak,d.ShiftNote2,d.ShiftNote3,d.ForeColor1,d.ForeColor2,d.ForeColor3,d.IsPostedHealthy,d.DayOffCredit,d.RegularWorkingTimeIsManual,d.IsDayOffCreditManual,d.BreakCorridorSettings,d.WorkBreakSettings,d.NoteBackColor1,d.NoteBackColor2,d.NoteBackColor3,d.IsDayOffCountManual,d.DayOffCount,d.PaidOffWorkingMinutes
			FROM        DutyRoster as d 
			WHERE       d.DutyRosterId IN (
				SELECT      dpe.DutyRosterId FROM DutyRoster dpe
				INNER JOIN  ContractDepartments as vp ON dpe.ContractId = vp.ContractId
				INNER JOIN  WorkAreas AS ab ON vp.WorkAreaId = ab.WorkAreaId
				WHERE       dpe.DutyRosterTypeId = @source
				        AND ab.DepartmentId = @departemntId
				        AND dpe.[Date] BETWEEN @start AND @end)
	END
END
GO

GRANT EXECUTE ON CopyDutyRoster TO Public
GO
--#endregion (SH 2021-05-06 Bugfix CopyDutyRoster, Berechtigung für Freigabe)

--#region SH 2021-05-21 Bugfix SetWorkVersionReferenceToProduction, workVersionId kann auch NULL sein
IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.SetWorkVersionReferenceToProduction')) DROP PROCEDURE [dbo].[SetWorkVersionReferenceToProduction]
GO

CREATE PROCEDURE [dbo].[SetWorkVersionReferenceToProduction]
	@productionId INT, @workVersionId INT = NULL
AS
BEGIN
	SET NOCOUNT ON
	UPDATE Productions SET WorkVersionId = @workVersionId WHERE ProductionId = @productionId
END	
GO

GRANT EXECUTE ON SetWorkVersionReferenceToProduction TO WorksWrite 
GO
--#endregion SH 2021-05-21 Bugfix SetWorkVersionReferenceToProduction, workVersionId kann auch NULL sein

--#region Bugfix GroupPosition
UPDATE [Cast] SET GroupPosition = 1 WHERE GroupPosition < 1
GO
--#endregion

--#endregion -------- (4.212.x Release Übertrag) --------------

--#region ----------- 4.213.x ---------------------------------

--#region 2021-04-19
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Auditions_WorkRoles') AND [name] = 'Category')
BEGIN
	PRINT('Adding Auditions_WorkRoles.Category ...')
	ALTER TABLE dbo.Auditions_WorkRoles ADD Category TINYINT NULL
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Productions') AND [name] = 'ProductionType')
BEGIN
	PRINT('Adding Productions.ProductionType ...')
	ALTER TABLE dbo.Productions ADD ProductionType TINYINT NOT NULL CONSTRAINT DF_Productions_ProductionType DEFAULT 0
	EXEC('UPDATE Productions SET ProductionType = 2 WHERE ProductionId = 0')
	EXEC('UPDATE Productions SET ProductionType = 3 WHERE ProductionId = -2')
	EXEC('UPDATE Productions SET ProductionType = 4 WHERE ProductionId = -1')
	EXEC('UPDATE Productions SET ProductionType = 5 WHERE Title LIKE ''*%''')
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Auditions') AND [name] = 'Date')
BEGIN
	PRINT('Adding Auditions.[Date] ...')
	ALTER TABLE Auditions ADD [Date] DATE NULL
	EXEC('UPDATE Auditions SET [Date] = [Start]')
	ALTER TABLE Auditions ALTER COLUMN [Date] DATE NOT NULL
	ALTER TABLE Auditions ALTER COLUMN [Start] SMALLDATETIME NULL
	IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'dbo.Auditions') AND o.Name = 'IX_Auditions_PersonId') DROP INDEX [IX_Auditions_PersonId] ON [dbo].[Auditions]
	CREATE CLUSTERED INDEX IX_Auditions_PersonId_Date_AuditionTypeId ON Auditions (PersonId, [Date]) ON [PRIMARY]
	CREATE INDEX IX_Auditions_Date ON Auditions ([Date]) ON [PRIMARY]
	EXEC sp_rename 'Auditions.Start', 'x_Start', 'COLUMN';
	EXEC sp_rename 'BasicCast.SeasonId', 'x_SeasonId', 'COLUMN';
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('BasicCast') AND [name] = 'X_BasicCastCategoryId')
BEGIN
PRINT('CastRepertoire->BasicCast...')
	ALTER TABLE BasicCast ADD X_BasicCastCategoryId INT NULL
	
	ALTER TABLE RepertoireCategories ADD UnderstudyPosition TINYINT NULL
	UPDATE RepertoireCategories SET ShowinModul = 1 WHERE ShowinModul IS NULL 
	EXEC('UPDATE RepertoireCategories SET RepertoireCategories.UnderstudyPosition = n FROM    
		RepertoireCategories INNER JOIN 
			(SELECT RepertoireCategoryId, CASE WHEN ShowinModul = 4 THEN 0 ELSE 10 END + ROW_NUMBER() OVER(PARTITION BY ShowinModul ORDER BY RepertoireCategoryId) AS n FROM RepertoireCategories ) AS n ON RepertoireCategories.RepertoireCategoryId = n.RepertoireCategoryId')

	ALTER TABLE RepertoireCategories ALTER COLUMN UnderstudyPosition TINYINT NOT NULL

	CREATE UNIQUE NONCLUSTERED  INDEX IX_RepertoireCategories_Module_UnderstudyPosition ON RepertoireCategories (ShowinModul, UnderstudyPosition)  ON [PRIMARY]
	CREATE UNIQUE NONCLUSTERED  INDEX IX_RepertoireCategories_Module_Name ON RepertoireCategories (ShowinModul, Name)  ON [PRIMARY]

	EXEC('INSERT INTO BasicCast (PersonId, RoleId, GroupPosition, UnderstudyPosition, X_BasicCastCategoryId, Note, LM, UM, LC, UC) 
	SELECT cr.PersonId, cr.RoleId, 1, ISNULL(rc.UnderstudyPosition, CASE WHEN OwnerGroups.Modul = 4 THEN 1 ELSE 11 END), cr.RepertoireCategoryId, ISNULL(''Ort:'' + Persons.KeyName + '', '', '''') + ISNULL(''Sprache: '' + LanguageCode + '', '', '''') + ISNULL(''Level: '' + CAST([Level] AS varchar(10)) + '', '', '''') + ISNULL(Memo, '''') AS Note, ISNULL(cr.LM,''19000101)''), cr.UM, ISNULL(cr.LC,''19000101)''), cr.UC 
	FROM CastRepertoire AS cr 
		LEFT JOIN Persons ON cr.City = Persons.PersonId
		LEFT JOIN Roles ON cr.RoleId = Roles.RoleId
		LEFT JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId
		LEFT JOIN RepertoireCategories AS rc ON cr.RepertoireCategoryId=rc.RepertoireCategoryId
	WHERE NOT EXISTS (SELECT * FROM BasicCast AS bc WHERE cr.PersonId = bc.PersonId AND cr.RoleId = bc.RoleId)')
		
	UPDATE Roles SET Roles.IsProductionTeam = 0 FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul = 4
	UPDATE BasicCast SET Note = SUBSTRING(note, 0, LEN(Note)) FROM BasicCast WHERE Note LIKE '%,'
	UPDATE BasicCast SET Note = NULL WHERE Note IN ('', ' ', ', ',  ',')
END
GO
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'RepertoireCategories') AND o.Name = 'PK_Bez') DROP INDEX PK_Bez ON dbo.RepertoireCategories
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'RepertoireCategories') AND o.Name = 'Bez') DROP INDEX Bez ON dbo.RepertoireCategories
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'RepertoireCategories') AND o.Name = 'Sort') DROP INDEX Sort ON dbo.RepertoireCategories

GO
DropColumn 'RepertoireCategories', 'Bem'
GO
DropColumn 'RepertoireCategories', 'Sort'
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [Name]='X_CastRepertoire')
BEGIN
	INSERT INTO RepertoireCategories (Name, Code, LM, LC,ShowInModul, UnderstudyPosition ) VALUES 
		('1. Besetzung', '1.', '19000101','19000101', 1, 1),
		('2. Besetzung', '2.', '19000101','19000101', 1, 2),
		('3. Besetzung', '3.', '19000101','19000101', 1, 3),
		('4. Besetzung', '4.', '19000101','19000101', 1, 4),
		('Festbesetzung', '1.', '19000101','19000101', 2, 1),
		('Besetzung', '1.', '19000101','19000101', 16, 1),
		('Ersatz', '2.', '19000101','19000101', 16, 2),
		('Studierbesetzung', '2.', '19000101','19000101', 16, 3),
		('1. Besetzung', '1.', '19000101','19000101', 32, 1),
		('2. Besetzung', '2.', '19000101','19000101', 32, 2),
		('3. Besetzung', '3.', '19000101','19000101', 32, 3),
		('4. Besetzung', '4.', '19000101','19000101', 32, 4),
		('Besetzung', '1.', '19000101','19000101', 256, 1),
		('Ersatz', '2.', '19000101','19000101', 256, 2)
		EXEC sp_rename 'CastRepertoire', 'X_CastRepertoire';
		EXEC sp_rename 'BesetzungStdSoliTabelle', 'X_BesetzungStdSoliTabelle';
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_CastRepertoire_Persons') AND type = 'F') ALTER TABLE dbo.X_CastRepertoire DROP CONSTRAINT FK_CastRepertoire_Persons
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_CastRepertoire_RepertoireCategories') AND type = 'F') ALTER TABLE dbo.X_CastRepertoire DROP CONSTRAINT FK_CastRepertoire_RepertoireCategories
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_CastRepertoire_Roles') AND type = 'F') ALTER TABLE dbo.X_CastRepertoire DROP CONSTRAINT FK_CastRepertoire_Roles
GO

ALTER PROCEDURE [dbo].[CastInProduction0Warning]
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
		
		IF (@infoOnly=0)
		BEGIN
			DELETE FROM BasicCast WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM [Cast] WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM TechnicalJobs WHERE RoleId IN (SELECT RoleId FROM Roles WHERE RoleId <> 0 AND ProductionId = 0)
			DELETE FROM Roles WHERE RoleId <> 0 AND ProductionId = 0
		END
		ELSE
		BEGIN
			SELECT ISNULL(Name,'NN') FROM Roles WHERE RoleId <> 0 AND ProductionId = 0				
		END
	END
GO

ALTER PROCEDURE [dbo].[ClearOldContacts]
@lastModifiedBefore DATETIME,
@infoOnly BIT
AS
Begin
		SELECT DISTINCT p.PersonId 
		INTO #TempContacts
		FROM Persons p 
		WHERE p.LM <@lastModifiedBefore and p.IsInactive=1	
			AND NOT EXISTS (SELECT PersonId FROM Contracts WHERE PersonId=p.PersonId) 
			AND NOT EXISTS (SELECT PersonId FROM [Cast] b WHERE b.PersonId=p.PersonId )
			AND NOT EXISTS (SELECT PersonId FROM PersonStatus s WHERE s.PersonId= p.PersonId);
		IF (@infoOnly=0)
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
			DELETE FROM PersonDetails WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);	
			DELETE FROM PersonEmployee WHERE PersonId IN (SELECT PersonId FROM #TempContacts);
			DELETE FROM BankAccounts WHERE PersonId IN (SELECT PersonId FROM #TempContacts);
			DELETE FROM BodyMeasurementData WHERE BodyMeasurementId IN (SELECT BodyMeasurementId FROM BodyMeasurements v WHERE  v.PersonId IN (SELECT PersonId FROM #TempContacts));
			DELETE FROM BodyMeasurements  WHERE  PersonId IN (SELECT PersonId FROM #TempContacts);
			UPDATE CheckListItem SET PersonId= NULL WHERE personid IN (SELECT PersonId FROM #tempcontacts);
			UPDATE CheckListItemTemplate set PersonId = NULL WHERE personid IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM MailingListEntries WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonContactData WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonAddress WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonRelations WHERE PersonId IN (SELECT PersonId FROM #tempcontacts) or ChildPersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonFieldData WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonEmployee WHERE personid IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonDetails WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonAdditionalData WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonAttachments WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonMemo WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonFeeNotes WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM Qualification_Person WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM ResourceObjects WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM PersonPermissions WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM BasicCastHistory WHERE PersonOldId in(SELECT PersonId FROM #tempcontacts) OR PersonNewId IN (SELECT PersonId FROM #tempcontacts);
			DELETE FROM Persons WHERE PersonId IN (SELECT PersonId FROM #tempcontacts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContacts
		END
		DROP TABLE #TempContacts	
END
GO

ALTER PROCEDURE [dbo].[DeleteProduction]
	@ProductionId INT
AS
BEGIN
SET NOCOUNT ON
DECLARE @UserGroup int
SELECT @UserGroup = OwnerGroupId FROM Productions WHERE  ProductionId = @ProductionId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 3) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permissions' AS MSG
	END
ELSE
	BEGIN 
		IF (@ProductionId = 0)	
		BEGIN
			SELECT 0 AS Attribut,'Keine gültige Produktion übergeben (Id 0)' AS MSG
		END
		ELSE
		BEGIN
			DELETE FROM BasicCast WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM ContractEngagements WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM ContractDateConfirmations WHERE  ContractDateId IN (SELECT ContractDateId FROM ContractDates 
				WHERE CastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)))
			DELETE FROM ContractDates WHERE  CastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			DELETE FROM CastBonus WHERE  CastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			DELETE FROM CashCommandPos_Cast WHERE  CastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			DELETE FROM CastCredits WHERE  ServiceCastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			DELETE FROM CastCredits WHERE  ReplacementCastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			UPDATE ContractDates SET CastId = NULL WHERE  CastId IN (SELECT CastId FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId))
			DELETE FROM [Cast] WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM TechnicalJobs WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM RoleBonus WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM Role_Season WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM Roles_Scenes WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM Qualification_Role WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)
			DELETE FROM Roles WHERE  RoleId IN (SELECT RoleId FROM Roles WHERE  ProductionId = @ProductionId)	
			DELETE FROM ProductionTimeFlow WHERE  ProductionId = @ProductionId
			DELETE FROM ProductionTimeFlow WHERE  ChildProductionId = @ProductionId
			DELETE FROM ActivityScenes WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ActivityDepartmentData WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM TechnicalJobs WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ActivityCosts WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ActivityDetails WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM JourneyTimetables WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM CostUnitWorkingTimes WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ActivityDetails WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ActivitySubscriptions WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM Activities WHERE  ActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			UPDATE Activities SET LinkedActivityId = NULL WHERE  LinkedActivityId IN (SELECT ActivityId FROM Activities WHERE  ProductionId = @ProductionId)
			DELETE FROM ProductionDetails WHERE  ProductionId = @ProductionId
			DELETE FROM ProductionInSeasons WHERE  ProductionId = @ProductionId
		END
	END
END
GO

ALTER PROCEDURE [dbo].[DeleteRole]
	@RoleId INT
AS
BEGIN
SET NOCOUNT ON

DECLARE @UserGroup int
SELECT @UserGroup = OwnerGroupId FROM Roles WHERE RoleId = @RoleId

--Berechtigungsprüfung
IF (dbo.GetCurrentPermission(@UserGroup, 4) < 2 ) 
	BEGIN
		SELECT 1 AS Attribut, 'No Permissions' AS MSG
	END
ELSE
	BEGIN 
		IF (@RoleId = 0)	
			BEGIN
				SELECT 0 AS Attribut,'Keine gültige Name übergeben (Id 0)' AS MSG
			END
		ELSE
			BEGIN
				DELETE FROM BasicCast WHERE RoleId = @RoleId
				DELETE FROM ContractEngagements WHERE RoleId = @RoleId
				DELETE FROM RoleBonus WHERE RoleId = @RoleId
				DELETE FROM Role_Season WHERE RoleId = @RoleId
				DELETE FROM Roles_Scenes WHERE RoleId = @RoleId
				DELETE FROM Qualification_Role WHERE RoleId = @RoleId
				DELETE FROM ContractDateConfirmations WHERE ContractDateId IN (SELECT ContractDateId FROM ContractDates WHERE CastId IN (SELECT CastId FROM [Cast] WHERE RoleId = @RoleId))
				DELETE FROM ContractDates WHERE CastId IN (SELECT CastId FROM [Cast] WHERE RoleId = @RoleId)
				DELETE FROM CastBonus WHERE CastId IN (SELECT CastId FROM [Cast] WHERE RoleId = @RoleId)
				DELETE FROM [Cast] WHERE RoleId = @RoleId
				DELETE FROM TechnicalJobs WHERE RoleId=@RoleId
				DELETE FROM Roles WHERE RoleId = @RoleId	
			END
		END
END
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.RoleQualifications_Update') AND type <> 'U')  DROP VIEW [dbo].[RoleQualifications_Update]
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.TR_Activity_Update')) DROP TRIGGER dbo.TR_Activity_Update
GO
CREATE TRIGGER dbo.TR_Activity_Update ON Activities AFTER UPDATE 
AS 
BEGIN
	DECLARE @activityId INT
	DECLARE @newDate DATE
	   
	IF UPDATE([Date])
	BEGIN
	
		SELECT @newDate = [Date], @activityId = activityId FROM INSERTED
		--Am Person Datum und MeasureType sind eindeitig, ggf vorahndenes entfernen
		DELETE MeasureParticipations FROM MeasureParticipations WHERE MeasureParticipationId IN 
			(SELECT mpp.MeasureParticipationId FROM MeasureParticipations AS mpp
											INNER JOIN [Cast] AS c ON mpp.PersonId = c.PersonId 
											INNER JOIN MeasureParticipations AS mpCast ON mpp.PersonId = mpCast.PersonId  AND  mpp.MeasureTypeId = mpCast.MeasureTypeId 
					WHERE mpp.ParticipationDate = @newDate AND c.ActivityId = @activityId)
						
		UPDATE MeasureParticipations SET ParticipationDate = @newDate FROM MeasureParticipations INNER JOIN [Cast] AS c ON MeasureParticipations.CastId = c.CastId WHERE c.ActivityId = @activityId 	
		UPDATE Auditions SET [Date] = @newDate FROM Auditions INNER JOIN [Cast] AS c ON Auditions.CastId = c.CastId WHERE c.ActivityId = @activityId
	END
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_Tours_Contracts_Persons') AND type = 'F')
BEGIN
	ALTER TABLE [dbo].[Tours_Contracts] DROP CONSTRAINT [UQ_Tours_TourId_ContractId]
	
	CREATE UNIQUE NONCLUSTERED INDEX IX_Tours_Contracts_TourId_ContractId ON Tours_Contracts (TourId, ContractId) WHERE (ContractId IS NOT NULL)
	CREATE NONCLUSTERED INDEX IX_Tours_Contracts_PersonId ON Tours_Contracts (PersonId) 

	ALTER TABLE Tours_Contracts WITH CHECK ADD CONSTRAINT FK_Tours_Contracts_Persons FOREIGN KEY(PersonId)
	REFERENCES Persons (PersonId) ON DELETE CASCADE
	ALTER TABLE Tours_Contracts CHECK CONSTRAINT FK_Tours_Contracts_Persons

	ALTER TABLE Tours DROP CONSTRAINT DF_Tours_IsDutyTour
	ALTER TABLE Tours ALTER COLUMN  IsDutyTour BIT NOT NULL
	ALTER TABLE Tours ADD CONSTRAINT DF_Tours_IsDutyTour DEFAULT 0 FOR IsDutyTour
END

--#endregion

--#region DH View für MeasureParticipations  26.04.2021
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbMeasureParticipations') AND type <> 'U') DROP VIEW dbo.AbMeasureParticipations
GO
CREATE VIEW AbMeasureParticipations AS (
SELECT *, (SELECT COUNT(*) AS FollowerCount FROM  MeasureParticipations mps 
								WHERE mps.PersonId = MeasureParticipations.PersonId 
									AND mps.ParticipationDate > MeasureParticipations.ParticipationDate 
									AND mps.MeasureTypeId = MeasureParticipations.MeasureTypeId) AS FollowerCount FROM MeasureParticipations)
GO
REVOKE INSERT, UPDATE, DELETE ON AbMeasureParticipations TO public
GRANT SELECT ON AbMeasureParticipations TO public
GO
--#endregion DH View für MeasureParticipations 26.04.2021

--#region DeletePersonReference

ALTER PROCEDURE [dbo].[DeletePersonReference] (@personId INT, @del INT) AS 
	DECLARE @conflictCounter INT
	SELECT @conflictCounter = 0
	DECLARE @conflictDescription VARCHAR(MAX)
	SELECT @conflictDescription = ''

	DECLARE @Temp INT
	SELECT  @Temp = 0
	DECLARE @CRLF char(2)
	SET @CRLF =  '|'
	SET NOCOUNT On
	/*
	Eingabeparameter: 
	@personId			=> Zu bearbeitendes PersonId
	@del			= 0 Nur überprüfen, ob das Löschen der Detaildaten möglich ist / 1 löschen

	Rückgabewerte:
	1. @conflictCounter			=> Anzahl der Tabellen in denen eine Löschung nicht möglich wäre.
	2. @ConflictDescription		=>	Ausgabe der Löschkonflikte
	*/

	if (@del > 0)
	--Rekusiveraufruf beim "echtem löschen mit Check (0)"
	BEGIN
		DECLARE @return_value int
		EXEC @return_value = dbo.DeletePersonReference @personId, 0

		IF (@return_value > 0) 
		BEGIN
			RETURN @return_value
		END
	END

	SELECT @Temp = OwnerGroupId FROM Persons WHERE PersonId = @personId

	IF (dbo.GetCurrentPermission(@Temp,0) <> 2) 
	BEGIN
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'No Owner Permissions' + @CRLF
		SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
		RETURN @conflictCounter
	END

	/*  Tabelle BasicCast */
	IF (SELECT COUNT(*) FROM BasicCast WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'BasicCast' + @CRLF
	END

	/*  Tabelle Besetzung */
	IF (SELECT COUNT(*) FROM Cast WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Cast' + @CRLF
	END

	/*  Bereich der Tabellen PersonStatus  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonStatus WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM AbPersStatus_Update WHERE PersonId = @personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Status' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM PersonStatus WHERE PersonId = @personId
			END
		END

	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM Contracts WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM ContractDetails WHERE ContractDetails.AgencyPersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

	/* Cashcommands*/
	IF (SELECT COUNT(*) FROM CashCommands WHERE PersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
	END

	IF (SELECT COUNT(*) FROM CashCommands WHERE AgencyId=@personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
	END

	/* PersonDetails*/
	IF (SELECT COUNT(*) FROM PersonDetails WHERE HealthInsuranceId=@personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal( HealthInsurance)' + @CRLF
	END

	IF (SELECT COUNT(*) FROM PersonDetails WHERE TaxOfficeId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal (TaxOffice)' + @CRLF
	END
	
	/* ------------------------------------Dispositionsbereich ende -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

	IF (@del > 0) DELETE FROM PersonDetails WHERE PersonId = @personId

	/*  Tabelle PersonRelations  */
	IF (@del > 0) 
		BEGIN
			UPDATE PersonRelations SET ContactPersonConnectionId = NULL WHERE ContactPersonConnectionId IN (SELECT PersonRelationId FROM PersonRelations WHERE ChildPersonId=@personid) 
			DELETE FROM PersonRelations WHERE ChildPersonId = @personId;
			DELETE FROM PersonRelations WHERE PersonId = @personId;			
		END

	/*  Tabelle BasicCastHistory */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
	IF (SELECT COUNT(*) FROM AbXHDelBasicCast_Update WHERE PersonOldId = @personId OR PersonNewId = @personId) < @Temp
		BEGIN 
			SELECT @conflictCounter=@conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'BasicCastHistory' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonFeeNotes  */
	IF (@del > 0) DELETE FROM PersonFeeNotes WHERE PersonId=@personId

/*  Tabelle AbPersonalNotizen_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonMemo WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM AbPersonalNotizen_Update WHERE PersonId=@personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Notes' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM PersonMemo WHERE PersonId = @personId
			END
		END


	/*  Tabelle ABPersKom_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonContactData WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM ABPersonContactData_Update WHERE PersonId = @personId) < @Temp
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Contactdata' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp)>0
			BEGIN 
				IF (@del > 0)DELETE FROM PersonContactData WHERE PersonId=@personId
			END
		END

	/*  Tabelle ABPersAdresse_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAddress WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM ABPersAdresse_Update WHERE PersonId = @personId) < @Temp
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Adressdata' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp)>0
				BEGIN 
					IF (@del > 0)DELETE FROM PersonAddress WHERE PersonId=@personId
				END
			END

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAdditionalData WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersonId = @personId) < @Temp 
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Personal attribute' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp) > 0
				BEGIN 
					IF (@del > 0)DELETE FROM PersonAdditionalData WHERE PersonId = @personId
				END
			END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM ResourceObjectBorrows WHERE PersonId = @personId AND EndDate IS NULL
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Open Borrows' + @CRLF
		END

	IF (@del > 0) DELETE FROM ResourceObjectBorrows WHERE PersonId = @personId


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands WHERE AgencyId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM DepartmentCollectives WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'DepartmentCollectives' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders (Supplier)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM OrderTravelers WHERE TravelerId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'OrderTravelers' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Departments WHERE HeadOfDepartmentId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Department (HeadOfDepartment)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonAttachments WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'PersonAttachments' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkCreators WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkCreators' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (Person)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE TheaterId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (TheaterId)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersions WHERE PublisherId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersions (Publisher)' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM MeasureParticipations WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'MeasureParticipations' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonRequiredMeasureTypes WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'PersonRequiredMeasureTypes' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM Tours_Contracts WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Tours_Contracts' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM ProductionPartners WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'ProductionPartners' + @CRLF
		END
		
	SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
	RETURN @conflictCounter
GO
--#endregion DeletePersonReference

--#region Locations
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'Locations') AND o.Name = 'IX_Locations_ShortName')
BEGIN
	ALTER TABLE Locations ALTER COLUMN ShortName VARCHAR(20) NOT NULL
	EXEC PrepareUniqueColumnIndex 'Locations','ShortName','LocationId','VARCHAR(20)'
	CREATE UNIQUE NONCLUSTERED INDEX IX_Locations_ShortName ON Locations (ShortName ) ON [PRIMARY]

	ALTER TABLE DutyRosterReleaseWorkflows ALTER COLUMN UserGroupId INT NULL

	INSERT INTO DutyRosterReleaseModels ([Name], LC, UC, LM, UM) VALUES ('-Default-', GETDATE(), -1, GETDATE() ,-1)
	DECLARE @int INT
	SELECT @int = MAX(DutyRosterReleaseModelId) FROM DutyRosterReleaseModels

	INSERT INTO dbo.DutyRosterReleaseWorkflows
			   (DutyRosterReleaseModelId, FromStatusId, ToStatusId, CopyDutyRosterTargetId, NotifyHeadOfDepartment, LC, UC, LM, UM)
		 VALUES (@int, NULL, 1, 1,    0, GETDATE(),-1, GETDATE(),-1),
				(@int, 2, 1, 1,    0, GETDATE(),-1, GETDATE(),-1),
				(@int, 1, 2, NULL, 0, GETDATE(),-1, GETDATE(),-1)
	UPDATE Departments SET DutyRosterReleaseModelId = @int FROM Departments INNER JOIN OwnerGroups ON Departments.OwnerGroupId = OwnerGroups.OwnerGroupId  WHERE DutyRosterReleaseModelId IS NULL AND OwnerGroups.Modul = 4
END
GO
--#endregion Locations

--#region DH Zuordnung von Abteilungsmaßnahmen zu Personen 30.04.2021

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ApplyMeasureRequirementsByPerson')) DROP PROCEDURE dbo.ApplyMeasureRequirementsByPerson
GO
CREATE PROCEDURE dbo.ApplyMeasureRequirementsByPerson 
	@departmentid INT, 
	@personid INT 
AS
BEGIN
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName = CURRENT_USER

	INSERT INTO PersonRequiredMeasureTypes(PersonId, MeasureTypeId, LC, LM, UC, UM) 
	SELECT DISTINCT @personid, MeasureTypeId, GETDATE(), GETDATE(), @userId, @userId 
	FROM DepartmentRequiredMeasureTypes AS rm
	WHERE DepartmentId = @departmentid
	AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes WHERE personid = @personid 
																AND PersonRequiredMeasureTypes.measureTypeId = rm.measureTypeId)
END
GO
GRANT EXECUTE ON dbo.ApplyMeasureRequirementsByPerson TO public
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.ApplyMeasureRequirements')) DROP PROCEDURE dbo.ApplyMeasureRequirements
GO
CREATE PROCEDURE dbo.ApplyMeasureRequirements 
	@departmentid INT = NULL,
	@measureTypeId INT = NULL
AS
BEGIN
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName = CURRENT_USER

	IF (NOT @departmentid IS NULL AND @measureTypeId IS NULL)
		BEGIN

			INSERT INTO PersonRequiredMeasureTypes(PersonId, MeasureTypeId, LC, LM, UC, UM) 
			SELECT DISTINCT c.PersonId, MeasureTypeId, GETDATE(), GETDATE(), @userId, @userId 
			FROM DepartmentRequiredMeasureTypes AS rm
				CROSS JOIN Contracts AS c 
				INNER JOIN ContractTypes AS ct ON c.ContractTypeId = ct.ContractTypeId
				INNER JOIN ContractDepartments AS cp ON c.ContractId = cp.ContractId
				INNER JOIN WorkAreas AS wa ON cp.WorkAreaId = wa.WorkAreaId
			WHERE rm.DepartmentId = @departmentid 
			AND wa.DepartmentId = @departmentid 
			AND cp.IsMainWorkArea = 1 
			AND c.IsCanceled = 0
			AND ct.ContractTypesCategory = 255
			AND (c.StartDate <= GETDATE() OR c.StartDate IS NULL) AND (c.EndDate >= GETDATE() OR c.EndDate IS NULL) 
			AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes WHERE personid = c.PersonId 
																	   AND PersonRequiredMeasureTypes.measureTypeId = rm.measureTypeId)
		END
	ELSE IF (@departmentid IS NULL AND NOT @measureTypeId IS NULL)
		BEGIN

			INSERT INTO PersonRequiredMeasureTypes(PersonId, MeasureTypeId, LC, LM, UC, UM) 
			SELECT DISTINCT c.PersonId, @measureTypeId, GETDATE(), GETDATE(), @userId, @userId 
			FROM DepartmentRequiredMeasureTypes AS rm
				CROSS JOIN Contracts AS c 
				INNER JOIN ContractTypes AS ct ON c.ContractTypeId = ct.ContractTypeId
				INNER JOIN ContractDepartments AS cp ON c.ContractId = cp.ContractId
				INNER JOIN WorkAreas AS wa ON cp.WorkAreaId = wa.WorkAreaId
			WHERE rm.MeasureTypeId = @measureTypeId 
			AND cp.IsMainWorkArea = 1
			AND c.IsCanceled = 0
			AND ct.ContractTypesCategory = 255
			AND (c.StartDate <= GETDATE() OR c.StartDate IS NULL) AND (c.EndDate >= GETDATE() OR c.EndDate IS NULL) 
			AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes WHERE PersonRequiredMeasureTypes.personid = c.PersonId 
																	   AND PersonRequiredMeasureTypes.measureTypeId = @measureTypeId)
		END
	ELSE IF (NOT @departmentid IS NULL AND NOT @measureTypeId IS NULL)
		BEGIN

			INSERT INTO PersonRequiredMeasureTypes(PersonId, MeasureTypeId, LC, LM, UC, UM) 
			SELECT DISTINCT c.PersonId, @measureTypeId, GETDATE(), GETDATE(), @userId, @userId 
			FROM DepartmentRequiredMeasureTypes AS rm 
				CROSS JOIN Contracts AS c 
				INNER JOIN ContractTypes AS ct ON c.ContractTypeId = ct.ContractTypeId
				INNER JOIN ContractDepartments AS cp ON c.ContractId = cp.ContractId
				INNER JOIN WorkAreas AS wa ON cp.WorkAreaId = wa.WorkAreaId
			WHERE rm.DepartmentId = @departmentid 
			AND wa.DepartmentId = @departmentid 
			AND rm.MeasureTypeId = @measureTypeId 
			AND cp.IsMainWorkArea = 1
			AND c.IsCanceled = 0
			AND ct.ContractTypesCategory = 255
			AND (c.StartDate <= GETDATE() OR c.StartDate IS NULL) AND (c.EndDate >= GETDATE() OR c.EndDate IS NULL) 
			AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes WHERE PersonRequiredMeasureTypes.personid = c.PersonId 
																	   AND PersonRequiredMeasureTypes.measureTypeId = @measureTypeId)
		END
END
GO
GRANT EXECUTE ON dbo.ApplyMeasureRequirements TO staffAdmin
GO
--#endregion DH Zuordnung von Abteilungsmaßnahmen zu Personen 30.04.2021

--#region 2021-05-11 K/M
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name] = 'ResourceObjectFieldData')
BEGIN
	PRINT('Add CostumeAdmin...')
	EXEC sp_addrole @rolename = N'CostumeAdmin'
	--Logische Kostüme
	ALTER TABLE ResourceContainer ALTER COLUMN WorkVersionId INT NULL
	ALTER TABLE ResourceContainer ADD RoleId INT NULL
	ALTER TABLE ResourceContainer ADD ResourceCount SMALLINT NOT NULL CONSTRAINT DF_ResourceCount_ResourceCount DEFAULT 0
	ALTER TABLE ResourceContainer  ALTER COLUMN Note VARCHAR(1024) SPARSE NULL
	
	ALTER TABLE ResourceContainer WITH CHECK ADD CONSTRAINT FK_ResourceContainer_Role FOREIGN KEY(RoleId)
	REFERENCES Roles (RoleId)
	ALTER TABLE ResourceContainer CHECK CONSTRAINT FK_ResourceContainer_Role
	  
	PRINT 'Creating ResourceContainerAttachments...'
 	CREATE TABLE dbo.ResourceContainerAttachments (
		ResourceContainerAttachmentId INT IDENTITY(1, 1) NOT NULL,
		ResourceContainerId INT NOT NULL,
		AttachmentId INT NOT NULL,
		Note VARCHAR(1024) SPARSE,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceContainerAttachments_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceContainerAttachments_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceContainerAttachments PRIMARY KEY NONCLUSTERED (ResourceContainerAttachmentId) ON [PRIMARY]
    ) ON [PRIMARY]
	
	CREATE CLUSTERED INDEX IX_ResourceContainerAttachments_ResourceContainerId ON ResourceContainerAttachments (ResourceContainerId) ON [PRIMARY]
	CREATE INDEX IX_ResourceContainerAttachments_AttachmentId ON ResourceContainerAttachments (AttachmentId) ON [PRIMARY]

	GRANT SELECT, INSERT, UPDATE, DELETE ON ResourceContainerAttachments TO DataService

	ALTER TABLE ResourceContainerAttachments WITH CHECK ADD CONSTRAINT FK_ResourceContainerAttachments_ResourceInContainer FOREIGN KEY(ResourceContainerId)
	REFERENCES ResourceContainer (ResourceContainerId)
	ALTER TABLE ResourceContainerAttachments CHECK CONSTRAINT FK_ResourceContainerAttachments_ResourceInContainer	

	ALTER TABLE ResourceContainerAttachments WITH CHECK ADD CONSTRAINT FK_ResourceContainerAttachments_Attachments FOREIGN KEY(AttachmentId)
	REFERENCES Attachments (AttachmentId)
	ALTER TABLE ResourceContainerAttachments CHECK CONSTRAINT FK_ResourceContainerAttachments_Attachments

	--Logische Anlagen für logische Ressourcen (Kostüm)Teile
	PRINT 'Creating ResourceAttachments...'
	CREATE TABLE dbo.ResourceAttachments (
		ResourcAttachmentId INT IDENTITY(1, 1) NOT NULL,
		ResourceId INT NOT NULL,
		AttachmentId INT NOT NULL,
		Note VARCHAR(1024) SPARSE NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceAttachments_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceAttachments_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceAttachments PRIMARY KEY NONCLUSTERED (ResourcAttachmentId) ON [PRIMARY]
    ) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_ResourceAttachments_ResourceId ON ResourceAttachments (ResourceId) ON [PRIMARY]
	CREATE INDEX IX_ResourceAttachments_AttachmentId ON ResourceAttachments (AttachmentId) ON [PRIMARY]

	GRANT SELECT, INSERT, UPDATE, DELETE ON ResourceAttachments TO DataService

	ALTER TABLE ResourceAttachments WITH CHECK ADD CONSTRAINT FK_ResourceAttachments_Resources FOREIGN KEY(ResourceId)
	REFERENCES Resources (ResourceId)
	ALTER TABLE ResourceAttachments CHECK CONSTRAINT FK_ResourceAttachments_Resources	

	ALTER TABLE ResourceAttachments WITH CHECK ADD CONSTRAINT FK_ResourceAttachments_Attachments FOREIGN KEY(AttachmentId)
	REFERENCES Attachments (AttachmentId)
	ALTER TABLE ResourceAttachments CHECK CONSTRAINT FK_ResourceAttachments_Attachments
	
	--logische Teile in logischen Kostümen
	PRINT 'Creating ResourceInContainer...'
	CREATE TABLE dbo.ResourceInContainer (
		ResourceInContainerId INT IDENTITY(1, 1) NOT NULL,
		ResourceContainerId INT NOT NULL,
		ResourceId INT NOT NULL,
		ResourceCount SMALLINT NOT NULL CONSTRAINT DF_ResourceInContainer_ResourceCount DEFAULT 0,
		CreationBy TINYINT NOT NULL CONSTRAINT DF_ResourceInContainer_CreationBy DEFAULT 0,
		Note VARCHAR(1024) SPARSE NULL ,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceInContainer_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceInContainer_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceInContainer PRIMARY KEY NONCLUSTERED (ResourceInContainerId) ON [PRIMARY]
    ) ON [PRIMARY]

	GRANT SELECT ON ResourceInContainer TO Public	

	CREATE UNIQUE CLUSTERED INDEX IX_ResourceInContainer_ResourceContainerId_ResourceId ON ResourceInContainer (ResourceContainerId, ResourceId) ON [PRIMARY]
	CREATE INDEX IX_ResourceInContainer_ResourceId_ResourceContainerId ON ResourceInContainer (ResourceId, ResourceContainerId) ON [PRIMARY]

	ALTER TABLE ResourceInContainer WITH CHECK ADD CONSTRAINT FK_ResourceInContainer_ResourceInContainer FOREIGN KEY(ResourceContainerId)
	REFERENCES ResourceContainer (ResourceContainerId)
	ALTER TABLE ResourceInContainer CHECK CONSTRAINT FK_ResourceInContainer_ResourceInContainer	

	ALTER TABLE ResourceInContainer WITH CHECK ADD CONSTRAINT FK_ResourceInContainer_Resources FOREIGN KEY(ResourceId)
	REFERENCES Resources (ResourceId) 
	ALTER TABLE ResourceInContainer CHECK CONSTRAINT FK_ResourceInContainer_Resources

	--Reale Kostümen
	PRINT 'Creating ResourceCostumes...'
	CREATE TABLE dbo.ResourceObjectContainers (
		ResourceObjectContainerId INT IDENTITY(1, 1) NOT NULL,
		ResourceContainerId INT NOT NULL,
		ObjectNumberInContainer SMALLINT NULL,
		PersonId INT NULL,
		Note VARCHAR(1024),
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectContainers_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectContainers_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceObjectContainers PRIMARY KEY NONCLUSTERED (ResourceObjectContainerId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_ResourceObjectContainers_ResourceContainerId ON ResourceObjectContainers (ResourceContainerId, ObjectNumberInContainer) ON [PRIMARY]
	CREATE INDEX IX_ResourceObjectContainers_PersonId ON ResourceObjectContainers (PersonId) ON [PRIMARY]

	GRANT SELECT ON ResourceObjectContainers TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceObjectContainers TO CostumeAdmin

	ALTER TABLE ResourceObjectContainers WITH CHECK ADD CONSTRAINT FK_ResourceObjectContainers_ResourceInContainer FOREIGN KEY(ResourceContainerId)
	REFERENCES ResourceContainer (ResourceContainerId)
	ALTER TABLE ResourceObjectContainers CHECK CONSTRAINT FK_ResourceObjectContainers_ResourceInContainer	

	ALTER TABLE ResourceObjectContainers WITH CHECK ADD CONSTRAINT FK_ResourceObjectContainers_Persons FOREIGN KEY(PersonId)
	REFERENCES Persons (PersonId) ON DELETE SET NULL
	ALTER TABLE ResourceObjectContainers CHECK CONSTRAINT FK_ResourceObjectContainers_Persons

	--logische Teile in logischen Kostümen
	PRINT 'Creating ResourceObjectInResourceCostumes...'
	CREATE TABLE dbo.ResourceObjectContainerParts (
		ResourceObjectContainerPartId INT IDENTITY(1, 1) NOT NULL,
		ResourceObjectContainerId INT NOT NULL,
		ResourceObjectId INT NOT NULL,
		Note VARCHAR(1024) SPARSE NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectContainerParts_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectContainerParts_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceObjectContainerParts PRIMARY KEY NONCLUSTERED (ResourceObjectContainerPartId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_ResourceObjectContainerParts_ResourceObjectContainerId ON ResourceObjectContainerParts (ResourceObjectContainerId) ON [PRIMARY]
	CREATE INDEX IX_ResourceObjectContainerParts_ResourceObjectId ON ResourceObjectContainerParts (ResourceObjectId) ON [PRIMARY]
	
	GRANT SELECT ON ResourceObjectContainerParts TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceObjectContainerParts TO CostumeAdmin
	ALTER TABLE ResourceObjectContainerParts WITH CHECK ADD CONSTRAINT FK_ResourceObjectContainerParts_ResourceObjectContainers FOREIGN KEY(ResourceObjectContainerId)
	REFERENCES ResourceObjectContainers (ResourceObjectContainerId)
	ALTER TABLE ResourceObjectContainerParts CHECK CONSTRAINT FK_ResourceObjectContainerParts_ResourceObjectContainers

	ALTER TABLE ResourceObjectContainerParts WITH CHECK ADD CONSTRAINT FK_ResourceObjectContainerParts_ResourceObjects FOREIGN KEY(ResourceObjectId)
	REFERENCES ResourceObjects (ResourceObjectId) 
	ALTER TABLE ResourceObjectContainerParts CHECK CONSTRAINT FK_ResourceObjectContainerParts_ResourceObjects

	--Teiele für logischen Kostümen
	PRINT 'Creating ResourceCreationPartList...'
	CREATE TABLE dbo.ResourceCreationPartList (
		ResourceCreationPartListId INT IDENTITY(1, 1) NOT NULL,
		ResourceId INT NOT NULL,
		SupplierId INT NULL,
		OrderId INT NULL,
		Quantity FLOAT NOT NULL CONSTRAINT DF_ResourceCreationPartList_Quantity DEFAULT 0,
		NetPrice DECIMAL(9, 2) NULL,
		Tax DECIMAL(4, 2) NULL,
		[Description] VARCHAR(1024) NULL,
		ReferenceNo VARCHAR(20) NULL,
		Notes VARCHAR(1024) SPARSE NULL,
		Options VARCHAR(64) NULL,
		OrderUnit TINYINT NOT NULL CONSTRAINT DF_ResourceCreationPartList_OrderUnit DEFAULT 0,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceCreationPartList_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceCreationPartList_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceCreationPartList PRIMARY KEY NONCLUSTERED (ResourceCreationPartListId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_ResourceCreationPartList_ResourceId ON ResourceCreationPartList (ResourceId) ON [PRIMARY]
	CREATE INDEX IX_ResourceCreationPartList_SupplierId ON ResourceCreationPartList (SupplierId) ON [PRIMARY]
	
	GRANT SELECT ON ResourceCreationPartList TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceCreationPartList TO CostumeAdmin
	ALTER TABLE ResourceCreationPartList WITH CHECK ADD CONSTRAINT FK_ResourceCreationPartList_Resources FOREIGN KEY(ResourceId)
	REFERENCES Resources (ResourceId) ON DELETE CASCADE
	ALTER TABLE ResourceCreationPartList CHECK CONSTRAINT FK_ResourceCreationPartList_Resources

	ALTER TABLE ResourceCreationPartList WITH CHECK ADD CONSTRAINT FK_ResourceCreationPartList_Persons FOREIGN KEY(SupplierId)
	REFERENCES Persons (PersonId) ON DELETE SET NULL
	ALTER TABLE ResourceCreationPartList CHECK CONSTRAINT FK_ResourceCreationPartList_Persons

	ALTER TABLE ResourceCreationPartList WITH CHECK ADD CONSTRAINT FK_ResourceCreationPartList_Orders FOREIGN KEY(OrderId)
	REFERENCES Orders (OrderId) 
	ALTER TABLE ResourceCreationPartList CHECK CONSTRAINT FK_ResourceCreationPartList_Orders

	--Maskewninfo pro Rollenposition
	PRINT 'Creating RolePositionInfos...'
	CREATE TABLE dbo.RolePositionInfos (
		RolePositionInfoId INT IDENTITY(1, 1) NOT NULL,
		RoleId INT NOT NULL,
		GroupPosition SMALLINT NOT NULL CONSTRAINT DF_RolePositionInfos_Quantity DEFAULT 1,
		RoleMakeupArtistId INT NULL,
		PreparationStartOffsetMinutes SMALLINT NULL,
		PreparationDurationMinutes SMALLINT NULL,
		CleanUpMinutes SMALLINT NULL,
		Notes VARCHAR(1024) SPARSE NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_RolePositionInfos_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_RolePositionInfos_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_RolePositionInfos PRIMARY KEY NONCLUSTERED (RolePositionInfoId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE CLUSTERED INDEX IX_RolePositionInfos_RoleId_GroupPosition ON RolePositionInfos (RoleId, GroupPosition) ON [PRIMARY]
	CREATE INDEX IX_RolePositionInfos_RoleMakeupArtistId ON RolePositionInfos (RoleId) ON [PRIMARY]
	
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 1, StartMasktime, EndMasktime FROM Roles WHERE NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 2, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 1')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 3, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 2')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 4, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 3')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 5, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 4')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 6, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 5')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 7, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 6')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 8, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 7')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 9, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 8')
	EXEC ('INSERT INTO RolePositionInfos (RoleId, GroupPosition, PreparationStartOffsetMinutes, CleanUpMinutes) SELECT RoleId, 10, StartMasktime, EndMasktime FROM Roles INNER JOIN OwnerGroups ON Roles.OwnerGroupId = OwnerGroups.OwnerGroupId WHERE OwnerGroups.Modul <> 4 AND   NOT StartMasktime IS NULL OR NOT EndMasktime IS NULL AND PersonCount > 9')
	GRANT SELECT ON RolePositionInfos TO Public
	GRANT INSERT, UPDATE, DELETE ON RolePositionInfos TO CostumeAdmin

	ALTER TABLE RolePositionInfos WITH CHECK ADD CONSTRAINT FK_RolePositionInfos_Roles FOREIGN KEY(RoleId)
	REFERENCES Roles (RoleId) 
	ALTER TABLE RolePositionInfos CHECK CONSTRAINT FK_RolePositionInfos_Roles

	ALTER TABLE RolePositionInfos WITH CHECK ADD CONSTRAINT FK_RolePositionInfos_RolesMakeupArtist FOREIGN KEY(RoleMakeupArtistId)
	REFERENCES Roles (RoleId) ON DELETE SET NULL
	ALTER TABLE RolePositionInfos CHECK CONSTRAINT FK_RolePositionInfos_RolesMakeupArtist

	EXEC sp_rename 'Roles.StartMasktime', 'x_StartMasktime', 'COLUMN';
	EXEC sp_rename 'Roles.EndMasktime', 'x_EndMasktime', 'COLUMN';

	--Aufgabenkategorien für Rollen
	PRINT 'Creating RoleJobStepCategories...'
	CREATE TABLE dbo.RoleJobStepCategories (
		RoleJobStepCategoryId INT IDENTITY(1, 1) NOT NULL,
		[Name] VARCHAR(100) NOT NULL,
		Module SMALLINT NOT NULL,
		IsPreparationOrSceneStep TINYINT NOT NULL CONSTRAINT DF_OwnerGroups_IsPreparationOrSceneStep DEFAULT 0,
		Sort SMALLINT NOT NULL CONSTRAINT DF_RoleJobStepCategoriess_Sort DEFAULT 0,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobStepCategories_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobStepCategories_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_RoleJobStepCategories PRIMARY KEY CLUSTERED (RoleJobStepCategoryId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_RoleJobStepCategories_Name  ON RoleJobStepCategories ([Name]) ON [PRIMARY]

	GRANT SELECT ON RoleJobStepCategories TO Public
	GRANT INSERT, UPDATE, DELETE ON RoleJobStepCategories TO CostumeAdmin
	--Aufgaben für Rollen
	PRINT 'Creating RoleJobSteps...'
	CREATE TABLE dbo.RoleJobSteps (
		RoleJobStepId INT IDENTITY(1, 1) NOT NULL,
		RoleId INT NOT NULL,
		RoleJobStepCategoryId INT NOT NULL,
		--OwnerGroupId INT NOT NULL,
		OnlyPersonId INT SPARSE NULL,
		SceneId INT NULL,
		SceneDuration TINYINT NOT NULL CONSTRAINT DF_RoleJobSteps_SceneDuration DEFAULT 1,
		Sort SMALLINT NOT NULL CONSTRAINT DF_RoleJobSteps_Sort DEFAULT 0,
		[Description] VARCHAR(MAX) NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobSteps_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobSteps_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_RoleJobSteps PRIMARY KEY NONCLUSTERED (RoleJobStepId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE CLUSTERED INDEX IX_RoleJobSteps_RoleId ON RoleJobSteps (RoleId) ON [PRIMARY]

	CREATE INDEX IX_RoleJobSteps_RoleJobStepCategoryId ON RoleJobSteps (RoleJobStepCategoryId) ON [PRIMARY]
	
	CREATE INDEX IX_RoleJobSteps_OnlyPersonId ON RoleJobSteps (OnlyPersonId) ON [PRIMARY]
	CREATE INDEX IX_RoleJobSteps_SceneId ON RoleJobSteps (SceneId) ON [PRIMARY]

	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_Roles FOREIGN KEY(RoleId)
	REFERENCES Roles (RoleId) ON DELETE CASCADE
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_Roles

	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_RoleJobStepCategories FOREIGN KEY(RoleJobStepCategoryId)
	REFERENCES RoleJobStepCategories (RoleJobStepCategoryId)
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_RoleJobStepCategories
	
	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_Persons FOREIGN KEY(OnlyPersonId)
	REFERENCES Persons (PersonId) ON DELETE CASCADE
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_Persons

	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_Scenes FOREIGN KEY(SceneId)
	REFERENCES Scenes (SceneId) ON DELETE SET NULL
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_Scenes

	PRINT 'Creating RoleJobStepAttachments...'
	CREATE TABLE dbo.RoleJobStepAttachments (
		RoleJobStepAttachmentId INT IDENTITY(1,1) NOT NULL,
		RoleJobStepId INT NOT NULL,
		AttachmentId INT NOT NULL,
		Note VARCHAR(1024) SPARSE,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobStepAttachments_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_RoleJobStepAttachments_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_RoleJobStepAttachments PRIMARY KEY NONCLUSTERED (RoleJobStepAttachmentId) ON [PRIMARY]
    ) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_RoleJobStepAttachments_RoleJobStepId ON RoleJobStepAttachments (RoleJobStepId) ON [PRIMARY]
	CREATE INDEX IX_RoleJobStepAttachments_AttachmentId ON RoleJobStepAttachments (AttachmentId) ON [PRIMARY]

	GRANT INSERT, UPDATE, DELETE ON RoleJobStepAttachments TO DataService

	ALTER TABLE RoleJobStepAttachments WITH CHECK ADD CONSTRAINT FK_ResourceContainerAttachments_RoleJobSteps FOREIGN KEY(RoleJobStepId)
	REFERENCES RoleJobSteps (RoleJobStepId)
	ALTER TABLE RoleJobStepAttachments CHECK CONSTRAINT FK_ResourceContainerAttachments_RoleJobSteps

	ALTER TABLE RoleJobStepAttachments WITH CHECK ADD CONSTRAINT FK_RoleJobStepAttachments_Attachments FOREIGN KEY(AttachmentId)
	REFERENCES Attachments (AttachmentId)
	ALTER TABLE RoleJobStepAttachments CHECK CONSTRAINT FK_RoleJobStepAttachments_Attachments
		
	--Aufgabenkategorien für Rollen
	PRINT 'Creating ResourceFieldTypes...'
	CREATE TABLE dbo.ResourceFieldTypes (
		ResourceFieldTypeId INT IDENTITY(1, 1) NOT NULL,
		[Name] VARCHAR(60) NOT NULL,
		Code VARCHAR(20) NOT NULL,
		GroupName VARCHAR(60) NULL,
		DataType TINYINT NOT NULL,
		IsVisibleInOn TINYINT NOT NULL,
		ResourceTypeCategory TINYINT NOT NULL,
		Note VARCHAR(1024) SPARSE NULL,
		Sort SMALLINT NOT NULL CONSTRAINT DF_ResourceFieldTypes_Sort DEFAULT 0,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceFieldTypes_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceFieldTypes_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourcesFieldTypes PRIMARY KEY CLUSTERED (ResourceFieldTypeId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_ResourcesFieldTypes_Name ON ResourceFieldTypes (GroupName, [Name]) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_ResourcesFieldTypes_Code ON ResourceFieldTypes ([Code]) ON [PRIMARY]

	GRANT SELECT ON ResourceFieldTypes TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceFieldTypes TO CostumeAdmin

	PRINT 'Creating ResourceFieldData...'
	CREATE TABLE dbo.ResourceFieldData (
		ResourceFieldDataId INT IDENTITY(1, 1) NOT NULL,
		ResourceId INT NOT NULL,
		ResourceFieldTypeId INT NOT NULL,
		TextValue VARCHAR(MAX) NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourcesFieldData_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourcesFieldData_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourcesFieldData PRIMARY KEY NONCLUSTERED (ResourceFieldDataId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE CLUSTERED INDEX IX_ResourcesFieldData_ResourcesId_ResourcesFieldTypeId ON ResourceFieldData (ResourceId, ResourceFieldTypeId) ON [PRIMARY]
	CREATE INDEX IX_ResourceFieldData_ResourceFieldTypeId ON ResourceFieldData (ResourceFieldTypeId) ON [PRIMARY]
	
	GRANT SELECT ON ResourceFieldData TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceFieldData TO CostumeAdmin

	ALTER TABLE ResourceFieldData WITH CHECK ADD CONSTRAINT FK_ResourceFieldData_ResourceFieldTypes FOREIGN KEY(ResourceFieldTypeId)
	REFERENCES ResourceFieldTypes (ResourceFieldTypeId)
	ALTER TABLE ResourceFieldData CHECK CONSTRAINT FK_ResourceFieldData_ResourceFieldTypes

	ALTER TABLE ResourceFieldData WITH CHECK ADD CONSTRAINT FK_ResourceFieldData_Resources FOREIGN KEY(ResourceId)
	REFERENCES Resources (ResourceId)
	ALTER TABLE ResourceFieldData CHECK CONSTRAINT FK_ResourceFieldData_Resources

	PRINT 'Creating ResourceObjectFieldData...'
	CREATE TABLE dbo.ResourceObjectFieldData (
		ResourceObjectFieldDataId INT IDENTITY(1, 1) NOT NULL,
		ResourceObjectId INT NOT NULL,
		ResourceFieldTypeId INT NOT NULL,
		TextValue VARCHAR(MAX) NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectFieldDataId_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceObjectFieldDataId_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT ResourceObjectFieldDataId PRIMARY KEY NONCLUSTERED (ResourceObjectFieldDataId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE CLUSTERED INDEX IX_ResourcesFieldData_ResourcesId_ResourcesFieldTypeId ON ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId) ON [PRIMARY]
	CREATE INDEX IX_ResourcesFieldData_ResourceFieldTypeId ON ResourceObjectFieldData (ResourceFieldTypeId) ON [PRIMARY]
	
	GRANT SELECT ON ResourceObjectFieldData TO Public

	ALTER TABLE ResourceObjectFieldData WITH CHECK ADD CONSTRAINT FK_ResourceObjectFieldData_ResourceFieldTypes FOREIGN KEY(ResourceFieldTypeId)
	REFERENCES ResourceFieldTypes (ResourceFieldTypeId)
	ALTER TABLE ResourceObjectFieldData CHECK CONSTRAINT FK_ResourceObjectFieldData_ResourceFieldTypes

	ALTER TABLE ResourceObjectFieldData WITH CHECK ADD CONSTRAINT FK_ResourceObjectFieldData_Resources FOREIGN KEY(ResourceObjectId)
	REFERENCES ResourceObjects (ResourceObjectId)
	ALTER TABLE ResourceObjectFieldData CHECK CONSTRAINT FK_ResourceObjectFieldData_Resources
END
GO

IF  EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceCostumes') AND [name] = 'ResourceCostumeId')
BEGIN
PRINT 'Rename'
	EXEC sp_rename 'ResourceCostumes','ResourceObjectContainers'
	EXEC sp_rename 'ResourceObjectContainers.ResourceCostumeId', 'ResourceObjectContainerId', 'COLUMN';

	EXEC sp_rename 'ResourceObjectInResourceCostumes','ResourceObjectContainerParts'
	EXEC sp_rename 'ResourceObjectContainerParts.ResourceObjectInResourceCostumeId', 'ResourceObjectContainerPartId', 'COLUMN';
	EXEC sp_rename 'ResourceObjectContainerParts.ResourceCostumeId', 'ResourceObjectContainerId', 'COLUMN';
END
GO

IF NOT EXISTS (SELECT * FROM ResourceFieldTypes)
BEGIN
	SET IDENTITY_INSERT ResourceFieldTypes ON

	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsForOpenAirTheater="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (1, 'Freilichtbühne', 'OpenAir', 4, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 1, 'True'  FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsForOpenAirTheater="true"%'
	END

	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsPrivate="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (2, 'Dienstinstrument', 'IsPrivate', 4, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 2, 'True'  FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsPrivate="true"%'
	END

	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%HasDecreaseInValue="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (3, 'Wertminderung', 'HasDecreaseInValue', 4, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 3, 'True'  FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%HasDecreaseInValue="true"%'
	END
			
	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsGuestPerformanceCapable="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (4, 'Gastspiel', 'IsGuestPerformance', 4, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 4, 'True'  FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsGuestPerformanceCapable="true"%'
	END

	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsLentOutside="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (5, 'Verliehen nach außerhalb', 'IsLentOutside', 4, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 5, 'True'  FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsLentOutside="true"%'
	END

	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%Place="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (6, 'Ort', 'Place', 0, 2, 1)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 6, ResourceData FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%Place="true"%'
	END
	   	
	IF EXISTS (SELECT * FROM  ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsArranged="true"%')
	BEGIN
		INSERT INTO ResourceFieldTypes (ResourceFieldTypeId, [Name], Code, DataType, IsVisibleInOn, ResourceTypeCategory) VALUES (7, 'eingerichtet', 'IsArranged', 4, 2, 2)
		INSERT INTO ResourceObjectFieldData (ResourceObjectId, ResourceFieldTypeId, TextValue)
			SELECT ResourceObjectId, 7, 'True' FROM ResourceObjects WHERE NOT ResourceData IS NULL AND ResourceData LIKE '%IsArranged="true"%'
	END
	SET IDENTITY_INSERT ResourceFieldTypes OFF
END
GO

DropColumn 'ResourceObjects', 'IsAssured'
GO
DropColumn 'ResourceObjects', 'IsOutdoorCapable'
GO
DropColumn 'ResourceObjects', 'HasDecreaseInValue'
GO
DropColumn 'ResourceObjects', 'IsGuestPerformanceCapable'
GO
DropColumn 'ResourceObjects', 'ValueEstimatedBy'
GO

IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.RoleJobSteps') AND o.Name = 'IX_RoleJobSteps_OwnerGroupId') DROP INDEX IX_RoleJobSteps_OwnerGroupId ON dbo.RoleJobSteps
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_RoleJobSteps_OwnerGroups') AND type = 'F') ALTER TABLE dbo.RoleJobSteps DROP CONSTRAINT FK_RoleJobSteps_OwnerGroups
GO

DropColumn 'RoleJobSteps', 'OwnerGroupId'
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbRolePositionInfos_Update') AND type <> 'U') DROP VIEW dbo.AbRolePositionInfos_Update
GO

CREATE VIEW [dbo].AbRolePositionInfos_Update
	AS
	SELECT      rsi.*
	FROM        RolePositionInfos AS rsi 
	WHERE rsi.RoleId IN (  SELECT RoleId FROM Roles AS R
								INNER JOIN Permissions AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId   
								INNER JOIN Users			 ON Ug.Userid  = Users.Userid 
							WHERE ug.PermissionArea = 4 AND ug.HasWritePermission = 1 AND Users.Username = CURRENT_USER)
	WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON AbRolePositionInfos_Update TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbRoleJobSteps') AND type <> 'U') DROP VIEW dbo.AbRoleJobSteps
GO
CREATE VIEW [dbo].AbRoleJobSteps
	AS
	SELECT rjs.*
	FROM RoleJobSteps AS rjs 
		INNER JOIN RoleJobStepCategories AS rsc ON rjs.RoleJobStepCategoryId = rsc.RoleJobStepCategoryId
		INNER JOIN Roles AS r			ON rjs.RoleId = r.RoleId
		INNER JOIN [Permissions] AS Ug	ON r.OwnerGroupId = Ug.OwnerGroupId   
		INNER JOIN Users				ON Ug.Userid  = Users.Userid 
	WHERE ug.PermissionArea = 4
	AND	((rsc.Module = 1024 AND (ug.OptionsFlag&2 = 2 OR ug.OptionsFlag&4 = 4)) OR (rsc.Module = 2048 AND (ug.OptionsFlag&8 = 8 OR ug.OptionsFlag&16 = 16))) 
	AND Users.Username = CURRENT_USER
GO
GRANT SELECT ON AbRoleJobSteps TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbRoleJobSteps_Update') AND type <> 'U') DROP VIEW dbo.AbRoleJobSteps_Update
GO
CREATE VIEW [dbo].AbRoleJobSteps_Update
	AS
	SELECT      rjs.*
	FROM        RoleJobSteps AS rjs 
	WHERE rjs.RoleJobStepId IN (SELECT RoleJobStepId 
								FROM RoleJobSteps AS rjs 
									INNER JOIN RoleJobStepCategories AS rsc ON rjs.RoleJobStepCategoryId = rsc.RoleJobStepCategoryId
							   		INNER JOIN Roles AS r			ON rjs.RoleId = r.RoleId
									INNER JOIN [Permissions]  AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId 
									INNER JOIN  Users				ON Ug.Userid  = Users.Userid 
							   WHERE ug.PermissionArea = 4 
									AND	((rsc.Module = 1024 AND (ug.OptionsFlag&2 = 2 OR ug.OptionsFlag&4 = 4)) OR (rsc.Module = 2048 AND (ug.OptionsFlag&8 = 8 OR ug.OptionsFlag&16 = 16))) 
									AND Users.Username = CURRENT_USER)
	WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON AbRoleJobSteps_Update TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceObjectFieldData_Update') AND type <> 'U') DROP VIEW dbo.AbResourceObjectFieldData_Update
GO
CREATE VIEW dbo.AbResourceObjectFieldData_Update
AS 
SELECT  rofd.* FROM dbo.ResourceObjectFieldData AS rofd
		 WHERE  rofd.ResourceObjectId IN (SELECT ro.ResourceObjectId FROM ResourceObjects AS ro
												INNER JOIN Resources AS r ON ro.ResourceId = r.ResourceId
												INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
												INNER JOIN Users AS pw ON ug.UserId = pw.UserId
											WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO

GRANT SELECT, UPDATE, INSERT, DELETE ON AbResourceObjectFieldData_Update TO PUBLIC
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceFieldData_Update') AND type <> 'U') DROP VIEW dbo.AbResourceFieldData_Update
GO
CREATE VIEW dbo.AbResourceFieldData_Update
AS 
SELECT  rfd.* FROM dbo.ResourceFieldData AS rfd
		 WHERE  rfd.ResourceId IN (SELECT r.ResourceId FROM Resources AS r 
														INNER JOIN Permissions AS ug ON r.OwnerGroupId = ug.OwnerGroupId
														INNER JOIN Users AS pw ON ug.UserId = pw.UserId
									WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON AbResourceFieldData_Update TO PUBLIC
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Roles_Scenes') AND [name] = 'CostumeId')
BEGIN
	PRINT('Adding Roles_Scenes.CostumeId ...')
	ALTER TABLE dbo.Roles_Scenes ADD CostumeId INT NULL
	ALTER TABLE dbo.Roles_Scenes ALTER COLUMN Note VARCHAR(1024) SPARSE NULL
	ALTER TABLE Roles_Scenes WITH CHECK ADD CONSTRAINT FK_Roles_Scenes_ResourceContainer FOREIGN KEY(CostumeId)
	REFERENCES ResourceContainer (ResourceContainerId) ON DELETE SET NULL
	ALTER TABLE Roles_Scenes CHECK CONSTRAINT FK_Roles_Scenes_ResourceContainer
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobSteps') AND [name] = 'SceneDuration')
BEGIN
	PRINT('Adding RoleJobSteps.CostumeId ...')
	ALTER TABLE dbo.RoleJobSteps ADD SceneDuration TINYINT NOT NULL CONSTRAINT DF_RoleJobSteps_SceneDuration DEFAULT 1
	ALTER TABLE dbo.RoleJobSteps ADD Sort SMALLINT NOT NULL CONSTRAINT DF_RoleJobSteps_Sort DEFAULT 0
END
GO

--#endregion K/M

--#region ProjectTaskTypes Änderungen
IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('ProjectTaskTypes') AND [name] = 'Sort')
BEGIN
	PRINT('Adding column ProjectTaskTypes.Sort ...')
	ALTER TABLE ProjectTaskTypes ADD Sort SMALLINT NOT NULL CONSTRAINT DF_ProjectTaskTypes_Sort DEFAULT 0
	EXEC ('UPDATE ProjectTaskTypes SET Sort = ProjectTaskTypeId')
END
GO
--#endregion (ProjectTaskTypes Änderungen)

--#region ProductionTaskTemplates Änderungen
IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('ProductionTaskTemplates') AND [name] = 'DefaultOwnerGroupId')
BEGIN
	PRINT('Adding column ProductionTaskTemplates.DefaultOwnerGroupId ...')
	ALTER TABLE ProductionTaskTemplates ADD DefaultOwnerGroupId INT NULL
	ALTER TABLE ProductionTaskTemplates WITH CHECK ADD CONSTRAINT FK_ProductionTaskTemplates_OwnerGroups FOREIGN KEY(DefaultOwnerGroupId)
	REFERENCES OwnerGroups (OwnerGroupId) ON DELETE SET NULL
	ALTER TABLE ProductionTaskTemplates CHECK CONSTRAINT FK_ProductionTaskTemplates_OwnerGroups
END
GO
DropColumn 'ProductionTemplates', 'DayExceptionRules'
GO
DropColumn 'ProductionTemplates', 'BackColor'
--#endregion (ProductionTaskTemplates Änderungen)

--#region Implementierung IFieldtype für Resourcefieldtype 2020-05-19- DH
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceFieldTypes') AND [name] = 'Settings')
BEGIN
PRINT 'Adding ResourceFieldTypeSettings';
ALTER TABLE ResourceFieldTypes ADD Settings XML NULL;
END
GO
---
--#endregion Implementierung IFieldtype für Resourcefieldtype 2020-05-19- DH

--#region SH 2021-05-28 Kassenordnungsexport auf ExportProfiles umstellen

--#region Index UQ_ExportProfiles_Name korrigieren
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'UQ_ExportProfiles_Name')
BEGIN
	DROP INDEX [UQ_ExportProfiles_Name] ON [dbo].[ExportProfiles]
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = 'UQ_ExportProfiles_Name_ExportArea')
BEGIN
	CREATE UNIQUE NONCLUSTERED INDEX [UQ_ExportProfiles_Name_ExportArea] ON [dbo].[ExportProfiles]
(
	[Name], ExportArea
)
END
GO
--#endregion (Index korrigieren)

--#region ABExportProfiles*Views anpassen, Kassenanordnungsexporte laufen über Berechtigung für Kassenanordnungen
ALTER VIEW [dbo].[AbExportProfiles_Update]
AS 
	SELECT 	ep.*
	FROM ExportProfiles AS ep  
	WHERE (
		ep.ExportArea <> 2
		AND ep.OwnerGroupId IN (
			SELECT OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 14 AND HasWritePermission = 1 AND (ep.ExportArea & OptionsFlag) <> 0
		)
	)
	OR (
		ep.ExportArea = 2
		AND ep.OwnerGroupId IN (
			SELECT OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 7 AND HasWritePermission = 1
		)
	)
GO

ALTER VIEW [dbo].[AbExportProfiles]
AS 
	SELECT
		ep.*
	FROM
		ExportProfiles ep
	WHERE (
		ep.ExportArea <> 2
		AND ep.OwnerGroupId IN (
			SELECT OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 14 AND (ep.ExportArea & OptionsFlag) <> 0
		)
	)
	OR (
		ep.ExportArea = 2
		AND ep.OwnerGroupId IN (
			SELECT OwnerGroupId 
			FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
			WHERE Username = CURRENT_USER AND PermissionArea = 7
		)
	)
GO
--#endregion ABExportProfiles*Views anpassen, Kassenanordnungsexporte laufen über Berechtigung für Kassenanordnungen

--#region Export für Stuttgart migrieren
IF EXISTS(SELECT * FROM settings WHERE Section = 'GlobalCashCommandSettings' AND KeyName = 'D234Settings' AND IsGlobalSetting = 1 AND DataValue LIKE '%<BSDSKey>%')
AND NOT EXISTS(SELECT * FROM ExportProfiles ep WHERE ep.ExportArea = 2 AND ep.ExportProvider = 'OneTimePaymentBadenWuerttembergExport')
AND EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 213 OR (Minor=213 AND Build < 100)))))
BEGIN
	PRINT('Migrating D234Settings to new cash command export...')

	DECLARE @ownerGroupId INT
	DECLARE @ownerGroupName VARCHAR(25)
	DECLARE @providerSettings VARCHAR(MAX)

	SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
	FROM Permissions p INNER JOIN OwnerGroups og ON p.OwnerGroupId = og.OwnerGroupId
	WHERE P.PermissionArea = 7 AND og.OwnerGroupId <> -1 
	ORDER BY p.HasWritePermission DESC, og.Modul, og.sort, og.name

	IF @ownerGroupId IS NULL
	BEGIN
		SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
		FROM OwnerGroups og
		WHERE og.OwnerGroupId <> -1
		ORDER BY og.Modul, og.sort, og.name
	END

	SELECT TOP 1 @providerSettings = s.DataValue FROM Settings s WHERE Section = 'GlobalCashCommandSettings' AND KeyName = 'D234Settings' AND IsGlobalSetting = 1 AND DataValue LIKE '%<BSDSKey>%'

	PRINT('Creating cash command export named "Einmalzahlungen Baden-Württemberg" with owner "' + @ownerGroupName + '"...')
	INSERT INTO ExportProfiles (Name, ExportArea, ExportProvider, ExportProviderSettings,  OwnerGroupId, LC, UC, LM, UM)
	VALUES ('Einmalzahlungen Baden-Württemberg', 2, 'OneTimePaymentBadenWuerttembergExport', @providerSettings , @ownerGroupId, GETDATE(), 0, GETDATE(), 0);
	UPDATE Settings SET KeyName = 'X_'+KeyName WHERE Section = 'GlobalCashCommandSettings' AND KeyName = 'D234Settings'
END
GO
--#endregion (Export für Stuttgart migrieren)

--#region Logaexport migrieren
IF EXISTS(SELECT * FROM Settings s WHERE s.Section='DBSetting' AND s.KeyName = 'CashCommandClient' AND s.IsGlobalSetting = 1 AND s.DataValue IS NOT NULL AND s.DataValue <> '')
AND NOT EXISTS(SELECT * FROM ExportProfiles ep WHERE ep.ExportArea = 2 AND ep.ExportProvider = 'LogaCashCommandExport')
AND EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 213 OR (Minor=213 AND Build < 100)))))
BEGIN
	PRINT('Migrating Loga-Export settings to new cash command export...')

	DECLARE @clientIdentifier VARCHAR(MAX)
	DECLARE @logaExportSettings VARCHAR(MAX)
	DECLARE @ownerGroupId INT
	DECLARE @ownerGroupName VARCHAR(25)

	SELECT TOP 1 @clientIdentifier = DataValue FROM Settings s WHERE s.Section='DBSetting' AND s.KeyName = 'CashCommandClient' AND s.IsGlobalSetting = 1
	SELECT TOP 1 @logaExportSettings = DataValue FROM Settings s WHERE s.Section='GlobalCashCommandSettings' AND s.KeyName = 'LogaExportSettings' AND s.IsGlobalSetting = 1
	IF @logaExportSettings IS NULL OR @logaExportSettings = ''
	BEGIN
		SET @logaExportSettings = '<LogaExportSettings><EnableCostUnitNumberTransformation>true</EnableCostUnitNumberTransformation><ClientIdentifier>' + @clientIdentifier + '</ClientIdentifier></LogaExportSettings>'
	END
	ELSE
	BEGIN
		SET @logaExportSettings = REPLACE(@logaExportSettings,'</LogaExportSettings>','<ClientIdentifier>' + @clientIdentifier + '</ClientIdentifier></LogaExportSettings>')
	END

	SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
	FROM Permissions p INNER JOIN OwnerGroups og ON p.OwnerGroupId = og.OwnerGroupId
	WHERE P.PermissionArea = 7 AND og.OwnerGroupId <> -1 
	ORDER BY p.HasWritePermission DESC, og.Modul, og.sort, og.name

	IF @ownerGroupId IS NULL
	BEGIN
		SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
		FROM OwnerGroups og
		WHERE og.OwnerGroupId <> -1
		ORDER BY og.Modul, og.sort, og.name
	END
	
	PRINT('Creating cash command export named "Loga-Export" with owner "' + @ownerGroupName + '"...')
	INSERT INTO ExportProfiles (Name, ExportArea, ExportProvider, ExportProviderSettings,  OwnerGroupId, LC, UC, LM, UM)
	VALUES ('Loga-Export', 2, 'LogaCashCommandExport', @logaExportSettings , @ownerGroupId, GETDATE(), 0, GETDATE(), 0);
	UPDATE Settings SET KeyName = 'X_'+KeyName WHERE Section = 'DBSetting' AND KeyName = 'CashCommandClient'
	UPDATE Settings SET KeyName = 'X_'+KeyName WHERE Section = 'GlobalCashCommandSettings' AND KeyName = 'LogaExportSettings'
END
GO
--#endregion (Logaexport migrieren)

--#region Performance Points Export erstellen
IF EXISTS (SELECT * FROM UserFeatures uf WHERE uf.FeatureId = 'theasoft.dispo.performancepoints' AND uf.IsAvailable = 1)
AND NOT EXISTS(SELECT * FROM ExportProfiles ep WHERE ep.ExportArea = 2 AND ep.ExportProvider = 'PerformancePointsCashCommandExport')
AND EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 213 OR (Minor=213 AND Build < 100)))))
BEGIN
	DECLARE @ownerGroupId INT
	DECLARE @ownerGroupName VARCHAR(25)

	SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
	FROM Permissions p INNER JOIN OwnerGroups og ON p.OwnerGroupId = og.OwnerGroupId
	WHERE P.PermissionArea = 7 AND og.OwnerGroupId <> -1 
	ORDER BY p.HasWritePermission DESC, og.Modul, og.sort, og.name

	IF @ownerGroupId IS NULL
	BEGIN
		SELECT TOP 1 @ownerGroupId = og.OwnerGroupId, @ownerGroupName = og.Name
		FROM OwnerGroups og
		WHERE og.OwnerGroupId <> -1
		ORDER BY og.Modul, og.sort, og.name
	END
	
	PRINT('Creating new cash command export for PerformancePoints named "Performance Points Report" with owner "' + @ownerGroupName + '"...')
	INSERT INTO ExportProfiles (Name, ExportArea, ExportProvider, OwnerGroupId, LC, UC, LM, UM)
	VALUES ('Performance Points Report', 2, 'PerformancePointsCashCommandExport', @ownerGroupId, GETDATE(), 0, GETDATE(), 0);
END
GO
--#endregion (Performance Points Export erstellen)

--#region Views für Pläne anpassen, Exporte über Payment Berechtigung
ALTER VIEW [dbo].[AbPlanConfiguration]
AS 
SELECT  p.* FROM PlanLayouts AS p
WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
	))
	OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
	))
	OR p.PlanLayoutId IN (
		SELECT pps.PlanLayoutId FROM PlanLayoutPermissions pps
		INNER JOIN Users g ON pps.UserId = g.UserID
		INNER JOIN UsersInGroups uig ON g.UserId = uig.GroupId  
		INNER JOIN Users u on uig.UserId = u.UserID AND u.UserName = CURRENT_USER
	)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[AbPlanConfiguration_Update]
AS 
SELECT  p.*  FROM PlanLayouts AS p
WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11 AND Permissions.HasWritePermission = 1
	)) OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7 AND Permissions.HasWritePermission = 1
	))
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[AbPlanColumn]
AS 
SELECT  ps.*  FROM [PlanColumns] ps INNER JOIN PlanLayouts  AS p on ps.PlanLayoutId = p.PlanLayoutId
WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
	))
	OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
	))
	OR p.PlanLayoutId IN (
		SELECT pps.PlanLayoutId FROM PlanLayoutPermissions pps
		INNER JOIN Users g ON pps.UserId = g.UserID
		INNER JOIN UsersInGroups uig ON g.UserId = uig.GroupId  
		INNER JOIN Users u on uig.UserId = u.UserID AND u.UserName = CURRENT_USER
	)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[AbPlanColumn_Update]
AS 
SELECT  ps.*  FROM [PlanColumns] ps WHERE ps.PlanLayoutId IN (
	SELECT p.PlanLayoutId FROM PlanLayouts p
	WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11 AND Permissions.HasWritePermission = 1
	)) OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7 AND Permissions.HasWritePermission = 1
	))
)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[AbPlanSort]
AS 
SELECT  pso.*  FROM PlanColumnContent pso
	INNER JOIN  PlanColumns ps ON pso.PlanColumnId = ps.PlanColumnId 
	INNER JOIN  PlanLayouts AS p ON ps.PlanLayoutId = p.PlanLayoutId 
WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11
	))
	OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7
	))
	OR p.PlanLayoutId IN (
		SELECT pps.PlanLayoutId FROM PlanLayoutPermissions pps
		INNER JOIN Users g ON pps.UserId = g.UserID
		INNER JOIN UsersInGroups uig ON g.UserId = uig.GroupId  
		INNER JOIN Users u on uig.UserId = u.UserID AND u.UserName = CURRENT_USER
	)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[AbPlanSort_Update]
AS 
SELECT  pso.*  FROM PlanColumnContent pso WHERE pso.PlanColumnId IN (
	SELECT ps.PlanColumnId FROM PlanColumns ps 
		INNER JOIN PlanLayouts p ON ps.PlanLayoutId=p.PlanLayoutId
	WHERE (p.PlanLayoutType <> 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 11 AND Permissions.HasWritePermission = 1
	)) OR (p.PlanLayoutType = 150 AND p.OwnerGroupId IN (
		SELECT Permissions.OwnerGroupId 
		FROM Permissions INNER JOIN Users ON Permissions.Userid = Users.Userid 
		WHERE Users.Username = CURRENT_USER AND PermissionArea = 7 AND Permissions.HasWritePermission = 1
	))
)
WITH CHECK OPTION
GO
--#endregion (Views für Pläne anpassen, Exporte über Payment Berechtigung)

--#endregion SH 2021-05-28

--#region 2021-06-18
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ResourceObjectContainerParts') AND o.Name = 'IX_ResourceObjectInResourceCostumes_ResourceCostumeId') 
	DROP INDEX IX_ResourceObjectInResourceCostumes_ResourceCostumeId ON dbo.ResourceObjectContainerParts

IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ResourceObjectContainerParts') AND o.Name = 'IX_ResourceObjectInResourceCostumes_ResourceCostumeId')
	DROP INDEX IX_ResourceObjectInResourceCostumes_ResourceCostumeId ON dbo.ResourceObjectContainerParts

IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ResourceObjectContainerParts') AND o.Name = 'IX_ResourceObjectContainerParts_ResourceObjectContainerId')
	DROP INDEX IX_ResourceObjectContainerParts_ResourceObjectContainerId ON dbo.ResourceObjectContainerParts
		
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.ResourceObjectContainerParts') AND o.Name = 'IX_ResourceObjectContainerParts_ResourceObjectContainerId_ResourceObjectId')
	CREATE UNIQUE CLUSTERED INDEX IX_ResourceObjectContainerParts_ResourceObjectContainerId_ResourceObjectId ON ResourceObjectContainerParts (ResourceObjectContainerId, ResourceObjectId) ON [PRIMARY]
GO
--#endregion

--#region 2021-06-08
IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('Persons') AND [name] = 'PrintFunctionInAddress')
BEGIN
	PRINT('Adding column Persons.PrintFunctionInAdress ...')
	ALTER TABLE Persons ADD PrintFunctionInAddress BIT NOT NULL CONSTRAINT DF_Persons_PrintFunctionInAddress DEFAULT 0
	ALTER TABLE Persons ADD IsOfficialOrDignitary BIT NOT NULL CONSTRAINT DF_Persons_IsOfficialOrDignitary DEFAULT 0
	ALTER TABLE PersonAddress ADD IsHomeAddress BIT NOT NULL CONSTRAINT DF_PersonAddress_IsHomeAddress DEFAULT 0
	ALTER TABLE PersonAddress ALTER COLUMN Note VARCHAR(1024) SPARSE NULL
	ALTER TABLE PersonAddress ALTER COLUMN CO NVARCHAR(80) SPARSE NULL
	UPDATE PersonAddress SET Street = NULL WHERE Street = ''
	UPDATE PersonAddress SET PostCode = NULL WHERE PostCode = ''
	UPDATE PersonAddress SET City = NULL WHERE City = ''
	UPDATE PersonAddress SET CountryCode = NULL WHERE CountryCode = ''
	UPDATE PersonAddress SET Co = NULL WHERE Co = ''
	UPDATE PersonAddress SET [Name] = NULL WHERE [Name]  = ''
	UPDATE PersonAddress SET [Note] = NULL WHERE [Note]  = ''
END

GO
--#endregion

--#region StaffAdmin DH 2021-06-08
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE NAME='StaffAdmin')
BEGIN
	PRINT('Add StaffAdmin...')
	EXEC sp_addrole @rolename = N'StaffAdmin'
	
	GRANT INSERT, UPDATE, DELETE ON MeasureTypes TO StaffAdmin
	REVOKE INSERT, UPDATE, DELETE ON MeasureTypes TO Public

	GRANT INSERT, UPDATE, DELETE ON QualificationRequiredMeasureTypes TO StaffAdmin
	REVOKE INSERT, UPDATE, DELETE ON QualificationRequiredMeasureTypes TO Public

	GRANT INSERT,UPDATE, DELETE ON QualificationCategory TO StaffAdmin
	GRANT INSERT,UPDATE, DELETE ON Qualification TO StaffAdmin
END
GO
--#endregion staffAdmin DH 2021-06-08

--#endregion ------- (4.213.x) --------------------------------

--#region ----------- 4.213.x Release Übertrag ----------------

--#region Bugfix CopyRole DH-2021-06-28

ALTER PROCEDURE [dbo].[CopyRole]
	@productionId int,
	@roleId  int
As
BEGIN
	DECLARE @userId INT

	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
INSERT INTO Roles (
	[Name],[Pos],[Leporello],[PresseSort],[IsProductionTeam],[RoleTypeId],JourneyGroupId,IsFontBold
      ,[PrintMode],[OwnerGroupId],PersonCount,[ShortName]
      ,[CountDownId],[PublishedName],[IsStarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast]
	  ,[ProductionId] 
      ,[LM]
      ,[UM]
      ,[LC]
      ,[UC]) 
SELECT 
	[Name],[Pos],[Leporello],[PresseSort],[IsProductionTeam],[RoleTypeId],JourneyGroupId,IsFontBold
      ,[PrintMode],[OwnerGroupId],PersonCount,[ShortName]
      ,[CountDownId],[PublishedName],[IsStarRole],[IsInactive],[RoleCode],[Note],[RoleCategoryId],[WorkVersionRoleId]
	  ,[AutoCast]
	  ,@productionId, 
	  GETDATE(),
	  @userId,
	  GETDATE(),
	  @userId
FROM Roles AS RoleSource WHERE RoleSource.RoleId = @roleId
SELECT CAST(@@IDENTITY as INT)
END
GO
--#endregion Bugfix CopyRole DH-2021-06-28

--#region SH 2021-06-28 Spalte CostUnitWorkingTimes.ActivityEndOffsetMinutes hinzufügen und ActivityStartOffsetMinutes auf NOT NULL ändern

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('CostUnitWorkingTimes') AND [name] = 'ActivityEndOffsetMinutes')
BEGIN
	PRINT('Adding CostUnitWorkingTimes.ActivityEndOffsetMinutes ...')
	ALTER TABLE dbo.CostUnitWorkingTimes ADD ActivityEndOffsetMinutes INT NOT NULL 
	CONSTRAINT DF_CostUnitWorkingTimes_ActivityEndOffsetMinutes DEFAULT 0

	UPDATE CostUnitWorkingTimes SET ActivityStartOffsetMinutes = 0 WHERE ActivityStartOffsetMinutes IS NULL
	ALTER TABLE CostUnitWorkingTimes ALTER COLUMN ActivityStartOffsetMinutes INT NOT NULL
END
GO


--#endregion (SH 2021-06-28 Spalte CostUnitWorkingTimes.ActivityEndOffsetMinutes hinzufügen)

--#region SH 2021-07-06 CashCommand CSV Exporte migrieren
IF EXISTS(
	SELECT * FROM PlanLayouts p
	WHERE
		p.PlanLayoutType = 150
		AND NOT EXISTS (
			SELECT * FROM ExportProfiles ep
			WHERE
				ep.ExportArea = 2
				AND ep.ExportProvider='DynamicCsvCashCommandExport'
				AND CONVERT(NVARCHAR(MAX), ep.ExportProviderSettings) LIKE '%'+ CONVERT(VARCHAR(MAX),P.PlanLayoutId) +'%' )
	)
	AND EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 213 OR (Minor=213 AND Build < 103)))))
BEGIN
	PRINT('Migrating CSV-Export settings to new cash command export...')

	INSERT INTO ExportProfiles (Name, ExportArea, ExportProvider, ExportProviderSettings,  OwnerGroupId, LC, UC, LM, UM)
	SELECT p.Name, 2, 'DynamicCsvCashCommandExport', '<DynamicCsvCashCommandExportProviderSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ExportPlanId>'+ CONVERT(VARCHAR(MAX),P.PlanLayoutId) + '</ExportPlanId>
</DynamicCsvCashCommandExportProviderSettings>', p.OwnerGroupId, p.lc, p.uc,p.lm,p.um FROM PlanLayouts p
	WHERE
		p.PlanLayoutType = 150
		AND NOT EXISTS (
			SELECT * FROM ExportProfiles ep
			WHERE
				ep.ExportArea = 2
				AND ep.ExportProvider='DynamicCsvCashCommandExport'
				AND CONVERT(NVARCHAR(MAX), ep.ExportProviderSettings) LIKE '%'+ CONVERT(VARCHAR(MAX),P.PlanLayoutId) +'%' )
END
GO
--#endregion (SH 2021-07-06 CashCommand CSV Exporte migrieren)

--#region SH 2021-07-19 Anpassung von SP da BonusDutyRosterData.DutyRosterId entfernt wurde

--#region ClearOldDutyRosterData

ALTER PROCEDURE [dbo].[ClearOldDutyRosterData]
@enddate datetime,
@monthclosedfor int,
@YearClosed bit, 
@infoOnly bit
AS
BEGIN
	IF @enddate is NULL set @enddate = getdate()

	--TEMPORÄRE TABELLE MIT DEN DIENSTPLANEINTRÄGEN, DIE GELÖSCHT WERDEN SOLLEN.
	SELECT DISTINCT d.DutyRosterId,d.Date 
	INTO #TempDutyRosterEntries 
	FROM DutyRoster d 
		INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId
		INNER JOIN  WorkAreas ON vp.WorkAreaId=WorkAreas.WorkAreaId 
		INNER JOIN Departments da ON WorkAreas.DepartmentId = da.DepartmentId
	WHERE
		d.Date < @endDate 
		AND (DATEPART(YEAR, d.Date)*100 + DATEPART(MONTH, d.Date)) <= (COALESCE(da.LastClosedYearMonth, 190001) - @monthclosedfor)
		AND (@YearClosed=0 
			    OR NOT EXISTS(SELECT * FROM YearClosePeriods j
				            WHERE (DATEPART(YEAR, d.Date)*100 + DATEPART(MONTH, d.Date)) BETWEEN j.StartYearMonth AND j.EndYearMonth
							        AND j.IsClosed = 0
			    )
		)

	IF(@infoOnly=0)
	BEGIN
		SELECT COUNT(*) FROM #TempDutyRosterEntries
		DELETE FROM CostUnitWorkingTimes where ShiftDayId in (select DutyRosterId from #TempDutyRosterEntries)
		DELETE FROM DutyRoster  where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntries)
	END
	ELSE
	BEGIN
		SELECT COUNT(*) FROM #TempDutyRosterEntries
	END
	DROP TABLE #TempDutyRosterEntries
END
GO

--#endregion (ClearOldDutyRosterData)

--#region ClearOldContracts

ALTER PROCEDURE [dbo].[ClearOldContracts]
@contractEndBefore DateTime,
@infoOnly bit
AS
BEGIN
		SELECT DISTINCT v.ContractId 
		INTO #TempContracts
		FROM Contracts v 
		WHERE      v.EndDate < @contractEndBefore	

		IF(@infoOnly=0)
		BEGIN	
			SELECT DISTINCT d.DutyRosterId,d.Date 
			INTO #TempDutyRosterEntrys 
			FROM DutyRoster d 
				INNER JOIN  ContractDepartments as vp ON d.ContractId = vp.ContractId where vp.ContractId in  (select ContractId from #TempContracts);
			DELETE FROM CostUnitWorkingTimes where ShiftDayId in (select DutyRosterId from #TempDutyRosterEntrys)
			DELETE FROM BonusDutyRosterData where ContractId in (select ContractId from #TempContracts)
			DELETE FROM DutyRoster  where DutyRosterId in (select DutyRosterId from #TempDutyRosterEntrys)
			SELECT COUNT(*) FROM #TempContracts
			DELETE FROM CastCredits where ContractId in (select ContractId from #TempContracts);
			DELETE FROM  Contract_Qualification_Person where ContractId in (select ContractId from #TempContracts);
			DELETE FROM  ContractBonus where ContractId in (select ContractId from #TempContracts);
			DELETE FROM ContractDateConfirmations where ContractConfirmationId in (SELECT ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select ContractId from #TempContracts));
			DELETE FROM ContractDocumentAttachments where ContractDocumentId in ((SELECT ContractConfirmationId FROM ContractConfirmations WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractConfirmations WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractFields WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractPartTimePeriods WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractSeasonInformation WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM TimeAccountUsage WHERE ContractId in (SELECT ContractId from #TempContracts);			
			DELETE FROM Tours_Contracts WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM Tours_InventoryItems WHERE ContractId in (SELECT ContractId from #TempContracts);	
			DELETE FROM Travels WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDetails WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractWorkingTimeModels where ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDepartments WHERE ContractId in (SELECT ContractId from #TempContracts);
			DELETE FROM ContractDateMaturities Where ContractDateId in (SELECT ContractDateId FROM ContractDates WHERE ContractEngagementId in (select ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractDateConfirmations where ContractDateId in (SELECT ContractDateId FROM ContractDates WHERE ContractEngagementId in (select ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts)));
			DELETE FROM ContractDates WHERE ContractEngagementId in (SELECT ContractEngagementId FROM ContractEngagements WHERE ContractId in (select ContractId from #TempContracts));	
			DELETE FROM ContractEngagements WHERE ContractId in (SELECT ContractId from #TempContracts);			
			DELETE FROM Contracts  where ContractId in (SELECT ContractId from #TempContracts);
			END
		ELSE
		BEGIN
			SELECT COUNT(*) FROM #TempContracts
		END
		DROP TABLE #TempContracts	
End
GO
IF EXISTS (SELECT * FROM  sysobjects o WHERE o.id = OBJECT_ID(N'dbo.PersQuali')) DROP TABLE dbo.PersQuali
GO
--#endregion (ClearOldContracts)

--#endregion (SH 2021-07-19 Anpassung von SP da BonusDutyRosterData.DutyRosterId entfernt wurde)

--#region SH 2021-07-22 Bugfix ProductionTimeFlow_Update, Auswertung vom Flag CanAddWorks hinzugefügt

ALTER VIEW [dbo].[ProductionTimeFlow_Update]
AS 
SELECT * FROM ProductionTimeFlow WHERE ProductionId IN (
	SELECT  p.ProductionId  FROM  Productions AS P INNER  JOIN(SELECT DISTINCT OwnerGroupId, HasWritePermission FROM Permissions 
					INNER JOIN	Users	ON Permissions.Userid = Users.Userid 
					WHERE Username = CURRENT_USER  AND PermissionArea = 3 AND (HasWritePermission = 1 OR OptionsFlag&2 = 2)) AS UG
	ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION
GO

--#endregion (SH 2021-07-22 Bugfix ProductionTimeFlow_Update, Auswertung vom Flag CanAddWorks hinzugefügt)

--#region 20210809 Arbeitszeiten dürfen kein Konto mit Standardarbeitszeiten haben 
UPDATE DutyRoster SET ShiftTypeId1 = 0  FROM DutyRoster INNER JOIN ShiftTypes ON DutyRoster.ShiftTypeId1 = ShiftTypes.ShiftTypeId 
WHERE NOT StartTime1 IS NULL
AND (SELECT TimeAccountId FROM ShiftTypes AS a WHERE ShiftTypeId = 0) = ShiftTypes.TimeAccountId
AND (NOT StartTimeDefault1 IS NULL OR NOT StartTimeDefault2 IS NULL OR NOT StartTimeDefault3 IS NULL)


UPDATE DutyRoster SET ShiftTypeId2 = 0  FROM DutyRoster INNER JOIN ShiftTypes ON DutyRoster.ShiftTypeId2 = ShiftTypes.ShiftTypeId 
WHERE NOT StartTime2 IS NULL
AND (SELECT TimeAccountId FROM ShiftTypes AS a WHERE ShiftTypeId = 0) = ShiftTypes.TimeAccountId
AND (NOT StartTimeDefault1 IS NULL OR NOT StartTimeDefault2 IS NULL OR NOT StartTimeDefault3 IS NULL)


UPDATE DutyRoster SET ShiftTypeId3 = 0 FROM DutyRoster INNER JOIN ShiftTypes ON DutyRoster.ShiftTypeId3 = ShiftTypes.ShiftTypeId 
WHERE NOT StartTime3 IS NULL
AND (SELECT TimeAccountId FROM ShiftTypes AS a WHERE ShiftTypeId = 0) = ShiftTypes.TimeAccountId
AND (NOT StartTimeDefault1 IS NULL OR NOT StartTimeDefault2 IS NULL OR NOT StartTimeDefault3 IS NULL)

UPDATE ShiftTypes SET Note = NULL WHERE Note = '#Script#'
GO
--#endregion 

--#endregion -------- (4.213.x Release Übertrag) --------------

--#region ----------- 4.214.x ---------------------------------

--#region 2021-06-08

IF NOT EXISTS (SELECT * FROM sys.columns WHERE  object_id = OBJECT_ID('ResourceCreationPartList') AND [name] = 'OrderUnit')
BEGIN
	PRINT('Adding column ResourceCreationPartList.Unit ...')
	--Farbe/Größe
	ALTER TABLE ResourceCreationPartList ADD Options VARCHAR(64) NULL 
	ALTER TABLE ResourceCreationPartList ADD OrderUnit TINYINT NOT NULL CONSTRAINT DF_ResourceCreationPartList_OrderUnit DEFAULT 0
END
GO
--#endregion

--#region TK 2021-07-06 Index
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'TimeAccountMonthValues') AND o.Name = 'IX_VertragsNr_ZeitktoNr_JahrMonat_ZmType_zmSort_FromDifferentTimeAccountId')
BEGIN
	PRINT('TimeAccountMonthValues ...')
	DELETE FROM TimeAccountMonthValues WHERE [DataValue] = 0 AND Note IS NULL AND IsManualEntry = 0

	DROP INDEX IX_VertragsNr_ZeitktoNr_JahrMonat_ZmType_zmSort_FromDifferentTimeAccountId ON [dbo].TimeAccountMonthValues
	ALTER TABLE [dbo].TimeAccountMonthValues DROP CONSTRAINT PK_TimeAccountMonthValues

	ALTER TABLE [dbo].[TimeAccountMonthValues] DROP CONSTRAINT DF_TimeAccountMonthValues_ZmType
	ALTER TABLE [dbo].[TimeAccountMonthValues] ALTER COLUMN ZmType TINYINT NOT NULL
	ALTER TABLE [dbo].[TimeAccountMonthValues] ADD CONSTRAINT DF_TimeAccountMonthValues_ZmType DEFAULT 1 FOR ZmType
	
	ALTER TABLE [dbo].[TimeAccountMonthValues] DROP CONSTRAINT DF_TimeAccountMonthValues_zmSort
	ALTER TABLE [dbo].[TimeAccountMonthValues] ALTER COLUMN ZmSort SMALLINT NOT NULL
	ALTER TABLE [dbo].[TimeAccountMonthValues] ADD CONSTRAINT DF_ZmSort DEFAULT 0 FOR ZmSort

	CREATE UNIQUE CLUSTERED INDEX IX_TimeAccountMonthValues_All ON [dbo].[TimeAccountMonthValues]
	(	[TimeAccountId], [ContractId], [YearMonth], [ZmType], [ZmSort], [FromDifferentTimeAccountId]) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX IX_TimeAccountMonthValues_Contract_YearMonth ON [dbo].[TimeAccountMonthValues]
	(	[ContractId], [YearMonth]
	) ON [PRIMARY]

	ALTER TABLE [dbo].TimeAccountMonthValues ADD CONSTRAINT PK_TimeAccountMonthValues PRIMARY KEY NONCLUSTERED 
	(	TimeAccountMonthValueId ) ON [PRIMARY]	
END
GO

IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'Tours_Contracts') AND o.Name = 'IX_Tours_Contracts_TourId_ContractId')
BEGIN
	PRINT('IX Tours_Contracts ...')
	
	DROP INDEX IX_Tours_Contracts_TourId_ContractId ON [dbo].Tours_Contracts

	ALTER TABLE [dbo].Tours_Contracts DROP CONSTRAINT PK_Tours_Contracts
	--Es ist nicht sinvoll die selbe Person einen Tour im selben Zeitraum mehrmals zuzuordnen. Deswegen index: tourPersonStart
	--Hack: Wurde eine Person bereits ein zweites mal zugeordnet, wird das StartDatumn der Tour eingetragen, dann gibt es einen Satz mit null un einen mit dem Datum
	--Ab drei Zuordnungen muss manuell nachgearbeitet werden...
	UPDATE Tours_Contracts SET StartDate = tours.[Start] FROM Tours_Contracts 
															INNER JOIN tours ON Tours_Contracts.tourId = Tours.tourId 
															INNER JOIN 	(SELECT MAX(TourContractId) AS id FROM Tours_Contracts GROUP BY TourId, PersonId, StartDate HAVING COUNT(*) > 1) AS sub 
																ON Tours_Contracts.TourContractId = sub.id

	CREATE UNIQUE CLUSTERED INDEX IX_Tours_Contracts_TourId_PersonId_StartDate ON [dbo].Tours_Contracts (TourId, PersonId, StartDate) ON [PRIMARY]
	   
	ALTER TABLE [dbo].Tours_Contracts ADD CONSTRAINT PK_Tours_Contracts PRIMARY KEY NONCLUSTERED 
	(TourContractId) ON [PRIMARY]	
END
GO

IF EXISTS (SELECT * FROM sysindexes o WHERE o.id = OBJECT_ID(N'TechnicalJobs') AND o.Name = 'IX_AuffTechAufgabe_Activity')
BEGIN
	PRINT('IX TechnicalJobs ...')
	
	DROP INDEX IX_AuffTechAufgabe_Activity ON [dbo].TechnicalJobs
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_TechnicalJobs_IntervalTask_IntervalId') AND type = 'F') ALTER TABLE dbo.TechnicalJobs DROP CONSTRAINT FK_TechnicalJobs_IntervalTask_IntervalId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_IntervalTask_TechnicalJobs_TaskId') AND type = 'F') ALTER TABLE dbo.IntervalTask DROP CONSTRAINT FK_IntervalTask_TechnicalJobs_TaskId
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_CostUnitWorkingTimes_TechnicalJobs_ActivityJobId') AND type = 'F') ALTER TABLE dbo.CostUnitWorkingTimes DROP CONSTRAINT FK_CostUnitWorkingTimes_TechnicalJobs_ActivityJobId
	ALTER TABLE [dbo].TechnicalJobs DROP CONSTRAINT PK_TechnicalJobs

	CREATE CLUSTERED INDEX IX_TechnicalJobs_ActivityId_RoleId ON [dbo].TechnicalJobs (ActivityId, RoleId) ON [PRIMARY]
	   
	ALTER TABLE [dbo].TechnicalJobs ADD CONSTRAINT PK_TechnicalJobs PRIMARY KEY NONCLUSTERED (TechnicalJobId) ON [PRIMARY]	
	
	ALTER TABLE [dbo].[TechnicalJobs]  WITH CHECK ADD  CONSTRAINT [FK_TechnicalJobs_IntervalTask_IntervalId] FOREIGN KEY([IntervalId])
		REFERENCES [dbo].[IntervalTask] ([IntervalTaskId])
	ALTER TABLE [dbo].[TechnicalJobs] CHECK CONSTRAINT [FK_TechnicalJobs_IntervalTask_IntervalId]
	    
	ALTER TABLE [dbo].[CostUnitWorkingTimes]  WITH CHECK ADD  CONSTRAINT [FK_CostUnitWorkingTimes_TechnicalJobs_ActivityJobId] FOREIGN KEY([ActivityJobId])
		REFERENCES [dbo].[TechnicalJobs] ([TechnicalJobId])
		ON DELETE CASCADE
	ALTER TABLE [dbo].[CostUnitWorkingTimes] CHECK CONSTRAINT [FK_CostUnitWorkingTimes_TechnicalJobs_ActivityJobId]
	
	ALTER TABLE TechnicalJobs DROP CONSTRAINT DF_TechnicalJobs_PersonCount
	ALTER TABLE TechnicalJobs ALTER COLUMN PersonCount SMALLINT NOT NULL
	ALTER TABLE TechnicalJobs ADD CONSTRAINT DF_TechnicalJobs_PersonCount DEFAULT 0 FOR PersonCount	
END
GO

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('SalaryLevel') AND [name] = 'SalaryLevelShortName' and max_length <21 )
BEGIN
	ALTER TABLE SalaryLevel ALTER COLUMN SalaryLevelShortName VARCHAR(20) NOT NULL
END
GO
--#endregion

--#region DH-20210705 CompensationWeek
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('personstatus') AND [name] = 'CompensationWeekValue')
BEGIN
ALTER TABLE PersonStatus ADD CompensationWeekValue INT NULL 
END
GO

Alter VIEW [dbo].[AbPersStatus]
AS 
SELECT PersonStatusId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN sr.Note  ELSE NULL END AS Note,
	CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,

	CASE WHEN z.Formel IN (1, 2) THEN 2  WHEN z.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
	CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
	sr.ApprovalStatus, sr.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, sr.LM, sr.UM, sr.LC, sr.UC,
	p.KeyName, p.OwnerGroupId,sr.CompensationWeekValue
FROM PersonStatus AS sr
	INNER JOIN Persons AS p ON sr.PersonId = p.PersonId 
	INNER JOIN PersonStatusTypes AS st ON sr.PersonStatusTypeId = st.PersonStatusTypeId 
	INNER JOIN TimeAccounts AS z ON st.TimeAccountId = z.TimeAccountId
	INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
	INNER JOIN Users ON ug.Userid = Users.Userid
WHERE Users.Username = CURRENT_USER AND PermissionArea = 8 
GO

ALTER PROCEDURE [dbo].[GetPersonStatusInternal]
	@condition VARCHAR(MAX),
	@collectives BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	IF (@collectives = 0)
		BEGIN
			 SET @SQLQuery ='SELECT PersonStatusId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.Note  ELSE NULL END AS Note,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,
				CASE WHEN TimeAccounts.Formel IN (1, 2) THEN 2 WHEN TimeAccounts.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
				CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
				ps.ApprovalStatus, ps.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, ps.LM, ps.UM, ps.LC, ps.UC,ps.CompensationWeekValue
			FROM PersonStatus AS ps
				INNER JOIN Persons AS p ON ps.PersonId = p.PersonId 
				INNER JOIN PersonStatusTypes AS st ON ps.PersonStatusTypeId = st.PersonStatusTypeId 
				INNER JOIN TimeAccounts  ON st.TimeAccountId = TimeAccounts.TimeAccountId
				INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
			WHERE ug.Userid = '+ CAST(@userId AS VARCHAR(10))+ 'AND PermissionArea = 8'
		END
	ELSE
		BEGIN
			 SET @SQLQuery =' SELECT ps.*, 
						st.TimeAccountId,
						1 AS AvailableStatus,
						CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1 ELSE 0 END AS IsHalfDayType
						,ps.CompensationWeekValue
			FROM		   PersonStatus		 AS ps
				INNER JOIN PersonStatusTypes AS st	ON ps.PersonStatusTypeId = st.PersonStatusTypeId
				INNER JOIN TimeAccounts				ON st.TimeAccountId = TimeAccounts.TimeAccountId
			WHERE EXISTS (SELECT PersonId
							FROM PersonInCategories AS pic
								INNER JOIN PersonCategories AS cat ON pic.PersonCategoryId = cat.PersonCategoryId
							WHERE cat.PersonCategoryType BETWEEN 10 AND 200 AND  pic.PersonId = ps.PersonId)'
		END

	SET @SQLQuery = @SQLQuery + ' AND ' + @condition
	EXECUTE sp_Executesql @SQLQuery
END
GO

ALTER PROCEDURE [dbo].[GetPersonStatusInternal]
	@condition VARCHAR(MAX),
	@collectives BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	IF (@collectives = 0)
		BEGIN
			 SET @SQLQuery ='SELECT PersonStatusId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.PersonStatusTypeId ELSE -1 END AS PersonStatusTypeId,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN ps.Note  ELSE NULL END AS Note,
				CASE WHEN ug.HasWritePermission = 1 OR ug.OptionsFlag & 256 = 256 THEN st.TimeAccountId  ELSE -1 END AS TimeAccountId,
				CASE WHEN TimeAccounts.Formel IN (1, 2) THEN 2 WHEN TimeAccounts.Formel = 4050 THEN 4 ELSE 1 END AS AvailableStatus,
				CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1  ELSE 0 END AS IsHalfDayType,
				ps.ApprovalStatus, ps.PersonId, ContractId, StartDate, EndDate, StartTime, EndTime, ManualDayCount, DateOfRequest, ps.LM, ps.UM, ps.LC, ps.UC,ps.CompensationWeekValue
			FROM PersonStatus AS ps
				INNER JOIN Persons AS p ON ps.PersonId = p.PersonId 
				INNER JOIN PersonStatusTypes AS st ON ps.PersonStatusTypeId = st.PersonStatusTypeId 
				INNER JOIN TimeAccounts  ON st.TimeAccountId = TimeAccounts.TimeAccountId
				INNER JOIN Permissions AS ug ON p.OwnerGroupId = ug.OwnerGroupId
			WHERE ug.Userid = '+ CAST(@userId AS VARCHAR(10))+ 'AND PermissionArea = 8'
		END
	ELSE
		BEGIN
			 SET @SQLQuery =' SELECT ps.*, 
						st.TimeAccountId,
						1 AS AvailableStatus,
						CASE WHEN NOT st.TemplateStartTime IS NULL OR NOT st.TemplateEndTime IS NULL THEN 1 ELSE 0 END AS IsHalfDayType
						,ps.CompensationWeekValue
			FROM		   PersonStatus		 AS ps
				INNER JOIN PersonStatusTypes AS st	ON ps.PersonStatusTypeId = st.PersonStatusTypeId
				INNER JOIN TimeAccounts				ON st.TimeAccountId = TimeAccounts.TimeAccountId
			WHERE EXISTS (SELECT PersonId
							FROM PersonInCategories AS pic
								INNER JOIN PersonCategories AS cat ON pic.PersonCategoryId = cat.PersonCategoryId
							WHERE cat.PersonCategoryType BETWEEN 10 AND 200 AND  pic.PersonId = ps.PersonId)'
		END

	SET @SQLQuery = @SQLQuery + ' AND ' + @condition
	EXECUTE sp_Executesql @SQLQuery
END
GO

--#endregion DH-20210705 CompensationWeek

--#region

IF EXISTS (SELECT * FROM NVDATA WHERE ByModulScript = 1 AND (Major * 100000000) + (Minor * 1000) + Build  < 400214003) 
BEGIN
	UPDATE Departments SET LayoutSettings = REPLACE(REPLACE(CAST(LayoutSettings AS VARCHAR(MAX)),'Seperate','Separate'),'DutyRosterLayotSettings','DutyRosterLayoutSettings')
	UPDATE Departments SET LayoutSettings = REPLACE(CAST(LayoutSettings AS VARCHAR(MAX)),'</NameFormat>','</NameFormat><ColWidthShifts>' + CAST(ISNULL(ColWidth, 65) AS VARCHAR(MAX)) +'</ColWidthShifts>')
	UPDATE Departments SET LayoutSettings = REPLACE(CAST(LayoutSettings AS VARCHAR(MAX)),'</NameFormat>',
	'</NameFormat>
	<VisibleCells>FirstShift' +  ISNULL( 
	 (CASE WHEN VisibleColumns&2=2 THEN ' SecondShift ' ELSE '' END) 
	+(CASE WHEN VisibleColumns&4=4 THEN ' ThirdShift ' ELSE '' END) 
	+(CASE WHEN VisibleColumns&8=8 THEN ' Note ' ELSE '' END)
	+(CASE WHEN VisibleColumns&16=16 THEN ' WorkingTime ' ELSE '' END)
	+(CASE WHEN VisibleColumns&32=32 THEN ' Duties ' ELSE '' END)
	+(CASE WHEN VisibleColumns&64=64 THEN ' RegularTime ' ELSE '' END)
	 , '')   +'</VisibleCells>')

	UPDATE Departments SET LayoutSettings = REPLACE(CAST(LayoutSettings AS VARCHAR(MAX)),'</NameFormat>',
	'</NameFormat>
		<UserDefaultSettings>
			<CountPresentShifts>' + ISNULL((CASE WHEN VisibleDaySums = 1 THEN 'Department' WHEN VisibleDaySums = 2 THEN 'WorkingArea'  WHEN VisibleDaySums = 3 THEN 'Department WorkingArea'  ELSE 'None' END), '')+ '</CountPresentShifts>
			<VisibleDaysNumber>' + CAST(ISNULL(VisibleDaysNumber, 7) AS VARCHAR(MAX)) +'</VisibleDaysNumber>
			<VisibleAreas>Roster '+ ISNULL( (CASE WHEN VisibleAreas&2=2 THEN ' Header ' ELSE '' END) +(CASE WHEN VisibleAreas&4=4 THEN ' Demand ' ELSE '' END)   +(CASE WHEN VisibleAreas&16=16 THEN ' DayNotes ' ELSE '' END), '')  +'</VisibleAreas>
		</UserDefaultSettings>')
	
	UPDATE Departments SET LayoutSettings = REPLACE(CAST(LayoutSettings AS varchar(MAX)),'</NameFormat>','</NameFormat><FormulaIds>' + val +'</FormulaIds>') 
		FROM Departments INNER JOIN (SELECT [DepartmentId], val =
		STUFF((SELECT (', ' +  CAST(FormulaConfigurationId AS VARCHAR(MAX)))
		FROM FormulaConfigurations_Departments a  WHERE b.DepartmentId = a.DepartmentId 
		FOR XML PATH('' )),1 , 2, '') FROM FormulaConfigurations_Departments b
		GROUP by DepartmentId) AS s ON s.DepartmentId = Departments.DepartmentId 
	WHERE NOT LayoutSettings IS NULL
	
	UPDATE Departments SET LayoutSettings = '<DutyRosterLayotSettings><FormulaIds>' + val + '</FormulaIds><NameFormat>{0:I}</NameFormat></DutyRosterLayotSettings>'
		FROM Departments INNER JOIN (SELECT DepartmentId, val =
		STUFF((SELECT (', ' +  CAST(FormulaConfigurationId AS VARCHAR(MAX)))
		FROM FormulaConfigurations_Departments a  WHERE b.DepartmentId = a.DepartmentId 
		FOR XML PATH('' )), 1, 2, '') FROM FormulaConfigurations_Departments b
		GROUP by DepartmentId) AS s ON s.DepartmentId = Departments.DepartmentId 
	WHERE LayoutSettings IS NULL
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleTypes') AND [name] = 'CollectivePersonId')
BEGIN
	ALTER TABLE RoleTypes ADD CollectivePersonId INT NULL
	ALTER TABLE RoleTypes WITH CHECK ADD  CONSTRAINT FK_RoleTypes_Persons_Collectiv FOREIGN KEY(CollectivePersonId)
		REFERENCES Persons (PersonId)
	ALTER TABLE RoleTypes CHECK CONSTRAINT FK_RoleTypes_Persons_Collectiv
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('TechnicalJobs') AND [name] = 'RoleTypeId')
BEGIN
	UPDATE WorkAreaGroups SET CollectivePersonId = NULL FROM WorkAreaGroups WHERE NOT CollectivePersonId IN (SELECT PersonId FROM Persons)
	SET IDENTITY_INSERT RoleTypes ON
	INSERT INTO RoleTypes
			   (RoleTypeId,
			   [Name]
			   ,LM, UM, LC, UC
			   ,Pos, PresseSort, Leporello
			   ,ShortName
			   ,TemplateName
			   ,Module
			   ,RoleTypeCategory
			   ,PrintMode
			   ,CollectivePersonId
			   ,Settings         )
	  SELECT WorkAreaGroupId + 5000
		  ,CASE WHEN Module = 2 THEN 'entfernen ' ELSE '' END + [Name]
		  ,ISNULL(LM, '19000101'), UM, ISNULL(LC, '19000101'), UC
		  ,Sort + 5000, 0, 0
		  ,CASE WHEN Module = 2 THEN 'x' ELSE '' END + [ShortName] --LEFT([Name], 15) --
		  ,[Name]
		  ,Module
		  ,ISNULL(GroupPos, 0) + CASE WHEN Module = 4 THEN 10 ELSE 0 END
		  ,ScheduleOutput
		  ,CollectivePersonId
		  ,REPLACE(REPLACE(REPLACE(CAST(FontFormat AS VARCHAR(MAX)),'FontFormat', 'Settings'), 'BackgroundColor', 'BackColor'), 'ForegroundColor', 'ForeColor')
	FROM WorkAreaGroups 

	SET IDENTITY_INSERT RoleTypes OFF

	ALTER TABLE TechnicalJobs ALTER COLUMN IntendedDuration SMALLINT NULL

	UPDATE Roles SET RoleTypeId = WorkAreaGroupId + 5000 WHERE Not WorkAreaGroupId IS NULL
	
	ALTER TABLE TechnicalJobs ADD RoleTypeId INT NULL
	EXEC('UPDATE TechnicalJobs SET RoleTypeId = WorkAreaGroupId + 5000 ')
	--SH 2021-08-30 In Testdatenbank war ein Eintrag mit WorkAreaGroupId NULL drin, was hier zu einem Fehler führt.
	--Sollte man den Fall im Script beachten? Ansonsten fliegt man an dieser Stelle hier raus...
	ALTER TABLE TechnicalJobs ALTER COLUMN RoleTypeId INT NOT NULL

	ALTER TABLE TechnicalJobs  WITH CHECK ADD  CONSTRAINT FK_TechnicalJobs_RoleTypes FOREIGN KEY(RoleTypeId)
		REFERENCES RoleTypes (RoleTypeId)
	ALTER TABLE TechnicalJobs CHECK CONSTRAINT FK_TechnicalJobs_RoleTypes

	ALTER TABLE WorkAreaGroupMembers ADD RoleTypeId INT NULL
	EXEC('UPDATE WorkAreaGroupMembers SET RoleTypeId = WorkAreaGroupId + 5000')
	ALTER TABLE WorkAreaGroupMembers ALTER COLUMN RoleTypeId INT NOT NULL

	ALTER TABLE WorkAreaGroupMembers  WITH CHECK ADD  CONSTRAINT FK_WorkAreaGroupMembers_RoleTypes FOREIGN KEY(RoleTypeId)
		REFERENCES RoleTypes (RoleTypeId) ON DELETE CASCADE
	ALTER TABLE WorkAreaGroupMembers CHECK CONSTRAINT FK_WorkAreaGroupMembers_RoleTypes
	
	ALTER TABLE ContractDepartments ADD PrimeryRoleTypeId INT NULL
	EXEC('UPDATE ContractDepartments SET PrimeryRoleTypeId = DefaultWorkAreaGroupId + 5000 WHERE Not DefaultWorkAreaGroupId IS NULL')

	ALTER TABLE ContractDepartments  WITH CHECK ADD  CONSTRAINT FK_ContractDepartments_RoleTypes FOREIGN KEY(PrimeryRoleTypeId)
		REFERENCES RoleTypes (RoleTypeId) ON DELETE SET NULL
	ALTER TABLE ContractDepartments CHECK CONSTRAINT FK_ContractDepartments_RoleTypes

	DROP TABLE PeriodNotes

	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_WorkAreaGroupMembers_WorkAreaGroups') AND type = 'F') ALTER TABLE dbo.WorkAreaGroupMembers DROP CONSTRAINT FK_WorkAreaGroupMembers_WorkAreaGroups
	ALTER TABLE WorkAreaGroupMembers ALTER COLUMN WorkAreaGroupId INT NULL

	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_TechnicalJobs_WorkAreaGroups') AND type = 'F') ALTER TABLE dbo.TechnicalJobs DROP CONSTRAINT FK_TechnicalJobs_WorkAreaGroups
	ALTER TABLE TechnicalJobs ALTER COLUMN WorkAreaGroupId INT NULL

	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_ContractDepartments_WorkAreaGroups_DefaultWorkAreaGroupId') AND type = 'F') ALTER TABLE dbo.ContractDepartments DROP CONSTRAINT FK_ContractDepartments_WorkAreaGroups_DefaultWorkAreaGroupId

	EXEC('UPDATE RoleTypes SET 
		TemplateOwnerGroupId = (SELECT TOP 1 Departments.OwnerGroupId FROM WorkAreaGroupMembers 
																INNER JOIN WorkAreas ON  WorkAreaGroupMembers.WorkAreaId = WorkAreas.WorkAreaId 
																INNER JOIN Departments ON  WorkAreas.DepartmentId = Departments.DepartmentId WHERE WorkAreaGroupMembers.RoleTypeId = RoleTypes.RoleTypeId)
		FROM RoleTypes WHERE EXISTS (SELECT * FROM WorkAreaGroupMembers WHERE WorkAreaGroupMembers.RoleTypeId = RoleTypes.RoleTypeId )')


	ALTER TABLE RoleTypes ADD RoleTypeCategoryId INT NULL
END
GO

ALTER VIEW dbo.AbTechnicalPersonalDemands
AS 
	SELECT Act.ActivityId AS ActivityId, Act.[Date], Job.RoleTypeId, Job.StartOffset, Job.EndOffset, Job.PersonCount AS SollZahl, COUNT(cuwt.ActivityJobId) AS IstZahl, Job.[Name] AS Info
	FROM
		TechnicalJobs AS Job
		INNER JOIN Activities AS Act ON  Act.ActivityId = Job.ActivityId
		INNER JOIN ActivityStatuses AS acts ON Act.ActivityStatusId = acts.ActivityStatusId
		LEFT JOIN CostUnitWorkingTimes AS cuwt ON cuwt.ActivityJobId = Job.TechnicalJobId AND cuwt.ActivityID = Act.ActivityId
	WHERE
		acts.StatusType >= 0
		AND Act.VariantId = 0 
	GROUP BY
		Act.ActivityId, Act.Date, Job.TechnicalJobId, Job.PersonCount, Job.RoleTypeId, Job.[Name], Job.StartOffset, Job.EndOffset
GO

IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name] = 'RoleTypeCategories')
BEGIN		  
	PRINT 'Creating RoleTypeCategories...'
 	CREATE TABLE dbo.RoleTypeCategories (
		RoleTypeCategoryId INT IDENTITY(1, 1) NOT NULL,
		[Name] VARCHAR(50) NOT NULL,
		[Code] VARCHAR(15),
		RoleTypeCategory TINYINT NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_RoleTypeCategories_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_RoleTypeCategories_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_RoleTypeCategoriess PRIMARY KEY NONCLUSTERED (RoleTypeCategoryId) ON [PRIMARY]
    ) ON [PRIMARY]
	
	CREATE UNIQUE INDEX IX_RoleTypeCategories_Name ON RoleTypeCategories ([Name]) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_RoleTypeCategories_Code ON RoleTypeCategories (Code) ON [PRIMARY]

	GRANT SELECT ON RoleTypeCategories TO Public
	GRANT INSERT, UPDATE, DELETE ON RoleTypeCategories TO DispoAdmin

	ALTER TABLE RoleTypes WITH CHECK ADD CONSTRAINT FK_RoleTypes_RoleTypeCategoryId FOREIGN KEY(RoleTypeCategoryId)
	REFERENCES RoleTypeCategories (RoleTypeCategoryId)
	ALTER TABLE RoleTypes CHECK CONSTRAINT FK_RoleTypes_RoleTypeCategoryId	

	SET IDENTITY_INSERT RoleTypeCategories ON 
	INSERT INTO RoleTypeCategories (RoleTypeCategoryId,[Name],Code, RoleTypeCategory ) SELECT DISTINCT RoleTypeCategory, 
				CASE WHEN RoleTypeCategory = 0 THEN 'Solisten/Mitwirkende' 
					WHEN RoleTypeCategory  BETWEEN 1 AND 6  THEN 'Leitungsteam ' + CAST(RoleTypeCategory AS VARCHAR(10))
					WHEN RoleTypeCategory = 100 THEN 'Kollektiv Orchester' 
					WHEN RoleTypeCategory = 110  THEN 'Kollektiv Chor' 
					WHEN RoleTypeCategory = 120 THEN 'Kollektiv Ballett' 
					WHEN RoleTypeCategory = 130 THEN 'Kollektiv Statisterie' 
						ELSE 'Technik '+ CAST(RoleTypeCategory AS VARCHAR(10)) END,
					
					CASE WHEN RoleTypeCategory = 0 THEN 'Soli' 
					WHEN RoleTypeCategory  BETWEEN 1 AND 6  THEN 'Gruppe' + CAST(RoleTypeCategory AS VARCHAR(10))
					WHEN RoleTypeCategory = 100 THEN 'Orchester' 
					WHEN RoleTypeCategory = 110  THEN 'Chor' 
					WHEN RoleTypeCategory = 120 THEN 'Ballett' 
					WHEN RoleTypeCategory = 130 THEN 'Statisterie' ELSE 'Technik '+ CAST(RoleTypeCategory AS VARCHAR(10)) END,

					CASE WHEN RoleTypeCategory  BETWEEN 1 AND 6  THEN 1
					WHEN RoleTypeCategory  BETWEEN 10 AND 99  THEN 10
						 ELSE RoleTypeCategory END
					FROM RoleTypes  
	SET IDENTITY_INSERT RoleTypeCategories OFF

	UPDATE RoleTypes SET RoleTypeCategoryId = RoleTypeCategory

	ALTER TABLE RoleTypes ALTER COLUMN RoleTypeCategoryId INT NOT NULL
	ALTER TABLE RoleTypes ALTER COLUMN RoleTypeCategory SMALLINT NULL
		 
	UPDATE PlanColumnContent SET ContentSettings =  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(CAST(ContentSettings AS varchar(MAX)),'RollenBereich','int'),'Gruppe',''),'Soli','0'),'Orchester','100'),'Chor','110'),'Ballett','120'),'Statisterie','130') FROM PlanColumnContent WHERE CAST(ContentSettings AS varchar(MAX))  LIKE '%RollenBereich%'
END
GO
--#endregion

--#region
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OwnerGroups') AND [name] = 'BasicCastPerSeason')
BEGIN
	ALTER TABLE OwnerGroups ADD BasicCastPerSeason BIT NOT NULL CONSTRAINT DF_OwnerGroups_BasicCastPerSeason DEFAULT 0
	EXEC('UPDATE OwnerGroups SET BasicCastPerSeason = CASE WHEN (SELECT TOP 1 DataValue FROM Settings WHERE Settings.Section = ''BasicCast'' AND Settings.KeyName  = ''Season'') IN (''1'',''2'') THEN 1 ELSE 0 END FROM OwnerGroups WHERE  Modul <> 4')
	ALTER TABLE ContractSalaryRules ALTER COLUMN salaryValue DECIMAL(9, 2) NULL
END
GO

IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'MergeSequentialPeriodFees'))	DROP PROCEDURE dbo.MergeSequentialPeriodFees
GO

CREATE PROCEDURE MergeSequentialPeriodFees
AS
BEGIN

	DECLARE @id INT, @contractId INT,  @accountId INT, @salaryPro SMALLINT, @numberUnpaid INT, @salaryLevelId INT, @salaryValue MONEY, @start DATE, @end DATE, @note VARCHAR(1000)
	DECLARE @oId INT, @oContractId INT, @oAccountId INT, @oSalaryPro SMALLINT, @oNumberUnpaid INT, @oSalaryLevelId INT, @oSalaryValue MONEY, @oEnd DATE, @oNote VARCHAR(1000)
	DECLARE cview_cursor CURSOR FOR 

	SELECT ContractSalaryRuleId, contractId, accountId, salaryPro, numberUnpaid, salaryLevelId, salaryValue, startDate, endDate, note
	FROM ContractSalaryRules WHERE ContractEngagementId IS NULL and ContractId = 387303
	ORDER BY contractId, contractEngagementId, accountId, salaryPro, numberUnpaid, salaryLevelId, StartDate
	
	OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @id, @contractId,  @accountId, @salaryPro, @numberUnpaid, @salaryLevelId, @salaryValue, @start, @end, @note
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
	IF (@oContractId = @contractId  AND @oAccountId = @accountId AND ISNULL(@oSalaryPro,0) = ISNULL(@salaryPro,0) AND @oNumberUnpaid = @numberUnpaid  AND  ISNULL(@oSalaryLevelId,0) = ISNULL(@salaryLevelId,'')  AND ISNULL(@oNote,'') = ISNULL(@note,'') AND  ISNULL(@oSalaryValue,0) = ISNULL(@salaryValue,0) AND DATEADD(d, 1, @oEnd) = @start)
			BEGIN
				UPDATE ContractSalaryRules SET EndDate = @end WHERE ContractSalaryRuleId = @oId
				Print 'Delete'
				DELETE FROM ContractSalaryRules WHERE  ContractSalaryRuleId = @id
			END
		ELSE
			BEGIN
				SET @oId = @id
				SET @oContractId = @contractId 
				SET @oAccountId = @accountId
				SET @oSalaryPro = @salaryPro
				SET @oNumberUnpaid = @numberUnpaid
				SET @oSalaryLevelId = @salaryLevelId
				SET @oSalaryValue = @salaryValue
				SET @oNote = @note
			END
		SET @oEnd = @end
		FETCH NEXT FROM cview_cursor 
		INTO @id, @contractId,  @accountId, @salaryPro, @numberUnpaid, @salaryLevelId, @salaryValue, @start, @end, @note
	END 
	CLOSE cview_cursor 
	DEALLOCATE cview_cursor 
END
GO

IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'MergeSequentialPeriodBasicCasts'))DROP PROCEDURE dbo.MergeSequentialPeriodBasicCasts
GO

CREATE PROCEDURE MergeSequentialPeriodBasicCasts
	@ownerGroupId varchar(100)
AS
BEGIN
	DECLARE @id INT, @roleId INT, @personId INT, @groupPosition SMALLINT, @understudyPosition TINYINT, @start DATE, @end DATE, @note VARCHAR(256)
	DECLARE @oId INT, @oRoleId INT, @oPersonId INT, @oGroupPosition SMALLINT, @oUnderstudyPosition TINYINT, @oEnd DATE, @oNote VARCHAR(256)
	DECLARE cview_cursor CURSOR FOR 

	SELECT BasiccastId, Basiccast.RoleId, PersonId, GroupPosition, UnderstudyPosition, StartDate, EndDate, Basiccast.Note
	FROM Basiccast 
		INNER JOIN Roles ON Basiccast.RoleId = Roles.RoleId
	WHERE OwnerGroupId = @ownerGroupId
	ORDER BY Basiccast.RoleId, PersonId, GroupPosition, UnderstudyPosition, StartDate
	
	OPEN cview_cursor 
	FETCH NEXT FROM cview_cursor 
	INTO @id, @roleId, @personId, @groupPosition, @understudyPosition, @start, @end, @note
	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF (@oRoleId = @roleId AND @oGroupPosition = @groupPosition AND @oUnderstudyPosition = @understudyPosition AND @oPersonId = @personId AND ISNULL(@oNote,'') = ISNULL(@note,'')  AND DATEADD(d, 1, @oEnd) = @start)
			BEGIN
				UPDATE Basiccast SET EndDate = @end WHERE BasiccastId = @oId
				DELETE FROM Basiccast WHERE  BasiccastId = @id
			END
		ELSE
			BEGIN
				SET @oRoleId = @roleId 
				SET @oPersonId = @personId
				SET @oGroupPosition = @groupPosition
				SET @oUnderstudyPosition = @understudyPosition
				SET @oId = @id
				SET @oNote = @note
			END
		SET @oEnd = @end
		FETCH NEXT FROM cview_cursor 
		INTO @id, @roleId, @personId, @groupPosition, @understudyPosition, @start, @end, @note
	END 
	CLOSE cview_cursor 
	DEALLOCATE cview_cursor 
		
	UPDATE BasicCast SET StartDate = NULL FROM BasicCast AS Bc INNER JOIN Roles ON Bc.RoleId = Roles.RoleId INNER JOIN (SELECT Basiccast.RoleId, GroupPosition, UnderstudyPosition, MIN(ISNULL(StartDate,'19000101')) AS m 
		FROM Basiccast INNER JOIN Roles ON Basiccast.RoleId = Roles.RoleId  WHERE OwnerGroupId = @ownerGroupId GROUP BY Basiccast.RoleId, GroupPosition, UnderstudyPosition) AS s
			ON Bc.RoleId = s.RoleId AND Bc.UnderstudyPosition = s.UnderstudyPosition AND Bc.GroupPosition = s.GroupPosition AND ISNULL(bc.StartDate, '19000101') = s.m
		WHERE (SELECT MIN(Seasons.StartDate) FROM ProductionInSeasons INNER JOIN Seasons ON ProductionInSeasons.SeasonId=Seasons.SeasonId WHERE ProductionInSeasons.ProductionId = Roles.ProductionId) = bc.StartDate

	UPDATE BasicCast SET EndDate = NULL  FROM BasicCast AS Bc INNER JOIN Roles ON Bc.RoleId = Roles.RoleId INNER JOIN  (SELECT Basiccast.RoleId, GroupPosition, UnderstudyPosition, MAX(ISNULL(EndDate,'30000101')) AS m
		FROM Basiccast INNER JOIN Roles ON Basiccast.RoleId = Roles.RoleId  WHERE OwnerGroupId = @ownerGroupId GROUP BY Basiccast.RoleId, GroupPosition, UnderstudyPosition) AS s
			ON Bc.RoleId = s.RoleId AND Bc.UnderstudyPosition = s.UnderstudyPosition AND Bc.GroupPosition = s.GroupPosition AND ISNULL(bc.EndDate, '30000101') = s.m 
		WHERE (SELECT MAX(Seasons.EndDate) FROM ProductionInSeasons INNER JOIN Seasons ON ProductionInSeasons.SeasonId=Seasons.SeasonId WHERE ProductionInSeasons.ProductionId = Roles.ProductionId)  = bc.EndDate

END
GO

--#endregion

--#region 2021-08-11
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobStepCategories') AND [name] = 'IsPreparationOrSceneStep')
	ALTER TABLE RoleJobStepCategories ADD IsPreparationOrSceneStep TINYINT NOT NULL CONSTRAINT DF_OwnerGroups_IsPreparationOrSceneStep DEFAULT 0

GO
--#endregion

--#region SH 2021-07-01 Sort Spalten für Resource*Attachments und RoleJobStepAttachments

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceAttachments') AND [name] = 'Sort')
BEGIN
	PRINT('Adding ResourceAttachments.Sort ...')
	ALTER TABLE dbo.ResourceAttachments ADD Sort SMALLINT NOT NULL CONSTRAINT DF_ResourceAttachments_Sort DEFAULT 0

	PRINT('Adding ResourceObjectAttachments.Sort ...')
	ALTER TABLE dbo.ResourceObjectAttachments ADD Sort SMALLINT NOT NULL CONSTRAINT DF_ResourceObjectAttachments_Sort DEFAULT 0

	PRINT('Adding ResourceContainerAttachments.Sort ...')
	ALTER TABLE dbo.ResourceContainerAttachments ADD Sort SMALLINT NOT NULL CONSTRAINT DF_ResourceContainerAttachments_Sort DEFAULT 0

	PRINT('Adding RoleJobStepAttachments.Sort ...')
	ALTER TABLE dbo.RoleJobStepAttachments ADD Sort SMALLINT NOT NULL CONSTRAINT DF_RoleJobStepAttachments_Sort DEFAULT 0
END
GO

--#endregion SH 2021-07-01 Sort Spalten für Resource*Attachments und RoleJobStepAttachments

--#region SH 2021-07-06 ResourceAttachments.ResourcAttachmentId richtig bennen

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceAttachments') AND [name] = 'ResourceAttachmentId')
BEGIN
	PRINT ('Renaming ResourceAttachments.ResourcAttachmentId to ResourceAttachmentId...')
	EXECUTE sp_rename N'dbo.ResourceAttachments.ResourcAttachmentId', N'ResourceAttachmentId', 'COLUMN' 
END
GO

--#endregion SH 2021-07-06 ResourceAttachments.ResourcAttachmentId richtig bennen

--#region 

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceCreationPartList') AND [name] = 'OrderId')
BEGIN
	ALTER TABLE ResourceCreationPartList ADD OrderId INT NULL
	ALTER TABLE ResourceCreationPartList WITH CHECK ADD CONSTRAINT FK_ResourceCreationPartList_Orders FOREIGN KEY(OrderId)
	REFERENCES Orders (OrderId) 
	ALTER TABLE ResourceCreationPartList CHECK CONSTRAINT FK_ResourceCreationPartList_Orders
END

GO
--#endregion

--#region
ALTER PROCEDURE [dbo].[GetActivitiesInternal]
	@start DATE,
	@end DATE,
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowActivitiesWithoutRights BIT, --AND Cast
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATE
	DECLARE @permissionPeriodEnd DATE

	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId 

	if (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  ActivityIds erstellen ***
	IF (@include <> 0)  CREATE TABLE #ActivitiesNP (ActivityId INT NOT NULL, NoPermission BIT NOT NULL)

	-- *** Berechtigungen des Users für Aktivitäten (2) und Besetzungen (4) in Temp Tabelle ***
	CREATE TABLE #Permissions (PermissionId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT Permissions.OwnerGroupId, Permissions.PermissionArea, OptionsFlag  FROM Permissions WHERE UserId = @userId AND PermissionArea IN (2,4)

	-- *** Spalten für ausgabe, wenn auch Daten ohne Berechtigungen geladen werden die ProduktionsId als 0 und keine Bemerkungen zurückgeben ***
	
	DECLARE @secretfields VARCHAR(MAX)
	DECLARE @fields VARCHAR(MAX)
	SET @fields  =', Activities.ActivityId, Activities.LocationId,
					Activities.Date, Activities.StartTime, Activities.EndTime, Activities.PrintEndTime, Activities.PrintStartTime,  
					Activities.ActivityStatusId, Activities.LinkedActivityId, Activities.IsSecret, Activities.CreateCountDownId, 
					Activities.IsTimeSpan, Activities.IsExtraPayLiable, Activities.VariantId, 
					Activities.LM, Activities.UM, Activities.LC, Activities.UC'

	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten ActivityIds in Temp
	-- *** Die "@secretfields" müssen dann "@ShowActivitiesWithoutRights" abfragen
	if (@include <> 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #ActivitiesNP SELECT  Activities.ActivityId, CASE WHEN  Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1)  THEN 1	ELSE 0 END'

			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN NoPermission = 1 THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
		END
	ELSE
		BEGIN
			IF (@ShowActivitiesWithoutRights = 1)
				
				SET @secretfields  =   'CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
			ELSE 
				SET @secretfields  =   'Activities.ProductionId,
										Activities.ActivityTypeId,
										Activities.ArtisticNote,
										Activities.TechnicalNote'

			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END

	-- ***	Immer auf Produktionen unf Berechtigungen ***
		SET @SQLQuery =  @SQLQuery + '	 FROM  Activities 
										INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '

		IF (@ShowActivitiesWithoutRights = 1) 
			SET @SQLQuery =  @SQLQuery + 'LEFT JOIN #Permissions AS UG ON UG.PermissionId = P.OwnerGroupId AND ug.PermissionArea = 2'
		ELSE 
			SET @SQLQuery =  @SQLQuery + 'INNER JOIN #Permissions AS UG ON UG.PermissionId = P.OwnerGroupId AND ug.PermissionArea = 2'

	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ActivityDetails ON Activities.ActivityId = ActivityDetails.ActivityId '

		IF (@joins&4 = 4 OR (@include = 0 AND CHARINDEX('Locations.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '

		IF (@joins&8 = 8 OR (@include = 0 AND CHARINDEX('ActivityTypes.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '

		IF (@joins&16 = 16)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ProductionDetails ON Activities.ProductionId = ProductionDetails.ProductionId '

		IF (@joins&32 = 32)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN OwnerGroups ON p.OwnerGroupId = OwnerGroups.OwnerGroupId '
			
		SET @SQLQuery = @SQLQuery + ' WHERE Activities.Date BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''
		
			--Wenn in allen Besitzergruppe gesperrte Aktivitäten gelesen werden können ist keine Prüfung auf IsSecret erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE PermissionArea = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			IF (@ShowActivitiesWithoutRights = 0)
					SET @SQLQuery = @SQLQuery  + ' AND (Activities.IsSecret = 0 OR ug.OptionsFlag&1 = 1)'
		END

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + @order 

		EXECUTE sp_Executesql @SQLQuery 
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT '+ @secretfields+ @fields +' FROM Activities AS Activities 
																	INNER JOIN  #ActivitiesNP ON Activities.ActivityId = #ActivitiesNP.ActivityId'

			If (@order IS NOT NULL)
			BEGIN
				--Prüfen ob Tabellen für Sortierungen gejoint werden müßen, ggf. auch bei Direktabfragen "@include =0" prüfen

				IF (CHARINDEX('Locations.', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '
				END
				IF (CHARINDEX('Title', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '
				END
				IF (CHARINDEX('ActivityTypes', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '
				END
				SET @SQLQuery = @SQLQuery + @order 

			END
			EXECUTE sp_Executesql  @SQLQuery
		END

-- *** Wenn Aktivitäten ohne Berechtigungen mitgeladen wurden für diese keine Abhängigen Daten laden
	IF (@ShowActivitiesWithoutRights = 1 AND @include <> 0)
		DELETE FROM #ActivitiesNP WHERE NoPermission = 1

	IF (@include&1 = 1)
		SELECT NULL AS [#1], ActivityDetails.*
		FROM ActivityDetails 
			INNER JOIN #ActivitiesNP On ActivityDetails.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&2 = 2)
		SELECT NULL AS [#2], ActivityProductionFieldData.*
		FROM ActivityProductionFieldData 
			INNER JOIN #ActivitiesNP ON ActivityProductionFieldData.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&4 = 4)
		SELECT NULL AS [#4], ActivitySubscriptions.*, Subscriptions.SubscriptionTypeId
		FROM ActivitySubscriptions 
			INNER JOIN Subscriptions ON ActivitySubscriptions.SubscriptionId = Subscriptions.SubscriptionId
			INNER JOIN #ActivitiesNP ON ActivitySubscriptions.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&8 = 8)
		SELECT NULL AS [#8], B.CastId, B.RoleId, CASE WHEN B.IsSecret = 1 AND ug.OptionsFlag&1 <> 1 THEN -1 ELSE b.PersonId END AS PersonId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, B.CastStatusId,
					B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId
		FROM Cast AS B 
			INNER JOIN #ActivitiesNP ON B.ActivityId = #ActivitiesNP.ActivityId
			INNER JOIN Roles ON Roles.RoleId = B.RoleId
			INNER JOIN #Permissions AS UG ON UG.PermissionId  = Roles.OwnerGroupId AND  ug.PermissionArea = 4 AND (@ShowActivitiesWithoutRights = 1 OR B.IsSecret = 0 OR ug.OptionsFlag&1 = 1)	

	IF (@include&16 = 16) 
	BEGIN
		DECLARE @changeSince DATETIME
		SET @changeSince = GETDATE() - 21 
		SELECT NULL AS [#16],ax.*
		FROM  ActivityHistory AS ax
			INNER JOIN #ActivitiesNP ON ax.ActivityId = #ActivitiesNP.ActivityId
			LEFT JOIN (SELECT xhid FROM HistoryConfirmations WHERE TableName = 'Activities' AND uc = @userId) AS d ON ax.xhID = d.xhid 
		WHERE d.xhId IS NULL AND ax.uc <> @userId AND ax.lm >= @changeSince AND ax.xhRelevant = 1 
		ORDER BY ax.lc DESC
	END

	IF (@include&32 = 32) 
		SELECT NULL AS [#32], ActivityDepartmentData.*
		FROM ActivityDepartmentData 
			INNER JOIN #ActivitiesNP ON ActivityDepartmentData.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&128 = 128) 
		SELECT NULL AS [#128], ActivityHistory.*
		FROM ActivityHistory 
			INNER JOIN #ActivitiesNP ON ActivityHistory.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&256 = 256) 
		SELECT NULL AS [#256], ActivityScenes.*
		FROM ActivityScenes 
			INNER JOIN #ActivitiesNP ON ActivityScenes.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&512 = 512) 
		SELECT NULL AS [#512], TechnicalJobs.*
		FROM TechnicalJobs 
			INNER JOIN #ActivitiesNP ON TechnicalJobs.ActivityId = #ActivitiesNP.ActivityId

		IF (@include <> 0) DROP TABLE #ActivitiesNP

END
GO

ALTER PROCEDURE [dbo].[GetActivities]
	@start DATETIME,
	@end DATETIME,
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowActivitiesWithoutRights BIT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @userId INT
	SELECT @userId = UserId FROM Users WHERE UserName  = CURRENT_USER
	EXECUTE GetActivitiesInternal @start, @end, @condition, @order, @joins, @include, @ShowActivitiesWithoutRights, @userId
END

GO

--#endregion

--#region SH 2021-08-12 Rechte für DataService erteilen
GRANT SELECT ON RoleJobSteps TO DataService
GRANT SELECT ON ResourceAttachments TO DataService
GRANT SELECT ON ResourceContainerAttachments TO DataService
GO
--#endregion (SH 2021-08-12 Rechte für DataService erteilen)

--#region
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleTypes') AND [name] = 'RoleTypeJob')
BEGIN
	PRINT('Adding RoleTypes.RoleTypeJob ...')
	ALTER TABLE RoleTypes ADD RoleTypeJob SMALLINT NULL 
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 1 WHERE Name IN (''Regie'', ''Inszenierung'',''Mise en scène'',''Mise en scène / Regie'')')
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 2 WHERE Name IN (''Musikalische Leitung'', ''ML'', ''Dirigat'', ''Dirigent'')')
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 4 WHERE Name IN (''Bühne'', ''Bühnenbild'',''Décors'',''Décors / Decor'')')
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 8 WHERE Name IN (''Kostüme'', ''Kostümbild'', ''Costumes'',''Costumes / Kostuums'',''Costume Design'')')
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 12 WHERE Name IN (''Ausstattung'', ''Bühne und Kostüme'',''Bühnenbild und Kostüme'',''Décors et costumes'',''Set Design'')')
	EXEC('UPDATE RoleTypes SET RoleTypeJob = 16 WHERE Name IN (''Dramaturgie'', ''Dramaturgie / Dramaturgie'', ''Dramaturgy'')')
END
GO
--#endregion

--#region
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobSteps') AND [name] = 'ResourceContainerId')
BEGIN
	PRINT('Adding RoleJobSteps.ResourceContainerId ...')
	ALTER TABLE RoleJobSteps ADD ResourceContainerId INT NULL 

	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_ResourceContainer FOREIGN KEY(ResourceContainerId)
	REFERENCES ResourceContainer (ResourceContainerId)
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_ResourceContainer

	ALTER TABLE Orders DROP CONSTRAINT DF_Orders_OrderType
	ALTER TABLE Orders ALTER COLUMN OrderType TINYINT
	ALTER TABLE Orders ADD CONSTRAINT DF_Orders_OrderType DEFAULT 0 FOR OrderType

	ALTER TABLE Orders DROP CONSTRAINT DF_Orders_CorrectionStatus
	ALTER TABLE Orders ALTER COLUMN CorrectionStatus TINYINT
	ALTER TABLE Orders ADD CONSTRAINT DF_Orders_CorrectionStatus DEFAULT 0 FOR CorrectionStatus

	ALTER TABLE Orders DROP CONSTRAINT DF_Orders_IsCanceled
	ALTER TABLE Orders ALTER COLUMN IsCanceled TINYINT
	ALTER TABLE Orders ADD CONSTRAINT DF_Orders_IsCanceled DEFAULT 0 FOR IsCanceled

	UPDATE Orders SET AccountancyPrintCount= 255 WHERE AccountancyPrintCount > 255
	ALTER TABLE Orders DROP CONSTRAINT DF_Orders_AccountancyPrintCount
	ALTER TABLE Orders ALTER COLUMN AccountancyPrintCount TINYINT
	ALTER TABLE Orders ADD CONSTRAINT DF_Orders_AccountancyPrintCount DEFAULT 0 FOR AccountancyPrintCount
	
	ALTER TABLE OrderPos ALTER COLUMN [Description] VARCHAR(1000) NULL
	ALTER TABLE Orders ALTER COLUMN InternalNote VARCHAR(1000) NULL
END
GO

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Orders') AND [name] = 'OwnerGroupId')
BEGIN
	PRINT('Delete Orders.OwnerGroupId ...')
	IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'Orders') AND o.Name = 'IX_Orders_OwnerGroupId') DROP INDEX IX_Orders_OwnerGroupId ON Orders
	IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'FK_Orders_OwnerGroups') AND type = 'F') ALTER TABLE Orders DROP CONSTRAINT FK_Orders_OwnerGroups
	ALTER TABLE Orders DROP COLUMN OwnerGroupId 

END
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'FK_Orders_CostTypes_SupplierId') AND type = 'F') ALTER TABLE Orders DROP CONSTRAINT FK_Orders_CostTypes_SupplierId

IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OrderPos') AND [name] = 'PositionType')
BEGIN
		PRINT('OrderPos.PositionType')
		ALTER TABLE OrderPos DROP CONSTRAINT DF_OrderPos_PositionType
		ALTER TABLE OrderPos ALTER COLUMN PositionType TINYINT NOT NULL
		ALTER TABLE OrderPos ADD CONSTRAINT DF_OrderPos_PositionType DEFAULT 0 FOR PositionType
	END 
ELSE
	BEGIN
		PRINT('OrderPos.PositionType')
		ALTER TABLE OrderPos ADD PositionType TINYINT NOT NULL CONSTRAINT DF_OrderPos_PositionType DEFAULT 0
	END

IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'OrderPos') AND o.Name = 'IX_OrderPos_OrderId_Sort')
BEGIN
	UPDATE  OrderPos SET Sort = 32000 WHERE Sort > 32000
	UPDATE  OrderPos SET Sort = 0 WHERE Sort < 0
	ALTER TABLE OrderPos ALTER COLUMN Sort SMALLINT NOT NULL
	PRINT('OrderPos drop PK_OrderPos')
	ALTER TABLE dbo.OrderPos DROP CONSTRAINT PK_OrderPos
	PRINT('OrderPos create IX_OrderPos_OrderId_Sort')
	CREATE CLUSTERED INDEX IX_OrderPos_OrderId_Sort ON OrderPos (OrderId, Sort) ON [PRIMARY]
	PRINT('OrderPos create PK_OrderPos')
	ALTER TABLE dbo.OrderPos ADD CONSTRAINT PK_OrderPos PRIMARY KEY NONCLUSTERED (OrderPosId) ON [PRIMARY]
	CREATE NONCLUSTERED INDEX IX_Orders_OrderDate ON Orders (OrderDate) ON [PRIMARY]
END
GO


--#endregion

--#region DH - 210902 Aufgabenbereiche für Orchester
IF EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'WorkAreaGroupMembers') AND o.Name = 'ABGruppe_AB')
	DROP INDEX [ABGruppe_AB] ON [dbo].[WorkAreaGroupMembers]
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'WorkAreaGroupMembers') AND o.Name = 'IX_WorkAreaGroupMembers_WorkArea_RoleType')
BEGIN

	CREATE UNIQUE NONCLUSTERED INDEX [IX_WorkAreaGroupMembers_WorkArea_RoleType] ON [dbo].[WorkAreaGroupMembers]
	(	[WorkAreaId] ASC,	[RoletypeId] ASC)

	INSERT INTO WorkAreaGroupMembers (WorkAreaId,LM,lc,um,uc,RoleTypeId)
		SELECT w.WorkAreaId, GETDATE(), GETDATE(), NULL, NULL, rq.RoleTypeId 
		FROM WorkAreas w 
		INNER JOIN (
			SELECT DISTINCT rt.Name, roletypeid,QualificationCategoryId 
			FROM RoleTypes RT INNER JOIN Qualification qc ON rt.QualificationId = qc.QualificationId) AS rq 
		ON rq.QualificationCategoryId = w.QualificationCategoryId 
		WHERE NOT EXISTS(SELECT * FROM WorkAreaGroupMembers r2 WHERE r2.WorkAreaId = w.WorkAreaId AND r2.RoleTypeId = rq.RoleTypeId)
END
GO
--#endregion DH - 210902 Aufgabenbereiche für Orchester
--#region
IF NOT EXISTS ( SELECT * FROM SYS.sysobjects  WHERE id = OBJECT_ID(N'CK_Cast_GroupPosition') )
BEGIN
	UPDATE [Cast] SET GroupPosition = 1 WHERE GroupPosition < 1
	PRINT('Cast add CK_Cast_GroupPosition')
	ALTER TABLE [Cast] ADD CONSTRAINT CK_Cast_GroupPosition CHECK (GroupPosition > 0)
END
GO
IF NOT EXISTS ( SELECT * FROM SYS.sysobjects  WHERE id = OBJECT_ID(N'CK_BasicCast_GroupPosition') )
BEGIN
	--"Doppelte" BasicCasts entfernen
	DELETE FROM BasicCast WHERE BasicCastId IN 
				(
				SELECT b1.BasicCastId 
				FROM BasicCast AS b1 
					INNER JOIN BasicCast AS b2
					ON  b1.RoleId = b2.RoleId 
					AND b1.PersonId = b2.PersonId 
					AND ISNULL(b1.StartDate, '19000101') = ISNULL(b2.StartDate, '19000101') 
					AND b2.GroupPosition  = 1
					AND b1.UnderstudyPosition = b2.UnderstudyPosition
				WHERE b1.GroupPosition <= 0
				)

	UPDATE BasicCast SET GroupPosition = 1 WHERE GroupPosition < 1

	PRINT('BasicCast add CK_BasicCast_GroupPosition')
	ALTER TABLE BasicCast ADD CONSTRAINT CK_BasicCast_GroupPosition CHECK (GroupPosition > 0)
END
GO
IF NOT EXISTS ( SELECT * FROM SYS.sysobjects  WHERE id = OBJECT_ID(N'CK_RolePositionInfos_GroupPosition') )
BEGIN
	UPDATE RolePositionInfos SET GroupPosition = 1 WHERE GroupPosition < 1
	PRINT('BasicCast add CK_RolePositionInfos_GroupPosition')
	ALTER TABLE RolePositionInfos ADD CONSTRAINT CK_RolePositionInfos_GroupPosition CHECK (GroupPosition > 0)
END
GO
--#endregion
--#region
DropColumn 'PlanLayouts', 'FarbeNach'
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'FK_PlanLayouts_OwnerGroups') AND type = 'F')
BEGIN
	UPDATE PlanLayouts SET OwnerGroupId = 1 WHERE OwnerGroupId NOT IN (SELECT OwnerGroupId FROM OwnerGroups )
	PRINT('FK_PlanLayouts_OwnerGroups')
	ALTER TABLE PlanLayouts WITH CHECK ADD CONSTRAINT FK_PlanLayouts_OwnerGroups FOREIGN KEY(OwnerGroupId)
	REFERENCES OwnerGroups (OwnerGroupId)
	ALTER TABLE PlanLayouts CHECK CONSTRAINT FK_PlanLayouts_OwnerGroups
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'FK_PlanLayouts_Templatess') AND type = 'F')
BEGIN
	UPDATE PlanLayouts SET TemplateId = NULL WHERE NOT TemplateId IS NULL AND TemplateId NOT IN (SELECT TemplateId FROM Templates )
	PRINT('FK_PlanLayouts_Templatess')
	ALTER TABLE PlanLayouts WITH CHECK ADD CONSTRAINT FK_PlanLayouts_Templatess FOREIGN KEY(TemplateId)
	REFERENCES Templates (TemplateId)
	ALTER TABLE PlanLayouts CHECK CONSTRAINT FK_PlanLayouts_Templatess
END
GO
ALTER PROCEDURE [dbo].[DeleteGroup] 
	@Id INT
AS
BEGIN
	SET NOCOUNT ON

	CREATE TABLE #Msg(cnt int, tbl varchar(100))

	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contacts'		FROM Persons WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Productions'	FROM Productions WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Contracts'	FROM Contracts WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Roles'		FROM Roles	WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Departments'	FROM Departments WHERE  OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Tours'		FROM Tours WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Exports'		FROM ExportProfiles WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ResourceContainer' FROM ResourceContainer  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'PlanLayouts' FROM PlanLayouts  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'AuditionTypes' FROM AuditionTypes  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'CheckListItem' FROM CheckListItem  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ExportProfiles' FROM ExportProfiles  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'PersonAdditionalDataTypes' FROM PersonAdditionalDataTypes  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ProductionTemplates' FROM ProductionTemplates  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'ResourceContainer' FROM ResourceContainer  WHERE OwnerGroupId = @id
	INSERT INTO #Msg (cnt, tbl) SELECT COUNT(*), 'Travels' FROM Travels  WHERE OwnerGroupId = @id

	IF NOT EXISTS (SELECT * FROM  #Msg WHERE cnt > 0) 
		BEGIN
			UPDATE RoleTypes SET TemplateOwnerGroupId = NULL WHERE TemplateOwnerGroupId = @id
			DELETE FROM Permissions WHERE OwnerGroupId = @id
			DELETE FROM Permissions WHERE OwnerGroupId = @id
			DELETE FROM OwnerGroupSettings WHERE OwnerGroupId = @id
			DELETE FROM CostCenter_OwnerGroup WHERE OwnerGroupId = @id
			DELETE FROM ActivityTypeGroups WHERE OwnerGroupId = @id
			DELETE FROM OwnerGroups WHERE OwnerGroupId = @id
			DELETE FROM PersonMemo WHERE OwnerGroupId = @id
			DELETE FROM SeasonOwnerGroupSettings WHERE OwnerGroupId = @id
		END
	ELSE 
		BEGIN 
			SELECT * FROM #Msg  WHERE cnt > 0
		END
END
GO
--#endregion

--#region 2021-09-09  /Index für Besitzer und Abteilungsnamen 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OwnerGroups') AND [name] = 'Description')
BEGIN
	PRINT('OwnerGroups Name')
	UPDATE OwnerGroups SET [Name] = CAST(OwnerGroupId AS VARCHAR(10)) FROM OwnerGroups WHERE [Name] IS NULL
	UPDATE OwnerGroups SET Sort = 0 FROM OwnerGroups WHERE Sort IS NULL
	UPDATE OwnerGroups SET [Name] = OwnerGroups.[Name] +  ' ' + CAST(row# AS varchar(10))
		FROM OwnerGroups
			INNER JOIN (SELECT ROW_NUMBER() OVER(PARTITION BY [Name] ORDER BY [Name] ASC) 
							AS Row#, OwnerGroupId 
						FROM [OwnerGroups] 
						WHERE [Name] IN (SELECT [Name] FROM OwnerGroups GROUP BY [Name] HAVING COUNT (*) > 1)) AS Sub ON OwnerGroups.OwnerGroupId  = Sub.OwnerGroupId 

	ALTER TABLE OwnerGroups ALTER COLUMN [Name] VARCHAR(25) NOT NULL
	ALTER TABLE OwnerGroups ALTER COLUMN Sort SMALLINT NOT NULL
	ALTER TABLE OwnerGroups ADD CONSTRAINT DF_OwnerGroups_Sort DEFAULT 0 FOR Sort
	CREATE UNIQUE INDEX IX_OwnerGroups_Name ON OwnerGroups ([Name])

	PRINT('Departments Name')
	UPDATE Departments SET [Name] = CAST(DepartmentId AS VARCHAR(10)) FROM Departments WHERE [Name] IS NULL
	UPDATE Departments SET [Name] = Departments.[Name] +  ' ' + CAST(row# AS varchar(10))
		FROM Departments 
			INNER JOIN (SELECT ROW_NUMBER() OVER(PARTITION BY [Name] ORDER BY [Name] ASC) 
							AS Row#, DepartmentId 
						FROM Departments 
						WHERE [Name] IN (SELECT [Name] FROM Departments GROUP BY [Name] HAVING COUNT (*) > 1)) AS Sub ON Departments.DepartmentId  = Sub.DepartmentId 

	ALTER TABLE Departments ALTER COLUMN [Name] VARCHAR(15) NOT NULL
	CREATE UNIQUE INDEX IX_Departments_Name ON OwnerGroups ([Name])

	PRINT('OwnerGroups + [Description]')
	ALTER TABLE OwnerGroups ADD [Description] VARCHAR(1024)
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ResourceTypes') AND [name] = 'Sort')
BEGIN
	PRINT('ResourceTypes Name')
	ALTER TABLE ResourceTypes ADD Sort SMALLINT  NOT NULL CONSTRAINT DF_ResourceTypes_Sort DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name] = 'ResourceContainerAttachmentsCategories')
BEGIN		  
	PRINT 'Creating ResourceContainerAttachmentsCategories...'
 	CREATE TABLE dbo.ResourceContainerAttachmentsCategories (
		ResourceContainerAttachmentsCategoryId INT IDENTITY(1, 1) NOT NULL,
		[Name] VARCHAR(50) NOT NULL,
		[Code] VARCHAR(15),
		Module SMALLINT NOT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceContainerAttachmentsCategories_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ResourceContainerAttachmentsCategories_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_ResourceContainerAttachmentsCategories PRIMARY KEY NONCLUSTERED (ResourceContainerAttachmentsCategoryId) ON [PRIMARY]
    ) ON [PRIMARY]
	
	CREATE UNIQUE INDEX IX_ResourceContainerAttachmentsCategories_Name ON ResourceContainerAttachmentsCategories ([Name]) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_ResourceContainerAttachmentsCategories_Code ON ResourceContainerAttachmentsCategories (Code) ON [PRIMARY]

	GRANT SELECT ON ResourceContainerAttachmentsCategories TO Public
	GRANT INSERT, UPDATE, DELETE ON ResourceContainerAttachmentsCategories TO CostumeAdmin

	ALTER TABLE ResourceContainerAttachments ADD ResourceContainerAttachmentsCategoryId INT NULL 

	ALTER TABLE ResourceContainerAttachments WITH CHECK ADD CONSTRAINT FK_ResourceContainerAttachments_ResourceContainerAttachmentsCategories FOREIGN KEY(ResourceContainerAttachmentsCategoryId)
	REFERENCES ResourceContainerAttachmentsCategories (ResourceContainerAttachmentsCategoryId)

	ALTER TABLE ResourceContainerAttachments CHECK CONSTRAINT FK_ResourceContainerAttachments_ResourceContainerAttachmentsCategories	
	UPDATE OwnerGroups SET Modul = 0 WHERE Modul IS NULL
	ALTER TABLE OwnerGroups ALTER COLUMN Modul SMALLINT NOT NULL

	UPDATE OwnerGroups SET DefaultPerformanceCastStatusId = 0 WHERE DefaultPerformanceCastStatusId NOT IN (SELECT CastStatusId FROM CastStatus)
	ALTER TABLE OwnerGroups WITH CHECK ADD CONSTRAINT FK_OwnerGroups_CastStatus FOREIGN KEY(DefaultPerformanceCastStatusId)
	REFERENCES CastStatus (CastStatusId)

END
GO
--#region bugfix castfeldreihenfolge dh-2021-09-16
ALTER PROCEDURE [dbo].[GetActivitiesInternal]
	@start DATE,
	@end DATE,
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowActivitiesWithoutRights BIT, --AND Cast
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)
	DECLARE @permissionPeriodStart DATE
	DECLARE @permissionPeriodEnd DATE

	-- *** Spielzeitberechtigungen prüfen ***
	SELECT @permissionPeriodStart = MIN(s.StartDate), @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s
			INNER JOIN SeasonPermissions AS us	ON s.SeasonId = us.SeasonId
		WHERE us.UserId = @userId 

	if (@permissionPeriodStart IS NULL)
		BEGIN 
			SELECT @start = '30000101'
			SELECT @end = '30000101'
		END
	ELSE
		BEGIN
			IF (@start < @permissionPeriodStart)	BEGIN SELECT @start = @permissionPeriodStart END
			IF (@end > @permissionPeriodEnd)		BEGIN SELECT @end = @permissionPeriodEnd END
		END

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  ActivityIds erstellen ***
	IF (@include <> 0)  CREATE TABLE #ActivitiesNP (ActivityId INT NOT NULL, NoPermission BIT NOT NULL)

	-- *** Berechtigungen des Users für Aktivitäten (2) und Besetzungen (4) in Temp Tabelle ***
	CREATE TABLE #Permissions (PermissionId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #Permissions SELECT Permissions.OwnerGroupId, Permissions.PermissionArea, OptionsFlag  FROM Permissions WHERE UserId = @userId AND PermissionArea IN (2,4)

	-- *** Spalten für ausgabe, wenn auch Daten ohne Berechtigungen geladen werden die ProduktionsId als 0 und keine Bemerkungen zurückgeben ***
	
	DECLARE @secretfields VARCHAR(MAX)
	DECLARE @fields VARCHAR(MAX)
	SET @fields  =', Activities.ActivityId, Activities.LocationId,
					Activities.Date, Activities.StartTime, Activities.EndTime, Activities.PrintEndTime, Activities.PrintStartTime,  
					Activities.ActivityStatusId, Activities.LinkedActivityId, Activities.IsSecret, Activities.CreateCountDownId, 
					Activities.IsTimeSpan, Activities.IsExtraPayLiable, Activities.VariantId, 
					Activities.LM, Activities.UM, Activities.LC, Activities.UC'

	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten ActivityIds in Temp
	-- *** Die "@secretfields" müssen dann "@ShowActivitiesWithoutRights" abfragen
	if (@include <> 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #ActivitiesNP SELECT  Activities.ActivityId, CASE WHEN  Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1)  THEN 1	ELSE 0 END'

			SET @secretfields  =       'CASE WHEN NoPermission = 1 THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN NoPermission = 1 THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN NoPermission = 1 THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
		END
	ELSE
		BEGIN
			IF (@ShowActivitiesWithoutRights = 1)
				
				SET @secretfields  =   'CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN -100 ELSE Activities.ProductionId		END	AS ProductionId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN 0	 ELSE Activities.ActivityTypeId		END	AS ActivityTypeId,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.ArtisticNote	END AS ArtisticNote,
										CASE WHEN Ug.PermissionId IS NULL OR (Activities.IsSecret = 1 AND ug.OptionsFlag&1 <> 1) THEN NULL ELSE Activities.TechnicalNote END AS TechnicalNote'
			ELSE 
				SET @secretfields  =   'Activities.ProductionId,
										Activities.ActivityTypeId,
										Activities.ArtisticNote,
										Activities.TechnicalNote'

			SET @SQLQuery = 'SELECT ' + @secretfields + @fields
		END

	-- ***	Immer auf Produktionen unf Berechtigungen ***
		SET @SQLQuery =  @SQLQuery + '	 FROM  Activities 
										INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '

		IF (@ShowActivitiesWithoutRights = 1) 
			SET @SQLQuery =  @SQLQuery + 'LEFT JOIN #Permissions AS UG ON UG.PermissionId = P.OwnerGroupId AND ug.PermissionArea = 2'
		ELSE 
			SET @SQLQuery =  @SQLQuery + 'INNER JOIN #Permissions AS UG ON UG.PermissionId = P.OwnerGroupId AND ug.PermissionArea = 2'

	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ActivityDetails ON Activities.ActivityId = ActivityDetails.ActivityId '

		IF (@joins&4 = 4 OR (@include = 0 AND CHARINDEX('Locations.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '

		IF (@joins&8 = 8 OR (@include = 0 AND CHARINDEX('ActivityTypes.', @order) > 0 )) 
			SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '

		IF (@joins&16 = 16)
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN ProductionDetails ON Activities.ProductionId = ProductionDetails.ProductionId '

		IF (@joins&32 = 32)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN OwnerGroups ON p.OwnerGroupId = OwnerGroups.OwnerGroupId '
			
		SET @SQLQuery = @SQLQuery + ' WHERE Activities.Date BETWEEN ''' + CAST(@start AS VARCHAR(MAX)) + '''  AND ''' + CAST(@end AS VARCHAR(MAX)) + ''''
		
			--Wenn in allen Besitzergruppe gesperrte Aktivitäten gelesen werden können ist keine Prüfung auf IsSecret erforderlich
		IF (EXISTS(SELECT * FROM #Permissions WHERE PermissionArea = 2 AND OptionsFlag&1 <> 1)) 
		BEGIN
			IF (@ShowActivitiesWithoutRights = 0)
					SET @SQLQuery = @SQLQuery  + ' AND (Activities.IsSecret = 0 OR ug.OptionsFlag&1 = 1)'
		END

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + @order 

		EXECUTE sp_Executesql @SQLQuery 
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT '+ @secretfields+ @fields +' FROM Activities AS Activities 
																	INNER JOIN  #ActivitiesNP ON Activities.ActivityId = #ActivitiesNP.ActivityId'

			If (@order IS NOT NULL)
			BEGIN
				--Prüfen ob Tabellen für Sortierungen gejoint werden müßen, ggf. auch bei Direktabfragen "@include =0" prüfen

				IF (CHARINDEX('Locations.', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN Locations ON Activities.LocationId = Locations.LocationId '
				END
				IF (CHARINDEX('Title', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN  Productions AS p ON Activities.ProductionId = p.ProductionId '
				END
				IF (CHARINDEX('ActivityTypes', @order) > 0) BEGIN
					SET @SQLQuery = @SQLQuery + ' INNER JOIN ActivityTypes ON Activities.ActivityTypeId = ActivityTypes.ActivityTypeId '
				END
				SET @SQLQuery = @SQLQuery + @order 

			END
			EXECUTE sp_Executesql  @SQLQuery
		END

-- *** Wenn Aktivitäten ohne Berechtigungen mitgeladen wurden für diese keine Abhängigen Daten laden
	IF (@ShowActivitiesWithoutRights = 1 AND @include <> 0)
		DELETE FROM #ActivitiesNP WHERE NoPermission = 1

	IF (@include&1 = 1)
		SELECT NULL AS [#1], ActivityDetails.*
		FROM ActivityDetails 
			INNER JOIN #ActivitiesNP On ActivityDetails.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&2 = 2)
		SELECT NULL AS [#2], ActivityProductionFieldData.*
		FROM ActivityProductionFieldData 
			INNER JOIN #ActivitiesNP ON ActivityProductionFieldData.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&4 = 4)
		SELECT NULL AS [#4], ActivitySubscriptions.*, Subscriptions.SubscriptionTypeId
		FROM ActivitySubscriptions 
			INNER JOIN Subscriptions ON ActivitySubscriptions.SubscriptionId = Subscriptions.SubscriptionId
			INNER JOIN #ActivitiesNP ON ActivitySubscriptions.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&8 = 8)
		SELECT NULL AS [#8], B.CastId, B.RoleId, CASE WHEN B.IsSecret = 1 AND ug.OptionsFlag&1 <> 1 THEN -1 ELSE b.PersonId END AS PersonId, B.ActivityId, B.StartOffset, B.EndOffset, B.Note, B.PrintMode, B.LM, B.UM, B.LC, B.UC, B.IsSecret, B.GroupPosition, B.CastStatusId,
					B.IsCover, B.IsCanceled, B.Creditable, B.BackColorArgb, B.IsReplacement, B.ContractId
		FROM Cast AS B 
			INNER JOIN #ActivitiesNP ON B.ActivityId = #ActivitiesNP.ActivityId
			INNER JOIN Roles ON Roles.RoleId = B.RoleId
			INNER JOIN #Permissions AS UG ON UG.PermissionId  = Roles.OwnerGroupId AND  ug.PermissionArea = 4 AND (@ShowActivitiesWithoutRights = 1 OR B.IsSecret = 0 OR ug.OptionsFlag&1 = 1)
			Order by roles.Pos

	IF (@include&16 = 16) 
	BEGIN
		DECLARE @changeSince DATETIME
		SET @changeSince = GETDATE() - 21 
		SELECT NULL AS [#16],ax.*
		FROM  ActivityHistory AS ax
			INNER JOIN #ActivitiesNP ON ax.ActivityId = #ActivitiesNP.ActivityId
			LEFT JOIN (SELECT xhid FROM HistoryConfirmations WHERE TableName = 'Activities' AND uc = @userId) AS d ON ax.xhID = d.xhid 
		WHERE d.xhId IS NULL AND ax.uc <> @userId AND ax.lm >= @changeSince AND ax.xhRelevant = 1 
		ORDER BY ax.lc DESC
	END

	IF (@include&32 = 32) 
		SELECT NULL AS [#32], ActivityDepartmentData.*
		FROM ActivityDepartmentData 
			INNER JOIN #ActivitiesNP ON ActivityDepartmentData.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&128 = 128) 
		SELECT NULL AS [#128], ActivityHistory.*
		FROM ActivityHistory 
			INNER JOIN #ActivitiesNP ON ActivityHistory.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&256 = 256) 
		SELECT NULL AS [#256], ActivityScenes.*
		FROM ActivityScenes 
			INNER JOIN #ActivitiesNP ON ActivityScenes.ActivityId = #ActivitiesNP.ActivityId

	IF (@include&512 = 512) 
		SELECT NULL AS [#512], TechnicalJobs.*
		FROM TechnicalJobs 
			INNER JOIN #ActivitiesNP ON TechnicalJobs.ActivityId = #ActivitiesNP.ActivityId

		IF (@include <> 0) DROP TABLE #ActivitiesNP

END
GO
--#endregion bugfix castfeldreihenfolge
--#endregion
--#region
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'MergeBasicCastSeasons')) DROP PROCEDURE MergeBasicCastSeasons
GO
ALTER TABLE Attachments ALTER COLUMN AttachmentType INT NULL
GO
--#endregion
--#region Berechtigung Maske/Kostüm Korrektur
ALTER VIEW [dbo].[AbRolePositionInfos_Update]
	AS
	SELECT      rsi.*
	FROM        RolePositionInfos AS rsi 
	WHERE rsi.RoleId IN (  SELECT RoleId FROM Roles AS R
								INNER JOIN Permissions AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId   
								INNER JOIN Users			 ON Ug.Userid  = Users.Userid 
							WHERE ug.PermissionArea = 4 AND (ug.HasWritePermission = 1 OR UG.OptionsFlag&16=16) AND Users.Username = CURRENT_USER)
	WITH CHECK OPTION
GO
Alter VIEW [dbo].[AbRoleJobSteps_Update]
	AS
	SELECT      rjs.*
	FROM        RoleJobSteps AS rjs 
	WHERE rjs.RoleJobStepId IN (SELECT RoleJobStepId 
								FROM RoleJobSteps AS rjs 
									INNER JOIN RoleJobStepCategories AS rsc ON rjs.RoleJobStepCategoryId = rsc.RoleJobStepCategoryId
							   		INNER JOIN Roles AS r			ON rjs.RoleId = r.RoleId
									INNER JOIN [Permissions]  AS Ug ON r.OwnerGroupId = Ug.OwnerGroupId 
									INNER JOIN  Users				ON Ug.Userid  = Users.Userid 
							   WHERE ug.PermissionArea = 4 
									AND	((rsc.Module = 1024 AND ug.OptionsFlag&4 = 4) OR (rsc.Module = 2048 AND ug.OptionsFlag&16 = 16)) 
									AND Users.Username = CURRENT_USER)
	WITH CHECK OPTION
GO
--#endregion Berechtigung Maske/Kostüm


--#endregion ------- (4.214.x) --------------------------------

--#region ----------- 4.215.x ---------------------------------

-- Neue Features hier eintragen. Bitte mit Regions umschließen und mit Datum und Namen versehen
--#region DH-20211007 Split Kostüm Maske
IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('OwnerGroups') AND [name] = 'ResourceModule')
BEGIN
PRINT 'Adding ResourceModule'
ALTER TABLE Ownergroups ADD ResourceModule SMALLINT NOT NULL CONSTRAINT DF_Ownergroups_ResourceModule DEFAULT 0 ;
END
GO
--#endregion DH-20211007 Split Kostüm Maske

--#region 2021-10-04
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ContractPartTimePeriods') AND [name] = 'BreakRules')
BEGIN
	PRINT 'ContractPartTimePeriods ADD BreakRules'
	ALTER TABLE ContractPartTimePeriods ADD CalculateEntitlementProRata BIT NOT NULL CONSTRAINT DF_ContractPartTimePeriods_CalculateEntitlementProRata DEFAULT 0
	ALTER TABLE ContractPartTimePeriods ADD BreakRules XML NULL
	ALTER TABLE ContractPartTimePeriods ADD UseBreakRules BIT NOT NULL CONSTRAINT DF_ContractPartTimePeriods_UseBreakRules DEFAULT 0
END
GO
--#endregion

--#region 2021-10-06
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('DayNoteCategories') AND [name] = 'DefaultContentFontFormatXML')
BEGIN
	PRINT 'DayNoteCategories RowHigh SMALLINT'
	UPDATE DayNoteCategories SET RowHigh = 255 WHERE RowHigh > 255
	ALTER TABLE DayNoteCategories ALTER COLUMN RowHigh TINYINT NULL

	PRINT 'DayNoteCategories Sort SMALLINT'
	ALTER TABLE DayNoteCategories DROP CONSTRAINT DF_DayNoteCategories_Sort
	UPDATE DayNoteCategories SET Sort = 0 WHERE Sort IS NULL
	UPDATE DayNoteCategories SET Sort = 32000 WHERE Sort > 32000
	ALTER TABLE DayNoteCategories ALTER COLUMN SORT SMALLINT NOT NULL
	ALTER TABLE DayNoteCategories ADD CONSTRAINT DF_DayNoteCategories_Sort DEFAULT 0 FOR Sort

	PRINT 'DayNoteCategories PermissionStatus TINYINT'
	ALTER TABLE DayNoteCategories DROP CONSTRAINT DF_DayNoteCategories_PermissionStatus
	ALTER TABLE DayNoteCategories ALTER COLUMN PermissionStatus TINYINT NOT NULL
	ALTER TABLE DayNoteCategories ADD CONSTRAINT DF_DayNoteCategories_PermissionStatus DEFAULT 0 FOR PermissionStatus

	PRINT 'DayNoteCategories ADD DefaultContentFontFormatXML'
	ALTER TABLE DayNoteCategories ADD DefaultContentFontFormatXML XML NULL

	ALTER TABLE DayNotes ALTER COLUMN Note VARCHAR(1024) NULL
END
GO
--#endregion

--#region 2021-10-06
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('CostUnitWorkingTimes') AND [name] = 'Note')
BEGIN
	PRINT 'CostUnitWorkingTimes ADD Note'
	ALTER TABLE CostUnitWorkingTimes ADD Note VARCHAR(1024) NULL
END
GO

IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 215 OR (Minor = 215 AND Build < 2)))))
BEGIN
	PRINT '[Permissions] '
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|2048 WHERE PermissionArea = 0
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|8192 WHERE PermissionArea = 0

	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|4096 WHERE HasWritePermission = 1 AND PermissionArea = 0
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|16384 WHERE HasWritePermission = 1 AND PermissionArea = 0
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|32768 WHERE HasWritePermission = 1 AND PermissionArea = 0

	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|2048
	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|8192
	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|4096 WHERE HasWritePermission = 1
	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|16384 WHERE HasWritePermission = 1
	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|32768 WHERE HasWritePermission = 1 

	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|2 WHERE HasWritePermission = 1 AND PermissionArea = 10
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|4 WHERE PermissionArea = 10
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|8 WHERE HasWritePermission = 1 AND PermissionArea = 10
END
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersKom') AND type <> 'U') DROP VIEW dbo.ABPersKom
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersonContactData') AND type <> 'U') DROP VIEW dbo.ABPersonContactData
GO

CREATE VIEW dbo.ABPersonContactData
AS
SELECT  
	pk.PersonContactDataId, 
	pk.CommunicationTypeId, 
	pk.PersonId, 
	pk.Sort, 
	pk.IsSecret,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pk.DataValue END AS DataValue,
	CASE WHEN IsSecret = 1 AND SecretPermission=0 THEN '**********' ELSE pk.Note END AS Note,
	pk.ContactPersonConnectionId,
	pk.LM, pk.UM, pk.LC, pk.UC
FROM PersonContactData AS pk INNER JOIN (
	SELECT  pp.PersonId, MAX(CASE WHEN ug.OptionsFlag&pp.OptionsFlag&1 <> 1 THEN 0 ELSE 1 END) AS SecretPermission 
	FROM PersonPermissions AS PP
		INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
		INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE PermissionArea = 0
			AND (ug.OptionsFlag&pp.OptionsFlag&8192=8192 OR ug.OptionsFlag&pp.OptionsFlag&16384=16384)
			AND Username = CURRENT_USER 
		GROUP BY pp.PersonId) AS sub ON pk.PersonId = sub.PersonId
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON ABPersonContactData TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersKom_Update') AND type <> 'U') DROP VIEW dbo.ABPersKom_Update
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersonContactData_Update') AND type <> 'U') DROP VIEW dbo.ABPersonContactData_Update
GO

CREATE VIEW dbo.ABPersonContactData_Update
AS
	SELECT pk.PersonContactDataId, pk.CommunicationTypeId, pk.PersonId, pk.Sort, pk.DataValue, pk.Note, 
		    pk.LM, pk.UM, pk.LC, pk.UC, pk.IsSecret, pk.ContactPersonConnectionId
	FROM PersonContactData  as pk
	WHERE pk.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS PP
			INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
			INNER JOIN Users ON Ug.Userid = Users.Userid 
		WHERE ug.HasWritePermission=1
			AND (IsSecret = 0 OR ug.OptionsFlag&pp.OptionsFlag&1 = 1)
			AND ug.OptionsFlag&pp.OptionsFlag&16384=16384
			AND PermissionArea = 0
			AND pp.HasWritePermission = 1
			AND Username = CURRENT_USER 
	)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON ABPersonContactData_Update TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersAdresse') AND type <> 'U') DROP VIEW dbo.ABPersAdresse
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersonAddress') AND type <> 'U') DROP VIEW dbo.ABPersonAddress
GO

CREATE VIEW dbo.ABPersonAddress
	AS 
		SELECT
			  pa.AddressId, 
			  pa.PersonId, 
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN '**********' ELSE pa.Street END AS Street,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN '*****' ELSE pa.PostCode END AS PostCode,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN '**********' ELSE pa.City END AS City,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN '***' ELSE pa.CountryCode END AS CountryCode,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN NULL ELSE pa.co END AS Co,
			  CASE WHEN pa.IsSecret = 1 AND SecretPermission = 0 THEN NULL ELSE pa.Note END AS Note,
			  pa.Sort, 
			  pa.[Name], 
			  pa.IsSecret, 
			  pa.IsTaxDomicile, 
			  pa.IsHomeAddress,
			  pa.LM, pa.UM, pa.LC, pa.UC
		FROM PersonAddress AS pa
			INNER JOIN (SELECT  pp.PersonId, MAX(CASE WHEN ug.OptionsFlag&pp.OptionsFlag&1 <> 1 THEN 0 ELSE 1 END) AS SecretPermission 
						  FROM PersonPermissions AS PP
								INNER JOIN [Permissions] AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
								INNER JOIN Users ON Ug.Userid = Users.Userid 
						  WHERE  PermissionArea = 0 
							AND (ug.OptionsFlag&pp.OptionsFlag&2048=2048 OR ug.OptionsFlag&pp.OptionsFlag&4096=4096)
						    AND  Username = CURRENT_USER 
						 GROUP BY pp.PersonId) AS sub ON pa.PersonId = sub.PersonId

GO
GRANT SELECT, UPDATE, INSERT, DELETE ON ABPersonAddress TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersAdresse_Update') AND type <> 'U') DROP VIEW dbo.ABPersAdresse_Update
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ABPersonAddress_Update') AND type <> 'U') DROP VIEW dbo.ABPersonAddress_Update
GO

CREATE VIEW dbo.ABPersonAddress_Update
AS
	SELECT Pa.*
	FROM PersonAddress as Pa
	WHERE PersonId IN ( SELECT  pp.PersonId
						FROM PersonPermissions AS PP
							INNER JOIN Permissions AS UG ON pp.OwnerGroupId =  UG.OwnerGroupId 
							INNER JOIN Users ON Ug.Userid = Users.Userid 
						WHERE     ug.HasWritePermission = 1
							  AND (IsSecret = 0 OR ug.OptionsFlag&pp.OptionsFlag&1 = 1)
							  AND PermissionArea = 0
							  AND  ug.OptionsFlag&pp.OptionsFlag&4096=4096
							  AND pp.HasWritePermission = 1
							  AND Username = CURRENT_USER )
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON ABPersonAddress_Update TO PUBLIC
GO

ALTER VIEW dbo.AbToursContracts_Update
AS 
SELECT tc.* FROM  Tours_Contracts AS tc WHERE tc.TourId IN (
	SELECT t.TourId FROM Tours AS t
	INNER JOIN OwnerGroups g ON t.OwnerGroupId = g.OwnerGroupId
	INNER JOIN [Permissions] AS ug ON g.OwnerGroupId = ug.OwnerGroupId AND ug.PermissionArea = 10
	INNER JOIN Users AS up ON ug.Userid = up.Userid 
	WHERE up.Username = CURRENT_USER AND ug.OptionsFlag&2=2
)
WITH CHECK OPTION
GO

ALTER PROCEDURE [dbo].[GetPersonsInternal]
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowPersonsWithoutRights BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  PersonIds erstellen ***
	IF (@include <> 0) 
	BEGIN
	 CREATE TABLE #PersonsNP (PersonId INT NOT NULL)
	End
	-- *** Berechtigungen des Users für Personen (0) in Temp Tabelle ***
	CREATE TABLE #UserGroupPermissions (OwnerGroupId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #UserGroupPermissions SELECT OwnerGroupId, PermissionArea, OptionsFlag FROM Permissions WHERE  UserId = @userId AND PermissionArea IN (0,1,6)
		
	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten PersonIds in Temp
	
	if (@include <> 0 OR @ShowPersonsWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #PersonsNP SELECT Persons.PersonId FROM Persons '
			IF (@ShowPersonsWithoutRights = 0) 
			BEGIN
				SET @SQLQuery =  @SQLQuery + ' INNER JOIN #UserGroupPermissions AS UG ON UG.OwnerGroupId = Persons.OwnerGroupId AND ug.PermissionArea = 0'
			END
		END								
	ELSE		
		BEGIN
			SET @SQLQuery = 'SELECT persons.* FROM Persons  ' 
		END			
	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
		
		IF (@joins&2 = 2) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN PersonDetails ON Persons.PersonId = PersonDetails.PersonId '

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' WHERE ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + ' ORDER BY ' + @order 

		print @sqlquery
		EXECUTE sp_Executesql @SQLQuery 		
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT persons.* 
								FROM Persons INNER JOIN  #PersonsNP ON Persons.PersonId = #PersonsNP.PersonId'
				
			If (@order IS NOT NULL)
			BEGIN
			IF (@joins&1 = 1)
				SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
				SET @SQLQuery = @SQLQuery  + ' ORDER BY ' + @order 
			END
			print @sqlquery
			EXECUTE sp_Executesql  @SQLQuery
		END

	IF(@include<>0)
	BEGIN
		WITH CTE AS(
			SELECT PP.PersonId
					,MIN(p.OwnerGroupId) AS BaseOwner
                    ,MAX(CONVERT(TINYINT, PP.HasWritePermission)) AS Write
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&1) AS ReadSecret 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&2) AS WriteQualifications
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&4) AS ReadPersonDetails
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&8) AS WritePersonDetails 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&16) AS ReadPersonBankData
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&32) AS WritePersonBankData
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&64) AS ReadPersonFeeNotes
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&128) AS WritePersonFeeNotes
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&256) AS WritePersonEmployee
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&512) AS ShowLinkedContacts
					,MAX(P.OptionsFlag&PP.OptionsFlag&2048)+MAX(P.OptionsFlag&PP.OptionsFlag&4096) AS ReadAddressData
					,MAX(P.OptionsFlag&PP.OptionsFlag&8192)+MAX(P.OptionsFlag&PP.OptionsFlag&16384) AS ReadContactData
		
                    FROM PersonPermissions PP  
                           INNER JOIN #UserGroupPermissions P ON PP.OwnerGroupId = P.OwnerGroupId AND P.PermissionArea = 0                            
                    WHERE pp.PersonId IN (SELECT PersonId FROM #PersonsNP)
					GROUP BY pp.PersonId
					
		) SELECT * INTO #includePermissions FROM cte 
	END 

	if (@include&1024 = 1024)   --An den Anfang verschoben um preloading zu optimieren
			SELECT NULL as [#1024],PP.* 
			FROM PersonPermissions PP INNER JOIN #PersonsNP PNP on PNP.PersonId = pp.PersonId

	IF (@include&1 = 1)
			SELECT NULL AS [#1], 
				pk.PersonContactDataId, 
				pk.CommunicationTypeId, 
				pk.PersonId, 
				pk.Sort, 
				pk.IsSecret,
				CASE WHEN IsSecret = 1 AND ReadSecret = 0 THEN '**********' ELSE  pk.DataValue END AS DataValue,
				CASE WHEN IsSecret = 1 AND ReadSecret = 0 THEN '**********' ELSE  pk.Note END AS Note,
				pk.ContactPersonConnectionID,
				pk.LM, pk.UM, pk.LC, pk.UC
			FROM PersonContactData AS pk
				INNER JOIN (
				SELECT pp.PersonId, pp.ReadSecret
				FROM #includePermissions AS PP WHERE PP.ReadContactData > 0 
					) AS sub ON pk.PersonId = sub.PersonId

	IF (@include&2 = 2)
		SELECT NULL AS [#2], PersonAddress.*
		FROM PersonAddress
			INNER JOIN #includePermissions AS PP ON PersonAddress.PersonId = PP.PersonId
		WHERE (PersonAddress.IsSecret = 0 OR ReadSecret > 0) AND PP.ReadAddressData > 0 
					
	IF (@include&4 = 4)
		SELECT NULL AS [#4], PersonDetails.*
		FROM PersonDetails 			
			INNER JOIN #includePermissions ON PersonDetails.PersonId = #includePermissions.PersonId WHERE ReadPersonDetails > 0 OR WRITEPERSONDETAILS>0
		
	IF (@include&8 = 8)
		SELECT NULL AS [#8],PersonEmployee.*
		FROM PersonEmployee
			INNER JOIN #includePermissions ON PersonEmployee.PersonId = #includePermissions.PersonId
			
	IF (@include&16 = 16) 
		SELECT NULL AS [#16], zd.*
		FROM PersonAdditionalData zd 
		WHERE zd.PersonAdditionalDataId IN 
		(SELECT PersonAdditionalDataId FROM PersonAdditionalData
			INNER JOIN	PersonAdditionalDataTypes	AS zdt	ON zd.PersonAdditionalDataTypeId = zdt.PersonAdditionalDataTypeId
			INNER JOIN	#includePermissions			AS gp	ON zd.PersonId = gp.PersonId
			INNER JOIN  #UserGroupPermissions		AS ug	ON zdt.OwnerGroupId = ug.OwnerGroupId			 
		WHERE 
			zdt.IsSecret = 0 OR ug.PermissionArea = 0)
	
	IF (@include&32 = 32) 
		SELECT NULL AS [#32], PersonRelations.*
		FROM PersonRelations
			INNER JOIN #includePermissions ON PersonRelations.PersonId = #includePermissions.PersonId AND ShowLinkedContacts > 0

	IF (@include&64 = 64) 
		SELECT NULL AS [#64], PersonRelations.*
		FROM PersonRelations 
			INNER JOIN #includePermissions ON PersonRelations.ChildPersonId = #includePermissions.PersonId

	IF (@include&128 = 128) 
		SELECT NULL AS [#128], Qualification_Person.*
		FROM Qualification_Person 
			INNER JOIN #includePermissions ON Qualification_Person.PersonId = #includePermissions.PersonId
	
	IF (@include&256 = 256) 
		SELECT NULL AS [#256], BodyMeasurements.*
		FROM BodyMeasurements 
			INNER JOIN #includePermissions ON BodyMeasurements.PersonId = #includePermissions.PersonId
			INNER JOIN #UserGroupPermissions prp ON prp.OwnerGroupId = #includePermissions.baseOwner AND prp.PermissionArea=6
	
	IF (@include&512 = 512) 
		SELECT NULL AS [#512], BankAccounts.*
		FROM BankAccounts 
			INNER JOIN #includePermissions ON BankAccounts.PersonId = #includePermissions.PersonId 
				AND (#includePermissions.ReadPersonBankdata>0 OR #includePermissions.WritePersonBankdata > 0)

	IF (@include&2048 = 2048) 
		SELECT NULL AS [#2048], PersonAttachments.PersonId, Count(*) AS CountAttachments
		FROM PersonAttachments 
			INNER JOIN #includePermissions ON PersonAttachments.PersonId = #includePermissions.PersonId
		GROUP BY PersonAttachments.PersonId

	IF (@include&4096 = 4096) 
		SELECT NULL AS [#4096], Birthdays.*
		FROM Birthdays 
			INNER JOIN #includePermissions ON Birthdays.PersonId = #includePermissions.PersonId		
	IF (@include&8192 = 8192 OR @include&16384 = 16384) 
		SELECT NULL AS [#8192], Contracts.*
		FROM Contracts 
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	AND contracts.OwnerGroupId IN 
			(SELECT OwnerGroupId FROM #UserGroupPermissions WHERE PermissionArea = 1)

	IF (@include&16384 = 16384) 
		SELECT NULL AS [#16384], ContractDepartments.*
		FROM ContractDepartments 
			INNER JOIN Contracts ON ContractDepartments.ContractId=Contracts.ContractId
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	AND contracts.OwnerGroupId IN 
			(SELECT OwnerGroupId FROM #UserGroupPermissions WHERE PermissionArea IN (1, 5))		

	IF (@include&32768 = 32768) 
		SELECT NULL AS [32768], PersonInCategories.*
		FROM PersonInCategories 
			INNER JOIN #PersonsNP ON PersonInCategories.PersonId = #PersonsNP.PersonId	

	IF (@include&65536 = 65536) 
		SELECT NULL AS [65536],pfd.*
		FROM PersonFieldData pfd 
				INNER JOIN PersonFields AS pf ON pfd.PersonFieldId = pf.PersonFieldId
				INNER JOIN #includePermissions AS PP ON pfd.PersonId = PP.PersonId
		WHERE ReadPersonDetails > 0 OR WritePersonDetails > 0 OR pf.ShowOnPage = 1 -- Pressetextseite(1) ist öffentlich

	IF (@include<>0) 
	BEGIN	
		DROP TABLE #includePermissions
		DROP TABLE #PersonsNP
	END
	DROP TABLE #UserGroupPermissions
END
GO
--#endregion

--#region SH 2021-10-11 Neue Rolle für Jobverwaltung
IF NOT EXISTS(SELECT * FROM sys.database_principals dp WHERE dp.name = 'JobManagement' AND dp.type = 'R')
BEGIN
	PRINT ('Creating Role JobManagement...')
	EXEC sp_addrole @rolename = 'JobManagement'
	EXEC sp_addrolemember 'JobManagement','Konfigurieren'
END
GO
--#endregion SH 2021-10-11 Neue Rolle für Jobverwaltung

--#region SH 2021-10-14 DataService Berechtigungen auf einige Interal Prozeduren geben, damit Abfragen im WCf über UserContext funktionieren
GRANT EXECUTE ON GetActivitiesInternal TO DataService
GRANT EXECUTE ON GetCastByCastIdInternal TO DataService
GRANT EXECUTE ON GetCastByActivityIdInternal TO DataService
GRANT EXECUTE ON GetCastByPeriodInternal TO DataService
GRANT EXECUTE ON GetDutyRosterByContractsInternal TO DataService
GRANT EXECUTE ON GetDutyRosterByDepartmentInternal TO DataService
GRANT EXECUTE ON GetGroupedDutyRosterByContractsInternal TO DataService
GRANT EXECUTE ON GetPersonsInternal TO DataService
GRANT EXECUTE ON GetPersonStatusInternal TO DataService
GO
--#endregion SH 2021-10-14 DataService Berechtigungen auf einige Interal Prozeduren geben, damit Abfragen im WCf über UserContext funktionieren

--#region DH 2021-10-19 AssistanceRole für Rolejobsteps 
IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobSteps') AND [name] = 'RoleMakeupArtistId')
BEGIN
	PRINT 'Adding AssistanceRoleId'
	ALTER TABLE RoleJobSteps ADD RoleMakeupArtistId INT NULL;
END
GO
--#endregion DH 2021-10-19 AssistanceRole für Rolejobsteps 
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name]='MeasureTypeCategories')
BEGIN
	PRINT 'Create MeasureTypeCategories'
	CREATE TABLE dbo.MeasureTypeCategories(
		MeasureTypeCategoryId INT IDENTITY(1, 1) NOT NULL,
		MeasureTypeCategory TINYINT	NOT NULL CONSTRAINT DF_MeasureTypeCategories_MeasureTypeCategory DEFAULT 0,
		[Name]				VARCHAR(50)	NOT NULL,
		[Description]		VARCHAR(MAX)	NULL,
		Sort				SMALLINT		NOT NULL  CONSTRAINT DF_MeasureTypeCategories_Sort DEFAULT 0,
		LM					SMALLDATETIME	NOT NULL CONSTRAINT DF_MeasureTypeCategories_LM DEFAULT GETDATE(),
		UM					INT				NULL,
		LC					SMALLDATETIME	NOT NULL CONSTRAINT DF_MeasureTypeCategories_LC DEFAULT GETDATE(),
		UC					INT				NULL,
		CONSTRAINT PK_MeasureTypeCategories PRIMARY KEY CLUSTERED (MeasureTypeCategoryId) ON [PRIMARY]
		) ON [PRIMARY]			

	CREATE UNIQUE INDEX IX_MeasureTypeCategories_Name ON MeasureTypeCategories ([Name]) ON [PRIMARY]
	GRANT SELECT ON MeasureTypeCategories TO [public]
	GRANT INSERT, UPDATE, DELETE ON MeasureTypeCategories TO [StaffAdmin]
	SET IDENTITY_INSERT MeasureTypeCategories ON
	INSERT INTO MeasureTypeCategories (MeasureTypeCategoryId, MeasureTypeCategory, [name]) VALUES (1, 0, 'Schulung'),(2, 1, 'Unterweiseung'),(3, 2, 'Untersuchung')
	SET IDENTITY_INSERT MeasureTypeCategories OFF
	ALTER TABLE MeasureTypes ADD MeasureTypeCategoryId INT NULL

	EXEC('UPDATE MeasureTypes SET MeasureTypeCategoryId = MeasureTypeCategory+1')
	ALTER TABLE MeasureTypes ALTER COLUMN MeasureTypeCategoryId INT NOT NULL
		
	ALTER TABLE MeasureTypes WITH CHECK ADD CONSTRAINT FK_MeasureTypes_MeasureTypeCategories FOREIGN KEY(MeasureTypeCategoryId)
	REFERENCES MeasureTypeCategories  (MeasureTypeCategoryId)
	ALTER TABLE MeasureTypes CHECK CONSTRAINT FK_MeasureTypes_MeasureTypeCategories
	ALTER TABLE MeasureTypes DROP CONSTRAINT DF_MeasureTypes_MeasureTypeCategory
	ALTER TABLE MeasureTypes DROP COLUMN MeasureTypeCategory
END

GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.MeasureTypes') AND o.Name = 'IX_MeasureTypes_Name') CREATE UNIQUE INDEX IX_MeasureTypes_Name ON MeasureTypes ([Name]) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name] = 'MeasureTypePriorities')
BEGIN
	PRINT 'Create MeasureTypePriorities'
	CREATE TABLE dbo.MeasureTypePriorities(
		MeasureTypePriorityId INT IDENTITY(1, 1) NOT NULL,
		[Name]				VARCHAR(50)   NOT NULL,
		[Description]		VARCHAR(MAX)  NULL,
		Sort				SMALLINT	  NOT NULL CONSTRAINT DF_MeasureTypePriorities_Sort DEFAULT 0,
		BackColor			INT NULL,
		ForeColor			INT NULL,
		LM					SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypePriorities_LM DEFAULT GETDATE(),
		UM					INT			  NULL,
		LC					SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypePriorities_LC DEFAULT GETDATE(),
		UC					INT			  NULL,
		CONSTRAINT PK_MeasureTypePriorities PRIMARY KEY CLUSTERED (MeasureTypePriorityId) ON [PRIMARY]
		) ON [PRIMARY]			

	CREATE UNIQUE INDEX IX_MeasureTypePriorities_Name ON MeasureTypePriorities ([Name]) ON [PRIMARY]
	GRANT SELECT ON MeasureTypePriorities TO [public]
	GRANT INSERT, UPDATE, DELETE ON MeasureTypePriorities TO [StaffAdmin]
	SET IDENTITY_INSERT MeasureTypePriorities ON
	INSERT INTO MeasureTypePriorities (MeasureTypePriorityId, [name]) VALUES (1, 'Standard')
	SET IDENTITY_INSERT MeasureTypePriorities OFF
	ALTER TABLE MeasureTypes ADD MeasureTypePriorityId INT NULL

	EXEC('UPDATE MeasureTypes SET MeasureTypePriorityId = 1')
	ALTER TABLE MeasureTypes ALTER COLUMN MeasureTypePriorityId INT NOT NULL
		
	ALTER TABLE MeasureTypes WITH CHECK ADD CONSTRAINT FK_MeasureTypes_MeasureTypePriorities FOREIGN KEY(MeasureTypePriorityId)
	REFERENCES MeasureTypePriorities (MeasureTypePriorityId)
	ALTER TABLE MeasureTypes CHECK CONSTRAINT FK_MeasureTypes_MeasureTypePriorities

END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('Departments') AND [name] = 'DefaultAllocationGroupId')
BEGIN
	PRINT 'Add DefaultAllocationGroupId'
	ALTER TABLE Departments ADD DefaultAllocationGroupId INT NULL
	ALTER TABLE Departments WITH CHECK ADD CONSTRAINT FK_Departments_AllocationGroups FOREIGN KEY(DefaultAllocationGroupId)
	REFERENCES AllocationGroup  (AllocationGroupId)
	ALTER TABLE Departments CHECK CONSTRAINT FK_Departments_AllocationGroups
END
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.PersonalStücke') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) DROP TABLE PersonalStücke
GO
--#endregion MeasurtypeCategories

--#region 2021-11-08 Views für Resources
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceObjectContainers_Update') AND type <> 'U') DROP VIEW dbo.AbResourceObjectContainers_Update
GO
CREATE VIEW [dbo].[AbResourceObjectContainers_Update]
AS 
SELECT  r.* FROM dbo.ResourceObjectContainers AS r
		 WHERE r.ResourceContainerId IN 
		 (	
			SELECT ResourceContainer.ResourceContainerId 
			FROM ResourceContainer 
				INNER JOIN [Permissions] AS ug ON ResourceContainer.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
			WHERE Username = CURRENT_USER
				AND PermissionArea = 16 
				AND HasWritePermission = 1
		)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON AbResourceObjectContainers_Update TO PUBLIC
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceObjectContainerParts_Update') AND type <> 'U') DROP VIEW dbo.AbResourceObjectContainerParts_Update
GO
CREATE VIEW [dbo].[AbResourceObjectContainerParts_Update]
AS 
SELECT  r.* FROM dbo.ResourceObjectContainerParts AS r
		 WHERE r.ResourceObjectContainerId IN 
		 (	
			SELECT ResourceObjectContainers.ResourceObjectContainerId 
			FROM ResourceContainer 
				INNER JOIN [Permissions] AS ug ON ResourceContainer.OwnerGroupId = ug.OwnerGroupId
				INNER JOIN Users AS pw ON ug.UserId = pw.UserId
				INNER JOIN ResourceObjectContainers ON ResourceContainer.ResourceContainerId = ResourceObjectContainers.ResourceContainerId
			WHERE Username = CURRENT_USER
				AND PermissionArea = 16 
				AND HasWritePermission = 1
		)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON [AbResourceObjectContainerParts_Update] TO PUBLIC

GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO chorAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO dispoAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO kontaktAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO orchesterAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO persoAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON MailingListEntries TO StatisterieAdmin
GRANT SELECT, UPDATE, INSERT, DELETE ON RoleJobStepAttachments TO dataService

GO
--#endregion

--#region 2021-11-23
--#region DeletePersonReference

ALTER PROCEDURE [dbo].[DeletePersonReference] (@personId INT, @del INT) AS 
	DECLARE @conflictCounter INT
	SELECT @conflictCounter = 0
	DECLARE @conflictDescription VARCHAR(MAX)
	SELECT @conflictDescription = ''

	DECLARE @Temp INT
	SELECT  @Temp = 0
	DECLARE @CRLF char(2)
	SET @CRLF =  '|'
	SET NOCOUNT On
	/*
	Eingabeparameter: 
	@personId			=> Zu bearbeitendes PersonId
	@del			= 0 Nur überprüfen, ob das Löschen der Detaildaten möglich ist / 1 löschen

	Rückgabewerte:
	1. @conflictCounter			=> Anzahl der Tabellen in denen eine Löschung nicht möglich wäre.
	2. @ConflictDescription		=>	Ausgabe der Löschkonflikte
	*/

	if (@del > 0)
	--Rekusiveraufruf beim "echtem löschen mit Check (0)"
	BEGIN
		DECLARE @return_value int
		EXEC @return_value = dbo.DeletePersonReference @personId, 0

		IF (@return_value > 0) 
		BEGIN
			RETURN @return_value
		END
	END

	SELECT @Temp = OwnerGroupId FROM Persons WHERE PersonId = @personId

	IF (dbo.GetCurrentPermission(@Temp,0) <> 2) 
	BEGIN
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'No Owner Permissions' + @CRLF
		SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
		RETURN @conflictCounter
	END

	/*  Tabelle BasicCast */
	IF (SELECT COUNT(*) FROM BasicCast WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'BasicCast' + @CRLF
	END

	/*  Tabelle Besetzung */
	IF (SELECT COUNT(*) FROM Cast WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Cast' + @CRLF
	END

	/*  Bereich der Tabellen PersonStatus  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonStatus WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM AbPersStatus_Update WHERE PersonId = @personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Status' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM PersonStatus WHERE PersonId = @personId
			END
		END

	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM Contracts WHERE PersonId = @personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract' + @CRLF
	END
	/*  Tabelle Contracts  */
	IF (SELECT COUNT(*) FROM ContractDetails WHERE ContractDetails.AgencyPersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Contract (Agency)' + @CRLF
	END

	/* Cashcommands*/
	IF (SELECT COUNT(*) FROM CashCommands WHERE PersonId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
	END

	IF (SELECT COUNT(*) FROM CashCommands WHERE AgencyId=@personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
	END

	/* PersonDetails*/
	IF (SELECT COUNT(*) FROM PersonDetails WHERE HealthInsuranceId=@personId) > 0
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal( HealthInsurance)' + @CRLF
	END

	IF (SELECT COUNT(*) FROM PersonDetails WHERE TaxOfficeId = @personId) > 0  
	BEGIN 
		SELECT @conflictCounter = @conflictCounter + 1
		SELECT @conflictDescription = @conflictDescription + 'Personal (TaxOffice)' + @CRLF
	END
	
	/* ------------------------------------Dispositionsbereich ende -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

	IF (@del > 0) DELETE FROM PersonDetails WHERE PersonId = @personId

	/*  Tabelle PersonRelations  */
	IF (@del > 0) 
		BEGIN
			UPDATE PersonRelations SET ContactPersonConnectionId = NULL WHERE ContactPersonConnectionId IN (SELECT PersonRelationId FROM PersonRelations WHERE ChildPersonId=@personid) 
			DELETE FROM PersonRelations WHERE ChildPersonId = @personId;
			DELETE FROM PersonRelations WHERE PersonId = @personId;			
		END

	/*  Tabelle BasicCastHistory */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
	IF (SELECT COUNT(*) FROM AbXHDelBasicCast_Update WHERE PersonOldId = @personId OR PersonNewId = @personId) < @Temp
		BEGIN 
			SELECT @conflictCounter=@conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'BasicCastHistory' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM BasicCastHistory WHERE PersonOldId = @personId OR PersonNewId = @personId
			END
		END

	/*  Tabelle PersonFeeNotes  */
	IF (@del > 0) DELETE FROM PersonFeeNotes WHERE PersonId=@personId

/*  Tabelle AbPersonalNotizen_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonMemo WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM AbPersonalNotizen_Update WHERE PersonId=@personId) < @Temp 
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Notes' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp) > 0
			BEGIN 
				IF (@del > 0) DELETE FROM PersonMemo WHERE PersonId = @personId
			END
		END


	/*  Tabelle ABPersKom_Update  */
	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonContactData WHERE PersonId = @personId
	IF (SELECT COUNT(*) FROM ABPersonContactData_Update WHERE PersonId = @personId) < @Temp
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Contactdata' + @CRLF
		END
	ELSE
		BEGIN
			IF(@Temp)>0
			BEGIN 
				IF (@del > 0)DELETE FROM PersonContactData WHERE PersonId=@personId
			END
		END

	/*  Tabelle ABPersonAddress_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAddress WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM ABPersonAddress_Update WHERE PersonId = @personId) < @Temp
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Adressdata' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp)>0
				BEGIN 
					IF (@del > 0)DELETE FROM PersonAddress WHERE PersonId=@personId
				END
			END

	/*  Tabelle AbPersZusatzDaten_Update  */
		SELECT  @Temp = 0
		SELECT @Temp = COUNT(*) FROM PersonAdditionalData WHERE PersonId = @personId
		IF (SELECT COUNT(*) FROM AbPersZusatzDaten_Update WHERE PersonId = @personId) < @Temp 
			BEGIN
				SELECT @conflictCounter = @conflictCounter + 1
				SELECT @conflictDescription = @conflictDescription + 'Personal attribute' + @CRLF
			END
		ELSE
			BEGIN
				IF(@Temp) > 0
				BEGIN 
					IF (@del > 0)DELETE FROM PersonAdditionalData WHERE PersonId = @personId
				END
			END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM ResourceObjectBorrows WHERE PersonId = @personId AND EndDate IS NULL
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Open Borrows' + @CRLF
		END

	IF (@del > 0) DELETE FROM ResourceObjectBorrows WHERE PersonId = @personId


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM CashCommands WHERE AgencyId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'CashCommand (Agency)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM DepartmentCollectives WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'DepartmentCollectives' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Orders WHERE SupplierId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Orders (Supplier)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM OrderTravelers WHERE TravelerId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'OrderTravelers' + @CRLF
		END


	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM Departments WHERE HeadOfDepartmentId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Department (HeadOfDepartment)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonAttachments WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'PersonAttachments' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkCreators WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkCreators' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (Person)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersionRoles_Repertoire WHERE TheaterId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersionRoles_Repertoire (TheaterId)' + @CRLF
		END

	SELECT  @Temp = 0
	SELECT @Temp = COUNT(*) FROM WorkVersions WHERE PublisherId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'WorkVersions (Publisher)' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM MeasureParticipations WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'MeasureParticipations' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM PersonRequiredMeasureTypes WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'PersonRequiredMeasureTypes' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM Tours_Contracts WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'Tours_Contracts' + @CRLF
		END

	SELECT @Temp = 0
	SELECT @Temp = COUNT(*) FROM ProductionPartners WHERE PersonId = @personId
	IF(@Temp) > 0
		BEGIN
			SELECT @conflictCounter = @conflictCounter + 1
			SELECT @conflictDescription = @conflictDescription + 'ProductionPartners' + @CRLF
		END
		
	SELECT @conflictCounter AS ConflictCount,  @conflictDescription AS ConflictDescription
	RETURN @conflictCounter
GO
--#endregion DeletePersonReference
--#endregion
--#region ContractTypePeriods
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF Not Exists (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.ContractTypePeriods') )
BEGIN
Print 'Tabelle abweichende Vertragsstunden';
CREATE TABLE [dbo].[ContractTypePeriods](
	[ContractTypePeriodId] [int] IDENTITY(1,1) NOT NULL,
	[ContractTypeId] [int] NOT NULL,
	[Start] date NULL,
	[End] date null,
	[LM] [smalldatetime] NOT NULL,
	[UM] [int] NULL,
	[LC] [smalldatetime] NOT NULL,
	[UC] [int] NULL,
	[Note] [varchar](max) SPARSE  NULL,
	[MonMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_MonMinutes]  DEFAULT (0),
	[TueMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_TueMinutes]  DEFAULT (0),
	[WedMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_WedMinutes]  DEFAULT (0),
	[ThuMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_ThuMinutes]  DEFAULT (0),
	[FriMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_FriMinutes]  DEFAULT (0),
	[SatMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_SatMinutes]  DEFAULT (0),
	[SunMinutes] [int] NOT NULL CONSTRAINT [DF_ContractTypePeriods_SunMinutes]  DEFAULT (0),
	[DebitServicesCount] [float] NOT NULL CONSTRAINT [DF_ContractTypePeriods_DebitServicesCount] Default (0),
	[DebitServicesCountPerMonth] [float] NOT NULL CONSTRAINT [DF_ContractTypePeriods_DebitServicesCountPerMonth] Default (0),
	[DebitServicesCountPerSeason] [float] NOT NULL CONSTRAINT [DF_ContractTypePeriods_DebitServicesCountPerSeason] Default (0),
 CONSTRAINT [PK_ContractTypePeriods] PRIMARY KEY NONCLUSTERED 
(
	[ContractTypePeriodId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY],
CONSTRAINT [FK_ContractTypePeriods_ContractTypes] FOREIGN KEY([ContractTypeId])
REFERENCES [dbo].[ContractTypes] ([ContractTypeId])
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF not exists(Select contracttypeid from ContractTypePeriods)
BEGIN
Print 'Vertragsstunden übernehmen';
INSERT INTO [dbo].[ContractTypePeriods](
	[ContractTypeId],[Start],[End],[LM],[UM],[LC],[UC],[MonMinutes],[TueMinutes],[WedMinutes],[ThuMinutes],[FriMinutes],[SatMinutes],[SunMinutes],[DebitServicesCount],[DebitServicesCountPerMonth],[DebitServicesCountPerSeason])
SELECT 
	[ContractTypeId],null,null,GETDATE(),0,Getdate(),0,[MonMinutes],[TueMinutes],[WedMinutes],[ThuMinutes],[FriMinutes],[SatMinutes],[SunMinutes],[DebitServicesCount],[DebitServicesCountPerMonth],[DebitServicesCountPerSeason]
FROM ContractTypes
END
GRANT SELECT on contracttypeperiods to public
GRANT INSERT, update, delete on contracttypeperiods to PersoAdmin,DispoAdmin,OrchesterAdmin,ChorAdmin,BallettAdmin,StatisterieAdmin
GO
--#endregion ContracttypePeriods

--#region

ALTER PROCEDURE [dbo].[CountCastShiftByContract]
	@countType INT,
	@start Datetime, 
	@end Datetime,
	@contractIds NVARCHAR(4000),
	@departmentId INT,
	@activitytypIds NVARCHAR(4000),
	@covercount INT
AS
BEGIN
	SET NOCOUNT ON;
	/*
	@countType
	0 = Anzahl
	1 = Anrechenbare
	2 = Zeit
	*/
	/*
	@covercount
	0 = Ohne Cover (withoutCover)
	1 = mit Cover (All)
	2 = nur Cover (CoverOnly)
	*/

	--Spielzeitberechtigungen prüfen und ggf Zeitraum anpassen
	DECLARE @permissionPeriodStart DATETIME
	DECLARE @permissionPeriodEnd DATETIME

	SELECT @permissionPeriodStart = MIN(s.SeasonId) , @permissionPeriodEnd = MAX(s.EndDate)
		FROM Seasons AS s	
		INNER JOIN SeasonPermissions	AS us	ON s.SeasonId = us.SeasonId
		INNER JOIN Users			AS U	ON us.UserId =u.UserId
	WHERE u.UserName  = CURRENT_USER

	IF (@start < @permissionPeriodStart)  SELECT @start = @permissionPeriodStart
	IF (@end > @permissionPeriodEnd)  SELECT @end = @permissionPeriodEnd

	--Unterscheidung ob die Anzahl oder die anrechenbare Zahl der Dienste gezählt wird(
	--z.B. Creditable = 2 als zwei Dienste)

	CREATE TABLE #contractIds (id INT  PRIMARY KEY)
	INSERT INTO #contractIds SELECT * FROM [dbo].[SplitIDs] ( @contractIds)

	IF @activitytypIds IS NOT NULL
	BEGIN
		CREATE TABLE #activitytypIds (id int  PRIMARY KEY)
		INSERT INTO #activitytypIds SELECT * FROM [dbo].[SplitIDs] ( @activitytypIds)
	END

	IF @countType = 0
		--Anzahl
		BEGIN
			IF @activitytypIds IS NULL
				--ohne Aufftypfilter
				BEGIN 
					SELECT ca.ContractId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS [Sum]  
					FROM
						Activities					AS ac
						INNER JOIN ActivityStatuses AS [as] ON ac.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN [Cast]			AS ca	ON ac.ActivityId = ca.ActivityId
						INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
					WHERE
						[Date] BETWEEN @start AND @end 
						AND ac.VariantId = 0
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						AND [as].StatusType >= 0
					GROUP BY
						ca.ContractId
				END
			ELSE
			--mit Aufftypfilter
				BEGIN
					SELECT ca.ContractId, CAST(COUNT (DISTINCT ca.ActivityId) AS float) AS [Sum]  
					FROM
						Activities					AS ac
						INNER JOIN ActivityStatuses AS [as] ON ac.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN [Cast]			AS ca	ON ac.ActivityId = ca.ActivityId
						INNER JOIN #contractIds				ON ca.ContractId = #contractIds.id
						INNER JOIN #activitytypIds			ON ac.ActivityTypeId = #activitytypIds.id
					WHERE
						[Date] BETWEEN @start AND @end 
						AND ac.VariantId = 0
						AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
						AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						AND [as].StatusType >= 0 
					GROUP BY
						ca.ContractId
				END
			END
		ELSE IF @countType = 1
			--Anrechenbare
			BEGIN
			IF @activitytypIds IS NULL
			--ohne Aufftypfilter
				BEGIN 
					SELECT
						ContractId, SUM(Sum1)
					FROM
						(SELECT ca.ContractId, ca.ActivityId, 
						MAX(ISNULL(ca.Creditable,
							ISNULL(ActDep.ShiftCount, 
							CASE WHEN [at].Category >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END))) AS Sum1 
						FROM	
							Activities							AS ac
							INNER JOIN ActivityTypes			AS [at]    ON at.ActivityTypeId = ac.ActivityTypeId
							INNER JOIN [Cast]					AS ca      ON ac.ActivityId =ca.ActivityId
							INNER JOIN ActivityStatuses			AS act     ON ac.ActivityStatusId = act.ActivityStatusId
							LEFT JOIN  ActivityDepartmentData	AS ActDep  ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
							LEFT JOIN  ProductionDeparmentData  AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
							INNER JOIN #contractIds						   ON ca.ContractId = #contractIds.id				
						WHERE
							[Date] BETWEEN @start AND @end 
							AND ac.VariantId = 0
							AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
							AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						GROUP BY
							ContractId, ca.ActivityId
						) AS SubSQL
					GROUP BY ContractId 
				END
			ELSE
			--mit Aufftypfilter
				BEGIN
					SELECT
						ContractId, SUM(Sum1)
					FROM (
						SELECT
							ContractId, ca.ActivityId, MAX(ISNULL(ca.Creditable,
							ISNULL(ActDep.ShiftCount, 
								CASE WHEN [at].Category  >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END ) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END))) AS Sum1 
						FROM
							Activities						  AS ac
							INNER JOIN ActivityTypes		  AS [at]	 ON at.ActivityTypeId = ac.ActivityTypeId
							INNER JOIN [Cast]				  AS ca		 ON ac.ActivityId = ca.ActivityId
							INNER JOIN ActivityStatuses		  AS act	 ON ac.ActivityStatusId = act.ActivityStatusId
							LEFT JOIN ActivityDepartmentData  AS ActDep	 ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
							LEFT JOIN ProductionDeparmentData AS ProdDep ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
							INNER JOIN #contractIds						 ON ca.ContractId = #contractIds.id
							INNER JOIN #activitytypIds					 ON ac.ActivityTypeId = #activitytypIds.id				
						WHERE
							[Date] BETWEEN @start AND @end 
							AND ac.VariantId = 0
							AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
							AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						GROUP BY
							ContractId, ca.ActivityId
					) AS SubSQL
					GROUP BY
						ContractId 
				END	
			END
	ELSE IF @countType = 2
		BEGIN
		--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
				IF @activitytypIds IS NULL
			--ohne Aufftypfilter
				BEGIN 
					SELECT
						ContractId, SUM(Sum1)
					FROM (
						SELECT ContractId, CONVERT(VARCHAR(10), ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5), ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS Shift, 
							MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
								CASE WHEN [at].Category >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END ) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END))) AS Sum1 
						FROM
							Activities							AS ac
							INNER JOIN ActivityTypes			AS [at]		ON [at]	.ActivityTypeId = ac.ActivityTypeId
							INNER JOIN [Cast]					AS ca		ON ac.ActivityId = ca.ActivityId
							INNER JOIN ActivityStatuses			AS act		ON ac.ActivityStatusId = act.ActivityStatusId
							LEFT JOIN  ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
							LEFT JOIN  ProductionDeparmentData	AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
							INNER JOIN #contractIds							ON ca.ContractId = #contractIds.id
						WHERE
							[Date] BETWEEN @start AND @end 
							AND ac.VariantId = 0
							AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
							AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						GROUP BY
							ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END
					) AS SubSQL
					GROUP BY 
						ContractId 
				END
			ELSE
			--mit Aufftypfilter
				BEGIN
					SELECT
						ContractId, SUM(Sum1)
					FROM (
						SELECT
							ContractId, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS [Shift], MAX(ISNULL(ca.Creditable,
								CASE WHEN [at].Category  >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END ) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END)) AS Sum1 
						FROM
							Activities							AS ac
							INNER JOIN ActivityTypes			AS [at]		ON [at].ActivityTypeId = ac.ActivityTypeId
							INNER JOIN [Cast]					AS ca		ON ac.ActivityId = ca.ActivityId
							INNER JOIN ActivityStatuses			AS act		ON ac.ActivityStatusId = act.ActivityStatusId
							LEFT JOIN ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
							LEFT JOIN ProductionDeparmentData	AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
							INNER JOIN #contractIds							ON ca.ContractId = #contractIds.id
							INNER JOIN #activitytypIds						ON ac.ActivityTypeId = #activitytypIds.id
						WHERE
							[Date] BETWEEN @start AND @end 
							AND ac.VariantId = 0
							AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
							AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
						GROUP BY 
							ContractId, CONVERT(VARCHAR(10), ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5), ac.StartTime, 108) > '14:00' THEN '2' ELSE '1' END
					) AS SubSQL
					GROUP BY
						ContractId 
				END		
		END
	ELSE IF @countType = 3
		BEGIN
		--Zählen pro Tag max 2 Dienst  (morgens < 14:00 und abends)
			IF @activitytypIds IS NULL
			--ohne Aufftypfilter
				BEGIN 
					SELECT
						ContractIdDay, SUM(SumDay)
					FROM (
						SELECT
							ContractId AS ContractIdDay, Date, SUM(Sum1)-1  AS [SumDay]
						FROM (
							SELECT
								ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS [Shift], 
								MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
								CASE WHEN [at].Category  >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END ) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END))) AS Sum1 
							FROM
								Activities							AS ac
								INNER JOIN ActivityTypes			AS [at]		ON [at]	.ActivityTypeId = ac.ActivityTypeId
								INNER JOIN [Cast]					AS ca		ON ac.ActivityId = ca.ActivityId
								INNER JOIN ActivityStatuses			AS act		ON ac.ActivityStatusId = act.ActivityStatusId
								LEFT JOIN  ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
								LEFT JOIN  ProductionDeparmentData	AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
								INNER JOIN #contractIds							ON ca.ContractId = #contractIds.id
							WHERE
								[Date] BETWEEN @start AND @end 
								AND ac.VariantId = 0
								AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
								AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
							GROUP BY
								ContractId, ac.Date, CONVERT(VARCHAR(10), ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5), ac.StartTime, 108) > '14:00' THEN '2' ELSE '1' END
						) AS SubSQL 
						GROUP BY
							ContractId, Date
					)  AS subDay
					Group BY
						ContractIdDay
				END		
			ELSE
			--mit Aufftypfilter
				BEGIN
					SELECT
						ContractIdDay, SUM(SumDay)
					FROM (
						SELECT
							ContractId AS ContractIdDay, Date, SUM(Sum1)-1  AS [SumDay]
						FROM (
							SELECT
								ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END AS [Shift], 
								MAX(ISNULL(ca.Creditable, ISNULL(ActDep.ShiftCount, 
								CASE WHEN [at].Category >= 2000 THEN ISNULL(ProdDep.ShiftCount, CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END ) ELSE CASE WHEN act.StatusType < 0 THEN 0 ELSE 1 END  END))) AS Sum1  
							FROM
								Activities							AS ac
								INNER JOIN ActivityStatuses			AS act		ON ac.ActivityStatusId = act.ActivityStatusId
								INNER JOIN ActivityTypes			AS [at]		ON [at].ActivityTypeId = ac.ActivityTypeId
								INNER JOIN [Cast]					AS ca		ON ac.ActivityId = ca.ActivityId
								INNER JOIN Roles					AS r		ON ca.RoleId = r.RoleId
								LEFT JOIN  ActivityDepartmentData	AS ActDep	ON ac.ActivityId = ActDep.ActivityId AND ActDep.DepartmentId = @departmentId
								LEFT JOIN  ProductionDeparmentData	AS ProdDep	ON ac.ProductionId = ProdDep.ProductionId AND ProdDep.DepartmentId = @departmentId AND ProdDep.SeasonId IS NULL
								INNER JOIN #contractIds							ON ca.ContractId = #contractIds.id
								INNER JOIN #activitytypIds ON ac.ActivityTypeId = #activitytypIds.id
							WHERE
								[Date] BETWEEN @start AND @end 
								AND ac.VariantId = 0
								AND (ca.IsCanceled = 0 OR ca.Creditable IS NULL OR ca.Creditable > 0)
								AND (@covercount = 1 OR (@covercount = 0 AND ca.isCover = 0) OR (@covercount = 2 AND ca.isCover = 1))
							GROUP BY
								ContractId, ac.Date, CONVERT(VARCHAR(10),ac.Date,126) + '_' + CASE WHEN CONVERT(VARCHAR(5),ac.StartTime, 108) > '14:00'  THEN '2' ELSE '1' END
						) AS SubSQL 
						GROUP BY
							ContractId, Date
					)  AS subDay
					Group BY
						ContractIdDay
				END		
		END
	ELSE IF @countType = 4
		BEGIN
			IF @activitytypIds IS NULL
				--ohne Aufftypfilter
				BEGIN 
					SELECT
						ca.ContractId, CAST(COUNT (DISTINCT ac.Date) AS float) AS [Sum]
					FROM
						Activities						AS ac
						INNER JOIN ActivityStatuses		AS [as] ON ac.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN [Cast]				AS ca	ON ac.ActivityId = ca.ActivityId
						INNER JOIN #contractIds					ON ca.ContractId = #contractIds.id
					WHERE
						[Date] BETWEEN @start AND @end 
						AND ac.VariantId = 0
						AND ca.IsCanceled = 0 
						AND [as].StatusType >= 0
					GROUP BY
						ContractId
				END
			ELSE
			--mit Aufftypfilter
				BEGIN
					SELECT
						ca.ContractId, CAST(COUNT (DISTINCT ac.Date) AS float) AS [Sum]
					FROM
						Activities						AS ac
						INNER JOIN ActivityStatuses		AS [as] ON ac.ActivityStatusId = [as].ActivityStatusId
						INNER JOIN [Cast]				AS ca	ON ac.ActivityId =ca.ActivityId
						INNER JOIN Roles				AS r	ON ca.RoleId =r.RoleId
						INNER JOIN #contractIds					ON ca.ContractId = #contractIds.id
						INNER JOIN #activitytypIds				ON ac.ActivityTypeId = #activitytypIds.id
					WHERE
						[Date] BETWEEN @start AND @end 
						AND ac.VariantId = 0
						AND ca.IsCanceled = 0 
						AND [as].StatusType >= 0
						AND (@covercount=1 OR (@covercount=0 AND ca.isCover=0) OR (@covercount=2 AND ca.isCover=1))
					GROUP BY
						ContractId
				END
			END

	END

	DROP TABLE  #contractIds
	IF @activitytypIds IS NOT NULL
	BEGIN
		DROP TABLE #activitytypIds
	END
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.CountCast')) DROP PROCEDURE dbo.CountCast

GO

--endregion
--#region Bugfix Berechtigung RoleTypes Perso
GRANT INSERT, update, delete on Roletypes to PersoAdmin
--#endregion Bugfix Berechtigung RoleTypes Perso






--#endregion ------- (4.215.x) --------------------------------
--#region ----------- 4.216.x ---------------------------------

--#region 2021-09-28
UPDATE Variants SET CheckOverlap = 1 WHERE IsMaster = 1 AND CheckOverlap = 0
--#endregion
-- Nur Änderungen im Release hier eintragen!!! (Bugfixes)
--#region SH 2021-09-21 Permission für GetPersonsInternal setzen
GRANT EXECUTE ON GetPersonsInternal TO DataService
GO
--#endregion

--#region 20210921
GRANT INSERT, UPDATE, DELETE ON ResourceTypes TO CostumeAdmin
GRANT INSERT, UPDATE, DELETE ON ResourceObjectConditions TO CostumeAdmin
GRANT INSERT, UPDATE, DELETE ON ResourceFieldTypes TO CostumeAdmin
GRANT INSERT, UPDATE, DELETE ON Templates TO CostumeAdmin
GRANT INSERT, UPDATE, DELETE ON RoleJobStepCategories TO CostumeAdmin
REVOKE INSERT, UPDATE, DELETE ON ResourceInContainer TO CostumeAdmin 
REVOKE INSERT, UPDATE, DELETE ON ResourceCreationPartList TO CostumeAdmin
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceInContainer_Update') AND type <> 'U') DROP VIEW dbo.AbResourceInContainer_Update
GO
CREATE VIEW dbo.AbResourceInContainer_Update
AS 
SELECT rfd.* FROM dbo.ResourceInContainer AS rfd
WHERE rfd.ResourceId IN (SELECT r.ResourceId FROM Resources AS r 
											INNER JOIN [Permissions] AS ug ON r.OwnerGroupId = ug.OwnerGroupId
											INNER JOIN Users AS pw ON ug.UserId = pw.UserId
						WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO

GRANT SELECT, UPDATE, INSERT, DELETE ON AbResourceInContainer_Update TO PUBLIC
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbResourceCreationPartList_Update') AND type <> 'U') DROP VIEW dbo.AbResourceCreationPartList_Update
GO

CREATE VIEW dbo.AbResourceCreationPartList_Update
AS 
SELECT rfd.* FROM dbo.ResourceCreationPartList AS rfd
WHERE rfd.ResourceId IN (SELECT r.ResourceId FROM Resources AS r 
											INNER JOIN [Permissions] AS ug ON r.OwnerGroupId = ug.OwnerGroupId
											INNER JOIN Users AS pw ON ug.UserId = pw.UserId
						 WHERE Username = CURRENT_USER AND PermissionArea = 16 AND HasWritePermission = 1)
WITH CHECK OPTION
GO

GRANT SELECT, UPDATE, INSERT, DELETE ON AbResourceCreationPartList_Update TO PUBLIC
GO

IF NOT EXISTS (SELECT * FROM [OrderApprovalStatus]) INSERT INTO OrderApprovalStatus ([Name], lm, lc, um, uc, CheckBudget) VALUES ('--', '19000101', '19000101', -1,-1, 0)
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobSteps') AND [name] = 'JobExecutedByRoleId')
BEGIN
	PRINT('RoleJobSteps DoneByRoleId')
	ALTER TABLE RoleJobSteps ADD JobExecutedByRoleId INT NULL

	ALTER TABLE RoleJobSteps WITH CHECK ADD CONSTRAINT FK_RoleJobSteps_DoneByRol FOREIGN KEY(JobExecutedByRoleId)
	REFERENCES Roles (RoleId)
	ALTER TABLE RoleJobSteps CHECK CONSTRAINT FK_RoleJobSteps_DoneByRol
END
GO

--#endregion

--#region MergeDoubletten Doppelte Qualifikationen
ALTER PROCEDURE [dbo].[MergeDoubletten]
	@PersonId INT, 
	@DoubletteId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	BEGIN TRY
		BEGIN TRAN
			UPDATE Auditions			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId 
			UPDATE BankAccounts			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE BasicCast			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE [Cast]				SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonInCategories	SET PersonId = @PersonId WHERE  PersonId = @DoubletteId AND PersonCategoryId NOT IN (SELECT PersonCategoryId FROM PersonInCategories WHERE  PersonId = @PersonId)
			UPDATE BodyMeasurements		SET PersonId = @PersonId, MeasuredAt = DATEADD(minute, 1, MeasuredAt) WHERE  PersonId = @DoubletteId
			UPDATE CashCommands			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE CashCommands			SET AgencyId = @PersonId WHERE  AgencyId = @DoubletteId
			UPDATE CheckListItem		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE CheckListItemTemplate SET PersonId= @PersonId WHERE  PersonId = @DoubletteId
	
			UPDATE dc SET PersonId = @PersonId FROM DepartmentCollectives dc 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM DepartmentCollectives d2 WHERE d2.DepartmentId = dc.DepartmentId AND d2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM MeasureParticipations mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM MeasureParticipations mp2 WHERE mp2.MeasureTypeId = mp.MeasureTypeId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM PersonRequiredMeasureTypes mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM PersonRequiredMeasureTypes mp2 WHERE mp2.MeasureTypeId = mp.MeasureTypeId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM Tours_Contracts mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM Tours_Contracts mp2 WHERE mp2.TourContractId = mp.TourContractId AND mp2.PersonId = @PersonId);

			UPDATE mp SET PersonId = @PersonId FROM ProductionPartners mp 
				WHERE PersonId = @DoubletteId AND NOT EXISTS (SELECT * FROM ProductionPartners mp2 WHERE mp2.ProductionId = mp.ProductionId AND mp2.PersonId = @PersonId);
				

			UPDATE Departments			SET HeadOfDepartmentId = @PersonId 
																 WHERE  HeadOfDepartmentId = @DoubletteId
			UPDATE MailingListEntries	SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Orders				SET SupplierId = @PersonId WHERE  SupplierId = @DoubletteId
			UPDATE OrderTravelers		SET TravelerId = @PersonId WHERE  TravelerId = @DoubletteId
			--Verweise zwischen Dublette und Zielperson werden gelöscht
			DELETE FROM PersonRelations WHERE PersonId = @PersonId AND ChildPersonId = @DoubletteId
			DELETE FROM PersonRelations WHERE PersonId = @DoubletteId AND ChildPersonId = @PersonId
	
			UPDATE PersonRelations		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId 
			UPDATE PersonRelations		SET ChildPersonId = @PersonId WHERE  ChildPersonId = @DoubletteId
	
			IF NOT EXISTS (SELECT * FROM PersonEmployee WHERE  PersonId=@PersonId)
				BEGIN
					UPDATE PersonEmployee SET PersonId=@PersonId WHERE  PersonId= @DoubletteId
				END
			ELSE
				BEGIN
					DELETE FROM PersonEmployee WHERE  PersonId = @DoubletteId
				END
			UPDATE PersonMemo					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonAdditionalData			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			-- Qualifikationen sind eindeutig pro Person
			DELETE FROM Qualification_Person WHERE  PersonId = @DoubletteId AND Qualification_Person.QualificationId IN (
				SELECT QualificationId FROM Qualification_Person WHERE  PersonId = @PersonId)
			
			UPDATE Qualification_Person			SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE ResourceObjectBorrows		SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE ResourceObjectInsurances		SET InsuredPersonId = @PersonId 
																 WHERE  InsuredPersonId = @DoubletteId
			UPDATE ResourceObjects				SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE PersonStatus					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Travels						SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE Contracts					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkCreators					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkVersionRoles_Repertoire  SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE WorkVersionRoles_Repertoire  SET TheaterId = @PersonId WHERE  TheaterId = @DoubletteId
			UPDATE WorkVersions					SET PublisherId = @PersonId WHERE  PublisherId = @DoubletteId
			UPDATE Locations					SET PersonId = @PersonId WHERE  PersonId = @DoubletteId
			UPDATE BasicCastHistory				SET PersonNewId = @PersonId	WHERE PersonNewId = @DoubletteId
			UPDATE MeasureParticipations		SET PersonId = @PersonId	WHERE PersonId = @DoubletteId 
				AND MeasureParticipationId NOT IN (SELECT MeasureParticipationId FROM MeasureParticipations AS a WHERE  PersonId = @PersonId AND a.MeasureTypeId = MeasureParticipations.MeasureTypeId AND a.ParticipationDate = MeasureParticipations.ParticipationDate  )
			UPDATE PersonRequiredMeasureTypes		SET PersonId = @PersonId	WHERE PersonId = @DoubletteId
				AND PersonRequiredMeasureTypeId NOT IN (SELECT PersonRequiredMeasureTypeId FROM PersonRequiredMeasureTypes AS a WHERE  PersonId = @PersonId AND a.MeasureTypeId = PersonRequiredMeasureTypes.MeasureTypeId)
			DELETE From MeasureParticipations	WHERE PersonId = @DoubletteId
			DELETE FROM PersonRequiredMeasureTypes	WHERE  PersonId = @DoubletteId
			
			DELETE From DepartmentCollectives WHERE PersonId = @DoubletteId
			DELETE From MeasureParticipations WHERE PersonId = @DoubletteId
			DELETE From PersonRequiredMeasureTypes WHERE PersonId = @DoubletteId
			DELETE From Tours_Contracts WHERE PersonId = @DoubletteId
			DELETE From ProductionPartners WHERE PersonId = @DoubletteId

			DELETE FROM PersonInCategories	WHERE  PersonId = @DoubletteId
			DELETE FROM PersonPermissions	WHERE PersonId = @DoubletteId
			DELETE FROM PersonContactData	WHERE PersonId = @DoubletteId
			DELETE FROM PersonAddress		WHERE PersonId = @DoubletteId
			DELETE FROM PersonDetails		WHERE PersonId = @DoubletteId
			DELETE FROM PersonFeeNotes		WHERE PersonId = @DoubletteId
			DELETE FROM Persons				WHERE PersonId = @DoubletteId
		COMMIT TRAN
	END TRY

	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK TRAN

		DECLARE @ErrorMessage NVARCHAR(4000);  
		DECLARE @ErrorSeverity INT;  
		DECLARE @ErrorState INT;  
  
		SELECT   
			@ErrorMessage = ERROR_MESSAGE(),  
			@ErrorSeverity = ERROR_SEVERITY(),  
			@ErrorState = ERROR_STATE();  

		RAISERROR (@ErrorMessage, -- Message text.  
				   @ErrorSeverity, -- Severity.  
				   @ErrorState -- State.  
				   );
	END CATCH
END 
GO
--#endregion MergeDoubletten Doppelte Qualifikationen
--#region DH-2021-10-05 Ausgabe von Creditsumaccounts - Zeitkonten, die Creditaccount sind, aber auch Gutschriften aus anderen Konten bekommen können
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('TimeAccounts') AND [name] = 'CreditAccount')
BEGIN
	ALTER TABLE TimeAccounts DROP CONSTRAINT DF_TimeAccounts_IsCreditAccount
	ALTER TABLE TimeAccounts ALTER COLUMN IsCreditAccount tinyint not null 
	ALTER TABLE TimeAccounts ADD  CONSTRAINT DF_TimeAccounts_IsCreditAccount DEFAULT ((0)) FOR IsCreditAccount
	EXEC sp_rename 'TimeAccounts.IsCreditAccount', 'CreditAccount', 'COLUMN';
END
GO
--#endregion DH-2021-10-05

--#region SH 2021-10-11 In LogLogin wird IsAutoUpdateEnabled nicht aktualisiert

ALTER PROCEDURE [dbo].[LogLogin] 
		@ComputerName VARCHAR(64),
		@OSVersion VARCHAR(24),
		@TheasoftVersion VARCHAR(24),
		@IsAutoUpdateEnabled BIT,
		@AutoUpdatePath VARCHAR(255),
		@FrameworkInfo VARCHAR(MAX),
		@OSInfo VARCHAR(100) = NULL,
		@FrameworkVersion VARCHAR(24) = NULL
	AS
BEGIN
	DECLARE  @ComputerId INT
	DECLARE  @UserId INT
	SET @UserId = 0
	SET @ComputerId = 0
	SELECT @ComputerId = ComputerId FROM Computer WHERE Name = @ComputerName
	SELECT @UserId = UserID FROM Users WHERE  UserName = CURRENT_USER

	IF @UserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @UserId = UserID FROM Users WHERE  UserName = CURRENT_USER
	END

	IF @ComputerId > 0
		BEGIN
			UPDATE Computer SET theasoftVersion = @TheasoftVersion, OSVersion = @OSVersion, AutoUpdatePath = @AutoUpdatePath, FrameworkInfo = @FrameworkInfo,
				            LM = GetDate(), UM = @UserId, OSInfo = @OSInfo, FrameworkVersion = @FrameworkVersion, IsAutoUpdateEnabled = @IsAutoUpdateEnabled
			WHERE  ComputerId = @ComputerId
		END
	ELSE
		BEGIN
			INSERT INTO Computer (Name, theasoftVersion, OSVersion,AutoUpdatePath, FrameworkInfo, LC, UC, LM, UM, OSInfo, FrameworkVersion, IsAutoUpdateEnabled) 
				VALUES (@ComputerName, @TheasoftVersion, @OSVersion, @AutoUpdatePath, @FrameworkInfo, GetDate(), @UserId, GetDate(), @UserId, @OSInfo, @FrameworkVersion, @IsAutoUpdateEnabled) 

			SELECT @ComputerId = ISNULL(scope_identity(),0)
		END	

		UPDATE Users SET LastLoginDate = GetDate(), LastLoginComputerId = @ComputerId WHERE UserID  = @UserId
END
GO

--#endregion SH 2021-10-11 In LogLogin wird IsAutoUpdateEnabled nicht aktualisiert

--#region
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RoleJobStepCategories') AND [name] = 'IsCostumeStep')
BEGIN
	EXEC('UPDATE RoleJobStepCategories SET Module = 1024 WHERE IsCostumeStep = 1')
	EXEC('ALTER TABLE RoleJobStepCategories DROP CONSTRAINT DF_RoleJobStepCategories_IsCostumeStep')
	EXEC('ALTER TABLE RoleJobStepCategories DROP COLUMN IsCostumeStep')
END
GO
--#endregion 


--#region Measure Groups
IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name] = 'MeasureGroups')
BEGIN
	PRINT 'Create MeasureGroups'
	CREATE TABLE dbo.MeasureGroups(
		MeasureGroupId INT IDENTITY(1,1) NOT NULL,
		LevelNumber VARCHAR(8) NOT NULL,
		[Name] VARCHAR(64) NOT NULL,
		Note VARCHAR(254) SPARSE NULL,
		ParentMeasureGroupId INT NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureGroups_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureGroups_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT PK_MeasureGroupId PRIMARY KEY CLUSTERED (MeasureGroupId) ON [PRIMARY]
    ) ON [PRIMARY]
	CREATE UNIQUE INDEX IX_MeasureGroups_Name ON MeasureGroups (Name) ON [PRIMARY]

	GRANT SELECT ON MeasureGroups TO [public]
	GRANT INSERT, UPDATE, DELETE ON MeasureGroups TO [StaffAdmin]
	
	CREATE TABLE dbo.MeasureGroupContent(
		MeasureGroupContentId INT IDENTITY(1,1) NOT NULL,
		MeasureGroupId INT NOT NULL,
		MeasureTypeId INT NOT NULL,
		Note VARCHAR(254) SPARSE NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureGroupContentId_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureGroupContentId_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT FK_MeasureGroupContent_MeasureGroups FOREIGN KEY(MeasureGroupId)
			REFERENCES MeasureGroups (MeasureGroupId) ON DELETE CASCADE,
		CONSTRAINT FK_MeasureGroupContent_MeasureTypes FOREIGN KEY(MeasureTypeId)
			REFERENCES MeasureTypes (MeasureTypeId) ON DELETE CASCADE,
		CONSTRAINT PK_MeasureGroupContentId PRIMARY KEY NONCLUSTERED (MeasureGroupContentId) ON [PRIMARY]
    ) ON [PRIMARY]

	CREATE UNIQUE CLUSTERED INDEX IX_MeasureGroupContent_MeasureGroupId_MeasureTypeId ON MeasureGroupContent (MeasureGroupId, MeasureTypeId) ON [PRIMARY]

	
	GRANT SELECT ON MeasureGroupContent TO [public]
	GRANT INSERT, UPDATE, DELETE ON MeasureGroupContent TO [StaffAdmin]
	
	CREATE TABLE ContractMeasureGroups(
		ContractMeasureGroupsId INT IDENTITY(1,1) NOT NULL,
		MeasureGroupId INT NOT NULL,
		ContractId INT NOT NULL,
		StartDate DATE SPARSE NULL,
		EndDate DATE SPARSE NULL,
		Note VARCHAR(254) SPARSE NULL,
		LM SMALLDATETIME NOT NULL CONSTRAINT DF_ContractMeasureGroups_LM DEFAULT GETDATE(),
		UM INT NULL,
		LC SMALLDATETIME NOT NULL CONSTRAINT DF_ContractMeasureGroups_LC DEFAULT GETDATE(),
		UC INT NULL,
		CONSTRAINT FK_ContractMeasureGroups_MeasureGroups FOREIGN KEY(MeasureGroupId)
			REFERENCES MeasureGroups (MeasureGroupId) ON DELETE CASCADE,
		CONSTRAINT FK_ContractMeasureGroups_Contracts FOREIGN KEY(ContractId)
			REFERENCES Contracts (ContractId) ON DELETE CASCADE,
		CONSTRAINT PK_MeasureGroupContents PRIMARY KEY NONCLUSTERED (ContractMeasureGroupsId) ON [PRIMARY]
    ) ON [PRIMARY]

	CREATE UNIQUE CLUSTERED INDEX IX_ContractMeasureGroups_ContractId_MeasureGroupId ON ContractMeasureGroups (ContractId, MeasureGroupId) ON [PRIMARY]
		
	GRANT SELECT ON ContractMeasureGroups TO [public]

	ALTER TABLE PersonRequiredMeasureTypes ADD ContractId INT NULL
		
	ALTER TABLE PersonRequiredMeasureTypes WITH CHECK ADD CONSTRAINT FK_PersonRequiredMeasureTypes_Contracts FOREIGN KEY(ContractId)
	REFERENCES Contracts  (ContractId) ON DELETE SET NULL

	CREATE INDEX IX_PersonRequiredMeasureTypes_ContractId ON PersonRequiredMeasureTypes (ContractId) ON [PRIMARY]
 
 END
 GO 
 IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].GetContractsInternal')) DROP PROCEDURE dbo.GetContractsInternal 
 GO
 CREATE PROCEDURE [dbo].[GetContractsInternal]
	@condition VARCHAR(MAX),
	@joins INT,
	@include INT,
	@userId INT,
	@orContact INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	IF (@include <> 0)
	BEGIN 
		CREATE TABLE #Contract (ContractId INT NOT NULL PRIMARY KEY , OwnerGroupId INT NOT NULL)
	END

	--Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben
	if (@include <> 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #Contract SELECT v.ContractId, v.OwnerGroupId   '
		END	
	ELSE
		BEGIN
			SET @SQLQuery = 'SELECT *'
		END

	SET @SQLQuery = @SQLQuery + ' FROM Contracts AS v '

	IF (@joins&1 = 1)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN Persons AS P ON v.PersonId = p.PersonId '

	IF (@joins&2 = 2)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN OwnerGroups AS g ON v.OwnerGroupId = g.OwnerGroupId '

	IF (@joins&4 = 4)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractTypes AS vv ON vv.ContractTypeId = v.ContractTypeId '

	IF (@joins&8 = 8)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN ContractDetails vd ON vd.ContractId = v.ContractId '

	IF (@joins&16 = 16)
		SET @SQLQuery = @SQLQuery + 'INNER JOIN PersonDetails pd ON v.PersonId = pd.PersonId '

	DECLARE @securetyWhere AS NVARCHAR(MAX)
	SET @securetyWhere = ' EXISTS (SELECT * FROM Permissions WHERE UserId = ' + CAST(@userId AS VARCHAR(MAX)) +' AND v.OwnerGroupId = Permissions.OwnerGroupId AND PermissionArea IN (1, 5))'
	IF (@orContact <> 0)	SET @securetyWhere = '(' + @securetyWhere + ' OR v.PersonId = ' + CAST(@orContact AS VARCHAR(MAX)) + ')'

	SET @SQLQuery = @SQLQuery+ ' WHERE ' + @securetyWhere

	IF (@condition IS NOT NULL  AND @condition <> '')
	SET @SQLQuery = @SQLQuery + ' AND ' + @condition 

	EXECUTE sp_Executesql @SQLQuery

	--Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
	IF (@include <> 0) 
	BEGIN
		SELECT * FROM Contracts AS V INNER JOIN #Contract ON v.ContractId = #Contract.ContractId 
	END
	ELSE
	BEGIN
		RETURN 
	END

	IF (@include&1 = 1) --Alle zugeordneten Perso Verträge
		SELECT NULL AS [#1], ContractDepartments.*
		FROM ContractDepartments
			INNER JOIN #Contract ON ContractDepartments.ContractId = #Contract.ContractId

	IF (@include&4 = 4)
	SELECT NULL AS [#4],
		vr.ContractId, vr.RoleId, vr.ContractEngagementId, vr.ProductionId, vr.StartDate, vr.EndDate, vr.RehearsalsCompensatedByPerformance, vr.CompensatedRehearselDays, vr.ProjectedPerformanceCount, vr.LM, vr.UM, vr.LC, vr.UC 
	FROM  
		ContractEngagements AS vr 
				INNER JOIN #Contract ON vr.ContractId = #Contract.ContractId
				INNER JOIN Permissions AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.OwnerGroupId AND u.PermissionArea = 1

	IF (@include&8 = 8) 
		SELECT NULL AS [#8], ContractDetails.*
		FROM ContractDetails
			INNER JOIN #Contract ON ContractDetails.ContractId = #Contract.ContractId

	IF (@include&16 = 16)
		SELECT NULL AS [#16], ContractBonus.* 
		FROM ContractBonus 
			INNER JOIN #Contract ON ContractBonus.ContractId = #Contract.ContractId

	IF (@include&32 = 32)
		SELECT NULL AS [#32], Contract_Qualification_Person.*
		FROM Contract_Qualification_Person
			INNER JOIN #Contract ON Contract_Qualification_Person.ContractId = #Contract.ContractId

	IF (@include&64 = 64)
		SELECT NULL AS [#64], ContractFields.*
		FROM ContractFields
			INNER JOIN #Contract ON ContractFields.ContractId = #Contract.ContractId

	IF (@include&128 = 128)
		SELECT NULL AS [#128], TimeAccountUsage.*
		FROM TimeAccountUsage
			INNER JOIN #Contract ON TimeAccountUsage.ContractId = #Contract.ContractId

	IF (@include&256 = 256)
		SELECT NULL AS [#256], ContractPartTimePeriods.*
		FROM ContractPartTimePeriods
			INNER JOIN #Contract ON ContractPartTimePeriods.ContractId = #Contract.ContractId

	IF (@include&512 = 512)
		SELECT NULL AS [#512], ContractWorkingTimeModels.*
		FROM ContractWorkingTimeModels
			INNER JOIN #Contract ON ContractWorkingTimeModels.ContractId = #Contract.ContractId

	IF (@include&1024 = 1024)
		SELECT NULL AS [#1024], ContractSalaryRules.*
		FROM ContractSalaryRules
			INNER JOIN #Contract ON ContractSalaryRules.ContractId = #Contract.ContractId
			INNER JOIN Permissions AS u ON u.UserId = @userId AND #Contract.OwnerGroupId = u.OwnerGroupId 
		WHERE u.PermissionArea = 1 AND u.OptionsFlag&1 = 1

	IF (@include&2048 = 2048)
		SELECT NULL AS [#2048], ContractMeasureGroups.*
		FROM ContractMeasureGroups
			INNER JOIN #Contract ON ContractMeasureGroups.ContractId = #Contract.ContractId
	DROP TABLE #Contract
END
GO
GRANT EXECUTE ON GetContractsInternal TO Public
GO

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbContractMeasureGroups_Update') AND type <> 'U') DROP VIEW dbo.[AbContractMeasureGroups_Update]
GO

CREATE VIEW [dbo].[AbContractMeasureGroups_Update]
AS 
SELECT * FROM ContractMeasureGroups WHERE
	ContractId IN 
	(
		SELECT Contracts.ContractId 
		FROM [Permissions] AS CoPerMi
			INNER JOIN	Users		ON CoPerMi.Userid = Users.Userid 
			INNER JOIN	Contracts	ON Contracts.OwnerGroupId = CoPerMi.OwnerGroupId 
		WHERE Username = CURRENT_USER AND PermissionArea = 1 AND CoPerMi.HasWritePermission = 1
	UNION 
		SELECT Contracts.ContractId 
		FROM [Permissions] AS PersonPerMi
			INNER JOIN	Users		ON PersonPerMi.Userid = Users.Userid 
			INNER JOIN	Persons		ON PersonPerMi.OwnerGroupId = Persons.OwnerGroupId 
			INNER JOIN	Contracts	ON Contracts.PersonId = Persons.PersonId 
		WHERE Username = CURRENT_USER AND PermissionArea = 0 AND PersonPerMi.OptionsFlag&131072 = 131072
	 )

WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON [AbContractMeasureGroups_Update] TO PUBLIC
GO
--#endregion Measure Groups
--#region Scenes
ALTER VIEW [dbo].[Scenes_Update]
AS 
SELECT * FROM Scenes 
WHERE ActId IN (
				SELECT  ptf.ProductionTimeFlowId  FROM 	ProductionTimeFlow AS ptf 
					INNER JOIN Productions AS P ON ptf.ProductionId= P.ProductionId
					INNER  JOIN	(SELECT OwnerGroupId, HasWritePermission FROM [Permissions] AS ug
									INNER JOIN Users ON ug.Userid = Users.Userid 
								WHERE Username = CURRENT_USER  
									AND PermissionArea = 3 
									AND (HasWritePermission = 1 OR ug.OptionsFlag&2=2)
								) AS UG ON p.OwnerGroupId = ug.OwnerGroupId)
WITH CHECK OPTION
GO

ALTER VIEW [dbo].[Roles_Scenes_Update]
AS 
SELECT * 
FROM Roles_Scenes 
WHERE RoleId IN (
				SELECT RoleId FROM Roles AS R 
					INNER JOIN (
								SELECT OwnerGroupId, HasWritePermission 
								FROM [Permissions] AS ug INNER JOIN	Users ON ug.Userid = Users.Userid 
								WHERE Username = CURRENT_USER AND PermissionArea = 4 AND (HasWritePermission = 1 OR ug.OptionsFlag&32=32)
								) AS UGS 
							ON r.OwnerGroupId = UGS.OwnerGroupId)
WITH CHECK OPTION
GO
IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 216 OR (Minor = 216 AND Build < 1)))))
BEGIN
	PRINT '[Permissions] '
	UPDATE [Permissions] SET OptionsFlag = OptionsFlag|32 WHERE HasWritePermission = 1 AND PermissionArea = 4 
END

GO
--#endregion Scenes
--#region Measure Groups Content
IF EXISTS (SELECT * FROM sysobjects o WHERE o.id = OBJECT_ID(N'dbo.[GetMeasureContentByMeasureGroup]') AND xtype = 'IF') DROP Function dbo.[GetMeasureContentByMeasureGroup]
GO
CREATE FUNCTION [dbo].[GetMeasureContentByMeasureGroup] (@MeasureGroupId INT)
RETURNS TABLE
AS
RETURN WITH sub(MeasureGroupId, ParentMeasureGroupId, name, MLevel) AS
					(
			SELECT MeasureGroupId, ParentMeasureGroupId, name, 0 AS MLevel
					FROM dbo.MeasureGroups
					WHERE MeasureGroupId = @MeasureGroupId

					UNION ALL

					SELECT e.MeasureGroupId, e.ParentMeasureGroupId, e.name, MLevel + 1
						FROM dbo.MeasureGroups AS e
						INNER JOIN sub AS d
						ON e.MeasureGroupId = d.ParentMeasureGroupId AND MLevel < 10
				)
		SELECT MeasureGroupContent.MeasureGroupId, MeasureGroupContent.MeasureTypeId
		FROM sub INNER JOIN MeasureGroupContent ON sub.MeasureGroupId = MeasureGroupContent.MeasureGroupId
GO
GRANT SELECT  ON GetMeasureContentByMeasureGroup TO PUBLIC

GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.[AbPersonRequiredMeasureTypes_Update]') AND type <> 'U') DROP VIEW dbo.[AbPersonRequiredMeasureTypes_Update]
GO

CREATE VIEW [dbo].[AbPersonRequiredMeasureTypes_Update]
AS 
SELECT
	prm.*
FROM
	PersonRequiredMeasureTypes prm
WHERE 
	prm.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN [Permissions] AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			p.OptionsFlag&pp.OptionsFlag&2 = 2
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
WITH CHECK OPTION
GO
REVOKE UPDATE, INSERT, DELETE ON PersonRequiredMeasureTypes TO PUBLIC
GRANT SELECT, UPDATE, INSERT, DELETE ON [AbPersonRequiredMeasureTypes_Update] TO PUBLIC
GO
--#endregion Measure Groups Content
--#region 20211124
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MeasureTypes') AND [name] = 'EstimatedCosts')
BEGIN
	ALTER TABLE MeasureTypes ADD EstimatedCosts DECIMAL(9, 2) NULL
	ALTER TABLE MeasureTypes ADD CarriedOutByPersonId INT NULL
	ALTER TABLE MeasureTypes ADD IsExtern BIT NOT NULL CONSTRAINT DF_MeasureTypes_IsExtern DEFAULT 0

	ALTER TABLE MeasureTypes WITH CHECK ADD CONSTRAINT FK_MeasureTypes_Persons FOREIGN KEY(CarriedOutByPersonId)
	REFERENCES Persons (PersonId) ON DELETE SET NULL
END
GO
--#endregion
--#region TK 2021-11-24
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.[AbPersP]') AND type <> 'U') DROP VIEW dbo.AbPersP
GO
IF NOT EXISTS(SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonAdditionalDataTypes') AND [name] = 'Code')
BEGIN
	PRINT 'PersonAdditionalDataTypes Code'
	ALTER TABLE PersonAdditionalDataTypes ADD Code VARCHAR(20) NULL
END
GO
--#endregion
--#region AP 2021-11-24 Biografie und Veröffentlichungskennzeichen in Felder auslagern

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonFields') AND name = 'ShowOnPage')
BEGIN
	PRINT 'Adding column PersonFields.ShowOnPage...'
	ALTER TABLE PersonFields ADD ShowOnPage TINYINT NOT NULL CONSTRAINT DF_PersonoFields_ShowOnPage DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PersonFields') AND name = 'KnownField')
BEGIN
	PRINT 'Adding column PersonFields.KnownField...'
	ALTER TABLE PersonFields ADD KnownField TINYINT NULL
	ALTER TABLE PersonFieldData ALTER COLUMN TextValue NVARCHAR(MAX) NULL
	DECLARE @country VARCHAR(20)
	SELECT  @country = DataValue FROM Settings WHERE Section = 'Adresse' AND KeyName = 'Country'
	DECLARE @bio VARCHAR(100)
	DECLARE @bio_en VARCHAR(100)
	DECLARE @inWeb VARCHAR(100)
	DECLARE @description VARCHAR(1024)

	IF @country = 'FI'
		BEGIN--Finnisch
		SET @bio = 'Biografia'
		SET @bio_en = 'Biografia englanti'
		SET @inWeb = 'Publish'
		SET @description = 'also publish online (no cast or contract necessary)'
		END
	ELSE IF @country = 'EN'
		BEGIN--Englisch
		SET @bio = 'Biographie'
		SET @bio_en = 'Biographie en'
		SET @inWeb = 'Publish'
		SET @description = 'also publish online (no cast or contract necessary)'
		END
	ELSE IF @country = 'F' OR @country = 'BE'
		BEGIN--Französisch
		SET @bio = 'Biographie'
		SET @bio_en = 'Biografie anglais'
		SET @inWeb = 'Publier'
		SET @description = 'également publier sue Internet (aucune distribution et aucun contrat nest nécessaire)'
		END
	ELSE IF @country = 'NL'
		BEGIN--Niederländisch
		SET @bio = 'Biografie'
		SET @bio_en = 'Biografie Engels'
		SET @inWeb = 'Publiceren'
		SET @description = 'bijkomend op het internet publiceren (geen verdeling of contract nodig)'
		END

	ELSE IF @country = 'CZ'
		BEGIN--Tschechisch
		SET @bio = 'Biografie'
		SET @bio_en = 'Biografie anglicky'
		SET @inWeb = 'zveřejnt'
		SET @description = 'dodatečně zveřejnt na Internetu (neni nutné obsazeni nebo smlouva)'
		END
	ELSE
		BEGIN--Deutsch
		SET @bio = 'Biografie'
		SET @bio_en = 'Biografie en'
		SET @inWeb = 'Veröffentlichen'
		SET @description = 'zusätzlich im Internet veröffentlichen (keine Besetzung oder Vertrag notwendig)'
		END

	--Veröffentlichen (InWeb) Checkbox
	EXEC(' INSERT INTO PersonFields(Name, Code, Sort, LM, LC, UM, UC, DataType, Settings, Note, ShowOnPage, KnownField)
	VALUES (''' + @inWeb + ''', ''Publish'', 0,GETDATE(), GETDATE(), -1, -1, 4, NULL , ''' + @description + '''
			, 1, 3)')					

	EXEC('DECLARE @id INT
	SELECT @id = PersonFieldId FROM PersonFields WHERE KnownField = 3
	INSERT INTO PersonFieldData (PersonFieldId, PersonId, TextValue, LM, LC, UM, UC) 
	SELECT @id, PersonId, ''True'' , LM,LC,ISNULL(UM,-1),ISNULL(UC,-1) 
	FROM PersonDetails WHERE ISNULL(InWeb, 0) = 1
	')
	-- Biografie anlegen
	EXEC(' INSERT INTO PersonFields(Name, Code, Sort, LM, LC, UM, UC, DataType, Settings, ShowOnPage, KnownField)
	VALUES (''' + @bio + ''', ''Bio'', 1 ,GETDATE(), GETDATE(), -1, -1, 1,
					''<MultiLineTextFieldSettings><ValidationAttributes /><LookupValues /><MinimumVisibleLines>25</MinimumVisibleLines></MultiLineTextFieldSettings>''
					, 1, 1)
					')
	EXEC('DECLARE @id INT
	SELECT @id = PersonFieldId FROM PersonFields WHERE KnownField = 1
	INSERT INTO PersonFieldData (PersonFieldId, PersonId, TextValue, LM, LC, UM, UC) SELECT @id, PersonId, MemoExtern, LM,LC,ISNULL(UM,-1),ISNULL(UC,-1) 
	FROM PersonDetails WHERE NOT MemoExtern IS NULL AND MemoExtern <> ''''
	')

	--Biografie englisch nur anlegen wenn min. 1 englischer Eintrag vorhanden ist
	DECLARE @count int
	SELECT @count = count(PersonId) FROM PersonDetails WHERE MemoExtern_en IS NOT NULL
	IF @count > 0
	BEGIN
		EXEC(' INSERT INTO PersonFields(Name, Code, Sort, LM, LC, UM, UC, DataType, Settings, ShowOnPage, KnownField)
		VALUES (''' + @bio_en + ''', ''BioEn'', 2 ,GETDATE(), GETDATE(), -1, -1, 1,
					''<MultiLineTextFieldSettings><ValidationAttributes /><LookupValues /><MinimumVisibleLines>25</MinimumVisibleLines></MultiLineTextFieldSettings>''
					, 1, 2)
					')

		EXEC('DECLARE @id INT
		SELECT @id = PersonFieldId FROM PersonFields WHERE KnownField = 2
		INSERT INTO PersonFieldData (PersonFieldId, PersonId, TextValue, LM, LC, UM, UC) SELECT @id, PersonId, MemoExtern_en, LM,LC,ISNULL(UM,-1),ISNULL(UC,-1) 
		FROM PersonDetails WHERE NOT MemoExtern_en IS NULL AND MemoExtern_en <> ''''
		')
	END		
END
GO
IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.PersonFields') AND o.Name = 'IX_PersonFields_KnownField')
BEGIN
	CREATE UNIQUE INDEX IX_PersonFields_KnownField ON PersonFields (KnownField) WHERE KnownField IS NOT NULL
END
GO
--#endregion
--#region DH - 20211209 Views für MeasureParticipations

--#region AbMeasureParticipation

IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbMeasureParticipations') AND type <> 'U') DROP VIEW dbo.[AbMeasureParticipations]
GO
CREATE VIEW [dbo].[AbMeasureParticipations]
AS 
SELECT
	mp.*,(SELECT COUNT(*) AS FollowerCount FROM  MeasureParticipations mps 
								WHERE mps.PersonId = mp.PersonId 
									AND mps.ParticipationDate > mp.ParticipationDate 
									AND mps.MeasureTypeId = mp.MeasureTypeId) AS FollowerCount 
FROM
	MeasureParticipations mp
WHERE 
	mp.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			p.OptionsFlag&pp.OptionsFlag&65536 = 65536
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
GO
GRANT SELECT ON [AbMeasureParticipations] TO PUBLIC
GO
--#endregion AbMeasureParticipation
--#region AbMeasureParticipation_Update
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbMeasureParticipations_Update') AND type <> 'U') DROP VIEW dbo.[AbMeasureParticipations_Update]
GO
CREATE VIEW [dbo].[AbMeasureParticipations_Update]
AS 
SELECT
	mp.*
FROM
	MeasureParticipations mp
WHERE 
	mp.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			p.OptionsFlag&pp.OptionsFlag&131072 = 131072
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON [AbMeasureParticipations_Update] TO PUBLIC
GO
--#endregion AbMeasureParticipation_Update
--#region Update PersonPermissions -Measure
IF EXISTS (SELECT * FROM NvData WHERE  ByModulScript = 1 AND (Major < 4 OR (Major = 4 AND (Minor < 216 OR (Minor = 216 AND Build < 5)))))
BEGIN
	UPDATE PersonPermissions SET OptionsFlag = OptionsFlag|196608 WHERE OptionsFlag&2=2
	UPDATE [Permissions]	 SET OptionsFlag = OptionsFlag|65536  WHERE OptionsFlag&2=2			AND PermissionArea = 0
	UPDATE [Permissions]	 SET OptionsFlag = OptionsFlag|131072 WHERE HasWritePermission = 1  AND PermissionArea = 0
END
GO
--#endregion Update PersonPermissions -Measure
--#endregion Views für MeasureParticipations
--#region View Für PersonRequiredMeasures anpassen
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbPersonRequiredMeasureTypes') AND type <> 'U') DROP VIEW dbo.[AbPersonRequiredMeasureTypes]
GO
CREATE VIEW [dbo].[AbPersonRequiredMeasureTypes]
AS 
SELECT
	prm.*
FROM
	PersonRequiredMeasureTypes prm
WHERE 
	prm.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN [Permissions] AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			(p.OptionsFlag&pp.OptionsFlag&131072 = 131072 OR p.OptionsFlag&pp.OptionsFlag&65536=65536 OR (p.OptionsFlag&131072=131072 AND pp.OptionsFlag&65536=65536) OR (p.OptionsFlag&65536=65536  AND pp.OptionsFlag&131072=131072) )
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
GO
GRANT SELECT ON [AbPersonRequiredMeasureTypes] TO PUBLIC
GO
ALTER VIEW [dbo].[AbPersonRequiredMeasureTypes_Update]
AS 
SELECT
	prm.*
FROM
	PersonRequiredMeasureTypes prm
WHERE 
	prm.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN [Permissions] AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			p.OptionsFlag&pp.OptionsFlag&131072 = 131072
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
WITH CHECK OPTION
GO
--#endregion View Für PersonRequiredMeasures anpassen
--#region ProductionFields_Genres
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('ProductionFieldTypes') AND [name] = 'FilterSettings')
BEGIN
	Print 'Create ProductionFieldTypeFilterSettings'
	Alter Table ProductionFieldTypes ADD FilterSettings XML Null
END
GO
--#endregion ProductionFields_Genres

--#region AP 2021-12-01 Kostenplan für die Kronberg Academy 17606, 17607, 17608

------------------ CREATE

-- CostPlans --

	PRINT 'Creating table CostPlans if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'CostPlans'))
	BEGIN
		CREATE TABLE dbo.CostPlans(
		CostPlanId				INT IDENTITY(1,1) NOT NULL,
		OwnerGroupId			INT NOT NULL,
		CostUnitId				INT NOT NULL,
		[Name]					VARCHAR (100) NOT NULL,
		Sponsor_1_Name			VARCHAR (100) NULL,
		Sponsor_2_Name			VARCHAR (100) NULL,
		Sponsor_3_Name			VARCHAR (100) NULL,
		Sponsor_4_Name			VARCHAR (100) NULL,
		Sponsor_5_Name			VARCHAR (100) NULL,
		[StartDate]				DATE NOT NULL,
		[EndDate]				DATE NOT NULL,
		LM						SMALLDATETIME NOT NULL CONSTRAINT DF_CostPlans_LM DEFAULT GETDATE(),
		UM						INT NULL,
		LC						SMALLDATETIME NOT NULL CONSTRAINT DF_CostPlans_LC DEFAULT GETDATE(),
		UC						INT NULL,
		CONSTRAINT PK_CostPlans PRIMARY KEY CLUSTERED (
		CostPlanId ASC
		))

		CREATE UNIQUE INDEX IX_CostPlan_Name ON CostPlans ([Name])
	END
	GO

--	CostPlanPositions --
	
	PRINT 'Creating table CostPlansPositions if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'CostPlanPositions'))
	BEGIN
		CREATE TABLE dbo.CostPlanPositions(
		CostPlanPositionId	INT IDENTITY(1,1) NOT NULL,
		Position			SMALLINT NOT NULL CONSTRAINT DF_CostPlans_Position DEFAULT 0,
		PositionText		VARCHAR (256) NULL,
		CostPlanId			INT NOT NULL,
		BudgetItemId		INT NOT NULL,
		CostCenterId		INT NOT NULL,
		ContractId			INT NULL,
		TimeAccountId		INT NULL,
		ReceiptNumber		VARCHAR (100) NULL,
		SupplierId			INT NULL,
		BillNumber			VARCHAR (100) NULL,
		PlanCost			DECIMAL (9,2) NULL,
		AdjustedCost		DECIMAL (9,2) NULL,
		IsCost				DECIMAL (9,2) NULL,
		DayOfPayment		DATE NULL,
		Sponsor_1_Sum		DECIMAL (9,2) NULL,
		Sponsor_2_Sum		DECIMAL (9,2) NULL,
		Sponsor_3_Sum		DECIMAL (9,2) NULL,
		Sponsor_4_Sum		DECIMAL (9,2) NULL,
		Sponsor_5_Sum		DECIMAL (9,2) NULL,
		Note				VARCHAR (1024) SPARSE NULL,
		LM					SMALLDATETIME NOT NULL CONSTRAINT DF_CostPlanPositions_LM DEFAULT GETDATE(),
		UM					INT NULL,
		LC					SMALLDATETIME NOT NULL CONSTRAINT DF_CostPlanPositions_LC DEFAULT GETDATE(),
		UC					INT NULL,
		CONSTRAINT PK_CostPlanPositions PRIMARY KEY NONCLUSTERED (
		CostPlanPositionId ASC
		))
		CREATE UNIQUE CLUSTERED INDEX IX_CostPlanPositions_CostPlanId_CostPlanPositionId ON CostPlanPositions (CostPlanId, CostPlanPositionId)
	END
	GO

	PRINT 'Creating table RuleCriteriaSelections if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'RuleCriteriaSelections'))
	BEGIN
		CREATE TABLE dbo.RuleCriteriaSelections(
		RuleCriteriaSelectionId	INT IDENTITY(1,1) NOT NULL,
		RuleType				TINYINT NOT NULL,
		OrderIndex				SMALLINT NOT NULL,
		StartDate				DATE NULL,
		EndDate					DATE NULL,
		CriteriaSetting			XML NULL,
		ID						INT NOT NULL,
		Note					VARCHAR(1024) NULL,
		LC						SMALLDATETIME NOT NULL CONSTRAINT DF_RuleCriteriaSelections_LC DEFAULT GETDATE(),
		UC						INT NULL,
		LM						SMALLDATETIME NOT NULL CONSTRAINT DF_RuleCriteriaSelections_LM DEFAULT GETDATE(),
		UM						INT NULL,
		CONSTRAINT PK_RuleCriteriaSelections PRIMARY KEY NONCLUSTERED(RuleCriteriaSelectionId ASC) ON [PRIMARY]) ON [PRIMARY]
	END
	GO
	
	IF NOT EXISTS (SELECT * FROM  sysindexes o WHERE o.id = OBJECT_ID(N'dbo.RuleCriteriaSelections') AND o.Name = 'IX_RuleCriteriaSelections_RuleType')
	BEGIN
		CREATE CLUSTERED INDEX IX_RuleCriteriaSelections_RuleType ON RuleCriteriaSelections (RuleType, OrderIndex) ON [PRIMARY]
	END
	GO

	BEGIN
		GRANT SELECT ON RuleCriteriaSelections TO Public
		GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO DispoAdmin
		GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO PersoAdmin
		GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO OrchesterAdmin
		GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO BallettAdmin
		GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO StatisterieAdmin
	END
	GO

	IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('RuleCriteriaSelections') AND [name] = 'ID')
BEGIN
	Alter Table RuleCriteriaSelections ADD Id INT
END

	IF NOT EXISTS (select * from RuleCriteriaSelections)
	BEGIN
		PRINT 'Migration from ContractType_Department to RuleCriteriaSelections'
		INSERT INTO RuleCriteriaSelections (RuleType, ID, OrderIndex, CriteriaSetting, LM, LC, UM, UC) 
		SELECT 1, BudgetItemId, 100, 
				'<RuleCriteriaBudgetItemSettings ContractTypeNodeNames="' + a.ContractType + '"' +
				' DepartmentNodeNames="' +  a.Department + '"/>',
				LM, LC, UM, UC
				FROM (
						SELECT BudgetItemId, 
							Department = STUFF((SELECT DISTINCT ' DepartmentId' + CAST(DepartmentId as VARCHAR(10))
							   FROM ContractType_Department b 
							   WHERE b.BudgetItemId = d.BudgetItemId 
							   FOR XML PATH('')), 1, 1, ''),
							ContractType = STUFF((SELECT DISTINCT ' ContractType_' +  CAST(ContractTypeId as VARCHAR(10))
							   FROM ContractType_Department b 
							   WHERE b.BudgetItemId = d.BudgetItemId 
							   FOR XML PATH('')), 1, 1, ''),
							   MIN(ISNULL(LM, '19000101')) AS LM,
							   MIN(ISNULL(LC, '19000101')) AS LC,
							   MIN(ISNULL(UM, -1)) AS UM,
							   MIN(ISNULL(UC, -1)) AS UC
						FROM ContractType_Department AS d
						WHERE NOT BudgetItemId IS NULL
						GROUP BY BudgetItemId 
					) AS a

		INSERT INTO RuleCriteriaSelections (RuleType, id, OrderIndex,  CriteriaSetting, LM, LC, UM, UC) 
		SELECT 2, AllocationGroupId, 100,
				'<RuleCriteriaAllocationGroupSettings ContractTypeNodeNames="' + a.ContractType + '"' +
				' DepartmentNodeNames="' +  a.Department + '"/>',
				LM, LC, UM, UC 
				FROM (
						SELECT AllocationGroupId, 
							Department = STUFF((SELECT DISTINCT ' DepartmentId' + CAST(DepartmentId as VARCHAR(10))
							   FROM ContractType_Department b 
							   WHERE b.AllocationGroupId = d.AllocationGroupId 
							   FOR XML PATH('')), 1, 1, ''),
							ContractType = STUFF((SELECT DISTINCT ' ContractType_' +  CAST(ContractTypeId as VARCHAR(10))
							   FROM ContractType_Department b 
							   WHERE b.AllocationGroupId = d.AllocationGroupId 
							   FOR XML PATH('')), 1, 1, ''),
							   MIN(ISNULL(LM, '19000101')) AS LM,
							   MIN(ISNULL(LC, '19000101')) AS LC,
							   MIN(ISNULL(UM, -1)) AS UM,
							   MIN(ISNULL(UC, -1)) AS UC
						FROM ContractType_Department AS d
						WHERE NOT AllocationGroupId IS NULL
						GROUP BY AllocationGroupId 
					) AS a
				
	END
	GO

------------------ ALTER


	PRINT 'Creating refernces CostPlansPositions to CostCenters if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlanPositions_CostCenters') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlanPositions
		WITH CHECK ADD CONSTRAINT FK_CostPlanPositions_CostCenters FOREIGN KEY(CostCenterId)
		REFERENCES CostCenters (CostCenterId)
	END
	GO

	PRINT 'Creating refernces CostPlans to CostUnits if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlans_CostUnits') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlans
		WITH CHECK ADD CONSTRAINT FK_CostPlans_CostUnits FOREIGN KEY(CostUnitId)
		REFERENCES CostUnits (CostUnitId)
	END
	GO

	PRINT 'Creating refernces CostPlans to OwnerGroups if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlans_OwnerGroups') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlans
		WITH CHECK ADD CONSTRAINT FK_CostPlans_OwnerGroups FOREIGN KEY(OwnerGroupId)
		REFERENCES OwnerGroups (OwnerGroupId)
	END
	GO

	PRINT 'Creating refernces CostPlansPositions to Contracts if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlanPositions_Contracts') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlanPositions
		WITH CHECK ADD CONSTRAINT FK_CostPlanPositions_Contracts FOREIGN KEY(ContractId)
		REFERENCES Contracts (ContractId)
	END
	GO

	PRINT 'Creating refernces CostPlansPositions to BudgetItems if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlanPositions_BudgetItems') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlanPositions
		WITH CHECK ADD CONSTRAINT FK_CostPlanPositions_BudgetItems FOREIGN KEY(BudgetItemId)
		REFERENCES BudgetItems (BudgetItemId)
	END
	GO

	PRINT 'Creating refernces CostPlansPositions to Persons as suppliers if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlanPositions_Suppliers') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlanPositions
		WITH CHECK ADD CONSTRAINT FK_CostPlanPositions_Suppliers FOREIGN KEY(SupplierId)
		REFERENCES Persons (PersonId)
	END
	GO
	PRINT 'Creating refernces CostPlansPositions to TimeAccounts as if not exists...'
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'FK_CostPlanPositions_TimeAccounts') AND type = 'F')
	BEGIN
		ALTER TABLE CostPlanPositions
		WITH CHECK ADD CONSTRAINT FK_CostPlanPositions_TimeAccounts FOREIGN KEY(TimeAccountId)
		REFERENCES TimeAccounts (TimeAccountId)
	END
	GO

	PRINT 'Check constraints on CostPlanPositions...'
	ALTER TABLE CostPlanPositions CHECK CONSTRAINT FK_CostPlanPositions_CostCenters
	ALTER TABLE CostPlans CHECK CONSTRAINT FK_CostPlans_CostUnits
	ALTER TABLE CostPlanPositions CHECK CONSTRAINT FK_CostPlanPositions_Contracts
	ALTER TABLE CostPlanPositions CHECK CONSTRAINT FK_CostPlanPositions_BudgetItems
	ALTER TABLE CostPlanPositions CHECK CONSTRAINT FK_CostPlanPositions_Suppliers
	ALTER TABLE CostPlanPositions CHECK CONSTRAINT FK_CostPlanPositions_TimeAccounts
	ALTER TABLE CostPlans CHECK CONSTRAINT FK_CostPlans_OwnerGroups
	GO

	------------ Views/Rights

	IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'AbCostPlans') AND type <> 'U') DROP VIEW AbCostPlans
	IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'AbCostPlans_Update') AND type <> 'U') DROP VIEW AbCostPlans_Update
	IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'AbCostPlanPositions') AND type <> 'U') DROP VIEW AbCostPlanPositions
	IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'AbCostPlanPositions_Update') AND type <> 'U') DROP VIEW AbCostPlanPositions_Update
	GO

	CREATE VIEW AbCostPlans
	AS 
		SELECT CostPlans.*
		FROM CostPlans
			INNER JOIN Permissions AS p ON CostPlans.OwnerGroupId =  p.OwnerGroupId
			INNER JOIN	Users ON p.Userid = Users.Userid
			WHERE p.PermissionArea = 22 AND  Username = CURRENT_USER
		WITH CHECK OPTION
	GO
	GRANT SELECT ON AbCostPlans TO PUBLIC
	GO

	CREATE VIEW AbCostPlans_Update
	AS 
		SELECT * FROM CostPlans WHERE CostPlanId IN (
		SELECT CostPlans.CostPlanId
		FROM CostPlans 
			INNER JOIN Permissions AS p ON CostPlans.OwnerGroupId = p.OwnerGroupId
			INNER JOIN	Users ON p.Userid = Users.Userid 
			WHERE  p.PermissionArea = 22 AND UserName = CURRENT_USER  AND p.HasWritePermission = 1) 
		WITH CHECK OPTION
	GO
	GRANT SELECT, UPDATE, INSERT, DELETE ON AbCostPlans_Update TO PUBLIC
	GO

	CREATE VIEW AbCostPlanPositions
	AS 
		SELECT CostPlanPositions.*
		FROM CostPlanPositions
			INNER JOIN CostPlans AS cp ON CostPlanPositions.CostPlanId = cp.CostPlanId
			INNER JOIN Permissions As p ON cp.OwnerGroupId = p.OwnerGroupId
			INNER JOIN	Users ON p.Userid = Users.Userid 
			WHERE p.PermissionArea = 22 AND Username = CURRENT_USER
		WITH CHECK OPTION
	GO
	GRANT SELECT ON AbCostPlanPositions TO PUBLIC
	GO

	CREATE VIEW AbCostPlanPositions_Update
	AS 
		SELECT * FROM CostPlanPositions WHERE CostPlanId IN (
		SELECT cp.CostPlanId
		FROM CostPlans AS cp
			INNER JOIN Permissions AS p ON cp.OwnerGroupId = p.OwnerGroupId
			INNER JOIN	Users ON p.Userid = Users.Userid 
			WHERE p.PermissionArea = 22 AND Username = CURRENT_USER AND p.HasWritePermission = 1) 
		WITH CHECK OPTION
	GO
	GRANT SELECT, UPDATE, INSERT, DELETE ON AbCostPlanPositions_Update TO PUBLIC
	GO

--#endregion

--#region
UPDATE Persons SET FirstName = null WHERE FirstName = ''
UPDATE Persons SET LastName = null WHERE LastName = ''
GO
--#endregion

--#region 2021-12-
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MeasureTypes') AND [name] = 'DurationMinutes')
BEGIN
	PRINT 'Add MeasureParticipations'
	ALTER TABLE MeasureParticipations ADD HasAgreement BIT NOT NULL CONSTRAINT DF_MeasureParticipations_HasAgreement DEFAULT 0
	ALTER TABLE MeasureParticipations ADD Agreement_Date DATE SPARSE NULL
	ALTER TABLE MeasureParticipations ADD Agreement_Text VARCHAR(1024) SPARSE NULL

	ALTER TABLE MeasureTypes ADD DurationMinutes			 SMALLINT NULL --?
END
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('WorkAreas') AND [name] = 'DefaultMeasureGroupId')
BEGIN
	PRINT 'Add WorkAreas DefaultMeasureGroupId'
	ALTER TABLE WorkAreas ADD DefaultMeasureGroupId INT NULL
		
	ALTER TABLE WorkAreas WITH CHECK ADD CONSTRAINT FK_WorkAreas_MeasureGroups FOREIGN KEY(DefaultMeasureGroupId)
	REFERENCES MeasureGroups (MeasureGroupId) ON DELETE SET NULL
END
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE [name] = 'MeasureParticipationAttachments')
BEGIN
	PRINT('Add MeasureParticipationAttachments...')
	CREATE TABLE dbo.MeasureParticipationAttachments(
		MeasureParticipationAttachmentId	INT IDENTITY(1, 1) NOT NULL,
		MeasureParticipationId				INT NOT NULL,
		AttachmentId						INT NOT NULL,
		Note								VARCHAR(1024) NULL,
		Sort								INT NOT NULL CONSTRAINT DF_MeasureParticipationAttachments_Sort  DEFAULT (0),
		LC									SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureParticipationAttachments_LC DEFAULT GETDATE(),
		UC									INT NOT NULL,
		LM									SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureParticipationAttachments_LM DEFAULT GETDATE(),
		UM									INT NOT NULL
	 CONSTRAINT PK_MeasureParticipationAttachments PRIMARY KEY NONCLUSTERED (MeasureParticipationAttachmentId ASC) ON [PRIMARY]
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_MeasureParticipationAttachments_MeasureParticipationId  ON MeasureParticipationAttachments (MeasureParticipationId) ON [PRIMARY]

	ALTER TABLE dbo.MeasureParticipationAttachments  WITH CHECK ADD  CONSTRAINT FK_MeasureParticipationAttachments_Attachments FOREIGN KEY(AttachmentId)
		REFERENCES dbo.Attachments (AttachmentId)
	ALTER TABLE dbo.MeasureParticipationAttachments CHECK CONSTRAINT FK_MeasureParticipationAttachments_Attachments
	
	ALTER TABLE dbo.MeasureParticipationAttachments  WITH CHECK ADD  CONSTRAINT FK_MeasureParticipationAttachments_MeasureParticipations FOREIGN KEY(MeasureParticipationId)
		REFERENCES dbo.MeasureParticipations (MeasureParticipationId)
	ALTER TABLE dbo.MeasureParticipationAttachments CHECK CONSTRAINT FK_MeasureParticipationAttachments_MeasureParticipations

	GRANT INSERT, UPDATE, DELETE ON MeasureParticipationAttachments TO DataService
	GRANT INSERT, UPDATE, DELETE ON TourAttachments TO DataService
END
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name] = 'MeasureTypeAttachments')
BEGIN
	PRINT('Add MeasureTypeAttachments...')
	CREATE TABLE dbo.MeasureTypeAttachments(
		MeasureTypeAttachmentId	INT IDENTITY(1, 1) NOT NULL,
		MeasureTypeId				INT NOT NULL,
		AttachmentId						INT NOT NULL,
		Note								VARCHAR(1024) NULL,
		Sort								INT NOT NULL CONSTRAINT DF_MeasureTypeAttachments_Sort  DEFAULT (0),
		LC									SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypeAttachments_LC DEFAULT GETDATE(),
		UC									INT NOT NULL,
		LM									SMALLDATETIME NOT NULL CONSTRAINT DF_MeasureTypeAttachments_LM DEFAULT GETDATE(),
		UM									INT NOT NULL
	 CONSTRAINT PK_MeasureTypeAttachments PRIMARY KEY NONCLUSTERED (MeasureTypeAttachmentId ASC) ON [PRIMARY]
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_MeasureTypeAttachments_MeasureTypeId  ON MeasureTypeAttachments (MeasureTypeId) ON [PRIMARY]

	ALTER TABLE dbo.MeasureTypeAttachments  WITH CHECK ADD  CONSTRAINT FK_MeasureTypeAttachments_Attachments FOREIGN KEY(AttachmentId)
		REFERENCES dbo.Attachments (AttachmentId)
	ALTER TABLE dbo.MeasureTypeAttachments CHECK CONSTRAINT FK_MeasureTypeAttachments_Attachments
	
	ALTER TABLE dbo.MeasureTypeAttachments  WITH CHECK ADD  CONSTRAINT FK_MeasureTypeAttachments_MeasureTypes FOREIGN KEY(MeasureTypeId)
		REFERENCES dbo.MeasureTypes (MeasureTypeId)
	ALTER TABLE dbo.MeasureTypeAttachments CHECK CONSTRAINT FK_MeasureTypeAttachments_MeasureTypes

	GRANT INSERT, UPDATE, DELETE ON MeasureParticipationAttachments TO DataService
END
GO
IF NOT EXISTS (SELECT * FROM sys.tables WHERE  [name] = 'ActivityAttachments')
BEGIN
	PRINT('Add ActivityAttachments...')
	CREATE TABLE dbo.ActivityAttachments(
		ActivityAttachmentId	INT IDENTITY(1, 1) NOT NULL,
		ActivityId				INT NOT NULL,
		AttachmentId						INT NOT NULL,
		Note								VARCHAR(1024) NULL,
		Sort								INT NOT NULL CONSTRAINT DF_ActivityAttachments_Sort DEFAULT (0),
		LC									SMALLDATETIME NOT NULL CONSTRAINT DF_ActivityAttachments_LC DEFAULT GETDATE(),
		UC									INT NOT NULL,
		LM									SMALLDATETIME NOT NULL CONSTRAINT DF_ActivityAttachments_LM DEFAULT GETDATE(),
		UM									INT NOT NULL
	 CONSTRAINT PK_ActivityAttachments PRIMARY KEY NONCLUSTERED (ActivityAttachmentId ASC) ON [PRIMARY]
	) ON [PRIMARY]

	CREATE CLUSTERED INDEX IX_ActivityAttachments_ActivityId  ON ActivityAttachments (ActivityId) ON [PRIMARY]

	ALTER TABLE dbo.ActivityAttachments  WITH CHECK ADD  CONSTRAINT FK_ActivityAttachments_Attachments FOREIGN KEY(AttachmentId)
		REFERENCES dbo.Attachments (AttachmentId)
	ALTER TABLE dbo.ActivityAttachments CHECK CONSTRAINT FK_ActivityAttachments_Attachments
	
	ALTER TABLE dbo.ActivityAttachments  WITH CHECK ADD  CONSTRAINT FK_ActivityAttachments_Activities FOREIGN KEY(ActivityId)
		REFERENCES dbo.Activities (ActivityId)
	ALTER TABLE dbo.ActivityAttachments CHECK CONSTRAINT FK_ActivityAttachments_Activities

	GRANT INSERT, UPDATE, DELETE ON ActivityAttachments TO DataService
END
GO

IF  EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.WarningContractInvalidOwner'))
BEGIN
DROP PROCEDURE dbo.WarningContractInvalidOwner
END
GO
CREATE PROCEDURE dbo.WarningContractInvalidOwner
		@infoOnly bit
		WITH EXECUTE AS 'dbo'
		AS
		BEGIN
					
		IF(@infoOnly=0)
		BEGIN
		UPDATE c SET c.OwnerGroupId = D.OwnerGroupId
			FROM Contracts AS c 
				INNER JOIN ContractDepartments AS cp ON c.ContractId = cp.ContractId 
				INNER JOIN WorkAreas AS wa ON cp.WorkAreaId = wa.WorkAreaId 
				INNER JOIN Departments AS D ON wa.DepartmentId = D.DepartmentId 
				INNER JOIN OwnerGroups AS G ON D.OwnerGroupId = G.OwnerGroupId
			WHERE cp.IsMainWorkArea = 1 
				AND G.Modul = 4
				AND D.OwnerGroupId <> c.OwnerGroupId
			END
		ELSE
		BEGIN
			SELECT p.KeyName, g.Name 
			FROM Contracts AS c 
				INNER JOIN ContractDepartments AS cp ON c.ContractId = cp.ContractId 
				INNER JOIN WorkAreas AS wa ON cp.WorkAreaId = wa.WorkAreaId 
				INNER JOIN Departments AS D ON wa.DepartmentId = D.DepartmentId 
				INNER JOIN OwnerGroups AS G ON D.OwnerGroupId = G.OwnerGroupId
				INNER JOIN Persons AS p ON c.PersonId = p.PersonId
			WHERE cp.IsMainWorkArea = 1 
				AND G.Modul = 4
				AND D.OwnerGroupId <> c.OwnerGroupId
		END
	END
GO
GRANT EXECUTE ON WarningContractInvalidOwner TO DataCleaningAdmin
--#endregion
--#region Nachtrag AbPersDataCategoryData 2021-12-29 DH
/****** Object:  View [dbo].[AbPersDataCategoryData]    Script Date: 29.12.2021 10:55:32 ******/
GO
ALTER VIEW [dbo].[AbPersDataCategoryData]
AS
	SELECT
		pfd.*
	FROM PersonFieldData AS pfd 
				INNER JOIN PersonFields AS pf ON pfd.PersonFieldId = pf.PersonFieldId
				INNER JOIN PersonPermissions AS pp ON pfd.personId = pp.personId
				INNER JOIN [Permissions] AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
				INNER JOIN Users AS u ON p.Userid = u.Userid 
			WHERE
				p.PermissionArea = 0
				AND (p.OptionsFlag&pp.OptionsFlag&4 = 4 OR p.OptionsFlag&pp.OptionsFlag&8 = 8 OR pf.ShowOnPage = 1) -- Pressetextseite(1) ist öffentlich
				AND Username = CURRENT_USER		
GO

ALTER VIEW [dbo].[AbPersDataCategoryData_Update]
AS
	SELECT
		pfd.*
	FROM
		PersonFieldData pfd
	WHERE
		pfd.PersDataCategoryDataId IN (
				SELECT pfd.PersDataCategoryDataId
				FROM PersonFieldData AS pfd 
					INNER JOIN PersonFields AS pf ON pfd.PersonFieldId = pf.PersonFieldId
					INNER JOIN PersonPermissions AS pp ON pfd.personId = pp.personId
					INNER JOIN [Permissions] AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
					INNER JOIN Users AS u ON p.Userid = u.Userid 
				WHERE
					p.PermissionArea = 0
					AND (
					 (
					 (pf.ShowOnPage = 0 AND p.OptionsFlag&pp.OptionsFlag&8 = 8)
					 OR
					 (pf.ShowOnPage = 1 AND p.OptionsFlag&pp.OptionsFlag&32768 = 32768 )
					 )
						)
					AND Username = CURRENT_USER		
		)
WITH CHECK OPTION
GO
DropColumn 'PersonFields','IsPublic'
GO
GRANT EXECUTE ON MergeSequentialPeriodBasicCasts TO DataCleaningAdmin
GRANT EXECUTE ON MergeSequentialPeriodFees TO DataCleaningAdmin
GO


--#endregion Nachtrag AbPersDataCategoryData
--#region Bugfix Dataservice
	GRANT SELECT ON MeasureParticipationAttachments TO DataService
	GRANT SELECT ON TourAttachments TO DataService
--#endregion Bugfix Dataservice
--#endregion ------- (4.216.x) --------------------------------

--------------------- Ende Änderungsblock --------------------- 
---------------------------------------------------------------
--------------------- RELEASE SECTION -------------------------

--#region ----------- 4.221.x Release Übertrag ----------------
IF EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByContractsInternal')) DROP PROCEDURE dbo.GetDutyRosterByContractsInternal
GO

CREATE PROCEDURE [dbo].[GetDutyRosterByContractsInternal]
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT,
	@topFromEnd INT,
	@userId INT,
	@personId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	DECLARE @e NVARCHAR(MAX)
	SET NOCOUNT ON
	
	CREATE TABLE #Permissions (ContractId INT NOT NULL, StartDate DATE NOT NULL, EndDate DATE NOT NULL)

	IF (NOT @personId IS NULL)
		BEGIN
			CREATE TABLE #OwnContracts (ContractId INT NOT NULL)
			INSERT INTO #OwnContracts SELECT ci.Id FROM @contractids AS ci INNER JOIN Contracts AS c ON ci.Id = c.ContractId WHERE c.PersonId = @personId

			IF ((SELECT COUNT(*) FROM #OwnContracts) > 0)
				BEGIN
					INSERT INTO #Permissions (ContractId, StartDate, EndDate) SELECT ContractId, @start, @end FROM #OwnContracts
					DECLARE @otherContractids IdFilterTable
					INSERT INTO @otherContractids SELECT c.Id FROM @contractids AS c WHERE NOT EXISTS (SELECT * FROM #OwnContracts AS oc WHERE oc.ContractId = c.Id)
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @otherContractids, @userId)
				END
			ELSE
				BEGIN
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
				END
		END
	ELSE
		BEGIN
			INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
		END
	
	
	SET @SQLQuery =	N'SELECT '
	IF (@topFromEnd > 0)  SET @SQLQuery = @SQLQuery + N' TOP ' + CAST(@topFromEnd AS VARCHAR(10))
	SET @SQLQuery = @SQLQuery + N' dp.* '

	SET @SQLQuery =@SQLQuery + N' FROM DutyRoster AS dp
						INNER JOIN #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate '
	
	 IF (ISNULL(@where, '') <> '' )  SET @SQLQuery = @SQLQuery + ' AND ' + @where
	 IF (@topFromEnd > 0)  SET @SQLQuery = @SQLQuery + ' ORDER BY dp.Date DESC'

	 EXECUTE sp_Executesql @SQLQuery
	--Weiteres Where wird aus Performancegründen ignoriert 	
	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate 
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 
END
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByDepartmentInternal')) DROP PROCEDURE dbo.GetDutyRosterByDepartmentInternal
GO

CREATE PROCEDURE dbo.GetDutyRosterByDepartmentInternal
	@start DATE,
	@end DATE,
	@Departmentids IdFilterTable READONLY,
	@where NVARCHAR(MAX),
	@include INT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	SET NOCOUNT ON
	
	CREATE TABLE #Permissions (DepartmentId INT NOT NULL,  StartDate DATE NOT NULL, EndDate DATE NOT NULL)
	INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByDepartments (@start,  @end, @Departmentids, @userId)

	SET @SQLQuery = 'SELECT dp.* 
					FROM DutyRoster AS dp 
						INNER JOIN ContractDepartments AS cd ON dp.ContractId = cd.ContractId 
						INNER JOIN WorkAreas AS w ON cd.WorkAreaId = w.WorkAreaId
						INNER JOIN #Permissions AS p ON w.DepartmentId = p.DepartmentId
					WHERE dp.[Date] BETWEEN p.StartDate AND p.EndDate'

	  IF (ISNULL(@where, '') <> '' )  SET @SQLQuery = @SQLQuery + ' AND ' + @where
	 EXECUTE sp_Executesql @SQLQuery

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate 
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 
END
GO
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.AbContractMeasureGroups_Update') AND type <> 'U') DROP VIEW dbo.[AbContractMeasureGroups_Update]
GO

IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.GetDutyRosterByContractsCore')) DROP PROCEDURE dbo.GetDutyRosterByContractsCore
GO

CREATE PROCEDURE dbo.GetDutyRosterByContractsCore
	@start DATE,
	@end DATE,
	@contractids IdFilterTable READONLY,
	@include INT
AS
BEGIN
	
	SET NOCOUNT ON
	DECLARE @userId INT
	DECLARE @personId INT
	SELECT @userId = UserId, @personId = PersonId FROM Users WHERE UserName  = CURRENT_USER

	IF (NOT @personId IS NULL) 
	BEGIN
		IF (IS_MEMBER('PersoWriteOwnRoster') = 0 AND IS_MEMBER('PersoWriteOwnRegularRoster') = 0)
		SET @personId = NULL
	END
	
	CREATE TABLE #Permissions (ContractId INT NOT NULL, StartDate DATE NOT NULL, EndDate DATE NOT NULL)
	
	IF (NOT @personId IS NULL)
		BEGIN
			CREATE TABLE #OwnContracts (ContractId INT NOT NULL)
			INSERT INTO #OwnContracts SELECT ci.Id FROM @contractids AS ci INNER JOIN Contracts AS c ON ci.Id = c.ContractId WHERE c.PersonId = @personId

			IF ((SELECT COUNT(*) FROM #OwnContracts) > 0)
				BEGIN
					INSERT INTO #Permissions (ContractId, StartDate, EndDate) SELECT ContractId, @start, @end FROM #OwnContracts
					DECLARE @otherContractids IdFilterTable
					INSERT INTO @otherContractids SELECT c.Id FROM @contractids AS c WHERE NOT EXISTS (SELECT * FROM #OwnContracts AS oc WHERE oc.ContractId = c.Id)
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @otherContractids, @userId)
				END
			ELSE
				BEGIN
					INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
				END
		END
	ELSE
		BEGIN
			INSERT INTO #Permissions SELECT * FROM dbo.DutyRosterPeriodPermissionByContracts (@start, @end, @contractids, @userId)
		END
		
	SELECT dp.* FROM DutyRoster AS dp
		INNER JOIN #Permissions AS p ON dp.ContractId = p.ContractId AND [Date] BETWEEN p.StartDate AND p.EndDate 
	WHERE dp.DutyRosterTypeId = 0

	IF (@include&1 = 1) 
		SELECT NULL AS [#1], * FROM BonusDutyRosterData AS b INNER JOIN #Permissions AS p ON b.ContractId = p.ContractId AND b.[Date] BETWEEN p.StartDate AND p.EndDate
	IF (@include&2 = 2) 
		SELECT NULL AS [#2], * FROM CostUnitWorkingTimes AS cuwt INNER JOIN DutyRoster AS dp ON cuwt.ShiftDayId = dp.DutyRosterId  INNER JOIN  #Permissions AS p ON dp.ContractId = p.ContractId AND dp.[Date] BETWEEN p.StartDate AND p.EndDate 

END
GO
GO

ALTER PROCEDURE [dbo].[GetPersonsInternal]
	@condition VARCHAR(MAX),
	@order VARCHAR(MAX),
	@joins INT,
	@include INT,
	@ShowPersonsWithoutRights BIT,
	@userId INT
	WITH EXECUTE AS 'dbo'
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLQuery AS NVARCHAR(MAX)

	-- *** Wenn weitere Daten mitgeladen werden Temp Tabelle mit  PersonIds erstellen ***
	IF (@include <> 0) 
	BEGIN
	 CREATE TABLE #PersonsNP (PersonId INT NOT NULL)
	End
	-- *** Berechtigungen des Users für Personen (0) in Temp Tabelle ***
	CREATE TABLE #UserGroupPermissions (OwnerGroupId INT NOT NULL, PermissionArea INT NOT NULL, OptionsFlag INT NOT NULL)
	INSERT INTO #UserGroupPermissions SELECT OwnerGroupId, PermissionArea, OptionsFlag FROM Permissions WHERE  UserId = @userId AND PermissionArea IN (0,1,6)
		
	-- *** Wenn keine weiteren Daten mitgeladen werden das Ergebnis direkt zurückgeben, ansonsten PersonIds in Temp
	
	if (@include <> 0 OR @ShowPersonsWithoutRights = 0) 
		BEGIN
			SET @SQLQuery = 'INSERT INTO #PersonsNP SELECT Persons.PersonId FROM Persons '
			IF (@ShowPersonsWithoutRights = 0) 
			BEGIN
				SET @SQLQuery =  @SQLQuery + ' INNER JOIN #UserGroupPermissions AS UG ON UG.OwnerGroupId = Persons.OwnerGroupId AND ug.PermissionArea = 0'
			END
		END								
	ELSE		
		BEGIN
			SET @SQLQuery = 'SELECT persons.* FROM Persons  ' 
		END			
	-- *** Weitere Joins ***	 
		IF (@joins&1 = 1)
			SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
		
		IF (@joins&2 = 2) 
			SET @SQLQuery = @SQLQuery + ' LEFT JOIN PersonDetails ON Persons.PersonId = PersonDetails.PersonId '

		 IF (@condition IS NOT NULL AND @condition <> '')
			 SET @SQLQuery = @SQLQuery + ' WHERE ' + @condition 

		if (@include = 0 AND @order IS NOT NULL) 
			SET @SQLQuery = @SQLQuery + ' ORDER BY ' + @order 

		print @sqlquery
		EXECUTE sp_Executesql @SQLQuery 		
	
	IF (@include <> 0) --Wenn keine weiteren Daten mitgeladen werden wurde das Ergebnis bereits zurückgeben
		BEGIN
			SET @SQLQuery = 'SELECT persons.* 
								FROM Persons INNER JOIN  #PersonsNP ON Persons.PersonId = #PersonsNP.PersonId'
				
			If (@order IS NOT NULL)
			BEGIN
			IF (@joins&1 = 1)
				SET @SQLQuery = @SQLQuery + ' INNER JOIN PersonCategories ON Persons.PersonCategoryId = PersonCategories.PersonCategoryId '
				SET @SQLQuery = @SQLQuery  + ' ORDER BY ' + @order 
			END
			print @sqlquery
			EXECUTE sp_Executesql  @SQLQuery
		END

	IF(@include<>0)
	BEGIN
		WITH CTE AS(
			SELECT PP.PersonId
					,MIN(p.OwnerGroupId) AS BaseOwner
                    ,MAX(CONVERT(TINYINT, PP.HasWritePermission)) AS Write
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&1) AS ReadSecret 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&2) AS WriteQualifications
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&4) AS ReadPersonDetails
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&8) AS WritePersonDetails 
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&16) AS ReadPersonBankData
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&32) AS WritePersonBankData
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&64) AS ReadPersonFeeNotes
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&128) AS WritePersonFeeNotes
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&256) AS WritePersonEmployee
                    ,MAX(P.OptionsFlag&PP.OptionsFlag&512) AS ShowLinkedContacts
					,MAX(P.OptionsFlag&PP.OptionsFlag&2048)+MAX(P.OptionsFlag&PP.OptionsFlag&4096) AS ReadAddressData
					,MAX(P.OptionsFlag&PP.OptionsFlag&8192)+MAX(P.OptionsFlag&PP.OptionsFlag&16384) AS ReadContactData
		
                    FROM PersonPermissions PP  
                           INNER JOIN #UserGroupPermissions P ON PP.OwnerGroupId = P.OwnerGroupId AND P.PermissionArea = 0                            
                    WHERE pp.PersonId IN (SELECT PersonId FROM #PersonsNP)
					GROUP BY pp.PersonId
					
		) SELECT * INTO #includePermissions FROM cte 
	END 

	if (@include&1024 = 1024)   --An den Anfang verschoben um preloading zu optimieren
			SELECT NULL as [#1024],PP.* 
			FROM PersonPermissions PP INNER JOIN #PersonsNP PNP on PNP.PersonId = pp.PersonId

	IF (@include&1 = 1)
			SELECT NULL AS [#1], 
				pk.PersonContactDataId, 
				pk.CommunicationTypeId, 
				pk.PersonId, 
				pk.Sort, 
				pk.IsSecret,
				CASE WHEN IsSecret = 1 AND ReadSecret = 0 THEN '**********' ELSE  pk.DataValue END AS DataValue,
				CASE WHEN IsSecret = 1 AND ReadSecret = 0 THEN '**********' ELSE  pk.Note END AS Note,
				pk.ContactPersonConnectionID,
				pk.LM, pk.UM, pk.LC, pk.UC
			FROM PersonContactData AS pk
				INNER JOIN (
				SELECT pp.PersonId, pp.ReadSecret
				FROM #includePermissions AS PP WHERE PP.ReadContactData > 0 
					) AS sub ON pk.PersonId = sub.PersonId

	IF (@include&2 = 2)
		SELECT NULL AS [#2], PersonAddress.*
		FROM PersonAddress
			INNER JOIN #includePermissions AS PP ON PersonAddress.PersonId = PP.PersonId
		WHERE (PersonAddress.IsSecret = 0 OR ReadSecret > 0) AND PP.ReadAddressData > 0 
					
	IF (@include&4 = 4)
		SELECT NULL AS [#4], PersonDetails.*
		FROM PersonDetails 			
			INNER JOIN #includePermissions ON PersonDetails.PersonId = #includePermissions.PersonId WHERE ReadPersonDetails > 0 OR WRITEPERSONDETAILS>0
		
	IF (@include&8 = 8)
		SELECT NULL AS [#8],PersonEmployee.*
		FROM PersonEmployee
			INNER JOIN #includePermissions ON PersonEmployee.PersonId = #includePermissions.PersonId
			
	IF (@include&16 = 16) 
		SELECT NULL AS [#16], zd.*
		FROM PersonAdditionalData zd 
		WHERE zd.PersonAdditionalDataId IN 
		(SELECT PersonAdditionalDataId FROM PersonAdditionalData
			INNER JOIN	PersonAdditionalDataTypes	AS zdt	ON zd.PersonAdditionalDataTypeId = zdt.PersonAdditionalDataTypeId
			INNER JOIN	#includePermissions			AS gp	ON zd.PersonId = gp.PersonId
			INNER JOIN  #UserGroupPermissions		AS ug	ON zdt.OwnerGroupId = ug.OwnerGroupId			 
		WHERE 
			zdt.IsSecret = 0 OR ug.PermissionArea = 0)
	
	IF (@include&32 = 32) 
		SELECT NULL AS [#32], PersonRelations.*
		FROM PersonRelations
			INNER JOIN #includePermissions ON PersonRelations.PersonId = #includePermissions.PersonId AND ShowLinkedContacts > 0

	IF (@include&64 = 64) 
		SELECT NULL AS [#64], PersonRelations.*
		FROM PersonRelations 
			INNER JOIN #includePermissions ON PersonRelations.ChildPersonId = #includePermissions.PersonId

	IF (@include&128 = 128) 
		SELECT NULL AS [#128], Qualification_Person.*
		FROM Qualification_Person 
			INNER JOIN #includePermissions ON Qualification_Person.PersonId = #includePermissions.PersonId
	
	IF (@include&256 = 256) 
		SELECT NULL AS [#256], BodyMeasurements.*
		FROM BodyMeasurements 
			INNER JOIN #includePermissions ON BodyMeasurements.PersonId = #includePermissions.PersonId
			INNER JOIN #UserGroupPermissions prp ON prp.OwnerGroupId = #includePermissions.baseOwner AND prp.PermissionArea=6
	
	IF (@include&512 = 512) 
		SELECT NULL AS [#512], BankAccounts.*
		FROM BankAccounts 
			INNER JOIN #includePermissions ON BankAccounts.PersonId = #includePermissions.PersonId 
				AND (#includePermissions.ReadPersonBankdata>0 OR #includePermissions.WritePersonBankdata > 0)

	IF (@include&2048 = 2048) 
		SELECT NULL AS [#2048], PersonAttachments.PersonId, Count(*) AS CountAttachments
		FROM PersonAttachments 
			INNER JOIN #includePermissions ON PersonAttachments.PersonId = #includePermissions.PersonId
		GROUP BY PersonAttachments.PersonId

	IF (@include&4096 = 4096) 
		SELECT NULL AS [#4096], Birthdays.*
		FROM Birthdays 
			INNER JOIN #includePermissions ON Birthdays.PersonId = #includePermissions.PersonId		
	IF (@include&8192 = 8192 OR @include&16384 = 16384) 
		SELECT NULL AS [#8192], Contracts.*
		FROM Contracts 
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	AND contracts.OwnerGroupId IN 
			(SELECT OwnerGroupId FROM #UserGroupPermissions WHERE PermissionArea = 1)

	IF (@include&16384 = 16384) 
		SELECT NULL AS [#16384], ContractDepartments.*
		FROM ContractDepartments 
			INNER JOIN Contracts ON ContractDepartments.ContractId=Contracts.ContractId
			INNER JOIN #includePermissions ON Contracts.PersonId = #includePermissions.PersonId	AND contracts.OwnerGroupId IN 
			(SELECT OwnerGroupId FROM #UserGroupPermissions WHERE PermissionArea IN (1, 5))		

	IF (@include&32768 = 32768) 
		SELECT NULL AS [32768], PersonInCategories.*
		FROM PersonInCategories 
			INNER JOIN #PersonsNP ON PersonInCategories.PersonId = #PersonsNP.PersonId	

	IF (@include&65536 = 65536) 
		SELECT NULL AS [65536],pfd.*
		FROM PersonFieldData pfd 
				INNER JOIN PersonFields AS pf ON pfd.PersonFieldId = pf.PersonFieldId
				INNER JOIN #includePermissions AS PP ON pfd.PersonId = PP.PersonId
		WHERE ReadPersonDetails > 0 OR WritePersonDetails > 0 OR pf.ShowOnPage = 1 -- Pressetextseite(1) ist öffentlich

	IF (@include<>0) 
	BEGIN	
		DROP TABLE #includePermissions
		DROP TABLE #PersonsNP
	END
	DROP TABLE #UserGroupPermissions
END
GO
CREATE VIEW [dbo].[AbContractMeasureGroups_Update]
AS 
SELECT * FROM ContractMeasureGroups WHERE
	ContractId IN 
	(
		SELECT Contracts.ContractId 
		FROM [Permissions] AS CoPerMi
			INNER JOIN	Users		ON CoPerMi.Userid = Users.Userid 
			INNER JOIN	Contracts	ON Contracts.OwnerGroupId = CoPerMi.OwnerGroupId 
		WHERE Username = CURRENT_USER AND PermissionArea = 1 AND CoPerMi.HasWritePermission = 1
	UNION 
		SELECT Contracts.ContractId 
		FROM [Permissions] AS PersonPerMi
			INNER JOIN	Users		ON PersonPerMi.Userid = Users.Userid 
			INNER JOIN	Persons		ON PersonPerMi.OwnerGroupId = Persons.OwnerGroupId 
			INNER JOIN	Contracts	ON Contracts.PersonId = Persons.PersonId 
		WHERE Username = CURRENT_USER AND PermissionArea = 0 AND PersonPerMi.OptionsFlag&131072 = 131072
	 )

WITH CHECK OPTION
GO
GRANT SELECT, UPDATE, INSERT, DELETE ON [AbContractMeasureGroups_Update] TO PUBLIC
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MeasureGroups') AND [name] = 'LevelNumber') ALTER TABLE MeasureGroups ADD LevelNumber VARCHAR(8) NULL
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MeasureTypePriorities') AND [name] = 'BackColor')	ALTER TABLE MeasureTypePriorities ADD BackColor INT NULL
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('MeasureTypePriorities') AND [name] = 'ForeColor')	ALTER TABLE MeasureTypePriorities ADD ForeColor INT NULL
GO
DropColumn 'EntitlementRules', 'TimeAccountId'
GO
IF EXISTS (SELECT * FROM  sys.objects o WHERE  o.object_id = OBJECT_ID(N'dbo.DeleteDutyRosterByContractId')) DROP PROCEDURE dbo.DeleteDutyRosterByContractId
GO
--Löschte Dienstplaneinträge und Zulagen pro Vertrag
CREATE PROCEDURE dbo.DeleteDutyRosterByContractId
	@contractIds INT
AS
BEGIN
	
	SET NOCOUNT ON
	
	IF EXISTS (	SELECT *
				FROM [Permissions]  AS P 
				INNER JOIN Users AS u ON p.UserID = u.UserID 
				INNER JOIN Departments AS D ON p.OwnerGroupId = d.OwnerGroupId 
				INNER JOIN WorkAreas AS w ON d.DepartmentId = w.DepartmentId
				INNER JOIN ContractDepartments AS cd ON cd.WorkAreaId = w.WorkAreaId 
				WHERE u.UserName = CURRENT_USER AND 
					PermissionArea IN (1, 5) AND 
					p.HasWritePermission = 1 AND
					cd.ContractId = @contractIds)
	BEGIN
		DELETE FROM DutyRoster WHERE ContractId = @contractIds
		DELETE FROM BonusDutyRosterData WHERE ContractId = @contractIds
	END
END
GO

GRANT EXECUTE ON DeleteDutyRosterByContractId TO Public
GO

--#region nvarchar für personfielddata textvalue
ALTER TABLE PersonFieldData ALTER COLUMN TextValue NVarChar(Max) NULL 
GO
--#endregion nvarchar für personfielddata textvalue

--#region Berechtigungen

GRANT INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO MasterAdmin
REVOKE INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO DispoAdmin
REVOKE INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO PersoAdmin
REVOKE INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO OrchesterAdmin
REVOKE INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO BallettAdmin
REVOKE INSERT, UPDATE, DELETE ON RuleCriteriaSelections TO StatisterieAdmin

--Plandetails: Lesen nicht über View
GRANT SELECT ON PlanColumns TO Public
GRANT SELECT ON PlanColumnContent TO Public

--#endregion

--#region Berechtigungen 2022-01-25  Veraltete Bereche entfernen
UPDATE PlanColumnContent
SET ContentSettings = CAST(REPLACE(CAST(ContentSettings AS NVARCHAR(MAX)), '&lt;Categories&gt;DailyTaskActivity&lt;/Categories&gt;','') AS XML) 
FROM PlanColumnContent WHERE NOT ContentSettings IS NULL AND CAST(ContentSettings AS VARCHAR(MAX)) LIKE '%&lt;Categories&gt;DailyTaskActivity&lt;/Categories&gt;%'
GO
--#endregion

--#region 2022-01-25 InheritPermissions / Berechtigungen für "jeder"

ALTER PROCEDURE [dbo].[InheritPermissions]
AS
BEGIN   
	DECLARE @dbo BIT
	DECLARE @secAdm BIT
	DECLARE @currentUserId INT
	DECLARE @authorizedByGroup BIT
	DECLARE @forAllUsers BIT
	
	SET @currentUserId = 0
	SET @authorizedByGroup = 0
	SET @forAllUsers = 0

	--daten für aktuellen benutzer abfragen, notfalls neu anlegen
	SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM Users WHERE UserName = CURRENT_USER
	IF @currentUserId = 0 
	BEGIN
		EXEC AddCurrentUser
		SELECT @currentUserId = UserId, @authorizedByGroup = IsAuthorizedByWindowsGroup FROM Users WHERE UserName = CURRENT_USER
	END

	SELECT @dbo = IS_MEMBER('db_owner') 
	SELECT @secAdm = IS_MEMBER('SecurityAdmin') 
	
	IF (@dbo = 1 OR @secAdm = 1) SET @forAllUsers = 1	

	--UsersInGroups in variable speichern, da im weiteren Verlauf viel damit gearbeitet wird und die abfragen ansonsten sehr langsam sind
	DECLARE @usersInGroups TABLE (GroupId INT, UserId INT)
	INSERT INTO @usersInGroups (GroupId, UserId)
	SELECT ugs.GroupId, ugs.UserId
	FROM UsersInGroups AS ugs

	--wenn über gruppe authorisiert, manuell benutzergruppenzugehörigkeit einfügen
	IF @authorizedByGroup = 1 
	BEGIN
		INSERT INTO @usersInGroups (GroupId, UserId)
		SELECT grp.UserID, @currentUserId
		FROM sys.database_principals dp 
		INNER JOIN Users grp ON dp.name = grp.UserName
		WHERE dp.type = 'R' AND IS_MEMBER(dp.name) = 1 AND dp.name LIKE '[_]%' 
		AND NOT EXISTS(SELECT * FROM @usersInGroups WHERE GroupId = grp.UserID AND UserId = @currentUserId)
	END

	--abfragedaten für alle benutzer die über windowsgruppen authorisiert wurden und ignoriert werden (aktueller benutzer ausgenommen)
	DECLARE @usersAuthorizedByGroup TABLE (userId INT)
	--füllen nur, wenn für alle benutzer berechtigungen erstellt werden
	IF @forAllUsers = 1
	BEGIN 
	   	INSERT INTO @usersAuthorizedByGroup
		SELECT up.UserID FROM Users up WHERE up.IsAuthorizedByWindowsGroup = 1 AND up.UserID <> @currentUserId
    END
	
	--neue Berechtigungen einfügen
	INSERT INTO Permissions (OwnerGroupId, UserID, PermissionArea, HasWritePermission, OptionsFlag, IsInherited, LM, UM, LC, UC)
	SELECT  soll.OwnerGroupId, ugs.UserID, soll.PermissionArea, CAST(COUNT(soll.HasWritePermission) AS BIT),
	  		  MAX(soll.OptionsFlag&1)
			 +MAX(soll.OptionsFlag&2)
			 +MAX(soll.OptionsFlag&4)
			 +MAX(soll.OptionsFlag&8)
			 +MAX(soll.OptionsFlag&16)
			 +MAX(soll.OptionsFlag&32)
			 +MAX(soll.OptionsFlag&64)
			 +MAX(soll.OptionsFlag&128)
			 +MAX(soll.OptionsFlag&256)
			 +MAX(soll.OptionsFlag&512)
			 +MAX(soll.OptionsFlag&1024)
			 +MAX(soll.OptionsFlag&2048)
			 +MAX(soll.OptionsFlag&4096)
			 +MAX(soll.OptionsFlag&8192)
			 +MAX(soll.OptionsFlag&16384)
			 +MAX(soll.OptionsFlag&32768)
			 +MAX(soll.OptionsFlag&65536)
			 +Max(soll.OptionsFlag&131072),
			 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM	@usersInGroups AS ugs 
		INNER JOIN	[Permissions] AS soll	ON ugs.GroupID = soll.UserID
		LEFT JOIN	[Permissions] AS ist	ON ugs.UserID = ist.UserID AND soll.OwnerGroupId  = ist.OwnerGroupId AND soll.PermissionArea = ist.PermissionArea
	WHERE  ist.PermissionId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY soll.OwnerGroupId, ugs.UserID, soll.PermissionArea

	--Berechtigungen entfernen
	DELETE FROM [Permissions] 
	WHERE IsInherited = 1 
		AND ([Permissions].UserId = @currentUserId OR @forAllUsers = 1)
		AND  PermissionId NOT IN 
				(
					SELECT  ist.PermissionId
					FROM			@usersInGroups AS ugs 
						INNER JOIN [Permissions] AS soll		ON ugs.GroupId = soll.UserID
						INNER JOIN [Permissions] as ist	ON ugs.UserID = ist.UserID AND soll.OwnerGroupId  = ist.OwnerGroupId AND soll.PermissionArea = ist.PermissionArea
				)
		AND ([Permissions].UserID NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	UPDATE [Permissions] SET [Permissions].HasWritePermission = SollSchreiben, Permissions.OptionsFlag=SollOp
	FROM 
	(SELECT ugs.UserId, g.OwnerGroupId, PermissionArea, MAX(CAST(g.HasWritePermission AS INT)) AS SollSchreiben,
			  MAX(g.OptionsFlag&1)
			 +MAX(g.OptionsFlag&2)
			 +MAX(g.OptionsFlag&4)
			 +MAX(g.OptionsFlag&8)
			 +MAX(g.OptionsFlag&16)
			 +MAX(g.OptionsFlag&32)
			 +MAX(g.OptionsFlag&64)
			 +MAX(g.OptionsFlag&128)
			 +MAX(g.OptionsFlag&256)
			 +MAX(g.OptionsFlag&512)
			 +MAX(g.OptionsFlag&1024)
			 +MAX(g.OptionsFlag&2048)
			 +MAX(g.OptionsFlag&4096)
			 +MAX(g.OptionsFlag&8192)
			 +MAX(g.OptionsFlag&16384)
			 +MAX(g.OptionsFlag&32768)
			 +MAX(g.OptionsFlag&65536)
			 +Max(g.OptionsFlag&131072) AS SollOp  
		FROM @usersInGroups AS ugs 
			INNER JOIN [Permissions] AS G ON ugs.GroupId = G.UserId
		GROUP BY ugs.UserId, g.OwnerGroupId, PermissionArea) AS soll 
	INNER JOIN [Permissions]  ON 
			soll.UserId = [Permissions].UserId AND 
			soll.OwnerGroupId = [Permissions].OwnerGroupId AND 
			soll.PermissionArea = [Permissions].PermissionArea
	WHERE
		(SollSchreiben <> [Permissions].HasWritePermission OR SollOp <> [Permissions].OptionsFlag)
		AND [Permissions].IsInherited = 1
		AND ([Permissions].UserId = @currentUserId OR @forAllUsers = 1)
		AND ([Permissions].UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))	
	
	--Jeden User in Gruppe Kontaktdaten Jeder
	INSERT INTO [Permissions] (OwnerGroupId, UserId, HasWritePermission, LM, UM, LC, UC, PermissionArea, OptionsFlag)
	SELECT -1, Users.UserId, -1, GETDATE(), -1, GETDATE(), 0, 0, 11796
	FROM Users LEFT JOIN (SELECT * FROM [Permissions] WHERE PermissionArea = 0 AND OwnerGroupId = -1) AS UG ON Users.UserId = UG.UserId WHERE UG.PermissionId IS NULL

	--Berechtigung für Jeder/Kontakte
	UPDATE [Permissions] SET OptionsFlag = 11796 WHERE PermissionArea = 0 AND OwnerGroupId = -1 AND OptionsFlag <> 11796

	DELETE FROM [Permissions] WHERE PermissionArea <> 0 AND OwnerGroupId = -1
	
	INSERT INTO SeasonPermissions (SeasonId, UserId, IsInherited, LM, UM, LC, UC)
	SELECT DISTINCT soll.SeasonId, ugs.UserId, 1, GETDATE(), -1, GETDATE(), -1
	FROM	@usersInGroups AS ugs 
		INNER JOIN	SeasonPermissions AS soll ON ugs.Groupid = soll.UserId
		LEFT JOIN	SeasonPermissions AS ist  ON ugs.UserId = ist.UserId AND soll.SeasonId=ist.SeasonId
	WHERE  ist.SeasonPermissionId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)

	DELETE FROM SeasonPermissions 
	WHERE IsInherited = 1 AND  SeasonPermissionId NOT IN (
		SELECT      ist.SeasonPermissionId
		FROM        @usersInGroups          AS ugs
		INNER JOIN	SeasonPermissions soll      ON ugs.GroupId = soll.UserId
		INNER JOIN	SeasonPermissions ist       ON ugs.UserId = ist.UserId  AND soll.SeasonId=ist.SeasonId
	) AND (UserId = @currentUserId OR @forAllUsers = 1)
	AND (UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatures
	--Neue UserFeatures einfügen
	INSERT INTO UserFeatures (UserId, FeatureId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, soll.FeatureId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatures AS soll ON ugs.GroupID = soll.UserId
		LEFT  JOIN UserFeatures AS ist ON ugs.UserId = ist.UserId AND soll.FeatureId  = ist.FeatureId
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserId, soll.FeatureId

	--Überflüssige UserFeatures entfernen
	DELETE FROM UserFeatures 
	WHERE IsInherited = 1 
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureId NOT IN 
				(
					SELECT  ist.UserFeatureId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatures AS soll ON ugs.GroupId = soll.UserId
						INNER JOIN	UserFeatures AS ist ON ugs.UserId = ist.UserId AND soll.FeatureId  = ist.FeatureId
				)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatures aktualisieren
	UPDATE UserFeatures SET UserFeatures.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, FeatureId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatures AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId, uf.FeatureId
	) AS soll 
	INNER JOIN UserFeatures  ON 
			soll.UserId = UserFeatures.UserId AND 
			soll.FeatureId = UserFeatures.FeatureId
	WHERE
		SollIsAvailable <> UserFeatures.IsAvailable
		AND UserFeatures.IsInherited = 1
		AND (UserFeatures.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatures.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))

	--UserFeatureDefaults
	--Neue UserFeatureDefaults einfügen
	INSERT INTO UserFeatureDefaults (UserId, IsAvailable, IsInherited, LM, UM, LC, UC)
	SELECT ugs.UserId, MAX(CAST(soll.IsAvailable AS INT)), 1, MAX(soll.LM), MAX(soll.UM), MAX(soll.LC), MAX(soll.UC)
	FROM @usersInGroups AS ugs 
		INNER JOIN UserFeatureDefaults AS soll ON ugs.GroupID = soll.UserId
		LEFT JOIN UserFeatureDefaults AS ist ON ugs.UserId = ist.UserId
	WHERE  ist.UserId IS NULL AND (ugs.UserId = @currentUserId OR @forAllUsers = 1)
	GROUP BY ugs.UserId

	--Überflüssige UserFeatureDefaults entfernen
	DELETE FROM UserFeatureDefaults 
	WHERE IsInherited = 1 
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND UserFeatureDefaultId NOT IN 
				(
					SELECT  ist.UserFeatureDefaultId
					FROM			@usersInGroups AS ugs 
						INNER JOIN	UserFeatureDefaults AS soll ON ugs.GroupId = soll.UserId
						INNER JOIN	UserFeatureDefaults AS ist ON ugs.UserID = ist.UserId
				)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
	
	--UserFeatureDefaults aktualisieren
	UPDATE UserFeatureDefaults SET UserFeatureDefaults.IsAvailable = SollIsAvailable
	FROM 
	(
		SELECT ugs.UserId, MAX(CAST(uf.IsAvailable AS INT)) AS SollIsAvailable
		FROM @usersInGroups AS ugs 
			INNER JOIN UserFeatureDefaults AS uf ON ugs.GroupId = uf.UserId
		GROUP BY ugs.UserId
	) AS soll 
	INNER JOIN UserFeatureDefaults  ON 
			soll.UserId = UserFeatureDefaults.UserId
	WHERE
		SollIsAvailable <> UserFeatureDefaults.IsAvailable
		AND UserFeatureDefaults.IsInherited = 1
		AND (UserFeatureDefaults.UserId = @currentUserId OR @forAllUsers = 1)
		AND (UserFeatureDefaults.UserId NOT IN (SELECT * FROM @usersAuthorizedByGroup))
END	
GO

--#endregion

--#region 2022-01-31 mit Reschreibrechten auch lesen
ALTER VIEW [dbo].[AbMeasureParticipations]
AS 
SELECT
	mp.*,(SELECT COUNT(*) AS FollowerCount FROM  MeasureParticipations mps 
								WHERE mps.PersonId = mp.PersonId 
									AND mps.ParticipationDate > mp.ParticipationDate 
									AND mps.MeasureTypeId = mp.MeasureTypeId) AS FollowerCount 
FROM
	MeasureParticipations mp
WHERE 
	mp.PersonId IN (
		SELECT  pp.PersonId
		FROM PersonPermissions AS pp
			INNER JOIN Permissions AS p ON pp.OwnerGroupId =  p.OwnerGroupId 
			INNER JOIN Users u ON p.Userid = u.Userid 
		WHERE 
			(p.OptionsFlag&pp.OptionsFlag&65536 = 65536 OR p.OptionsFlag&pp.OptionsFlag&131072 = 131072)
			AND PermissionArea = 0
			AND Username = CURRENT_USER
		GROUP BY pp.PersonId
	)
GO
--#endregion 

--#regionauf 2022-02 "ON DELETE SET NULL" ändern
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_Auditions_Cast') AND type = 'F') ALTER TABLE dbo.Auditions DROP CONSTRAINT FK_Auditions_Cast
ALTER TABLE dbo.Auditions ADD CONSTRAINT FK_Auditions_Cast FOREIGN KEY (CastId) REFERENCES [Cast] (CastId) ON DELETE SET NULL
GO
--#endregion

--#region 2022-02-17 in eingen DBs Fehler in PlanLayoutPermissions reperieren
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('PlanLayoutPermissions') AND [name] = 'PublishInWeb') 
BEGIN
Print 'Rename PlanLayoutPermissions.PublicateInWeb'
	EXEC sp_rename 'PlanLayoutPermissions.PublicateInWeb', 'PublishInWeb', 'COLUMN';
END 
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_PlanLayoutPermissions_OwnerGroups_UserId') AND type = 'F') ALTER TABLE dbo.PlanLayoutPermissions DROP CONSTRAINT FK_PlanLayoutPermissions_OwnerGroups_UserId

DELETE FROM PlanLayoutPermissions WHERE NOT EXISTS(SELECT * FROM [Users] AS U  WHERE U.UserID = PlanLayoutPermissions.UserId)

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE  id = OBJECT_ID(N'dbo.FK_PlanLayoutPermissions_Users') AND type = 'F') ALTER TABLE dbo.PlanLayoutPermissions ADD CONSTRAINT FK_PlanLayoutPermissions_Users FOREIGN KEY (UserId) REFERENCES [Users] (UserId) 

GRANT SELECT ON PlanLayoutPermissions TO Public

--#endregion
--#endregion -------- (4.221.x Release Übertrag) --------------

---------------------------------------------------------------
--#region ----------- Views aktualisieren ---------------------
Print ('Updating Views...')
DECLARE @SchemaView VARCHAR(100)
DECLARE view_cursor CURSOR FOR
SELECT Name
	FROM 	sysobjects
	WHERE	xtype = 'V'
	ORDER BY Name

OPEN view_cursor
FETCH NEXT FROM view_cursor INTO @SchemaView
WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT '	' + @SchemaView
		BEGIN TRY
			EXEC sp_refreshview @SchemaView;
		END TRY
		BEGIN CATCH
			declare @error int, @line INT, @severity INT, @state INT, @procedure NVARCHAR(128), @message nvarchar(4000), @xstate int;
			select @error = ERROR_NUMBER(), @line = ERROR_LINE(), @severity = ERROR_SEVERITY(), @state = ERROR_STATE(),
			       @procedure = ERROR_PROCEDURE(), @message = ERROR_MESSAGE(),@xstate = XACT_STATE();
			PRINT('		Refreshing view failed...')
			PRINT('		ERROR #' + CONVERT(VARCHAR, @error) +' Severity '+ CONVERT(VARCHAR, @severity) + ' State ' + CONVERT(VARCHAR, @state))
			PRINT('		XACT_STATE ' + CONVERT(VARCHAR, @xstate))
			PRINT('		Procedure ' + @procedure + ' Line ' + CONVERT(VARCHAR, @line))
			PRINT('		Message ' + @message)

			-- wenn es noch offene transaktionen aus sp_refreshview gibt,
			-- diese rückgängig machen,
			-- da sonst folgefehler bei der nächsten view kommen
			-- tritt bei tests auf sql 2008 auf
			IF @xstate = -1 BEGIN
				PRINT('		Rolling back open transaction...')
				ROLLBACK;
			END

		END CATCH
		FETCH NEXT FROM view_cursor INTO @SchemaView
	END
CLOSE view_cursor
DEALLOCATE view_cursor
GO

--#endregion ----------- Views aktualisieren ---------------------
--#region ----------- UpdateLog verkleineren ------------------
--Aufräumen
DELETE FROM Settings WHERE IsGlobalSetting = 0 AND NOT EXISTS (SELECT * FROM Users WHERE Users.UserID = Settings.uc )

Print ('Alter TruncateUpdateLog...')
GO
ALTER PROCEDURE dbo.TruncateUpdateLog
	@fromDate DATE
AS
BEGIN	
	BEGIN TRY
		BEGIN TRANSACTION
		DECLARE @treuncatedrows INT
		DECLARE @total INT
		SELECT @treuncatedrows = COUNT(*) FROM UpdateLog WHERE LC <= @fromDate
		SELECT @total = COUNT(*) FROM UpdateLog
		PRINT 'TruncateUpdateLog from: ' + CAST(@fromDate AS VARCHAR(10)) + ' Total: ' + CAST( @total AS VARCHAR(100)) + ' Delete: ' + CAST( @treuncatedrows AS VARCHAR(100))

		IF (@treuncatedrows < 10000)
			BEGIN
				PRINT  'Delete rows: '  + CAST( @treuncatedrows AS VARCHAR(100))
				DELETE FROM UpdateLog WHERE LC <= @fromDate
			END
		ELSE
			BEGIN
				CREATE TABLE #UpdateLogTEMP(
					UpdateLogId INT NOT NULL,
					WinUser VARCHAR(100) NOT NULL,
					LogText VARCHAR(MAX) NOT NULL,
					LogArt TINYINT NOT NULL,
					LC DATETIME2(3) NOT NULL,
					UC INT NULL,
					LogTable VARCHAR(100) NOT NULL,
					PKValue INT NULL,
					PKField VARCHAR(100) NULL,
					TransactionId INT NULL)
						
				PRINT  'In Temp. rows: '  + CAST((@total - @treuncatedrows) AS VARCHAR(100))
				INSERT INTO #UpdateLogTEMP WITH (TABLOCK) (UpdateLogId, WinUser, LogText, LogArt, LC, UC, LogTable, PKValue, PKField, TransactionId)
				SELECT									   UpdateLogId, WinUser, LogText, LogArt, LC, UC, LogTable, PKValue, PKField, TransactionId
				FROM UpdateLog WHERE LC > @fromDate

				PRINT  'Truncat UpdateLog' 
				TRUNCATE TABLE UpdateLog

				PRINT  'Back to Log. rows: '  + CAST((@total-@treuncatedrows) AS VARCHAR(100))
				SET IDENTITY_INSERT UpdateLog ON
					INSERT INTO UpdateLog WITH (TABLOCK) (UpdateLogId, WinUser, LogText, LogArt, LC, UC, LogTable, PKValue, PKField, TransactionId)
					SELECT								  UpdateLogId, WinUser, LogText, LogArt, LC, UC, LogTable, PKValue, PKField, TransactionId
					FROM dbo.#UpdateLogTEMP 
				SET IDENTITY_INSERT updateLog OFF

				PRINT  'Drop temp '
				DROP TABLE #UpdateLogTEMP
			END
			COMMIT TRANSACTION
		PRINT  'Removed rows: ' + CAST(@treuncatedrows AS VARCHAR(100))
		END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		PRINT 'Error'
	END CATCH
END
GO
PRINT ('Execute TruncateUpdateLog...')
GO
DECLARE @from DATE
SELECT @from = GETDATE()-1095
EXECUTE TruncateUpdateLog @from



--DECLARE @Date DATETIME;
--SET @Date = GETDATE()-100;

--DECLARE @Deleted_Rows INT;
--SET @Deleted_Rows = 1;

--DECLARE @All_Rows INT;
--SELECT @All_Rows = COUNT(*) FROM Updatelog WHERE lc < @Date
  
--  DECLARE @All_Deleted_Rows INT;
--  SET @All_Deleted_Rows = 1;
--WHILE (@Deleted_Rows > 0)
--  BEGIN
  
--  DELETE TOP (10000)  Updatelog WHERE lc < @Date

--  SET @Deleted_Rows = @@ROWCOUNT;
--  SET @All_Deleted_Rows = @All_Deleted_Rows + @Deleted_Rows;

--  PRINT 'DELETED: ' + CAST(@All_Deleted_Rows  AS VARCHAR)  + '/ FROM: ' +   CAST(@All_Rows  AS VARCHAR) + '/ REMAINING: ' +   CAST(@All_Rows-@All_Deleted_Rows  AS VARCHAR)
--  RAISERROR(N'', 0, 1) WITH NOWAIT
--END


GO
--#endregion 
--#region ----------- zum Löschen in 2021 vormarkiert ---------
--PlanZR
--Attachment Type
--FormulaConfigurations_Departments
--Departments: VisibleDaysNumber, TimePartitionMinutes, VisibleDaySums, VisibleColumns, ColWidth, VisibleAreas, ActivitiesTimePartitions
--EXEC sp_rename 'ResourceObjects.ResourceData', 'x_ResourceData', 'COLUMN';
	--ContractDepartments.DefaultWorkAreaGroupId
	--WorkAreaGroupMembers.WorkAreaGroupId
	--TechnicalJobs.WorkAreaGroupId
	--RoleTypes.RoleTypeCategory
	--ContractSalaryRules.IsDefaultValue
--#endregion
--------------------------------------------------------------
--#region ----------- Wegräumen der Hilfsprozeduren -----------
Print ('Clean up...')
GO
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropIndexByTable'))			DROP PROCEDURE dbo.DropIndexByTable
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropColumn'))					DROP PROCEDURE dbo.DropColumn 
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropDefaultConstraint'))		DROP PROCEDURE dbo.DropDefaultConstraint 
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].DropRoleWithDropRoleMember'))	DROP PROCEDURE dbo.DropRoleWithDropRoleMember 
IF EXISTS (SELECT * FROM sys.objects o WHERE  o.object_id = OBJECT_ID(N'[dbo].PrepareUniqueColumnIndex'))	DROP PROCEDURE dbo.PrepareUniqueColumnIndex
GO
--#endregion ----------- Wegräumen der Hilfsprozeduren -----------
---------------------------------------------------------------
--#region ----------- VERSIONIERUNG ---------------------------
--#region ----------- Version aus ts_evt in TS_DataClass ------
DECLARE @major INT
DECLARE @minor INT
DECLARE @build INT
DECLARE @Datum DATE
----------
SET @major = 4
SET @minor = 216
SET @build = 103
SET @Datum = '20220211'
--#endregion ----------- Version aus ts_evt in TS_DataClass ------
--#region ----------- Version setzen ---------------------------
PRINT('Updating NvData...')
IF NOT EXISTS (SELECT * FROM  NvData WHERE ByModulScript = 1)
BEGIN
	INSERT INTO NvData (VersionDate, ByModulScript)
	VALUES				('19000101', 1)
END

--Ausführungen des Datenbankskripts werden geloggt.
--Diese haben für ByModulScript den Wert 2
INSERT INTO NVData
		  (VersionDate, ByModulScript, Major, Minor, LastDatabaseUpdateDate, Build) 
	SELECT VersionDate, 2,             Major, Minor, LastDataBaseUpdateDate, Build 
	FROM NVData 
	WHERE ByModulScript = 1

--Version setzen.

--Diese hat für ByModulScript den Wert 1.
UPDATE NvData
SET Major = @major, Minor = @minor, Build = @build, VersionDate = @Datum, LastDatabaseUpdateDate = GetDate()
WHERE ByModulScript = 1

PRINT	('		Script version ' + CAST(@major AS VARCHAR(4))+'.'+ CAST(@minor AS VARCHAR(4))+'.'+CAST(@build AS VARCHAR(4)) + ' finished.		')
GO

--#endregion  ----------- Version setzen ---------------------------
--#endregion ----------- VERSIONIERUNG ---------------------------
--#region ----------- NOEXEC OFF ------------------------------
SET NOEXEC OFF
--#endregion ----------- NOEXEC OFF ------------------------------