SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetDurationByFinishDate
		   	(@CalendarId int,
			@StartDate datetime,
			@EndDate datetime
			)
RETURNS INT AS
BEGIN
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @StartDate = [dbo].GetLocalDate(@TimeZoneId, @StartDate)
SET @EndDate = [dbo].GetLocalDate(@TimeZoneId, @EndDate)
DECLARE @DayOfWeek tinyint
DECLARE @Duration int, @DayDuration int
SET @Duration = 0
SET @DayDuration = 0
DECLARE @StartTime smallint
SET @StartTime = DATEPART(hh, @StartDate) * 60 + DATEPART(mi, @StartDate)
DECLARE @EndTime smallint
SET @EndTime = 24*60
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@StartTime, @StartDate)
WHILE @ProcessDate <= @EndDate BEGIN
	IF DATEDIFF(dd, @ProcessDate, @EndDate) = 0
			SET @EndTime = DATEPART(hh, @EndDate) * 60 + DATEPART(mi, @EndDate)
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(CASE WHEN ToTime < @EndTime THEN ToTime ELSE @EndTime END  - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		  FROM CAL_EXCEPTION_HOURS
		  WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND ToTime > @StartTime AND FromTime < @EndTime
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(CASE WHEN ToTime < @EndTime THEN ToTime ELSE @EndTime END - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		  FROM CAL_WEEKDAYS
		  WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime AND FromTime < @EndTime
	END
	IF @DayDuration IS NOT NULL
		SET @Duration = @Duration + @DayDuration
	SET @ProcessDate = DATEADD(dd, 1, @ProcessDate)
	SET @StartTime = 0
END
RETURN @Duration
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetFinishDateByDuration
		 (@CalendarId int,
		  @StartDate datetime,
		  @Duration int)
RETURNS DateTime AS
BEGIN
DECLARE @EndDate datetime
DECLARE @FromTime smallint, @ToTime smallint
DECLARE @IntervalDuration smallint
DECLARE @DayDuration smallint
DECLARE @DayOfWeek tinyint
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @StartDate = [dbo].GetLocalDate(@TimeZoneId, @StartDate)
DECLARE @StartTime smallint
SET @StartTime = DATEPART(hh, @StartDate) * 60 + DATEPART(mi, @StartDate)
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@StartTime, @StartDate)
WHILE @Duration >= 0 BEGIN
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(ToTime - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		 FROM CAL_EXCEPTION_HOURS
		 WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND ToTime > @StartTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration <= @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END AS FromTime, ToTime
					 FROM CAL_EXCEPTION_HOURS
					 WHERE ExceptionId IN
						(SELECT ExceptionId
						  FROM CAL_EXCEPTIONS
						  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
						AND ToTime > @StartTime
					 ORDER BY FromTime
				BREAK
			END
		END
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(ToTime - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		 FROM CAL_WEEKDAYS
		 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration <= @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END AS FromTime, ToTime
					 FROM CAL_WEEKDAYS
					 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime
					 ORDER BY FromTime
				BREAK
			END
		END
	END
	SET @ProcessDate = DATEADD(dd, 1, @ProcessDate)
	SET @StartTime = 0
END
OPEN HoursCursor
FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @IntervalDuration = @ToTime - @FromTime
	IF @IntervalDuration <= @Duration
		SET @Duration = @Duration - @IntervalDuration
	ELSE BEGIN
		SET @EndDate = DATEADD(mi, @FromTime + @Duration,@ProcessDate)
		BREAK
	END
	FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
END
CLOSE HoursCursor
DEALLOCATE HoursCursor
return [dbo].GetUTCDateFromLocal(@TimeZoneId, @EndDate)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetLocalDate
		 (@TimeZoneId int,
		  @UTCDate datetime)
RETURNS DateTime AS
BEGIN
DECLARE @TimeOffset int
SELECT @TimeOffset = TimeOffset
FROM TimeZones_UTC_Local
WHERE TimeZoneId = @TimeZoneId AND Start <= @UTCDate AND [End] > @UTCDate
IF @TimeOffset IS NULL
	SELECT @TimeOffset = -Bias FROM TimeZones WHERE TimeZoneId = @TimeZoneId
RETURN DATEADD(mi, @TimeOffset, @UTCDate)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetNextOutlineNum
		(@OLD_NUM VARCHAR(255),
		@CUR_LEVEL INT,
		@PREV_LEVEL INT)
RETURNS VARCHAR(255)  AS
BEGIN
	DECLARE @POSITION INT, @NEW_NUM VARCHAR(255);
	IF(@CUR_LEVEL < @PREV_LEVEL)
		WHILE(@PREV_LEVEL > @CUR_LEVEL)
		BEGIN
			SET @POSITION = PATINDEX('%.%', REVERSE(@OLD_NUM)) ;
			SET @OLD_NUM = LEFT(@OLD_NUM,LEN(@OLD_NUM)-@POSITION)
			SET @CUR_LEVEL = @CUR_LEVEL + 1
		END
	ELSE
	IF(@CUR_LEVEL > @PREV_LEVEL)
		RETURN @OLD_NUM+'.1'
	SET @POSITION = PATINDEX('%.%', REVERSE(@OLD_NUM)) ;
	IF @POSITION  <>  0
		Set @NEW_NUM = LEFT(@OLD_NUM,LEN(@OLD_NUM)-@POSITION+1)  + CAST(( RIGHT(@OLD_NUM,@POSITION -1) +1) AS VARCHAR(255))
	ELSE
		 Set @NEW_NUM = CAST(@OLD_NUM+1 AS VARCHAR(255))
RETURN @NEW_NUM
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetStartDateByDuration
		 (@CalendarId int,
		  @FinishDate datetime,
		  @Duration int)
RETURNS DateTime AS
BEGIN
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @FinishDate = [dbo].GetLocalDate(@TimeZoneId, @FinishDate)
DECLARE @StartdDate datetime
DECLARE @FromTime smallint, @ToTime smallint
DECLARE @IntervalDuration smallint
DECLARE @DayDuration smallint
DECLARE @DayOfWeek tinyint
DECLARE @FinishTime smallint
SET @FinishTime = DATEPART(hh, @FinishDate) * 60 + DATEPART(mi, @FinishDate)
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@FinishTime, @FinishDate)
WHILE @Duration >= 0 BEGIN
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END - FromTime)
		 FROM CAL_EXCEPTION_HOURS
		 WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND FromTime <= @FinishTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration < @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT FromTime, CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END AS ToTime
					 FROM CAL_EXCEPTION_HOURS
					 WHERE ExceptionId IN
						(SELECT ExceptionId
						  FROM CAL_EXCEPTIONS
						  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
						AND FromTime <= @FinishTime
					 ORDER BY ToTime DESC
				BREAK
			END
		END
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END - FromTime)
		 FROM CAL_WEEKDAYS
		 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND FromTime <= @FinishTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration < @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT FromTime, CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END AS ToTime
					 FROM CAL_WEEKDAYS
					 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND FromTime <= @FinishTime
					 ORDER BY ToTime DESC
				BREAK
			END
		END
	END
	SET @ProcessDate = DATEADD(dd, -1, @ProcessDate)
	SET @FinishTime = 24*60
END
OPEN HoursCursor
FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @IntervalDuration = @ToTime - @FromTime
	IF @IntervalDuration < @Duration
		SET @Duration = @Duration - @IntervalDuration
	ELSE BEGIN
		SET @StartdDate = DATEADD(mi, @ToTime - @Duration, @ProcessDate)
		BREAK
	END
	FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
END
CLOSE HoursCursor
DEALLOCATE HoursCursor
return [dbo].GetUTCDateFromLocal(@TimeZoneId, @StartdDate)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE FUNCTION [dbo].GetUTCDateFromLocal
		 (@TimeZoneId int,
		  @LocalDate datetime)
RETURNS DateTime AS
BEGIN
DECLARE @TimeOffset  int
SELECT @TimeOffset = TimeOffset
FROM TimeZones_Local_Utc
WHERE TimeZoneId = @TimeZoneId AND Start <= @LocalDate AND [End] > @LocalDate
IF @TimeOffset IS NULL
	SELECT @TimeOffset = Bias FROM TimeZones WHERE TimeZoneId = @TimeZoneId
RETURN DATEADD(mi, @TimeOffset, @LocalDate)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE TABLE [dbo].[ACCOUNTS] (
	[AccountId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[OutlineLevel] [int] NOT NULL ,
	[OutlineNumber] [varchar] (255) NOT NULL ,
	[IsSummary] [bit] NOT NULL ,
	[TCur] [money] NOT NULL ,
	[TSub] [money] NOT NULL ,
	[ECur] [money] NOT NULL ,
	[ESub] [money] NOT NULL ,
	[ACur] [money] NOT NULL ,
	[ASub] [money] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[LastEditorId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ACTIVATION_TYPE_LANGUAGE] (
	[ActivationTypeId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[ActivationTypeName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ACTUAL_FINANCES] (
	[ActualId] [int] IDENTITY (1, 1) NOT NULL ,
	[AccountId] [int] NOT NULL ,
	[ActualDate] [datetime] NOT NULL ,
	[Description] [nvarchar] (250) NOT NULL ,
	[AValue] [money] NOT NULL ,
	[LastEditorId] [int] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[AlertTemplates] (
	[Key] [nvarchar] (100) NOT NULL ,
	[Subject] [nvarchar] (1000) NOT NULL ,
	[Body] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[BroadcastMessages] (
	[MessageId] [int] IDENTITY (1, 1) NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[ExpirationDate] [datetime] NOT NULL ,
	[Text] [ntext] NOT NULL ,
	[CreatorId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[BroadcastRecipients] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[MessageId] [int] NOT NULL ,
	[GroupId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CAL_EXCEPTION_HOURS] (
	[ExceptionHourId] [int] IDENTITY (1, 1) NOT NULL ,
	[ExceptionId] [int] NOT NULL ,
	[FromTime] [int] NOT NULL ,
	[ToTime] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CAL_EXCEPTIONS] (
	[ExceptionId] [int] IDENTITY (1, 1) NOT NULL ,
	[CalendarId] [int] NOT NULL ,
	[FromDate] [datetime] NOT NULL ,
	[ToDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CAL_WEEKDAYS] (
	[WeekDayId] [int] IDENTITY (1, 1) NOT NULL ,
	[CalendarId] [int] NOT NULL ,
	[DayOfWeek] [tinyint] NOT NULL ,
	[FromTime] [int] NOT NULL ,
	[ToTime] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CATEGORIES] (
	[CategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[CategoryName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CATEGORY_USER] (
	[CategoryId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_ACCOUNTS] (
	[CollapsedId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[AccountId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_DOCUMENTS] (
	[UserId] [int] NOT NULL ,
	[ProjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_INCIDENTS] (
	[UserId] [int] NOT NULL ,
	[ProjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_MANAGERTIMESHEETS] (
	[ManagerId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_TASKS] (
	[CollapsedId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[TaskId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COLLAPSED_USERTIMESHEETS] (
	[UserId] [int] NOT NULL ,
	[ProjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COMPLETION_REASON_LANGUAGE] (
	[ReasonId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[ReasonName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COMPLETION_TYPE_LANGUAGE] (
	[CompletionTypeId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[CompletionTypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CONSTRAINT_TYPE_LANGUAGE] (
	[ConstraintTypeId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[ConstraintTypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CONTENT_TYPES] (
	[ContentTypeId] [int] IDENTITY (1, 1) NOT NULL ,
	[Extension] [nvarchar] (10) NOT NULL ,
	[ContentTypeString] [nvarchar] (250) NOT NULL ,
	[IconFileId] [int] NULL ,
	[BigIconFileId] [int] NULL ,
	[FriendlyName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DATE_TYPE_HANDLERS] (
	[HandlerId] [int] IDENTITY (1, 1) NOT NULL ,
	[HandlerName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DATE_TYPE_HOOKS] (
	[HookId] [int] IDENTITY (1, 1) NOT NULL ,
	[DateTypeId] [int] NOT NULL ,
	[ObjectId] [int] NULL ,
	[Lag] [int] NOT NULL ,
	[HandlerId] [int] NOT NULL ,
	[Params] [nvarchar] (1024) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DATE_TYPE_PROCESSED] (
	[ProcessedId] [int] IDENTITY (1, 1) NOT NULL ,
	[ValueId] [int] NOT NULL ,
	[HookId] [int] NOT NULL ,
	[DateValue] [datetime] NOT NULL ,
	[Lag] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DATE_TYPE_VALUES] (
	[ValueId] [int] IDENTITY (1, 1) NOT NULL ,
	[DateTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[DateValue] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DATE_TYPES] (
	[DateTypeId] [int] NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[DateTypeName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DISCUSSIONS] (
	[DiscussionId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[Text] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[EMAILS] (
	[EmailId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[Email] [nvarchar] (250) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EVENT_REMINDER] (
	[ReminderId] [int] IDENTITY (1, 1) NOT NULL ,
	[EventId] [int] NOT NULL ,
	[Interval] [int] NOT NULL ,
	[WasSent] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EVENT_TYPE_LANGUAGE] (
	[TypeId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[TypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EXTERNAL_GATE] (
	[GateId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[UserId] [int] NULL ,
	[Email] [nvarchar] (250) NULL ,
	[GUID] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[FAVORITES] (
	[FavoriteId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_FileBinaries] (
	[FileBinaryId] [int] IDENTITY (1, 1) NOT NULL ,
	[Data] [image] NULL ,
	[ContentTypeId] [int] NULL ,
	[DownloadCount] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_Files] (
	[FileId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[DirectoryId] [int] NOT NULL ,
	[FileBinaryId] [int] NULL ,
	[CreatorId] [int] NULL ,
	[Created] [datetime] NOT NULL ,
	[ModifierId] [int] NULL ,
	[Modified] [datetime] NOT NULL ,
	[AllowHistory] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_Files_History] (
	[Id] [int] IDENTITY (1, 1) NOT NULL ,
	[FileId] [int] NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[DirectoryId] [int] NOT NULL ,
	[FileBinaryId] [int] NULL ,
	[ModifierId] [int] NOT NULL ,
	[Modified] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_Forums] (
	[ForumId] [int] IDENTITY (1, 1) NOT NULL ,
	[ContainerKey] [nvarchar] (50) NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ForumThreadNodes] (
	[NodeId] [int] IDENTITY (1, 1) NOT NULL ,
	[ThreadId] [int] NOT NULL ,
	[Text] [ntext] NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[CreatorId] [int] NULL ,
	[CreatorName] [nvarchar] (255) NULL ,
	[CreatorEmail] [nvarchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ForumThreads] (
	[ThreadId] [int] IDENTITY (1, 1) NOT NULL ,
	[ForumId] [int] NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ReportAccessControlEntries] (
	[AceId] [int] IDENTITY (1, 1) NOT NULL ,
	[AclId] [int] NOT NULL ,
	[Role] [nvarchar] (50) NULL ,
	[PrincipalId] [int] NULL ,
	[Action] [nvarchar] (50) NOT NULL ,
	[Allow] [bit] NOT NULL ,
	[IsInternal] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ReportAccessControlLists] (
	[AclId] [int] IDENTITY (1, 1) NOT NULL ,
	[ReportId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ReportCategories] (
	[ReportCategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_Reports] (
	[ReportId] [int] IDENTITY (1, 1) NOT NULL ,
	[ContainerKey] [nvarchar] (50) NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[ReportCategoryId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[HIDDEN_STUBS] (
	[HidedStubId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[StubId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[HISTORY] (
	[HistoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectTitle] [nvarchar] (250) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[Dt] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_CATEGORIES] (
	[CategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[CategoryName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_CATEGORY] (
	[IncidentCategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[IncidentId] [int] NOT NULL ,
	[CategoryId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_RELATIONS] (
	[RelationId] [int] IDENTITY (1, 1) NOT NULL ,
	[IncidentId] [int] NOT NULL ,
	[RelIncidentId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_STATUS_LANGUAGE] (
	[StatusId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENTCATEGORY_USER] (
	[CategoryId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LANGUAGES] (
	[LanguageId] [int] NOT NULL ,
	[Locale] [varchar] (50) NOT NULL ,
	[FriendlyName] [nvarchar] (50) NOT NULL ,
	[IsDefault] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_ITEMS] (
	[ItemId] [int] IDENTITY (1, 1) NOT NULL ,
	[ListId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[LastEditorId] [int] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_STATUS_LANGUAGE] (
	[StatusId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MESSAGE_LOG] (
	[LogId] [int] IDENTITY (1, 1) NOT NULL ,
	[Sent] [datetime] NOT NULL ,
	[Subject] [nvarchar] (1000) NOT NULL ,
	[Body] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MESSAGE_TYPES] (
	[MessageTypeId] [int] IDENTITY (1, 1) NOT NULL ,
	[MessageTypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaAttribute] (
	[AttrOwnerId] [int] NOT NULL ,
	[AttrOwnerType] [int] NOT NULL ,
	[Key] [nvarchar] (256) NOT NULL ,
	[Value] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaClass] (
	[MetaClassId] [int] IDENTITY (1, 1) NOT NULL ,
	[Namespace] [nvarchar] (1024) NOT NULL ,
	[Name] [nvarchar] (256) NOT NULL ,
	[FriendlyName] [nvarchar] (256) NOT NULL ,
	[IsSystem] [bit] NOT NULL ,
	[IsAbstract] [bit] NOT NULL ,
	[ParentClassId] [int] NOT NULL ,
	[TableName] [nvarchar] (256) NOT NULL ,
	[PrimaryKeyName] [nvarchar] (256) NOT NULL ,
	[Description] [ntext] NULL ,
	[FieldListChangedSqlScript] [ntext] NULL ,
	[Tag] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaClassMetaFieldRelation] (
	[MetaClassId] [int] NOT NULL ,
	[MetaFieldId] [int] NOT NULL ,
	[Weight] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaDataType] (
	[DataTypeId] [int] NOT NULL ,
	[Name] [nvarchar] (256) NOT NULL ,
	[FriendlyName] [nvarchar] (256) NOT NULL ,
	[Description] [ntext] NULL ,
	[Length] [int] NOT NULL ,
	[SqlName] [nvarchar] (256) NOT NULL ,
	[AllowNulls] [bit] NOT NULL ,
	[Variable] [bit] NOT NULL ,
	[IsSQLCommonType] [bit] NOT NULL ,
	[DefaultValue] [nvarchar] (256) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaDictionary] (
	[MetaDictionaryId] [int] IDENTITY (1, 1) NOT NULL ,
	[MetaFieldId] [int] NOT NULL ,
	[Value] [nvarchar] (2048) NOT NULL ,
	[Tag] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaField] (
	[MetaFieldId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (256) NOT NULL ,
	[Namespace] [nvarchar] (1024) NOT NULL ,
	[SystemMetaClassId] [int] NOT NULL ,
	[FriendlyName] [nvarchar] (256) NOT NULL ,
	[Description] [ntext] NULL ,
	[DataTypeId] [int] NOT NULL ,
	[Length] [int] NOT NULL ,
	[AllowNulls] [bit] NOT NULL ,
	[SaveHistory] [bit] NOT NULL ,
	[MultiLanguageValue] [bit] NOT NULL ,
	[AllowSearch] [bit] NOT NULL ,
	[Tag] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaFileValue] (
	[MetaKey] [int] NOT NULL ,
	[FileName] [nvarchar] (256) NULL ,
	[ContentType] [nvarchar] (50) NULL ,
	[Data] [image] NULL ,
	[Size] [int] NOT NULL ,
	[CreationTime] [datetime] NOT NULL ,
	[LastWriteTime] [datetime] NOT NULL ,
	[LastReadTime] [datetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaKey] (
	[MetaKey] [int] IDENTITY (1, 1) NOT NULL ,
	[MetaObjectId] [int] NOT NULL ,
	[MetaClassId] [int] NOT NULL ,
	[MetaFieldId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaMultiValueDictionary] (
	[MetaKey] [int] NOT NULL ,
	[MetaDictionaryId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaObjectValue] (
	[MetaKey] [int] NOT NULL ,
	[MetaClassId] [int] NOT NULL ,
	[MetaObjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaRule] (
	[RuleId] [int] IDENTITY (1, 1) NOT NULL ,
	[MetaClassId] [int] NOT NULL ,
	[Data] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[MetaStringDictionaryValue] (
	[MetaKey] [int] NOT NULL ,
	[Key] [nvarchar] (512) NOT NULL ,
	[Value] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_CATEGORY] (
	[ObjectCategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[CategoryId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_MENUS] (
	[MenuId] [int] IDENTITY (1, 1) NOT NULL ,
	[Description] [nvarchar] (500) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_MENUS_LANGUAGE] (
	[MenuId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[MenuXML] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_ROLES] (
	[ObjectRoleId] [int] NOT NULL ,
	[ObjectRoleName] [nvarchar] (50) NOT NULL ,
	[ObjectTypeId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_STATE_LANGUAGE] (
	[StateId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[StateName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_VIEW_PAGES] (
	[ViewPageId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[MenuId] [int] NOT NULL ,
	[ShortInfoPath] [nvarchar] (250) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_VIEW_PAGES_LANGUAGE] (
	[ViewPageLanguageId] [int] IDENTITY (1, 1) NOT NULL ,
	[ViewPageId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[Title] [nvarchar] (500) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_VIEW_TABS] (
	[TabId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[TemplateId] [int] NOT NULL ,
	[IsDefault] [bit] NOT NULL ,
	[RowNum] [int] NOT NULL ,
	[PosNum] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_VIEW_TABS_LANGUAGE] (
	[TabId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[Title] [nvarchar] (500) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_VIEW_TEMPLATES] (
	[TemplateId] [int] IDENTITY (1, 1) NOT NULL ,
	[Preview] [image] NULL ,
	[Description] [nvarchar] (500) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[page_ControlProperties] (
	[Id] [int] IDENTITY (1, 1) NOT NULL ,
	[PageUID] [nvarchar] (250) NOT NULL ,
	[ControlPlaceID] [nvarchar] (250) NOT NULL ,
	[ControlIndex] [int] NOT NULL ,
	[ControlUID] [nvarchar] (250) NOT NULL ,
	[ControlProperties] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[PARTNER_GROUP] (
	[PartnerId] [int] NOT NULL ,
	[GroupId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[POP3_INCIDENTS] (
	[IncidentId] [int] IDENTITY (1, 1) NOT NULL ,
	[MailboxId] [int] NOT NULL ,
	[From] [nvarchar] (255) NOT NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NOT NULL ,
	[PriorityId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[FirstName] [nvarchar] (50) NOT NULL ,
	[LastName] [nvarchar] (50) NOT NULL ,
	[MHTFileId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Pop3Boxes] (
	[Pop3BoxId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (255) NULL ,
	[Server] [nvarchar] (255) NOT NULL ,
	[Port] [int] NOT NULL ,
	[Login] [nvarchar] (255) NOT NULL ,
	[Password] [nvarchar] (255) NOT NULL ,
	[Active] [bit] NOT NULL ,
	[Interval] [int] NOT NULL ,
	[LastRequest] [datetime] NULL ,
	[LastSuccessfulRequest] [datetime] NULL ,
	[LastErrorText] [nvarchar] (255) NULL ,
	[AutoKillForRead] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Pop3BoxParameters] (
	[Pop3BoxParameterId] [int] IDENTITY (1, 1) NOT NULL ,
	[Pop3BoxId] [int] NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[Value] [nvarchar] (255) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Pop3BoxPop3DocumentHandler] (
	[Pop3HandlerId] [int] IDENTITY (1, 1) NOT NULL ,
	[Pop3BoxId] [int] NOT NULL ,
	[HandlerName] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Pop3MailRequests] (
	[Pop3MailRequestId] [int] IDENTITY (1, 1) NOT NULL ,
	[Sender] [nvarchar] (250) NOT NULL ,
	[SenderIbnUserId] [int] NULL ,
	[FirstName] [nvarchar] (50) NOT NULL ,
	[LastName] [nvarchar] (50) NOT NULL ,
	[Subject] [nvarchar] (1024) NOT NULL ,
	[InnerText] [ntext] NOT NULL ,
	[Priority] [int] NOT NULL ,
	[Pop3BoxId] [int] NOT NULL ,
	[Received] [datetime] NOT NULL ,
	[MhtFileId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Pop3MessageUIds] (
	[Pop3MessageId] [int] IDENTITY (1, 1) NOT NULL ,
	[Pop3BoxId] [int] NOT NULL ,
	[MessageUId] [varchar] (70) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PORTAL_LOGINS] (
	[UserId] [int] NOT NULL ,
	[LoginTime] [datetime] NOT NULL ,
	[IP] [varchar] (15) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PRIORITY_LANGUAGE] (
	[PriorityId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[PriorityName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_CATEGORIES] (
	[CategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[CategoryName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_CATEGORY] (
	[ProjectCategoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[CategoryId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_GROUP] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[ProjectGroupId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_GROUPS] (
	[ProjectGroupId] [int] IDENTITY (1, 1) NOT NULL ,
	[Title] [nvarchar] (100) NOT NULL ,
	[Description] [ntext] NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[CreatorId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_MEMBERS] (
	[MemberId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[Code] [nchar] (2) NULL ,
	[Rate] [money] NOT NULL ,
	[IsTeamMember] [bit] NOT NULL ,
	[IsSponsor] [bit] NOT NULL ,
	[IsStakeHolder] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_RELATIONS] (
	[RelationId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[RelProjectId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_SNAPSHOTS] (
	[SnapshotId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[StatusId] [int] NOT NULL ,
	[TargetBudget] [money] NOT NULL ,
	[EstimatedBudget] [money] NOT NULL ,
	[ActualBudget] [money] NOT NULL ,
	[StartDate] [datetime] NOT NULL ,
	[FinishDate] [datetime] NOT NULL ,
	[TargetFinishDate] [datetime] NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[PhaseId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_STATUS_LANGUAGE] (
	[StatusId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_TEMPLATES] (
	[TemplateId] [int] IDENTITY (1, 1) NOT NULL ,
	[TemplateName] [nvarchar] (255) NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[LastEditorId] [int] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[TemplateData] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_USER_DATE] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[UserId] [int] NOT NULL ,
	[GanttStartDate] [datetime] NULL ,
	[GanttDateLength] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECTCATEGORY_USER] (
	[CategoryId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECTGROUP_USER] (
	[ProjectGroupId] [int] NOT NULL ,
	[UserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[RECURRENCE] (
	[RecurrenceId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[StartTime] [int] NOT NULL ,
	[EndTime] [int] NOT NULL ,
	[Pattern] [tinyint] NOT NULL ,
	[SubPattern] [tinyint] NOT NULL ,
	[Frequency] [tinyint] NOT NULL ,
	[Weekdays] [tinyint] NOT NULL ,
	[DayOfMonth] [tinyint] NOT NULL ,
	[WeekNumber] [tinyint] NOT NULL ,
	[MonthNumber] [tinyint] NOT NULL ,
	[EndAfter] [int] NOT NULL ,
	[TimeZoneId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[REMINDER_SUBSCRIPTIONS] (
	[SubscriptionId] [int] IDENTITY (1, 1) NOT NULL ,
	[DateTypeId] [int] NOT NULL ,
	[UserId] [int] NULL ,
	[ObjectId] [int] NULL ,
	[Lag] [int] NOT NULL ,
	[IsActive] [bit] NOT NULL ,
	[HookId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Report] (
	[ReportId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[LastEditorId] [int] NOT NULL ,
	[IBNReportTemplate] [ntext] NOT NULL ,
	[IsGlobal] [bit] NOT NULL ,
	[IsTemporary] [bit] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[ReportHistory] (
	[ReportItemId] [int] IDENTITY (1, 1) NOT NULL ,
	[ReportId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[ReportData] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[SCHEDULE] (
	[ScheduleId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[ContUserId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ScheduleProcessHandlerTempItems] (
	[Id] [int] IDENTITY (1, 1) NOT NULL ,
	[Created] [datetime] NOT NULL ,
	[IsProcessed] [bit] NOT NULL ,
	[Processed] [datetime] NULL ,
	[DateTypeName] [nvarchar] (100) NOT NULL ,
	[ObjectTypeId] [int] NULL ,
	[ObjectId] [int] NULL ,
	[Dt] [datetime] NOT NULL ,
	[HookId] [int] NOT NULL ,
	[HandlerId] [int] NOT NULL ,
	[Params] [nvarchar] (1024) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SHARING] (
	[SharingId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[ProUserId] [int] NOT NULL ,
	[Level] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[STUB_GROUP] (
	[StubGroupId] [int] IDENTITY (1, 1) NOT NULL ,
	[StubId] [int] NOT NULL ,
	[GroupId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[STUBS] (
	[StubId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NULL ,
	[Abbreviation] [nchar] (2) NOT NULL ,
	[ToolTip] [nvarchar] (250) NOT NULL ,
	[Url] [varchar] (1000) NOT NULL ,
	[Icon] [image] NULL ,
	[OpenInBrowser] [bit] NOT NULL ,
	[Width] [int] NOT NULL ,
	[Height] [int] NOT NULL ,
	[IsInternal] [bit] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[SUBSCRIPTION_DETAILS] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[SubscriptionId] [int] NOT NULL ,
	[ObjectRoleId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SUBSCRIPTIONS] (
	[SubscriptionId] [int] IDENTITY (1, 1) NOT NULL ,
	[EventTypeId] [int] NOT NULL ,
	[UserId] [int] NULL ,
	[ObjectId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SYSTEM_EVENT_RECIPIENTS] (
	[RecipientId] [int] IDENTITY (1, 1) NOT NULL ,
	[SystemEventId] [int] NOT NULL ,
	[UserId] [int] NULL ,
	[MessageTypeId] [int] NOT NULL ,
	[Email] [nvarchar] (250) NULL ,
	[Processed] [bit] NOT NULL ,
	[SendEmail] [bit] NOT NULL ,
	[SendIbn] [bit] NOT NULL ,
	[SentEmail] [bit] NOT NULL ,
	[SentIbn] [bit] NOT NULL ,
	[LogId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SYSTEM_EVENT_TYPES] (
	[EventTypeId] [int] NOT NULL ,
	[ParentId] [int] NOT NULL ,
	[ObjectTypeId] [int] NULL ,
	[RelObjectTypeId] [int] NULL ,
	[Title] [nvarchar] (100) NOT NULL ,
	[IsActive] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[SYSTEM_EVENTS] (
	[SystemEventId] [int] IDENTITY (1, 1) NOT NULL ,
	[EventTypeId] [int] NOT NULL ,
	[ObjectId] [int] NULL ,
	[ObjectTitle] [nvarchar] (250) NOT NULL ,
	[RelObjectId] [int] NULL ,
	[RelObjectTitle] [nvarchar] (250) NOT NULL ,
	[Dt] [datetime] NOT NULL ,
	[UserId] [int] NULL ,
	[TranId] [char] (36) NOT NULL ,
	[XMLData] [ntext] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[TASK_LINKS] (
	[LinkId] [int] IDENTITY (1, 1) NOT NULL ,
	[PredId] [int] NOT NULL ,
	[SuccId] [int] NOT NULL ,
	[Lag] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TASK_UPDATES] (
	[UpdateId] [uniqueidentifier] NOT NULL ,
	[TaskId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMESHEET_STATUS] (
	[StatusId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMESHEET_TODO] (
	[TimeSheetToDoId] [int] IDENTITY (1, 1) NOT NULL ,
	[Title] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMESHEETS] (
	[TimesheetId] [int] IDENTITY (1, 1) NOT NULL ,
	[WeekTimesheetId] [int] NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectId] [int] NOT NULL ,
	[Day1] [int] NOT NULL ,
	[Day2] [int] NOT NULL ,
	[Day3] [int] NOT NULL ,
	[Day4] [int] NOT NULL ,
	[Day5] [int] NOT NULL ,
	[Day6] [int] NOT NULL ,
	[Day7] [int] NOT NULL ,
	[TotalApproved] [int] NOT NULL ,
	[Rate] [money] NOT NULL ,
	[UserComments] [ntext] NOT NULL ,
	[ActualId] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMEZONES_LANGUAGE] (
	[TimeZoneId] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[DisplayName] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMEZONES_LOCAL_UTC] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[TimeZoneId] [int] NOT NULL ,
	[Start] [datetime] NOT NULL ,
	[End] [datetime] NOT NULL ,
	[TimeOffset] [int] NOT NULL ,
	[IsDaylight] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMEZONES_UTC_LOCAL] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[TimeZoneId] [int] NOT NULL ,
	[Start] [datetime] NOT NULL ,
	[End] [datetime] NOT NULL ,
	[TimeOffset] [int] NOT NULL ,
	[IsDayLight] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USER_DETAILS] (
	[UserId] [int] NOT NULL ,
	[phone] [nvarchar] (100) NULL ,
	[fax] [nvarchar] (100) NULL ,
	[mobile] [nvarchar] (100) NULL ,
	[position] [nvarchar] (100) NULL ,
	[department] [nvarchar] (100) NULL ,
	[company] [nvarchar] (100) NULL ,
	[location] [nvarchar] (100) NULL ,
	[PictureUrl] [nvarchar] (1024) NULL ,
	[PictureFileId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USER_PREFERENCES] (
	[UserId] [int] NOT NULL ,
	[IsNotified] [bit] NOT NULL ,
	[IsNotifiedByEmail] [bit] NOT NULL ,
	[IsNotifiedByIBN] [bit] NOT NULL ,
	[IsBatchNotifications] [bit] NOT NULL ,
	[Period] [int] NOT NULL ,
	[From] [int] NOT NULL ,
	[Till] [int] NOT NULL ,
	[LanguageId] [int] NOT NULL ,
	[TimeZoneId] [int] NOT NULL ,
	[TimeOffsetLatest] [int] NOT NULL ,
	[MenuInAlerts] [bit] NOT NULL ,
	[ReminderType] [int] NOT NULL ,
	[BatchLastSent] [datetime] NULL ,
	[BatchNextSend] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USER_PROJECT_TEAM] (
	[UserId] [int] NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[MemberId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USER_SETTINGS] (
	[SettingId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[Key] [nvarchar] (100) NOT NULL ,
	[Value] [ntext] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[WeekTimeSheet] (
	[WeekTimeSheetId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[ProjectId] [int] NULL ,
	[StartDate] [datetime] NOT NULL ,
	[StatusId] [int] NOT NULL ,
	[ManagerComments] [ntext] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[LastEditorId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[ACTIVATION_TYPES] (
	[ActivationTypeId] [int] NOT NULL ,
	[ActivationTypeName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CLIENTS] (
	[ClientId] [int] IDENTITY (1, 1) NOT NULL ,
	[ClientName] [nvarchar] (50) NOT NULL ,
	[IsInternal] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COMPLETION_REASONS] (
	[ReasonId] [int] NOT NULL ,
	[ReasonName] [nvarchar] (50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[COMPLETION_TYPES] (
	[CompletionTypeId] [int] NOT NULL ,
	[CompletionTypeName] [nvarchar] (50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CONSTRAINT_TYPES] (
	[ConstraintTypeId] [int] NOT NULL ,
	[ConstraintTypeName] [nvarchar] (50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CURRENCY] (
	[CurrencyId] [int] IDENTITY (1, 1) NOT NULL ,
	[CurrencySymbol] [nvarchar] (10) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EVENT_TYPES] (
	[TypeId] [int] NOT NULL ,
	[TypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_Directories] (
	[DirectoryId] [int] IDENTITY (1, 1) NOT NULL ,
	[ContainerKey] [nvarchar] (50) NOT NULL ,
	[Name] [nvarchar] (255) NOT NULL ,
	[Path] [varchar] (512) NOT NULL ,
	[ParentDirectoryId] [int] NULL ,
	[CreatorId] [int] NULL ,
	[Created] [datetime] NOT NULL ,
	[ModifierId] [int] NULL ,
	[Modified] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_ForeignContainerKeys] (
	[ContainerKey] [nvarchar] (50) NOT NULL ,
	[ForeignContainerKey] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_UserRoles] (
	[UserRoleId] [int] IDENTITY (1, 1) NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[ContainerKey] [nvarchar] (50) NULL ,
	[Role] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_SEVERITY] (
	[SeverityId] [int] IDENTITY (1, 1) NOT NULL ,
	[SeverityName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_TYPES] (
	[TypeId] [int] IDENTITY (1, 1) NOT NULL ,
	[TypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_STATUS] (
	[StatusId] [int] IDENTITY (1, 1) NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_TYPES] (
	[TypeId] [int] IDENTITY (1, 1) NOT NULL ,
	[TypeName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_STATES] (
	[StateId] [int] NOT NULL ,
	[StateName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_TYPES] (
	[ObjectTypeId] [int] NOT NULL ,
	[ObjectTypeName] [nvarchar] (100) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PRINCIPALS] (
	[PrincipalId] [int] IDENTITY (1, 1) NOT NULL ,
	[IsGroup] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PRIORITIES] (
	[PriorityId] [int] NOT NULL ,
	[PriorityName] [nvarchar] (50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_PHASES] (
	[PhaseId] [int] IDENTITY (1, 1) NOT NULL ,
	[PhaseName] [nvarchar] (50) NOT NULL ,
	[Weight] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECT_STATUS] (
	[StatusId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NULL ,
	[IsActive] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[RISK_LEVELS] (
	[RiskLevelId] [int] IDENTITY (1, 1) NOT NULL ,
	[RiskLevelName] [nvarchar] (50) NOT NULL ,
	[Weight] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TIMEZONES] (
	[TimeZoneId] [int] IDENTITY (1, 1) NOT NULL ,
	[Bias] [int] NOT NULL ,
	[StandardBias] [int] NOT NULL ,
	[DaylightBias] [int] NOT NULL ,
	[DaylightMonth] [int] NOT NULL ,
	[DaylightDayOfWeek] [int] NOT NULL ,
	[DaylightWeek] [int] NOT NULL ,
	[DaylightHour] [int] NOT NULL ,
	[StandardMonth] [int] NOT NULL ,
	[StandardDayOfWeek] [int] NOT NULL ,
	[StandardWeek] [int] NOT NULL ,
	[StandardHour] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CONTAINERSHIP] (
	[RowId] [int] IDENTITY (1, 1) NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[ParentPrincipalId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DOCUMENT_STATUS] (
	[StatusId] [int] IDENTITY (1, 1) NOT NULL ,
	[StatusName] [nvarchar] (50) NOT NULL ,
	[IsInternal] [bit] NOT NULL ,
	[StateId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_AccessControlLists] (
	[AclId] [int] IDENTITY (1, 1) NOT NULL ,
	[DirectoryId] [int] NOT NULL ,
	[IsInherited] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[GROUPS] (
	[PrincipalId] [int] NOT NULL ,
	[GroupName] [nvarchar] (250) NOT NULL ,
	[IMGroupId] [int] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_STATUS] (
	[StatusId] [int] IDENTITY (1, 1) NOT NULL ,
	[StateId] [int] NOT NULL ,
	[StatusName] [nvarchar] (50) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[OBJECT_FORMS] (
	[FormId] [int] IDENTITY (1, 1) NOT NULL ,
	[ObjectTypeId] [int] NOT NULL ,
	[FormName] [nvarchar] (50) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USERS] (
	[PrincipalId] [int] NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[Login] [nvarchar] (250) NULL ,
	[Password] [nvarchar] (50) NULL ,
	[FirstName] [nvarchar] (50) NOT NULL ,
	[LastName] [nvarchar] (50) NOT NULL ,
	[Email] [nvarchar] (250) NOT NULL ,
	[Activity] [tinyint] NOT NULL ,
	[IsExternal] [bit] NOT NULL ,
	[IMGroupId] [int] NULL ,
	[OriginalId] [int] NULL ,
	[CreatedBy] [int] NULL ,
	[Comments] [nvarchar] (1024) NULL ,
	[InviteText] [ntext] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[fsc_AccessControlEntries] (
	[AceId] [int] IDENTITY (1, 1) NOT NULL ,
	[AclId] [int] NOT NULL ,
	[IsInherited] [bit] NOT NULL ,
	[Role] [nvarchar] (50) NULL ,
	[PrincipalId] [int] NULL ,
	[Action] [nvarchar] (50) NOT NULL ,
	[Allow] [tinyint] NOT NULL ,
	[IsInternal] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[USER_GROUP] (
	[UserGroupId] [int] IDENTITY (1, 1) NOT NULL ,
	[UserId] [int] NOT NULL ,
	[GroupId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[CALENDARS] (
	[CalendarId] [int] IDENTITY (1, 1) NOT NULL ,
	[CalendarName] [nvarchar] (250) NULL ,
	[ProjectId] [int] NULL ,
	[TimeZoneId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DOCUMENT_RESOURCES] (
	[ResourceId] [int] IDENTITY (1, 1) NOT NULL ,
	[DocumentId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ResponsePending] [bit] NOT NULL ,
	[IsConfirmed] [bit] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[CanManage] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DOCUMENT_TODO] (
	[DocumentToDoId] [int] IDENTITY (1, 1) NOT NULL ,
	[DocumentId] [int] NOT NULL ,
	[ToDoId] [int] NOT NULL ,
	[CompleteDocument] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[DOCUMENTS] (
	[DocumentId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[ProjectId] [int] NULL ,
	[CreatorId] [int] NOT NULL ,
	[ManagerId] [int] NOT NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NOT NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[StatusId] [int] NOT NULL ,
	[PriorityId] [int] NOT NULL ,
	[IsCompleted] [bit] NOT NULL ,
	[ReasonId] [int] NOT NULL ,
	[ClosedDate] [datetime] NULL ,
	[StateId] [int] NOT NULL ,
	[ActivatedManually] [bit] NOT NULL ,
	[ActivationTypeId] [int] NOT NULL ,
	[TaskTime] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[EVENT_RESOURCES] (
	[ResourceId] [int] IDENTITY (1, 1) NOT NULL ,
	[EventId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ResponsePending] [bit] NOT NULL ,
	[IsConfirmed] [bit] NOT NULL ,
	[LastSavedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[EVENTS] (
	[EventId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[ProjectId] [int] NULL ,
	[CreatorId] [int] NOT NULL ,
	[ManagerId] [int] NOT NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL ,
	[Location] [nvarchar] (1000) NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[StartDate] [datetime] NOT NULL ,
	[FinishDate] [datetime] NOT NULL ,
	[PriorityId] [int] NOT NULL ,
	[TypeId] [int] NOT NULL ,
	[Interval] [int] NOT NULL ,
	[StateId] [int] NOT NULL ,
	[TaskTime] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_RESOURCES] (
	[ResourceId] [int] IDENTITY (1, 1) NOT NULL ,
	[IncidentId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ResponsePending] [bit] NOT NULL ,
	[IsConfirmed] [bit] NOT NULL ,
	[LastSavedDate] [datetime] NOT NULL ,
	[CanManage] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENT_TODO] (
	[IncidentToDoId] [int] IDENTITY (1, 1) NOT NULL ,
	[IncidentId] [int] NOT NULL ,
	[ToDoId] [int] NOT NULL ,
	[StatusId] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[INCIDENTS] (
	[IncidentId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[ProjectId] [int] NULL ,
	[CreatorId] [int] NOT NULL ,
	[ManagerId] [int] NOT NULL ,
	[ActivatedBy] [int] NULL ,
	[ClosedBy] [int] NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL ,
	[Resolution] [ntext] NULL ,
	[Workaround] [ntext] NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[ActivationDate] [datetime] NULL ,
	[CloseDate] [datetime] NULL ,
	[TypeId] [int] NOT NULL ,
	[PriorityId] [int] NOT NULL ,
	[StatusId] [int] NOT NULL ,
	[SeverityId] [int] NOT NULL ,
	[IsEmail] [bit] NOT NULL ,
	[MailSenderEmail] [nvarchar] (250) NULL ,
	[StateId] [int] NOT NULL ,
	[TaskTime] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_ACCESS] (
	[ListAccessId] [int] IDENTITY (1, 1) NOT NULL ,
	[ListId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[AllowLevel] [tinyint] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LIST_FOLDERS] (
	[ListFolderId] [int] IDENTITY (1, 1) NOT NULL ,
	[Name] [nvarchar] (250) NOT NULL ,
	[ParentFolderId] [int] NOT NULL ,
	[ProjectId] [int] NULL ,
	[IsPrivate] [bit] NOT NULL ,
	[CreatorId] [int] NULL ,
	[CreationDate] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[LISTS] (
	[ListId] [int] IDENTITY (1, 1) NOT NULL ,
	[FolderId] [int] NOT NULL ,
	[Title] [nvarchar] (100) NOT NULL ,
	[Description] [ntext] NOT NULL ,
	[TypeId] [int] NOT NULL ,
	[StatusId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CreationDate] [datetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[PROJECTS] (
	[ProjectId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[FormId] [int] NOT NULL ,
	[CalendarId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[ManagerId] [int] NOT NULL ,
	[ExecutiveManagerId] [int] NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[StartDate] [datetime] NULL ,
	[FinishDate] [datetime] NULL ,
	[TargetStartDate] [datetime] NOT NULL ,
	[TargetFinishDate] [datetime] NULL ,
	[ActualStartDate] [datetime] NULL ,
	[ActualFinishDate] [datetime] NULL ,
	[FixedHours] [int] NULL ,
	[FixedCost] [int] NULL ,
	[Goals] [ntext] NULL ,
	[Scope] [ntext] NULL ,
	[Deliverables] [ntext] NULL ,
	[StatusId] [int] NOT NULL ,
	[ClientId] [int] NOT NULL ,
	[XMLFileId] [int] NOT NULL ,
	[CurrencyId] [int] NOT NULL ,
	[PriorityId] [int] NOT NULL ,
	[PercentCompleted] [int] NOT NULL ,
	[InitialPhaseId] [int] NOT NULL ,
	[PhaseId] [int] NOT NULL ,
	[RiskLevelId] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[TASK_RESOURCES] (
	[ResourceId] [int] IDENTITY (1, 1) NOT NULL ,
	[TaskId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ResponsePending] [bit] NOT NULL ,
	[IsConfirmed] [bit] NOT NULL ,
	[PercentCompleted] [int] NOT NULL ,
	[ActualFinishDate] [datetime] NULL ,
	[LastSavedDate] [datetime] NULL ,
	[CanManage] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TASK_TODO] (
	[TaskToDoId] [int] IDENTITY (1, 1) NOT NULL ,
	[TaskId] [int] NOT NULL ,
	[ToDoId] [int] NOT NULL ,
	[CompleteTask] [bit] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TASKS] (
	[TaskId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[TaskNum] [int] NOT NULL ,
	[ProjectId] [int] NOT NULL ,
	[CreatorId] [int] NOT NULL ,
	[CompletedBy] [int] NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[StartDate] [datetime] NOT NULL ,
	[FinishDate] [datetime] NOT NULL ,
	[Duration] [int] NOT NULL ,
	[ActualFinishDate] [datetime] NULL ,
	[ActualStartDate] [datetime] NULL ,
	[PriorityId] [int] NOT NULL ,
	[PercentCompleted] [int] NOT NULL ,
	[OutlineNumber] [varchar] (255) NOT NULL ,
	[OutlineLevel] [int] NOT NULL ,
	[IsSummary] [bit] NOT NULL ,
	[IsMilestone] [bit] NOT NULL ,
	[ConstraintTypeId] [int] NOT NULL ,
	[ConstraintDate] [datetime] NULL ,
	[CompletionTypeId] [int] NOT NULL ,
	[IsCompleted] [bit] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ReasonId] [int] NOT NULL ,
	[ActivatedManually] [bit] NOT NULL ,
	[ActivationTypeId] [int] NOT NULL ,
	[StateId] [int] NOT NULL ,
	[PhaseId] [int] NULL ,
	[TaskTime] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[TODO] (
	[ToDoId] [int] IDENTITY (1, 1) NOT NULL ,
	[UID] [uniqueidentifier] NOT NULL ,
	[ProjectId] [int] NULL ,
	[CreatorId] [int] NOT NULL ,
	[ManagerId] [int] NOT NULL ,
	[CompletedBy] [int] NULL ,
	[Title] [nvarchar] (255) NOT NULL ,
	[Description] [ntext] NULL ,
	[CreationDate] [datetime] NOT NULL ,
	[StartDate] [datetime] NULL ,
	[FinishDate] [datetime] NULL ,
	[ActualStartDate] [datetime] NULL ,
	[ActualFinishDate] [datetime] NULL ,
	[PriorityId] [int] NOT NULL ,
	[PercentCompleted] [int] NOT NULL ,
	[IsActual] [bit] NOT NULL ,
	[CompletionTypeId] [int] NOT NULL ,
	[IsCompleted] [bit] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ReasonId] [int] NOT NULL ,
	[ActivatedManually] [bit] NOT NULL ,
	[ActivationTypeId] [int] NOT NULL ,
	[StateId] [int] NOT NULL ,
	[TaskTime] [int] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[TODO_RESOURCES] (
	[ResourceId] [int] IDENTITY (1, 1) NOT NULL ,
	[ToDoId] [int] NOT NULL ,
	[PrincipalId] [int] NOT NULL ,
	[MustBeConfirmed] [bit] NOT NULL ,
	[ResponsePending] [bit] NOT NULL ,
	[IsConfirmed] [bit] NOT NULL ,
	[PercentCompleted] [int] NOT NULL ,
	[ActualFinishDate] [datetime] NULL ,
	[LastSavedDate] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACCOUNTS] WITH NOCHECK ADD
	CONSTRAINT [PK_ACCOUNTS] PRIMARY KEY  CLUSTERED
	(
		[AccountId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACTIVATION_TYPE_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_ACTIVATION_TYPE_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[ActivationTypeId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACTUAL_FINANCES] WITH NOCHECK ADD
	CONSTRAINT [PK_ACTUAL_FINANCES] PRIMARY KEY  CLUSTERED
	(
		[ActualId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[AlertTemplates] WITH NOCHECK ADD
	CONSTRAINT [PK_AlertTemplates] PRIMARY KEY  CLUSTERED
	(
		[Key]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[BroadcastMessages] WITH NOCHECK ADD
	CONSTRAINT [PK_BroadcastMessages] PRIMARY KEY  CLUSTERED
	(
		[MessageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[BroadcastRecipients] WITH NOCHECK ADD
	CONSTRAINT [PK_BroadcastRecipients] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CAL_EXCEPTION_HOURS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_CAL_EXCEPTION_HOURS] PRIMARY KEY  CLUSTERED
	(
		[ExceptionHourId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CAL_EXCEPTIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_CAL_EXCEPTIONS] PRIMARY KEY  CLUSTERED
	(
		[ExceptionId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CAL_WEEKDAYS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_CAL_WEEKDAYS] PRIMARY KEY  CLUSTERED
	(
		[WeekDayId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CATEGORIES] WITH NOCHECK ADD
	CONSTRAINT [PK_CATEGORIES] PRIMARY KEY  CLUSTERED
	(
		[CategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CATEGORY_USER] WITH NOCHECK ADD
	CONSTRAINT [PK_CATEGORY_USER] PRIMARY KEY  CLUSTERED
	(
		[CategoryId],
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_ACCOUNTS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_ACCOUNTS] PRIMARY KEY  CLUSTERED
	(
		[CollapsedId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_DOCUMENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_DOCUMENTS] PRIMARY KEY  CLUSTERED
	(
		[UserId],
		[ProjectId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_INCIDENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_INCIDENTS] PRIMARY KEY  CLUSTERED
	(
		[UserId],
		[ProjectId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_MANAGERTIMESHEETS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_MANAGERTIMESHEETS] PRIMARY KEY  CLUSTERED
	(
		[ManagerId],
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_TASKS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_TASKS] PRIMARY KEY  CLUSTERED
	(
		[CollapsedId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_USERTIMESHEETS] WITH NOCHECK ADD
	CONSTRAINT [PK_COLLAPSED_USERTIMESHEETS] PRIMARY KEY  CLUSTERED
	(
		[UserId],
		[ProjectId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COMPLETION_REASON_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_COMPLETION_REASON_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[ReasonId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COMPLETION_TYPE_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_COMPLETION_TYPE_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[CompletionTypeId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CONSTRAINT_TYPE_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_CONSTRAINT_TYPE_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[ConstraintTypeId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CONTENT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_CONTENTTYPES] PRIMARY KEY  CLUSTERED
	(
		[ContentTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DATE_TYPE_HANDLERS] WITH NOCHECK ADD
	CONSTRAINT [PK_DATE_TYPE_HANDLERS] PRIMARY KEY  CLUSTERED
	(
		[HandlerId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DATE_TYPE_HOOKS] WITH NOCHECK ADD
	CONSTRAINT [PK_DATE_TYPE_HOOKS] PRIMARY KEY  CLUSTERED
	(
		[HookId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DATE_TYPE_PROCESSED] WITH NOCHECK ADD
	CONSTRAINT [PK_DATE_TYPE_PROCESSED] PRIMARY KEY  CLUSTERED
	(
		[ProcessedId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DATE_TYPE_VALUES] WITH NOCHECK ADD
	CONSTRAINT [PK_DATE_TYPE_VALUES] PRIMARY KEY  CLUSTERED
	(
		[ValueId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DATE_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_DateTypes] PRIMARY KEY  CLUSTERED
	(
		[DateTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DISCUSSIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_DISCUSSIONS] PRIMARY KEY  CLUSTERED
	(
		[DiscussionId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EMAILS] WITH NOCHECK ADD
	CONSTRAINT [PK_EMAILS] PRIMARY KEY  CLUSTERED
	(
		[EmailId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_REMINDER] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_EVENT_REMINDER] PRIMARY KEY  CLUSTERED
	(
		[ReminderId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_TYPE_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_EVENT_TYPE_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[TypeId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EXTERNAL_GATE] WITH NOCHECK ADD
	CONSTRAINT [PK_EXTERNAL_GATE] PRIMARY KEY  CLUSTERED
	(
		[GateId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[FAVORITES] WITH NOCHECK ADD
	CONSTRAINT [PK_FAVORITES] PRIMARY KEY  CLUSTERED
	(
		[FavoriteId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_FileBinaries] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_FileBinaries] PRIMARY KEY  CLUSTERED
	(
		[FileBinaryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Files] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_Files] PRIMARY KEY  CLUSTERED
	(
		[FileId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Files_History] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_FileHistory] PRIMARY KEY  CLUSTERED
	(
		[Id]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Forums] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_Forum] PRIMARY KEY  CLUSTERED
	(
		[ForumId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ForumThreadNodes] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_ForumThreadNodes] PRIMARY KEY  CLUSTERED
	(
		[NodeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ForumThreads] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_ForumThreads] PRIMARY KEY  CLUSTERED
	(
		[ThreadId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ReportAccessControlEntries] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_ReportAccessControlEntry] PRIMARY KEY  CLUSTERED
	(
		[AceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ReportAccessControlLists] WITH NOCHECK ADD
	CONSTRAINT [PK_ReportAccessControlLists] PRIMARY KEY  CLUSTERED
	(
		[AclId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ReportCategories] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_ReportCategories] PRIMARY KEY  CLUSTERED
	(
		[ReportCategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Reports] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_Reports] PRIMARY KEY  CLUSTERED
	(
		[ReportId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[HIDDEN_STUBS] WITH NOCHECK ADD
	CONSTRAINT [PK_HIDED_STUBS] PRIMARY KEY  CLUSTERED
	(
		[HidedStubId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[HISTORY] WITH NOCHECK ADD
	CONSTRAINT [PK_HISTORY] PRIMARY KEY  CLUSTERED
	(
		[HistoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_CATEGORIES] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_CATEGORIES] PRIMARY KEY  CLUSTERED
	(
		[CategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_CATEGORY] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_CATEGORY] PRIMARY KEY  CLUSTERED
	(
		[IncidentCategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_RELATIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_RELATIONS] PRIMARY KEY  CLUSTERED
	(
		[RelationId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_STATUS_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_STATUS_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[StatusId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENTCATEGORY_USER] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENTCATEGORY_USER] PRIMARY KEY  CLUSTERED
	(
		[CategoryId],
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LANGUAGES] WITH NOCHECK ADD
	CONSTRAINT [PK_LANGUAGES] PRIMARY KEY  CLUSTERED
	(
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_ITEMS] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_ITEMS] PRIMARY KEY  CLUSTERED
	(
		[ItemId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_STATUS_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_STATUS_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[StatusId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MESSAGE_LOG] WITH NOCHECK ADD
	CONSTRAINT [PK_MESSAGE_LOG] PRIMARY KEY  CLUSTERED
	(
		[LogId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MESSAGE_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_MESSAGE_TYPES] PRIMARY KEY  CLUSTERED
	(
		[MessageTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaAttribute] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaAttribute] PRIMARY KEY  CLUSTERED
	(
		[AttrOwnerId],
		[AttrOwnerType],
		[Key]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaClass] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaClass] PRIMARY KEY  CLUSTERED
	(
		[MetaClassId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaClassMetaFieldRelation] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaClassMetaFieldRelation] PRIMARY KEY  CLUSTERED
	(
		[MetaClassId],
		[MetaFieldId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaDataType] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaDataType] PRIMARY KEY  CLUSTERED
	(
		[DataTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaDictionary] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaDictionary] PRIMARY KEY  CLUSTERED
	(
		[MetaDictionaryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaField] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaField] PRIMARY KEY  CLUSTERED
	(
		[MetaFieldId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaFileValue] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaFileValue] PRIMARY KEY  CLUSTERED
	(
		[MetaKey]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaKey] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaKey] PRIMARY KEY  CLUSTERED
	(
		[MetaKey]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaMultiValueDictionary] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaMultiValueDictionary] PRIMARY KEY  CLUSTERED
	(
		[MetaKey],
		[MetaDictionaryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaObjectValue] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaObjectValue] PRIMARY KEY  CLUSTERED
	(
		[MetaKey]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaRule] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaRule] PRIMARY KEY  CLUSTERED
	(
		[RuleId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaStringDictionaryValue] WITH NOCHECK ADD
	CONSTRAINT [PK_MetaStringDictionaryValue] PRIMARY KEY  CLUSTERED
	(
		[MetaKey]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_CATEGORY] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_CATEGORY] PRIMARY KEY  CLUSTERED
	(
		[ObjectCategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_MENUS] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_MENUS] PRIMARY KEY  CLUSTERED
	(
		[MenuId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_ROLES] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_ROLES] PRIMARY KEY  CLUSTERED
	(
		[ObjectRoleId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_STATE_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_STATE_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[StateId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_VIEW_PAGES] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_VIEW_PAGES] PRIMARY KEY  CLUSTERED
	(
		[ViewPageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_VIEW_PAGES_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_VIEW_PAGES_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[ViewPageLanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_VIEW_TABS] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_VIEW_TABS] PRIMARY KEY  CLUSTERED
	(
		[TabId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_VIEW_TEMPLATES] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_VIEW_TEMPLATES] PRIMARY KEY  CLUSTERED
	(
		[TemplateId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[page_ControlProperties] WITH NOCHECK ADD
	CONSTRAINT [PK_page_ControlProperties] PRIMARY KEY  CLUSTERED
	(
		[Id]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PARTNER_GROUP] WITH NOCHECK ADD
	CONSTRAINT [PK_PARTNER_GROUP] PRIMARY KEY  CLUSTERED
	(
		[PartnerId],
		[GroupId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[POP3_INCIDENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_POP3_INCIDENTS] PRIMARY KEY  CLUSTERED
	(
		[IncidentId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3Boxes] WITH NOCHECK ADD
	CONSTRAINT [PK_Pop3Boxes] PRIMARY KEY  CLUSTERED
	(
		[Pop3BoxId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3BoxParameters] WITH NOCHECK ADD
	CONSTRAINT [PK_Pop3BoxParameters] PRIMARY KEY  CLUSTERED
	(
		[Pop3BoxParameterId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3BoxPop3DocumentHandler] WITH NOCHECK ADD
	CONSTRAINT [PK_Pop3BoxPop3DocumentHandler] PRIMARY KEY  CLUSTERED
	(
		[Pop3HandlerId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3MailRequests] WITH NOCHECK ADD
	CONSTRAINT [PK_Pop3MailRequests] PRIMARY KEY  CLUSTERED
	(
		[Pop3MailRequestId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3MessageUIds] WITH NOCHECK ADD
	CONSTRAINT [PK_Pop3MessagesId] PRIMARY KEY  CLUSTERED
	(
		[Pop3MessageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PRIORITY_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_PRIORITY_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[PriorityId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_CATEGORIES] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_CATEGORIES] PRIMARY KEY  CLUSTERED
	(
		[CategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_CATEGORY] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_CATEGORY] PRIMARY KEY  CLUSTERED
	(
		[ProjectCategoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_GROUP] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_GROUP] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_GROUPS] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_GROUPS] PRIMARY KEY  CLUSTERED
	(
		[ProjectGroupId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_MEMBERS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_PROJECT_MEMBERS] PRIMARY KEY  CLUSTERED
	(
		[MemberId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_RELATIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_RELATIONS] PRIMARY KEY  CLUSTERED
	(
		[RelationId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_SNAPSHOTS] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_SNAPSHOTS] PRIMARY KEY  CLUSTERED
	(
		[SnapshotId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_STATUS_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_STATUS_LANGUAGE] PRIMARY KEY  CLUSTERED
	(
		[StatusId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_TEMPLATES] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_TEMPLATES] PRIMARY KEY  CLUSTERED
	(
		[TemplateId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_USER_DATE] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_USER_DATE] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECTCATEGORY_USER] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECTCATEGORY_USER] PRIMARY KEY  CLUSTERED
	(
		[CategoryId],
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECTGROUP_USER] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECTGROUP_USER] PRIMARY KEY  CLUSTERED
	(
		[ProjectGroupId],
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[RECURRENCE] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_EVENT_RECURRENCE] PRIMARY KEY  CLUSTERED
	(
		[RecurrenceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[REMINDER_SUBSCRIPTIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_REMINDER_SUBSCRIPTIONS] PRIMARY KEY  CLUSTERED
	(
		[SubscriptionId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[Report] WITH NOCHECK ADD
	CONSTRAINT [PK_Report] PRIMARY KEY  CLUSTERED
	(
		[ReportId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ReportHistory] WITH NOCHECK ADD
	CONSTRAINT [PK_ReportHistory] PRIMARY KEY  CLUSTERED
	(
		[ReportItemId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SCHEDULE] WITH NOCHECK ADD
	CONSTRAINT [PK_SCHEDULE] PRIMARY KEY  CLUSTERED
	(
		[ScheduleId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ScheduleProcessHandlerTempItems] WITH NOCHECK ADD
	CONSTRAINT [PK_ScheduleProcessHandlerTempItems] PRIMARY KEY  CLUSTERED
	(
		[Id]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SHARING] WITH NOCHECK ADD
	CONSTRAINT [PK_SHARING] PRIMARY KEY  CLUSTERED
	(
		[SharingId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[STUB_GROUP] WITH NOCHECK ADD
	CONSTRAINT [PK_STUB_GROUP] PRIMARY KEY  CLUSTERED
	(
		[StubGroupId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[STUBS] WITH NOCHECK ADD
	CONSTRAINT [PK_STUBS] PRIMARY KEY  CLUSTERED
	(
		[StubId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SUBSCRIPTION_DETAILS] WITH NOCHECK ADD
	CONSTRAINT [PK_SUBSCRIPTION_DETAILS] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SUBSCRIPTIONS] WITH NOCHECK ADD
	CONSTRAINT [PK_SUBSCRIPTIONS] PRIMARY KEY  CLUSTERED
	(
		[SubscriptionId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_RECIPIENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_SYSTEM_EVENT_RECIPIENTS] PRIMARY KEY  CLUSTERED
	(
		[RecipientId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_SYSTEM_EVENTS] PRIMARY KEY  CLUSTERED
	(
		[EventTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_SYSTEM_EVENTS_LOG] PRIMARY KEY  CLUSTERED
	(
		[SystemEventId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_LINKS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_LINKS] PRIMARY KEY  CLUSTERED
	(
		[LinkId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMESHEET_STATUS] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMESHEET_STATUS] PRIMARY KEY  CLUSTERED
	(
		[StatusId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMESHEET_TODO] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMESHEET_TODO] PRIMARY KEY  CLUSTERED
	(
		[TimeSheetToDoId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMESHEETS] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMESHEETS] PRIMARY KEY  CLUSTERED
	(
		[TimesheetId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMEZONES_LANGUAGE] WITH NOCHECK ADD
	CONSTRAINT [PK_TIME_ZONE_LANGUAGE1] PRIMARY KEY  CLUSTERED
	(
		[TimeZoneId],
		[LanguageId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMEZONES_LOCAL_UTC] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMEZONES_DAYLIGHT] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMEZONES_UTC_LOCAL] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMEZONES_UTC_LOCAL] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_DETAILS] WITH NOCHECK ADD
	CONSTRAINT [PK_USER_DETAILS] PRIMARY KEY  CLUSTERED
	(
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_PREFERENCES] WITH NOCHECK ADD
	CONSTRAINT [PK_USER_PREFERENCES] PRIMARY KEY  CLUSTERED
	(
		[UserId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_PROJECT_TEAM] WITH NOCHECK ADD
	CONSTRAINT [PK_USER_PROJECT_TEAM] PRIMARY KEY  CLUSTERED
	(
		[UserId],
		[ProjectId],
		[MemberId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_SETTINGS] WITH NOCHECK ADD
	CONSTRAINT [PK_USER_SETTINGS] PRIMARY KEY  CLUSTERED
	(
		[SettingId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[WeekTimeSheet] WITH NOCHECK ADD
	CONSTRAINT [PK_WeekTimeSheet] PRIMARY KEY  CLUSTERED
	(
		[WeekTimeSheetId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACTIVATION_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_ACTIVATION_TYPES] PRIMARY KEY  CLUSTERED
	(
		[ActivationTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CLIENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_CLIENTS] PRIMARY KEY  CLUSTERED
	(
		[ClientId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COMPLETION_REASONS] WITH NOCHECK ADD
	CONSTRAINT [PK_COMPLETION_REASONS] PRIMARY KEY  CLUSTERED
	(
		[ReasonId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[COMPLETION_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_COMPLETION_TYPES] PRIMARY KEY  CLUSTERED
	(
		[CompletionTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CONSTRAINT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_CONSTRAINT_TYPES] PRIMARY KEY  CLUSTERED
	(
		[ConstraintTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CURRENCY] WITH NOCHECK ADD
	CONSTRAINT [PK_CURRENCY] PRIMARY KEY  CLUSTERED
	(
		[CurrencyId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_EVENT_TYPES] PRIMARY KEY  CLUSTERED
	(
		[TypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Directories] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_Folders] PRIMARY KEY  CLUSTERED
	(
		[DirectoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_ForeignContainerKeys] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_ForeignContainerKeys] PRIMARY KEY  CLUSTERED
	(
		[ContainerKey],
		[ForeignContainerKey]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_UserRoles] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_UserRoles] PRIMARY KEY  CLUSTERED
	(
		[UserRoleId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_SEVERITY] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_INCIDENT_SEVERITY] PRIMARY KEY  CLUSTERED
	(
		[SeverityId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_INCIDENT_TYPES] PRIMARY KEY  CLUSTERED
	(
		[TypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_STATUS] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_STATUS] PRIMARY KEY  CLUSTERED
	(
		[StatusId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_TYPES] PRIMARY KEY  CLUSTERED
	(
		[TypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_STATES] WITH NOCHECK ADD
	CONSTRAINT [PK_OBJECT_STATES] PRIMARY KEY  CLUSTERED
	(
		[StateId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_TYPES] WITH NOCHECK ADD
	CONSTRAINT [PK_RELATIONTYPES] PRIMARY KEY  CLUSTERED
	(
		[ObjectTypeId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PRINCIPALS] WITH NOCHECK ADD
	CONSTRAINT [PK_Principals] PRIMARY KEY  CLUSTERED
	(
		[PrincipalId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PRIORITIES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_PRIORITIES] PRIMARY KEY  CLUSTERED
	(
		[PriorityId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_PHASES] WITH NOCHECK ADD
	CONSTRAINT [PK_PROJECT_PHASES] PRIMARY KEY  CLUSTERED
	(
		[PhaseId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_STATUS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_PROJECT_STATUS] PRIMARY KEY  CLUSTERED
	(
		[StatusId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[RISK_LEVELS] WITH NOCHECK ADD
	CONSTRAINT [PK_RISK_LEVELS] PRIMARY KEY  CLUSTERED
	(
		[RiskLevelId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMEZONES] WITH NOCHECK ADD
	CONSTRAINT [PK_TIMEZONES] PRIMARY KEY  CLUSTERED
	(
		[TimeZoneId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CONTAINERSHIP] WITH NOCHECK ADD
	CONSTRAINT [PK_CONTAINERSHIP] PRIMARY KEY  CLUSTERED
	(
		[RowId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_STATUS] WITH NOCHECK ADD
	CONSTRAINT [PK_DOCUMENT_STATUS] PRIMARY KEY  CLUSTERED
	(
		[StatusId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_AccessControlLists] WITH NOCHECK ADD
	CONSTRAINT [PK_AccessControlLists] PRIMARY KEY  CLUSTERED
	(
		[AclId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[GROUPS] WITH NOCHECK ADD
	CONSTRAINT [PK_GROUPS] PRIMARY KEY  CLUSTERED
	(
		[PrincipalId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_STATUS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_INCIDENT_STATUS] PRIMARY KEY  CLUSTERED
	(
		[StatusId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_FORMS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_OBJECT_FORMS] PRIMARY KEY  CLUSTERED
	(
		[FormId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USERS] WITH NOCHECK ADD
	CONSTRAINT [PK_USERS] PRIMARY KEY  CLUSTERED
	(
		[PrincipalId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_AccessControlEntries] WITH NOCHECK ADD
	CONSTRAINT [PK_fsc_AccessControlEntry] PRIMARY KEY  CLUSTERED
	(
		[AceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_GROUP] WITH NOCHECK ADD
	CONSTRAINT [PK_USER_GROUP] PRIMARY KEY  CLUSTERED
	(
		[UserGroupId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CALENDARS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_CALENDARS] PRIMARY KEY  CLUSTERED
	(
		[CalendarId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_RESOURCES] WITH NOCHECK ADD
	CONSTRAINT [PK_DOCUMENT_RESOURCES] PRIMARY KEY  CLUSTERED
	(
		[ResourceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_TODO] WITH NOCHECK ADD
	CONSTRAINT [PK_DOCUMENT_TODO] PRIMARY KEY  CLUSTERED
	(
		[DocumentToDoId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_DOCUMENTS] PRIMARY KEY  CLUSTERED
	(
		[DocumentId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_RESOURCES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_EVENT_RESOURCES] PRIMARY KEY  CLUSTERED
	(
		[ResourceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_EVENTS] PRIMARY KEY  CLUSTERED
	(
		[EventId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_RESOURCES] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_RESOURCES] PRIMARY KEY  CLUSTERED
	(
		[ResourceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_TODO] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENT_TODO] PRIMARY KEY  CLUSTERED
	(
		[IncidentToDoId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENTS] WITH NOCHECK ADD
	CONSTRAINT [PK_INCIDENTS] PRIMARY KEY  CLUSTERED
	(
		[IncidentId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_ACCESS] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_FOLDER_ACCESS] PRIMARY KEY  CLUSTERED
	(
		[ListAccessId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_FOLDERS] WITH NOCHECK ADD
	CONSTRAINT [PK_LIST_FOLDERS] PRIMARY KEY  CLUSTERED
	(
		[ListFolderId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LISTS] WITH NOCHECK ADD
	CONSTRAINT [PK_LISTS] PRIMARY KEY  CLUSTERED
	(
		[ListId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECTS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_PROJECTS] PRIMARY KEY  CLUSTERED
	(
		[ProjectId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_RESOURCES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_TASK_RESOURCES] PRIMARY KEY  CLUSTERED
	(
		[ResourceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_TODO] WITH NOCHECK ADD
	CONSTRAINT [PK_TASK_TODO] PRIMARY KEY  CLUSTERED
	(
		[TaskToDoId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASKS] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_TASKS] PRIMARY KEY  CLUSTERED
	(
		[TaskId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TODO] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_TODO] PRIMARY KEY  CLUSTERED
	(
		[ToDoId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[TODO_RESOURCES] WITH NOCHECK ADD
	CONSTRAINT [PK_MSP_TODO_RESOURCES] PRIMARY KEY  CLUSTERED
	(
		[ResourceId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACCOUNTS] ADD
	CONSTRAINT [DF_ACCOUNTS_OutlineLevel] DEFAULT (1) FOR [OutlineLevel],
	CONSTRAINT [DF_ACCOUNTS_IsSummary] DEFAULT (0) FOR [IsSummary],
	CONSTRAINT [DF_ACCOUNTS_TCur] DEFAULT (0) FOR [TCur],
	CONSTRAINT [DF_ACCOUNTS_TSub] DEFAULT (0) FOR [TSub],
	CONSTRAINT [DF_ACCOUNTS_ECur] DEFAULT (0) FOR [ECur],
	CONSTRAINT [DF_ACCOUNTS_ESub] DEFAULT (0) FOR [ESub],
	CONSTRAINT [DF_ACCOUNTS_ACur] DEFAULT (0) FOR [ACur],
	CONSTRAINT [DF_ACCOUNTS_ASub] DEFAULT (0) FOR [ASub],
	CONSTRAINT [DF_ACCOUNTS_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate]
GO
 CREATE  INDEX [IX_ACCOUNTS] ON [dbo].[ACCOUNTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACCOUNTS_1] ON [dbo].[ACCOUNTS]([LastEditorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTIVATION_TYPE_LANGUAGE] ON [dbo].[ACTIVATION_TYPE_LANGUAGE]([ActivationTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTIVATION_TYPE_LANGUAGE_1] ON [dbo].[ACTIVATION_TYPE_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACTUAL_FINANCES] ADD
	CONSTRAINT [DF_ACTUAL_FINANCES_ActualDate] DEFAULT (getdate()) FOR [ActualDate],
	CONSTRAINT [DF_ACTUAL_FINANCES_Description] DEFAULT ('') FOR [Description],
	CONSTRAINT [DF_ACTUAL_FINANCES_AValue] DEFAULT (0) FOR [AValue],
	CONSTRAINT [DF_ACTUAL_FINANCES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate]
GO
 CREATE  INDEX [IX_ACTUAL_FINANCES] ON [dbo].[ACTUAL_FINANCES]([AccountId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTUAL_FINANCES_1] ON [dbo].[ACTUAL_FINANCES]([ActualDate]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTUAL_FINANCES_2] ON [dbo].[ACTUAL_FINANCES]([LastEditorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTUAL_FINANCES_3] ON [dbo].[ACTUAL_FINANCES]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_ACTUAL_FINANCES_4] ON [dbo].[ACTUAL_FINANCES]([ObjectId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[BroadcastMessages] ADD
	CONSTRAINT [DF_BroadcastMessages_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_BroadcastMessages_Text] DEFAULT ('') FOR [Text]
GO
 CREATE  INDEX [IX_BroadcastMessages] ON [dbo].[BroadcastMessages]([ExpirationDate]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_BroadcastMessages_1] ON [dbo].[BroadcastMessages]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_BroadcastRecipients] ON [dbo].[BroadcastRecipients]([MessageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_BroadcastRecipients_1] ON [dbo].[BroadcastRecipients]([GroupId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTION_HOURS] ON [dbo].[CAL_EXCEPTION_HOURS]([ExceptionId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTION_HOURS_1] ON [dbo].[CAL_EXCEPTION_HOURS]([FromTime]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTION_HOURS_2] ON [dbo].[CAL_EXCEPTION_HOURS]([ToTime]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTIONS] ON [dbo].[CAL_EXCEPTIONS]([CalendarId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTIONS_1] ON [dbo].[CAL_EXCEPTIONS]([FromDate]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_EXCEPTIONS_2] ON [dbo].[CAL_EXCEPTIONS]([ToDate]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CAL_WEEKDAYS] ADD
	CONSTRAINT [CK_CAL_WEEKDAYS] CHECK ([DayOfWeek] >= 1 and [DayOfWeek] <= 7)
GO
 CREATE  INDEX [IX_MSP_CAL_WEEKDAYS] ON [dbo].[CAL_WEEKDAYS]([CalendarId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_WEEKDAYS_1] ON [dbo].[CAL_WEEKDAYS]([DayOfWeek]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_WEEKDAYS_2] ON [dbo].[CAL_WEEKDAYS]([FromTime]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_CAL_WEEKDAYS_3] ON [dbo].[CAL_WEEKDAYS]([ToTime]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CATEGORIES] ADD
	CONSTRAINT [IX_CATEGORIES] UNIQUE  NONCLUSTERED
	(
		[CategoryName]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_CATEGORY_USER] ON [dbo].[CATEGORY_USER]([CategoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CATEGORY_USER_1] ON [dbo].[CATEGORY_USER]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_ACCOUNTS] ON [dbo].[COLLAPSED_ACCOUNTS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_ACCOUNTS_1] ON [dbo].[COLLAPSED_ACCOUNTS]([AccountId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_DOCUMENTS] ON [dbo].[COLLAPSED_DOCUMENTS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_DOCUMENTS_1] ON [dbo].[COLLAPSED_DOCUMENTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_INCIDENTS] ON [dbo].[COLLAPSED_INCIDENTS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_INCIDENTS_1] ON [dbo].[COLLAPSED_INCIDENTS]([ProjectId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[COLLAPSED_TASKS] ADD
	CONSTRAINT [IX_COLLAPSED_TASKS] UNIQUE  NONCLUSTERED
	(
		[UserId],
		[TaskId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_USERTIMESHEETS] ON [dbo].[COLLAPSED_USERTIMESHEETS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COLLAPSED_USERTIMESHEETS_1] ON [dbo].[COLLAPSED_USERTIMESHEETS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COMPLETION_REASON_LANGUAGE] ON [dbo].[COMPLETION_REASON_LANGUAGE]([ReasonId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COMPLETION_REASON_LANGUAGE_1] ON [dbo].[COMPLETION_REASON_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COMPLETION_TYPE_LANGUAGE] ON [dbo].[COMPLETION_TYPE_LANGUAGE]([CompletionTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_COMPLETION_TYPE_LANGUAGE_1] ON [dbo].[COMPLETION_TYPE_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CONSTRAINT_TYPE_LANGUAGE] ON [dbo].[CONSTRAINT_TYPE_LANGUAGE]([ConstraintTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CONSTRAINT_TYPE_LANGUAGE_1] ON [dbo].[CONSTRAINT_TYPE_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CONTENT_TYPES] ADD
	CONSTRAINT [DF_CONTENT_TYPES_FriendlyName] DEFAULT ('') FOR [FriendlyName]
GO
ALTER TABLE [dbo].[DATE_TYPE_HOOKS] ADD
	CONSTRAINT [DF_DATE_TYPE_HOOKS_Params] DEFAULT ('') FOR [Params]
GO
 CREATE  INDEX [IX_DATE_TYPE_HOOKS] ON [dbo].[DATE_TYPE_HOOKS]([DateTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_HOOKS_1] ON [dbo].[DATE_TYPE_HOOKS]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_HOOKS_2] ON [dbo].[DATE_TYPE_HOOKS]([HandlerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_PROCESSED] ON [dbo].[DATE_TYPE_PROCESSED]([ValueId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_PROCESSED_1] ON [dbo].[DATE_TYPE_PROCESSED]([HookId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_VALUES] ON [dbo].[DATE_TYPE_VALUES]([DateTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DATE_TYPE_VALUES_1] ON [dbo].[DATE_TYPE_VALUES]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DateTypes] ON [dbo].[DATE_TYPES]([ObjectTypeId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DISCUSSIONS] ADD
	CONSTRAINT [DF_DISCUSSIONS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate]
GO
 CREATE  INDEX [IX_DISCUSSIONS] ON [dbo].[DISCUSSIONS]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DISCUSSIONS_1] ON [dbo].[DISCUSSIONS]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DISCUSSIONS_2] ON [dbo].[DISCUSSIONS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_EMAILS] ON [dbo].[EMAILS]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_REMINDER] ADD
	CONSTRAINT [DF_MSP_EVENT_REMINDER_Interval] DEFAULT (0) FOR [Interval],
	CONSTRAINT [DF_MSP_EVENT_REMINDER_WasSent] DEFAULT (0) FOR [WasSent]
GO
 CREATE  INDEX [IX_MSP_EVENT_REMINDER] ON [dbo].[EVENT_REMINDER]([EventId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[EXTERNAL_GATE] ADD
	CONSTRAINT [DF_EXTERNAL_GATE_GUID] DEFAULT (newid()) FOR [GUID],
	CONSTRAINT [IX_EXTERNAL_GATE_3] UNIQUE  NONCLUSTERED
	(
		[ObjectTypeId],
		[ObjectId],
		[UserId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_EXTERNAL_GATE] ON [dbo].[EXTERNAL_GATE]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_EXTERNAL_GATE_1] ON [dbo].[EXTERNAL_GATE]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_EXTERNAL_GATE_2] ON [dbo].[EXTERNAL_GATE]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_FAVORITES] ON [dbo].[FAVORITES]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_FAVORITES_1] ON [dbo].[FAVORITES]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_FileBinaries] ADD
	CONSTRAINT [DF_fsc_FileBinaries_DownloadCount] DEFAULT (0) FOR [DownloadCount]
GO
ALTER TABLE [dbo].[fsc_Files] ADD
	CONSTRAINT [DF_fsc_Files_Created] DEFAULT (getutcdate()) FOR [Created],
	CONSTRAINT [DF_fsc_Files_Modified] DEFAULT (getutcdate()) FOR [Modified],
	CONSTRAINT [DF_fsc_Files_AllowHistory] DEFAULT (0) FOR [AllowHistory],
	CONSTRAINT [IX_fsc_Files] UNIQUE  NONCLUSTERED
	(
		[Name],
		[DirectoryId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Forums] ADD
	CONSTRAINT [DF_fsc_Forum_Created] DEFAULT (getdate()) FOR [Created],
	CONSTRAINT [DF_fsc_Forum_Name] DEFAULT (N'') FOR [Name]
GO
ALTER TABLE [dbo].[fsc_ForumThreadNodes] ADD
	CONSTRAINT [DF_fsc_ForumThreadNodes_Created] DEFAULT (getdate()) FOR [Created]
GO
ALTER TABLE [dbo].[fsc_ForumThreads] ADD
	CONSTRAINT [DF_fsc_ForumThreads_Created] DEFAULT (getdate()) FOR [Created],
	CONSTRAINT [DF_fsc_ForumThreads_Name] DEFAULT (N'') FOR [Name]
GO
ALTER TABLE [dbo].[fsc_ReportAccessControlEntries] ADD
	CONSTRAINT [DF_fsc_ReportAccessControlEntries_IsInternal] DEFAULT (0) FOR [IsInternal]
GO
 CREATE  UNIQUE  INDEX [IX_fsc_Reports] ON [dbo].[fsc_Reports]([Name], [ContainerKey]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[HIDDEN_STUBS] ADD
	CONSTRAINT [IX_HIDED_STUBS_2] UNIQUE  NONCLUSTERED
	(
		[UserId],
		[StubId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_HIDED_STUBS] ON [dbo].[HIDDEN_STUBS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_HIDED_STUBS_1] ON [dbo].[HIDDEN_STUBS]([StubId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[HISTORY] ADD
	CONSTRAINT [DF_HISTORY_Dt] DEFAULT (getutcdate()) FOR [Dt]
GO
 CREATE  INDEX [IX_HISTORY] ON [dbo].[HISTORY]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_HISTORY_1] ON [dbo].[HISTORY]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_HISTORY_2] ON [dbo].[HISTORY]([Dt]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_CATEGORIES] ADD
	CONSTRAINT [IX_INCIDENT_CATEGORIES] UNIQUE  NONCLUSTERED
	(
		[CategoryName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_CATEGORY] ADD
	CONSTRAINT [IX_INCIDENT_CATEGORY_2] UNIQUE  NONCLUSTERED
	(
		[IncidentId],
		[CategoryId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_CATEGORY] ON [dbo].[INCIDENT_CATEGORY]([IncidentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_CATEGORY_1] ON [dbo].[INCIDENT_CATEGORY]([CategoryId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_RELATIONS] ADD
	CONSTRAINT [IX_INCIDENT_RELATIONS_2] UNIQUE  NONCLUSTERED
	(
		[IncidentId],
		[RelIncidentId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_RELATIONS] ON [dbo].[INCIDENT_RELATIONS]([IncidentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_RELATIONS_1] ON [dbo].[INCIDENT_RELATIONS]([RelIncidentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_STATUS_LANGUAGE] ON [dbo].[INCIDENT_STATUS_LANGUAGE]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_STATUS_LANGUAGE_1] ON [dbo].[INCIDENT_STATUS_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENTCATEGORY_USER] ON [dbo].[INCIDENTCATEGORY_USER]([CategoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENTCATEGORY_USER_1] ON [dbo].[INCIDENTCATEGORY_USER]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[LANGUAGES] ADD
	CONSTRAINT [DF_LANGUAGES_IsDefault] DEFAULT (0) FOR [IsDefault]
GO
ALTER TABLE [dbo].[LIST_ITEMS] ADD
	CONSTRAINT [DF_LIST_ITEMS_CreationDte] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_LIST_ITEMS_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate]
GO
 CREATE  INDEX [IX_LIST_ITEMS] ON [dbo].[LIST_ITEMS]([ListId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_ITEMS_1] ON [dbo].[LIST_ITEMS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_ITEMS_2] ON [dbo].[LIST_ITEMS]([LastEditorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MESSAGE_LOG] ADD
	CONSTRAINT [DF_MESSAGE_LOG_Sent] DEFAULT (getutcdate()) FOR [Sent]
GO
ALTER TABLE [dbo].[MetaClass] ADD
	CONSTRAINT [DF_MetaClass_Namespace] DEFAULT (N'') FOR [Namespace],
	CONSTRAINT [DF_MetaClass_FriendlyName] DEFAULT (N'') FOR [FriendlyName],
	CONSTRAINT [DF_MetaClass_IsSystem] DEFAULT (0) FOR [IsSystem],
	CONSTRAINT [DF_MetaClass_IsAbstract] DEFAULT (0) FOR [IsAbstract],
	CONSTRAINT [DF_MetaClass_ParentClassId] DEFAULT (0) FOR [ParentClassId],
	CONSTRAINT [DF_MetaClass_PrimaryKeyName] DEFAULT (N'') FOR [PrimaryKeyName],
	CONSTRAINT [IX_MetaClass] UNIQUE  NONCLUSTERED
	(
		[Name]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaClassMetaFieldRelation] ADD
	CONSTRAINT [DF_MetaClassMetaFieldRelation_Weight] DEFAULT (0) FOR [Weight],
	CONSTRAINT [DF_MetaClassMetaFieldRelation_Enabled] DEFAULT (1) FOR [Enabled]
GO
ALTER TABLE [dbo].[MetaDataType] ADD
	CONSTRAINT [DF_MetaDataType_Length] DEFAULT (0) FOR [Length],
	CONSTRAINT [DF_MetaDataType_AllowNulls] DEFAULT (1) FOR [AllowNulls],
	CONSTRAINT [DF_MetaDataType_Variable] DEFAULT (0) FOR [Variable],
	CONSTRAINT [DF_MetaDataType_IsSQLCommonType] DEFAULT (1) FOR [IsSQLCommonType],
	CONSTRAINT [DF_MetaDataType_DefaultValue] DEFAULT (N'') FOR [DefaultValue]
GO
ALTER TABLE [dbo].[MetaDictionary] ADD
	CONSTRAINT [DF_MetaDictionary_Value] DEFAULT (N'') FOR [Value]
GO
ALTER TABLE [dbo].[MetaField] ADD
	CONSTRAINT [DF_MetaField_Namespace] DEFAULT ('') FOR [Namespace],
	CONSTRAINT [DF_MetaField_SystemMetaClassId] DEFAULT (0) FOR [SystemMetaClassId],
	CONSTRAINT [DF_MetaField_Length] DEFAULT (0) FOR [Length],
	CONSTRAINT [DF_MetaField_AllowNulls] DEFAULT (1) FOR [AllowNulls],
	CONSTRAINT [DF_MetaField_SaveHistory] DEFAULT (0) FOR [SaveHistory],
	CONSTRAINT [DF_MetaField_MultiLanguageValue] DEFAULT (0) FOR [MultiLanguageValue],
	CONSTRAINT [IX_MetaField] UNIQUE  NONCLUSTERED
	(
		[Name],
		[SystemMetaClassId]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[MetaFileValue] ADD
	CONSTRAINT [DF_MetaFileValue_Size] DEFAULT (0) FOR [Size],
	CONSTRAINT [DF_MetaFileValue_CreationTime] DEFAULT (getdate()) FOR [CreationTime],
	CONSTRAINT [DF_MetaFileValue_LastWriteTime] DEFAULT (getdate()) FOR [LastWriteTime],
	CONSTRAINT [DF_MetaFileValue_LastReadTime] DEFAULT (getdate()) FOR [LastReadTime]
GO
ALTER TABLE [dbo].[OBJECT_CATEGORY] ADD
	CONSTRAINT [IX_OBJECT_CATEGORY_3] UNIQUE  NONCLUSTERED
	(
		[ObjectTypeId],
		[ObjectId],
		[CategoryId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_CATEGORY] ON [dbo].[OBJECT_CATEGORY]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_CATEGORY_1] ON [dbo].[OBJECT_CATEGORY]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_CATEGORY_2] ON [dbo].[OBJECT_CATEGORY]([CategoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_MENUS_LANGUAGE] ON [dbo].[OBJECT_MENUS_LANGUAGE]([MenuId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_MENUS_LANGUAGE_1] ON [dbo].[OBJECT_MENUS_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_ROLES] ON [dbo].[OBJECT_ROLES]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_STATE_LANGUAGE] ON [dbo].[OBJECT_STATE_LANGUAGE]([StateId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_STATE_LANGUAGE_1] ON [dbo].[OBJECT_STATE_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_VIEW_PAGES] ON [dbo].[OBJECT_VIEW_PAGES]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_VIEW_PAGES_1] ON [dbo].[OBJECT_VIEW_PAGES]([MenuId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_VIEW_PAGES_LANGUAGE] ON [dbo].[OBJECT_VIEW_PAGES_LANGUAGE]([ViewPageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_OBJECT_VIEW_PAGES_LANGUAGE_1] ON [dbo].[OBJECT_VIEW_PAGES_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PARTNER_GROUP] ON [dbo].[PARTNER_GROUP]([PartnerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PARTNER_GROUP_1] ON [dbo].[PARTNER_GROUP]([GroupId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[POP3_INCIDENTS] ADD
	CONSTRAINT [DF_POP3_INCIDENTS_Description] DEFAULT ('') FOR [Description],
	CONSTRAINT [DF_POP3_INCIDENTS_Priority] DEFAULT (1) FOR [PriorityId],
	CONSTRAINT [DF_POP3_INCIDENTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_POP3_INCIDENTS_FirstName] DEFAULT ('') FOR [FirstName],
	CONSTRAINT [DF_POP3_INCIDENTS_LastName] DEFAULT ('') FOR [LastName],
	CONSTRAINT [DF_POP3_INCIDENTS_MHTFileId] DEFAULT ((-1)) FOR [MHTFileId]
GO
 CREATE  INDEX [IX_POP3_INCIDENTS] ON [dbo].[POP3_INCIDENTS]([PriorityId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3Boxes] ADD
	CONSTRAINT [DF_Pop3Boxes_Port] DEFAULT (110) FOR [Port],
	CONSTRAINT [DF_Pop3Boxes_Active] DEFAULT (1) FOR [Active],
	CONSTRAINT [DF_Pop3Boxes_Interval] DEFAULT (10) FOR [Interval],
	CONSTRAINT [DF_Pop3Boxes_AutoKillForRead] DEFAULT (1) FOR [AutoKillForRead]
GO
 CREATE  INDEX [IX_Pop3BoxParameters] ON [dbo].[Pop3BoxParameters]([Name]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Pop3MailRequests] ADD
	CONSTRAINT [DF_Pop3MailRequests_InnerText] DEFAULT (N'') FOR [InnerText],
	CONSTRAINT [DF_Pop3MailRequests_Pop3BoxId] DEFAULT (500) FOR [Pop3BoxId],
	CONSTRAINT [DF_Pop3MailRequests_Received] DEFAULT (getutcdate()) FOR [Received],
	CONSTRAINT [DF_Pop3MailRequests_MhtFileId] DEFAULT ((-1)) FOR [MhtFileId]
GO
 CREATE  INDEX [IX_Pop3MailRequests] ON [dbo].[Pop3MailRequests]([Pop3MailRequestId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_Pop3MessageUIds] ON [dbo].[Pop3MessageUIds]([Pop3BoxId], [MessageUId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PORTAL_LOGINS] ADD
	CONSTRAINT [DF_PORTAL_LOGINS_IP] DEFAULT ('') FOR [IP]
GO
 CREATE  INDEX [IX_PORTAL_LOGINS] ON [dbo].[PORTAL_LOGINS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PRIORITY_LANGUAGE] ON [dbo].[PRIORITY_LANGUAGE]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PRIORITY_LANGUAGE_1] ON [dbo].[PRIORITY_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_CATEGORIES] ADD
	CONSTRAINT [IX_PROJECT_CATEGORIES] UNIQUE  NONCLUSTERED
	(
		[CategoryName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_CATEGORY] ADD
	CONSTRAINT [IX_PROJECT_CATEGORY_2] UNIQUE  NONCLUSTERED
	(
		[ProjectId],
		[CategoryId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_CATEGORY] ON [dbo].[PROJECT_CATEGORY]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_CATEGORY_1] ON [dbo].[PROJECT_CATEGORY]([CategoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_GROUP] ON [dbo].[PROJECT_GROUP]([RowId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_GROUP_ProjectId] ON [dbo].[PROJECT_GROUP]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_GROUP_ProjectGroupId] ON [dbo].[PROJECT_GROUP]([ProjectGroupId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_MEMBERS] ADD
	CONSTRAINT [DF_PROJECT_MEMBERS_Rate] DEFAULT (0) FOR [Rate],
	CONSTRAINT [DF_MSP_PROJECT_MEMBERS_IsTeamMember] DEFAULT (0) FOR [IsTeamMember],
	CONSTRAINT [DF_MSP_PROJECT_MEMBERS_IsSponsor] DEFAULT (0) FOR [IsSponsor],
	CONSTRAINT [DF_MSP_PROJECT_MEMBERS_IsStakeHolder] DEFAULT (0) FOR [IsStakeHolder],
	CONSTRAINT [IX_PROJECT_MEMBERS] UNIQUE  NONCLUSTERED
	(
		[ProjectId],
		[PrincipalId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECT_MEMBERS] ON [dbo].[PROJECT_MEMBERS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECT_MEMBERS_1] ON [dbo].[PROJECT_MEMBERS]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_RELATIONS] ADD
	CONSTRAINT [IX_PROJECT_RELATIONS_2] UNIQUE  NONCLUSTERED
	(
		[ProjectId],
		[RelProjectId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_RELATIONS] ON [dbo].[PROJECT_RELATIONS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_RELATIONS_1] ON [dbo].[PROJECT_RELATIONS]([RelProjectId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_SNAPSHOTS] ADD
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_TargetBudget] DEFAULT (0) FOR [TargetBudget],
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_EstimatedBudget] DEFAULT (0) FOR [EstimatedBudget],
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_ActualBudget] DEFAULT (0) FOR [ActualBudget],
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_StartDate] DEFAULT (getutcdate()) FOR [StartDate],
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_FinishDate] DEFAULT (getutcdate()) FOR [FinishDate],
	CONSTRAINT [DF_PROJECT_SNAPSHOTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate]
GO
 CREATE  INDEX [IX_PROJECT_SNAPSHOTS] ON [dbo].[PROJECT_SNAPSHOTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_SNAPSHOTS_1] ON [dbo].[PROJECT_SNAPSHOTS]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_SNAPSHOTS_2] ON [dbo].[PROJECT_SNAPSHOTS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_STATUS_LANGUAGE] ON [dbo].[PROJECT_STATUS_LANGUAGE]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_STATUS_LANGUAGE_1] ON [dbo].[PROJECT_STATUS_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_TEMPLATES] ADD
	CONSTRAINT [DF_PROJECT_TEMPLATES_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_PROJECT_TEMPLATES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [DF_PROJECT_TEMPLATES_ProjectTemplate] DEFAULT ('') FOR [TemplateData]
GO
 CREATE  INDEX [IX_PROJECT_TEMPLATES] ON [dbo].[PROJECT_TEMPLATES]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_TEMPLATES_1] ON [dbo].[PROJECT_TEMPLATES]([LastEditorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_USER_DATE] ADD
	CONSTRAINT [IX_PROJECT_USER_DATE_2] UNIQUE  NONCLUSTERED
	(
		[ProjectId],
		[UserId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_USER_DATE] ON [dbo].[PROJECT_USER_DATE]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECT_USER_DATE_1] ON [dbo].[PROJECT_USER_DATE]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTCATEGORY_USER] ON [dbo].[PROJECTCATEGORY_USER]([CategoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTCATEGORY_USER_1] ON [dbo].[PROJECTCATEGORY_USER]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTGROUP_USER] ON [dbo].[PROJECTGROUP_USER]([ProjectGroupId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTGROUP_USER_1] ON [dbo].[PROJECTGROUP_USER]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[RECURRENCE] ADD
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_Pattern] DEFAULT (1) FOR [Pattern],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_PatternType] DEFAULT (1) FOR [SubPattern],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_Frequency] DEFAULT (1) FOR [Frequency],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_Weekdays] DEFAULT (1) FOR [Weekdays],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_DayOfMonth] DEFAULT (1) FOR [DayOfMonth],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_WeekNumber] DEFAULT (1) FOR [WeekNumber],
	CONSTRAINT [DF_MSP_EVENT_RECURRENCE_MonthNumber] DEFAULT (1) FOR [MonthNumber],
	CONSTRAINT [DF_RECURRENCE_EndAfter] DEFAULT (1) FOR [EndAfter],
	CONSTRAINT [DF_RECURRENCE_TimeZoneId] DEFAULT (0) FOR [TimeZoneId]
GO
 CREATE  INDEX [IX_MSP_EVENT_RECURRENCE] ON [dbo].[RECURRENCE]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_RECURRENCE] ON [dbo].[RECURRENCE]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_RECURRENCE] ON [dbo].[RECURRENCE]([TimeZoneId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[REMINDER_SUBSCRIPTIONS] ADD
	CONSTRAINT [DF_USER_REMINDERS_Lag] DEFAULT (0) FOR [Lag],
	CONSTRAINT [DF_REMINDER_SUBSCRIPTIONS_IsActive] DEFAULT (1) FOR [IsActive],
	CONSTRAINT [IX_REMINDER_SUBSCRIPTIONS_3] UNIQUE  NONCLUSTERED
	(
		[DateTypeId],
		[UserId],
		[ObjectId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_REMINDER_SUBSCRIPTIONS] ON [dbo].[REMINDER_SUBSCRIPTIONS]([DateTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_REMINDER_SUBSCRIPTIONS_1] ON [dbo].[REMINDER_SUBSCRIPTIONS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_REMINDER_SUBSCRIPTIONS_2] ON [dbo].[REMINDER_SUBSCRIPTIONS]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_REMINDER_SUBSCRIPTIONS_4] ON [dbo].[REMINDER_SUBSCRIPTIONS]([HookId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Report] ADD
	CONSTRAINT [DF_Report_Created] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_Report_Modified] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [DF_Report_IBNReportTemplate] DEFAULT (N'') FOR [IBNReportTemplate],
	CONSTRAINT [DF_Report_IsGlobal] DEFAULT (1) FOR [IsGlobal],
	CONSTRAINT [DF_Report_IsTemporary] DEFAULT (0) FOR [IsTemporary]
GO
 CREATE  INDEX [IX_Report] ON [dbo].[Report]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_Report_1] ON [dbo].[Report]([LastEditorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ReportHistory] ADD
	CONSTRAINT [DF_ReportHistory_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate]
GO
 CREATE  INDEX [IX_ReportHistory] ON [dbo].[ReportHistory]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SCHEDULE] ON [dbo].[SCHEDULE]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SCHEDULE_1] ON [dbo].[SCHEDULE]([ContUserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ScheduleProcessHandlerTempItems] ADD
	CONSTRAINT [DF_ScheduleProcessHandlerTempItems_Created] DEFAULT (getutcdate()) FOR [Created],
	CONSTRAINT [DF_ScheduleProcessHandlerTempItems_IsProcessed] DEFAULT (0) FOR [IsProcessed]
GO
ALTER TABLE [dbo].[SHARING] ADD
	CONSTRAINT [DF_SHARING_Level] DEFAULT (0) FOR [Level],
	CONSTRAINT [IX_SHARING_2] UNIQUE  NONCLUSTERED
	(
		[UserId],
		[ProUserId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_SHARING] ON [dbo].[SHARING]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SHARING_1] ON [dbo].[SHARING]([ProUserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[STUB_GROUP] ADD
	CONSTRAINT [IX_STUB_GROUP_2] UNIQUE  NONCLUSTERED
	(
		[StubId],
		[GroupId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_STUB_GROUP] ON [dbo].[STUB_GROUP]([StubId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_STUB_GROUP_1] ON [dbo].[STUB_GROUP]([GroupId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[STUBS] ADD
	CONSTRAINT [DF_STUBS_ToolTip] DEFAULT ('') FOR [ToolTip],
	CONSTRAINT [DF_STUBS_OpenInBrowser] DEFAULT (1) FOR [OpenInBrowser],
	CONSTRAINT [DF_STUBS_Width] DEFAULT (300) FOR [Width],
	CONSTRAINT [DF_STUBS_Height] DEFAULT (250) FOR [Height],
	CONSTRAINT [DF_STUBS_IsInternal] DEFAULT (0) FOR [IsInternal]
GO
 CREATE  INDEX [IX_STUBS] ON [dbo].[STUBS]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SUBSCRIPTION_DETAILS] ADD
	CONSTRAINT [IX_SUBSCRIPTION_DETAILS_2] UNIQUE  NONCLUSTERED
	(
		[SubscriptionId],
		[ObjectRoleId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_SUBSCRIPTION_DETAILS] ON [dbo].[SUBSCRIPTION_DETAILS]([SubscriptionId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SUBSCRIPTION_DETAILS_1] ON [dbo].[SUBSCRIPTION_DETAILS]([ObjectRoleId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SUBSCRIPTIONS] ADD
	CONSTRAINT [IX_SUBSCRIPTIONS_3] UNIQUE  NONCLUSTERED
	(
		[EventTypeId],
		[UserId],
		[ObjectId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_SUBSCRIPTIONS] ON [dbo].[SUBSCRIPTIONS]([EventTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SUBSCRIPTIONS_1] ON [dbo].[SUBSCRIPTIONS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SUBSCRIPTIONS_2] ON [dbo].[SUBSCRIPTIONS]([ObjectId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_RECIPIENTS] ADD
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_MessageTypeId] DEFAULT (1) FOR [MessageTypeId],
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_WasSent] DEFAULT (0) FOR [Processed],
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_SendEmail] DEFAULT (0) FOR [SendEmail],
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_SendIbn] DEFAULT (0) FOR [SendIbn],
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_SentEmail] DEFAULT (0) FOR [SentEmail],
	CONSTRAINT [DF_SYSTEM_EVENT_RECIPIENTS_SentIbn] DEFAULT (0) FOR [SentIbn]
GO
 CREATE  INDEX [IX_SYSTEM_EVENT_RECIPIENTS] ON [dbo].[SYSTEM_EVENT_RECIPIENTS]([SystemEventId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENT_RECIPIENTS_1] ON [dbo].[SYSTEM_EVENT_RECIPIENTS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENT_RECIPIENTS_2] ON [dbo].[SYSTEM_EVENT_RECIPIENTS]([MessageTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENT_RECIPIENTS_3] ON [dbo].[SYSTEM_EVENT_RECIPIENTS]([LogId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_TYPES] ADD
	CONSTRAINT [DF_SYSTEM_EVENTS_ParentId] DEFAULT (0) FOR [ParentId],
	CONSTRAINT [DF_SYSTEM_EVENT_TYPES_IsActive] DEFAULT (1) FOR [IsActive]
GO
 CREATE  INDEX [IX_SYSTEM_EVENTS] ON [dbo].[SYSTEM_EVENT_TYPES]([ObjectTypeId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SYSTEM_EVENTS] ADD
	CONSTRAINT [DF_SYSTEM_EVENTS_LOG_ObjectTitle] DEFAULT ('') FOR [ObjectTitle],
	CONSTRAINT [DF_SYSTEM_EVENTS_LOG_RelObjectTitle] DEFAULT ('') FOR [RelObjectTitle],
	CONSTRAINT [DF_SYSTEM_EVENTS_LOG_Dt] DEFAULT (getutcdate()) FOR [Dt],
	CONSTRAINT [DF_SYSTEM_EVENTS_LOG_TranId] DEFAULT (newid()) FOR [TranId]
GO
 CREATE  INDEX [IX_SYSTEM_EVENTS_LOG] ON [dbo].[SYSTEM_EVENTS]([EventTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENTS_LOG_1] ON [dbo].[SYSTEM_EVENTS]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENTS_LOG_2] ON [dbo].[SYSTEM_EVENTS]([Dt]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_SYSTEM_EVENTS_LOG_3] ON [dbo].[SYSTEM_EVENTS]([UserId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_LINKS] ADD
	CONSTRAINT [DF_MSP_LINKS_Lag] DEFAULT (0) FOR [Lag]
GO
 CREATE  INDEX [IX_MSP_LINKS] ON [dbo].[TASK_LINKS]([PredId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_LINKS_1] ON [dbo].[TASK_LINKS]([SuccId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMESHEETS] ADD
	CONSTRAINT [DF_TIMESHEETS_Day1] DEFAULT (0) FOR [Day1],
	CONSTRAINT [DF_TIMESHEETS_Day2] DEFAULT (0) FOR [Day2],
	CONSTRAINT [DF_TIMESHEETS_Day3] DEFAULT (0) FOR [Day3],
	CONSTRAINT [DF_TIMESHEETS_Day4] DEFAULT (0) FOR [Day4],
	CONSTRAINT [DF_TIMESHEETS_Day5] DEFAULT (0) FOR [Day5],
	CONSTRAINT [DF_TIMESHEETS_Day6] DEFAULT (0) FOR [Day6],
	CONSTRAINT [DF_TIMESHEETS_Day7] DEFAULT (0) FOR [Day7],
	CONSTRAINT [DF_TIMESHEETS_TotalApproved] DEFAULT (0) FOR [TotalApproved],
	CONSTRAINT [DF_TIMESHEETS_Rate] DEFAULT (0) FOR [Rate],
	CONSTRAINT [DF_TIMESHEETS_UserComments] DEFAULT ('') FOR [UserComments],
	CONSTRAINT [IX_TIMESHEETS_3] UNIQUE  NONCLUSTERED
	(
		[WeekTimesheetId],
		[ObjectTypeId],
		[ObjectId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMESHEETS] ON [dbo].[TIMESHEETS]([ObjectTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMESHEETS_1] ON [dbo].[TIMESHEETS]([ObjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMESHEETS_2] ON [dbo].[TIMESHEETS]([WeekTimesheetId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMESHEETS_4] ON [dbo].[TIMESHEETS]([ActualId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_LANGUAGE] ON [dbo].[TIMEZONES_LANGUAGE]([TimeZoneId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_LANGUAGE_1] ON [dbo].[TIMEZONES_LANGUAGE]([LanguageId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TIMEZONES_LOCAL_UTC] ADD
	CONSTRAINT [DF_TIMEZONES_DAYLIGHT_RealBias] DEFAULT (0) FOR [TimeOffset],
	CONSTRAINT [DF_TIMEZONEDAYLIGHT_IsDaylight] DEFAULT (0) FOR [IsDaylight]
GO
 CREATE  INDEX [IX_TIMEZONES_DAYLIGHT] ON [dbo].[TIMEZONES_LOCAL_UTC]([TimeZoneId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_DAYLIGHT_1] ON [dbo].[TIMEZONES_LOCAL_UTC]([Start]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_DAYLIGHT_2] ON [dbo].[TIMEZONES_LOCAL_UTC]([End]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_LOCAL_UTC] ON [dbo].[TIMEZONES_LOCAL_UTC]([TimeZoneId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_LOCAL_UTC_1] ON [dbo].[TIMEZONES_LOCAL_UTC]([Start]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_LOCAL_UTC_2] ON [dbo].[TIMEZONES_LOCAL_UTC]([End]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TIMEZONES_UTC_LOCAL] ON [dbo].[TIMEZONES_UTC_LOCAL]([TimeZoneId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_PREFERENCES] ADD
	CONSTRAINT [DF_USER_PREFERENCES_IsNotified] DEFAULT (1) FOR [IsNotified],
	CONSTRAINT [DF_USER_PREFERENCES_IsNotifiedByEmail] DEFAULT (1) FOR [IsNotifiedByEmail],
	CONSTRAINT [DF_USER_PREFERENCES_IsNotifiedByIBN] DEFAULT (1) FOR [IsNotifiedByIBN],
	CONSTRAINT [DF_USER_PREFERENCES_IsBatchNotifications] DEFAULT (0) FOR [IsBatchNotifications],
	CONSTRAINT [DF_USER_PREFERENCES_Period] DEFAULT (60) FOR [Period],
	CONSTRAINT [DF_USER_PREFERENCES_From] DEFAULT (8) FOR [From],
	CONSTRAINT [DF_USER_PREFERENCES_Till] DEFAULT (20) FOR [Till],
	CONSTRAINT [DF_USER_PREFERENCES_TimeZone] DEFAULT (0) FOR [TimeZoneId],
	CONSTRAINT [DF_USER_PREFERENCES_TimeZoneIdLatest] DEFAULT (0) FOR [TimeOffsetLatest],
	CONSTRAINT [DF_USER_PREFERENCES_MenuInAlerts] DEFAULT (0) FOR [MenuInAlerts],
	CONSTRAINT [DF_USER_PREFERENCES_ReminderType] DEFAULT (3) FOR [ReminderType]
GO
 CREATE  INDEX [IX_USER_PREFERENCES] ON [dbo].[USER_PREFERENCES]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_PREFERENCES_1] ON [dbo].[USER_PREFERENCES]([LanguageId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_PROJECT_TEAM] ON [dbo].[USER_PROJECT_TEAM]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_PROJECT_TEAM_1] ON [dbo].[USER_PROJECT_TEAM]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_PROJECT_TEAM_2] ON [dbo].[USER_PROJECT_TEAM]([MemberId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[USER_SETTINGS] ADD
	CONSTRAINT [DF_USER_SETTINGS_InterfaceLanguageId] DEFAULT (1) FOR [Key]
GO
 CREATE  INDEX [IX_USER_SETTINGS] ON [dbo].[USER_SETTINGS]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_SETTINGS_1] ON [dbo].[USER_SETTINGS]([Key]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[WeekTimeSheet] ADD
	CONSTRAINT [DF_WeekTimeSheet_StatusId] DEFAULT (1) FOR [StatusId],
	CONSTRAINT [DF_WeekTimeSheet_ManagerComments] DEFAULT ('') FOR [ManagerComments],
	CONSTRAINT [DF_WeekTimeSheet_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [IX_WeekTimeSheet_4] UNIQUE  NONCLUSTERED
	(
		[UserId],
		[ProjectId],
		[StartDate]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_WeekTimeSheet] ON [dbo].[WeekTimeSheet]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_WeekTimeSheet_1] ON [dbo].[WeekTimeSheet]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_WeekTimeSheet_2] ON [dbo].[WeekTimeSheet]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_WeekTimeSheet_3] ON [dbo].[WeekTimeSheet]([StartDate]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_WeekTimeSheet_5] ON [dbo].[WeekTimeSheet]([LastEditorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CLIENTS] ADD
	CONSTRAINT [DF_CLIENTS_IsInternal] DEFAULT (0) FOR [IsInternal],
	CONSTRAINT [IX_CLIENTS] UNIQUE  NONCLUSTERED
	(
		[ClientName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[CURRENCY] ADD
	CONSTRAINT [IX_CURRENCY] UNIQUE  NONCLUSTERED
	(
		[CurrencySymbol]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_Directories] ADD
	CONSTRAINT [DF_fsc_Directories_Created] DEFAULT (getutcdate()) FOR [Created],
	CONSTRAINT [DF_fsc_Directories_Modified] DEFAULT (getutcdate()) FOR [Modified]
GO
 CREATE  INDEX [IX_fsc_Folders] ON [dbo].[fsc_Directories]([ContainerKey]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_Folders_1] ON [dbo].[fsc_Directories]([Path]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_ForeignContainerKeys] ON [dbo].[fsc_ForeignContainerKeys]([ContainerKey]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_ForeignContainerKeys_1] ON [dbo].[fsc_ForeignContainerKeys]([ForeignContainerKey]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_UserRoles] ADD
	CONSTRAINT [IX_fsc_UserRoles] UNIQUE  NONCLUSTERED
	(
		[PrincipalId],
		[ContainerKey],
		[Role]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_UserRoles_1] ON [dbo].[fsc_UserRoles]([Role]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_UserRoles_2] ON [dbo].[fsc_UserRoles]([PrincipalId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_UserRoles_3] ON [dbo].[fsc_UserRoles]([ContainerKey]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_SEVERITY] ADD
	CONSTRAINT [IX_INCIDENT_SEVERITY] UNIQUE  NONCLUSTERED
	(
		[SeverityName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_TYPES] ADD
	CONSTRAINT [IX_INCIDENT_TYPES] UNIQUE  NONCLUSTERED
	(
		[TypeName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_TYPES] ADD
	CONSTRAINT [IX_LIST_TYPES] UNIQUE  NONCLUSTERED
	(
		[TypeName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PRINCIPALS] ADD
	CONSTRAINT [DF_PRINCIPALS_IsGroup] DEFAULT (0) FOR [IsGroup]
GO
ALTER TABLE [dbo].[PROJECT_PHASES] ADD
	CONSTRAINT [DF_PROJECT_PHASES_Weight] DEFAULT (0) FOR [Weight],
	CONSTRAINT [IX_PROJECT_PHASES] UNIQUE  NONCLUSTERED
	(
		[PhaseName]
	)  ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECT_STATUS] ADD
	CONSTRAINT [DF_MSP_PROJECT_STATE_IsActive] DEFAULT (0) FOR [IsActive]
GO
 CREATE  INDEX [IX_RISK_LEVELS] ON [dbo].[RISK_LEVELS]([Weight]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CONTAINERSHIP] ON [dbo].[CONTAINERSHIP]([PrincipalId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CONTAINERSHIP_1] ON [dbo].[CONTAINERSHIP]([ParentPrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_STATUS] ADD
	CONSTRAINT [DF_DOCUMENT_STATUS_IsInternal] DEFAULT (0) FOR [IsInternal],
	CONSTRAINT [IX_DOCUMENT_STATUS_1] UNIQUE  NONCLUSTERED
	(
		[StatusName]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENT_STATUS] ON [dbo].[DOCUMENT_STATUS]([StateId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_AccessControlLists] ON [dbo].[fsc_AccessControlLists]([DirectoryId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENT_STATUS] ON [dbo].[INCIDENT_STATUS]([StateId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[OBJECT_FORMS] ADD
	CONSTRAINT [IX_OBJECT_FORMS] UNIQUE  NONCLUSTERED
	(
		[ObjectTypeId],
		[FormName]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_OBJECT_FORMS] ON [dbo].[OBJECT_FORMS]([ObjectTypeId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[USERS] ADD
	CONSTRAINT [DF_USERS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_USERS_Activity] DEFAULT (1) FOR [Activity],
	CONSTRAINT [DF_USERS_IsActive] DEFAULT (0) FOR [IsExternal],
	CONSTRAINT [IX_USERS] UNIQUE  NONCLUSTERED
	(
		[Login]
	)  ON [PRIMARY] ,
	CONSTRAINT [IX_USERS_4] UNIQUE  NONCLUSTERED
	(
		[Email]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_USERS_1] ON [dbo].[USERS]([IMGroupId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USERS_2] ON [dbo].[USERS]([CreatedBy]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USERS_3] ON [dbo].[USERS]([Email]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[fsc_AccessControlEntries] ADD
	CONSTRAINT [DF_fsc_AccessControlEntries_IsInternal] DEFAULT (0) FOR [IsInternal]
GO
 CREATE  INDEX [IX_fsc_AccessControlEntries] ON [dbo].[fsc_AccessControlEntries]([Action]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_AccessControlEntries_1] ON [dbo].[fsc_AccessControlEntries]([Role]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_fsc_AccessControlEntries_2] ON [dbo].[fsc_AccessControlEntries]([AclId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_GROUP] ON [dbo].[USER_GROUP]([UserId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_USER_GROUP_1] ON [dbo].[USER_GROUP]([GroupId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[CALENDARS] ADD
	CONSTRAINT [DF_CALENDARS_TimeZoneId] DEFAULT (0) FOR [TimeZoneId]
GO
 CREATE  INDEX [IX_CALENDARS] ON [dbo].[CALENDARS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_CALENDARS_1] ON [dbo].[CALENDARS]([TimeZoneId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_RESOURCES] ADD
	CONSTRAINT [DF_DOCUMENT_RESOURCES_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_DOCUMENT_RESOURCES_ResponsePending] DEFAULT (1) FOR [ResponsePending],
	CONSTRAINT [DF_DOCUMENT_RESOURCES_IsConfirmed] DEFAULT (0) FOR [IsConfirmed],
	CONSTRAINT [DF_DOCUMENT_RESOURCES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [DF_DOCUMENT_RESOURCES_CanManage] DEFAULT (0) FOR [CanManage]
GO
 CREATE  INDEX [IX_DOCUMENT_RESOURCES] ON [dbo].[DOCUMENT_RESOURCES]([DocumentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENT_RESOURCES_1] ON [dbo].[DOCUMENT_RESOURCES]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENT_TODO] ADD
	CONSTRAINT [DF_DOCUMENT_TODO_CompleteDocument] DEFAULT (0) FOR [CompleteDocument],
	CONSTRAINT [IX_DOCUMENT_TODO_2] UNIQUE  NONCLUSTERED
	(
		[DocumentId],
		[ToDoId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENT_TODO] ON [dbo].[DOCUMENT_TODO]([DocumentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENT_TODO_1] ON [dbo].[DOCUMENT_TODO]([ToDoId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[DOCUMENTS] ADD
	CONSTRAINT [DF_DOCUMENTS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_DOCUMENTS_Description] DEFAULT ('') FOR [Description],
	CONSTRAINT [DF_DOCUMENTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_DOCUMENTS_PriorityId] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_DOCUMENTS_IsCompleted] DEFAULT (0) FOR [IsCompleted],
	CONSTRAINT [DF_DOCUMENTS_ReasonId] DEFAULT ((-1)) FOR [ReasonId],
	CONSTRAINT [DF_DOCUMENTS_StateId] DEFAULT (1) FOR [StateId],
	CONSTRAINT [DF_DOCUMENTS_ActivatedManually] DEFAULT (0) FOR [ActivatedManually],
	CONSTRAINT [DF_DOCUMENTS_ActivationTypeId] DEFAULT (3) FOR [ActivationTypeId],
	CONSTRAINT [DF_DOCUMENTS_TaskTime] DEFAULT (0) FOR [TaskTime]
GO
 CREATE  INDEX [IX_DOCUMENTS] ON [dbo].[DOCUMENTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_1] ON [dbo].[DOCUMENTS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_2] ON [dbo].[DOCUMENTS]([ManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_4] ON [dbo].[DOCUMENTS]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_5] ON [dbo].[DOCUMENTS]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_6] ON [dbo].[DOCUMENTS]([ReasonId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_7] ON [dbo].[DOCUMENTS]([StateId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_DOCUMENTS_8] ON [dbo].[DOCUMENTS]([ActivationTypeId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENT_RESOURCES] ADD
	CONSTRAINT [DF_EVENT_RESOURCES_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_EVENT_RESOURCES_ResponsePending] DEFAULT (1) FOR [ResponsePending],
	CONSTRAINT [DF_EVENT_RESOURCES_IsConfirmed] DEFAULT (0) FOR [IsConfirmed],
	CONSTRAINT [DF_EVENT_RESOURCES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [IX_MSP_EVENT_RESOURCES_2] UNIQUE  NONCLUSTERED
	(
		[EventId],
		[PrincipalId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENT_RESOURCES] ON [dbo].[EVENT_RESOURCES]([EventId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENT_RESOURCES_1] ON [dbo].[EVENT_RESOURCES]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[EVENTS] ADD
	CONSTRAINT [DF_EVENTS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_MSP_EVENTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_MSP_EVENTS_Priority] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_EVENTS_Interval] DEFAULT ((-1)) FOR [Interval],
	CONSTRAINT [DF_EVENTS_StateId] DEFAULT (1) FOR [StateId],
	CONSTRAINT [DF_EVENTS_TaskTime] DEFAULT (0) FOR [TaskTime]
GO
 CREATE  INDEX [IX_MSP_EVENTS] ON [dbo].[EVENTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENTS_1] ON [dbo].[EVENTS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENTS_2] ON [dbo].[EVENTS]([ManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENTS_4] ON [dbo].[EVENTS]([TypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_EVENTS_5] ON [dbo].[EVENTS]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_EVENTS] ON [dbo].[EVENTS]([StartDate]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_RESOURCES] ADD
	CONSTRAINT [DF_INCIDENT_RESOURCES_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_INCIDENT_RESOURCES_ResponsePending] DEFAULT (1) FOR [ResponsePending],
	CONSTRAINT [DF_INCIDENT_RESOURCES_IsConfirmed] DEFAULT (0) FOR [IsConfirmed],
	CONSTRAINT [DF_INCIDENT_RESOURCES_LastSavedDate] DEFAULT (getdate()) FOR [LastSavedDate],
	CONSTRAINT [DF_INCIDENT_RESOURCES_CanManage] DEFAULT (0) FOR [CanManage],
	CONSTRAINT [IX_INCIDENT_RESOURCES_2] UNIQUE  NONCLUSTERED
	(
		[IncidentId],
		[PrincipalId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_RESOURCES] ON [dbo].[INCIDENT_RESOURCES]([IncidentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_RESOURCES_1] ON [dbo].[INCIDENT_RESOURCES]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENT_TODO] ADD
	CONSTRAINT [DF_INCIDENT_TODO_StatusId] DEFAULT ((-1)) FOR [StatusId],
	CONSTRAINT [IX_INCIDENT_TODO_2] UNIQUE  NONCLUSTERED
	(
		[IncidentId],
		[ToDoId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_TODO] ON [dbo].[INCIDENT_TODO]([IncidentId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENT_TODO_1] ON [dbo].[INCIDENT_TODO]([ToDoId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[INCIDENTS] ADD
	CONSTRAINT [DF_INCIDENTS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_INCIDENTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_INCIDENTS_Priority] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_INCIDENTS_IsEmail] DEFAULT (0) FOR [IsEmail],
	CONSTRAINT [DF_INCIDENTS_StateId] DEFAULT (1) FOR [StateId],
	CONSTRAINT [DF_INCIDENTS_TaskTime] DEFAULT (0) FOR [TaskTime]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS] ON [dbo].[INCIDENTS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_2] ON [dbo].[INCIDENTS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_3] ON [dbo].[INCIDENTS]([ManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_5] ON [dbo].[INCIDENTS]([TypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_6] ON [dbo].[INCIDENTS]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_7] ON [dbo].[INCIDENTS]([SeverityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_INCIDENTS_8] ON [dbo].[INCIDENTS]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_INCIDENTS_1] ON [dbo].[INCIDENTS]([StateId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_FOLDER_ACCESS] ON [dbo].[LIST_ACCESS]([ListId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_FOLDER_ACCESS_1] ON [dbo].[LIST_ACCESS]([PrincipalId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_FOLDER_ACCESS_2] ON [dbo].[LIST_ACCESS]([AllowLevel]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[LIST_FOLDERS] ADD
	CONSTRAINT [DF_LIST_FOLDERS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate]
GO
 CREATE  INDEX [IX_LIST_FOLDERS] ON [dbo].[LIST_FOLDERS]([ParentFolderId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_FOLDERS_1] ON [dbo].[LIST_FOLDERS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LIST_FOLDERS_2] ON [dbo].[LIST_FOLDERS]([ProjectId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[LISTS] ADD
	CONSTRAINT [DF_LISTS_Description] DEFAULT ('') FOR [Description],
	CONSTRAINT [DF_LISTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate]
GO
 CREATE  INDEX [IX_LISTS] ON [dbo].[LISTS]([TypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LISTS_1] ON [dbo].[LISTS]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_LISTS_2] ON [dbo].[LISTS]([CreatorId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PROJECTS] ADD
	CONSTRAINT [DF_PROJECTS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_MSP_PROJECTS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_PROJECTS_TargetStartDate] DEFAULT (getutcdate()) FOR [TargetStartDate],
	CONSTRAINT [DF_MSP_PROJECTS_StateId] DEFAULT (1) FOR [StatusId],
	CONSTRAINT [DF_PROJECTS_ClientId] DEFAULT (1) FOR [ClientId],
	CONSTRAINT [DF_PROJECTS_XMLFileId] DEFAULT ((-1)) FOR [XMLFileId],
	CONSTRAINT [DF_PROJECTS_CurrencyId] DEFAULT (1) FOR [CurrencyId],
	CONSTRAINT [DF_PROJECTS_PriorityId] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_PROJECTS_PercentCompleted] DEFAULT (0) FOR [PercentCompleted],
	CONSTRAINT [DF_PROJECTS_InitialPhaseId] DEFAULT (1) FOR [InitialPhaseId],
	CONSTRAINT [DF_PROJECTS_RiskLevelId] DEFAULT (1) FOR [RiskLevelId]
GO
 CREATE  INDEX [IX_MSP_PROJECTS] ON [dbo].[PROJECTS]([FormId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECTS_2] ON [dbo].[PROJECTS]([CalendarId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECTS_3] ON [dbo].[PROJECTS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECTS_4] ON [dbo].[PROJECTS]([ManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_PROJECTS_5] ON [dbo].[PROJECTS]([ExecutiveManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS] ON [dbo].[PROJECTS]([StatusId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS_1] ON [dbo].[PROJECTS]([ClientId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS_2] ON [dbo].[PROJECTS]([CurrencyId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS_4] ON [dbo].[PROJECTS]([PhaseId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS_8] ON [dbo].[PROJECTS]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_PROJECTS_5] ON [dbo].[PROJECTS]([InitialPhaseId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_RESOURCES] ADD
	CONSTRAINT [DF_MSP_ASSIGNMENTS_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_MSP_ASSIGNMENTS_ResponsePending] DEFAULT (1) FOR [ResponsePending],
	CONSTRAINT [DF_MSP_ASSIGNMENTS_IsConfirmed] DEFAULT (0) FOR [IsConfirmed],
	CONSTRAINT [DF_MSP_ASSIGNMENTS_PercentCompleted] DEFAULT (0) FOR [PercentCompleted],
	CONSTRAINT [DF_TASK_RESOURCES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [DF_TASK_RESOURCES_CanManage] DEFAULT (0) FOR [CanManage],
	CONSTRAINT [IX_MSP_TASK_RESOURCES_2] UNIQUE  NONCLUSTERED
	(
		[TaskId],
		[PrincipalId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASK_RESOURCES] ON [dbo].[TASK_RESOURCES]([TaskId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASK_RESOURCES_1] ON [dbo].[TASK_RESOURCES]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASK_TODO] ADD
	CONSTRAINT [DF_TASK_TODO_CompleteTask] DEFAULT (0) FOR [CompleteTask],
	CONSTRAINT [IX_TASK_TODO_2] UNIQUE  NONCLUSTERED
	(
		[TaskId],
		[ToDoId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_TASK_TODO] ON [dbo].[TASK_TODO]([TaskId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TASK_TODO_1] ON [dbo].[TASK_TODO]([ToDoId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TASKS] ADD
	CONSTRAINT [DF_TASKS_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_MSP_TASKS_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_MSP_TASKS_Priority] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_MSP_TASKS_PercentCompleted] DEFAULT (0) FOR [PercentCompleted],
	CONSTRAINT [DF_MSP_TASKS_IsSummary] DEFAULT (0) FOR [IsSummary],
	CONSTRAINT [DF_MSP_TASKS_IsMilestone] DEFAULT (0) FOR [IsMilestone],
	CONSTRAINT [DF_TASKS_IsCompleted] DEFAULT (0) FOR [IsCompleted],
	CONSTRAINT [DF_TASKS_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_TASKS_ReasonId] DEFAULT ((-1)) FOR [ReasonId],
	CONSTRAINT [DF_TASKS_ActivatedManually] DEFAULT (0) FOR [ActivatedManually],
	CONSTRAINT [DF_TASKS_ActivationTypeId] DEFAULT (1) FOR [ActivationTypeId],
	CONSTRAINT [DF_TASKS_StateId] DEFAULT (1) FOR [StateId],
	CONSTRAINT [DF_TASKS_TaskTime] DEFAULT (0) FOR [TaskTime],
	CONSTRAINT [CK_TASKS] CHECK ([PercentCompleted] <= 100)
GO
 CREATE  INDEX [IX_MSP_TASKS] ON [dbo].[TASKS]([TaskNum]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_1] ON [dbo].[TASKS]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_2] ON [dbo].[TASKS]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_5] ON [dbo].[TASKS]([ConstraintTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_4] ON [dbo].[TASKS]([CompletionTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_6] ON [dbo].[TASKS]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_7] ON [dbo].[TASKS]([OutlineNumber]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_8] ON [dbo].[TASKS]([OutlineLevel]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TASKS_9] ON [dbo].[TASKS]([IsSummary]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TASKS] ON [dbo].[TASKS]([CompletedBy]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TASKS_2] ON [dbo].[TASKS]([PhaseId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TODO] ADD
	CONSTRAINT [DF_TODO_UID] DEFAULT (newid()) FOR [UID],
	CONSTRAINT [DF_MSP_TODO_CreationDate] DEFAULT (getutcdate()) FOR [CreationDate],
	CONSTRAINT [DF_MSP_TODO_Priority] DEFAULT (500) FOR [PriorityId],
	CONSTRAINT [DF_MSP_TODO_PercentCompleted] DEFAULT (0) FOR [PercentCompleted],
	CONSTRAINT [DF_MSP_TODO_IsActual] DEFAULT (0) FOR [IsActual],
	CONSTRAINT [DF_TODO_IsCompleted] DEFAULT (0) FOR [IsCompleted],
	CONSTRAINT [DF_TODO_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_TODO_ReasonId] DEFAULT ((-1)) FOR [ReasonId],
	CONSTRAINT [DF_TODO_ActivatedManually] DEFAULT (0) FOR [ActivatedManually],
	CONSTRAINT [DF_TODO_ActivationTypeId] DEFAULT (1) FOR [ActivationTypeId],
	CONSTRAINT [DF_TODO_StateId] DEFAULT (1) FOR [StateId],
	CONSTRAINT [DF_TODO_TaskTime] DEFAULT (0) FOR [TaskTime]
GO
 CREATE  INDEX [IX_MSP_TODO] ON [dbo].[TODO]([ProjectId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_1] ON [dbo].[TODO]([CreatorId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_2] ON [dbo].[TODO]([ManagerId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_5] ON [dbo].[TODO]([CompletionTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_6] ON [dbo].[TODO]([PriorityId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TODO] ON [dbo].[TODO]([CompletedBy]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TODO_2] ON [dbo].[TODO]([ActivationTypeId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_TODO_3] ON [dbo].[TODO]([StateId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TODO_RESOURCES] ADD
	CONSTRAINT [DF_MSP_TODO_RESOURCES_MustBeConfirmed] DEFAULT (0) FOR [MustBeConfirmed],
	CONSTRAINT [DF_MSP_TODO_RESOURCES_ResponsePending] DEFAULT (1) FOR [ResponsePending],
	CONSTRAINT [DF_MSP_TODO_RESOURCES_IsConfirmed] DEFAULT (0) FOR [IsConfirmed],
	CONSTRAINT [DF_MSP_TODO_RESOURCES_PercentCompleted] DEFAULT (0) FOR [PercentCompleted],
	CONSTRAINT [DF_TODO_RESOURCES_LastSavedDate] DEFAULT (getutcdate()) FOR [LastSavedDate],
	CONSTRAINT [IX_MSP_TODO_RESOURCES_2] UNIQUE  NONCLUSTERED
	(
		[ToDoId],
		[PrincipalId]
	)  ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_RESOURCES] ON [dbo].[TODO_RESOURCES]([ToDoId]) ON [PRIMARY]
GO
 CREATE  INDEX [IX_MSP_TODO_RESOURCES_1] ON [dbo].[TODO_RESOURCES]([PrincipalId]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ACCOUNTS] ADD
	CONSTRAINT [FK_ACCOUNTS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_ACCOUNTS_USERS] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[ACTIVATION_TYPE_LANGUAGE] ADD
	CONSTRAINT [FK_ACTIVATION_TYPE_LANGUAGE_ACTIVATION_TYPES] FOREIGN KEY
	(
		[ActivationTypeId]
	) REFERENCES [dbo].[ACTIVATION_TYPES] (
		[ActivationTypeId]
	),
	CONSTRAINT [FK_START_TYPE_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[ACTUAL_FINANCES] ADD
	CONSTRAINT [FK_ACTUAL_FINANCES_ACCOUNTS] FOREIGN KEY
	(
		[AccountId]
	) REFERENCES [dbo].[ACCOUNTS] (
		[AccountId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_ACTUAL_FINANCES_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_ACTUAL_FINANCES_USERS] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[BroadcastRecipients] ADD
	CONSTRAINT [FK_BroadcastRecipients_BroadcastMessages] FOREIGN KEY
	(
		[MessageId]
	) REFERENCES [dbo].[BroadcastMessages] (
		[MessageId]
	) ON DELETE CASCADE  ON UPDATE CASCADE ,
	CONSTRAINT [FK_BroadcastRecipients_GROUPS] FOREIGN KEY
	(
		[GroupId]
	) REFERENCES [dbo].[GROUPS] (
		[PrincipalId]
	) ON DELETE CASCADE  ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[CAL_EXCEPTION_HOURS] ADD
	CONSTRAINT [FK_MSP_CAL_EXCEPTION_HOURS_MSP_CAL_EXCEPTIONS] FOREIGN KEY
	(
		[ExceptionId]
	) REFERENCES [dbo].[CAL_EXCEPTIONS] (
		[ExceptionId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CAL_EXCEPTIONS] ADD
	CONSTRAINT [FK_MSP_CAL_EXCEPTIONS_MSP_CALENDARS] FOREIGN KEY
	(
		[CalendarId]
	) REFERENCES [dbo].[CALENDARS] (
		[CalendarId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CAL_WEEKDAYS] ADD
	CONSTRAINT [FK_MSP_CAL_WEEKDAYS_MSP_CALENDARS] FOREIGN KEY
	(
		[CalendarId]
	) REFERENCES [dbo].[CALENDARS] (
		[CalendarId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CATEGORY_USER] ADD
	CONSTRAINT [FK_CATEGORY_USER_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[CATEGORIES] (
		[CategoryId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_CATEGORY_USER_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[COLLAPSED_ACCOUNTS] ADD
	CONSTRAINT [FK_COLLAPSED_ACCOUNTS_ACCOUNTS] FOREIGN KEY
	(
		[AccountId]
	) REFERENCES [dbo].[ACCOUNTS] (
		[AccountId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_COLLAPSED_ACCOUNTS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[COLLAPSED_DOCUMENTS] ADD
	CONSTRAINT [FK_COLLAPSED_DOCUMENTS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[COLLAPSED_INCIDENTS] ADD
	CONSTRAINT [FK_COLLAPSED_INCIDENTS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[COLLAPSED_MANAGERTIMESHEETS] ADD
	CONSTRAINT [FK_COLLAPSED_MANAGERTIMESHEETS_USERS] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_COLLAPSED_MANAGERTIMESHEETS_USERS1] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[COLLAPSED_TASKS] ADD
	CONSTRAINT [FK_COLLAPSED_TASKS_TASKS] FOREIGN KEY
	(
		[TaskId]
	) REFERENCES [dbo].[TASKS] (
		[TaskId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_COLLAPSED_TASKS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[COLLAPSED_USERTIMESHEETS] ADD
	CONSTRAINT [FK_COLLAPSED_USERTIMESHEETS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[COMPLETION_REASON_LANGUAGE] ADD
	CONSTRAINT [FK_COMPLETION_REASON_LANGUAGE_COMPLETION_REASONS] FOREIGN KEY
	(
		[ReasonId]
	) REFERENCES [dbo].[COMPLETION_REASONS] (
		[ReasonId]
	),
	CONSTRAINT [FK_COMPLETION_REASON_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[COMPLETION_TYPE_LANGUAGE] ADD
	CONSTRAINT [FK_COMPLETION_TYPE_LANGUAGE_COMPLETION_TYPES] FOREIGN KEY
	(
		[CompletionTypeId]
	) REFERENCES [dbo].[COMPLETION_TYPES] (
		[CompletionTypeId]
	),
	CONSTRAINT [FK_COMPLETION_TYPE_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[CONSTRAINT_TYPE_LANGUAGE] ADD
	CONSTRAINT [FK_CONSTRAINT_TYPE_LANGUAGE_CONSTRAINT_TYPES] FOREIGN KEY
	(
		[ConstraintTypeId]
	) REFERENCES [dbo].[CONSTRAINT_TYPES] (
		[ConstraintTypeId]
	),
	CONSTRAINT [FK_CONSTRAINT_TYPE_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[DATE_TYPE_HOOKS] ADD
	CONSTRAINT [FK_DATE_TYPE_HOOKS_DATE_TYPE_HANDLERS] FOREIGN KEY
	(
		[HandlerId]
	) REFERENCES [dbo].[DATE_TYPE_HANDLERS] (
		[HandlerId]
	),
	CONSTRAINT [FK_DATE_TYPE_HOOKS_DATE_TYPES] FOREIGN KEY
	(
		[DateTypeId]
	) REFERENCES [dbo].[DATE_TYPES] (
		[DateTypeId]
	)
GO
ALTER TABLE [dbo].[DATE_TYPE_PROCESSED] ADD
	CONSTRAINT [FK_DATE_TYPE_PROCESSED_DATE_TYPE_HOOKS] FOREIGN KEY
	(
		[HookId]
	) REFERENCES [dbo].[DATE_TYPE_HOOKS] (
		[HookId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_DATE_TYPE_PROCESSED_DATE_TYPE_VALUES] FOREIGN KEY
	(
		[ValueId]
	) REFERENCES [dbo].[DATE_TYPE_VALUES] (
		[ValueId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[DATE_TYPE_VALUES] ADD
	CONSTRAINT [FK_DATE_TYPE_VALUES_DATE_TYPES] FOREIGN KEY
	(
		[DateTypeId]
	) REFERENCES [dbo].[DATE_TYPES] (
		[DateTypeId]
	)
GO
ALTER TABLE [dbo].[DATE_TYPES] ADD
	CONSTRAINT [FK_DATE_TYPES_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[DISCUSSIONS] ADD
	CONSTRAINT [FK_DISCUSSIONS_RELATIONTYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_DISCUSSIONS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[EMAILS] ADD
	CONSTRAINT [FK_EMAILS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[EVENT_REMINDER] ADD
	CONSTRAINT [FK_EVENT_REMINDER_EVENTS] FOREIGN KEY
	(
		[EventId]
	) REFERENCES [dbo].[EVENTS] (
		[EventId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[EVENT_TYPE_LANGUAGE] ADD
	CONSTRAINT [FK_EVENT_TYPE_LANGUAGE_EVENT_TYPES] FOREIGN KEY
	(
		[TypeId]
	) REFERENCES [dbo].[EVENT_TYPES] (
		[TypeId]
	),
	CONSTRAINT [FK_EVENT_TYPE_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[EXTERNAL_GATE] ADD
	CONSTRAINT [FK_EXTERNAL_GATE_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_EXTERNAL_GATE_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[FAVORITES] ADD
	CONSTRAINT [FK_FAVORITES_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_FAVORITES_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[fsc_FileBinaries] ADD
	CONSTRAINT [FK_fsc_FileBinaries_CONTENT_TYPES] FOREIGN KEY
	(
		[ContentTypeId]
	) REFERENCES [dbo].[CONTENT_TYPES] (
		[ContentTypeId]
	)
GO
ALTER TABLE [dbo].[fsc_Files] ADD
	CONSTRAINT [FK_fsc_Files_fsc_FileBinaries] FOREIGN KEY
	(
		[FileBinaryId]
	) REFERENCES [dbo].[fsc_FileBinaries] (
		[FileBinaryId]
	),
	CONSTRAINT [FK_fsc_Files_fsc_Folders] FOREIGN KEY
	(
		[DirectoryId]
	) REFERENCES [dbo].[fsc_Directories] (
		[DirectoryId]
	)
GO
ALTER TABLE [dbo].[fsc_Files_History] ADD
	CONSTRAINT [FK_fsc_Files_History_fsc_Files] FOREIGN KEY
	(
		[FileId]
	) REFERENCES [dbo].[fsc_Files] (
		[FileId]
	)
GO
ALTER TABLE [dbo].[fsc_ForumThreadNodes] ADD
	CONSTRAINT [FK_fsc_ForumThreadNodes_fsc_ForumThreads] FOREIGN KEY
	(
		[ThreadId]
	) REFERENCES [dbo].[fsc_ForumThreads] (
		[ThreadId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[fsc_ForumThreads] ADD
	CONSTRAINT [FK_fsc_ForumThreads_fsc_Forums] FOREIGN KEY
	(
		[ForumId]
	) REFERENCES [dbo].[fsc_Forums] (
		[ForumId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[fsc_ReportAccessControlEntries] ADD
	CONSTRAINT [FK_fsc_ReportAccessControlEntries_fsc_ReportAccessControlLists] FOREIGN KEY
	(
		[AclId]
	) REFERENCES [dbo].[fsc_ReportAccessControlLists] (
		[AclId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[fsc_ReportAccessControlLists] ADD
	CONSTRAINT [FK_fsc_ReportAccessControlLists_fsc_Reports] FOREIGN KEY
	(
		[ReportId]
	) REFERENCES [dbo].[fsc_Reports] (
		[ReportId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[fsc_Reports] ADD
	CONSTRAINT [FK_fsc_Reports_fsc_ReportCategories] FOREIGN KEY
	(
		[ReportCategoryId]
	) REFERENCES [dbo].[fsc_ReportCategories] (
		[ReportCategoryId]
	)
GO
ALTER TABLE [dbo].[HIDDEN_STUBS] ADD
	CONSTRAINT [FK_HIDED_STUBS_STUBS] FOREIGN KEY
	(
		[StubId]
	) REFERENCES [dbo].[STUBS] (
		[StubId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_HIDED_STUBS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[HISTORY] ADD
	CONSTRAINT [FK_HISTORY_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_HISTORY_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[INCIDENT_CATEGORY] ADD
	CONSTRAINT [FK_INCIDENT_CATEGORY_INCIDENT_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[INCIDENT_CATEGORIES] (
		[CategoryId]
	),
	CONSTRAINT [FK_INCIDENT_CATEGORY_INCIDENTS] FOREIGN KEY
	(
		[IncidentId]
	) REFERENCES [dbo].[INCIDENTS] (
		[IncidentId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[INCIDENT_RELATIONS] ADD
	CONSTRAINT [FK_INCIDENT_RELATIONS_INCIDENTS] FOREIGN KEY
	(
		[IncidentId]
	) REFERENCES [dbo].[INCIDENTS] (
		[IncidentId]
	),
	CONSTRAINT [FK_INCIDENT_RELATIONS_INCIDENTS1] FOREIGN KEY
	(
		[RelIncidentId]
	) REFERENCES [dbo].[INCIDENTS] (
		[IncidentId]
	)
GO
ALTER TABLE [dbo].[INCIDENT_STATUS_LANGUAGE] ADD
	CONSTRAINT [FK_INCIDENT_STATUS_LANGUAGE_INCIDENT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[INCIDENT_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_INCIDENT_STATUS_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[INCIDENTCATEGORY_USER] ADD
	CONSTRAINT [FK_INCIDENTCATEGORY_USER_INCIDENT_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[INCIDENT_CATEGORIES] (
		[CategoryId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_INCIDENTCATEGORY_USER_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[LIST_ITEMS] ADD
	CONSTRAINT [FK_LIST_ITEMS_LISTS] FOREIGN KEY
	(
		[ListId]
	) REFERENCES [dbo].[LISTS] (
		[ListId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_LIST_ITEMS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_LIST_ITEMS_USERS1] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[LIST_STATUS_LANGUAGE] ADD
	CONSTRAINT [FK_LIST_STATUS_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_LIST_STATUS_LANGUAGE_LIST_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[LIST_STATUS] (
		[StatusId]
	)
GO
ALTER TABLE [dbo].[MetaClassMetaFieldRelation] ADD
	CONSTRAINT [FK_MetaClassMetaFieldRelation_MetaClass] FOREIGN KEY
	(
		[MetaClassId]
	) REFERENCES [dbo].[MetaClass] (
		[MetaClassId]
	),
	CONSTRAINT [FK_MetaClassMetaFieldRelation_MetaField] FOREIGN KEY
	(
		[MetaFieldId]
	) REFERENCES [dbo].[MetaField] (
		[MetaFieldId]
	)
GO
ALTER TABLE [dbo].[MetaDictionary] ADD
	CONSTRAINT [FK_MetaDictionary_MetaField] FOREIGN KEY
	(
		[MetaFieldId]
	) REFERENCES [dbo].[MetaField] (
		[MetaFieldId]
	)
GO
ALTER TABLE [dbo].[MetaField] ADD
	CONSTRAINT [FK_MetaField_MetaDataType] FOREIGN KEY
	(
		[DataTypeId]
	) REFERENCES [dbo].[MetaDataType] (
		[DataTypeId]
	)
GO
ALTER TABLE [dbo].[MetaFileValue] ADD
	CONSTRAINT [FK_MetaFileValue_MetaKey] FOREIGN KEY
	(
		[MetaKey]
	) REFERENCES [dbo].[MetaKey] (
		[MetaKey]
	)
GO
ALTER TABLE [dbo].[MetaMultiValueDictionary] ADD
	CONSTRAINT [FK_MetaMultiValueDictionary_MetaKey] FOREIGN KEY
	(
		[MetaKey]
	) REFERENCES [dbo].[MetaKey] (
		[MetaKey]
	)
GO
ALTER TABLE [dbo].[OBJECT_CATEGORY] ADD
	CONSTRAINT [FK_OBJECT_CATEGORY_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[CATEGORIES] (
		[CategoryId]
	),
	CONSTRAINT [FK_OBJECT_CATEGORY_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[OBJECT_MENUS_LANGUAGE] ADD
	CONSTRAINT [FK_OBJECT_MENUS_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_OBJECT_MENUS_LANGUAGE_OBJECT_MENUS] FOREIGN KEY
	(
		[MenuId]
	) REFERENCES [dbo].[OBJECT_MENUS] (
		[MenuId]
	)
GO
ALTER TABLE [dbo].[OBJECT_ROLES] ADD
	CONSTRAINT [FK_OBJECT_ROLES_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[OBJECT_STATE_LANGUAGE] ADD
	CONSTRAINT [FK_OBJECT_STATE_LANGUAGE_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_TASK_STATE_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	)
GO
ALTER TABLE [dbo].[OBJECT_VIEW_PAGES] ADD
	CONSTRAINT [FK_OBJECT_VIEW_PAGES_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[OBJECT_VIEW_PAGES_LANGUAGE] ADD
	CONSTRAINT [FK_OBJECT_VIEW_PAGES_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_OBJECT_VIEW_PAGES_LANGUAGE_OBJECT_VIEW_PAGES] FOREIGN KEY
	(
		[ViewPageId]
	) REFERENCES [dbo].[OBJECT_VIEW_PAGES] (
		[ViewPageId]
	)
GO
ALTER TABLE [dbo].[OBJECT_VIEW_TABS] ADD
	CONSTRAINT [FK_OBJECT_VIEW_TABS_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_OBJECT_VIEW_TABS_OBJECT_VIEW_TEMPLATES] FOREIGN KEY
	(
		[TemplateId]
	) REFERENCES [dbo].[OBJECT_VIEW_TEMPLATES] (
		[TemplateId]
	)
GO
ALTER TABLE [dbo].[OBJECT_VIEW_TABS_LANGUAGE] ADD
	CONSTRAINT [FK_OBJECT_VIEW_TABS_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_OBJECT_VIEW_TABS_LANGUAGE_OBJECT_VIEW_TABS] FOREIGN KEY
	(
		[TabId]
	) REFERENCES [dbo].[OBJECT_VIEW_TABS] (
		[TabId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PARTNER_GROUP] ADD
	CONSTRAINT [FK_PARTNER_GROUP_GROUPS] FOREIGN KEY
	(
		[PartnerId]
	) REFERENCES [dbo].[GROUPS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_PARTNER_GROUP_GROUPS1] FOREIGN KEY
	(
		[GroupId]
	) REFERENCES [dbo].[GROUPS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[Pop3BoxParameters] ADD
	CONSTRAINT [FK_Pop3BoxParameters_Pop3Boxes] FOREIGN KEY
	(
		[Pop3BoxId]
	) REFERENCES [dbo].[Pop3Boxes] (
		[Pop3BoxId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pop3BoxPop3DocumentHandler] ADD
	CONSTRAINT [FK_Pop3BoxPop3DocumentHandler_Pop3Boxes] FOREIGN KEY
	(
		[Pop3BoxId]
	) REFERENCES [dbo].[Pop3Boxes] (
		[Pop3BoxId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pop3MailRequests] ADD
	CONSTRAINT [FK_Pop3MailRequests_Pop3Boxes] FOREIGN KEY
	(
		[Pop3BoxId]
	) REFERENCES [dbo].[Pop3Boxes] (
		[Pop3BoxId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Pop3MessageUIds] ADD
	CONSTRAINT [FK_Pop3MessagesId_Pop3Boxes] FOREIGN KEY
	(
		[Pop3BoxId]
	) REFERENCES [dbo].[Pop3Boxes] (
		[Pop3BoxId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PORTAL_LOGINS] ADD
	CONSTRAINT [FK_PORTAL_LOGINS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PRIORITY_LANGUAGE] ADD
	CONSTRAINT [FK_PRIORITY_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_PRIORITY_LANGUAGE_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	)
GO
ALTER TABLE [dbo].[PROJECT_CATEGORY] ADD
	CONSTRAINT [FK_PROJECT_CATEGORY_PROJECT_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[PROJECT_CATEGORIES] (
		[CategoryId]
	),
	CONSTRAINT [FK_PROJECT_CATEGORY_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PROJECT_GROUP] ADD
	CONSTRAINT [FK_PROJECT_GROUP_PROJECT_GROUPS] FOREIGN KEY
	(
		[ProjectGroupId]
	) REFERENCES [dbo].[PROJECT_GROUPS] (
		[ProjectGroupId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_PROJECT_GROUP_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PROJECT_GROUPS] ADD
	CONSTRAINT [FK_PROJECT_GROUPS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[PROJECT_MEMBERS] ADD
	CONSTRAINT [FK_MSP_PROJECT_MEMBERS_MSP_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_MSP_PROJECT_MEMBERS_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[PROJECT_RELATIONS] ADD
	CONSTRAINT [FK_PROJECT_RELATIONS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	),
	CONSTRAINT [FK_PROJECT_RELATIONS_PROJECTS1] FOREIGN KEY
	(
		[RelProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	)
GO
ALTER TABLE [dbo].[PROJECT_SNAPSHOTS] ADD
	CONSTRAINT [FK_PROJECT_SNAPSHOTS_PROJECT_PHASES] FOREIGN KEY
	(
		[PhaseId]
	) REFERENCES [dbo].[PROJECT_PHASES] (
		[PhaseId]
	),
	CONSTRAINT [FK_PROJECT_SNAPSHOTS_PROJECT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[PROJECT_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_PROJECT_SNAPSHOTS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_PROJECT_SNAPSHOTS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PROJECT_STATUS_LANGUAGE] ADD
	CONSTRAINT [FK_PROJECT_STATUS_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_PROJECT_STATUS_LANGUAGE_PROJECT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[PROJECT_STATUS] (
		[StatusId]
	)
GO
ALTER TABLE [dbo].[PROJECT_TEMPLATES] ADD
	CONSTRAINT [FK_PROJECT_TEMPLATES_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_PROJECT_TEMPLATES_USERS1] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[PROJECT_USER_DATE] ADD
	CONSTRAINT [FK_PROJECT_USER_DATE_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_PROJECT_USER_DATE_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PROJECTCATEGORY_USER] ADD
	CONSTRAINT [FK_PROJECTCATEGORY_USER_PROJECT_CATEGORIES] FOREIGN KEY
	(
		[CategoryId]
	) REFERENCES [dbo].[PROJECT_CATEGORIES] (
		[CategoryId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_PROJECTCATEGORY_USER_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PROJECTGROUP_USER] ADD
	CONSTRAINT [FK_PROJECTGROUP_USER_PROJECT_GROUPS] FOREIGN KEY
	(
		[ProjectGroupId]
	) REFERENCES [dbo].[PROJECT_GROUPS] (
		[ProjectGroupId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_PROJECTGROUP_USER_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[RECURRENCE] ADD
	CONSTRAINT [FK_MSP_RECURRENCE_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_RECURRENCE_TIMEZONES] FOREIGN KEY
	(
		[TimeZoneId]
	) REFERENCES [dbo].[TIMEZONES] (
		[TimeZoneId]
	)
GO
ALTER TABLE [dbo].[REMINDER_SUBSCRIPTIONS] ADD
	CONSTRAINT [FK_REMINDER_SUBSCRIPTIONS_DATE_TYPE_HOOKS] FOREIGN KEY
	(
		[HookId]
	) REFERENCES [dbo].[DATE_TYPE_HOOKS] (
		[HookId]
	),
	CONSTRAINT [FK_REMINDER_SUBSCRIPTIONS_DATE_TYPES] FOREIGN KEY
	(
		[DateTypeId]
	) REFERENCES [dbo].[DATE_TYPES] (
		[DateTypeId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_REMINDER_SUBSCRIPTIONS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Report] ADD
	CONSTRAINT [FK_Report_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_Report_USERS1] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[ReportHistory] ADD
	CONSTRAINT [FK_ReportHistory_Report] FOREIGN KEY
	(
		[ReportId]
	) REFERENCES [dbo].[Report] (
		[ReportId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_ReportHistory_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[SCHEDULE] ADD
	CONSTRAINT [FK_SCHEDULE_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_SCHEDULE_USERS1] FOREIGN KEY
	(
		[ContUserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[SHARING] ADD
	CONSTRAINT [FK_SHARING_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_SHARING_USERS1] FOREIGN KEY
	(
		[ProUserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[STUB_GROUP] ADD
	CONSTRAINT [FK_STUB_GROUP_GROUPS] FOREIGN KEY
	(
		[GroupId]
	) REFERENCES [dbo].[GROUPS] (
		[PrincipalId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_STUB_GROUP_STUBS] FOREIGN KEY
	(
		[StubId]
	) REFERENCES [dbo].[STUBS] (
		[StubId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[STUBS] ADD
	CONSTRAINT [FK_STUBS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[SUBSCRIPTION_DETAILS] ADD
	CONSTRAINT [FK_SUBSCRIPTION_DETAILS_OBJECT_ROLES] FOREIGN KEY
	(
		[ObjectRoleId]
	) REFERENCES [dbo].[OBJECT_ROLES] (
		[ObjectRoleId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_SUBSCRIPTION_DETAILS_SUBSCRIPTIONS] FOREIGN KEY
	(
		[SubscriptionId]
	) REFERENCES [dbo].[SUBSCRIPTIONS] (
		[SubscriptionId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SUBSCRIPTIONS] ADD
	CONSTRAINT [FK_SUBSCRIPTIONS_SYSTEM_EVENT_TYPES] FOREIGN KEY
	(
		[EventTypeId]
	) REFERENCES [dbo].[SYSTEM_EVENT_TYPES] (
		[EventTypeId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_SUBSCRIPTIONS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_RECIPIENTS] ADD
	CONSTRAINT [FK_SYSTEM_EVENT_RECIPIENTS_MESSAGE_LOG] FOREIGN KEY
	(
		[LogId]
	) REFERENCES [dbo].[MESSAGE_LOG] (
		[LogId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_SYSTEM_EVENT_RECIPIENTS_MESSAGE_TYPES] FOREIGN KEY
	(
		[MessageTypeId]
	) REFERENCES [dbo].[MESSAGE_TYPES] (
		[MessageTypeId]
	),
	CONSTRAINT [FK_SYSTEM_EVENT_RECIPIENTS_SYSTEM_EVENTS] FOREIGN KEY
	(
		[SystemEventId]
	) REFERENCES [dbo].[SYSTEM_EVENTS] (
		[SystemEventId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_SYSTEM_EVENT_RECIPIENTS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SYSTEM_EVENT_TYPES] ADD
	CONSTRAINT [FK_SYSTEM_EVENTS_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_SYSTEM_EVENTS_OBJECT_TYPES1] FOREIGN KEY
	(
		[RelObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[SYSTEM_EVENTS] ADD
	CONSTRAINT [FK_SYSTEM_EVENTS_LOG_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_SYSTEM_EVENTS_SYSTEM_EVENT_TYPES] FOREIGN KEY
	(
		[EventTypeId]
	) REFERENCES [dbo].[SYSTEM_EVENT_TYPES] (
		[EventTypeId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TASK_LINKS] ADD
	CONSTRAINT [FK_MSP_LINKS_MSP_TASKS] FOREIGN KEY
	(
		[PredId]
	) REFERENCES [dbo].[TASKS] (
		[TaskId]
	),
	CONSTRAINT [FK_MSP_LINKS_MSP_TASKS1] FOREIGN KEY
	(
		[SuccId]
	) REFERENCES [dbo].[TASKS] (
		[TaskId]
	)
GO
ALTER TABLE [dbo].[TIMESHEETS] ADD
	CONSTRAINT [FK_TIMESHEETS_ACTUAL_FINANCES] FOREIGN KEY
	(
		[ActualId]
	) REFERENCES [dbo].[ACTUAL_FINANCES] (
		[ActualId]
	),
	CONSTRAINT [FK_TIMESHEETS_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	),
	CONSTRAINT [FK_TIMESHEETS_WeekTimeSheet] FOREIGN KEY
	(
		[WeekTimesheetId]
	) REFERENCES [dbo].[WeekTimeSheet] (
		[WeekTimeSheetId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TIMEZONES_LANGUAGE] ADD
	CONSTRAINT [FK_TIMEZONES_LANGUAGE_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_TIMEZONES_LANGUAGE_TIMEZONES] FOREIGN KEY
	(
		[TimeZoneId]
	) REFERENCES [dbo].[TIMEZONES] (
		[TimeZoneId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TIMEZONES_LOCAL_UTC] ADD
	CONSTRAINT [FK_TIMEZONES_DAYLIGHT_TIMEZONES] FOREIGN KEY
	(
		[TimeZoneId]
	) REFERENCES [dbo].[TIMEZONES] (
		[TimeZoneId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[USER_DETAILS] ADD
	CONSTRAINT [FK_USER_DETAILS_fsc_Files] FOREIGN KEY
	(
		[PictureFileId]
	) REFERENCES [dbo].[fsc_Files] (
		[FileId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_USER_DETAILS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[USER_PREFERENCES] ADD
	CONSTRAINT [FK_USER_PREFERENCES_LANGUAGES] FOREIGN KEY
	(
		[LanguageId]
	) REFERENCES [dbo].[LANGUAGES] (
		[LanguageId]
	),
	CONSTRAINT [FK_USER_PREFERENCES_TIMEZONES] FOREIGN KEY
	(
		[TimeZoneId]
	) REFERENCES [dbo].[TIMEZONES] (
		[TimeZoneId]
	),
	CONSTRAINT [FK_USER_PREFERENCES_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[USER_PROJECT_TEAM] ADD
	CONSTRAINT [FK_USER_PROJECT_TEAM_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_USER_PROJECT_TEAM_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_USER_PROJECT_TEAM_USERS1] FOREIGN KEY
	(
		[MemberId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[USER_SETTINGS] ADD
	CONSTRAINT [FK_USER_SETTINGS_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[WeekTimeSheet] ADD
	CONSTRAINT [FK_WeekTimeSheet_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_WeekTimeSheet_TIMESHEET_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[TIMESHEET_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_WeekTimeSheet_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_WeekTimeSheet_USERS1] FOREIGN KEY
	(
		[LastEditorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CONTAINERSHIP] ADD
	CONSTRAINT [FK_CONTAINERSHIP_Principals] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_CONTAINERSHIP_Principals1] FOREIGN KEY
	(
		[ParentPrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[DOCUMENT_STATUS] ADD
	CONSTRAINT [FK_DOCUMENT_STATUS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	)
GO
ALTER TABLE [dbo].[fsc_AccessControlLists] ADD
	CONSTRAINT [FK_fsc_AccessControlLists_fsc_Folders] FOREIGN KEY
	(
		[DirectoryId]
	) REFERENCES [dbo].[fsc_Directories] (
		[DirectoryId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[GROUPS] ADD
	CONSTRAINT [FK_GROUPS_Principals] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[INCIDENT_STATUS] ADD
	CONSTRAINT [FK_INCIDENT_STATUS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	)
GO
ALTER TABLE [dbo].[OBJECT_FORMS] ADD
	CONSTRAINT [FK_MSP_OBJECT_FORMS_OBJECT_TYPES] FOREIGN KEY
	(
		[ObjectTypeId]
	) REFERENCES [dbo].[OBJECT_TYPES] (
		[ObjectTypeId]
	)
GO
ALTER TABLE [dbo].[USERS] ADD
	CONSTRAINT [FK_USERS_Principals] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[fsc_AccessControlEntries] ADD
	CONSTRAINT [FK_fsc_AccessControlEntries_fsc_AccessControlLists] FOREIGN KEY
	(
		[AclId]
	) REFERENCES [dbo].[fsc_AccessControlLists] (
		[AclId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[USER_GROUP] ADD
	CONSTRAINT [FK_USER_GROUP_GROUPS] FOREIGN KEY
	(
		[GroupId]
	) REFERENCES [dbo].[GROUPS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_USER_GROUP_USERS] FOREIGN KEY
	(
		[UserId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[CALENDARS] ADD
	CONSTRAINT [FK_CALENDARS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_CALENDARS_TIMEZONES] FOREIGN KEY
	(
		[TimeZoneId]
	) REFERENCES [dbo].[TIMEZONES] (
		[TimeZoneId]
	)
GO
ALTER TABLE [dbo].[DOCUMENT_RESOURCES] ADD
	CONSTRAINT [FK_DOCUMENT_RESOURCES_DOCUMENTS] FOREIGN KEY
	(
		[DocumentId]
	) REFERENCES [dbo].[DOCUMENTS] (
		[DocumentId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_DOCUMENT_RESOURCES_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[DOCUMENT_TODO] ADD
	CONSTRAINT [FK_DOCUMENT_TODO_DOCUMENTS] FOREIGN KEY
	(
		[DocumentId]
	) REFERENCES [dbo].[DOCUMENTS] (
		[DocumentId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_DOCUMENT_TODO_TODO] FOREIGN KEY
	(
		[ToDoId]
	) REFERENCES [dbo].[TODO] (
		[ToDoId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[DOCUMENTS] ADD
	CONSTRAINT [FK_DOCUMENTS_ACTIVATION_TYPES] FOREIGN KEY
	(
		[ActivationTypeId]
	) REFERENCES [dbo].[ACTIVATION_TYPES] (
		[ActivationTypeId]
	),
	CONSTRAINT [FK_DOCUMENTS_COMPLETION_REASONS] FOREIGN KEY
	(
		[ReasonId]
	) REFERENCES [dbo].[COMPLETION_REASONS] (
		[ReasonId]
	),
	CONSTRAINT [FK_DOCUMENTS_DOCUMENT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[DOCUMENT_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_DOCUMENTS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_DOCUMENTS_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_DOCUMENTS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_DOCUMENTS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_DOCUMENTS_USERS1] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[EVENT_RESOURCES] ADD
	CONSTRAINT [FK_MSP_EVENT_RESOURCES_MSP_EVENTS] FOREIGN KEY
	(
		[EventId]
	) REFERENCES [dbo].[EVENTS] (
		[EventId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_MSP_EVENT_RESOURCES_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[EVENTS] ADD
	CONSTRAINT [FK_EVENTS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_EVENTS_USERS1] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_EVENTS_USERS3] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_MSP_EVENTS_MSP_EVENT_TYPES] FOREIGN KEY
	(
		[TypeId]
	) REFERENCES [dbo].[EVENT_TYPES] (
		[TypeId]
	),
	CONSTRAINT [FK_MSP_EVENTS_MSP_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_MSP_EVENTS_MSP_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	)
GO
ALTER TABLE [dbo].[INCIDENT_RESOURCES] ADD
	CONSTRAINT [FK_INCIDENT_RESOURCES_INCIDENTS] FOREIGN KEY
	(
		[IncidentId]
	) REFERENCES [dbo].[INCIDENTS] (
		[IncidentId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_INCIDENT_RESOURCES_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[INCIDENT_TODO] ADD
	CONSTRAINT [FK_INCIDENT_TODO_INCIDENTS] FOREIGN KEY
	(
		[IncidentId]
	) REFERENCES [dbo].[INCIDENTS] (
		[IncidentId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_INCIDENT_TODO_TODO] FOREIGN KEY
	(
		[ToDoId]
	) REFERENCES [dbo].[TODO] (
		[ToDoId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[INCIDENTS] ADD
	CONSTRAINT [FK_INCIDENTS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_INCIDENTS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_INCIDENTS_USERS2] FOREIGN KEY
	(
		[ClosedBy]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_INCIDENTS_USERS4] FOREIGN KEY
	(
		[ActivatedBy]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_MSP_INCIDENT_SEVERITY] FOREIGN KEY
	(
		[SeverityId]
	) REFERENCES [dbo].[INCIDENT_SEVERITY] (
		[SeverityId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_MSP_INCIDENT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[INCIDENT_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_MSP_INCIDENT_TYPES] FOREIGN KEY
	(
		[TypeId]
	) REFERENCES [dbo].[INCIDENT_TYPES] (
		[TypeId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_MSP_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_MSP_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	),
	CONSTRAINT [FK_MSP_INCIDENTS_PRINCIPALS1] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[LIST_ACCESS] ADD
	CONSTRAINT [FK_LIST_FOLDER_ACCESS_LISTS] FOREIGN KEY
	(
		[ListId]
	) REFERENCES [dbo].[LISTS] (
		[ListId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[LIST_FOLDERS] ADD
	CONSTRAINT [FK_LIST_FOLDERS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	),
	CONSTRAINT [FK_LIST_FOLDERS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[LISTS] ADD
	CONSTRAINT [FK_LISTS_LIST_FOLDERS] FOREIGN KEY
	(
		[FolderId]
	) REFERENCES [dbo].[LIST_FOLDERS] (
		[ListFolderId]
	),
	CONSTRAINT [FK_LISTS_LIST_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[LIST_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_LISTS_LIST_TYPES] FOREIGN KEY
	(
		[TypeId]
	) REFERENCES [dbo].[LIST_TYPES] (
		[TypeId]
	),
	CONSTRAINT [FK_LISTS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[PROJECTS] ADD
	CONSTRAINT [FK_MSP_PROJECTS_MSP_CALENDARS] FOREIGN KEY
	(
		[CalendarId]
	) REFERENCES [dbo].[CALENDARS] (
		[CalendarId]
	),
	CONSTRAINT [FK_MSP_PROJECTS_MSP_OBJECT_FORMS] FOREIGN KEY
	(
		[FormId]
	) REFERENCES [dbo].[OBJECT_FORMS] (
		[FormId]
	),
	CONSTRAINT [FK_MSP_PROJECTS_MSP_PROJECT_STATUS] FOREIGN KEY
	(
		[StatusId]
	) REFERENCES [dbo].[PROJECT_STATUS] (
		[StatusId]
	),
	CONSTRAINT [FK_PROJECTS_CLIENTS] FOREIGN KEY
	(
		[ClientId]
	) REFERENCES [dbo].[CLIENTS] (
		[ClientId]
	),
	CONSTRAINT [FK_PROJECTS_CURRENCY] FOREIGN KEY
	(
		[CurrencyId]
	) REFERENCES [dbo].[CURRENCY] (
		[CurrencyId]
	),
	CONSTRAINT [FK_PROJECTS_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_PROJECTS_PROJECT_PHASES] FOREIGN KEY
	(
		[PhaseId]
	) REFERENCES [dbo].[PROJECT_PHASES] (
		[PhaseId]
	),
	CONSTRAINT [FK_PROJECTS_PROJECT_PHASES1] FOREIGN KEY
	(
		[InitialPhaseId]
	) REFERENCES [dbo].[PROJECT_PHASES] (
		[PhaseId]
	),
	CONSTRAINT [FK_PROJECTS_RISK_LEVELS] FOREIGN KEY
	(
		[RiskLevelId]
	) REFERENCES [dbo].[RISK_LEVELS] (
		[RiskLevelId]
	),
	CONSTRAINT [FK_PROJECTS_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_PROJECTS_USERS1] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_PROJECTS_USERS3] FOREIGN KEY
	(
		[ExecutiveManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[TASK_RESOURCES] ADD
	CONSTRAINT [FK_MSP_TASK_RESOURCES_MSP_TASKS] FOREIGN KEY
	(
		[TaskId]
	) REFERENCES [dbo].[TASKS] (
		[TaskId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_MSP_TASK_RESOURCES_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[TASK_TODO] ADD
	CONSTRAINT [FK_TASK_TODO_TASKS] FOREIGN KEY
	(
		[TaskId]
	) REFERENCES [dbo].[TASKS] (
		[TaskId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_TASK_TODO_TODO] FOREIGN KEY
	(
		[ToDoId]
	) REFERENCES [dbo].[TODO] (
		[ToDoId]
	) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TASKS] ADD
	CONSTRAINT [FK_TASKS_ACTIVATION_TYPES] FOREIGN KEY
	(
		[ActivationTypeId]
	) REFERENCES [dbo].[ACTIVATION_TYPES] (
		[ActivationTypeId]
	),
	CONSTRAINT [FK_TASKS_COMPLETION_REASONS] FOREIGN KEY
	(
		[ReasonId]
	) REFERENCES [dbo].[COMPLETION_REASONS] (
		[ReasonId]
	),
	CONSTRAINT [FK_TASKS_COMPLETION_TYPES] FOREIGN KEY
	(
		[CompletionTypeId]
	) REFERENCES [dbo].[COMPLETION_TYPES] (
		[CompletionTypeId]
	),
	CONSTRAINT [FK_TASKS_CONSTRAINT_TYPES] FOREIGN KEY
	(
		[ConstraintTypeId]
	) REFERENCES [dbo].[CONSTRAINT_TYPES] (
		[ConstraintTypeId]
	),
	CONSTRAINT [FK_TASKS_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_TASKS_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_TASKS_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_TASKS_USERS1] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_TASKS_USERS3] FOREIGN KEY
	(
		[CompletedBy]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[TODO] ADD
	CONSTRAINT [FK_MSP_TODO_MSP_COMPLETION_TYPES] FOREIGN KEY
	(
		[CompletionTypeId]
	) REFERENCES [dbo].[COMPLETION_TYPES] (
		[CompletionTypeId]
	),
	CONSTRAINT [FK_MSP_TODO_MSP_PRIORITIES] FOREIGN KEY
	(
		[PriorityId]
	) REFERENCES [dbo].[PRIORITIES] (
		[PriorityId]
	),
	CONSTRAINT [FK_MSP_TODO_MSP_PROJECTS] FOREIGN KEY
	(
		[ProjectId]
	) REFERENCES [dbo].[PROJECTS] (
		[ProjectId]
	),
	CONSTRAINT [FK_TODO_ACTIVATION_TYPES] FOREIGN KEY
	(
		[ActivationTypeId]
	) REFERENCES [dbo].[ACTIVATION_TYPES] (
		[ActivationTypeId]
	),
	CONSTRAINT [FK_TODO_COMPLETION_REASONS] FOREIGN KEY
	(
		[ReasonId]
	) REFERENCES [dbo].[COMPLETION_REASONS] (
		[ReasonId]
	),
	CONSTRAINT [FK_TODO_OBJECT_STATES] FOREIGN KEY
	(
		[StateId]
	) REFERENCES [dbo].[OBJECT_STATES] (
		[StateId]
	),
	CONSTRAINT [FK_TODO_USERS] FOREIGN KEY
	(
		[CreatorId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_TODO_USERS1] FOREIGN KEY
	(
		[ManagerId]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	),
	CONSTRAINT [FK_TODO_USERS4] FOREIGN KEY
	(
		[CompletedBy]
	) REFERENCES [dbo].[USERS] (
		[PrincipalId]
	)
GO
ALTER TABLE [dbo].[TODO_RESOURCES] ADD
	CONSTRAINT [FK_MSP_TODO_RESOURCES_MSP_TODO] FOREIGN KEY
	(
		[ToDoId]
	) REFERENCES [dbo].[TODO] (
		[ToDoId]
	) ON DELETE CASCADE ,
	CONSTRAINT [FK_MSP_TODO_RESOURCES_PRINCIPALS] FOREIGN KEY
	(
		[PrincipalId]
	) REFERENCES [dbo].[PRINCIPALS] (
		[PrincipalId]
	)
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.EVENT_SECURITY
AS
SELECT EventId, PrincipalId, MAX(IsResource) AS IsResource, MAX(IsManager) AS IsManager
FROM
	(
	SELECT EventId, PrincipalId, 1 AS IsResource, 0 AS IsManager
	  FROM EVENT_RESOURCES
	  WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
	UNION ALL
	SELECT EventId, ManagerId AS PrincipalId, 0 AS IsResource, 1 AS IsManager
	  FROM EVENTS E
	) A
GROUP BY EventId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.EVENT_SECURITY_ALL
AS
SELECT EventId, PrincipalId, MAX(IsResource) AS IsResource, MAX(IsManager) AS IsManager
  FROM (
	SELECT EventId, PrincipalId, IsResource, IsManager
	  FROM EVENT_SECURITY
	  WHERE PrincipalId NOT IN (SELECT PrincipalId FROM GROUPS)
	UNION ALL
	SELECT TS.EventId, UG.UserId AS PrincipalId, TS.IsResource, TS.IsManager
	  FROM EVENT_SECURITY TS
		JOIN USER_GROUP UG ON (TS .PrincipalId = UG.GroupId)
	) S
  GROUP BY EventId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.TODO_SECURITY
AS
SELECT ToDoId, PrincipalId, MAX(IsResource) AS IsResource, MAX(IsManager) AS IsManager
FROM
	(
	SELECT ToDoId, PrincipalId, 1 AS IsResource, 0 AS IsManager
	  FROM TODO_RESOURCES
	  WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
	UNION ALL
	SELECT ToDoId, ManagerId AS PrincipalId, 0 AS IsResource, 1 AS IsManager
	  FROM TODO
	) A
GROUP BY ToDoId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.TODO_SECURITY_ALL
AS
SELECT ToDoId, PrincipalId, MAX(IsResource) AS IsResource, MAX(IsManager) AS IsManager
  FROM
	(SELECT ToDoId, PrincipalId, IsResource, IsManager
	  FROM TODO_SECURITY
	  WHERE PrincipalId NOT IN
		(SELECT PrincipalId FROM GROUPS)
	UNION ALL
	SELECT TS.ToDoId, UG.UserId AS PrincipalId, TS.IsResource, TS.IsManager
	  FROM TODO_SECURITY TS
		JOIN USER_GROUP UG ON (TS .PrincipalId = UG.GroupId)
	) S
  GROUP BY ToDoId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.INCIDENT_SECURITY
AS
SELECT IncidentId, PrincipalId, MAX(IsManager) AS IsManager, MAX(IsCreator) AS IsCreator, MAX(IsResource) AS IsResource,
	MAX(IsRealIncidentManager) AS IsRealIncidentManager, MAX(IsRealIncidentResource) AS IsRealIncidentResource
FROM
	(SELECT IncidentId, ManagerId AS PrincipalId, 1 AS IsManager, 0 AS IsCreator, 0 AS IsResource, 1 AS IsRealIncidentManager, 0 AS IsRealIncidentResource
	  FROM INCIDENTS
	UNION ALL
	SELECT IncidentId, PrincipalId,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsManager,
		0 AS IsCreator, 1 AS IsResource,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsRealIncidentManager,
		1 AS IsRealIncidentResource
	  FROM INCIDENT_RESOURCES
	  WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
	UNION ALL
	SELECT IncidentId, CreatorId AS PrincipalId, 0 AS IsManager, 1 AS IsCreator, 0 AS IsResource, 0 AS IsRealIncidentManager, 0 AS IsRealIncidentResource
	  FROM INCIDENTS
	UNION ALL
	SELECT IT.IncidentId, T.PrincipalId, T.IsManager, 0 AS IsCreator, T.IsResource, 0 AS IsRealIncidentManager, 0 AS IsRealIncidentResource
	  FROM TODO_SECURITY T
		JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
	) A
GROUP BY IncidentId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.INCIDENT_SECURITY_ALL
AS
SELECT IncidentId, PrincipalId, MAX(IsManager) AS IsManager, MAX(IsCreator) AS IsCreator, MAX(IsResource) AS IsResource,
	MAX(IsRealIncidentManager) AS IsRealIncidentManager, MAX(IsRealIncidentResource) AS IsRealIncidentResource
  FROM (
	SELECT IncidentId, PrincipalId, IsManager, IsCreator, IsResource, IsRealIncidentManager, IsRealIncidentResource
	  FROM INCIDENT_SECURITY
	  WHERE PrincipalId NOT IN (SELECT PrincipalId FROM GROUPS)
	UNION ALL
	SELECT TS.IncidentId, UG.UserId AS PrincipalId, TS.IsManager , TS.IsCreator, TS.IsResource, IsRealIncidentManager, IsRealIncidentResource
	  FROM INCIDENT_SECURITY TS
		JOIN USER_GROUP UG ON (TS .PrincipalId = UG.GroupId)
	) S
  GROUP BY IncidentId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.PROJECT_SECURITY
AS
SELECT ProjectId, PrincipalId, MAX(IsTeamMember) AS IsTeamMember, MAX(IsSponsor) AS IsSponsor, MAX(IsStakeHolder) AS IsStakeHolder,
                      MAX(IsManager) AS IsManager, MAX(IsExecutiveManager)  AS IsExecutiveManager
FROM
	(
	SELECT ProjectId, PrincipalId, IsTeamMember, IsSponsor, IsStakeHolder, 0 AS IsManager, 0  AS IsExecutiveManager
	FROM PROJECT_MEMBERS
	UNION ALL
	SELECT P.ProjectId, U.PrincipalId, 0 AS IsTeamMember, 0 AS IsSponsor, 0 AS IsStakeHolder,
		CASE WHEN P.ManagerId = U.PrincipalId Then 1 ELSE 0 END AS IsManager,
		CASE WHEN P.ExecutiveManagerId = U.PrincipalId Then 1 ELSE 0 END AS IsExecutiveManager
	 FROM PROJECTS P, USERS U
	 WHERE (P.ManagerId = U.PrincipalId OR P.ExecutiveManagerId = U.PrincipalId)
	) A
GROUP BY ProjectId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.PROJECT_SECURITY_ALL
AS
SELECT ProjectId, PrincipalId,
	MAX(IsTeamMember) AS IsTeamMember, MAX(IsSponsor) AS IsSponsor,
	MAX(IsStakeHolder) AS IsStakeHolder, MAX(IsManager) AS IsManager,
	MAX(IsExecutiveManager) AS IsExecutiveManager
  FROM
	(SELECT ProjectId, PrincipalId, IsTeamMember, IsSponsor, IsStakeHolder, IsManager, IsExecutiveManager
	  FROM PROJECT_SECURITY
	  WHERE PrincipalId NOT IN (SELECT PrincipalId FROM GROUPS)
	UNION ALL
	SELECT PS.ProjectId, UG.UserId AS PrincipalId, PS.IsTeamMember, PS.IsSponsor, PS.IsStakeHolder, PS.IsManager, PS.IsExecutiveManager
	  FROM PROJECT_SECURITY PS
		JOIN USER_GROUP UG ON (PS.PrincipalId = UG.GroupId)
	) S
GROUP BY ProjectId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.LIST_SECURITY_ALL
AS
SELECT ListId, PrincipalId, MAX(AllowLevel) AS AllowLevel
  FROM
	(
	SELECT ListId, PrincipalId, AllowLevel
	  FROM LIST_ACCESS
	  WHERE PrincipalId IN (SELECT PrincipalId FROM USERS)
	UNION ALL
	SELECT LA.ListId, UG.UserId AS PrincipalId, LA.AllowLevel
	  FROM LIST_ACCESS LA
		JOIN USER_GROUP UG ON (LA.PrincipalId = UG.GroupId)
	UNION ALL
	SELECT LA.ListId, PSA.PrincipalId, LA.AllowLevel
	  FROM LIST_ACCESS LA
		JOIN LISTS L ON (LA.ListId = L.ListId)
		JOIN LIST_FOLDERS LF ON (L.FolderId = LF.ListFolderId)
		JOIN PROJECT_SECURITY_ALL PSA ON (LF.ProjectId = PSA.ProjectId)
	  WHERE (LA.PrincipalId = - 1 AND PSA.IsManager = 1) OR
		(LA.PrincipalId = - 2 AND PSA.IsTeamMember = 1) OR
		(LA.PrincipalId = - 3 AND PSA.IsSponsor = 1) OR
		(LA.PrincipalId = - 4 AND PSA.IsStakeHolder = 1) OR
		(LA.PrincipalId = - 2 AND PSA.IsExecutiveManager = 1)
	UNION ALL
	SELECT ListId, CreatorId AS PrincipalId, 3 AS AllowLevel
	  FROM LISTS L
	UNION ALL
	SELECT ListId, UG.UserId AS PrincipalId, 3 AS AllowLevel
	  FROM LISTS L, USER_GROUP UG
	  WHERE UG.GroupId = 2 AND L.FolderId IN (SELECT ListFolderId FROM LIST_FOLDERS WHERE IsPrivate = 0 AND ProjectId IS NULL)
	UNION ALL
	SELECT ListId, UG.UserId AS PrincipalId, 3 AS AllowLevel
	  FROM LISTS L, USER_GROUP UG
	  WHERE UG.GroupId = 4 AND L.FolderId IN (SELECT ListFolderId FROM LIST_FOLDERS WHERE IsPrivate = 0 AND ProjectId IS NOT NULL)
	UNION ALL
	SELECT L.ListId, P.ManagerId AS PrincipalId, 3 AS AllowLevel
	  FROM LISTS L
		JOIN LIST_FOLDERS LF ON (L.FolderId = LF.ListFolderId)
		JOIN PROJECTS P ON (LF.ProjectId = P.ProjectId)
	  WHERE LF.IsPrivate = 0
	) A
  GROUP BY ListId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.TASK_SECURITY
AS
SELECT TaskId, PrincipalId, MAX(IsResource) AS IsResource, MAX(IsManager) AS IsManager,
	MAX(IsRealTaskResource) AS IsRealTaskResource, MAX(IsRealTaskManager) AS IsRealTaskManager
FROM
	(
	SELECT TaskId, PrincipalId, 1 AS IsResource,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsManager,
		1 AS IsRealTaskResource,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsRealTaskManager
	  FROM TASK_RESOURCES
	  WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
	UNION
	SELECT T.TaskId, P.ManagerId AS PrincipalId, 0 AS IsResource, 1 AS IsManager, 0 AS IsRealTaskResource, 1 AS IsRealTaskManager
	  FROM TASKS T, PROJECTS P
	  WHERE T.ProjectId = P.ProjectId
	UNION
	SELECT TT.TaskId, T.PrincipalId, T.IsResource, T.IsManager, 0 AS IsRealTaskResource, 0 AS IsRealTaskManager
	  FROM TODO_SECURITY_ALL T
		JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
	) A
GROUP BY TaskId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.DOCUMENT_SECURITY
AS
SELECT DocumentId, PrincipalId, MAX(IsManager) AS IsManager, MAX(IsResource) AS IsResource,
	MAX(IsRealDocumentManager) AS IsRealDocumentManager, MAX(IsRealDocumentResource) AS IsRealDocumentResource
FROM
	(SELECT DocumentId, ManagerId AS PrincipalId, 1 AS IsManager, 0 AS IsResource, 1 AS IsRealDocumentManager, 0 AS IsRealDocumentResource
	  FROM DOCUMENTS
	UNION ALL
	SELECT DocumentId, PrincipalId,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsManager,
		1 AS IsResource,
		CASE WHEN CanManage = 1 THEN 1 ELSE 0 END AS IsRealDocumentManager,
		1 AS IsRealDocumentResource
	  FROM DOCUMENT_RESOURCES
	  WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
	UNION ALL
	SELECT DocumentId, 0 AS IsManager, 1 AS IsCreator, 0 AS IsResource, 0 AS IsRealDocumentManager, 0 AS IsRealDocumentResource
	  FROM DOCUMENTS
	UNION ALL
	SELECT DT.DocumentId, T.PrincipalId, T.IsManager, T.IsResource, 0 AS IsRealDocumentManager, 0 AS IsRealDocumentResource
	  FROM TODO_SECURITY T
		JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	) A
GROUP BY DocumentId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.DOCUMENT_SECURITY_ALL
AS
SELECT DocumentId, PrincipalId, MAX(IsManager) AS IsManager, MAX(IsResource) AS IsResource,
	MAX(IsRealDocumentManager) AS IsRealDocumentManager, MAX(IsRealDocumentResource) AS IsRealDocumentResource
  FROM (
	SELECT DocumentId, PrincipalId, IsManager, IsResource, IsRealDocumentManager, IsRealDocumentResource
	  FROM DOCUMENT_SECURITY
	  WHERE PrincipalId NOT IN (SELECT PrincipalId FROM GROUPS)
	UNION ALL
	SELECT TS.DocumentId, UG.UserId AS PrincipalId, TS.IsManager , TS.IsResource, IsRealDocumentManager, IsRealDocumentResource
	  FROM DOCUMENT_SECURITY TS
		JOIN USER_GROUP UG ON (TS .PrincipalId = UG.GroupId)
	) S
  GROUP BY DocumentId, PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE VIEW dbo.fsc_FolderSecurityAll
AS
SELECT DirectoryId, ContainerKey, PrincipalId, [Action], MIN(Allow) AS Allow
FROM
(
	SELECT DD.DirectoryId, DD.ContainerKey, UU.PrincipalId, ACE.[Action], ACE.Allow
	  FROM fsc_Directories DD
		JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
		JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
		JOIN USERS UU ON (ACE.PrincipalId = UU.PrincipalId)
	  WHERE ACE.PrincipalId IS NOT NULL
	UNION ALL
	SELECT DD.DirectoryId, DD.ContainerKey, UU.PrincipalId, ACE.[Action], ACE.Allow
	  FROM fsc_Directories DD
		JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
		JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
		JOIN USER_GROUP UG ON (ACE.PrincipalId = UG.GroupId)
		JOIN USERS UU ON (UG.UserId = UU.PrincipalId)
	  WHERE ACE.PrincipalId IS NOT NULL
	UNION ALL
	SELECT DD.DirectoryId, DD.ContainerKey, UR.PrincipalId, ACE.[Action], ACE.Allow
		  FROM fsc_Directories DD
			JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
			JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
			JOIN fsc_UserRoles UR ON (ACE.Role = UR.Role AND (UR.ContainerKey IS NULL OR UR.ContainerKey = DD.ContainerKey))
			JOIN USERS U ON (UR.PrincipalId = U.PrincipalId)
		  WHERE ACE.Role IS NOT NULL
	UNION ALL
	SELECT DD.DirectoryId, DD.ContainerKey, C.PrincipalId, ACE.[Action], ACE.Allow
		  FROM fsc_Directories DD
			JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
			JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
			JOIN fsc_UserRoles UR ON (ACE.Role = UR.Role AND (UR.ContainerKey IS NULL OR UR.ContainerKey = DD.ContainerKey))
			JOIN GROUPS G ON (UR.PrincipalId = G.PrincipalId)
			JOIN CONTAINERSHIP C ON (G.PrincipalId = C.ParentPrincipalId)
		  WHERE ACE.Role IS NOT NULL
	UNION ALL
	SELECT DD.DirectoryId, DD.ContainerKey, UR.PrincipalId, ACE.[Action], ACE.Allow
	  FROM fsc_Directories DD
		JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
		JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
		JOIN fsc_UserRoles UR ON (ACE.Role = UR.Role)
		JOIN fsc_ForeignContainerKeys FCK ON (UR.ContainerKey = FCK.ForeignContainerKey AND FCK.ContainerKey = DD.ContainerKey)
		JOIN USERS U ON (UR.PrincipalId = U.PrincipalId)
	  WHERE ACE.Role IS NOT NULL
	UNION ALL
	SELECT DD.DirectoryId, DD.ContainerKey, C.PrincipalId, ACE.[Action], ACE.Allow
	  FROM fsc_Directories DD
		JOIN fsc_AccessControlLists ACL ON (DD.DirectoryId = ACL.DirectoryId)
		JOIN fsc_AccessControlEntries ACE ON (ACL.AclId = ACE.AclId)
		JOIN fsc_UserRoles UR ON (ACE.Role = UR.Role)
		JOIN fsc_ForeignContainerKeys FCK ON (UR.ContainerKey = FCK.ForeignContainerKey AND FCK.ContainerKey = DD.ContainerKey)
		JOIN GROUPS G ON (UR.PrincipalId = G.PrincipalId)
		JOIN CONTAINERSHIP C ON (G.PrincipalId = C.ParentPrincipalId)
	  WHERE ACE.Role IS NOT NULL
) A
GROUP BY DirectoryId, ContainerKey, PrincipalId, [Action]
HAVING MIN(Allow) = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountAddChild
	@ParentId int,
	@Title nvarchar(255),
	@LastEditorId int,
	@retval int output
as
DECLARE @ProjectId int, @OutlineLevel int, @OutlineNumber varchar(255), @NewOutlineNumber varchar(255), @IsSummary bit
SELECT @ProjectId = ProjectId, @OutlineLevel  = OutlineLevel, @OutlineNumber  = OutlineNumber, @IsSummary = IsSummary
  FROM ACCOUNTS
  WHERE AccountId = @ParentId
IF @IsSummary = 0
BEGIN
	UPDATE ACCOUNTS SET IsSummary = 1 WHERE AccountId = @ParentId
	SET @NewOutlineNumber = @OutlineNumber + '.1'
END
ELSE
BEGIN
	DECLARE @ChildrenCount int
	SELECT @ChildrenCount = COUNT(*)
	  FROM ACCOUNTS
	  WHERE @ProjectId = ProjectId AND OutlineLevel = @OutlineLevel + 1 AND OutlineNumber LIKE @OutlineNumber + '.%'
	SET @NewOutlineNumber = @OutlineNumber + '.' + CAST(@ChildrenCount+1 as varchar(10))
END
INSERT INTO ACCOUNTS (ProjectId, Title, OutlineLevel, OutlineNumber, IsSummary, LastEditorId, LastSavedDate)
  VALUES (@ProjectId, @Title, @OutlineLevel + 1 , @NewOutlineNumber, 0, @LastEditorId, getutcdate())
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountCreateRoot
	@ProjectId int,
	@Title nvarchar(255),
	@LastEditorId int,
	@retval int output
as
INSERT INTO ACCOUNTS (ProjectId, Title, OutlineLevel, OutlineNumber, IsSummary, LastEditorId, LastSavedDate)
  VALUES (@ProjectId, @Title, 1, '1', 0, @LastEditorId, getutcdate())
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountDelete
	@AccountId int
as
DECLARE @ProjectId int, @OutlineNumber varchar(255), @OutlineLevel int
SELECT @ProjectId = ProjectId , @OutlineNumber = OutlineNumber, @OutlineLevel = OutlineLevel
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
DECLARE @Table TABLE (AccountId int)
INSERT INTO @Table (AccountId)
	SELECT AccountId FROM ACCOUNTS
	  WHERE AccountId = @AccountId
		OR
		(ProjectId = @ProjectId AND OutlineLevel > @OutlineLevel AND OutlineNumber LIKE @OutlineNumber + '.%')
DELETE FROM WeekTimeSheet WHERE WeekTimeSheetId IN
	(SELECT WeekTimeSheetId FROM TIMESHEETS WHERE ActualId IN
		(SELECT ActualId FROM ACTUAL_FINANCES WHERE AccountId IN
			(SELECT AccountId FROM @Table)
		)
	)
DELETE FROM TIMESHEETS WHERE ActualId IN
	(SELECT ActualId FROM ACTUAL_FINANCES WHERE AccountId IN
		(SELECT AccountId FROM @Table)
	)
DELETE FROM COLLAPSED_ACCOUNTS WHERE AccountId IN
	(SELECT AccountId FROM @Table)
DELETE FROM ACTUAL_FINANCES WHERE AccountId IN
	(SELECT AccountId FROM @Table)
DELETE FROM ACCOUNTS  WHERE AccountId IN
	(SELECT AccountId FROM @Table)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGet
	@AccountId int
as
SELECT AccountId, ProjectId, Title, OutlineLevel, OutlineNumber, IsSummary,
	TCur + TSub AS TTotal, TCur, TSub,
	ECur + ESub AS ETotal, ECur, ESub,
	ACur + ASub AS ATotal, ACur, ASub
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetList
	@ProjectId int
as
SELECT AccountId, ProjectId, Title, OutlineLevel, OutlineNumber, IsSummary
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId
  ORDER BY OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetListChildren
	@AccountId int
as
DECLARE @OutlineLevel int, @OutlineNumber varchar(255), @ProjectId int
SELECT @OutlineLevel = OutlineLevel, @OutlineNumber = OutlineNumber, @ProjectId = ProjectId
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT AccountId, Title, OutlineNumber
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel + 1 AND OutlineNumber LIKE @OutlineNumber + '.%'
  ORDER BY OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetListForMove
	@AccountId int
as
DECLARE @ProjectId int, @OutlineNumber varchar(255)
SELECT @ProjectId = ProjectId , @OutlineNumber = OutlineNumber
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT AccountId, Title, OutlineLevel, OutlineNumber, IsSummary
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId
	AND OutlineNumber != @OutlineNumber
	AND OutlineNumber NOT LIKE @OutlineNumber + '.%'
  ORDER BY OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetListParents
	@AccountId int
as
DECLARE @OutlineLevel int, @OutlineNumber varchar(255), @ProjectId int
SELECT @OutlineLevel = OutlineLevel, @OutlineNumber = OutlineNumber, @ProjectId = ProjectId
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT AccountId, ProjectId, Title, OutlineLevel, OutlineNumber, IsSummary, TCur, TSub, ECur, ESub, ACur, ASub
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel < @OutlineLevel  AND @OutlineNumber LIKE OutlineNumber + '.%'
  ORDER BY OutlineNumber DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetListTopLevel
	@ProjectId int
as
SELECT AccountId, OutlineLevel, Title, TCur + TSub AS Target, ECur + ESub AS Estimated, ACur + ASub AS Actual
  FROM Accounts
  WHERE ProjectId = @ProjectId
	AND OutlineLevel = 2
UNION ALL
SELECT AccountId, OutlineLevel, Title, TCur AS Target, ECur AS Estimated, ACur AS Actual
  FROM Accounts
  WHERE ProjectId = @ProjectId
	AND OutlineLevel = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountGetParentId
	@AccountId int,
	@retval int output
as
DECLARE @OutlineLevel int, @OutlineNumber varchar(255), @ProjectId int
SELECT @OutlineLevel = OutlineLevel, @OutlineNumber = OutlineNumber, @ProjectId = ProjectId
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT @retval = AccountId
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel - 1  AND @OutlineNumber LIKE OutlineNumber + '.%'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountMove
	@AccountId int,
	@ParentId int
as
DECLARE @ProjectId int, @OutlineLevel int, @OutlineNumber varchar(255), @NewOutlineNumber varchar(255), @IsSummary bit
SELECT @ProjectId = ProjectId, @OutlineLevel  = OutlineLevel, @OutlineNumber  = OutlineNumber, @IsSummary = IsSummary
  FROM ACCOUNTS
  WHERE AccountId = @ParentId
IF @IsSummary = 0
BEGIN
	UPDATE ACCOUNTS SET IsSummary = 1 WHERE AccountId = @ParentId
	SET @NewOutlineNumber = @OutlineNumber + '.1'
END
ELSE
BEGIN
	DECLARE @ChildrenCount int
	SELECT @ChildrenCount = COUNT(*)
	  FROM ACCOUNTS
	  WHERE @ProjectId = ProjectId AND OutlineLevel = @OutlineLevel + 1 AND OutlineNumber LIKE @OutlineNumber + '.%'
	SET @NewOutlineNumber = @OutlineNumber + '.' + CAST(@ChildrenCount+1 as varchar(10))
END
UPDATE ACCOUNTS
  SET OutlineLevel = @OutlineLevel + 1, OutlineNumber = @NewOutlineNumber
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountRecalculateACur
	@AccountId int,
	@LastEditorId int
as
DECLARE @Total money
SELECT @Total = SUM(AValue) FROM ACTUAL_FINANCES WHERE AccountId = @AccountId
IF @Total IS NOT NULL
	UPDATE ACCOUNTS
	  SET ACur = @Total, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
	  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountRecalculateSub
	@AccountId int,
	@LastEditorId int
as
DECLARE @TSub money, @ESub money, @ASub money, @OutlineLevel int, @OutlineNumber varchar(255), @ProjectId int
SELECT @OutlineLevel = OutlineLevel, @OutlineNumber = OutlineNumber, @ProjectId = ProjectId
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT @TSub = SUM(TCur + TSub), @ESub = SUM(ECur + ESub), @ASub = SUM(ACur + ASub)
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel + 1 AND OutlineNumber LIKE @OutlineNumber + '.%'
IF @TSub IS NULL
BEGIN
	SET @TSub = 0
	SET @ESub = 0
	SET @ASub = 0
END
UPDATE ACCOUNTS
  SET TSub = @TSub, ESub = @ESub, ASub = @ASub, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountRecalculateSubWithPreserving
	@AccountId int,
	@LastEditorId int
as
DECLARE @TSub money, @ESub money, @ASub money, @OutlineLevel int, @OutlineNumber varchar(255), @ProjectId int
SELECT @OutlineLevel = OutlineLevel, @OutlineNumber = OutlineNumber, @ProjectId = ProjectId
  FROM ACCOUNTS
  WHERE AccountId = @AccountId
SELECT @TSub = SUM(TCur + TSub), @ESub = SUM(ECur + ESub), @ASub = SUM(ACur + ASub)
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel + 1 AND OutlineNumber LIKE @OutlineNumber + '.%'
IF @TSub IS NOT NULL
	UPDATE ACCOUNTS
	  SET 	TSub = @TSub, TCur = TCur + TSub - @TSub,
		ESub = @ESub, ECur = ECur + ESub - @ESub,
		ASub = @ASub,  ACur = ACur + ASub - @ASub,
		LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
	  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountRename
	@AccountId int,
	@Title nvarchar(255),
	@LastEditorId int
as
UPDATE ACCOUNTS
  SET Title = @Title, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountsGetByProjectCollapsed
	@ProjectId as int,
	@UserId as int
as
SELECT A.AccountId, A.ProjectId, A.Title, A.OutlineLevel, A.OutlineNumber, A.IsSummary,
	A.TCur + A.TSub AS TTotal, A.TCur, A.TSub,
	A.ECur + A.ESub AS ETotal, A.ECur, A.ESub,
	A.ACur + A.ASub AS ATotal, A.ACur, A.ASub,
	CAST(0 as money) AS TParent, CAST(0 as money) AS EParent,
	CASE WHEN C.CollapsedId IS NOT NULL AND A.IsSummary = 1 THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS IsCollapsed
  FROM ACCOUNTS A
	LEFT JOIN COLLAPSED_ACCOUNTS C ON (A.AccountId = C.AccountId AND C.UserId = @UserId)
  WHERE A.ProjectId = @ProjectId
  ORDER BY A.OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountUpdateECur
	@AccountId int,
	@Value money,
	@LastEditorId int
as
UPDATE ACCOUNTS
  SET ECur = @Value, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountUpdateIsSummary
	@AccountId int,
	@IsSummary bit
as
UPDATE ACCOUNTS
  SET IsSummary = @IsSummary
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountUpdateOutlineLevelAndNumber
	@AccountId int,
	@OutlineLevel int,
	@OutlineNumber varchar(255)
as
UPDATE ACCOUNTS
  SET OutlineLevel = @OutlineLevel, OutlineNumber = @OutlineNumber
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].AccountUpdateTCur
	@AccountId int,
	@Value money,
	@LastEditorId int
as
UPDATE ACCOUNTS
  SET TCur = @Value, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentResourceAdd
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit
AS
INSERT INTO DOCUMENT_RESOURCES (DocumentId, PrincipalId, MustBeConfirmed, CanManage)
  VALUES(@ObjectId, @PrincipalId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentResourceReply
	@ObjectId int,
	@UserId int,
	@IsConfirmed bit,
	@retval int output
AS
UPDATE DOCUMENT_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = getutcdate()
  WHERE DocumentId = @ObjectId AND PrincipalId = @UserId AND MustBeConfirmed = 1 AND ResponsePending = 1
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentResourceUpdate
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit,
	@retval int output
AS
UPDATE DOCUMENT_RESOURCES
 SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
 WHERE DocumentId = @ObjectId AND PrincipalId = @PrincipalId AND (MustBeConfirmed != @MustBeConfirmed OR CanManage != @CanManage)
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentUpdateGeneralInfo
	@DocumentId int,
	@Title nvarchar(255),
	@Description ntext
AS
UPDATE DOCUMENTS
 SET Title = @Title, [Description] = @Description
 WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentUpdatePriority
	@DocumentId int,
	@ValueId int,
	@retval int output
AS
UPDATE DOCUMENTS
 SET PriorityId = @ValueId
 WHERE DocumentId = @DocumentId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentUpdateState
	@DocumentId int,
	@StateId int
AS
UPDATE DOCUMENTS
 SET StateId = @StateId
 WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentUpdateStatus
	@DocumentId int,
	@ValueId int,
	@retval int output
AS
UPDATE DOCUMENTS
 SET StatusId = @ValueId
 WHERE DocumentId = @DocumentId AND StatusId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_DocumentUpdateTimeline
	@DocumentId int,
	@TaskTime int,
	@retval int output
AS
UPDATE DOCUMENTS SET TaskTime = @TaskTime
  WHERE DocumentId = @DocumentId AND TaskTime != @TaskTime
SET @retval = @@rowcount
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventResourceAdd
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit
AS
INSERT INTO EVENT_RESOURCES (EventId, PrincipalId, MustBeConfirmed)
  VALUES(@ObjectId, @PrincipalId, @MustBeConfirmed)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventResourceReply
	@ObjectId int,
	@UserId int,
	@IsConfirmed bit,
	@retval int output
AS
UPDATE EVENT_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = getutcdate()
  WHERE EventId = @ObjectId AND PrincipalId = @UserId AND MustBeConfirmed = 1 AND ResponsePending = 1
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventResourceUpdate
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@retval int output
AS
UPDATE EVENT_RESOURCES
 SET MustBeConfirmed = @MustBeConfirmed
 WHERE EventId = @ObjectId AND PrincipalId = @PrincipalId AND MustBeConfirmed != @MustBeConfirmed
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventUpdateGeneralInfo
	@EventId int,
	@TypeId int,
	@Title nvarchar(255),
	@Description ntext,
	@Location nvarchar(1000)
AS
UPDATE EVENTS
 SET TypeId = @TypeId, Title = @Title, [Description] = @Description, Location = @Location
 WHERE EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventUpdatePriority
	@EventId int,
	@ValueId int,
	@retval int output
AS
UPDATE EVENTS
 SET PriorityId = @ValueId
 WHERE EventId = @EventId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventUpdateProjectAndManager
	@EventId int,
	@ProjectId int,
	@ManagerId int
AS
IF @ProjectId <= 0
	SET @ProjectId = NULL
UPDATE EVENTS
 SET ManagerId = @ManagerId, ProjectId = @ProjectId
 WHERE EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_EventUpdateTimeline
	@EventId int,
	@StartDate datetime,
	@FinishDate datetime = null,
	@TaskTime int,
	@retval int output
AS
DECLARE @OldStartDate DateTime, @OldFinishDate DateTime, @OldTaskTime int
SELECT @OldStartDate = StartDate, @OldFinishDate = FinishDate, @OldTaskTime = TaskTime
  FROM EVENTS
  WHERE EventId = @EventId
IF @StartDate != @OldStartDate AND @FinishDate != @OldFinishDate
BEGIN
	UPDATE EVENTS SET StartDate = @StartDate, FinishDate = @FinishDate, TaskTime = @TaskTime WHERE EventId = @EventId
	SET @retval = 3
END
ELSE IF @StartDate != @OldStartDate
BEGIN
	UPDATE EVENTS SET StartDate = @StartDate, TaskTime = @TaskTime WHERE EventId = @EventId
	SET @retval = 1
END
ELSE IF @FinishDate != @OldFinishDate
BEGIN
	UPDATE EVENTS SET FinishDate = @FinishDate, TaskTime = @TaskTime WHERE EventId = @EventId
	SET @retval = 2
END
ELSE IF @TaskTime != @OldTaskTime
BEGIN
	UPDATE EVENTS SET TaskTime = @TaskTime WHERE EventId = @EventId
	SET @retval = 4
END
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueResourceAdd
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit
AS
INSERT INTO INCIDENT_RESOURCES (IncidentId, PrincipalId, MustBeConfirmed, CanManage)
  VALUES(@ObjectId, @PrincipalId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueResourceReply
	@ObjectId int,
	@UserId int,
	@IsConfirmed bit,
	@retval int output
AS
UPDATE INCIDENT_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = getutcdate()
  WHERE IncidentId = @ObjectId AND PrincipalId = @UserId AND MustBeConfirmed = 1 AND ResponsePending = 1
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueResourceUpdate
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit,
	@retval int output
AS
UPDATE INCIDENT_RESOURCES
 SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
 WHERE IncidentId = @ObjectId AND PrincipalId = @PrincipalId AND (MustBeConfirmed != @MustBeConfirmed OR CanManage != @CanManage)
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdateGeneralInfo
	@IssueId int,
	@Title nvarchar(255),
	@Description ntext,
	@TypeId int,
	@SeverityId int
AS
UPDATE INCIDENTS
 SET Title = @Title, [Description] = @Description, TypeId = @TypeId, SeverityId = @SeverityId
 WHERE IncidentId = @IssueId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdateMailSenderEmail
	@IssueId int,
	@Email nvarchar(250)
AS
UPDATE INCIDENTS SET MailSenderEmail = @Email WHERE IncidentId  = @IssueId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdatePriority
	@IssueId int,
	@ValueId int,
	@retval int output
AS
UPDATE INCIDENTS
 SET PriorityId = @ValueId
 WHERE IncidentId = @IssueId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdateResolutionInfo
	@IssueId int,
	@Resolution ntext,
	@Workaround ntext
AS
UPDATE INCIDENTS
 SET Resolution = @Resolution, Workaround = @Workaround
 WHERE IncidentId = @IssueId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdateStatus
	@IssueId int,
	@ValueId int,
	@ClosedDate as DateTime,
	@retval int output
AS
DECLARE @CDate as datetime
IF (@ValueId=3 OR @ValueId=4 OR @ValueId=5)
	SET @CDate = @ClosedDate
DECLARE @StateId int
SELECT @StateId = StateId FROM INCIDENT_STATUS WHERE StatusId = @ValueId
UPDATE INCIDENTS
 SET StatusId = @ValueId, CloseDate=@CDate, StateId = @StateId
 WHERE IncidentId = @IssueId AND StatusId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_IssueUpdateTimeline
	@IssueId int,
	@TaskTime int,
	@retval int output
AS
UPDATE INCIDENTS
 SET TaskTime = @TaskTime
 WHERE IncidentId = @IssueId AND TaskTime != @TaskTime
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ListUpdateGeneralInfo
	@ObjectId int,
	@TypeId int,
	@Title nvarchar(255),
	@Description ntext
AS
UPDATE LISTS
 SET TypeId = @TypeId, Title = @Title, [Description] = @Description
 WHERE ListId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ListUpdateStatus
	@ObjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE LISTS
 SET StatusId = @ValueId
 WHERE ListId = @ObjectId AND StatusId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectMemberAddTeamMember
	@ProjectId int,
	@PrincipalId int,
	@Code nchar(2),
	@Rate money
AS
INSERT INTO PROJECT_MEMBERS (ProjectId, PrincipalId, Code, Rate, IsTeamMember)
  VALUES(@ProjectId, @PrincipalId, @Code, @Rate, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectMemberUpdateTeamMember
	@ProjectId int,
	@PrincipalId int,
	@Code nchar(2),
	@Rate money,
	@retval int output
AS
UPDATE PROJECT_MEMBERS
 SET Code=@Code, Rate=@Rate, IsTeamMember=1
 WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId AND (Code != @Code OR Rate != @Rate)
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateActualFinishDate
	@ProjectId int,
	@Date datetime = null,
	@retval int output
AS
UPDATE PROJECTS
 SET ActualFinishDate = @Date
 WHERE ProjectId = @ProjectId AND ActualFinishDate != @Date
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateActualStartDate
	@ProjectId int,
	@Date datetime = null,
	@retval int output
AS
UPDATE PROJECTS
 SET ActualStartDate = @Date
 WHERE ProjectId = @ProjectId AND ActualStartDate != @Date
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateClient
	@ProjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE PROJECTS
 SET ClientId = @ValueId
 WHERE ProjectId = @ProjectId AND ClientId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateConfigurationInfo
	@ProjectId int,
	@CalendarId int,
	@CurrencyId int,
	@TypeId int,
	@InitialPhaseId int,
	@retval int output
AS
UPDATE PROJECTS
 SET CalendarId = @CalendarId, CurrencyId = @CurrencyId, FormId=@TypeId, InitialPhaseId = @InitialPhaseId
 WHERE ProjectId = @ProjectId AND (CalendarId != @CalendarId OR CurrencyId != @CurrencyId OR InitialPhaseId != @InitialPhaseId OR FormId!=@TypeId)
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateExecutiveManager
	@ProjectId int,
	@ValueId int = null
AS
UPDATE PROJECTS
 SET ExecutiveManagerId = @ValueId
 WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateGeneralInfo
	@ProjectId int,
	@Title nvarchar(255),
	@Description ntext,
	@Goals ntext,
	@Scope ntext,
	@Deliverables ntext
AS
UPDATE PROJECTS
 SET Title = @Title, [Description] = @Description, Goals = @Goals, Scope = @Scope, Deliverables = @Deliverables
 WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateManager
	@ProjectId int,
	@ValueId int
AS
UPDATE PROJECTS
 SET ManagerId = @ValueId
 WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdatePhase
	@ProjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE PROJECTS
 SET PhaseId = @ValueId
 WHERE ProjectId = @ProjectId AND PhaseId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdatePriority
	@ProjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE PROJECTS
 SET PriorityId = @ValueId
 WHERE ProjectId = @ProjectId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateProgress
	@ProjectId int,
	@Value int,
	@retval int output
AS
UPDATE PROJECTS
 SET PercentCompleted = @Value
 WHERE ProjectId = @ProjectId AND PercentCompleted != @Value
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateRiskLevel
	@ProjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE PROJECTS
 SET RiskLevelId = @ValueId
 WHERE ProjectId = @ProjectId AND RiskLevelId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateStatus
	@ProjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE PROJECTS
 SET StatusId = @ValueId
 WHERE ProjectId = @ProjectId AND StatusId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_ProjectUpdateTargetDates
	@ProjectId int,
	@StartDate datetime,
	@FinishDate datetime = null,
	@retval int output
AS
DECLARE @OldStartDate DateTime, @OldFinishDate DateTime
SELECT @OldStartDate = TargetStartDate, @OldFinishDate = TargetFinishDate FROM PROJECTS WHERE ProjectId = @ProjectId
IF @StartDate != @OldStartDate AND @FinishDate != @OldFinishDate
BEGIN
	UPDATE PROJECTS SET TargetStartDate = @StartDate, TargetFinishDate = @FinishDate WHERE ProjectId = @ProjectId
	SET @retval = 3
END
ELSE IF @StartDate != @OldStartDate
BEGIN
	UPDATE PROJECTS SET TargetStartDate = @StartDate WHERE ProjectId = @ProjectId
	SET @retval = 1
END
ELSE IF @FinishDate != @OldFinishDate
BEGIN
	UPDATE PROJECTS SET TargetFinishDate = @FinishDate WHERE ProjectId = @ProjectId
	SET @retval = 2
END
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TaskResourceAdd
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit
AS
INSERT INTO TASK_RESOURCES (TaskId, PrincipalId, MustBeConfirmed, CanManage)
  VALUES(@ObjectId, @PrincipalId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TaskResourceUpdate
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@CanManage bit,
	@retval int output
AS
UPDATE TASK_RESOURCES
 SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
 WHERE TaskId = @ObjectId AND PrincipalId = @PrincipalId AND (MustBeConfirmed != @MustBeConfirmed OR CanManage != @CanManage)
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TaskUpdateGeneralInfo
	@ObjectId int,
	@Title nvarchar(255),
	@Description ntext
AS
UPDATE TASKS
 SET Title = @Title, [Description] = @Description
 WHERE TaskId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TaskUpdatePriority
	@ObjectId int,
	@ValueId int,
	@retval int output
AS
UPDATE TASKS
 SET PriorityId = @ValueId
 WHERE TaskId = @ObjectId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoResourceAdd
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit
AS
INSERT INTO TODO_RESOURCES (TodoId, PrincipalId, MustBeConfirmed)
  VALUES(@ObjectId, @PrincipalId, @MustBeConfirmed)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoResourceReply
	@ObjectId int,
	@UserId int,
	@IsConfirmed bit,
	@retval int output
AS
UPDATE TODO_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = getutcdate()
  WHERE TodoId = @ObjectId AND PrincipalId = @UserId AND MustBeConfirmed = 1 AND ResponsePending = 1
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoResourceUpdate
	@ObjectId int,
	@PrincipalId int,
	@MustBeConfirmed bit,
	@retval int output
AS
UPDATE TODO_RESOURCES
 SET MustBeConfirmed = @MustBeConfirmed
 WHERE TodoId = @ObjectId AND PrincipalId = @PrincipalId AND MustBeConfirmed != @MustBeConfirmed
SELECT @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoUpdateConfigurationInfo
	@TodoId int,
	@ActivationTypeId int,
	@CompletionTypeId int,
	@MustBeConfirmed bit,
	@retval int output
AS
UPDATE TODO
 SET ActivationTypeId = @ActivationTypeId, CompletionTypeId = @CompletionTypeId, MustBeConfirmed = @MustBeConfirmed
 WHERE TodoId = @TodoId AND ActivationTypeId != @ActivationTypeId AND CompletionTypeId != @CompletionTypeId AND MustBeConfirmed != @MustBeConfirmed
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoUpdateGeneralInfo
	@TodoId int,
	@Title nvarchar(255),
	@Description ntext
AS
UPDATE TODO
 SET Title = @Title, [Description] = @Description
 WHERE TodoId = @TodoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoUpdatePriority
	@TodoId int,
	@ValueId int,
	@retval int output
AS
UPDATE TODO
 SET PriorityId = @ValueId
 WHERE TodoId = @TodoId AND PriorityId != @ValueId
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Act_TodoUpdateTimeline
	@TodoId int,
	@StartDate datetime = null,
	@FinishDate datetime = null,
	@TaskTime int,
	@retval int output
AS
DECLARE @OldStartDate DateTime, @OldFinishDate DateTime, @OldTaskTime int
SELECT @OldStartDate = StartDate, @OldFinishDate = FinishDate, @OldTaskTime = TaskTime
  FROM TODO
  WHERE TodoId = @TodoId
UPDATE TODO SET StartDate = @StartDate, FinishDate = @FinishDate, TaskTime = @TaskTime  WHERE TodoId = @TodoId
IF @StartDate != @OldStartDate AND @FinishDate != @OldFinishDate
	SET @retval = 3
ELSE IF @StartDate != @OldStartDate
	SET @retval = 1
ELSE IF @FinishDate != @OldFinishDate
	SET @retval = 2
ELSE IF @TaskTime != @OldTaskTime
	SET @retval = 4
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActionsGetList
	@UserId int
as
DECLARE @NewStatus int, @ActiveStatus  int, @HDMGroup int
SET @NewStatus = 1
SET @ActiveStatus = 2
SET @HDMGroup = 5
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDMGroup)
	SET @IsHDM = 1
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT 1 AS ActionType, COUNT(*) AS Counter
  FROM USERS
  WHERE Activity = 2
UNION ALL
SELECT 2 AS ActionType, COUNT(*) AS Counter
  FROM INCIDENTS
  WHERE (StatusId = @NewStatus OR StatusId = @ActiveStatus)
	AND (ManagerId = @UserId OR (ProjectId IS NULL AND ManagerId = @HDMGroup AND @IsHDM = 1))
	AND (IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_TODO)
		OR IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_TODO IT, TODO T WHERE IT.ToDoId = T.ToDoId AND T.IsCompleted = 0)
	)
	AND IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
UNION ALL
SELECT 3 AS ActionType,
	(SELECT COUNT(*)
	  FROM TODO
	  WHERE ManagerId = @Userid AND IsCompleted=0 AND PercentCompleted = 100
	) +
	(SELECT COUNT(*)
	  FROM TASKS T, PROJECTS P
	  WHERE T.ProjectId = P.ProjectId AND T.IsSummary = 0 AND T.IsMilestone = 0
		AND P.ManagerId = @UserId AND T.IsCompleted=0 AND T.PercentCompleted = 100
	) AS Counter
UNION ALL
SELECT 4 AS ActionType, COUNT(*) AS Counter
  FROM POP3_INCIDENTS
  WHERE @IsHDM = 1
UNION ALL
SELECT 5 AS ActionType,
	(SELECT COUNT(*)
	  FROM TODO T, TODO_RESOURCES R
	  WHERE T.ToDoId = R.ToDoId AND R.PrincipalId = @UserId
		AND T.IsCompleted=0
		AND R.MustBeConfirmed=1 AND R.ResponsePending=1
	) +
	(SELECT COUNT(*)
	  FROM TASKS T, TASK_RESOURCES R
	  WHERE T.TaskId = R.TaskId AND R.PrincipalId = @UserId
		AND T.IsCompleted=0  AND T.IsMileStone = 0 AND T.IsSummary = 0
		AND R.MustBeConfirmed=1 AND R.ResponsePending=1
	) AS Counter
UNION ALL
SELECT 6 AS ActionType, COUNT(*) AS Counter
  FROM EVENTS E, EVENT_RESOURCES R
  WHERE E.EventId = R.EventId AND R.PrincipalId = @UserId
	AND E.FinishDate > GETUTCDATE()
	AND R.MustBeConfirmed=1 AND R.ResponsePending=1
UNION ALL
SELECT 7 AS ActionType,
	(SELECT COUNT(*)
	  FROM TODO
	  WHERE ManagerId = @UserId AND IsCompleted=0
		AND ToDoId NOT IN (SELECT ToDoId FROM TODO_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
	) +
	(SELECT COUNT(*)
	  FROM TASKS T, PROJECTS P
	  WHERE T.ProjectId = P.ProjectId AND P.ManagerId = @UserId
		AND T.IsCompleted=0  AND IsSummary = 0 AND IsMilestone = 0
		AND T.TaskId NOT IN (SELECT TaskId FROM TASK_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
		AND T.TaskId NOT IN (SELECT TaskId FROM TASK_TODO)
	) AS Counter
UNION ALL
SELECT 8 AS ActionType, COUNT(*) AS Counter
  FROM INCIDENTS I, INCIDENT_RESOURCES R
  WHERE I.IncidentId = R.IncidentId AND R.PrincipalId = @UserId
	AND R.MustBeConfirmed=1 AND R.ResponsePending=1
	AND (I.StatusId = @NewStatus OR I.StatusId = @ActiveStatus)
UNION ALL
SELECT 9 AS ActionType, COUNT(*) AS Counter
  FROM WeekTimeSheet
  WHERE StatusId = 2
	AND (@IsPPM_Exec = 1 OR ProjectId IN (SELECT ProjectId FROM PROJECT_SECURITY_ALL PS WHERE PrincipalId = @UserId AND IsManager = 1))
UNION ALL
SELECT 10 AS ActionType, COUNT(*) AS Counter
  FROM PROJECTS P, PROJECT_SECURITY_ALL PS, PROJECT_STATUS S
  WHERE P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId
	AND P.StatusId = S.StatusId AND S.IsActive = 1
	AND (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActivationTypesGet
	@LanguageId as int
as
SELECT ActivationTypeId, ActivationTypeName
  FROM ACTIVATION_TYPE_LANGUAGE
  WHERE LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesAdd
	@AccountId int,
	@ObjectTypeId int,
	@ObjectId int,
	@ActualDate datetime,
	@Description nvarchar(255),
	@AValue money,
	@LastEditorId int,
	@retval int output
as
INSERT INTO ACTUAL_FINANCES (AccountId, ObjectTypeId, ObjectId, ActualDate, [Description], AValue, LastEditorId, LastSavedDate)
  VALUES (@AccountId, @ObjectTypeId, @ObjectId, @ActualDate, @Description, @AValue, @LastEditorId, getutcdate())
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesAddFromTimeSheet
	@WeekTimeSheetId int,
	@AccountId int,
	@ActualDate datetime,
	@Description nvarchar(255),
	@LastEditorId int
AS
DECLARE @Dt datetime
SET @Dt = getutcdate()
DECLARE @TimeSheetId int, @ObjectId int, @ObjectTypeId int, @Total money, @ActualId int
DECLARE ts_cursor CURSOR FOR
	SELECT TimeSheetId, ObjectId, ObjectTypeId, TotalApproved * Rate / 60 AS Total
	  FROM TIMESHEETS
	  WHERE WeekTimeSheetId = @WeekTimeSheetId
OPEN ts_cursor
FETCH NEXT FROM ts_cursor INTO @TimeSheetId, @ObjectId, @ObjectTypeId, @Total
WHILE @@FETCH_STATUS = 0
BEGIN
	INSERT INTO ACTUAL_FINANCES (AccountId, ActualDate, [Description], AValue, LastEditorId, LastSavedDate, ObjectTypeId, ObjectId)
	  VALUES (@AccountId, @ActualDate, @Description, @Total, @LastEditorId, @Dt, @ObjectTypeId, @ObjectId)
	SET @ActualId = @@identity
	UPDATE TIMESHEETS SET ActualId = @ActualId WHERE TimeSheetId = @TimeSheetId
	FETCH NEXT FROM ts_cursor INTO @TimeSheetId, @ObjectId, @ObjectTypeId, @Total
END
CLOSE ts_cursor
DEALLOCATE ts_cursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesDelete
	@ActualId int
as
DELETE ACTUAL_FINANCES WHERE ActualId = @ActualId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesGet
	@ActualId int
as
SELECT F.ActualId, F.AccountId, F.[Description], F.AValue, F.LastEditorId, F.ObjectTypeId, F.ObjectId,
	CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
  FROM ACTUAL_FINANCES F
	LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
  WHERE F.ActualId = @ActualId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesGetListByObject
	@ObjectTypeId int,
	@ObjectId int
as
DECLARE @ToDoType int
SET @ToDoType = 6
IF @ObjectTypeId = 5
	SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate,
		F.ObjectTypeId, F.ObjectId, '' AS ObjectTitle,
		CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
	  FROM ACTUAL_FINANCES F
		JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
		LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	  WHERE F.ObjectTypeId = @ObjectTypeId AND F.ObjectId = @ObjectId
	UNION ALL
	SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate,
		F.ObjectTypeId, F.ObjectId, TD.Title AS ObjectTitle,
		CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
	  FROM ACTUAL_FINANCES F
		JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
		JOIN TODO TD ON (F.ObjectId = TD.ToDoId)
		LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	  WHERE F.ObjectTypeId = @ToDoType AND F.ObjectId IN (SELECT ToDoId FROM TASK_TODO WHERE TaskId = @ObjectId)
	  ORDER BY F.ActualDate DESC
ELSE IF @ObjectTypeId = 7
	SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate,
		F.ObjectTypeId, F.ObjectId, '' AS ObjectTitle,
		CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
	  FROM ACTUAL_FINANCES F
		JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
		LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	  WHERE F.ObjectTypeId = @ObjectTypeId AND F.ObjectId = @ObjectId
	UNION ALL
	SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate,
		F.ObjectTypeId, F.ObjectId, TD.Title AS ObjectTitle,
		CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
	  FROM ACTUAL_FINANCES F
		JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
		JOIN TODO TD ON (F.ObjectId = TD.ToDoId)
		LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	  WHERE F.ObjectTypeId = @ToDoType AND F.ObjectId IN (SELECT ToDoId FROM INCIDENT_TODO WHERE IncidentId = @ObjectId)
	  ORDER BY F.ActualDate DESC
ELSE
	SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate,
		F.ObjectTypeId, F.ObjectId, '' AS ObjectTitle,
		CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
	  FROM ACTUAL_FINANCES F
		JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
		LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	  WHERE F.ObjectTypeId = @ObjectTypeId AND F.ObjectId = @ObjectId
	  ORDER BY F.ActualDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesGetListByProject
	@ProjectId int
as
SELECT F.ActualId, F.AccountId, A.Title, A.OutlineLevel, F.ActualDate, F.[Description], F.AValue, F.LastEditorId, F.LastSavedDate, F.ObjectTypeId, F.ObjectId,
	CASE
		WHEN F.ObjectTypeId = 4 THEN E.Title
		WHEN F.ObjectTypeId = 5 THEN TA.Title
		WHEN F.ObjectTypeId = 6 THEN TD.Title
		WHEN F.ObjectTypeId = 7 THEN I.Title
		WHEN F.ObjectTypeId = 16 THEN D.Title
		WHEN F.ObjectTypeId = 11 THEN TT.Title
		ELSE ''
	END AS ObjectTitle,
	CASE WHEN T.TimeSheetId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsTimeSheet
  FROM ACTUAL_FINANCES F
	JOIN ACCOUNTS A ON (F.AccountId = A.AccountId)
	LEFT JOIN TIMESHEETS T ON (F.ActualId = T.ActualId)
	LEFT JOIN EVENTS E ON (F.ObjectId = E.EventId AND F.ObjectTypeId = 4)
	LEFT JOIN TASKS TA ON (F.ObjectId = TA.TaskId AND F.ObjectTypeId = 5)
	LEFT JOIN TODO TD ON (F.ObjectId = TD.ToDoId AND F.ObjectTypeId = 6)
	LEFT JOIN INCIDENTS I ON (F.ObjectId = I.IncidentId AND F.ObjectTypeId = 7)
	LEFT JOIN DOCUMENTS D ON (F.ObjectId = D.DocumentId AND F.ObjectTypeId = 16)
	LEFT JOIN TIMESHEET_TODO TT ON (F.ObjectId = TT.TimeSheetToDoId AND F.ObjectTypeId = 11)
  WHERE A.ProjectId = @ProjectId
  ORDER BY F.ActualDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesUpdateValue
	@ActualId int,
	@AValue money,
	@LastEditorId int
as
UPDATE ACTUAL_FINANCES
  SET AValue = @AValue, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE ActualId = @ActualId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ActualFinancesUpdateValueAndDescription
	@ActualId int,
	@AValue money,
	@Description nvarchar(255),
	@LastEditorId int
as
UPDATE ACTUAL_FINANCES
  SET [Description] = @Description, AValue = @AValue, LastEditorId = @LastEditorId, LastSavedDate = getutcdate()
  WHERE ActualId = @ActualId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2MessageLogAdd
	@Subject nvarchar(1000),
	@Body ntext,
	@retval int output
AS
INSERT INTO MESSAGE_LOG (Subject, Body) VALUES (@Subject, @Body)
SET @retval  = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2TemplateDelete
	@Key nvarchar(100)
AS
DELETE FROM AlertTemplates
 WHERE [Key] = @Key
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2TemplateGet
	@Key nvarchar(100)
AS
SELECT [Key], Subject, Body
 FROM AlertTemplates
 WHERE [Key] = @Key
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2TemplateUpdate
	@Key nvarchar(100),
	@Subject nvarchar(1000),
	@Body ntext
AS
IF EXISTS(SELECT * FROM AlertTemplates WHERE [Key] = @Key)
	UPDATE AlertTemplates SET Subject = @Subject, Body = @Body WHERE [Key] = @Key
ELSE
	INSERT INTO AlertTemplates ([Key], Subject, Body) VALUES (@Key, @Subject, @Body)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2UserGet
	@UserId int
AS
SELECT U.PrincipalId, U.Login, U.FirstName, U.LastName, U.Email, U.IsExternal, U.OriginalId AS ImId,
	P.IsNotifiedByEmail, P.IsNotifiedByIbn, P.LanguageId, L.Locale, P.TimeZoneId, P.MenuInAlerts, P.BatchLastSent, P.BatchNextSend, P.[From], P.Till, P.Period
 FROM USERS U
 JOIN USER_PREFERENCES P ON (P.UserId = U.PrincipalId)
 JOIN LANGUAGES L ON (L.LanguageId = P.LanguageId)
 WHERE U.PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetCalendarEntry
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 4
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.ProjectId, O.PriorityId, O.PriorityId, O.TypeId, O.StartDate AS Start, O.Finishdate AS [End], P.Title AS ProjectTitle, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy, M.FirstName+' '+M.LastName AS Manager
  FROM EVENTS O
	LEFT JOIN PROJECTS P ON (O.ProjectId = P.ProjectId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	JOIN USERS M ON (M.PrincipalId = O.ManagerId)
  WHERE O.EventId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetComment
	@ObjectId int
AS
SELECT O.Text AS Title
 FROM DISCUSSIONS O
 WHERE O.DiscussionId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetDocument
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 16
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.ProjectId, O.PriorityId, S.StatusName AS DocumentStatus, P.Title AS ProjectTitle, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy, M.FirstName+' '+M.LastName AS Manager
  FROM DOCUMENTS O
	LEFT JOIN PROJECTS P ON (O.ProjectId = P.ProjectId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	JOIN USERS M ON (M.PrincipalId = O.ManagerId)
	JOIN DOCUMENT_STATUS S ON (S.StatusId = O.StatusId)
  WHERE O.DocumentId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetFile
	@ObjectId int
AS
SELECT O.Name AS Title, datalength(B.Data) AS FileSize
  FROM fsc_Files O
	LEFT JOIN fsc_FileBinaries B ON (B.FileBinaryId = O.FileBinaryId)
  WHERE O.FileId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetIssue
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 7
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.ProjectId, O.PriorityId, O.StatusId, P.Title AS ProjectTitle, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy,
	ISNULL(M.FirstName+' '+M.LastName, G.GroupName) AS Manager
  FROM INCIDENTS O
	LEFT JOIN PROJECTS P ON (O.ProjectId = P.ProjectId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	LEFT JOIN USERS M ON (M.PrincipalId = O.ManagerId)
	LEFT JOIN GROUPS G ON (G.PrincipalId = O.ManagerId)
  WHERE O.IncidentId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetIssueRequest
	@ObjectId int
AS
SELECT O.Subject AS Title, O.Sender AS Email, O.Priority, O.FirstName+' '+O.LastName AS CreatedBy, B.Pop3BoxId AS MailBoxId, B.Name AS MailBoxTitle
 FROM Pop3MailRequests O
 JOIN Pop3Boxes B ON (B.Pop3BoxId = O.Pop3BoxId)
 WHERE O.Pop3MailRequestId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetList
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 15
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.StatusId, T.TypeName AS ListType, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy
  FROM LISTS O
	LEFT JOIN LIST_TYPES T ON (T.Typeid = O.TypeId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
  WHERE O.ListId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetProject
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 3
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.PercentCompleted, O.PriorityId, O.StatusId, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy, M.FirstName+' '+M.LastName AS Manager, O.TargetStartDate as Start, O.TargetFinishDate as [End]
  FROM PROJECTS O
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	JOIN USERS M ON (M.PrincipalId = O.ManagerId)
  WHERE O.ProjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetTask
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 5
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.PercentCompleted, O.ProjectId, O.PriorityId, P.Title AS ProjectTitle, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy, M.FirstName+' '+M.LastName AS Manager, O.StartDate as Start, O.FinishDate as [End]
  FROM TASKS O
	LEFT JOIN PROJECTS P ON (O.ProjectId = P.ProjectId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	JOIN USERS M ON (M.PrincipalId = P.ManagerId)
  WHERE O.TaskId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetTodo
	@ObjectId int
AS
DECLARE @ObjectType int, @UpdatedBy nvarchar(100)
SET @ObjectType = 6
SELECT @UpdatedBy = U.FirstName+' '+U.LastName
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
	JOIN USERS U ON (E.UserId = U.PrincipalId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectType
  ORDER BY E.Dt DESC
SELECT O.Title, O.PercentCompleted, O.ProjectId, O.PriorityId, P.Title AS ProjectTitle, C.FirstName+' '+C.LastName AS CreatedBy,
	ISNULL(@UpdatedBy, C.FirstName+' '+C.LastName) AS UpdatedBy, M.FirstName+' '+M.LastName AS Manager, O.StartDate as Start, O.FinishDate as [End]
  FROM TODO O
	LEFT JOIN PROJECTS P ON (O.ProjectId = P.ProjectId)
	JOIN USERS C ON (C.PrincipalId = O.CreatorId)
	JOIN USERS M ON (M.PrincipalId = O.ManagerId)
  WHERE O.ToDoId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Alert2VariablesGetUser
	@ObjectId int
AS
SELECT O.FirstName+' '+O.LastName AS Title, Email, Login, [Password]
 FROM USERS O
 WHERE O.PrincipalId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].BroadCastMessageAdd
	@Text ntext,
	@ExpirationDate datetime,
	@CreatorId int,
	@retval int output
as
INSERT INTO BroadCastMessages (ExpirationDate, [Text], CreatorId)
  VALUES (@ExpirationDate, @Text, @CreatorId)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].BroadCastMessagesGet
	@UserId int,
	@OnlyActive bit
as
IF @OnlyActive = 1
	SELECT TOP 5 MessageId, CreationDate, ExpirationDate, [Text], CreatorId
	  FROM BroadCastMessages
	  WHERE ExpirationDate > GetUtcDate()
		AND MessageId IN (SELECT MessageId FROM BroadCastRecipients WHERE GroupId IN (SELECT GroupId FROM USER_GROUP WHERE UserId = @UserId))
	  ORDER BY CreationDate DESC
ELSE
	SELECT TOP 20 MessageId, CreationDate, ExpirationDate, [Text], CreatorId
	  FROM BroadCastMessages
	  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].BroadCastRecipientAdd
	@MessageId int,
	@GroupId int
as
INSERT INTO BroadCastRecipients (MessageId, GroupId)
  VALUES (@MessageId, @GroupId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].BroadcastRecipientGetUsers
	@MessageId int
AS
SELECT DISTINCT U.OriginalId AS ImId, L.Locale
FROM BroadcastRecipients R
 JOIN USER_GROUP UG ON (UG.GroupId = R.GroupId)
 JOIN USERS U ON (U.PrincipalId = UG.UserId)
 JOIN USER_PREFERENCES P ON (P.UserId = U.PrincipalId)
 JOIN LANGUAGES L ON (L.LanguageId = P.LanguageId)
WHERE R.MessageId = @MessageId AND U.OriginalId IS NOT NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Cal_GetDurationByFinishDate
	@CalendarId int,
	@StartDate datetime,
	@EndDate datetime,
	@retval int output
AS
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @StartDate = [dbo].GetLocalDate(@TimeZoneId, @StartDate)
SET @EndDate = [dbo].GetLocalDate(@TimeZoneId, @EndDate)
DECLARE @DayOfWeek tinyint
DECLARE @Duration int, @DayDuration int
SET @Duration = 0
SET @DayDuration = 0
DECLARE @StartTime smallint
SET @StartTime = DATEPART(hh, @StartDate) * 60 + DATEPART(mi, @StartDate)
DECLARE @EndTime smallint
SET @EndTime = 24*60
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@StartTime, @StartDate)
WHILE @ProcessDate <= @EndDate BEGIN
	IF DATEDIFF(dd, @ProcessDate, @EndDate) = 0
			SET @EndTime = DATEPART(hh, @EndDate) * 60 + DATEPART(mi, @EndDate)
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(CASE WHEN ToTime < @EndTime THEN ToTime ELSE @EndTime END  - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		  FROM CAL_EXCEPTION_HOURS
		  WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND ToTime > @StartTime AND FromTime < @EndTime
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(CASE WHEN ToTime < @EndTime THEN ToTime ELSE @EndTime END - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		  FROM CAL_WEEKDAYS
		  WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime AND FromTime < @EndTime
	END
	IF @DayDuration IS NOT NULL
		SET @Duration = @Duration + @DayDuration
	SET @ProcessDate = DATEADD(dd, 1, @ProcessDate)
	SET @StartTime = 0
END
SET @retval = @Duration
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Cal_GetFinishDateByDuration
	@CalendarId int,
	@StartDate datetime,
	@Duration int,
	@retval datetime output
AS
DECLARE @EndDate datetime
DECLARE @FromTime smallint, @ToTime smallint
DECLARE @IntervalDuration smallint
DECLARE @DayDuration smallint
DECLARE @DayOfWeek tinyint
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @StartDate = [dbo].GetLocalDate(@TimeZoneId, @StartDate)
DECLARE @StartTime smallint
SET @StartTime = DATEPART(hh, @StartDate) * 60 + DATEPART(mi, @StartDate)
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@StartTime, @StartDate)
WHILE @Duration >= 0 BEGIN
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(ToTime - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		 FROM CAL_EXCEPTION_HOURS
		 WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND ToTime > @StartTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration <= @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END AS FromTime, ToTime
					 FROM CAL_EXCEPTION_HOURS
					 WHERE ExceptionId IN
						(SELECT ExceptionId
						  FROM CAL_EXCEPTIONS
						  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
						AND ToTime > @StartTime
					 ORDER BY FromTime
				BREAK
			END
		END
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(ToTime - CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END)
		 FROM CAL_WEEKDAYS
		 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration <= @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT CASE WHEN FromTime > @StartTime THEN FromTime ELSE @StartTime END AS FromTime, ToTime
					 FROM CAL_WEEKDAYS
					 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND ToTime > @StartTime
					 ORDER BY FromTime
				BREAK
			END
		END
	END
	SET @ProcessDate = DATEADD(dd, 1, @ProcessDate)
	SET @StartTime = 0
END
OPEN HoursCursor
FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @IntervalDuration = @ToTime - @FromTime
	IF @IntervalDuration <= @Duration
		SET @Duration = @Duration - @IntervalDuration
	ELSE BEGIN
		SET @EndDate = DATEADD(mi, @FromTime + @Duration,@ProcessDate)
		BREAK
	END
	FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
END
CLOSE HoursCursor
DEALLOCATE HoursCursor
SET @retval = [dbo].GetUTCDateFromLocal(@TimeZoneId, @EndDate)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Cal_GetStartDateByDuration
	@CalendarId int,
	@FinishDate datetime,
	@Duration int,
	@retval datetime output
AS
DECLARE @TimeZoneId int
SELECT @TimeZoneId = TimeZoneId FROM CALENDARS WHERE CalendarId = @CalendarId
SET @FinishDate = [dbo].GetLocalDate(@TimeZoneId, @FinishDate)
DECLARE @StartdDate datetime
DECLARE @FromTime smallint, @ToTime smallint
DECLARE @IntervalDuration smallint
DECLARE @DayDuration smallint
DECLARE @DayOfWeek tinyint
DECLARE @FinishTime smallint
SET @FinishTime = DATEPART(hh, @FinishDate) * 60 + DATEPART(mi, @FinishDate)
DECLARE @ProcessDate datetime
SET @ProcessDate = DATEADD(mi, -@FinishTime, @FinishDate)
WHILE @Duration >= 0 BEGIN
	IF EXISTS(SELECT * FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
	BEGIN
		SELECT @DayDuration = SUM(CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END - FromTime)
		 FROM CAL_EXCEPTION_HOURS
		 WHERE ExceptionId IN
			(SELECT ExceptionId
			  FROM CAL_EXCEPTIONS
			  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
			AND FromTime <= @FinishTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration < @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT FromTime, CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END AS ToTime
					 FROM CAL_EXCEPTION_HOURS
					 WHERE ExceptionId IN
						(SELECT ExceptionId
						  FROM CAL_EXCEPTIONS
						  WHERE CalendarId = @CalendarId AND FromDate <= @ProcessDate AND ToDate >= @ProcessDate)
						AND FromTime <= @FinishTime
					 ORDER BY ToTime DESC
				BREAK
			END
		END
	END
	ELSE BEGIN
		SET @DayOfWeek = CASE WHEN DATEPART(dw, @ProcessDate) = 1 THEN 7 ELSE DATEPART(dw, @ProcessDate) - 1 END
		SELECT @DayDuration = SUM(CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END - FromTime)
		 FROM CAL_WEEKDAYS
		 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND FromTime <= @FinishTime
		IF @DayDuration IS NOT NULL BEGIN
			IF @DayDuration < @Duration
				SET @Duration =  @Duration - @DayDuration
			ELSE BEGIN
				DECLARE HoursCursor CURSOR FOR
					SELECT FromTime, CASE WHEN ToTime > @FinishTime THEN @FinishTime ELSE ToTime END AS ToTime
					 FROM CAL_WEEKDAYS
					 WHERE CalendarId = @CalendarId  AND [DayOfWeek] = @DayOfWeek AND FromTime <= @FinishTime
					 ORDER BY ToTime DESC
				BREAK
			END
		END
	END
	SET @ProcessDate = DATEADD(dd, -1, @ProcessDate)
	SET @FinishTime = 24*60
END
OPEN HoursCursor
FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @IntervalDuration = @ToTime - @FromTime
	IF @IntervalDuration < @Duration
		SET @Duration = @Duration - @IntervalDuration
	ELSE BEGIN
		SET @StartdDate = DATEADD(mi, @ToTime - @Duration, @ProcessDate)
		BREAK
	END
	FETCH NEXT FROM HoursCursor INTO @FromTime, @ToTime
END
CLOSE HoursCursor
DEALLOCATE HoursCursor
SET @StartdDate = [dbo].GetUTCDateFromLocal(@TimeZoneId, @StartdDate)
SET @retval = @StartdDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarCopy
	@FromCalendarId as int,
	@ToCalendarId as int
as
DECLARE @ExceptionId int
DECLARE @NewExceptionId int
BEGIN TRANSACTION
	DELETE FROM 	CAL_WEEKDAYS WHERE CalendarId = @ToCalendarId
	IF @@error != 0
		GOTO err
	DELETE FROM CAL_EXCEPTIONS WHERE CalendarId = @ToCalendarId
	IF @@error != 0
		GOTO err
	INSERT INTO CAL_WEEKDAYS (CalendarId, DayOfWeek, FromTime, ToTime)
	  SELECT @ToCalendarId AS CalendarId, DayOfWeek, FromTime, ToTime FROM CAL_WEEKDAYS WHERE CalendarId = @FromCalendarId
	IF @@error != 0
		GOTO err
	DECLARE ExceptionsCursor CURSOR FOR
	  SELECT ExceptionId FROM CAL_EXCEPTIONS WHERE CalendarId = @FromCalendarId
	OPEN ExceptionsCursor
	FETCH NEXT FROM ExceptionsCursor INTO @ExceptionId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		INSERT INTO CAL_EXCEPTIONS (CalendarId, FromDate, ToDate)
		  SELECT @ToCalendarId AS CalendarId, FromDate, ToDate FROM CAL_EXCEPTIONS WHERE ExceptionId = @ExceptionId
		IF @@error != 0
			GOTO err
		SET @NewExceptionId = @@identity
		INSERT INTO CAL_EXCEPTION_HOURS (ExceptionId, FromTime, ToTime)
		  SELECT @NewExceptionId AS ExceptionId, FromTime, ToTime FROM CAL_EXCEPTION_HOURS WHERE ExceptionId = @ExceptionId
		IF @@error != 0
			GOTO err
		FETCH NEXT FROM ExceptionsCursor INTO @ExceptionId
	END
	CLOSE ExceptionsCursor
	DEALLOCATE ExceptionsCursor
COMMIT TRANSACTION
RETURN
err:
	ROLLBACK TRANSACTION
	RAISERROR('Unable to copy calendar', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarCreate
	@CalendarName as nvarchar(250),
	@TimeZoneId as int,
	@retval int output
as
INSERT INTO CALENDARS (CalendarName, TimeZoneId) VALUES(@CalendarName, @TimeZoneId)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarCreateWithProject
	@CalendarName as nvarchar(250),
	@TimeZoneId as int,
	@ProjectId as int,
	@retval int output
as
INSERT INTO CALENDARS (CalendarName, ProjectId, TimeZoneId) VALUES(@CalendarName, @ProjectId, @TimeZoneId)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarDelete
	@CalendarId as int
as
DELETE FROM CALENDARS  WHERE CalendarId = @CalendarId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarEmpty
	@CalendarId as int
as
BEGIN TRAN
	DELETE FROM CAL_WEEKDAYS WHERE CalendarId = @CalendarId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM CAL_EXCEPTIONS WHERE CalendarId = @CalendarId
	IF @@ERROR <> 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RAISERROR('Unable to empty calendar', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarGetByProject
	@ProjectId as int,
	@Retval int output
as
SELECT @Retval = CalendarId
  FROM CALENDARS
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarsGet
       @CalendarId as int
as
SELECT C.CalendarId, C.ProjectId, P.Title AS ProjectName, C.CalendarName, C.TimeZoneId,
	CASE WHEN EXISTS (SELECT * FROM PROJECTS PP WHERE PP.CalendarId = C.CalendarId) THEN 0 ELSE 1 END AS CanDelete
  FROM CALENDARS C
	LEFT JOIN PROJECTS P ON (C.ProjectId = P.ProjectId)
  WHERE C.CalendarId = @CalendarId or @CalendarId=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarsGetForProject
	@ProjectId as int
as
SELECT CalendarId, ProjectId, CalendarName, TimeZoneId
  FROM CALENDARS
  WHERE ProjectId IS NULL OR ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalendarUpdate
	@CalendarId as int ,
	@CalendarName as nvarchar(250),
	@TimeZoneId as int
as
UPDATE CALENDARS
  SET CalendarName=@CalendarName, TimeZoneId = @TimeZoneId
  WHERE CalendarId = @CalendarId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionAdd
	@CalendarId as int ,
	@FromDate as datetime ,
	@ToDate as datetime ,
	@retval int output
as
INSERT INTO CAL_EXCEPTIONS (CalendarId, FromDate, ToDate)
  VALUES(@CalendarId, @FromDate, @ToDate)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionDelete
	@ExceptionId as int
as
DELETE FROM CAL_EXCEPTIONS  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionGet
	@ExceptionId as int
as
SELECT ExceptionId, CalendarId, FromDate, DATEADD(d, -1, ToDate) AS ToDate
  FROM CAL_EXCEPTIONS
  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionGetCalendar
	@ExceptionId as int,
	@retval as int output
as
SELECT @retval = CalendarId
  FROM CAL_EXCEPTIONS
  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionHoursAdd
	@ExceptionId as int ,
	@FromTime as int ,
	@ToTime as int
as
INSERT INTO CAL_EXCEPTION_HOURS (ExceptionId, FromTime, ToTime)
  VALUES(@ExceptionId, @FromTime, @ToTime)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionHoursCopy
	@FromExceptionId as int ,
	@ToExceptionId as int
as
INSERT INTO CAL_EXCEPTION_HOURS (ExceptionId, FromTime, ToTime)
  SELECT @ToExceptionId AS ExceptionId, FromTime, ToTime FROM CAL_EXCEPTION_HOURS WHERE ExceptionId = @FromExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionHoursDelete
	@ExceptionId as int
as
DELETE FROM CAL_EXCEPTION_HOURS
  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionHoursGet
	@ExceptionId as int
as
SELECT ExceptionId, FromTime,
	CASE WHEN ToTime = 1440 THEN 0 ELSE ToTime END AS ToTime
  FROM CAL_EXCEPTION_HOURS
  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].CalExceptionHoursGetByCalendar
	@CalendarId as int
as
SELECT E.ExceptionId, E.CalendarId, E.FromDate, DateAdd(d, -1,E.ToDate) as ToDate, H.FromTime, H.ToTime
  FROM CAL_EXCEPTIONS E
	LEFT JOIN CAL_EXCEPTION_HOURS H ON (E.ExceptionId = H.ExceptionId)
  WHERE E.CalendarId = @CalendarId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionsGet
	@CalendarId as int
as
SELECT ExceptionId, CalendarId, FromDate, DATEADD(d, -1, ToDate) AS ToDate
  FROM CAL_EXCEPTIONS
  WHERE CalendarId = @CalendarId
  ORDER BY FromDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionsGetOverlaped
	@ExceptionId as int ,
	@FromDate as datetime ,
	@ToDate as datetime
as
DECLARE @CalendarId int
SELECT @CalendarId = CalendarId FROM CAL_EXCEPTIONS WHERE ExceptionId = @ExceptionId
SELECT ExceptionId, FromDate, ToDate
  FROM CAL_EXCEPTIONS
  WHERE FromDate < @ToDate AND ToDate > @FromDate
	AND CalendarId = @CalendarId AND ExceptionId != @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalExceptionUpdate
	@ExceptionId as int ,
	@FromDate as datetime ,
	@ToDate as datetime
as
UPDATE CAL_EXCEPTIONS
  SET FromDate=@FromDate, ToDate=@ToDate
  WHERE ExceptionId = @ExceptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalWeekdayAddHours
	@CalendarId as int ,
	@DayOfWeek as tinyint,
	@FromTime as int ,
	@ToTime as int
as
INSERT INTO CAL_WEEKDAYS (CalendarId, DayOfWeek ,FromTime, ToTime)
  VALUES(@CalendarId, @DayOfWeek, @FromTime, @ToTime)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalWeekdayDelete
	@CalendarId as int,
	@DayOfWeek as tinyint
as
DELETE FROM CAL_WEEKDAYS
  WHERE CalendarId = @CalendarId AND DayOfWeek = @DayOfWeek
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CalWeekdayGetHours
	@CalendarId as int,
	@DayOfWeek as tinyint
as
SELECT CalendarId, DayOfWeek, FromTime,
	CASE WHEN ToTime = 1440 THEN 0 ELSE ToTime END AS ToTime
  FROM CAL_WEEKDAYS
  WHERE CalendarId = @CalendarId
	AND (@DayOfWeek = 0 OR DayOfWeek = @DayOfWeek)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoriesGet
	@CategoryId as int
as
SELECT CategoryId, CategoryName
  FROM CATEGORIES
  WHERE CategoryId = @CategoryId or @CategoryId=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoriesGetByObject
	@ObjectTypeId as int ,
	@ObjectId as int
as
SELECT CategoryId, CategoryName
  FROM CATEGORIES
  WHERE CategoryId  IN
	(SELECT CategoryId FROM OBJECT_CATEGORY WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoriesGetForDictionaries
as
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName,
	CASE WHEN
		EXISTS(SELECT * FROM OBJECT_CATEGORY OC WHERE OC.CategoryId = C.CategoryId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM CATEGORIES C
  ORDER BY C.CategoryName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoriesGetProjectStatisticForPMAndPPM
	@UserId as int
as
DECLARE @ProjectObjectType int
SET @ProjectObjectType = 3
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM = 1
SELECT C.CategoryId, C.CategoryName, COUNT(*) AS [Count]
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (C.CategoryId = OC.CategoryId)
  WHERE OC.ObjectTypeId = @ProjectObjectType AND  OC.ObjectId IN
	(SELECT ProjectId
	  FROM PROJECTS
	  WHERE @IsPPM = 1 OR ManagerId = @UserId
	)
  GROUP BY C.CategoryId, C.CategoryName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryAdd
	@CategoryName as nvarchar(50)
AS
INSERT INTO CATEGORIES (CategoryName) VALUES(@CategoryName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryDelete
	@CategoryId as int
as
DELETE FROM CATEGORIES  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryUpdate
	@CategoryId as int ,
	@CategoryName as nvarchar(50)
as
UPDATE CATEGORIES SET CategoryName=@CategoryName
  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryUserAdd
	@CategoryId as int,
	@UserId as int
as
if NOT EXISTS(SELECT * FROM CATEGORY_USER WHERE CategoryId = @CategoryId AND UserId = @UserId)
	INSERT INTO CATEGORY_USER (CategoryId, UserId) VALUES(@CategoryId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryUserDelete
	@CategoryId as int,
	@UserId as int
as
DELETE FROM CATEGORY_USER
  WHERE CategoryId = @CategoryId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CategoryUserGetList
	@UserId as int
as
SELECT CategoryId, UserId
  FROM CATEGORY_USER
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ClientAdd
	@ClientName as nvarchar(50)
as
INSERT INTO CLIENTS (ClientName) VALUES(@ClientName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ClientDelete
	@ClientId as int
as
DELETE FROM CLIENTS  WHERE ClientId = @ClientId AND IsInternal = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ClientsGet
as
SELECT ClientId, ClientName, IsInternal
  FROM CLIENTS
  ORDER BY ClientName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ClientsGetForDictionaries
as
SELECT C.ClientId AS ItemId, C.ClientName AS ItemName,
	CASE WHEN EXISTS(SELECT * FROM PROJECTS P WHERE P.ClientId = C.ClientId) OR IsInternal = 1
	THEN 0 ELSE 1 END AS CanDelete
  FROM CLIENTS C
  ORDER BY C.ClientName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ClientUpdate
	@ClientId as int ,
	@ClientName as nvarchar(50)
as
UPDATE CLIENTS SET ClientName=@ClientName
  WHERE ClientId = @ClientId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedAccountAdd
	@UserId as int ,
	@AccountId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_ACCOUNTS WHERE UserId = @UserId AND AccountId = @AccountId)
	INSERT INTO COLLAPSED_ACCOUNTS (UserId, AccountId)
	  VALUES(@UserId, @AccountId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedAccountDelete
	@UserId as int,
	@AccountId as int
as
DELETE FROM COLLAPSED_ACCOUNTS
  WHERE UserId = @UserId AND AccountId = @AccountId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedDocumentAdd
	@UserId as int ,
	@ProjectId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_DOCUMENTS WHERE UserId = @UserId AND ProjectId = @ProjectId)
	INSERT INTO COLLAPSED_DOCUMENTS (UserId, ProjectId)
	  VALUES(@UserId, @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedDocumentDelete
	@UserId as int,
	@ProjectId as int
as
DELETE FROM COLLAPSED_DOCUMENTS
  WHERE UserId = @UserId AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedIncidentAdd
	@UserId as int ,
	@ProjectId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_INCIDENTS WHERE UserId = @UserId AND ProjectId = @ProjectId)
	INSERT INTO COLLAPSED_INCIDENTS (UserId, ProjectId)
	  VALUES(@UserId, @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedIncidentDelete
	@UserId as int,
	@ProjectId as int
as
DELETE FROM COLLAPSED_INCIDENTS
  WHERE UserId = @UserId AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedManagerTimesheetAdd
	@ManagerId as int,
	@UserId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_MANAGERTIMESHEETS WHERE UserId = @UserId AND ManagerId = @ManagerId)
	INSERT INTO COLLAPSED_MANAGERTIMESHEETS (ManagerId, UserId)
	  VALUES(@ManagerId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedManagerTimesheetDelete
	@ManagerId int,
	@UserId as int
as
DELETE FROM COLLAPSED_MANAGERTIMESHEETS
  WHERE ManagerId = @ManagerId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedTaskAdd
	@UserId as int ,
	@TaskId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_TASKS WHERE UserId = @UserId AND TaskId = @TaskId)
	INSERT INTO COLLAPSED_TASKS (UserId, TaskId)
	  VALUES(@UserId, @TaskId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedTaskDelete
	@UserId as int,
	@TaskId as int
as
DELETE FROM COLLAPSED_TASKS
  WHERE UserId = @UserId AND TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedUserTimesheetAdd
	@UserId as int,
	@ProjectId as int
as
if NOT EXISTS(SELECT * FROM COLLAPSED_USERTIMESHEETS WHERE UserId = @UserId AND ProjectId = @ProjectId)
	INSERT INTO COLLAPSED_USERTIMESHEETS (UserId, ProjectId)
	  VALUES(@UserId, @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CollapsedUserTimesheetDelete
	@UserId as int,
	@ProjectId as int
as
DELETE FROM COLLAPSED_USERTIMESHEETS
  WHERE UserId = @UserId AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CompletionTypesGet
	@LanguageId as int
as
SELECT CompletionTypeId, CompletionTypeName
  FROM COMPLETION_TYPE_LANGUAGE
  WHERE LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeCreate
	@Extension as nvarchar(10),
	@ContentTypeString as nvarchar(250),
	@FriendlyName as nvarchar(50),
	@IconFileId as int,
	@BigIconFileId as int,
	@retval int output
as
INSERT INTO CONTENT_TYPES (Extension, ContentTypeString, IconFileId, BigIconFileId, FriendlyName)
  VALUES (@Extension, @ContentTypeString, @IconFileId, @BigIconFileId, @FriendlyName)
select @retval = @@identity
UPDATE fsc_FileBinaries SET ContentTypeId = @retval
WHERE FileBinaryId IN
	(Select FileBinaryId from fsc_Files
		WHERE
		CHARINDEX('.',REVERSE([Name])) >  0
		AND
		RIGHT([Name], CHARINDEX('.',REVERSE([Name]))-1) = @Extension
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeDelete
	@ContentTypeId as int
AS
DECLARE @DefaultContentTypeId INT
SET @DefaultContentTypeId = (SELECT ContentTypeId FROM CONTENT_TYPES WHERE Extension = N'')
UPDATE fsc_FileBinaries SET ContentTypeId = @DefaultContentTypeId WHERE ContentTypeId = @ContentTypeId
DELETE FROM CONTENT_TYPES WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeGet
	@ContentTypeId as int
as
SELECT ContentTypeId, Extension, ContentTypeString, FriendlyName,
	CASE WHEN IconFileId IS NULL THEN -1 ELSE IconFileId END AS IconFileId,
	CASE WHEN BigIconFileId IS NULL THEN -1 ELSE BigIconFileId END AS BigIconFileId
  FROM CONTENT_TYPES
  WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeGetBigIconFileId
       @ContentTypeId as int,
       @retval as int out
AS
SELECT @retval = BigIconFileId
  FROM CONTENT_TYPES
  WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeGetByExtension
       @Extension as nvarchar(10)
as
SELECT ContentTypeId, Extension, ContentTypeString, FriendlyName
  FROM CONTENT_TYPES
  WHERE Extension = @Extension
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeGetIconFileId
       @ContentTypeId as int,
       @retval as int out
AS
SELECT @retval = IconFileId
  FROM CONTENT_TYPES
  WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypesGet
as
SELECT ContentTypeId, Extension, ContentTypeString, FriendlyName,
	CASE WHEN IconFileId IS NULL THEN -1 ELSE IconFileId END AS IconFileId,
	CASE WHEN BigIconFileId IS NULL THEN -1 ELSE BigIconFileId END AS BigIconFileId
  FROM CONTENT_TYPES
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypesRefresh
as
DECLARE @ContentTypeId int
DECLARE @Extension NVARCHAR(10)
DECLARE ctypes_cursor CURSOR FOR
	SELECT ContentTypeId, Extension FROM CONTENT_TYPES
OPEN ctypes_cursor
FETCH NEXT FROM ctypes_cursor INTO @ContentTypeId, @Extension
WHILE @@FETCH_STATUS = 0
BEGIN
	UPDATE fsc_FileBinaries SET ContentTypeId = @ContentTypeId
	WHERE FileBinaryId IN
	(Select FileBinaryId from fsc_Files
		WHERE
		CHARINDEX('.',REVERSE([Name])) >  0
		AND
		RIGHT([Name], CHARINDEX('.',REVERSE([Name]))-1) = @Extension
	)
	FETCH NEXT FROM ctypes_cursor INTO @ContentTypeId, @Extension
END
CLOSE ctypes_cursor
DEALLOCATE ctypes_cursor
DECLARE @DefaultContentTypeId INT
SET @DefaultContentTypeId = (SELECT ContentTypeId FROM CONTENT_TYPES WHERE Extension = N'')
UPDATE fsc_FileBinaries SET ContentTypeId = @DefaultContentTypeId WHERE ContentTypeId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeUpdate
	@ContentTypeId as int,
	@FriendlyName as nvarchar(50)
as
UPDATE CONTENT_TYPES
  SET FriendlyName = @FriendlyName
  WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeUpdateBigIconFileId
	@ContentTypeId as int,
	@BigIconFileId as int
AS
UPDATE CONTENT_TYPES SET BigIconFileId = @BigIconFileId
WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ContentTypeUpdateIconFileId
	@ContentTypeId as int,
	@IconFileId as int
AS
UPDATE CONTENT_TYPES SET IconFileId = @IconFileId
WHERE ContentTypeId = @ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Converter_RecalculateDateTypeValues
AS
DELETE DATE_TYPE_VALUES
INSERT INTO DATE_TYPE_VALUES (DateTypeId, ObjectId, DateValue)
 SELECT 1 AS DateTypeId, ProjectId AS ObjectId, TargetStartDate AS DateValue
 FROM PROJECTS
 WHERE TargetStartDate IS NOT NULL AND TargetStartDate > GETUTCDATE()
 UNION
 SELECT 2 AS DateTypeId, ProjectId AS ObjectId, TargetFinishDate AS DateValue
 FROM PROJECTS
 WHERE TargetFinishDate IS NOT NULL AND TargetFinishDate > GETUTCDATE()
 UNION
 SELECT 3 AS DateTypeId, EventId AS ObjectId, StartDate AS DateValue
 FROM EVENTS
 WHERE StartDate IS NOT NULL AND StartDate > GETUTCDATE()
 UNION
 SELECT 4 AS DateTypeId, EventId AS ObjectId, FinishDate AS DateValue
 FROM EVENTS
 WHERE FinishDate IS NOT NULL AND FinishDate > GETUTCDATE()
 UNION
 SELECT 5 AS DateTypeId, TaskId AS ObjectId, StartDate AS DateValue
 FROM TASKS
 WHERE StartDate IS NOT NULL AND StartDate > GETUTCDATE()
 UNION
 SELECT 6 AS DateTypeId, TaskId AS ObjectId, FinishDate AS DateValue
 FROM TASKS
 WHERE FinishDate IS NOT NULL AND FinishDate > GETUTCDATE()
 UNION
 SELECT 7 AS DateTypeId, ToDoId AS ObjectId, StartDate AS DateValue
 FROM TODO
 WHERE StartDate IS NOT NULL AND StartDate > GETUTCDATE()
 UNION
 SELECT 8 AS DateTypeId, ToDoId AS ObjectId, FinishDate AS DateValue
 FROM TODO
 WHERE FinishDate IS NOT NULL AND FinishDate > GETUTCDATE()
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Converter_RecalculateObjectStates
AS
SET NOCOUNT ON
DECLARE @Reason1 int, @Reason2 int
SET @Reason1 = 1
SET @Reason2 = 2
DECLARE @UpcomingState int, @ActiveState int, @OverdueState int, @SuspendedState int, @CompletedState int
SET @UpcomingState = 1
SET @ActiveState = 2
SET @OverdueState = 3
SET @SuspendedState = 4
SET @CompletedState = 5
DECLARE @UtcNow datetime
SET @UtcNow = GETUTCDATE()
UPDATE TASKS SET ActivationTypeId = 2
DECLARE @TaskId int, @StartDate datetime, @FinishDate datetime, @ActualFinishDate datetime, @IsCompleted bit, @ReasonId int
DECLARE tasks_cursor CURSOR FOR
  SELECT TaskId, StartDate, FinishDate, ActualFinishDate, IsCompleted, ReasonId FROM TASKS
OPEN tasks_cursor
FETCH NEXT FROM tasks_cursor INTO @TaskId, @StartDate, @FinishDate, @ActualFinishDate, @IsCompleted, @ReasonId
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @IsCompleted = 1
	BEGIN
		IF @ActualFinishDate IS NULL
			SET @ActualFinishDate = @FinishDate
		IF @ReasonId = @Reason1 OR @ReasonId = @Reason2
			UPDATE TASKS
			  SET StateId = @CompletedState, ActualFinishDate = @ActualFinishDate
			  WHERE TaskId = @TaskId
		ELSE
			UPDATE TASKS
			  SET StateId = @SuspendedState, ActualFinishDate = @ActualFinishDate
			  WHERE TaskId = @TaskId
	END
	ELSE
	BEGIN
		IF @StartDate > @UtcNow
			UPDATE TASKS
			  SET StateId = @UpcomingState, ActualFinishDate = NULL
			  WHERE TaskId = @TaskId
		ELSE IF @FinishDate <= @UtcNow
			UPDATE TASKS
			  SET StateId = @OverdueState, ActualFinishDate = NULL
			  WHERE TaskId = @TaskId
		ELSE
			UPDATE TASKS
			  SET StateId = @ActiveState, ActualFinishDate = NULL
			  WHERE TaskId = @TaskId
	END
	FETCH NEXT FROM tasks_cursor INTO @TaskId, @StartDate, @FinishDate, @ActualFinishDate, @IsCompleted, @ReasonId
END
CLOSE tasks_cursor
DEALLOCATE tasks_cursor
UPDATE TODO SET ActivationTypeId = 2
DECLARE @TodoId int
DECLARE todo_cursor CURSOR FOR
  SELECT TodoId, StartDate, FinishDate, ActualFinishDate, IsCompleted, ReasonId FROM TODO
OPEN todo_cursor
FETCH NEXT FROM todo_cursor INTO @TodoId, @StartDate, @FinishDate, @ActualFinishDate, @IsCompleted, @ReasonId
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @IsCompleted = 1
	BEGIN
		IF @ActualFinishDate IS NULL
			SET @ActualFinishDate = @FinishDate
		IF @ActualFinishDate IS NULL
			SET @ActualFinishDate = @UtcNow
		IF @ReasonId = @Reason1 OR @ReasonId = @Reason2
			UPDATE TODO
			  SET StateId = @CompletedState, ActualFinishDate = @ActualFinishDate
			  WHERE TodoId = @TodoId
		ELSE
			UPDATE TODO
			  SET StateId = @SuspendedState, ActualFinishDate = @ActualFinishDate
			  WHERE TodoId = @TodoId
	END
	ELSE
	BEGIN
		IF @StartDate IS NOT NULL AND @StartDate > @UtcNow
			UPDATE TODO
			  SET StateId = @UpcomingState, ActualFinishDate = NULL
			  WHERE TodoId = @TodoId
		ELSE IF @FinishDate IS NOT NULL AND @FinishDate <= @UtcNow
			UPDATE TODO
			  SET StateId = @OverdueState, ActualFinishDate = NULL
			  WHERE TodoId = @TodoId
		ELSE
			UPDATE TODO
			  SET StateId = @ActiveState, ActualFinishDate = NULL
			  WHERE TodoId = @TodoId
	END
	FETCH NEXT FROM todo_cursor INTO @TodoId, @StartDate, @FinishDate, @ActualFinishDate, @IsCompleted, @ReasonId
END
CLOSE todo_cursor
DEALLOCATE todo_cursor
DECLARE @EventId int
DECLARE event_cursor CURSOR FOR
  SELECT EventId, StartDate, FinishDate FROM EVENTS
OPEN event_cursor
FETCH NEXT FROM event_cursor INTO @EventId, @StartDate, @FinishDate
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @StartDate > @UtcNow
		UPDATE EVENTS
		  SET StateId = @UpcomingState
		  WHERE EventId = @EventId
	ELSE IF @FinishDate <= @UtcNow
		UPDATE EVENTS
		  SET StateId = @CompletedState
		  WHERE EventId = @EventId
	ELSE
		UPDATE EVENTS
		  SET StateId = @ActiveState
		  WHERE EventId = @EventId
	FETCH NEXT FROM event_cursor INTO @EventId, @StartDate, @FinishDate
END
CLOSE event_cursor
DEALLOCATE event_cursor
UPDATE INCIDENTS SET StateId = @UpcomingState WHERE StatusId = 1
UPDATE INCIDENTS SET StateId = @ActiveState WHERE StatusId = 2
UPDATE INCIDENTS SET StateId = @CompletedState WHERE StatusId > 2
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CopyDataFromMain
	@company_id int
AS
declare @tblName nvarchar(100)
declare @dropString nvarchar(500)
BEGIN TRAN
set @tblName= N'[dbo].[BACKUP_AUTH_LIST]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_BINARY_DATA]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_CHATS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_CHAT_MESS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_CHAT_USERS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_COMPANIES]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_CONTACT_LIST]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_DEPENDENCES]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_FILE]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_IMGROUPS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_SESSIONS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_USER]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
set @tblName= N'[dbo].[BACKUP_USER_MESS]'
if exists (select * from dbo.sysobjects where id = object_id(@tblName) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @dropString=N'drop table '+@tblName
exec sp_executesql @dropString
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_AUTH_LIST] FROM [ibn40_main].[dbo].[AUTH_LIST] AL WHERE
	EXISTS (SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE ( EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id])) AND (AL.[from_user_id]=U.[user_id] ) ) OR
	EXISTS (SELECT [user_id] FROM [ibn40_main].[dbo].[User]  U WHERE ( EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id])) AND (AL.[to_user_id]=U.[user_id]))
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_BINARY_DATA] FROM [ibn40_main].[dbo].[BINARY_DATA] BD WHERE
	EXISTS( SELECT [file_id] FROM [ibn40_main].[dbo].[File] F WHERE
		 ( EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND F.[from_user_id]=U.[user_id]) OR
		   EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND F.[to_user_id]=U.[user_id])
		)
		 AND BD.[fid] = F.[file_id]
	)
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_CHAT_MESS] FROM [ibn40_main].[dbo].[CHAT_MESS] CM WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
			EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND
		CM.[user_id]=U.[user_id])
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_CHAT_USERS]  FROM [ibn40_main].[dbo].[CHAT_USERS] CU WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id])
		AND CU.[user_id]=U.[user_id]
		)
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_CHATS] FROM [ibn40_main].[dbo].[CHATS] C WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id])
		AND C.[owner_id]=U.[user_id]
		)
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_CONTACT_LIST] FROM [ibn40_main].[dbo].[CONTACT_LIST] CL WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND CL.[user_id]=U.[user_id]) OR
	 EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND CL.[cont_user_id]=U.[user_id])
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_DEPENDENCES] FROM [ibn40_main].[dbo].[DEPENDENCES] D WHERE
	EXISTS(SELECT [imgroup_id] FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND D.[imgroup_id]=IG.[imgroup_id]) OR
	EXISTS(SELECT [imgroup_id] FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND D.[dep_imgroup_id]=IG.[imgroup_id])
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_FILE] FROM [ibn40_main].[dbo].[FILE] F WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[USER] U WHERE
		 EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND F.[from_user_id]=U.[user_id]) OR
	 EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[USER] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND F.[to_user_id]=U.[user_id])
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_SESSIONS] FROM [ibn40_main].[dbo].[SESSIONS] S WHERE
	EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND S.[user_id]=U.[user_id])
IF @@error<>0 goto err
SELECT *  INTO [dbo].[BACKUP_USER_MESS] FROM [ibn40_main].[dbo].[USER_MESS] UM WHERE
	EXISTS (SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND UM.[from_user_id]=U.[user_id]) OR
	 EXISTS(SELECT [user_id] FROM [ibn40_main].[dbo].[User] U WHERE
		EXISTS(SELECT imgroup_id FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id]) AND UM.[to_user_id]=U.[user_id])
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_USER] FROM [ibn40_main].[dbo].[USER] U WHERE
	EXISTS(SELECT [imgroup_id] FROM [ibn40_main].[dbo].[IMGROUPS] IG WHERE company_id = @company_id AND U.[imgroup_id]=IG.[imgroup_id])
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_IMGROUPS] FROM [ibn40_main].[dbo].[IMGROUPS] WHERE company_id = @company_id
IF @@error<>0 goto err
SELECT * INTO [dbo].[BACKUP_COMPANIES] FROM [ibn40_main].[dbo].[COMPANIES] WHERE company_id = @company_id
IF @@error<>0 goto err
err:
IF @@error<>0 ROLLBACK TRAN
ELSE COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CopyDataToMain
	@company_name nvarchar(100),
	@domain nvarchar(255),
	@retval int output
AS
BEGIN TRAN
INSERT INTO [ibn40_main].[dbo].[COMPANIES]
         (company_name, domain, db_name, app_id, description, contact_name, contact_phone, contact_email, support_name,  support_email, product_name,
          company_logo, theme, use_im, title1, title2, text1, text2, hp_image, max_users, max_external_users, is_global, creation_date, company_type, start_date, end_date, rate_per_user,
          is_active, max_disk_space, enable_alerts, show_admin_wizard)
SELECT @company_name as company_name, @domain as domain, db_name() as db_name, app_id, description, contact_name, contact_phone, contact_email, support_name,  support_email, product_name,
          company_logo, theme, use_im, title1, title2, text1, text2, hp_image, max_users, max_external_users, is_global, creation_date, company_type, start_date, end_date, rate_per_user,
          is_active, max_disk_space, enable_alerts, show_admin_wizard
  FROM [BACKUP_COMPANIES]
set @retval = (select ident_current('[ibn40_main].[dbo].[COMPANIES]'))
IF @@error!=0 GOTO err
IF (SELECT use_im FROM [BACKUP_COMPANIES])=1 BEGIN
	UPDATE [BACKUP_IMGROUPS] SET company_id=@retval
	IF @@error!=0 GOTO err
	declare @company_id int
	declare @imgroup_id int, @new_imgroup_id int
	declare @imgroup_name nvarchar(50)
	declare @color char(6)
	declare @logo_version int
	declare @is_internal bit
	declare @is_global bit
	DECLARE IMGroupsCursor CURSOR FOR
		SELECT IMGROUP_ID, COMPANY_ID, IMGROUP_NAME, COLOR, LOGO_VERSION, IS_INTERNAL, IS_GLOBAL FROM [BACKUP_IMGROUPS]
	OPEN IMGroupsCursor
	FETCH NEXT FROM IMGroupsCursor INTO @imgroup_id, @company_id, @imgroup_name, @color, @logo_version, @is_internal, @is_global
	WHILE @@fetch_status=0 BEGIN
		INSERT INTO [ibn40_main].[dbo].[IMGROUPS] (COMPANY_ID, IMGROUP_NAME, COLOR, LOGO_VERSION, IS_INTERNAL, IS_GLOBAL)
			VALUES (@company_id, @IMGROUP_NAME, @COLOR, @LOGO_VERSION, @IS_INTERNAL, @IS_GLOBAL)
		set @new_imgroup_id = (select ident_current('[ibn40_main].[dbo].[IMGROUPS]'))
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_USER] SET imgroup_id = @new_imgroup_id WHERE imgroup_id=@imgroup_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_DEPENDENCES] SET imgroup_id = @new_imgroup_id WHERE imgroup_id=@imgroup_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_DEPENDENCES] SET dep_imgroup_id = @new_imgroup_id WHERE dep_imgroup_id=@imgroup_id
		IF @@error!=0 GOTO err
		UPDATE USERS SET IMGroupID=@new_imgroup_id WHERE imgroupid=@imgroup_id
		IF @@error!=0 GOTO err
		UPDATE GROUPS SET IMGroupID = @new_imgroup_id WHERE IMGroupID = @imgroup_id
		IF @@error!=0 GOTO err
		UPDATE [ibn40_main].[dbo].[IMGROUPS] SET client_logo = Portal.client_logo
			FROM [ibn40_main].[dbo].[IMGROUPS] Main, BACKUP_IMGROUPS Portal WHERE Portal.imgroup_id=@imgroup_id AND Main.imgroup_id = @new_imgroup_id
		IF @@error!=0 GOTO err
		FETCH NEXT FROM IMGroupsCursor INTO @imgroup_id, @company_id, @imgroup_name, @color, @logo_version, @is_internal, @is_global
	END
	CLOSE IMGroupsCursor
	DEALLOCATE IMGroupsCursor
	declare @user_id int, @new_user_id int
	declare @first_name nvarchar(50)
	declare @last_name nvarchar(50)
	declare @login nvarchar(250)
	declare @password nvarchar(50)
	declare @email nvarchar(250)
	declare @is_active bit
	declare @stubs_version int
	DECLARE UsersCursor CURSOR FOR
		SELECT USER_ID, IMGROUP_ID, FIRST_NAME, LAST_NAME, LOGIN, [PASSWORD], EMAIL, IS_ACTIVE, stubs_version FROM [BACKUP_USER]
	OPEN UsersCursor
	FETCH NEXT FROM UsersCursor INTO @user_id, @imgroup_id, @first_name, @last_name, @login, @password, @email, @is_active, @stubs_version
	WHILE @@fetch_status=0 BEGIN
		INSERT INTO [ibn40_main].[dbo].[USER] (IMGROUP_ID, FIRST_NAME, LAST_NAME, LOGIN, [PASSWORD], EMAIL, IS_ACTIVE, stubs_version)
			VALUES (@imgroup_id, @first_name, @last_name, @login, @password, @email, @is_active, @stubs_version)
		set @new_user_id = (select ident_current('[ibn40_main].[dbo].[USER]'))
		IF @@error!=0 GOTO err
		UPDATE USERS SET OriginalID=@new_user_id WHERE OriginalID=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_AUTH_LIST] SET from_user_id = @new_user_id WHERE from_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_AUTH_LIST] SET to_user_id = @new_user_id WHERE to_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHAT_MESS] SET user_id = @new_user_id WHERE user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHAT_USERS] SET user_id = @new_user_id WHERE user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHAT_USERS] SET from_user_id = @new_user_id WHERE from_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHATS] SET owner_id = @new_user_id WHERE owner_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CONTACT_LIST] SET user_id = @new_user_id WHERE user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CONTACT_LIST] SET cont_user_id = @new_user_id WHERE cont_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_FILE] SET from_user_id = @new_user_id WHERE from_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_FILE] SET to_user_id = @new_user_id WHERE to_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_SESSIONS] SET user_id = @new_user_id WHERE user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_USER_MESS] SET from_user_id = @new_user_id WHERE from_user_id=@user_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_USER_MESS] SET to_user_id = @new_user_id WHERE to_user_id=@user_id
		IF @@error!=0 GOTO err
		FETCH NEXT FROM UsersCursor INTO @user_id, @imgroup_id, @first_name, @last_name, @login, @password, @email, @is_active, @stubs_version
	END
	CLOSE UsersCursor
	DEALLOCATE UsersCursor
	declare @chat_id int, @new_chat_id int
	declare @name nvarchar(50)
	declare @desc nvarchar(1000)
	declare @cuid char(36)
	declare @owner_id int
	declare @begin_time int
	declare @end_time int
	DECLARE ChatsCursor CURSOR FOR
		SELECT CHAT_ID, [NAME], [DESC], CUID, OWNER_ID, BEGIN_TIME, END_TIME FROM [BACKUP_CHATS]
	OPEN ChatsCursor
	FETCH NEXT FROM ChatsCursor INTO @chat_id, @name, @desc, @cuid, @owner_id, @begin_time, @end_time
	WHILE @@fetch_status=0 BEGIN
		INSERT INTO [ibn40_main].[dbo].[CHATS] ([NAME], [DESC], OWNER_ID, BEGIN_TIME, END_TIME)
			VALUES (@name, @desc, @owner_id, @begin_time, @end_time)
		set @new_chat_id = (select ident_current('[ibn40_main].[dbo].[CHATS]'))
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHAT_MESS] SET chat_id = @new_chat_id WHERE chat_id=@chat_id
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_CHAT_USERS] SET chat_id = @new_chat_id WHERE chat_id=@chat_id
		IF @@error!=0 GOTO err
		FETCH NEXT FROM ChatsCursor INTO @chat_id, @name, @desc, @cuid, @owner_id, @begin_time, @end_time
	END
	CLOSE ChatsCursor
	DEALLOCATE ChatsCursor
	declare @from_user_id int
	declare @to_user_id int
	declare @file_descr nvarchar(1024)
	declare @file_id char(36), @new_file_id char(36)
	declare @file_name nvarchar(255)
	declare @file_status int
	declare @file_date int
	declare @file_size int
	DECLARE FilesCursor CURSOR FOR
		SELECT [FROM_USER_ID], [TO_USER_ID], [FILE_DESCR], [FILE_ID], [FILE_NAME], [FILE_STATUS], [FILE_DATE], [FILE_SIZE] FROM [BACKUP_FILE]
	OPEN FilesCursor
	FETCH NEXT FROM FilesCursor INTO @from_user_id, @to_user_id, @file_descr, @file_id, @file_name, @file_status, @file_date, @file_size
	WHILE @@fetch_status=0 BEGIN
		set @new_file_id = (convert(char(36),newid()))
		INSERT INTO [ibn40_main].[dbo].[FILE] ([FROM_USER_ID], [TO_USER_ID], [FILE_ID], [FILE_DESCR], [FILE_NAME], [FILE_STATUS], [FILE_DATE], [FILE_SIZE])
			VALUES (@from_user_id, @to_user_id, @new_file_id, @file_descr, @file_name, @file_status, @file_date, @file_size)
		IF @@error!=0 GOTO err
		UPDATE [BACKUP_BINARY_DATA] SET fid = @new_file_id WHERE fid=@file_id
		IF @@error!=0 GOTO err
		FETCH NEXT FROM FilesCursor INTO @from_user_id, @to_user_id, @file_descr, @file_id, @file_name, @file_status, @file_date, @file_size
	END
	CLOSE FilesCursor
	DEALLOCATE FilesCursor
	INSERT INTO [ibn40_main].[dbo].[AUTH_LIST] (from_user_id, to_user_id, mess_text, deny_flag) SELECT from_user_id, to_user_id, mess_text, deny_flag FROM [BACKUP_AUTH_LIST]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[BINARY_DATA] (fid, filedata) SELECT fid, filedata FROM [BACKUP_BINARY_DATA]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[CHAT_MESS] (chat_id, mid, send_time, mess_text, [user_id]) SELECT chat_id, mid, send_time, mess_text, [user_id] FROM [BACKUP_CHAT_MESS]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[CHAT_USERS] (chat_id, [user_id], accepted, exited, user_status, invite_text, from_user_id, [time]) SELECT chat_id, [user_id], accepted, exited, user_status, invite_text, from_user_id, [time] FROM [BACKUP_CHAT_USERS]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[CONTACT_LIST] ([user_id], cont_user_id, list_type, has_authorization) SELECT [user_id], cont_user_id, list_type, has_authorization FROM [BACKUP_CONTACT_LIST]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[DEPENDENCES] (imgroup_id, dep_imgroup_id) SELECT imgroup_id, dep_imgroup_id FROM [BACKUP_DEPENDENCES]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[SESSIONS] ([user_id], dt_begin, dt_end) SELECT [user_id], dt_begin, dt_end FROM [BACKUP_SESSIONS]
	IF @@error!=0 GOTO err
	INSERT INTO [ibn40_main].[dbo].[USER_MESS] (from_user_id, to_user_id, mess_text, send_time, from_user_sid, to_user_sid) SELECT from_user_id, to_user_id, mess_text, send_time, from_user_sid, to_user_sid FROM [BACKUP_USER_MESS]
	IF @@error!=0 GOTO err
END
err:
IF @@error!=0 BEGIN
	ROLLBACK TRAN
	set @retval = 0
END
ELSE COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CurrencyAdd
	@CurrencySymbol as nvarchar(10)
AS
INSERT INTO CURRENCY (CurrencySymbol) VALUES(@CurrencySymbol)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CurrencyDelete
	@CurrencyId as int
as
DELETE FROM CURRENCY  WHERE CurrencyId = @CurrencyId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CurrencyGet
	@CurrencyId as int
as
SELECT CurrencyId, CurrencySymbol
  FROM CURRENCY
  WHERE @CurrencyId=0 OR CurrencyId = @CurrencyId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CurrencyGetForDictionaries
as
SELECT C.CurrencyId AS ItemId, C.CurrencySymbol AS ItemName,
	CASE WHEN
		EXISTS(SELECT * FROM PROJECTS P WHERE P.CurrencyId = C.CurrencyId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM CURRENCY C
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].CurrencyUpdate
	@CurrencyId as int ,
	@CurrencySymbol as nvarchar(10)
as
UPDATE CURRENCY SET CurrencySymbol=@CurrencySymbol
  WHERE CurrencyId = @CurrencyId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DatabaseGetSize
	@retval bigint output
as
SELECT @retval = [size] FROM [sysfiles] WHERE fileid=1
set @retval = @retval*8*1024
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeHookAdd
	@DateTypeId as int ,
	@ObjectId as int = null,
	@Lag as int ,
	@HandlerId as int ,
	@Params as nvarchar(1024) ,
	@retval int output
AS
INSERT INTO DATE_TYPE_HOOKS (DateTypeId, ObjectId, Lag, HandlerId, Params)
  VALUES(@DateTypeId, @ObjectId, @Lag, @HandlerId, @Params)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeHookDelete
	@HookId int
AS
DELETE FROM  DATE_TYPE_HOOKS WHERE HookId = @HookId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeHookGet
	@HookId int
AS
SELECT H.HookId, H.DateTypeId, H.ObjectId, H.Lag, H.HandlerId, H.Params, T.ObjectTypeId
  FROM DATE_TYPE_HOOKS H
	JOIN DATE_TYPES T ON (H.DateTypeId = T.DateTypeId)
  WHERE H.HookId = @HookId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeHookUpdate
	@HookId int,
	@Lag as int
AS
UPDATE DATE_TYPE_HOOKS SET Lag = @Lag WHERE HookId = @HookId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeProcessedAdd
	@ValueId as int ,
	@HookId as int ,
	@DateValue as datetime ,
	@Lag as int
as
IF EXISTS (SELECT * FROM DATE_TYPE_VALUES WHERE ValueId = @ValueId)
	INSERT INTO DATE_TYPE_PROCESSED (ValueId, HookId, DateValue, Lag) VALUES(@ValueId, @HookId, @DateValue, @Lag)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypesGetByObjectType
	@ObjectTypeId as int
as
SELECT DateTypeId, ObjectTypeId, DateTypeName
  FROM DATE_TYPES
  WHERE ObjectTypeId = @ObjectTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueAdd
	@DateTypeId as int ,
	@ObjectId as int ,
	@DateValue as datetime ,
	@retval int output
as
	INSERT INTO DATE_TYPE_VALUES (DateTypeId, ObjectId, DateValue) VALUES(@DateTypeId, @ObjectId, @DateValue)
	SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueAddNew
	@DateTypeId as int ,
	@ObjectId as int ,
	@DateValue as datetime
as
IF NOT EXISTS(SELECT * FROM DATE_TYPE_VALUES WHERE DateTypeId = @DateTypeId AND ObjectId = @ObjectId AND DateValue = @DateValue)
	INSERT INTO DATE_TYPE_VALUES (DateTypeId, ObjectId, DateValue) VALUES(@DateTypeId, @ObjectId, @DateValue)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueDelete
	@DateTypeId as int ,
	@ObjectId as int
as
DELETE FROM DATE_TYPE_VALUES WHERE DateTypeId = @DateTypeId AND ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueDeleteByDate
	@DateTypeId as int ,
	@ObjectId as int,
	@DateValue datetime
as
DELETE FROM DATE_TYPE_VALUES WHERE DateTypeId = @DateTypeId AND ObjectId = @ObjectId AND DateValue = @DateValue
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueDeleteByValueId
	@ValueId as int
as
DELETE FROM DATE_TYPE_VALUES WHERE ValueId = @ValueId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DateTypeValueUpdate
	@DateTypeId int,
	@ObjectId int,
	@DateValue datetime,
	@retval int output
AS
SELECT @retval = ValueId FROM DATE_TYPE_VALUES WHERE DateTypeId = @DateTypeId AND ObjectId = @ObjectId
IF @retval IS NOT NULL
	UPDATE DATE_TYPE_VALUES SET DateValue = @DateValue WHERE ValueId = @retval
ELSE
BEGIN
	INSERT INTO DATE_TYPE_VALUES (DateTypeId, ObjectId, DateValue) VALUES(@DateTypeId, @ObjectId, @DateValue)
	SELECT @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DeclinedRequestsGet
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT T.ToDoId AS ObjectId, 6 AS ObjectTypeId, T.Title, T.PriorityId, PL.PriorityName, R.LastSavedDate, R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM TODO T
	JOIN PRIORITY_LANGUAGE PL ON (T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN TODO_RESOURCES R ON (T.ToDoId = R.ToDoId AND R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ManagerId = @UserId
	AND T.IsCompleted=0
UNION ALL
SELECT T.TaskId AS ObjectId, 5 AS ObjectTypeId, T.Title, T.PriorityId, PL.PriorityName, R.LastSavedDate, R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PL ON (T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN TASK_RESOURCES R ON (T.TaskId = R.TaskId AND R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND P.ManagerId = @UserId
	AND T.IsCompleted=0  AND T.IsSummary = 0 AND T.IsMilestone = 0
UNION ALL
SELECT D.DocumentId AS ObjectId, 16 AS ObjectTypeId, D.Title, D.PriorityId, PL.PriorityName, R.LastSavedDate, R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM DOCUMENTS D
	JOIN PRIORITY_LANGUAGE PL ON (D.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN DOCUMENT_RESOURCES R ON (D.DocumentId = R.DocumentId AND R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE (@ProjectId = 0 OR D.ProjectId = @ProjectId)
	AND D.ManagerId = @UserId
	AND D.IsCompleted=0
UNION ALL
SELECT I.IncidentId AS ObjectId, 7 AS ObjectTypeId, I.Title, I.PriorityId, PL.PriorityName, R.LastSavedDate, R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM INCIDENTS I
	JOIN PRIORITY_LANGUAGE PL ON (I.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN INCIDENT_RESOURCES R ON (I.IncidentId = R.IncidentId AND R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE (@ProjectId = 0 OR I.ProjectId = @ProjectId)
	AND I.ManagerId = @UserId
	AND I.StateId < 4
UNION ALL
SELECT E.EventId AS ObjectId, 4 AS ObjectTypeId, E.Title, E.PriorityId, PL.PriorityName, R.LastSavedDate, R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM EVENTS E
	JOIN PRIORITY_LANGUAGE PL ON (E.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN EVENT_RESOURCES R ON (E.EventId = R.EventId AND R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE (@ProjectId = 0 OR E.ProjectId = @ProjectId)
	AND E.ManagerId = @UserId
	AND E.StateId < 4
ORDER BY R.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DirectoryIsAssignedByPop3MessageHandler
	@DirectoryId INT,
	@Retval INT OUT
AS
	SET @Retval = 0
	IF EXISTS(SELECT * FROM Pop3BoxPop3DocumentHandler PDH
			JOIN Pop3BoxParameters PP ON PP.Pop3BoxId = PDH.Pop3BoxId
			WHERE PDH.HandlerName = N'File.Pop3MessageHandler'
					AND
				PP.Name = N'FolderId'
					AND
				PP.Value = CAST(@DirectoryId AS NVARCHAR(10)) )
		SET @Retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionAdd
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@CreatorId as int ,
	@CreationDate as datetime ,
	@Text as ntext,
	@retval int output
AS
INSERT INTO DISCUSSIONS (ObjectTypeId, ObjectId, CreatorId, CreationDate, [Text])
  VALUES(@ObjectTypeId, @ObjectId, @CreatorId, @CreationDate, @Text)
SET @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionGet
	@DiscussionId as int
as
SELECT D.DiscussionId, D.ObjectTypeId, D.ObjectId, D.CreatorId, D.CreationDate,
	D.[Text], U.LastName + ', ' + U.FirstName AS CreatorName
  FROM DISCUSSIONS D
	JOIN USERS U ON (D.CreatorId = U.PrincipalId)
  WHERE D.DiscussionId = @DiscussionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM DISCUSSIONS WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsGet
	@ObjectTypeId as int,
	@ObjectId as int
as
SELECT D.DiscussionId, D.ObjectTypeId, D.ObjectId, D.CreatorId, 	D.CreationDate,
	D.[Text], U.LastName + ', ' + U.FirstName AS CreatorName
  FROM DISCUSSIONS D
	JOIN USERS U ON (D.CreatorId = U.PrincipalId)
  WHERE D.ObjectTypeId = @ObjectTypeId AND D.ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsGetByIncident
	@IncidentId as int
as
DECLARE @ToDoType int
SET @ToDoType = 6
DECLARE @IncidentType int
SET @IncidentType = 7
SELECT D.DiscussionId, D.ObjectTypeId, D.ObjectId, D.CreatorId, 	D.CreationDate,
	D.[Text], U.LastName + ', ' + U.FirstName AS CreatorName
  FROM DISCUSSIONS D
	JOIN USERS U ON (D.CreatorId = U.PrincipalId)
  WHERE (D.ObjectTypeId = @IncidentType AND D.ObjectId = @IncidentId)
	OR
	(D.ObjectTypeId = @ToDoType AND D.ObjectId IN
		(SELECT ToDoId FROM INCIDENT_TODO WHERE IncidentId = @IncidentId))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsGetByTask
	@TaskId as int
as
DECLARE @ToDoType int
SET @ToDoType = 6
DECLARE @TaskType int
SET @TaskType = 5
SELECT D.DiscussionId, D.ObjectTypeId, D.ObjectId, D.CreatorId, 	D.CreationDate,
	D.[Text], U.LastName + ', ' + U.FirstName AS CreatorName
  FROM DISCUSSIONS D
	JOIN USERS U ON (D.CreatorId = U.PrincipalId)
  WHERE (D.ObjectTypeId = @TaskType AND D.ObjectId = @TaskId)
	OR
	(D.ObjectTypeId = @ToDoType AND D.ObjectId IN
		(SELECT ToDoId FROM TASK_TODO WHERE TaskId = @TaskId))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsGetByToDo
	@ToDoId as int
as
DECLARE @TaskType int
SET @TaskType = 5
DECLARE @ToDoType int
SET @ToDoType = 6
DECLARE @IncidentType int
SET @IncidentType = 7
SELECT D.DiscussionId, D.ObjectTypeId, D.ObjectId, D.CreatorId, 	D.CreationDate,
	D.[Text], U.LastName + ', ' + U.FirstName AS CreatorName
  FROM DISCUSSIONS D
	JOIN USERS U ON (D.CreatorId = U.PrincipalId)
  WHERE (D.ObjectTypeId = @ToDoType AND D.ObjectId = @ToDoId)
	OR
	(D.ObjectTypeId = @IncidentType AND D.ObjectId IN
		(SELECT IncidentId FROM INCIDENT_TODO WHERE ToDoId = @ToDoId))
	OR
	(D.ObjectTypeId = @TaskType AND D.ObjectId IN
		(SELECT TaskId FROM TASK_TODO WHERE ToDoId = @ToDoId))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE DISCUSSIONS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionsReplaceUnchangeableUserToManager
	@UserId as int
as
DECLARE @ProjectType int
DECLARE @EventType int
DECLARE @TaskType int
DECLARE @ToDoType int
DECLARE @IncidentType int
DECLARE @DocumentType int
SET @ProjectType = 3
SET @EventType = 4
SET @TaskType = 5
SET @ToDoType = 6
SET @IncidentType = 7
SET @DocumentType = 16
BEGIN TRAN
	UPDATE DISCUSSIONS
	  SET CreatorId = P.ManagerId
	  FROM DISCUSSIONS D, PROJECTS P
	  WHERE D.ObjectId = P.ProjectId AND D.ObjectTypeId = @ProjectType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE DISCUSSIONS
	  SET CreatorId = E.ManagerId
	  FROM DISCUSSIONS D, EVENTS E
	  WHERE D.ObjectId = E.EventId AND D.ObjectTypeId = @EventType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE DISCUSSIONS
	  SET CreatorId = P.ManagerId
	  FROM DISCUSSIONS D, TASKS T, PROJECTS P
	  WHERE D.ObjectId = T.TaskId AND T.ProjectId = P.ProjectId AND D.ObjectTypeId = @TaskType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE DISCUSSIONS
	  SET CreatorId = T.ManagerId
	  FROM DISCUSSIONS D, TODO T
	  WHERE D.ObjectId = T.ToDoId AND D.ObjectTypeId = @ToDoType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE DISCUSSIONS
	  SET CreatorId = I.ManagerId
	  FROM DISCUSSIONS D, INCIDENTS I
	  WHERE D.ObjectId = I.IncidentId AND D.ObjectTypeId = @IncidentType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE DISCUSSIONS
	  SET CreatorId = DOC.ManagerId
	  FROM DISCUSSIONS D, DOCUMENTS DOC
	  WHERE D.ObjectId = DOC.DocumentId AND D.ObjectTypeId = @DocumentType AND D.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DiscussionUpdate
	@DiscussionId as int ,
	@Text as ntext
AS
UPDATE DISCUSSIONS SET [Text] = @Text
  WHERE DiscussionId = @DiscussionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentCreate
	@ProjectId as int=null ,
	@CreatorId as int ,
	@ManagerId as int,
	@Title as nvarchar(255) ,
	@Description as ntext,
	@CreationDate as datetime ,
	@PriorityId as int ,
	@StatusId as int ,
	@TaskTime int,
	@retval int output
as
INSERT INTO DOCUMENTS (ProjectId, CreatorId, ManagerId, Title, [Description], CreationDate, PriorityId, StatusId, TaskTime)
  VALUES(@ProjectId, @CreatorId, @ManagerId, @Title, @Description, @CreationDate, @PriorityId, @StatusId, @TaskTime)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentDelete
	@DocumentId as int
as
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @DocumentObjectType AND ObjectId = @DocumentId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @DocumentObjectType AND ObjectId = @DocumentId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @DocumentObjectType AND ObjectId = @DocumentId
	IF @@ERROR != 0
		GOTO err
	DELETE DOCUMENT_RESOURCES WHERE DocumentId = @DocumentId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @DocumentObjectType AND ObjectId = @DocumentId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @DocumentId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @DocumentObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM DOCUMENTS  WHERE DocumentId = @DocumentId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentGet
	@DocumentId as int,
	@LanguageId as int
as
SELECT D.DocumentId, D.ProjectId, P.Title AS ProjectTitle, D.CreatorId, D.ManagerId, D.Title, D.[Description],
	D.CreationDate, D.PriorityId, PR.PriorityName, D.StatusId, S.StatusName, D.IsCompleted, D.ReasonId, D.StateId, OS.StateName, D.TaskTime
  FROM DOCUMENTS D
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (D.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN DOCUMENT_STATUS S ON (D.StatusId = S.StatusId)
	JOIN OBJECT_STATE_LANGUAGE OS ON (D.StateId = OS.StateId AND OS.LanguageId = @LanguageId)
  WHERE D.DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentGetIsCompleted
	@DocumentId as int,
	@retval int output
as
IF EXISTS(SELECT * FROM DOCUMENTS WHERE DocumentId = @DocumentId AND IsCompleted = 0)
	SET @retval = 0
ELSE
	SET @retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentGetProject
	@DocumentId as int,
	@Retval as int output
AS
SELECT @Retval = ProjectId FROM DOCUMENTS WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentGetSecurityForUser
	@DocumentId as int,
	@UserId as int
as
SELECT DocumentId, PrincipalId, IsManager, IsResource, IsRealDocumentResource
   FROM DOCUMENT_SECURITY_ALL
  WHERE DocumentId = @DocumentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentGetTitle
	@DocumentId as int
as
SELECT Title FROM DOCUMENTS  WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentManagerGet
	@DocumentId as int,
	@retval int output
as
SELECT @retval = ManagerId
  FROM DOCUMENTS
  WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentManagersGet
as
SELECT DISTINCT D.ManagerId AS UserId, U.LastName + ', ' + U.FirstName AS UserName, U.FirstName +' '+U.LastName AS UserName2
  FROM DOCUMENTS D
	JOIN USERS U ON (D.ManagerId = U.PrincipalId)
  ORDER BY 2
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentRecalculateState
	@DocumentId INT
 AS
DECLARE @StateId INT
DECLARE @NewStateId INT
DECLARE @ActivationTypeId INT
DECLARE @ActivatedManually INT
DECLARE @ReasonId INT
DECLARE @IsCompleted INT
SELECT @IsCompleted = [IsCompleted],
	@ReasonId = [ReasonId],
	@ActivatedManually = [ActivatedManually],
	@ActivationTypeId = [ActivationTypeId],
	@StateId = [StateId]
FROM DOCUMENTS
WHERE DocumentId = @DocumentId
SET @NewStateId = 1
IF @IsCompleted = 1
BEGIN
	IF @ReasonId = 1  OR @ReasonId = 2 /*completed auto*/
	   SET @NewStateId = 5
	IF @ReasonId = 3  OR @ReasonId = 4 /*suspended auto*/
	   SET @NewStateId = 4
END
ELSE IF @ActivatedManually = 1 OR @ActivationTypeId = 1  OR @ActivationTypeId = 2 /*auto no check*/
	SET @NewStateId = 2
UPDATE DOCUMENTS
SET  StateId= @NewStateId
WHERE DocumentId = @DocumentId AND @StateId != @NewStateId
SELECT @StateId As OldStateId, @NewStateId as NewStateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentResourceAdd
	@DocumentId as int ,
	@PrincipalId as int ,
	@MustBeConfirmed as bit,
	@CanManage as bit
as
IF EXISTS(SELECT * FROM DOCUMENT_RESOURCES WHERE DocumentId = @DocumentId AND PrincipalId = @PrincipalId)
	UPDATE DOCUMENT_RESOURCES
	  SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
	  WHERE DocumentId = @DocumentId AND PrincipalId = @PrincipalId
ELSE
	INSERT INTO DOCUMENT_RESOURCES (DocumentId, PrincipalId, MustBeConfirmed, CanManage)
	  VALUES(@DocumentId, @PrincipalId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentResourceDelete
	@DocumentId as int ,
	@PrincipalId as int
as
DELETE FROM DOCUMENT_RESOURCES WHERE DocumentId = @DocumentId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentResourceGetByUser
	@DocumentId as int,
	@UserId as int
as
SELECT MustBeConfirmed, ResponsePending, IsConfirmed
  FROM DOCUMENT_RESOURCES
  WHERE DocumentId = @DocumentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentResourceReply
	@DocumentId as int,
	@UserId as int,
	@IsConfirmed as bit,
	@LastSavedDate as datetime
as
UPDATE DOCUMENT_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = @LastSavedDate
  WHERE DocumentId = @DocumentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentResourcesGet
	@DocumentId as int
as
SELECT DR.ResourceId, DR.DocumentId, DR.PrincipalId, P.IsGroup, DR.MustBeConfirmed, DR.ResponsePending, DR.IsConfirmed, DR.CanManage, DR.LastSavedDate,
	CASE WHEN U.IsExternal = 1 THEN 1 ELSE 0 END AS IsExternal
  FROM DOCUMENT_RESOURCES DR
	JOIN PRINCIPALS P ON (DR.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (DR.PrincipalId = U.PrincipalId)
  WHERE DR.DocumentId = @DocumentId
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM DOCUMENT_RESOURCES WHERE PrincipalId = @UserId)
	SET @Retval = 1
ELSE BEGIN
	IF EXISTS (SELECT * FROM DOCUMENTS WHERE ManagerId = @UserId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM DOCUMENTS WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsDeleteByProject
	@ProjectId as int
as
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
DELETE DISCUSSIONS WHERE ObjectTypeId = @DocumentObjectType AND ObjectId IN
	(SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId)
DELETE EXTERNAL_GATE WHERE ObjectTypeId = @DocumentObjectType AND ObjectId IN
	(SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId)
DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @DocumentObjectType AND ObjectId IN
	(SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId)
DELETE DOCUMENT_RESOURCES WHERE DocumentId IN
	(SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId)
DELETE FAVORITES WHERE ObjectTypeId = @DocumentObjectType AND ObjectId IN
	(SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId)
DELETE SUBSCRIPTIONS WHERE ObjectId IN (SELECT DocumentId FROM DOCUMENTS WHERE ProjectId = @ProjectId) AND
	EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @DocumentObjectType)
DELETE FROM DOCUMENTS  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetActiveByUserOnly
	@UserId as int,
	@LanguageId as int
as
DECLARE @ActiveState int, @OverdueState int
SET @ActiveState = 2
SET @OverdueState = 3
SELECT D.DocumentId, D.Title, D.CreationDate, D.PriorityId, P.PriorityName, A.IsRealDocumentManager AS IsManager, A.IsRealDocumentResource AS IsResource, D.IsCompleted, D.ReasonId, D.CreatorId
  FROM DOCUMENTS D, PRIORITY_LANGUAGE P, DOCUMENT_SECURITY_ALL A
  WHERE (D.StateId = @ActiveState OR D.StateId = @OverdueState)
	AND D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND D.DocumentId = A.DocumentId AND A.PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetByFilter
	@ProjectId as int,
	@ManagerId as int,
	@ResourceId as int,
	@PriorityId as int,
	@StatusId as int,
	@Keyword as nvarchar(100),
	@UserId as int,
	@LanguageId as int,
	@CategoryType as int
as
SET @Keyword = '%' + @Keyword + '%'
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
SELECT D.DocumentId, D.ProjectId, P.Title AS ProjectTitle,
	D.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,
	D.ManagerId, U2.LastName + ', ' + U2.FirstName AS ManagerName,
	D.Title, D.CreationDate, D.PriorityId, PR.PriorityName, D.StatusId, S.StatusName, D.IsCompleted, D.StateId,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM DOCUMENTS D
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (D.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN DOCUMENT_STATUS S ON (D.StatusId = S.StatusId)
	JOIN USERS U1 ON (D.CreatorId = U1.PrincipalId)
	JOIN USERS U2 ON (D.ManagerId = U2.PrincipalId)
  WHERE
	(@ProjectId = 0 OR D.ProjectId = @ProjectId OR (@ProjectId = -1 AND D.ProjectId IS NULL))
	AND (@ManagerId = 0 OR D.DocumentId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL WHERE PrincipalId = @ManagerId AND IsManager = 1))
	AND (@ResourceId = 0 OR D.DocumentId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL WHERE PrincipalId = @ResourceId AND IsResource = 1))
	AND (@PriorityId = -1 OR D.PriorityId = @PriorityId)
	AND (@StatusId = 0 OR D.StatusId = @StatusId)
	AND (D.Title LIKE @Keyword OR D.[Description] LIKE @Keyword)
	AND
	(	@IsPPM = 1 OR @IsExec = 1
		OR D.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR D.DocumentId IN
			(SELECT DocumentId FROM DOCUMENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsResource = 1)
			)
	)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND D.DocumentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType = 2 AND D.DocumentId NOT IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType < 0 AND D.DocumentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType AND CategoryId = -@CategoryType
			)
	)
  ORDER BY ProjectTitle
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetByFilterGroupedByProject
	@ProjectId as int,
	@ManagerId as int,
	@ResourceId as int,
	@PriorityId as int,
	@StatusId as int,
	@Keyword as nvarchar(100),
	@UserId as int,
	@LanguageId as int,
	@CategoryType as int
as
SET @Keyword = '%' + @Keyword + '%'
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
DECLARE @Documents
	TABLE (DocumentId int, ProjectId int, ProjectTitle nvarchar(255), CreatorId int, CreatorName nvarchar(102), ManagerId int, ManagerName nvarchar(102),
		Title nvarchar(255), CreationDate DateTime, PriorityId int, PriorityName nvarchar(50),
		StatusId int, StatusName nvarchar(50), IsCompleted bit, StateId int, CanEdit int, CanDelete int)
INSERT INTO @Documents
SELECT D.DocumentId, D.ProjectId, P.Title AS ProjectTitle,
	D.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,
	D.ManagerId, U2.LastName + ', ' + U2.FirstName AS ManagerName,
	D.Title, D.CreationDate, D.PriorityId, PR.PriorityName, D.StatusId, S.StatusName, D.IsCompleted, D.StateId,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM DOCUMENTS D
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (D.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN DOCUMENT_STATUS S ON (D.StatusId = S.StatusId)
	JOIN USERS U1 ON (D.CreatorId = U1.PrincipalId)
	JOIN USERS U2 ON (D.ManagerId = U2.PrincipalId)
  WHERE
	(@ProjectId = 0 OR D.ProjectId = @ProjectId OR (@ProjectId = -1 AND D.ProjectId IS NULL))
	AND (@ManagerId = 0 OR D.DocumentId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL WHERE PrincipalId = @ManagerId AND IsManager = 1))
	AND (@ResourceId = 0 OR D.DocumentId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL WHERE PrincipalId = @ResourceId AND IsResource = 1))
	AND (@PriorityId = -1 OR D.PriorityId = @PriorityId)
	AND (@StatusId = 0 OR D.StatusId = @StatusId)
	AND (D.Title LIKE @Keyword OR D.[Description] LIKE @Keyword)
	AND
	(	@IsPPM = 1 OR @IsExec = 1
		OR D.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR D.DocumentId IN
			(SELECT DocumentId FROM DOCUMENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsResource = 1)
			)
	)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND D.DocumentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType = 2 AND D.DocumentId NOT IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType < 0 AND D.DocumentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @DocumentObjectType AND CategoryId = -@CategoryType
			)
	)
DECLARE @CollapseNonProjectDocument bit
SET @CollapseNonProjectDocument = 0
IF EXISTS (SELECT * FROM COLLAPSED_DOCUMENTS WHERE UserId = @UserId AND ProjectId = -1)
	SET @CollapseNonProjectDocument = 1
SELECT DISTINCT CASE WHEN D.ProjectId IS NULL THEN -1 ELSE D.ProjectId END AS ProjectId,
	CASE WHEN ProjectTitle IS NULL THEN '' ELSE ProjectTitle END AS ProjectTitle,
	0 as DocumentId, '' as Title, 0 as CreatorId, '' as CreatorName, 0 as ManagerId, '' as ManagerName,
	NULL as CreationDate, -1 as PriorityId, '' as PriorityName,
	0 as StatusId, '' as StatusName, 0 AS StateId, 0 as IsCompleted, 0 as CanEdit, 0 as CanDelete, CAST (1 as bit) AS IsProject,
	CASE WHEN
		(CD.ProjectId IS NULL  AND D.ProjectId IS NOT NULL)
		OR
		(D.ProjectId IS NULL AND @CollapseNonProjectDocument = 0)
	THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsCollapsed
  FROM @Documents D
		LEFT JOIN COLLAPSED_DOCUMENTS CD ON (D.ProjectId = CD.ProjectId AND CD.UserId = @UserId)
UNION ALL
SELECT CASE WHEN D.ProjectId IS NULL THEN -1 ELSE D.ProjectId END AS ProjectId,
	CASE WHEN ProjectTitle IS NULL THEN '' ELSE ProjectTitle END AS ProjectTitle,
	DocumentId, Title, CreatorId, CreatorName, ManagerId, ManagerName, CreationDate, PriorityId, PriorityName,
	StatusId, StatusName, IsCompleted, StateId, CanEdit, CanDelete, CAST (0 as bit) AS IsProject, CAST(0 as bit) as IsCollapsed
  FROM @Documents D
	LEFT JOIN COLLAPSED_DOCUMENTS CD ON (D.ProjectId = CD.ProjectId AND CD.UserId = @UserId)
  WHERE
	(CD.ProjectId IS NULL  AND D.ProjectId IS NOT NULL)
	OR
	(D.ProjectId IS NULL AND @CollapseNonProjectDocument = 0)
ORDER BY ProjectTitle, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT D.DocumentId, D.ProjectId, P.Title AS ProjectTitle,
	D.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,
	D.ManagerId, U2.LastName + ', ' + U2.FirstName AS ManagerName,
	D.Title, D.CreationDate, D.PriorityId, PR.PriorityName, D.StatusId, S.StatusName, D.IsCompleted, D.StateId,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM DOCUMENTS D
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (D.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN DOCUMENT_STATUS S ON (D.StatusId = S.StatusId)
	JOIN USERS U1 ON (D.CreatorId = U1.PrincipalId)
	JOIN USERS U2 ON (D.ManagerId = U2.PrincipalId)
  WHERE
	(@ProjectId = 0 OR D.ProjectId = @ProjectId OR (@ProjectId = -1 AND D.ProjectId IS NULL))
	AND
	(@IsPPM = 1 OR @IsExec = 1
		OR D.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR D.DocumentId IN
			(SELECT DocumentId FROM DOCUMENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsResource = 1)
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT D.DocumentId, D.Title, D.IsCompleted, D.ReasonId, D.StateId,
	CASE WHEN D.ManagerId = @UserId THEN 1 ELSE 0 END AS IsManager,
	CASE WHEN DR.ResourceId IS NOT NULL THEN 1 ELSE 0 END AS IsResource,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR S.IsManager = 1 OR S.IsResource = 1 THEN 1 ELSE 0 END AS CanView,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @CurrentUserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR D.ManagerId = @CurrentUserId THEN 1 ELSE 0 END AS CanDelete
  FROM DOCUMENTS D
	LEFT JOIN DOCUMENT_SECURITY_ALL S ON (D.DocumentId = S.DocumentId AND S.PrincipalId = @CurrentUserId)
	LEFT JOIN DOCUMENT_RESOURCES DR ON (D.DocumentId = DR.DocumentId AND DR.PrincipalId = @UserId)
  WHERE D.ManagerId = @UserId OR DR.ResourceId IS NOT NULL
  ORDER BY D.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetForManagerView
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
SELECT  D.DocumentId AS ItemId, D.Title, D.PriorityId, P.PriorityName, 16 AS ItemType, D.CreationDate, D.CreationDate as StartDate, D.ClosedDate as FinishDate, 0 as PercentCompleted, D.IsCompleted,
	D.ManagerId, D.ReasonId, D.ProjectId, D.StateId, 0 as CompletionTypeId
  FROM DOCUMENTS D, PRIORITY_LANGUAGE P
  WHERE (@ManagerId=0 OR D.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR D.ProjectId=@ProjectId)
	AND D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND
	(
	((@StartDate is not null)AND(D.CreationDate<=@StartDate)AND(D.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(D.ClosedDate>=@CompletedDate)AND(D.IsCompleted=1))
	OR((@ShowActive=1 AND (D.StateId=@ActiveState OR D.StateId=@OverdueState)))
	)
	AND
	(
		@PrincipalId = 1
	OR
		DocumentId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL
				WHERE IsRealDocumentResource = 1 AND (PrincipalId = @PrincipalId OR PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId))
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetForResourceView
	@UserId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
 SELECT DISTINCT D.DocumentId AS ItemId, D.Title, D.PriorityId, P.PriorityName, 16 AS ItemType, D.CreationDate, D.CreationDate as StartDate, D.ClosedDate as FinishDate, 0 as PercentCompleted, D.IsCompleted,
	D.ManagerId, D.ReasonId, D.ProjectId, PR.Title as ProjectTitle, D.StateId, 0 as CompletionTypeId
  FROM DOCUMENTS D
  LEFT JOIN PROJECTS PR ON D.ProjectId=PR.ProjectId
  JOIN DOCUMENT_SECURITY_ALL DS ON (D.DocumentId = DS.DocumentId AND DS.IsRealDocumentResource=1 AND DS.PrincipalId = @UserId)
  JOIN PRIORITY_LANGUAGE P ON (D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE  (@ManagerId=0 OR D.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR D.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(D.CreationDate<=@StartDate)AND(D.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(D.ClosedDate>=@CompletedDate)AND(D.IsCompleted=1))
	OR((@ShowActive=1 AND (D.StateId=@ActiveState OR D.StateId=@OverdueState)))
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetNotAssigned
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT D.DocumentId, D.Title, D.PriorityId, PR.PriorityName, D.StatusId, S.StatusName, D.CreationDate, D.CreatorId, D.StateId
  FROM DOCUMENTS D
	JOIN PRIORITY_LANGUAGE PR ON (D.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN DOCUMENT_STATUS S ON (D.StatusId = S.StatusId)
  WHERE (@ProjectId = 0 OR D.ProjectId = @ProjectId)
	AND D.IsCompleted=0
	AND D.ManagerId = @UserId
	AND D.DocumentId NOT IN (SELECT DocumentId FROM DOCUMENT_TODO)
	AND D.DocumentId NOT IN (SELECT DocumentId FROM DOCUMENT_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetPending
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT D.DocumentId, D.Title, D.[Description], D.PriorityId, P.PriorityName, D.ManagerId, D.CreationDate, D.StateId
  FROM DOCUMENTS D, DOCUMENT_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR D.ProjectId = @ProjectId)
	AND D.DocumentId = R.DocumentId AND R.PrincipalId = @UserId
	AND D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND D.IsCompleted = 0
	AND (R.MustBeConfirmed=1 AND R.ResponsePending=1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetSimple
	@ProjectId as int,
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit
as
SELECT DocumentId, Title
  FROM DOCUMENTS D
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId OR (@ProjectId = -1 AND ProjectId IS NULL))
	AND
	(
		(@GetAssigned = 1 AND DocumentId IN
			(SELECT DocumentId FROM DOCUMENT_RESOURCES R WHERE PrincipalId = @UserId
				AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)))
		OR
		(@GetManaged =1 AND ManagerId = @UserId)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetUpdatedByUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT D.DocumentId, D.Title, D.StateId, A.LastSavedDate
  FROM DOCUMENTS D,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @DocumentObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE D.DocumentId = A.ObjectId
	AND (@ProjectId = 0 OR D.ProjectId = @ProjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
  ORDER BY A.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsGetUpdatedForUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
DECLARE @DocumentObjectType int
SET @DocumentObjectType = 16
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT DocumentId, Title, CreatorId, ManagerId, LastEditorId, LastSavedDate, ProjectId, ProjectName, StateId
FROM
(
	SELECT D.DocumentId, D.Title, D.CreatorId, D.ManagerId, ISNULL(D.ProjectId, -1) AS ProjectId, ISNULL(P.Title, '') AS ProjectName,
		SE.UserId AS LastEditorId, SE.Dt AS LastSavedDate, D.StateId
	  FROM DOCUMENTS D
		JOIN SYSTEM_EVENTS SE ON (D.DocumentId = SE.ObjectId)
		LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	  WHERE (@ProjectId = 0 OR D.ProjectId = @ProjectId)
		AND
		(@IsPPM_Exec = 1
			OR D.ProjectId IN
				(SELECT ProjectId FROM PROJECT_SECURITY
					WHERE PrincipalId = @UserId
						AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
				)
			OR D.DocumentId IN
				(SELECT DocumentId FROM DOCUMENT_SECURITY_ALL
					WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsResource = 1)
				)
		)
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @DocumentObjectType
			  GROUP BY E.ObjectId)
) A
  WHERE DATEDIFF(dd, DATEADD(mi, @TimeOffset, LastSavedDate) , @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE DOCUMENTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentsReplaceUnchangeableUserToManager
	@UserId as int
as
UPDATE DOCUMENTS SET CreatorId = ManagerId WHERE CreatorId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStateGetByStatus
	@StatusId int,
	@retval int output
as
SELECT @retval = StateId
  FROM DOCUMENT_STATUS
  WHERE StatusId = @StatusId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStatusAdd
	@StatusName as nvarchar(50),
	@StateId int
as
IF @StateId <= 0
	SET @StateId = NULL
INSERT INTO DOCUMENT_STATUS (StatusName, StateId) VALUES (@StatusName, @StateId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStatusDelete
	@StatusId as int
as
DELETE FROM DOCUMENT_STATUS  WHERE StatusId = @StatusId AND IsInternal = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStatusGet
as
SELECT StatusId, StatusName, StateId
  FROM DOCUMENT_STATUS
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStatusGetForDictionaries
	@LanguageId int
as
SELECT S.StatusId AS ItemId, S.StatusName AS ItemName, S.StateId, SL.StateName,
	CASE WHEN EXISTS(SELECT * FROM DOCUMENTS D WHERE D.StatusId = S.StatusId) OR IsInternal = 1
	THEN 0 ELSE 1 END AS CanDelete
  FROM DOCUMENT_STATUS S
	LEFT JOIN OBJECT_STATE_LANGUAGE SL ON (S.StateId = SL.StateId AND SL.LanguageId = @LanguageId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentStatusUpdate
	@StatusId as int ,
	@StatusName as nvarchar(50),
	@StateId int
as
IF @StateId <= 0
	SET @StateId = NULL
UPDATE DOCUMENT_STATUS
  SET StatusName = @StatusName, StateId = @StateId
  WHERE StatusId = @StatusId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentToDoAdd
	@DocumentId as int ,
	@ToDoId as int ,
	@CompleteDocument as bit
as
if EXISTS(SELECT * FROM DOCUMENT_TODO WHERE DocumentId = @DocumentId AND ToDoId = @ToDoId)
	UPDATE DOCUMENT_TODO
	  SET CompleteDocument = @CompleteDocument
	  WHERE DocumentId = @DocumentId AND ToDoId = @ToDoId
else
	INSERT INTO DOCUMENT_TODO (DocumentId, ToDoId, CompleteDocument)
	  VALUES(@DocumentId, @ToDoId, @CompleteDocument)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentUpdateActivation
	@DocumentId as int
as
UPDATE DOCUMENTS
  SET ActivatedManually = 1
  WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentUpdateCompletion
	@DocumentId as int,
	@IsCompleted as bit,
	@ReasonId as int
as
DECLARE @ClosedDate as DateTime
IF @IsCompleted=1
	SET @ClosedDate = getutcdate()
UPDATE DOCUMENTS
  SET IsCompleted = @IsCompleted, ReasonId = @ReasonId, ClosedDate=@ClosedDate
  WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].DocumentUpdateProjectAndManager
	@DocumentId as int ,
	@ProjectId as int,
	@ManagerId as int
as
IF @ProjectId <= 0
	SET @ProjectId = NULL
UPDATE DOCUMENTS
  SET ProjectId = @ProjectId, ManagerId = @ManagerId
  WHERE DocumentId = @DocumentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailAdd
	@UserId as int,
	@Email as nvarchar(250)
as
IF NOT EXISTS (SELECT * FROM EMAILS WHERE UserId = @UserId AND Email = @Email)
	INSERT INTO EMAILS (UserId, Email) VALUES(@UserId, @Email)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailCheck
	@Email nvarchar(250),
	@retval int output
as
SELECT @retval = COUNT(*)
  FROM EMAILS
  WHERE Email = @Email
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailDelete
	@EmailId as int
as
DELETE FROM EMAILS WHERE EmailId = @EmailId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailGet
	@EmailId int
as
SELECT EmailId, UserId, Email FROM EMAILS WHERE EmailId = @EmailId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailSetPrimary
	@UserId as int,
	@Email as nvarchar(250)
as
DECLARE @CurrentEmail nvarchar(250)
SELECT @CurrentEmail = Email FROM USERS WHERE PrincipalId = @UserId
UPDATE USERS SET Email = @Email WHERE PrincipalId = @UserId
DELETE FROM EMAILS WHERE UserId = @UserId AND Email = @Email
IF NOT EXISTS (SELECT * FROM EMAILS WHERE UserId = @UserId AND Email = @CurrentEmail)
	INSERT INTO EMAILS (UserId, Email) VALUES (@UserId, @CurrentEmail)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailsGet
	@UserId as int
as
SELECT EmailId, Email FROM EMAILS WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EmailUpdate
	@EmailId as int,
	@Email as nvarchar(250)
as
UPDATE EMAILS SET Email = @Email WHERE EmailId = @EmailId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EngineEditionGet
AS
SELECT SERVERPROPERTY('EngineEdition')
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventCreate
	@ProjectId as int = null ,
	@CreatorId as int ,
	@ManagerId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext,
	@Location as nvarchar(1000) ,
	@CreationDate as datetime ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@PriorityId as int ,
	@TypeId as int ,
	@TaskTime int,
	@retval int output
as
INSERT INTO EVENTS (ProjectId, CreatorId, ManagerId, Title, [Description], Location, CreationDate, StartDate, FinishDate, PriorityId, TypeId, TaskTime)
  VALUES(@ProjectId, @CreatorId, @ManagerId, @Title, @Description, @Location, @CreationDate, @StartDate, @FinishDate, @PriorityId, @TypeId, @TaskTime)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventDelete
	@EventId as int
as
DECLARE @EventObjectType int
SET @EventObjectType = 4
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @EventObjectType AND ObjectId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @EventObjectType AND ObjectId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @EventObjectType AND ObjectId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE RECURRENCE WHERE ObjectTypeId = @EventObjectType AND ObjectId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE EVENT_RESOURCES WHERE EventId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @EventObjectType AND ObjectId = @EventId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @EventId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId = @EventId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId = @EventId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId = @EventId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM EVENTS  WHERE EventId = @EventId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventDeleteByProject
	@ProjectId as int
as
DECLARE @EventObjectType int
SET @EventObjectType = 4
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @EventObjectType AND ObjectId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @EventObjectType AND ObjectId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @EventObjectType AND ObjectId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE RECURRENCE WHERE ObjectTypeId = @EventObjectType AND ObjectId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE EVENT_RESOURCES WHERE EventId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @EventObjectType AND ObjectId IN
		(SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId IN (SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId) AND
		EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId IN (SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId IN (SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId IN (SELECT EventId FROM EVENTS WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @EventObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM EVENTS  WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGet
	@EventId as int,
	@LanguageId as int
as
DECLARE @EventType int
SET @EventType = 4
SELECT E.EventId, E.ProjectId, P.Title AS ProjectTitle, E.CreatorId, E.ManagerId, E.Title, E.[Description], E.Location, 	E.CreationDate, E.StartDate, E.FinishDate,
	E.PriorityId, PR.PriorityName, E.TypeId, ET.TypeName, E.Interval AS ReminderInterval, E.StateId, OS.StateName, E.TaskTime,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	LEFT JOIN PROJECTS P ON (E.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (E.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN EVENT_TYPE_LANGUAGE ET ON (E.TypeId = ET.TypeId AND ET.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
	JOIN OBJECT_STATE_LANGUAGE OS ON (E.StateId = OS.StateId AND OS.LanguageId = @LanguageId)
  WHERE E.EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetCreators
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT CreatorId FROM EVENTS)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetDates
	@EventId as int
as
SELECT EventId, StartDate, FinishDate
  FROM EVENTS
  WHERE EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetInUTC
	@EventId as int,
	@LanguageId as int
as
DECLARE @EventType int
SET @EventType = 4
SELECT E.EventId, E.ProjectId, P.Title AS ProjectTitle, E.CreatorId, E.ManagerId, E.Title, E.[Description], E.Location,
	E.CreationDate, E.StartDate, E.FinishDate,
	E.PriorityId, PR.PriorityName, E.TypeId, ET.TypeName, E.Interval AS ReminderInterval, E.StateId, E.TaskTime,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	LEFT JOIN PROJECTS P ON (E.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (E.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN EVENT_TYPE_LANGUAGE ET ON (E.TypeId = ET.TypeId AND ET.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE E.EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetManagers
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT ManagerId FROM EVENTS)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetProject
	@EventId as int,
	@Retval as int output
AS
SELECT @Retval = ProjectId FROM EVENTS WHERE EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventGetSecurityForUser
	@EventId as int,
	@UserId as int
as
SELECT EventId, PrincipalId, IsResource, IsManager
   FROM EVENT_SECURITY_ALL
  WHERE EventId = @EventId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventManagerGet
	@EventId int,
	@retval int output
AS
SELECT @retval = ManagerId
 FROM EVENTS
 WHERE EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventRecalculateState
	@EventId INT,
	@DateNow DateTime
 AS
DECLARE @StateId INT
DECLARE @NewStateId INT
DECLARE @StartDate DATETIME
DECLARE @FinishDate DATETIME
SELECT @StartDate = [StartDate], @FinishDate = [FinishDate], @StateId = [StateId]
  FROM EVENTS
  WHERE EventId = @EventId
SET @NewStateId = 1
IF @StartDate <= @DateNow AND @DateNow  <= @FinishDate
	SET @NewStateId = 2
ELSE IF  @DateNow > @FinishDate
	SET @NewStateId = 5
UPDATE EVENTS
  SET StateId = @NewStateId
  WHERE EventId = @EventId AND @StateId != @NewStateId
SELECT @StateId As OldStateId, @NewStateId as NewStateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventResourceAdd
	@EventId as int ,
	@PrincipalId as int,
	@MustBeConfirmed as bit
as
if EXISTS(SELECT * FROM EVENT_RESOURCES WHERE EventId = @EventId AND PrincipalId = @PrincipalId)
	UPDATE EVENT_RESOURCES SET MustBeConfirmed = @MustBeConfirmed WHERE EventId = @EventId AND PrincipalId = @PrincipalId
ELSE
	INSERT INTO EVENT_RESOURCES (EventId, PrincipalId, MustBeConfirmed) VALUES(@EventId, @PrincipalId, @MustBeConfirmed)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventResourceDelete
	@EventId as int ,
	@PrincipalId as int
as
DELETE FROM EVENT_RESOURCES WHERE EventId = @EventId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventResourceGetByUser
	@EventId as int,
	@UserId as int
as
SELECT MustBeConfirmed, ResponsePending, IsConfirmed
  FROM EVENT_RESOURCES
  WHERE EventId = @EventId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventResourcesGet
	@EventId as int
as
DECLARE @ExternalGroup int
SET @ExternalGroup  = 7
SELECT ER.ResourceId, ER.EventId, ER.PrincipalId, P.IsGroup, ER.MustBeConfirmed, ER.ResponsePending, ER.IsConfirmed, ER.LastSavedDate,
	CASE WHEN U.IsExternal = 1 THEN 1 ELSE 0 END AS IsExternal
  FROM EVENT_RESOURCES ER
	JOIN PRINCIPALS P ON (ER.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (ER.PrincipalId = U.PrincipalId)
  WHERE EventId = @EventId
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventResourcesGetNotPending
	@UserId as int
as
SELECT ER.EventId, E.Title, ER.PrincipalId, ER.IsConfirmed, ER.LastSavedDate, E.StartDate, E.FinishDate, E.StateId
  FROM EVENT_RESOURCES ER
	JOIN EVENTS E ON (ER.EventId = E.EventId)
  WHERE E.ManagerId = @UserId AND MustBeConfirmed = 1 AND ResponsePending = 0
  ORDER BY ER.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM EVENT_RESOURCES WHERE PrincipalId = @UserId)
	SET @Retval = 1
ELSE BEGIN
	IF EXISTS (SELECT * FROM EVENTS WHERE ManagerId = @UserId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM EVENTS WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventSecurityGetByEvent
	@EventId as int
as
SELECT S.PrincipalId AS UserId, U.FirstName, U.LastName, U.Email, U.Login
  FROM EVENT_SECURITY_ALL S
	JOIN USERS U ON (S.PrincipalId = U.PrincipalId)
  WHERE S.EventId = @EventId
	AND (S.IsMAnager = 1 OR S.IsResource = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetAllForUserByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @EventType int
SET @EventType = 4
SELECT E.EventId, E.Title, E.[Description], E.PriorityId, P.PriorityName, E.TypeId, StartDate, FinishDate, E.StateId,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE ProjectId = @ProjectId
	AND EventId IN
		(SELECT EventId FROM EVENT_SECURITY_ALL S
		  WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetByFilter
	@ProjectId as int,
	@UserId as int,
	@ResourceId as int,
	@StartDate as datetime,
	@FinishDate as datetime,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit,
	@Keyword as nvarchar(100)
as
SET @Keyword = '%' + @Keyword + '%'
DECLARE @EventType int
SET @EventType = 4
SET @FinishDate = DATEADD(d, 1, @FinishDate)
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT EventId, Title, [Description], TypeId, Location, StartDate, FinishDate,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence,
	CASE WHEN @IsPPM = 1 OR E.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR E.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete,
	ManagerId, PriorityId, Interval, E.StateId
  FROM EVENTS E
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId OR (@ProjectId = -1 AND ProjectId IS NULL))
	AND StartDate < @FinishDate AND FinishDate > @StartDate
	AND (@Keyword = '%%' OR E.Title LIKE @Keyword OR E.[Description] LIKE @Keyword OR E.Location LIKE @Keyword)
	AND
	(
		(@GetAssigned = 1 AND (@ResourceId = 0 OR EventId IN
			(SELECT EventId FROM EVENT_SECURITY_ALL S
			  WHERE PrincipalId = @ResourceId AND (IsResource = 1 OR IsManager = 1))))
		OR
		(@GetManaged =1 AND (@ResourceId = 0 OR E.ManagerId = @ResourceId))
		OR
		(@GetCreated =1 AND (@ResourceId = 0 OR E.CreatorId = @ResourceId))
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetByProject
	@ProjectId as int,
	@LanguageId as int
as
SELECT E.EventId, E.ProjectId, E.CreatorId, E.ManagerId, E.Title, E.[Description], E.Location, E.CreationDate, E.StartDate, E.FinishDate,
	E.PriorityId, PR.PriorityName, E.TypeId, ET.TypeName, E.StateId
  FROM EVENTS E
	JOIN PRIORITY_LANGUAGE PR ON (E.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN EVENT_TYPE_LANGUAGE ET ON (E.TypeId = ET.TypeId AND ET.LanguageId = @LanguageId)
  WHERE E.ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @IsPPM bit, @IsExec bit
SET @IsPPM = 0
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 7)
	SET @IsExec = 1
SELECT E.EventId, E.Title,
	CASE WHEN E.ManagerId = @UserId THEN 1 ELSE 0 END AS IsManager,
	CASE WHEN ER.ResourceId IS NOT NULL THEN 1 ELSE 0 END AS IsResource,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR ES.IsManager = 1 OR ES.IsResource = 1 THEN 1 ELSE 0 END AS CanView,
	CASE WHEN @IsPPM = 1 OR ES.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR ES.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM EVENTS E
	LEFT JOIN EVENT_SECURITY_ALL ES ON (E.EventId = ES.EventId AND ES.PrincipalId = @CurrentUserId)
	LEFT JOIN EVENT_RESOURCES ER ON (E.EventId = ER.EventId AND ER.PrincipalId = @UserId)
  WHERE E.ManagerId = @UserID OR ER.ResourceId IS NOT NULL
  ORDER BY E.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForEventScheduling
	@EventId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
DECLARE @EventType int
SET @EventType = 4
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT ES.PrincipalId AS UserId, E.EventId, E.TypeId, E.StartDate, E.FinishDate, E.StateId,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
	JOIN EVENT_SECURITY_ALL ES ON (E.EventId = ES.EventId)
	JOIN EVENT_SECURITY_ALL  S ON (ES.PrincipalId = S.PrincipalId)
  WHERE E.StartDate < @FinishDate AND E.FinishDate > @StartDate
	AND (ES.IsResource = 1 OR ES.IsManager = 1)
	AND (S.IsResource = 1 OR S.IsManager = 1)
	AND S.EventId = @EventId
	AND E.EventId != @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForManagerView
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @CompletedState as int
set @CompletedState=5
DECLARE @EventType int
SET @EventType = 4
SELECT E.EventId AS ItemId, E.Title, E.PriorityId, P.PriorityName, 4 AS ItemType, E.CreationDate, E.StartDate, E.FinishDate, 0 as PercentCompleted, CAST(0 as bit) as IsCompleted,
	E.ManagerId, 0 as ReasonId, E.ProjectId, E.StateId, 0 as CompletionTypeId,
	CASE WHEN R.RecurrenceId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS HasRecurrence
  FROM EVENTS E
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE (@ManagerId=0 OR E.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR E.ProjectId=@ProjectId)
	AND
	(
		(R.RecurrenceId IS NULL AND
		(
			(@StartDate is not null AND E.StartDate<=@StartDate AND E.StateId=@UpcomingState)
			OR
			(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StateId=@CompletedState)
			OR
			(@ShowActive=1 AND E.StateId=@ActiveState)
		))
		OR
		(R.RecurrenceId IS NOT NULL AND
		(
			(@StartDate is not null AND E.StartDate<=@StartDate AND E.FinishDate>=@dt)
			OR
			(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StartDate<=@dt)
			OR
			(@ShowActive=1 AND E.StateId=@ActiveState)
		))
	)
	AND
	(
		@PrincipalId = 1
	OR
		EventId IN (SELECT EventId FROM EVENT_SECURITY_ALL
				WHERE IsResource = 1 AND (PrincipalId = @PrincipalId OR PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId))
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForResourceView
	@UserId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @CompletedState as int
set @CompletedState=5
DECLARE @EventType int
SET @EventType = 4
 SELECT DISTINCT E.EventId AS ItemId, E.Title, E.PriorityId, P.PriorityName, 4 AS ItemType, E.CreationDate, E.StartDate, E.FinishDate, 0 as PercentCompleted, CAST(0 as bit) as IsCompleted,
	E.ManagerId, 0 as ReasonId, E.ProjectId, PR.Title as ProjectTitle, E.StateId, 0 as CompletionTypeId,
	CASE WHEN R.RecurrenceId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS HasRecurrence
  FROM EVENTS E
	LEFT JOIN PROJECTS PR ON E.ProjectId=PR.ProjectId
	JOIN EVENT_SECURITY_ALL ES ON (E.EventId = ES.EventId AND ES.IsResource=1 AND ES.PrincipalId = @UserId)
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE (@ManagerId=0 OR E.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR E.ProjectId=@ProjectId)
	AND
	(
		(
			R.RecurrenceId IS NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.StateId=@UpcomingState)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StateId=@CompletedState)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
		OR
		(
			R.RecurrenceId IS NOT NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.FinishDate>=@dt)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StartDate<=@dt)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForScheduling
	@UserId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
DECLARE @EventType int
SET @EventType = 4
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT ES.PrincipalId AS UserId, E.EventId, E.TypeId, E.StartDate, E.FinishDate, E.StateId,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
	JOIN EVENT_SECURITY_ALL ES ON (E.EventId = ES.EventId)
	JOIN SCHEDULE S ON (ES.PrincipalId = S.ContUserId)
  WHERE E.StartDate < @FinishDate AND E.FinishDate > @StartDate
	AND S.UserId = @UserId
	AND (ES.IsResource = 1 OR ES.IsManager = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForUser
	@UserId as int
as
DECLARE @EventObjectType int
SET @EventObjectType = 4
SELECT EventId, Title, Location, TypeId, StartDate, FinishDate, ManagerId, PriorityId, Interval, [Description], StateId
  FROM EVENTS
  WHERE EventId IN
	(SELECT EventId FROM EVENT_SECURITY_ALL S
	  WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetForUserByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @EventType int
SET @EventType = 4
DECLARE @dt datetime
DECLARE @dt1 datetime
SET @dt = GETUTCDATE()
SET @dt1 = DATEADD(dd, 1, @dt)
SELECT E.EventId, E.Title, E.[Description], E.PriorityId, P.PriorityName, E.TypeId, StartDate, FinishDate, E.StateId,
	CASE WHEN R.RecurrenceId IS NULL THEN 0 ELSE 1 END AS HasRecurrence
  FROM EVENTS E
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE ProjectId = @ProjectId
	AND StartDate < = @dt1 AND FinishDate >= @dt
	AND EventId IN
		(SELECT EventId FROM EVENT_SECURITY_ALL S
		  WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetPending
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT E.EventId, E.Title, E.Location, E.PriorityId, P.PriorityName, E.TypeId, E.ManagerId, E.StartDate, E.FinishDate, E.StateId
  FROM EVENTS E, EVENT_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR E.ProjectId = @ProjectId)
	AND E.EventId = R.EventId AND R.PrincipalId = @UserId
	AND E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND E.FinishDate > GETUTCDATE()
	AND (R.MustBeConfirmed=1 AND R.ResponsePending=1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetSimple
	@ProjectId as int,
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit
as
DECLARE @EventType int
SET @EventType = 4
SELECT EventId, Title, TypeId, StateId
  FROM EVENTS E
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId OR (@ProjectId = -1 AND ProjectId IS NULL))
	AND
	(
		(@GetAssigned = 1 AND EventId IN
			(SELECT EventId FROM EVENT_SECURITY_ALL S
			  WHERE PrincipalId = @UserId AND IsResource = 1))
		OR
		(@GetManaged =1 AND ManagerId = @UserId)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetTotalCountWithType
	@UserId as int,
	@LanguageId as int
AS
SELECT ET.TypeName AS Type, COUNT(E.EventId) AS Count
FROM EVENTS E
	JOIN EVENT_TYPE_LANGUAGE ET ON (E.TypeId = ET.TypeId AND ET.LanguageId = @LanguageId)
WHERE EventId IN
(
	SELECT EventId FROM EVENT_SECURITY_ALL S
	WHERE PrincipalId = @UserId
)
GROUP BY ET.TypeName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetUpdatedByUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @EventObjectType int
SET @EventObjectType = 4
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT EventId, Title, Location, TypeId, 	StartDate, FinishDate, A.LastSavedDate, E.StateId
  FROM EVENTS E,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @EventObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE E.EventId = A.ObjectId
	AND (@ProjectId = 0 OR E.ProjectId = @ProjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
  ORDER BY A.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsGetUpdatedForUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @EventObjectType int
SET @EventObjectType = 4
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT EventId, Title, Location, TypeId,  StartDate, FinishDate, LastSavedDate, LastEditorId, ProjectId, ProjectName, StateId
FROM
(
	SELECT E.EventId, E.Title, E.Location, E.TypeId, 	E.StartDate, E.FinishDate, E.StateId,
		ISNULL(E.ProjectId, -1) AS ProjectId, ISNULL(P.Title, '') AS ProjectName, SE.Dt AS LastSavedDate, SE.UserId AS LastEditorId
	  FROM EVENTS E
		JOIN SYSTEM_EVENTS SE ON (E.EventId = SE.ObjectId)
		LEFT JOIN PROJECTS P ON (E.ProjectId = P.ProjectId)
	  WHERE (@ProjectId = 0 OR E.ProjectId = @ProjectId)
		AND E.EventId IN
			(SELECT EventId FROM EVENT_SECURITY_ALL S
			  WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1)
			)
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @EventObjectType
			  GROUP BY E.ObjectId)
) A
WHERE  DATEDIFF(dd, DATEADD(mi, @TimeOffset, LastSavedDate), @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE EVENTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventsReplaceUnchangeableUserToManager
	@UserId as int
as
UPDATE EVENTS SET CreatorId = ManagerId WHERE CreatorId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventTypeGetNames
	@TypeId int
AS
SELECT LanguageId, TypeName AS Name
  FROM EVENT_TYPE_LANGUAGE
  WHERE TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].EventTypesGet
	@LanguageId as int
as
SELECT TypeId, TypeName
  FROM EVENT_TYPE_LANGUAGE
  WHERE LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ExternalGateAdd
	@ObjectTypeId int,
	@ObjectId int,
	@UserId int,
	@Email nvarchar(250)
AS
IF NOT EXISTS(SELECT * FROM EXTERNAL_GATE WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId AND Email = @Email)
 INSERT INTO EXTERNAL_GATE (ObjectTypeId, ObjectId, UserId, Email)
  VALUES(@ObjectTypeId, @ObjectId, @UserId, @Email)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ExternalGateDelete
	@ObjectTypeId int,
	@ObjectId int,
	@UserId int,
	@Email nvarchar(250)
AS
DELETE FROM EXTERNAL_GATE WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId AND Email = @Email
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ExternalGateGetByGuid
	@Guid uniqueidentifier
AS
SELECT ObjectTypeId, ObjectId, UserId, Email
 FROM EXTERNAL_GATE
 WHERE GUID = @Guid
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ExternalGateGetGuid
	@ObjectTypeId int,
	@ObjectId int,
	@UserId int,
	@Email nvarchar(250)
AS
SELECT GUID
 FROM EXTERNAL_GATE
 WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId AND Email = @Email
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FavoritesAdd
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@UserId as int
AS
IF  NOT EXISTS(SELECT * FROM FAVORITES WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId)
               INSERT INTO FAVORITES (ObjectTypeId, ObjectId, UserId) VALUES(@ObjectTypeId, @ObjectId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FavoritesCheck
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@UserId as int ,
	@Retval int output
AS
SET @Retval = 0
IF EXISTS(SELECT * FROM FAVORITES WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId)
	SET @Retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FavoritesDelete
	@ObjectTypeId int,
	@ObjectId int,
	@UserId int
as
DELETE FROM FAVORITES WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FavoritesGet
	@ObjectTypeId int,
	@UserId as int
as
IF @ObjectTypeId = 3
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN PROJECTS O ON F.ObjectId = O.ProjectId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 4
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN EVENTS O ON F.ObjectId = O.EventId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 5
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN TASKS O ON F.ObjectId = O.TaskId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 6
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN TODO O ON F.ObjectId = O.ToDoId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 7
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN INCIDENTS O ON F.ObjectId = O.IncidentId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 16
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN DOCUMENTS O ON F.ObjectId = O.DocumentId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = 15
	SELECT F.FavoriteId, F.ObjectTypeId, F.ObjectId, F.UserId, O.Title
	  FROM FAVORITES F
		JOIN LISTS O ON F.ObjectId = O.ListId
	  WHERE F.UserId = @UserId AND F.ObjectTypeId = @ObjectTypeId
	  ORDER BY O.Title
ELSE IF @ObjectTypeId = -1
	SELECT FavoriteId, ObjectTypeId, ObjectId, UserId, '' AS Title
	  FROM FAVORITES
	  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileCreate
	@FileName as nvarchar(250) ,
	@ContentTypeId as int ,
	@retval int output
as
INSERT INTO [FILE] (FileName, ContentTypeId)
  VALUES(@FileName, @ContentTypeId)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileDelete
	@FileId as int
as
DELETE FROM [FILE]  WHERE FileId = @FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileGetData
       @FileId as int as
SELECT Data FROM [FILE] WHERE FileId = @FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileGetInfo
       @FileId as int as
SELECT F.FileId, F.FileName, C.ContentTypeString as ContentType, F.Size
  FROM [FILE] F, CONTENT_TYPES C
  WHERE F.FileId = @FileId AND F.ContentTypeId = C.ContentTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileUpdateData
	@Pointer as binary(16),
	@Offset as int ,
	@Delete as int ,
	@Bytes as image
as
UPDATETEXT [FILE].Data @Pointer @Offset @Delete WITH LOG @Bytes
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FileUpdateDataPrepare
	@FileId as int ,
	@Size as int ,
	@Pointer as varbinary(16) output
as
SET NOCOUNT ON
UPDATE [FILE] SET Size = @Size, Data = 0x0 WHERE FileId = @FileId
IF @Size = 0
BEGIN
	SET @Pointer = NULL
END
ELSE
BEGIN
	SELECT @Pointer = TEXTPTR(Data) FROM [FILE] WHERE FileId = @FileId
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FinancesCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM ACTUAL_FINANCES WHERE LastEditorId = @UserId)
	OR EXISTS(SELECT * FROM WeekTimeSheet WHERE LastEditorId = @UserId)
	OR EXISTS(SELECT * FROM ACCOUNTS WHERE LastEditorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FinancesReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
BEGIN TRAN
	UPDATE ACTUAL_FINANCES SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE ACCOUNTS SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE WeekTimeSheet SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].FinancesReplaceUnchangeableUserToManager
	@UserId as int
as
BEGIN TRAN
	UPDATE ACTUAL_FINANCES
	    SET LastEditorId = P.ManagerId
	    FROM ACTUAL_FINANCES F, ACCOUNTS A, PROJECTS P
	    WHERE F.AccountId = A.AccountId AND A.ProjectId = P.ProjectId AND F.LastEditorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE ACCOUNTS
	    SET LastEditorId = P.ManagerId
	    FROM ACCOUNTS A, PROJECTS P
	    WHERE A.ProjectId = P.ProjectId AND A.LastEditorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE WeekTimeSheet
	    SET LastEditorId = P.ManagerId
	    FROM WeekTimeSheet W, PROJECTS P
	    WHERE W.ProjectId = P.ProjectId AND W.LastEditorId = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlEntriesClear
	@AclId INT
AS
	DELETE FROM fsc_AccessControlEntries WHERE AclId = @AclId AND IsInherited = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlEntriesGet
	@DirectoryId INT
AS
SELECT
	ACL.AclId, ACL.IsInherited as AclIsInherited, ACL.DirectoryId,
	ACE.AceId, ACE.IsInherited, ACE.Role, ACE.PrincipalId, ACE.[Action], ACE.Allow
FROM fsc_AccessControlEntries ACE
	RIGHT JOIN fsc_AccessControlLists ACL ON ACL.AclId = ACE.AclId
WHERE
	ACL.DirectoryId = @DirectoryId AND (ACE.IsInternal = 0 OR ACE.IsInternal IS NULL)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlEntriesGetAclIdByDirectoryId
	@DirectoryId int,
	@retVal int output
AS
	SELECT @retVal = AclId FROM fsc_AccessControlLists WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlEntryAdd
	@AclId int,
	@Role nvarchar(50),
	@PrincipalId int,
	@Action nvarchar(50),
	@Allow bit,
	@IsInternal bit,
	@Retval int out
AS
	INSERT INTO  fsc_AccessControlEntries
		(AclId, IsInherited, Role, PrincipalId, [Action], Allow,  IsInternal )
	VALUES
		(@AclId, 0, @Role, @PrincipalId, @Action, @Allow, @IsInternal)
	SET @Retval = @@IDENTITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlListCopy
	@SrcDirectoryId INT,
	@DestDirectoryId INT,
	@Retval INT OUT
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE @SrcAclId INT
	DECLARE @DestAclIsInherited INT
	SELECT @SrcAclId = AclId FROM fsc_AccessControlLists WHERE DirectoryId = @SrcDirectoryId
	SELECT @Retval = AclId FROM fsc_AccessControlLists WHERE DirectoryId = @DestDirectoryId
	IF @Retval IS NULL
	BEGIN
		SELECT @DestAclIsInherited = IsInherited FROM fsc_AccessControlLists WHERE DirectoryId = @SrcDirectoryId
		INSERT INTO fsc_AccessControlLists ([DirectoryId], [IsInherited])	VALUES( @DestDirectoryId, @DestAclIsInherited)
		IF @@ERROR <> 0 GOTO ERR
		SET @Retval = @@IDENTITY
	END
	INSERT INTO fsc_AccessControlEntries([AclId], [IsInherited], [Role], [PrincipalId], [Action], [Allow], [IsInternal])
	SELECT @Retval, [IsInherited], [Role], [PrincipalId], [Action], [Allow], [IsInternal] FROM fsc_AccessControlEntries
	WHERE AclId = @SrcAclId
	IF @@ERROR <> 0 GOTO ERR
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlListTurnOffInheritFromParent
	@AclId INT,
	@Copy BIT
AS
BEGIN TRAN
	DECLARE @DirectoryId INT
	SELECT @DirectoryId = DirectoryId FROM fsc_AccessControlLists WHERE AclId = @AclId
	UPDATE fsc_AccessControlLists SET IsInherited = 0 WHERE AclId = @AclId
	IF @@ERROR <> 0 GOTO ERR
	IF @Copy = 1
	BEGIN
		UPDATE fsc_AccessControlEntries SET IsInherited = 0 WHERE AclId = @AclId AND IsInherited = 1
		IF @@ERROR <> 0 GOTO ERR
	END
	ELSE
	BEGIN
		DELETE FROM fsc_AccessControlEntries WHERE AclId = @AclId AND IsInherited = 1
		IF @@ERROR <> 0 GOTO ERR
	END
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_AccessControlListTurnOnInheritFromParent
	@AclId INT
AS
BEGIN TRAN
	UPDATE fsc_AccessControlLists SET IsInherited = 1 WHERE AclId = @AclId
	IF @@ERROR <> 0 GOTO ERR
	DECLARE @ParenDirectoryId INT
	SELECT @ParenDirectoryId = D.ParentDirectoryId FROM fsc_Directories  D
		INNER JOIN fsc_AccessControlLists ACL ON ACL.DirectoryId = D.DirectoryId
		WHERE ACL.AclId = @AclId
	EXEC fsc_DirectoryRefreshInheritedACL @ParenDirectoryId
	IF @@ERROR <> 0 GOTO ERR
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_CanUserRunAction
	@UserId INT,
	@ContainerKey NVARCHAR(50),
	@DirectoryId INT,
	@Action NVARCHAR(50),
	@Retval INT OUT
AS
SET NOCOUNT ON
IF EXISTS (SELECT * FROM fsc_FolderSecurityAll WHERE PrincipalId = @UserId AND ContainerKey = @ContainerKey AND DirectoryId = @DirectoryId AND [Action] = @Action AND Allow = 1 )
	SET @Retval =  1
ELSE
	SET @Retval =  0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ContainerKeyByDirectoryId]
	@DirectoryId int
AS
       SELECT ContainerKey FROM fsc_Directories WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoriesGetByParent]
	@ParentDirectoryId as int,
	@ContainerKey nvarchar(255)
AS
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId=@ParentDirectoryId AND ContainerKey=@ContainerKey)
	BEGIN
		RAISERROR ('Invalid @DirectoryId. The folder doesn''t exist or isn''t  in the current container', 16,1)
		GOTO ERR
	END
	SELECT DirectoryId, Name,  Path, ParentDirectoryId, CreatorId, Created, ModifierId, Modified
	FROM fsc_Directories
	WHERE ParentDirectoryId=@ParentDirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryCreate]
	@ContainerKey as nvarchar(255),
	@Name as nvarchar(255),
	@ParentDirectoryId as int,
	@CreatorId as int,
	@Created as datetime
AS
	DECLARE @Path as varchar(512)
	SELECT @Path = Path + CAST(@ParentDirectoryId AS varchar(512)) + '.' FROM fsc_Directories WHERE DirectoryId=@ParentDirectoryId
	IF (@Path IS NULL)
	BEGIN
		RAISERROR ('Invalid @ParentDirectoryId. The folder doesn''t exist', 16,1)
		GOTO ERR
	END
	INSERT INTO fsc_Directories(ContainerKey, Name, Path, ParentDirectoryId, CreatorId, Created, ModifierId, Modified)
	VALUES (@ContainerKey, @Name, @Path, @ParentDirectoryId, @CreatorId, @Created, @CreatorId, @Created)
	DECLARE @DirectoryId int
	SET @DirectoryId=@@identity
	INSERT INTO fsc_AccessControlLists(DirectoryId, IsInherited)
	VALUES (@DirectoryId, 0)
	EXEC fsc_AccessControlListTurnOnInheritFromParent @@identity
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, ParentDirectoryId
	FROM fsc_Directories t
	WHERE DirectoryId=@DirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryCreateRoot]
	@ContainerKey as nvarchar(255),
	@Name as nvarchar(255),
	@CreatorId as int,
	@Created as datetime
AS
	INSERT INTO fsc_Directories(ContainerKey, Name, Path, CreatorId, Created, ModifierId, Modified)
	VALUES (@ContainerKey, @Name, '.', @CreatorId, @Created, @CreatorId, @Created)
	DECLARE @DirectoryId int
	SET @DirectoryId=@@identity
	INSERT INTO fsc_AccessControlLists(DirectoryId, IsInherited)
	VALUES (@DirectoryId, 0)
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, NULL as ParentDirectoryId
	FROM fsc_Directories t
	WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_DirectoryDelete
	@DirectoryId INT
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId = @DirectoryId)
	BEGIN
		RAISERROR('Invalid DirectoryId.',16,1)
		GOTO ERR
	END
	DECLARE @SearchPath VARCHAR(512)
	SELECT @SearchPath = (Path + CAST(@DirectoryId AS VARCHAR(10)) + '.%') FROM fsc_Directories WHERE DirectoryId = @DirectoryId
	DECLARE @DeletedDirectories TABLE (DirectoryId INT)
	INSERT INTO @DeletedDirectories (DirectoryId)
	SELECT DirectoryId FROM fsc_Directories WHERE Path LIKE @SearchPath OR DirectoryId = @DirectoryId ORDER BY Path
	DECLARE CurFile CURSOR LOCAL FOR
		SELECT FileId FROM fsc_Files WHERE DirectoryId IN (SELECT DirectoryId FROM @DeletedDirectories)
	OPEN CurFile
	DECLARE @CurFileId int
	FETCH NEXT FROM CurFile INTO @CurFileId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC fsc_FileDelete @CurFileId
		IF @@ERROR <> 0 GOTO ERR
	FETCH NEXT FROM CurFile INTO @CurFileId
	END
	DELETE FROM fsc_Directories WHERE DirectoryId IN (SELECT DirectoryId FROM @DeletedDirectories)
	IF @@ERROR <> 0 GOTO ERR
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryGetById]
	@DirectoryId int
AS
	SELECT DirectoryId, Name,  Path, ParentDirectoryId, CreatorId, Created, ModifierId, Modified
	FROM fsc_Directories
	WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryGetByName]
	@Name as nvarchar(255),
	@ParentDirectoryId as int,
	@ContainerKey as nvarchar(255)
AS
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId=@ParentDirectoryId AND ContainerKey=@ContainerKey)
	BEGIN
		RAISERROR ('Invalid @ParentDirectoryId. The folder doesn''t exist or isn''t  in the current container', 16,1)
		GOTO ERR
	END
	SELECT DirectoryId, Name,  Path, ParentDirectoryId, CreatorId, Created, ModifierId, Modified
	FROM fsc_Directories
	WHERE Name=@Name AND ParentDirectoryId=@ParentDirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryGetParentById]
	@DirectoryId int
AS
	DECLARE @ParentDirectoryId int
	SELECT @ParentDirectoryId = ParentDirectoryId
	FROM fsc_Directories
	WHERE DirectoryId=@DirectoryId
	IF (@ParentDirectoryId IS NULL)
	BEGIN
		RAISERROR ('Invalid @DirectoryId. The folder doesn''t exist', 16,1)
		GOTO ERR
	END
	SELECT DirectoryId, Name,  Path, ParentDirectoryId, CreatorId, Created, ModifierId, Modified
	FROM fsc_Directories
	WHERE DirectoryId=@ParentDirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryGetRoot]
	@ContainerKey nvarchar(255)
AS
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, ParentDirectoryId
	FROM fsc_Directories t
	WHERE ContainerKey=@ContainerKey AND Path='.'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryModify]
	@DirectoryId as int,
	@ModifierId as int,
	@Modified as datetime
AS
	UPDATE fsc_Directories SET ModifierId=@ModifierId, Modified=@Modified
	WHERE DirectoryId=@DirectoryId
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, ParentDirectoryId
	FROM fsc_Directories
	WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryMove]
	@DirectoryId as int,
	@NewParentDirectoryId as int
AS
	DECLARE @NewContainerKey NVARCHAR(255)
	SELECT @NewContainerKey = ContainerKey FROM fsc_Directories WHERE DirectoryId = @NewParentDirectoryId
	DECLARE @OldPath varchar(512)
	SELECT @OldPath = Path FROM fsc_Directories WHERE DirectoryId=@DirectoryId
	DECLARE @NewPath varchar(512)
	SELECT @NewPath = Path + CAST(@NewParentDirectoryId as varchar(512)) + '.' FROM fsc_Directories WHERE DirectoryId=@NewParentDirectoryId
	UPDATE fsc_Directories
	SET Path = replace(path, @oldpath, @newpath), ContainerKey = @NewContainerKey
	WHERE Path like @OldPath + cast(@DirectoryId as varchar(512)) + '.%'
	UPDATE fsc_Directories
	SET Path = @NewPath, ParentDirectoryId=@NewParentDirectoryId, ContainerKey = @NewContainerKey
	WHERE DirectoryId=@DirectoryId
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, ParentDirectoryId
	FROM fsc_Directories
	WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_DirectoryRefreshInheritedACL
	@DirectoryId INT
AS
DECLARE @RootPath varchar(2048)
DECLARE @RootKey nvarchar(255)
SELECT @RootPath = Path, @RootKey = ContainerKey FROM fsc_Directories WHERE DirectoryId = @DirectoryId
PRINT @RootPath
PRINT @RootKey
DECLARE @ChildDirectories TABLE (DirectoryId int, ParentDirectoryId int, Path varchar(2048))
INSERT INTO @ChildDirectories
	(DirectoryId, ParentDirectoryId, Path)
	SELECT D.DirectoryId, D.ParentDirectoryId, D.Path FROM fsc_Directories D
		INNER JOIN fsc_AccessControlLists ACL ON ACL.DirectoryId = D.DirectoryId
	WHERE 	D.ContainerKey = @RootKey AND
		D.Path LIKE (@RootPath + CAST(@DirectoryId AS VARCHAR(2048)) + '.%')
		AND ACL.IsInherited = 1
BEGIN TRAN
DECLARE CurFile CURSOR LOCAL FOR
	SELECT DirectoryId, ParentDirectoryId, Path FROM @ChildDirectories ORDER BY Path
OPEN CurFile
DECLARE @CurDirectoryId int
DECLARE @CurParentDirectoryId int
DECLARE @CurPath varchar(2048)
FETCH NEXT FROM CurFile INTO @CurDirectoryId, @CurParentDirectoryId, @CurPath
WHILE @@FETCH_STATUS = 0
BEGIN
	DECLARE @CurrAclId INT
	DECLARE @CurrParentDirectoryAclId INT
	SELECT @CurrAclId = AclId FROM fsc_AccessControlLists WHERE DirectoryId = @CurDirectoryId
	SELECT @CurrParentDirectoryAclId = AclId FROM fsc_AccessControlLists WHERE DirectoryId = @CurParentDirectoryId
	DELETE FROM fsc_AccessControlEntries
	WHERE IsInherited = 1 AND AclId = @CurrAclId
	INSERT INTO fsc_AccessControlEntries
		(AclId, IsInherited, Role, PrincipalId, [Action], Allow, IsInternal)
	SELECT
		@CurrAclId as AclId, 1 as IsInherited, Role, PrincipalId, [Action], Allow, IsInternal
	FROM fsc_AccessControlEntries
	WHERE AclId = @CurrParentDirectoryAclId
	IF @@ERROR <> 0 GOTO ERR
FETCH NEXT FROM CurFile INTO @CurDirectoryId, @CurParentDirectoryId, @CurPath
END
IF @@ERROR <> 0 GOTO ERR
CLOSE CurFile
DEALLOCATE CurFile
COMMIT TRAN
RETURN
ERR:
	CLOSE CurFile
	DEALLOCATE CurFile
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_DirectoryRename]
	@DirectoryId as int,
	@NewName as nvarchar(255),
	@ModifierId as int,
	@Modified as datetime
AS
	UPDATE fsc_Directories SET Name=@NewName, ModifierId=@ModifierId, Modified=@Modified
	WHERE DirectoryId=@DirectoryId
	SELECT DirectoryId, Name,  Path, CreatorId, Created, ModifierId, Modified, ParentDirectoryId
	FROM fsc_Directories
	WHERE DirectoryId=@DirectoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileAllowHistory]
	@FileId int,
	@AllowHistory bit
AS
	UPDATE fsc_Files SET AllowHistory=@AllowHistory
	WHERE FileId=@FileId
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileBinaryCreate]
	@FileId int,
	@ContentTypeId int,
	@retVal int output
AS
	INSERT INTO fsc_FileBinaries(ContentTypeId)
	VALUES (@ContentTypeId)
	SELECT @retVal=@@identity
	UPDATE fsc_Files SET FileBinaryId=@retVal WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileBinaryModifyCounter]
	@FileBinaryId int
AS
	SET NOCOUNT ON
	UPDATE fsc_FileBinaries SET DownloadCount=DownloadCount + 1
	WHERE FileBinaryId=@FileBinaryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_FileCopy
	@FileId INT,
	@DestDirectoryId INT,
	@Retval INT OUT
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId = @DestDirectoryId)
	BEGIN
		RAISERROR('Invalid DestDirectoryId.',16,1)
		GOTO ERR
	END
	IF NOT EXISTS(SELECT * FROM fsc_Files WHERE FileId = @FileId)
	BEGIN
		RAISERROR('Invalid FileId.',16,1)
		GOTO ERR
	END
	DECLARE @SrcDirectoryId INT
	DECLARE @SrcAllowHistory BIT
	SELECT @SrcDirectoryId = DirectoryId, @SrcAllowHistory = AllowHistory FROM fsc_Files WHERE FileId = @FileId
	IF @SrcDirectoryId<>@DestDirectoryId
	BEGIN
		INSERT INTO [fsc_Files]([Name],  [DirectoryId], [FileBinaryId], [CreatorId], [Created], [ModifierId], [Modified], [AllowHistory])
		SELECT [Name],  @DestDirectoryId, [FileBinaryId], [CreatorId], [Created], [ModifierId], [Modified], [AllowHistory] FROM fsc_Files WHERE FileId = @FileId
		IF @@ERROR <> 0 GOTO ERR
		SET @Retval = @@IDENTITY
		IF @SrcAllowHistory = 1
		BEGIN
			INSERT INTO fsc_Files_History ([FileId], [Name], [DirectoryId], [FileBinaryId], [ModifierId], [Modified])
			SELECT @Retval, [Name], [DirectoryId], [FileBinaryId], [ModifierId], [Modified] FROM fsc_Files_History
			IF @@ERROR <> 0 GOTO ERR
		END
	END
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileCreate]
	@Name as nvarchar(255),
	@DirectoryId as int,
	@CreatorId as int,
	@Created as datetime
AS
	DECLARE @FileId INT
	IF EXISTS(SELECT * FROM fsc_Files WHERE DirectoryId = @DirectoryId AND [Name] = @Name)
	BEGIN
		SELECT TOP 1 @FileId = FileId FROM fsc_Files WHERE DirectoryId = @DirectoryId AND [Name] = @Name
	END
	ELSE
	BEGIN
		INSERT INTO fsc_Files(Name, DirectoryId, CreatorId, Created, ModifierId, Modified)
		VALUES (@Name, @DirectoryId, @CreatorId, @Created, @CreatorId, @Created)
		SET @FileId = @@identity
	END
	SELECT FileId, Name, DirectoryId, FileBinaryId, CreatorId, Created, ModifierId, Modified, 0 as Length, NULL as ContentTypeString, NULL as ContentTypeId, AllowHistory
	FROM fsc_Files t
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_FileDelete
	@FileId INT
AS
SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM fsc_Files WHERE FileId = @FileId)
	BEGIN
		RAISERROR('Invalid FileId.',16,1)
		GOTO ERR
	END
	DECLARE @FileBinariesRef TABLE (FileBinaryId INT)
	INSERT INTO @FileBinariesRef (FileBinaryId)
	SELECT FileBinaryId FROM fsc_FileBinaries
	WHERE FileBinaryId IN
		(
			SELECT FileBinaryId FROM fsc_FileBinaries
			WHERE
				FileBinaryId IN (SELECT DISTINCT FileBinaryId FROM fsc_Files WHERE FileId = @FileId)
				OR
				FileBinaryId IN (SELECT DISTINCT FileBinaryId FROM fsc_Files_History WHERE FileId = @FileId)
		)
		AND
		FileBinaryId NOT IN (SELECT DISTINCT FileBinaryId FROM fsc_Files WHERE FileId <> @FileId)
		AND
		FileBinaryId NOT IN (SELECT DISTINCT FileBinaryId FROM fsc_Files_History WHERE FileId <> @FileId)
	IF @@ERROR <> 0 GOTO ERR
	DELETE FROM fsc_Files_History WHERE FileId = @FileId
	IF @@ERROR <> 0 GOTO ERR
	DELETE FROM fsc_Files WHERE FileId = @FileId
	IF @@ERROR <> 0 GOTO ERR
	DELETE FROM fsc_FileBinaries WHERE FileBinaryId IN (SELECT DISTINCT FileBinaryId FROM @FileBinariesRef)
	IF @@ERROR <> 0 GOTO ERR
COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileGetById]
	@FileId as int
AS
	SELECT FileId,
		t.Name,
		D.DirectoryId,
		t.FileBinaryId, t.CreatorId, t.Created, t.ModifierId, t.Modified,
		DATALENGTH(FB.Data) as Length,
		CT.ContentTypeString, CT.ContentTypeId, AllowHistory,
		D.ContainerKey
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
		INNER JOIN fsc_Directories D ON T.DirectoryId = D.DirectoryId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileGetByName]
	@Name as nvarchar(255),
	@DirectoryId as int,
	@ContainerKey as nvarchar(255)
AS
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId=@DirectoryId AND ContainerKey=@ContainerKey)
	BEGIN
		RAISERROR ('Invalid @ParentDirectoryId. The folder doesn''t exist or isn''t  in the current container', 16,1)
		GOTO ERR
	END
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE Name=@Name AND DirectoryId=@DirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_FileGetCountByProject
	@ProjectId as int,
	@retval int output
AS
SELECT @retval = COUNT(*)
  FROM fsc_files f
	JOIN fsc_directories d on (f.directoryId = d.directoryId)
  WHERE d.containerkey='projectid_' + CAST(@ProjectId AS varchar(10))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileGetDownloadCount]
	@FileBinaryId int,
	@retVal int out
AS
	SELECT @retVal = DownloadCount FROM fsc_FileBinaries
	WHERE FileBinaryId=@FileBinaryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileGetHistory]
	@FileId	int
AS
	SELECT [Id], FileId, Name, t.FileBinaryId, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId
	FROM fsc_Files_History t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileModify]
	@FileId as int,
	@ModifierId as int,
	@Modified as datetime
AS
	IF EXISTS(SELECT * FROM fsc_Files WHERE FileId=@FileId AND AllowHistory=1)
		INSERT INTO fsc_Files_History (FileId, Name, DirectoryId, FileBinaryId, ModifierId, Modified)
		SELECT FileId, Name, DirectoryId, FileBinaryId, ModifierId, Modified
		FROM fsc_Files
		WHERE FileId=@FileId
	UPDATE fsc_Files SET ModifierId=@ModifierId, Modified=@Modified
	WHERE FileId=@FileId
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileMove]
	@FileId int,
	@DestDirectoryId int
AS
	UPDATE fsc_Files SET DirectoryId=@DestDirectoryId
	WHERE FileId=@FileId
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FileRename]
	@FileId as int,
	@NewName as nvarchar(255),
	@ModifierId as int,
	@Modified as datetime
AS
	IF EXISTS(SELECT * FROM fsc_Files WHERE FileId=@FileId AND AllowHistory=1)
		INSERT INTO fsc_Files_History (FileId, Name, DirectoryId, FileBinaryId, ModifierId, Modified)
		SELECT FileId, Name, DirectoryId, FileBinaryId, @ModifierId, @Modified
		FROM fsc_Files
		WHERE FileId=@FileId
	UPDATE fsc_Files SET Name=@NewName, ModifierId=@ModifierId, Modified=@Modified
	WHERE FileId=@FileId
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE FileId=@FileId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_FilesGetByDirectoryId]
	@DirectoryId as int,
	@ContainerKey nvarchar(255)
AS
	IF NOT EXISTS(SELECT * FROM fsc_Directories WHERE DirectoryId=@DirectoryId AND ContainerKey=@ContainerKey)
	BEGIN
		RAISERROR ('Invalid @DirectoryId. The folder doesn''t exist or isn''t  in the current container', 16,1)
		GOTO ERR
	END
	SELECT FileId, Name, DirectoryId, t.FileBinaryId, CreatorId, Created, ModifierId, Modified, DATALENGTH(FB.Data) as Length, CT.ContentTypeString, CT.ContentTypeId, AllowHistory
	FROM fsc_Files t
		LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = t.FileBinaryId
		LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	WHERE DirectoryId=@DirectoryId
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_FilesSearch
	@UserId INT,
	@ContainerKey nvarchar(50) = NULL,
	@DirectoryId int = NULL,
	@Deep bit = NULL,
	@Keyword nvarchar(255) = NULL,
	@ContentType int = NULL,
	@ModifiedFrom DateTime = NULL,
	@ModifiedTo DateTime = NULL,
	@LengthFrom int = NULL,
	@LengthTo int = NULL
AS
SELECT D.ContainerKey,
	F.FileId,
	F.[Name],
	F.DirectoryId,
	F.FileBinaryId,
	F.CreatorId,
	F.Created,
	F.ModifierId,
	F.Modified,
	DATALENGTH(FB.Data) as Length,
	CT.ContentTypeString, CT.ContentTypeId,
	AllowHistory
FROM fsc_Files F
	LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = F.FileBinaryId
	LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	INNER JOIN fsc_Directories D ON F.DirectoryId = D.DirectoryId
	INNER JOIN fsc_FolderSecurityAll FSA ON
		FSA.DirectoryId = F.DirectoryId AND
		FSA.ContainerKey = D.ContainerKey AND
		FSA.[Action] = N'Read' AND
		FSA.Allow = 1 AND
		FSA.PrincipalId = @UserId
WHERE
	(
		@ContainerKey IS NULL
		OR
		D.ContainerKey = @ContainerKey
	)
	AND
	(
		@DirectoryId IS NULL
		OR
		@Deep = 1
		OR
		F.DirectoryId = @DirectoryId
	)
	AND
	(
		@Deep IS NULL
		OR
		@DirectoryId IS NULL
		OR
		@Deep = 0
		OR
		F.DirectoryId IN (SELECT DD.DirectoryId From fsc_Directories DD WHERE DD.Path LIKE ('%.' + CAST(@DirectoryId AS VARCHAR(10)) + '.%'))
		OR
		F.DirectoryId = @DirectoryId
	)
	AND
	(
		@Keyword IS NULL
		OR
		F.[Name] LIKE '%'+@Keyword+'%'
	)
	AND
	(
		@ContentType IS NULL
		OR
		CT.ContentTypeId = @ContentType
	)
	AND
	(
		@ModifiedFrom IS NULL
		OR
		F.Modified >= @ModifiedFrom
	)
	AND
	(
		@ModifiedTo IS NULL
		OR
		F.Modified <= @ModifiedTo
	)
	AND
	(
		@LengthFrom IS NULL
		OR
		DATALENGTH(FB.Data) >= @LengthFrom
	)
	AND
	(
		@LengthTo IS NULL
		OR
		DATALENGTH(FB.Data) <= @LengthTo
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ForeignContainerKeyAdd
	@ContainerKey NVARCHAR(50),
	@ForeignContainerKey NVARCHAR(50)
AS
	SET NOCOUNT ON
	IF NOT EXISTS(SELECT * FROM fsc_ForeignContainerKeys WHERE ContainerKey = @ContainerKey AND ForeignContainerKey = @ForeignContainerKey)
		INSERT INTO fsc_ForeignContainerKeys (ContainerKey, ForeignContainerKey) VALUES (@ContainerKey, @ForeignContainerKey)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ForeignContainerKeyDelete
	@ContainerKey NVARCHAR(50),
	@ForeignContainerKey NVARCHAR(50) = NULL
AS
	DELETE FROM fsc_ForeignContainerKeys WHERE ContainerKey = @ContainerKey AND (ForeignContainerKey = @ForeignContainerKey OR @ForeignContainerKey IS NULL)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumCreate
@ContainerKey nvarchar(50),
@Name nvarchar(255),
@Description ntext,
@Created datetime,
@Retval int out
AS
INSERT INTO [fsc_Forums] ([ContainerKey], [Created], [Name], [Description])
VALUES(@ContainerKey, @Created, @Name, @Description)
SET @Retval = @@IDENTITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumDeleteByContainerKey
	@ContainerKey nvarchar(50)
AS
	DELETE FROM [fsc_Forums] WHERE ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumDeleteById
	@ForumId INT
AS
	DELETE FROM [fsc_Forums] WHERE ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumGet
	@ForumId INT
AS
SELECT [ForumId], [ContainerKey], [Created], [Name], [Description] FROM [fsc_Forums]
WHERE ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumRename
	@ForumId int,
	@NewName nvarchar(255),
	@NewDescription ntext
AS
	UPDATE [fsc_Forums]
	SET [Name]=@NewName, [Description] = @NewDescription
	WHERE ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ForumsDeleteByContainerKey
	@ContainerKey NVARCHAR(50)
AS
	DELETE FROM fsc_Forums WHERE ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ForumsGetByContainerKey
	@ContainerKey NVARCHAR(50)
AS
SELECT [ForumId], [ContainerKey], [Created], [Name], [Description]  FROM fsc_Forums
WHERE ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumTheradNodesGetByContainerKey
@ContainerKey NVARCHAR(50)
AS
SELECT FTN.[NodeId], FTN.[ThreadId], FTN.[Text], FTN.[Created], FTN.[CreatorId], FTN.[CreatorName], FTN.[CreatorEmail]
FROM [fsc_ForumThreadNodes] FTN
	INNER JOIN fsc_ForumThreads FT ON FTN.ThreadId = FT.ThreadId
	INNER JOIN fsc_Forums F ON F.ForumId = FT.ForumId
WHERE F.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumTheradNodesGetByForumId
@ForumId INT
AS
SELECT FTN.[NodeId], FTN.[ThreadId], FTN.[Text], FTN.[Created], FTN.[CreatorId], FTN.[CreatorName], FTN.[CreatorEmail]
FROM [fsc_ForumThreadNodes] FTN
INNER JOIN fsc_ForumThread FT ON FTN.[ThreadId] =  FT.[ThreadId]
WHERE FT.ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumTheradNodesGetByThreadId
@ThreadId INT
AS
SELECT FTN.[NodeId], FTN.[ThreadId], FTN.[Text], FTN.[Created], FTN.[CreatorId], FTN.[CreatorName], FTN.[CreatorEmail]
FROM [fsc_ForumThreadNodes] FTN
WHERE FTN.ThreadId = @ThreadId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumTheradsGetByContainerKey
@ContainerKey NVARCHAR(50)
AS
SELECT FT.[ThreadId], FT.[ForumId], FT.[Created], FT.[Name] FROM [fsc_ForumThreads] FT
INNER JOIN fsc_Forums F ON F.ForumId = FT.ForumId
WHERE F.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumTheradsGetByForumId
@ForumId INT
AS
SELECT [ThreadId], [ForumId], [Created], [Name] FROM [fsc_ForumThreads]
WHERE ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadCreate
@ForumId int,
@Name nvarchar(255),
@Created datetime,
@Retval int out
AS
IF NOT EXISTS(SELECT * FROM fsc_Forums WHERE ForumId = @ForumId )
BEGIN
	RAISERROR ('Invalid @ForumId. The folder doesn''t exist or isn''t  in the current container', 16,1)
	GOTO ERR
END
INSERT INTO [fsc_ForumThreads]([ForumId], [Created], [Name])
VALUES(@ForumId,@Created,@Name)
SET @Retval = @@IDENTITY
RETURN
ERR:
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadDeleteByForumId
	@ForumId INT
AS
	DELETE FROM dbo.fsc_ForumThreads
	WHERE ForumId = @ForumId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadDeleteById
	@ThreadId INT
AS
	DELETE FROM dbo.fsc_ForumThreads
	WHERE ThreadId = @ThreadId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadGet
	@ThreadId INT
AS
	SELECT [ThreadId], [ForumId], [Created], [Name] FROM [fsc_ForumThreads]
	WHERE ThreadId = @ThreadId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeCreate
@ThreadId int,
@Text ntext,
@Created datetime,
@CreatorId int,
@CreatorName nvarchar(255),
@CreatorEmail nvarchar(50),
@Retval int out
AS
INSERT INTO [fsc_ForumThreadNodes]([ThreadId], [Text], [Created], [CreatorId], [CreatorName], [CreatorEmail])
VALUES(@ThreadId, @Text, @Created, @CreatorId, @CreatorName, @CreatorEmail)
SET @Retval = @@IDENTITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeDeleteById
	@NodeId INT
AS
	DELETE FROM fsc_ForumThreadNodes
	WHERE NodeId = @NodeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeDeleteByThreadId
	@ThreadId INT
AS
	DELETE FROM fsc_ForumThreadNodes
	WHERE ThreadId = @ThreadId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeGet
	@NodeId INT
AS
	SELECT [NodeId], [ThreadId], [Text], [Created], [CreatorId], [CreatorName], [CreatorEmail] FROM [fsc_ForumThreadNodes]
	WHERE NodeId = @NodeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeSetText
	@NodeId int,
	@Text ntext
AS
	UPDATE [fsc_ForumThreadNodes]
	SET [Text]=@Text
	WHERE NodeId = @NodeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadNodeSimpleCreate
@ContainerKey nvarchar(50),
@Text ntext,
@Created datetime,
@CreatorId int,
@CreatorName nvarchar(255),
@CreatorEmail nvarchar(50),
@Retval int out
AS
DECLARE @ForumId INT
DECLARE @ThreadId INT
BEGIN TRAN
SET @ForumId = (SELECT TOP 1 ForumId FROM fsc_Forums WHERE ContainerKey = @ContainerKey)
IF @ForumId IS NULL
BEGIN
	EXEC fsc_ForumCreate @ContainerKey, 'Default', 'Auto-generated forum', @Created, @ForumId OUTPUT
	IF @@ERROR<>0 GOTO ERR
END
SET @ThreadId = (SELECT TOP 1 ThreadId FROM fsc_ForumThreads WHERE ForumId = @ForumId)
IF @ThreadId IS NULL
BEGIN
	EXEC fsc_ForumThreadCreate @ForumId, 'Default', @Created, @ThreadId OUTPUT
	IF @@ERROR<>0 GOTO ERR
END
INSERT INTO [fsc_ForumThreadNodes]([ThreadId], [Text], [Created], [CreatorId], [CreatorName], [CreatorEmail])
VALUES(@ThreadId, @Text, @Created, @CreatorId, @CreatorName, @CreatorEmail)
IF @@ERROR<>0 GOTO ERR
SET @Retval = @@IDENTITY
COMMIT TRAN
RETURN
ERR:
ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadRename
	@ThreadId int,
	@NewName nvarchar(255)
AS
	UPDATE [fsc_ForumThreads]
	SET [Name]=@NewName
	WHERE ThreadId = @ThreadId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].fsc_ForumThreadSimpleCreate
@ContainerKey nvarchar(50),
@Name nvarchar(255),
@Created datetime,
@Retval int out
AS
DECLARE @ForumId INT
BEGIN TRAN
SET @ForumId = (SELECT TOP 1 ForumId FROM fsc_Forums WHERE ContainerKey = @ContainerKey)
IF @ForumId IS NULL
BEGIN
	EXEC fsc_ForumCreate @ContainerKey, 'Default', 'Auto-generated forum', @Created, @ForumId OUTPUT
	IF @@ERROR<>0 GOTO ERR
END
INSERT INTO [fsc_ForumThreads]([ForumId], [Created], [Name])
VALUES(@ForumId,@Created,@Name)
IF @@ERROR<>0 GOTO ERR
SET @Retval = @@IDENTITY
COMMIT TRAN
RETURN
ERR:
ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ReportAccessControlEntriesClear
	@AclId INT
AS
	DELETE FROM fsc_ReportAccessControlEntries WHERE AclId = @AclId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ReportAccessControlEntriesGet
	@ReportId INT
AS
SELECT
	ACL.AclId, ACL.ReportId, ACE.AceId, ACE.Role, ACE.PrincipalId, ACE.[Action], ACE.Allow
FROM fsc_ReportAccessControlEntries ACE
	RIGHT JOIN fsc_ReportAccessControlLists ACL ON ACL.AclId = ACE.AclId
WHERE
	ACL.ReportId = @ReportId AND (ACE.IsInternal = 0 OR ACE.IsInternal IS NULL)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ReportAccessControlEntriesGetAclIdByReportId
	@ReportId int,
	@retVal int output
AS
	SELECT @retVal = AclId FROM fsc_ReportAccessControlLists WHERE ReportId=@ReportId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ReportAccessControlEntryAdd
	@AclId int,
	@Role nvarchar(50),
	@PrincipalId int,
	@Action nvarchar(50),
	@Allow bit,
	@IsInternal bit,
	@Retval int out
AS
	INSERT INTO  fsc_ReportAccessControlEntries
		(AclId, Role, PrincipalId, [Action], Allow,  IsInternal )
	VALUES
		(@AclId, @Role, @PrincipalId, @Action, @Allow, @IsInternal)
	SET @Retval = @@IDENTITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].fsc_ReportCanUserRunAction
	@UserId INT,
	@ContainerKey NVARCHAR(50),
	@ReportId INT,
	@Action NVARCHAR(50),
	@Retval INT OUT
AS
SET NOCOUNT ON
SET @Retval = (SELECT TOP 1 Allow
	FROM fsc_ReportAccessControlEntries ACE
	INNER JOIN fsc_ReportAccessControlLists ACL ON ACE.AclId = ACL.AclId
	INNER JOIN fsc_Reports D ON ACL.ReportId = D.ReportId
	LEFT JOIN fsc_UserRoles R ON
		R.Role = ACE.Role  AND
		R.PrincipalId = @UserId AND
		(R.ContainerKey = @ContainerKey OR R.ContainerKey IS NULL OR R.ContainerKey IN (SELECT ForeignContainerKey FROM fsc_ForeignContainerKeys WHERE  ContainerKey =  R.ContainerKey))
	LEFT JOIN Principals P ON P.PrincipalId = ACE.PrincipalId
WHERE
	ACE.[Action] = @Action
	AND
	D.ContainerKey = @ContainerKey
	AND
	D.ReportId = @ReportId
	AND
	(
		(
			(R.Role IS NOT NULL)
			OR
			(P.IsGroup = 0 AND P.PrincipalId=@UserId)
			OR
			(P.IsGroup = 1 AND EXISTS(SELECT * FROM USER_GROUP UG WHERE UG.UserId = @UserId AND UG.GroupId=P.PrincipalId))
		)
	)
ORDER BY R.Role, ACE.Allow )
IF @Retval IS NULL
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportCategoryCreate]
	@Name NVARCHAR(255),
	@Retval INT OUT
AS
	IF EXISTS(SELECT * FROM fsc_ReportCategories WHERE [Name] = @Name)
	BEGIN
		SET @Retval  = (SELECT TOP 1 ReportCategoryId FROM fsc_ReportCategories WHERE [Name] = @Name )
	END
	ELSE
	BEGIN
		INSERT INTO fsc_ReportCategories ([Name]) VALUES (@Name)
		SET @Retval = @@IDENTITY
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportCategoryGetList]
AS
	SELECT ReportCategoryId, [Name] FROM fsc_ReportCategories
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportCreate]
	@ContainerKey NVARCHAR(50),
	@ReportName NVARCHAR(255),
	@Retval INT OUT
AS
	INSERT INTO [dbo].fsc_Reports ([Name], ContainerKey) VALUES (@ReportName, @ContainerKey)
	SET @Retval = @@IDENTITY
	INSERT INTO fsc_ReportAccessControlLists(ReportId) VALUES (@Retval)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportGetByCategory]
	@ContainerKey NVARCHAR(50),
	@ReportCategoryName NVARCHAR(255)
AS
	SELECT R.ReportId, R.[Name], R.ReportCategoryId, RC.Name as ReportCategoryName
	FROM fsc_Reports R
		LEFT JOIN fsc_ReportCategories RC ON R.ReportCategoryId = RC.ReportCategoryId
	WHERE RC.Name = @ReportCategoryName AND R.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportGetById]
	@ContainerKey NVARCHAR(50),
	@ReportId INT
AS
	SELECT R.ReportId, R.[Name], R.ReportCategoryId, RC.Name as ReportCategoryName
	FROM fsc_Reports R
		LEFT JOIN fsc_ReportCategories RC ON R.ReportCategoryId = RC.ReportCategoryId
	WHERE R.ReportId = @ReportId AND R.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportGetByName]
	@ContainerKey NVARCHAR(50),
	@ReportName NVARCHAR(255)
AS
	SELECT R.ReportId, R.[Name], R.ReportCategoryId, RC.Name as ReportCategoryName
	FROM fsc_Reports R
		LEFT JOIN fsc_ReportCategories RC ON R.ReportCategoryId = RC.ReportCategoryId
	WHERE R.[Name] = @ReportName AND R.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportGetList]
	@ContainerKey NVARCHAR(50)
AS
	SELECT R.ReportId, R.[Name], R.ReportCategoryId, RC.Name as ReportCategoryName
	FROM fsc_Reports R
		LEFT JOIN fsc_ReportCategories RC ON R.ReportCategoryId = RC.ReportCategoryId
	WHERE R.ContainerKey = @ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_ReportSetCategory]
	@ReportId INT,
	@ReportCategoryId INT
AS
	UPDATE fsc_Reports SET ReportCategoryId = @ReportCategoryId WHERE ReportId = @ReportId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_UserRoleAdd]
	@PrincipalId int,
	@ContainerKey nvarchar(50),
	@Role nvarchar(50),
	@Retval int output
AS
	IF EXISTS(SELECT * FROM fsc_UserRoles WHERE PrincipalId = @PrincipalId AND ContainerKey = @ContainerKey AND Role = @Role)
	BEGIN
		SELECT @Retval =  UserRoleId FROM fsc_UserRoles WHERE PrincipalId = @PrincipalId AND ContainerKey = @ContainerKey AND Role = @Role
	END
	ELSE
	BEGIN
		INSERT INTO fsc_UserRoles (PrincipalId, ContainerKey, Role)
		VALUES (@PrincipalId, @ContainerKey, @Role)
		SELECT @Retval =@@identity
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_UserRoleDeleteByContainerKey]
	@ContainerKey nvarchar(50)
AS
	SET NOCOUNT ON
	DELETE FROM fsc_ForeignContainerKeys WHERE ContainerKey=@ContainerKey OR ForeignContainerKey=@ContainerKey
	DELETE FROM fsc_UserRoles WHERE ContainerKey=@ContainerKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_UserRoleDeleteByRole]
	@ContainerKey nvarchar(50),
	@Role nvarchar(50)
AS
	SET NOCOUNT ON
	IF @ContainerKey IS NULL
		DELETE FROM fsc_UserRoles WHERE ContainerKey IS NULL AND Role=@Role
	ELSE
		DELETE FROM fsc_UserRoles WHERE ContainerKey=@ContainerKey AND Role=@Role
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_UserRoleDeleteByUser]
	@PrincipalId int,
	@ContainerKey nvarchar(50),
	@Role nvarchar(50)
AS
	SET NOCOUNT ON
	IF @ContainerKey IS NULL
		DELETE FROM fsc_UserRoles WHERE PrincipalId=@PrincipalId AND ContainerKey IS NULL AND Role=@Role
	ELSE
		DELETE FROM fsc_UserRoles WHERE PrincipalId=@PrincipalId AND ContainerKey=@ContainerKey AND Role=@Role
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[fsc_UserRoleListByRole]
	@ContainerKey nvarchar(50),
	@Role nvarchar(50)
AS
	IF @ContainerKey IS NULL
		SELECT PrincipalId FROM fsc_UserRoles WHERE ContainerKey IS NULL AND Role=@Role
	ELSE
		SELECT PrincipalId FROM fsc_UserRoles WHERE ContainerKey=@ContainerKey AND Role=@Role
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupChangeParent
	@PrincipalId as int,
	@ParentPrincipalId as int
as
Declare @cur_user_id as int
Declare @cur_group_id as int
Declare @child_group_id as int
Declare @parent_group_id as int
BEGIN TRAN
 	Declare Cur_Group Cursor For
	Select [PrincipalID] From Groups Where ([PrincipalId]<>1)AND([PrincipalId] <>@PrincipalId)
	Open Cur_Group
	Create Table #Temp
	(
		[User_ID] int,
		[Parent_ID] int
	)
	Insert Into #Temp
		Select C.[PrincipalId], C.[ParentPrincipalId] From Containership AS C, [Users] As U
			Where (C.[ParentPrincipalId]=@PrincipalId) AND (C.[PrincipalId]=U.[PrincipalId])
	If @@error <> 0
		Goto ErrorLabel
	Fetch Next From Cur_Group Into @cur_group_id
	While @@Fetch_Status = 0
	Begin
		set @child_group_id = @cur_group_id
		Select @parent_group_id=[ParentPrincipalId] From Containership
			Where [PrincipalId]=@child_group_id
		While(@@rowcount>0)AND(@parent_group_id<>1)AND(@parent_group_id<>@PrincipalId)
		Begin
			set @child_group_id=@parent_group_id
			Select @parent_group_id=[ParentPrincipalId] From Containership
					Where [PrincipalId]=@child_group_id
		End
		If @parent_group_id=@PrincipalId
		Begin
			Insert Into #Temp
				Select C.[PrincipalId], C.[ParentPrincipalId] From Containership AS C, [Users] As U
					Where (C.[ParentPrincipalId]=@cur_group_id) AND (C.[PrincipalId]=U.[PrincipalId])
			If @@error <> 0
				Goto ErrorLabel
		End
		Fetch Next From Cur_Group Into @cur_group_id
	End
	Close Cur_Group
	Deallocate Cur_Group
	Declare Cur_Records Cursor For
	Select [User_ID], [Parent_ID] From #Temp
	Open Cur_Records
	Fetch Next From Cur_Records Into @cur_user_id, @cur_group_id
	While @@Fetch_Status = 0
	Begin
		exec UserDeleteFromGroup @cur_user_id, @cur_group_id
		If @@error <> 0
			Goto ErrorLabel
		Fetch Next From Cur_Records Into @cur_user_id, @cur_group_id
	End
	Close Cur_Records
	Deallocate Cur_Records
	Update Containership SET [ParentPrincipalId]=@ParentPrincipalId Where [PrincipalId]=@PrincipalId
	If @@error <> 0
		Goto ErrorLabel
	Declare Cur_Records Cursor For
	Select [User_ID], [Parent_ID] From #Temp
	Open Cur_Records
	Fetch Next From Cur_Records Into @cur_user_id, @cur_group_id
	While @@Fetch_Status = 0
	Begin
		exec UserAddToGroup @cur_user_id, @cur_group_id
		If @@error <> 0
			Goto ErrorLabel
		Fetch Next From Cur_Records Into @cur_user_id, @cur_group_id
	End
	Close Cur_Records
	Deallocate Cur_Records
	Drop Table #Temp
COMMIT TRAN
RETURN
ErrorLabel:
	ROLLBACK TRAN
	RAISERROR('Parent group is not changed', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupCheckChildren
	@GroupId int,
	@retval int output
as
IF EXISTS(SELECT * FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId)
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupCreate
	@ParentPrincipalId as int,
	@GroupName as nvarchar(50) ,
	@retval int output
as
BEGIN TRAN
	INSERT INTO PRINCIPALS (IsGroup) VALUES (1)
	IF @@error != 0
		GOTO err
	SELECT @retval = @@identity
	INSERT INTO GROUPS (PrincipalId, GroupName)
	  VALUES(@retval, @GroupName)
	IF @@error != 0
		GOTO err
	INSERT INTO CONTAINERSHIP (PrincipalId, ParentPrincipalId) VALUES (@retval, @ParentPrincipalId)
	IF @@error != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RAISERROR('Group is not created', 16, 1)
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupCreate2
	@GroupID as int,
	@GroupName as nvarchar(50)
as
BEGIN TRAN
	SET IDENTITY_INSERT PRINCIPALS ON
	 INSERT INTO PRINCIPALS (PrincipalId, IsGroup) VALUES (@GroupId, 1)
	 IF @@error != 0
	 	GOTO err
	 INSERT INTO GROUPS (PrincipalId, GroupName)
		VALUES(@GroupId, @GroupName)
	IF @@error != 0
		GOTO err
	INSERT INTO CONTAINERSHIP (PrincipalId, ParentPrincipalId) VALUES (@GroupId, 1)
	IF @@error != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	SET IDENTITY_INSERT PRINCIPALS OFF
	ROLLBACK TRAN
	RAISERROR('Group is not created', 16, 1)
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupCreateForInstall
	@GroupId as int,
	@ParentGroupId as int,
	@GroupName as nvarchar(50)
as
SET IDENTITY_INSERT PRINCIPALS ON
BEGIN TRAN
	INSERT INTO PRINCIPALS (PrincipalId, IsGroup) VALUES (@GroupId, 1)
	IF @@error != 0
		GOTO err
	INSERT INTO GROUPS (PrincipalId, GroupName)
	  VALUES(@GroupId, @GroupName)
	IF @@error != 0
		GOTO err
	IF @ParentGroupId > 0
	BEGIN
		INSERT INTO CONTAINERSHIP (PrincipalId, ParentPrincipalId) VALUES (@GroupId, @ParentGroupId)
		IF @@error != 0
			GOTO err
	END
COMMIT TRAN
SET IDENTITY_INSERT PRINCIPALS ON
RETURN
err:
	ROLLBACK TRAN
	SET IDENTITY_INSERT PRINCIPALS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupDelete
	@GroupId as int
as
BEGIN TRAN
	DELETE FROM BroadCastRecipients WHERE GroupId = @GroupId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM EVENT_RESOURCES WHERE PrincipalId = @GroupId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM INCIDENT_RESOURCES WHERE PrincipalId = @GroupId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM PARTNER_GROUP WHERE GroupId = @GroupId OR PartnerId = @GroupId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM GROUPS WHERE PrincipalId = @GroupId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM PRINCIPALS WHERE PrincipalId = @GroupId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupGet
       @PrincipalId as int
as
SELECT PrincipalId AS GroupId, GroupName, IMGroupId
  FROM GROUPS
  WHERE PrincipalId = @PrincipalId or @PrincipalId=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupGetForPartnerUser
	@PrincipalId as int,
	@retval as int output
as
SELECT @retval = ParentPrincipalId
  FROM CONTAINERSHIP
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupGetParent
	@PrincipalId as int,
	@retval as int output
as
SELECT @retval = ParentPrincipalId
  FROM CONTAINERSHIP
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGet
	@IncludeEveryone as bit,
	@IncludeAdmin as bit,
	@IncludePM as bit,
	@IncludePPM as bit,
	@IncludeHDM as bit,
	@IncludePartner as bit,
	@IncludeSubPartners as bit,
	@IncludeExecutive as bit,
	@IncludeRoles as bit,
	@IncludeIntranet as bit
as
DECLARE @Everyone int
SET @Everyone = 1
DECLARE @Admin int
SET @Admin = 2
DECLARE @PM int
SET @PM = 3
DECLARE @PPM int
SET @PPM = 4
DECLARE @HDM int
SET @HDM = 5
DECLARE @Partner int
SET @Partner = 6
DECLARE @Executive int
SET @Executive = 7
DECLARE @Roles int
SET @Roles = 8
DECLARE @Intranet int
SET @Intranet = 9
SELECT PrincipalId AS GroupId, GroupName
  FROM GROUPS
  WHERE (PrincipalId <> @Everyone OR @IncludeEveryone = 1)
	AND (PrincipalId <> @Admin OR @IncludeAdmin = 1)
	AND (PrincipalId <> @PM OR @IncludePM = 1)
	AND (PrincipalId <> @PPM OR @IncludePPM = 1)
	AND (PrincipalId <> @HDM OR @IncludeHDM = 1)
	AND (PrincipalId <> @Partner OR @IncludePartner = 1)
	AND (PrincipalId NOT IN (SELECT PrincipalId FROM Containership WHERE ParentPrincipalId = @Partner) OR @IncludeSubPartners = 1)
	AND (PrincipalId <> @Executive OR @IncludeExecutive = 1)
	AND (PrincipalId <> @Roles OR @IncludeRoles = 1)
	AND (PrincipalId <> @Intranet OR @IncludeIntranet = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetAsTree
as
DECLARE @GroupId int
DECLARE @ParentGroupId int
DECLARE @NewParentGroupId int
DECLARE @Table TABLE(GroupId int, OutlineNumber varchar(100), OutlineLevel int)
DECLARE @CharGroupId varchar(10)
DECLARE @OutlineNumber varchar(1000)
DECLARE @OutlineLevel int
DECLARE Cur_Group CURSOR FOR
	SELECT PrincipalID FROM GROUPS WHERE PrincipalId<>1
OPEN Cur_Group
FETCH NEXT FROM Cur_Group INTO @GroupId
WHILE @@Fetch_Status = 0
BEGIN
	SET @CharGroupId = CONVERT(varchar(10), @GroupId)
	SET @OutlineNumber = REPLICATE('0', 10 - LEN(@CharGroupId)) + @CharGroupId
	SET @OutlineLevel = 0
	SET @ParentGroupId = @GroupId
	WHILE @ParentGroupId != 1
	BEGIN
		SELECT @NewParentGroupId = ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId = @ParentGroupId
		SET @OutlineLevel = @OutlineLevel + 1
		SET @CharGroupId = CONVERT(varchar(10), @NewParentGroupId)
		SET @OutlineNumber = REPLICATE('0', 10 - LEN(@CharGroupId)) + @CharGroupId + '.' + @OutlineNumber
		SET @ParentGroupId = @NewParentGroupId
	END
	INSERT INTO @Table (GroupId, OutlineNumber, OutlineLevel) VALUES (@GroupId, LEFT(@OutlineNumber, 100), @OutlineLevel)
	FETCH NEXT FROM Cur_Group INTO @GroupId
END
CLOSE Cur_Group
DEALLOCATE Cur_Group
SELECT T.GroupId, G.GroupName, T.OutlineLevel AS [Level]
  FROM @Table T, GROUPS G
  WHERE T.GroupId = G.PrincipalId
  ORDER BY OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetAsTree2
as
DECLARE @GroupId int
DECLARE @ParentGroupId int
DECLARE @NewParentGroupId int
DECLARE @Table TABLE(GroupId int, OutlineNumber varchar(100), OutlineLevel int)
DECLARE @CharGroupId varchar(10)
DECLARE @OutlineNumber varchar(1000)
DECLARE @OutlineLevel int
DECLARE Cur_Group CURSOR FOR
	SELECT PrincipalID FROM GROUPS ORDER BY GroupName
OPEN Cur_Group
FETCH NEXT FROM Cur_Group INTO @GroupId
WHILE @@Fetch_Status = 0
BEGIN
	SET @CharGroupId = CONVERT(varchar(10), @GroupId)
	SET @OutlineNumber = REPLICATE('0', 10 - LEN(@CharGroupId)) + @CharGroupId
	SET @OutlineLevel = 0
	SET @ParentGroupId = @GroupId
	WHILE @ParentGroupId != 1
	BEGIN
		SELECT @NewParentGroupId = ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId = @ParentGroupId
		SET @OutlineLevel = @OutlineLevel + 1
		SET @CharGroupId = CONVERT(varchar(10), @NewParentGroupId)
		SET @OutlineNumber = REPLICATE('0', 10 - LEN(@CharGroupId)) + @CharGroupId + '.' + @OutlineNumber
		SET @ParentGroupId = @NewParentGroupId
	END
	INSERT INTO @Table (GroupId, OutlineNumber, OutlineLevel) VALUES (@GroupId, LEFT(@OutlineNumber, 100), @OutlineLevel)
	FETCH NEXT FROM Cur_Group INTO @GroupId
END
CLOSE Cur_Group
DEALLOCATE Cur_Group
SELECT T.GroupId, G.GroupName, T.OutlineLevel AS [Level]
  FROM @Table T, GROUPS G
  WHERE T.GroupId = G.PrincipalId
  ORDER BY OutlineNumber
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetAvailable
as
SELECT PrincipalId AS GroupId, GroupName
  FROM GROUPS
  WHERE PrincipalId <> 1 AND PrincipalId <> 5
	AND PrincipalId IN
		(SELECT ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId IN
		(SELECT PrincipalId FROM USERS))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetAvailableForPartner
	@PrincipalId as int
as
DECLARE @PartnerId int
SELECT @PartnerId = ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId  = @PrincipalId
SELECT PrincipalId AS GroupId, GroupName
  FROM GROUPS
  WHERE PrincipalId <> 1 AND PrincipalId <> 5
	AND PrincipalId IN
		(SELECT ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId IN
		(SELECT PrincipalId FROM USERS))
	AND (PrincipalId = @PartnerId
		OR PrincipalId IN (SELECT GroupId FROM PARTNER_GROUP WHERE PartnerId = @PartnerId))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetByParent
       @GroupId as int
as
SELECT PrincipalId AS GroupId, GroupName,
	CASE WHEN EXISTS(SELECT * FROM CONTAINERSHIP C WHERE C.ParentPrincipalId = G.PrincipalId) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS HasChildren
  FROM GROUPS G
  WHERE PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId)
  ORDER BY GroupName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetByUser
	@PrincipalId int
AS
SELECT ParentPrincipalId AS GroupId, G.GroupName
  FROM CONTAINERSHIP C JOIN GROUPS G ON (C.ParentPrincipalId = G.PrincipalId)
  WHERE C.PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetByUser_All
	@PrincipalId int
AS
SELECT GroupId
  FROM USER_GROUP
  WHERE UserId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsGetForMove
	@GroupId as int
as
DECLARE @PartnerGroupId int
SET @PartnerGroupId = 6
Declare @cur_group_id as int
Declare @child_group_id as int
Declare @parent_group_id as int
Declare @cur_group_name as nvarchar(100)
BEGIN TRAN
	Declare Cur_Group Cursor For
	Select [PrincipalID], [GroupName] From Groups Where ([PrincipalId] = 1 OR [PrincipalId] > 9) AND [PrincipalId] <>@GroupId
		AND PrincipalID NOT IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @PartnerGroupId)
	Open Cur_Group
	Create Table #Temp
	(
		[GroupID] int,
		[GroupName] nvarchar(100)
	)
	Fetch Next From Cur_Group Into @cur_group_id, @cur_group_name
		While @@Fetch_Status = 0
		Begin
			set @child_group_id = @cur_group_id
			Select @parent_group_id=[ParentPrincipalId] From Containership
				Where [PrincipalId]=@child_group_id
			While(@@rowcount>0)AND(@parent_group_id<>1)AND(@parent_group_id<>@GroupId)
			Begin
				set @child_group_id=@parent_group_id
				Select @parent_group_id=[ParentPrincipalId] From Containership
						Where [PrincipalId]=@child_group_id
			End
			If @parent_group_id<>@GroupId
			Begin
				Insert Into #Temp
					([GroupID], [GroupName])
					Values (@cur_group_id, @cur_group_name)
				If @@error <> 0
					Goto ErrorLabel
			End
			Fetch Next From Cur_Group Into @cur_group_id, @cur_group_name
		End
		Close Cur_Group
		Deallocate Cur_Group
	SELECT GroupId, GroupName  FROM #Temp
	Drop Table #Temp
COMMIT TRAN
RETURN
ErrorLabel:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsSearch
	@SubString as nvarchar(50)
as
SET @SubString = '%' + @SubString + '%'
SELECT PrincipalId AS GroupId, GroupName,
	CASE WHEN EXISTS(SELECT * FROM CONTAINERSHIP C WHERE C.ParentPrincipalId = G.PrincipalId) THEN 1 ELSE 0 END AS HasChildren
  FROM GROUPS G
  WHERE GroupName LIKE @SubString
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupsSearchForPartner
	@SubString as nvarchar(50),
	@PrincipalId as int
as
SET @SubString = '%' + @SubString + '%'
DECLARE @PartnerId int
SELECT @PartnerId = ParentPrincipalId FROM CONTAINERSHIP WHERE PrincipalId  = @PrincipalId
SELECT PrincipalId AS GroupId, GroupName,
	CASE WHEN EXISTS(SELECT * FROM CONTAINERSHIP C WHERE C.ParentPrincipalId = G.PrincipalId) THEN 1 ELSE 0 END AS HasChildren
  FROM GROUPS G
  WHERE GroupName LIKE @SubString
	AND (PrincipalId = @PartnerId OR PrincipalId IN (SELECT GroupId FROM PARTNER_GROUP WHERE PartnerId = @PartnerId))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupUpdate
	@PrincipalId as int,
	@GroupName as nvarchar(50)
as
UPDATE GROUPS SET GroupName = @GroupName WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].GroupUpdateIMGroupId
	@PrincipalId as int,
	@IMGroupId as int
as
UPDATE GROUPS
  SET IMGroupId = @IMGroupId
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].HistoryAdd
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@ObjectTitle nvarchar(250),
	@UserId as int
AS
IF  NOT EXISTS(SELECT * FROM HISTORY WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId)
	INSERT INTO HISTORY (ObjectTypeId, ObjectId, UserId, ObjectTitle) VALUES(@ObjectTypeId, @ObjectId, @UserId, @ObjectTitle)
ELSE
	UPDATE HISTORY
	  SET Dt = getutcdate(), ObjectTitle = @ObjectTitle
	  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].HistoryGet
	@UserId as int
as
SELECT TOP 100 HistoryId, ObjectTypeId, ObjectId, ObjectTitle, Dt
  FROM HISTORY
  WHERE UserId = @UserId
  ORDER BY Dt DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].HistoryGetByObject
	@ObjectId as int,
	@ObjectTypeId as int
as
SELECT UserId, Dt
  FROM HISTORY
  WHERE ObjectId = @ObjectId AND ObjectTypeId = @ObjectTypeId
  ORDER BY Dt DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoriesGet
	@CategoryId as int
as
SELECT CategoryId, CategoryName
  FROM INCIDENT_CATEGORIES
  WHERE CategoryId = @CategoryId or @CategoryId=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoriesGetByIncident
	@IncidentId as int
as
SELECT CategoryId, CategoryName
  FROM INCIDENT_CATEGORIES
  WHERE CategoryId  IN
	(SELECT CategoryId FROM INCIDENT_CATEGORY WHERE IncidentId = @IncidentId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoriesGetForDictionaries
as
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName,
	CASE WHEN
		EXISTS(SELECT * FROM INCIDENT_CATEGORY I WHERE I.CategoryId = C.CategoryId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM INCIDENT_CATEGORIES C
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryAdd
	@CategoryName as nvarchar(100)
AS
INSERT INTO INCIDENT_CATEGORIES (CategoryName) VALUES(@CategoryName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryAssign
	@IncidentId as int ,
	@CategoryId as int
as
INSERT INTO INCIDENT_CATEGORY (IncidentId, CategoryId)
  VALUES(@IncidentId, @CategoryId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryDelete
	@CategoryId as int
as
DELETE FROM INCIDENT_CATEGORIES  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryRemove
	@IncidentId as int,
	@CategoryId as int
AS
DELETE FROM INCIDENT_CATEGORY
  WHERE IncidentId = @IncidentId AND CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryUpdate
	@CategoryId as int ,
	@CategoryName as nvarchar(100)
as
UPDATE INCIDENT_CATEGORIES SET CategoryName=@CategoryName
  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryUserAdd
	@CategoryId as int,
	@UserId as int
as
if NOT EXISTS(SELECT * FROM INCIDENTCATEGORY_USER WHERE CategoryId = @CategoryId AND UserId = @UserId)
	INSERT INTO INCIDENTCATEGORY_USER (CategoryId, UserId) VALUES(@CategoryId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryUserDelete
	@CategoryId as int,
	@UserId as int
as
DELETE FROM INCIDENTCATEGORY_USER
  WHERE CategoryId = @CategoryId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCategoryUserGetList
	@UserId as int
as
SELECT CategoryId, UserId
  FROM INCIDENTCATEGORY_USER
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCreate
	@ProjectId as int=null ,
	@CreatorId as int ,
	@ManagerId as int,
	@Title as nvarchar(255) ,
	@Description as ntext,
	@CreationDate as datetime ,
	@TypeId as int ,
	@PriorityId as int ,
	@StatusId as int ,
	@SeverityId as int ,
	@IsEmail as bit,
	@TaskTime int,
	@retval int output
as
DECLARE @StateId int
SELECT @StateId = StateId FROM INCIDENT_STATUS WHERE StatusId = @StatusId
INSERT INTO INCIDENTS (ProjectId, CreatorId, ManagerId, Title, [Description], CreationDate, TypeId, PriorityId, StatusId, SeverityId, IsEmail, StateId, TaskTime)
  VALUES(@ProjectId, @CreatorId, @ManagerId, @Title, @Description, @CreationDate, @TypeId, @PriorityId, @StatusId, @SeverityId, @IsEmail, @StateId, @TaskTime)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentCreatorsGet
as
SELECT DISTINCT I.CreatorId AS UserId, U.LastName + ', ' + U.FirstName AS UserName, U.FirstName +' '+ U.LastName AS UserName2
  FROM INCIDENTS I
	JOIN USERS U ON (I.CreatorId = U.PrincipalId)
  ORDER BY UserName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentDelete
	@IncidentId as int
as
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @IncidentObjectType AND ObjectId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @IncidentObjectType AND ObjectId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @IncidentObjectType AND ObjectId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE INCIDENT_RESOURCES WHERE IncidentId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE INCIDENT_RELATIONS WHERE IncidentId = @IncidentId OR RelIncidentId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @IncidentObjectType AND ObjectId = @IncidentId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @IncidentId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @IncidentObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM INCIDENTS  WHERE IncidentId = @IncidentId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentGet
	@IncidentId as int,
	@LanguageId as int
as
SELECT I.IncidentId, I.ProjectId, P.Title AS ProjectTitle, I.CreatorId, I.ManagerId, I.ActivatedBy, I.ClosedBy, I.Title, I.[Description], I.Resolution, I.Workaround,
	I.CreationDate, I.ActivationDate, I.CloseDate,
	I.TypeId, IT.TypeName, I.PriorityId, PR.PriorityName, I.StatusId, S.StatusName, I.SeverityId, SV.SeverityName, I.IsEmail, I.MailSenderEmail, I.StateId, I.TaskTime
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN INCIDENT_TYPES IT ON (I.TypeId = IT.TypeId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN INCIDENT_SEVERITY SV ON (I.SeverityId = SV.SeverityId)
  WHERE I.IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentGetProject
	@IncidentId as int,
	@Retval as int output
AS
SELECT @Retval = ProjectId FROM INCIDENTS WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentGetSecurityForUser
	@IncidentId as int,
	@UserId as int
as
SELECT IncidentId, PrincipalId, IsManager, IsCreator, IsResource
   FROM INCIDENT_SECURITY_ALL
  WHERE IncidentId = @IncidentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentGetStatus
	@IncidentId as int,
	@Retval as int output
AS
SELECT @Retval = StatusId FROM INCIDENTS WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentGetTitle
	@IncidentId as int
as
SELECT Title FROM INCIDENTS  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentManagerGet
	@IncidentId as int,
	@retval int output
as
SELECT @retval = ManagerId
  FROM INCIDENTS
  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentManagersGet
as
SELECT DISTINCT I.ManagerId AS UserId, U.LastName + ', ' + U.FirstName AS UserName, U.FirstName +' '+U.LastName AS UserName2
  FROM INCIDENTS I
	JOIN USERS U ON (I.ManagerId = U.PrincipalId)
  ORDER BY 2
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentRelationDelete
	@IncidentId as int,
	@RelIncidentId as int
AS
DELETE FROM INCIDENT_RELATIONS
  WHERE (IncidentId = @IncidentId AND RelIncidentId = @RelIncidentId)
	OR (IncidentId = @RelIncidentId AND RelIncidentId = @IncidentId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentRelatonAdd
	@IncidentId as int ,
	@RelIncidentId as int
as
IF NOT EXISTS(SELECT * FROM INCIDENT_RELATIONS WHERE (IncidentId = @IncidentId AND RelIncidentId = @RelIncidentId) OR (IncidentId = @RelIncidentId AND RelIncidentId = @IncidentId))
	INSERT INTO INCIDENT_RELATIONS (IncidentId, RelIncidentId) VALUES(@IncidentId, @RelIncidentId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentRelatonsGet
	@IncidentId as int,
	@UserId as int
as
DECLARE @IsPPMorExec bit
SET @IsPPMorExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPMorExec = 1
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 5)
	SET @IsHDM = 1
SELECT I.IncidentId, I.Title, I.ManagerId, I.StateId,
	CASE WHEN
		(@IsPPMorExec = 1
			OR (I.ProjectId IS NULL AND @IsHDM = 1)
			OR I.ProjectId IN
				(SELECT ProjectId FROM PROJECT_SECURITY
					WHERE PrincipalId = @UserId
						AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
				)
			OR I.IncidentId IN
				(SELECT IncidentId FROM INCIDENT_SECURITY_ALL
					WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsCreator = 1 OR IsResource = 1)
				)
		)
		THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanView
  FROM INCIDENTS I
  WHERE I.IncidentId IN (SELECT IncidentId FROM Incident_Relations WHERE RelIncidentId = @IncidentId)
	OR I.IncidentId IN (SELECT RelIncidentId FROM Incident_Relations WHERE IncidentId = @IncidentId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentResourceAdd
	@IncidentId as int ,
	@PrincipalId as int ,
	@MustBeConfirmed as bit,
	@CanManage as bit
as
IF EXISTS(SELECT * FROM INCIDENT_RESOURCES WHERE IncidentId = @IncidentId AND PrincipalId = @PrincipalId)
	UPDATE INCIDENT_RESOURCES
	  SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
	  WHERE IncidentId = @IncidentId AND PrincipalId = @PrincipalId
ELSE
	INSERT INTO INCIDENT_RESOURCES (IncidentId, PrincipalId, MustBeConfirmed, CanManage)
	  VALUES(@IncidentId, @PrincipalId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentResourceDelete
	@IncidentId as int ,
	@PrincipalId as int
as
DELETE FROM INCIDENT_RESOURCES WHERE IncidentId = @IncidentId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentResourceGetByUser
	@IncidentId as int,
	@UserId as int
as
SELECT MustBeConfirmed, ResponsePending, IsConfirmed
  FROM INCIDENT_RESOURCES
  WHERE IncidentId = @IncidentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentResourceReply
	@IncidentId as int,
	@UserId as int,
	@IsConfirmed as bit,
	@LastSavedDate as datetime
as
UPDATE INCIDENT_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = @LastSavedDate
  WHERE IncidentId = @IncidentId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentResourcesGet
	@IncidentId as int
as
SELECT IR.ResourceId, IR.IncidentId, IR.PrincipalId, P.IsGroup, IR.MustBeConfirmed, IR.ResponsePending, IR.IsConfirmed, IR.CanManage, IR.LastSavedDate,
	CASE WHEN U.IsExternal = 1 THEN 1 ELSE 0 END AS IsExternal
  FROM INCIDENT_RESOURCES IR
	JOIN PRINCIPALS P ON (IR.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (IR.PrincipalId = U.PrincipalId)
  WHERE IR.IncidentId = @IncidentId
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM INCIDENT_RESOURCES WHERE PrincipalId = @UserId)
	SET @Retval = 1
ELSE BEGIN
	IF EXISTS (SELECT * FROM INCIDENTS WHERE ManagerId = @UserId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM INCIDENTS WHERE CreatorId = @UserId OR ActivatedBy = @UserID OR ClosedBy = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsDeleteByProject
	@ProjectId as int
as
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
DELETE DISCUSSIONS WHERE ObjectTypeId = @IncidentObjectType AND ObjectId IN
	(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE EXTERNAL_GATE WHERE ObjectTypeId = @IncidentObjectType AND ObjectId IN
	(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @IncidentObjectType AND ObjectId IN
	(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE INCIDENT_RESOURCES WHERE IncidentId IN
	(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE INCIDENT_RELATIONS
  WHERE IncidentId IN
		(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
	OR RelIncidentId IN
		(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE FAVORITES WHERE ObjectTypeId = @IncidentObjectType AND ObjectId IN
	(SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DELETE SUBSCRIPTIONS WHERE ObjectId IN (SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId) AND
	EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @IncidentObjectType)
DELETE FROM INCIDENTS  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentSeverityAdd
	@SeverityName as nvarchar(50)
as
INSERT INTO INCIDENT_SEVERITY (SeverityName) VALUES(@SeverityName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentSeverityDelete
	@SeverityId as int
as
DELETE FROM INCIDENT_SEVERITY  WHERE SeverityId = @SeverityId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentSeverityGet
as
SELECT SeverityId, SeverityName
  FROM INCIDENT_SEVERITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentSeverityGetForDictionaries
as
SELECT S.SeverityId AS ItemId, S.SeverityName AS ItemName,
	CASE WHEN EXISTS(SELECT * FROM INCIDENTS I WHERE I.SeverityId = S.SeverityId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM INCIDENT_SEVERITY S
  ORDER BY S.SeverityName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentSeverityUpdate
	@SeverityId as int ,
	@SeverityName as nvarchar(50)
as
UPDATE INCIDENT_SEVERITY SET SeverityName=@SeverityName
  WHERE SeverityId = @SeverityId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByCategory
	@CategoryId as int,
	@LanguageId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
DECLARE @IncidentType int
SET @IncidentType = 7
SELECT I.IncidentId, I.Title, I.ProjectId, P.Title AS ProjectName, I.ManagerId, I.PriorityId, PR.PriorityName, I.StatusId, L.StatusName, I.StateId,
	CASE WHEN U.PrincipalId IS NOT NULL THEN U.FirstName + ' ' + U.LastName ELSE G.GroupName END AS ManagerName
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	LEFT JOIN USERS U ON (I.ManagerId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS S ON (I.StatusId = S.StatusId)
	JOIN INCIDENT_STATUS_LANGUAGE L ON (I.StatusId = L.StatusId AND L.LanguageId = @LanguageId)
  WHERE I.StateId != @ClosedState AND IncidentId IN
	(SELECT ObjectId FROM OBJECT_CATEGORY WHERE ObjectTypeId = @IncidentType AND CategoryId = @CategoryId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByFilter
	@ProjectId as int,
	@ManagerId as int,
	@CreatorId as int,
	@ResourceId as int,
	@PriorityId as int,
	@TypeId as int,
	@StatusId as int,
	@SeverityId int,
	@Keyword as nvarchar(100),
	@UserId as int,
	@LanguageId as int,
	@CategoryType as int,
	@IncidentCategoryType as int
as
SET @Keyword = '%' + @Keyword + '%'
DECLARE @NewState int
DECLARE @ActiveState  int
SET @NewState = 1
SET @ActiveState = 2
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @HDM int
SET @HDM = 5
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDM)
	SET @IsHDM = 1
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
SELECT I.IncidentId, I.ProjectId, P.Title AS ProjectTitle,
	I.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,  I.ManagerId,
	CASE WHEN U2.PrincipalId IS NOT NULL THEN U2.LastName + ', ' + U2.FirstName ELSE G.GroupName END AS ManagerName,
	I.ActivatedBy, I.ClosedBy, I.Title, I.CreationDate,
	I.TypeId, T.TypeName, I.PriorityId, PR.PriorityName, I.StatusId, S.StatusName, I.SeverityId, I.StateId,
	CASE WHEN (I.StateId = @NewState OR I.StateId = @ActiveState)
		AND (@IsPPM = 1 OR I.ManagerId = @UserId OR I.CreatorId = @UserId OR (I.ProjectId IS NULL AND @IsHDM = 1)) THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR I.ManagerId = @UserId OR (I.CreatorId = @UserId AND I.StateId = @NewState) OR (I.ProjectId IS NULL AND @IsHDM = 1) THEN 1 ELSE 0 END AS CanDelete
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_TYPES T ON (I.TypeId = T.TypeId)
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN USERS U1 ON (I.CreatorId = U1.PrincipalId)
	LEFT JOIN USERS U2 ON (I.ManagerId = U2.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
  WHERE
	(@ProjectId = 0 OR I.ProjectId = @ProjectId OR (@ProjectId = -1 AND I.ProjectId IS NULL))
	AND (@ManagerId = 0 OR I.IncidentId IN (SELECT IncidentId FROM INCIDENT_SECURITY WHERE PrincipalId = @ManagerId AND IsManager = 1))
	AND (@ResourceId = 0 OR I.IncidentId IN (SELECT IncidentId FROM INCIDENT_SECURITY_ALL WHERE PrincipalId = @ResourceId AND IsResource = 1))
	AND (@CreatorId = 0 OR I.CreatorId = @CreatorId)
	AND (@PriorityId = -1 OR I.PriorityId = @PriorityId)
	AND (@TypeId = 0 OR I.TypeId = @TypeId)
	AND (@SeverityId = 0 OR I.SeverityId = @SeverityId)
	AND
	(
		@StatusId = 0
		OR I.StatusId = @StatusId
		OR (@StatusId = -1 AND ( I.StateId = @NewState OR I.StateId = @ActiveState))
		OR (@StatusId = -2 AND ( I.StateId <> @NewState AND I.StateId <> @ActiveState))
	)
	AND (I.Title LIKE @Keyword OR I.[Description] LIKE @Keyword OR I.Resolution LIKE @Keyword OR I.Workaround LIKE @Keyword OR CAST(I.IncidentId AS nvarchar(10)) LIKE @Keyword)
	AND
	(	@IsPPM = 1 OR @IsExec = 1
		OR (I.ProjectId IS NULL AND @IsHDM = 1)
		OR I.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR I.IncidentId IN
			(SELECT IncidentId FROM INCIDENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsCreator = 1 OR IsResource = 1)
			)
	)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND I.IncidentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType = 2 AND I.IncidentId NOT IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType < 0 AND I.IncidentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType AND CategoryId = -@CategoryType
			)
	)
	AND (@IncidentCategoryType = 0
		OR @IncidentCategoryType = 1 AND I.IncidentId IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM INCIDENTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @IncidentCategoryType = 2 AND I.IncidentId NOT IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM INCIDENTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @IncidentCategoryType < 0 AND I.IncidentId IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId = -@IncidentCategoryType
			)
	)
  ORDER BY ProjectTitle
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByFilterGroupedByProject
	@ProjectId as int,
	@ManagerId as int,
	@CreatorId as int,
	@ResourceId as int,
	@PriorityId as int,
	@TypeId as int,
	@StatusId as int,
	@SeverityId int,
	@Keyword as nvarchar(100),
	@UserId as int,
	@LanguageId as int,
	@CategoryType as int,
	@IncidentCategoryType as int
as
SET @Keyword = '%' + @Keyword + '%'
DECLARE @NewState int
DECLARE @ActiveState  int
SET @NewState = 1
SET @ActiveState = 2
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @HDM int
SET @HDM = 5
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDM)
	SET @IsHDM = 1
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
DECLARE @Incidents
	TABLE (IncidentId int, ProjectId int, ProjectTitle nvarchar(255), CreatorId int, CreatorName nvarchar(102), ManagerId int, ManagerName nvarchar(102),
		ActivatedBy int, ClosedBy int, Title nvarchar(255), CreationDate DateTime, TypeId int, TypeName nvarchar(50), PriorityId int, PriorityName nvarchar(50),
		StatusId int, StatusName nvarchar(50), SeverityId int, StateId int, CanEdit int, CanDelete int)
INSERT INTO @Incidents
SELECT I.IncidentId, I.ProjectId, P.Title AS ProjectTitle,
	I.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,  I.ManagerId,
	CASE WHEN U2.PrincipalId IS NOT NULL THEN U2.LastName + ', ' + U2.FirstName ELSE G.GroupName END AS ManagerName,
	I.ActivatedBy, I.ClosedBy, I.Title, I.CreationDate,
	I.TypeId, T.TypeName, I.PriorityId, PR.PriorityName, I.StatusId, S.StatusName, I.SeverityId, I.StateId,
	CASE WHEN (I.StateId = @NewState OR I.StateId = @ActiveState)
		AND (@IsPPM = 1 OR I.ManagerId = @UserId OR I.CreatorId = @UserId OR (I.ProjectId IS NULL AND @IsHDM = 1)) THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR I.ManagerId = @UserId OR (I.CreatorId = @UserId AND I.StateId = @NewState) OR (I.ProjectId IS NULL AND @IsHDM = 1) THEN 1 ELSE 0 END AS CanDelete
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_TYPES T ON (I.TypeId = T.TypeId)
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN USERS U1 ON (I.CreatorId = U1.PrincipalId)
	LEFT JOIN USERS U2 ON (I.ManagerId = U2.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
  WHERE
	(@ProjectId = 0 OR I.ProjectId = @ProjectId OR (@ProjectId = -1 AND I.ProjectId IS NULL))
	AND (@ManagerId = 0 OR I.IncidentId IN (SELECT IncidentId FROM INCIDENT_SECURITY WHERE PrincipalId = @ManagerId AND IsManager = 1))
	AND (@ResourceId = 0 OR I.IncidentId IN (SELECT IncidentId FROM INCIDENT_SECURITY_ALL WHERE PrincipalId = @ResourceId AND IsResource = 1))
	AND (@CreatorId = 0 OR I.CreatorId = @CreatorId)
	AND (@PriorityId = -1 OR I.PriorityId = @PriorityId)
	AND (@TypeId = 0 OR I.TypeId = @TypeId)
	AND (@SeverityId = 0 OR I.SeverityId = @SeverityId)
	AND
	(
		@StatusId = 0
		OR I.StatusId = @StatusId
		OR (@StatusId = -1 AND ( I.StateId = @NewState OR I.StateId = @ActiveState))
		OR (@StatusId = -2 AND ( I.StateId <> @NewState AND I.StateId <> @ActiveState))
	)
	AND (I.Title LIKE @Keyword OR I.[Description] LIKE @Keyword OR I.Resolution LIKE @Keyword OR I.Workaround LIKE @Keyword OR CAST(I.IncidentId AS nvarchar(10)) LIKE @Keyword )
	AND
	(	@IsPPM = 1 OR @IsExec = 1
		OR (I.ProjectId IS NULL AND @IsHDM = 1)
		OR I.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR I.IncidentId IN
			(SELECT IncidentId FROM INCIDENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsCreator = 1 OR IsResource = 1)
			)
	)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND I.IncidentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType = 2 AND I.IncidentId NOT IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType < 0 AND I.IncidentId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @IncidentObjectType AND CategoryId = -@CategoryType
			)
	)
	AND (@IncidentCategoryType = 0
		OR @IncidentCategoryType = 1 AND I.IncidentId IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM INCIDENTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @IncidentCategoryType = 2 AND I.IncidentId NOT IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM INCIDENTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @IncidentCategoryType < 0 AND I.IncidentId IN
			(SELECT IncidentId
			  FROM INCIDENT_CATEGORY
			  WHERE CategoryId = -@IncidentCategoryType
			)
	)
DECLARE @CollapseNonProjectIncident bit
SET @CollapseNonProjectIncident = 0
IF EXISTS (SELECT * FROM COLLAPSED_INCIDENTS WHERE UserId = @UserId AND ProjectId = -1)
	SET @CollapseNonProjectIncident = 1
SELECT DISTINCT CASE WHEN I.ProjectId IS NULL THEN -1 ELSE I.ProjectId END AS ProjectId,
	CASE WHEN ProjectTitle IS NULL THEN '' ELSE ProjectTitle END AS ProjectTitle,
	0 as IncidentId, '' as Title, 0 as CreatorId, '' as CreatorName, 0 as ManagerId, '' as ManagerName,
	0 as ActivatedBy, 0 as ClosedBy, NULL as CreationDate, 0 as TypeId, '' as TypeName, -1 as PriorityId, '' as PriorityName,
	0 as StatusId, '' as StatusName, 0 as SeverityId, 0 as StateId, 0 as CanEdit, 0 as CanDelete, CAST (1 as bit) AS IsProject,
	CASE WHEN
		(CI.ProjectId IS NULL  AND I.ProjectId IS NOT NULL)
		OR
		(I.ProjectId IS NULL AND @CollapseNonProjectIncident = 0)
	THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsCollapsed
  FROM @Incidents I
		LEFT JOIN COLLAPSED_INCIDENTS CI ON (I.ProjectId = CI.ProjectId AND CI.UserId = @UserId)
UNION ALL
SELECT CASE WHEN I.ProjectId IS NULL THEN -1 ELSE I.ProjectId END AS ProjectId,
	CASE WHEN ProjectTitle IS NULL THEN '' ELSE ProjectTitle END AS ProjectTitle,
	IncidentId, Title, CreatorId, CreatorName, ManagerId, ManagerName,
	ActivatedBy, ClosedBy, CreationDate, TypeId, TypeName, PriorityId, PriorityName,
	StatusId, StatusName, SeverityId, StateId, CanEdit, CanDelete, CAST (0 as bit) AS IsProject, CAST(0 as bit) as IsCollapsed
  FROM @Incidents I
	LEFT JOIN COLLAPSED_INCIDENTS CI ON (I.ProjectId = CI.ProjectId AND CI.UserId = @UserId)
  WHERE
	(CI.ProjectId IS NULL  AND I.ProjectId IS NOT NULL)
	OR
	(I.ProjectId IS NULL AND @CollapseNonProjectIncident = 0)
ORDER BY ProjectTitle, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByManager
	@ManagerId as int,
	@LanguageId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT I.IncidentId, I.Title, I.ProjectId, P.Title AS ProjectName, I.PriorityId, PR.PriorityName, I.StatusId, L.StatusName, I.StateId
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS S ON (I.StatusId = S.StatusId)
	JOIN INCIDENT_STATUS_LANGUAGE L ON (I.StatusId = L.StatusId AND L.LanguageId = @LanguageId)
  WHERE I.StateId != @ClosedState AND I.ManagerId = @ManagerId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @NewState int
DECLARE @ActiveState  int
SET @NewState = 1
SET @ActiveState = 2
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @HDM int
SET @HDM = 5
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDM)
	SET @IsHDM = 1
SELECT I.IncidentId, I.ProjectId, P.Title AS ProjectTitle,
	I.CreatorId, U1.LastName + ', ' + U1.FirstName AS CreatorName,
	I.ManagerId, U2.LastName + ', ' + U2.FirstName AS ManagerName,
	I.ActivatedBy, I.ClosedBy, I.Title, I.CreationDate, I.ActivationDate, I.CloseDate,
	I.TypeId, IT.TypeName, I.PriorityId, PR.PriorityName, I.StatusId, S.StatusName, I.SeverityId, SV.SeverityName, I.StateId,
	CASE WHEN (I.StateId = @NewState OR I.StateId = @ActiveState)
		AND (@IsPPM = 1 OR I.ManagerId = @UserId OR I.CreatorId = @UserId OR (I.ProjectId IS NULL AND @IsHDM = 1)) THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR I.ManagerId = @UserId OR (I.CreatorId = @UserId AND I.StateId = @NewState) OR (I.ProjectId IS NULL AND @IsHDM = 1) THEN 1 ELSE 0 END AS CanDelete
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN INCIDENT_TYPES IT ON (I.TypeId = IT.TypeId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN INCIDENT_SEVERITY SV ON (I.SeverityId = SV.SeverityId)
	JOIN USERS U1 ON (I.CreatorId = U1.PrincipalId)
	LEFT JOIN USERS U2 ON (I.ManagerId = U2.PrincipalId)
  WHERE
	(@ProjectId = 0 OR I.ProjectId = @ProjectId OR (@ProjectId = -1 AND I.ProjectId IS NULL))
	AND
	(@IsPPM = 1 OR @IsExec = 1
		OR (I.ProjectId IS NULL AND @IsHDM = 1)
		OR I.ProjectId IN
			(SELECT ProjectId FROM PROJECT_SECURITY
				WHERE PrincipalId = @UserId
					AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
			)
		OR I.IncidentId IN
			(SELECT IncidentId FROM INCIDENT_SECURITY_ALL
				WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsCreator = 1 OR IsResource = 1)
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByState
	@ProjectId as int,
	@StateId as int,
	@LanguageId as int
as
SELECT I.IncidentId, I.Title, I.ProjectId, P.Title AS ProjectName, I.ManagerId, I.PriorityId, PR.PriorityName, I.TypeId, T.TypeName,
	CASE WHEN U.PrincipalId IS NOT NULL THEN U.FirstName + ' ' + U.LastName ELSE G.GroupName END AS ManagerName,
	I.CreationDate, I.ActivationDate, I.CloseDate
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	LEFT JOIN USERS U ON (I.ManagerId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_TYPES T ON (I.TypeId = T.TypeId)
  WHERE I.StateId = @StateId
	AND (@ProjectId = 0 OR I.ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetByType
	@TypeId as int,
	@LanguageId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT I.IncidentId, I.Title, I.ProjectId, P.Title AS ProjectName, I.ManagerId, I.PriorityId, PR.PriorityName, I.StatusId, L.StatusName, I.StateId,
	CASE WHEN U.PrincipalId IS NOT NULL THEN U.FirstName + ' ' + U.LastName ELSE G.GroupName END AS ManagerName
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	LEFT JOIN USERS U ON (I.ManagerId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS S ON (I.StatusId = S.StatusId)
	JOIN INCIDENT_STATUS_LANGUAGE L ON (I.StatusId = L.StatusId AND L.LanguageId = @LanguageId)
  WHERE I.StateId != @ClosedState AND TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @NewState int
DECLARE @ActiveState  int
SET @NewState = 1
SET @ActiveState = 2
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 5)
	SET @IsHDM = 1
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT I.IncidentId, I.Title,
	CASE WHEN I.ManagerId = @UserId THEN 1 ELSE 0 END AS IsManager,
	CASE WHEN IR.ResourceId IS NOT NULL THEN 1 ELSE 0 END AS IsResource,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR S.IsManager = 1 OR S.IsCreator = 1 OR S.IsResource = 1 THEN 1 ELSE 0 END AS CanView,
	CASE WHEN (I.StateId = @NewState OR I.StateId = @ActiveState)
		AND (@IsPPM = 1 OR I.ManagerId = @CurrentUserId OR I.CreatorId = @CurrentUserId OR (I.ProjectId IS NULL AND @IsHDM = 1)) THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR I.ManagerId = @CurrentUserId OR (I.CreatorId = @CurrentUserId AND I.StateId = @NewState) OR (I.ProjectId IS NULL AND @IsHDM = 1) THEN 1 ELSE 0 END AS CanDelete
  FROM INCIDENTS I
	LEFT JOIN INCIDENT_SECURITY_ALL S ON (I.IncidentId = S.IncidentId AND S.PrincipalId = @CurrentUserId)
	LEFT JOIN INCIDENT_RESOURCES IR ON (I.IncidentId = IR.IncidentId AND IR.PrincipalId = @UserId)
  WHERE I.ManagerId = @UserID OR IR.ResourceId IS NOT NULL
  ORDER BY I.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetForManagerView
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
SELECT I.IncidentId AS ItemId, I.Title, I.PriorityId, P.PriorityName, 7 AS ItemType, I.CreationDate, I.ActivationDate as StartDate, I.CloseDate as FinishDate, 0 as PercentCompleted, CAST(0 AS bit) AS IsCompleted,
	I.ManagerId, 0 as ReasonId, I.ProjectId, I.StateId, 0 as CompletionTypeId
  FROM INCIDENTS I, PRIORITY_LANGUAGE P
  WHERE (@ManagerId=0 OR I.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR I.ProjectId=@ProjectId)
	AND I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND
	(
	((@StartDate is not null)AND(I.ActivationDate<=@StartDate)AND(I.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(I.CloseDate>=@CompletedDate)AND(I.StateId=4 OR I.StateId=5))
	OR((@ShowActive=1 AND (I.StateId=@ActiveState OR I.StateId=@OverdueState)))
	)
	AND
	(
		@PrincipalId = 1
	OR
		IncidentId IN (SELECT IncidentId FROM INCIDENT_SECURITY_ALL
				WHERE IsRealIncidentResource = 1 AND (PrincipalId = @PrincipalId OR PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId))
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetForResourceView
	@UserId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
 SELECT DISTINCT I.IncidentId AS ItemId, I.Title, I.PriorityId, P.PriorityName, 7 AS ItemType, I.CreationDate, I.ActivationDate as StartDate, I.CloseDate as FinishDate, 0 as PercentCompleted, CAST(0 AS bit) AS IsCompleted,
	I.ManagerId, 0 as ReasonId, I.ProjectId, PR.Title as ProjectTitle, I.StateId, 0 as CompletionTypeId
  FROM INCIDENTS I
  LEFT JOIN PROJECTS PR ON I.ProjectId=PR.ProjectId
  JOIN INCIDENT_SECURITY_ALL ISS ON (I.IncidentId = ISS.IncidentId AND ISS.IsRealIncidentResource=1 AND ISS.PrincipalId = @UserId)
  JOIN PRIORITY_LANGUAGE P ON (I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE  (@ManagerId=0 OR I.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR I.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(I.ActivationDate<=@StartDate)AND(I.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(I.CloseDate>=@CompletedDate)AND(I.StateId=4 OR I.StateId=5))
	OR((@ShowActive=1 AND (I.StateId=@ActiveState OR I.StateId=@OverdueState)))
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetHighPriority
	@LanguageId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
DECLARE @NormalPriority int
SET @NormalPriority = 500
SELECT I.IncidentId, I.Title, I.ProjectId, P.Title AS ProjectTitle, I.StatusId, S.StatusName, I.PriorityId, PL.PriorityName, I.CreationDate, I.StateId
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	JOIN INCIDENT_STATUS ST ON (I.StatusId = ST.StatusId)
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN PRIORITY_LANGUAGE PL ON (I.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
  WHERE I.PriorityId > @NormalPriority AND I.StateId != @ClosedState
  ORDER BY I.PriorityId DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetManagers
as
SELECT PrincipalId AS UserId, LastName + ', ' + FirstName AS FullName
  FROM USERS
  WHERE PrincipalId IN (SELECT ManagerId FROM INCIDENTS)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetNewCount
	@UserId as int,
	@retval int output
as
DECLARE @NewState int
DECLARE @HDM int, @PPM int, @Exec int
SET @NewState = 1
SET @HDM = 5
SET @PPM = 4
SET @Exec = 7
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = @PPM OR GroupId = @Exec))
	SET @IsPPM_Exec = 1
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDM)
	SET @IsHDM = 1
SELECT @retval = COUNT(*)
  FROM INCIDENTS
  WHERE StateId = @NewState
	AND (@IsPPM_Exec = 1 OR ManagerId = @UserId OR (ProjectId IS NULL AND @IsHDM = 1))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetNotAssigned
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @NewState int
DECLARE @ActiveState  int
DECLARE @HDM int
SET @NewState = 1
SET @ActiveState = 2
SET @HDM = 5
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @HDM)
	SET @IsHDM = 1
SELECT I.IncidentId, I.Title, I.PriorityId, PR.PriorityName, I.StatusId, SL.StatusName, I.CreationDate, I.CreatorId, I.StateId
  FROM INCIDENTS I
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN INCIDENT_STATUS S ON (I.StatusId = S.StatusId)
	JOIN INCIDENT_STATUS_LANGUAGE SL ON (S.StatusId = SL.StatusId AND SL.LanguageId = @LanguageId)
  WHERE (@ProjectId = 0 OR I.ProjectId = @ProjectId)
	AND (I.StateId = @NewState OR I.StateId = @ActiveState)
	AND (I.ManagerId = @UserId OR (I.ProjectId IS NULL AND I.ManagerId = @HDM AND @IsHDM = 1))
	AND (I.IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_TODO)
		OR I.IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_TODO IT, TODO T WHERE IT.ToDoId = T.ToDoId AND T.IsCompleted = 0)
	)
	AND I.IncidentId NOT IN (SELECT IncidentId FROM INCIDENT_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetOpenByProject
	@ProjectId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT I.IncidentId, I.Title, I.TypeId, IT.TypeName, I.StateId, I.ManagerId,
	CASE WHEN U.PrincipalId IS NOT NULL THEN U.LastName + ', ' + U.FirstName ELSE G.GroupName END AS ManagerName
  FROM INCIDENTS I
	JOIN INCIDENT_TYPES IT ON (I.TypeId = IT.TypeId)
	LEFT JOIN USERS U ON (I.ManagerId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
	JOIN INCIDENT_STATUS S ON (I.StatusId = S.StatusId)
  WHERE I.ProjectId = @ProjectId AND I.StateId != @ClosedState
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetOpenByUserOnly
	@UserId as int,
	@LanguageId as int
as
DECLARE @ActiveState int
SET @ActiveState = 2
SELECT I.IncidentId, I.Title, I.CreationDate, I.PriorityId, P.PriorityName, I.StatusId, S.StatusName, I.CreatorId, I.ManagerId,  A.IsRealIncidentManager AS IsManager,
	A.IsCreator, A.IsRealIncidentResource AS IsResource, I.StateId
  FROM INCIDENTS I, INCIDENT_STATUS S, PRIORITY_LANGUAGE P, INCIDENT_SECURITY_ALL A
  WHERE I.StatusId = S.StatusId AND I.StateId = @ActiveState
	AND I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND I.IncidentId = A.IncidentId AND A.PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetPending
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT I.IncidentId, I.Title, I.[Description], I.PriorityId, P.PriorityName, I.ManagerId, I.ActivationDate, I.StateId
  FROM INCIDENTS I, INCIDENT_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR I.ProjectId = @ProjectId)
	AND I.IncidentId = R.IncidentId AND R.PrincipalId = @UserId
	AND I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND I.StateId != @ClosedState
	AND (R.MustBeConfirmed=1 AND R.ResponsePending=1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetSimple
	@ProjectId as int,
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit
as
SELECT IncidentId, Title
  FROM INCIDENTS I
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId OR (@ProjectId = -1 AND ProjectId IS NULL))
	AND
	(
		(@GetAssigned = 1 AND IncidentId IN
			(SELECT IncidentId FROM INCIDENT_RESOURCES R WHERE PrincipalId = @UserId
				AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)))
		OR
		(@GetManaged =1 AND ManagerId = @UserId)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatistic
	@ProjectId as int,
	@ManagerId as int
as
DECLARE @NewState int
SET @NewState = 1
DECLARE @ActiveState int
SET @ActiveState = 2
DECLARE @ClosedState int
SET @ClosedState = 5
DECLARE @Dt datetime
SET @Dt = getutcdate()
DECLARE @IncidentCount int
DECLARE @Pop3IncidentCount int
DECLARE @NewIncidentCount int
DECLARE @ActiveIncidentCount int
DECLARE @ClosedIncidentCount int
DECLARE @AvgTimeInNewState int
DECLARE @AvgTimeInActiveState int
DECLARE @AvgTimeForResolveClosed int
DECLARE @AvgTimeForResolveAll int
SELECT @IncidentCount = COUNT(*)
  FROM INCIDENTS
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
SELECT @Pop3IncidentCount = COUNT(*)
  FROM POP3_INCIDENTS
SELECT @NewIncidentCount = COUNT(*)
  FROM INCIDENTS
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	AND StateId = @NewState
SELECT @ActiveIncidentCount = COUNT(*)
  FROM INCIDENTS
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	AND StateId = @ActiveState
SELECT @ClosedIncidentCount = COUNT(*)
  FROM INCIDENTS
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	AND StateId = @ClosedState
SELECT @AvgTimeInNewState = AVG(DATEDIFF(mi, StartDate, EndDate))
  FROM
	(SELECT CreationDate AS StartDate,
		CASE WHEN ActivationDate IS NOT NULL THEN ActivationDate ELSE @Dt END AS EndDate
	  FROM INCIDENTS
	  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
		AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	) A
IF @AvgTimeInNewState IS NULL
	SET @AvgTimeInNewState = 0
SELECT @AvgTimeInActiveState = AVG(DATEDIFF(mi, StartDate, EndDate))
  FROM
	(SELECT ActivationDate AS StartDate,
		CASE WHEN CloseDate IS NOT NULL THEN CloseDate ELSE @Dt END AS EndDate
	  FROM INCIDENTS
	  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
		AND (@ManagerId = 0 OR ManagerId = @ManagerId)
		AND StateId != @NewState
	) A
IF @AvgTimeInActiveState IS NULL
	SET @AvgTimeInActiveState = 0
SELECT @AvgTimeForResolveClosed = AVG(DATEDIFF(mi, CreationDate, CloseDate))
  FROM INCIDENTS
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	AND StateId = @ClosedState
IF @AvgTimeForResolveClosed IS NULL
	SET @AvgTimeForResolveClosed = 0
SELECT @AvgTimeForResolveAll = AVG(DATEDIFF(mi, StartDate, EndDate))
  FROM
	(SELECT CreationDate AS StartDate,
		CASE WHEN CloseDate IS NOT NULL THEN CloseDate ELSE @Dt END AS EndDate
	  FROM INCIDENTS
	  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
		AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	) A
IF @AvgTimeForResolveAll IS NULL
	SET @AvgTimeForResolveAll = 0
SELECT @IncidentCount AS IncidentCount, @Pop3IncidentCount AS Pop3IncidentCount, @NewIncidentCount AS NewIncidentCount,
	@ActiveIncidentCount AS ActiveIncidentCount, @ClosedIncidentCount AS ClosedIncidentCount, @AvgTimeInNewState AS AvgTimeInNewState,
	@AvgTimeInActiveState AS AvgTimeInActiveState, @AvgTimeForResolveClosed AS AvgTimeForResolveClosed, @AvgTimeForResolveAll AS AvgTimeForResolveAll
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByGeneralCategory
	@ProjectId as int,
	@ManagerId as int
as
DECLARE @IncidentType int
SET @IncidentType = 7
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName, COUNT(*) AS [Count]
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (C.CategoryId = OC.CategoryId AND ObjectTypeId = @IncidentType)
	JOIN INCIDENTS I ON (OC.ObjectId = I.IncidentId)
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND I.ProjectId IS NULL) OR I.ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR I.ManagerId = @ManagerId)
  GROUP BY C.CategoryId, C.CategoryName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByIncidentCategory
	@ProjectId as int,
	@ManagerId as int
as
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName, COUNT(*) AS [Count]
  FROM INCIDENT_CATEGORIES C
	JOIN INCIDENT_CATEGORY IC ON (C.CategoryId = IC.CategoryId)
	JOIN INCIDENTS I ON (IC.IncidentId = I.IncidentId)
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND I.ProjectId IS NULL) OR I.ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR I.ManagerId = @ManagerId)
  GROUP BY C.CategoryId, C.CategoryName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByManager
as
SELECT I.ManagerId AS ItemId, U.LastName + ', ' + U.FirstName as ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN USERS U ON (I.ManagerId = U.PrincipalId)
  GROUP BY I.ManagerId, U.LastName + ', ' + U.FirstName
UNION ALL
SELECT I.ManagerId AS ItemId, G.GroupName as ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN GROUPS G ON (I.ManagerId = G.PrincipalId)
  GROUP BY I.ManagerId, G.GroupName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByPriority
	@LanguageId int
as
SELECT P.PriorityId AS ItemId, P.PriorityName AS ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN PRIORITY_LANGUAGE P ON (I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  GROUP BY P.PriorityId, P.PriorityName
  ORDER BY ItemId DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByProject
	@ManagerId as int
as
SELECT I.ProjectId AS ItemId, P.Title as ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
  WHERE (@ManagerId = 0 OR I.ManagerId = @ManagerId)
  GROUP BY I.ProjectId, P.Title
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticBySeverity
as
SELECT S.SeverityId AS ItemId, S.SeverityName AS ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN INCIDENT_SEVERITY S ON (I.SeverityId = S.SeverityId)
  GROUP BY S.SeverityId, S.SeverityName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByStatus
	@LanguageId int
as
SELECT S.StatusId AS ItemId, S.StatusName AS ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN INCIDENT_STATUS_LANGUAGE S ON (I.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
  GROUP BY S.StatusId, S.StatusName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetStatisticByType
	@ProjectId as int,
	@ManagerId as int
as
SELECT IT.TypeId AS ItemId, IT.TypeName AS ItemName, COUNT(*) AS [Count]
  FROM INCIDENTS I
	JOIN INCIDENT_TYPES IT ON (I.TypeId = IT.TypeId)
  WHERE (@ProjectId = 0 OR (@ProjectId = -1 AND ProjectId IS NULL) OR ProjectId = @ProjectId)
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
  GROUP BY IT.TypeId, IT.TypeName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetUpdatedByUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT I.IncidentId, I.Title, I.StateId, A.LastSavedDate
  FROM INCIDENTS I,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @IncidentObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE I.IncidentId = A.ObjectId
	AND (@ProjectId = 0 OR I.ProjectId = @ProjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
  ORDER BY A.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsGetUpdatedForUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 5)
	SET @IsHDM = 1
DECLARE @IncidentObjectType int
SET @IncidentObjectType = 7
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT IncidentId, Title, CreatorId, ManagerId, LastEditorId, LastSavedDate, ProjectId, ProjectName, StateId
FROM
(
	SELECT I.IncidentId, I.Title, I.CreatorId, I.ManagerId, ISNULL(I.ProjectId, -1) AS ProjectId, ISNULL(P.Title, '') AS ProjectName,
		SE.UserId AS LastEditorId, SE.Dt AS LastSavedDate,
		I.StateId
	  FROM INCIDENTS I
		JOIN SYSTEM_EVENTS SE ON (I.IncidentId = SE.ObjectId)
		LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	  WHERE (@ProjectId = 0 OR I.ProjectId = @ProjectId)
		AND
		(@IsPPM_Exec = 1
			OR (I.ProjectId IS NULL AND @IsHDM = 1)
			OR I.ProjectId IN
				(SELECT ProjectId FROM PROJECT_SECURITY
					WHERE PrincipalId = @UserId
						AND (IsManager = 1 OR IsExecutiveManager = 1 OR IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1)
				)
			OR I.IncidentId IN
				(SELECT IncidentId FROM INCIDENT_SECURITY_ALL
					WHERE PrincipalId = @UserId AND (IsManager = 1 OR IsCreator = 1 OR IsResource = 1)
				)
		)
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @IncidentObjectType
			  GROUP BY E.ObjectId)
) A
  WHERE DATEDIFF(dd, DATEADD(mi, @TimeOffset, LastSavedDate), @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
BEGIN TRAN
	UPDATE INCIDENTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE INCIDENTS SET ActivatedBy = @ToUserId WHERE ActivatedBy = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE INCIDENTS SET ClosedBy = @ToUserId WHERE ClosedBy = @FromUserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentsReplaceUnchangeableUserToManager
	@UserId as int
as
BEGIN TRAN
	UPDATE INCIDENTS SET CreatorId = ManagerId WHERE CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE INCIDENTS SET ActivatedBy = ManagerId WHERE ActivatedBy = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE INCIDENTS SET ClosedBy = ManagerId WHERE ClosedBy = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentStatusGet
	@LanguageId as int
as
SELECT StatusId, StatusName
  FROM INCIDENT_STATUS_LANGUAGE WHERE LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentToDoAdd
	@IncidentId as int ,
	@ToDoId as int ,
	@StatusId as int
as
if EXISTS(SELECT * FROM INCIDENT_TODO WHERE IncidentId = @IncidentId AND ToDoId = @ToDoId)
	UPDATE INCIDENT_TODO
	  SET StatusId=@StatusId
	  WHERE IncidentId = @IncidentId AND ToDoId = @ToDoId
else
	INSERT INTO INCIDENT_TODO (IncidentId,ToDoId,StatusId)
	  VALUES(@IncidentId, @ToDoId, @StatusId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentTypeAdd
	@TypeName as nvarchar(50)
as
INSERT INTO INCIDENT_TYPES (TypeName) VALUES(@TypeName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentTypeDelete
	@TypeId as int
as
DELETE FROM INCIDENT_TYPES  WHERE TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentTypesGet
as
SELECT TypeId, TypeName
  FROM INCIDENT_TYPES
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentTypesGetForDictionaries
as
SELECT T.TypeId AS ItemId, T.TypeName AS ItemName,
	CASE WHEN EXISTS(SELECT * FROM INCIDENTS I WHERE I.TypeId = T.TypeId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM INCIDENT_TYPES T
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentTypeUpdate
	@TypeId as int ,
	@TypeName as nvarchar(50)
as
UPDATE INCIDENT_TYPES SET TypeName=@TypeName
  WHERE TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentUpdateActivatedBy
	@IncidentId as int ,
	@UserId as int ,
	@LastSavedDate as datetime
as
UPDATE INCIDENTS SET ActivatedBy = @UserId, ActivationDate = @LastSavedDate
  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentUpdateClosedBy
	@IncidentId as int ,
	@UserId as int
as
UPDATE INCIDENTS SET ClosedBy = @UserId
  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentUpdateManager
	@IncidentId as int ,
	@ManagerId as int
as
UPDATE INCIDENTS SET ManagerId = @ManagerId WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentUpdateProjectAndManager
	@IncidentId as int ,
	@ProjectId as int,
	@ManagerId as int
as
IF @ProjectId <= 0
	SET @ProjectId = NULL
UPDATE INCIDENTS
  SET ProjectId = @ProjectId, ManagerId = @ManagerId
  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IncidentUpdateStatus
	@IncidentId as int ,
	@StatusId as int,
	@LastEditorId as int ,
	@LastSavedDate as datetime
as
DECLARE @ActiveStatus int
SET @ActiveStatus = 2
DECLARE @ClosedBy int
SET @ClosedBy = null
DECLARE @CloseDate datetime
SET @CloseDate = null
IF @StatusId != @ActiveStatus
BEGIN
	SET @ClosedBy = @LastEditorId
	SET @CloseDate = @LastSavedDate
END
DECLARE @StateId int
SELECT @StateId = StateId FROM INCIDENT_STATUS WHERE StatusId = @StatusId
UPDATE INCIDENTS SET StatusId = @StatusId, ClosedBy=@ClosedBy, CloseDate=@CloseDate, StateId = @StateId
  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].IssueStatusGetNames
	@StatusId int
AS
SELECT LanguageId, StatusName AS Name
  FROM INCIDENT_STATUS_LANGUAGE
  WHERE StatusId = @StatusId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].LanguageGetByLocale
	@Locale varchar(50)
as
SELECT FriendlyName
  FROM LANGUAGES
  WHERE Locale = @Locale
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].LanguageGetDefault
	 @retval as int output
AS
SELECT @retval=LanguageId
  FROM LANGUAGES
  WHERE IsDefault = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].LanguageLocaleNameDefaultGet
AS
Select LanguageId,Locale,FriendlyName
FROM Languages
WHERE IsDefault=1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].LanguagesAdd
	@languageID as int,
	@locale as nvarchar(50),
	@friendlyName as nvarchar(50),
	@isDefault as bit
AS
INSERT LANGUAGES (languageID, locale, friendlyName, isDefault) VALUES (@languageID, @locale, @friendlyName, @isDefault)
IF @@error<>0
	RAISERROR ('Cannot add new language', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].LanguagesAdd2
	@locale as nvarchar(50),
	@friendlyName as nvarchar(50),
	@isDefault as bit,
	@retval int output
AS
SET @retval = -1
declare @newLangID int
SET @newLangID = (select MAX(languageID) from LANGUAGES)
if(@newLangID IS NULL)
	SET @newLangID = 1
else
	SET @newLangID = @newLangID+1
INSERT LANGUAGES(languageID, locale, friendlyName, isdefault)
	VALUES(@newLangID, @locale, @friendlyName, @isDefault)
SET @retval = @newLangID
IF @@error<>0
	RAISERROR ('Cannot add new language', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].LanguagesGet
AS
SELECT LanguageId, Locale, FriendlyName, IsDefault
  FROM LANGUAGES
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAccessCreate
	@ListId as int,
	@PrincipalId as int,
	@AllowLevel as tinyint,
	@retval int output
as
SELECT @retval = ListAccessId FROM LIST_ACCESS WHERE ListId = @ListId AND PrincipalId = @PrincipalId
IF @retval IS NULL
BEGIN
	INSERT INTO LIST_ACCESS (ListId, PrincipalId, AllowLevel) VALUES(@ListId, @PrincipalId, @AllowLevel)
	SELECT @retval = @@identity
END
ELSE
	UPDATE LIST_ACCESS SET AllowLevel = @AllowLevel WHERE ListId = @ListId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAccessDelete
		@ListAccessId int
AS
	DELETE FROM LIST_ACCESS  WHERE ListAccessId = ListAccessId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAccessDeleteByList
		@ListId int
AS
	DELETE FROM LIST_ACCESS  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAccessesGet
	@ListId as int
AS
SELECT LA.ListAccessId, LA.PrincipalId, LA.AllowLevel,
	CASE WHEN P.IsGroup = 1 OR P.IsGroup IS NULL THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS IsGroup
  FROM LIST_ACCESS LA
	LEFT JOIN PRINCIPALS P ON (LA.PrincipalId = P.PrincipalId)
  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAccessGet
	@ListAccessId as int
AS
	SELECT ListId, PrincipalId, AllowLevel  FROM LIST_ACCESS WHERE ListAccessId = @ListAccessId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListAdd
	@Title as nvarchar(100) ,
	@Description as ntext,
	@FolderId INT,
	@TypeId as int ,
	@StatusId as int ,
	@CreatorId as int ,
	@CreationDate as datetime ,
	@retval int output
as
INSERT INTO LISTS (Title, [Description], FolderId, TypeId, StatusId, CreatorId, CreationDate)
 VALUES(@Title, @Description, @FolderId, @TypeId, @StatusId, @CreatorId, @CreationDate)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListDelete
	@ListId as int
 as
DECLARE @ListObjectType int
SET @ListObjectType = 15
DELETE FROM FAVORITES WHERE ObjectId = @ListId AND ObjectTypeId = @ListObjectType
DELETE SUBSCRIPTIONS WHERE ObjectId = @ListId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @ListObjectType)
DELETE FROM LISTS  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderAdd
			@Name nvarchar(250),
			@ParentFolderId INT,
			@CreatorId INT,
			@CreationDate DateTime,
			@retval INT output
AS
SELECT @retval = -1
IF EXISTS(SELECT * FROM LIST_FOLDERS WHERE ListFolderId = @ParentFolderId AND IsPrivate = 1 AND CreatorId = @CreatorId)
BEGIN
	INSERT INTO [LIST_FOLDERS]([Name], [ParentFolderId], [IsPrivate], [CreatorId], [CreationDate])
	VALUES(@Name, @ParentFolderId, 1, @CreatorId, @CreationDate)
	SELECT @retval = @@IDENTITY
END
ELSE IF EXISTS(SELECT * FROM LIST_FOLDERS WHERE ListFolderId = @ParentFolderId AND IsPrivate = 0)
BEGIN
	DECLARE @ProjectId int
	SELECT @ProjectId = ProjectId FROM LIST_FOLDERS WHERE ListFolderId = @ParentFolderId
	IF  @ProjectId IS NULL
		INSERT INTO [LIST_FOLDERS]([Name], [ParentFolderId], [IsPrivate], [CreatorId], [CreationDate])
		  VALUES(@Name, @ParentFolderId, 0, @CreatorId, @CreationDate)
	ELSE
		INSERT INTO [LIST_FOLDERS]([Name], [ParentFolderId], [IsPrivate], [CreatorId], [CreationDate], ProjectId)
		  VALUES(@Name, @ParentFolderId, 0, @CreatorId, @CreationDate, @ProjectId)
	SELECT @retval = @@IDENTITY
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderAddForProject
	@Name nvarchar(250),
	@ParentFolderId INT,
	@ProjectId int,
	@CreatorId INT,
	@CreationDate DateTime,
	@retval INT output
AS
SELECT @retval = -1
IF @ParentFolderId = 0 OR EXISTS(SELECT * FROM LIST_FOLDERS WHERE ListFolderId = @ParentFolderId AND IsPrivate = 0 AND ProjectId = @ProjectId)
BEGIN
	INSERT INTO [LIST_FOLDERS]([Name], ParentFolderId, ProjectId, IsPrivate, CreatorId, CreationDate)
	VALUES(@Name, @ParentFolderId, @ProjectId, 0, @CreatorId, @CreationDate)
	SELECT @retval = @@IDENTITY
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderAddPrivateRoot
	@UserId int,
	@retval int output
AS
SET @retval = -1
IF NOT EXISTS(SELECT * FROM LIST_FOLDERS WHERE IsPrivate = 1 AND CreatorId = @UserId AND ParentFolderId = 0)
BEGIN
	INSERT INTO LIST_FOLDERS([Name], ParentFolderId, IsPrivate, CreatorId, CreationDate) VALUES('Private lists',0,1,@UserId,getutcdate())
	SELECT @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderDelete
	@ListFolderId int
AS
DELETE FROM LIST_FOLDERS WHERE ListFolderId = @ListFolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGet
          	@FolderId INT
AS
SELECT F.ListFolderId,
	CASE WHEN F.ParentFolderId = 0 AND P.Title IS NOT NULL THEN P.Title ELSE F.[Name] END AS [Name],
	F.ParentFolderId, F.ProjectId, F.IsPrivate, F.CreatorId, F.CreationDate
  FROM LIST_FOLDERS F
	LEFT JOIN PROJECTS P ON (F.ProjectId = P.ProjectId)
  WHERE ListFolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetChildrenFolders
	@FolderId INT
AS
SELECT ListFolderId, [Name]
  FROM LIST_FOLDERS
  WHERE ParentFolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetParent
		          	@FolderId INT,
			@retval INT output
			AS
SET @retval = -1
SELECT @retval = ParentFolderId FROM [LIST_FOLDERS] WHERE ListFolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetPrivateFoldersByParent
	@ParentFolderId INT
AS
SELECT ListFolderId, [Name], ParentFolderId, ProjectId, IsPrivate, CreatorId, CreationDate,
	CAST(1 as bit) AS CanEdit, CAST(1 as bit) AS CanDelete
FROM LIST_FOLDERS LF
WHERE ParentFolderId = @ParentFolderId AND IsPrivate = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetPrivateFoldersByParentForTree
	@ParentFolderId INT
AS
SELECT ListFolderId, [Name], IsPrivate,
	(SELECT COUNT (*) FROM LIST_FOLDERS LF1 WHERE ParentFolderId = LF.ListFolderId AND IsPrivate = 1)  AS ChildrenCount
  FROM LIST_FOLDERS LF
  WHERE ParentFolderId = @ParentFolderId AND IsPrivate = 1
  ORDER BY [Name]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetProjectFolders
	@UserId int
AS
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT F.ListFolderId, P.Title AS [Name], F.ParentFolderId, F.ProjectId, F.IsPrivate, F.CreatorId, F.CreationDate,
	CAST(0 as bit) AS CanEdit, CAST(0 as bit) AS CanDelete
  FROM LIST_FOLDERS F
	JOIN PROJECTS P ON (F.ProjectId = P.ProjectId)
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
  WHERE ParentFolderId = 0
	AND (@IsPPM_Exec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetProjectFoldersForTree
	@UserId int
AS
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT F.ListFolderId, P.Title AS [Name], IsPrivate,
	(SELECT COUNT (*) FROM LIST_FOLDERS LF WHERE LF.ParentFolderId = F.ListFolderId AND IsPrivate = 0)  AS ChildrenCount
  FROM LIST_FOLDERS F
	JOIN PROJECTS P ON (F.ProjectId = P.ProjectId)
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
  WHERE ParentFolderId = 0
	AND (@IsPPM_Exec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetPublicFoldersByParent
          	@ParentFolderId INT,
	@AllFolders BIT,
	@UserId INT
AS
IF @AllFolders = 1
BEGIN
	IF EXISTS (SELECT * FROM LIST_FOLDERS WHERE ListFolderId = @ParentFolderId AND ProjectId IS NULL)
	BEGIN
		DECLARE @IsAdmin bit
		SET @IsAdmin = 0
		IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 2)
			SET @IsAdmin = 1
		SELECT ListFolderId, [Name], ParentFolderId, IsPrivate, CreatorId, ProjectId, CreationDate,
			CASE WHEN @IsAdmin = 1 OR LF.CreatorId = @UserId THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanEdit,
			CASE WHEN @IsAdmin = 1
				OR (LF.CreatorId = @UserId
					AND NOT EXISTS(SELECT * FROM LIST_FOLDERS WHERE ParentFolderId = LF.ListFolderId )
					AND NOT EXISTS(SELECT * FROM LISTS WHERE FolderId = LF.ListFolderId)
				) THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanDelete
		  FROM LIST_FOLDERS LF
		  WHERE ParentFolderId = @ParentFolderId AND IsPrivate = 0
	END
	ELSE BEGIN
		DECLARE @IsPPM bit
		SET @IsPPM = 0
		IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
			SET @IsPPM = 1
		DECLARE @IsExec bit
		SET @IsExec = 0
		IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
			SET @IsExec = 1
		SELECT LF.ListFolderId, LF.[Name], LF.ParentFolderId, LF.IsPrivate, LF.CreatorId, LF.ProjectId, LF.CreationDate,
			CASE WHEN @IsPPM = 1 OR PSA.IsManager = 1 OR LF.CreatorId = @UserId THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanEdit,
			CASE WHEN @IsPPM = 1 OR PSA.IsManager = 1
				OR (LF.CreatorId = @UserId
					AND NOT EXISTS(SELECT * FROM LIST_FOLDERS WHERE ParentFolderId = LF.ListFolderId )
					AND NOT EXISTS(SELECT * FROM LISTS WHERE FolderId = LF.ListFolderId)
				) THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanDelete
		  FROM LIST_FOLDERS LF
			LEFT JOIN PROJECT_SECURITY_ALL PSA ON (LF.ProjectId = PSA.ProjectId AND PSA.PrincipalId = @UserId)
		  WHERE ParentFolderId = @ParentFolderId AND IsPrivate = 0
			AND (@IsPPM = 1 OR @IsExec = 1 OR PSA.IsManager = 1 OR PSA.IsExecutiveManager = 1 OR PSA.IsTeamMember = 1 OR PSA.IsSponsor = 1 OR PSA.IsStakeHolder = 1)
	END
END
ELSE
BEGIN
	SELECT ListFolderId, [Name], ParentFolderId, IsPrivate, CreatorId, ProjectId, CreationDate,
		(
			SELECT COUNT (*) FROM LIST_FOLDERS LF1 WHERE
				ParentFolderId = LF.ListFolderId AND IsPrivate = 0
				AND EXISTS(
					SELECT * FROM LISTS L WHERE L.FolderId = LF1.ListFolderID
						AND (L.[CreatorId] = @UserId
							OR EXISTS (SELECT * FROM LIST_ACCESS LA WHERE
									LA.ListId= LF1.ListFolderID
									AND (LA.PrincipalId = @UserId
										OR EXISTS (SELECT * FROM USER_GROUP  ug WHERE ug.UserId = @UserId AND ug.GroupId=LA.PrincipalId)
										)
								    )
							)
				)
		)  AS ChildrenCount
	FROM [LIST_FOLDERS] LF
	WHERE IsPrivate = 0 AND ParentFolderId = @ParentFolderId
		AND ([CreatorId] = @UserId  OR EXISTS
			(SELECT * FROM LIST_ACCESS LA WHERE
				LA.ListId= LF.ListFolderID
				AND (LA.PrincipalId = @UserId OR EXISTS
					(SELECT * FROM USER_GROUP  ug WHERE ug.UserId = @UserId AND ug.GroupId=LA.PrincipalId)
				)
			)
		)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetPublicFoldersByParentForTree
	@ParentFolderId INT
AS
SELECT ListFolderId, [Name], IsPrivate,
	(SELECT COUNT (*) FROM LIST_FOLDERS LF1 WHERE ParentFolderId = LF.ListFolderId AND IsPrivate = 0)  AS ChildrenCount
  FROM LIST_FOLDERS LF
  WHERE ParentFolderId = @ParentFolderId AND IsPrivate = 0
  ORDER BY [Name]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetRootForUser
	@UserId INT,
	@retval int output
 AS
SELECT @retval = ListFolderId FROM LIST_FOLDERS WHERE IsPrivate = 1 AND CreatorId = @UserId AND ParentFolderId = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetRootProjectFolder
	@ProjectId int,
	@retval int output
AS
SELECT @retval = ListFolderId
  FROM LIST_FOLDERS
  WHERE ProjectId = @ProjectId AND ParentFolderId = 0 AND IsPrivate = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderGetRoots
			@UserId INT
AS
SELECT ListFolderId, IsPrivate,
	(SELECT COUNT (*) FROM [LIST_FOLDERS] LF1 WHERE CreatorId = @UserId AND ParentFolderId = LF.[ListFolderId] AND IsPrivate = 1)  AS ChildrenCount
FROM LIST_FOLDERS LF
WHERE  (IsPrivate = 1 AND CreatorId = @UserId AND ParentFolderId = 0)
UNION ALL
SELECT ListFolderId, IsPrivate,
	 (SELECT COUNT (*) FROM [LIST_FOLDERS] LF1 WHERE ParentFolderId = LF.[ListFolderId] AND IsPrivate = 0)  AS ChildrenCount
FROM LIST_FOLDERS LF
WHERE  (IsPrivate = 0 AND  ParentFolderId = 0 AND ProjectId is null)
ORDER BY ListFolderId DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderIsPrivate
			@FolderId INT,
			@retval INT output
AS
SELECT @retval = IsPrivate FROM LIST_FOLDERS WHERE ListFolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderMoveTo
	@FolderId as int,
	@ParentFolderId as int
as
DECLARE @IsPrivate bit
DECLARE @ProjectId int
SELECT @IsPrivate = IsPrivate, @ProjectId = ProjectId
  FROM LIST_FOLDERS
  WHERE ListFolderId = @ParentFolderId
UPDATE LIST_FOLDERS
  SET ParentFolderId = @ParentFolderId, IsPrivate = @IsPrivate, ProjectId = @ProjectId
  WHERE ListFolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFoldersReplaceUnchangeableUserToManager
	@UserId as int
as
UPDATE LIST_FOLDERS
  SET CreatorId = P.ManagerId
  FROM LIST_FOLDERS F, PROJECTS P
  WHERE F.ProjectId = P.ProjectId AND F.CreatorId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListFolderUpdate
	@ListFolderId int,
	@Name nvarchar(250)
AS
UPDATE LIST_FOLDERS
  SET [Name] = @Name
  WHERE ListFolderId = @ListFolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListGetById
	@ListId as int,
	@LanguageId as int
as
SELECT L.ListId, L.Title, L.[Description], L.FolderId,  L.TypeId, T.TypeName, L.StatusId, S.StatusName, L.CreatorId, L.CreationDate
  FROM LISTS L
	JOIN LIST_TYPES T ON (l.TypeId = T.TypeId)
	JOIN LIST_STATUS_LANGUAGE S ON (L.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListGetFolder
          	@ListId INT,
	@retval int output
AS
SELECT @retval = FolderId
  FROM LISTS
  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListGetSecurityForUser
	@ListId as int,
	@UserId as int,
	@retval int output
as
SELECT @retval = AllowLevel
   FROM LIST_SECURITY_ALL
  WHERE ListId = @ListId AND PrincipalId = @UserId
IF @retval IS NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListMoveTo
	@ListId as int,
	@FolderId as int
as
UPDATE LISTS
  SET FolderId = @FolderId
  WHERE ListId = @ListId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM LISTS WHERE CreatorId = @UserId)
	OR EXISTS(SELECT * FROM LIST_ITEMS WHERE CreatorId = @UserId OR LastEditorId = @UserId)
	OR EXISTS(SELECT * FROM LIST_FOLDERS WHERE CreatorId = @UserId AND IsPrivate = 0)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsGet
	@UserId int,
	@StatusId int,
	@TypeId int,
	@CategoryType as int,
	@Keyword nvarchar(100),
	@LanguageId as int
as
DECLARE @ListType int
SET @ListType = 15
SET @Keyword = '%' + @Keyword + '%'
SELECT L.ListId, L.Title, L.[Description], L.FolderId, L.TypeId, T.TypeName, L.StatusId, S.StatusName, L.CreatorId, LSA.AllowLevel, L.CreationDate
  FROM LISTS L
	JOIN LIST_TYPES T ON (l.TypeId = T.TypeId)
	JOIN LIST_STATUS_LANGUAGE S ON (L.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN LIST_SECURITY_ALL LSA ON (L.ListId = LSA.ListId AND LSA.PrincipalId = @UserId)
  WHERE (@StatusId = 0 OR L.StatusId = @StatusId)
	AND (@TypeId = 0 OR L.TypeId = @TypeId)
	AND (@Keyword = '%%' OR L.Title LIKE @Keyword)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND L.ListId IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @ListType AND CU.UserId = @UserId
			)
		OR @CategoryType = 2 AND L.ListId NOT IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @ListType AND CU.UserId = @UserId
			)
		OR @CategoryType < 0 AND L.ListId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @ListType AND CategoryId = -@CategoryType
			)
	)
  ORDER BY L.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsGetAllByFolder
	@FolderId INT
AS
SELECT ListId
  FROM LISTS
  WHERE FolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsGetByFolder
			@FolderId INT,
			@UserId INT,
			@LanguageId as int
AS
DECLARE @IsPrivate INT
SELECT @IsPrivate = IsPrivate FROM LIST_FOLDERS WHERE ListFolderId = @FolderId
IF @IsPrivate = 1
BEGIN
	SELECT
		L.ListId, L.Title, L.[Description], L.TypeId, T.TypeName, L.StatusId, S.StatusName, L.CreatorId, L.CreationDate, 3 AS AllowLevel
	FROM
		[LISTS] L
		JOIN LIST_TYPES T ON (l.TypeId = T.TypeId)
		JOIN LIST_STATUS_LANGUAGE S ON (L.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	WHERE L.FolderId = @FolderId
END
ELSE
BEGIN
	SELECT
		L.ListId, L.Title, L.[Description], L.TypeId, T.TypeName, L.StatusId, S.StatusName, L.CreatorId, LSA.AllowLevel, L.CreationDate
	  FROM [LISTS] L
		JOIN LIST_TYPES T ON (l.TypeId = T.TypeId)
		JOIN LIST_STATUS_LANGUAGE S ON (L.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
		JOIN LIST_SECURITY_ALL LSA ON (L.ListId = LSA.ListId AND LSA.PrincipalId = @UserId)
	  WHERE L.FolderId = @FolderId
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsGetCountByProject
	@ProjectId INT,
	@retval int output
AS
SELECT @retval = COUNT(*)
  FROM LISTS
  WHERE FolderId IN
	(SELECT ListFolderId FROM LIST_FOLDERS WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsGetUpdatedForUser
	@UserId int,
	@TimeZoneId as int,
	@LanguageId as int,
	@Days int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT L.ListId, L.Title, L.[Description], L.FolderId, L.TypeId, T.TypeName, L.StatusId, S.StatusName, L.CreatorId, SE.UserId AS LastEditorId, LSA.AllowLevel,
	ISNULL(LF.ProjectId, -1) AS ProjectId, ISNULL(P.Title, '') AS ProjectName, L.CreationDate, SE.Dt AS LastSavedDate
  FROM LISTS L
	JOIN LIST_FOLDERS LF ON (L.FolderId = LF.ListFolderId)
	LEFT JOIN PROJECTS P ON (LF.ProjectId = P.ProjectId)
	JOIN LIST_TYPES T ON (l.TypeId = T.TypeId)
	JOIN LIST_STATUS_LANGUAGE S ON (L.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN LIST_SECURITY_ALL LSA ON (L.ListId = LSA.ListId AND LSA.PrincipalId = @UserId)
	JOIN SYSTEM_EVENTS SE ON (L.ListId = SE.ObjectId)
  WHERE SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = 15
			  GROUP BY E.ObjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, SE.Dt), @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE LISTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
UPDATE LIST_ITEMS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
UPDATE LIST_ITEMS SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
UPDATE LIST_FOLDERS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId AND IsPrivate = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListStatusGet
	@LanguageId as int
as
SELECT StatusId, StatusName
  FROM LIST_STATUS_LANGUAGE WHERE LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListStatusGetNames
	@StatusId int
AS
SELECT LanguageId, StatusName AS Name
  FROM LIST_STATUS_LANGUAGE
  WHERE StatusId = @StatusId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListTypeAdd
	@TypeName as nvarchar(50)
as
INSERT INTO LIST_TYPES (TypeName) VALUES(@TypeName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListTypeDelete
	@TypeId as int
as
DECLARE @Rows int
SELECT @Rows = COUNT(*) FROM LIST_TYPES
IF @Rows > 1
	DELETE FROM LIST_TYPES  WHERE TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListTypeGetForDictionaries
as
SELECT T.TypeId AS ItemId, T.TypeName AS ItemName,
	CASE WHEN EXISTS(SELECT * FROM LISTS L WHERE L.TypeId = T.TypeId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM LIST_TYPES T
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListTypeGetList
as
SELECT TypeId, TypeName
  FROM LIST_TYPES
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ListTypeUpdate
	@TypeId as int ,
	@TypeName as nvarchar(50)
as
UPDATE LIST_TYPES SET TypeName = @TypeName
  WHERE TypeId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].LocalDateGet
	@TimeZoneId int,
	@UTCDate datetime,
	@retval Datetime output
AS
SELECT @retval = [dbo].GetLocalDate(@TimeZoneId, @UTCDate)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].MailboxDelete
	@MailboxId int
AS
DELETE FROM Mailboxes
WHERE MailboxId = @MailboxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].MailboxDisable
	@MailboxId int
AS
UPDATE Mailboxes SET IsEnabled = 0
WHERE MailboxId = @MailboxId OR @MailboxId = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].MailboxGet
	@MailboxId int,
	@OnlyActive bit,
	@Simple bit
AS
IF @Simple = 1
	SELECT MailboxId, Title, Type
	FROM Mailboxes
	WHERE (MailboxId = @MailboxId OR @MailboxId = 0) AND (IsEnabled = 1 OR @OnlyActive = 0)
ELSE
	SELECT MailboxId, Title, IsEnabled, Type, FolderId, Period, LastTime, Server, Port, [User], [Password], AutoApproveForKnown, AutoKillForUnknown, OnlyExternalSenders
	FROM Mailboxes
	WHERE (MailboxId = @MailboxId OR @MailboxId = 0) AND (IsEnabled = 1 OR @OnlyActive = 0)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].MailboxUpdate
	@MailboxId as int,
	@Title as nvarchar(250),
	@IsEnabled as bit,
	@Type as int,
	@FolderId as int,
	@Period as int ,
	@Server as nvarchar(250) ,
	@Port as int ,
	@User as nvarchar(50) ,
	@Password as nvarchar(50) ,
	@AutoApproveForKnown as bit ,
	@AutoKillForUnknown as bit ,
	@OnlyExternalSenders as bit,
	@retval int output
AS
IF EXISTS(SELECT * FROM Mailboxes WHERE MailboxId = @MailboxId)
	UPDATE Mailboxes
	SET IsEnabled = @IsEnabled, Title = @Title, Type = @Type, FolderId = @FolderId, Period = @Period, Server = @Server, Port = @Port, [User] = @User, [Password] = @Password, AutoApproveForKnown = @AutoApproveForKnown, AutoKillForUnknown = @AutoKillForUnknown, OnlyExternalSenders = @OnlyExternalSenders
	WHERE MailboxId = @MailboxId
ELSE
BEGIN
	INSERT INTO Mailboxes (Title, IsEnabled, Type, FolderId, Period, Server, Port, [User], [Password], AutoApproveForKnown, AutoKillForUnknown, OnlyExternalSenders)
	  VALUES(@Title, @IsEnabled, @Type, @FolderId, @Period, @Server, @Port, @User, @Password, @AutoApproveForKnown, @AutoKillForUnknown, @OnlyExternalSenders)
	SELECT @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].MailboxUpdateTime
	@MailboxId int,
	@LastTime datetime
as
UPDATE Mailboxes SET LastTime = @LastTime
WHERE MailboxId = @MailboxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ManagersGet
AS
SELECT PrincipalId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName+' '+LastName as DisplayName
  FROM Users
  WHERE
	PrincipalId IN (SELECT P.ManagerId FROM TASKS T, PROJECTS P WHERE T.ProjectId = P.ProjectId)
	OR
	PrincipalId IN (SELECT ManagerId FROM TODO)
	OR
	PrincipalId IN (SELECT ManagerId FROM INCIDENTS)
	OR
	PrincipalId IN (SELECT ManagerId FROM EVENTS)
	OR
	PrincipalId IN (SELECT ManagerId FROM DOCUMENTS)
ORDER BY FullName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMetaAttribute
	@AttrOwnerId		INT,
	@AttrOwnerType	INT,
	@Key			NVARCHAR(256),
	@Value			NTEXT
AS
	IF ( (SELECT COUNT(*) FROM MetaAttribute WHERE AttrOwnerId = @AttrOwnerId AND AttrOwnerType = @AttrOwnerType AND [Key] = @Key) = 0)
	BEGIN
		INSERT INTO MetaAttribute (AttrOwnerId, AttrOwnerType, [Key], [Value] ) VALUES (@AttrOwnerId, @AttrOwnerType, @Key, @Value)
	END
	ELSE
	BEGIN
		UPDATE MetaAttribute SET [Value] = @Value  WHERE AttrOwnerId = @AttrOwnerId AND AttrOwnerType = @AttrOwnerType AND [Key] = @Key
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMetaDictionary
	@MetaFieldId	INT,
	@Value		NVARCHAR(2048),
	@Retval	INT OUT
AS
	SET NOCOUNT ON
	SET @Retval = -1
BEGIN TRAN
	INSERT INTO MetaDictionary (MetaFieldId, [Value]) VALUES (@MetaFieldId, @Value)
	IF @@ERROR <> 0 GOTO ERR
	SET @Retval = @@IDENTITY
	COMMIT TRAN
RETURN
ERR:
	SET @Retval = -1
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMetaField
	@Namespace 		NVARCHAR(1024) = N'Mediachase.MetaDataPlus.User',
	@Name		NVARCHAR(256),
	@FriendlyName	NVARCHAR(256),
	@Description	NTEXT,
	@DataTypeId	INT,
	@Length	INT,
	@AllowNulls	BIT,
	@SaveHistory	BIT,
	@MultiLanguageValue BIT,
	@AllowSearch	BIT,
	@Retval 	INT OUTPUT
AS
	SET NOCOUNT ON
	SET @Retval = -1
BEGIN TRAN
	DECLARE @DataTypeVariable	INT
	DECLARE @DataTypeLength	INT
	SELECT @DataTypeVariable = Variable, @DataTypeLength = Length FROM MetaDataType WHERE DataTypeId = @DataTypeId
	IF (@Length <= 0 OR @Length > @DataTypeLength )
		SET @Length = @DataTypeLength
	INSERT INTO [MetaField]  ([Namespace], [Name], [FriendlyName], [Description], [DataTypeId], [Length], [AllowNulls],  [SaveHistory], [MultiLanguageValue], [AllowSearch])
		VALUES(@Namespace, @Name,  @FriendlyName, @Description, @DataTypeId, @Length, @AllowNulls, @SaveHistory,@MultiLanguageValue, @AllowSearch)
	IF @@ERROR <> 0 GOTO ERR
	SET @Retval = @@IDENTITY
	COMMIT TRAN
RETURN
ERR:
	SET @Retval = -1
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMetaFieldToMetaClass
	@MetaClassId	INT,
	@MetaFieldId	INT,
	@Weight	INT
AS
	SET NOCOUNT ON
	DECLARE @IsAbstractClass	BIT
	SELECT @IsAbstractClass = IsAbstract FROM MetaClass WHERE MetaClassId = @MetaClassId
BEGIN TRAN
	IF NOT EXISTS( SELECT * FROM MetaClass WHERE MetaClassId = @MetaClassId AND IsSystem = 0)
	BEGIN
		RAISERROR ('Wrong @MetaClassId. The class is system or not existed.', 16,1)
		GOTO ERR
	END
	IF NOT EXISTS( SELECT * FROM MetaField WHERE MetaFieldId = @MetaFieldId AND SystemMetaClassId = 0)
	BEGIN
		RAISERROR ('Wrong @MetaFieldId. The field is system or not existed.', 16,1)
		GOTO ERR
	END
	IF @IsAbstractClass = 0
	BEGIN
		DECLARE @Name		NVARCHAR(256)
		DECLARE @DataTypeId	INT
		DECLARE @Length		INT
		DECLARE @AllowNulls		BIT
		DECLARE @SaveHistory	BIT
		DECLARE @MultiLanguageValue BIT
		DECLARE @AllowSearch	BIT
		SELECT @Name = Name, @DataTypeId = DataTypeId,  @Length = Length, @AllowNulls = AllowNulls,
			@SaveHistory = SaveHistory, @MultiLanguageValue = MultiLanguageValue, @AllowSearch = AllowSearch
		FROM MetaField WHERE MetaFieldId = @MetaFieldId AND SystemMetaClassId = 0
		DECLARE @MetaClassTableName NVARCHAR(256)
		DECLARE @SqlDataTypeName NVARCHAR(256)
		DECLARE @IsVariableDataType BIT
		DECLARE @DefaultValue	NVARCHAR(50)
		SELECT @MetaClassTableName = TableName FROM MetaClass WHERE MetaClassId = @MetaClassId
		IF @@ERROR<> 0 GOTO ERR
		SELECT @SqlDataTypeName = SqlName,  @IsVariableDataType = Variable, @DefaultValue = DefaultValue FROM MetaDataType WHERE DataTypeId= @DataTypeId
		IF @@ERROR<> 0 GOTO ERR
		DECLARE @ExecLine 		NVARCHAR(1024)
		DECLARE @ExecLineHistory 	NVARCHAR(1024)
		SET @ExecLine = 'ALTER TABLE [dbo].['+@MetaClassTableName+'] ADD ['+@Name+'] ' + @SqlDataTypeName
		SET @ExecLineHistory = 'ALTER TABLE [dbo].['+@MetaClassTableName+'_History] ADD ['+@Name+'] ' + @SqlDataTypeName
		IF @IsVariableDataType = 1
		BEGIN
			SET @ExecLine = @ExecLine + ' (' + STR(@Length) + ')'
			SET @ExecLineHistory = @ExecLineHistory + ' (' + STR(@Length) + ')'
		END
		SET @ExecLineHistory = @ExecLineHistory + ' NULL'
		IF @AllowNulls = 1
		BEGIN
			SET @ExecLine = @ExecLine + ' NULL'
		END
		ELSE
			BEGIN
				SET @ExecLine = @ExecLine + ' NOT NULL DEFAULT ' + @DefaultValue
				SET @ExecLine = @ExecLine  +'  WITH VALUES'
			END
		EXEC (@ExecLine)
		IF @@ERROR<> 0 GOTO ERR
		EXEC (@ExecLineHistory)
		IF @@ERROR <> 0 GOTO ERR
	END
	INSERT INTO [MetaClassMetaFieldRelation] (MetaClassId, MetaFieldId, Weight) VALUES(@MetaClassId, @MetaFieldId, @Weight)
	IF @@ERROR <> 0 GOTO ERR
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_CreateMetaClassProcedure @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
		EXEC mdpsp_sys_CreateMetaClassHistoryTrigger @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
	END
	COMMIT TRAN
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId,1
	END
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMetaStringDictionary
	@MetaKey	INT,
	@Key		NVARCHAR(512),
	@Value		NTEXT
AS
	SET NOCOUNT ON
BEGIN TRAN
	INSERT INTO MetaStringDictionaryValue (MetaKey, [Key], [Value]) VALUES (@MetaKey, @Key, @Value)
COMMIT TRAN
RETURN
ERR:
ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_AddMultiValueDictionary
	@MetaKey	INT,
	@MetaDictionaryId	INT
AS
	SET NOCOUNT ON
BEGIN TRAN
	INSERT INTO MetaMultiValueDictionary (MetaKey, MetaDictionaryId) VALUES (@MetaKey, @MetaDictionaryId)
COMMIT TRAN
RETURN
ERR:
ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_CheckReplaceUser
	@OldUserId AS INT,
	@Retval AS INT OUTPUT
AS
	SET NOCOUNT ON
	SET @Retval = 0
	DECLARE classall_cursor CURSOR FOR
		SELECT MetaClassId, TableName FROM MetaClass WHERE IsSystem =0 AND IsAbstract = 0
	DECLARE @MetaClassId	INT
	DECLARE @TableName		NVARCHAR(255)
	OPEN classall_cursor
	FETCH NEXT FROM classall_cursor INTO @MetaClassId, @TableName
	DECLARE @SQLString NVARCHAR(500)
	WHILE(@@FETCH_STATUS = 0 AND @Retval = 0)
	BEGIN
		SET @SQLString  = N'IF EXISTS(SELECT TOP 1 * FROM ' + @TableName  + ' WHERE CreatorId = @OldUserId) SELECT 1'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT', @OldUserId = @OldUserId
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @Retval = 1
			BREAK
		END
		SET @SQLString  = N'IF EXISTS(SELECT TOP 1 * FROM ' + @TableName  + ' WHERE ModifierId = @OldUserId) SELECT 1'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT', @OldUserId = @OldUserId
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @Retval = 1
			BREAK
		END
		SET @SQLString  = N'IF EXISTS(SELECT TOP 1 * FROM ' + @TableName  + '_History WHERE ModifierId = @OldUserId) SELECT 1'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT', @OldUserId = @OldUserId
		IF @@ROWCOUNT <> 0
		BEGIN
			SET @Retval = 1
			BREAK
		END
		FETCH NEXT FROM classall_cursor INTO @MetaClassId, @TableName
	END
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_ClearMetaAttribute
	@AttrOwnerId		INT,
	@AttrOwnerType	INT
AS
	DELETE FROM MetaAttribute WHERE AttrOwnerId = @AttrOwnerId AND AttrOwnerType = @AttrOwnerType
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_ClearMultiValueDictionary
	@MetaKey	INT
AS
	DELETE FROM MetaMultiValueDictionary WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_ClearStringDictionary
	@MetaKey	INT
AS
	DELETE FROM MetaStringDictionaryValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_CreateMetaClass
	@Namespace 		NVARCHAR(1024),
	@Name 		NVARCHAR(256),
	@FriendlyName		NVARCHAR(256),
	@TableName 		NVARCHAR(256),
	@ParentClassId 		INT,
	@IsSystem		BIT,
	@IsAbstract		BIT	=	0,
	@Description 		NTEXT,
	@Retval 		INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET @Retval = -1
BEGIN TRAN
	INSERT INTO [MetaClass] ([Namespace],[Name], [FriendlyName],[Description], [TableName], [ParentClassId], [IsSystem], [IsAbstract])
		VALUES (@Namespace, @Name, @FriendlyName, @Description, @TableName, @ParentClassId, @IsSystem, @IsAbstract)
	IF @@ERROR <> 0 GOTO ERR
	SET @Retval = @@IDENTITY
	IF @IsSystem = 1
	BEGIN
		IF NOT EXISTS(SELECT * FROM SYSOBJECTS WHERE [NAME] = @TableName AND [type] = 'U')
		BEGIN
			RAISERROR ('Wrong System TableName.', 16,1 )
			GOTO ERR
		END
		INSERT INTO [MetaField]  ([Namespace], [Name], [FriendlyName], [SystemMetaClassId], [DataTypeId], [Length], [AllowNulls],  [SaveHistory], [MultiLanguageValue], [AllowSearch])
			 SELECT @Namespace+ N'.' + @Name, SC .[name] , SC .[name] , @Retval ,MDT .[DataTypeId], SC .[length], SC .[isnullable], 0, 0, 0  FROM SYSCOLUMNS AS SC
				INNER JOIN SYSOBJECTS SO ON SO.[ID] = SC.ID
				INNER JOIN SYSTYPES ST ON ST.[xtype] = SC .[xtype]
				INNER JOIN MetaDataType MDT ON MDT.[Name] = ST .[name]
			WHERE SO.[ID]  = object_id( @TableName) and OBJECTPROPERTY( SO.[ID], N'IsTable') = 1 and ST.name<>'sysname'
		IF @@ERROR<> 0 GOTO ERR
		INSERT INTO [MetaClassMetaFieldRelation]  (MetaClassId, MetaFieldId)
			SELECT @Retval, MetaFieldId FROM MetaField WHERE [SystemMetaClassId] = @Retval
	END
	ELSE
	BEGIN
		IF @IsAbstract = 0
		BEGIN
			EXEC('CREATE TABLE [dbo].[' + @TableName  + '] ([ObjectId] [int] NOT NULL , [CreatorId] [int]  , [Created] [datetime], [ModifierId] [int]  , [Modified] [datetime] ) ON [PRIMARY]')
			IF @@ERROR <> 0 GOTO ERR
			EXEC('ALTER TABLE [dbo].[' + @TableName  + '] WITH NOCHECK ADD CONSTRAINT [PK_' + @TableName  + '] PRIMARY KEY  CLUSTERED ([ObjectId])  ON [PRIMARY]')
			IF @@ERROR <> 0 GOTO ERR
			EXEC('CREATE TABLE [dbo].[' + @TableName  + '_History] ([Id] [int] IDENTITY (1, 1)  NOT NULL, [ObjectId] [int] NOT NULL , [ModifierId] [int]  ,	[Modified] [datetime] ) ON [PRIMARY]')
			IF @@ERROR <> 0 GOTO ERR
			EXEC('ALTER TABLE [dbo].[' + @TableName  + '_History] WITH NOCHECK ADD CONSTRAINT [PK_' + @TableName  + '_History] PRIMARY KEY  CLUSTERED ([Id])  ON [PRIMARY]')
			IF @@ERROR<> 0 GOTO ERR
			IF EXISTS(SELECT * FROM MetaClass WHERE MetaClassId = @ParentClassId  )
			BEGIN
				INSERT INTO [MetaClassMetaFieldRelation]  (MetaClassId, MetaFieldId)
					SELECT @Retval, MetaFieldId FROM MetaField WHERE [SystemMetaClassId] = @ParentClassId
			END
			IF @@ERROR<> 0 GOTO ERR
			EXEC mdpsp_sys_CreateMetaClassProcedure @Retval
			IF @@ERROR <> 0 GOTO ERR
		END
	END
	DECLARE @PrimaryKeyName	NVARCHAR(256)
	SELECT @PrimaryKeyName = name FROM Sysobjects WHERE OBJECTPROPERTY(id, N'IsPrimaryKey') = 1 and parent_obj = OBJECT_ID(@TableName) and OBJECTPROPERTY(parent_obj, N'IsUserTable') = 1
	IF @PrimaryKeyName IS NOT NULL
		UPDATE [MetaClass] SET PrimaryKeyName = @PrimaryKeyName WHERE MetaClassId = @Retval
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
	SET @Retval = -1
RETURN
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_CreateMetaClassHistoryTrigger
	@MetaClassId	INT
AS
	SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS( SELECT * FROM MetaClass WHERE MetaClassId = @MetaClassId AND IsSystem = 0)
	BEGIN
		RAISERROR ('Wrong @MetaClassId. The class is system or not existed.', 16,1)
		GOTO ERR
	END
	DECLARE	@MetaClassTable			NVARCHAR(256)
	DECLARE	@MetaClassHistoryTrigger		NVARCHAR(256)
	SELECT @MetaClassTable = TableName FROM MetaClass WHERE MetaClassId = @MetaClassId
	SET @MetaClassHistoryTrigger 		= 'mdptr_avto_' +@MetaClassTable +'_History'
	if EXISTS (SELECT name FROM sysobjects WHERE name = @MetaClassHistoryTrigger AND type = 'TR')
		EXEC('DROP TRIGGER ' + @MetaClassHistoryTrigger)
	IF @@ERROR <> 0 GOTO ERR
	DECLARE	@MetaClassFieldList		NVARCHAR(4000)
	DECLARE	@MetaClassFieldListWithI	NVARCHAR(4000)
	DECLARE	@MetaClassFieldListCmpr	NVARCHAR(4000)
	DECLARE	@MetaClassFieldListIF		NVARCHAR(4000)
	SET @MetaClassFieldList = 'ObjectId, ModifierId, Modified'
	SET @MetaClassFieldListWithI = 'D.ObjectId, D.ModifierId, D.Modified'
	SET @MetaClassFieldListCmpr = '1<>1'
	SET @MetaClassFieldListIF = '1<>1'
	DECLARE field_cursor CURSOR FOR
		SELECT MF.[Name] FROM MetaField MF
			INNER JOIN MetaClassMetaFieldRelation MCFR ON MCFR.MetaFieldId = MF.MetaFieldId
		WHERE MCFR.MetaClassId = @MetaClassId AND MF.SystemMetaClassId = 0 AND MF.SaveHistory = 1 ORDER BY MCFR.Weight
	DECLARE @Name 	NVARCHAR(256)
	OPEN field_cursor
	FETCH NEXT FROM field_cursor INTO @Name
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @MetaClassFieldList = @MetaClassFieldList + ', [' + @Name + ']'
		SET @MetaClassFieldListWithI = @MetaClassFieldListWithI + ', D.[' + @Name + ']'
		SET @MetaClassFieldListCmpr = @MetaClassFieldListCmpr + ' OR I.[' + @Name + '] <> D.[' + @Name + ']'
		SET @MetaClassFieldListIF = @MetaClassFieldListIF + ' OR UPDATE([' + @Name + '])'
	FETCH NEXT FROM field_cursor INTO @Name
	END
	CLOSE field_cursor
	DEALLOCATE field_cursor
		SET QUOTED_IDENTIFIER OFF
		SET ANSI_NULLS OFF
		EXEC('CREATE TRIGGER ' + @MetaClassHistoryTrigger + ' ON ' + @MetaClassTable + ' FOR INSERT, UPDATE AS' + ' DECLARE @rows INT ' +
			'SELECT @rows = @@rowcount IF @rows = 0 RETURN '  +
			'IF ' + @MetaClassFieldListIF +' BEGIN INSERT INTO ' +@MetaClassTable+ '_History (' + @MetaClassFieldList + ')  SELECT ' + @MetaClassFieldListWithI + ' FROM DELETED D JOIN INSERTED I ON (D.ObjectId = I.ObjectId) WHERE ' +  @MetaClassFieldListCmpr + ' END')
		IF @@ERROR <> 0 GOTO ERR
		SET QUOTED_IDENTIFIER OFF
		SET ANSI_NULLS ON
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_CreateMetaClassProcedure
	@MetaClassId	INT
AS
	SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS( SELECT * FROM MetaClass WHERE MetaClassId = @MetaClassId)
	BEGIN
		RAISERROR ('Wrong @MetaClassId. The class is system or not existed.', 16,1)
		GOTO ERR
	END
	DECLARE	@MetaClassTable			NVARCHAR(256)
	DECLARE	@MetaClassGetSpName			NVARCHAR(256)
	DECLARE	@MetaClassUpdateSpName		NVARCHAR(256)
	DECLARE	@MetaClassDeleteSpName		NVARCHAR(256)
	DECLARE	@MetaClassListSpName			NVARCHAR(256)
	DECLARE	@MetaClassHistorySpName		NVARCHAR(256)
	SELECT @MetaClassTable = TableName FROM MetaClass WHERE MetaClassId = @MetaClassId
	SET @MetaClassGetSpName 		= 'mdpsp_avto_' +@MetaClassTable +'_Get'
	SET @MetaClassUpdateSpName 	= 'mdpsp_avto_' +@MetaClassTable +'_Update'
	SET @MetaClassDeleteSpName 		= 'mdpsp_avto_' +@MetaClassTable +'_Delete'
	SET @MetaClassListSpName 		= 'mdpsp_avto_' +@MetaClassTable +'_List'
	SET @MetaClassHistorySpName 	= 'mdpsp_avto_' +@MetaClassTable +'_History'
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassGetSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassGetSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassUpdateSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassUpdateSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassDeleteSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassDeleteSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassListSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassListSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassHistorySpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassHistorySpName)
	IF @@ERROR <> 0 GOTO ERR
	DECLARE	@MetaClassFieldList		NVARCHAR(4000)
	DECLARE	@MetaClassFieldListWithAt	NVARCHAR(4000)
	DECLARE	@MetaClassFieldListSet		NVARCHAR(4000)
	DECLARE	@MetaClassFieldListInsert	NVARCHAR(4000)
	SET @MetaClassFieldList = 'ObjectId, CreatorId, Created, ModifierId, Modified'
	SET @MetaClassFieldListWithAt = '@ObjectId INT, @CreatorId INT, @Created DATETIME, @ModifierId INT, @Modified DATETIME, @Retval INT OUT'
	SET @MetaClassFieldListSet = 'CreatorId = @CreatorId, Created = @Created, ModifierId = @ModifierId, Modified = @Modified'
	SET @MetaClassFieldListInsert = '@ObjectId, @CreatorId, @Created, @ModifierId, @Modified'
	DECLARE field_cursor CURSOR FOR
		SELECT MF.[Name], DT.SqlName, DT.Variable, MF.Length FROM MetaField MF
			INNER JOIN MetaDataType DT ON DT.DataTypeId = MF.DataTypeId
			INNER JOIN MetaClassMetaFieldRelation MCFR ON MCFR.MetaFieldId = MF.MetaFieldId
		WHERE MCFR.MetaClassId = @MetaClassId AND MF.SystemMetaClassId = 0 ORDER BY MCFR.Weight
	DECLARE @Name 	NVARCHAR(256)
	DECLARE @SqlName 	NVARCHAR(256)
	DECLARE @Variable 	BIT
	DECLARE @Length 	INT
	OPEN field_cursor
	FETCH NEXT FROM field_cursor INTO @Name, @SqlName, @Variable, @Length
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @MetaClassFieldList = @MetaClassFieldList + ', '
		SET @MetaClassFieldListWithAt = @MetaClassFieldListWithAt + ', '
		SET @MetaClassFieldListSet = @MetaClassFieldListSet + ', '
		SET @MetaClassFieldListInsert = @MetaClassFieldListInsert + ', '
		SET @MetaClassFieldList = @MetaClassFieldList + '[' + @Name + ']'
		SET @MetaClassFieldListSet = @MetaClassFieldListSet + '[' +@Name + '] = @' + @Name
		SET @MetaClassFieldListInsert = @MetaClassFieldListInsert + '@' + @Name
		IF @Variable = 0
			SET @MetaClassFieldListWithAt = @MetaClassFieldListWithAt + '@' + @Name + ' ' + @SqlName
		ELSE
			SET @MetaClassFieldListWithAt = @MetaClassFieldListWithAt + '@' + @Name + ' ' + @SqlName + '(' + STR(@Length) + ') '
	FETCH NEXT FROM field_cursor INTO @Name, @SqlName, @Variable, @Length
	END
	CLOSE field_cursor
	DEALLOCATE field_cursor
	SET QUOTED_IDENTIFIER OFF
	SET ANSI_NULLS OFF
	EXEC('CREATE PROCEDURE [dbo].[' + @MetaClassGetSpName + '] '  + '@ObjectId INT AS SELECT ' + @MetaClassFieldList + ' FROM ' +@MetaClassTable + ' WHERE ObjectId = @ObjectId')
	IF @@ERROR <> 0 GOTO ERR
	EXEC('CREATE PROCEDURE [dbo].[' + @MetaClassUpdateSpName + '] '  + @MetaClassFieldListWithAt +
		' AS ' +
		' SET NOCOUNT ON ' +
		' BEGIN TRAN IF @ObjectId = -1 BEGIN SELECT @ObjectId = MAX(ObjectId)+1 FROM ' + @MetaClassTable + ' IF (@ObjectId IS NULL)  SET @ObjectId = 1 END ' +
		' SET @Retval = @ObjectId ' +
                           ' IF EXISTS(SELECT * FROM '+ @MetaClassTable +' WHERE ObjectId = @ObjectId  ) UPDATE ' + @MetaClassTable + ' SET ' + @MetaClassFieldListSet + ' WHERE ObjectId = @ObjectId' +
		' ELSE INSERT INTO ' + @MetaClassTable + ' ('+ @MetaClassFieldList + ') VALUES (' + @MetaClassFieldListInsert + ')' +
		' IF @@ERROR <> 0 GOTO ERR COMMIT TRAN RETURN ERR: ROLLBACK TRAN RETURN '
	)
	IF @@ERROR <> 0 GOTO ERR
	DECLARE @MetaClassIdSTR NVARCHAR(10)
	SET @MetaClassIdSTR = CAST( @MetaClassId AS NVARCHAR(10) )
	EXEC ('CREATE PROCEDURE [dbo].[' + @MetaClassDeleteSpName + ']  @ObjectId INT AS DELETE FROM '  + @MetaClassTable + ' WHERE ObjectId = @ObjectId DELETE FROM ' + @MetaClassTable +'_History WHERE ObjectId = @ObjectId ' +
		' EXEC mdpsp_sys_DeleteMetaKeyObjects '+@MetaClassIdSTR+', -1, @ObjectId ')
	IF @@ERROR <> 0 GOTO ERR
	EXEC('CREATE PROCEDURE [dbo].[' + @MetaClassListSpName + '] '  + ' AS SELECT ' + @MetaClassFieldList + ' FROM ' +@MetaClassTable )
	IF @@ERROR <> 0 GOTO ERR
	EXEC('CREATE PROCEDURE [dbo].[' + @MetaClassHistorySpName + '] '  + ' @ObjectId INT  AS SELECT * FROM ' +@MetaClassTable + '_History WHERE ObjectId = @ObjectId' )
	IF @@ERROR <> 0 GOTO ERR
	SET QUOTED_IDENTIFIER OFF
	SET ANSI_NULLS ON
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_CreateMetaClassProcedureAll
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE classall_cursor CURSOR FOR
		SELECT MetaClassId FROM MetaClass WHERE IsSystem =0 AND IsAbstract = 0
	DECLARE @MetaClassId	INT
	OPEN classall_cursor
	FETCH NEXT FROM classall_cursor INTO @MetaClassId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC  mdpsp_sys_CreateMetaClassProcedure @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
	FETCH NEXT FROM classall_cursor INTO @MetaClassId
	END
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	COMMIT TRAN
RETURN
ERR:
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteDContrainByTableAndField
	@TableName	NVARCHAR(256),
	@FieldName	NVARCHAR(256)
AS
	SET NOCOUNT ON
	DECLARE @DConstrainName NVARCHAR(256)
	DECLARE DConstrainCursor CURSOR FOR
		SELECT SO.Name FROM sysobjects SO
			LEFT JOIN syscolumns SC ON SC.ID = SO.parent_obj
			LEFT JOIN sysobjects ST ON SC.ID = ST.id
		WHERE (SC.Name = @FieldName AND ST.Name = @TableName AND ST.type='U' AND SO.type = 'D')
	OPEN DConstrainCursor
	FETCH NEXT FROM DConstrainCursor  INTO @DConstrainName
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC('ALTER TABLE [dbo].[' + @TableName +'] DROP  CONSTRAINT '+ @DConstrainName)
		FETCH NEXT FROM DConstrainCursor  INTO @DConstrainName
	END
	CLOSE DConstrainCursor
	DEALLOCATE DConstrainCursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaAttribute
	@AttrOwnerId		INT,
	@AttrOwnerType	INT,
	@Key			NVARCHAR(512)
AS
	DELETE FROM MetaAttribute WHERE AttrOwnerId = @AttrOwnerId AND AttrOwnerType = @AttrOwnerType AND [Key] = @Key
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaClass
	@MetaClassId	INT
AS
	SET NOCOUNT ON
	BEGIN TRAN
	DECLARE @MetaFieldOwnerTable	NVARCHAR(256)
	IF EXISTS(SELECT *  FROM MetaClass MC WHERE ParentClassId = @MetaClassId)
	BEGIN
		RAISERROR ('The class have childs.', 16, 1)
		GOTO ERR
	END
	IF EXISTS(SELECT *  FROM MetaClass MC WHERE MetaClassId = @MetaClassId)
	BEGIN
		IF EXISTS(SELECT *  FROM MetaClass MC WHERE MetaClassId = @MetaClassId AND IsSystem = 0 AND IsAbstract = 0)
		BEGIN
			SELECT @MetaFieldOwnerTable = TableName  FROM MetaClass MC WHERE MetaClassId = @MetaClassId AND IsSystem = 0 AND IsAbstract = 0
			IF @@ERROR <> 0 GOTO ERR
			EXEC mdpsp_sys_DeleteMetaClassProcedure @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
			EXEC('DROP TABLE [dbo].[' + @MetaFieldOwnerTable + ']')
			IF @@ERROR <> 0 GOTO ERR
			EXEC('DROP TABLE [dbo].[' + @MetaFieldOwnerTable + '_History]')
			IF @@ERROR <> 0 GOTO ERR
			EXEC mdpsp_sys_DeleteMetaKeyObjects @MetaClassId
			 IF @@ERROR <> 0 GOTO ERR
			EXEC mdpsp_sys_ClearMetaAttribute @MetaClassId, 1
			 IF @@ERROR <> 0 GOTO ERR
			DELETE FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
			DELETE FROM MetaClass WHERE MetaClassId = @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
		END
		ELSE
		BEGIN
			EXEC mdpsp_sys_ClearMetaAttribute @MetaClassId, 1
			 IF @@ERROR <> 0 GOTO ERR
			DELETE FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
			DELETE FROM MetaField WHERE SystemMetaClassId = @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
			DELETE FROM MetaClass WHERE MetaClassId = @MetaClassId
			IF @@ERROR <> 0 GOTO ERR
		END
	END
	ELSE
	BEGIN
		RAISERROR ('Wrong @MetaClassId.', 16, 1)
		GOTO ERR
	END
	COMMIT TRAN
	RETURN
ERR:
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaClassProcedure
	@MetaClassId	INT
AS
	SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS( SELECT * FROM MetaClass WHERE MetaClassId = @MetaClassId)
	BEGIN
		RAISERROR ('Wrong @MetaClassId. The class is system or not existed.', 16,1)
		GOTO ERR
	END
	PRINT'Step 1. Create SQL Code'
	DECLARE	@MetaClassTable			NVARCHAR(256)
	DECLARE	@MetaClassGetSpName			NVARCHAR(256)
	DECLARE	@MetaClassUpdateSpName		NVARCHAR(256)
	DECLARE	@MetaClassDeleteSpName		NVARCHAR(256)
	DECLARE	@MetaClassListSpName		NVARCHAR(256)
	DECLARE	@MetaClassHistorySpName		NVARCHAR(256)
	SELECT @MetaClassTable = TableName FROM MetaClass WHERE MetaClassId = @MetaClassId
	SET @MetaClassGetSpName 		= 'mdpsp_avto_' +@MetaClassTable +'_Get'
	SET @MetaClassUpdateSpName 	= 'mdpsp_avto_' +@MetaClassTable +'_Update'
	SET @MetaClassDeleteSpName 	= 'mdpsp_avto_' +@MetaClassTable +'_Delete'
	SET @MetaClassListSpName 	= 'mdpsp_avto_' +@MetaClassTable +'_List'
	SET @MetaClassHistorySpName 	= 'mdpsp_avto_' +@MetaClassTable +'_History'
	PRINT'Step 2. Drop operation'
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassUpdateSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassUpdateSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassGetSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassGetSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassDeleteSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassDeleteSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassListSpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassListSpName)
	IF @@ERROR <> 0 GOTO ERR
	if exists (select * from dbo.sysobjects where id = object_id(@MetaClassHistorySpName) and OBJECTPROPERTY(id, N'IsProcedure') = 1)
		EXEC('drop procedure ' + @MetaClassHistorySpName)
	IF @@ERROR <> 0 GOTO ERR
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaDictionary
	@MetaDictionaryId	INT
AS
BEGIN
	SET NOCOUNT ON
	BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM MetaDictionary WHERE MetaDictionaryId = @MetaDictionaryId)
	BEGIN
		RAISERROR ('Wrong @MetaDictionaryId.', 16, 1)
		GOTO ERR
	END
	DELETE FROM MetaDictionary WHERE MetaDictionaryId = @MetaDictionaryId
	IF @@ERROR <> 0 GOTO ERR
	COMMIT TRAN
	RETURN
ERR:
	ROLLBACK TRAN
	RETURN @@Error
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaField
	@MetaFieldId	INT
AS
BEGIN
	SET NOCOUNT ON
	BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM MetaClassMetaFieldRelation WHERE MetaFieldId = @MetaFieldId)
	BEGIN
		DELETE FROM MetaDictionary WHERE MetaFieldId = @MetaFieldId
		IF @@ERROR <> 0 GOTO ERR
		DELETE FROM MetaField WHERE MetaFieldId = @MetaFieldId
		IF @@ERROR <> 0 GOTO ERR
		EXEC mdpsp_sys_ClearMetaAttribute @MetaFieldId, 2
		IF @@ERROR <> 0 GOTO ERR
	END
	ELSE
	BEGIN
		RAISERROR ('The MetaClass have got a link to @MetaFieldId.', 16, 1)
		GOTO ERR
	END
	COMMIT TRAN
	RETURN
ERR:
	ROLLBACK TRAN
	RETURN @@Error
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaFieldFromMetaClass
	@MetaClassId	INT,
	@MetaFieldId	INT
AS
BEGIN
	IF NOT EXISTS(SELECT * FROM MetaClassMetaFieldRelation WHERE MetaFieldId = @MetaFieldId AND MetaClassId = @MetaClassId)
	BEGIN
		RETURN
	END
	SET NOCOUNT ON
	DECLARE @MetaFieldName		NVARCHAR(256)
	DECLARE @MetaFieldOwnerTable	NVARCHAR(256)
	DECLARE @IsAbstractClass		BIT
	IF NOT EXISTS(SELECT * FROM MetaField MF WHERE MetaFieldId = @MetaFieldId AND SystemMetaClassId = 0 )
	BEGIN
		RAISERROR ('Wrong @MetaFieldId.', 16, 1)
		GOTO ERR
	END
	SELECT @MetaFieldName = MF.[Name] FROM MetaField MF WHERE MetaFieldId = @MetaFieldId AND SystemMetaClassId = 0
	IF NOT EXISTS(SELECT * FROM MetaClass MC WHERE MetaClassId = @MetaClassId AND IsSystem = 0)
	BEGIN
		RAISERROR ('Wrong @MetaClassId.', 16, 1)
		GOTO ERR
	END
	SELECT @MetaFieldOwnerTable = MC.TableName, @IsAbstractClass = MC.IsAbstract FROM MetaClass MC WHERE MetaClassId = @MetaClassId AND IsSystem = 0
	 IF @@ERROR <> 0 GOTO ERR
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId, 0
	END
	BEGIN TRAN
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_DeleteMetaKeyObjects @MetaClassId, @MetaFieldId
		 IF @@ERROR <> 0 GOTO ERR
		EXEC mdpsp_sys_DeleteDContrainByTableAndField @MetaFieldOwnerTable, @MetaFieldName
		IF @@ERROR <> 0 GOTO ERR
		EXEC ('ALTER TABLE ['+@MetaFieldOwnerTable+'] DROP COLUMN [' + @MetaFieldName + ']')
		IF @@ERROR <> 0 GOTO ERR
		SET @MetaFieldOwnerTable = @MetaFieldOwnerTable + '_History'
		EXEC mdpsp_sys_DeleteDContrainByTableAndField @MetaFieldOwnerTable, @MetaFieldName
		IF @@ERROR <> 0 GOTO ERR
		EXEC ('ALTER TABLE ['+@MetaFieldOwnerTable+'] DROP COLUMN [' + @MetaFieldName + ']')
		IF @@ERROR <> 0 GOTO ERR
	END
	DELETE FROM MetaClassMetaFieldRelation WHERE MetaFieldId = @MetaFieldId AND MetaClassId = @MetaClassId
	IF @@ERROR <> 0 GOTO ERR
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_CreateMetaClassProcedure @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
		EXEC mdpsp_sys_CreateMetaClassHistoryTrigger @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
	END
	COMMIT TRAN
	RETURN
ERR:
	ROLLBACK TRAN
	IF @IsAbstractClass = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId, 1
	END
	RETURN @@Error
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaFile
	@MetaKey	INT
AS
	SET NOCOUNT ON
	DELETE FROM MetaFileValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaKeyObjects
	@MetaClassId	INT,
	@MetaFieldId	INT	=	-1,
	@MetaObjectId	INT	=	-1
AS
	DELETE FROM MetaObjectValue  WHERE MetaKey IN
		(SELECT MK.MetaKey FROM MetaKey MK WHERE
			(@MetaObjectId = MK.MetaObjectId OR @MetaObjectId = -1)  AND
			(@MetaClassId = MK.MetaClassId OR @MetaClassId = -1) AND
			(@MetaFieldId = MK.MetaFieldId  OR @MetaFieldId = -1)
		)
	 IF @@ERROR <> 0 GOTO ERR
	DELETE FROM MetaStringDictionaryValue  WHERE MetaKey IN
		(SELECT MK.MetaKey FROM MetaKey MK WHERE
			(@MetaObjectId = MK.MetaObjectId OR @MetaObjectId = -1)  AND
			(@MetaClassId = MK.MetaClassId OR @MetaClassId = -1) AND
			(@MetaFieldId = MK.MetaFieldId  OR @MetaFieldId = -1)
		)
	 IF @@ERROR <> 0 GOTO ERR
	DELETE FROM MetaMultiValueDictionary  WHERE MetaKey IN
		(SELECT MK.MetaKey FROM MetaKey MK WHERE
			(@MetaObjectId = MK.MetaObjectId OR @MetaObjectId = -1)  AND
			(@MetaClassId = MK.MetaClassId OR @MetaClassId = -1) AND
			(@MetaFieldId = MK.MetaFieldId  OR @MetaFieldId = -1)
		)
	 IF @@ERROR <> 0 GOTO ERR
	DELETE FROM MetaFileValue  WHERE MetaKey IN
		(SELECT MK.MetaKey FROM MetaKey MK WHERE
			(@MetaObjectId = MK.MetaObjectId OR @MetaObjectId = -1)  AND
			(@MetaClassId = MK.MetaClassId OR @MetaClassId = -1) AND
			(@MetaFieldId = MK.MetaFieldId  OR @MetaFieldId = -1)
		)
	 IF @@ERROR <> 0 GOTO ERR
	DELETE FROM MetaKey  WHERE
		(@MetaObjectId = MetaObjectId OR @MetaObjectId = -1)  AND
		(@MetaClassId = MetaClassId OR @MetaClassId = -1) AND
		(@MetaFieldId = MetaFieldId  OR @MetaFieldId = -1)
ERR:
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_DeleteMetaObjectValue
	@MetaKey	INT
AS
	SET NOCOUNT ON
	DELETE FROM MetaObjectValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[mdpsp_sys_DeleteMetaRule]
	@RuleId	INT
AS
	SET NOCOUNT ON
	DELETE FROM MetaRule WHERE RuleId=@RuleId
	SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesActivate
AS
	EXEC sp_fulltext_database  'enable'
	EXEC sp_fulltext_catalog 'MetaDataFullTextQueriesCatalog', 'create'
	EXEC sp_fulltext_catalog  'MetaDataFullTextQueriesCatalog',  'start_full'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesAddAllFields
AS
	DECLARE field_w_search CURSOR FOR
		SELECT MCMFR.MetaClassId, MCMFR.MetaFieldId FROM MetaClassMetaFieldRelation MCMFR
			INNER JOIN MetaField MF ON MCMFR.MetaFieldId = MF.MetaFieldId
		WHERE MF.AllowSearch = 1 AND (MF.SystemMetaClassId = 0 OR MF.SystemMetaClassId = MCMFR.MetaClassId)
	DECLARE @MetaClassId INT
	DECLARE @MetaFieldId  INT
	OPEN field_w_search
	FETCH NEXT FROM field_w_search INTO @MetaClassId, @MetaFieldId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId, 1
	FETCH NEXT FROM field_w_search INTO @MetaClassId, @MetaFieldId
	END
	CLOSE field_w_search
	DEALLOCATE field_w_search
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesDeactivate
AS
	DECLARE TableInFulltextCatalog	CURSOR FOR
		SELECT SO.[Name] as TableName FROM dbo.sysobjects SO INNER JOIN sysfulltextcatalogs SFTC ON SFTC.ftcatid = SO.ftcatid where OBJECTPROPERTY(id, N'IsTable') = 1 AND SFTC.[Name] = 'MetaDataFullTextQueriesCatalog'
	DECLARE @TableName 	NVARCHAR(256)
	OPEN TableInFulltextCatalog
	FETCH NEXT FROM TableInFulltextCatalog INTO @TableName
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC sp_fulltext_table @TableName, 'Drop'
	FETCH NEXT FROM TableInFulltextCatalog INTO @TableName
	END
	CLOSE  TableInFulltextCatalog
	DEALLOCATE TableInFulltextCatalog
	EXEC sp_fulltext_catalog 'MetaDataFullTextQueriesCatalog', 'drop'
	EXEC sp_fulltext_database  'disable'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesDeleteAllFields
AS
	DECLARE field_w_search CURSOR FOR
		SELECT MCMFR.MetaClassId, MCMFR.MetaFieldId FROM MetaClassMetaFieldRelation MCMFR
			INNER JOIN MetaField MF ON MCMFR.MetaFieldId = MF.MetaFieldId
		WHERE MF.AllowSearch = 1
	DECLARE @MetaClassId INT
	DECLARE @MetaFieldId  INT
	OPEN field_w_search
	FETCH NEXT FROM field_w_search INTO @MetaClassId, @MetaFieldId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId, 0
	FETCH NEXT FROM field_w_search INTO @MetaClassId, @MetaFieldId
	END
	CLOSE field_w_search
	DEALLOCATE field_w_search
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesEnable
AS
	SELECT CASE FULLTEXTSERVICEPROPERTY( 'IsFullTextInstalled' )
	WHEN 1 THEN
		CASE DatabaseProperty (DB_NAME(DB_ID()),  'IsFulltextEnabled')
		WHEN 1 THEN 1
		ELSE 0
		END
	ELSE 0
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_FullTextQueriesFieldUpdate
	@MetaClassId 	INT,
	@MetaFieldId	INT,
	@Add		BIT
AS
	DECLARE 	@IsFulltextEnabled INT
	SELECT @IsFulltextEnabled = (CASE FULLTEXTSERVICEPROPERTY( 'IsFullTextInstalled' ) WHEN 1 THEN CASE DatabaseProperty (DB_NAME(DB_ID()),  'IsFulltextEnabled') WHEN 1 THEN 1 ELSE 0 END ELSE 0 END)
	IF @IsFulltextEnabled = 0
		RETURN
	DECLARE @TableName		NVARCHAR(256)
	SELECT @TableName	= TableName FROM MetaClass WHERE MetaClassId = @MetaClassId
	DECLARE @FieldName		NVARCHAR(256)
	SELECT @FieldName	= MF.Name FROM MetaField MF
		INNER JOIN MetaDataType MDT ON MDT.DataTypeId = MF.DataTypeId
	WHERE MF.MetaFieldId = @MetaFieldId AND MDT.SqlName IN (N'char', N'nchar', N'varchar', N'nvarchar', N'text', N'ntext', N'image')
	IF (@TableName IS NULL) OR (@FieldName IS NULL)
		RETURN
	DECLARE @TableFulltextCatalogId	INT
	SELECT @TableFulltextCatalogId = OBJECTPROPERTY (OBJECT_ID(TableName), 'TableFulltextCatalogId') FROM MetaClass WHERE MetaClassId = @MetaClassId
	IF @TableFulltextCatalogId = 0
	BEGIN
		DECLARE	@PK_Table NVARCHAR(256)
		SELECT 	@PK_Table = PrimaryKeyName FROM MetaClass WHERE MetaClassId = @MetaClassId
		EXEC sp_fulltext_table  @TableName, 'create', 'MetaDataFullTextQueriesCatalog', @PK_Table
		IF @Add = 1
			EXEC sp_fulltext_column @TableName,  @FieldName,  'add'
	END
	ELSE
	BEGIN
		EXEC sp_fulltext_table  @TableName,  'deactivate'
		IF @Add = 1
			EXEC sp_fulltext_column @TableName,  @FieldName,  'add'
		ELSE
			EXEC sp_fulltext_column @TableName,  @FieldName,  'drop'
	END
	DECLARE @SFCount	INT
	SELECT @SFCount = SUM(COLUMNPROPERTY ( OBJECT_ID(@TableName), [name],  'IsFullTextIndexed' )) FROM MetaField
	IF @SFCount = 0
	BEGIN
		EXEC sp_fulltext_table  @TableName,  'drop'
	END
	ELSE
	BEGIN
		EXEC sp_fulltext_table @TableName,  'activate'
	END
	EXEC sp_fulltext_catalog  'MetaDataFullTextQueriesCatalog',  'start_full'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_GetMetaKey
	@MetaObjectId	INT,
	@MetaClassId	INT,
	@MetaFieldId	INT,
	@Retval	INT	OUT
AS
	SET NOCOUNT ON
	IF EXISTS(SELECT * FROM MetaKey WHERE MetaObjectId = @MetaObjectId AND MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId)
	BEGIN
		SELECT @RetVal = MetaKey FROM MetaKey WHERE MetaObjectId = @MetaObjectId AND MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId
	END
	ELSE
	BEGIN
		INSERT INTO MetaKey (MetaObjectId, MetaClassId, MetaFieldId) VALUES (@MetaObjectId, @MetaClassId, @MetaFieldId)
		SET @Retval = @@IDENTITY
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_GetMetaKeyInfo
	@MetaKey	INT
AS
	SET NOCOUNT ON
	SELECT * FROM MetaKey WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_GetUniqueFieldName
	@Name		NVARCHAR(256),
	@UniqueName 	NVARCHAR(256) OUT
AS
	SET NOCOUNT OFF
	DECLARE	@Index		INT
	SET @UniqueName 	= @Name
	SET @Index		= (SELECT COUNT(*) FROM MetaField WHERE SystemMetaClassId = 0 AND Name LIKE @Name + '[0123456789]%')
	WHILE (SELECT COUNT(*) FROM MetaField WHERE SystemMetaClassId = 0 AND Name=@UniqueName) <> 0
	BEGIN
		SET @UniqueName = @Name + CAST(@Index  AS NVARCHAR(32))
		SET @Index = @Index + 1
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadChildMetaClassList
	@MetaClassId	INT
AS
	SELECT MetaClassId, Namespace,Name, [FriendlyName], IsSystem, IsAbstract, ParentClassId, TableName, Description, FieldListChangedSqlScript, Tag
	FROM MetaClass WHERE ParentClassId = @MetaClassId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaAttributes
	@AttrOwnerId		INT,
	@AttrOwnerType	INT
AS
	SELECT [Key], [Value] FROM MetaAttribute WHERE AttrOwnerId = @AttrOwnerId AND AttrOwnerType = @AttrOwnerType
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaClassById
	@MetaClassId	INT
AS
	SELECT MetaClassId, Namespace, Name, FriendlyName, IsSystem, IsAbstract, ParentClassId, TableName, Description, FieldListChangedSqlScript, Tag
	FROM MetaClass WHERE MetaClassId = @MetaClassId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaClassByName
	@Name		NVARCHAR(256)
AS
	SELECT MetaClassId, Namespace, Name, FriendlyName, IsSystem, IsAbstract,ParentClassId, TableName, Description, FieldListChangedSqlScript, Tag
	FROM MetaClass WHERE Name = @Name
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaClassByNamespace
	@Namespace		NVARCHAR(1024),
	@Deep			BIT
AS
	IF @Deep = 1
		SELECT MetaClassId, Namespace, Name, FriendlyName, IsSystem, IsAbstract, ParentClassId, TableName, Description, FieldListChangedSqlScript, Tag
		FROM MetaClass WHERE  Namespace = @Namespace OR Namespace LIKE (@Namespace + '.%')
	ELSE
		SELECT MetaClassId, Namespace, Name, FriendlyName, IsSystem, IsAbstract, ParentClassId, TableName, Description, FieldListChangedSqlScript, Tag
		FROM MetaClass WHERE Namespace = @Namespace
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaClassList
AS
SELECT C.MetaClassId, C.Namespace, C.[Name], C.FriendlyName, C.IsSystem, C.IsAbstract, C.ParentClassId, C.TableName, C.[Description], C.FieldListChangedSqlScript, C.Tag,
	P.[Name] AS ParentName, P.TableName AS ParentTableName, P.FriendlyName AS ParentFriendlyName
  FROM MetaClass C
	LEFT JOIN MetaClass P ON (C.ParentClassId = P.MetaClassId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaClassListByMetaField
	@MetaFieldId	INT
AS
	SELECT MC.MetaClassId, MC.Namespace, MC.Name, MC.FriendlyName, MC.IsSystem,  MC.IsAbstract, MC.ParentClassId, MC.TableName, MC.Description, MC.FieldListChangedSqlScript, MC.Tag
	FROM MetaClass MC
	INNER JOIN MetaClassMetaFieldRelation MCFR ON MCFR.MetaClassId = MC.MetaClassId
	WHERE MCFR.MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaDictionary
	@MetaFieldId	INT
AS
	SELECT MetaDictionaryId, MetaFieldId, [Value] FROM MetaDictionary WHERE MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaField
	@MetaFieldId	INT
AS
	SELECT [MetaFieldId] , [Namespace], [Name], [FriendlyName], [Description], [SystemMetaClassId], [DataTypeId],[Length],[AllowNulls],[SaveHistory],[MultiLanguageValue], [AllowSearch], [Tag]
	FROM MetaField WHERE MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFieldByName
	@Name		NVARCHAR(256)
AS
	SELECT [MetaFieldId] ,  [Namespace], [Name], [FriendlyName], [Description], [SystemMetaClassId], [DataTypeId],[Length],[AllowNulls],[SaveHistory],[MultiLanguageValue], [AllowSearch], [Tag]
	FROM MetaField WHERE  [Name] = @Name	AND SystemMetaClassId = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFieldByNamespace
	@Namespace		NVARCHAR(1024),
	@Deep			BIT
AS
	IF @Deep = 1
		SELECT [MetaFieldId] ,  [Namespace], [Name], [FriendlyName], [Description], [SystemMetaClassId], [DataTypeId],[Length],[AllowNulls],[SaveHistory],[MultiLanguageValue], [AllowSearch], [Tag]
		FROM MetaField WHERE Namespace = @Namespace OR Namespace LIKE (@Namespace + '.%')
	ELSE
		SELECT [MetaFieldId] ,  [Namespace], [Name], [FriendlyName], [Description], [SystemMetaClassId], [DataTypeId],[Length],[AllowNulls],[SaveHistory],[MultiLanguageValue], [AllowSearch], [Tag]
		FROM MetaField WHERE Namespace = @Namespace
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFieldList
AS
	SELECT [MetaFieldId] ,  [Namespace], [Name], [FriendlyName], [Description], [SystemMetaClassId], [DataTypeId],[Length],[AllowNulls],[SaveHistory],[MultiLanguageValue], [AllowSearch], [Tag]
	FROM MetaField
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFieldListByMetaClassId
	@MetaClassId	INT
AS
	SELECT MF.[MetaFieldId] ,  MF.[Namespace], MF.[Name], MF.[FriendlyName], MF.[Description], MF.[SystemMetaClassId] , MF.[DataTypeId], MF.[Length], MF.[AllowNulls], MF.[SaveHistory], MF.[MultiLanguageValue], MF.[AllowSearch] , MF.Tag, MCFR.[Weight], MCFR.[Enabled]
		FROM MetaField MF
	INNER JOIN MetaClassMetaFieldRelation MCFR ON MCFR.MetaFieldId = MF.MetaFieldId
	WHERE MCFR.MetaClassId = @MetaClassId
	ORDER BY MCFR.[Weight]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFieldWeight
	@MetaClassId	INT,
	@MetaFieldId	INT
AS
	IF NOT EXISTS(	SELECT * FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId)
		RAISERROR ('Wrong @MetaClassId or @MetaFieldId.', 16,1)
	SELECT Weight, Enabled FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFile
	@MetaKey	INT
AS
	SELECT MetaKey, [FileName], ContentType, Data, CreationTime, LastWriteTime, LastReadTime FROM MetaFileValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaFileList
 AS
	SELECT MetaKey, [FileName], ContentType, Data, CreationTime, LastWriteTime, LastReadTime FROM MetaFileValue
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaObjectValue
	@MetaKey	INT
AS
	SELECT MetaKey, MetaClassId, MetaObjectId  FROM MetaObjectValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[mdpsp_sys_LoadMetaRuleById]
	@RuleId	INT
AS
	SELECT RuleId, MetaClassId, Data FROM MetaRule
	WHERE RuleId = @RuleId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[mdpsp_sys_LoadMetaRuleByMetaClassId]
	@MetaClassId	INT
AS
	SELECT RuleId, MetaClassId, Data FROM MetaRule
	WHERE MetaClassId = @MetaClassId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaStringDictionary
	@MetaKey	INT
AS
	SELECT MetaKey, [Key],[Value] FROM MetaStringDictionaryValue WHERE MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaType
	@MetaTypeId	INT
AS
	SELECT DataTypeId, Name, FriendlyName, Description, Length, SqlName, AllowNulls, Variable, IsSQLCommonType FROM MetaDataType WHERE
		DataTypeId = @MetaTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMetaTypeList
AS
	SELECT DataTypeId, [Name], FriendlyName, [Description], Length, SqlName, AllowNulls, Variable, IsSQLCommonType FROM MetaDataType
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_LoadMultiValueDictionary
	@MetaKey	INT
AS
	SELECT MD.MetaDictionaryId, MD.MetaFieldId, MD.[Value] FROM MetaDictionary MD
		INNER JOIN MetaMultiValueDictionary  MVD ON MVD.MetaDictionaryId = MD.MetaDictionaryId
		WHERE MVD.MetaKey = @MetaKey
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_MetaFieldAllowSearch
	@MetaFieldId 	INT,
	@AllowSearch	BIT
AS
	SET NOCOUNT ON
	IF NOT EXISTS( SELECT * FROM MetaField WHERE MetaFieldId = @MetaFieldId)
	BEGIN
		RAISERROR ('Wrong @MetaFieldId. The field is system or not existed.', 16,1)
		GOTO ERR
	END
	UPDATE MetaField SET AllowSearch = @AllowSearch WHERE MetaFieldId = @MetaFieldId
	DECLARE class_w_search CURSOR FOR
		SELECT MCMFR.MetaClassId FROM MetaClassMetaFieldRelation MCMFR
			INNER JOIN MetaField MF ON MF.MetaFieldId = MCMFR.MetaFieldId
			INNER JOIN MetaClass MC ON MC.MetaClassId = MCMFR.MetaClassId
		WHERE MCMFR.MetaFieldId = @MetaFieldId AND (MC.IsSystem = 1 OR MF.SystemMetaClassId = 0 )
	DECLARE @MetaClassId INT
	OPEN class_w_search
	FETCH NEXT FROM class_w_search INTO @MetaClassId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC mdpsp_sys_FullTextQueriesFieldUpdate @MetaClassId, @MetaFieldId, @AllowSearch
		FETCH NEXT FROM class_w_search INTO @MetaClassId
	END
	CLOSE class_w_search
	DEALLOCATE class_w_search
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_MetaFieldSaveHistory
	@MetaFieldId 	INT,
	@SaveHistory	BIT
AS
	SET NOCOUNT ON
	BEGIN TRAN
	IF NOT EXISTS( SELECT * FROM MetaField WHERE MetaFieldId = @MetaFieldId  AND SystemMetaClassId = 0)
	BEGIN
		RAISERROR ('Wrong @MetaFieldId. The field is system or not existed.', 16,1)
		GOTO ERR
	END
	UPDATE MetaField SET SaveHistory = @SaveHistory WHERE MetaFieldId = @MetaFieldId
	IF @@ERROR <> 0 GOTO ERR
	DECLARE class_cursor CURSOR FOR
		SELECT MetaClassId  FROM MetaClassMetaFieldRelation WHERE MetaFieldId =   @MetaFieldId
	DECLARE @MetaClassId INT
	OPEN class_cursor
	FETCH NEXT FROM class_cursor INTO @MetaClassId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC mdpsp_sys_CreateMetaClassHistoryTrigger @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
	FETCH NEXT FROM class_cursor INTO @MetaClassId
	END
	CLOSE class_cursor
	DEALLOCATE class_cursor
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_RefreshSystemMetaClassInfo
	@MetaClassId	INT
AS
	SET NOCOUNT ON
BEGIN TRAN
	DECLARE @TableName NVARCHAR(256)
	DECLARE @Namespace NVARCHAR(1024)
	DECLARE @Name NVARCHAR(256)
	IF NOT EXISTS( SELECT * FROM MetaClass WHERE MetaClassId = @MetaClassId AND IsSystem = 1)
	BEGIN
		RAISERROR ('Wrong @MetaClassId. The class is neither system nor existed.', 16,1)
		GOTO ERR
	END
	SELECT @Name = [Name], @TableName = TableName, @Namespace = Namespace FROM MetaClass WHERE MetaClassId = @MetaClassId AND IsSystem = 1
	DELETE FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId
	IF @@ERROR<> 0 GOTO ERR
	DELETE FROM MetaClassMetaFieldRelation WHERE MetaFieldId IN (SELECT MetaFieldId FROM MetaField WHERE SystemMetaClassId = @MetaClassId)
	IF @@ERROR<> 0 GOTO ERR
	DELETE FROM MetaField WHERE SystemMetaClassId = @MetaClassId
	IF @@ERROR<> 0 GOTO ERR
	INSERT INTO [MetaField]  ([Namespace], [Name], [FriendlyName], [SystemMetaClassId], [DataTypeId], [Length], [AllowNulls],  [SaveHistory], [MultiLanguageValue], [AllowSearch])
			 SELECT @Namespace+ N'.' + @Name, SC .[name] , SC .[name] , @MetaClassId ,MDT .[DataTypeId], SC .[length], SC .[isnullable], 0, 0, 0  FROM SYSCOLUMNS AS SC
				INNER JOIN SYSOBJECTS SO ON SO.[ID] = SC.ID
				INNER JOIN SYSTYPES ST ON ST.[xtype] = SC .[xtype]
				INNER JOIN MetaDataType MDT ON MDT.[Name] = ST .[name]
			WHERE SO.[ID]  = object_id( @TableName) and OBJECTPROPERTY( SO.[ID], N'IsTable') = 1 and ST.name<>'sysname'
	IF @@ERROR<> 0 GOTO ERR
	INSERT INTO [MetaClassMetaFieldRelation]  (MetaClassId, MetaFieldId)
		SELECT @MetaClassId, MetaFieldId FROM MetaField WHERE [SystemMetaClassId] = @MetaClassId
	IF @@ERROR<> 0 GOTO ERR
	INSERT INTO [MetaClassMetaFieldRelation]  (MetaClassId, MetaFieldId)
		SELECT MC.MetaClassId, MF.MetaFieldId FROM MetaField MF, MetaClass MC
			WHERE MF.[SystemMetaClassId] = @MetaClassId AND MC.ParentClassId = @MetaClassId ORDER BY MC.MetaClassId
	IF @@ERROR<> 0 GOTO ERR
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_RefreshSystemMetaClassInfoAll
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE classall_cursor CURSOR FOR
		SELECT MetaClassId FROM MetaClass WHERE IsSystem =1
	DECLARE @MetaClassId	INT
	OPEN classall_cursor
	FETCH NEXT FROM classall_cursor INTO @MetaClassId
	WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT @MetaClassId
		EXEC  mdpsp_sys_RefreshSystemMetaClassInfo @MetaClassId
		IF @@ERROR <> 0 GOTO ERR
	FETCH NEXT FROM classall_cursor INTO @MetaClassId
	END
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	COMMIT TRAN
RETURN
ERR:
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_ReplaceUser
	@OldUserId AS INT,
	@NewUserId AS INT
AS
SET NOCOUNT ON
BEGIN TRAN
	DECLARE classall_cursor CURSOR FOR
		SELECT MetaClassId, TableName FROM MetaClass WHERE IsSystem =0 AND IsAbstract = 0
	DECLARE @MetaClassId	INT
	DECLARE @TableName		NVARCHAR(255)
	OPEN classall_cursor
	FETCH NEXT FROM classall_cursor INTO @MetaClassId, @TableName
	DECLARE @SQLString NVARCHAR(500)
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @SQLString  = N'UPDATE ' + @TableName  + ' SET CreatorId = @NewUserId WHERE CreatorId = @OldUserId'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT, 	@NewUserId AS INT', @OldUserId = @OldUserId, @NewUserId = @NewUserId
		IF @@ERROR <> 0 GOTO ERR
		SET @SQLString  = N'UPDATE ' + @TableName  + ' SET ModifierId = @NewUserId WHERE ModifierId = @OldUserId'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT, 	@NewUserId AS INT', @OldUserId = @OldUserId, @NewUserId = @NewUserId
		IF @@ERROR <> 0 GOTO ERR
		SET @SQLString  = N'UPDATE ' + @TableName  + '_History SET ModifierId = @NewUserId WHERE ModifierId = @OldUserId'
		EXEC sp_executesql @SQLString, N'@OldUserId AS INT, 	@NewUserId AS INT', @OldUserId = @OldUserId, @NewUserId = @NewUserId
		IF @@ERROR <> 0 GOTO ERR
	FETCH NEXT FROM classall_cursor INTO @MetaClassId, @TableName
	END
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	COMMIT TRAN
RETURN
ERR:
	CLOSE classall_cursor
	DEALLOCATE classall_cursor
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaClass
	@MetaClassId 	INT,
	@Namespace		NVARCHAR(1024),
	@Name			NVARCHAR(256),
	@FriendlyName		NVARCHAR(256),
	@Description		NTEXT,
	@Tag			IMAGE
AS
	UPDATE MetaClass SET Namespace = @Namespace, Name = @Name, FriendlyName = @FriendlyName, Description = @Description, Tag = @Tag WHERE MetaClassId = @MetaClassId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaDictionary
	@MetaDictionaryId	INT,
	@Value			NVARCHAR(1024)
AS
	SET NOCOUNT ON
BEGIN TRAN
	IF NOT EXISTS(SELECT * FROM MetaDictionary WHERE MetaDictionaryId = @MetaDictionaryId )
	BEGIN
		RAISERROR('Wrong @MetaDictionaryId.',16,1)
		GOTO ERR
	END
	UPDATE MetaDictionary SET [Value] = @Value WHERE MetaDictionaryId = @MetaDictionaryId
	IF @@ERROR <> 0 GOTO ERR
	COMMIT TRAN
RETURN
ERR:
	ROLLBACK TRAN
RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaField
	@MetaFieldId 	INT,
	@Namespace 	NVARCHAR(1024) = N'Mediachase.MetaDataPlus.User',
	@FriendlyName	NVARCHAR(256),
	@Description	NTEXT,
	@Tag		IMAGE
AS
	UPDATE MetaField SET Namespace = @Namespace, FriendlyName = @FriendlyName, Description = @Description, Tag = @Tag WHERE MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaFieldEnabled
	@MetaClassId	INT,
	@MetaFieldId	INT,
	@Enabled	BIT
AS
	IF NOT EXISTS(	SELECT * FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId)
		RAISERROR ('Wrong @MetaClassId or @MetaFieldId.', 16,1)
	ELSE
		UPDATE MetaClassMetaFieldRelation SET  Enabled = @Enabled WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaFieldWeight
	@MetaClassId	INT,
	@MetaFieldId	INT,
	@Weight	INT
AS
	IF NOT EXISTS(	SELECT * FROM MetaClassMetaFieldRelation WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId)
		RAISERROR ('Wrong @MetaClassId or @MetaFieldId.', 16,1)
	ELSE
		UPDATE MetaClassMetaFieldRelation SET  Weight = @Weight WHERE MetaClassId = @MetaClassId AND MetaFieldId = @MetaFieldId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaFile
	@MetaKey	INT,
	@FileName	NVARCHAR(256),
	@ContentType	NVARCHAR(256),
	@Data		image,
	@Size		INT,
	@CreationTime	DATETIME,
	@LastWriteTime 	DATETIME,
	@LastReadTime	DATETIME
AS
	SET NOCOUNT ON
	IF (EXISTS(SELECT * FROM MetaFileValue WHERE MetaKey = @MetaKey) )
		UPDATE MetaFileValue SET [FileName] = @FileName, ContentType = @ContentType, Data = @Data, [Size] = @Size,
			CreationTime = @CreationTime, LastWriteTime = @LastWriteTime, LastReadTime = @LastReadTime WHERE MetaKey = @MetaKey
	ELSE
		INSERT INTO MetaFileValue (MetaKey,FileName,ContentType,Data, Size,CreationTime, LastWriteTime, LastReadTime )
			VALUES (@MetaKey,@FileName,@ContentType,@Data, @Size,@CreationTime, @LastWriteTime, @LastReadTime)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaObjectValue
	@MetaKey	INT,
	@MetaClassId	INT,
	@MetaObjectId	INT
AS
	SET NOCOUNT ON
	IF (EXISTS(SELECT * FROM MetaObjectValue WHERE MetaKey = @MetaKey) )
		UPDATE MetaObjectValue SET MetaClassId = @MetaClassId, MetaObjectId = @MetaObjectId WHERE MetaKey = @MetaKey
	ELSE
		INSERT INTO MetaObjectValue (MetaKey,MetaClassId,MetaObjectId)
			VALUES (@MetaKey,@MetaClassId,@MetaObjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[mdpsp_sys_UpdateMetaRule]
	@RuleId	INT,
	@MetaClassId	INT,
	@Data		IMAGE,
	@RetVal	INT	OUTPUT
AS
	SET NOCOUNT ON
	IF ((SELECT COUNT(*) FROM MetaRule WHERE RuleId=@RuleId) = 0)
	BEGIN
		INSERT INTO MetaRule(MetaClassId, Data) VALUES (@MetaClassId, @Data)
		IF @@ERROR <> 0 SET @RetVal = -1
		ELSE SET @RetVal = @@IDENTITY
	END
	ELSE
	BEGIN
		UPDATE MetaRule SET Data=@Data WHERE RuleId=@RuleId
		SET @RetVal = @RuleId
	END
	SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].mdpsp_sys_UpdateMetaSqlScriptTemplate
	@MetaClassId 	INT,
	@FieldListChanged	NTEXT
AS
	UPDATE MetaClass SET FieldListChangedSqlScript = @FieldListChanged WHERE MetaClassId = @MetaClassId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Message_GetByUserIdAndTimeFilter]
	@UserId as int,
	@StartDate as datetime,
	@EndDate as datetime
as
SELECT LogId, Sent, Subject, Body
  FROM MESSAGE_LOG
  WHERE Sent >= @StartDate AND Sent <= @EndDate
	AND LogId IN (SELECT LogId FROM SYSTEM_EVENT_RECIPIENTS WHERE UserId = @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ObjectCategoryAdd
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@CategoryId as int
as
INSERT INTO OBJECT_CATEGORY (ObjectTypeId, ObjectId, CategoryId)
  VALUES(@ObjectTypeId, @ObjectId, @CategoryId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ObjectCategoryDelete
	@ObjectTypeId as int,
	@ObjectId as int,
	@CategoryId as int
AS
DELETE FROM OBJECT_CATEGORY
  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId AND CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ObjectsGetForManagerViewGroupedByCategory
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
DECLARE @CompletedState as int
set @CompletedState=5
DECLARE @EventType int
SET @EventType = 4
SELECT DISTINCT C.CategoryId, C.CategoryName, 3 AS ItemType, PR.ProjectId AS ItemId, PR.Title, PR.PriorityId, P.PriorityName, PR.CreationDate, PR.StartDate, PR.FinishDate, PR.PercentCompleted, CAST(0 as bit) as IsCompleted,
	PR.ManagerId, 0 as ReasonId, PR.ProjectId, 0 as StateId, 0 as CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=3 AND OC.CategoryId = C.CategoryId)
	JOIN PROJECTS PR ON (OC.ObjectId = PR.ProjectId)
	JOIN PROJECT_MEMBERS PM ON (PR.ProjectId = PM.ProjectId)
	JOIN PRIORITY_LANGUAGE P ON (PR.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	JOIN PROJECT_STATUS PS ON (PR.StatusId = PS.StatusId)
  WHERE (PM.PrincipalId = @PrincipalId OR PM.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND(PM.IsTeamMember=1)
	AND (@ManagerId=0 OR PR.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR PR.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(PR.StartDate<=@StartDate)AND(PR.StatusId=4))
	OR((@CompletedDate is not null)AND(PR.ActualFinishDate>=@CompletedDate)AND(PS.IsActive=0))
	OR((@ShowActive=1 AND PS.IsActive = 1))
	)
UNION ALL
SELECT DISTINCT C.CategoryId, C.CategoryName, 5 AS ItemType, T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	PR.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=5 AND OC.CategoryId = C.CategoryId)
	JOIN TASKS T ON (OC.ObjectId = T.TaskId)
	JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId)
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	JOIN PROJECTS PR ON (T.ProjectId=PR.ProjectId)
  WHERE  (TS.PrincipalId = @PrincipalId OR TS.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (TS.IsRealTaskResource=1)
	AND (@ManagerId=0 OR PR.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
UNION ALL
SELECT DISTINCT C.CategoryId, C.CategoryName, 6 AS ItemType, T.TodoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	T.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=6 AND OC.CategoryId = C.CategoryId)
	JOIN TODO T ON (OC.ObjectId = T.TodoId)
	JOIN TODO_SECURITY_ALL TS ON (T.TodoId = TS.TodoId)
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (TS.PrincipalId = @PrincipalId OR TS.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (TS.IsResource=1)
	AND (@ManagerId=0 OR T.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
UNION ALL
SELECT DISTINCT C.CategoryId, C.CategoryName, 7 AS ItemType, I.IncidentId AS ItemId, I.Title, I.PriorityId, P.PriorityName, I.CreationDate, I.ActivationDate as StartDate, I.CloseDate as FinishDate, 0 as PercentCompleted, CAST(0 AS bit) AS IsCompleted,
	I.ManagerId, 0 as ReasonId, I.ProjectId, I.StateId, 0 as CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=7 AND OC.CategoryId = C.CategoryId)
	JOIN INCIDENTS I ON (OC.ObjectId = I.IncidentId)
	JOIN INCIDENT_SECURITY_ALL S ON (I.IncidentId = S.IncidentId)
	JOIN PRIORITY_LANGUAGE P ON (I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsRealIncidentResource=1)
	AND (@ManagerId=0 OR I.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR I.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(I.ActivationDate<=@StartDate)AND(I.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(I.CloseDate>=@CompletedDate)AND(I.StateId=4 OR I.StateId=5))
	OR((@ShowActive=1 AND (I.StateId=@ActiveState OR I.StateId=@OverdueState)))
	)
UNION ALL
SELECT DISTINCT C.CategoryId, C.CategoryName, 4 AS ItemType, E.EventId AS ItemId, E.Title, E.PriorityId, P.PriorityName, E.CreationDate, E.StartDate, E.FinishDate, 0 as PercentCompleted, CAST(0 as bit) as IsCompleted,
	E.ManagerId, 0 as ReasonId, E.ProjectId, E.StateId, 0 as CompletionTypeId,
	CASE WHEN R.RecurrenceId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=4 AND OC.CategoryId = C.CategoryId)
	JOIN EVENTS E ON (OC.ObjectId = E.EventId)
	JOIN EVENT_SECURITY_ALL S ON (E.EventId = S.EventId)
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsResource=1)
	AND (@ManagerId=0 OR E.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR E.ProjectId=@ProjectId)
	AND
	(
		(
			R.RecurrenceId IS NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.StateId=@UpcomingState)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StateId=@CompletedState)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
		OR
		(
			R.RecurrenceId IS NOT NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.FinishDate>=@dt)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StartDate<=@dt)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
	)
UNION ALL
SELECT DISTINCT C.CategoryId, C.CategoryName, 16 AS ItemType, D.DocumentId AS ItemId, D.Title, D.PriorityId, P.PriorityName, D.CreationDate, D.CreationDate as StartDate, D.ClosedDate as FinishDate, 0 as PercentCompleted, D.IsCompleted,
	D.ManagerId, D.ReasonId, D.ProjectId, D.StateId, 0 as CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (OC.ObjectTypeId=16 AND OC.CategoryId = C.CategoryId)
	JOIN DOCUMENTS D ON (OC.ObjectId = D.DocumentId)
	JOIN DOCUMENT_SECURITY_ALL S ON (D.DocumentId = S.DocumentId)
	JOIN PRIORITY_LANGUAGE P ON (D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsRealDocumentResource=1)
	AND (@ManagerId=0 OR D.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR D.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(D.CreationDate<=@StartDate)AND(D.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(D.ClosedDate>=@CompletedDate)AND(D.IsCompleted=1))
	OR((@ShowActive=1 AND (D.StateId=@ActiveState OR D.StateId=@OverdueState)))
	)
ORDER BY C.CategoryId, ItemType
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ObjectsGetForManagerViewGroupedByUser
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
DECLARE @CompletedState as int
set @CompletedState=5
DECLARE @EventType int
SET @EventType = 4
SELECT U.PrincipalId, U.FirstName, U.LastName, 5 AS ItemType, T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	PR.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM Users U
	JOIN TASK_SECURITY TS ON (U.PrincipalId = TS.PrincipalId)
	JOIN TASKS T ON (TS.TaskId = T.TaskId)
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	JOIN PROJECTS PR ON (T.ProjectId=PR.ProjectId)
  WHERE (TS.PrincipalId = @PrincipalId OR TS.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND(TS.IsRealTaskResource=1)
	AND (@ManagerId=0 OR PR.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
UNION ALL
SELECT U.PrincipalId, U.FirstName, U.LastName, 6 AS ItemType, T.TodoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	T.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM Users U
	JOIN TODO_SECURITY_ALL TS ON (U.PrincipalId = TS.PrincipalId)
	JOIN TODO T ON (TS.TodoId = T.TodoId)
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (TS.PrincipalId = @PrincipalId OR TS.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (TS.IsResource=1)
	AND (@ManagerId=0 OR T.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
UNION ALL
SELECT U.PrincipalId, U.FirstName, U.LastName, 7 AS ItemType, I.IncidentId AS ItemId, I.Title, I.PriorityId, P.PriorityName, I.CreationDate, I.ActivationDate as StartDate, I.CloseDate as FinishDate, 0 as PercentCompleted, CAST(0 AS bit) AS IsCompleted,
	I.ManagerId, 0 as ReasonId, I.ProjectId, I.StateId, 0 as CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM Users U
	JOIN INCIDENT_SECURITY_ALL S ON (U.PrincipalId = S.PrincipalId)
	JOIN INCIDENTS I ON (S.IncidentId = I.IncidentId)
	JOIN PRIORITY_LANGUAGE P ON (I.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsRealIncidentResource=1)
	AND (@ManagerId=0 OR I.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR I.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(I.ActivationDate<=@StartDate)AND(I.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(I.CloseDate>=@CompletedDate)AND(I.StateId=4 OR I.StateId=5))
	OR((@ShowActive=1 AND (I.StateId=@ActiveState OR I.StateId=@OverdueState)))
	)
UNION ALL
SELECT U.PrincipalId, U.FirstName, U.LastName, 4 AS ItemType, E.EventId AS ItemId, E.Title, E.PriorityId, P.PriorityName, E.CreationDate, E.StartDate, E.FinishDate, 0 as PercentCompleted, CAST(0 as bit) as IsCompleted,
	E.ManagerId, 0 as ReasonId, E.ProjectId, E.StateId, 0 as CompletionTypeId,
	CASE WHEN R.RecurrenceId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS HasRecurrence
  FROM Users U
	JOIN EVENT_SECURITY_ALL S ON (U.PrincipalId = S.PrincipalId)
	JOIN EVENTS E ON (S.EventId = E.EventId)
	JOIN PRIORITY_LANGUAGE P ON (E.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
	LEFT JOIN RECURRENCE R ON (E.EventId = R.ObjectId AND R.ObjectTypeId = @EventType)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsResource=1)
	AND (@ManagerId=0 OR E.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR E.ProjectId=@ProjectId)
	AND
	(
		(
			R.RecurrenceId IS NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.StateId=@UpcomingState)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StateId=@CompletedState)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
		OR
		(
			R.RecurrenceId IS NOT NULL AND
			(
				(@StartDate is not null AND E.StartDate<=@StartDate AND E.FinishDate>=@dt)
				OR
				(@CompletedDate is not null AND E.FinishDate>=@CompletedDate AND E.StartDate<=@dt)
				OR
				(@ShowActive=1 AND E.StateId=@ActiveState)
			)
		)
	)
UNION ALL
SELECT U.PrincipalId, U.FirstName, U.LastName, 16 AS ItemType, D.DocumentId AS ItemId, D.Title, D.PriorityId, P.PriorityName, D.CreationDate, D.CreationDate as StartDate, D.ClosedDate as FinishDate, 0 as PercentCompleted, D.IsCompleted,
	D.ManagerId, D.ReasonId, D.ProjectId, D.StateId, 0 as CompletionTypeId, CAST(0 as bit) AS HasRecurrence
  FROM Users U
	JOIN DOCUMENT_SECURITY_ALL S ON (U.PrincipalId = S.PrincipalId)
	JOIN DOCUMENTS D ON (S.DocumentId = D.DocumentId)
	JOIN PRIORITY_LANGUAGE P ON (D.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE (S.PrincipalId = @PrincipalId OR S.PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId ))
	AND (S.IsRealDocumentResource=1)
	AND (@ManagerId=0 OR D.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR D.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(D.CreationDate<=@StartDate)AND(D.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(D.ClosedDate>=@CompletedDate)AND(D.IsCompleted=1))
	OR((@ShowActive=1 AND (D.StateId=@ActiveState OR D.StateId=@OverdueState)))
	)
ORDER BY U.PrincipalId, ItemType, ItemId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ObjectViewTabsGetByObjectTypeId
	@ObjectTypeId as int,
	@LanguageId as int
as
SELECT T.TabId, T.TemplateId, T.IsDefault, T.RowNum, T.PosNum, TL.Title
	FROM OBJECT_VIEW_TABS  T
	JOIN OBJECT_VIEW_TABS_LANGUAGE TL ON TL.TabId=T.TabId
  WHERE T.ObjectTypeId=@ObjectTypeId AND TL.LanguageId=@LanguageId
ORDER BY T.PosNum
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[page_ControlPropertiesDeleteAllInControlPlace]
	@PageUID nvarchar(250),
	@ControlPlaceID nvarchar(250)
 AS
DELETE dbo.page_ControlProperties
WHERE [PageUID]=@PageUID AND [ControlPlaceID]=@ControlPlaceID
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[page_ControlPropertiesInsertInControlPlace]
	@PageUID nvarchar(250),
	@ControlPlaceID nvarchar(250),
	@ControlIndex int,
	@ControlUID nvarchar (250),
	@ControlProperties ntext
 AS
INSERT INTO  dbo.page_ControlProperties ([PageUID], [ControlPlaceID], [ControlIndex], [ControlUID], [ControlProperties])
VALUES  (@PageUID, @ControlPlaceID, @ControlIndex, @ControlUID, @ControlProperties)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[page_ControlPropertiesSelectAllInControlPlace]
	@PageUID nvarchar(250),
	@ControlPlaceID nvarchar(250)
 AS
SELECT [ControlIndex],[ControlUID], [ControlProperties]
	FROM dbo.page_ControlProperties
	WHERE [PageUID] = @PageUID AND [ControlPlaceID]  = @ControlPlaceID
	ORDER BY [ControlIndex] ASC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PageViewGetByObjectTypeId
	@ObjectTypeId as int,
	@LanguageId as int
as
SELECT P.ViewPageId, P.MenuId, P.ShortInfoPath, PL.Title, ML.MenuXML
	FROM OBJECT_VIEW_PAGES  P
	JOIN OBJECT_VIEW_PAGES_LANGUAGE PL ON PL.ViewPageId=P.ViewPageId
	JOIN OBJECT_MENUS_LANGUAGE ML ON ML.MenuId=P.MenuId
	WHERE P.ObjectTypeId=@ObjectTypeId AND PL.LanguageId=@LanguageId AND ML.LanguageId=@LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PartnerGroupAdd
	@PartnerId as int ,
	@GroupId as int
as
if NOT EXISTS(SELECT * FROM PARTNER_GROUP WHERE PartnerId = @PartnerId AND GroupId = @GroupId)
	INSERT INTO PARTNER_GROUP (PartnerId, GroupId) VALUES(@PartnerId, @GroupId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PartnerGroupCheckGroupVisibility
	@PartnerId as int ,
	@GroupId as int,
	@retval as int output
as
if EXISTS(SELECT * FROM PARTNER_GROUP WHERE PartnerId = @PartnerId AND GroupId = @GroupId) OR @PartnerId = @GroupId
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PartnerGroupCheckUserVisibility
	@PartnerId as int ,
	@UserId as int,
	@retval as int output
as
if EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId
		AND (GroupId = @PartnerId OR GroupId IN (SELECT GroupId FROM PARTNER_GROUP WHERE PartnerId = @PartnerId)))
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PartnerGroupDelete
	@PartnerId as int,
	@GroupId as int
as
DELETE FROM PARTNER_GROUP
  WHERE PartnerId = @PartnerId AND GroupId = @GroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PartnerGroupGetListByPartner
	@PartnerId as int,
	@IncludeCurrent as bit,
	@IncludeEveryone as bit
as
IF @IncludeCurrent = 0
	SELECT P.PartnerId, P.GroupId, G.GroupName, 1 AS [Level]
	  FROM PARTNER_GROUP  P
		JOIN GROUPS G ON (P.GroupId = G.PrincipalId)
	  WHERE P.PartnerId = @PartnerId AND (@IncludeEveryone = 1 OR GroupId != 1)
ELSE
	SELECT P.PartnerId, P.GroupId, G.GroupName, 1 AS [Level]
	  FROM PARTNER_GROUP  P
		JOIN GROUPS G ON (P.GroupId = G.PrincipalId)
	  WHERE P.PartnerId = @PartnerId AND (@IncludeEveryone = 1 OR GroupId != 1)
	UNION
	SELECT PrincipalId AS PartnerId, PrincipalId AS GroupId, GroupName, 1 AS [Level]
	  FROM GROUPS
	  WHERE PrincipalId = @PartnerId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxAddMessageUId]
	@Pop3BoxId int,
	@MessageUId varchar(70)
AS
	INSERT INTO Pop3MessageUIds (Pop3BoxId, MessageUId)
	VALUES (@Pop3BoxId, @MessageUId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxAddParameter]
	@Pop3BoxId int,
	@Name nvarchar(255),
	@Value nvarchar(255)
AS
	SET NOCOUNT ON
	INSERT INTO Pop3BoxParameters (Pop3BoxId, Name, [Value])
	VALUES (@Pop3BoxId, @Name,  @Value)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxCheckMessageUId]
	@Pop3BoxId int,
	@MessageUId varchar(70),
	@Retval int output
AS
	IF EXISTS(SELECT * FROM Pop3MessageUIds WHERE Pop3BoxId=@Pop3BoxId AND MessageUId=@MessageUId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxCreate]
	@Name nvarchar(255),
	@Server nvarchar(255),
	@Port int,
	@Login nvarchar(255),
	@Password nvarchar(255),
	@Active bit,
	@Interval int,
	@LastRequest datetime,
	@LastSuccessfulRequest datetime,
	@LastErrorText nvarchar(255),
	@AutoKillForRead bit
AS
	INSERT INTO Pop3Boxes (Name, Server, Port, Login, Password, Active, [Interval], LastRequest, LastSuccessfulRequest, LastErrorText, AutoKillForRead)
	VALUES (@Name, @Server, @Port, @Login, @Password, @Active, @Interval, @LastRequest, @LastSuccessfulRequest, @LastErrorText, @AutoKillForRead)
	SELECT pb.Pop3BoxId, Name, Server, Port, Login, Password, [Interval], LastRequest, LastSuccessfulRequest, Active, AutoKillForRead, LastErrorText
	FROM Pop3Boxes pb
	WHERE pb.Pop3BoxId=@@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxCreateHandler]
	@Pop3BoxId int,
	@HandlerName nvarchar(255)
AS
	SET NOCOUNT ON
	INSERT INTO Pop3BoxPop3DocumentHandler (Pop3BoxId, HandlerName)
	VALUES (@Pop3BoxId, @HandlerName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxDelete]
	@Pop3BoxId int
AS
	SET NOCOUNT ON
	DELETE FROM Pop3Boxes WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxDeleteHandlers]
	@Pop3BoxId int
AS
	SET NOCOUNT ON
	DELETE FROM Pop3BoxPop3DocumentHandler WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxDeleteMessageUIds]
	@Pop3BoxId int
AS
	DELETE FROM Pop3MessageUIds WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxDeleteParameters]
	@Pop3BoxId int
AS
	SET NOCOUNT ON
	DELETE FROM Pop3BoxParameters WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3BoxGetById
	@Pop3BoxId int
AS
SELECT Pop3BoxId, [Name], Server, Port, Login, [Password], [Interval], LastRequest, LastSuccessfulRequest, Active, AutoKillForRead, LastErrorText
  FROM Pop3Boxes
  WHERE Pop3BoxId = @Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxGetList]
AS
	SELECT pb.Pop3BoxId, Name, Server, Port, Login, Password, [Interval], LastRequest, LastSuccessfulRequest, HandlerName, Active, AutoKillForRead, LastErrorText
	FROM Pop3Boxes pb
		LEFT JOIN Pop3BoxPop3DocumentHandler pbh ON pb.Pop3BoxId=pbh.Pop3BoxId
	ORDER BY pb.Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxGetParameterList]
	@Pop3BoxId int
AS
	SELECT [Name], [Value]
	FROM Pop3BoxParameters
	WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxUpdate]
	@Pop3BoxId int,
	@Name nvarchar(255),
	@Server nvarchar(255),
	@Port int,
	@Login nvarchar(255),
	@Password nvarchar(255),
	@Active bit,
	@Interval int,
	@LastRequest datetime,
	@LastSuccessfulRequest datetime,
	@LastErrorText nvarchar(255),
	@AutoKillForRead bit
AS
	SET NOCOUNT ON
	UPDATE  Pop3Boxes SET Active=@Active, Name=@Name, Server=@Server, Port=@Port, Login=@Login, Password=@Password, [Interval]=@Interval,
		LastRequest=@LastRequest, LastSuccessfulRequest=@LastSuccessfulRequest, LastErrorText=@LastErrorText, AutoKillForRead=@AutoKillForRead
	WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[Pop3BoxUpdateTime]
	@Pop3BoxId int,
	@LastRequest datetime,
	@LastSuccessfulRequest datetime,
	@LastErrorText nvarchar(255)
AS
	SET NOCOUNT ON
	UPDATE  Pop3Boxes SET LastRequest=@LastRequest, LastSuccessfulRequest=@LastSuccessfulRequest, LastErrorText=@LastErrorText
	WHERE Pop3BoxId=@Pop3BoxId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].POP3IncidentAdd
	@MailboxId as int,
	@From as nvarchar(255) ,
	@FirstName as nvarchar(50),
	@LastName as nvarchar(50),
	@Title as nvarchar(255) ,
	@Description as ntext = null ,
	@PriorityId as int,
	@retval int output
as
INSERT INTO POP3_INCIDENTS (MailboxId, [From], FirstName, LastName, Title, [Description], PriorityId)
  VALUES(@MailboxId, @From, @FirstName, @LastName, @Title, @Description, @PriorityId)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[POP3IncidentAddMHTFile]
	@Pop3IncidentId as int,
	@MHTFileId as int
AS
UPDATE POP3_INCIDENTS SET MHTFileId = @MHTFileId WHERE IncidentId = @Pop3IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].POP3IncidentDelete
       @IncidentId as int
as
DELETE FROM POP3_INCIDENTS  WHERE IncidentId = @IncidentId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].POP3IncidentsGet
	@IncidentId as int,
	@MailboxId as int,
	@LanguageId as int
as
SELECT I.IncidentId, I.MailboxId, I.[From] AS Sender, I.FirstName, I.LastName, I.Title, I.[Description], I.PriorityId, PR.PriorityName, I.MHTFileId, I.CreationDate,
	CASE
		WHEN EXISTS(SELECT * FROM USERS WHERE Email = I.[From] AND IsExternal = 1) THEN 1
		WHEN EXISTS(SELECT * FROM USERS WHERE Email = I.[From] AND IsExternal = 0) THEN 2
		ELSE 0
	END AS SenderType
  FROM POP3_INCIDENTS I
	JOIN PRIORITY_LANGUAGE PR ON (I.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
  WHERE (I.IncidentId = @IncidentId OR @IncidentId=0) AND (I.MailboxId = @MailboxId OR @MailboxId=0)
  ORDER BY I.CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3MailRequestCreate
	@Sender NVARCHAR(50),
	@SenderIbnUserId INT,
	@FirstName NVARCHAR(50),
	@LastName NVARCHAR(50),
	@Subject NVARCHAR(1024),
	@InnerText NTEXT,
	@Priority INT,
	@Pop3BoxId INT,
	@Received DATETIME,
	@Retval int out
AS
	SET NOCOUNT ON
	INSERT INTO [Pop3MailRequests]
	([Sender], [SenderIbnUserId], [FirstName], [LastName], [Subject], [InnerText], [Priority], [Pop3BoxId], [Received])
	VALUES
	(@Sender, @SenderIbnUserId, @FirstName, @LastName, @Subject, @InnerText, @Priority, @Pop3BoxId, @Received)
	SET @Retval = @@IDENTITY
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3MailRequestDelete
	@Pop3MailRequestId INT
AS
DECLARE @IssueRequestType int
SET @IssueRequestType = 12
DELETE SUBSCRIPTIONS WHERE ObjectId = @Pop3MailRequestId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @IssueRequestType)
DELETE FROM Pop3MailRequests WHERE Pop3MailRequestId = @Pop3MailRequestId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3MailRequestSetMhtFileId
	@Pop3MailRequestId INT,
	@MhtFileId INT
AS
	UPDATE Pop3MailRequests SET MhtFileId = @MhtFileId WHERE Pop3MailRequestId = @Pop3MailRequestId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3MailRequestsGet
	@Pop3MailRequestId as int,
	@Pop3BoxId as int,
	@LanguageId as int
as
SELECT R.Pop3MailRequestId, R.Sender, R.SenderIbnUserId, R.FirstName, R.LastName, R.Subject, R.InnerText, R.Priority, P.PriorityName,
	R.Pop3BoxId, R.Received, R.MhtFileId, B.[Name] AS Pop3BoxName,
	CASE
		WHEN EXISTS
		(
			SELECT * FROM USERS WHERE IsExternal = 1 AND
				(Email = R.Sender OR PrincipalId IN (SELECT UserId FROM EMAILS WHERE Email = R.Sender ))
		) THEN 1
		WHEN EXISTS
		(
			SELECT * FROM USERS WHERE IsExternal = 0 AND
				(Email = R.Sender OR PrincipalId IN (SELECT UserId FROM EMAILS WHERE Email = R.Sender ))
		) THEN 2
		ELSE 0
	END AS SenderType
  FROM Pop3MailRequests R
	JOIN PRIORITY_LANGUAGE P ON (R.Priority = P.PriorityId AND P.LanguageId = @LanguageId)
	JOIN POP3Boxes B ON (R.Pop3BoxId = B.Pop3BoxId)
  WHERE (@Pop3MailRequestId=0 OR R.Pop3MailRequestId = @Pop3MailRequestId)
	AND (@Pop3BoxId=0 OR R.Pop3BoxId = @Pop3BoxId)
  ORDER BY R.Received DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Pop3MailRequestUpdate
	@Pop3MailRequestId INT,
	@Subject NVARCHAR(1024),
	@InnerText NTEXT,
	@Priority INT
AS
	UPDATE Pop3MailRequests SET Subject = @Subject, InnerText = @InnerText, Priority = @Priority WHERE Pop3MailRequestId = @Pop3MailRequestId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].Portal_LoginsStatisticGet
	@UserId as int,
	@StartDate as datetime,
	@EndDate as datetime
AS
SELECT IP, CAST(LTRIM(STR(DATEPART(yy, LoginTime))) + '-' + LTRIM(STR(DATEPART(mm, LoginTime))) + '-' + LTRIM(STR(DATEPART(dd, LoginTime))) AS datetime) As LoginDate, Count(*) As LoginCount
FROM portal_logins
	Where (UserId  = @UserId)AND(LoginTime>=@StartDate)AND(LoginTime<=@EndDate)
  GROUP BY IP, CAST(LTRIM(STR(DATEPART(yy, LoginTime))) + '-' + LTRIM(STR(DATEPART(mm, LoginTime))) + '-' + LTRIM(STR(DATEPART(dd, LoginTime))) AS datetime)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PortalLoginAdd
	@UserId as int,
	@LoginTime as datetime,
	@IP as varchar(15)
AS
INSERT INTO Portal_Logins ( UserId, LoginTime, IP)
  VALUES (@UserId, @LoginTime, @IP)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PortalLoginCountGet
	@StartDate as datetime,
	@EndDate as datetime
AS
	Select Distinct(P.UserId), U.OriginalId From Portal_Logins AS P, Users AS U Where (LoginTime>=@StartDate)AND(LoginTime<=@EndDate)AND(P.UserId = U.PrincipalId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PrincipalDelete
       @PrincipalId as int
as
DELETE FROM PRINCIPALS WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PrincipalGet
	@PrincipalId as int
AS
SELECT  PrincipalId, IsGroup
FROM PRINCIPALS
WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PrincipalGetIsGroup
       @PrincipalId as int,
       @retval int out
AS
SELECT  @retval = p.IsGroup
FROM PRINCIPALS p
WHERE p.PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PrioritiesGet
	@LanguageId as int
as
SELECT PriorityId, PriorityName
  FROM PRIORITY_LANGUAGE
  WHERE @LanguageId = 0 OR LanguageId = @LanguageId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PriorityGetNames
	@PriorityId int
AS
SELECT LanguageId, PriorityName AS Name
  FROM PRIORITY_LANGUAGE
  WHERE PriorityId = @PriorityId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].PROCESS
AS
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProductVersionGet
AS
SELECT SERVERPROPERTY('productversion')
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].ProjectActivitiesGetCreators
	@ProjectId as int
as
Select PrincipalId As UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
	From USERS
	Where PrincipalId IN (SELECT CreatorId FROM TODO Where ProjectId=@ProjectId)
		OR PrincipalId IN (SELECT CreatorId FROM TASKS Where ProjectId=@ProjectId)
		OR PrincipalId IN (SELECT CreatorId FROM EVENTS Where ProjectId=@ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectActivitiesGetManagers
	@ProjectId as int
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT ManagerId FROM EVENTS Where ProjectId = @ProjectId)
	OR PrincipalId IN (SELECT ManagerId FROM TODO Where ProjectId = @ProjectId)
	OR PrincipalId IN (SELECT ManagerId FROM PROJECTS WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoriesGet
	@CategoryId as int
as
SELECT CategoryId, CategoryName
  FROM PROJECT_CATEGORIES
  WHERE CategoryId = @CategoryId or @CategoryId=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoriesGetByProject
	@ProjectId as int
as
SELECT CategoryId, CategoryName
  FROM PROJECT_CATEGORIES
  WHERE CategoryId  IN
	(SELECT CategoryId FROM PROJECT_CATEGORY WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoriesGetForDictionaries
as
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName,
	CASE WHEN
		EXISTS(SELECT * FROM PROJECT_CATEGORY P WHERE P.CategoryId = C.CategoryId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM PROJECT_CATEGORIES C
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoriesGetProjectStatisticForPMAndPPM
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT C.CategoryId, C.CategoryName, COUNT(*) AS [Count]
  FROM PROJECT_CATEGORIES C
	JOIN PROJECT_CATEGORY PC ON (C.CategoryId = PC.CategoryId)
  WHERE PC.ProjectId IN
	(SELECT ProjectId
	  FROM PROJECTS
	  WHERE @IsPPM_Exec = 1 OR ManagerId = @UserId
	)
  GROUP BY C.CategoryId, C.CategoryName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryAdd
	@CategoryName as nvarchar(100)
AS
INSERT INTO PROJECT_CATEGORIES (CategoryName) VALUES(@CategoryName)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryAssign
	@ProjectId as int ,
	@CategoryId as int
as
INSERT INTO PROJECT_CATEGORY (ProjectId, CategoryId)
  VALUES(@ProjectId, @CategoryId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryDelete
	@CategoryId as int
as
DELETE FROM PROJECT_CATEGORIES  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryRemove
	@ProjectId as int,
	@CategoryId as int
AS
DELETE FROM PROJECT_CATEGORY
  WHERE ProjectId = @ProjectId AND CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryUpdate
	@CategoryId as int ,
	@CategoryName as nvarchar(100)
as
UPDATE PROJECT_CATEGORIES SET CategoryName=@CategoryName
  WHERE CategoryId = @CategoryId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryUserAdd
	@CategoryId as int,
	@UserId as int
as
if NOT EXISTS(SELECT * FROM PROJECTCATEGORY_USER WHERE CategoryId = @CategoryId AND UserId = @UserId)
	INSERT INTO PROJECTCATEGORY_USER (CategoryId, UserId) VALUES(@CategoryId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryUserDelete
	@CategoryId as int,
	@UserId as int
as
DELETE FROM PROJECTCATEGORY_USER
  WHERE CategoryId = @CategoryId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCategoryUserGetList
	@UserId as int
as
SELECT CategoryId, UserId
  FROM PROJECTCATEGORY_USER
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectCreate
	@TypeId as int ,
	@StatusId as int ,
	@CalendarId as int ,
	@CreatorId as int ,
	@ManagerId as int ,
	@ExecutiveManagerId as int = null ,
	@Title as nvarchar(255) ,
	@Description as ntext,
	@CreationDate as datetime ,
	@TargetStartDate as datetime ,
	@TargetFinishDate as datetime ,
	@ActualStartDate as datetime = null,
	@ActualFinishDate as datetime = null,
	@Goals as ntext,
	@Scope as ntext,
	@Deliverables as ntext,
	@ClientId as int,
	@CurrencyId as int,
	@PriorityId as int,
	@InitialPhaseId as int,
	@PhaseId as int,
	@PercentCompleted as int,
	@RiskLevelId int,
	@retval int output
as
if @InitialPhaseId = 0
	set @InitialPhaseId = @PhaseId
INSERT INTO PROJECTS (FormId, CalendarId, CreatorId, ManagerId, ExecutiveManagerId, Title, [Description], CreationDate,
	TargetStartDate, TargetFinishDate, ActualStartDate, ActualFinishDate, Goals, Scope, Deliverables, StatusId, ClientId, CurrencyId, PriorityId,
	InitialPhaseId, PhaseId, PercentCompleted, RiskLevelId)
  VALUES(@TypeId, @CalendarId, @CreatorId, @ManagerId, @ExecutiveManagerId, @Title, @Description, @CreationDate,
	@TargetStartDate, @TargetFinishDate, @ActualStartDate, @ActualFinishDate, @Goals, @Scope, @Deliverables, @StatusId, @ClientId, @CurrencyId, @PriorityId,
	@InitialPhaseId, @PhaseId, @PercentCompleted, @RiskLevelId)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectDelete
	@ProjectId as int
as
DECLARE @ProjectObjectType int
SET @ProjectObjectType = 3
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @ProjectObjectType AND ObjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @ProjectObjectType AND ObjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @ProjectObjectType AND ObjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE PROJECT_MEMBERS WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_INCIDENTS WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_USERTIMESHEETS WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @ProjectObjectType AND ObjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE PROJECT_SNAPSHOTS WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE ACTUAL_FINANCES WHERE AccountId IN (SELECT AccountId FROM ACCOUNTS WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE ACCOUNTS WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @ProjectId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @ProjectObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId = @ProjectId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @ProjectObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId = @ProjectId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @ProjectObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId = @ProjectId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @ProjectObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE PROJECT_RELATIONS WHERE ProjectId = @ProjectId OR RelProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM PROJECTS  WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectExecutiveManagersGet
as
SELECT DISTINCT P.ExecutiveManagerId, U.LastName + ', ' + U.FirstName AS UserName
  FROM PROJECTS P
	JOIN USERS U ON P.ExecutiveManagerId = U.PrincipalId
  ORDER BY UserName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGet
	@ProjectId as int,
	@LanguageId as int
as
SELECT P.ProjectId, P.FormId AS TypeId, F.FormName AS TypeName, P.CalendarId, C.CalendarName, P.CreatorId, P.ManagerId, P.ExecutiveManagerId, P.Title, P.[Description],
	P.CreationDate, P.StartDate, P.FinishDate, P.TargetStartDate, P.TargetFinishDate, P.ActualStartDate, P.ActualFinishDate,
	P.FixedHours, P.FixedCost, P.Goals, P.Scope, P.Deliverables, P.StatusId , S.StatusName, P.ClientId, CL.ClientName, P.XMLFileId, P.CurrencyId,
	CU.CurrencySymbol, C.TimeZoneId, P.PriorityId, PR.PriorityName, P.PercentCompleted, P.PhaseId, PP.PhaseName, P.RiskLevelId, L.RiskLevelName,
	L.Weight AS RiskLevelWeight, P.InitialPhaseId, PP2.PhaseName AS InitialPhaseName
  FROM PROJECTS P
	JOIN CALENDARS C ON P.CalendarId = C.CalendarId
	JOIN OBJECT_FORMS F ON P.FormId = F.FormId
	JOIN PROJECT_STATUS_LANGUAGE S ON (P.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN CLIENTS CL ON (P.ClientId = CL.ClientId)
	JOIN CURRENCY CU ON (P.CurrencyId = CU.CurrencyId)
	JOIN PRIORITY_LANGUAGE PR ON (P.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
	JOIN PROJECT_PHASES PP2 ON (P.InitialPhaseId = PP2.PhaseId)
	JOIN RISK_LEVELS L ON P.RiskLevelId = L.RiskLevelId
  WHERE P.ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetCalendar
	@ProjectId as int,
	@retval int output
as
SELECT @retval = CalendarId
  FROM PROJECTS
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetCurrencySymbol
	@ProjectId as int
as
SELECT CurrencySymbol
  FROM Currency
  WHERE CurrencyId IN (SELECT CurrencyId FROM PROJECTS  WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetDateRange
			@ProjectId INT
 AS
	SELECT MIN(StartDate) AS StartDate, MAX(FinishDate) AS FinishDate FROM (
		SELECT StartDate, FinishDate FROM TODO  WHERE ProjectId = @ProjectId
			UNION ALL
		SELECT StartDate, FinishDate From TASKS  WHERE ProjectId = @ProjectId
			UNION ALL
		SELECT StartDate, FinishDate From  EVENTS  WHERE ProjectId = @ProjectId
							)  A
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetFirstLevelTasks
			@ProjectId INT
AS
SELECT TaskId,TaskNum FROM TASKS T WHERE ProjectId = @ProjectId  AND NOT EXISTS(SELECT * FROM TASK_LINKS TL  WHERE TL. SuccId = T.TaskId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[ProjectGetIdByFolder]
	@FolderId as int,
	@RetVal as int out
AS
	SELECT @RetVal = ProjectId FROM FOLDER_PROJECT WHERE FolderId = @FolderId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetMembers
	@ProjectId as int
as
SELECT PrincipalId, IsTeamMember, IsSponsor, IsStakeholder
  FROM PROJECT_MEMBERS
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetSecurityForUser
	@ProjectId as int,
	@UserId as int
as
SELECT ProjectId, PrincipalId, IsTeamMember, IsSponsor, IsStakeHolder, IsManager, IsExecutiveManager
   FROM PROJECT_SECURITY_ALL
  WHERE ProjectId = @ProjectId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetSponsors
	@ProjectId as int
as
SELECT PM.MemberId, PM.ProjectId, PM.PrincipalId, P.IsGroup
  FROM PROJECT_MEMBERS PM
	JOIN PRINCIPALS P ON (PM.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (PM.PrincipalId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (PM.PrincipalId = G.PrincipalId)
  WHERE PM.ProjectId = @ProjectId AND PM.IsSponsor = 1
ORDER BY P.IsGroup DESC, G.GroupName, U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetStakeholders
	@ProjectId as int
as
SELECT PM.MemberId, PM.ProjectId, PM.PrincipalId, P.IsGroup
  FROM PROJECT_MEMBERS PM
	JOIN PRINCIPALS P ON (PM.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (PM.PrincipalId = U.PrincipalId)
	LEFT JOIN GROUPS G ON (PM.PrincipalId = G.PrincipalId)
  WHERE PM.ProjectId = @ProjectId AND PM.IsStakeHolder = 1
ORDER BY P.IsGroup DESC, G.GroupName, U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].ProjectGetTaskInRecalculateOrder
			@ProjectId INT
AS
CREATE TABLE #TASKS_TEMP (
	[TaskId] [int] NOT NULL ,
	[ParentId] [int] NULL,
	[lev][int] NULL
)
CREATE  INDEX [IX_MSP_TASKS_t1] ON [dbo].[#TASKS_TEMP]([TaskId]) 	ON [PRIMARY]
CREATE  INDEX [IX_MSP_TASKS_t2] ON [dbo].[#TASKS_TEMP]([ParentId]) 	ON [PRIMARY]
CREATE  INDEX [IX_MSP_TASKS_t3] ON [dbo].[#TASKS_TEMP]([lev]) 		ON [PRIMARY]
INSERT INTO #TASKS_TEMP (TaskId, ParentId, lev) SELECT T1.TaskId , PT.TaskId As ParentId, T1.OutlineLevel - PT.OutlineLevel FROM TASKS T1 LEFT JOIN TASKS PT ON (PT.IsSummary = 1 AND  PT.ProjectId = @ProjectId  AND T1.OutlineNumber LIKE PT.OutlineNumber + '.%')
						    	WHERE T1.ProjectId = @ProjectId
DECLARE @Table TABLE(TID INT IDENTITY(1,1) PRIMARY KEY,  TaskId INT)
DECLARE @DoNext INT
SET @DoNext = 1
WHILE(@DoNext = 1)
BEGIN
INSERT INTO @Table (TaskId) SELECT  DISTINCT T1.TaskId FROM  #TASKS_TEMP T1
			    WHERE NOT EXISTS(SELECT T0.TaskId FROM @Table T0 WHERE T0.TaskId = T1.TaskId)
				  AND NOT EXISTS
	(SELECT T2.TaskId FROM
		(SELECT T3.TaskId FROM #TASKS_TEMP T3 WHERE T3.ParentId = T1.TaskId and t3.lev = 1
			UNION
		SELECT PredId FROM TASK_LINKS WHERE SuccId = T1.TaskId
			UNION
		SELECT PredId FROM TASK_LINKS WHERE EXISTS (SELECT T4.TaskId FROM #TASKS_TEMP T4 WHERE SuccId = T4.ParentId AND T1.TaskId = T4.TaskId)
		) T2
		WHERE NOT EXISTS(SELECT T00.TaskId FROM @Table T00 WHERE T00.TaskId = T2.TaskId)
	)
IF(@@ROWCOUNT = 0)
SET @DoNext = 0
END
SELECT TaskId FROM @Table  ORDER BY TID
DROP TABLE #TASKS_TEMP
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetTeamMemberNames
	@ProjectId as int
as
DECLARE @Active tinyint
DECLARE @Pending tinyint
SET @Active = 3
SET @Pending = 2
SELECT M.PrincipalId AS UserId, U.FirstName, U.LastName, U.Activity
  FROM PROJECT_MEMBERS M
	JOIN USERS U ON (M.PrincipalId = U.PrincipalId)
  WHERE M.ProjectId = @ProjectId AND M.IsTeamMember = 1
	AND (U.Activity = @Active OR U.Activity = @Pending)
ORDER BY U.LastName, U.FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetTeamMemberNamesWithManager
	@ProjectId as int
as
DECLARE @Active tinyint
DECLARE @Pending tinyint
SET @Active = 3
SET @Pending = 2
SELECT P.ManagerId AS UserId, U.FirstName, U.LastName
  FROM PROJECTS P
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
  WHERE P.ProjectId = @ProjectId
	AND (U.Activity = @Active OR U.Activity = @Pending)
UNION
SELECT M.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM PROJECT_MEMBERS M
	JOIN USERS U ON (M.PrincipalId = U.PrincipalId)
  WHERE M.ProjectId = @ProjectId AND M.IsTeamMember = 1
	AND (U.Activity = @Active OR U.Activity = @Pending)
ORDER BY U.LastName, U.FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetTeamMembers
	@ProjectId as int
as
SELECT M.MemberId, M.ProjectId, M.PrincipalId AS UserId, M.Code, M.Rate
  FROM PROJECT_MEMBERS M
	JOIN USERS U ON (M.PrincipalId = U.PrincipalId)
  WHERE M.ProjectId = @ProjectId AND M.IsTeamMember = 1
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGetTitle
	@ProjectId as int
as
SELECT Title FROM PROJECTS  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupAssign
		@ProjectId INT,
		@ProjectGroupId INT
AS
INSERT INTO [PROJECT_GROUP]([ProjectId], [ProjectGroupId])
VALUES(@ProjectId,@ProjectGroupId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupCreate
	@Title nvarchar(100),
	@Description ntext,
	@CreationDate datetime,
	@CreatorId int,
	@retval int output
AS
INSERT INTO [PROJECT_GROUPS]([Title], [Description], [CreationDate], [CreatorId])
VALUES(@Title, @Description,@CreationDate,@CreatorId)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupDelete
	@ProjectGroupId as int
AS
DELETE FROM PROJECT_GROUPS
  WHERE ProjectGroupId = @ProjectGroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupGet
	@ProjectGroupId INT
AS
SELECT ProjectGroupId, Title, [Description], CreationDate, CreatorId
  FROM PROJECT_GROUPS
  WHERE ProjectGroupId = @ProjectGroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupRemove
	@ProjectId as int,
	@ProjectGroupId as int
AS
DELETE FROM PROJECT_GROUP
  WHERE ProjectId = @ProjectId AND ProjectGroupId = @ProjectGroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM PROJECT_GROUPS WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupsGet
AS
SELECT ProjectGroupId, Title, [Description], CreationDate, CreatorId
  FROM PROJECT_GROUPS
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupsGetByProject
			@ProjectId int
AS
SELECT A.[ProjectGroupId], B.[Title] FROM [PROJECT_GROUP] A JOIN PROJECT_GROUPS B ON A.[ProjectGroupId] = B.[ProjectGroupId] WHERE A.[ProjectId] = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE PROJECT_GROUPS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupUpdate
	@ProjectGroupId int,
	@Title nvarchar(100),
	@Description ntext
AS
UPDATE [PROJECT_GROUPS]
SET [Title]= @Title, [Description]=@Description
WHERE [ProjectGroupId]= @ProjectGroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupUserAdd
	@ProjectGroupId as int,
	@UserId as int
as
if NOT EXISTS(SELECT * FROM PROJECTGROUP_USER WHERE ProjectGroupId = @ProjectGroupId AND UserId = @UserId)
	INSERT INTO PROJECTGROUP_USER (ProjectGroupId, UserId) VALUES(@ProjectGroupId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupUserDelete
	@ProjectGroupId as int,
	@UserId as int
as
DELETE FROM PROJECTGROUP_USER
  WHERE ProjectGroupId = @ProjectGroupId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectGroupUserGetList
	@UserId as int
as
SELECT ProjectGroupId, UserId
  FROM PROJECTGROUP_USER
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectManagerGet
	@ProjectId as int,
	@retval int output
as
SELECT @retval = ManagerId
  FROM PROJECTS
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectManagersGet
as
SELECT DISTINCT P.ManagerId, U.LastName + ', ' + U.FirstName AS UserName
  FROM PROJECTS P
	JOIN USERS U ON P.ManagerId = U.PrincipalId
  ORDER BY UserName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberAddMember
	@ProjectId as int ,
	@PrincipalId as int ,
	@Code as nchar(2) ,
	@Rate as money
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId)
	UPDATE PROJECT_MEMBERS
	  SET Code=@Code, Rate=@Rate, IsTeamMember=1
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	INSERT INTO PROJECT_MEMBERS (ProjectId, PrincipalId, Code, Rate, IsTeamMember)
	  VALUES(@ProjectId, @PrincipalId, @Code, @Rate, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberAddSponsor
	@ProjectId as int ,
	@PrincipalId as int
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId)
	UPDATE PROJECT_MEMBERS
	  SET IsSponsor = 1
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	INSERT INTO PROJECT_MEMBERS (ProjectId, PrincipalId, IsSponsor)
	  VALUES(@ProjectId, @PrincipalId, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberAddStakeholder
	@ProjectId as int ,
	@PrincipalId as int
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId)
	UPDATE PROJECT_MEMBERS
	  SET IsStakeholder = 1
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	INSERT INTO PROJECT_MEMBERS (ProjectId, PrincipalId, IsStakeholder)
	  VALUES(@ProjectId, @PrincipalId, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberDeleteMember
	@ProjectId as int ,
	@PrincipalId as int
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId AND (IsStakeHolder = 1 OR IsSponsor = 1))
	UPDATE PROJECT_MEMBERS
	  SET IsTeamMember = 0
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	DELETE FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberDeleteSponsor
	@ProjectId as int ,
	@PrincipalId as int
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId AND (IsStakeHolder = 1 OR IsTeamMember = 1))
	UPDATE PROJECT_MEMBERS
	  SET IsSponsor = 0
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	DELETE FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberDeleteStakeholder
	@ProjectId as int ,
	@PrincipalId as int
as
if EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId AND (IsSponsor = 1 OR IsTeamMember = 1))
	UPDATE PROJECT_MEMBERS
	  SET IsStakeholder = 0
	  WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
else
	DELETE FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMemberGetByCode
			@ProjectId INT,
			@RName nVarChar(250) = NULL,
			@Code nVarChar(250) = NULL,
			@RetVal INT OUTPUT
AS
IF EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND ((@Code IS NOT NULL AND @Code = Code) OR @RName = Code) AND IsTeamMember=1)
BEGIN
	SELECT TOP 1 @RetVal = PrincipalId FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND (@Code = Code OR @RName = Code) AND IsTeamMember=1
END
ELSE
BEGIN
	SELECT TOP 1 @RetVal = PM.PrincipalId FROM PROJECT_MEMBERS PM JOIN USERS U ON U.PrincipalId = PM.PrincipalId
		 WHERE PM.ProjectId = @ProjectId AND IsTeamMember=1
		 AND (FirstName = @Code OR LastName = @Code OR
		      FirstName + ' ' + LastName = @Code    OR
		      FirstName = @RName OR LastName = @RName OR
		      FirstName + ' ' + LastName = @RName)
END
IF @@ROWCOUNT = 0
	SET @RetVal = -1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectMetricsGet
as
DECLARE @ActiveProjects int, @OnHoldProjects int, @CompletedProjects int, @ProjectIncidents int, @ProjectFiles int,
	@TargetBudget int, @EstimatedBudget int, @ActualBudget int, @TotalMinutes int, @ActiveTasks int, @OpenIssues int
SELECT @ActiveProjects = COUNT(*)
  FROM PROJECTS P
	JOIN  PROJECT_STATUS PS ON (P.StatusId = PS.StatusId)
  WHERE PS.IsActive = 1
SELECT @OnHoldProjects = COUNT(*)
  FROM PROJECTS
  WHERE StatusId = 2
SELECT @CompletedProjects = COUNT(*)
  FROM PROJECTS
  WHERE StatusId = 3
SELECT @ProjectIncidents = COUNT(*)
  FROM INCIDENTS
  WHERE ProjectId IS NOT NULL
SELECT @TotalMinutes = SUM(TotalApproved)
  FROM WeekTimeSheet W
	JOIN TIMESHEETS T ON (W.WeekTimeSheetId = T.WeekTimeSheetId)
  WHERE W.ProjectId IS NOT NULL AND W.StatusId = 4
IF @TotalMinutes IS NULL
	SET @TotalMinutes = 0
SELECT @TargetBudget = SUM(TCur+TSub), @EstimatedBudget = SUM(ECur+ESub), @ActualBudget = SUM(ACur+ASub)
  FROM Accounts
  WHERE OutlineLevel=1
IF @TargetBudget IS NULL
BEGIN
	SET @TargetBudget = 0
	SET @EstimatedBudget = 0
	SET @ActualBudget = 0
END
SELECT @ActiveTasks = COUNT(*)
  FROM TASKS
  WHERE IsCompleted = 0 AND IsMilestone = 0 AND IsSummary = 0
SELECT @OpenIssues = COUNT(*)
  FROM INCIDENTS
  WHERE (StatusId = 1 OR StatusId = 2)
	AND ProjectId IS NOT NULL
SELECT @ActiveProjects AS ActiveProjects, @OnHoldProjects AS OnHoldProjects, @CompletedProjects AS CompletedProjects,
	@ProjectIncidents AS ProjectIncidents, @TotalMinutes AS TotalMinutes,
	@TargetBudget AS TargetBudget, @EstimatedBudget AS EstimatedBudget, @ActualBudget AS ActualBudget,
	@ActiveTasks AS ActiveTasks, @OpenIssues AS OpenIssues
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectPhaseAdd
	@PhaseName as nvarchar(50),
	@Weight int
AS
INSERT INTO PROJECT_PHASES (PhaseName, Weight) VALUES(@PhaseName, @Weight)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectPhaseDelete
	@PhaseId as int
as
DELETE FROM PROJECT_PHASES  WHERE PhaseId = @PhaseId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectPhasesGet
	@PhaseId as int
as
SELECT PhaseId, PhaseName, Weight
  FROM PROJECT_PHASES
  WHERE PhaseId = @PhaseId or @PhaseId = 0
  ORDER BY Weight
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectPhasesGetForDictionaries
as
DECLARE @Items int
SELECT @Items = COUNT(*) FROM PROJECT_PHASES
SELECT PP.PhaseId AS ItemId, PP.PhaseName AS ItemName, PP.Weight,
	CASE WHEN EXISTS(SELECT * FROM PROJECTS P WHERE P.PhaseId = PP.PhaseId) OR @Items = 1
	THEN 0 ELSE 1 END AS CanDelete
  FROM PROJECT_PHASES PP
  ORDER BY PP.Weight
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectPhaseUpdate
	@PhaseId as int ,
	@PhaseName as nvarchar(50) ,
	@Weight int
as
UPDATE PROJECT_PHASES SET PhaseName = @PhaseName, Weight = @Weight
  WHERE PhaseId = @PhaseId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectRelationDelete
	@ProjectId as int,
	@RelProjectId as int
AS
DELETE FROM PROJECT_RELATIONS
  WHERE (ProjectId = @ProjectId AND RelProjectId = @RelProjectId)
	OR (ProjectId = @RelProjectId AND RelProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectRelatonAdd
	@ProjectId as int ,
	@RelProjectId as int
AS
IF NOT EXISTS(SELECT * FROM PROJECT_RELATIONS WHERE (ProjectId = @ProjectId AND RelProjectId = @RelProjectId) OR (ProjectId = @RelProjectId AND RelProjectId = @ProjectId))
	INSERT INTO PROJECT_RELATIONS (ProjectId, RelProjectId) VALUES(@ProjectId, @RelProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectRelatonsGet
	@ProjectId as int,
	@UserId as int
AS
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT P.ProjectId, P.Title, P.ManagerId,
	CASE WHEN @IsPPM_Exec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1
		THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanView,
	CASE WHEN @IsPPM_Exec = 1 OR PS.IsManager = 1
		THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS CanViewSnapshot
  FROM PROJECTS P
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
  WHERE P.ProjectId IN (SELECT ProjectId FROM Project_Relations WHERE RelProjectId = @ProjectId)
	OR P.ProjectId IN (SELECT RelProjectId FROM Project_Relations WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM PROJECTS WHERE ManagerId = @UserId OR ExecutiveManagerId = @UserId)
	SET @Retval = 1
ELSE BEGIN
	IF EXISTS(SELECT * FROM PROJECT_MEMBERS WHERE PrincipalId = @UserId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM PROJECTS WHERE CreatorId = @UserId)
	OR EXISTS(SELECT * FROM PROJECT_SNAPSHOTS WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectSecurityGet
	@ProjectId int
AS
SELECT PrincipalId AS UserId
  FROM PROJECT_SECURITY_ALL
  WHERE ProjectId = @ProjectId
	AND (IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1 OR IsManager = 1 OR IsExecutiveManager = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].ProjectsGet
	@UserId as int,
	@LanguageId as int
as
DECLARE @ProjectTypeId int
SET @ProjectTypeId = 3
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT P.ProjectId, P.FormId AS TypeId, F.FormName AS TypeName, P.CalendarId, P.CreatorId, P.ManagerId, U.LastName + ', ' + U.FirstName AS ManagerName,
	P.ExecutiveManagerId, P.Title, P.[Description], P.PriorityId, PR.PriorityName, P.PercentCompleted, P.CreationDate, P.StartDate, P.FinishDate,
	P.TargetStartDate, P.TargetFinishDate, P.ActualStartDate, P.ActualFinishDate, P.FixedHours, P.FixedCost, P.Goals, P.Scope, P.Deliverables,
	P.StatusId, S.StatusName, P.PhaseId, PP.PhaseName, P.RiskLevelId, L.RiskLevelName, L.Weight AS RiskLevelWeight,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM PROJECTS P
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
	JOIN PROJECT_STATUS_LANGUAGE S ON (P.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
	JOIN OBJECT_FORMS F ON (P.FormId = F.FormId AND F.ObjectTypeId = @ProjectTypeId)
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
	JOIN PRIORITY_LANGUAGE PR ON (P.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
	JOIN RISK_LEVELS L ON (P.RiskLevelId = L.RiskLevelId)
  WHERE @IsPPM = 1 OR @IsExec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetActive
as
SELECT P.ProjectId, P.Title
  FROM PROJECTS P
	JOIN PROJECT_STATUS S ON (P.StatusId = S.StatusId)
  WHERE S.IsActive = 1
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetActiveByManager
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT P.ProjectId, P.Title
  FROM PROJECTS P
	JOIN PROJECT_STATUS S ON (P.StatusId = S.StatusId)
  WHERE S.IsActive = 1
	 AND (@IsPPM_Exec = 1 OR P.ManagerId = @UserId)
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetActiveByUser
	@UserId as int
as
DECLARE @PPM int, @Exec int
SET @PPM = 4
SET @Exec = 7
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = @PPM OR GroupId = @Exec))
	SELECT P.ProjectId, P.Title, P.ManagerId, P.CreationDate, P.TargetFinishDate
	  FROM PROJECTS P, PROJECT_STATUS S
	  WHERE P.StatusId = S.StatusId AND S.IsActive = 1
	  ORDER BY CreationDate DESC
ELSE
	SELECT P.ProjectId, P.Title, P.ManagerId, P.CreationDate, P.TargetFinishDate
	  FROM PROJECTS P, PROJECT_SECURITY_ALL PS, PROJECT_STATUS S
	  WHERE P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId
		AND P.StatusId = S.StatusId AND S.IsActive = 1
 		AND (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
	  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetActiveByUserOnly
	@UserId as int,
	@LanguageId as int
as
SELECT P.ProjectId, P.Title, P.ManagerId, P.StatusId, P.PercentCompleted, P.TargetStartDate, P.TargetFinishDate, P.PriorityId, PL.PriorityName,
	CAST (PS.IsManager as bit) AS IsManager,
	CAST(PS.IsExecutiveManager as bit) AS IsExecutiveManager,
	CAST(PS.IsTeamMember as bit) AS IsTeamMember,
	CAST(PS.IsSponsor as bit) AS IsSponsor,
	CAST(PS.IsStakeHolder as bit) AS IsStakeHolder
  FROM PROJECTS P, PROJECT_SECURITY_ALL PS, PROJECT_STATUS S, PRIORITY_LANGUAGE PL
  WHERE P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId
	AND P.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND P.StatusId = S.StatusId AND S.IsActive = 1
	AND (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetByCalendar
	@CalendarId as int
as
SELECT ProjectId FROM PROJECTS WHERE CalendarId = @CalendarId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetByFilter
	@UserId as int,
	@SearchString as nvarchar(100),
	@State as int,
	@StatusId as int,
	@FormId as int,
	@PriorityId as int,
	@ClientId as int,
	@StartDateCondition as int,
	@StartDate as datetime = null,
	@FinishDateCondition as int,
	@FinishDate as datetime = null,
	@ManagerId as int,
	@ExecutiveManagerId as int,
	@LanguageId as int,
	@CategoryType as int,
	@ProjectCategoryType as int,
	@ProjectGroupType as int,
	@PhaseId as int,
	@OnlyForUser bit = 0
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
DECLARE @ProjectType int
SET @ProjectType = 3
SET @SearchString = '%' + @SearchString + '%'
SELECT P.ProjectId, P.FormId AS TypeId, P.CalendarId, P.CreatorId, P.ManagerId, U.LastName + ', ' + U.FirstName AS ManagerName,
	P.ExecutiveManagerId, P.Title, P.[Description], P.PriorityId, PR.PriorityName, P.PercentCompleted,
	P.CreationDate, P.StartDate, P.FinishDate, P.TargetStartDate, P.TargetFinishDate, P.ActualStartDate, P.ActualFinishDate,
	P.StatusId, SL.StatusName, P.PhaseId, PP.PhaseName, PP.Weight AS PhaseWeight, P.RiskLevelId, L.RiskLevelName, L.Weight AS RiskLevelWeight,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanViewSnapShot
  FROM PROJECTS P
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId)
	JOIN PROJECT_STATUS S ON (P.StatusId = S.StatusId)
	JOIN PROJECT_STATUS_LANGUAGE SL ON (S.StatusId = SL.StatusId AND SL.LanguageId = @LanguageId)
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
	JOIN PRIORITY_LANGUAGE PR ON (P.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
	JOIN RISK_LEVELS L ON (P.RiskLevelId = L.RiskLevelId)
  WHERE (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1 OR
		(@OnlyForUser = 0 AND (@IsPPM = 1 OR @IsExec = 1 )))
	AND (@SearchString = '%%' OR P.Title LIKE @SearchString OR P.[Description] LIKE @SearchString OR CAST(P.ProjectId AS nvarchar(10)) LIKE @SearchString )
	AND (@State = 0 OR @State = 1 AND S.IsActive = 1 OR @State = 2 AND S.IsActive = 0)
	AND (@StatusId = 0 OR P.StatusId = @StatusId)
	AND (@FormId = 0 OR P.FormId = @FormId)
	AND (@PriorityId = -1 OR P.PriorityId = @PriorityId)
	AND (@ClientId = 0 OR P.ClientId = @ClientId)
	AND (@PhaseId = 0 OR P.PhaseId = @PhaseId)
	AND (@StartDateCondition = 0
		OR @StartDateCondition = 1 AND TargetStartDate >= @StartDate
		OR @StartDateCondition = 2 AND TargetStartDate < DATEADD(d, 1, @StartDate)
		OR @StartDateCondition = 3 AND TargetStartDate >= @StartDate AND TargetStartDate < DATEADD(d, 1, @StartDate))
	AND (@FinishDateCondition = 0
		OR @FinishDateCondition = 1 AND TargetFinishDate >= @FinishDate
		OR @FinishDateCondition = 2 AND TargetFinishDate < DATEADD(d, 1, @FinishDate)
		OR @FinishDateCondition = 3 AND TargetFinishDate >= @FinishDate AND TargetFinishDate < DATEADD(d, 1, @FinishDate))
	AND (@ManagerId = 0 OR ManagerId = @ManagerId)
	AND (@ExecutiveManagerId = 0 OR ExecutiveManagerId = @ExecutiveManagerId)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND P.ProjectId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @ProjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType = 2 AND P.ProjectId NOT IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @ProjectType
				AND CategoryId IN (SELECT CategoryId FROM CATEGORY_USER WHERE UserId = @UserId)
			)
		OR @CategoryType < 0 AND P.ProjectId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @ProjectType AND CategoryId = -@CategoryType
			)
	)
	AND (@ProjectCategoryType = 0
		OR @ProjectCategoryType = 1 AND P.ProjectId IN
			(SELECT ProjectId
			  FROM PROJECT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM PROJECTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @ProjectCategoryType = 2 AND P.ProjectId NOT IN
			(SELECT ProjectId
			  FROM PROJECT_CATEGORY
			  WHERE CategoryId IN (SELECT CategoryId FROM PROJECTCATEGORY_USER WHERE UserId = @UserId)
			)
		OR @ProjectCategoryType < 0 AND P.ProjectId IN
			(SELECT ProjectId
			  FROM PROJECT_CATEGORY
			  WHERE CategoryId = -@ProjectCategoryType
			)
	)
	AND (@ProjectGroupType = 0
		OR @ProjectGroupType = 1 AND P.ProjectId IN
			(SELECT ProjectId
			  FROM PROJECT_GROUP
			  WHERE ProjectGroupId IN (SELECT ProjectGroupId FROM PROJECTGROUP_USER WHERE UserId = @UserId)
			)
		OR @ProjectGroupType = 2 AND P.ProjectId NOT IN
			(SELECT ProjectId
			  FROM PROJECT_GROUP
			  WHERE ProjectGroupId IN (SELECT ProjectGroupId FROM PROJECTGROUP_USER WHERE UserId = @UserId)
			)
		OR @ProjectGroupType < 0 AND P.ProjectId IN
			(SELECT ProjectId
			  FROM PROJECT_GROUP
			  WHERE ProjectGroupId = -@ProjectGroupType
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetByManager
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT ProjectId, Title
  FROM PROJECTS
  WHERE ManagerId = @UserId OR @IsPPM_Exec = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetByUsersInGroup
	@GroupId as int,
	@LanguageId as int
as
DECLARE @Table TABLE (UserId int, UserName nvarchar(100), ProjectId int, Title nvarchar(255),
	PriorityId int, StatusId int, PhaseId int, IsTeamMember bit, IsSponsor bit, IsStakeHolder bit,
	IsManager bit, IsExecutiveManager bit)
INSERT INTO @Table (UserId, UserName, ProjectId, Title, PriorityId, StatusId, PhaseId, IsTeamMember, IsSponsor, IsStakeHolder, IsManager, IsExecutiveManager)
SELECT U.PrincipalId AS UserId, U.LastName + ' ' + U.FirstName AS UserName, P.ProjectId, P.Title,
	P.PriorityId, P.StatusId, P.PhaseId, PS.IsTeamMember, PS.IsSponsor, PS.IsStakeHolder,
	PS.IsManager, PS.IsExecutiveManager
  FROM Users U
	JOIN USER_GROUP UG ON (U.PrincipalId = UG.UserId)
	JOIN PROJECT_SECURITY_ALL PS ON (U.PrincipalId = PS.PrincipalId)
	JOIN PROJECTS P ON (PS.ProjectId = P.ProjectId)
  WHERE UG.GroupId = @GroupId
SELECT DISTINCT UserId, UserName, 0 AS ProjectId, '' AS Title, 0 AS PriorityId, '' AS PriorityName,
	0 AS StatusId, '' AS StatusName, 0 AS PhaseId, '' AS PhaseName, CAST(0 as bit) AS IsTeamMember,
	CAST(0 as bit) AS IsSponsor, CAST(0 as bit) AS IsStakeHolder, CAST(0 as bit) AS IsManager,
	CAST(0 as bit) AS IsExecutiveManager, CAST(1 as bit) AS IsGroup
  FROM @Table
UNION ALL
SELECT T.UserId, T.UserName, T.ProjectId, T.Title, T.PriorityId, PL.PriorityName,
	T.StatusId, SL.StatusName, T.PhaseId, PP.PhaseName, T.IsTeamMember,
	T.IsSponsor, T.IsStakeHolder, T.IsManager, T.IsExecutiveManager,
	CAST(0 as bit) AS IsGroup
  FROM @Table T
	JOIN PRIORITY_LANGUAGE PL ON (T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId)
	JOIN PROJECT_STATUS_LANGUAGE SL ON (T.StatusId = SL.StatusId AND SL.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (T.PhaseId = PP.PhaseId)
  ORDER BY UserName, IsGroup DESC, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 7)
	SET @IsExec = 1
SELECT P.ProjectId, P.Title, P.StatusId,
	CASE WHEN P.ManagerId = @UserId THEN 1 ELSE 0 END AS IsManager,
	CASE WHEN P.ExecutiveManagerId = @UserId THEN 1 ELSE 0 END AS IsExecutiveManagerId,
	CASE WHEN PM.IsTeamMember = 1 THEN 1 ELSE 0 END AS IsTeamMember,
	CASE WHEN PM.IsSponsor = 1 THEN 1 ELSE 0 END AS IsSponsor,
	CASE WHEN PM.IsStakeHolder = 1 THEN 1 ELSE 0 END AS IsStakeHolder,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR P.ProjectId IN
		(SELECT ProjectId FROM PROJECT_SECURITY_ALL WHERE PrincipalId = @CurrentUserId) THEN 1 ELSE 0 END AS CanView,
	CASE WHEN @IsPPM = 1 OR P.ManagerId = @CurrentUserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR P.ManagerId = @CurrentUserId THEN 1 ELSE 0 END AS CanDelete
  FROM PROJECTS P
	LEFT JOIN PROJECT_MEMBERS PM ON (P.ProjectId = PM.ProjectId AND PM.PrincipalId = @UserId)
  WHERE P.ManagerId = @UserId OR P.ExecutiveManagerId = @UserId OR PM.MemberId IS NOT NULL
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetForIncidents
as
SELECT ProjectId, Title
  FROM PROJECTS
  WHERE ProjectId IN (SELECT ProjectId FROM INCIDENTS)
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetForPMAndPPM
	@UserId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT P.ProjectId, P.FormId AS TypeId, P.CalendarId, P.CreatorId, P.ManagerId, U.LastName + ', ' + U.FirstName AS ManagerName,
	P.ExecutiveManagerId, P.Title, P.[Description], P.PercentCompleted,
	P.CreationDate, P.StartDate, P.FinishDate, P.TargetStartDate, P.TargetFinishDate, P.ActualStartDate, P.ActualFinishDate,
	P.FixedHours, P.FixedCost, P.Goals, P.Scope, P.Deliverables, P.StatusId, S.StatusName,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR PS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM PROJECTS P
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
	JOIN PROJECT_STATUS S ON (P.StatusId = S.StatusId)
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
  WHERE @IsPPM = 1 OR @IsExec = 1 OR PS.IsManager = 1
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetForUserOnly
	@UserId as int,
	@LanguageId as int,
	@CompletedDate as datetime = null,
	@StartingDate as datetime = null
as
SELECT P.ProjectId, P.Title, P.ManagerId, P.StatusId, S.StatusName, P.PercentCompleted, P.TargetStartDate, P.TargetFinishDate, P.PriorityId, PL.PriorityName,
	CAST (PS.IsManager as bit) AS IsManager,
	CAST(PS.IsExecutiveManager as bit) AS IsExecutiveManager,
	CAST(PS.IsTeamMember as bit) AS IsTeamMember,
	CAST(PS.IsSponsor as bit) AS IsSponsor,
	CAST(PS.IsStakeHolder as bit) AS IsStakeHolder
  FROM PROJECTS P, PROJECT_SECURITY_ALL PS, PROJECT_STATUS S, PRIORITY_LANGUAGE PL
  WHERE P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId
	AND P.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND P.StatusId = S.StatusId
	AND (
		S.StatusId = 1
		OR ( S.StatusId=3 AND (@CompletedDate is not null)AND(P.ActualFinishDate>=@CompletedDate) )
		OR ( S.StatusId=4 AND (@StartingDate is not null)AND(P.ActualStartDate<=@StartingDate) )
	)
	AND (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
  ORDER BY P.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetGroupedByManager
	@PortfolioId int,
	@PhaseId int,
	@StatusId int,
	@ManagerId int,
	@LanguageId int
AS
DECLARE @dummy TABLE (ManagerId int, ManagerName nvarchar(100), ProjectId int, ProjectName nvarchar(255),
	StatusName nvarchar(50), OpenTasks int, CompletedTasks int, Issues int, IsHeader bit)
INSERT INTO @dummy (ManagerId, ManagerName, ProjectId, ProjectName, StatusName, OpenTasks,
	CompletedTasks, Issues, IsHeader)
SELECT P.ManagerId, U.LastName + ' ' + U.FirstName AS ManagerName,
	P.ProjectId, P.Title AS ProjectName, PSL.StatusName,
	(SELECT COUNT(*) FROM TASKS T WHERE T.ProjectId = P.ProjectId AND T.IsCompleted = 0) +
	(SELECT COUNT(*) FROM TODO T WHERE T.ProjectId = P.ProjectId AND T.IsCompleted = 0) AS OpenTasks,
	(SELECT COUNT(*) FROM TASKS T WHERE T.ProjectId = P.ProjectId AND T.IsCompleted = 1) +
	(SELECT COUNT(*) FROM TODO T WHERE T.ProjectId = P.ProjectId AND T.IsCompleted = 1) AS CompletedTasks,
	(SELECT COUNT(*) FROM INCIDENTS I WHERE I.ProjectId = P.ProjectId) AS Issues,
	CAST(0 as bit) AS IsHeader
  FROM PROJECTS P
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
	JOIN PROJECT_STATUS_LANGUAGE PSL ON (P.StatusId = PSL.StatusId AND PSL.LanguageId = @LanguageId)
  WHERE (@PortfolioId = 0 OR P.ProjectId IN
		(SELECT ProjectId FROM PROJECT_GROUP WHERE ProjectGroupId = @PortfolioId))
	AND (@PhaseId = 0 OR P.PhaseId = @PhaseId)
	AND (@StatusId = 0 OR P.StatusId = @StatusId)
	AND (@ManagerId = 0 OR P.ManagerId = @ManagerId)
SELECT ManagerId, ManagerName, 0 AS ProjectId, '' AS ProjectName, '' AS StatusName,
	0 AS OpenTasks, 0 AS CompletedTasks, 0 AS Issues,
	CAST(1 as bit) AS IsHeader
  FROM
	(SELECT DISTINCT ManagerId, ManagerName
	  FROM @Dummy
	) PP
UNION ALL
SELECT ManagerId, ManagerName, ProjectId, ProjectName, StatusName, OpenTasks,
	CompletedTasks, Issues, IsHeader
  FROM @Dummy
  ORDER BY ManagerName, ProjectName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetGroupedByPhase
	@PortfolioId int,
	@PhaseId int,
	@StatusId int,
	@LanguageId int
AS
DECLARE @dummy TABLE (PhaseId int, PhaseName nvarchar(50), Weight int, ProjectId int,
	ProjectName nvarchar(255), StatusName nvarchar(50), Resources int, TasksTodos int,
	Issues int, ProjectsCount int, ActiveProjectsCount int, IsHeader bit)
INSERT INTO @dummy (PhaseId, PhaseName, Weight, ProjectId, ProjectName, StatusName, Resources,
	TasksTodos, Issues, ProjectsCount, ActiveProjectsCount, IsHeader)
SELECT P.PhaseId, PP.PhaseName, PP.Weight, P.ProjectId, P.Title AS ProjectName, PSL.StatusName,
	(SELECT COUNT(*) FROM PROJECT_MEMBERS PM WHERE PM.ProjectId = P.ProjectId AND IsTeamMember = 1) AS Resources,
	(SELECT COUNT(*) FROM TASKS T WHERE T.ProjectId = P.ProjectId) +
	(SELECT COUNT(*) FROM TODO T WHERE T.ProjectId = P.ProjectId) AS TasksTodos,
	(SELECT COUNT(*) FROM INCIDENTS I WHERE I.ProjectId = P.ProjectId) AS Issues,
	0 AS ProjectsCount, 0 AS ActiveProjectsCount,
	CAST(0 as bit) AS IsHeader
  FROM PROJECTS P
	JOIN PROJECT_STATUS_LANGUAGE PSL ON (P.StatusId = PSL.StatusId AND PSL.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
  WHERE (@PortfolioId = 0 OR P.ProjectId IN
		(SELECT ProjectId FROM PROJECT_GROUP WHERE ProjectGroupId = @PortfolioId))
	AND (@PhaseId = 0 OR P.PhaseId = @PhaseId)
	AND (@StatusId = 0 OR P.StatusId = @StatusId)
SELECT PhaseId, PhaseName, Weight, 0 AS ProjectId, '' AS ProjectName, '' AS StatusName, 0 AS Resources,
	0 AS TasksTodos, 0 AS Issues,
	(SELECT COUNT(*) FROM PROJECTS P WHERE P.PhaseId = PP.PhaseId) AS ProjectsCount,
	(SELECT COUNT(*) FROM PROJECTS P
			JOIN PROJECT_STATUS PS ON (P.StatusId = PS.StatusId)
		  WHERE P.PhaseId = PP.PhaseId AND PS.IsActive=1
		) AS ActiveProjectsCount,
	CAST(1 as bit) AS IsHeader
  FROM
	(SELECT DISTINCT PhaseId, PhaseName, Weight
	  FROM @Dummy
	) PP
UNION ALL
SELECT PhaseId, PhaseName, Weight, ProjectId, ProjectName, StatusName, Resources,
	TasksTodos, Issues, ProjectsCount, ActiveProjectsCount, IsHeader
  FROM @Dummy
  ORDER BY Weight DESC, PhaseName, ProjectName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetGroupedByPortfolio
	@PortfolioId int,
	@PhaseId int,
	@StatusId int,
	@LanguageId int
AS
DECLARE @dummy TABLE (PortfolioId int, PortfolioName nvarchar(100), ProjectId int,
	ProjectName nvarchar(255), StatusName nvarchar(50), Resources int, TasksTodos int,
	Issues int, PhaseName nvarchar(50), ProjectsCount int, ActiveProjectsCount int, IsHeader bit)
INSERT INTO @dummy (PortfolioId, PortfolioName, ProjectId, ProjectName, StatusName, Resources,
	TasksTodos, Issues, PhaseName, ProjectsCount, ActiveProjectsCount, IsHeader)
SELECT G.ProjectGroupId AS PortfolioId, G.Title AS PortfolioName,
	P.ProjectId, P.Title AS ProjectName, PSL.StatusName,
	(SELECT COUNT(*) FROM PROJECT_MEMBERS PM WHERE PM.ProjectId = P.ProjectId AND IsTeamMember = 1) AS Resources,
	(SELECT COUNT(*) FROM TASKS T WHERE T.ProjectId = P.ProjectId) +
	(SELECT COUNT(*) FROM TODO T WHERE T.ProjectId = P.ProjectId) AS TasksTodos,
	(SELECT COUNT(*) FROM INCIDENTS I WHERE I.ProjectId = P.ProjectId) AS Issues,
	PP.PhaseName, 0 AS ProjectsCount, 0 AS ActiveProjectsCount,
	CAST(0 as bit) AS IsHeader
  FROM PROJECTS P
	JOIN PROJECT_STATUS_LANGUAGE PSL ON (P.StatusId = PSL.StatusId AND PSL.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
	JOIN PROJECT_GROUP PG ON (P.ProjectId = PG.ProjectId)
	JOIN PROJECT_GROUPS G ON (PG.ProjectGroupId = G.ProjectGroupId)
  WHERE (@PortfolioId = 0 OR PG.ProjectGroupId = @PortfolioId)
	AND (@PhaseId = 0 OR P.PhaseId = @PhaseId)
	AND (@StatusId = 0 OR P.StatusId = @StatusId)
SELECT PortfolioId, PortfolioName, 0 AS ProjectId, '' AS ProjectName, '' AS StatusName, 0 AS Resources,
	0 AS TasksTodos, 0 AS Issues, '' AS PhaseName,
	(SELECT COUNT(*) FROM PROJECT_GROUP PG WHERE PG.ProjectGroupId = G.PortfolioId) AS ProjectsCount,
	(SELECT COUNT(*) FROM PROJECT_GROUP PG
			JOIN PROJECTS P ON (PG.ProjectId = P.ProjectId)
			JOIN PROJECT_STATUS PS ON (P.StatusId = PS.StatusId)
		  WHERE PG.ProjectGroupId = G.PortfolioId AND PS.IsActive=1
	) AS ActiveProjectsCount,
	CAST(1 as bit) AS IsHeader
  FROM
	(SELECT DISTINCT PortfolioId, PortfolioName
	  FROM @Dummy
	) G
UNION ALL
SELECT PortfolioId, PortfolioName, ProjectId, ProjectName, StatusName, Resources,
	TasksTodos, Issues, PhaseName, ProjectsCount, ActiveProjectsCount, IsHeader
  FROM @Dummy
  ORDER BY PortfolioName, ProjectName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetSimple
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT P.ProjectId, P.Title
  FROM PROJECTS P
	LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
  WHERE @IsPPM_Exec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatistic
as
DECLARE @ProjectCount int
SELECT @ProjectCount = COUNT(*)
  FROM PROJECTS
SELECT @ProjectCount AS ProjectCount
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByClient
as
SELECT C.ClientId AS ItemId, C.ClientName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN CLIENTS C ON (P.ClientId = C.ClientId)
  GROUP BY C.ClientId, C.ClientName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByGeneralCategory
as
DECLARE @ProjectType int
SET @ProjectType = 3
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName, COUNT(*) AS [Count]
  FROM CATEGORIES C
	JOIN OBJECT_CATEGORY OC ON (C.CategoryId = OC.CategoryId AND ObjectTypeId = @ProjectType)
	JOIN PROJECTS P ON (OC.ObjectId = P.ProjectId)
  GROUP BY C.CategoryId, C.CategoryName
  ORDER BY C.CategoryName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByManager
as
SELECT P.ManagerId AS ItemId, U.LastName + ', ' + U.FirstName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN USERS U ON (P.ManagerId = U.PrincipalId)
  GROUP BY P.ManagerId, U.LastName + ', ' + U.FirstName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByPhase
as
SELECT PP.PhaseId AS ItemId, PP.PhaseName AS ItemName, COUNT(*) AS [Count], PP.Weight
  FROM PROJECTS P
	JOIN PROJECT_PHASES PP ON (P.PhaseId = PP.PhaseId)
  GROUP BY PP.PhaseId, PP.PhaseName, PP.Weight
  ORDER BY PP.Weight DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByPriority
	@LanguageId as int
as
SELECT PR.PriorityId AS ItemId, PR.PriorityName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN PRIORITY_LANGUAGE PR ON (P.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
  GROUP BY PR.PriorityId, PR.PriorityName
  ORDER BY ItemId DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByProjectCategory
as
SELECT C.CategoryId AS ItemId, C.CategoryName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN PROJECT_CATEGORY PC ON (P.ProjectId = PC.ProjectId)
	JOIN PROJECT_CATEGORIES C ON (PC.CategoryId = C.CategoryId)
  GROUP BY C.CategoryId, C.CategoryName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByProjectGroup
as
SELECT G.ProjectGroupId AS ItemId, G.Title AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN PROJECT_GROUP PG ON (P.ProjectId = PG.ProjectId)
	JOIN PROJECT_GROUPS G ON (PG.ProjectGroupId = G.ProjectGroupId)
  GROUP BY G.ProjectGroupId, G.Title
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByStatus
	@LanguageId as int
as
SELECT S.StatusId AS ItemId, S.StatusName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN PROJECT_STATUS_LANGUAGE S ON (P.StatusId = S.StatusId AND S.LanguageId = @LanguageId)
  GROUP BY S.StatusId, S.StatusName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetStatisticByType
as
DECLARE @ProjectType int
SET @ProjectType = 3
SELECT P.FormId AS ItemId, F.FormName AS ItemName, COUNT(*) AS [Count]
  FROM PROJECTS P
	JOIN OBJECT_FORMS F ON (P.FormId = F.FormId AND F.ObjectTypeId = @ProjectType)
  GROUP BY P.FormId, F.FormName
  ORDER BY ItemName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetUpdatedByUser
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @ProjectObjectType int
SET @ProjectObjectType = 3
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT P.ProjectId, P.Title, P.StatusId, A.LastSavedDate
  FROM PROJECTS P,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @ProjectObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE P.ProjectId = A.ObjectId
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
  ORDER BY A.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetUpdatedForUser
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
DECLARE @ProjectObjectType int
SET @ProjectObjectType = 3
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT ProjectId, Title, LastEditorId, LastSavedDate, StatusId
FROM
(
	SELECT P.ProjectId, P.Title, P.StatusId, SE.UserId AS LastEditorId, SE.Dt AS LastSavedDate
	  FROM PROJECTS P
		JOIN SYSTEM_EVENTS SE ON (P.ProjectId = SE.ObjectId)
		LEFT JOIN PROJECT_SECURITY_ALL PS ON (P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId )
	  WHERE (@IsPPM_Exec = 1 OR PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @ProjectObjectType
			  GROUP BY E.ObjectId)
) A
  WHERE DATEDIFF(dd, DATEADD(mi, @TimeOffset, LastSavedDate) , @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsGetWithTimeSheets
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT ProjectId, Title
  FROM PROJECTS
  WHERE
	ProjectId IN (SELECT ProjectId FROM WeekTimeSheet)
	and (@IsPPM_Exec = 1 OR ManagerId = @UserId)
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectSnapshotAdd
	@ProjectId as int ,
	@CreatorId as int
as
DECLARE @StatusId int, @TargetBudget money, @EstimatedBudget money, @ActualBudget money, @StartDate datetime, @FinishDate datetime, @TargetFinishDate datetime, @PhaseId as int
SELECT @StatusId = StatusId, @StartDate = StartDate, @FinishDate = FinishDate, @TargetFinishDate = TargetFinishDate, @PhaseId = PhaseId
  FROM PROJECTS
  WHERE ProjectId = @ProjectId
SELECT @TargetBudget = TCur + TSub, @EstimatedBudget = ECur + ESub, @ActualBudget = ACur + ASub
  FROM ACCOUNTS
  WHERE ProjectId = @ProjectId AND OutlineLevel = 1
INSERT INTO PROJECT_SNAPSHOTS (ProjectId, StatusId, TargetBudget, EstimatedBudget, ActualBudget, StartDate, FinishDate, TargetFinishDate, CreatorId, CreationDate, PhaseId)
  VALUES(@ProjectId, @StatusId, @TargetBudget, @EstimatedBudget, @ActualBudget, @StartDate, @FinishDate, @TargetFinishDate, @CreatorId, getutcdate(), @PhaseId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectSnapshotDelete
	@SnapshotId as int
as
DELETE FROM PROJECT_SNAPSHOTS  WHERE SnapshotId = @SnapshotId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectSnapshotGetList
	@ProjectId as int,
	@LanguageId int
as
SELECT P.SnapshotId, P.ProjectId, P.StatusId, L.StatusName, P.TargetBudget, P.EstimatedBudget, P.ActualBudget,
	P.StartDate, P.FinishDate, P.TargetFinishDate, P.CreatorId, P.CreationDate,	P.PhaseId, F.PhaseName
  FROM PROJECT_SNAPSHOTS  P
	JOIN PROJECT_STATUS_LANGUAGE L ON (P.StatusId = L.StatusId AND L.LanguageId = @LanguageId)
	JOIN PROJECT_PHASES F ON P.PhaseId = F.PhaseId
  WHERE ProjectId = @ProjectId
  ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
BEGIN TRAN
	UPDATE PROJECTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE PROJECT_SNAPSHOTS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectsReplaceUnchangeableUserToManager
	@UserId as int
as
BEGIN TRAN
	UPDATE PROJECTS SET CreatorId = ManagerId WHERE CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE PROJECT_SNAPSHOTS
	    SET CreatorId = P.ManagerId
	    FROM PROJECT_SNAPSHOTS S, PROJECTS P
	    WHERE S.ProjectId = P.ProjectId AND S.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectStatusGet
	@LanguageId as int
as
SELECT S.StatusId, SL.StatusName, S.IsActive
  FROM PROJECT_STATUS S
	JOIN PROJECT_STATUS_LANGUAGE SL ON (S.StatusId = SL.StatusId AND SL.LanguageId = @LanguageId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectStatusGetNames
	@StatusId int
AS
SELECT LanguageId, StatusName AS Name
  FROM PROJECT_STATUS_LANGUAGE
  WHERE StatusId = @StatusId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTaskCheckConsistency
			@ProjectId INT,
			@retval INT OUTPUT
AS
SET @retval = 0
CREATE TABLE #TASKS_TEMP (
	[TaskId] [int] NOT NULL ,
	[ParentId] [int] NULL,
	[lev][int] NULL
)
CREATE  INDEX [IX_MSP_TASKS_t1] ON [dbo].[#TASKS_TEMP]([TaskId]) 	ON [PRIMARY]
CREATE  INDEX [IX_MSP_TASKS_t2] ON [dbo].[#TASKS_TEMP]([ParentId]) 	ON [PRIMARY]
CREATE  INDEX [IX_MSP_TASKS_t3] ON [dbo].[#TASKS_TEMP]([lev]) 		ON [PRIMARY]
INSERT INTO #TASKS_TEMP (TaskId, ParentId, lev) SELECT T1.TaskId , PT.TaskId As ParentId, T1.OutlineLevel - PT.OutlineLevel FROM TASKS T1 LEFT JOIN TASKS PT ON (PT.IsSummary = 1 AND  PT.ProjectId = @ProjectId  AND T1.OutlineNumber LIKE PT.OutlineNumber + '.%')
						    	WHERE T1.ProjectId = @ProjectId
DECLARE @Table TABLE(TID INT IDENTITY(1,1) PRIMARY KEY,  TaskId INT)
DECLARE @DoNext INT
SET @DoNext = 1
WHILE(@DoNext = 1)
BEGIN
INSERT INTO @Table (TaskId) SELECT  DISTINCT T1.TaskId FROM  #TASKS_TEMP T1
			    WHERE NOT EXISTS(SELECT T0.TaskId FROM @Table T0 WHERE T0.TaskId = T1.TaskId)
				  AND NOT EXISTS
	(SELECT T2.TaskId FROM
		(SELECT T3.TaskId FROM #TASKS_TEMP T3 WHERE T3.ParentId = T1.TaskId and t3.lev = 1
			UNION
		SELECT PredId FROM TASK_LINKS WHERE SuccId = T1.TaskId
			UNION
		SELECT PredId FROM TASK_LINKS WHERE EXISTS (SELECT T4.TaskId FROM #TASKS_TEMP T4 WHERE SuccId = T4.ParentId AND T1.TaskId = T4.TaskId)
		) T2
		WHERE NOT EXISTS(SELECT T00.TaskId FROM @Table T00 WHERE T00.TaskId = T2.TaskId)
	)
IF(@@ROWCOUNT = 0)
SET @DoNext = 0
END
DECLARE @AllTaskCount INT
DECLARE @CheckTaskCount INT
SELECT @AllTaskCount = COUNT(*) FROM Tasks WHERE ProjectId = @ProjectId
SELECT @CheckTaskCount = COUNT(*) FROM @Table
DROP TABLE #TASKS_TEMP
IF(@AllTaskCount = @CheckTaskCount)
	SET @retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplateAdd
	@TemplateName as nvarchar(255) ,
	@CreatorId as int ,
	@CreationDate as datetime ,
	@TemplateData as ntext ,
	@retval int output
as
INSERT INTO PROJECT_TEMPLATES (TemplateName, CreatorId, CreationDate, LastEditorId, LastSavedDate, TemplateData)
  VALUES(@TemplateName, @CreatorId, @CreationDate, @CreatorId, @CreationDate, @TemplateData)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplateDelete
	@TemplateId as int
as
DELETE FROM PROJECT_TEMPLATES  WHERE TemplateId = @TemplateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplateGet
	@TemplateId as int
as
SELECT TemplateId, TemplateName, CreatorId, LastEditorId, CreationDate, LastSavedDate, TemplateData
  FROM PROJECT_TEMPLATES
  WHERE TemplateId = @TemplateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplateGetList
as
SELECT TemplateId, TemplateName, CreatorId, LastEditorId, CreationDate, LastSavedDate, TemplateData
  FROM PROJECT_TEMPLATES
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplatesCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM PROJECT_TEMPLATES WHERE CreatorId = @UserId OR LastEditorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplatesReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE PROJECT_TEMPLATES SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
UPDATE PROJECT_TEMPLATES SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTemplateUpdate
	@TemplateId as int ,
	@TemplateName as nvarchar(255) ,
	@LastEditorId as int ,
	@LastSavedDate as datetime ,
	@TemplateData as ntext
as
UPDATE PROJECT_TEMPLATES
  SET TemplateName=@TemplateName, LastEditorId=@LastEditorId, LastSavedDate=@LastSavedDate, TemplateData=@TemplateData
  WHERE TemplateId = @TemplateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTypeAdd
	@TypeName as nvarchar(50),
	@retval int output
as
DECLARE @ProjectTypeId int
SET @ProjectTypeId = 3
INSERT INTO OBJECT_FORMS (ObjectTypeId, FormName) VALUES(@ProjectTypeId, @TypeName)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTypeDelete
	@TypeId as int
as
DECLARE @ObjectTypeId int
SELECT @ObjectTypeId = ObjectTypeId FROM OBJECT_FORMS WHERE FormId = @TypeId
DECLARE @RowCount int
SELECT @RowCount = COUNT(*)  FROM OBJECT_FORMS WHERE ObjectTypeId = @ObjectTypeId
IF @RowCount > 1
	DELETE FROM OBJECT_FORMS  WHERE FormId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTypesGet
as
SELECT FormId AS TypeId, FormName AS TypeName
  FROM OBJECT_FORMS
  WHERE ObjectTypeId = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTypesGetForDictionaries
as
DECLARE @rows int
SELECT @rows = COUNT(*) FROM OBJECT_FORMS
SELECT F.FormId AS ItemId, F.FormName AS ItemName,
	CASE WHEN @rows = 1 OR EXISTS(SELECT * FROM PROJECTS P WHERE P.FormId = F.FormId)
	THEN 0 ELSE 1 END AS CanDelete
  FROM OBJECT_FORMS F
  WHERE ObjectTypeId = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectTypeUpdate
	@TypeId as int ,
	@TypeName as nvarchar(50)
as
UPDATE OBJECT_FORMS
 SET FormName=@TypeName WHERE FormId = @TypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUpdateDates
	@ProjectId as int,
	@StartDate as datetime = null,
	@FinishDate as datetime = null
as
UPDATE PROJECTS SET StartDate = @StartDate, FinishDate = @FinishDate
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUpdateManagerAtAssociatedObjects
	@ProjectId as int,
	@ManagerId as int
as
BEGIN TRAN
	UPDATE TODO SET ManagerId = @ManagerId WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	UPDATE EVENTS SET ManagerId = @ManagerId WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	UPDATE INCIDENTS SET ManagerId = @ManagerId WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	UPDATE DOCUMENTS SET ManagerId = @ManagerId WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUpdateTargetDates
	@ProjectId as int,
	@TargetStartDate as datetime ,
	@TargetFinishDate as datetime
as
UPDATE PROJECTS SET TargetStartDate = @TargetStartDate, TargetFinishDate = @TargetFinishDate
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUserGanttDateLengthGet
	@ProjectId as int,
	@UserId as int
as
SELECT GanttDateLength FROM PROJECT_USER_DATE WHERE (ProjectId = @ProjectId AND UserId = @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUserGanttDateLengthSet
	@ProjectId as int,
	@UserId as int,
	@DateLength as int
as
if NOT EXISTS(SELECT * FROM PROJECT_USER_DATE WHERE ProjectId = @ProjectId AND UserId = @UserId)
	INSERT INTO PROJECT_USER_DATE (ProjectId, UserId, GanttDateLength) VALUES(@ProjectId, @UserId, @DateLength)
else
	Update PROJECT_USER_DATE
		set GanttDateLength = @DateLength WHERE (ProjectId = @ProjectId AND UserId = @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUserGanttStartDateGet
	@ProjectId as int,
	@UserId as int
as
SELECT GanttStartDate FROM PROJECT_USER_DATE WHERE (ProjectId = @ProjectId AND UserId = @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjectUserGanttStartDateSet
	@ProjectId as int,
	@UserId as int,
	@StartDate as datetime
as
if NOT EXISTS(SELECT * FROM PROJECT_USER_DATE WHERE ProjectId = @ProjectId AND UserId = @UserId)
	INSERT INTO PROJECT_USER_DATE (ProjectId, UserId, GanttStartDate) VALUES(@ProjectId, @UserId, @StartDate)
else
	Update PROJECT_USER_DATE
		set GanttStartDate = @StartDate WHERE (ProjectId = @ProjectId AND UserId = @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ProjecUpdateXMLFileId
	@ProjectId as int,
	@XMLFileId as int
as
UPDATE PROJECTS
  SET XMLFileId = @XMLFileId
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[RebuildForeignContainerKeys]
AS
BEGIN TRAN
DELETE FROM fsc_ForeignContainerKeys
INSERT INTO fsc_ForeignContainerKeys (ContainerKey, ForeignContainerKey)
(
SELECT
	(N'EventId_' + CAST(E.EventId AS NVARCHAR(10))) AS ContainerKey,
	(N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10))) AS ForeignContainerKey
FROM
	EVENTS E
JOIN PROJECTS P ON E.ProjectId = P.ProjectId
UNION ALL
SELECT
	(N'DocumentId_' + CAST(D.DocumentId AS NVARCHAR(10))) AS ContainerKey,
	(N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10))) AS ForeignContainerKey
FROM
	DOCUMENTS D
JOIN PROJECTS P ON D.ProjectId = P.ProjectId
UNION ALL
SELECT
	(N'IncidentId_' + CAST(I.IncidentId AS NVARCHAR(10))) AS ContainerKey,
	(N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10))) AS ForeignContainerKey
FROM
	INCIDENTS I
JOIN PROJECTS P ON I.ProjectId = P.ProjectId
UNION ALL
SELECT
	(N'ToDoId_' + CAST(T.ToDoId AS NVARCHAR(10))) AS ContainerKey,
	(N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10))) AS ForeignContainerKey
FROM
	TODO T
JOIN PROJECTS P ON T.ProjectId = P.ProjectId
WHERE
	T.ToDoId NOT IN (SELECT ToDoId FROM INCIDENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM DOCUMENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM TASK_TODO)
UNION ALL
SELECT
	(N'TaskId_' + CAST(T.TaskId AS NVARCHAR(10))) AS ContainerKey,
	(N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10))) AS ForeignContainerKey
FROM
	TASKS T
JOIN PROJECTS P ON T.ProjectId = P.ProjectId
)
COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[RebuildUserRoles]
AS
BEGIN TRAN
DELETE FROM fsc_UserRoles
INSERT INTO fsc_UserRoles (PrincipalId, ContainerKey, Role)
(
SELECT U.PrincipalId as PrincipalId, NULL as ContainerKey, N'Admin' as Role FROM USERS U
JOIN USER_GROUP UG ON U.PrincipalId = UG.UserId
WHERE
	UG.GroupId = 2
UNION ALL
SELECT U.PrincipalId as PrincipalId, NULL as ContainerKey, N'GlobalPM' as Role FROM USERS U
JOIN USER_GROUP UG ON U.PrincipalId = UG.UserId
WHERE
	UG.GroupId = 3
UNION ALL
SELECT U.PrincipalId as PrincipalId, NULL as ContainerKey, N'PPM' as Role FROM USERS U
JOIN USER_GROUP UG ON U.PrincipalId = UG.UserId
WHERE
	UG.GroupId = 4
UNION ALL
SELECT U.PrincipalId as PrincipalId, NULL as ContainerKey, N'HDM' as Role FROM USERS U
JOIN USER_GROUP UG ON U.PrincipalId = UG.UserId
WHERE
	UG.GroupId = 5
UNION ALL
SELECT U.PrincipalId as PrincipalId, NULL as ContainerKey, N'GlobalEM' as Role FROM USERS U
JOIN USER_GROUP UG ON U.PrincipalId = UG.UserId
WHERE
	UG.GroupId = 7
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10)) ) as ContainerKey, N'PM' as Role FROM USERS U
JOIN PROJECTS P ON P.ManagerId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ProjectId_' + CAST(P.ProjectId AS NVARCHAR(10)) ) as ContainerKey, N'EM' as Role FROM USERS U
JOIN PROJECTS P ON P.ExecutiveManagerId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ProjectId_' + CAST(PM.ProjectId AS NVARCHAR(10)) ) as ContainerKey, N'PTeam' as Role FROM USERS U
JOIN PROJECT_MEMBERS PM ON PM.PrincipalId = U.PrincipalId
WHERE PM.IsTeamMember = 1
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ProjectId_' + CAST(PM.ProjectId AS NVARCHAR(10)) ) as ContainerKey, N'PSponsor' as Role FROM USERS U
JOIN PROJECT_MEMBERS PM ON PM.PrincipalId = U.PrincipalId
WHERE PM.IsSponsor = 1
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ProjectId_' + CAST(PM.ProjectId AS NVARCHAR(10)) ) as ContainerKey, N'PStakeholder' as Role FROM USERS U
JOIN PROJECT_MEMBERS PM ON PM.PrincipalId = U.PrincipalId
WHERE PM.IsStakeholder = 1
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'IncidentId_' + CAST(I.IncidentId AS NVARCHAR(10)) ) as ContainerKey, N'ICreator' as Role FROM USERS U
JOIN INCIDENTS I ON I.CreatorId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'IncidentId_' + CAST(I.IncidentId AS NVARCHAR(10)) ) as ContainerKey, N'IManager' as Role FROM USERS U
JOIN INCIDENTS I ON I.ManagerId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'IncidentId_' + CAST(IR.IncidentId AS NVARCHAR(10)) ) as ContainerKey, N'IManager' as Role FROM USERS U
JOIN INCIDENT_RESOURCES IR ON IR.PrincipalId = U.PrincipalId
WHERE IR.CanManage = 1
	AND
      U.PrincipalId NOT IN (SELECT II.ManagerId FROM INCIDENTS II WHERE II.IncidentId = IR.IncidentId)
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'IncidentId_' + CAST(IR.IncidentId AS NVARCHAR(10)) ) as ContainerKey, N'IResource' as Role FROM USERS U
JOIN INCIDENT_RESOURCES IR ON IR.PrincipalId = U.PrincipalId
WHERE IR.CanManage = 0
UNION ALL
SELECT DISTINCT U.PrincipalId as PrincipalId, (N'IncidentId_' + CAST(IT.IncidentId AS NVARCHAR(10)) ) as ContainerKey, N'ITodoResource' as Role FROM USERS U
JOIN TODO_RESOURCES TR ON TR.PrincipalId = U.PrincipalId
JOIN INCIDENT_TODO IT ON IT.ToDoId = TR.ToDoId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'TaskId_' + CAST(T.TaskId AS NVARCHAR(10)) ) as ContainerKey, N'TCreator' as Role FROM USERS U
JOIN TASKS T ON T.CreatorId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'TaskId_' + CAST(TR.TaskId AS NVARCHAR(10)) ) as ContainerKey, N'TManager' as Role FROM USERS U
JOIN TASK_RESOURCES TR ON TR.PrincipalId = U.PrincipalId
WHERE TR.CanManage = 1
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'TaskId_' + CAST(TR.TaskId AS NVARCHAR(10)) ) as ContainerKey, N'TResource' as Role FROM USERS U
JOIN TASK_RESOURCES TR ON TR.PrincipalId = U.PrincipalId
WHERE TR.CanManage = 0
UNION ALL
SELECT DISTINCT  U.PrincipalId as PrincipalId, (N'TaskId_' + CAST(TT.TaskId AS NVARCHAR(10)) ) as ContainerKey, N'TTodoResource' as Role FROM USERS U
JOIN TODO_RESOURCES TR ON TR.PrincipalId = U.PrincipalId
JOIN TASK_TODO TT ON TT.ToDoId = TR.ToDoId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'DocumentId_' + CAST(D.DocumentId AS NVARCHAR(10)) ) as ContainerKey, N'DCreator' as Role FROM USERS U
JOIN DOCUMENTS D ON D.CreatorId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'DocumentId_' + CAST(D.DocumentId AS NVARCHAR(10)) ) as ContainerKey, N'DManager' as Role FROM USERS U
JOIN DOCUMENTS D ON D.ManagerId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'DocumentId_' + CAST(DR.DocumentId AS NVARCHAR(10)) ) as ContainerKey, N'DManager' as Role FROM USERS U
JOIN DOCUMENT_RESOURCES DR ON DR.PrincipalId = U.PrincipalId
WHERE DR.CanManage = 1
	AND
      U.PrincipalId NOT IN (SELECT DD.ManagerId FROM DOCUMENTS DD WHERE DD.DocumentId = DR.DocumentId)
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'DocumentId_' + CAST(DR.DocumentId AS NVARCHAR(10)) ) as ContainerKey, N'DResource' as Role FROM USERS U
JOIN DOCUMENT_RESOURCES DR ON DR.PrincipalId = U.PrincipalId
WHERE DR.CanManage = 0
UNION ALL
SELECT DISTINCT U.PrincipalId as PrincipalId, (N'DocumentId_' + CAST(DT.DocumentId AS NVARCHAR(10)) ) as ContainerKey, N'DTodoResource' as Role FROM USERS U
JOIN TODO_RESOURCES TR ON TR.PrincipalId = U.PrincipalId
JOIN DOCUMENT_TODO DT ON DT.ToDoId = TR.ToDoId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'EventId_' + CAST(E.EventId AS NVARCHAR(10)) ) as ContainerKey, N'ECreator' as Role FROM USERS U
JOIN EVENTS E ON E.CreatorId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'EventId_' + CAST(E.EventId AS NVARCHAR(10)) ) as ContainerKey, N'EManager' as Role FROM USERS U
JOIN EVENTS E ON E.ManagerId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'EventId_' + CAST(ER.EventId AS NVARCHAR(10)) ) as ContainerKey, N'EResource' as Role FROM USERS U
JOIN EVENT_RESOURCES ER ON ER.PrincipalId = U.PrincipalId
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ToDoId_' + CAST(T.ToDoId AS NVARCHAR(10)) ) as ContainerKey, N'TodoCreator' as Role FROM USERS U
JOIN TODO T ON T.CreatorId = U.PrincipalId
WHERE
	T.ToDoId NOT IN (SELECT ToDoId FROM INCIDENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM DOCUMENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM TASK_TODO)
UNION ALL
SELECT U.PrincipalId as PrincipalId, (N'ToDoId_' + CAST(T.ToDoId AS NVARCHAR(10)) ) as ContainerKey, N'TodoManager' as Role FROM USERS U
JOIN TODO T ON T.ManagerId = U.PrincipalId
WHERE
	T.ToDoId NOT IN (SELECT ToDoId FROM INCIDENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM DOCUMENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM TASK_TODO)
UNION ALL
SELECT 	PrincipalId as PrincipalId, (N'ToDoId_' + CAST(T.ToDoId AS NVARCHAR(10))) AS ContainerKey,  N'TodoResource' as Role
FROM TODO_RESOURCES TR
JOIN TODO T ON T.ToDoId = TR.ToDoId
WHERE
	T.ToDoId NOT IN (SELECT ToDoId FROM INCIDENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM DOCUMENT_TODO)
	AND
	T.ToDoId NOT IN (SELECT ToDoId FROM TASK_TODO)
)
COMMIT TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RecurrenceAdd
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@StartTime as int ,
	@EndTime as int ,
	@Pattern as tinyint,
	@SubPattern as tinyint,
	@Frequency as tinyint,
	@Weekdays as tinyint,
	@DayOfMonth as tinyint,
	@WeekNumber as tinyint,
	@MonthNumber as tinyint,
	@EndAfter as int,
	@TimeZoneId as int
as
if EXISTS(SELECT * FROM RECURRENCE WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId)
	UPDATE RECURRENCE
	  SET StartTime=@StartTime, EndTime=@EndTime, Pattern=@Pattern, SubPattern=@SubPattern, Frequency=@Frequency, Weekdays=@Weekdays,
		DayOfMonth=@DayOfMonth, WeekNumber=@WeekNumber, MonthNumber=@MonthNumber, EndAfter=@EndAfter, TimeZoneId=@TimeZoneId
	  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
else
	INSERT INTO RECURRENCE (ObjectTypeId, ObjectId, StartTime, EndTime, Pattern, SubPattern, Frequency, Weekdays, DayOfMonth, WeekNumber, MonthNumber, EndAfter, TimeZoneId)
	  VALUES(@ObjectTypeId, @ObjectId, @StartTime, @EndTime, @Pattern, @SubPattern, @Frequency, @Weekdays, @DayOfMonth, @WeekNumber, @MonthNumber, @EndAfter, @TimeZoneId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RecurrenceDelete
	@ObjectTypeId as int ,
	@ObjectId as int
as
DELETE FROM RECURRENCE  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RecurrenceGet
	@ObjectTypeId as int ,
	@ObjectId as int
as
SELECT RecurrenceId, ObjectTypeId, ObjectId, StartTime, EndTime, Pattern, SubPattern, Frequency, Weekdays, DayOfMonth, WeekNumber, MonthNumber, EndAfter, TimeZoneId
  FROM RECURRENCE
  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionAddGlobal
	@DateTypeId int,
	@Lag int,
	@IsActive bit,
	@retval int output
AS
SELECT @retval = SubscriptionId FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId IS NULL AND ObjectId IS NULL
IF @retval IS NULL
BEGIN
	INSERT INTO REMINDER_SUBSCRIPTIONS (DateTypeId, Lag, IsActive) VALUES (@DateTypeId, @Lag, @IsActive)
	SET @retval = @@identity
END
ELSE
	UPDATE REMINDER_SUBSCRIPTIONS SET Lag = @Lag, IsActive = @IsActive WHERE SubscriptionId = @retval
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionAddPersonal
	@DateTypeId int,
	@UserId int,
	@Lag int,
	@IsActive bit,
	@retval int output
AS
SELECT @retval = SubscriptionId FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL
IF @retval IS NULL
BEGIN
	INSERT INTO REMINDER_SUBSCRIPTIONS (DateTypeId, UserId, Lag, IsActive) VALUES (@DateTypeId, @UserId, @Lag, @IsActive)
	SET @retval = @@identity
END
ELSE
	UPDATE REMINDER_SUBSCRIPTIONS SET Lag = @Lag, IsActive = @IsActive WHERE SubscriptionId = @retval
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionAddPersonalForObject
	@DateTypeId int,
	@UserId int,
	@ObjectId int,
	@Lag int,
	@IsActive bit,
	@retval int output
AS
SELECT @retval = SubscriptionId FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId = @ObjectId
IF @retval IS NULL
BEGIN
	INSERT INTO REMINDER_SUBSCRIPTIONS (DateTypeId, UserId, ObjectId, Lag, IsActive) VALUES (@DateTypeId, @UserId, @ObjectId, @Lag, @IsActive)
	SET @retval = @@identity
END
ELSE
	UPDATE REMINDER_SUBSCRIPTIONS SET Lag = @Lag, IsActive = @IsActive WHERE SubscriptionId = @retval
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionDeletePersonal
	@DateTypeId int,
	@UserId int
AS
DECLARE @HookId int
SELECT @HookId = HookId FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL
BEGIN TRAN
	DELETE FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL
	IF @@error != 0
		GOTO err
	IF @HookId IS NOT NULL
	BEGIN
		DELETE FROM DATE_TYPE_HOOKS WHERE HookId = @HookId
		IF @@error != 0
			GOTO err
	END
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionDeletePersonalForObject
	@DateTypeId int,
	@UserId int,
	@ObjectId int
AS
DECLARE @HookId int
SELECT @HookId = HookId FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId = @ObjectId
BEGIN TRAN
	DELETE FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId = @ObjectId
	IF @@error != 0
		GOTO err
	IF @HookId IS NOT NULL
	BEGIN
		DELETE FROM DATE_TYPE_HOOKS WHERE HookId = @HookId
		IF @@error != 0
			GOTO err
	END
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionGetByHookId
	@HookId int
AS
SELECT S.SubscriptionId, S.DateTypeId, S.UserId, S.ObjectId, S.Lag, S.IsActive, S.HookId, D.ObjectTypeId
  FROM REMINDER_SUBSCRIPTIONS S
	JOIN DATE_TYPES D ON (S.DateTypeId = D.DateTypeId)
  WHERE S.HookId = @HookId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionGetGlobal
	@DateTypeId int
AS
SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId
  FROM REMINDER_SUBSCRIPTIONS
  WHERE DateTypeId = @DateTypeId AND UserId IS NULL AND ObjectId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionGetPersonal
	@DateTypeId int,
	@UserId int
AS
IF EXISTS(SELECT * FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL)
	SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId, 2 AS SubscriptionType
	  FROM REMINDER_SUBSCRIPTIONS
	  WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL
ELSE
	SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId, 1 AS SubscriptionType
	  FROM REMINDER_SUBSCRIPTIONS
	  WHERE DateTypeId = @DateTypeId AND UserId IS NULL AND ObjectId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionGetPersonalForObject
	@DateTypeId int,
	@UserId int,
	@ObjectId int
AS
IF EXISTS(SELECT * FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId, 3 AS SubscriptionType
	  FROM REMINDER_SUBSCRIPTIONS
	  WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId = @ObjectId
ELSE IF EXISTS(SELECT * FROM REMINDER_SUBSCRIPTIONS WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL)
	SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId, 2 AS SubscriptionType
	  FROM REMINDER_SUBSCRIPTIONS
	  WHERE DateTypeId = @DateTypeId AND UserId = @UserId AND ObjectId IS NULL
ELSE
	SELECT SubscriptionId, DateTypeId, UserId, ObjectId, Lag, IsActive, HookId, 1 AS SubscriptionType
	  FROM REMINDER_SUBSCRIPTIONS
	  WHERE DateTypeId = @DateTypeId AND UserId IS NULL AND ObjectId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReminderSubscribtionUpdateHookId
	@SubscriptionId int,
	@HookId int = null
AS
UPDATE REMINDER_SUBSCRIPTIONS SET HookId = @HookId WHERE SubscriptionId = @SubscriptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportGet
	@ReportItemId as int
AS
Select RH.ReportId As TemplateId, RH.CreationDate As ReportCreated, RH.CreatorId As ReportCreator, R.[Name], R.IsGlobal,
	R.CreationDate As TemplateCreated, R.LastSavedDate As TemplateModified,
	R.CreatorId As TemplateCreatorId, R.LastEditorId As TemplateModifierId, R.IBNReportTemplate As TemplateXML
	FROM ReportHistory AS RH, Report AS R
	WHERE (R.ReportId = RH.ReportId)AND(RH.ReportItemId = @ReportItemId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportGetAuthors
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT CreatorId FROM Report)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportGetBinaryData
	@ReportItemId as int
as
SELECT ReportData FROM ReportHistory WHERE ReportItemId = @ReportItemId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportGetModifiers
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT LastEditorId FROM Report)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportGroupStatistics
	@startdate as DateTime,
	@enddate as DateTime,
	@GroupId as int,
	@ShowAll as bit
as
DECLARE @Inactive tinyint
SET @Inactive = 1
DECLARE @Active tinyint
SET @Active = 3
declare @v1 as int, @v2 as int, @v3 as int, @v4 as int, @v5 as int, @v6 as int, @v7 as int, @v8 as int, @v9 as int, @v10 as int
set @v1 = (select COUNT(PrincipalId) From Users Where (Activity = @Active) AND PrincipalId In (Select UserId From User_Group Where GroupId=@GroupId) )
set @v2 = (select COUNT(PrincipalId) From Users Where (Activity = @Inactive) AND PrincipalId In (Select UserId From User_Group Where GroupId=@GroupId) )
IF @ShowAll = 1
BEGIN
	set @v3 = (select COUNT(*) from Projects Where (CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (Select UserId From User_Group Where GroupId=@GroupId))  )
	set @v4 = (select COUNT(*) from Events Where (CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (Select UserId From User_Group Where GroupId=@GroupId))  )
	set @v7 = (select COUNT(*) from Incidents Where (CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (Select UserId From User_Group Where GroupId=@GroupId))  )
	set @v8 = (select COUNT(*) from ToDo Where (CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (Select UserId From User_Group Where GroupId=@GroupId))  )
	set @v9 = (select COUNT(*) from Tasks  Where (CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (Select UserId From User_Group Where GroupId=@GroupId))  )
END
ELSE
BEGIN
	set @v3 = (select COUNT(*) from Projects Where ( CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId))  )
	set @v4 = (select COUNT(*) from Events Where ( CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId))  )
	set @v7 = (select COUNT(*) from Incidents Where ( CreationDate >= @startdate)
				AND (CreationDate <= @enddate)
				AND (CreatorId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId))  )
	set @v8 = (select COUNT(*) from ToDo Where (CreationDate >= @startdate)
				AND(CreationDate <= @enddate)
				AND(CreatorId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId))  )
	set @v9 = (select COUNT(*) from Tasks  Where (CreationDate >= @startdate)
				AND(CreationDate <= @enddate)
				AND(CreatorId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId))  )
END
set @v10 = (select COUNT(*) from Portal_Logins Where
			(
				UserId in (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId)
				AND
				LoginTime >= @startdate
				AND
				LoginTime <= @enddate
			)
		)
select @v1 as ActiveAccounts, @v2 as InactiveAccounts, @v3 as NewProjectsCount, @v4 as NewEventsCount,
	@v7 AS NewIncidentsCount, @v8 AS NewToDosCount, @v9 AS NewTasksCount, @v10 AS PortalLogins
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportHelpDeskIssuesSnapshot
as
DECLARE @Active tinyint
SET @Active = 3
DECLARE @Pending tinyint
SET @Pending = 2
DECLARE @HDMGroup int
SET @HDMGroup = 5
DECLARE @HDM int
SELECT @HDM = COUNT(*)
  FROM USERS
  WHERE (Activity = @Active OR Activity = @Pending)
	AND PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @HDMGroup)
DECLARE @TotalIssues int
SELECT @TotalIssues = COUNT(*)
  FROM INCIDENTS
DECLARE @ProjectIssues int
SELECT @ProjectIssues = COUNT(*)
  FROM INCIDENTS
  WHERE ProjectId IS NOT NULL
DECLARE @GeneralIssues int
SELECT @GeneralIssues = COUNT(*)
  FROM INCIDENTS
  WHERE ProjectId IS NULL
SELECT @HDM AS HDM, @TotalIssues AS TotalIssues, @ProjectIssues AS ProjectIssues, @GeneralIssues AS GeneralIssues
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportHistoryAdd
	@ReportId as int,
	@CreationDate as datetime,
	@CreatorId as int,
	@ResultXML as image,
	@retval as int out
as
INSERT INTO ReportHistory ( ReportId, CreationDate, CreatorId, ReportData )
		VALUES(@ReportId, @CreationDate, @CreatorId, @ResultXML )
select @retval=@@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportHistoryDelete
	@ReportItemId int
as
Delete From ReportHistory Where ReportItemId = @ReportItemId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportIncidentsBreakdownByManager
as
DECLARE @NewState int
SET @NewState = 1
DECLARE @ActiveState int
SET @ActiveState = 2
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT U.PrincipalId AS UserId, U.FirstName, U.LastName, B.NewCount, B.ActiveCount, B.ClosedCount,
	B.NewCount + B.ActiveCount + B.ClosedCount AS TotalCount
  FROM USERS U,
	(SELECT ManagerId, SUM(NewCount) AS NewCount, SUM(ActiveCount) AS ActiveCount, SUM(ClosedCount) AS ClosedCount
	  FROM
	  (
		SELECT ManagerId, COUNT(*) AS NewCount, 0 AS ActiveCount, 0 AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @NewState
		  GROUP BY ManagerId
		UNION ALL
		SELECT ManagerId, 0 AS NewCount, COUNT(*) AS ActiveCount, 0 AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @ActiveState
		  GROUP BY ManagerId
		UNION ALL
		SELECT ManagerId, 0 AS NewCount, 0 AS ActiveCount, COUNT(*) AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @ClosedState
		  GROUP BY ManagerId
	  ) A
	  GROUP BY ManagerId
	) B
WHERE U.PrincipalId = B.ManagerId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportIncidentsBreakdownByProject
as
DECLARE @NewState int
SET @NewState = 1
DECLARE @ActiveState int
SET @ActiveState = 2
DECLARE @ClosedState int
SET @ClosedState = 5
SELECT P.ProjectId, P.Title AS ProjectTitle, B.NewCount, B.ActiveCount, B.ClosedCount,
	B.NewCount + B.ActiveCount + B.ClosedCount AS TotalCount
  FROM PROJECTS P,
	(SELECT ProjectId, SUM(NewCount) AS NewCount, SUM(ActiveCount) AS ActiveCount, SUM(ClosedCount) AS ClosedCount
	  FROM
	  (
		SELECT ProjectId, COUNT(*) AS NewCount, 0 AS ActiveCount, 0 AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @NewState
		  GROUP BY ProjectId
		UNION ALL
		SELECT ProjectId, 0 AS NewCount, COUNT(*) AS ActiveCount, 0 AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @ActiveState
		  GROUP BY ProjectId
		UNION ALL
		SELECT ProjectId, 0 AS NewCount, 0 AS ActiveCount, COUNT(*) AS ClosedCount
		  FROM INCIDENTS
		  WHERE StateId = @ClosedState
		  GROUP BY ProjectId
	  ) A
	  GROUP BY ProjectId
	) B
WHERE P.ProjectId = B.ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByEvent
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN EVENTS E ON (C.PrincipalId = E.CreatorId)
	  WHERE E.CreationDate >= @FromDate AND E.CreationDate < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByIncident
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN INCIDENTS I ON (C.PrincipalId = I.CreatorId)
	  WHERE I.CreationDate >= @FromDate AND I.CreationDate < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByPortalLogins
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN Portal_Logins T ON (C.PrincipalId = T.UserId)
	  WHERE T.LoginTime >= @FromDate AND T.LoginTime < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByProject
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN PROJECTS P ON (C.PrincipalId = P.CreatorId)
	  WHERE P.CreationDate >= @FromDate AND P.CreationDate < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByTask
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN TASKS T ON (C.PrincipalId = T.CreatorId)
	  WHERE T.CreationDate >= @FromDate AND T.CreationDate < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportMostActiveGroupsByToDo
	@FromDate as DateTime,
	@ToDate as DateTime
as
SELECT G.GroupName AS DisplayName, Value AS [Count]
  FROM Groups G,
	(SELECT C.ParentPrincipalId, COUNT(*) AS Value
	  FROM CONTAINERSHIP C
		JOIN TODO T ON (C.PrincipalId = T.CreatorId)
	  WHERE T.CreationDate >= @FromDate AND T.CreationDate < @ToDate
	  GROUP BY C.ParentPrincipalId
	) A
  WHERE G.PrincipalId = A.ParentPrincipalId
  ORDER BY Value DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportProjectStatistic
	@ProjectId as int
as
DECLARE @ProjectType int
SET @ProjectType = 3
DECLARE @FolderType int
SET @FolderType = 10
DECLARE @Discussions int
SELECT @Discussions = COUNT(*)
  FROM DISCUSSIONS
  WHERE ObjectId = @ProjectId AND ObjectTypeId = @ProjectType
DECLARE @Events int
SELECT @Events = COUNT(*)
  FROM EVENTS
  WHERE ProjectId = @ProjectId
DECLARE @Tasks int
SELECT @Tasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId
DECLARE @ToDo int
SELECT @ToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId
DECLARE @Incidents int
SELECT @Incidents = COUNT(*)
  FROM INCIDENTS
  WHERE ProjectId = @ProjectId
DECLARE @Resources int
SELECT @Resources = COUNT(*)
  FROM PROJECT_MEMBERS
  WHERE ProjectId = @ProjectId AND IsTeamMember = 1
DECLARE @Minutes int
SELECT @Minutes = SUM(T.TotalApproved)
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
  WHERE W.ProjectId = @ProjectId
IF @Minutes IS NULL
	SET @Minutes = 0
SELECT @Discussions AS Discussions, @Events AS Events, @Tasks AS Tasks, @ToDo AS ToDo, @Incidents AS Incidents,
	@Resources AS Resources, @Minutes AS Minutes
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportProjectStatisticByUser
	@ProjectId as int,
	@UserId as int
as
DECLARE @Minutes int
SELECT @Minutes = SUM(T.TotalApproved)
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
  WHERE W.ProjectId = @ProjectId AND W.UserId = @UserId
IF @Minutes IS NULL
	SET @Minutes = 0
DECLARE @IncidentsCreated int
SELECT @IncidentsCreated = COUNT(*)
  FROM INCIDENTS
  WHERE ProjectId = @ProjectId AND CreatorId = @UserId
DECLARE @IncidentType int
SET @IncidentType = 7
DECLARE @IncidentsModified int
SELECT @IncidentsModified = COUNT(DISTINCT E.ObjectId)
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
  WHERE T.ObjectTypeId = @IncidentType
	AND E.UserId = @UserId
	AND ObjectId IN (SELECT IncidentId FROM INCIDENTS WHERE ProjectId = @ProjectId)
DECLARE @ClosedState int
SET @ClosedState = 5
DECLARE @IncidentsClosed int
SELECT @IncidentsClosed = COUNT(*)
  FROM INCIDENTS
  WHERE StateId = @ClosedState AND ProjectId = @ProjectId AND ClosedBy = @UserId
DECLARE @Events int
SELECT @Events = COUNT(*)
  FROM EVENTS
  WHERE ProjectId = @ProjectId AND CreatorId = @UserId
DECLARE @ProjectType int
SET @ProjectType = 3
DECLARE @Discussions int
SELECT @Discussions = COUNT(*)
  FROM DISCUSSIONS
  WHERE ObjectId = @ProjectId AND ObjectTypeId = @ProjectType AND CreatorId = @UserId
SELECT @Minutes AS Minutes, @IncidentsCreated AS IncidentsCreated, @IncidentsModified AS IncidentsModified, @IncidentsClosed AS IncidentsClosed,
	@Events AS Events, @Discussions AS Discussions
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportProjectTeamBreakdown
	@ProjectId as int
as
SELECT M.ProjectId, M.PrincipalId AS UserId, U.FirstName, U.LastName, M.Code, M.Rate,
	CASE WHEN T.Minutes IS NULL THEN 0 ELSE T.Minutes END AS Minutes
  FROM PROJECT_MEMBERS M
	LEFT JOIN
		(SELECT W.UserId, SUM(T.TotalApproved) AS Minutes
			FROM TimeSheets T
				JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
			WHERE W.ProjectId = @ProjectId
			GROUP BY W.UserId
		) T
	ON (M.PrincipalId = T.UserId)
	JOIN USERS U ON (M.PrincipalId = U.PrincipalId)
  WHERE M.ProjectId = @ProjectId AND M.IsTeamMember = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportQuickSnapshot
	@startdate as DateTime,
	@enddate as DateTime,
	@creatorid as int
as
declare @v1 as int, @v2 as int, @v5 as int, @v6 as int, @v9 as int, @v10 as int, @v11 as int, @v12 as int, @v13 as int, @v14 as int, @v15 as int
set @v1 = (select COUNT(*) from Projects)
set @v2 = (select COUNT(*) from Events)
set @v5 = (select COUNT(*) from Projects Where ( (CreationDate >= @startdate)
			AND (CreationDate <= @enddate)
			AND (CreatorId=@creatorid OR @creatorid=0)  )    )
set @v6 = (select COUNT(*) from Events Where (( CreationDate >= @startdate)
			AND (CreationDate <= @enddate)
			AND (CreatorId=@creatorid OR @creatorid=0)  )    )
set @v9 = (select COUNT(*) from Incidents)
set @v10 = (select COUNT(*) from ToDo)
set @v11 = (select COUNT(*) from Tasks)
set @v12 = (select COUNT(*) from Incidents Where ( (CreationDate >= @startdate)
			AND (CreationDate <= @enddate)
			AND (CreatorId=@creatorid OR @creatorid=0)  )    )
set @v13 = (select COUNT(*) from ToDo Where (( CreationDate >= @startdate)
			AND (CreationDate <= @enddate)
			AND (CreatorId=@creatorid OR @creatorid=0)  )    )
set @v14 = (select COUNT(*) from Tasks  Where ((CreationDate >= @startdate)
			AND (CreationDate <= @enddate)
			AND (CreatorId=@creatorid OR @creatorid=0)  )    )
set @v15 = (select COUNT(*) from Portal_Logins Where (LoginTime >= @startdate)
			AND (LoginTime <= @enddate)
			AND (UserId = @creatorid OR @creatorid=0) )
select @v1 as ProjectsCount, @v2 as EventsCount, @v5 AS NewProjectsCount, @v6 AS NewEventsCount,
	@v9 AS IncidentsCount, @v10 AS ToDosCount, @v11 AS TasksCount,
	@v12 AS NewIncidentsCount, @v13 AS NewToDosCount, @v14 AS NewTasksCount, @v15 AS PortalLogins
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportQuickUsageStats
	@UserId as int
as
DECLARE @ActiveStatus int
SET @ActiveStatus = 1
DECLARE @ActiveProjects int
SELECT @ActiveProjects = COUNT(*)
  FROM PROJECTS P, PROJECT_SECURITY_ALL PS
  WHERE P.ProjectId = PS.ProjectId AND PS.PrincipalId = @UserId
	AND (PS.IsManager = 1 OR PS.IsExecutiveManager = 1 OR PS.IsTeamMember = 1 OR PS.IsSponsor = 1 OR PS.IsStakeHolder = 1)
	AND StatusId = @ActiveStatus
DECLARE @CalendarEntries int
SELECT @CalendarEntries = COUNT(*)
  FROM EVENTS E, EVENT_SECURITY_ALL ES
  WHERE E.EventId = ES.EventId AND ES.PrincipalId = @UserId
	AND (ES.IsManager = 1 OR ES.IsResource = 1)
DECLARE @ToDoCompleted int
SELECT @ToDoCompleted = COUNT(*)
  FROM TODO T, TODO_SECURITY_ALL TS
  WHERE T.ToDoId = TS.ToDoId AND TS.PrincipalId = @UserId AND TS.IsResource = 1 AND T.IsCompleted = 1
DECLARE @TasksCompleted int
SELECT @TasksCompleted = COUNT(*)
  FROM TASKS T, TASK_SECURITY TS
  WHERE T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId AND TS.IsResource = 1 AND T.IsCompleted = 1
DECLARE @IssuesResolved int
SELECT @IssuesResolved = COUNT(*)
  FROM INCIDENTS
  WHERE ClosedBy = @UserId
SELECT @ActiveProjects AS ActiveProjects, @CalendarEntries AS CalendarEntries,
	@ToDoCompleted + @TasksCompleted AS TasksCompleted, @IssuesResolved AS IssuesResolved
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportsCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM Report WHERE CreatorId = @UserId OR LastEditorId = @UserId)
	OR EXISTS(SELECT * FROM ReportHistory WHERE CreatorId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportsGetByTemplateId
	@TemplateId as int
AS
Select ReportItemId, ReportId, CreationDate, CreatorId
	FROM ReportHistory
	WHERE ReportId = @TemplateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportsReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
UPDATE Report SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
UPDATE Report SET LastEditorId = @ToUserId WHERE LastEditorId = @FromUserId
UPDATE ReportHistory SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplateAdd
	@Name as nvarchar(255),
	@CreationDate as datetime,
	@CreatorId as int,
	@IsGlobal as bit,
	@IsTemporary as bit,
	@ReportTemplate as ntext,
	@retval as int out
as
INSERT INTO Report ( [Name], CreationDate, LastSavedDate, CreatorId, LastEditorId, IBNReportTemplate, IsGlobal, IsTemporary )
		VALUES(@Name, @CreationDate, @CreationDate, @CreatorId, @CreatorId, @ReportTemplate, @IsGlobal, @IsTemporary)
select @retval=@@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplateDelete
	@TemplateId int
as
Begin Tran
Delete From ReportHistory Where ReportId = @TemplateId
IF @@ERROR != 0
		GOTO err
Delete From Report Where ReportId = @TemplateId
IF @@ERROR != 0
		GOTO err
Commit Tran
Return
err:
	Rollback Tran
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplateDeleteTemporary
AS
Delete From ReportHistory  Where ReportId in (Select T.ReportId From Report As T Where (IsTemporary=1 AND DATEDIFF(day, CreationDate, getdate())>1))
Delete FROM Report WHERE (IsTemporary=1 AND DATEDIFF(day, CreationDate, getdate())>1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplateGet
	@ReportTemplateId as int
AS
Select ReportId As TemplateId, [Name], CreationDate As TemplateCreated, LastSavedDate As TemplateModified,
	CreatorId As TemplateCreatorId, LastEditorId As TemplateModifierId, IBNReportTemplate As TemplateXML, IsGlobal, IsTemporary
	FROM Report
	WHERE (ReportId = @ReportTemplateId) OR (@ReportTemplateId=0 AND IsTemporary=0)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplatesGetByFilter
	@CreatorId as int,
	@LastEditorId as int,
	@UserId as int,
	@StartDate as datetime = null,
	@FinishDate as datetime = null
As
Select ReportId As TemplateId, [Name] As TemplateName,
	CreationDate As TemplateCreated,
	LastSavedDate As TemplateModified,
	CreatorId As TemplateCreatorId, LastEditorId As TemplateModifierId,
	IBNReportTemplate As TemplateXML, IsGlobal
  From Report
  Where (CreatorId = @CreatorId Or @CreatorId=0) AND (LastEditorId = @LastEditorId Or @LastEditorId =0)
	AND (@StartDate=null Or CreationDate>=@StartDate)
	AND (@FinishDate=null Or CreationDate<=@FinishDate)
	AND (IsGlobal = 1 OR CreatorId = @UserId)
	AND IsTemporary=0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportTemplateUpdate
	@TemplateId as int,
	@Name as nvarchar(255),
	@LastSavedDate as datetime,
	@LastEditorId as int,
	@IsGlobal as bit,
	@IsTemporary as bit,
	@ReportTemplate as ntext
as
Update Report
set [Name]=@Name,  LastSavedDate=@LastSavedDate, LastEditorId = @LastEditorId, IsGlobal = @IsGlobal, IsTemporary = @IsTemporary, IBNReportTemplate = @ReportTemplate
Where ReportId = @TemplateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ReportToDoAndTaskTracking
	@ProjectId as int
as
DECLARE @Dt datetime
SET @Dt = GETUTCDATE()
DECLARE @TotalToDo int
SELECT @TotalToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId
DECLARE @TotalTasks int
SELECT @TotalTasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0
DECLARE @CompletedToDo int
SELECT @CompletedToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId AND IsCompleted = 1
DECLARE @CompletedTasks int
SELECT @CompletedTasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0 AND IsCompleted = 1
DECLARE @PastDueToDo int
SELECT @PastDueToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId AND IsCompleted = 0 AND FinishDate <= @Dt
DECLARE @PastDueTasks int
SELECT @PastDueTasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0 AND IsCompleted = 0 AND FinishDate <= @Dt
DECLARE @ActiveToDo int
SELECT @ActiveToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId AND IsCompleted = 0 AND (StartDate <= @Dt OR StartDate IS NULL)
DECLARE @ActiveTasks int
SELECT @ActiveTasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0 AND IsCompleted = 0 AND StartDate <= @Dt
DECLARE @UpcomingToDo int
SELECT @UpcomingToDo = COUNT(*)
  FROM TODO
  WHERE ProjectId = @ProjectId AND IsCompleted = 0 AND StartDate > @Dt
DECLARE @UpcomingTasks int
SELECT @UpcomingTasks = COUNT(*)
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0 AND IsCompleted = 0 AND StartDate > @Dt
SELECT @TotalToDo + @TotalTasks AS Total, @CompletedToDo + @CompletedTasks AS Completed,
	@PastDueToDo + @PastDueTasks AS PastDue, @ActiveToDo + @ActiveTasks AS Active, @UpcomingToDo + @UpcomingTasks AS Upcoming
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RiskLevelAdd
	@RiskLevelName as nvarchar(50),
	@Weight int
AS
INSERT INTO RISK_LEVELS (RiskLevelName, Weight) VALUES(@RiskLevelName, @Weight)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RiskLevelDelete
	@RiskLevelId as int
as
DELETE FROM RISK_LEVELS  WHERE RiskLevelId = @RiskLevelId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RiskLevelsGet
as
SELECT RiskLevelId, RiskLevelName, Weight
  FROM RISK_LEVELS
  ORDER BY Weight
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RiskLevelsGetForDictionaries
as
DECLARE @Items int
SELECT @Items = COUNT(*) FROM RISK_LEVELS
SELECT RL.RiskLevelId AS ItemId, RL.RiskLevelName AS ItemName, RL.Weight,
	CASE WHEN EXISTS(SELECT * FROM PROJECTS P WHERE P.RiskLevelId = RL.RiskLevelId) OR @Items = 1
	THEN 0 ELSE 1 END AS CanDelete
  FROM RISK_LEVELS RL
  ORDER BY RL.Weight
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].RiskLevelUpdate
	@RiskLevelId as int ,
	@RiskLevelName as nvarchar(50) ,
	@Weight int
as
UPDATE RISK_LEVELS SET RiskLevelName = @RiskLevelName, Weight = @Weight
  WHERE RiskLevelId = @RiskLevelId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ScheduleAdd
	@UserId as int ,
	@ContUserId as int
as
IF NOT EXISTS(SELECT * FROM SCHEDULE WHERE UserId = @UserId AND ContUserId = @ContUserId)
	INSERT INTO SCHEDULE (UserId, ContUserId) VALUES(@UserId, @ContUserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ScheduleDelete
	@UserId as int,
	@ContUserId as int
as
DELETE FROM SCHEDULE  WHERE UserId = @UserId AND ContUserId = @ContUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ScheduleGetByUser
	@UserId as int
as
SELECT S.ContUserId AS UserId, U.FirstName, U.LastName, U.Email, U.Login, U.Activity
  FROM SCHEDULE S
	JOIN USERS U ON (S.ContUserId = U.PrincipalId)
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ScheduleProcessHandlerTempItemProcess
	@Id int
AS
	UPDATE ScheduleProcessHandlerTempItems SET IsProcessed = 1, Processed = getutcdate() WHERE Id = @Id
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ScheduleProcessHandlerTempItemsFill
AS
	SET NOCOUNT ON
	DECLARE @To DATETIME
	SET @To = getutcdate()
	SELECT V.ValueId, D.DateTypeName, D.ObjectTypeId, V.ObjectId, DATEADD(mi, -H.Lag, V.DateValue) AS Dt, H.HookId, H.HandlerId, H.Params, V.DateValue, H.Lag
	FROM DATE_TYPE_VALUES V
		JOIN DATE_TYPE_HOOKS H ON (V.DateTypeId = H.DateTypeId)
		JOIN DATE_TYPES D ON (V.DateTypeId = D.DateTypeId)
	WHERE
		(V.ObjectId = H.ObjectId OR H.ObjectId IS NULL)
		AND
		(DATEADD(mi, -H.Lag, V.DateValue) <= @To )
		AND NOT EXISTS (SELECT * FROM DATE_TYPE_PROCESSED P WHERE V.ValueId = P.ValueId AND H.HookId = P.HookId AND V.DateValue = P.DateValue AND H.Lag = P.Lag)
	ORDER BY Dt
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingAdd
	@UserId as int ,
	@ProUserId as int,
	@Level int
as
IF EXISTS(SELECT * FROM SHARING WHERE UserId = @UserId AND ProUserId = @ProUserId)
	UPDATE SHARING SET [Level] = @Level WHERE UserId = @UserId AND ProUserId = @ProUserId
ELSE
	INSERT INTO SHARING (UserId, ProUserId, [Level]) VALUES(@UserId, @ProUserId, @Level)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingDelete
	@UserId as int,
	@ProUserId as int
as
DELETE FROM SHARING  WHERE UserId = @UserId AND ProUserId = @ProUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetByProUser
	@ProUserId as int
as
SELECT S.UserId, U.FirstName, U.LastName, U.Email, U.Login, S.[Level]
  FROM SHARING S
	JOIN USERS U ON (S.UserId = U.PrincipalId)
  WHERE ProUserId = @ProUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetByUser
	@UserId as int
as
SELECT S.ProUserId AS UserId, U.FirstName, U.LastName, U.Email, U.Login, S.[Level]
  FROM SHARING S
	JOIN USERS U ON (S.ProUserId = U.PrincipalId)
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevel
	@UserId as int,
	@ProUserId as int,
	@retval int output
as
SELECT @retval = [Level] FROM SHARING WHERE UserId = @UserId AND ProUserId = @ProUserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForDocument
	@UserId as int,
	@DocumentId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM DOCUMENT_SECURITY_ALL DS, SHARING S
  WHERE DS.PrincipalId = S.UserId
	AND DS.DocumentId = @DocumentId
	AND S.ProUserId = @UserId
	AND (DS.IsManager = 1 OR DS.IsResource = 1)
IF @retval IS NULL
	SET @retval = -1
IF @retval > 0
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForEvent
	@UserId as int,
	@EventId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM EVENT_SECURITY_ALL TS, SHARING S
  WHERE TS.PrincipalId = S.UserId
	AND TS.EventId = @EventId
	AND S.ProUserId = @UserId
	AND TS.IsManager = 1
IF @retval IS NULL
BEGIN
	SELECT @retval = MAX(S.[Level])
	  FROM EVENT_SECURITY_ALL TS, SHARING S
	  WHERE TS.PrincipalId = S.UserId
		AND TS.EventId = @EventId
		AND S.ProUserId = @UserId
		AND TS.IsResource = 1
	IF @retval > 0
		SET @retval = 0
END
IF @retval IS NULL
	SET @retval = -1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForIncident
	@UserId as int,
	@IncidentId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM INCIDENT_SECURITY_ALL TS, SHARING S
  WHERE TS.PrincipalId = S.UserId
	AND TS.IncidentId = @IncidentId
	AND S.ProUserId = @UserId
	AND (TS.IsManager = 1 OR TS.IsCreator = 1 OR TS.IsResource = 1)
IF @retval IS NULL
	SET @retval = -1
IF @retval > 0
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForProject
	@UserId as int,
	@ProjectId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM PROJECT_SECURITY_ALL TS, SHARING S
  WHERE TS.PrincipalId = S.UserId
	AND TS.ProjectId = @ProjectId
	AND S.ProUserId = @UserId
	AND (TS.IsManager = 1 OR TS.IsTeamMember = 1 OR TS.IsSponsor = 1 OR TS.IsStakeHolder = 1 OR TS.IsExecutiveManager = 1)
IF @retval IS NULL
	SET @retval = -1
IF @retval > 0
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForTask
	@UserId as int,
	@TaskId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM TASK_SECURITY TS, SHARING S
  WHERE TS.PrincipalId = S.UserId
	AND TS.TaskId = @TaskId
	AND S.ProUserId = @UserId
	AND (TS.IsManager = 1 OR TS.IsResource = 1)
IF @retval IS NULL
	SET @retval = -1
IF @retval > 0
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SharingGetLevelForToDo
	@UserId as int,
	@ToDoId as int,
	@retval int output
as
SELECT @retval = MAX(S.[Level])
  FROM TODO_SECURITY_ALL TS, SHARING S
  WHERE TS.PrincipalId = S.UserId
	AND TS.ToDoId = @ToDoId
	AND S.ProUserId = @UserId
	AND (TS.IsManager = 1 OR TS.IsResource = 1)
IF @retval IS NULL
	SET @retval = -1
IF @retval > 0
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubCreate
	@UserId as int = null,
	@Abbreviation as nchar(2) ,
	@ToolTip as nvarchar(250) ,
	@Url as varchar(1000) ,
	@OpenInBrowser as bit ,
	@Width as int ,
	@Height as int ,
	@retval int output
as
IF @OpenInBrowser = 1
	INSERT INTO STUBS (UserId, Abbreviation, ToolTip, Url, OpenInBrowser)
	  VALUES(@UserId, @Abbreviation, @ToolTip, @Url, @OpenInBrowser)
ELSE
	INSERT INTO STUBS (UserId, Abbreviation, ToolTip, Url, OpenInBrowser, Width, Height)
	  VALUES(@UserId, @Abbreviation, @ToolTip, @Url, @OpenInBrowser, @Width, @Height)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubDelete
       @StubId as int
as
DELETE FROM STUBS  WHERE StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubGet
	@StubId as int
as
SELECT StubId, Abbreviation, ToolTip, Url, OpenInBrowser, Width, Height, IsInternal, UserId,
	CASE WHEN Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS
  WHERE StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubGetIcon
	@StubId as int
as
SELECT Icon FROM STUBS WHERE StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubGroupAdd
	@StubId as int ,
	@GroupId as int
as
INSERT INTO STUB_GROUP (StubId, GroupId) VALUES(@StubId, @GroupId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubGroupDelete
	@StubId as int,
	@GroupId as int
as
DELETE FROM STUB_GROUP  WHERE StubId = @StubId AND GroupId = @GroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubGroupsGetByStub
	@StubId as int
as
SELECT SG.GroupId, G.GroupName
  FROM STUB_GROUP SG
	JOIN GROUPS G ON (SG.GroupId = G.PrincipalId)
  WHERE SG.StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubHide
	@StubId int,
	@UserId int
AS
IF NOT EXISTS (SELECT * FROM HIDDEN_STUBS WHERE StubId = @StubId AND UserId = @UserId)
	INSERT INTO HIDDEN_STUBS (StubId, UserId) VALUES (@StubId, @UserId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubsGetInheritedForUser
	@UserId as int
as
SELECT DISTINCT S.StubId, S.Abbreviation, S.ToolTip, S.Url, S.OpenInBrowser, S.Width, S.Height, S.IsInternal,
	CASE WHEN HS.HidedStubId IS NULL THEN 1 ELSE 0 END AS IsVisible,
	CASE WHEN S.Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS S
	JOIN STUB_GROUP SG ON (S.StubId = SG.StubId)
	JOIN USER_GROUP UG ON (SG.GroupId = UG.GroupId)
	LEFT JOIN HIDDEN_STUBS HS ON (S.StubId = HS.StubId AND HS.UserId = @UserId)
  WHERE UG.UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubsGetVisibleForUser
	@UserId as int
as
SELECT DISTINCT S.StubId, S.Abbreviation, S.ToolTip, S.Url, S.OpenInBrowser, S.Width, S.Height, S.IsInternal,
	CASE WHEN S.Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS S
	JOIN STUB_GROUP SG ON (S.StubId = SG.StubId)
	JOIN USER_GROUP UG ON (SG.GroupId = UG.GroupId)
  WHERE UG.UserId = @UserId
	AND S.StubId NOT IN (SELECT StubId FROM HIDDEN_STUBS WHERE UserId = @UserId)
UNION ALL
SELECT S.StubId, S.Abbreviation, S.ToolTip, S.Url, S.OpenInBrowser, S.Width, S.Height, S.IsInternal,
	CASE WHEN Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS S
  WHERE S.UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubsGetWithoutUser
as
SELECT StubId, Abbreviation, ToolTip, Url, OpenInBrowser, Width, Height, IsInternal,
	CASE WHEN Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS
  WHERE UserId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubsGetWithUser
	@UserId as int
as
SELECT StubId, Abbreviation, ToolTip, Url, OpenInBrowser, Width, Height, IsInternal,
	CASE WHEN Icon IS NULL THEN 0 ELSE 1 END AS HasIcon
  FROM STUBS
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubShow
	@StubId int,
	@UserId int
AS
DELETE FROM HIDDEN_STUBS WHERE StubId = @StubId AND UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubUpdate
	@StubId as int ,
	@Abbreviation as nchar(2) ,
	@ToolTip as nvarchar(250) ,
	@Url as varchar(1000) ,
	@OpenInBrowser as bit ,
	@Width as int ,
	@Height as int
as
UPDATE STUBS
  SET Abbreviation=@Abbreviation, ToolTip=@ToolTip, Url=@Url, OpenInBrowser=@OpenInBrowser, Width=@Width, Height=@Height
  WHERE StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].StubUpdateIcon
	@StubId int,
	@Icon image
AS
UPDATE STUBS SET Icon = @Icon
  WHERE StubId = @StubId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForCalendarEntry
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetResources bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ResourceRole int, @GlobalRole int
SET @ManagerRole = 6
SET @ResourceRole = 7
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsResource int)
INSERT INTO @ROLES (UserId, IsManager, IsResource)
  SELECT PrincipalId, IsManager, IsResource FROM EVENT_SECURITY_ALL WHERE EventId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForDocument
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetResources bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ResourceRole int, @GlobalRole int
SET @ManagerRole = 15
SET @ResourceRole = 16
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsResource int)
INSERT INTO @ROLES (UserId, IsManager, IsResource)
  SELECT PrincipalId, IsRealDocumentManager, IsRealDocumentResource FROM DOCUMENT_SECURITY_ALL WHERE DocumentId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForIssue
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetResources bit,
	@GetCreators bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ResourceRole int, @CreatorRole int, @GlobalRole int
SET @ManagerRole = 13
SET @ResourceRole = 14
SET @CreatorRole = 12
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsResource int, IsCreator int)
INSERT INTO @ROLES (UserId, IsManager, IsResource, IsCreator)
  SELECT PrincipalId, IsRealIncidentManager, IsRealIncidentResource, IsCreator FROM INCIDENT_SECURITY_ALL WHERE IncidentId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetCreators = 1 AND R.IsCreator = 1 AND
			(D.ObjectRoleId = @CreatorRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetCreators = 1 AND R.IsCreator = 1 AND
			(D.ObjectRoleId = @CreatorRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetCreators = 1 AND R.IsCreator = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @CreatorRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForList
	@EventTypeId int,
	@ObjectId int
AS
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
  WHERE EXISTS
		(SELECT * FROM SUBSCRIPTIONS S
			JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
		  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
		)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForPop3MailRequests
	@EventTypeId int,
	@ObjectId int
AS
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
  WHERE EXISTS
		(SELECT * FROM SUBSCRIPTIONS S
			JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
		  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
		)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForProject
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetExecutiveManagers bit,
	@GetTeamMembers bit,
	@GetSponsors bit,
	@GetStakeholders bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ExecutiveManagerRole int, @TeamMemberRole int, @SponsorRole int, @StakeholderRole int, @GlobalRole int
SET @ManagerRole = 1
SET @ExecutiveManagerRole = 2
SET @TeamMemberRole = 3
SET @SponsorRole = 4
SET @StakeholderRole = 5
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsExecutiveManager int, IsTeamMember int, IsSponsor int, IsStakeHolder int)
INSERT INTO @ROLES (UserId, IsManager, IsExecutiveManager, IsTeamMember, IsSponsor, IsStakeHolder)
  SELECT PrincipalId, IsManager, IsExecutiveManager, IsTeamMember, IsSponsor, IsStakeHolder FROM PROJECT_SECURITY_ALL WHERE ProjectId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetExecutiveManagers = 1 AND R.IsExecutiveManager = 1 AND
			(D.ObjectRoleId = @ExecutiveManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetTeamMembers = 1 AND R.IsTeamMember = 1 AND
			(D.ObjectRoleId = @TeamMemberRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetSponsors = 1 AND R.IsSponsor = 1 AND
			(D.ObjectRoleId = @SponsorRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetStakeholders = 1 AND R.IsStakeholder = 1 AND
			(D.ObjectRoleId = @StakeholderRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetExecutiveManagers = 1 AND R.IsExecutiveManager = 1 AND
			(D.ObjectRoleId = @ExecutiveManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetTeamMembers = 1 AND R.IsTeamMember = 1 AND
			(D.ObjectRoleId = @TeamMemberRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetSponsors = 1 AND R.IsSponsor = 1 AND
			(D.ObjectRoleId = @SponsorRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetStakeholders = 1 AND R.IsStakeholder = 1 AND
			(D.ObjectRoleId = @StakeholderRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetExecutiveManagers = 1 AND R.IsExecutiveManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ExecutiveManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetTeamMembers = 1 AND R.IsTeamMember = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @TeamMemberRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetSponsors = 1 AND R.IsSponsor = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @SponsorRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetStakeholders = 1 AND R.IsStakeholder = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @StakeholderRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForTask
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetResources bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ResourceRole int, @GlobalRole int
SET @ManagerRole = 8
SET @ResourceRole = 9
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsResource int)
INSERT INTO @ROLES (UserId, IsManager, IsResource)
  SELECT PrincipalId, IsRealTaskManager, IsRealTaskResource FROM TASK_SECURITY WHERE TaskId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForToDo
	@EventTypeId int,
	@ObjectId int,
	@GetManagers bit,
	@GetResources bit,
	@GetAll bit
AS
DECLARE @ManagerRole int, @ResourceRole int, @GlobalRole int
SET @ManagerRole = 10
SET @ResourceRole = 11
SET @GlobalRole = 0
DECLARE @ROLES TABLE (UserId int, IsManager int, IsResource int)
INSERT INTO @ROLES (UserId, IsManager, IsResource)
  SELECT PrincipalId, IsManager, IsResource FROM TODO_SECURITY_ALL WHERE ToDoId = @ObjectId
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	LEFT JOIN @ROLES R ON (S.UserId = R.UserId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND
	(	(@GetManagers = 1 AND R.IsManager = 1 AND
			(D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND
			(D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole))
		OR
		(@GetAll = 1 AND D.ObjectRoleId = @GlobalRole)
	)
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
	LEFT JOIN @ROLES R ON (U.PrincipalId = R.UserId)
  WHERE
	(	(@GetManagers = 1 AND R.IsManager = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ManagerRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetResources = 1 AND R.IsResource = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND (D.ObjectRoleId = @ResourceRole OR D.ObjectRoleId = @GlobalRole)
		)	)
		OR
		(@GetAll = 1 AND EXISTS
			(SELECT * FROM SUBSCRIPTIONS S
				JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
			  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
				AND D.ObjectRoleId = @GlobalRole
	)	)	)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribersGetForUser
	@EventTypeId int,
	@ObjectId int
AS
DECLARE @USERS TABLE (UserId int)
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId = @ObjectId AND S.UserId IS NOT NULL
INSERT INTO @USERS (UserId)
SELECT S.UserId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId
	AND S.ObjectId IS NULL AND S.UserId IS NOT NULL
	AND S.UserId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId AND UserId IS NOT NULL)
INSERT INTO @USERS (UserId)
SELECT U.PrincipalId
  FROM USERS U
  WHERE EXISTS
		(SELECT * FROM SUBSCRIPTIONS S
			JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
		  WHERE S.EventTypeId = @EventTypeId AND S.UserId IS NULL
		)
	AND U.PrincipalId NOT IN
		(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NOT NULL)
SELECT DISTINCT U.UserId
  FROM @USERS U
	JOIN USERS U2 ON (U.UserId = U2.PrincipalId)
  WHERE U2.Activity = 2 OR U2.Activity = 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionAddGlobal
	@EventTypeId int,
	@ObjectRoleId int
AS
DECLARE @SubscriptionId int
SELECT @SubscriptionId = SubscriptionId
  FROM SUBSCRIPTIONS
  WHERE EventTypeId = @EventTypeId AND UserId IS NULL AND ObjectId IS NULL
IF @SubscriptionId IS NULL
BEGIN
	INSERT INTO SUBSCRIPTIONS (EventTypeId) VALUES (@EventTypeId)
	SET @SubscriptionId = @@identity
END
IF NOT EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS WHERE SubscriptionId = @SubscriptionId AND ObjectRoleId = @ObjectRoleId)
	INSERT INTO SUBSCRIPTION_DETAILS (SubscriptionId, ObjectRoleId) VALUES (@SubscriptionId, @ObjectRoleId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionAddPersonal
	@EventTypeId int,
	@UserId int,
	@retval int output
AS
SELECT @retval = SubscriptionId
  FROM SUBSCRIPTIONS
  WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId IS NULL
IF @retval IS NULL
BEGIN
	INSERT INTO SUBSCRIPTIONS (EventTypeId, UserId) VALUES (@EventTypeId, @UserId)
	SET @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionAddPersonalForObject
	@EventTypeId int,
	@UserId int,
	@ObjectId int,
	@retval int output
AS
SELECT @retval = SubscriptionId
  FROM SUBSCRIPTIONS
  WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId
IF @retval IS NULL
BEGIN
	INSERT INTO SUBSCRIPTIONS (EventTypeId, UserId, ObjectId) VALUES (@EventTypeId, @UserId, @ObjectId)
	SET @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionCheckForToDo
	@EventTypeId int,
	@ObjectId int,
	@UserId int,
	@CheckManagerSubscription bit,
	@CheckResourcesSubscription bit,
	@CheckGlobalSubscription bit,
	@retval int output
AS
DECLARE @ManagerRole int, @ResourceRole int, @GlobalRole int
SET @ManagerRole = 10
SET @ResourceRole = 11
SET @GlobalRole = 0
SET @retval = 0
IF EXISTS
	(SELECT *
	  FROM SUBSCRIPTIONS S
		JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	  WHERE S.EventTypeId = @EventTypeId
		AND S.UserId = @UserId AND S.ObjectId = @ObjectId
		AND
		(	(@CheckManagerSubscription = 1 AND D.ObjectRoleId = @ManagerRole)
			OR
			(@CheckResourcesSubscription = 1 AND D.ObjectRoleId = @ResourceRole)
			OR
			(@CheckGlobalSubscription = 1 AND D.ObjectRoleId = @GlobalRole)
		)
	)
OR EXISTS
	(SELECT *
	  FROM SUBSCRIPTIONS S
		JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	  WHERE S.EventTypeId = @EventTypeId
		AND S.UserId = @UserId AND S.ObjectId IS NULL
		AND
		(	(@CheckManagerSubscription = 1 AND D.ObjectRoleId = @ManagerRole)
			OR
			(@CheckResourcesSubscription = 1 AND D.ObjectRoleId = @ResourceRole)
			OR
			(@CheckGlobalSubscription = 1 AND D.ObjectRoleId = @GlobalRole)
		)
		AND S.UserId NOT IN
			(SELECT UserId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND ObjectId = @ObjectId)
	)
OR EXISTS
	(SELECT *
	  FROM SUBSCRIPTIONS S
		JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
	  WHERE S.EventTypeId = @EventTypeId
		AND S.UserId IS NULL AND S.ObjectId IS NULL
		AND
		(	(@CheckManagerSubscription = 1 AND D.ObjectRoleId = @ManagerRole)
			OR
			(@CheckResourcesSubscription = 1 AND D.ObjectRoleId = @ResourceRole)
			OR
			(@CheckGlobalSubscription = 1 AND D.ObjectRoleId = @GlobalRole)
		)
		AND NOT EXISTS (SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId = @UserId)
	)
SET @retval = 1
RETURN @retval
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionDeleteGlobal
	@EventTypeId int,
	@ObjectRoleId int
AS
DELETE FROM SUBSCRIPTION_DETAILS
  WHERE ObjectRoleId = @ObjectRoleId AND SubscriptionId IN
	(SELECT SubscriptionId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId IS NULL AND ObjectId IS NULL)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionDeletePersonal
	@EventTypeId int,
	@UserId int
AS
DELETE FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionDeletePersonalForObject
	@EventTypeId int,
	@UserId int,
	@ObjectId int
AS
DELETE FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionDetailsAdd
	@SubscriptionId int,
	@ObjectRoleId int
AS
IF NOT EXISTS (SELECT * FROM SUBSCRIPTION_DETAILS WHERE SubscriptionId = @SubscriptionId AND ObjectRoleId = @ObjectRoleId)
	INSERT INTO SUBSCRIPTION_DETAILS (SubscriptionId, ObjectRoleId) VALUES (@SubscriptionId, @ObjectRoleId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionDetailsDelete
	@SubscriptionId int,
	@ObjectRoleId int
AS
DELETE FROM SUBSCRIPTION_DETAILS WHERE SubscriptionId = @SubscriptionId AND  ObjectRoleId = @ObjectRoleId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionUnsubscribePersonal
	@EventTypeId int,
	@UserId int
AS
DECLARE @SubscriptionId int
SELECT @SubscriptionId = SubscriptionId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId IS NULL
IF @SubscriptionId IS NULL
	INSERT INTO SUBSCRIPTIONS (EventTypeId, UserId) VALUES (@EventTypeId, @UserId)
ELSE
	DELETE FROM SUBSCRIPTION_DETAILS WHERE SubscriptionId = @SubscriptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscribtionUnsubscribePersonalForObject
	@EventTypeId int,
	@UserId int,
	@ObjectId int
AS
DECLARE @SubscriptionId int
SELECT @SubscriptionId = SubscriptionId FROM SUBSCRIPTIONS WHERE EventTypeId = @EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId
IF @SubscriptionId IS NULL
	INSERT INTO SUBSCRIPTIONS (EventTypeId, UserId, ObjectId) VALUES (@EventTypeId, @UserId, @ObjectId)
ELSE
	DELETE FROM SUBSCRIPTION_DETAILS WHERE SubscriptionId = @SubscriptionId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionDetailsGetPersonal
	@EventTypeId int,
	@UserId int
AS
SELECT ObjectRoleId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionDetailsGetPersonalForObject
	@EventTypeId int,
	@UserId int,
	@ObjectId int
AS
SELECT ObjectRoleId
  FROM SUBSCRIPTIONS S
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE S.EventTypeId = @EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionsGetGlobal
	@ObjectTypeId int
AS
IF @ObjectTypeId = 3
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE IF @ObjectTypeId = 4
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE IF @ObjectTypeId = 5
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE IF @ObjectTypeId = 6
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE IF @ObjectTypeId = 7
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE IF @ObjectTypeId = 16
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
ELSE
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionsGetGlobalAsList
	@ObjectTypeId int
AS
SELECT E.EventTypeId, D.ObjectRoleId
  FROM System_Event_Types E
	LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	JOIN SUBSCRIPTION_DETAILS D ON (S.SubscriptionId = D.SubscriptionId)
  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionsGetPersonal
	@ObjectTypeId int,
	@UserId int
AS
IF @ObjectTypeId = 3
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 4
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 5
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 6
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 7
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 16
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
ELSE
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId IS NULL)
	ORDER BY E.EventTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SubscriptionsGetPersonalForObject
	@ObjectTypeId int,
	@UserId int,
	@ObjectId int
AS
IF @ObjectTypeId = 3
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 1) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_1,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 2) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_2,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 3) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_3,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 4) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_4,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 5) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_5,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 4
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 6) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_6,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 7) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_7,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 5
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 8) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_8,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 9) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_9,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 6
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 10) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_10,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 11) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_11,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	 WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 7
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 12) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_12,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 13) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_13,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 14) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_14,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE IF @ObjectTypeId = 16
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 15) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_15,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 16) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_16,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
ELSE
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(0 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId = @ObjectId)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId = @UserId AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId AND ObjectId = @ObjectId)
	UNION ALL
	SELECT E.EventTypeId, E.ObjectTypeId, E.Title,
		CASE WHEN EXISTS(SELECT * FROM SUBSCRIPTION_DETAILS D WHERE D.SubscriptionId = S.SubscriptionId AND ObjectRoleId = 0) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Role_0,
		CAST(1 AS bit) AS IsDefault
	  FROM System_Event_Types E
		LEFT JOIN SUBSCRIPTIONS S ON (E.EventTypeId = S.EventTypeId AND S.UserId IS NULL AND S.ObjectId IS NULL)
	  WHERE E.ObjectTypeId = @ObjectTypeId AND E.IsActive = 1
		AND NOT EXISTS(SELECT * FROM SUBSCRIPTIONS WHERE EventTypeId = E.EventTypeId AND UserId = @UserId)
	ORDER BY E.EventTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventGet
	@SystemEventId as int
AS
SELECT E.SystemEventId, E.EventTypeId, E.ObjectId, E.ObjectTitle, ISNULL(E.RelObjectId , -1) AS RelObjectId, E.RelObjectTitle, E.Dt, E.UserId, E.XmlData,
	T.Title AS SystemEventTitle, T.ObjectTypeId, ISNULL(T.RelObjectTypeId , -1) AS RelObjectTypeId
 FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
 WHERE E.SystemEventId = @SystemEventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientAdd
	@SystemEventId as int ,
	@UserId as int ,
	@MessageTypeId as int,
	@Email as nvarchar(250)
as
IF @Email = ''
	SET @Email = NULL
IF @UserId = -1
	SET @UserId = NULL
INSERT INTO SYSTEM_EVENT_RECIPIENTS (SystemEventId, UserId, MessageTypeId, Email)
  VALUES (@SystemEventId, @UserId, @MessageTypeId, @Email)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientsGetByTran
	@TranId as char(36)
AS
SELECT R.RecipientId, R.SystemEventId, R.MessageTypeId, ISNULL(R.UserId, -1) AS UserId, R.Email
 FROM SYSTEM_EVENT_RECIPIENTS R
 JOIN SYSTEM_EVENTS E ON (E.systemEventId = R.SystemEventId)
 LEFT JOIN USERS U ON (U.PrincipalId = R.UserId)
 LEFT JOIN USER_PREFERENCES P ON (P.UserId = U.PrincipalId)
 LEFT JOIN LANGUAGES L ON (L.LanguageId = P.LanguageId)
 WHERE
	R.Processed=0
	AND (E.TranId = @TranId OR @TranId = '')
	AND (R.Email IS NOT NULL OR P.IsBatchNotifications = 0 AND P.IsNotified = 1 AND (P.IsNotifiedByEmail = 1 OR P.IsNotifiedByIBN = 1))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientsGetForBatch
	@UserId int,
	@Dt datetime
AS
SELECT R.RecipientId, R.SystemEventId, R.MessageTypeId, ISNULL(R.UserId, -1) AS UserId, R.Email
 FROM SYSTEM_EVENT_RECIPIENTS R
 JOIN SYSTEM_EVENTS E ON (E.systemEventId = R.SystemEventId)
 LEFT JOIN USERS U ON (U.PrincipalId = R.UserId)
 LEFT JOIN USER_PREFERENCES P ON (P.UserId = U.PrincipalId)
 WHERE
	R.UserId = @UserId
	AND R.Processed=0
	AND P.IsBatchNotifications = 1
	AND P.IsNotified = 1 AND (P.IsNotifiedByEmail = 1 OR P.IsNotifiedByIBN = 1)
	AND P.BatchNextSend = @Dt
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientUpdateLogId
	@RecipientId int,
	@LogId int
AS
UPDATE SYSTEM_EVENT_RECIPIENTS
  SET LogId = @LogId
  WHERE RecipientId = @RecipientId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientUpdateSend
	@RecipientId int,
	@SendEmail bit,
	@SendIbn bit,
	@LogId int = null
AS
UPDATE SYSTEM_EVENT_RECIPIENTS
  SET Processed = 1, SendEmail = @SendEmail, SendIbn = @SendIbn, LogId = @LogId
  WHERE RecipientId = @RecipientId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventRecipientUpdateSent
	@RecipientId int,
	@DeliveryTypeId int,
	@Sent bit
AS
IF @DeliveryTypeId = 1
	UPDATE SYSTEM_EVENT_RECIPIENTS SET SentEmail = @Sent WHERE RecipientId = @RecipientId
IF @DeliveryTypeId = 2
	UPDATE SYSTEM_EVENT_RECIPIENTS SET SentIbn = @Sent WHERE RecipientId = @RecipientId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventsAdd
	@EventTypeId as int ,
	@ObjectId as int ,
	@ObjectTitle nvarchar(250),
	@RelObjectId as int ,
	@RelObjectTitle nvarchar(250),
	@UserId as int,
	@XMLData ntext,
	@TranId char(36),
	@retval int output
as
IF @UserId <= 0
	SET @UserId = null
IF @RelObjectId < 0
	SET @RelObjectId = null
INSERT INTO SYSTEM_EVENTS (EventTypeId, ObjectId, ObjectTitle, RelObjectId, RelObjectTitle, UserId, [XMLData], TranId)
  VALUES(@EventTypeId, @ObjectId, @ObjectTitle, @RelObjectId, @RelObjectTitle, @UserId, @XMLData, @TranId)
SET @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventsGet
	@UserId as int,
	@StartDate datetime,
	@EndDate datetime
as
DECLARE @ProjectType int, @EventType int, @TaskType int, @ToDoType int, @IncidentType int, @DocumentType int, @ListType int
SET @ProjectType = 3
SET @EventType = 4
SET @TaskType = 5
SET @ToDoType = 6
SET @IncidentType = 7
SET @ListType = 15
SET @DocumentType = 16
DECLARE @IsPPMExec bit
SET @IsPPMExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPMExec = 1
DECLARE @IsHDM bit
SET @IsHDM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 5)
	SET @IsHDM = 1
SET TRANSACTION ISOLATION LEVEL  READ UNCOMMITTED
SELECT E.SystemEventId, E.EventTypeId, E.ObjectId, E.ObjectTitle, E.RelObjectTitle,
	ISNULL(E.UserId, -1) AS UserId,
	E.Dt, T.ObjectTypeId, T.Title AS SystemEventTitle,
	ISNULL(T.RelObjectTypeId , -1) AS RelObjectTypeId, ISNULL(E.RelObjectId , -1) AS RelObjectId
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
  WHERE Dt >= @StartDate AND Dt < @EndDate
	AND
	(
		(	T.ObjectTypeId = @ProjectType
			AND
			(	@IsPPMExec = 1
				 OR
				ObjectId IN (SELECT ProjectId FROM PROJECT_SECURITY_ALL WHERE PrincipalId = @UserId AND (IsTeamMember = 1 OR IsSponsor = 1 OR IsStakeHolder = 1 OR IsManager = 1 OR IsExecutiveManager = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @EventType
			AND
			(	(@IsPPMExec = 1 AND ObjectId IN (SELECT EventId FROM EVENTS WHERE ProjectId IS NOT NULL))
				OR
				ObjectId IN (SELECT EventId FROM EVENT_SECURITY_ALL WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @TaskType
			AND
			(	@IsPPMExec = 1
				OR
				ObjectId IN (SELECT TaskId FROM TASK_SECURITY WHERE PrincipalId = @UserId AND (IsRealTaskResource = 1 OR IsRealTaskManager = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @ToDoType
			AND
			(	(@IsPPMExec = 1 AND ObjectId IN (SELECT ToDoId FROM TODO WHERE ProjectId IS NOT NULL))
				OR
				ObjectId IN (SELECT ToDoId FROM TODO_SECURITY_ALL WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @IncidentType
			AND
			(	(@IsPPMExec = 1 AND ObjectId IN (SELECT IncidentId FROM INCIDENTS WHERE ProjectId IS NOT NULL))
				OR
				(@IsHDM = 1 AND ObjectId IN (SELECT IncidentId FROM INCIDENTS WHERE ProjectId IS NULL))
				OR
				ObjectId IN (SELECT IncidentId FROM INCIDENT_SECURITY_ALL WHERE PrincipalId = @UserId AND (IsRealIncidentResource = 1 OR IsRealIncidentManager = 1 OR IsCreator = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @DocumentType
			AND
			(	(@IsPPMExec = 1 AND ObjectId IN (SELECT DocumentId FROM DOCUMENTS WHERE ProjectId IS NOT NULL))
				OR
				ObjectId IN (SELECT DocumentId FROM DOCUMENT_SECURITY_ALL WHERE PrincipalId = @UserId AND (IsRealDocumentResource = 1 OR IsRealDocumentManager = 1))
			)
		)
		OR
		(	T.ObjectTypeId = @ListType
			AND
			ObjectId IN (SELECT ListId FROM LIST_SECURITY_ALL WHERE PrincipalId = @UserId AND AllowLevel > 0)
		)
	)
  ORDER BY E.Dt DESC
SET TRANSACTION ISOLATION LEVEL  READ COMMITTED
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventsGetByObject
	@ObjectId as int,
	@ObjectTypeId as int
as
SELECT E.SystemEventId, E.EventTypeId, E.ObjectId, E.ObjectTitle, E.RelObjectTitle,
	ISNULL(E.UserId, -1) AS UserId,
	E.Dt, T.ObjectTypeId, T.Title AS SystemEventTitle,
	ISNULL(T.RelObjectTypeId , -1) AS RelObjectTypeId, ISNULL(E.RelObjectId , -1) AS RelObjectId
  FROM SYSTEM_EVENTS E
	JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
  WHERE E.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectTypeId
  ORDER BY E.Dt DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventTypeGet
	@EventTypeId int
AS
SELECT EventTypeId, ParentId, ObjectTypeId, RelObjectTypeId, Title, IsActive
  FROM SYSTEM_EVENT_TYPES
  WHERE EventTypeId = @EventTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventTypeGetObjectType
	@EventTypeId int,
	@retval int output
AS
SELECT @retval = ObjectTypeId
  FROM SYSTEM_EVENT_TYPES
  WHERE EventTypeId = @EventTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].SystemEventTypeGetRelObjectType
	@EventTypeId int,
	@retval int output
AS
SELECT @retval = RelObjectTypeId
  FROM SYSTEM_EVENT_TYPES
  WHERE EventTypeId = @EventTypeId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskCheckSecurityByToDoResource
	@UserId int,
	@TaskId int,
	@retval int output
AS
IF EXISTS(SELECT * FROM TODO_RESOURCES
		 WHERE PrincipalId = @UserId
			AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
			AND ToDoId IN (SELECT ToDoId FROM TASK_TODO WHERE TaskId = @TaskId)
	)
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskCreate
	@ProjectId as int ,
	@CreatorId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext ,
	@CreationDate as datetime ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@Duration as int ,
	@PriorityId as int ,
	@IsMilestone as bit ,
	@ConstraintTypeId as int ,
	@ConstraintDate as datetime ,
	@ActivationTypeId int,
	@CompletionTypeId as int ,
	@MustBeConfirmed as bit,
	@PhaseId int,
	@TaskTime int,
	@retval int output
AS
DECLARE @TaskNum int
DECLARE @OutlineNumber varchar(255)
DECLARE @OutlineLevel int
IF (@PhaseId < 0)
	SET @PhaseId = NULL
BEGIN TRAN
	IF EXISTS(SELECT * FROM TASKS WHERE ProjectId = @ProjectId)
	BEGIN
		SELECT @TaskNum = TaskNum+1, @OutlineNumber = OutlineNumber, @OutlineLevel = OutlineLevel
		  FROM TASKS WITH (HOLDLOCK)
		   WHERE ProjectId = @ProjectId AND TaskNum =
			(SELECT MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId)
		SET @OutlineNumber = dbo.GetNextOutlineNum(@OutlineNumber, 1, @OutlineLevel)
	END
	ELSE BEGIN
		SET @TaskNum = 1
		SET @OutlineNumber = '1'
	END
	SET @OutlineLevel = 1
	INSERT INTO TASKS (ProjectId, CreatorId, Title, [Description], CreationDate, StartDate, FinishDate, Duration, PriorityId,
		IsMilestone, ConstraintTypeId, ConstraintDate, CompletionTypeId, TaskNum, OutlineNumber, OutlineLevel, MustBeConfirmed, ActivationTypeId, PhaseId, TaskTime)
	  VALUES(@ProjectId, @CreatorId, @Title, @Description, @CreationDate, @StartDate, @FinishDate, @Duration, @PriorityId,
		@IsMilestone, @ConstraintTypeId, @ConstraintDate, @CompletionTypeId, @TaskNum, @OutlineNumber, @OutlineLevel, @MustBeConfirmed, @ActivationTypeId, @PhaseId, @TaskTime)
	IF @@error != 0
		GOTO err
	SELECT @retval = @@identity
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskCreateFromExport
	@ProjectId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext ,
	@CreatorId as int ,
	@CreationDate as datetime ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@ActualFinishDate as datetime =null,
	@Duration as int ,
	@PriorityId as int ,
	@ConstraintTypeId as int ,
	@ActivationTypeId int,
	@CompletionTypeId as int ,
	@TaskNum as int,
	@IsMilestone as bit ,
	@IsSummary as bit ,
	@OutlineNumber as varchar(255),
	@OutlineLevel as int,
	@PercentCompleted as int,
	@ReasonId as int,
	@retval int output
AS
DECLARE @IsCompleted as bit
IF @PercentCompleted = 100
	SET @IsCompleted = 1
ELSE
	SET @IsCompleted = 0
INSERT INTO TASKS (ProjectId, Title, CreatorId, CreationDate, StartDate, FinishDate, Duration, PriorityId, ActivationTypeId,
	ConstraintTypeId, CompletionTypeId, TaskNum, IsMilestone, IsSummary, OutlineNumber, OutlineLevel, [Description], PercentCompleted, ReasonId, ActualFinishDate, IsCompleted, TaskTime)
  VALUES(@ProjectId, @Title, @CreatorId, @CreationDate, @StartDate, @FinishDate, @Duration, @PriorityId, @ActivationTypeId,
	@ConstraintTypeId, @CompletionTypeId, @TaskNum, @IsMilestone, @IsSummary, @OutlineNumber, @OutlineLevel, @Description, @PercentCompleted, @ReasonId, @ActualFinishDate, @IsCompleted, @Duration)
SELECT @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskDelete
	@UpdateId char(36),
	@TaskId as int
AS
DECLARE @TaskObjectType int
DECLARE @AfterTaskNum int
SET @TaskObjectType = 5
DECLARE @ProjectId INT, @OutlineNumber VarChar(255)
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber, @AfterTaskNum = TaskNum - 1 FROM TASKS WHERE TaskId = @TaskId
BEGIN TRAN
	DECLARE @AfterId INT
	SET @AfterId = -1
	DECLARE @DeletedTask TABLE (TaskId INT)
	DECLARE @DelCount INT
	INSERT INTO @DeletedTask (TaskId) SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND (OutlineNumber LIKE @OutlineNumber + '.%' OR TaskId = @TaskId)
	IF @@ERROR != 0
		GOTO err
	SELECT @DelCount = COUNT(*) FROM @DeletedTask
	SELECT @AfterId = TaskId FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = 1+ (SELECT MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId AND (OutlineNumber LIKE @OutlineNumber + '.%' OR TaskId = @TaskId))
	IF @@ERROR != 0
		GOTO err
	INSERT INTO TASK_UPDATES (UpdateId, TaskId) SELECT @UpdateId,SuccId FROM TASK_LINKS WHERE EXISTS(SELECT TaskId FROM @DeletedTask WHERE PredId = TaskId)
				   									 AND NOT EXISTS(SELECT TaskId FROM @DeletedTask WHERE SuccId = TaskId)
	Select * from TASK_UPDATES
	IF @@ERROR != 0
		GOTO err
	DELETE FROM TASK_LINKS WHERE EXISTS(SELECT TaskId FROM @DeletedTask WHERE PredId = TaskId)
			  OR EXISTS(SELECT TaskId FROM @DeletedTask WHERE SuccId = TaskId)
	IF @@ERROR != 0
		GOTO err
	UPDATE TASKS SET TaskNum = TaskNum - @DelCount WHERE ProjectId = @ProjectId AND TaskNum > @AfterTaskNum
	DECLARE @OutlineLevel INT
	SET @OutlineLevel = -1
	SELECT @OutlineLevel = OutlineLevel FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum
	UPDATE TASKS SET  IsSummary = 0 WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum
	DELETE FROM TASKS WHERE TaskId IN (SELECT TaskId FROM @DeletedTask)
	IF @@ERROR != 0
		GOTO err
	UPDATE TASKS SET  IsSummary = 1 WHERE ProjectId = @ProjectId AND TaskId IN
	(SELECT F.TaskId FROM TASKS F
	JOIN TASKS S ON (F.TaskNum +1 = S.TaskNum)
	WHERE @ProjectId = S.ProjectId AND @ProjectId = F.ProjectId AND F.OutlineLevel +1 = S.OutlineLevel)
	IF(@AfterId != -1)
		EXEC TaskRenumFrom @AfterId
		IF @@ERROR != 0
		GOTO err
	DELETE DISCUSSIONS WHERE ObjectTypeId = @TaskObjectType AND ObjectId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @TaskObjectType AND ObjectId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @TaskObjectType AND ObjectId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @TaskObjectType AND ObjectId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE TASK_RESOURCES WHERE TaskId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @TaskId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @TaskObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId = @TaskId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId = @TaskId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId = @TaskId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE TASK_LINKS  WHERE PredId = @TaskId OR SuccId = @TaskId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM TASKS  WHERE TaskId = @TaskId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskDeleteAll
			@ProjectId  INT
AS
DECLARE @TaskObjectType int
SET @TaskObjectType = 5
DELETE DISCUSSIONS WHERE ObjectTypeId = @TaskObjectType AND ObjectId IN
	(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE EXTERNAL_GATE WHERE ObjectTypeId = @TaskObjectType AND ObjectId IN
	(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @TaskObjectType AND ObjectId IN
	(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE TASK_RESOURCES WHERE TaskId IN
	(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE FAVORITES WHERE ObjectTypeId = @TaskObjectType AND ObjectId  IN
	(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE TASK_LINKS  WHERE
	PredId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId) OR
	 SuccId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
DELETE SUBSCRIPTIONS WHERE
	ObjectId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId) AND
	EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @TaskObjectType)
DELETE REMINDER_SUBSCRIPTIONS WHERE
	ObjectId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId) AND
	DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
DELETE DATE_TYPE_VALUES WHERE
	ObjectId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId) AND
	DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
DELETE DATE_TYPE_HOOKS WHERE
	ObjectId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId) AND
	DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TaskObjectType)
DELETE TASKS WHERE  ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskDeleteLinkToChild
			@TaskId INT
AS
DECLARE @ProjectId INT
DECLARE @ParetsChildTable TABLE(TaskId INT)
DECLARE @OutlineNumber VarChar(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
INSERT INTO @ParetsChildTable (TaskId) SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND
					(OutlineNumber LIKE @OutlineNumber + '.%' OR @OutlineNumber LIKE OutlineNumber + '.%' OR TaskId = @TaskId)
DELETE FROM TASK_LINKS WHERE  EXISTS (SELECT * FROM @ParetsChildTable WHERE  TaskId = SuccId) AND EXISTS (SELECT * FROM @ParetsChildTable WHERE  TaskId = PredId)
DELETE @ParetsChildTable
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGet
	@TaskId as int,
	@LanguageId as int
as
SELECT T.TaskId, T.TaskNum, T.ProjectId, P.Title AS ProjectTitle, P.ManagerId, T.CreatorId, T.CompletedBy, T.Title, T.[Description],
	T.CreationDate, T.StartDate, T.FinishDate, T.Duration, T.ActualFinishDate,
	T.PriorityId, PR.PriorityName, T.PercentCompleted, T.OutlineNumber, T.OutlineLevel,
	T.IsSummary, T.IsMilestone, T.ConstraintTypeId, CR.ConstraintTypeName, T.ConstraintDate, T.CompletionTypeId, CT.CompletionTypeName,
	T.IsCompleted, T.MustBeConfirmed, T.ReasonId, T.ActivationTypeId, T.StateId, T.ActivatedManually, A.ActivationTypeName, OS.StateName,
	T.PhaseId, PP.PhaseName, T.TaskTime
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (T.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN COMPLETION_TYPE_LANGUAGE CT ON (T.CompletionTypeId = CT.CompletionTypeId AND CT.LanguageId = @LanguageId)
	JOIN CONSTRAINT_TYPE_LANGUAGE CR ON (T.ConstraintTypeId = CR.ConstraintTypeId AND CR.LanguageId = @LanguageId)
	JOIN ACTIVATION_TYPE_LANGUAGE A ON (T.ActivationTypeId = A.ActivationTypeId AND A.LanguageId = @LanguageId)
	JOIN OBJECT_STATE_LANGUAGE OS ON (T.StateId = OS.StateId AND OS.LanguageId = @LanguageId)
	LEFT JOIN PROJECT_PHASES PP ON (T.PhaseId = PP.PhaseId)
  WHERE T.TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetAllChild
			@TaskId INT AS
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255)
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @TaskId
SELECT TaskId, IsCompleted, ReasonId FROM Tasks WHERE OutlineNumber LIKE @OutlineNumber+'.%'  AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetAllDependentTasks
			@TaskId INT
AS
DECLARE @ProjectId INT
DECLARE @Table TABLE( TASKID INT PRIMARY KEY)
DECLARE @Table2 TABLE( TASKID INT PRIMARY KEY)
DECLARE @Table3 TABLE( TASKID INT PRIMARY KEY, OutlineNumber varchar(255) COLLATE database_default)
SELECT @ProjectId = ProjectId FROM TASKS WHERE TaskId =@TaskId
INSERT INTO @Table2
	SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND OutlineNumber LIKE  (SELECT TOP 1 OutlineNumber FROM TASKS WHERE TaskId = @TaskId) +'.%'
	UNION
	SELECT SuccId FROM TASK_LINKS WHERE PredId = @TaskId
WHILE(EXISTS(SELECT TaskId FROM @Table2  WHERE TaskId NOT IN (SELECT TaskId FROM @Table )))
BEGIN
	INSERT INTO @Table SELECT TaskId FROM @Table2   WHERE TaskId NOT IN (SELECT TaskId FROM @Table)
	DELETE FROM @Table3
	INSERT INTO @Table3 SELECT t2.TaskId, t3.OutlineNumber FROM @Table2 t2 JOIN  TASKS t3 ON t2.TaskId = t3.TaskId
	DELETE FROM @Table2
	INSERT INTO @Table2
		SELECT t1.TaskId  FROM Tasks t1, @Table3 t3 WHERE t1.ProjectId = @ProjectId AND  t1.OutlineNumber Like t3.OutlineNumber+'.%'
		UNION
		SELECT SuccId FROM TASK_LINKS WHERE PredId  IN (SELECT TaskId FROM @Table3)
END
SELECT TaskId From @Table
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetAllDependOnTasks
			@TaskId INT
AS
DECLARE @ProjectId INT
DECLARE @Table TABLE( TASKID INT PRIMARY KEY)
DECLARE @Table2 TABLE( TASKID INT PRIMARY KEY)
DECLARE @Table3 TABLE( TASKID INT PRIMARY KEY, OutlineNumber varchar(255) COLLATE database_default)
SELECT @ProjectId = ProjectId FROM TASKS WHERE TaskId =@TaskId
INSERT INTO @Table2
	SELECT TaskId FROM TASKS WHERE IsSummary = 1 AND ProjectId = @ProjectId AND  (SELECT TOP 1 OutlineNumber FROM TASKS WHERE TaskId = @TaskId)  LIKE OutlineNumber +'.%'
	UNION
	SELECT PredId FROM TASK_LINKS WHERE SuccId = @TaskId
WHILE(EXISTS(SELECT TaskId FROM @Table2  WHERE TaskId NOT IN (SELECT TaskId FROM @Table )))
BEGIN
	INSERT INTO @Table SELECT TaskId FROM @Table2   WHERE TaskId NOT IN (SELECT TaskId FROM @Table)
	DELETE FROM @Table3
	INSERT INTO @Table3 SELECT t2.TaskId, t3.OutlineNumber FROM @Table2 t2 JOIN  TASKS t3 ON t2.TaskId = t3.TaskId
	DELETE FROM @Table2
	INSERT INTO @Table2
		SELECT t1.TaskId  FROM Tasks t1, @Table3 t3 WHERE t1.ProjectId = @ProjectId AND t3.OutlineNumber Like t1.OutlineNumber + '.%'
		UNION
		SELECT PredId FROM TASK_LINKS WHERE SuccId  IN (SELECT TaskId FROM @Table3)
END
SELECT TaskId From @Table
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetAllParents
			@TaskId INT
AS
SELECT TaskId FROM TASKS WHERE IsSummary = 1 AND  (SELECT OutlineNumber FROM TASKS WHERE TaskId = @TaskId) LIKE OutlineNumber + '.%'  ORDER BY TaskNum
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetBranch
			@TaskId INT AS
SELECT TaskId FROM Tasks WHERE OutlineNumber LIKE (SELECT OutlineNumber FROM Tasks WHERE TaskId = @TaskId)+'%'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetChild
			@TaskId INT AS
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255), @OutlineLevel INT
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber, @OutlineLevel =OutlineLevel FROM TASKS WHERE TaskId = @TaskId
SELECT TaskId
  FROM Tasks
  WHERE OutlineNumber LIKE @OutlineNumber+'.%'  AND ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel +1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetChildrenInfo
	@TaskId INT
AS
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255), @OutlineLevel INT
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber, @OutlineLevel =OutlineLevel FROM TASKS WHERE TaskId = @TaskId
SELECT TaskId, CreatorId, CompletedBy, Title, [Description],
	CreationDate, StartDate, FinishDate, Duration, ActualFinishDate,
	PercentCompleted, IsSummary, IsMilestone, IsCompleted, CompletionTypeId, ReasonId, StateId
  FROM Tasks
  WHERE OutlineNumber LIKE @OutlineNumber+'.%'  AND ProjectId = @ProjectId AND OutlineLevel = @OutlineLevel +1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetDependOnTasks
			@TaskId INT
	 AS
	SELECT TaskId FROM TASKS WHERE IsSummary = 1 AND   (SELECT TOP 1 TaskNum FROM TASKS WHERE TaskId = @TaskId)  LIKE TaskNum +'.%'
	UNION
	SELECT PredId FROM TASK_LINKS WHERE SuccId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetInUTC
	@TaskId as int,
	@LanguageId as int
as
SELECT T.TaskId, T.TaskNum, T.ProjectId, P.Title AS ProjectTitle, P.ManagerId, T.CreatorId, T.CompletedBy, T.Title, T.[Description],
	T.CreationDate, 	T.StartDate, T.FinishDate,
	T.Duration, T.ActualFinishDate,
	T.PriorityId, PR.PriorityName, T.PercentCompleted, T.OutlineNumber, T.OutlineLevel,
	T.IsSummary, T.IsMilestone,
	T.ConstraintTypeId, CR.ConstraintTypeName, T.ConstraintDate,
	T.CompletionTypeId, CT.CompletionTypeName, T.IsCompleted, T.MustBeConfirmed, T.ReasonId, T.StateId
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	JOIN PRIORITY_LANGUAGE PR ON (T.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN COMPLETION_TYPE_LANGUAGE CT ON (T.CompletionTypeId = CT.CompletionTypeId AND CT.LanguageId = @LanguageId)
	JOIN CONSTRAINT_TYPE_LANGUAGE CR ON (T.ConstraintTypeId = CR.ConstraintTypeId AND CR.LanguageId = @LanguageId)
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetIsCompleted
	@TaskId as int,
	@retval int output
as
IF EXISTS(SELECT * FROM TASKS WHERE TaskId = @TaskId AND IsCompleted = 0)
	SET @retval = 0
ELSE
	SET @retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetMaxFinishDateOfChild
			@TaskId INT,
			@retval DATETIME OUTPUT
AS
SET @retval = null
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
SELECT @retval = MAX(FinishDate) FROM Tasks WHERE OutlineNumber LIKE @OutlineNumber+'.%' AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetMinPossibleStartDate
			@TaskId INT,
			@CalendarId INT,
			@retval Datetime output
AS
SET @retval = null
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
SELECT @retval = MAX( CASE
			WHEN TL.Lag >= 0 THEN dbo.GetFinishDateByDuration(@CalendarId,T.FinishDate,TL.Lag)
			WHEN TL.Lag < 0 THEN dbo.GetStartDateByDuration(@CalendarId,T.FinishDate, -TL.Lag)
			    END)
  FROM TASKS T JOIN TASK_LINKS TL ON (T.TaskId = TL.PredId)
  WHERE 	T.ProjectId = @ProjectId
		AND TL.SuccId  IN (SELECT TaskId FROM TASKS WHERE ProjectId= @ProjectId AND (TaskId = @TaskId OR @OutlineNumber LIKE  OutlineNumber + '.%' ))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetMinStartDateOfChild
			@TaskId INT,
			@retval DATETIME OUTPUT
AS
SET @retval = null
DECLARE @ProjectId INT, @OutlineNumber VARCHAR(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
SELECT @retval = MIN(StartDate) FROM Tasks WHERE OutlineNumber LIKE @OutlineNumber+'.%' AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetParent
	@TaskId INT,
	@RetVal INT OUTPUT
AS
DECLARE @ProjectId INT
DECLARE @OutlineLevel INT
DECLARE @OutlineNumber VARCHAR(255)
SELECT @ProjectId = ProjectId,  @OutlineNumber = OutlineNumber, @OutlineLevel = OutlineLevel
  FROM TASKS
  WHERE TaskId = @TaskId
Set @RetVal = -1
SELECT @RetVal = TaskId
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 1 AND OutlineLevel = @OutlineLevel - 1AND @OutlineNumber LIKE OutlineNumber + '.%'
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetPredecessorDates
			@TaskId INT,
			@CalendarId INT
AS
SELECT LinkId, PredId, FinishDate, Lag, CASE
	when lag >= 0 then DBO.GetFinishDateByDuration(@CalendarId,FinishDate,Lag)
	when lag < 0 then DBO.GetStartDateByDuration(@CalendarId,FinishDate,-Lag)
END As PossibleStartDate FROM  TASK_LINKS JOIN TASKS ON PredId = TaskId
WHERE SuccId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetPredecessorsDetails
	@TaskId as int
AS
SELECT TL.LinkId, TL.PredId AS TaskId, T.TaskNum, T.Title, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.Duration, T.PriorityId, T.PercentCompleted, T.OutlineNumber, T.OutlineLevel, T.IsCompleted, TL.Lag, T.StateId
  FROM TASK_LINKS TL
	JOIN TASKS T ON (TL.PredId = T.TaskId)
  WHERE TL.SuccId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetProject
	@TaskId as int,
	@Retval as int output
AS
SELECT @Retval = ProjectId FROM TASKS WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetSecurityForUser
	@TaskId as int,
	@UserId as int
as
SELECT TaskId, PrincipalId, IsResource, IsManager, IsRealTaskResource
   FROM TASK_SECURITY
  WHERE TaskId = @TaskId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetSuccessors
	@TaskId INT
AS
SELECT SuccId as TaskId  FROM TASK_LINKS WHERE PredId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetSuccessorsDetails
	@TaskId as int
AS
SELECT TL.LinkId, TL.SuccId AS TaskId, T.TaskNum, T.Title, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.Duration, T.PriorityId, T.PercentCompleted, T.OutlineNumber, T.OutlineLevel, T.IsCompleted, TL.Lag, T.StateId
  FROM TASK_LINKS TL
	JOIN TASKS T ON (TL.SuccId = T.TaskId)
  WHERE TL.PredId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetVacantPredecessors
			@TaskId INT
AS
DECLARE @ProjectId INT
DECLARE @ShareTable TABLE(TaskId INT)
DECLARE @ParetsChildTable TABLE(TaskId INT)
DECLARE @SuccTable TABLE(TaskId INT, OutlineNumber varchar(255) COLLATE database_default)
DECLARE @OutlineNumber VarChar(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
INSERT INTO @ParetsChildTable (TaskId) SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND
					(OutlineNumber LIKE @OutlineNumber + '.%' OR @OutlineNumber LIKE OutlineNumber + '.%' OR TaskId = @TaskId)
WHILE(EXISTS(SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)))
BEGIN
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @ParetsChildTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @ShareTable)
WHILE EXISTS (SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @SuccTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @SuccTable))
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @SuccTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @SuccTable)
DELETE @ParetsChildTable
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @SuccTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @ParetsChildTable (TaskId) SELECT DISTINCT T.TaskId FROM TASKS T, @SuccTable PT  WHERE T.ProjectId = @ProjectId AND
					(T.OutlineNumber LIKE PT.OutlineNumber + '.%' OR PT.OutlineNumber LIKE T.OutlineNumber + '.%')
					AND T.TaskId NOT IN (SELECT TaskId FROM @ShareTable)
DELETE @SuccTable
END
INSERT INTO @ShareTable (TaskId) SELECT PredId FROM TASK_LINKS TL WHERE SuccId = @TaskId AND PredId NOT IN  (SELECT TaskId FROM @ShareTable)
SELECT TaskId, TaskNum, Title FROM TASKS WHERE  ProjectId = @ProjectId AND TaskId NOT IN (SELECT TaskId FROM @ShareTable)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskGetVacantSuccessors
			@TaskId INT
AS
DECLARE @ProjectId INT
DECLARE @ShareTable TABLE(TaskId INT)
DECLARE @ParetsChildTable TABLE(TaskId INT)
DECLARE @SuccTable TABLE(TaskId INT, OutlineNumber varchar(255) COLLATE database_default)
DECLARE @OutlineNumber VarChar(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
INSERT INTO @ParetsChildTable (TaskId) SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND
					(OutlineNumber LIKE @OutlineNumber + '.%' OR @OutlineNumber LIKE OutlineNumber + '.%' OR TaskId = @TaskId)
WHILE(EXISTS(SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)))
BEGIN
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT TL.PredId, PT.OutlineNumber FROM TASK_LINKS TL JOIN TASKS PT ON TL.PredId = PT.TaskId
				WHERE TL.SuccId IN (SELECT TaskId FROM @ParetsChildTable) AND TL.PredId NOT IN (SELECT TaskId FROM @ShareTable)
WHILE (EXISTS(SELECT TL.PredId, PT.OutlineNumber FROM TASK_LINKS TL JOIN TASKS PT ON TL.PredId = PT.TaskId
				WHERE TL.SuccId IN (SELECT TaskId FROM @SuccTable) AND TL.PredId NOT IN (SELECT TaskId FROM @SuccTable)) )
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT TL.PredId, PT.OutlineNumber FROM TASK_LINKS TL JOIN TASKS PT ON TL.PredId = PT.TaskId
				WHERE TL.SuccId IN (SELECT TaskId FROM @SuccTable) AND TL.PredId NOT IN (SELECT TaskId FROM @SuccTable)
DELETE @ParetsChildTable
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @SuccTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @ParetsChildTable (TaskId) SELECT DISTINCT T.TaskId FROM TASKS T, @SuccTable PT  WHERE T.ProjectId = @ProjectId AND
					(T.OutlineNumber LIKE PT.OutlineNumber + '.%' OR PT.OutlineNumber LIKE T.OutlineNumber + '.%')
					AND T.TaskId NOT IN (SELECT TaskId FROM @ShareTable)
DELETE @SuccTable
END
INSERT INTO @ShareTable (TaskId) SELECT SuccId FROM TASK_LINKS  WHERE PredId = @TaskId AND SuccId NOT IN (SELECT TaskId FROM @ShareTable)
SELECT TaskId, TaskNum, Title FROM TASKS WHERE  ProjectId = @ProjectId AND TaskId NOT IN (SELECT TaskId FROM @ShareTable)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskInAllChild
			@TaskId INT,
			@ChildTaskId INT,
			@retval int OUTPUT
AS
IF(EXISTS(SELECT TaskId FROM Tasks WHERE TaskId = @ChildTaskId AND OutlineNumber LIKE (SELECT OutlineNumber FROM Tasks WHERE TaskId = @TaskId)+'.%') )
SET @retval = 1
ELSE
SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskInAllDependOnTasks
			@TaskId INT,
			@DepTaskId INT,
			@retVal int output
AS
DECLARE @ProjectId INT
DECLARE @ShareTable TABLE(TaskId INT)
DECLARE @ParetsChildTable TABLE(TaskId INT)
DECLARE @SuccTable TABLE(TaskId INT, OutlineNumber varchar(255) COLLATE database_default)
DECLARE @OutlineNumber VarChar(255)
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
INSERT INTO @ParetsChildTable (TaskId) SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND
					(OutlineNumber LIKE @OutlineNumber + '.%' OR @OutlineNumber LIKE OutlineNumber + '.%' OR TaskId = @TaskId)
WHILE(EXISTS(SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)))
BEGIN
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @ParetsChildTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @ParetsChildTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @ShareTable)
WHILE EXISTS (SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @SuccTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @SuccTable))
INSERT INTO @SuccTable (TaskId,OutlineNumber) SELECT SuccId, OutlineNumber FROM TASK_LINKS TL JOIN TASKS T ON TL.SuccId = T.TaskId
				WHERE TL.PredId IN (SELECT TaskId FROM @SuccTable) AND TL.SuccId NOT IN (SELECT TaskId FROM @SuccTable)
DELETE @ParetsChildTable
INSERT INTO @ShareTable (TaskId) SELECT TaskId FROM @SuccTable WHERE TaskId NOT IN (SELECT TaskId FROM @ShareTable)
INSERT INTO @ParetsChildTable (TaskId) SELECT DISTINCT T.TaskId FROM TASKS T, @SuccTable PT  WHERE T.ProjectId = @ProjectId AND
					(T.OutlineNumber LIKE PT.OutlineNumber + '.%' OR PT.OutlineNumber LIKE T.OutlineNumber + '.%')
					AND T.TaskId NOT IN (SELECT TaskId FROM @ShareTable)
DELETE @SuccTable
END
INSERT INTO @ShareTable (TaskId) SELECT PredId FROM TASK_LINKS TL WHERE SuccId = @TaskId AND PredId NOT IN  (SELECT TaskId FROM @ShareTable)
IF(EXISTS(SELECT * FROM @ShareTable WHERE TaskId = @DepTaskId))
	SET @retVal = 1
ELSE
	SET @retVal = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskInsert
	@ProjectId as int ,
	@BeforeTaskId As INT,
	@CreatorId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext ,
	@CreationDate as datetime ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@Duration as int ,
	@PriorityId as int ,
	@IsMilestone as bit ,
	@ConstraintTypeId as int ,
	@ConstraintDate as datetime ,
	@ActivationTypeId int,
	@CompletionTypeId as int ,
	@MustBeConfirmed as bit,
	@PhaseId int,
	@TaskTime int,
	@retval int output
AS
DECLARE @TaskNum int
DECLARE @OutlineNumber varchar(255)
DECLARE @OutlineLevel int
DECLARE @MaxTaskNum INT
DECLARE @AfterTaskNum  INT
IF @PhaseId < 0
	SET @PhaseId = NULL
BEGIN TRAN
	SELECT @MaxTaskNum = MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId
	SET @AfterTaskNum = 0
	SELECT  @AfterTaskNum = TaskNum FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum + 1 = ( SELECT TaskNum FROM TASKS WHERE   ProjectId = @ProjectId  AND TaskId = @BeforeTaskId)
	IF(@AfterTaskNum > @MaxTaskNum)
		GOTO err
	SET @TaskNum = @AfterTaskNum +1
	IF(@AfterTaskNum = 0)
	BEGIN
		SET @OutlineLevel = 1
		SET @OutlineNumber = '1'
	END
	ELSE
	BEGIN
		SELECT @OutlineLevel = OutlineLevel FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum
		IF(EXISTS(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum AND IsSummary = 1))
			SET @OutlineLevel = @OutlineLevel+1
		SET @OutlineNumber = '0'
	END
	UPDATE TASKS SET TaskNum = TaskNum +1 WHERE ProjectId = @ProjectId AND TaskNum > @AfterTaskNum
	INSERT INTO TASKS (ProjectId, CreatorId, Title, [Description], CreationDate, StartDate, FinishDate, Duration, PriorityId,
		IsMilestone, ConstraintTypeId, ConstraintDate, CompletionTypeId, TaskNum, OutlineNumber, OutlineLevel, MustBeConfirmed, ActivationTypeId, PhaseId, TaskTime )
	  VALUES(@ProjectId, @CreatorId, @Title, @Description, @CreationDate, @StartDate, @FinishDate, @Duration, @PriorityId,
		@IsMilestone, @ConstraintTypeId, @ConstraintDate, @CompletionTypeId, @TaskNum, @OutlineNumber, @OutlineLevel, @MustBeConfirmed, @ActivationTypeId, @PhaseId, @TaskTime )
	IF @@error != 0
		GOTO err
	SELECT @retval = @@identity
	EXEC TaskRenumFrom @retval
COMMIT TRAN
RETURN
err:
	RAISERROR('UNABLE INSERT ',16,1)
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskInsertTo
	@ProjectId as int ,
	@FromTaskId As INT,
	@Place As tinyint,
	@CreatorId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext ,
	@CreationDate as datetime ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@Duration as int ,
	@PriorityId as int ,
	@IsMilestone as bit ,
	@ConstraintTypeId as int ,
	@ConstraintDate as datetime ,
	@ActivationTypeId int,
	@CompletionTypeId as int ,
	@MustBeConfirmed as bit,
	@PhaseId int,
	@TaskTime int,
	@retval int output
AS
DECLARE @TaskNum int
DECLARE @LastChildNum int
DECLARE @OutlineNumber varchar(255)
DECLARE @OutlineLevel int
BEGIN TRAN
		SELECT @OutlineLevel = OutlineLevel, @TaskNum = TaskNum, @OutlineNumber =  OutlineNumber  FROM TASKS WHERE ProjectId = @ProjectId and  @FromTaskId = TaskId
		SELECT @LastChildNum = MAX(TaskNum) FROM TASKS WHERE (OutlineNumber LIKE @OutlineNumber +'.%' OR @FromTaskId = TaskId) AND  ProjectId = @ProjectId
		SET @OutlineNumber = '0'
		IF (@Place  =1)
		BEGIN
			IF(@TaskNum = 1)
				SET @OutlineNumber = '1'
		END
		ELSE
		IF (@Place  = 2)
		BEGIN
			SET @TaskNum = @LastChildNum + 1
		END
		ELSE
		IF (@Place  = 3)
		BEGIN
			SET @OutlineLevel = @OutlineLevel +1
			SET @TaskNum = @TaskNum + 1
			UPDATE TASKS SET IsSummary  = 1 WHERE ProjectId = @ProjectId AND @FromTaskId = TaskId
		END
		ELSE
		IF (@Place  = 4)
		BEGIN
			SET @OutlineLevel = @OutlineLevel +1
			SET @TaskNum = @LastChildNum + 1
			UPDATE TASKS SET IsSummary  = 1 WHERE ProjectId = @ProjectId AND @FromTaskId = TaskId
		END
		ELSE
			RETURN
	UPDATE TASKS SET TaskNum = TaskNum +1 WHERE ProjectId = @ProjectId AND TaskNum >= @TaskNum
	INSERT INTO TASKS (ProjectId, CreatorId, Title, [Description], CreationDate, StartDate, FinishDate, Duration, PriorityId,
		IsMilestone, ConstraintTypeId, ConstraintDate, CompletionTypeId, TaskNum, OutlineNumber, OutlineLevel, MustBeConfirmed, ActivationTypeId, PhaseId, TaskTime)
	  VALUES(@ProjectId, @CreatorId, @Title, @Description, @CreationDate, @StartDate, @FinishDate, @Duration, @PriorityId,
		@IsMilestone, @ConstraintTypeId, @ConstraintDate, @CompletionTypeId, @TaskNum, @OutlineNumber, @OutlineLevel, @MustBeConfirmed, @ActivationTypeId, @PhaseId, @TaskTime)
	IF @@error != 0
		GOTO err
	SELECT @retval = @@identity
	EXEC TaskRenumFrom @retval
COMMIT TRAN
RETURN
err:
	RAISERROR('UNABLE INSERT ',16,1)
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinkCreate
	@PredId as int ,
	@SuccId as int ,
	@Lag as int ,
	@retval int output
as
INSERT INTO TASK_LINKS (PredId, SuccId, Lag)
  VALUES(@PredId, @SuccId, @Lag)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinkDelete
	@LinkId as int,
	@retval int output
AS
SELECT @retval = SuccId FROM TASK_LINKS WHERE LinkId = @LinkId
DELETE FROM TASK_LINKS  WHERE LinkId = @LinkId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinkDeleteByPredSucc
	@PredId as int,
	@SuccId as int
AS
DELETE FROM TASK_LINKS  WHERE PredId = @PredId AND SuccId = @SuccId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinkGet
	@LinkId as int
as
SELECT LinkId, PredId, SuccId, Lag
  FROM TASK_LINKS
  WHERE LinkId = @LinkId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinksGetByProject
	@ProjectId as int
as
SELECT LinkId, PredId, SuccId, Lag
  FROM TASK_LINKS
  WHERE PredId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskLinkUpdate
	@LinkId as int ,
	@Lag as int,
	@retval int output
as
SELECT @retval = SuccId FROM TASK_LINKS WHERE LinkId = @LinkId
UPDATE TASK_LINKS
  SET Lag=@Lag
  WHERE LinkId = @LinkId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskMoveLeft
			@TaskId INT,
			@retval INT OUTPUT
AS
DECLARE @ProjectId  INT
DECLARE @OutlineNumber VarChar(255)
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @TaskId
DECLARE @SummaryId INT
SET @SummaryId = -1
SET @retval = -1
IF(EXISTS(SELECT TaskId FROM TASKS WHERE TaskId = @TaskId AND OutlineLevel > 1))
BEGIN
	UPDATE TASKS SET IsSummary = 1, @SummaryId  = TaskId WHERE TaskId IN (SELECT TOP 1 T.TaskId FROM TASKS T JOIN TASKS NT ON NT.TaskNum =T.TaskNum + 1 AND T.ProjectId = NT.ProjectId
		WHERE T.TaskId = @TaskId AND NT.OutlineLevel = T.OutlineLevel)
	UPDATE TASKS SET IsSummary = 0, @retval = TaskId WHERE TaskId IN (SELECT TOP 1 PT.TaskId FROM TASKS T JOIN TASKS PT ON PT.TaskNum =T.TaskNum-1 AND T.ProjectId = PT.ProjectId
		WHERE T.TaskId = @TaskId AND PT.IsSummary = 1 )
	UPDATE TASKS SET OutlineLevel = OutlineLevel - 1 WHERE TaskId = @TaskId OR (ProjectId = @ProjectId AND OutlineNumber LIKE @OutlineNumber+'.%')
	EXEC TaskRenumFrom @TaskId
	IF(@SummaryId <> -1)
		EXEC TaskDeleteLinkToChild @SummaryId
END
ELSE
RAISERROR('UNABLE MOVE LEFT',16,1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskMoveRight
			@TaskID INT,
			@retval INT OUTPUT
 AS
DECLARE @ProjectId  INT
DECLARE @OutlineNumber VarChar(255)
SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @TaskId
SET @retval = -2
IF(EXISTS( SELECT PT. TaskId FROM TASKS T JOIN TASKS PT ON PT.TaskNum =T.TaskNum-1 AND T.ProjectId = PT.ProjectId
		WHERE T.TaskId = @TaskId AND PT.OutlineLevel >= T.OutlineLevel AND PT.IsMileStone= 0))
BEGIN
	SET @retval = -1
	UPDATE TASKS SET IsSummary = 1, @retval = TaskId WHERE TaskId IN (SELECT TOP 1 PT.TaskId FROM TASKS T JOIN TASKS PT ON PT.TaskNum =T.TaskNum-1 AND T.ProjectId = PT.ProjectId
		WHERE T.TaskId = @TaskId AND PT.OutlineLevel = T.OutlineLevel)
	UPDATE TASKS SET OutlineLevel = OutlineLevel +1 WHERE  TaskId = @TaskId OR (ProjectId = @ProjectId AND OutlineNumber LIKE @OutlineNumber + '.%')
	EXEC TaskRenumFrom @TaskId
		EXEC TaskDeleteLinkToChild @TaskId
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskMoveTo
			@TaskId INT,
			@AfterTaskNum INT,
			 @retval INT output
AS
DECLARE @FromTaskNum INT, @ToTaskNum INT, @MaxTaskNum INT, @OldOutlineLevel INT, @NewOutlineLevel INT, @ProjectId INT
SELECT @OldOutlineLevel = T.OutlineLevel, @FromTaskNum = T.TaskNum,  @ProjectId = T.ProjectId FROM TASKS T  WHERE T.TaskId = @TaskId
SELECT @MaxTaskNum = MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId
SELECT @ToTaskNum = MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId AND OutlineNumber LIKE
	(SELECT OutlineNumber FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @FromTaskNum)+'%'
IF(@AfterTaskNum = 0)
	SET @NewOutlineLevel = 1
ELSE
BEGIN
	SELECT @NewOutlineLevel = OutlineLevel FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum
	IF(EXISTS(SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @AfterTaskNum AND IsSummary = 1))
		SET @NewOutlineLevel = @NewOutlineLevel+1
END
IF(NOT EXISTS(SELECT TaskID FROM TASKS WHERE TaskNum = @ToTaskNum + 1 AND ProjectId = @ProjectId AND OutlineLevel = @OldOutlineLevel))
	UPDATE TASKS SET IsSummary = 0, @retval = TaskId WHERE TaskNum = @FromTaskNum - 1 AND ProjectId = @ProjectId AND OutlineLevel < @OldOutlineLevel
IF(@AfterTaskNum + 1 < @FromTaskNum)
BEGIN
	UPDATE TASKS SET
		TaskNum = CASE
			WHEN (TaskNum > @AfterTaskNum AND TaskNum < @FromTaskNum) THEN (TaskNum + (@ToTaskNum - @FromTaskNum +1))
			WHEN (TaskNum >= @FromTaskNum AND TaskNum <= @ToTaskNum)  THEN (TaskNum - (@FromTaskNum - @AfterTaskNum - 1))
			ELSE TaskNum
		END,
		OutLineLevel = CASE
			WHEN (TaskNum >= @FromTaskNum AND TaskNum <= @ToTaskNum) THEN OutLineLevel + (@NewOutlineLevel - @OldOutlineLevel)
			ELSE OutLineLevel
		END
	WHERE ProjectId = @ProjectId
END
ELSE
IF(@AfterTaskNum > @ToTaskNum AND @AfterTaskNum <=@MaxTaskNum)
BEGIN
UPDATE TASKS SET
		TaskNum = CASE
			WHEN (TaskNum > @ToTaskNum AND TaskNum <= @AfterTaskNum) THEN TaskNum - (@ToTaskNum - @FromTaskNum +1)
			WHEN (TaskNum >= @FromTaskNum AND TaskNum <= @ToTaskNum)  THEN TaskNum + (@AfterTaskNum - @ToTaskNum)
			ELSE TaskNum
		END,
		OutLineLevel = CASE
			WHEN (TaskNum >= @FromTaskNum AND TaskNum <= @ToTaskNum) THEN OutLineLevel + (@NewOutlineLevel - @OldOutlineLevel)
			ELSE OutLineLevel
		END
	WHERE ProjectId = @ProjectId
END
ELSE
BEGIN
RAISERROR('test',16,1)
END
DECLARE @TaskIdRenum INT
SELECT @TaskIdRenum = TaskId FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = 1
EXEC TaskRenumFrom @TaskIdRenum
EXEC TaskDeleteLinkToChild @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskRecalculateState
	@TaskId INT,
	@DateNow DATETIME
 AS
DECLARE @StateId INT
DECLARE @NewStateId INT
DECLARE @ActivationTypeId INT
DECLARE @ActivatedManually INT
DECLARE @ReasonId INT
DECLARE @IsCompleted INT
DECLARE @IsExistUncompletedPred INT
DECLARE @StartDate DATETIME
DECLARE @FinishDate DATETIME
SELECT @IsExistUncompletedPred = count(*) FROM TASKS PT JOIN TASK_LINKS L ON L.PredId = PT.TaskId
	WHERE L.SuccId = @TaskId AND PT.StateId < 4
SELECT @IsCompleted = [IsCompleted],
	@ReasonId = [ReasonId],
	@ActivatedManually = [ActivatedManually],
	@ActivationTypeId = [ActivationTypeId],
	@StartDate = [StartDate],
	@FinishDate = [FinishDate],
	@StateId = [StateId]
FROM [TASKS]
WHERE [TaskId] = @TaskId
SET @NewStateId = 1
IF @IsCompleted = 1
BEGIN
	IF @ReasonId = 1  OR @ReasonId = 2 /*completed auto*/
	   SET @NewStateId = 5
	IF @ReasonId = 3  OR @ReasonId = 4 /*suspended auto*/
	   SET @NewStateId = 4
END
ELSE
BEGIN
	IF @ActivatedManually = 1
	   SET @NewStateId = 2
	ELSE
	BEGIN
		IF @ActivationTypeId = 1
		BEGIN
			IF @StartDate < @DateNow AND @IsExistUncompletedPred = 0
			SET @NewStateId = 2
		END
		ELSE
		IF @ActivationTypeId = 2
		BEGIN
			IF @StartDate < @DateNow
			  SET @NewStateId = 2
		END
	END
	IF @NewStateId = 2 AND @FinishDate < @DateNow
		SET @NewStateId = 3
END
UPDATE [TASKS]
SET  [StateId]= @NewStateId
WHERE [TaskId]= @TaskId AND @StateId != @NewStateId
SELECT @StateId As OldStateId, @NewStateId as NewStateId, @StartDate AS StartDate, @FinishDate AS FinishDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskRecalculateSummaryPercent
			@TaskId INT
AS
DECLARE @Dt datetime
SET @Dt = getutcdate()
DECLARE @OutlineNumber VarChar(255)
DECLARE @ProjectId INT
SELECT @OutlineNumber = OutlineNumber, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
DECLARE SummaryCursor CURSOR FOR SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId AND IsSummary = 1 AND (@OutlineNumber LIKE OutlineNumber + '.%' OR @TaskId = TaskId) ORDER BY TaskNum DESC
DECLARE @reOutlineNumber VarChar(255)
DECLARE @reTaskId INT, @reOutlineLevel INT
OPEN SummaryCursor
FETCH NEXT FROM SummaryCursor INTO @reTaskId
WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @reOutlineNumber = OutlineNumber, @reOutlineLevel = OutlineLevel FROM TASKS WHERE TaskId = @reTaskId
	UPDATE TASKS SET PercentCompleted =
		(SELECT AVG(PercentCompleted) FROM TASKS WHERE OutlineNumber LIKE @reOutlineNumber + '.%'  AND OutlineLevel = @reOutlineLevel +1 AND ProjectId = @ProjectId)
	  WHERE TaskId = @reTaskId
 	IF NOT EXISTS(SELECT * FROM TASKS WHERE IsCompleted = 0 AND OutlineNumber LIKE @reOutlineNumber + '.%'  AND OutlineLevel = @reOutlineLevel +1 AND ProjectId = @ProjectId)
		UPDATE TASKS SET IsCompleted = 1, ActualFinishDate = @Dt
		  WHERE TaskId = @reTaskId
	ELSE
		UPDATE TASKS SET IsCompleted = 0, ActualFinishDate = null
		  WHERE TaskId = @reTaskId
   FETCH NEXT FROM SummaryCursor INTO @reTaskId
END
CLOSE SummaryCursor
DEALLOCATE SummaryCursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskRenumFrom
			@TaskId INT
AS
	DECLARE @ProjectId INT, @TaskNum INT
	SELECT @TaskNum = TaskNum, @ProjectId = ProjectId FROM TASKS WHERE TaskId = @TaskId
	DECLARE task_cur CURSOR LOCAL FOR SELECT OutLineLevel FROM tasks WHERE TaskNum >= @TaskNum  AND ProjectId = @ProjectId order by TaskNum
	DECLARE @PREV_NUM VARCHAR(255), @PREV_LEVEL INT, @CUR_LEVEL INT
	SET @PREV_NUM = '0'
	SET @PREV_LEVEL = 1
	SELECT @PREV_NUM = OutlineNumber, @PREV_LEVEL  = OutlineLevel FROM TASKS WHERE TaskNum = @TaskNum - 1 AND ProjectId = @ProjectId
	OPEN TASK_CUR
	FETCH NEXT FROM TASK_CUR INTO @CUR_LEVEL
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET  @PREV_NUM = DBO.GetNextOutlineNum(@PREV_NUM,@CUR_LEVEL,@PREV_LEVEL)
		SET @PREV_LEVEL = @CUR_LEVEL
		UPDATE TASKS SET OutlineNumber = @PREV_NUM WHERE CURRENT OF TASK_CUR
	   FETCH NEXT FROM TASK_CUR INTO @CUR_LEVEL
	END
	CLOSE TASK_CUR
	DEALLOCATE TASK_CUR
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResetCompletedBy
	@TaskId as int
as
UPDATE TASKS
  SET CompletedBy = null, ActualFinishDate = null
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceAdd
	@TaskId as int ,
	@UserId as int ,
	@MustBeConfirmed as bit,
	@CanManage as bit
as
IF EXISTS(SELECT * FROM TASK_RESOURCES WHERE TaskId = @TaskId AND PrincipalId = @UserId)
	UPDATE TASK_RESOURCES
	  SET MustBeConfirmed = @MustBeConfirmed, CanManage = @CanManage
	  WHERE TaskId = @TaskId AND PrincipalId = @UserId
ELSE
	INSERT INTO TASK_RESOURCES (TaskId, PrincipalId, MustBeConfirmed, CanManage)
	  VALUES(@TaskId, @UserId, @MustBeConfirmed, @CanManage)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceCheck
	@TaskId as int,
	@UserId as int,
	@retval int output
as
IF EXISTS(SELECT * FROM TASK_RESOURCES WHERE PrincipalId = @UserId AND TaskId = @TaskId)
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceDelete
	@TaskId as int,
	@UserId as int
as
DELETE FROM TASK_RESOURCES WHERE TaskId = @TaskId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceGetByUser
	@TaskId as int,
	@UserId as int
as
SELECT MustBeConfirmed, ResponsePending, IsConfirmed, PercentCompleted
  FROM TASK_RESOURCES
  WHERE TaskId = @TaskId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceReply
	@TaskId as int,
	@UserId as int,
	@IsConfirmed as bit,
	@LastSavedDate as datetime
as
UPDATE TASK_RESOURCES
  SET ResponsePending = 0, IsConfirmed = @IsConfirmed, LastSavedDate = @LastSavedDate
  WHERE TaskId = @TaskId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourcesGet
	@TaskId as int
as
SELECT R.ResourceId, R.TaskId, R.PrincipalId AS UserId, R.MustBeConfirmed, R.ResponsePending, R.IsConfirmed, R.PercentCompleted, R.CanManage,
	R.ActualFinishDate, R.LastSavedDate, P.IsGroup,
	CASE WHEN U.IsExternal = 1 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS IsExternal
  FROM TASK_RESOURCES R
	JOIN PRINCIPALS P ON (R.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE R.TaskId = @TaskId
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourcesGetByProject
	@ProjectId as int
as
SELECT DISTINCT R.PrincipalId AS UserId, U.FirstName, U.LastName
  FROM TASK_RESOURCES R
	JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE R.TaskId IN (SELECT TaskId FROM TASKS WHERE ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskResourceUpdatePercent
	@TaskId as int,
	@UserId as int,
	@PercentCompleted as int,
	@LastSavedDate as datetime
as
if @PercentCompleted = 100
	UPDATE TASK_RESOURCES
	  SET PercentCompleted = @PercentCompleted, LastSavedDate = @LastSavedDate, ActualFinishDate = @LastSavedDate
	  WHERE TaskId = @TaskId AND PrincipalId = @UserId
ELSE
	UPDATE TASK_RESOURCES
	  SET PercentCompleted = @PercentCompleted, LastSavedDate = @LastSavedDate
	  WHERE TaskId = @TaskId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM TASK_RESOURCES WHERE PrincipalId = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM TASKS WHERE CreatorId = @UserId  OR CompletedBy = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskSecurityGet
	@TaskId int
AS
SELECT PrincipalId AS UserId, CAST(IsResource as bit) AS IsResource, CAST(IsManager as bit) AS IsManager,
	CAST(IsRealTaskResource as bit) AS IsRealTaskResource, CAST(IsRealTaskManager as bit) AS IsRealTaskManager
  FROM TASK_SECURITY
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetAllForUser
	@UserId as int,
              @ProjectId as int,
	@LanguageId as int
as
SELECT T.TaskId, T.Title, T.[Description], T.ProjectId,  P.Title AS ProjectTitle,  T.PercentCompleted, IsCompleted,  U.LastName + ', ' + U.FirstName AS ManagerName,
	T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T, PROJECTS P ,USERS U
  WHERE (P.ManagerId = U.PrincipalId) AND (P.ProjectId=T.ProjectId) AND
                 ((T.ProjectId=@ProjectId)OR(@ProjectId=0)) AND
		TaskId IN
		(SELECT TaskId FROM TASK_RESOURCES R
		  WHERE PrincipalId = @UserId AND R.TaskId = T.TaskId
		)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetByFilter
	@ProjectId as int,
	@UserId as int,
	@ResourceId as int,
	@StartDate as datetime,
	@FinishDate as datetime,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit,
	@Keyword as nvarchar(100)
as
SET @Keyword = '%' + @Keyword + '%'
SET @FinishDate = DATEADD(d, 1, @FinishDate)
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.TaskId, T.Title, T.[Description], T.IsCompleted,
	T.StartDate, T.FinishDate,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete,
	T.PriorityId, T.PercentCompleted, T.StateId
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
	LEFT JOIN TASK_SECURITY TS2 ON (T.TaskId = TS2.TaskId AND TS2.PrincipalId = @ResourceId)
  WHERE T.IsMilestone = 0
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.StartDate < @FinishDate  AND T.FinishDate > @StartDate
	AND (@Keyword = '%%' OR T.Title LIKE @Keyword OR T.[Description] LIKE @Keyword)
	AND
	(
		(@GetAssigned = 1 AND T.IsSummary = 0
			AND (@ResourceId = 0 OR TS2.IsResource = 1))
		OR
		(@GetManaged =1 AND (@ResourceId = 0 OR TS2.IsManager = 1))
		OR
		(@GetCreated = 1 AND (@ResourceId = 0  OR T.CreatorId = @UserId))
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetByProject
	@ProjectId as int,
	@LanguageId as int
as
SELECT T.TaskId, T.TaskNum, T.ProjectId, T.CreatorId, T.Title, T.[Description],
	T.CreationDate, T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.Duration, T.PriorityId, T.PercentCompleted, T.OutlineNumber, T.OutlineLevel, T.IsSummary, T.IsMilestone, T.ConstraintTypeId,
	T.ConstraintDate, T.CompletionTypeId, T.IsCompleted, T.MustBeConfirmed, T.ReasonId, P.PriorityName, T.StateId
  FROM TASKS T
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE ProjectId = @ProjectId
  ORDER BY TaskNum
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetByProjectCollapsed
	@ProjectId as int,
	@UserId as int
as
SELECT T.TaskId, T.TaskNum, T.OutlineNumber, T.OutlineLevel, T.IsSummary, T.IsMilestone, T.Title, T.PercentCompleted, T.CompletionTypeId, T.IsCompleted,
	CASE WHEN CT.CollapsedId IS NOT NULL AND T.IsSummary = 1 THEN 1 ELSE 0 END AS IsCollapsed,
	T.StartDate, T.FinishDate, T.Duration, T.StateId
  FROM TASKS T
	LEFT JOIN COLLAPSED_TASKS CT ON (T.TaskId = CT.TaskId AND CT.UserId = @UserId)
  WHERE T.ProjectId = @ProjectId
  ORDER BY T.TaskNum
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 7)
	SET @IsExec = 1
SELECT T.TaskId, T.Title, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate, 1 AS IsResource, T.StateId,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR TS.IsManager = 1 OR TS.IsResource = 1 THEN 1 ELSE 0 END AS CanView,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM TASKS T
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @CurrentUserId)
	LEFT JOIN TASK_RESOURCES TR ON (T.TaskId = TR.TaskId AND TR.PrincipalId = @UserId)
  WHERE T.TaskId IN (SELECT TaskId FROM TASK_RESOURCES WHERE PrincipalId = @UserId)
  ORDER BY T.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetForEventScheduling
	@EventId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT TR.PrincipalId AS UserId, T.TaskId, T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T
	JOIN TASK_RESOURCES TR ON (T.TaskId = TR.TaskId)
	JOIN EVENT_SECURITY_ALL S ON (TR.PrincipalId = S.PrincipalId)
  WHERE T.IsCompleted = 0 AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND T.StartDate < @FinishDate AND T.FinishDate > @StartDate
	AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND TR.IsConfirmed = 0)
	AND (S.IsResource = 1 OR S.IsManager = 1)
	AND S.EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetForMove
			@TaskId INT
AS
DECLARE @ToTaskNum INT, @TaskNum INT ,@ProjectId INT
SELECT @ProjectId = ProjectId, @TaskNum = TaskNum FROM TASKS WHERE TaskId = @TaskId
SELECT @ToTaskNum = MAX(TaskNum) FROM TASKS WHERE ProjectId = @ProjectId AND OutlineNumber LIKE
	(SELECT OutlineNumber FROM TASKS WHERE ProjectId = @ProjectId AND TaskNum = @TaskNum)+'%'
SELECT T.TaskNum, T.Title FROM  (SELECT TaskNum, Title FROM TASKS WHERE ProjectId = @ProjectId
					UNION
				       SELECT 0 ,'') T
WHERE (TaskNum < @TaskNum - 1)  OR  (T.TaskNum > @ToTaskNum)  ORDER BY TaskNum
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetForScheduling
	@UserId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT TR.PrincipalId AS UserId, T.TaskId, T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T
	JOIN TASK_RESOURCES TR ON (T.TaskId = TR.TaskId)
	JOIN SCHEDULE S ON (TR.PrincipalId = S.ContUserId)
  WHERE T.IsCompleted = 0 AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND T.StartDate < @FinishDate AND T.FinishDate > @StartDate
	AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND TR.IsConfirmed = 0)
	AND S.UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetForUserByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @dt datetime
SET @dt = GETUTCDATE()
SELECT T.TaskId, T.Title, T.[Description], T.PriorityId, P.PriorityName, PercentCompleted, IsCompleted, StartDate, FinishDate, T.StateId
  FROM TASKS T
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE ProjectId = @ProjectId AND IsCompleted = 0 AND IsSummary = 0 AND IsMileStone = 0
	AND StartDate < = @dt
	AND TaskId IN
		(SELECT TaskId FROM TASK_RESOURCES R
		  WHERE PrincipalId = @UserId
			AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
		)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetMilestones
	@ProjectId as int,
	@UserId as int,
	@ResourceId as int,
	@StartDate as datetime,
	@FinishDate as datetime,
	@Keyword as nvarchar(100)
as
SET @Keyword = '%' + @Keyword + '%'
SET @FinishDate = DATEADD(dd, 1, @FinishDate)
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.TaskId, T.Title, T.[Description], T.IsCompleted, T.StartDate, T.FinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR P.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR P.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE T.IsMilestone = 1
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND (@Keyword = '%%' OR T.Title LIKE @Keyword OR T.[Description] LIKE @Keyword)
	AND T.StartDate < @FinishDate AND T.FinishDate >= @StartDate
	AND (@ResourceId = 0 OR  T.TaskId IN (SELECT TaskId FROM TASK_SECURITY WHERE PrincipalId = @ResourceId AND (IsResource = 1 OR IsManager = 1)))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetSimple
	@ProjectId as int,
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit
as
SELECT T.TaskId, T.Title
  FROM TASKS T
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId)
	AND
	(
		(@GetAssigned = 1 AND TS.IsResource = 1)
		OR
		(@GetManaged =1 AND TS.IsManager = 1)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksGetSummaryByProject
	@ProjectId as int
as
SELECT TaskId, TaskNum, OutlineNumber, OutlineLevel
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
BEGIN TRAN
	UPDATE TASKS SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE TASKS SET CompletedBy = @ToUserId WHERE CompletedBy = @FromUserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TasksReplaceUnchangeableUserToManager
	@UserId as int
as
BEGIN TRAN
	UPDATE TASKS
	    SET CreatorId = P.ManagerId
	    FROM TASKS T, PROJECTS P
	    WHERE T.ProjectId = P.ProjectId AND T.CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE TASKS
	    SET CompletedBy = P.ManagerId
	    FROM TASKS T, PROJECTS P
	    WHERE T.ProjectId = P.ProjectId AND T.CompletedBy = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskToDoAdd
	@TaskId as int ,
	@ToDoId as int ,
	@CompleteTask as bit
as
if EXISTS(SELECT * FROM TASK_TODO WHERE TaskId = @TaskId AND ToDoId = @ToDoId)
	UPDATE TASK_TODO
	  SET CompleteTask=@CompleteTask
	  WHERE TaskId = @TaskId AND ToDoId = @ToDoId
else
	INSERT INTO TASK_TODO (TaskId, ToDoId, CompleteTask)
	  VALUES(@TaskId, @ToDoId, @CompleteTask)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdate
	@TaskId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@Duration as int ,
	@PriorityId as int ,
	@IsMilestone as bit ,
	@ConstraintTypeId as int,
	@ConstraintDate as datetime = null,
	@ActivationTypeId int,
	@CompletionTypeId int,
	@MustBeConfirmed bit,
	@PhaseId int,
	@TaskTime int
as
IF @PhaseId < 0
	SET @PhaseId = NULL
UPDATE TASKS
  SET Title=@Title, [Description]=@Description, StartDate=@StartDate,
	FinishDate=@FinishDate, Duration=@Duration, PriorityId=@PriorityId, IsMilestone=@IsMilestone,
	ConstraintTypeId = @ConstraintTypeId, ConstraintDate = @ConstraintDate, ActivationTypeId = @ActivationTypeId,
	CompletionTypeId = @CompletionTypeId, MustBeConfirmed = @MustBeConfirmed, PhaseId = @PhaseId, TaskTime = @TaskTime
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateActivation
	@TaskId as int
as
UPDATE TASKS
  SET ActivatedManually = 1
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateAddPossibleSuccessor
			@UpdateId char(36),
			@TaskId INT,
			@retval INT OUTPUT
		AS
DECLARE @IsSummary BIT
DECLARE @ProjectId INT
DECLARE @OutlineNumber VARCHAR(255)
DECLARE @SuccId INT
SET @retval = 0
DECLARE Succ_Cursor CURSOR FOR SELECT SuccId FROM TASK_LINKS WHERE PredId = @TaskId
OPEN Succ_Cursor
FETCH NEXT FROM Succ_Cursor INTO @SuccId
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @IsSummary = IsSummary, @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @SuccId
IF @IsSummary = 1
	BEGIN
	  INSERT INTO TASK_UPDATES (UpdateId, TaskId) SELECT @UpdateId,TaskId FROM TASKS WHERE
			ProjectId = @ProjectId AND (TaskId = @SuccId OR OutlineNumber LIKE @OutlineNumber + '.%')
	END
ELSE
	BEGIN
	  INSERT INTO TASK_UPDATES (UpdateId, TaskId) VALUES(@UpdateId,@SuccId)
	END
SET @retval = @retval + @@ROWCOUNT
   FETCH NEXT FROM Succ_Cursor INTO @SuccId
END
CLOSE Succ_Cursor
DEALLOCATE Succ_Cursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateAddPossibleTask
			@UpdateId char(36),
			@TaskId INT,
			@FromChild BIT,
			@retval INT OUTPUT
		AS
DECLARE @IsSummary BIT
DECLARE @ProjectId INT
DECLARE @OutlineNumber VARCHAR(255)
SELECT @IsSummary = IsSummary, @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @TaskId
IF @IsSummary = 1 AND @FromChild = 0
	BEGIN
	  INSERT INTO TASK_UPDATES (UpdateId, TaskId) SELECT @UpdateId,TaskId FROM TASKS WHERE
			ProjectId = @ProjectId AND (TaskId = @TaskId OR OutlineNumber LIKE @OutlineNumber + '.%')
	END
ELSE
	BEGIN
	  INSERT INTO TASK_UPDATES (UpdateId, TaskId) VALUES(@UpdateId,@TaskId)
	END
SET @retval = @@ROWCOUNT
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateCompletedBy
	@TaskId as int,
	@UserId as int
as
UPDATE TASKS
  SET CompletedBy = @UserId, ActualFinishDate = getutcdate()
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateCompletion
	@TaskId as int,
	@IsCompleted as bit,
	@ReasonId as int
as
UPDATE TASKS
  SET IsCompleted = @IsCompleted, ReasonId = @ReasonId
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateDates
	@TaskId as int ,
	@StartDate as datetime ,
	@FinishDate as datetime ,
	@Duration as int ,
	@ConstraintTypeId as int,
	@ConstraintDate as DateTime = null
as
UPDATE TASKS
  SET StartDate=@StartDate, FinishDate=@FinishDate, Duration=@Duration,
	ConstraintTypeId=@ConstraintTypeId, ConstraintDate=@ConstraintDate
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateDeleteAll
			@UpdateId char(36)
		AS
DELETE FROM TASK_UPDATES WHERE UpdateId = @UpdateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateDeleteTask
			@UpdateId char(36),
			@TaskId INT
		AS
DELETE FROM TASK_UPDATES WHERE UpdateId = @UpdateId AND TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdateGetTask
			@UpdateId CHAR(36),
			@RetVal INT OUTPUT
AS
DECLARE @ProjectId INT
DECLARE @OutlineNumber VARCHAR(255)
DECLARE @TaskId INT
SET @RetVal = -1
DECLARE Task_Cursor CURSOR FOR SELECT TaskId FROM TASK_UPDATES WHERE UpdateId = @UpdateId
OPEN Task_Cursor
FETCH NEXT FROM Task_Cursor INTO @TaskId
WHILE @@FETCH_STATUS = 0
BEGIN
 	SELECT @ProjectId = ProjectId, @OutlineNumber = OutlineNumber FROM TASKS WHERE TaskId = @TaskId
	IF NOT EXISTS(
		SELECT TaskId FROM TASKS T WHERE ProjectId = @ProjectId AND OutlineNumber LIKE @OutlineNumber + '.%' AND
						    EXISTS (SELECT TaskId FROM TASK_UPDATES TU WHERE TU.TaskId = T.TaskId AND UpdateId = @UpdateId )
		UNION
		SELECT PredId FROM TASK_LINKS WHERE SuccId = @TaskId AND
						    EXISTS (SELECT TaskId FROM TASK_UPDATES TU WHERE TU.TaskId = PredId AND UpdateId = @UpdateId )
		     )
	BEGIN
		SET @Retval = @TaskId
		CLOSE Task_Cursor
		DEALLOCATE Task_Cursor
		RETURN
	END
   FETCH NEXT FROM Task_Cursor INTO @TaskId
END
CLOSE Task_Cursor
DEALLOCATE Task_Cursor
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TaskUpdatePercent
	@TaskId as int,
	@PercentCompleted as int
as
UPDATE TASKS
  SET PercentCompleted = @PercentCompleted
  WHERE TaskId = @TaskId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[test]
AS
	SELECT * from fsc_Reports
	SELECT @@version
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetAdd
	@WeekTimeSheetId as int ,
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@Day1 as int,
	@Day2 as int,
	@Day3 as int,
	@Day4 as int,
	@Day5 as int,
	@Day6 as int,
	@Day7 as int,
	@UserComments ntext
as
if EXISTS(SELECT * FROM TIMESHEETS WHERE WeekTimeSheetId = @WeekTimeSheetId AND ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId)
	UPDATE TIMESHEETS
	  SET Day1=@Day1, Day2=@Day2, Day3=@Day3, Day4=@Day4, Day5=@Day5, Day6=@Day6, Day7=@Day7, UserComments = @UserComments
	  WHERE WeekTimeSheetId = @WeekTimeSheetId AND ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
else
	INSERT INTO TIMESHEETS (WeekTimeSheetId, ObjectTypeId, ObjectId, Day1, Day2, Day3, Day4, Day5, Day6, Day7, UserComments)
	  VALUES(@WeekTimeSheetId, @ObjectTypeId, @ObjectId, @Day1, @Day2, @Day3, @Day4, @Day5, @Day6, @Day7, @UserComments)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetAddWithoutComments
	@WeekTimeSheetId as int ,
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@Day1 as int,
	@Day2 as int,
	@Day3 as int,
	@Day4 as int,
	@Day5 as int,
	@Day6 as int,
	@Day7 as int
as
if EXISTS(SELECT * FROM TIMESHEETS WHERE WeekTimeSheetId = @WeekTimeSheetId AND ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId)
	UPDATE TIMESHEETS
	  SET Day1=@Day1, Day2=@Day2, Day3=@Day3, Day4=@Day4, Day5=@Day5, Day6=@Day6, Day7=@Day7
	  WHERE WeekTimeSheetId = @WeekTimeSheetId AND ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
else
	INSERT INTO TIMESHEETS (WeekTimeSheetId, ObjectTypeId, ObjectId, Day1, Day2, Day3, Day4, Day5, Day6, Day7)
	  VALUES(@WeekTimeSheetId, @ObjectTypeId, @ObjectId, @Day1, @Day2, @Day3, @Day4, @Day5, @Day6, @Day7)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetAndTaskTimeGetByObjects
	@ProjectId as int
AS
DECLARE @Approved int
SET @Approved = 4
DECLARE @TaskType int, @ToDoType int, @IncidentType int, @DocumentType int
SET @TaskType = 5
SET @ToDoType = 6
SET @IncidentType = 7
SET @DocumentType = 16
SELECT T.TaskId AS ObjectId, @TaskType AS ObjectTypeId, T.Title, T.TaskTime,
	(SELECT ISNULL(SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7), 0)
	  FROM TIMESHEETS TT WHERE TT.ObjectId = T.TaskId AND TT.ObjectTypeId = @TaskType
	) AS Total,
	(SELECT ISNULL(SUM(TotalApproved), 0)
	  FROM TIMESHEETS TT JOIN WeekTimeSheet W ON TT.WeekTimeSheetId = W.WeekTimeSheetId
	  WHERE TT.ObjectId = T.TaskId AND TT.ObjectTypeId = @TaskType AND W.StatusId = @Approved
	) AS TotalApproved
  FROM TASKS T
  WHERE T.ProjectId = @ProjectId
	AND T.IsSummary = 0 AND T.IsMileStone = 0
UNION ALL
SELECT T.ToDoId AS ObjectId, @ToDoType AS ObjectTypeId, T.Title, T.TaskTime,
	(SELECT ISNULL(SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7), 0)
	  FROM TIMESHEETS TT WHERE TT.ObjectId = T.ToDoId AND TT.ObjectTypeId = @ToDoType
	) AS Total,
	(SELECT ISNULL(SUM(TotalApproved), 0)
	  FROM TIMESHEETS TT JOIN WeekTimeSheet W ON TT.WeekTimeSheetId = W.WeekTimeSheetId
	  WHERE TT.ObjectId = T.ToDoId AND TT.ObjectTypeId = @ToDoType AND W.StatusId = @Approved
	) AS TotalApproved
  FROM TODO T
  WHERE T.ProjectId = @ProjectId
UNION ALL
SELECT T.IncidentId AS ObjectId, @IncidentType AS ObjectTypeId, T.Title, T.TaskTime,
	(SELECT ISNULL(SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7), 0)
	  FROM TIMESHEETS TT WHERE TT.ObjectId = T.IncidentId AND TT.ObjectTypeId = @IncidentType
	) AS Total,
	(SELECT ISNULL(SUM(TotalApproved), 0)
	  FROM TIMESHEETS TT JOIN WeekTimeSheet W ON TT.WeekTimeSheetId = W.WeekTimeSheetId
	  WHERE TT.ObjectId = T.IncidentId AND TT.ObjectTypeId = @IncidentType AND W.StatusId = @Approved
	) AS TotalApproved
  FROM INCIDENTS T
  WHERE T.ProjectId = @ProjectId
UNION ALL
SELECT T.DocumentId AS ObjectId, @DocumentType AS ObjectTypeId, T.Title, T.TaskTime,
	(SELECT ISNULL(SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7), 0)
	  FROM TIMESHEETS TT WHERE TT.ObjectId = T.DocumentId AND TT.ObjectTypeId = @DocumentType
	) AS Total,
	(SELECT ISNULL(SUM(TotalApproved), 0)
	  FROM TIMESHEETS TT JOIN WeekTimeSheet W ON TT.WeekTimeSheetId = W.WeekTimeSheetId
	  WHERE TT.ObjectId = T.DocumentId AND TT.ObjectTypeId = @DocumentType AND W.StatusId = @Approved
	) AS TotalApproved
  FROM DOCUMENTS T
  WHERE T.ProjectId = @ProjectId
ORDER BY ObjectTypeId, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetDeleteByObject
	@ObjectTypeId as int ,
	@ObjectId as int
as
BEGIN TRAN
	IF @ObjectTypeId = 11
	BEGIN
		DELETE FROM TIMESHEET_TODO WHERE TimeSheetToDoId = @ObjectId
		IF @@ERROR != 0
			GOTO err
	END
	DELETE FROM TIMESHEETS WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
	IF @@ERROR != 0
		GOTO err
	DELETE FROM WeekTimeSheet
	  WHERE StatusId <> 4
		AND WeekTimeSheetId NOT IN (SELECT WeekTimeSheetId FROM TimeSheets)
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetDeleteByProject
	@ProjectId as int
as
DELETE FROM TIMESHEET_TODO
  WHERE TimeSheetToDoId IN
		(SELECT ObjectId FROM TIMESHEETS WHERE ObjectTypeId = 11 AND WeekTimeSheetId IN
		(SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE Projectid = @ProjectId))
DELETE FROM TIMESHEETS
  WHERE WeekTimeSheetId IN
		(SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE Projectid = @ProjectId)
DELETE FROM WeekTimeSheet WHERE Projectid = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetDeleteByStartDate
	@UserId as int ,
	@ObjectTypeId as int ,
	@ObjectId as int ,
	@StartDate as datetime
as
DECLARE @WeekTimeSheetId int, @ProjectId int
SELECT @ProjectId = ProjectId, @WeekTimeSheetId = WeekTimeSheetId
  FROM WeekTimeSheet
  WHERE UserId = @UserId AND StartDate = @StartDate AND
	WeekTimeSheetId IN (SELECT WeekTimeSheetId FROM TIMESHEETS WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId)
IF @WeekTimeSheetId IS NULL
	RETURN
BEGIN TRAN
	IF @ObjectTypeId = 11
	BEGIN
		DELETE FROM TIMESHEET_TODO WHERE TimeSheetToDoId = @ObjectId
		IF @@ERROR != 0
			GOTO err
	END
	DELETE FROM TIMESHEETS
	  WHERE WeekTimeSheetId = @WeekTimeSheetId AND ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
	IF @@ERROR != 0
		GOTO err
	IF NOT EXISTS (SELECT * FROM TIMESHEETS WHERE WeekTimeSheetId = @WeekTimeSheetId )
	BEGIN
		DELETE FROM WeekTimeSheet WHERE WeekTimeSheetId = @WeekTimeSheetId AND StatusId <> 4
		IF @@ERROR != 0
			GOTO err
	END
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGet
	@UserId as int,
	@ObjectTypeId as int,
	@ObjectId as int,
	@StartDate as datetime
AS
SELECT T.WeekTimeSheetId, T.Day1, T.Day2, T.Day3, T.Day4, T.Day5, T.Day6, T.Day7, T.Day1 + T.Day2 + T.Day3 + T.Day4 + T.Day5 + T.Day6 + T.Day7 AS Total,
	T.TotalApproved, T.UserComments, W.StatusId, T.ActualId
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
	AND W.UserId = @UserId AND W.StartDate = @StartDate
	AND T.ObjectTypeId = @ObjectTypeId AND T.ObjectId = @ObjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByObject
	@ObjectTypeId as int,
	@ObjectId as int,
	@UserId as int
AS
SELECT W.StartDate, T.Day1 + T.Day2 + T.Day3 + T.Day4 + T.Day5 + T.Day6 + T.Day7 AS Total, 	T.TotalApproved, W.StatusId
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
	AND W.UserId = @UserId
	AND T.ObjectTypeId = @ObjectTypeId AND T.ObjectId = @ObjectId
  ORDER BY W.StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByObjectTotals
	@ObjectTypeId as int,
	@ObjectId as int
AS
DECLARE @Approved int
SET @Approved = 4
DECLARE @Total int, @TotalApproved int
SELECT @Total = ISNULL(SUM(Day1 + Day2 + Day3 + Day4 + Day5 + Day6 + Day7), 0)
  FROM TIMESHEETS
  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
SELECT @TotalApproved = ISNULL(SUM(TotalApproved), 0)
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
  WHERE T.ObjectTypeId = @ObjectTypeId AND T.ObjectId = @ObjectId
	AND  W.StatusId = @Approved
SELECT @Total AS Total, @TotalApproved AS TotalApproved
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByProject
	@ProjectId as int,
	@UserId as int
AS
SELECT W.StartDate, SUM(T.Day1 + T.Day2 + T.Day3 + T.Day4 + T.Day5 + T.Day6 + T.Day7) AS Total, SUM(T.TotalApproved) AS TotalApproved, W.StatusId
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
	AND W.ProjectId = @ProjectId AND W.UserId = @UserId
  GROUP BY W.StartDate, W.StatusId
  ORDER BY W.StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByProjectAll
	@ProjectId as int
AS
DECLARE @ApprovedStatus int, @TaskObjectType int, @IncidentObjectType int, @DocumentObjectType int,
	@TodoObjectType int, @EventObjectType int, @TimeSheetToDoType int
SET @ApprovedStatus = 4
SET @TaskObjectType = 5
SET @IncidentObjectType = 7
SET @DocumentObjectType = 16
SET @TodoObjectType = 6
SET @EventObjectType = 4
SET @TimeSheetToDoType = 11
DECLARE @Dummy TABLE (ObjectId int, ObjectTypeId int, Title nvarchar(255), TaskTime int, Total int, TotalApproved int)
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT TaskId AS ObjectId, @TaskObjectType AS ObjectTypeId, Title, TaskTime,
	ISNULL((SELECT SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7)
	  FROM Timesheets TS
	  WHERE TS.ObjectTypeId = @TaskObjectType AND TS.ObjectId = O.TaskId
	), 0) AS Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @TaskObjectType AND TS.ObjectId = O.TaskId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
  FROM TASKS O WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT IncidentId AS ObjectId, @IncidentObjectType AS ObjectTypeId, Title, TaskTime,
	ISNULL((SELECT SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7)
	  FROM Timesheets TS
	  WHERE TS.ObjectTypeId = @IncidentObjectType AND TS.ObjectId = O.IncidentId
	), 0) AS Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @IncidentObjectType AND TS.ObjectId = O.IncidentId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
  FROM INCIDENTS O WHERE ProjectId = @ProjectId
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT DocumentId AS ObjectId, @DocumentObjectType AS ObjectTypeId, Title, TaskTime,
	ISNULL((SELECT SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7)
	  FROM Timesheets TS
	  WHERE TS.ObjectTypeId = @DocumentObjectType AND TS.ObjectId = O.DocumentId
	), 0) AS Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @DocumentObjectType AND TS.ObjectId = O.DocumentId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
  FROM DOCUMENTS O WHERE ProjectId = @ProjectId
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT TodoId AS ObjectId, @TodoObjectType AS ObjectTypeId, Title, TaskTime,
	ISNULL((SELECT SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7)
	  FROM Timesheets TS
	  WHERE TS.ObjectTypeId = @TodoObjectType AND TS.ObjectId = O.TodoId
	), 0) AS Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @TodoObjectType AND TS.ObjectId = O.TodoId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
  FROM TODO O WHERE ProjectId = @ProjectId
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT EventId AS ObjectId, @EventObjectType AS ObjectTypeId, Title, TaskTime,
	ISNULL((SELECT SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7)
	  FROM Timesheets TS
	  WHERE TS.ObjectTypeId = @EventObjectType AND TS.ObjectId = O.EventId
	), 0) AS Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @EventObjectType AND TS.ObjectId = O.EventId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
  FROM EVENTS O WHERE ProjectId = @ProjectId
INSERT INTO @Dummy (ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved)
SELECT ObjectId, ObjectTypeId, Title, 0 AS TaskTime, Total,
	ISNULL((SELECT SUM(TotalApproved)
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
	  WHERE TS.ObjectTypeId = @TimeSheetToDoType AND TS.ObjectId = O.ObjectId AND W.StatusId = @ApprovedStatus
	), 0) AS TotalApproved
FROM
(	SELECT TS.ObjectId, TS.ObjectTypeId, TT.Title,
		SUM(Day1+Day2+Day3+Day4+Day5+Day6+Day7) AS Total
	  FROM WeekTimeSheet W
		JOIN Timesheets TS ON (W.WeekTimesheetId = TS.WeekTimesheetId)
		JOIN Timesheet_Todo TT ON (TS.ObjectId = TT.TimeSheetToDoId)
	  WHERE W.ProjectId = @ProjectId AND TS.ObjectTypeId = @TimeSheetToDoType
	  GROUP BY TS.ObjectId, TS.ObjectTypeId, TT.Title
) O
SELECT ObjectId, ObjectTypeId, Title, TaskTime, Total, TotalApproved
  FROM @Dummy
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByProjectAndUserTotals
	@ProjectId as int,
	@UserId as int
AS
SELECT A.ObjectTypeId, A.ObjectId, A.TotalApproved,
	CASE
		WHEN A.ObjectTypeId = 4 THEN E.Title
		WHEN A.ObjectTypeId = 5 THEN TA.Title
		WHEN A.ObjectTypeId = 6 THEN T.Title
		WHEN A.ObjectTypeId = 7 THEN I.Title
		WHEN A.ObjectTypeId = 11 THEN TT.Title
		WHEN A.ObjectTypeId = 16 THEN D.Title
	END AS Title
  FROM (SELECT ObjectTypeId, ObjectId, SUM(TotalApproved) AS TotalApproved
	  FROM TIMESHEETS
	  WHERE WeekTimeSheetId IN
		(SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE ProjectId = @ProjectId AND UserId = @UserId)
	  GROUP BY ObjectTypeId, ObjectId
	) A
	LEFT JOIN EVENTS E ON (A.ObjectId = E.EventId AND A.ObjectTypeId = 4)
	LEFT JOIN TASKS TA ON (A.ObjectId = TA.TaskId AND A.ObjectTypeId = 5)
	LEFT JOIN TODO T ON (A.ObjectId = T.ToDoId AND A.ObjectTypeId = 6)
	LEFT JOIN INCIDENTS I ON (A.ObjectId = I.IncidentId AND A.ObjectTypeId = 7)
	LEFT JOIN TIMESHEET_TODO TT ON (A.ObjectId = TT.TimeSheetToDoId AND A.ObjectTypeId = 11)
	LEFT JOIN DOCUMENTS D ON (A.ObjectId = D.DocumentId AND A.ObjectTypeId = 16)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByUser
	@UserId as int,
             @StartDate as DateTime,
             @EndDate as DateTime
AS
SELECT T.ObjectTypeId, T.ObjectId, W.ProjectId, W.StartDate, T.TotalApproved, W.StatusId
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
	AND (@UserId=0 OR UserId = @UserId)
	AND W.StartDate >=@StartDate AND W.StartDate <= @EndDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByUserProjectDate
	@UserId as int,
	@ProjectId as int,
	@StartDate as datetime
AS
SELECT T.ObjectTypeId, T.ObjectId,
	CASE
		WHEN T.ObjectTypeId = 4 THEN E.Title
		WHEN T.ObjectTypeId = 5 THEN TA.Title
		WHEN T.ObjectTypeId = 6 THEN TD.Title
		WHEN T.ObjectTypeId = 7 THEN I.Title
		WHEN T.ObjectTypeId = 11 THEN TT.Title
		WHEN T.ObjectTypeId = 16 THEN D.Title
	END AS Title,
	T.Day1, T.Day2, T.Day3, T.Day4, T.Day5, T.Day6, T.Day7,
	T.Day1 + T.Day2 + T.Day3 + T.Day4 + T.Day5 + T.Day6 + T.Day7 AS Total,
	T.TotalApproved, T.Rate, T.TotalApproved * T.Rate / 60 AS Cost, T.UserComments
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
	LEFT JOIN EVENTS E ON (T.ObjectId = E.EventId AND T.ObjectTypeId = 4)
	LEFT JOIN TASKS TA ON (T.ObjectId = TA.TaskId AND T.ObjectTypeId = 5)
	LEFT JOIN TODO TD ON (T.ObjectId = TD.ToDoId AND T.ObjectTypeId = 6)
	LEFT JOIN INCIDENTS I ON (T.ObjectId = I.IncidentId AND T.ObjectTypeId = 7)
	LEFT JOIN TIMESHEET_TODO TT ON (T.ObjectId = TT.TimeSheetToDoId AND T.ObjectTypeId = 11)
	LEFT JOIN DOCUMENTS D ON (T.ObjectId = D.DocumentId AND T.ObjectTypeId = 16)
  WHERE W.UserId = @UserId AND W.ProjectId = @ProjectId AND W.StartDate = @StartDate
  ORDER BY Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByWeekAllRows
	@StartDate as datetime,
	@UserId as int,
	@ProjectId as int
AS
DECLARE @Pending int, @Approved int, @ActiveStatus int
SET @Pending = 2
SET @Approved = 4
SET @ActiveStatus = 2
DECLARE @EventType int, @TaskType int, @ToDoType int, @IncidentType int, @TimeSheetToDoType int, @DocumentType int
SET @EventType = 4
SET @TaskType = 5
SET @ToDoType = 6
SET @IncidentType = 7
SET @TimeSheetToDoType = 11
SET @DocumentType = 16
DECLARE @FinishDate datetime
SET @FinishDate = DATEADD(d, 7, @StartDate)
DECLARE @CurDate AS datetime
SET @CurDate = GETUTCDATE()
DECLARE @table
	TABLE (ObjectId int, ObjectTypeId int, ObjectName nvarchar(255), ProjectId int, ProjectName nvarchar(255),
		Minutes1 int, Minutes2 int, Minutes3 int, Minutes4 int, Minutes5 int, Minutes6 int, Minutes7 int, TimeSheetId int)
INSERT INTO @table
SELECT T.ToDoId AS ObjectId, @ToDoType AS ObjectTypeId, T.Title AS ObjectName,
	ISNULL(T.ProjectId, -1) AS ProjectId, ISNULL(P.Title , '') AS ProjectName,
	ISNULL(A.Day1, 0) AS Minutes1,	ISNULL(A.Day2, 0) AS Minutes2,	ISNULL(A.Day3, 0) AS Minutes3, ISNULL(A.Day4, 0) AS Minutes4,
	ISNULL(A.Day5, 0) AS Minutes5,	ISNULL(A.Day6, 0) AS Minutes6, ISNULL(A.Day7, 0) AS Minutes7,	ISNULL(A.TimeSheetId, 0) AS TimeSheetId
  FROM TODO T
	JOIN TODO_SECURITY_ALL S ON (T.ToDoId = S.ToDoId AND S.PrincipalId = @UserId)
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN (
		SELECT TS.ObjectId, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7, TS.TimeSheetId
		  FROM WeekTimeSheet W, TimeSheets TS
		  WHERE W.WeekTimeSheetId = TS.WeekTimeSheetId
			AND W.UserId = @UserId AND W.StartDate = @StartDate
			AND TS.ObjectTypeId = @ToDoType
		) A ON (T.ToDoId = A.ObjectId)
  WHERE ((T.StartDate < @FinishDate AND T.FinishDate >= @StartDate)
		OR (T.StartDate IS NULL AND T.IsCompleted = 0 AND @StartDate <= @CurDate AND @CurDate < @FinishDate))
	AND (@ProjectId = 0 OR P.ProjectId = @ProjectId)
	AND NOT EXISTS (SELECT * FROM WeekTimeSheet WHERE UserId = @UserId AND ProjectId = T.ProjectId AND StartDate = @StartDate AND (StatusId = @Pending OR StatusId = @Approved))
UNION ALL
SELECT T.TaskId AS ObjectId, @TaskType AS ObjectTypeId, T.Title AS ObjectName,
	T.ProjectId, P.Title AS ProjectName,
	ISNULL(A.Day1, 0) AS Minutes1,	ISNULL(A.Day2, 0) AS Minutes2,	ISNULL(A.Day3, 0) AS Minutes3, ISNULL(A.Day4, 0) AS Minutes4,
	ISNULL(A.Day5, 0) AS Minutes5,	ISNULL(A.Day6, 0) AS Minutes6, ISNULL(A.Day7, 0) AS Minutes7,	ISNULL(A.TimeSheetId, 0) AS TimeSheetId
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	JOIN TASK_RESOURCES R ON (T.TaskId = R.TaskId AND R.PrincipalId = @UserId
		AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0))
	LEFT JOIN (
		SELECT TS.ObjectId, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7, TS.TimeSheetId
		  FROM WeekTimeSheet W, TimeSheets TS
		  WHERE W.WeekTimeSheetId = TS.WeekTimeSheetId
			AND W.UserId = @UserId AND W.StartDate = @StartDate
			AND TS.ObjectTypeId = @TaskType
		) A ON (T.TaskId = A.ObjectId)
  WHERE T.StartDate < @FinishDate AND T.FinishDate >= @StartDate
	AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND (@ProjectId = 0 OR P.ProjectId = @ProjectId)
	AND NOT EXISTS (SELECT * FROM WeekTimeSheet WHERE UserId = @UserId AND ProjectId = T.ProjectId AND StartDate = @StartDate AND (StatusId = @Pending OR StatusId = @Approved))
UNION ALL
SELECT E.EventId AS ObjectId, @EventType AS ObjectTypeId, E.Title AS ObjectName,
	ISNULL(E.ProjectId, -1) AS ProjectId, ISNULL(P.Title , '') AS ProjectName,
	ISNULL(A.Day1, 0) AS Minutes1,	ISNULL(A.Day2, 0) AS Minutes2,	ISNULL(A.Day3, 0) AS Minutes3, ISNULL(A.Day4, 0) AS Minutes4,
	ISNULL(A.Day5, 0) AS Minutes5,	ISNULL(A.Day6, 0) AS Minutes6, ISNULL(A.Day7, 0) AS Minutes7,	ISNULL(A.TimeSheetId, 0) AS TimeSheetId
  FROM EVENTS E
	JOIN EVENT_SECURITY_ALL S ON (E.EventId = S.EventId AND S.PrincipalId = @UserId)
	LEFT JOIN PROJECTS P ON (E.ProjectId = P.ProjectId)
	LEFT JOIN (
		SELECT TS.ObjectId, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7, TS.TimeSheetId
		  FROM WeekTimeSheet W, TimeSheets TS
		  WHERE W.WeekTimeSheetId = TS.WeekTimeSheetId
			AND W.UserId = @UserId AND W.StartDate = @StartDate
			AND TS.ObjectTypeId = @EventType
		) A ON (E.EventId = A.ObjectId)
  WHERE E.StartDate < @FinishDate AND E.FinishDate >= @StartDate
	AND (@ProjectId = 0 OR P.ProjectId = @ProjectId)
	AND NOT EXISTS (SELECT * FROM WeekTimeSheet WHERE UserId = @UserId AND ProjectId = E.ProjectId AND StartDate = @StartDate AND (StatusId = @Pending OR StatusId = @Approved))
UNION ALL
SELECT I.IncidentId AS ObjectId, @IncidentType AS ObjectTypeId, I.Title AS ObjectName,
	ISNULL(I.ProjectId, -1) AS ProjectId, ISNULL(P.Title , '') AS ProjectName,
	ISNULL(A.Day1, 0) AS Minutes1,	ISNULL(A.Day2, 0) AS Minutes2,	ISNULL(A.Day3, 0) AS Minutes3, ISNULL(A.Day4, 0) AS Minutes4,
	ISNULL(A.Day5, 0) AS Minutes5,	ISNULL(A.Day6, 0) AS Minutes6, ISNULL(A.Day7, 0) AS Minutes7,	ISNULL(A.TimeSheetId, 0) AS TimeSheetId
  FROM INCIDENTS I
	JOIN INCIDENT_SECURITY_ALL S ON (I.IncidentId = S.IncidentId AND S.PrincipalId = @UserId)
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	LEFT JOIN (
		SELECT TS.ObjectId, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7, TS.TimeSheetId
		  FROM WeekTimeSheet W, TimeSheets TS
		  WHERE W.WeekTimeSheetId = TS.WeekTimeSheetId
			AND W.UserId = @UserId AND W.StartDate = @StartDate
			AND TS.ObjectTypeId = @IncidentType
		) A ON (I.IncidentId = A.ObjectId)
  WHERE I.StatusId = @ActiveStatus
	AND (@ProjectId = 0 OR P.ProjectId = @ProjectId)
	AND NOT EXISTS (SELECT * FROM WeekTimeSheet WHERE UserId = @UserId AND ProjectId = I.ProjectId AND StartDate = @StartDate AND (StatusId = @Pending OR StatusId = @Approved))
UNION ALL
SELECT D.DocumentId AS ObjectId, @DocumentType AS ObjectTypeId, D.Title AS ObjectName,
	ISNULL(D.ProjectId, -1) AS ProjectId, ISNULL(P.Title , '') AS ProjectName,
	ISNULL(A.Day1, 0) AS Minutes1,	ISNULL(A.Day2, 0) AS Minutes2,	ISNULL(A.Day3, 0) AS Minutes3, ISNULL(A.Day4, 0) AS Minutes4,
	ISNULL(A.Day5, 0) AS Minutes5,	ISNULL(A.Day6, 0) AS Minutes6, ISNULL(A.Day7, 0) AS Minutes7,	ISNULL(A.TimeSheetId, 0) AS TimeSheetId
  FROM DOCUMENTS D
	JOIN DOCUMENT_SECURITY_ALL S ON (D.DocumentId = S.DocumentId AND S.PrincipalId = @UserId)
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	LEFT JOIN (
		SELECT TS.ObjectId, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7, TS.TimeSheetId
		  FROM WeekTimeSheet W, TimeSheets TS
		  WHERE W.WeekTimeSheetId = TS.WeekTimeSheetId
			AND W.UserId = @UserId AND W.StartDate = @StartDate
			AND TS.ObjectTypeId = @DocumentType
		) A ON (D.DocumentId = A.ObjectId)
  WHERE IsCompleted = 0
	AND (@ProjectId = 0 OR P.ProjectId = @ProjectId)
	AND NOT EXISTS (SELECT * FROM WeekTimeSheet WHERE UserId = @UserId AND ProjectId = D.ProjectId AND StartDate = @StartDate AND (StatusId = @Pending OR StatusId = @Approved))
UNION
SELECT TS.ObjectId, TS.ObjectTypeId,
	CASE
		WHEN TS.ObjectTypeId = 4 THEN E.Title
		WHEN TS.ObjectTypeId = 5 THEN TA.Title
		WHEN TS.ObjectTypeId = 6 THEN T.Title
		WHEN TS.ObjectTypeId = 7 THEN I.Title
		WHEN TS.ObjectTypeId = 11 THEN TT.Title
		WHEN TS.ObjectTypeId = 16 THEN D.Title
	END AS ObjectName,
	ISNULL(W.ProjectId, -1) AS ProjectId, ISNULL(P.Title , '') AS ProjectName,
	TS.Day1 AS Minutes1, TS.Day2 AS Minutes2, TS.Day3 AS Minutes3, TS.Day4 AS Minutes4,
	TS.Day5 AS Minutes5, TS.Day6 AS Minutes6, TS.Day7 AS Minutes7, TimeSheetId
  FROM TIMESHEETS TS
	JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @StartDate AND NOT (StatusId = @Pending OR StatusId = @Approved))
	LEFT JOIN PROJECTS P ON (W.ProjectId = P.ProjectId)
	LEFT JOIN EVENTS E ON (TS.ObjectId = E.EventId AND TS.ObjectTypeId = @EventType)
	LEFT JOIN TASKS TA ON (TS.ObjectId = TA.TaskId AND TS.ObjectTypeId = @TaskType)
	LEFT JOIN TODO T ON (TS.ObjectId = T.ToDoId AND TS.ObjectTypeId = @ToDoType)
	LEFT JOIN INCIDENTS I ON (TS.ObjectId = I.IncidentId AND TS.ObjectTypeId = @IncidentType)
	LEFT JOIN DOCUMENTS D ON (TS.ObjectId = D.DocumentId AND TS.ObjectTypeId = @DocumentType)
	LEFT JOIN TIMESHEET_TODO TT ON (TS.ObjectId = TT.TimeSheetToDoId AND TS.ObjectTypeId = @TimeSheetToDoType)
  WHERE (@ProjectId = 0 OR P.ProjectId = @ProjectId)
  ORDER BY ProjectName, ObjectName
SELECT B.ProjectId, B.ProjectName, 0 AS ObjectTypeId, 0 AS ObjectId, '' AS ObjectName,
	B.Minutes1, B.Minutes2, B.Minutes3, B.Minutes4, B.Minutes5, B.Minutes6, B.Minutes7,
	B.RowTotal, CAST (1 as bit) AS IsProject, '' AS UserComments
  FROM (
	SELECT ProjectId, ProjectName,
		SUM(Minutes1) AS Minutes1, SUM(Minutes2) AS Minutes2, SUM(Minutes3) AS Minutes3, SUM(Minutes4) AS Minutes4,
		SUM(Minutes5) AS Minutes5, SUM(Minutes6) AS Minutes6, SUM(Minutes7) AS Minutes7, SUM(RowTotal) AS RowTotal
	  FROM (
		SELECT ProjectId, ProjectName, Minutes1, Minutes2, Minutes3, Minutes4, Minutes5, Minutes6, Minutes7,
			Minutes1 + Minutes2 + Minutes3 + Minutes4 + Minutes5 + Minutes6 + Minutes7 AS RowTotal
		  FROM @table
		) A
	  GROUP BY ProjectId, ProjectName
	) B
UNION ALL
SELECT T.ProjectId, T.ProjectName, T.ObjectTypeId, T.ObjectId, T.ObjectName,
	T.Minutes1, T.Minutes2, T.Minutes3, T.Minutes4, T.Minutes5, T.Minutes6, T.Minutes7,
	T.Minutes1 + T.Minutes2 + T.Minutes3 + T.Minutes4 + T.Minutes5 + T.Minutes6 + T.Minutes7 AS RowTotal,
	CAST (0 as bit) AS IsProject, TT.UserComments
  FROM @table T
	LEFT JOIN TIMESHEETS TT ON (T.TimeSheetId = TT.TimeSheetId)
ORDER BY ProjectName, ProjectId, ObjectName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByWeekGroupedByProject
	@StartDate as datetime,
	@UserId as int,
	@ProjectId as int
AS
DECLARE @table
	TABLE (ProjectId int, ProjectName nvarchar(255), ObjectTypeId int, ObjectId int, ObjectName nvarchar(255),
		Minutes1 int, Minutes2 int, Minutes3 int, Minutes4 int, Minutes5 int, Minutes6 int, Minutes7 int,
		RowTotal int, TotalApproved int, StatusId int, UserComments ntext)
INSERT INTO @table
SELECT W.ProjectId, P.Title AS ProjectName, A.ObjectTypeId, A.ObjectId,
	CASE
		WHEN A.ObjectTypeId = 4 THEN E.Title
		WHEN A.ObjectTypeId = 5 THEN TA.Title
		WHEN A.ObjectTypeId = 6 THEN T.Title
		WHEN A.ObjectTypeId = 7 THEN I.Title
		WHEN A.ObjectTypeId = 11 THEN TT.Title
		WHEN A.ObjectTypeId = 16 THEN D.Title
	END AS ObjectName,
	A.Day1 AS Minutes1, A.Day2 AS Minutes2, A.Day3 AS Minutes3, A.Day4 AS Minutes4, A.Day5 AS Minutes5, A.Day6 AS Minutes6, A.Day7 AS Minutes7,
	A.Day1 + A.Day2 + A.Day3 + A.Day4 + A.Day5 + A.Day6 + A.Day7 AS RowTotal, A.TotalApproved, W.StatusId, A.UserComments
FROM WeekTimeSheet W
	JOIN TIMESHEETS A ON (W.WeekTimeSheetId = A.WeekTimeSheetId)
		LEFT JOIN EVENTS E ON (A.ObjectId = E.EventId AND A.ObjectTypeId = 4)
		LEFT JOIN TASKS TA ON (A.ObjectId = TA.TaskId AND A.ObjectTypeId = 5)
		LEFT JOIN TODO T ON (A.ObjectId = T.ToDoId AND A.ObjectTypeId = 6)
		LEFT JOIN INCIDENTS I ON (A.ObjectId = I.IncidentId AND A.ObjectTypeId = 7)
		LEFT JOIN TIMESHEET_TODO TT ON (A.ObjectId = TT.TimeSheetToDoId AND A.ObjectTypeId = 11)
		LEFT JOIN DOCUMENTS D ON (A.ObjectId = D.DocumentId AND A.ObjectTypeId = 16)
	LEFT JOIN PROJECTS P ON (W.ProjectId = P.ProjectId)
WHERE W.StartDate = @StartDate AND W.UserId = @UserId AND (@ProjectId = 0 OR W.ProjectId = @ProjectId OR (@ProjectId = -1 AND W.ProjectId IS NULL))
DECLARE @CollapseNonProject bit
SET @CollapseNonProject = 0
IF EXISTS (SELECT * FROM COLLAPSED_USERTIMESHEETS WHERE UserId = @UserId AND ProjectId = -1)
	SET @CollapseNonProject = 1
SELECT B.ProjectId, B.ProjectName, 0 AS ObjectTypeId, 0 AS ObjectId, '' AS ObjectName, B.Minutes1, B.Minutes2, B.Minutes3, B.Minutes4, B.Minutes5, B.Minutes6, B.Minutes7,
	B.RowTotal, B.TotalApproved, B.StatusId, '' AS UserComments, CAST (1 as bit) AS IsProject, B.IsCollapsed, W.ManagerComments
FROM (
	SELECT ProjectId, ProjectName, StatusId, IsCollapsed,
		SUM(Minutes1) AS Minutes1, SUM(Minutes2) AS Minutes2, SUM(Minutes3) AS Minutes3, SUM(Minutes4) AS Minutes4, SUM(Minutes5) AS Minutes5,
		SUM(Minutes6) AS Minutes6, SUM(Minutes7) AS Minutes7, SUM(RowTotal) AS RowTotal, SUM(TotalApproved) AS TotalApproved
	  FROM (
		SELECT CASE WHEN T.ProjectId IS NULL THEN -1 ELSE T.ProjectId END AS ProjectId,
			CASE WHEN T.ProjectName IS NULL THEN '' ELSE T.ProjectName END AS ProjectName,
			StatusId,
			CASE WHEN
				(T.ProjectId IS NOT NULL AND C.ProjectId IS NULL)
				OR
				(T.ProjectId IS NULL AND @CollapseNonProject = 0)
			THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsCollapsed,
			Minutes1, Minutes2, Minutes3, Minutes4, Minutes5, Minutes6, Minutes7, RowTotal, TotalApproved
		  FROM @table T
			LEFT JOIN COLLAPSED_USERTIMESHEETS C ON (T.ProjectId = C.ProjectId AND C.UserId = @UserId)
		) A
	  GROUP BY ProjectId, ProjectName, StatusId, IsCollapsed
	) B LEFT JOIN WeekTimeSheet W ON (B.ProjectId = W.ProjectId AND W.UserId = @UserId AND W.StartDate = @StartDate)
UNION ALL
SELECT ISNULL(T.ProjectId, -1) ProjectId, ISNULL(T.ProjectName, '') ProjectName,
	ObjectTypeId, ObjectId, ObjectName, Minutes1, Minutes2, Minutes3, Minutes4, Minutes5, Minutes6, Minutes7, RowTotal, TotalApproved, StatusId, UserComments,
	CAST (0 as bit) AS IsProject, CAST(0 as bit) as IsCollapsed, '' AS ManagerComments
  FROM @table T
	LEFT JOIN COLLAPSED_USERTIMESHEETS C ON (T.ProjectId = C.ProjectId AND C.UserId = @UserId)
  WHERE
	(T.ProjectId IS NOT NULL AND C.ProjectId IS NULL)
	OR
	(T.ProjectId IS NULL AND @CollapseNonProject = 0)
ORDER BY ProjectName, B.ProjectId, ObjectName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetByWeekTotals
	@ProjectId as int,
	@StartDate as datetime,
	@UserId as int,
	@retval as int output
AS
SELECT @retval = SUM(TotalApproved)
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetID)
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId)
	AND UserId = @UserId
	AND StartDate = @StartDate
IF @retval IS NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetHoursByProject
	@ProjectId as int,
	@retval as int output
AS
SELECT @retval = SUM(T.TotalApproved)
    FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
  WHERE W.ProjectId = @ProjectId
IF @retval = NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetHoursByProjetcsForPMAndPPM
	@UserId as int,
	@retval int output
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT @retval = SUM(T.TotalApproved)
  FROM TIMESHEETS T
	JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
  WHERE @IsPPM_Exec = 1 OR W.ProjectId IN
	(SELECT ProjectId FROM PROJECTS WHERE ManagerId = @UserId)
IF @retval IS NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetTotalsByProject
	@ObjectId as int,
	@ObjectTypeId as int,
	@FromDate as datetime,
	@ToDate as datetime,
	@ProjectId as int,
	@retval as int output
AS
SET @ToDate = DATEADD(dd, 1, @ToDate)
SELECT @retval = SUM(T.TotalApproved)
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
  	AND W.ProjectId = @ProjectId AND W.StartDate >= @FromDate AND W.StartDate < @ToDate
	AND T.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectTypeId
IF @retval IS NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetTotalsByUser
	@ObjectId as int,
	@ObjectTypeId as int,
	@FromDate as datetime,
	@ToDate as datetime,
	@UserId as int,
	@retval as int output
AS
SET @ToDate = DATEADD(dd, 1, @ToDate)
SELECT @retval = SUM(T.TotalApproved)
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
  	AND W.UserId = @UserId AND W.StartDate >= @FromDate AND W.StartDate < @ToDate
	AND T.ObjectId = @ObjectId AND T.ObjectTypeId = @ObjectTypeId
IF @retval IS NULL
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetGetUsersByProject
	@ProjectId as int
AS
SELECT DISTINCT T.UserId, U.FirstName, U.LastName
  FROM WeekTimeSheet T
	JOIN USERS U ON (T.UserId = U.PrincipalId)
  WHERE T.ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetHoursGetByResourcesForProject
	@ProjectId as int
AS
DECLARE @Dummy TABLE (UserId int, UserName nvarchar(100), TaskHours int, ToDoHours int, IssueHours int, DocumentHours int, OtherHours int)
INSERT INTO @Dummy (UserId, UserName, TaskHours, ToDoHours, IssueHours, DocumentHours, OtherHours)
SELECT UserId, UserName,
	ISNULL(TaskHours, 0) AS TaskHours,
	ISNULL(ToDoHours, 0) AS ToDoHours,
	ISNULL(IssueHours, 0) AS IssueHours,
	ISNULL(DocumentHours, 0) AS DocumentHours,
	ISNULL(OtherHours, 0) AS OtherHours
FROM
(	SELECT U.PrincipalId AS UserId, U.LastName + ' ' + U.FirstName AS UserName,
	(SELECT SUM(T.TotalApproved)
	  FROM TIMESHEETS T, WeekTimeSheet W
	  WHERE T.WeekTimeSheetId = W.WeekTimeSheetId
		AND W.ProjectId = @ProjectId
		AND W.UserId = U.PrincipalId
		AND W.StatusId = 4
		AND
		(
			T.ObjectTypeId = 5
			OR
			T.ObjectTypeId = 6 AND T.ObjectId IN (SELECT ToDoId FROM TASK_TODO)
		)
	) AS TaskHours,
	(SELECT SUM(T.TotalApproved)
	  FROM TIMESHEETS T, WeekTimeSheet W
	  WHERE T.WeekTimeSheetId = W.WeekTimeSheetId
		AND W.ProjectId = @ProjectId
		AND W.UserId = U.PrincipalId
		AND W.StatusId = 4
		AND
		(
			T.ObjectTypeId = 16
			OR
			T.ObjectTypeId = 6 AND T.ObjectId IN (SELECT ToDoId FROM DOCUMENT_TODO)
		)
	) AS DocumentHours,
	(SELECT SUM(T.TotalApproved)
	  FROM TIMESHEETS T, WeekTimeSheet W
	  WHERE T.WeekTimeSheetId = W.WeekTimeSheetId
		AND W.ProjectId = @ProjectId
		AND W.UserId = U.PrincipalId
		AND W.StatusId = 4
		AND T.ObjectTypeId = 6
		AND T.ObjectId NOT IN (SELECT ToDoId FROM TASK_TODO)
		AND T.ObjectId NOT IN (SELECT ToDoId FROM INCIDENT_TODO)
		AND T.ObjectId NOT IN (SELECT ToDoId FROM DOCUMENT_TODO)
	) AS ToDoHours,
	(SELECT SUM(T.TotalApproved)
	  FROM TIMESHEETS T, WeekTimeSheet W
	  WHERE T.WeekTimeSheetId = W.WeekTimeSheetId
		AND W.ProjectId = @ProjectId
		AND W.UserId = U.PrincipalId
		AND W.StatusId = 4
		AND
		(
			T.ObjectTypeId = 7
			OR
			T.ObjectTypeId = 6 AND T.ObjectId IN (SELECT ToDoId FROM INCIDENT_TODO)
		)
	) AS IssueHours,
	(SELECT SUM(T.TotalApproved)
	  FROM TIMESHEETS T, WeekTimeSheet W
	  WHERE T.WeekTimeSheetId = W.WeekTimeSheetId
		AND W.ProjectId = @ProjectId
		AND W.UserId = U.PrincipalId
		AND W.StatusId = 4
		AND NOT (T.ObjectTypeId = 5 OR T.ObjectTypeId = 6 OR T.ObjectTypeId = 7 OR T.ObjectTypeId = 16)
	) AS OtherHours
  FROM USERS U
  WHERE U.PrincipalId IN (SELECT UserId FROM WeekTimeSheet WHERE ProjectId = @ProjectId AND StatusId = 4)
) A
ORDER BY UserName
SELECT UserId, UserName, TaskHours, ToDoHours, IssueHours, DocumentHours, OtherHours,
	TaskHours + ToDoHours + IssueHours + DocumentHours + OtherHours AS TotalHours
  FROM @Dummy
UNION ALL
SELECT 0 AS UserId, '' AS UserName, SUM(TaskHours), SUM(ToDoHours), SUM(IssueHours), SUM(DocumentHours), SUM(OtherHours),
	SUM(TaskHours + ToDoHours + IssueHours + DocumentHours + OtherHours)
  FROM @Dummy
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetObjectsGetByDate
	@Dt as datetime,
	@FirstDateOfWeek as datetime,
	@UserId as int
as
DECLARE @All int, @ActiveStatus int
SET @All = 1
SET @ActiveStatus = 2
DECLARE @ToDoType int, @TaskType int, @EventType int, @TimeSheetToDoType int, @DocumentType int, @IncidentType int
SET @ToDoType = 6
SET @TaskType = 5
SET @EventType = 4
SET @TimeSheetToDoType = 11
SET @DocumentType = 16
SET @IncidentType = 7
DECLARE @StartDate datetime
DECLARE @FinishDate datetime
SET @StartDate = @Dt
SET @FinishDate = DATEADD(d, 1, @Dt)
DECLARE @CurDate AS datetime
SET @CurDate = GETUTCDATE()
SELECT T.ToDoId AS ObjectId, @ToDoType AS ObjectTypeId,  T.Title, T.ProjectId, P.Title AS ProjectTitle, -1 AS EventTypeId, IsCompleted,
	CASE WHEN T.CompletionTypeId = @All THEN R.PercentCompleted ELSE T.PercentCompleted END AS PercentCompleted,
	TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM TODO T
	JOIN TODO_RESOURCES R ON (T.ToDoId = R.ToDoId AND R.PrincipalId = @UserId
		AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0))
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TIMESHEETS TS ON (T.ToDoId = TS.ObjectId AND TS.ObjectTypeId = @ToDoType)
		JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
  WHERE ((T.StartDate < @FinishDate AND T.FinishDate >= @StartDate)
		OR (T.StartDate IS NULL AND T.IsCompleted = 0 AND @StartDate <= @CurDate AND @CurDate < @FinishDate))
UNION ALL
SELECT T.TaskId AS ObjectId, @TaskType AS ObjectTypeId, T.Title, T.ProjectId, P.Title AS ProjectTitle, -1 AS EventTypeId, IsCompleted,
	CASE WHEN T.CompletionTypeId = @All THEN R.PercentCompleted ELSE T.PercentCompleted END AS PercentCompleted,
	TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	JOIN TASK_RESOURCES R ON (T.TaskId = R.TaskId AND R.PrincipalId = @UserId
		AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0))
	LEFT JOIN TIMESHEETS TS ON (T.TaskId = TS.ObjectId AND TS.ObjectTypeId = @TaskType)
		JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
  WHERE T.StartDate < @FinishDate AND T.FinishDate >= @StartDate
	AND T.IsMileStone = 0 AND T.IsSummary = 0
UNION ALL
SELECT E.EventId AS ObjectId, @EventType AS ObjectTypeId, E.Title, E.ProjectId, P.Title AS ProjectTitle, E.TypeId AS EventTypeId,
	CAST(1 as bit) AS IsCompleted, 0 AS PercentCompleted,
	TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM EVENTS E
	LEFT JOIN PROJECTS P ON (E.ProjectId = P.ProjectId)
	LEFT JOIN TIMESHEETS TS ON (E.EventId = TS.ObjectId AND TS.ObjectTypeId = @EventType)
		JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
  WHERE E.StartDate < @FinishDate AND E.FinishDate >= @StartDate
	AND EventId IN
		(SELECT EventId FROM EVENT_SECURITY_ALL S WHERE PrincipalId = @UserId)
UNION ALL
SELECT I.IncidentId AS ObjectId, @IncidentType AS ObjectTypeId, I.Title, I.ProjectId, P.Title AS ProjectTitle, -1 AS EventTypeId,
	CAST(0 as bit)  AS IsCompleted, 0 AS PercentCompleted, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM INCIDENTS I
	LEFT JOIN PROJECTS P ON (I.ProjectId = P.ProjectId)
	LEFT JOIN TIMESHEETS TS ON (I.IncidentId = TS.ObjectId AND TS.ObjectTypeId = @IncidentType)
		JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
  WHERE I.StatusId = @ActiveStatus
	AND IncidentId IN
		(SELECT IncidentId FROM INCIDENT_SECURITY_ALL S WHERE PrincipalId = @UserId)
UNION ALL
SELECT D.DocumentId AS ObjectId, @DocumentType AS ObjectTypeId, D.Title, D.ProjectId, P.Title AS ProjectTitle, -1 AS EventTypeId,
	IsCompleted, 0 AS PercentCompleted, TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM DOCUMENTS D
	LEFT JOIN PROJECTS P ON (D.ProjectId = P.ProjectId)
	LEFT JOIN TIMESHEETS TS ON (D.DocumentId = TS.ObjectId AND TS.ObjectTypeId = @DocumentType)
		JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
  WHERE IsCompleted = 0
	AND DocumentId IN
		(SELECT DocumentId FROM DOCUMENT_SECURITY_ALL S WHERE PrincipalId = @UserId)
UNION ALL
SELECT TS.ObjectId, TS.ObjectTypeId, TT.Title, W.ProjectId, P.Title AS ProjectTitle, -1 AS EventTypeId,
	CAST(1 as bit)  AS IsCompleted, 0 AS PercentCompleted,
	TS.Day1, TS.Day2, TS.Day3, TS.Day4, TS.Day5, TS.Day6, TS.Day7
  FROM TIMESHEETS TS
	JOIN WeekTimeSheet W ON (TS.WeekTimeSheetId = W.WeekTimeSheetId AND W.UserId = @UserId AND W.StartDate = @FirstDateOfWeek)
	JOIN TIMESHEET_TODO TT ON (TS.ObjectId = TT.TimeSheetToDoId)
	LEFT JOIN PROJECTS P ON (W.ProjectId = P.ProjectId)
  WHERE TS.ObjectTypeId = @TimeSheetToDoType
ORDER BY 2, 6, 3
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetResetProject
	@ProjectId as int
as
UPDATE WeekTimeSheet SET ProjectId = NULL WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetToDoAdd
	@Title as nvarchar(255) ,
	@retval int output
as
INSERT INTO TIMESHEET_TODO (Title) VALUES(@Title)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetToDoGet
	@TimeSheetToDoId as int
AS
SELECT  Title
  FROM TIMESHEET_TODO
  WHERE TimeSheetToDoId=@TimeSheetToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetToDoGetProject
	@TimeSheetToDoId as int,
	@Retval as int output
AS
SELECT @Retval = W.ProjectId
  FROM WeekTimeSheet W, TIMESHEETS T
  WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
	AND T.ObjectTypeId = 11 AND T.ObjectId = @TimeSheetToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetTransform
	@ObjectTypeId as int,
	@ObjectId as int
as
DECLARE @EventType int, @TaskType int, @ToDoType int, @TimeSheetToDoType int, @DocumentType int, @IncidentType int
SET @EventType = 4
SET @TaskType = 5
SET @ToDoType = 6
SET @IncidentType = 7
SET @TimeSheetToDoType = 11
SET @DocumentType = 16
DECLARE @Title nvarchar(255)
DECLARE @TimeSheetToDoId int
BEGIN TRAN
	IF @ObjectTypeId = @EventType
	BEGIN
		SELECT @Title = Title FROM EVENTS WHERE EventId = @ObjectId
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO TIMESHEET_TODO (Title) VALUES (@Title)
			IF @@error <> 0
				GOTO err
			SET @TimeSheetToDoId = @@IDENTITY
			UPDATE TIMESHEETS
			  SET ObjectTypeId = @TimeSheetToDoType, ObjectId = @TimeSheetToDoId
			  WHERE ObjectTypeId = @EventType AND ObjectId = @ObjectId
			IF @@error <> 0
				GOTO err
		END
	END
	IF @ObjectTypeId = @TaskType
	BEGIN
		SELECT @Title = Title FROM TASKS WHERE TaskId = @ObjectId
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO TIMESHEET_TODO (Title) VALUES (@Title)
			IF @@error <> 0
				GOTO err
			SET @TimeSheetToDoId = @@IDENTITY
			UPDATE TIMESHEETS
			  SET ObjectTypeId = @TimeSheetToDoType, ObjectId = @TimeSheetToDoId
			  WHERE ObjectTypeId = @TaskType AND ObjectId = @ObjectId
			IF @@error <> 0
				GOTO err
		END
	END
	IF @ObjectTypeId = @ToDoType
	BEGIN
		SELECT @Title = Title FROM TODO WHERE ToDoId = @ObjectId
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO TIMESHEET_TODO (Title) VALUES (@Title)
			IF @@error <> 0
				GOTO err
			SET @TimeSheetToDoId = @@IDENTITY
			UPDATE TIMESHEETS
			  SET ObjectTypeId = @TimeSheetToDoType, ObjectId = @TimeSheetToDoId
			  WHERE ObjectTypeId = @ToDoType AND ObjectId = @ObjectId
			IF @@error <> 0
				GOTO err
		END
	END
	IF @ObjectTypeId = @DocumentType
	BEGIN
		SELECT @Title = Title FROM DOCUMENTS WHERE DocumentId = @ObjectId
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO TIMESHEET_TODO (Title) VALUES (@Title)
			IF @@error <> 0
				GOTO err
			SET @TimeSheetToDoId = @@IDENTITY
			UPDATE TIMESHEETS
			  SET ObjectTypeId = @TimeSheetToDoType, ObjectId = @TimeSheetToDoId
			  WHERE ObjectTypeId = @DocumentType AND ObjectId = @ObjectId
			IF @@error <> 0
				GOTO err
		END
	END
	IF @ObjectTypeId = @IncidentType
	BEGIN
		SELECT @Title = Title FROM INCIDENTS WHERE IncidentId = @ObjectId
		IF @@ROWCOUNT > 0
		BEGIN
			INSERT INTO TIMESHEET_TODO (Title) VALUES (@Title)
			IF @@error <> 0
				GOTO err
			SET @TimeSheetToDoId = @@IDENTITY
			UPDATE TIMESHEETS
			  SET ObjectTypeId = @TimeSheetToDoType, ObjectId = @TimeSheetToDoId
			  WHERE ObjectTypeId = @IncidentType AND ObjectId = @ObjectId
			IF @@error <> 0
				GOTO err
		END
	END
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeSheetUpdateTotal
	@WeekTimeSheetId int,
	@ObjectId int,
	@ObjectTypeId int,
	@TotalApproved int,
	@Rate money,
	@ManagerId int
as
UPDATE TIMESHEETS
  SET TotalApproved = @TotalApproved, Rate = @Rate
  WHERE ObjectTypeId = @ObjectTypeId AND ObjectId = @ObjectId
	AND WeekTimeSheetId = @WeekTimeSheetId
UPDATE WeekTimeSheet SET LastEditorId = @ManagerId, LastSavedDate = getutcdate()
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[TimeZoneAddLocalUtc]
	@TimeZoneId as Int,
	@Start	as Datetime,
	@End	as Datetime,
	@TimeOffset as int,
	@IsDaylight as bit,
	@retval int output
AS
	INSERT INTO [dbo].[TimeZones_Local_Utc] (TimeZoneId, Start, [End], TimeOffset, IsDaylight) VALUES(@TimeZoneId, @Start, @End, @TimeOffset, @IsDaylight)
	SET @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[TimeZoneAddUtcLocal]
	@TimeZoneId as Int,
	@Start	as Datetime,
	@End	as Datetime,
	@TimeOffset as int,
	@IsDaylight as bit,
	@retval int output
AS
	INSERT INTO [dbo].[TimeZones_Utc_Local] (TimeZoneId, Start, [End], TimeOffset, IsDaylight) VALUES(@TimeZoneId, @Start, @End, @TimeOffset, @IsDaylight)
	SET @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeZoneGet
	@TimeZoneId as int,
	@LanguageId as int
as
SELECT Z.TimeZoneId, Z.Bias, Z.StandardBias, Z.DaylightBias, Z.DaylightMonth, Z.DaylightDayOfWeek, Z.DaylightWeek, Z.DaylightHour, Z.StandardMonth,
	Z.StandardDayOfWeek, Z.StandardWeek, Z.StandardHour, ZL.DisplayName, ZL.LanguageId
  FROM TIMEZONES Z
	JOIN TIMEZONES_LANGUAGE ZL ON (Z.TimeZoneId = ZL.TimeZoneId AND ZL.LanguageId = @LanguageId)
  WHERE Z.TimeZoneId = @TimeZoneId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeZoneGetBias
	@TimeZoneId as int,
	@retval int output
as
SELECT @retval = Bias
  FROM TIMEZONES
  WHERE TimeZoneId = @TimeZoneId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeZoneGetByBias
	@Bias as int,
	@retval int output
as
SELECT @retval = TimeZoneId
  FROM TIMEZONES
  WHERE Bias = @Bias
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeZoneGetName
	@TimeZoneId as int,
	@LanguageId as int
as
SELECT DisplayName
  FROM TIMEZONES_LANGUAGE
  WHERE LanguageId = @LanguageId AND TimeZoneId = @TimeZoneId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TimeZonesGet
	@LanguageId as int
as
SELECT Z.TimeZoneId, Z.Bias, Z.StandardBias, Z.DaylightBias, Z.DaylightMonth, Z.DaylightDayOfWeek, Z.DaylightWeek, Z.DaylightHour, Z.StandardMonth,
	Z.StandardDayOfWeek, Z.StandardWeek, Z.StandardHour, ZL.DisplayName, ZL.LanguageId
  FROM TIMEZONES Z
	JOIN TIMEZONES_LANGUAGE ZL ON (Z.TimeZoneId = ZL.TimeZoneId AND ZL.LanguageId = @LanguageId)
  ORDER BY Bias DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTaskGetCreators
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT CreatorId FROM TODO)
	OR PrincipalId IN (SELECT CreatorId FROM TASKS)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTaskGetManagers
as
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS FullName, FirstName + ' ' +LastName AS FullName2
  FROM USERS
  WHERE PrincipalId IN (SELECT ManagerId FROM TODO)
	OR PrincipalId IN (SELECT ManagerId FROM PROJECTS WHERE ProjectId IN
			(SELECT ProjectId FROM TASKS))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTaskResourcesGetByManager
	@ManagerId as int
as
SELECT U.PrincipalId AS UserId, U.FirstName, U.LastName, U.LastName + ', ' + U.FirstName AS FullName
  FROM USERS U
	JOIN
(SELECT DISTINCT PrincipalId
  FROM TODO_RESOURCES
  WHERE @ManagerId = 0
	OR ToDoId IN (SELECT ToDoId FROM TODO WHERE ManagerId = @ManagerId)
UNION
SELECT DISTINCT PrincipalId
  FROM TASK_RESOURCES
  WHERE @ManagerId = 0
	OR TaskId IN (SELECT TaskId FROM TASKS WHERE ProjectId IN
			(SELECT ProjectId FROM Projects WHERE ManagerId = @ManagerId))
) A ON (U.PrincipalId = A.PrincipalId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTaskResourcesGetCount
	@ProjectId as int
as
SELECT B.PrincipalId AS UserId, B.TaskTodoCount, U.FirstName, U.LastName
FROM
(SELECT PrincipalId, SUM(TaskTodoCount) AS TaskTodoCount
  FROM
	(SELECT R.PrincipalId, COUNT(*) AS TaskTodoCount
		FROM TASK_RESOURCES R, TASKS T
		WHERE R.TaskId = T.TaskId AND T.ProjectId = @ProjectId
			AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
		GROUP BY R.PrincipalId
	UNION ALL
	SELECT R.PrincipalId, COUNT(*) AS TaskTodoCount
		FROM TODO_RESOURCES R, TODO T
		WHERE R.ToDoId = T.ToDoId AND T.ProjectId = @ProjectId
			AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
		GROUP BY R.PrincipalId
	) A
  GROUP BY PrincipalId
) B JOIN USERS U ON (B.PrincipalId = U.PrincipalId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTaskResourcesGetNotPending
	@UserId as int
as
SELECT TR.ToDoId AS ItemId, T.Title, TR.PrincipalId, TR.IsConfirmed, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	TR.LastSavedDate, T.StartDate, 	T.FinishDate, T.StateId
  FROM TODO_RESOURCES TR
	JOIN TODO T ON (TR.ToDoId = T.ToDoId)
  WHERE T.ManagerId = @UserId AND TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0
UNION ALL
SELECT TR.TaskId AS ItemId, T.Title, TR.PrincipalId, TR.IsConfirmed, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	TR.LastSavedDate, T.StartDate, T.FinishDate, T.StateId
  FROM TASK_RESOURCES TR
	JOIN TASKS T ON (TR.TaskId = T.TaskId)
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE P.ManagerId = @UserId AND TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0
  ORDER BY TR.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetActive
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @ActiveState int, @OverdueState int
SET @ActiveState = 2
SET @OverdueState  = 3
SELECT T.ToDoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, T.ManagerId, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.CreationDate, T.StartDate, T.FinishDate, T.StateId
  FROM TODO T, TODO_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ToDoId = R.ToDoId AND R.PrincipalId = @UserId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND (T.StateId = @ActiveState OR T.StateId = @OverdueState)
	AND R.PercentCompleted < 100
	AND (R.MustBeConfirmed=0 OR (R.MustBeConfirmed=1 AND R.ResponsePending=0 AND R.IsConfirmed=1))
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, PR.ManagerId, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.CreationDate, T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T, TASK_RESOURCES R, PRIORITY_LANGUAGE P, PROJECTS PR
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.TaskId = R.TaskId AND R.PrincipalId = @UserId AND T.ProjectId = PR.ProjectId
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND (T.StateId = @ActiveState OR T.StateId = @OverdueState)
	AND R.PercentCompleted < 100
	AND (R.MustBeConfirmed=0 OR (R.MustBeConfirmed=1 AND R.ResponsePending=0 AND R.IsConfirmed=1))
ORDER BY StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetActiveByProject
	@FromDate as datetime,
	@ToDate as datetime,
	@ProjectId as int
as
DECLARE @ToDoType int
DECLARE @TaskType int
SET @ToDoType = 6
SET @TaskType = 5
SET @ToDate = DATEADD(d, 1, @ToDate)
SELECT T.ToDoId AS ObjectId, T.Title, T.IsCompleted, 1 AS IsToDo, OC.CategoryId, TS.Hours,
	CASE WHEN IT.IncidentToDoId IS NULL THEN 0 ELSE 1 END AS IsIncidentTodo,
	CASE WHEN TT.TaskToDoId IS NULL THEN 0 ELSE 1 END AS IsTaskTodo,
	CASE WHEN DT.DocumentToDoId IS NULL THEN 0 ELSE 1 END AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TODO T
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.ToDoId = OC.ObjectId AND OC.ObjectTypeId = @ToDoType)
	LEFT JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.ProjectId = @ProjectId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @ToDoType
			GROUP BY T.ObjectId
		) TS ON (T.ToDoId = TS.ObjectId)
  WHERE T.ProjectId = @ProjectId
	AND T.ActualStartDate IS NOT NULL AND T.ActualStartDate < @ToDate
	AND (T.ActualFinishDate IS NULL OR T.ActualFinishDate >= @FromDate)
UNION ALL
SELECT T.TaskId AS ObjectId, T.Title, T.IsCompleted, 0 AS IsToDo, OC.CategoryId, TS.Hours,
	0 AS IsIncidentTodo, 0 AS IsTaskTodo, 0 AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TASKS T
	LEFT JOIN OBJECT_CATEGORY OC ON (T.TaskId = OC.ObjectId AND OC.ObjectTypeId = @TaskType)
	LEFT JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.ProjectId = @ProjectId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @TaskType
			GROUP BY T.ObjectId
		) TS ON (T.TaskId = TS.ObjectId)
  WHERE T.ProjectId = @ProjectId
	AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND T.ActualStartDate IS NOT NULL AND T.ActualStartDate < @ToDate
	AND (T.ActualFinishDate IS NULL OR T.ActualFinishDate >= @FromDate)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetActiveByUser
	@FromDate as datetime,
	@ToDate as datetime,
	@UserId as int
as
DECLARE @ToDoType int
DECLARE @TaskType int
SET @ToDoType = 6
SET @TaskType = 5
SET @ToDate = DATEADD(d, 1, @ToDate)
SELECT T.ToDoId AS ObjectId, T.Title, T.IsCompleted, 1 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, OC.CategoryId, TS.Hours,
	CASE WHEN IT.IncidentToDoId IS NULL THEN 0 ELSE 1 END AS IsIncidentTodo,
	CASE WHEN TT.TaskToDoId IS NULL THEN 0 ELSE 1 END AS IsTaskTodo,
	CASE WHEN DT.DocumentToDoId IS NULL THEN 0 ELSE 1 END AS IsDocumentTodo,
	T.ActualFinishDate, T.ManagerId, U.LastName + ', ' + U.FirstName AS ManagerName, T.StateId
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.ToDoId = OC.ObjectId AND OC.ObjectTypeId = @ToDoType)
	LEFT JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.UserId = @UserId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @ToDoType
			GROUP BY T.ObjectId
		) TS ON (T.ToDoId = TS.ObjectId)
	LEFT JOIN USERS U ON (T.ManagerId = U.PrincipalId)
  WHERE T.ActualStartDate IS NOT NULL AND T.ActualStartDate < @ToDate
	AND (T.ActualFinishDate IS NULL OR T.ActualFinishDate >= @FromDate)
	AND T.ToDoId IN
		(SELECT ToDoId FROM TODO_RESOURCES R
		  WHERE PrincipalId = @UserId AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
UNION ALL
SELECT T.TaskId AS ObjectId, T.Title, T.IsCompleted, 0 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, OC.CategoryId, TS.Hours,
	0 AS IsIncidentTodo, 0 AS IsTaskTodo, 0 AS IsDocumentTodo,
	T.ActualFinishDate, P.ManagerId, U.LastName + ', ' + U.FirstName AS ManagerName, T.StateId
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.TaskId = OC.ObjectId AND OC.ObjectTypeId = @TaskType)
	LEFT JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.UserId = @UserId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @TaskType
			GROUP BY T.ObjectId
		) TS ON (T.TaskId = TS.ObjectId)
	LEFT JOIN USERS U ON (P.ManagerId = U.PrincipalId)
  WHERE T.ActualStartDate IS NOT NULL AND T.ActualStartDate < @ToDate
	AND (T.ActualFinishDate IS NULL OR T.ActualFinishDate >= @FromDate)
	AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND T.TaskId IN
		(SELECT TaskId FROM TASK_RESOURCES R
		  WHERE PrincipalId = @UserId AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetActiveByUserOnly
	@UserId as int,
	@LanguageId as int
as
DECLARE @ActiveState int, @OverdueState int
SET @ActiveState = 2
SET @OverdueState  = 3
SELECT T.ToDoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 1 AS IsToDo, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.CompletionTypeId, T.IsCompleted,
	TS.IsResource, TS.IsManager, T.StateId, T.ManagerId
  FROM TODO T, TODO_SECURITY_ALL TS, PRIORITY_LANGUAGE P
  WHERE T.ToDoId = TS.ToDoId AND TS.PrincipalId = @UserId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND (T.StateId = @ActiveState OR T.StateId = @OverdueState)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 0 AS IsToDo, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.CompletionTypeId, T.IsCompleted,
	TS.IsRealTaskResource AS IsResource, TS.IsManager, T.StateId, PR.ManagerId
  FROM TASKS T, TASK_SECURITY TS, PRIORITY_LANGUAGE P, PROJECTS PR
  WHERE T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId AND PR.ProjectId=T.ProjectId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND (T.StateId = @ActiveState OR T.StateId = @OverdueState)
ORDER BY StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetAssignedGroupdeByUser
	@UserId as int,
	@ProjectId as int
as
DECLARE @Dummy TABLE (ItemId int, Title nvarchar(255), IsCompleted bit, IsToDo int, PercentCompleted int,
	CompletionTypeId int, StartDate DateTime, FinishDate DateTime, UserId int, UserName nvarchar(100), StateId int)
INSERT INTO @Dummy
SELECT T.ToDoId AS ItemId, T.Title, T.IsCompleted, 1 AS IsToDo, T.PercentCompleted, T.CompletionTypeId,
	T.StartDate, T.FinishDate, R.PrincipalId AS UserId, U.LastName + ' ' + U.FirstName AS UserName, T.StateId
  FROM TODO T, TODO_RESOURCES R, Users U
  WHERE T.ToDoId = R.ToDoId
	AND R.PrincipalId = U.PrincipalId
	AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	AND T.ProjectId = @ProjectId
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.IsCompleted, 0 AS IsToDo, T.PercentCompleted, T.CompletionTypeId,
	T.StartDate, T.FinishDate, R.PrincipalId AS UserId, U.LastName + ' ' + U.FirstName AS UserName, T.StateId
FROM TASKS T, TASK_RESOURCES R, Users U
  WHERE T.TaskId = R.TaskId
	AND R.PrincipalId = U.PrincipalId
	AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	AND T.ProjectId = @ProjectId AND T.IsMileStone = 0 AND T.IsSummary = 0
SELECT 0 AS ItemId, '' AS Title, CAST(0 as bit) AS IsCompleted, 0 AS IsToDo, 0 AS PercentCompleted,
	0 AS CompletionTypeId, null AS StartDate, null as FinishDate, A.UserId, A.UserName, 0 AS StateId,
	CAST(1 as bit) AS IsHeader,
	CASE WHEN UPT.MemberId IS NULL THEN CAST(0 AS bit) ELSE CAST(1 AS bit) END AS IsCollapsed
  FROM
	(SELECT DISTINCT UserId, UserName FROM @Dummy) A
	LEFT JOIN USER_PROJECT_TEAM UPT ON (A.UserId = UPT.MemberId AND UPT.ProjectId = @ProjectId AND UPT.UserId = @UserId)
UNION ALL
SELECT ItemId, Title, IsCompleted, IsToDo, PercentCompleted,
	CompletionTypeId, StartDate, FinishDate, UserId, UserName, StateId,
	CAST(0 as bit) AS IsHeader, CAST(0 as bit) AS IsCollapsed
  FROM @Dummy
  WHERE UserId NOT IN (SELECT MemberId FROM USER_PROJECT_TEAM WHERE ProjectId = @ProjectId AND UserId = @UserId)
  ORDER BY UserName, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetByFilter
	@ProjectId as int,
	@UserId as int,
	@ResourceId as int,
	@StartDateCondition int,
	@StartDate as datetime = null,
	@FinishDateCondition int,
	@FinishDate as datetime = null,
	@SearchString as nvarchar(100),
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit,
	@CategoryType int
as
DECLARE @ToDoType as int
SET @ToDoType = 6
DECLARE @TaskType as int
SET @TaskType = 5
SET @SearchString = '%' + @SearchString + '%'
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 7)
	SET @IsExec = 1
SELECT T.ToDoId AS ItemId, T.Title, T.[Description], T.IsCompleted, 1 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, T.ManagerId, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete,
	T.PriorityId, T.PercentCompleted, T.StateId
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId OR (@ProjectId = -1 AND T.ProjectId IS NULL))
	AND (@ResourceId = 0 OR T.ToDoId IN (SELECT ToDoId FROM TODO_RESOURCES WHERE PrincipalId = @ResourceId))
	AND (	@StartDateCondition = 0
		OR
		@StartDateCondition = 1 AND
		(
			(T.StartDate IS NOT NULL AND T.StartDate >= @StartDate)
			OR
			(T.StartDate IS NULL AND T.CreationDate >= @StartDate)
		)
		OR
		@StartDateCondition = 2 AND
		(
			(T.StartDate IS NOT NULL AND T.StartDate < DATEADD(d, 1, @StartDate))
			OR
			(T.StartDate IS NULL AND T.CreationDate < DATEADD(d, 1, @StartDate))
		)
		OR
		@StartDateCondition = 3 AND
		(
			(T.StartDate IS NOT NULL AND T.StartDate >= @StartDate AND T.StartDate < DATEADD(d, 1, @StartDate))
			OR
			(T.StartDate IS NULL AND T.CreationDate >= @StartDate AND T.CreationDate < DATEADD(d, 1, @StartDate))
		)
	)
	AND (	@FinishDateCondition = 0
		OR
		@FinishDateCondition = 1 AND
		(
			(T.FinishDate IS NOT NULL AND T.FinishDate >= @FinishDate)
			OR
			(T.FinishDate IS NULL AND T.IsCompleted = 1 AND T.ActualFinishDate >= @FinishDate)
		)
		OR
		@FinishDateCondition = 2 AND
		(
			(T.FinishDate IS NOT NULL AND T.FinishDate < DATEADD(d, 1, @FinishDate))
			OR
			(T.FinishDate IS NULL AND T.IsCompleted = 1 AND T.ActualFinishDate < DATEADD(d, 1, @FinishDate))
		)
		OR
		@FinishDateCondition = 3 AND
		(
			(T.FinishDate IS NOT NULL AND T.FinishDate >= @FinishDate AND T.FinishDate < DATEADD(d, 1, @FinishDate))
			OR
			(T.FinishDate IS NULL AND T.IsCompleted = 1 AND T.ActualFinishDate >= @FinishDate AND T.ActualFinishDate < DATEADD(d, 1, @FinishDate))
		)
	)
	AND (
		(@GetAssigned = 1 AND T.ToDoId IN
			(SELECT ToDoId FROM TODO_RESOURCES R
			  WHERE PrincipalId = @UserId AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
			))
		OR
		(@GetManaged =1 AND (@IsPPM = 1 OR @IsExec = 1 OR T.ManagerId = @UserId))
		OR
		(@GetCreated = 1 AND T.CreatorId = @UserId)
	)
	AND (T.Title LIKE @SearchString OR T.[Description] LIKE @SearchString)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND T.ToDoId IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @ToDoType AND CU.UserId = @UserId
			)
		OR @CategoryType = 2 AND T.ToDoId NOT IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @ToDoType AND CU.UserId = @UserId
			)
		OR @CategoryType < 0 AND T.ToDoId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @ToDoType AND CategoryId = -@CategoryType
			)
	)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.[Description], T.IsCompleted, 0 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, P.ManagerId, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete,
	T.PriorityId, T.PercentCompleted, T.StateId
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
  WHERE
	(@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND (@ResourceId = 0 OR T.TaskId IN (SELECT TaskId FROM TASK_RESOURCES WHERE PrincipalId = @ResourceId))
	AND (	@StartDateCondition = 0
		OR
		@StartDateCondition = 1 AND T.StartDate >= @StartDate
		OR
		@StartDateCondition = 2 AND T.StartDate < DATEADD(d, 1, @StartDate)
		OR
		@StartDateCondition = 3 AND T.StartDate >= @StartDate AND T.StartDate < DATEADD(d, 1, @StartDate)
	)
	AND (	@FinishDateCondition = 0
		OR
		@FinishDateCondition = 1 AND T.FinishDate >= @FinishDate
		OR
		@FinishDateCondition = 2 AND T.FinishDate < DATEADD(d, 1, @FinishDate)
		OR
		@FinishDateCondition = 3 AND T.FinishDate >= @FinishDate AND T.FinishDate < DATEADD(d, 1, @FinishDate)
	)
	AND
	(
		(@GetAssigned = 1 AND T.IsMileStone = 0 AND T.IsSummary = 0 AND TS.IsResource = 1)
		OR
		(@GetManaged =1 AND (@IsPPM = 1 OR @IsExec = 1 OR TS.IsManager = 1))
		OR
		(@GetCreated = 1 AND T.CreatorId = @UserId)
	)
	AND (T.Title LIKE @SearchString OR T.[Description] LIKE @SearchString)
	AND (@CategoryType = 0
		OR @CategoryType = 1 AND T.TaskId IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @TaskType AND CU.UserId = @UserId
			)
		OR @CategoryType = 2 AND T.TaskId NOT IN
			(SELECT OC.ObjectId
			  FROM OBJECT_CATEGORY OC, CATEGORY_USER CU
			  WHERE OC.CategoryId = CU.CategoryId AND OC.ObjectTypeId = @TaskType AND CU.UserId = @UserId
			)
		OR @CategoryType < 0 AND T.TaskId IN
			(SELECT ObjectId
			  FROM OBJECT_CATEGORY
			  WHERE ObjectTypeId = @TaskType AND CategoryId = -@CategoryType
			)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetCompleted
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId AS ItemId, T.Title, T.[Description], T.IsCompleted, 1 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, T.ManagerId, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.ActualFinishDate AS FinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE T.IsCompleted = 1
	AND
	(
		(@GetAssigned = 1 AND T.ToDoId IN
			(SELECT ToDoId FROM TODO_RESOURCES R
			  WHERE PrincipalId = @UserId AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
			)
		)
		OR
		(@GetManaged =1 AND T.ManagerId = @UserId)
		OR
		(@GetCreated = 1 AND T.CreatorId = @UserId)
	)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.[Description], T.IsCompleted, 0 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, P.ManagerId, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.ActualFinishDate AS FinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
  WHERE T.IsCompleted = 1
	AND
	(
		(@GetAssigned = 1 AND T.IsMileStone = 0 AND T.IsSummary = 0 AND TS.IsResource = 1)
		OR
		(@GetManaged =1 AND TS.IsManager = 1)
		OR
		(@GetCreated = 1 AND T.CreatorId = @UserId)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetCompletedByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
SELECT T.ToDoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 1 AS IsToDo,
	T.CreationDate, T.ActualFinishDate, T.StateId
  FROM TODO T, TODO_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ToDoId = R.ToDoId AND R.PrincipalId = @UserId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsCompleted=1
	AND NOT (R.MustBeConfirmed=1 AND R.ResponsePending=0 AND R.IsConfirmed=0)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 0 AS IsToDo,
	T.CreationDate, T.ActualFinishDate, T.StateId
  FROM TASKS T, TASK_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.TaskId = R.TaskId AND R.PrincipalId = @UserId
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsCompleted=1
	AND NOT (R.MustBeConfirmed=1 AND R.ResponsePending=0 AND R.IsConfirmed=0)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetForManagerView
	@PrincipalId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
SELECT T.ToDoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 6 AS ItemType, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	T.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId
  FROM TODO T, PRIORITY_LANGUAGE P
  WHERE (@ManagerId=0 OR T.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
	AND
	(
		@PrincipalId = 1
	OR
		ToDoId IN (SELECT ToDoId FROM TODO_SECURITY_ALL
				WHERE IsResource = 1 AND (PrincipalId = @PrincipalId OR PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId))
			)
	)
 UNION ALL
 SELECT T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 5 AS ItemType, T.CreationDate, T.StartDate, T.FinishDate, T.PercentCompleted, T.IsCompleted,
	PR.ManagerId, T.ReasonId, T.ProjectId, T.StateId, T.CompletionTypeId
  FROM TASKS T,  PRIORITY_LANGUAGE P, PROJECTS PR
  WHERE T.ProjectId=PR.ProjectId
	AND (@ManagerId=0 OR PR.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND(T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1))
	OR((@ShowActive=1 AND (T.StateId=@ActiveState OR T.StateId=@OverdueState)))
	)
	AND
	(
		@PrincipalId = 1
	OR
		TaskId IN (SELECT TaskId FROM TASK_SECURITY
				WHERE IsRealTaskResource = 1 AND (PrincipalId = @PrincipalId OR PrincipalId IN (SELECT UserId FROM User_Group UG WHERE UG.GroupId=@PrincipalId))
			)
	)
ORDER By ItemType, FinishDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetForResourceView
	@UserId as int,
	@LanguageId as int,
	@ManagerId as int,
	@ProjectId as int,
	@ShowActive as bit,
	@CompletedDate as datetime=null,
	@StartDate as datetime=null
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
DECLARE @UpcomingState as int
set @UpcomingState=1
DECLARE @ActiveState as int
set @ActiveState=2
DECLARE @OverdueState as int
set @OverdueState=3
DECLARE @All int
SET @All = 1
 SELECT DISTINCT T.ToDoId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 6 AS ItemType, T.CreationDate, T.StartDate, T.FinishDate,
	CASE WHEN T.ReasonId = @All THEN TR.PercentCompleted ELSE T.PercentCompleted END AS PercentCompleted,
	T.IsCompleted, T.ManagerId, T.ReasonId, T.ProjectId, PR.Title as ProjectTitle, T.StateId, T.CompletionTypeId
  FROM TODO T
  LEFT JOIN PROJECTS PR ON T.ProjectId=PR.ProjectId
  JOIN TODO_SECURITY_ALL TS ON (T.ToDoId = TS.ToDoId AND TS.IsResource=1 AND TS.PrincipalId = @UserId)
  JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  JOIN TODO_RESOURCES TR ON (TR.ToDoId = T.ToDoId) AND (TR.PrincipalId=@UserId)
  WHERE (@ManagerId=0 OR T.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND ((T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1)) OR (TR.ActualFinishDate>=@CompletedDate AND TR.PercentCompleted=100) )
	OR(@ShowActive=1 AND TR.PercentCompleted!=100 AND(T.StateId=@ActiveState OR T.StateId=@OverdueState))
	)
 UNION ALL
 SELECT DISTINCT T.TaskId AS ItemId, T.Title, P.PriorityId, P.PriorityName, 5 AS ItemType, T.CreationDate, T.StartDate, T.FinishDate,
	CASE WHEN T.ReasonId = @All THEN TR.PercentCompleted ELSE T.PercentCompleted END AS PercentCompleted,
	T.IsCompleted, PR.ManagerId, T.ReasonId, T.ProjectId, PR.Title as ProjectTitle, T.StateId, T.CompletionTypeId
  FROM TASKS T
  LEFT JOIN PROJECTS PR ON T.ProjectId=PR.ProjectId
  JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.IsRealTaskResource=1 AND TS.PrincipalId = @UserId)
  JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  JOIN TASK_RESOURCES TR ON (TR.TaskId = T.TaskId) AND (TR.PrincipalId=@UserId)
  WHERE (@ManagerId=0 OR PR.ManagerId=@ManagerId)
	AND (@ProjectId=0 OR T.ProjectId=@ProjectId)
	AND T.IsMilestone = 0 AND T.IsSummary = 0
	AND
	(
	((@StartDate is not null)AND(T.StartDate<=@StartDate)AND(T.StateId=@UpcomingState))
	OR((@CompletedDate is not null)AND ((T.ActualFinishDate>=@CompletedDate)AND(T.IsCompleted=1)) OR (TR.ActualFinishDate>=@CompletedDate AND TR.PercentCompleted=100) )
	OR(@ShowActive=1 AND TR.PercentCompleted!=100 AND(T.StateId=@ActiveState OR T.StateId=@OverdueState))
	)
ORDER By ItemType, T.FinishDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetForUser
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit
as
DECLARE @TaskObjectType int
SET @TaskObjectType = 5
DECLARE @ToDoObjectType int
SET @ToDoObjectType = 6
SELECT ItemId, Title, CreatorId, IsToDo, StartDate, FinishDate, CreationDate, IsCompleted, CompletionTypeId, ReasonId, StateId
FROM
	(SELECT ToDoId AS ItemId, Title,  IsCompleted, CompletionTypeId, ReasonId, CreatorId,
		1 AS IsToDo, StartDate, FinishDate, StateId, CreationDate
	  FROM TODO
	  WHERE (@GetAssigned = 1 AND ToDoId IN
			(SELECT ToDoId FROM TODO_SECURITY_ALL S
			  WHERE PrincipalId = @UserId AND IsResource = 1))
		OR (@GetManaged = 1 AND ManagerId = @UserId)
		OR (@GetCreated = 1 AND CreatorId = @UserId)
	UNION ALL
	SELECT T.TaskId  AS ItemId, Title, IsCompleted, CompletionTypeId, ReasonId, CreatorId,
		0 AS IsToDo, StartDate, FinishDate, T.StateId, CreationDate
	  FROM TASKS T
		LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
	  WHERE (@GetAssigned = 1 AND TS.IsResource = 1)
		OR (@GetManaged = 1 AND TS.IsManager = 1)
		OR (@GetCreated = 1 AND CreatorId = @UserId)
	) A
ORDER BY CreationDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetManagedByResource
	@UserId as int,
	@ResourceId as int,
	@ProjectId as int
as
DECLARE @ToDoType int
SET @ToDoType = 6
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId AS ItemId, T.Title, T.PriorityId, 1 AS IsToDo, T.ManagerId, T.CompletionTypeId,  T.ReasonId,
	T.ProjectId, P.Title AS ProjectTitle, T.IsCompleted,
	T.StartDate, T.FinishDate, T.ActualFinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE (T.ManagerId = @UserId OR T.CreatorId = @UserId)
	AND (@ResourceId = 0 OR T.ToDoId IN (SELECT ToDoId FROM TODO_RESOURCES WHERE PrincipalId = @ResourceId))
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId OR (@ProjectId = -1 AND T.ProjectId IS NULL))
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.PriorityId, 0 AS IsToDo, P.ManagerId, T.CompletionTypeId, T.ReasonId,
	T.ProjectId, P.Title AS ProjectTitle, T.IsCompleted, T.StateId,
	T.StartDate, T.FinishDate, T.ActualFinishDate,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM TASKS T
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
  WHERE T.IsSummary = 0 AND (P.ManagerId = @UserId OR T.CreatorId = @UserId)
	AND (@ResourceId = 0 OR TS.IsResource = 1)
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetNotApproved
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT T.ToDoId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TODO T, PRIORITY_LANGUAGE PL
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND T.ManagerId = @UserId
	AND T.IsCompleted=0  AND T.PercentCompleted = 100
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T, PROJECTS P, PRIORITY_LANGUAGE PL
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ProjectId = P.ProjectId AND T.IsSummary = 0 AND T.IsMilestone = 0
	AND T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND P.ManagerId = @UserId
	AND T.IsCompleted=0  AND T.PercentCompleted = 100
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetNotCompleted
	@UserId as int,
	@LanguageId as int,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit
as
DECLARE @ToDoType int
SET @ToDoType = 6
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 1 AS IsToDo, T.ManagerId, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.ProjectId, P.Title AS ProjectTitle, T.StartDate, T.FinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete
  FROM TODO T
	JOIN PRIORITY_LANGUAGE PL ON (T.PriorityId = PL.PriorityId )
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
  WHERE PL.LanguageId = @LanguageId
	AND T.IsCompleted=0
	AND
	(
		(@GetAssigned = 1 AND T.ToDoId IN
			(SELECT ToDoId FROM TODO_RESOURCES TR
			  WHERE TR.PrincipalId = @UserId
				AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND IsConfirmed = 0)))
		OR
		(@GetManaged =1 AND T.ManagerId = @UserId)
		OR
		(@GetCreated =1 AND T.CreatorId = @UserId)
	)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 0 AS IsToDo, P.ManagerId, T.IsCompleted, T.CompletionTypeId,T.ReasonId,
	T.ProjectId, P.Title AS ProjectTitle, T.StartDate, T.FinishDate, T.StateId,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM TASKS T
	JOIN PRIORITY_LANGUAGE PL ON (T.PriorityId = PL.PriorityId )
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN TASK_SECURITY TS ON (T.TaskId = TS.TaskId AND TS.PrincipalId = @UserId)
  WHERE PL.LanguageId = @LanguageId
	AND T.IsCompleted=0  AND T.IsSummary = 0
	AND
	(
		(@GetAssigned = 1 AND T.IsMilestone=0 AND T.TaskId IN
			(SELECT TaskId FROM TASK_RESOURCES TR
			  WHERE TR.PrincipalId = @UserId
				AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND IsConfirmed = 0)))
		OR
		(@GetManaged =1 AND TS.IsManager = 1)
		OR
		(@GetCreated =1 AND T.CreatorId = @UserId)
	)
ORDER BY T.StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetPastDueByProject
	@ProjectId as int
as
DECLARE @OverdueState int
SET @OverdueState = 3
SELECT ToDoId AS ItemId, Title, [Description], 1 AS IsToDo, FinishDate
  FROM TODO
  WHERE ProjectId = @ProjectId AND StateId = @OverdueState
UNION ALL
SELECT TaskId AS ItemId, Title, [Description], 0 AS IsToDo, FinishDate
  FROM TASKS
  WHERE ProjectId = @ProjectId AND IsSummary = 0 AND IsMileStone = 0 AND StateId = @OverdueState
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetPending
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT T.ToDoId AS ItemId, T.Title, T.PriorityId, P.PriorityName, T.ManagerId, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TODO T, TODO_RESOURCES R, PRIORITY_LANGUAGE P
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ToDoId = R.ToDoId AND R.PrincipalId = @UserId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsCompleted=0
	AND (R.MustBeConfirmed=1 AND R.ResponsePending=1)
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.PriorityId, P.PriorityName, PR.ManagerId, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T, TASK_RESOURCES R, PRIORITY_LANGUAGE P, PROJECTS PR
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.TaskId = R.TaskId AND R.PrincipalId = @UserId AND T.ProjectId = PR.ProjectId
	AND T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId
	AND T.IsCompleted=0  AND T.IsMileStone = 0 AND T.IsSummary = 0
	AND (R.MustBeConfirmed=1 AND R.ResponsePending=1)
ORDER BY StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetUpdatedByUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @ToDoObjectType int
DECLARE @TaskObjectType int
SET @ToDoObjectType = 6
SET @TaskObjectType = 5
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
SELECT T.ToDoId AS ItemId, T.Title, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate, A.LastSavedDate, T.StateId
  FROM TODO T,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @ToDoObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE T.ToDoId = A.ObjectId
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
UNION ALL
SELECT T.TaskId  AS ItemId, T.Title, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId,
	T.StartDate, T.FinishDate, A.LastSavedDate, T.StateId
  FROM TASKS T,
	(
		SELECT E.ObjectId, MAX(E.Dt) AS LastSavedDate
		  FROM SYSTEM_EVENTS E
			JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
		  WHERE T.ObjectTypeId = @TaskObjectType
			AND E.UserId = @UserId
		  GROUP BY E.ObjectId
	) A
  WHERE T.TaskId = A.ObjectId
	AND (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND DATEDIFF(dd, DATEADD(mi, @TimeOffset, A.LastSavedDate), @UserDate) <= @Days
  ORDER BY A.LastSavedDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetUpdatedForUser
	@ProjectId as int,
	@UserId as int,
	@TimeZoneId as int,
	@Days as int
as
SET NOCOUNT ON
DECLARE @TimeOffset int
SELECT @TimeOffset = -Bias FROM TIMEZONES WHERE TimeZoneId = @TimeZoneId
IF @TimeOffset IS NULL
	SET @TimeOffset = 0
DECLARE @UserDate datetime
SET @UserDate = DATEADD(mi, @TimeOffset, GETUTCDATE())
DECLARE @TaskObjectType int
SET @TaskObjectType = 5
DECLARE @ToDoObjectType int
SET @ToDoObjectType = 6
SELECT ItemId, Title, LastEditorId, IsToDo, StartDate, FinishDate, LastSavedDate, IsCompleted, CompletionTypeId, ProjectId, ProjectName, ReasonId, StateId
  FROM
	(SELECT T.ToDoId AS ItemId, T.Title, SE.UserId AS LastEditorId,
		1 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId, T.StartDate, T.FinishDate, T.StateId,
		ISNULL(T.ProjectId, -1) AS ProjectId, ISNULL(P.Title, '') AS ProjectName, SE.Dt AS LastSavedDate
	  FROM TODO T
		JOIN SYSTEM_EVENTS SE ON (T.ToDoId = SE.ObjectId)
		LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
		AND (T.ToDoId IN (SELECT ToDoId FROM TODO_SECURITY_ALL S
			 	 WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
			OR T.CreatorId = @UserId)
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @ToDoObjectType
			  GROUP BY E.ObjectId)
	UNION ALL
	SELECT T.TaskId  AS ItemId, T.Title, SE.UserId AS LastEditorId,
		0 AS IsToDo, T.IsCompleted, T.CompletionTypeId,  T.ReasonId, T.StartDate, T.FinishDate, T.StateId,
		T.ProjectId, P.Title AS ProjectName, SE.Dt AS LastSavedDate
	  FROM TASKS T
		JOIN SYSTEM_EVENTS SE ON (T.TaskId = SE.ObjectId)
		JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
		AND T.TaskId IN (SELECT TaskId FROM TASK_SECURITY S
				  WHERE PrincipalId = @UserId AND (IsResource = 1 OR IsManager = 1))
		AND SE.SystemEventId IN
			(SELECT MAX(E.SystemEventId)
			  FROM SYSTEM_EVENTS E
				JOIN SYSTEM_EVENT_TYPES T ON (E.EventTypeId = T.EventTypeId)
			  WHERE T.ObjectTypeId = @TaskObjectType
			  GROUP BY E.ObjectId)
	) A
  WHERE  DATEDIFF(dd, DATEADD(mi, @TimeOffset, LastSavedDate), @UserDate) <= @Days
  ORDER BY LastSavedDate DESC
SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetWithoutResources
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT T.ToDoId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 1 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TODO T, PRIORITY_LANGUAGE PL
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND T.ManagerId = @UserId
	AND T.IsCompleted=0
	AND T.ToDoId NOT IN (SELECT ToDoId FROM TODO_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
UNION ALL
SELECT T.TaskId AS ItemId, T.Title, T.PriorityId, PL.PriorityName, 0 AS IsToDo, T.IsCompleted, T.CompletionTypeId, T.ReasonId,
	T.StartDate, T.FinishDate, T.StateId
  FROM TASKS T, PROJECTS P, PRIORITY_LANGUAGE PL
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId)
	AND T.ProjectId = P.ProjectId
	AND T.PriorityId = PL.PriorityId AND PL.LanguageId = @LanguageId
	AND P.ManagerId = @UserId
	AND T.IsCompleted=0  AND IsSummary = 0 AND IsMilestone = 0
	AND T.TaskId NOT IN (SELECT TaskId FROM TASK_RESOURCES WHERE NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0))
	AND T.TaskId NOT IN (SELECT TaskId FROM TASK_TODO)
ORDER BY StartDate DESC
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetWithTimeSheetByProject
	@FromDate as datetime,
	@ToDate as datetime,
	@ProjectId as int
as
DECLARE @ToDoType int
DECLARE @TaskType int
SET @ToDoType = 6
SET @TaskType = 5
SET @ToDate = DATEADD(d, 1, @ToDate)
SELECT T.ToDoId AS ObjectId, T.Title, T.IsCompleted, 1 AS IsToDo, OC.CategoryId, TS.Hours,
	CASE WHEN IT.IncidentToDoId IS NULL THEN 0 ELSE 1 END AS IsIncidentTodo,
	CASE WHEN TT.TaskToDoId IS NULL THEN 0 ELSE 1 END AS IsTaskTodo,
	CASE WHEN DT.DocumentToDoId IS NULL THEN 0 ELSE 1 END AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TODO T
	JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.ProjectId = @ProjectId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @ToDoType
			GROUP BY T.ObjectId
		) TS ON (T.ToDoId = TS.ObjectId)
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.ToDoId = OC.ObjectId AND OC.ObjectTypeId = @ToDoType)
  WHERE T.ProjectId = @ProjectId
	AND T.ToDoId IN
		(SELECT T.ObjectId FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId AND @FromDate <= W.StartDate AND W.StartDate <= @ToDate AND T.ObjectTypeId = @ToDoType)
UNION ALL
SELECT T.TaskId AS ObjectId, T.Title, T.IsCompleted, 0 AS IsToDo, OC.CategoryId, TS.Hours,
	0 AS IsIncidentTodo, 0 AS IsTaskTodo, 0 AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TASKS T
	JOIN (SELECT T.ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.ProjectId = @ProjectId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @TaskType
			GROUP BY T.ObjectId
		) TS ON (T.TaskId = TS.ObjectId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.TaskId = OC.ObjectId AND OC.ObjectTypeId = @TaskType)
  WHERE T.ProjectId = @ProjectId
	AND T.TaskId IN
		(SELECT T.ObjectId FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId AND @FromDate <= W.StartDate AND W.StartDate <= @ToDate AND T.ObjectTypeId = @TaskType )
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoAndTasksGetWithTimeSheetByUser
	@FromDate as datetime,
	@ToDate as datetime,
	@UserId as int
as
DECLARE @ToDoType int
DECLARE @TaskType int
SET @ToDoType = 6
SET @TaskType = 5
SET @ToDate = DATEADD(d, 1, @ToDate)
SELECT T.ToDoId AS ObjectId, T.Title, T.IsCompleted, 1 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, OC.CategoryId, TS.Hours,
	CASE WHEN IT.IncidentToDoId IS NULL THEN 0 ELSE 1 END AS IsIncidentTodo,
	CASE WHEN TT.TaskToDoId IS NULL THEN 0 ELSE 1 END AS IsTaskTodo,
	CASE WHEN DT.DocumentToDoId IS NULL THEN 0 ELSE 1 END AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TODO T
	JOIN (SELECT ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.UserId = @UserId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @ToDoType
			GROUP BY T.ObjectId
		) TS ON (T.ToDoId = TS.ObjectId)
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.ToDoId = OC.ObjectId AND OC.ObjectTypeId = @ToDoType)
UNION ALL
SELECT T.TaskId AS ObjectId, T.Title, T.IsCompleted, 0 AS IsToDo, T.ProjectId, P.Title AS ProjectTitle, OC.CategoryId, TS.Hours,
	0 AS IsIncidentTodo, 0 AS IsTaskTodo, 0 AS IsDocumentTodo,
	T.ActualFinishDate, T.StateId
  FROM TASKS T
	JOIN (SELECT ObjectId, SUM(T.TotalApproved) AS Hours
			FROM WeekTimeSheet W, TIMESHEETS T
			WHERE W.WeekTimeSheetId = T.WeekTimeSheetId
				AND W.Userid = @UserId AND @FromDate <= W.StartDate AND W.StartDate < @ToDate
				AND T.ObjectTypeId = @TaskType
			GROUP BY T.ObjectId
		) TS ON (T.TaskId = TS.ObjectId)
	JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN OBJECT_CATEGORY OC ON (T.TaskId = OC.ObjectId AND OC.ObjectTypeId = @TaskType)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoCheckForChangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM TODO_RESOURCES WHERE PrincipalId = @UserId)
	SET @Retval = 1
ELSE BEGIN
	IF EXISTS (SELECT * FROM TODO WHERE ManagerId = @UserId)
		SET @Retval = 1
	ELSE
		SET @Retval = 0
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoCheckForUnchangeableRoles
	@UserId as int,
	@Retval int output
as
IF EXISTS(SELECT * FROM TODO WHERE CreatorId = @UserId OR CompletedBy = @UserId)
	SET @Retval = 1
ELSE
	SET @Retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoCreate
	@ProjectId as int = null ,
	@CreatorId as int ,
	@ManagerId as int ,
	@Title as nvarchar(255) ,
	@Description as ntext,
	@CreationDate as datetime ,
	@StartDate as datetime = null,
	@FinishDate as datetime = null,
	@PriorityId as int ,
	@ActivationTypeId as int,
	@CompletionTypeId as int ,
	@MustBeConfirmed as bit,
	@TaskTime as int,
	@retval int output
as
INSERT INTO TODO (ProjectId, CreatorId, ManagerId, Title, [Description], CreationDate, StartDate, FinishDate, PriorityId, ActivationTypeId, CompletionTypeId, MustBeConfirmed, TaskTime)
  VALUES(@ProjectId, @CreatorId, @ManagerId, @Title, @Description, @CreationDate, @StartDate, @FinishDate, @PriorityId, @ActivationTypeId, @CompletionTypeId, @MustBeConfirmed, @TaskTime)
select @retval = @@identity
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoDelete
	@ToDoId as int
AS
DECLARE @TodoObjectType int
SET @TodoObjectType = 6
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @TodoObjectType AND ObjectId = @ToDoId
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @TodoObjectType AND ObjectId = @ToDoId
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @TodoObjectType AND ObjectId = @ToDoId
	IF @@ERROR != 0
		GOTO err
	DELETE TODO_RESOURCES WHERE ToDoId = @ToDoId
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @TodoObjectType AND ObjectId = @ToDoId
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId = @ToDoId AND EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId = @ToDoId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId = @ToDoId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId = @ToDoId AND DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM TODO  WHERE ToDoId = @ToDoId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoDeleteByProject
	@ProjectId as int
AS
DECLARE @TodoObjectType int
SET @TodoObjectType = 6
BEGIN TRAN
	DELETE DISCUSSIONS WHERE ObjectTypeId = @TodoObjectType AND ObjectId IN
		(SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE EXTERNAL_GATE WHERE ObjectTypeId = @TodoObjectType AND ObjectId IN
		(SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE OBJECT_CATEGORY WHERE ObjectTypeId = @TodoObjectType AND ObjectId IN
		(SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE TODO_RESOURCES WHERE ToDoId IN
		(SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE FAVORITES WHERE ObjectTypeId = @TodoObjectType AND ObjectId IN
		(SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId)
	IF @@ERROR != 0
		GOTO err
	DELETE SUBSCRIPTIONS WHERE ObjectId IN (SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId) AND
		EventTypeId IN (SELECT EventTypeId FROM SYSTEM_EVENT_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE REMINDER_SUBSCRIPTIONS WHERE ObjectId IN (SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE ObjectId IN (SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_HOOKS WHERE ObjectId IN (SELECT ToDoId FROM TODO WHERE ProjectId = @ProjectId) AND
		DateTypeId IN (SELECT DateTypeId FROM DATE_TYPES WHERE ObjectTypeId = @TodoObjectType)
	IF @@ERROR != 0
		GOTO err
	DELETE FROM TODO  WHERE ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGet
	@ToDoId as int,
	@LanguageId as int
as
DECLARE @ToDoType int
SET @ToDoType = 6
SELECT T.ToDoId, T.ProjectId, P.Title AS ProjectTitle, IT.IncidentId, I.Title AS IncidentTitle, IT.StatusId,
	DT.DocumentId, D.Title AS DocumentTitle, DT.CompleteDocument,
	T.CreatorId, T.ManagerId, T.CompletedBy, T.Title, T.[Description],
	T.CreationDate, T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.PriorityId, PR.PriorityName, T.PercentCompleted, T.IsActual, T.CompletionTypeId, CT.CompletionTypeName,
	T.IsCompleted, T.MustBeConfirmed, T.ReasonId, TT.TaskId, TT.CompleteTask, TA.Title AS TaskTitle, T.StateId,
	OS.StateName, T.ActivationTypeId, T.TaskTime
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
		LEFT JOIN INCIDENTS I ON (IT.IncidentId = I.IncidentId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
		LEFT JOIN DOCUMENTS D ON (DT.DocumentId = D.DocumentId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
		LEFT JOIN TASKS TA ON (TT.TaskId = TA.TaskId)
	JOIN PRIORITY_LANGUAGE PR ON (T.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN COMPLETION_TYPE_LANGUAGE CT ON (T.CompletionTypeId = CT.CompletionTypeId AND CT.LanguageId = @LanguageId)
	JOIN OBJECT_STATE_LANGUAGE OS ON (T.StateId = OS.StateId AND OS.LanguageId = @LanguageId)
  WHERE T.ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetAllForUserByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
SELECT T.ToDoId, T.Title, T.[Description], T.PriorityId, P.PriorityName, PercentCompleted, IsCompleted, StartDate, FinishDate, T.StateId
  FROM TODO T
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE ProjectId = @ProjectId
	AND ToDoId IN
		(SELECT ToDoId FROM TODO_RESOURCES R
		  WHERE PrincipalId = @UserId AND R.ToDoId = T.ToDoId
		)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetByDocument
	@DocumentId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId, T.Title, T.[Description], T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.PercentCompleted, T.IsCompleted, T.ReasonId, R.ReasonName, T.CompletedBy, T.StateId
  FROM TODO T
	JOIN COMPLETION_REASON_LANGUAGE R ON (T.ReasonId = R.ReasonId AND R.LanguageId = @LanguageId)
  WHERE
	ToDoId IN (SELECT ToDoId FROM DOCUMENT_TODO WHERE DocumentId = @DocumentId)
	AND
	(
		@IsPPM = 1
		OR
		ToDoId IN (SELECT ToDoId FROM TODO_SECURITY_ALL WHERE PrincipalId = @UserId)
		OR
		@UserId IN (SELECT PrincipalId FROM DOCUMENT_SECURITY_ALL WHERE DocumentId = @DocumentId AND IsManager = 1)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetByFilter
	@ProjectId as int,
	@UserId as int,
	@ResourceId as int,
	@StartDate as datetime,
	@FinishDate as datetime,
	@GetAssigned as bit,
	@GetManaged as bit,
	@GetCreated as bit,
	@Keyword as nvarchar(100)
as
SET @Keyword = '%' + @Keyword + '%'
SET @FinishDate = DATEADD(d, 1, @FinishDate)
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId, T.Title, T.[Description], T.IsCompleted, T.StartDate, T.FinishDate, T.CreationDate,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR T.ManagerId = @UserId THEN 1 ELSE 0 END AS CanDelete,
	T.PriorityId, T.PercentCompleted, T.StateId
  FROM TODO T
  WHERE (@ProjectId = 0 OR T.ProjectId = @ProjectId OR (@ProjectId = -1 AND T.ProjectId IS NULL))
	AND (
		(T.StartDate IS NOT NULL AND T.FinishDate IS NOT NULL AND T.StartDate  < @FinishDate AND T.FinishDate > @StartDate)
		OR (T.StartDate IS NOT NULL AND T.FinishDate IS NULL AND T.StartDate < @FinishDate AND (T.IsCompleted = 0 OR T.ActualFinishDate > @StartDate))
		OR (T.StartDate IS NULL AND T.FinishDate IS NOT NULL AND T.CreationDate < @FinishDate AND T.FinishDate > @StartDate)
		OR (T.StartDate IS NULL AND T.FinishDate IS NULL AND T.CreationDate < @FinishDate AND (T.IsCompleted = 0 OR T.ActualFinishDate > @StartDate))
	)
	AND (@Keyword = '%%' OR T.Title LIKE @Keyword OR T.[Description] LIKE @Keyword)
	AND
	(
		(@GetAssigned = 1 AND (@ResourceId = 0 OR T.ToDoId IN
			(SELECT ToDoId FROM TODO_RESOURCES R
			  WHERE PrincipalId = @ResourceId AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
			)))
		OR
		(@GetManaged =1 AND (@ResourceId = 0 OR T.ManagerId = @ResourceId))
		OR
		(@GetCreated =1 AND (@ResourceId = 0 OR T.CreatorId = @ResourceId))
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetByIncident
	@IncidentId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId, T.Title, T.[Description], T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.PercentCompleted, T.IsCompleted, T.ReasonId, R.ReasonName, T.CompletedBy, T.StateId
  FROM TODO T
	JOIN COMPLETION_REASON_LANGUAGE R ON (T.ReasonId = R.ReasonId AND R.LanguageId = @LanguageId)
  WHERE
	ToDoId IN (SELECT ToDoId FROM INCIDENT_TODO WHERE IncidentId = @IncidentId)
	AND
	(
		@IsPPM = 1
		OR
		ToDoId IN (SELECT ToDoId FROM TODO_SECURITY_ALL WHERE PrincipalId = @UserId)
		OR
		@UserId IN (SELECT PrincipalId FROM INCIDENT_SECURITY_ALL WHERE IncidentId = @IncidentId AND IsManager = 1)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetByProject
	@ProjectId as int,
	@LanguageId as int
as
SELECT T.ToDoId, T.Title, T.[Description], T.StartDate, T.FinishDate,
	T.IsCompleted, T.PercentCompleted, P.PriorityId, P.PriorityName, T.StateId
  FROM TODO T
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetByTask
	@TaskId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = 4)
	SET @IsPPM = 1
SELECT T.ToDoId, T.Title, T.[Description], T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.PercentCompleted, T.IsCompleted, T.ReasonId, R.ReasonName, T.CompletedBy, T.StateId, T.PriorityId
  FROM TODO T
	JOIN COMPLETION_REASON_LANGUAGE R ON (T.ReasonId = R.ReasonId AND R.LanguageId = @LanguageId)
  WHERE
	ToDoId IN (SELECT ToDoId FROM TASK_TODO WHERE TaskId = @TaskId)
	AND
	(	@IsPPM = 1
		OR
		ToDoId IN (SELECT ToDoId FROM TODO_SECURITY_ALL WHERE PrincipalId = @UserId)
		OR
		@UserId IN (SELECT PrincipalId FROM TASK_SECURITY WHERE TaskId = @TaskId AND IsManager = 1)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetContainerManagers
	@ToDoId int
AS
DECLARE @false bit
SET @false = 0
SELECT ManagerId AS UserId, @false AS MustBeConfirmed, @false AS ResponsePending, @false AS IsConfirmed
 FROM INCIDENTS
 WHERE IncidentId IN (SELECT IncidentId FROM INCIDENT_TODO WHERE ToDoId = @ToDoId)
UNION ALL
SELECT PrincipalId AS UserId, MustBeConfirmed, ResponsePending, IsConfirmed
 FROM INCIDENT_RESOURCES
 WHERE CanManage = 1 AND IncidentId IN (SELECT IncidentId FROM INCIDENT_TODO WHERE ToDoId = @ToDoId)
UNION ALL
SELECT P.ManagerId AS UserId, @false AS MustBeConfirmed, @false AS ResponsePending, @false AS IsConfirmed
 FROM TASKS T
 JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
 WHERE TaskId IN (SELECT TaskId FROM Task_TODO WHERE ToDoId = @ToDoId)
UNION ALL
SELECT PrincipalId AS UserId, MustBeConfirmed, ResponsePending, IsConfirmed
 FROM TASK_RESOURCES
 WHERE CanManage = 1 AND TaskId IN (SELECT TaskId FROM TASK_TODO WHERE ToDoId = @ToDoId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TodoGetForChangeableRoles
	@UserId as int,
	@CurrentUserId as int
as
DECLARE @IsPPM bit
SET @IsPPM = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 4)
	SET @IsPPM = 1
DECLARE @IsExec bit
SET @IsExec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @CurrentUserId AND GroupId = 7)
	SET @IsExec = 1
SELECT T.ToDoId, T.Title, T.IsCompleted, T.CompletionTypeId, T.ReasonId, T.StartDate, T.FinishDate, T.StateId,
	CASE WHEN T.ManagerId = @UserId THEN 1 ELSE 0 END AS IsManager,
	CASE WHEN TR.ResourceId IS NOT NULL THEN 1 ELSE 0 END AS IsResource,
	CASE WHEN @IsPPM = 1 OR @IsExec = 1 OR TS.IsManager = 1 OR TS.IsResource = 1 THEN 1 ELSE 0 END AS CanView,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanEdit,
	CASE WHEN @IsPPM = 1 OR TS.IsManager = 1 THEN 1 ELSE 0 END AS CanDelete
  FROM TODO T
	LEFT JOIN TODO_SECURITY_ALL TS ON (T.ToDoId = TS.ToDoId AND TS.PrincipalId = @CurrentUserId)
	LEFT JOIN TODO_RESOURCES TR ON (T.ToDoId = TR.ToDoId AND TR.PrincipalId = @UserId)
  WHERE T.ManagerId = @UserId OR TR.ResourceId IS NOT NULL
  ORDER BY T.Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TodoGetForEventScheduling
	@EventId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT TR.PrincipalId AS UserId, T.ToDoId, T.StartDate, T.FinishDate, T.StateId
  FROM TODO T
	JOIN TODO_RESOURCES TR ON (T.ToDoId = TR.ToDoId)
	JOIN EVENT_SECURITY_ALL S ON (TR.PrincipalId = S.PrincipalId)
  WHERE T.IsCompleted = 0
	AND T.StartDate IS NOT NULL AND T.FinishDate IS NOT NULL AND T.StartDate < @FinishDate AND T.FinishDate > @StartDate
	AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND TR.IsConfirmed = 0)
	AND (S.IsResource = 1 OR S.IsManager = 1)
	AND S.EventId = @EventId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TodoGetForScheduling
	@UserId as int,
	@StartDate as datetime,
	@FinishDate as datetime
as
SET @FinishDate = DATEADD(d, 1, @FinishDate)
SELECT TR.PrincipalId AS UserId, T.ToDoId, T.StartDate, T.FinishDate, T.StateId
  FROM TODO T
	JOIN TODO_RESOURCES TR ON (T.ToDoId = TR.ToDoId)
	JOIN SCHEDULE S ON (TR.PrincipalId = S.ContUserId)
  WHERE T.IsCompleted = 0
	AND T.StartDate IS NOT NULL AND T.FinishDate IS NOT NULL AND T.StartDate < @FinishDate AND T.FinishDate > @StartDate
	AND NOT (TR.MustBeConfirmed = 1 AND TR.ResponsePending = 0 AND TR.IsConfirmed = 0)
	AND S.UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetForUserByProject
	@ProjectId as int,
	@UserId as int,
	@LanguageId as int
as
DECLARE @dt AS datetime
SET @dt = GETUTCDATE()
SELECT T.ToDoId, T.Title, T.[Description], T.PriorityId, P.PriorityName, PercentCompleted, IsCompleted, StartDate, FinishDate, T.StateId
  FROM TODO T
	JOIN PRIORITY_LANGUAGE P ON (T.PriorityId = P.PriorityId AND P.LanguageId = @LanguageId)
  WHERE ProjectId = @ProjectId AND IsCompleted = 0
	AND (StartDate IS NULL OR (StartDate IS NOT NULL AND StartDate < = @dt))
	AND ToDoId IN
		(SELECT ToDoId FROM TODO_RESOURCES R
		  WHERE PrincipalId = @UserId
			AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)
		)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetInUTC
	@ToDoId as int,
	@LanguageId as int
as
DECLARE @ToDoType int
SET @ToDoType = 6
SELECT T.ToDoId, T.ProjectId, P.Title AS ProjectTitle, IT.IncidentId, I.Title AS IncidentTitle, IT.StatusId,
	T.CreatorId, T.ManagerId, T.CompletedBy, T.Title, T.[Description],
	T.CreationDate, 	T.StartDate, T.FinishDate, T.ActualFinishDate,
	T.PriorityId, PR.PriorityName, T.PercentCompleted, T.IsActual, T.CompletionTypeId, CT.CompletionTypeName,
	T.IsCompleted, T.MustBeConfirmed, T.ReasonId, DT.DocumentId, TT.TaskId, TT.CompleteTask, TA.Title AS TaskTitle, T.StateId
  FROM TODO T
	LEFT JOIN PROJECTS P ON (T.ProjectId = P.ProjectId)
	LEFT JOIN INCIDENT_TODO IT ON (T.ToDoId = IT.ToDoId)
		LEFT JOIN INCIDENTS I ON (IT.IncidentId = I.IncidentId)
	LEFT JOIN TASK_TODO TT ON (T.ToDoId = TT.ToDoId)
		LEFT JOIN TASKS TA ON (TT.TaskId = TA.TaskId)
	LEFT JOIN DOCUMENT_TODO DT ON (T.ToDoId = DT.ToDoId)
	JOIN PRIORITY_LANGUAGE PR ON (T.PriorityId = PR.PriorityId AND PR.LanguageId = @LanguageId)
	JOIN COMPLETION_TYPE_LANGUAGE CT ON (T.CompletionTypeId = CT.CompletionTypeId AND CT.LanguageId = @LanguageId)
  WHERE T.ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetIsCompleted
	@ToDoId as int,
	@retval int output
as
IF EXISTS(SELECT * FROM TODO WHERE ToDoId = @ToDoId AND IsCompleted = 0)
	SET @retval = 0
ELSE
	SET @retval = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetProject
	@ToDoId as int,
	@Retval as int output
AS
SELECT @Retval = ProjectId FROM TODO WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetSecurityForUser
	@ToDoId as int,
	@UserId as int
as
SELECT ToDoId, PrincipalId, IsResource, IsManager
   FROM TODO_SECURITY_ALL
  WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoGetSimple
	@ProjectId as int,
	@UserId as int,
	@GetAssigned as bit,
	@GetManaged as bit
as
SELECT ToDoId, Title
  FROM TODO T
  WHERE (@ProjectId = 0 OR ProjectId = @ProjectId OR (@ProjectId = -1 AND ProjectId IS NULL))
	AND
	(
		(@GetAssigned = 1 AND ToDoId IN
			(SELECT ToDoId FROM TODO_RESOURCES R WHERE PrincipalId = @UserId
				AND NOT (MustBeConfirmed = 1 AND ResponsePending = 0 AND IsConfirmed = 0)))
		OR
		(@GetManaged =1 AND ManagerId = @UserId)
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].TodoManagerGet
	@TodoId int,
	@retval int output
AS
SELECT @retval = ManagerId
  FROM TODO
  WHERE TodoId = @TodoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoRecalculateState
	@TodoId INT,
	@DateNow DateTime
 AS
DECLARE @StateId INT
DECLARE @NewStateId INT
DECLARE @ActivationTypeId INT
DECLARE @ActivatedManually INT
DECLARE @ReasonId INT
DECLARE @IsCompleted INT
DECLARE @StartDate DATETIME
DECLARE @FinishDate DATETIME
DECLARE @IsExistUnstartedTask INT, @IsExistUnstartedDocument int, @IsExistUnstartedIssue int
SELECT @IsExistUnstartedTask = count(*) FROM  TASKS T
	JOIN TASK_TODO TT ON T.TaskId = TT.TaskId
  WHERE TT.ToDoId= @TodoId AND T.StateId = 1
SELECT @IsExistUnstartedDocument = count(*) FROM  DOCUMENTS D
	JOIN DOCUMENT_TODO DT ON D.DocumentId = DT.DocumentId
  WHERE DT.ToDoId= @TodoId AND D.StateId = 1
SELECT @IsExistUnstartedIssue = count(*) FROM  INCIDENTS I
	JOIN INCIDENT_TODO IT ON I.IncidentId = IT.IncidentId
  WHERE IT.ToDoId= @TodoId AND I.StateId = 1
SELECT @IsCompleted = [IsCompleted],
	@ReasonId = [ReasonId],
	@ActivatedManually = [ActivatedManually],
	@ActivationTypeId = [ActivationTypeId],
	@StartDate = [StartDate],
	@FinishDate = [FinishDate],
	@StateId = [StateId]
FROM [TODO]
WHERE [TodoId] = @TodoId
SET @NewStateId = 1
IF @IsCompleted = 1
BEGIN
	IF @ReasonId = 1  OR @ReasonId = 2 /*completed auto*/
	   SET @NewStateId = 5
	IF @ReasonId = 3  OR @ReasonId = 4 /*suspended auto*/
	   SET @NewStateId = 4
END
ELSE
BEGIN
	IF @ActivatedManually = 1
		SET @NewStateId = 2
	ELSE
	BEGIN
		IF @ActivationTypeId = 1
		BEGIN
			IF (@StartDate IS NULL OR @StartDate < @DateNow) AND @IsExistUnstartedTask = 0 AND @IsExistUnstartedDocument = 0 AND @IsExistUnstartedIssue = 0
				SET @NewStateId = 2
		END
		ELSE
		IF @ActivationTypeId = 2
		BEGIN
			IF @StartDate IS NULL OR @StartDate < @DateNow
				SET @NewStateId = 2
		END
	END
	IF @NewStateId = 2 AND (@FinishDate IS NOT NULL AND @FinishDate < @DateNow)
		SET @NewStateId = 3
END
UPDATE [TODO]
SET  [StateId]= @NewStateId
WHERE [ToDoId]= @ToDoId AND @StateId != @NewStateId
SELECT @StateId As OldStateId, @NewStateId as NewStateId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoReplaceUnchangeableUser
	@FromUserId as int,
	@ToUserId as int
as
BEGIN TRAN
	UPDATE TODO SET CreatorId = @ToUserId WHERE CreatorId = @FromUserId
	IF @@ERROR != 0
		GOTO err
	UPDATE TODO SET CompletedBy = @ToUserId WHERE CompletedBy = @FromUserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoReplaceUnchangeableUserToManager
	@UserId as int
as
BEGIN TRAN
	UPDATE TODO SET CreatorId = ManagerId WHERE CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE TODO SET CompletedBy = ManagerId WHERE CompletedBy = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResetCompletedBy
	@ToDoId as int
as
UPDATE TODO
  SET CompletedBy = null, ActualFinishDate = null
  WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResourceAdd
	@ToDoId as int ,
	@UserId as int ,
	@MustBeConfirmed as bit
as
IF EXISTS(SELECT * FROM TODO_RESOURCES WHERE ToDoId = @ToDoId AND PrincipalId = @UserId)
	UPDATE TODO_RESOURCES SET MustBeConfirmed = @MustBeConfirmed WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
ELSE
	INSERT INTO TODO_RESOURCES (ToDoId, PrincipalId, MustBeConfirmed)
	  VALUES(@ToDoId, @UserId, @MustBeConfirmed)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResourceDelete
	@ToDoId as int,
	@UserId as int
as
DELETE FROM TODO_RESOURCES WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResourceGetByUser
	@ToDoId as int,
	@UserId as int
as
SELECT MustBeConfirmed, ResponsePending, IsConfirmed, PercentCompleted
  FROM TODO_RESOURCES
  WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResourcesGet
	@ToDoId as int
as
SELECT R.ResourceId, R.ToDoId, R.PrincipalId AS UserId, R.MustBeConfirmed, R.ResponsePending, R.IsConfirmed, R.PercentCompleted,
	R.ActualFinishDate, R.LastSavedDate, P.IsGroup,
	CASE WHEN U.IsExternal = 1 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS IsExternal
  FROM TODO_RESOURCES R
	JOIN PRINCIPALS P ON (R.PrincipalId = P.PrincipalId)
	LEFT JOIN USERS U ON (R.PrincipalId = U.PrincipalId)
  WHERE R.ToDoId = @ToDoId
ORDER BY U.FirstName, U.LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoResourceUpdatePercent
	@ToDoId as int,
	@UserId as int,
	@PercentCompleted as int,
	@LastSavedDate as datetime
as
if @PercentCompleted = 100
	UPDATE TODO_RESOURCES
	  SET PercentCompleted = @PercentCompleted, LastSavedDate = @LastSavedDate, ActualFinishDate = @LastSavedDate
	  WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
ELSE
	UPDATE TODO_RESOURCES
	  SET PercentCompleted = @PercentCompleted, LastSavedDate = @LastSavedDate
	  WHERE ToDoId = @ToDoId AND PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoSecurityGet
	@ToDoId int
AS
SELECT PrincipalId AS UserId
  FROM TODO_SECURITY_ALL
  WHERE ToDoId = @ToDoId
	AND (IsResource = 1 OR IsManager = 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoStatusGet
as
SELECT StatusId, StatusName, IsActive FROM TODO_STATUS
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoUpdateActivation
	@TodoId as int
as
UPDATE TODO
  SET ActivatedManually = 1
  WHERE TodoId = @TodoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoUpdateCompletedBy
	@ToDoId as int,
	@UserId as int
as
UPDATE TODO
  SET CompletedBy = @UserId, ActualFinishDate = getutcdate()
  WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoUpdateCompletion
	@ToDoId as int,
	@IsCompleted as bit,
	@ReasonId as int
as
UPDATE TODO
  SET IsCompleted = @IsCompleted, ReasonId = @ReasonId
  WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoUpdatePercent
	@ToDoId as int,
	@PercentCompleted as int
as
UPDATE TODO
  SET PercentCompleted = @PercentCompleted
  WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].ToDoUpdateProjectAndManager
	@ToDoId as int,
	@ProjectId as int,
	@ManagerId as int
as
IF @ProjectId <= 0
	SET @ProjectId = NULL
UPDATE TODO
  SET ManagerId = @ManagerId, ProjectId = @ProjectId
  WHERE ToDoId = @ToDoId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[UserAddToGroup]
	@UserID as int,
	@GroupID as int
AS
Declare @grouptype_id as int
Declare @child_group_id as int
Declare @parent_group_id as int
Begin Tran
If Not Exists (Select * From Containership Where (PrincipalId=@UserID)AND(ParentPrincipalId=@GroupID))
Begin
	Insert Containership (PrincipalId, ParentPrincipalId)
		Values (@UserID, @GroupID)
	If @@error <> 0
		Goto ErrorLabel
End
If Not Exists (Select * From User_Group Where (UserId=@UserID)AND(GroupId=@GroupID))
Begin
	Insert User_Group (UserId, GroupId)
		Values (@UserID, @GroupID)
	If @@error <> 0
		Goto ErrorLabel
End
set @child_group_id=@GroupID
Select @parent_group_id=C.[ParentPrincipalId] From Containership AS C Where C.[PrincipalId]=@child_group_id
while @@rowcount > 0
Begin
	If NOT Exists(Select * From User_Group Where (UserId=@UserID)AND(GroupId=@parent_group_id))
	Begin
		Insert Into User_Group (UserId, GroupId)
		Values (@UserID, @parent_group_id)
		If @@error <> 0
			Goto ErrorLabel
	End
	set @child_group_id=@parent_group_id
	Select @parent_group_id=C.[ParentPrincipalId] From Containership AS C Where C.[PrincipalId]=@child_group_id
End
Commit Tran
Return
ErrorLabel:
	Rollback Tran
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserAssignOriginalId
	@UserId as int ,
	@OriginalId as int
as
UPDATE USERS
  SET OriginalId = @OriginalId
  WHERE PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserConvertFromExternal
	@PrincipalId as int ,
	@Login as nvarchar(250),
	@Password as nvarchar(50) ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250),
	@Activity as tinyint,
	@CreatedBy as int
as
UPDATE USERS
  SET Login = @Login, FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity = @Activity, [Password] = @Password, CreatedBy = @CreatedBy, IsExternal = 0
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserCreate
	@Login as nvarchar(250) ,
	@Password as nvarchar(50) ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250) ,
	@Activity as tinyint ,
	@IsExternal as bit,
	@CreatedBy as int,
	@InviteText as ntext,
	@retval int output
as
IF @CreatedBy < 0
	SET @CreatedBy = NULL
BEGIN TRAN
	INSERT INTO PRINCIPALS (IsGroup) VALUES (0)
	IF @@error != 0
		GOTO err
	SELECT @retval = @@identity
	INSERT INTO USERS (PrincipalId, Login, [Password], FirstName, LastName, Email, Activity, IsExternal, CreatedBy, InviteText)
	  VALUES(@retval, @Login, @Password, @FirstName, @LastName, @Email, @Activity, @IsExternal, @CreatedBy, @InviteText)
	IF @@error != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDeactivate
	@UserId as int
as
DECLARE @Inactive tinyint
SET @Inactive = 1
UPDATE USERS SET Activity = @Inactive WHERE PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDelete
	@UserId as int
as
DECLARE @BatchAlertType int
SET @BatchAlertType = 9
BEGIN TRAN
	DELETE COLLAPSED_TASKS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_ACCOUNTS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_INCIDENTS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_USERTIMESHEETS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE COLLAPSED_MANAGERTIMESHEETS WHERE UserId = @UserId OR ManagerId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_PROJECT_TEAM WHERE MemberId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_PROJECT_TEAM WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE CONTAINERSHIP WHERE PrincipalId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE SCHEDULE WHERE UserId = @UserId OR ContUserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE SHARING WHERE UserId = @UserId OR ProUserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE DATE_TYPE_VALUES WHERE DateTypeId = @BatchAlertType AND ObjectId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE TIMESHEET_TODO WHERE TimesheetToDoId IN
		(SELECT ObjectId FROM TIMESHEETS T WHERE T.ObjectTypeId = 11 AND WeekTimeSheetId IN
			(SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE UserId = @UserId))
	IF @@ERROR != 0
		GOTO err
	DELETE TIMESHEETS WHERE WeekTimeSheetId IN (SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE UserId = @UserId)
	IF @@ERROR != 0
		GOTO err
	DELETE WeekTimeSheet WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE STUBS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE BroadCastMessages WHERE CreatorId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE PORTAL_LOGINS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	UPDATE SYSTEM_EVENTS SET UserId = NULL WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_GROUP WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_SETTINGS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_PREFERENCES WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USER_DETAILS WHERE UserId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE USERS WHERE PrincipalId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE PRINCIPALS WHERE PrincipalId = @UserId
	IF @@ERROR != 0
		GOTO err
	DELETE LIST_ACCESS WHERE PrincipalId = @UserId
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[UserDeleteFromGroup]
	@UserID as int,
	@GroupID as int
AS
Declare @parent_group_id as int
Declare @child_group_id as int
Declare @cur_group_id as int
Begin Tran
Delete From Containership Where (PrincipalId=@UserID) AND(ParentPrincipalId=@GroupID)
If @@error <> 0
	Goto ErrorLabel
Declare TempCur Cursor For
	Select ParentPrincipalId From Containership  Where (PrincipalId=@UserID)AND(ParentPrincipalId<>1)
Open TempCur
Fetch Next From TempCur Into @cur_group_id
While @@Fetch_Status = 0
Begin
	set @child_group_id=@cur_group_id
	Select @parent_group_id=[ParentPrincipalId] From Containership
					Where [PrincipalId]=@child_group_id
	While (@@rowcount >0 ) AND (@parent_group_id<>@GroupID) AND (@parent_group_id<>1)
	Begin
		set @child_group_id=@parent_group_id
		Select @parent_group_id=[ParentPrincipalId] From Containership
					Where [PrincipalId]=@child_group_id
	End
	If @parent_group_id=@GroupID
	Begin
		Close TempCur
		Deallocate TempCur
		Commit Tran
		Return
	End
	Fetch Next From TempCur Into @cur_group_id
End
Close TempCur
Deallocate TempCur
Delete From User_Group Where (UserId=@UserID) AND(GroupId=@GroupID)
If @@error <> 0
	Goto ErrorLabel
set @child_group_id=@GroupID
Select @parent_group_id=[ParentPrincipalId] From Containership
					Where [PrincipalId]=@child_group_id
While(@@rowcount>0)AND(@parent_group_id<>1)
Begin
	If Exists (Select * From Containership Where (PrincipalId=@UserID)AND(ParentPrincipalId=@parent_group_id))
	Begin
		Commit Tran
		Return
	End
	Delete From User_Group Where (UserId=@UserID) AND(GroupId=@parent_group_id)
	If @@error <> 0
		Goto ErrorLabel
	set @child_group_id=@parent_group_id
	Select @parent_group_id=[ParentPrincipalId] From Containership
					Where [PrincipalId]=@child_group_id
End
Commit Tran
Return
ErrorLabel:
	Rollback Tran
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDetailsCreateUpdate
	@UserId as int ,
	@phone as nvarchar(100) ,
	@fax as nvarchar(100) ,
	@mobile as nvarchar(100) ,
	@position as nvarchar(100) ,
	@department as nvarchar(100) ,
	@company as nvarchar(100) ,
	@location as nvarchar(100)
as
if EXISTS(SELECT * FROM USER_DETAILS WHERE UserId = @UserId)
	UPDATE USER_DETAILS
	  SET phone=@phone, fax=@fax, mobile=@mobile, position=@position, department=@department, company=@company, location=@location
	  WHERE UserId = @UserId
else
	INSERT INTO USER_DETAILS (UserId, phone, fax, mobile, position, department, company, location)
	  VALUES(@UserId, @phone, @fax, @mobile, @position, @department, @company, @location)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].UserDetailsGet
	@UserId as int
as
SELECT UserId, phone, fax, mobile, position, department, company, location, PictureUrl
  FROM USER_DETAILS
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDetailsUpdate
	@UserId as int ,
	@phone as nvarchar(100) ,
	@mobile as nvarchar(100)
as
UPDATE USER_DETAILS
  SET phone=@phone, mobile=@mobile
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDetailsUpdate2
	@UserId as int ,
	@position as nvarchar(100) ,
	@department as nvarchar(100),
	@company as nvarchar(100),
	@location as nvarchar(100)
as
UPDATE USER_DETAILS
  SET position=@position, department=@department, company=@company, location=@location
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserDetailsUpdatePhoto
	@UserId as int ,
	@PictureUrl as nvarchar(1024)
as
UPDATE USER_DETAILS SET PictureUrl = @PictureUrl WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGet
       @PrincipalId as int
as
DECLARE @Active tinyint
SET @Active = 3
DECLARE @Pending tinyint
SET @Pending = 2
SELECT PrincipalId AS UserId, [Password], Login, FirstName, LastName, Email, Activity,
	CASE WHEN Activity = @Active OR Activity = @Pending THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS IsActive, IMGroupId, CreatedBy, Comments, OriginalId, IsExternal,
	CASE WHEN Activity = @Pending THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS IsPending
  FROM USERS U
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetByEmail
	@Email as nvarchar(250),
	@OnlyExternal as bit,
	@retval int output
as
IF @OnlyExternal = 1
BEGIN
	SELECT @retval = PrincipalId
	  FROM USERS
	  WHERE Email = @Email AND IsExternal = 1
	IF @retval IS NULL
		SELECT @retval = UserId
		  FROM EMAILS
		  WHERE Email = @Email AND UserId IN (SELECT PrincipalId FROM USERS WHERE IsExternal = 1)
END
ELSE
BEGIN
	SELECT @retval = PrincipalId
	  FROM USERS
	  WHERE Email = @Email
	IF @retval IS NULL
		SELECT @retval = UserId
		  FROM EMAILS
		  WHERE Email = @Email
END
IF @retval IS NULL
	SET @retval = -1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetByLogin
	@Login as nvarchar(250),
	@retval int output
AS
	SELECT @retval = PrincipalId
	  FROM USERS
	  WHERE Login = @Login
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetByOriginalId
       @OriginalId as int
as
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, Activity, IMGroupId
  FROM USERS U
  WHERE OriginalId = @OriginalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetInfoByLogin
       @Login as nvarchar(250)
AS
DECLARE @Pending tinyint
SET @Pending = 2
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, Activity, IMGroupId, OriginalId, IsExternal,
	CASE WHEN Activity = @Pending THEN CAST(1 as bit) ELSE CAST(0 as bit) END AS IsPending
  FROM USERS
  WHERE Login = @Login
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetOriginalId
	@UserId INT,
	@RetVal INT OUTPUT
AS
Set @RetVal = -1
SELECT @RetVal = OriginalId FROM USERS WHERE PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGetPassword
	@UserId as int
as
SELECT [Password] FROM USERS  WHERE PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserGroupCheck
	@UserId as int,
	@GroupId as int,
	@retval int output
as
IF EXISTS (SELECT * FROM USER_GROUP WHERE UserId = @UserId AND GroupId = @GroupId)
	SET @retval = 1
ELSE
	SET @retval = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserIMGroupAssign
	@UserId as int ,
	@IMGroupId as int
as
UPDATE USERS
  SET IMGroupId = @IMGroupId
  WHERE PrincipalId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserLogin
	@Login as nvarchar(250),
	@Password as nvarchar(50),
	@retval as int output
AS
DECLARE @Active tinyint
SET @Active  = 3
SELECT @retval = PrincipalId
 FROM USERS
 WHERE Login = @Login AND [Password] = @Password AND Activity = @Active AND IsExternal = 0
IF @retval IS NULL AND NOT EXISTS (SELECT * FROM USERS WHERE Login = @Login)
	SET @retval = -1
IF @retval IS NULL AND NOT EXISTS (SELECT * FROM USERS WHERE Login = @Login AND [Password] = @Password )
	SET @retval = -2
IF @retval IS NULL AND NOT EXISTS (SELECT * FROM USERS WHERE Login = @Login AND [Password] = @Password AND Activity = @Active)
	SET @retval = -3
IF @retval IS NULL
	SET @retval = -4
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserLoginByEmail
	@Email as nvarchar(250),
	@retval as int output
AS
DECLARE @Active tinyint
SET @Active = 3
SELECT @retval = PrincipalId
 FROM USERS
 WHERE Login = @Email AND Activity = @Active  AND ([Password] IS NULL OR [Password] = '')
	AND IsExternal = 1
IF @@ROWCOUNT = 0
	RAISERROR('User is not found', 16, 1)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferenceMenuInAlertsGet
	@UserId as int
as
SELECT MenuInAlerts
  FROM USER_PREFERENCES
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesCreateUpdate
	@UserId as int ,
	@IsNotified as bit ,
	@IsNotifiedByEmail as bit ,
	@IsNotifiedByIBN as bit ,
	@IsBatchNotifications as bit ,
	@Period as int ,
	@From as int,
	@Till as int,
	@TimeZoneId as int,
	@LanguageId as int,
	@ReminderType as int
as
if EXISTS(SELECT * FROM USER_PREFERENCES WHERE UserId = @UserId)
	UPDATE USER_PREFERENCES
	  SET IsNotified=@IsNotified, IsNotifiedByEmail=@IsNotifiedByEmail, IsNotifiedByIBN=@IsNotifiedByIBN, IsBatchNotifications=@IsBatchNotifications,
		Period=@Period, [From]=@From, Till=@Till, TimeZoneId = @TimeZoneId, LanguageId = @LanguageId, ReminderType=@ReminderType
	  WHERE UserId = @UserId
else
BEGIN
	DECLARE @TimeOffsetLatest int
	DECLARE @UTCDate datetime
	SET @UTCDate = getutcdate()
	SELECT @TimeOffsetLatest = TimeOffset
	  FROM TimeZones_UTC_Local
	  WHERE TimeZoneId = @TimeZoneId AND Start <= @UTCDate AND [End] > @UTCDate
	IF @TimeOffsetLatest IS NULL
		SELECT @TimeOffsetLatest = Bias FROM TimeZones WHERE TimeZoneId = @TimeZoneId
	INSERT INTO USER_PREFERENCES (UserId,IsNotified,IsNotifiedByEmail,IsNotifiedByIBN,IsBatchNotifications,Period,[From],Till, TimeZoneId, TimeOffsetLatest, LanguageId, ReminderType)
	  VALUES(@UserId, @IsNotified, @IsNotifiedByEmail, @IsNotifiedByIBN, @IsBatchNotifications, @Period, @From, @Till, @TimeZoneId, @TimeOffsetLatest, @LanguageId, @ReminderType)
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesGet
	@UserId as int
as
SELECT U.UserId, U.IsNotified, U.IsNotifiedByEmail, U.IsNotifiedByIBN, U.IsBatchNotifications, U.Period, U.[From], U.Till,
	U.TimeZoneId, U.TimeOffsetLatest, U.LanguageId, L.Locale, L.FriendlyName AS LanguageName, U.ReminderType, U.BatchLastSent, U.BatchNextSend
  FROM USER_PREFERENCES U
	JOIN LANGUAGES L ON (U.LanguageId = L.LanguageId)
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesUpdateLanguage
	@UserId as int ,
	@LanguageId as int
as
UPDATE USER_PREFERENCES
  SET LanguageId = @LanguageId
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesUpdateMenuInAlerts
	@UserId as int ,
	@MenuInAlerts as bit
as
UPDATE USER_PREFERENCES
  SET MenuInAlerts = @MenuInAlerts
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesUpdateTimeOffsetLatest
	@UserId as int ,
	@TimeOffset as int
as
UPDATE USER_PREFERENCES
  SET TimeOffsetLatest = @TimeOffset
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPreferencesUpdateTimeZoneId
	@UserId as int ,
	@TimeZoneId as int
as
UPDATE USER_PREFERENCES
  SET TimeZoneId = @TimeZoneId
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserProjectTeamAdd
	@UserId as int ,
	@ProjectId as int ,
	@MemberId as int
as
if NOT EXISTS(SELECT * FROM USER_PROJECT_TEAM WHERE UserId = @UserId AND ProjectId = @ProjectId AND MemberId = @MemberId)
	INSERT INTO USER_PROJECT_TEAM (UserId, ProjectId, MemberId) VALUES(@UserId, @ProjectId, @MemberId)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserProjectTeamAddAll
	@UserId as int ,
	@ProjectId as int
as
BEGIN TRAN
	DELETE FROM USER_PROJECT_TEAM WHERE UserId = @UserId AND ProjectId = @ProjectId
	IF @@ERROR != 0
		GOTO err
	INSERT INTO USER_PROJECT_TEAM (UserId, ProjectId, MemberId)
		SELECT @UserId AS UserId, @ProjectId AS ProjectId, PrincipalId AS MemberId
		  FROM PROJECT_MEMBERS
		  WHERE ProjectId = @ProjectId AND IsTeamMember=1
	IF @@ERROR != 0
		GOTO err
COMMIT TRAN
RETURN
err:
	ROLLBACK TRAN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserProjectTeamDelete
	@UserId as int,
	@ProjectId as int,
	@MemberId as int
as
DELETE FROM USER_PROJECT_TEAM
  WHERE UserId = @UserId AND ProjectId = @ProjectId AND MemberId = @MemberId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserProjectTeamDeleteAll
	@UserId as int ,
	@ProjectId as int
as
DELETE FROM USER_PROJECT_TEAM
  WHERE UserId = @UserId AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserProjectTeamGet
	@UserId as int,
	@ProjectId as int
as
SELECT M.PrincipalId AS MemberId, U.FirstName + ' ' + U.LastName AS FullName,
	CASE WHEN T.MemberId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsExpanded
  FROM PROJECT_MEMBERS M
	LEFT JOIN USER_PROJECT_TEAM T ON (M.ProjectId = T.ProjectId AND M.PrincipalId = T.MemberId AND T.UserId = @UserId)
	JOIN USERS U ON (M.PrincipalId = U.PrincipalId)
  WHERE M.ProjectId = @ProjectId AND IsTeamMember = 1
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPropertyGet
	@UserId as int
as
SELECT SettingId, UserId, [Key], Value
  FROM USER_SETTINGS
  WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPropertyRemove
	@UserId as int,
	@Key as nvarchar(100)
as
DELETE FROM USER_SETTINGS WHERE UserId = @UserId AND [Key] = @Key
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserPropertySet
	@UserId as int,
	@Key as nvarchar(100),
	@Value as ntext,
	@retval as int output
as
SELECT @retval = SettingId FROM USER_SETTINGS WHERE UserId = @UserId AND [Key] = @Key
IF @retval IS NOT NULL
	UPDATE USER_SETTINGS SET Value = @Value WHERE SettingId = @retval
ELSE
	BEGIN
		INSERT INTO USER_SETTINGS (UserId, [Key], Value) VALUES(@UserId, @Key, @Value)
		SET @retval = @@identity
	END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGet
as
DECLARE @Active tinyint
SET @Active = 3
DECLARE @Pending tinyint
SET @Pending = 2
SELECT PrincipalId, Login, [Password], FirstName, LastName, Email,
	CASE WHEN Activity = @Active THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS IsActive,
	IMGroupId, OriginalId
  FROM USERS
  WHERE IsExternal = 0 AND Activity != @Pending
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetActive
as
DECLARE @Active tinyint
SET @Active = 3
SELECT PrincipalId, Login, [Password], FirstName, LastName, Email, IMGroupId, OriginalId
  FROM USERS
  WHERE Activity = @Active AND IsExternal = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetActiveByGroup
       @GroupId as int
as
DECLARE @InActive tinyint
SET @InActive = 1
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, IMGroupId, CreatedBy
  FROM USERS
  WHERE PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId)
	AND Activity != @InActive
ORDER BY LastName, FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetActiveByGroupAll
       @GroupId as int
as
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, IMGroupId, OriginalId, CreatedBy, Activity, IsExternal, FirstName + ' ' + LastName as DisplayName
  FROM USERS
  WHERE PrincipalId IN (SELECT UserId FROM USER_GROUP WHERE GroupId = @GroupId)
	AND Activity = 3
ORDER BY LastName, FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetActiveCount
       @Retval as int output
as
DECLARE @Active tinyint
SET @Active = 3
SELECT @Retval = COUNT(*) FROM USERS
  WHERE Activity = @Active AND IsExternal = 0
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetAll
as
DECLARE @Active tinyint
DECLARE @Pending tinyint
SET @Active = 3
SET @Pending = 2
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, IsExternal, Activity,
	CASE WHEN Activity = @Pending THEN CAST(1 as bit)  ELSE CAST(0 as bit)  END AS IsPending
  FROM USERS
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].UsersGetByGroup
       @GroupId as int
as
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, Activity, IMGroupId, CreatedBy, IsExternal
  FROM USERS
  WHERE PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @GroupId)
ORDER BY LastName, FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetByGroupAll
       @GroupId as int
as
DECLARE @Active tinyint
SET @Active = 3
DECLARE @Pending tinyint
SET @Pending = 2
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, IMGroupId, OriginalId, CreatedBy, Activity, IsExternal
  FROM USERS
  WHERE PrincipalId IN (SELECT UserId FROM USER_GROUP WHERE GroupId = @GroupId)
	AND (Activity = @Active OR Activity = @Pending)
ORDER BY LastName, FirstName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetByIMGroup
       @IMGroupId as int
as
SELECT PrincipalId AS UserId, Login, FirstName, LastName, Email, Activity, IMGroupId, OriginalId
  FROM USERS
  WHERE IMGroupId = @IMGroupId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetExternalCount
	@retval int output
as
DECLARE @Active tinyint
SET @Active = 3
SELECT @retval = COUNT(*)
  FROM USERS
  WHERE IsExternal = 1 AND Activity = @Active
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetGroupedByRole
AS
DECLARE @Role int
SET @Role  = 8
DECLARE @Roles TABLE (RoleId int, RoleName nvarchar(250))
INSERT INTO @Roles
SELECT PrincipalId AS RoleId, GroupName AS RoleName
  FROM GROUPS
  WHERE PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @Role)
	OR PrincipalId IN (SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId IN
		(SELECT PrincipalId FROM CONTAINERSHIP WHERE ParentPrincipalId = @Role))
DECLARE @Users TABLE (UserId int, UserName nvarchar(100), OpenTasks int, CompletedTasks int, Issues int)
INSERT INTO @Users (UserId, UserName, OpenTasks, CompletedTasks, Issues)
SELECT U.PrincipalId AS UserId, U.LastName + ' ' + U.FirstName AS UserName,
	(SELECT COUNT(*) FROM TASK_RESOURCES R
		JOIN TASKS T ON (R.TaskId = T.TaskId AND T.IsCompleted = 0)
	  WHERE R.PrincipalId = U.PrincipalId AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	) +
	(SELECT COUNT(*) FROM TODO_RESOURCES R
		JOIN TODO T ON (R.ToDoId = T.ToDoId AND T.IsCompleted = 0)
	  WHERE R.PrincipalId = U.PrincipalId AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	) AS OpenTasks,
	(SELECT COUNT(*) FROM TASK_RESOURCES R
		JOIN TASKS T ON (R.TaskId = T.TaskId AND T.IsCompleted = 1)
	  WHERE R.PrincipalId = U.PrincipalId AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	) +
	(SELECT COUNT(*) FROM TODO_RESOURCES R
		JOIN TODO T ON (R.ToDoId = T.ToDoId AND T.IsCompleted = 1)
	  WHERE R.PrincipalId = U.PrincipalId AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	) AS CompletedTasks,
	(SELECT COUNT(*) FROM INCIDENT_RESOURCES R
		JOIN INCIDENTS I ON (R.IncidentId = I.IncidentId)
	  WHERE R.PrincipalId = U.PrincipalId AND NOT (R.MustBeConfirmed = 1 AND R.ResponsePending = 0 AND R.IsConfirmed = 0)
	) AS Issues
  FROM Users U
  WHERE U.PrincipalId IN (SELECT UserId FROM USER_GROUP WHERE GroupId IN (SELECT RoleId FROM @Roles))
DECLARE @dummy TABLE (RoleId int, RoleName nvarchar(250), UserId int, UserName nvarchar(100),
	OpenTasks int, CompletedTasks int, Issues int)
INSERT INTO @dummy (RoleId, RoleName, UserId, UserName, OpenTasks, CompletedTasks, Issues)
SELECT R.RoleId, R.RoleName, U.UserId, U.UserName, U.OpenTasks, U.CompletedTasks, U.Issues
  FROM @Users U
	JOIN USER_GROUP UG ON (U.UserId = UG.UserId)
	JOIN @Roles R ON (UG.GroupId = R.RoleId)
SELECT RoleId, RoleName, 0 AS UserId, '' AS UserName, 0 AS OpenTasks, 0 AS CompletedTasks, 0 AS Issues,
	CAST(1 as bit) AS IsHeader
  FROM (SELECT DISTINCT RoleId, RoleName FROM @dummy) A
UNION ALL
SELECT RoleId, RoleName, UserId, UserName, OpenTasks, CompletedTasks, Issues,
	CAST(0 as bit) AS IsHeader
  FROM @dummy
  ORDER BY RoleId, UserName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetPending
as
SELECT PrincipalId, Login, [Password], FirstName, LastName, Email, IMGroupId, OriginalId
  FROM USERS
  WHERE Activity = 2
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetStatistic
as
DECLARE @RolesCount int
SET @RolesCount = 9
DECLARE @PartnerGroup int
SET @PartnerGroup = 6
DECLARE @MaxSytemPrincipalId int
SET @MaxSytemPrincipalId = 9
DECLARE @Active tinyint
SET @Active = 3
DECLARE @Pending tinyint
SET @Pending = 2
DECLARE @Inactive tinyint
SET @Inactive = 1
DECLARE @TotalUserCount int
DECLARE @ActiveUserCount int
DECLARE @InactiveUserCount int
DECLARE @ExternalCount int
DECLARE @PendingCount int
DECLARE @SecureGroupCount int
DECLARE @AvgCountUserInGroup int
DECLARE @PartnerGroupCount int
DECLARE @PartnerUserCount int
DECLARE @RegularUserCount int
Declare @PortalLoginCount int
SELECT @PortalLoginCount = COUNT(*)
  FROM Portal_Logins
SELECT @TotalUserCount = COUNT(*)
  FROM USERS
SELECT @ActiveUserCount = COUNT(*)
  FROM USERS
  WHERE Activity = @Active AND IsExternal = 0
SELECT @InactiveUserCount = COUNT(*)
  FROM USERS
  WHERE Activity = @Inactive AND IsExternal = IsExternal
SELECT @ExternalCount = COUNT(*)
  FROM USERS
  WHERE IsExternal = 1
SELECT @PendingCount = COUNT(*)
  FROM USERS
  WHERE Activity = @Pending
SELECT @SecureGroupCount = COUNT(*) - @RolesCount
  FROM GROUPS
SELECT @AvgCountUserInGroup = AVG(UserCount)
  FROM
	 (SELECT COUNT(*) AS UserCount
	  FROM GROUPS G
		LEFT JOIN USER_GROUP UG ON (G.PrincipalId = UG.GroupId)
	  WHERE G.PrincipalId > @MaxSytemPrincipalId
	  GROUP BY G.PrincipalId)
	 A
SELECT @PartnerGroupCount = COUNT(*)
  FROM CONTAINERSHIP
  WHERE ParentPrincipalId = @PartnerGroup
SELECT @PartnerUserCount = COUNT(*)
  FROM USER_GROUP
  WHERE GroupId = @PartnerGroup
SELECT @RegularUserCount = COUNT(*)
  FROM USERS
  WHERE Activity <> @Pending AND IsExternal = 0 AND
	PrincipalId NOT IN (SELECT UserId FROM USER_GROUP WHERE GroupId = @PartnerGroup)
SELECT @TotalUserCount AS TotalUserCount, @ActiveUserCount AS ActiveUserCount, @InactiveUserCount AS InactiveUserCount,
	@ExternalCount AS ExternalCount, @PendingCount AS PendingCount, @SecureGroupCount AS SecureGroupCount,
	@AvgCountUserInGroup AS AvgCountUserInGroup, @PartnerGroupCount AS PartnerGroupCount, @PartnerUserCount AS PartnerUserCount,
	@RegularUserCount AS RegularUserCount, @PortalLoginCount As PortalLoginsCount
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UsersGetWithTimeSheets
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT PrincipalId AS UserId, FirstName, LastName, LastName + ', ' + FirstName AS UserName
  FROM USERS
  WHERE PrincipalId IN
	(SELECT UserId FROM WeekTimeSheet WHERE ProjectId IN
		(SELECT ProjectId FROM PROJECTS WHERE @IsPPM_Exec = 1 OR ManagerId = @UserId)
	)
  ORDER BY LastName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdate
	@PrincipalId as int ,
	@Password as nvarchar(50) ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250) ,
	@Activity as tinyint,
	@IsExternal as bit
as
IF @Password = ''
	UPDATE USERS
	  SET FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity=@Activity, IsExternal = @IsExternal
	  WHERE PrincipalId = @PrincipalId
ELSE
	UPDATE USERS
	  SET FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity=@Activity, IsExternal = @IsExternal, [Password] = @Password
	  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdateBatchLastSent
	@UserId int,
	@Dt datetime
AS
UPDATE USER_PREFERENCES
 SET BatchLastSent = @Dt
 WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdateBatchNextSend
	@UserId int,
	@Dt datetime
AS
UPDATE USER_PREFERENCES
 SET BatchNextSend = @Dt
 WHERE UserId = @UserId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdateExternal
	@PrincipalId as int ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250) ,
	@Activity as tinyint
as
UPDATE USERS
  SET FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity=@Activity, Login = @Email
  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdatePending
	@PrincipalId as int ,
	@Login as nvarchar(250),
	@Password as nvarchar(50) ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250),
	@Activity as tinyint,
	@CreatedBy as int
as
IF @Password = ''
	UPDATE USERS
	  SET Login = @Login, FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity = @Activity, CreatedBy = @CreatedBy
	  WHERE PrincipalId = @PrincipalId
ELSE
	UPDATE USERS
	  SET Login = @Login, FirstName=@FirstName, LastName=@LastName, Email=@Email, Activity = @Activity, [Password] = @Password, CreatedBy = @CreatedBy
	  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UserUpdateSimple
	@PrincipalId as int ,
	@Password as nvarchar(50) ,
	@FirstName as nvarchar(50) ,
	@LastName as nvarchar(50) ,
	@Email as nvarchar(250)
as
IF @Password = ''
	UPDATE USERS
	  SET FirstName=@FirstName, LastName=@LastName, Email=@Email
	  WHERE PrincipalId = @PrincipalId
ELSE
	UPDATE USERS
	  SET FirstName=@FirstName, LastName=@LastName, Email=@Email, [Password] = @Password
	  WHERE PrincipalId = @PrincipalId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].UTCDateGet
	@TimeZoneId int,
	@LocalDate datetime,
	@retval Datetime output
AS
SELECT @retval = [dbo].GetUTCDateFromLocal(@TimeZoneId, @LocalDate)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetAccept
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime,
	@ManagerId as int
as
DECLARE @StatusId int
SET @StatusId = 4
UPDATE WeekTimeSheet
  SET StatusId = @StatusId, LastEditorId = @ManagerId, LastSavedDate = getutcdate()
  WHERE UserId = @UserId AND StartDate = @StartDate AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetCount
	@retval int output
as
SELECT @retval = count(WeekTimeSheetId)
  FROM WeekTimeSheet
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetDeny
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime,
	@ManagerComments ntext,
	@ManagerId as int
as
DECLARE @StatusId int
SET @StatusId = 3
UPDATE WeekTimeSheet
  SET StatusId = @StatusId, ManagerComments = @ManagerComments, LastEditorId = @ManagerId, LastSavedDate = getutcdate()
  WHERE UserId = @UserId AND StartDate = @StartDate
	AND (ProjectId = @ProjectId OR (@ProjectId < 0 AND ProjectId IS NULL))
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetGet
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime
as
SELECT WeekTimeSheetId, StatusId, ManagerComments
  FROM WeekTimeSheet
  WHERE UserId = @UserId AND ProjectId = @ProjectId AND StartDate = @StartDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetGetId
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime,
	@retval int output
as
SELECT @retval = WeekTimeSheetId
  FROM WeekTimeSheet
  WHERE UserId = @UserId AND StartDate = @StartDate
	AND (ProjectId = @ProjectId  OR (@ProjectId < 0 AND ProjectId IS NULL))
IF @retval  IS NULL
BEGIN
	IF @ProjectId < 0
		SET @ProjectId = null
	INSERT INTO WeekTimeSheet (UserId, ProjectId, StartDate, LastEditorId) VALUES (@UserId, @ProjectId, @StartDate, @UserId)
	SELECT @retval = @@identity
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetGetStatus
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime,
	@retval int output
as
IF @ProjectId < 0
	SELECT @retval = StatusId
	  FROM WeekTimeSheet
	  WHERE UserId = @UserId AND StartDate = @StartDate AND ProjectId IS NULL
ELSE
	SELECT @retval = StatusId
	  FROM WeekTimeSheet
	  WHERE UserId = @UserId AND StartDate = @StartDate AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetSendToApprove
	@UserId as int ,
	@ProjectId as int,
	@StartDate as datetime
as
DECLARE @StatusId int
SET @StatusId = 2
DECLARE @Rate money
SELECT @Rate = Rate FROM PROJECT_MEMBERS WHERE ProjectId = @ProjectId AND PrincipalId = @UserId AND IsTeamMember = 1
IF @Rate IS NULL
	SET @Rate = 0
UPDATE TIMESHEETS
  SET TotalApproved = Day1 + Day2 + Day3 + Day4 + Day5 + Day6 + Day7, Rate = @Rate
  WHERE WeekTimeSheetId IN
	(SELECT WeekTimeSheetId FROM WeekTimeSheet WHERE UserId = @UserId AND StartDate = @StartDate
		AND (ProjectId = @ProjectId OR (@ProjectId < 0 AND ProjectId IS NULL))
	)
UPDATE WeekTimeSheet
  SET StatusId = @StatusId, LastEditorId = UserId, LastSavedDate = getutcdate()
  WHERE UserId = @UserId AND StartDate = @StartDate AND ProjectId = @ProjectId
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetsGetApproved
	@UserId as int,
	@ProjectId as int,
	@StartDate as datetime = null,
	@BeginDate as datetime = null,
	@EndDate as datetime = null,
	@ManagerId as int
as
SET @EndDate = DATEADD(dd, 1, @EndDate)
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @ManagerId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
SELECT WTS.UserId, U.LastName + ' ' + U.FirstName AS UserName, WTS.ProjectId, P.Title, WTS.StartDate, WTS.StatusId, WTS.LastEditorId, A.TotalApproved, A.TotalCost,
	WTS.LastSavedDate
  FROM WeekTimeSheet WTS
	JOIN (
		SELECT W.WeekTimeSheetId, SUM(TotalApproved) AS TotalApproved, SUM(TotalApproved * Rate) / 60 AS TotalCost
		  FROM TIMESHEETS T
			JOIN WeekTimeSheet W ON (T.WeekTimeSheetId = W.WeekTimeSheetId)
			JOIN PROJECTS P ON (W.ProjectId = P.ProjectId)
		  WHERE
			(@IsPPM_Exec = 1 OR P.ManagerId = @ManagerId)
			AND W.StatusId = 4
			AND (@UserId = 0 OR W.UserId = @UserId)
			AND (@ProjectId = 0 OR W.ProjectId = @ProjectId)
			AND (@StartDate IS NULL OR W.StartDate = @StartDate)
			AND (@BeginDate IS NULL OR W.LastSavedDate >= @BeginDate)
			AND (@EndDate IS NULL OR W.LastSavedDate <= @EndDate)
		  GROUP BY W.WeekTimeSheetId
	) A ON (WTS.WeekTimeSheetId = A.WeekTimeSheetId)
	JOIN PROJECTS P ON (WTS.ProjectId = P.ProjectId)
	JOIN USERS U ON (WTS.UserId = U.PrincipalId)
  ORDER BY WTS.StartDate DESC, P.Title, P.ProjectId, UserName
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetsGetPendingForManager
	@UserId as int
as
DECLARE @IsPPM_Exec bit
SET @IsPPM_Exec = 0
IF EXISTS(SELECT * FROM USER_GROUP WHERE UserId = @UserId AND (GroupId = 4 OR GroupId = 7))
	SET @IsPPM_Exec = 1
DECLARE @table TABLE (ProjectId int, StartDate DateTime, PendingCount int)
INSERT INTO @table
	SELECT ProjectId, StartDate, COUNT(UserId)  AS PendingCount
	  FROM WeekTimeSheet
	  WHERE StatusId = 2
		AND (@IsPPM_Exec = 1 OR ProjectId IN (SELECT ProjectId FROM PROJECT_SECURITY_ALL PS WHERE PrincipalId = @UserId AND IsManager = 1))
	  GROUP BY ProjectId, StartDate
SELECT B.ProjectId, P.Title, B.StartDate, B.PendingCount, B.IsProject
  FROM
	(SELECT A.ProjectId, null AS StartDate, A.PendingCount, CAST(1 as bit) AS IsProject
	  FROM
		(SELECT ProjectId, SUM(PendingCount) AS PendingCount
		  FROM @table
		  GROUP BY ProjectId
		) A
	UNION ALL
	SELECT ProjectId, StartDate, PendingCount, CAST(0 as bit) AS IsProject
	  FROM @Table
	) B
	JOIN PROJECTS P ON (B.ProjectId = P.ProjectId)
  ORDER BY P.Title, P.ProjectId, B.StartDate
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].WeekTimeSheetsGetPendingGroupedByUser
	@ManagerId as int,
	@ProjectId as int,
	@StartDate as DateTime
as
DECLARE @table TABLE (UserId int, ObjectTypeId int, ObjectId int, Day1 int, Day2 int, Day3 int, Day4 int, Day5 int, Day6 int, Day7 int, Total int,
		TotalApproved int, Rate money, Cost money, UserComments ntext)
INSERT INTO @table
	SELECT W.UserId, T.ObjectTypeId, T.ObjectId, T.Day1, T.Day2, T.Day3, T.Day4, T.Day5, T.Day6, T.Day7,
		T.Day1 + T.Day2 + T.Day3 + T.Day4 + T.Day5 + T.Day6 + T.Day7 AS Total, T.TotalApproved, T.Rate, T.TotalApproved * T.Rate / 60 AS Cost, T.UserComments
	  FROM WeekTimeSheet W
		JOIN TIMESHEETS T ON (W.WeekTimeSheetId = T.WeekTimeSheetId)
	  WHERE W.StatusId = 2
		AND W.ProjectId = @ProjectId AND W.StartDate = @StartDate
SELECT A.UserId, U.LastName + ' ' + U.FirstName AS UserName, 0 AS ObjectTypeId, 0 AS ObjectId, '' AS Title, 0 AS Day1, 0 AS Day2, 0 AS Day3, 0 AS Day4, 0 AS Day5, 0 AS Day6, 0 AS Day7, Total, TotalApproved, Rate, Cost, '' AS UserComments,
	CAST(1 as bit) AS IsGroup,
	CASE WHEN C.UserId IS NULL THEN CAST(0 as bit) ELSE CAST(1 as bit) END AS IsCollapsed
  FROM
	(SELECT UserId, SUM(Total) AS Total, SUM(TotalApproved) AS TotalApproved, AVG(Rate) AS Rate, SUM(Cost) AS Cost
	  FROM @Table
	  GROUP BY UserId
	) A
	JOIN Users U ON A.UserId = U.PrincipalId
	LEFT JOIN COLLAPSED_MANAGERTIMESHEETS C ON (A.UserId = C.UserId AND C.ManagerId = @ManagerId)
UNION ALL
SELECT T.UserId, U.LastName + ' ' + U.FirstName AS UserName, T.ObjectTypeId, T.ObjectId,
	CASE
		WHEN T.ObjectTypeId = 4 THEN E.Title
		WHEN T.ObjectTypeId = 5 THEN TA.Title
		WHEN T.ObjectTypeId = 6 THEN TD.Title
		WHEN T.ObjectTypeId = 7 THEN I.Title
		WHEN T.ObjectTypeId = 11 THEN TT.Title
		WHEN T.ObjectTypeId = 16 THEN D.Title
	END AS Title,
	T.Day1, T.Day2, T.Day3, T.Day4, T.Day5, T.Day6, T.Day7, T.Total, T.TotalApproved, T.Rate, T.Cost, T.UserComments,
	CAST(0 as bit) AS IsGroup, CAST(0 as bit) as IsCollapsed
  FROM @Table T
	JOIN Users U ON T.UserId = U.PrincipalId
	LEFT JOIN COLLAPSED_MANAGERTIMESHEETS C ON (T.UserId = C.UserId AND C.ManagerId = @ManagerId)
	LEFT JOIN EVENTS E ON (T.ObjectId = E.EventId AND T.ObjectTypeId = 4)
	LEFT JOIN TASKS TA ON (T.ObjectId = TA.TaskId AND T.ObjectTypeId = 5)
	LEFT JOIN TODO TD ON (T.ObjectId = TD.ToDoId AND T.ObjectTypeId = 6)
	LEFT JOIN INCIDENTS I ON (T.ObjectId = I.IncidentId AND T.ObjectTypeId = 7)
	LEFT JOIN TIMESHEET_TODO TT ON (T.ObjectId = TT.TimeSheetToDoId AND T.ObjectTypeId = 11)
	LEFT JOIN DOCUMENTS D ON (T.ObjectId = D.DocumentId AND T.ObjectTypeId = 16)
  WHERE C.UserId IS NULL
  ORDER BY UserName, Title
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].WorkSpaceFilesSearch
	@UserId INT,
	@ProjectId INT = NULL,
	@ObjectTypeId INT = NULL,
	@ObjectId INT = NULL,
	@Keyword nvarchar(255) = NULL,
	@ContentType int = NULL,
	@ModifiedFrom DateTime = NULL,
	@ModifiedTo DateTime = NULL,
	@LengthFrom int = NULL,
	@LengthTo int = NULL
AS
DECLARE @SelectedContainerKeys TABLE(ContainerKey nvarchar(50) COLLATE database_default)
IF @ProjectId IS NULL AND @ObjectTypeId IS NULL
BEGIN
	INSERT INTO @SelectedContainerKeys SELECT DISTINCT ContainerKey FROM fsc_Directories
END
ELSE IF @ProjectId IS NULL AND @ObjectTypeId = 3
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'ProjectId_' + CAST(ProjectId as NVARCHAR(10)) FROM Projects
		UNION
		SELECT DISTINCT N'IncidentId_' + CAST(IncidentId as NVARCHAR(10)) FROM Incidents WHERE ProjectId IS NOT NULL
		UNION
		SELECT DISTINCT N'TaskId_' + CAST(TaskId as NVARCHAR(10)) FROM Tasks WHERE ProjectId IS NOT NULL
		UNION
		SELECT DISTINCT N'DocumentId_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId IS NOT NULL
		UNION
		SELECT DISTINCT N'EventId_' + CAST(EventId as NVARCHAR(10)) FROM EVENTS WHERE ProjectId IS NOT NULL
		UNION
		SELECT DISTINCT N'ToDoId_' + CAST(ToDoId as NVARCHAR(10)) FROM TODO WHERE ProjectId IS NOT NULL
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId IS NULL
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'ProjectId_' + CAST(ProjectId as NVARCHAR(10)) FROM Projects WHERE ProjectId = @ProjectId
		UNION
		SELECT DISTINCT N'IncidentId_' + CAST(IncidentId as NVARCHAR(10)) FROM Incidents WHERE ProjectId = @ProjectId
		UNION
		SELECT DISTINCT N'TaskId_' + CAST(TaskId as NVARCHAR(10)) FROM Tasks WHERE ProjectId = @ProjectId
		UNION
		SELECT DISTINCT N'DocumentId_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId = @ProjectId
		UNION
		SELECT DISTINCT N'EventId_' + CAST(EventId as NVARCHAR(10)) FROM EVENTS WHERE ProjectId = @ProjectId
		UNION
		SELECT DISTINCT N'ToDoId_' + CAST(ToDoId as NVARCHAR(10)) FROM TODO WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId = 7
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'IncidentId_' + CAST(IncidentId as NVARCHAR(10)) FROM Incidents WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId = 5
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'TaskId_' + CAST(TaskId as NVARCHAR(10)) FROM Tasks WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId = 16
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'DocumentId_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId = @ProjectId
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'DocumentVers_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId = 4
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'EventId_' + CAST(EventId as NVARCHAR(10)) FROM EVENTS WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NOT NULL AND @ObjectTypeId = 6
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'ToDoId_' + CAST(ToDoId as NVARCHAR(10)) FROM TODO WHERE ProjectId = @ProjectId
END
ELSE IF @ProjectId IS NULL AND @ObjectTypeId = 7
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'IncidentId_' + CAST(IncidentId as NVARCHAR(10)) FROM Incidents WHERE ProjectId IS NULL
END
ELSE IF @ProjectId IS NULL AND @ObjectTypeId = 16
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'DocumentId_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId IS NULL
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'DocumentVers_' + CAST(DocumentId as NVARCHAR(10)) FROM Documents WHERE ProjectId IS NULL
END
ELSE IF @ProjectId IS NULL AND @ObjectTypeId = 4
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'EventId_' + CAST(EventId as NVARCHAR(10)) FROM EVENTS WHERE ProjectId IS NULL
END
ELSE IF @ProjectId IS NULL AND @ObjectTypeId = 6
BEGIN
	INSERT INTO @SelectedContainerKeys
		SELECT DISTINCT N'ToDoId_' + CAST(ToDoId as NVARCHAR(10)) FROM TODO WHERE ProjectId IS NULL
END
SELECT D.ContainerKey,
	F.FileId,
	F.[Name],
	F.DirectoryId,
	F.FileBinaryId,
	F.CreatorId,
	F.Created,
	F.ModifierId,
	F.Modified,
	DATALENGTH(FB.Data) as Length,
	CT.ContentTypeString, CT.ContentTypeId,
	AllowHistory
FROM fsc_Files F
	LEFT JOIN fsc_FileBinaries FB ON FB.FileBinaryId = F.FileBinaryId
	LEFT JOIN CONTENT_TYPES CT ON CT.ContentTypeId = FB.ContentTypeId
	INNER JOIN fsc_Directories D ON F.DirectoryId = D.DirectoryId
	INNER JOIN fsc_FolderSecurityAll FSA ON
		FSA.DirectoryId = F.DirectoryId AND
		FSA.ContainerKey = D.ContainerKey AND
		FSA.[Action] = N'Read' AND
		FSA.Allow = 1 AND
		FSA.PrincipalId = @UserId
WHERE
	D.ContainerKey IN (SELECT ContainerKey FROM @SelectedContainerKeys)
	AND
	(
		@Keyword IS NULL
		OR
		F.[Name] LIKE '%'+@Keyword+'%'
	)
	AND
	(
		@ContentType IS NULL
		OR
		CT.ContentTypeId = @ContentType
	)
	AND
	(
		@ModifiedFrom IS NULL
		OR
		F.Modified >= @ModifiedFrom
	)
	AND
	(
		@ModifiedTo IS NULL
		OR
		F.Modified <= @ModifiedTo
	)
	AND
	(
		@LengthFrom IS NULL
		OR
		DATALENGTH(FB.Data) >= @LengthFrom
	)
	AND
	(
		@LengthTo IS NULL
		OR
		DATALENGTH(FB.Data) <= @LengthTo
	)
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
